-
Notifications
You must be signed in to change notification settings - Fork 8
/
fileIO.py
5972 lines (5364 loc) · 247 KB
/
fileIO.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
"""For parsing input/output files"""
import os
import re
import sys
from copy import deepcopy
from io import IOBase, StringIO
from math import ceil
import numpy as np
from AaronTools import addlogger
from AaronTools.atoms import Atom
from AaronTools.const import AARONTOOLS
from AaronTools.oniomatoms import OniomAtom
from AaronTools.const import ELEMENTS, PHYSICAL, UNIT
from AaronTools.orbitals import Orbitals
from AaronTools.spectra import (
Frequency,
ValenceExcitations,
NMR,
)
from AaronTools.theory import *
from AaronTools.utils.utils import (
is_alpha,
is_int,
is_num,
float_num,
perp_vector,
rotation_matrix,
angle_between_vectors,
)
read_types = [
"xyz",
"log",
"com",
"gjf",
"sd",
"sdf",
"mol",
"mol2",
"out",
"dat",
"fchk",
"pdb",
"pdbqt",
"cif",
"mmcif",
"crest",
"xtb",
"sqmout",
"47",
"31",
"qout",
]
write_types = ["xyz", "com", "inp", "inq", "in", "sqmin", "cube", "xtb", "crest", "mol"]
file_type_err = "File type not yet implemented: {}"
#LAH_bonded_to = re.compile("(LAH) bonded to ([0-9]+)")
#LA_atom_type = re.compile("(?<=')[A-Z][A-Z](?=')")
#LA_charge = re.compile("[-+]?[0-9]*\.[0-9]+")
#LA_bonded_to = re.compile("(?<=')([0-9][0-9]?)(?![0-9 A-Z\.])(?=')")
#Svalue = re.compile("(?<=diff= +)-?[0-9]+\.[0-9]+")
NORM_FINISH = "Normal termination"
ORCA_NORM_FINISH = "****ORCA TERMINATED NORMALLY****"
PSI4_NORM_FINISH = "*** Psi4 exiting successfully. Buy a developer a beer!"
ERROR = {
"Fatal Problem: The smallest alpha delta epsilon is": "OMO_UMO_GAP",
"SCF has not converged. Gradients and post-SCF results would be GARBAGE!!": "SCF_CONV",
"Convergence failure -- run terminated.": "SCF_CONV",
"Inaccurate quadrature in CalDSu": "CONV_CDS",
"Error termination request processed by link 9999": "OPT_CONV",
"FormBX had a problem": "FBX",
"NtrErr Called from FileIO": "CHK",
"Wrong number of Negative eigenvalues": "EIGEN",
"Erroneous write": "QUOTA",
"Atoms too close": "CLASH",
"Small interatomic distances encountered:": "CLASH",
"The combination of multiplicity": "CHARGEMULT",
"Bend failed for angle": "REDUND",
"Linear angle in Bend": "REDUND",
"Error in internal coordinate system": "COORD",
"galloc: could not allocate memory": "GALLOC",
"Error imposing constraints": "CONSTR",
"End of file reading basis center.": "BASIS_READ",
re.compile("Atomic number out of range for .* basis set."): "BASIS",
"Unrecognized atomic symbol": "ATOM",
"malloc failed.": "MEM",
"A syntax error was detected in the input line": "SYNTAX",
"Unknown message": "UNKNOWN",
"Atoms in 1 layers were given but there should be 2": "LAYER",
"MM function not complete": "MM_PARAM",
"PCMIOp: Cannot load options.": "PCM",
"Unrecognized potential number 6 in GetPot": "TYPO",
"Inv3 failed in PCMMkU": "PCM",
}
ERROR_ORCA = {
"ORCA finished by error termination in SCF": "SCF_CONV",
"SCF NOT CONVERGED AFTER": "SCF_CONV",
# ORCA doesn't actually exit if the SCF doesn't converge...
# "CONV_CDS": "",
"The optimization did not converge but reached the maximum": "OPT_CONV",
# ORCA still prints the normal finish line if opt doesn't converge...
# "FBX": "",
# "CHK": "",
# "EIGEN": "", <- ORCA doesn't seem to have this
# "QUOTA": "",
"Zero distance between atoms": "CLASH", # <- only get an error if atoms are literally on top of each other
"Error : multiplicity": "CHARGEMULT",
# "REDUND": "",
# "REDUND": "",
# "GALLOC": "",
# "CONSTR": "",
"The basis set was either not assigned or not available for this element": "BASIS",
"Element name/number, dummy atom or point charge expected": "ATOM",
"Error (ORCA_SCF): Not enough memory available!": "MEM",
"WARNING: Analytical MP2 frequency calculations": "NUMFREQ",
"WARNING: Analytical Hessians are not yet implemented for meta-GGA functionals": "NUMFREQ",
"ORCA finished with error return": "UNKNOWN",
"UNRECOGNIZED OR DUPLICATED KEYWORD(S) IN SIMPLE INPUT LINE": "TYPO",
}
# some exceptions are listed in https://psicode.org/psi4manual/master/_modules/psi4/driver/p4util/exceptions.html
ERROR_PSI4 = {
"PsiException: Could not converge SCF iterations": "SCF_CONV",
"psi4.driver.p4util.exceptions.SCFConvergenceError: Could not converge SCF iterations": "SCF_CONV",
"OptimizationConvergenceError": "OPT_CONV",
"TDSCFConvergenceError": "TDCF_CONV",
"The INTCO_EXCEPTion handler": "INT_COORD",
# ^ this is basically psi4's FBX
# "CONV_CDS": "",
# "CONV_LINK": "",
# "FBX": "",
# "CHK": "",
# "EIGEN": "", <- psi4 doesn't seem to have this
# "QUOTA": "",
# "ValidationError:": "INPUT", <- generic input error, CHARGEMULT and CLASH would also get caught by this
"qcelemental.exceptions.ValidationError: Following atoms are too close:": "CLASH",
"qcelemental.exceptions.ValidationError: Inconsistent or unspecified chg/mult": "CHARGEMULT",
"MissingMethodError": "INVALID_METHOD",
# "REDUND": "",
# "REDUND": "",
# "GALLOC": "",
# "CONSTR": "",
"psi4.driver.qcdb.exceptions.BasisSetNotFound: BasisSet::construct: Unable to find a basis set for": "BASIS",
"qcelemental.exceptions.NotAnElementError": "ATOM",
"psi4.driver.p4util.exceptions.ValidationError: set_memory()": "MEM",
# ERROR_PSI4[""] = "UNKNOWN",
"Could not converge backtransformation.": "ICOORDS",
}
def step2str(step):
if int(step) == step:
return str(int(step))
else:
return str(step).replace(".", "-")
def str2step(step_str):
if "-" in step_str:
return float(step_str.replace("-", "."))
else:
return float(step_str)
def expected_inp_ext(exec_type):
"""
extension expected for an input file for exec_type
* Gaussian - .com (.gjf on windows)
* ORCA - .inp
* Psi4 - .in
* SQM - .mdin
* qchem - .inp
"""
if exec_type.lower() == "gaussian":
if sys.platform.startswith("win"):
return ".gjf"
return ".com"
if exec_type.lower() == "orca":
return ".inp"
if exec_type.lower() == "psi4":
return ".in"
if exec_type.lower() == "sqm":
return ".mdin"
if exec_type.lower() == "qchem":
return ".inp"
def expected_out_ext(exec_type):
"""
extension expected for an input file for exec_type
* Gaussian - .log
* ORCA - .out
* Psi4 - .out
* SQM - .mdout
* qchem - .out
"""
if exec_type.lower() == "gaussian":
return ".log"
if exec_type.lower() == "orca":
return ".out"
if exec_type.lower() == "psi4":
return ".out"
if exec_type.lower() == "sqm":
return ".mdout"
if exec_type.lower() == "qchem":
return ".out"
class FileWriter:
"""
class for handling file writing
"""
@classmethod
def write_file(
cls, geom, style=None, append=False, outfile=None, *args, **kwargs
):
"""
Writes file from geometry in the specified style
:param Geometry geom: the Geometry to use
:param str style: the file type style to generate
Currently supported options: "xyz" (default), "com",
"inp", "inq", "in", "sqmin", "cube", "xtb", "crest", "mol"
if outfile has one of these extensions, default is that style
:param bool append: for *.xyz, append geometry to the same file
:param str|None|False outfile: output destination - default is
[geometry name] + [extension] or [geometry name] + [step] + [extension]
:param str kwargs: allowed kwargs:
* oniom
* models
* theory
if outfile is False, no output file will be written, but the contents will be returned
:param Theory theory: for com, inp, and in files, an object with a get_header and get_footer method
"""
if isinstance(outfile, str) and style is None:
name, ext = os.path.splitext(outfile)
style = ext.strip(".")
elif style is None:
style = "xyz"
if style.lower() not in write_types:
if style.lower() == "gaussian":
style = "com"
elif style.lower() == "orca":
style = "inp"
elif style.lower() == "psi4":
style = "in"
elif style.lower() == "sqm":
style = "sqmin"
elif style.lower() == "qchem":
style = "inq"
elif style.lower() == "pdb":
style = "pdb"
else:
raise NotImplementedError(file_type_err.format(style))
if (
outfile is None and
os.path.dirname(geom.name) and
not os.access(os.path.dirname(geom.name), os.W_OK)
):
os.makedirs(os.path.dirname(geom.name))
elif (
isinstance(outfile, str) and
os.path.dirname(outfile) and
not os.access(os.path.dirname(outfile), os.W_OK)
):
os.makedirs(os.path.dirname(outfile))
if style.lower() == "xyz":
if "oniom" in kwargs and "models" not in kwargs:
out = cls.write_oniom_xyz(geom, append, outfile, **kwargs)
elif "oniom" in kwargs and "models" in kwargs:
out = cls.write_multi_xyz(geom, append, outfile, **kwargs)
else:
out = cls.write_xyz(geom, append, outfile, **kwargs)
elif style.lower() == "mol":
out = cls.write_mol(geom, outfile=outfile)
elif style.lower() == "com":
if "theory" in kwargs:
theory = kwargs["theory"]
del kwargs["theory"]
else:
raise TypeError(
"when writing 'com/gjf' files, **kwargs must include: theory=Aaron.Theory() (or AaronTools.Theory())"
)
out = cls.write_com(geom, theory, outfile, **kwargs)
elif style.lower() == "inp":
if "theory" in kwargs:
theory = kwargs["theory"]
del kwargs["theory"]
out = cls.write_inp(geom, theory, outfile=outfile, **kwargs)
else:
raise TypeError(
"when writing 'inp' files, **kwargs must include: theory=Aaron.Theory() (or AaronTools.Theory())"
)
elif style.lower() == "in":
if "theory" in kwargs:
theory = kwargs["theory"]
del kwargs["theory"]
out = cls.write_in(geom, theory, outfile=outfile, **kwargs)
else:
raise TypeError(
"when writing 'in' files, **kwargs must include: theory=Aaron.Theory() (or AaronTools.Theory())"
)
elif style.lower() == "sqmin":
if "theory" in kwargs:
theory = kwargs["theory"]
del kwargs["theory"]
out = cls.write_sqm(geom, theory, outfile=outfile, **kwargs)
else:
raise TypeError(
"when writing 'sqmin' files, **kwargs must include: theory=Aaron.Theory() (or AaronTools.Theory())"
)
elif style.lower() == "inq":
if "theory" in kwargs:
theory = kwargs["theory"]
del kwargs["theory"]
out = cls.write_inq(geom, theory, outfile=outfile, **kwargs)
else:
raise TypeError(
"when writing 'inq' files, **kwargs must include: theory=Aaron.Theory() (or AaronTools.Theory())"
)
elif style.lower() == "xtb":
if "theory" in kwargs:
theory = kwargs["theory"]
del kwargs["theory"]
out = cls.write_xtb(geom, theory, outfile=outfile, **kwargs)
else:
raise TypeError(
"when writing 'xtb' files, **kwargs must include: theory=Aaron.Theory() (or AaronTools.Theory())"
)
elif style.lower() == "crest":
if "theory" in kwargs:
theory = kwargs["theory"]
del kwargs["theory"]
out = cls.write_crest(geom, theory, outfile=outfile, **kwargs)
else:
raise TypeError(
"when writing 'crest' files, **kwargs must include: theory=Aaron.Theory() (or AaronTools.Theory())"
)
elif style.lower() == "cube":
out = cls.write_cube(geom, outfile=outfile, **kwargs)
elif style.lower() == "pdb":
out = cls.write_pdb(geom, append, outfile=outfile, **kwargs)
return out
@classmethod
def write_xyz(cls, geom, append, outfile=None, comment=None, **kwargs):
"""
write xyz file (file with coordinate system of input geometry)
:param Geometry geom: molecule(s) to be written to the output
:param bool append: whether the output should be appended to a file (True) or overwrite (False)
:param str outfile: filename to append/write output to
| Default/None: output file is the name of the geometry object provided (e.g. benzene.xyz if geom.name = 'benzene')
| False: method simply returns the contents of the output file instead of writing/appending.
:param str comment: comment to be added to the output
Default/None: comment is the same as the geom object's comment
:returns: xyz file contents if outfile=False, otherwise no return value
:rtype: str
"""
mode = "a" if append else "w"
fmt = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f}\n"
s = "%i\n" % len(geom.atoms)
if comment is None:
s += "%s\n" % geom.comment
else:
s += comment.strip() + "\n"
for atom in geom.atoms:
s += fmt.format(atom.element, *atom.coords)
if outfile is None:
# if no output file is specified, use the name of the geometry
with open(geom.name + ".xyz", mode) as f:
f.write(s)
elif outfile is False:
# if no output file is desired, just return the file contents
return s.strip()
else:
# write output to the requested destination
with open(outfile, mode) as f:
f.write(s)
return
@classmethod
def write_multi_xyz(cls, geom, append, outfile=None, **kwargs):
"""
write multiple oniom xyz files from geometry with multiple poses such as a pdb derived geometry
:param Geometry geom: molecule(s) to be written to the outputs
:param bool append: whether the output should be appended to a file (True) or overwrite (False)
:param str outfile: filename to append/write output to
| Default/None: output file is the name of the geometry object provided (e.g. benzene.xyz if geom.name = 'benzene')
| False: method simply returns the contents of the output file instead of writing/appending.
kwargs["models"] can be string "all", string of model number e.g. "2", string of model range e.g. "1-5",
or list of model numbers including ranges e.g. ["1", "3-5", "10"]
kwargs["oniom"] can be string "all" or string "frag" which requires a specification of the fragment in another kwarg
kwargs["layer"] can be defined if kwargs["oniom"] == "frag", can be "H", "M", or "L"
"""
models = None
geom_list = [geom]
if "models" in kwargs.keys():
models = kwargs["models"]
if models is not None:
if isinstance(models, str):
if models != "all":
try:
models = int(models)
models = ["model_%s" % str(models)]
except ValueError:
if "-" in models:
models = models.split("-")
model_list = []
for i in range(int(models[0]), int(models[1])+1):
model_list.append("models_%s" % str(i))
models = model_list
else: raise ValueError("improper specification of included models")
elif isinstance(models, list):
model_list = []
for model in models:
if "-" in model:
model = model.split("-")
for i in range(int(model[0]), int(model[1])+1):
model_list.append("model_%s" % str(i))
else:
model_list.append("model_%s" % str(model))
models = model_list
for key in geom.other.keys():
if key.startswith("model"):
if models == "all":
geom_list.append(Geometry(structure=geom.other[key], name=geom.name + "_" + key, refresh_connected=False, refresh_ranks = False))
elif isinstance(models, list):
if key in models:
geom_list.append(Geometry(structure=geom.other[key], name=geom.name + "_" + key, refresh_connected=False, refresh_ranks = False))
counter = 0
for geom in geom_list:
if outfile == False:
FileWriter.write_oniom_xyz(geom, append, outfile = False, **kwargs)
elif outfile==None:
FileWriter.write_oniom_xyz(geom, append, outfile = geom.name, **kwargs)
else:
counter += 1
outfile_name = outfile.split(".")[0] + "_" + str(counter) + "." + outfile.split(".")[1]
FileWriter.write_oniom_xyz(geom, append, outfile = outfile_name, **kwargs)
return
@classmethod
def write_oniom_xyz(cls, geom, append, outfile=None, **kwargs):
"""
write xyz files with additional columns for atomtype, charge, and link atom info
:param Geometry geom: molecule(s) to be written to the outputs
:param bool append: whether the output should be appended to a file (True) or overwrite (False)
:param str outfile: filename to append/write output to
| Default/None: output file is the name of the geometry object provided (e.g. benzene.xyz if geom.name = 'benzene')
| False: method simply returns the contents of the output file instead of writing/appending.
kwargs["oniom"] can be string "all" or string "frag" which requires a specification of the fragment in another kwarg
kwargs["layer"] can be defined if kwargs["oniom"] == "frag", can be "H", "M", or "L"
"""
frag = kwargs["oniom"]
if frag == 'all':
geom.sub_links()
elif frag == 'layer':
geom=geom.oniom_frag(layer=kwargs["layer"], as_object=True)
mode = "a" if append else "w"
fmt1a = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f} {:2s} {:3s} {: 8.6f} {:2s} {:2s} {: 8.6f} {:2d}\n"
fmt1b = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f} {:2s} {:3s} {:2s} {:2s} {:2d}\n"
fmt1c = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f} {:2s} {: 8.6f} {:2s} {: 8.6f} {:2d}\n"
fmt1d = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f} {:2s} {:2s} {:2d}\n"
fmt2a = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f} {:2s} {:3s} {: 8.6f}\n"
fmt2b = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f} {:2s} {:3s}\n"
fmt2c = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f} {:2s} {: 8.6f}\n"
fmt2d = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f} {:2s}\n"
fmt3 = "{:3s} {: 10.5f} {: 10.5f} {: 10.5f} \n"
s = "%i\n" % len(geom.atoms)
s += "%s\n" % geom.comment
for atom in geom.atoms:
if atom.link_info:
if "atomtype" not in atom.link_info.keys():
connected_elements = []
for connected in atom.connected:
connected_elements.append(connected.element)
if "C" in connected_elements:
atom.link_info["atomtype"] = "hc"
elif "C" not in connected_elements and "N" in connected_elements:
atom.link_info["atomtype"] = "hn"
elif "C" not in connected_elements and "O" in connected_elements:
atom.link_info["atomtype"] = "ho"
elif "C" not in connected_elements and "S" in connected_elements:
atom.link_info["atomtype"] = "hs"
elif "C" not in connected_elements and "P" in connected_elements:
atom.link_info["atomtype"] = "hp"
if "charge" not in atom.link_info.keys():
atom.link_info["charge"] = atom.charge
if "element" not in atom.link_info.keys():
atom.link_info["element"] = "H"
if "connected" not in atom.link_info.keys():
print("Determining link atom connection from connectivity")
for connected in atom.connected:
if connected.layer == "":
raise ValueError("cannot determine link atom connection without defined layers")
elif connected.layer != atom.layer:
for i, a in enumerate(geom.atoms):
if a == connected:
atom.link_info["connected"] = i+1
break
if "connected" not in atom.link_info.keys():
raise ValueError("Cannot determine link atom connection based on layers")
try:
if atom.atomtype != "" and atom.charge != "" and atom.link_info:
s += fmt1a.format(atom.element, *atom.coords, atom.layer, atom.atomtype, atom.charge, atom.link_info["element"], atom.link_info["atomtype"], float(atom.link_info["charge"]), int(atom.link_info["connected"]))
elif atom.atomtype != "" and atom.charge == "" and atom.link_info:
s += fmt1b.format(atom.element, *atom.coords, atom.layer, atom.atomtype, atom.link_info["element"], atom.link_info["atomtype"], int(atom.link_info["connected"]))
elif atom.atomtype == "" and atom.charge != "" and atom.link_info:
s += fmt1c.format(atom.element, *atom.coords, atom.layer, atom.charge, atom.link_info["element"], float(atom.link_info["charge"]), int(atom.link_info["connected"]))
elif atom.atomtype == "" and atom.charge == "" and atom.link_info:
s += fmt1d.format(atom.element, *atom.coords, atom.layer, atom.link_info["element"], int(atom.link_info["connected"]))
elif atom.atomtype != "" and atom.charge != "" and not atom.link_info:
s += fmt2a.format(atom.element, *atom.coords, atom.layer, atom.atomtype, atom.charge)
elif atom.atomtype != "" and atom.charge == "" and not atom.link_info:
s += fmt2b.format(atom.element, *atom.coords, atom.layer, atom.atomtype)
elif atom.atomtype == "" and atom.charge != "" and not atom.link_info:
s += fmt2c.format(atom.element, *atom.coords, atom.layer, atom.charge)
elif atom.atomtype == "" and atom.charge == "" and not atom.link_info:
s += fmt2d.format(atom.element, *atom.coords, atom.layer)
except ValueError:
self.LOG.warning("no layers designated for OniomAtom object(s)")
s += fmt3.format(atom.element, *atom.coords)
s = s.rstrip()
if outfile is None:
#if no output file is specified, use the name of the geometry
with open(geom.name + ".xyz", mode) as f:
f.write(s)
elif outfile is False:
#if no output file is desired, just return the file contents
return s
else:
#write output to the requested destination
with open(outfile, mode) as f:
f.write(s)
return
@classmethod
def write_mol(
cls, geom, outfile=None, **kwargs
):
"""
write V2000 mol file
:param Geometry geom: molecule(s) to be written
:param str outfile: file to be written to
| Default/None: output file is the name of the geometry object provided (e.g. benzene.mol if geom.name = 'benzene')
| False: method simply returns the contents of the output file instead of writing.
"""
from AaronTools.finders import ChiralCenters
from AaronTools.const import ELECTRONEGATIVITY
elements = geom.element_counts()
s = ""
for ele, n in sorted(elements.items(), key=lambda ele: -1 if ele[0] == "C" else ELEMENTS.index(ele[0])):
s += "%s%i" % (ele, n)
s += "\nAaronTools\n%s\n" % geom.comment
def bond_order_to_code(x):
if x == 1.5:
return 4
return int(x)
atom_block = ""
bond_block = ""
n_bonds = 0
for i, atom in enumerate(geom.atoms):
atom_block += "%10.4f%10.4f%10.4f %3s 0%3i 0 0 0 0 0 0 0 0\n" % (
*atom.coords,
atom.element,
0 # if not hasattr(atom, "_saturation") else len(atom.connected) - atom._saturation,
)
n_bonds += len(atom.connected)
try:
geom.find(ChiralCenters())
chiral = True
except LookupError:
chiral = False
s += "%3i%3i 0 0%3i 0 0 0 0 0 0 V2000\n" % (
len(geom.atoms),
n_bonds // 2,
1 if chiral else 0,
)
s += atom_block
# determine bond info
# need to be extra careful with aromatic bonds b/c
# sometimes conjugated bonds look like aromatic to AaronTools
# only atoms in a ring should have aromatic bonds, and those
# bonds should only be to atoms in the same ring
rings = []
bonds = dict()
ndx = {atom: i for i, atom in enumerate(geom.atoms)}
for atom in geom.atoms:
for i, atom2 in enumerate(atom.connected):
bond_order = atom.bond_order(atom2)
if ndx[atom] < ndx[atom2]:
bonds[(atom, atom2)] = bond_order
for atom3 in list(atom.connected)[:i]:
try:
path = geom.shortest_path(atom2, atom3, avoid=atom)
rings.append(set([*path, atom]))
except LookupError:
pass
for bond, order in bonds.items():
if order == 1.5:
for ring in rings:
if len(ring.intersection(bond)) == 2:
break
elif len(ring.intersection(bond)) == 1:
bonds[bond] = 1
break
else:
# flip the sign to show that this is something AaronTools
# says is aromatic, but isn't in a ring
if bonds[bond] == 1.5:
bonds[bond] *= -1
# group delocalized bonds together
contiguous_aro_bonds = []
for bond, order in bonds.items():
if order < 0:
for group in contiguous_aro_bonds:
if group.intersection(bond):
group.update(bond)
break
else:
contiguous_aro_bonds.append(set(bond))
for i, group in enumerate(contiguous_aro_bonds):
pass
# print(i)
# for atom in group:
# print(atom)
# print("\n\n")
# combine groups of delocalized bonds if they overlap
overlapping_groups = False
for i, group1 in enumerate(contiguous_aro_bonds):
for group2 in contiguous_aro_bonds[:i]:
if group1.intersection(group2):
overlapping_groups = True
while overlapping_groups:
overlapping_groups = False
for i, group1 in enumerate(contiguous_aro_bonds):
found_overlap = False
for j, group2 in enumerate(contiguous_aro_bonds[:i]):
if group1.intersection(group2):
group1.update(group2)
found_overlap = True
contiguous_aro_bonds.pop(j)
break
if found_overlap:
break
for i, group1 in enumerate(contiguous_aro_bonds):
for group2 in contiguous_aro_bonds[:i]:
if group1.intersection(group2):
overlapping_groups = True
# finding the longest path from one atom to another in a group
# will give us the chain in order
for group in contiguous_aro_bonds:
longest_path = []
for i, atom1 in enumerate(group):
for atom2 in list(group)[:i]:
avoid = [atom for atom in atom1.connected if atom not in group]
avoid.extend([atom for atom in atom2.connected if atom not in group])
path = geom.shortest_path(
atom1, atom2, avoid,
)
if len(path) > len(longest_path):
longest_path = path
# there might be branches coming off of the main chain
branches = [longest_path]
excluded = group - set(longest_path)
included = group.intersection(longest_path)
while excluded:
for branch in branches:
for atom in branch[1:-1]:
branch_added = False
for atom2 in atom.connected.intersection(excluded):
longest_path = []
for atom3 in excluded - set([atom2]):
try:
path = geom.shortest_path(
atom2, atom3, avoid=included,
)
if len(path) > len(longest_path):
longest_path = path
except LookupError:
pass
if longest_path:
branches.append(longest_path)
branch_added = True
break
if branch_added:
excluded = excluded - set(branches[-1])
included = included.union(set(branches[-1]))
for branch in branches:
# if a branch one has two atoms (one bond), look
# at the neighbors of this to determine a better
# bond order
if len(branch) == 2:
branch_bond = (branch[0], branch[1])
if ndx[branch[0]] > ndx[branch[1]]:
branch_bond = (branch[1], branch[0])
total_diff = 0
for atom in branch:
for neighbor in atom.connected - set(branch):
total_diff += neighbor._saturation
for neighbor2 in neighbor.connected:
bond = (neighbor, neighbor2)
if ndx[neighbor] > ndx[neighbor2]:
bond = (neighbor2, neighbor)
if bonds[bond] > 0:
total_diff -= bonds[bond]
else:
total_diff -= 1
if total_diff <= 1:
bonds[branch_bond] = 1
continue
# for longer chains, just alternate double and single bonds
# favor double bonds at the more electronegative side of the chain?
# maybe there's a better way
start_e_nrg = sum(ELECTRONEGATIVITY[atom.element] for atom in branch[:2])
end_e_nrg = sum(ELECTRONEGATIVITY[atom.element] for atom in branch[-2:])
if end_e_nrg > start_e_nrg:
branch.reverse()
for i, atom in enumerate(branch[:-1]):
atom2 = branch[i + 1]
bond = (atom, atom2)
if ndx[atom] > ndx[atom2]:
bond = (atom2, atom)
if i % 2 == 0:
bonds[bond] = 2
else:
bonds[bond] = 1
for bond in bonds:
# print(bond, bonds[bond])
bond_block += "%3i%3i%3i 0 0 0 0\n" % (
ndx[bond[0]] + 1, ndx[bond[1]] + 1, bond_order_to_code(bonds[bond])
)
s += bond_block
s += "M END\n"
if outfile is None:
# if no output file is specified, use the name of the geometry
with open(geom.name + ".mol", "w") as f:
f.write(s)
elif outfile is False:
# if no output file is desired, just return the file contents
return s.strip()
else:
# write output to the requested destination
with open(outfile, "w") as f:
f.write(s)
@classmethod
def write_com(
cls, geom, theory, outfile=None, return_warnings=False, **kwargs
):
"""
write Gaussian input file for given Theory and Geometry
:param Geometry geom: structure
:param Theory theory: input file parameters
:param None|False|str outfile:
output file option
* None - geom.name + ".com" is used as output destination
* False - return contents of the input file as a str
* str - output destination
:param bool return_warnings: True to return a list of warnings (e.g. basis
set might be misspelled
:param kwargs: passed to Theory methods (make_header, make_molecule, etc.)
"""
# get file content string
header, header_warnings = theory.make_header(
geom, return_warnings=True, **kwargs
)
mol, mol_warnings = theory.make_molecule(
geom, return_warnings=True, **kwargs
)
footer, footer_warnings = theory.make_footer(
geom, return_warnings=True, **kwargs
)
s = header + mol + footer
warnings = header_warnings + mol_warnings + footer_warnings
if outfile is None:
# if outfile is not specified, name file in Aaron format
if "step" in kwargs:
outfile = "{}.{}.com".format(geom.name, step2str(kwargs["step"]))
else:
outfile = "{}.com".format(geom.name)
if outfile is False:
if return_warnings:
return s, warnings
return s
else:
fname = os.path.basename(outfile)
name, ext = os.path.splitext(fname)
# could use jinja, but it's one thing...
s = re.sub("{{\s?name\s?}}", name, s)
with open(outfile, "w") as f:
f.write(s)
if return_warnings:
return warnings
return
@classmethod
def write_inp(
cls, geom, theory, outfile=None, return_warnings=False, **kwargs
):
"""
write ORCA input file for the given Theory() and Geometry()
:param Geometry geom: structure
:param Theory theory: input file parameters
:param None|False|str outfile:
* None - geom.name + ".inp" is used as output destination
* False - return contents of the input file as a str
* str - output destination
:param bool return_warnings: True to return a list of warnings (e.g. basis
set might be misspelled
:param kwargs: passed to Theory methods (make_header, make_molecule, etc.)
"""
fmt = "{:<3s} {: 9.5f} {: 9.5f} {: 9.5f}\n"
header, warnings = theory.make_header(
geom, style="orca", return_warnings=True, **kwargs
)
footer = theory.make_footer(
geom, style="orca", return_warnings=False, **kwargs
)
s = header
for atom in geom.atoms:
if atom.is_dummy:
s += fmt.format("DA", *atom.coords)
continue
s += fmt.format(atom.element, *atom.coords)
s += "*\n"
s += footer
if outfile is None:
# if outfile is not specified, name file in Aaron format
if "step" in kwargs:
outfile = "{}.{}.inp".format(geom.name, step2str(kwargs["step"]))
else:
outfile = "{}.inp".format(geom.name)
if outfile is False:
if return_warnings:
return s, warnings
return s
else:
fname = os.path.basename(outfile)
name, ext = os.path.splitext(fname)
# could use jinja, but it's one thing...
s = re.sub("{{\s?name\s?}}", name, s)
with open(outfile, "w") as f:
f.write(s)
if return_warnings:
return warnings
@classmethod
def write_inq(
cls, geom, theory, outfile=None, return_warnings=False, **kwargs
):
"""
write QChem input file for the given Theory() and Geometry()
:param Geometry geom: structure
:param Theory theory: input file parameters
:param None|False|str outfile:
* None - geom.name + ".inq" is used as output destination
* False - return contents of the input file as a str
* str - output destination
:param bool return_warnings: True to return a list of warnings (e.g. basis
set might be misspelled
:param kwargs: passed to Theory methods (make_header, make_molecule, etc.)
"""
fmt = "{:<3s} {: 9.5f} {: 9.5f} {: 9.5f}\n"
header, header_warnings = theory.make_header(
geom, style="qchem", return_warnings=True, **kwargs
)
mol, mol_warnings = theory.make_molecule(
geom, style="qchem", return_warnings=True, **kwargs
)
out = header + mol
warnings = header_warnings + mol_warnings
if outfile is None:
# if outfile is not specified, name file in Aaron format
if "step" in kwargs:
outfile = "{}.{}.inq".format(geom.name, step2str(kwargs["step"]))
else:
outfile = "{}.inq".format(geom.name)
if outfile is False:
if return_warnings:
return out, warnings
return out
else:
fname = os.path.basename(outfile)
name, ext = os.path.splitext(fname)
# could use jinja, but it's one thing...
out = re.sub("{{\s?name\s?}}", name, out)
with open(outfile, "w") as f:
f.write(out)
if return_warnings:
return warnings
@classmethod
def write_in(
cls, geom, theory, outfile=None, return_warnings=False, **kwargs
):
"""
write Psi4 input file for the given Theory() and Geometry()
:param Geometry geom: structure
:param Theory theory: input file parameters
:param None|False|str outfile:
* None - geom.name + ".in" is used as output destination
* False - return contents of the input file as a str
* str - output destination
:param bool return_warnings: True to return a list of warnings (e.g. basis
set might be misspelled
:param kwargs: passed to Theory methods (make_header, make_molecule, etc.)
"""
header, header_warnings = theory.make_header(
geom, style="psi4", return_warnings=True, **kwargs
)
mol, mol_warnings = theory.make_molecule(
geom, style="psi4", return_warnings=True, **kwargs
)
footer, footer_warnings = theory.make_footer(
geom, style="psi4", return_warnings=True, **kwargs
)
s = header + mol + footer
warnings = header_warnings + mol_warnings + footer_warnings
if outfile is None:
# if outfile is not specified, name file in Aaron format
if "step" in kwargs:
outfile = "{}.{}.in".format(geom.name, step2str(kwargs["step"]))