-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathconfig.py
1226 lines (1141 loc) · 45.9 KB
/
config.py
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
import configparser
from difflib import SequenceMatcher as seqmatch
import itertools as it
import os
import re
import AaronTools
from AaronTools import addlogger
from AaronTools.const import AARONLIB, AARONTOOLS
from AaronTools.theory import (
GAUSSIAN_COMMENT,
GAUSSIAN_CONSTRAINTS,
GAUSSIAN_COORDINATES,
GAUSSIAN_GEN_BASIS,
GAUSSIAN_GEN_ECP,
GAUSSIAN_POST,
GAUSSIAN_PRE_ROUTE,
GAUSSIAN_ROUTE,
GAUSSIAN_ONIOM,
GAUSSIAN_MM,
GAUSSIAN_MM_PARAMS,
ORCA_BLOCKS,
ORCA_COMMENT,
ORCA_COORDINATES,
ORCA_ROUTE,
PSI4_AFTER_JOB,
PSI4_BEFORE_GEOM,
PSI4_BEFORE_JOB,
PSI4_COMMENT,
PSI4_JOB,
PSI4_MOLECULE,
PSI4_OPTKING,
PSI4_SETTINGS,
PSI4_SOLVENT,
SQM_COMMENT,
SQM_QMMM,
QCHEM_MOLECULE,
QCHEM_REM,
QCHEM_COMMENT,
QCHEM_SETTINGS,
XTB_CONTROL_BLOCKS,
XTB_COMMAND_LINE,
Theory,
OptimizationJob,
FrequencyJob,
)
from AaronTools.theory.implicit_solvent import ImplicitSolvent
from AaronTools.theory.job_types import job_from_string
from AaronTools.utils.utils import getuser, to_closing
THEORY_OPTIONS = [
"GAUSSIAN_COMMENT",
"GAUSSIAN_CONSTRAINTS",
"GAUSSIAN_COORDINATES",
"GAUSSIAN_GEN_BASIS",
"GAUSSIAN_GEN_ECP",
"GAUSSIAN_POST",
"GAUSSIAN_PRE_ROUTE",
"GAUSSIAN_ROUTE",
"ORCA_BLOCKS",
"ORCA_COMMENT",
"ORCA_COORDINATES",
"ORCA_ROUTE",
"PSI4_AFTER_JOB",
"PSI4_BEFORE_GEOM",
"PSI4_BEFORE_JOB",
"PSI4_COMMENT",
"PSI4_MOLECULE",
"PSI4_JOB",
"PSI4_OPTKING",
"PSI4_SETTINGS",
"SQM_COMMENT",
"SQM_QMMM",
"QCHEM_MOLECULE",
"QCHEM_REM",
"QCHEM_COMMENT",
"QCHEM_SETTINGS",
"XTB_COMMAND_LINE",
"XTB_CONTROL_BLOCKS"
]
@addlogger
class Config(configparser.ConfigParser):
"""
Reads configuration information from INI files found at:
$QCHASM/AaronTools/config.ini
$AARONLIB/config.ini
./config.ini or /path/to/file supplied during initialization
Access to configuration information available using dictionary notation.
eg: self[`section_name`][`option_name`] returns `option_value`
See help(configparser.ConfigParser) for more information
"""
LOG = None
SPEC_ATTRS = [
"_changes",
"_changed_list",
"_args",
"_kwargs",
"infile",
"metadata",
]
@classmethod
def _process_content(cls, filename, quiet=True):
"""
process file content to handle optional default section header
"""
contents = filename
if os.path.isfile(filename):
try:
with open(filename) as f:
contents = f.read()
except Exception as e:
if not quiet:
cls.LOG.INFO("failed to read %s: %s", filename, e)
return ""
elif not len(filename.splitlines()) > 1:
return ""
try:
configparser.ConfigParser().read_string(contents)
except configparser.MissingSectionHeaderError:
contents = "[DEFAULT]\n" + contents
return contents
def __init__(
self,
infile=None,
quiet=False,
skip_user_default=False,
interpolation=configparser.ExtendedInterpolation(),
**kwargs
):
"""
infile: the configuration file to read
quiet: prints helpful status information
skip_user_default: change to True to skip importing user's default config files
**kwargs: passed to initialization of parent class
"""
configparser.ConfigParser.__init__(
self, interpolation=None, comment_prefixes=("#"), **kwargs
)
self.infile = infile
if not quiet:
print("Reading configuration...")
self._read_config(infile, quiet, skip_user_default)
# enforce case-sensitivity in certain sections
for section in self:
if section in [
"Substitution",
"Mapping",
"Configs",
"Results",
]:
continue
for option, value in list(self[section].items()):
if section == "Geometry" and option.lower().startswith(
"structure"
):
del self[section][option]
option = option.split(".")
option[0] = option[0].lower()
option = ".".join(option)
self[section][option] = value
continue
if section == "Geometry" and "structure" in value.lower():
re.sub("structure", "structure", value, flags=re.I)
self[section][option] = value
if option.lower() != option:
self[section][option.lower()] = value
del self[section][option]
# handle included sections
self._parse_includes()
if infile is not None:
self.read(infile)
# set additional default values
if infile:
if "top_dir" not in self["DEFAULT"]:
self["DEFAULT"]["top_dir"] = os.path.dirname(
os.path.abspath(infile)
)
if "name" not in self["DEFAULT"]:
self["DEFAULT"]["name"] = ".".join(
os.path.relpath(
infile, start=self["DEFAULT"]["top_dir"]
).split(".")[:-1]
)
else:
if "top_dir" not in self["DEFAULT"]:
self["DEFAULT"]["top_dir"] = os.path.abspath(os.path.curdir)
# handle substitutions/mapping
self._changes = {}
self._changed_list = []
self._parse_changes()
# for passing to Theory(*args, **kwargs)
self._args = []
self._kwargs = {}
# metadata is username and project name
self.metadata = {
"user": self.get(
"DEFAULT",
"user",
fallback=self.get("HPC", "user", fallback=getuser()),
),
"project": self.get("DEFAULT", "project", fallback=""),
}
def get(self, section, option, *, junk="_ ", max_junk=1, **kwargs):
"""
see ConfigParser.get for details
junk are characters that are not important in the option name
max_junk - number of allowed junk characters
e.g. junk="_" with max_junk=1 when looking for
'empirical dispersion' will match 'empirical_dispersion'
"""
# dummy class to allow user to specify whatever they
# want for fallback - even False and None
class NoFallback:
pass
fallback = NoFallback
if "fallback" in kwargs:
fallback = kwargs.pop("fallback")
# see if option is present as given
out = super().get(section, option, fallback=NoFallback, **kwargs)
# otherwise, look through the rest of the options to see if one
# is basically the same but with some extra junk characters
# e.g. 'empirical_dispersion' instead of 'empirical dispersion'
if out is NoFallback and junk and self.has_section(section):
for test_opt in self.options(section):
# calculate similarity
similarity = seqmatch(lambda x: x in junk, option, test_opt).ratio()
# must have no more than max_junk junk characters
if similarity >= 1 - max_junk / len(option) and any(
x in test_opt for x in junk
):
out = super().get(section, test_opt, fallback=NoFallback, **kwargs)
break
if out is NoFallback and fallback is NoFallback:
raise configparser.NoOptionError(section, option)
if out is NoFallback:
out = fallback
return out
def optionxform(self, option):
return str(option)
def __str__(self):
rv = ""
for section in self:
if "." in section:
continue
rv += "[{}]\n".format(section)
for option, value in self[section].items():
rv += "{} = {}\n".format(option, value)
rv += "\n"
return rv
def copy(self):
config = Config(infile=None, quiet=True)
for section in config.sections():
config.remove_section(section)
for option in list(config["DEFAULT"].keys()):
config.remove_option("DEFAULT", option)
for section in ["DEFAULT"] + self.sections():
try:
config.add_section(section)
except (configparser.DuplicateSectionError, ValueError):
pass
for key, val in self[section].items():
config[section][key] = val
for section in self.SPEC_ATTRS:
setattr(config, section, getattr(self, section))
return config
def for_change(self, change, structure=None):
this_config = self.copy()
if structure is not None:
this_config["Job"]["name"] = structure.name
if change:
this_config["Job"]["name"] = os.path.join(
change, this_config["Job"]["name"]
)
this_config._changes = {change: self._changes[change]}
return this_config
def _parse_changes(self):
for section in ["Substitution", "Mapping"]:
if section not in self:
continue
if self[section].getboolean("reopt", fallback=True):
self._changes[""] = ({}, None)
for key, val in self[section].items():
if key in self["DEFAULT"]:
continue
del self[section][key]
key = "\n".join(["".join(k.split()) for k in key.split("\n")])
val = "\n".join(["".join(v.split()) for v in val.split("\n")])
self[section][key] = val
for key, val in self[section].items():
if key in self["DEFAULT"] or key == "reopt":
continue
if "=" not in val:
val = [v.strip() for v in val.split(",")]
else:
tmp = [v.strip() for v in val.split(";")]
val = []
for t in tmp:
t = t.strip()
if not t:
continue
elif "\n" in t:
val += t.split("\n")
else:
val += [t]
tmp = {}
for i, v in enumerate(val):
if i == 0 and len(v.split("=")) == 1:
v = "{}={}".format(key, v)
val[i] = v
del self[section][key]
key = ""
self[section]["~PLACEHOLDER~"] = ";".join(val)
v = v.split("=")
if (
not key.startswith("&combinations")
and "(" not in v[0]
):
v[0] = v[0].split(",")
else:
v[0] = [v[0]]
for k in v[0]:
tmp[k] = v[1]
val = tmp
# handle request for combinations
if key.startswith("&combination"):
atoms = []
subs = []
# val <= { "2, 4": "H, CH3", "7, 9": "OH, NH2", .. }
for k, v in val.items():
if "(" not in k:
# regular substituents
atoms.append(k.split(","))
else:
# ring substitutions
atoms.append(re.findall("\(.*?\)", k))
subs.append([None] + [i for i in v.strip().split(",")])
# atoms <= [ [2, 4], [7, 9], .. ]
# subs <= [ [None, H, CH3], [None, OH, NH2], .. ]
for combo in it.product(*[range(len(s)) for s in subs]):
# combos <= (0, 0,..), (0,.., 1),..(1,.. 0),..(1,.., 1),..
if not any(combo):
# skip if no substitutions
# (already included if reopt=True)
continue
name = []
tmp = {}
for i, p in enumerate(combo):
# don't add subsitution if sub == None
if subs[i][p] is None:
continue
name.append(subs[i][p])
for a in atoms[i]:
tmp[a] = subs[i][p]
name = "_".join(name)
self._changes[name] = (
tmp,
section,
)
else:
if isinstance(val, list):
name = "_".join(val)
val = {key: ",".join(val)}
elif not key:
name = "_".join(
[
"_".join([v] * len(k.split(",")))
for k, v in val.items()
]
)
self[section][name] = self[section]["~PLACEHOLDER~"]
del self[section]["~PLACEHOLDER~"]
else:
name = key
self._changes[name] = (val, section)
def parse_functions(self):
"""
Evaluates functions supplied in configuration file
Functions indicated by "%{...}"
Pulls in values of options indicated by $option_name
Eg:
ppn = 4
memory = %{ $ppn * 2 }GB --> memory = 8GB
"""
func_patt = re.compile("(%{(.*?)})")
attr_patt = re.compile("\$([a-zA-Z0-9_:]+)")
for section in ["DEFAULT"] + self.sections():
# evaluate functions
for key, val in self[section].items():
match_list = func_patt.findall(val)
while match_list:
match = match_list.pop()
eval_match = match[1]
for attr in attr_patt.findall(match[1]):
if ":" in attr:
from_section, option = attr.split(":")
else:
option, from_section = attr, section
option = self[from_section][option]
eval_match = eval_match.replace("$" + attr, option, 1)
try:
eval_match = eval(eval_match, {})
except TypeError as e:
raise TypeError(
"{} for\n\t[{}]\n\t{} = {}\nin config file. Could not evaluate {}".format(
e.args[0], section, key, val, eval_match
)
)
except (NameError, SyntaxError):
if attr_patt.findall(eval_match):
eval_match = "%{" + eval_match.strip() + "}"
else:
eval_match = eval_match.strip()
val = val.replace(match[0], str(eval_match))
self[section][key] = val
match_list = func_patt.findall(val)
def getlist(self, section, option, *args, delim=",", **kwargs):
"""returns a list of option values by splitting on the delimiter specified by delim"""
raw = self.get(section, option, *args, **kwargs)
out = [x.strip() for x in raw.split(delim) if len(x.strip()) > 0]
return out
def read(self, filename, quiet=True):
try:
self.read_string(self._process_content(filename, quiet=quiet))
except configparser.ParsingError:
pass
def _read_config(self, infile, quiet, skip_user_default):
"""
Reads configuration information from `infile` after pulling defaults
"""
filenames = [
os.path.join(AARONTOOLS, "config.ini"),
]
if not skip_user_default:
filenames += [os.path.join(AARONLIB, "config.ini")]
if infile:
filenames += [infile]
local_only = False
job_include = None
for i, filename in enumerate(filenames):
if not quiet:
if os.path.isfile(filename):
print(" ✓", end=" ")
else:
print(" ✗", end=" ")
print(filename)
content = self._process_content(filename)
self.read(content, quiet=quiet)
if filename != infile:
try:
self.remove_option("Job", "include")
except configparser.NoSectionError:
pass
job_include = self.get("Job", "include", fallback=job_include)
# local_only can only be overridden at the user level if "False" in the system config file
if i == 0:
local_only = self["DEFAULT"].getboolean("local_only")
elif local_only:
self["DEFAULT"]["local_only"] = str(local_only)
if "Job" in self:
type_spec = [
re.search("(?<!_)type", option) for option in self["Job"]
]
else:
type_spec = []
if job_include and not any(type_spec):
self.set("Job", "include", job_include)
def get_other_kwargs(self, section="Theory"):
"""
Returns dict() that can be unpacked and passed to Geometry.write along with a theory
Example:
[Theory]
route = pop NBORead
opt MaxCycle=1000, NoEigenTest
end_of_file = $nbo RESONANCE NBOSUM E2PERT=0.0 NLMO BNDIDX $end
this adds opt(MaxCycle=1000,NoEigenTest) pop=NBORead to the route with any other
pop or opt options being added by the job type
'two-layer' options can also be specified as a python dictionary
the following is equivalent to the above example:
[Theory]
route = {"pop":["NBORead"], "opt":["MaxCycle=1000", NoEigenTest"]}
end_of_file = $nbo RESONANCE NBOSUM E2PERT=0.0 NLMO BNDIDX $end
"""
# these need to be dicts
two_layer = [
GAUSSIAN_ROUTE,
GAUSSIAN_PRE_ROUTE,
GAUSSIAN_MM,
ORCA_BLOCKS,
PSI4_JOB,
QCHEM_REM,
QCHEM_SETTINGS,
PSI4_SOLVENT,
XTB_CONTROL_BLOCKS,
XTB_COMMAND_LINE,
]
# these need to be dicts, but can only have one value
two_layer_single_value = [
PSI4_OPTKING,
PSI4_SETTINGS,
PSI4_MOLECULE,
]
# these need to be lists
one_layer = [
GAUSSIAN_COMMENT,
GAUSSIAN_CONSTRAINTS,
GAUSSIAN_POST,
GAUSSIAN_ONIOM,
GAUSSIAN_MM_PARAMS,
ORCA_COMMENT,
ORCA_ROUTE,
PSI4_AFTER_JOB,
PSI4_BEFORE_GEOM,
PSI4_BEFORE_JOB,
PSI4_COMMENT,
QCHEM_MOLECULE,
QCHEM_COMMENT,
]
theory_kwargs = [
"method",
"high_method",
"medium_method",
"low_method",
"charge",
"multiplicity",
"type",
"basis",
"high_basis",
"medium_basis",
"low_basis",
"high_ecp",
"medium_ecp",
"low_ecp",
"ecp",
"grid",
"empirical_dispersion",
]
# two layer options are separated by newline
# individual options are split on white space, with the first defining the primary layer
out = {}
for option in two_layer:
value = self[section].get(option, fallback=False)
value = self._kwargs.get(option, value)
if value:
if isinstance(value, dict):
out[option] = value
elif "{{" not in value and "{" in value:
# if it's got brackets, it's probably a python-looking dictionary
# eval it instead of parsing
# double brackets would indicate an interpolated value
# e.g. link0=chk {{ name }}.chk
out[option] = eval(value, {})
else:
out[option] = {}
for v in value.splitlines():
data = v.split()
key = data[0]
if len(data) > 1:
i = 1
info = []
while i < len(data):
word = data[i]
if word == "{{" and i < len(data) - 2:
word += " " + data[i + 1] + " " + data[i + 2]
info.extend(word.split(","))
i += 3
continue
info.extend(word.split(","))
i += 1
else:
info = []
out[option][key] = [x.strip() for x in info]
for option in two_layer_single_value:
value = self.get(section, option, fallback=False)
value = self._kwargs.get(option, value)
if value:
if "{" in value:
out[option] = eval(value, {})
else:
out[option] = {}
for v in value.splitlines():
key = v.split()[0]
if len(v.split()) > 1:
info = [v.split()[1]]
else:
info = []
out[option][key] = [x.strip() for x in info]
for option in one_layer:
value = self[section].get(option, fallback=False)
value = self._kwargs.get(option, value)
if value:
out[option] = value.splitlines()
for option in theory_kwargs:
value = self[section].get(option, fallback=False)
if value:
out[option] = value
return out
def get_constraints(self, geometry):
constraints = {}
try:
con_list = []
word = ""
constraint_str = self["Geometry"]["constraints"]
# print(constraint_str)
i = 0
while i < len(constraint_str):
x = constraint_str[i]
# print(i, x, word)
if x.strip() and x != "(":
word += x
i += 1
elif word:
con_list.append(word)
word = ""
i += 1
if x == "(":
word = to_closing(constraint_str[i:], "(")
con_list.append(word)
i += len(word) - 1
word = ""
if word:
con_list.append(word)
except KeyError:
try:
geometry.parse_comment()
con_list = geometry.other["constraint"]
except KeyError:
raise RuntimeError(
"Constraints for forming/breaking bonds must be specified for TS search"
)
# print(con_list)
for con in con_list:
# print(con)
if "(" in con:
c = eval(con)
tmp = geometry.find(list(c))
if len(con) == 2:
constraints.setdefault("bonds", [])
constraints["bonds"] += [tmp]
elif len(con) == 3:
constraints.setdefault("angles", [])
constraints["angles"] += [tmp]
elif len(con) == 4:
constraints.setdefault("torsions", [])
constraints["torsions"] += [tmp]
else:
constraints.setdefault("atoms", [])
constraints["atoms"].extend(geometry.find(con))
# print("constraints", constraints, flush=True)
return constraints
def get_theory(self, geometry, section="Theory"):
"""
Get the theory object according to configuration information
"""
if not self.has_section(section):
self.LOG.warning(
'config has no "%s" section, switching to "Theory"' % section
)
section = "Theory"
kwargs = self.get_other_kwargs(section=section)
theory = Theory(*self._args, geometry=geometry, **kwargs)
theory.processors = self["Job"].getint("procs", fallback=None)
theory.memory = self["Job"].getint("exec_memory", fallback=None)
# build ImplicitSolvent object
if self[section].get("solvent", fallback="gas") == "gas":
theory.solvent = None
elif self[section]["solvent"]:
solvent_model = self.get(section, "solvent_model", fallback=False)
theory.solvent = ImplicitSolvent(
solvent_model,
self[section]["solvent"],
)
# build JobType list
job_type = self["Job"].get("type", fallback=False)
if job_type:
theory.job_type = []
numerical = self[section].get("numerical", fallback=False)
temperature = self[section].get("temperature", fallback=298.15)
try:
constraints = self.get_constraints(theory.geometry)
except RuntimeError:
constraints = None
theory.geometry.freeze()
theory.geometry.relax(self._changed_list)
info = {
"numerical": numerical,
"temperature": temperature,
"constraints": constraints,
"geometry": theory.geometry,
}
try:
theory.job_type += [job_from_string(job_type, **info)]
except ValueError:
raise ValueError("cannot parse job type: %s" % ".".join(job_type))
else:
# default to opt+freq
theory.job_type = [
OptimizationJob(geometry=geometry),
FrequencyJob(
numerical=self[section].get("numerical", fallback=False),
temperature=self[section].get(
"temperature", fallback=None
),
),
]
# return updated theory object
return theory
def get_template(self):
from AaronTools.geometry import Geometry
# captures name placeholder and iterator from for-loop initilaizer
for_patt = re.compile("&for\s+(.+)\s+in\s+(.+)")
# captures structure_dict-style structure/suffix -> (structure['suffix'], suffix)
parsed_struct_patt = re.compile("(structure\['(\S+?)'\])\.?")
# captures config-style structure/suffix -> (structure.suffix, suffix)
structure_patt = re.compile("(structure\.([^\(\s\.]+))\.?")
def get_multiple(filenames, path=None, suffix=None):
rv = []
for name in filenames:
kind = "Minimum"
if name.startswith("TS"):
kind = "TS"
if path is not None:
name = os.path.join(path, name)
if not os.path.isfile(name):
continue
geom = AaronTools.geometry.Geometry(name)
if suffix is not None:
geom.name += ".{}".format(suffix)
rv += [(geom, kind)]
return rv
def structure_assignment(line):
# assignments must be done outside of eval()
# left -> structure.suffix -> structure_dict["suffix"]
# right -> eval(right)
# left = right -> structure_dict[suffix] = eval(right)
left = line.split("=")[0].strip()
right = line.split("=")[1].strip()
suffix_match = parsed_struct_patt.search(left)
if suffix_match is None:
raise RuntimeError(
"Can only assign to Geometry objects with names of the form `structure.suffix`"
)
suffix = suffix_match.group(2)
structure_dict[suffix] = eval(right, eval_dict)
structure_dict[suffix].name = ".".join(
structure_dict[suffix].name.split(".")[:-1] + [suffix]
)
if structure_dict[suffix].name.startswith("TS"):
kind_dict[suffix] = "TS"
def structure_suffix_parse(line, for_loop=None):
if for_loop is not None:
for_match, it_val = for_loop
for structure_match in structure_patt.findall(line):
if getattr(AaronTools.geometry.Geometry, structure_match[1], False):
continue
# if our suffix is not the iterator, keep it's value for the dict key
if for_loop is None or structure_match[1] != for_match.group(
1
):
suffix = structure_match[1]
else:
suffix = str(it_val)
# change to dict-style syntax (structure.suffix -> structure["suffix"])
line = line.replace(
structure_match[0],
"structure['{}']".format(suffix),
)
if suffix not in structure_dict:
structure_dict[suffix] = AaronTools.geometry.Geometry()
kind_dict[suffix] = None
return line
structure_dict = {}
kind_dict = {}
structure_list = []
# load templates from AARONLIB
if "Reaction" in self:
path = None
if "template" in self["Reaction"]:
path = os.path.join(
AARONLIB,
"template_geoms",
self["Reaction"]["reaction"],
self["Reaction"]["template"],
)
for dirpath, dirnames, filenames in os.walk(path):
structure_list += get_multiple(filenames, path=dirpath)
else:
path = os.path.join(
AARONLIB,
"template_geoms",
self["Reaction"]["reaction"],
)
for dirpath, dirnames, filenames in os.walk(path):
structure_list += get_multiple(filenames, path=dirpath)
for structure, kind in structure_list:
structure.name = os.path.relpath(structure.name, path)
if not self.has_section("Geometry"):
return structure_list
# load templates from config[Geometry]
# store in structure_dict, keyed by structure option suffix
# `structure.suffix = geom.xyz` store as {suffix: geom.xyz}
# `structure = geom.xyz` (no suffix), store as {"": geom.xyz}
if "structure" in self["Geometry"]:
structure_dict[""] = self["Geometry"]["structure"]
else:
for key in self["Geometry"]:
if key.startswith("structure."):
suffix = ".".join(key.split(".")[1:])
structure_dict[suffix] = self["Geometry"][key]
# create Geometry objects
pop_sd = set([])
for suffix, structure in structure_dict.items():
if structure is not None and os.path.isdir(structure):
# if structure is a directory
for dirpath, dirnames, filenames in os.walk(structure):
structure_list += get_multiple(
filenames, path=dirpath, suffix=suffix
)
elif structure is not None:
try:
# if structure is a filename
structure = Geometry(structure)
except FileNotFoundError:
# if structure is a filename
structure = Geometry(
os.path.join(self["DEFAULT"]["top_dir"], structure)
)
except (IndexError, NotImplementedError):
if "coordination_complex" in structure.lower():
shape = None
center = None
ligands = None
for line in structure.splitlines():
line = line.strip()
if "coordination_complex" in line.lower():
shape = re.split("[:=]", line)[1].strip()
if "center" in line.lower():
center = re.split("[:=]", line)[1].strip()
if "ligands" in line.lower():
ligands = (
re.split("[:=]", line)[1].strip().split()
)
for (
geom
) in Geometry.get_coordination_complexes(
center=center, ligands=ligands, shape=shape
)[
0
]:
if suffix:
geom.name += "." + suffix
structure_list += [(geom, None)]
structure = None
pop_sd.add(suffix)
else:
# if structure is a smiles string
structure = Geometry.from_string(
structure
)
# adjust structure attributes
if structure is not None:
if self.has_option("Job", "name"):
structure.name = self["Job"]["name"]
elif self.has_option("","name"):
structure.name = self["DEFAULT"]["name"]
if "Geometry" in self and "comment" in self["Geometry"]:
structure.comment = self["Geometry"]["comment"]
structure.parse_comment()
structure_dict[suffix] = structure
kind_dict[suffix] = None
for s in pop_sd:
del structure_dict[s]
# for loop for structure modification/creation
# structure.suffix = geom.xyz
# &for name in <iterator>:
# structure.name = structure.suffix.copy()
# structure.name.method_call(*args, **kwargs)
if "Geometry" in self:
for key in self["Geometry"]:
if not key.startswith("&for"):
continue
for_match = for_patt.search(key)
if for_match is None:
raise SyntaxError(
"Malformed &for loop specification in config"
)
lines = self["Geometry"][key].split("\n")
for it_val in eval(for_match.group(2), {}):
eval_dict = {
"Geometry": Geometry,
"structure": structure_dict,
for_match.group(1): it_val,
}
for line in lines:
line = line.strip()
if not line:
continue
line = structure_suffix_parse(
line,
for_loop=(for_match, it_val),
)
if "=" in line:
structure_assignment(line)
else:
eval(line, eval_dict)
# add structure_dict to structure list
try:
padding = max(
[
len(suffix)
for suffix in structure_dict.keys()
if suffix.isnumeric()
]
)
except ValueError:
padding = 0
for suffix in structure_dict:
geom = structure_dict[suffix]
if suffix and self.has_option("Job", "name"):
geom.name = "{}.{}".format(
self["Job"]["name"], suffix.zfill(padding)
)
structure_list += [(geom, kind_dict[suffix])]
# apply functions found in [Geometry] section
if "Geometry" in self and "&call" in self["Geometry"]:
eval_dict = {
"Geometry": AaronTools.geometry.Geometry,
"structure": structure_dict,
}
lines = self["Geometry"]["&call"]