-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis.py
More file actions
executable file
·2108 lines (1930 loc) · 84.3 KB
/
analysis.py
File metadata and controls
executable file
·2108 lines (1930 loc) · 84.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""analysis.py
grab data from different sources and perform selections on that data based on
certain criteria.
"""
import os
import sys
import random
from math import cos, sin, sqrt, pi, exp, floor
import numpy as np
import scipy
from scipy import stats
from options import Options
import subprocess
import zipfile
import uuid
import itertools
from logging import info, debug, warning, error, critical
sys.path.append("/home/pboyd/codes_in_development/faps")
from faps import PyNiss, Structure, Atom, Cell, Guest, Symmetry
import pickle
import stat
DEG2RAD = pi / 180.0
ATOM_NUM = [
"ZERO", "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg",
"Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn",
"Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb",
"Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In",
"Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm",
"Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta",
"W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At",
"Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk",
"Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt",
"Ds", "Rg", "Cn", "Uut", "Uuq", "Uup", "Uuh", "Uuo"]
class CSV(dict):
"""
Reads in a .csv file for data parsing.
"""
def __init__(self, filename, _MOFNAME=True):
self._columns = {"MOF":"MOFname", "uptake":"mmol/g",
"temperature":"T/K", "pressure":"p/bar",
"heat of adsorption":"hoa/kcal/mol"}
self.filename = filename
if not os.path.isfile(filename):
error("Could not find the file: %s"%filename)
sys.exit(1)
head_read = open(filename, "r")
self.headings = head_read.readline().lstrip("#").split(",")
head_read.close()
if _MOFNAME:
self._parse_by_mofname()
else:
self._parse_by_heading()
def obtain_data(self, column, _TYPE="float", **kwargs):
"""return the value of the data in column, based on values of
other columns assigned in the kwargs.
"""
# create a set of lists for the data we care about
trunc = []
trunc_keys = {}
# check to see if the columns are actually in the csv file
for ind, key in enumerate([column] + kwargs.keys()):
try:
rightkey = self._columns[key]
except KeyError:
rightkey = key
if rightkey not in self.headings:
warning("Could not find the column %s in the csv file %s "%
(rightkey, self.filename) + "returning...")
return 0. if _TYPE is "float" else None
else:
trunc.append(self[rightkey])
trunc_keys[ind] = key
if key == column:
colind = ind
for entry in itertools.izip_longest(*trunc):
# tie an entry list index to column + kwargs keys
kwargs_id =[i for i in range(len(entry)) if trunc_keys[i] in
kwargs.keys()]
if all([entry[i] == kwargs[trunc_keys[i]] for i in kwargs_id]):
# grab the entry for the column
col = entry[colind]
return float(col) if _TYPE is "float" else col
warning("Didn't find the data point requested in the csv file %s"%
self.filename)
return 0. if _TYPE is "float" else None
def _parse_by_heading(self):
"""The CSV dictionary will store data to heading keys"""
filestream = open(self.filename, "r")
# burn the header, as it's already read
# if the file is empty append zeroes..
if self._line_count(self.filename) <= 1:
for ind in range(len(self.headings)):
self.setdefault(self.headings[ind], []).append(0.)
filestream.close()
return
burn = filestream.readline()
for line in filestream:
line = line.lstrip("#").split(",")
for ind, entry in enumerate(line):
try:
entry = float(entry)
except ValueError:
#probably a string
pass
self.setdefault(self.headings[ind], []).append(entry)
filestream.close()
def _line_count(self, filename):
with open(filename) as f:
for i, l in enumerate(f):
pass
return i + 1
def _parse_by_mofname(self):
"""The CSV dictionary will have MOFnames as headings and contain
sub-dictionaries for additional row data.
"""
filestream = open(self.filename, "r")
try:
mofind = self.headings.index(self._columns["MOF"])
except ValueError:
error("the csv file %s does not have %s as a column! "%
(self.filename, self._columns["MOF"]) +
"EXITING ...")
sys.exit(0)
try:
uptind = self.headings.index(self._columns["uptake"])
except ValueError:
warning("the csv file %s does not have %s as a column"%
(self.filename, self._columns["uptake"]) +
" the qst will be reported as 0.0 kcal/mol")
try:
hoaind = self.headings.index(self._columns["heat of adsorption"])
except ValueError:
warning("the csv file %s does not have %s as a column"%
(self.filename, self._columns["heat of adsorption"]) +
" the qst will be reported as 0.0 kcal/mol")
burn = filestream.readline()
for line in filestream:
line = line.strip()
if line:
line = line.lstrip("#").split(",")
mofname = line[mofind].strip()
mofname = clean(mofname)
try:
uptake = line[uptind]
except UnboundLocalError:
uptake = 0.
self.setdefault(mofname, {})["mmol/g"] = float(uptake)
try:
hoa = line[hoaind]
except UnboundLocalError:
hoa = 0.
self.setdefault(mofname, {})["hoa"] = float(hoa)
filestream.close()
class FunctionalGroups(dict):
"""
Reads in a .sqlout file and returns a dictionary containing mofnames and
their functionalizations.
"""
def __init__(self, filename):
"""Read in all the mofs and store in the dictionary."""
if not os.path.isfile(filename):
error("could not find the file: %s"%(filename))
sys.exit(1)
filestream = open(filename, 'r')
for line in filestream:
line = line.split("|")
mof = "%s.sym.%s"%(line[0], line[1])
# use a dictionary to sort the functionalizations
groups = line[2]
dic = {}
if len(groups) > 0:
[dic.setdefault(i.split("@")[0], []).append(i.split("@")[1])
for i in groups.split(".")]
if len(dic.keys()) == 1:
dic[None] = []
elif len(dic.keys()) == 0:
dic[None] = []
dic[False] = []
else:
dic = {None:[], False:[]}
# check if the entry already exists!
if self._check_duplicate(mof):
if self[mof] == dic:
# duplicate
debug("Duplicate found %s"%(mof))
#pass
else:
warning("duplicate found for %s"%(mof) +
" but with different functionalization!")
else:
self[mof] = dic
filestream.close()
def _check_duplicate(self, entry):
"""Return true if the key exists, otherwise, false."""
if self.has_key(entry):
return True
return False
class MOFlist(list):
"""Returns a list of MOFs parsed from a simple text file."""
def __init__(self, filename):
filestream = open(filename, "r")
header = filestream.readline()
mofind = header.split(',').index("MOFname")
for line in filestream:
line = line.strip()
line = line.split(",")
line = line[mofind]
if "sym" in line:
line.lstrip("#")
line = clean(line)
self.append(line)
filestream.close()
class Selector(object):
"""
Take in a dictionary of a mof, complete with data, and select a set
according to some criteria.
"""
metal_indices = {
"Zn" : (1, 3),
"Cu" : (2,),
"Co" : (4,),
"Cd" : (5,),
"Mn" : (6,),
"Zr" : (7,),
"In" : (8, 11),
"V" : (9,),
"Ba" : (10,),
"Ni" : (12,)
}
bad_organics = [
9,
15,
10,
(2, 11),
(20, 23),
(24, 27),
(15, 25)
]
functional_groups = [
"H",
"F",
"Cl",
"Br",
"I",
"NH2",
"Me",
"Et",
"Pr",
"NO2",
"HCO",
"COOH",
"OH",
"CN",
"Ph",
"OMe",
"OEt",
"OPr",
"NHMe",
"SO3H"
]
def __init__(self, options, mof_dic):
self.options = options
self.mof_dic = mof_dic.copy()
self.dataset = {'master_list':[]}
self.ignore = MOFlist(self.options.ignore_list)
self._assign_metalind()
if self.options.max_gridpoints == 0:
self.options.max_gridpoints = None
self.trim_undesired()
def _print_info(self):
info("Inclusive functional groups: %s"%
(', '.join(self.options.fnl_include)))
info("Exclude functional groups: %s"%
(', '.join(self.options.fnl_exclude)))
info("Partial functional groups: %s"%
(', '.join(self.options.fnl_partial)))
info("Weight uptake (gaussian): %s"%self.options.gaussian)
info("Max grid points: %s"%str(self.options.max_gridpoints))
info("Total number of MOFs: %i"%self.options.total_mofs)
info("Maximum per functional group: %i"%self.options.functional_max)
info("Maximum per organic linker: %i"%self.options.organic_max)
info("Maximum per metal index: %i"%self.options.metal_max)
info("Maximum per topology: %i"%self.options.topology_max)
def _assign_metalind(self):
# assert if a metal is selected
self.metalind = []
if self.options.metals:
for metal in self.options.metals:
# try to extract a metal index from the list of metals
try:
metind = int(metal)
if not metind in [ind for sublist in
self.metal_indices.values()
for ind in sublist]:
error("Metal index %i is not in the database!"
%metind)
sys.exit(1)
self.metalind.append(metind)
except ValueError:
try:
indices = self.metal_indices[metal]
for ind in indices:
self.metalind.append(ind)
except KeyError:
error("ERROR: metal %s is not in the database!"%(metal))
sys.exit(1)
# all metals are fair game
else:
for metalind in self.metal_indices.values():
for i in metalind:
self.metalind.append(i)
def _assign_maxima(self):
# topologies
if self.options.topology_max == 0 and len(self.options.topologies) != 0:
self.options.topology_max = (self.options.total_mofs /
len(self.options.topologies))
elif self.options.topology_max == 0 and len(self.options.topologies) == 0:
self.options.topology_max = self.options.total_mofs
# metal
if self.options.metal_max == 0 and len(self.metalind) != 0:
self.options.metal_max = (self.options.total_mofs /
len(self.metalind))
# organic
if self.options.organic_max == 0 and len(self.options.org_include) != 0:
self.options.organic_max = (self.options.total_mofs /
len(self.options.org_include))
elif self.options.organic_max == 0:
self.options.organic_max = self.options.total_mofs / 30
# functional
if self.options.functional_max == 0:
self.options.functional_max = (self.options.total_mofs / 20)
def trim_undesired(self):
"""Trims the MOFs with bad organic linkers from the database.
This is temporary and should be removed.
"""
temp_moflist = self.mof_dic.keys()
for mof in temp_moflist:
met, org1, org2, top, fnl = parse_mof_data(mof)
pop = False
o1 = org1()
o2 = org2()
orgpair = tuple(sorted([o1, o2]))
if (o1 in self.bad_organics):
pop = True
elif (o2 in self.bad_organics):
pop = True
elif (orgpair in self.bad_organics):
pop = True
if pop:
self.mof_dic.pop(mof)
def non_existing(self, mof):
"""Checks a MOF against a directory to see if the cif exists."""
dir = self.options.lookup
if not os.path.isdir(self.options.lookup):
error("Could not find the .cif directory, exiting..")
sys.exit(1)
# re-name mof to the out directory standards.
met, org1, org2, top, fnl = parse_mof_data(mof)
newmofname = "str_m" + str(met()) + "_o" + str(org1()) + \
"_o" + str(org2()) + "_f0_" + top() + ".sym." + \
str(fnl()) + ".out.cif"
if not os.path.isfile(dir + "/" + newmofname):
return True
return False
def top_select(self):
"""Order the mofs by top ranked structures. store in a dataset
dictionary and write to a csv file.
"""
mofnames = self.mof_dic.keys()
info("Size of the list of MOFs to sample from: %i"%(
len(mofnames)))
for mof in mofnames:
if self._valid_mof(mof):
self._bin_mof(mof)
self.dataset['master_list'].append(mof)
# rank bins by uptake
limit = self.options.total_mofs if self.options.total_mofs else None
for bin, dic in self.dataset.items():
if bin == 'master_list':
self.dataset[bin] = self._rank_by_uptake(dic)
self.write_dataset(self.dataset[bin][:limit],
basename="top_ranked")
else:
for key, val in dic.items():
self.dataset[bin][key] = self._rank_by_uptake(val)
if isinstance(key, tuple):
name = "-".join([str(i) for i in key])
else:
name = str(key)
self.write_dataset(self.dataset[bin][key][:limit],
basename="%s_%s_top_ranked"%(bin,name))
def _rank_by_uptake(self, list):
"""Rank by mmol/g uptake."""
order = []
for mof in list:
try:
uptake = self.mof_dic[mof]['mmol/g']
except KeyError:
uptake = 0.
order.append(tuple([uptake, mof]))
order = [i for i in reversed(sorted(order))]
return [i[1] for i in order[:]]
def _bin_mof(self, mof):
"""Bin mof into different categories"""
met, org1, org2, top, fnl = parse_mof_data(mof)
met = met()
org1 = org1()
org2 = org2()
top = top()
try:
(fnl_grp1, fnl_grp2) = self.mof_dic[mof]['functional_groups']
if not fnl_grp1:
fnl_grp1 = "None"
if not fnl_grp2:
fnl_grp2 = "None"
except ValueError:
# doesn't find two functional groups in the dictionary
fnl_grp1, fnl_grp2 = "None", "None"
org_pair = tuple(sorted([org1, org2]))
fnl_pair = tuple(sorted([fnl_grp1, fnl_grp2]))
mofname = "str_m%i_o%i_o%i_%s"%(met, org_pair[0], org_pair[1], top)
self.dataset.setdefault('mof_id',{}).setdefault(mofname,[]).append(mof)
self.dataset.setdefault('fnl_p',{}).setdefault(fnl_pair,[]).append(mof)
self.dataset.setdefault('org_p',{}).setdefault(org_pair,[]).append(mof)
self.dataset.setdefault('org',{}).setdefault(org1,[]).append(mof)
self.dataset.setdefault('org',{}).setdefault(org2,[]).append(mof)
self.dataset.setdefault('met',{}).setdefault(met, []).append(mof)
if fnl_grp1 == fnl_grp2:
self.dataset.setdefault('fnl',{}).setdefault(fnl_grp1,[]).append(mof)
else:
self.dataset.setdefault('fnl',{}).setdefault(fnl_grp1,[]).append(mof)
self.dataset.setdefault('fnl',{}).setdefault(fnl_grp2,[]).append(mof)
def _valid_mof(self, mof):
"""Discriminate a mof based on whatever criteria is set in the
input file.
Current checks in order are:
1 - MOF is not in the ignore list
2 - MOF exists in the lookup directory
3 - the reported uptake (mmol/g) is above the cutoff
4 - the reported uptake (mmol/g) samples a gaussian dist.
5 - Functional groups are not in the EXCLUDE list
6 - Functional groups are in the PARTIAL list
7 - Functional group is in the INCLUDE list
8 - Organic linkers are not in the EXCLUDE list
9 - Organic linkers are in the INCLUDE list (read: PARTIAL)
10 - Metal indices are in the metal INCLUDE list
11 - The topology is in the topology INCLUDE list
12 - ESP gridpoints is below a given maximum
"""
# grab the data for the mof
met, org1, org2, top, fnl = parse_mof_data(mof)
org1, org2 = org1(), org2()
met = met()
top = top()
try:
(fnl1, fnl2) = self.mof_dic[mof]['functional_groups']
except ValueError:
# doesn't find two functional groups in the dictionary
fnl1, fnl2 = None, None
# return false in the case that discriminating against
# functional group was requested. False due to the
# assumption that the functional group listing for this mof
# could not be found.
if self.options.fnl_include or self.options.fnl_partial:
return False
uptake = self.mof_dic[mof]['mmol/g']
# 1 - check if the MOF exists in the ignore list
if mof in self.ignore:
debug("%s was found in the ignore list"%(mof))
return False
# 2 - check if the MOF exists in the directory of .cif files
if self.options.lookup:
if self.non_existing(mof):
debug("%s does not exist!"%(mof))
return False
# 3 - check if the uptake reported in mmol/g is above the cutoff
if uptake < self.options.uptake_cutoff:
debug("%s has an uptake, %4.2f. This is lower than the cutoff"%
(mof, uptake))
return False
# 4 - determine if the uptake fits in the gaussian distribution
if self.options.gaussian:
# NOTE: this creates a gaussian each instance it's called -
# I should implement a pre-computed gaussian curve to reduce
# computational expense
if not self.weight_by_gaussian(uptake):
debug("%s has an uptake, %4.2f not sampled by the gaussian."%
(mof, uptake))
return False
# 5 - check if the functional groups are in the EXCLUDE list
if (fnl1 in self.options.fnl_exclude) or \
(fnl2 in self.options.fnl_exclude):
debug("%s has functional groups in the exclude list"%mof)
return False
# 6 - check if the functional groups are in the PARTIAL list
if self.options.fnl_partial:
if (fnl1 not in self.options.fnl_partial) and \
(fnl2 not in self.options.fnl_partial):
debug("%s has functional groups not in the partial list"%mof)
return False
# 7 - check if the functional group is in the INCLUDE list
if self.options.fnl_include:
if fnl1 and not fnl2:
if fnl1 not in self.options.fnl_include:
debug("%s has a functional group not in the include list"
%(mof))
return False
elif fnl2 and not fnl1:
if fnl2 not in self.options.fnl_include:
debug("%s has a functional group not in the include list"
%(mof))
return False
else:
debug("%s contains two functional groups,"%(mof) +
"the fnl_include list restricts only one per MOF")
return False
# 8 - check if the organic linkers are in the EXCLUDE list
if (org1 in self.options.org_exclude) or \
(org2 in self.options.org_exclude):
debug("%s has organic linkers in the exclude list"%mof)
return False
# 9 - check if the organic linkers are in the INCLUDE list
if self.options.org_include:
if (org1 not in self.options.org_include) and \
(org2 not in self.options.org_include):
debug("%s has organic linkers not in the include list"%mof)
return False
# 10 - check if the metal index is in the list of METALS.
if met not in self.metalind:
debug("%s metal linker is not in the metal list"%(mof))
return False
# 11 - check if the topology is in the topology list.
if self.options.topologies:
if top not in self.options.topologies:
debug("%s topology is not in the topology include list"%(mof))
return False
# 12 - determine if the number of esp grid points is below
# a maximum (if requested)
# TODO(pboyd): include some estimating scheme, this takes
# way to long for the entire database.
if self.options.report_ngrid:
try:
ngrid = self.mof_dic[mof]['ngrid']
except KeyError:
ngrid = self.grid_points(mof)
self.mof_dic[mof]['ngrid'] = ngrid
if ngrid <= 0:
debug("gridpoint calculation had errors, ignoring %s"%mof)
return False
if ngrid > self.options.max_gridpoints:
debug("%s contains %i gridpoints. The max is %i"%
(mof,ngrid,self.options.max_gridpoints))
return False
# all tests passed, return True.
return True
def random_select(self):
"""Select a list of MOFs randomly
"""
# check if total_mofs is allocated, if not, then assign default of 100
if not self.options.total_mofs:
self.options.total_mofs = 100
self._assign_maxima()
self._print_info()
organics_count, fnl_groups_count = {}, {}
top_count, met_index_count = {}, {}
mofcount = 0
# generate a list of valid mofs which obey the inclusive, partial and
# exclude lists.
moflist = self.mof_dic.keys()
done = False
info("Size of the list of MOFs to sample from: %i"%(len(moflist)))
while not done:
try:
mof = random.choice(moflist)
moflist.pop(moflist.index(mof))
except IndexError:
warning("Sampled all MOFs without completing list! Writing " +
"output file anyways..")
self.write_dataset(self.dataset['master_list'])
return
if self._valid_mof(mof):
met, org1, org2, top, junk = parse_mof_data(mof)
(fnl_grp1, fnl_grp2) = self.mof_dic[mof]['functional_groups']
org_max = self.check_dictionary_counts(organics_count,
organic1=org1(),
organic2=org2())
fnl_max = self.check_dictionary_counts(fnl_groups_count,
fnl_group1=fnl_grp1,
fnl_group2=fnl_grp2)
top_max = self.check_dictionary_counts(top_count,
topology=top())
met_max = self.check_dictionary_counts(met_index_count,
metal=met())
if not org_max and not fnl_max and not top_max and \
not met_max:
# increment counts
self.increment_dictionary_counts(organics_count,
org1(),
org2())
# keep track of functional group counts
self.increment_dictionary_counts(fnl_groups_count,
fnl_grp1,
fnl_grp2)
# keep track of metal index counts
self.increment_dictionary_counts(met_index_count,
met())
# keep track of topology counts
self.increment_dictionary_counts(top_count,
top())
# append to list
self.dataset['master_list'].append(mof)
mofcount += 1
if mofcount >= self.options.total_mofs:
done = True
self.write_dataset(self.dataset['master_list'])
def check_dictionary_counts(self, dictionary, **kwargs):
if 'fnl_group1' in kwargs.keys():
maximum = self.options.functional_max
combine_max = self.options.functional_max / 2
elif 'organic1' in kwargs.keys():
maximum = self.options.organic_max
combine_max = self.options.organic_max / 2
elif 'metal' in kwargs.keys():
maximum = self.options.metal_max
combine_max = self.options.metal_max
elif 'topology' in kwargs.keys():
maximum = self.options.topology_max
combine_max = self.options.topology_max
# check the combination of arguments
# only currently valid for organic and functional group dictionaries.
combine = sorted(kwargs.keys())
try:
combine.pop(combine.index(None))
except ValueError:
pass
if len(combine) > 1:
dictionary.setdefault(tuple(combine), 0)
if dictionary[tuple(combine)] >= combine_max:
return True
# check the individual value counts
for key, value in kwargs.items():
dictionary.setdefault(value, 0)
if dictionary[value] >= maximum:
return True
return False
def increment_dictionary_counts(self, dictionary, *args):
# increment individual entries.
for arg in args:
if arg is not None:
dictionary.setdefault(arg, 0)
dictionary[arg] += 1
# increment combinations as well...
if len(set(args)) > 1 and None not in args:
dictionary.setdefault(tuple(args), 0)
dictionary[tuple(args)] += 1
def weight_by_gaussian(self, uptake, a=1, b=0.5, c=1.3):
"""Weight according to a gaussian distribution based on uptake.
Defaults are a distribution amplitude of 1, centered around
5 mmol/g, smeared by 1.3 (width)"""
gauss = gaussian(a, b, c)
# probability of accepting the gaussian weight determined
# by a random number between 0 and a.
if gauss(uptake) < (random.random()*a):
return False
return True
def grid_points(self, mofname):
"""Determine the maximum number of grid points needed for the esp."""
# have to source the correct file.
mofname = clean(mofname)
dirmof = os.path.join(self.options.lookup, mofname+'.out.cif')
ngrid = -1
if os.path.isfile(dirmof):
from_cif = CifFile(dirmof)
ngrid = GrabGridPoints(from_cif.cell,
from_cif.atom_symbols,
from_cif.cart_coordinates)
return ngrid
def write_dataset(self, dataset, basename=None):
"""Writes the data to a file."""
os.chdir(self.options.job_dir)
if basename is None:
basename = ""
if self.metalind:
metal_titles = []
for met in self.metalind:
for key, value in self.metal_indices.items():
if met in value:
metal_titles.append(key)
for metal in set(metal_titles):
basename += "%s_"%metal
basename += "dataset"
if self.options.topologies:
for top in self.options.topologies:
basename += "_%s"%top
count = 0
order_by_fnl = {}
filename = create_csv_filename(basename)
info("Writing dataset to %s.csv ..."%(filename))
outstream = open(filename+".csv", "w")
header="MOFname,mmol/g,hoa/kcal/mol,functional_group1,functional_group2"
if (self.options.max_gridpoints is not None) or\
(self.options.report_ngrid):
header += ",ngrid\n"
else:
header += "\n"
outstream.writelines(header)
for mof in dataset:
try:
fnl1, fnl2 = self.mof_dic[mof]['functional_groups'].keys()
except (KeyError, ValueError):
fnl1, fnl2 = None, None
if not fnl1:
fnl1 = "None"
if not fnl2:
fnl2 = "None"
order_by_fnl.setdefault((fnl1,fnl2),[]).append(mof)
try:
uptake = self.mof_dic[mof]['mmol/g']
except KeyError:
uptake = 0.
try:
hoa = self.mof_dic[mof]['hoa']
except KeyError:
hoa = 0.
line = "%s,%f,%f,%s,%s"%(mof, uptake, hoa, fnl1, fnl2)
if (self.options.report_ngrid):
try:
ngrid = self.mof_dic[mof]['ngrid']
except KeyError:
ngrid = self.grid_points(mof)
line += ",%i\n"%(ngrid)
else:
line += "\n"
outstream.writelines(line)
outstream.close()
# write this stuff to the terminal (log file)
# this was legacy from an older version of the code.
for fnl, mofs in order_by_fnl.items():
debug("Functional groups: %s, %s"%(fnl[0], fnl[1]))
for mof in mofs:
debug(" " + mof)
info("Done.")
class GrabNewData(object):
"""Takes a mof dictionary and adds new uptake data to it."""
def __init__(self, options, mofs, extended = False):
self.mofs = mofs
self.options = options
# determines if hydrogen replacements are shown in the output
self.extended = extended
# base directory containing all the faps job info.
if self.options.directory:
if os.path.exists(self.options.directory):
self.basedir = self.options.directory
else:
error("The directory specified in the input file "+
"could not be found: %s"%(self.options.directory))
sys.exit(1)
else:
error("No directory with new data specified in the "+
"input file!")
sys.exit(1)
def grab_data(self, temp=298.0, press=0.15):
"""Descends into directories and grabs appropriate data."""
os.chdir(self.basedir)
all_list = os.listdir('.')
directories = [i for i in all_list if os.path.isdir(i)]
for mof in self.mofs.keys():
if mof in directories:
info("grabbing data from %s"%mof)
os.chdir(mof)
if os.path.isfile(mof + "-CO2.csv"):
data = CSV(mof + "-CO2.csv", _MOFNAME=False)
new_uptake = data.obtain_data("mmol/g",
temperature=temp,
pressure=press)
new_hoa = data.obtain_data("heat of adsorption",
temperature=temp,
pressure=press)
else:
warning("could not find %s-CO2.csv"%(mof))
new_uptake = 0.
new_hoa = 0.
os.chdir('..')
else:
warning("could not find %s in the directory %s"%(
mof, self.basedir))
new_uptake = 0.
new_hoa = 0.
self.mofs[mof]['new_uptake'] = new_uptake
self.mofs[mof]['new_hoa'] = new_hoa
os.chdir(self.options.job_dir)
def write_data(self, filename="default.report.csv"):
"""Write all MOF data to a csv file."""
os.chdir(self.options.job_dir)
basename = clean(filename)
count = 0
# make sure there's no overwriting, goes up to 99
filename = create_csv_filename(basename)
info("Writing report to %s.csv ..."%(os.path.basename(filename)))
outstream = open(filename + ".csv", "w")
header = "MOFname,mmol/g,hoa/kcal/mol,functional_group1,functional_group2"
if self.extended:
header += ",grp1_replacements,grp2_replacements"
if self.options.report_ngrid:
header += ",ngrid"
header += "\n"
outstream.writelines(header)
for mof in self.mofs.keys():
new_uptake = self.mofs[mof]['new_uptake']
new_hoa = self.mofs[mof]['new_hoa']
try:
replaced_groups = self.mofs[mof]['functional_groups']
except KeyError:
replaced_groups = {False:[], None:[]}
names = replaced_groups.keys()
names.sort()
fnl_grp1 = names[0]
fnl_grp2 = names[1]
rep_1 = " ".join(replaced_groups[fnl_grp1])
rep_2 = " ".join(replaced_groups[fnl_grp2])
line = "%s,%f,%f,%s,%s"%(mof, new_uptake, new_hoa,
fnl_grp1, fnl_grp2)
if self.extended:
line += "%s,%s"%(rep_1, rep_2)
if self.options.report_ngrid:
line += ",%i"%(self.grid_points(mof))
line += "\n"
outstream.writelines(line)
info("Done.")
outstream.close()
def grid_points(self, mofname):
"""Determine the maximum number of grid points needed for the esp."""
# have to source the correct file.
mofname = clean(mofname)
dirmof = os.path.join(self.options.lookup, mofname+'.out.cif')
ngrid = -1
if os.path.isfile(dirmof):
from_cif = CifFile(dirmof)
ngrid = GrabGridPoints(from_cif.cell,
from_cif.atom_symbols,
from_cif.cart_coordinates)
return ngrid
class GrabGridPoints(int):
"""Extracts an integer of grid points from an egulp calculation."""
code_loc = "/home/pboyd/bin"
# directory to submit jobs and remove later.
dir = "/home/pboyd/.temp"
config_file = 'tempconfig.ini'
param_file = 'tempparam.dat'
config_lines = ("build_grid 1\n" +
"build_grid_from_scratch 1 none 0.25 0.25 0.25 2.0\n" +
"save_grid 0 temp\n" +
"calculate_pot_diff 0\n" +
"skip_everything 1\n" +
"point_charges_present 0\n" +
"include_pceq 0\n" +
"imethod 0\n")
param_lines = ("1\n 1 4.52800000 6.94520000")
def __new__(cls, cell, atoms, coordinates, value=0):
i = int.__new__(cls, value)
i.cell = cell
# make the geo_file difficult to duplicate
i.geo_file = str(uuid.uuid1())
i.atoms = atoms
i.nums = [ATOM_NUM.index(j) for j in atoms]
i.coordinates = coordinates
i._write_geo_file()
i = i._submit_egulp_job()
return i
def _write_geo_file(self):
"""Sets up the .geo file to run e-gulp."""
filestream = open(self.dir + "/" + self.geo_file, "w")
filestream.writelines("temp\n")
a, b, c = self.cell[:]
filestream.writelines(('%15.12f %15.12f %15.12f \n'%(tuple(a))))
filestream.writelines(('%15.12f %15.12f %15.12f \n'%(tuple(b))))
filestream.writelines(('%15.12f %15.12f %15.12f \n'%(tuple(c))))
filestream.writelines("%i\n"%(len(self.atoms)))
for atom, (x, y, z) in zip(self.nums, self.coordinates):
filestream.writelines("%6d %12.7f %12.7f %12.7f %12.7f\n"%
(atom, x, y, z, 0.))
filestream.close()
def _submit_egulp_job(self):
"""Submits the EGULP calculation to determine the number of grid
points to calculate.
"""
os.chdir(self.dir)
if not os.path.isfile(self.config_file):
configstream = open(self.config_file, 'w')
configstream.writelines(self.config_lines)
configstream.close()
if not os.path.isfile(self.param_file):
parameterstream = open(self.param_file, 'w')
parameterstream.writelines(self.param_lines)
parameterstream.close()
code_exe = self.code_loc + "/egulppot"
job = subprocess.Popen([code_exe, self.geo_file,
self.param_file, self.config_file],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
comm = job.communicate()
if comm[1] is not '':
warning("ERROR in EGULP calculation!")
return -1
else:
os.remove(self.geo_file)
return self._grab_ngrid_points(comm[0].split('\n'))
def _grab_ngrid_points(self, lines):
"""Grab the number of grid points from the output file."""
search_string = "total number of simulation points"
for line in reversed(lines):
if search_string in line:
parse = line.lstrip(search_string)
return int(parse.strip())
return -1
class JobHandler(object):
"""Reads the data in options and directs the program to the