forked from grimme-lab/enso
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenso.py
executable file
·12194 lines (11872 loc) · 493 KB
/
enso.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
#!/usr/bin/env python3
# This file is part of ENSO.
# Copyright (C) 2019 Fabian Bohle, Karola Schmitz
#
# ENSO is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ENSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ENSO. If not, see <https://www.gnu.org/licenses/>.
coding = "ISO-8859-1"
try:
import argparse
except ImportError:
raise ImportError(
"ENSO requires the module argparse. Please install the module argparse."
)
try:
import sys
except ImportError:
raise ImportError("ENSO requires the module sys. Please install the module sys.")
try:
import os
except ImportError:
raise ImportError("ENSO requires the module os. Please install the module sys.")
from os.path import expanduser
try:
import shutil
except ImportError:
raise ImportError(
"ENSO requires the module shutil. Please install the module shutil."
)
try:
import subprocess
except ImportError:
raise ImportError(
"ENSO requires the module subprocess. Please install the module subprocess."
)
try:
from multiprocessing import JoinableQueue as Queue
except ImportError:
raise ImportError(
"ENSO requires the module multiprocessing. Please install the module "
"multiprocessing."
)
try:
from threading import Thread
except ImportError:
raise ImportError(
"ENSO requires the module threading. Please install the module threading."
)
try:
import time
except ImportError:
raise ImportError("ENSO requires the module time. Please install the module time.")
try:
import csv
except ImportError:
raise ImportError("ENSO requires the module csv. Please install the module csv.")
try:
import math
except ImportError:
raise ImportError("ENSO requires the module math. Please install the module math.")
try:
import json
except ImportError:
raise ImportError("ENSO requires the module json. Please install the module json.")
try:
from collections import OrderedDict
except ImportError:
raise ImportError(
"ENSO requires the module OrderedDict. Please install the module" "OrderedDict."
)
try:
import traceback
except ImportError:
raise ImportError("ENSO uses the module traceback.")
def cml(
descr, solvents, func, func3, funcJ, funcS, gfnv, href, cref, fref, pref, siref, choice_smgsolv2, input_object, argv=None):
""" Get args object from commandline interface.
Needs argparse module."""
parser = argparse.ArgumentParser(
description=descr,
formatter_class=argparse.RawDescriptionHelpFormatter,
usage=argparse.SUPPRESS,
)
group1 = parser.add_argument_group()
group1.add_argument(
"-checkinput",
"--checkinput",
dest="checkinput",
action="store_true",
required=False,
help="Option to check if all necessary information for the ENSO calculation are provided and check if certain setting combinations make sence.",
)
group1.add_argument(
"-run",
"--run",
dest="run",
action="store_true",
required=False,
help="Option to read all settings from the file flags.dat and start the ENSO calculation.",
)
group1.add_argument(
"-write_ensorc",
"--write_ensorc",
dest="writeensorc",
default=False,
action="store_true",
required=False,
help="Write new ensorc, which is placed into the current directory.",
)
group1.add_argument(
"-printout",
"--printout",
dest="doprintout",
default=False,
action="store_true",
required=False,
help="Printout energies only based on the data from enso.json.",
)
group2 = parser.add_argument_group("System specific flags")
group2.add_argument(
"-chrg",
"--charge",
dest="chrg",
action="store",
required=False,
help="Charge of the investigated molecule.",
)
group2.add_argument(
"-solv",
"--solvent",
dest="solv",
choices=solvents,
metavar="",
action="store",
required=False,
help="Solvent the molecule is solvated in, available solvents are: {}.".format(
solvents
),
)
group2.add_argument(
"-u",
"--unpaired",
dest="unpaired",
action="store",
required=False,
type=int,
help="Integer number of unpaired electrons of the investigated molecule.",
)
group2.add_argument(
"-T",
"--temperature",
dest="temperature",
action="store",
required=False,
help="Temperature in Kelvin for thermostatistical evaluation.",
)
group3 = parser.add_argument_group("Programms")
group3.add_argument(
"-prog",
"--program",
choices=input_object.value_options["prog"],
dest="prog",
required=False,
help="QM-program used for part1 either 'orca' or 'tm'.",
)
group3.add_argument(
"-prog_rrho",
"--programrrho",
choices=input_object.value_options["prog_rrho"],
dest="rrhoprog",
required=False,
help="QM-program for RRHO contribution in part2 and 3, either 'xtb' or 'prog'.",
)
group3.add_argument(
"-prog3",
"--programpart3",
choices=input_object.value_options["prog3"],
dest="prog3",
required=False,
help="QM-program used for part3 either 'orca' or 'tm'.",
)
group3.add_argument(
"-prog4",
"--programpart4",
choices=input_object.value_options["prog4"],
dest="prog4",
required=False,
help="QM-program used for shielding- and couplingconstant calculations, either 'orca' or 'tm'.",
)
group3.add_argument(
"-gfn",
"--gfnversion",
dest="gfnv",
choices=gfnv,
action="store",
required=False,
help="GFN-xTB version employed for calculating the RRHO contribution.",
)
group3.add_argument(
"-ancopt",
"--ancoptoptimization",
choices=["on", "off"],
dest="ancopt",
required=False,
help="Option to use xtb as driver for the ANCopt optimzer in part1 and 2.",
)
group4 = parser.add_argument_group("Part specific flags (sorted by part)")
group4.add_argument(
"-part1",
"--part1",
choices=["on", "off"],
dest="part1",
action="store",
required=False,
help="Option to turn the crude optimization (part1) 'on' or 'off'.",
)
group4.add_argument(
"-thrpart1",
"--thresholdpart1",
dest="thr1",
action="store",
required=False,
help=("Threshold in kcal/mol. All conformers in part1 (crude optimization)"
" with a relativ energy below the threshold are considered for part2."),
)
group4.add_argument(
"-func",
"--functional",
dest="func",
choices=func,
action="store",
required=False,
help="Functional for geometry optimization (used in part1 and part2).",
)
group4.add_argument(
"-sm",
"--solventmodel",
choices=input_object.value_options["sm"],
dest="sm",
action="store",
required=False,
help="Solvent model employed during the geometry optimization in part1 and part2.",
)
group4.add_argument(
"-part2",
"--part2",
choices=["on", "off"],
dest="part2",
action="store",
required=False,
help="Option to turn the full optimization (part2) 'on' or 'off'.",
)
group4.add_argument(
"-thrpart2",
"--thresholdpart2",
dest="thr2",
action="store",
required=False,
help=("Threshold in kcal/mol. All conformers in part2 (full optimization"
" + low level free energy evaluation) with a relativ free energy below "
"the threshold are considered for part3."),
)
group4.add_argument(
"-smgsolv2",
"--solventmodelgsolvpart2",
choices=choice_smgsolv2,
dest="gsolv2",
action="store",
required=False,
help="Solvent model for the Gsolv calculation in part2. Either the solvent"
" model of the optimizations (sm) or an additive solvation model.",
)
group4.add_argument(
"-part3",
"--part3",
choices=["on", "off"],
dest="part3",
action="store",
required=False,
help="Option to turn the high level free energy evaluation (part3) 'on' or 'off'.",
)
group4.add_argument(
"-func3",
"--functionalpart3",
dest="func3",
choices=func3,
action="store",
required=False,
help="Functional for the high level single point in part3.",
)
group4.add_argument(
"-basis3",
"--basis3",
dest="basis3",
action="store",
required=False,
help="Basis set employed together with the functional (func3) for the "
"high level single point in part3.",
)
group4.add_argument(
"-sm3",
"--solventmoldel3",
choices=input_object.value_options["sm3"],
dest="sm3",
action="store",
required=False,
help="Solvent model for part3. It can be an implicit solvation model, "
"applied during the high level single-point calculation or an additive solvation model.",
)
group4.add_argument(
"-part4",
"--part4",
choices=["on", "off"],
dest="part4",
action="store",
required=False,
help="Option to turn the shielding and coupling constants calculations "
"of the refined ensemble (part4) 'on' or 'off'.",
)
group4.add_argument(
"-J",
"--couplings",
choices=["on", "off"],
dest="calcJ",
action="store",
required=False,
help="Option to calculate coupling constants: 'on' or 'off'.",
)
group4.add_argument(
"-funcJ",
"--functionalcoupling",
dest="funcJ",
choices=funcJ,
action="store",
required=False,
help="Functional employed in the calculation of coupling constants in part4.",
)
group4.add_argument(
"-basisJ",
"--basisJ",
dest="basisJ",
action="store",
required=False,
help="Basis set employed together with funcJ for calculation of coupling constants in part4.",
)
group4.add_argument(
"-S",
"--shieldings",
choices=["on", "off"],
dest="calcS",
action="store",
required=False,
help="Option to calculate shielding constants: 'on' or 'off'.",
)
group4.add_argument(
"-funcS",
"--functionalshielding",
dest="funcS",
choices=funcS,
action="store",
required=False,
help="Functional employed in the calculation of shielding constants in part4.",
)
group4.add_argument(
"-basisS",
"--basisS",
dest="basisS",
action="store",
required=False,
help="Basis set employed together with funcS for calculation of shielding"
" constants in part4.",
)
group4.add_argument(
"-sm4",
"--solventmoldel4",
choices=input_object.value_options["sm4"],
dest="sm4",
action="store",
required=False,
help="Solvent model employed in the calculation of coupling and shielding"
" constants (part4).",
)
group5 = parser.add_argument_group("NMR specific flags")
group5.add_argument(
"-href",
"-hydrogenreference",
choices=href,
dest="href",
required=False,
help="Reference molecule for 1H spectrum.",
)
group5.add_argument(
"-cref",
"-carbonreference",
choices=cref,
dest="cref",
required=False,
help="Reference molecule for 13C spectrum.",
)
group5.add_argument(
"-fref",
"-fluorinereference",
choices=fref,
dest="fref",
required=False,
help="Reference molecule for 19F spectrum.",
)
group5.add_argument(
"-pref",
"-phosphorusreference",
choices=pref,
dest="pref",
required=False,
help="Reference molecule for 31P spectrum.",
)
group5.add_argument(
"-siref",
"-siliconreference",
choices=siref,
dest="siref",
required=False,
help="Reference molecule for 29Si spectrum.",
)
group5.add_argument(
"-hactive",
"-hydrogenactive",
choices=["on", "off"],
dest="hactive",
required=False,
help="Calculate properties for all hydrogen atoms within the molecule e.g. for 1H NMR spectrum.",
)
group5.add_argument(
"-cactive",
"-carbonactive",
choices=["on", "off"],
dest="cactive",
required=False,
help="Calculate properties for all carbon atoms within the molecule e.g. for 13C NMR spectrum.",
)
group5.add_argument(
"-factive",
"-fluorineactive",
choices=["on", "off"],
dest="factive",
required=False,
help="Calculate properties for all fluorine atoms within the molecule e.g. for 19F NMR spectrum.",
)
group5.add_argument(
"-pactive",
"-phosphorusactive",
choices=["on", "off"],
dest="pactive",
required=False,
help="Calculate properties for all phosphorus atoms within the molecule e.g. for 31P NMR spectrum.",
)
group5.add_argument(
"-siactive",
"-siliconactive",
choices=["on", "off"],
dest="siactive",
required=False,
help="Calculate properties for all phosphorus atoms within the molecule e.g. for 29Si NMR spectrum.",
)
group5.add_argument(
"-mf",
"--resonancefrequency",
dest="mf",
type=int,
action="store",
required=False,
help="Setting of the experimental resonance frequency in MHz.",
)
group6 = parser.add_argument_group("Further options")
group6.add_argument(
"-backup",
"--backup",
dest="backup",
action="store",
required=False,
help="Backup-option to easily/automatically include conformers in a "
"second ENSO run which are only slightly above the threshold of part1.",
)
group6.add_argument(
"-boltzmann",
"--boltzmann",
dest="boltzmann",
choices=["on", "off"],
action="store",
required=False,
help="Option to only reevaluate the Boltzmann population in part3.",
)
group6.add_argument(
"-check",
"--check",
dest="check",
choices=["on", "off"],
action="store",
required=False,
help="Option to terminate the ENSO-run if too many calculations/preparation"
" steps fail.",
)
group6.add_argument(
"-crestcheck",
"--crestcheck",
dest="crestcheck",
choices=["on", "off"],
action="store",
required=False,
help="Option to sort out conformers after DFT optimization which CREST "
"identifies as identical or rotamers of each other. The identification is"
" always performed, but the removal of conformers has to be the choice of the user.",
)
group6.add_argument(
"-nc",
"--nconf",
dest="nconf",
type=int,
action="store",
required=False,
help="Number of conformers taken from crest_conformers.xyz to be evaluated at DFT level.",
)
group7 = parser.add_argument_group("Options for parallel calculation")
group7.add_argument(
"-O",
"--omp",
dest="omp",
type=int,
action="store",
help="Number of cores each thread can use. E.g. (maxthreads) 5 threads "
"with each (omp) 4 cores --> 20 cores need to be available on the machine.",
)
group7.add_argument(
"-P",
"--maxthreads",
dest="maxthreads",
type=int,
action="store",
help="Number of threads during the ENSO calculation. E.g. (maxthreads) 5"
" threads with each (omp) 4 cores --> 20 cores need to be available on the machine.",
)
group7.add_argument(
"--debug",
dest="debug",
action="store_true",
default=False,
help=argparse.SUPPRESS,
)
args = parser.parse_args(argv)
return args
def mkdir_p(path):
""" create mkdir -p like behaviour"""
try:
os.makedirs(path)
except OSError as e:
if os.path.isdir(path):
pass
else:
raise e
return
def print_block(strlist):
"""Print all elements of strlist in block mode
e.g. within 80 characters then newline
"""
length = 0
try:
maxlen = max([len(str(x)) for x in strlist])
except:
maxlen = 12
for item in strlist:
length += maxlen + 2
if length <= 80:
if not item == strlist[-1]: # works only if item only once in list!
print("{:>{digits}}, ".format(str(item), digits=maxlen), end="")
else:
print("{:>{digits}}".format(str(item), digits=maxlen), end="")
else:
print("{:>{digits}}".format(str(item), digits=maxlen))
length = 0
if length != 0:
print("\n")
return
def last_folders(path, number=1):
"""get last folder or last two folders of path, depending on number"""
if number not in (1, 2):
number = 1
if number == 1:
folder = os.path.basename(path)
if number == 2:
folder = os.path.join(
os.path.basename(os.path.dirname(path)), os.path.basename(path)
)
return folder
def check_for_float(line):
""" Go through line and check for float, return first float"""
elements = line.split()
value = None
for element in elements:
try:
value = float(element)
found = True
except ValueError:
found = False
value = None
if found:
break
return value
def conformersxyz2coord(conformersxyz, nat, foldername, nconf, conflist, input_object, onlyenergy=False):
"""read crest_conformers.xyz and write coord into
designated folders, also get GFNn/GFNFF-xTB energies """
with open(conformersxyz, "r", encoding=coding, newline=None) as xyzfile:
stringfile_lines = xyzfile.readlines()
if (int(nconf) * (int(nat) + 2)) > len(stringfile_lines):
print(
"ERROR: Either the number of conformers ({}) or the number of "
"atoms ({}) is wrong!".format(str(nconf), str(nat))
)
input_object.write_json("save_and_exit")
for conf in conflist:
i = int(conf.name[4:])
conf.xtb_energy = check_for_float(stringfile_lines[(i - 1) * (nat + 2) + 1])
if conf.xtb_energy is None:
print(
"Error in float conversion while reading file"
" {}!".format(conformersxyz)
)
conf.xtb_energy = None
input_object.json_dict[conf.name]["xtb_energy"] = conf.xtb_energy
if not onlyenergy:
atom = []
x = []
y = []
z = []
start = (i - 1) * (nat + 2) + 2
end = i * (nat + 2)
bohr2ang = 0.52917721067
for line in stringfile_lines[start:end]:
atom.append(str(line.split()[0].lower()))
x.append(float(line.split()[1]) / bohr2ang)
y.append(float(line.split()[2]) / bohr2ang)
z.append(float(line.split()[3]) / bohr2ang)
coordxyz = []
for j in range(len(x)):
coordxyz.append(
"{: 09.7f} {: 09.7f} {: 09.7f} {}".format(
x[j], y[j], z[j], atom[j]
)
)
tmppath = os.path.join(conf.name, foldername, "coord")
if not os.path.isfile(tmppath):
print(
"Write new coord file in {}".format(tmppath)
)
with open(tmppath,"w", newline=None) as coord:
coord.write("$coord\n")
for line in coordxyz:
coord.write(line + "\n")
coord.write("$end")
return conflist
def crest_routine(args, results, func, crestcheck, json_dict, crestpath, environsettings):
"""check if two conformers are rotamers of each other,
this check is always performed, but removing conformers depends on
the value of crestcheck"""
error_logical = False
cwd = os.getcwd()
dirn = "conformer_rotamer_check" ### directory name
fn = "conformers.xyz" ### file name
dirp = os.path.join(cwd, dirn) ### directory path
fp = os.path.join(dirp, fn) ### file path
### create new directory
if not os.path.isdir(dirp):
mkdir_p(dirp)
### delete file if it already exists
if os.path.isfile(fp):
os.remove(fp)
### sort conformers according to energy of optimization
results.sort(key=lambda x: float(x.energy_opt))
### cp coord file of lowest conformer in directory
try:
shutil.copy(
os.path.join(results[0].name, func, "coord"), os.path.join(dirp, "coord")
)
except:
print(
"ERROR: while copying the coord file from {}! Probably, the "
"corresponding directory or file does not exist.".format(
os.path.join(results[0].name, func)
)
)
error_logical = True
### write crest file in xyz
with open(fp, "a", encoding=coding, newline=None) as inp:
for i in results:
conf_xyz, nat = coord2xyz(
os.path.join(cwd, i.name, func)
) ### coordinates in xyz
inp.write(" {}\n".format(nat)) ### number of atoms
inp.write("{:20.8f} !{}\n".format(i.energy_opt, i.name)) ### energy
for line in conf_xyz:
inp.write(line + "\n")
print(
"\nChecking if conformers became rotamers of each other during "
"the DFT-optimization.\nThe check is performed in the directory"
" {}.".format(dirn)
)
### call crest
print("Calling CREST to identify rotamers.")
with open(os.path.join(dirp, "crest.out"), "w", newline=None) as outputfile:
subprocess.call(
[crestpath, "-cregen", fn, "-enso"],
shell=False,
stdin=None,
stderr=subprocess.STDOUT,
universal_newlines=False,
cwd=dirp,
stdout=outputfile,
env=environsettings,
)
time.sleep(0.05)
### read in crest results
try:
with open(
os.path.join(dirp, "cregen.enso"), "r", encoding=coding, newline=None
) as inp:
store = inp.readlines()
except:
print("ERROR: output file (cregen.enso) of CREST routine does not exist!")
error_logical = True
if error_logical:
print("ERROR: CREST-CHECK can not be performed!")
else:
rotlist = []
rotdict = {}
if " ALL UNIQUE\n" in store:
print("No conformers are identified as rotamers or identical.")
elif " DUPLICATES FOUND\n" in store:
if args.crestcheck:
print(
"\nWARNING: The following conformers are identified as "
"rotamers or identical. They are sorted out."
)
else:
print(
"\nWARNING: The following conformers are identified as "
"rotamers or identical.\nWARNING: They are NOT sorted out "
"since crestcheck is switched off."
)
try:
length = max([len(str(j)) for i in store[1:] for j in i.split()]) + 4
except ValueError:
length = 4 + int(args.nconf) + 1
print(
"{:{digits}} {:10} {:5}<--> {:{digits}} {:10} {:5}".format(
"CONFA", "E(A):", "ΔG(A):", "CONFB", "E(B):", "ΔG(B):", digits=length
)
)
for line in store[1:]:
confa = results[int(line.split()[0]) - 1]
confb = results[int(line.split()[1]) - 1]
rotlist.append(confa.name)
rotdict[confa.name] = confb.name
print(
"{:{digits}} {:>10.5f} {:>5.2f} <--> {:{digits}} {:>10.5f} {:>5.2f}".format(
confa.name,
confa.energy_opt,
confa.rel_free_energy,
confb.name,
confb.energy_opt,
confb.rel_free_energy,
digits=length,
)
)
if rotlist:
for confa, confb in rotdict.items():
if json_dict[confa]["removed_by_user"]:
for i in list(results):
if i.name == confa:
json_dict[confa]["consider_for_part3"] = False
results.remove(i)
if json_dict[confb]["removed_by_user"]:
for i in list(results):
if i.name == confb:
json_dict[confb]["consider_for_part3"] = False
results.remove(i)
if args.crestcheck and rotlist:
for i in list(results):
if i.name in rotlist:
json_dict[i.name]["consider_for_part3"] = False
results.remove(i)
print("Removing {:{digits}}.".format(i.name, digits=length))
else:
print("ERROR: could not read CREST output (cregen.enso)!.")
error_logical = True
if error_logical:
rotdict = {}
return rotdict
def get_degeneracy(cwd, results, tmp_results, input_object):
''' read degeneracies determined by CREST'''
degenfile = os.path.join(cwd, 'cre_degen2')
if not os.path.isfile(degenfile):
print('WARNING: Degeneracies (gi) could not be determined and are set to 1.0.\n')
degengi = {}
else:
with open(degenfile, 'r', encoding=coding, newline=None) as inp:
degen = inp.readlines()
try:
degengi = {}
for line in degen[1:]:
conf = int(line.split()[0])
gi = float(line.split()[1])
degengi[conf] = gi
except ValueError:
print('WARNING: Value conversion Error from data in {}. All gi are set to 1.0.'.format(degenfile))
for conf in results + tmp_results:
if degengi:
if degengi.get(int(conf.name[4:]), None) is not None:
conf.degeneracy = degengi[int(conf.name[4:])]
else:
print('Conformer {} not found in {} and gi is set to 1.0.'.format(conf.name, degenfile))
conf.degeneracy = 1.0
else:
conf.degeneracy = 1.0
input_object.json_dict[conf.name]["degeneracy"] = conf.degeneracy
return results, tmp_results, input_object
def write_trj(results, cwd, outpath, optfolder, nat):
"""Write trajectory to file"""
try:
with open(outpath, "a", encoding=coding, newline=None) as out:
for i in results:
conf_xyz, nat = coord2xyz(
os.path.join(cwd, i.name, optfolder)
) ### coordinates in xyz
out.write(" {}\n".format(nat)) ### number of atoms
out.write(
"E= {:20.8f} G= {:20.8f} !{}\n".format(
i.sp3_energy, i.free_energy, i.name
)
) ### energy
for line in conf_xyz:
out.write(line + "\n")
except (FileExistsError, ValueError):
print("Could not write trajectory: {}.".format(last_folders(outpath, 1)))
newoutpath = outpath.split('.')[0]+'_G.xyz'
try:
with open(newoutpath, "w", encoding=coding, newline=None) as out:
for i in results:
conf_xyz, nat = coord2xyz(
os.path.join(cwd, i.name, optfolder)
) ### coordinates in xyz
out.write(" {}\n".format(nat)) ### number of atoms
out.write(
"G= {:20.8f} E= {:20.8f} !{}\n".format(
i.free_energy, i.sp3_energy, i.name
)
) ### free energy
for line in conf_xyz:
out.write(line + "\n")
except (FileExistsError, ValueError):
print("Could not write trajectory: {}.".format(last_folders(outpath, 1)))
return
def coord2xyz(path):
"""convert TURBOMOLE coord file to xyz"""
time.sleep(0.1)
bohr2ang = 0.52917721067
with open(os.path.join(path, "coord"), "r", encoding=coding, newline=None) as f:
coord = f.readlines()
x = []
y = []
z = []
atom = []
for line in coord[1:]:
if "$" in line: # stop at $end ...
break
x.append(float(line.split()[0]) * bohr2ang)
y.append(float(line.split()[1]) * bohr2ang)
z.append(float(line.split()[2]) * bohr2ang)
atom.append(str(line.split()[3].lower()))
# natoms = int(len(coord[1:-1])) # unused
coordxyz = []
for i in range(len(x)):
coordxyz.append(
"{:3} {: 19.10f} {: 19.10f} {: 19.10f}".format(
atom[i][0].upper() + atom[i][1:], x[i], y[i], z[i]
)
)
return coordxyz, len(coordxyz)
def RMSD_routine(workdir, nat):
bohr2ang = 0.52917721067
new = [[0.0, 0.0, 0.0] for _ in range(nat)]
old = [[0.0, 0.0, 0.0] for _ in range(nat)]
squared_difference_x = []
squared_difference_y = []
squared_difference_z = []
with open(os.path.join(workdir, "coord"), "r", encoding=coding, newline=None) as f:
coord = f.readlines()
x = []
y = []
z = []
for line in coord[1:]:
if "$" in line: # stop at $end ...
break
x.append(float(line.split()[0]) * bohr2ang)
y.append(float(line.split()[1]) * bohr2ang)
z.append(float(line.split()[2]) * bohr2ang)
for i in range(len(x)):
# old.append("{: 09.7f} {: 09.7f} {: 09.7f}".format(float(x[i]),float(y[i]),float(z[i])))
old[i][0] = float(x[i])
old[i][1] = float(y[i])
old[i][2] = float(z[i])
with open(
os.path.join(workdir, "xtbopt.coord"), "r", encoding=coding, newline=None
) as f:
coord = f.readlines()
x = []
y = []
z = []
for line in coord[1:]:
if "$" in line: # stop at $end ...
break
x.append(float(line.split()[0]) * bohr2ang)
y.append(float(line.split()[1]) * bohr2ang)
z.append(float(line.split()[2]) * bohr2ang)
for i in range(len(x)):
# old.append("{: 09.7f} {: 09.7f} {: 09.7f}".format(float(x[i]),float(y[i]),float(z[i])))
new[i][0] = float(x[i])
new[i][1] = float(y[i])
new[i][2] = float(z[i])
for i in range(len(old)):
squared_difference_x.append(float((old[i][0] - new[i][0]) ** 2))
squared_difference_y.append(float((old[i][1] - new[i][1]) ** 2))
squared_difference_z.append(float((old[i][2] - new[i][2]) ** 2))
sumdiff = math.fsum(
squared_difference_x[i] + squared_difference_y[i] + squared_difference_z[i]
for i in range(nat)
)
return math.sqrt(sumdiff / nat)
def RMSD_subprocess(workdir, environsettings):
rmsd = None
with open(os.path.join(workdir, "rmsd"), "w", newline=None) as outputfile:
callargs = ["rmsd", "coord", "xtbopt.coord"]
subprocess.call(
callargs,
shell=False,
stdin=None,
stderr=subprocess.STDOUT,
universal_newlines=False,
cwd=workdir,
stdout=outputfile,
env=environsettings,
)
with open(os.path.join(workdir, "rmsd"), "r", encoding=coding, newline=None) as out:
stor = out.readlines()
for line in stor: