-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy paththermo.py
2862 lines (2472 loc) · 130 KB
/
thermo.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
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# #
# Copyright (c) 2002-2023 Prof. William H. Green (whgreen@mit.edu), #
# Prof. Richard H. West (r.west@neu.edu) and the RMG Team (rmg_dev@mit.edu) #
# #
# Permission is hereby granted, free of charge, to any person obtaining a #
# copy of this software and associated documentation files (the 'Software'), #
# to deal in the Software without restriction, including without limitation #
# the rights to use, copy, modify, merge, publish, distribute, sublicense, #
# and/or sell copies of the Software, and to permit persons to whom the #
# Software is furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER #
# DEALINGS IN THE SOFTWARE. #
# #
###############################################################################
"""
"""
import itertools
import logging
import math
import os.path
import re
import time
from copy import deepcopy
import numpy as np
import rmgpy.constants as constants
import rmgpy.molecule
import rmgpy.quantity
from rmgpy.data.base import Database, Entry, make_logic_node, DatabaseError
from rmgpy.ml.estimator import MLEstimator
from rmgpy.molecule import Molecule, Bond, Group
from rmgpy.species import Species
from rmgpy.thermo import NASAPolynomial, NASA, ThermoData, Wilhoit
from rmgpy.data.surface import MetalDatabase
from rmgpy import settings
from rmgpy.molecule.fragment import Fragment
from rmgpy.data.surface import MetalDatabase
from rmgpy import settings
#: This dictionary is used to add multiplicity to species label
_multiplicity_labels = {1: 'S', 2: 'D', 3: 'T', 4: 'Q', 5: 'V'}
################################################################################
def save_entry(f, entry):
"""
Write a Pythonic string representation of the given `entry` in the thermo
database to the file object `f`.
"""
f.write('entry(\n')
f.write(' index = {0:d},\n'.format(entry.index))
f.write(' label = "{0}",\n'.format(entry.label))
if isinstance(entry.item, Molecule):
f.write(' molecule = \n')
f.write('"""\n')
f.write(entry.item.to_adjacency_list(remove_h=False))
f.write('""",\n')
elif isinstance(entry.item, Group):
f.write(' group = \n')
f.write('"""\n')
f.write(entry.item.to_adjacency_list())
f.write('""",\n')
else:
f.write(' group = "{0}",\n'.format(entry.item))
if isinstance(entry.data, ThermoData):
f.write(' thermo = ThermoData(\n')
f.write(' Tdata = {0!r},\n'.format(entry.data.Tdata))
f.write(' Cpdata = {0!r},\n'.format(entry.data.Cpdata))
f.write(' H298 = {0!r},\n'.format(entry.data.H298))
f.write(' S298 = {0!r},\n'.format(entry.data.S298))
if entry.data.Tmin is not None:
f.write(' Tmin = {0!r},\n'.format(entry.data.Tmin))
if entry.data.Tmax is not None:
f.write(' Tmax = {0!r},\n'.format(entry.data.Tmax))
f.write(' ),\n')
elif isinstance(entry.data, Wilhoit):
f.write(' thermo = Wilhoit(\n')
f.write(' cp0 = {0!r},\n'.format(entry.data.cp0))
f.write(' cpInf = {0!r},\n'.format(entry.data.cpInf))
f.write(' a0 = {0:g},\n'.format(entry.data.a0))
f.write(' a1 = {0:g},\n'.format(entry.data.a1))
f.write(' a2 = {0:g},\n'.format(entry.data.a2))
f.write(' a3 = {0:g},\n'.format(entry.data.a3))
f.write(' B = {0!r},\n'.format(entry.data.B))
f.write(' H0 = {0!r},\n'.format(entry.data.H0))
f.write(' S0 = {0!r},\n'.format(entry.data.S0))
if entry.data.Tmin is not None:
f.write(' Tmin = {0!r},\n'.format(entry.data.Tmin))
if entry.data.Tmax is not None:
f.write(' Tmax = {0!r},\n'.format(entry.data.Tmax))
f.write(' ),\n')
elif isinstance(entry.data, NASA):
f.write(' thermo = NASA(\n')
f.write(' polynomials = [\n')
for poly in entry.data.polynomials:
f.write(' {0!r},\n'.format(poly))
f.write(' ],\n')
if entry.data.Tmin is not None:
f.write(' Tmin = {0!r},\n'.format(entry.data.Tmin))
if entry.data.Tmax is not None:
f.write(' Tmax = {0!r},\n'.format(entry.data.Tmax))
if entry.data.E0 is not None:
f.write(' E0 = {0!r},\n'.format(entry.data.E0))
if entry.data.Cp0 is not None:
f.write(' Cp0 = {0!r},\n'.format(entry.data.Cp0))
if entry.data.CpInf is not None:
f.write(' CpInf = {0!r},\n'.format(entry.data.CpInf))
f.write(' ),\n')
else:
f.write(' thermo = {0!r},\n'.format(entry.data))
if entry.reference is not None:
f.write(' reference = {0!r},\n'.format(entry.reference))
if entry.reference_type != "":
f.write(' referenceType = "{0}",\n'.format(entry.reference_type))
f.write(f' shortDesc = """{entry.short_desc.strip()}""",\n')
f.write(f' longDesc = \n"""\n{entry.long_desc.strip()}\n""",\n')
if entry.rank:
f.write(" rank = {0},\n".format(entry.rank))
if entry.metal:
f.write(' metal = "{0}",\n'.format(entry.metal))
if entry.facet:
f.write(' facet = "{0}",\n'.format(entry.facet))
if entry.site:
f.write(' site = "{0}",\n'.format(entry.site))
f.write(')\n\n')
def generate_old_library_entry(data):
"""
Return a list of values used to save entries to the old-style RMG
thermo database based on the thermodynamics object `data`.
"""
if isinstance(data, ThermoData):
return '{0:9g} {1:9g} {2:9g} {3:9g} {4:9g} {5:9g} {6:9g} {7:9g} {8:9g} {9:9g} {10:9g} {11:9g}'.format(
data.H298.value_si / 4184.,
data.S298.value_si / 4.184,
data.Cpdata.value_si[0] / 4.184,
data.Cpdata.value_si[1] / 4.184,
data.Cpdata.value_si[2] / 4.184,
data.Cpdata.value_si[3] / 4.184,
data.Cpdata.value_si[4] / 4.184,
data.Cpdata.value_si[5] / 4.184,
data.Cpdata.value_si[6] / 4.184,
data.H298.uncertainty / 4184.,
data.S298.uncertainty / 4.184,
max(data.Cpdata.uncertainty) / 4.184,
)
elif isinstance(data, str):
return data
else:
return '{0:9g} {1:9g} {2:9g} {3:9g} {4:9g} {5:9g} {6:9g} {7:9g} {8:9g} {9:9g} {10:9g} {11:9g}'.format(
data.get_enthalpy(298) / 4184.,
data.get_entropy(298) / 4.184,
data.get_heat_capacity(300) / 4.184,
data.get_heat_capacity(400) / 4.184,
data.get_heat_capacity(500) / 4.184,
data.get_heat_capacity(600) / 4.184,
data.get_heat_capacity(800) / 4.184,
data.get_heat_capacity(1000) / 4.184,
data.get_heat_capacity(1500) / 4.184,
0,
0,
0,
)
def process_old_library_entry(data):
"""
Process a list of parameters `data` as read from an old-style RMG
thermo database, returning the corresponding thermodynamics object.
"""
return ThermoData(
Tdata=([300, 400, 500, 600, 800, 1000, 1500], "K"),
Cpdata=([float(d) for d in data[2:9]], "cal/(mol*K)", "+|-", float(data[11])),
H298=(float(data[0]), "kcal/mol", "+|-", float(data[9])),
S298=(float(data[1]), "cal/(mol*K)", "+|-", float(data[10])),
)
def add_thermo_data(thermo_data1, thermo_data2, group_additivity=False, verbose=False):
"""
Add the thermodynamic data `thermo_data2` to the data `thermo_data1`,
and return `thermo_data1`.
If `group_additivity` is True, append comments related to group additivity estimation
If `verbose` is False, omit the comments from a "zero entry", whose H298, S298, and Cp are all 0.
If `verbose` is True, or thermo_data2 is not a zero entry, add thermo_data2.comment to thermo_data1.comment.
"""
if (len(thermo_data1.Tdata.value_si) != len(thermo_data2.Tdata.value_si) or
any([T1 != T2 for T1, T2 in zip(thermo_data1.Tdata.value_si, thermo_data2.Tdata.value_si)])):
raise ValueError('Cannot add these ThermoData objects due to their having different temperature points.')
for i in range(thermo_data1.Tdata.value_si.shape[0]):
thermo_data1.Cpdata.value_si[i] += thermo_data2.Cpdata.value_si[i]
thermo_data1.H298.value_si += thermo_data2.H298.value_si
thermo_data1.S298.value_si += thermo_data2.S298.value_si
test_zero = sum(abs(value) for value in
[thermo_data2.H298.value_si, thermo_data2.S298.value_si] + thermo_data2.Cpdata.value_si.tolist())
# Used to check if all of the entries in thermo_data2 are zero
if group_additivity:
if verbose or test_zero != 0:
# If verbose==True or test_zero!=0, add thermo_data2.comment to thermo_data1.comment.
if thermo_data1.comment:
thermo_data1.comment += ' + {0}'.format(thermo_data2.comment)
else:
thermo_data1.comment = 'Thermo group additivity estimation: ' + thermo_data2.comment
return thermo_data1
def remove_thermo_data(thermo_data1, thermo_data2, group_additivity=False, verbose=False):
"""
Remove the thermodynamic data `thermo_data2` from the data `thermo_data1`,
and return `thermo_data1`.
If `verbose` is True, append ' - thermo_data2.comment' to the thermo_data1.comment.
If `verbose` is False, remove the thermo_data2.comment from the thermo_data1.comment.
"""
if (len(thermo_data1.Tdata.value_si) != len(thermo_data2.Tdata.value_si) or
any([T1 != T2 for T1, T2 in zip(thermo_data1.Tdata.value_si, thermo_data2.Tdata.value_si)])):
raise ValueError('Cannot take the difference between these ThermoData objects due to their having different '
'temperature points.')
for i in range(thermo_data1.Tdata.value_si.shape[0]):
thermo_data1.Cpdata.value_si[i] -= thermo_data2.Cpdata.value_si[i]
thermo_data1.H298.value_si -= thermo_data2.H298.value_si
thermo_data1.S298.value_si -= thermo_data2.S298.value_si
if group_additivity:
if verbose:
thermo_data1.comment += ' - {0}'.format(thermo_data2.comment)
else:
thermo_data1.comment = re.sub(re.escape(' + ' + thermo_data2.comment), '', thermo_data1.comment, 1)
return thermo_data1
def average_thermo_data(thermo_data_list=None):
"""
Average a list of ThermoData values together.
Sets uncertainty values to be the approximately the 95% confidence interval, equivalent to
2 standard deviations calculated using the sample standard variance:
Uncertainty = 2s
s = sqrt( sum(abs(x - x.mean())^2) / N - 1) where N is the number of values averaged
Note that uncertainties are only computed when number of values is greater than 1.
"""
if thermo_data_list is None:
thermo_data_list = []
num_values = len(thermo_data_list)
if num_values == 0:
raise ValueError('No thermo data values were inputted to be averaged.')
else:
logging.debug('Averaging thermo data over {0} value(s).'.format(num_values))
if num_values == 1:
return deepcopy(thermo_data_list[0])
else:
averaged_thermo_data = deepcopy(thermo_data_list[0])
for thermo_data in thermo_data_list[1:]:
averaged_thermo_data = add_thermo_data(averaged_thermo_data, thermo_data)
for i in range(averaged_thermo_data.Tdata.value_si.shape[0]):
averaged_thermo_data.Cpdata.value_si[i] /= num_values
cp_data = [thermo_data.Cpdata.value_si[i] for thermo_data in thermo_data_list]
averaged_thermo_data.Cpdata.uncertainty_si[i] = 2 * np.std(cp_data, ddof=1)
h_data = [thermo_data.H298.value_si for thermo_data in thermo_data_list]
averaged_thermo_data.H298.value_si /= num_values
averaged_thermo_data.H298.uncertainty_si = 2 * np.std(h_data, ddof=1)
s_data = [thermo_data.S298.value_si for thermo_data in thermo_data_list]
averaged_thermo_data.S298.value_si /= num_values
averaged_thermo_data.S298.uncertainty_si = 2 * np.std(s_data, ddof=1)
return averaged_thermo_data
def common_atoms(cycle1, cycle2):
"""
INPUT: two cycles with type: list of atoms
OUTPUT: a set of common atoms
"""
set1 = set(cycle1)
set2 = set(cycle2)
return set1.intersection(set2)
def combine_cycles(cycle1, cycle2):
"""
INPUT: two cycles with type: list of atoms
OUTPUT: a combined cycle with type: list of atoms
"""
set1 = set(cycle1)
set2 = set(cycle2)
return list(set1.union(set2))
def is_aromatic_ring(submol):
"""
This method takes a monoring submol (Molecule initialized with a list of atoms containing just
the ring), and check if it is a aromatic ring.
"""
ring_size = len(submol.atoms)
if ring_size not in [5, 6]:
return False
for ring_atom in submol.atoms:
for bonded_atom, bond in ring_atom.edges.items():
if bonded_atom in submol.atoms:
if not bond.is_benzene():
return False
return True
def is_bicyclic(polyring):
"""
Given a polyring (a list of `Atom`s)
returns True if it's a bicyclic, False otherwise
"""
submol, _ = convert_ring_to_sub_molecule(polyring)
sssr = submol.get_smallest_set_of_smallest_rings()
return len(sssr) == 2
def find_aromatic_bonds_from_sub_molecule(submol):
"""
This method finds all the aromatic bonds within a input submolecule and
returns a set of unique aromatic bonds
"""
aromatic_bonds = []
for atom in submol.atoms:
bonds = submol.get_bonds(atom)
for atom_j in bonds:
if atom_j in submol.atoms:
bond = bonds[atom_j]
if bond.is_benzene():
aromatic_bonds.append(bond)
return set(aromatic_bonds)
def convert_ring_to_sub_molecule(ring):
"""
This function takes a ring structure (can either be monoring or polyring) to create a new
submolecule with newly deep copied atoms
Outputted submolecules may have incomplete valence and may cause errors with some Molecule.methods(), such
as update_atomtypes() or update(). In the future we may consider using groups for the sub-molecules.
"""
atoms_mapping = {}
for atom in ring:
atoms_mapping[atom] = atom.copy() # this copy is deep copy of origin atom with empty edges
mol0 = Molecule(atoms=list(atoms_mapping.values()))
for atom in ring:
for bonded_atom, bond in atom.edges.items():
if bonded_atom in ring:
if not mol0.has_bond(atoms_mapping[atom], atoms_mapping[bonded_atom]):
mol0.add_bond(Bond(atoms_mapping[atom], atoms_mapping[bonded_atom], order=bond.order))
mol0.update_multiplicity()
mol0.update_connectivity_values()
return mol0, atoms_mapping
def combine_two_rings_into_sub_molecule(ring1, ring2):
"""
This function combines 2 rings (with common atoms) to create a new
submolecule with newly deep copied atoms
"""
assert len(common_atoms(ring1, ring2)) > 0, "The two input rings don't have common atoms."
atoms_mapping = {}
for atom in ring1 + ring2:
if atom not in atoms_mapping:
atoms_mapping[atom] = atom.copy()
mol0 = Molecule(atoms=list(atoms_mapping.values()))
for atom in ring1:
for bonded_atom, bond in atom.edges.items():
if bonded_atom in ring1:
if not mol0.has_bond(atoms_mapping[atom], atoms_mapping[bonded_atom]):
mol0.add_bond(Bond(atoms_mapping[atom], atoms_mapping[bonded_atom], order=bond.order))
for atom in ring2:
for bonded_atom, bond in atom.edges.items():
if bonded_atom in ring2:
if not mol0.has_bond(atoms_mapping[atom], atoms_mapping[bonded_atom]):
mol0.add_bond(Bond(atoms_mapping[atom], atoms_mapping[bonded_atom], order=bond.order))
mol0.update_multiplicity()
mol0.update_connectivity_values()
return mol0, atoms_mapping
def get_copy_for_one_ring(ring):
"""
Make a copy of a single ring from a molecule.
Returns a list of atoms.
"""
atoms_mapping = convert_ring_to_sub_molecule(ring)[1]
ring_copy = [atoms_mapping[atom] for atom in ring]
return ring_copy
def get_copy_from_two_rings_with_common_atoms(ring1, ring2):
"""
Make a copy of a two rings from a molecule and also generates the merged ring.
Returns a copy of ring1, a copy of ring2, and the merged rings, each as a list of atoms.
"""
merged_ring, atoms_mapping = combine_two_rings_into_sub_molecule(ring1, ring2)
ring1_copy = [atoms_mapping[atom] for atom in ring1]
ring2_copy = [atoms_mapping[atom] for atom in ring2]
return ring1_copy, ring2_copy, merged_ring
def is_ring_partial_matched(ring, matched_group):
"""
An example of ring partial match is tricyclic ring is matched by a bicyclic group
usually because of not enough data in polycyclic tree. The method takes a matched group
returned from descend_tree and the ring (a list of non-hydrogen atoms in the ring)
"""
# if matched group has less atoms than the target ring
# it's surely a partial match
if len(ring) > len(matched_group.atoms):
return True
else:
submol_ring, _ = convert_ring_to_sub_molecule(ring)
sssr = submol_ring.get_smallest_set_of_smallest_rings()
sssr_grp = matched_group.get_smallest_set_of_smallest_rings()
if sorted([len(sr) for sr in sssr]) == sorted([len(sr_grp) for sr_grp in sssr_grp]):
return False
else:
return True
def bicyclic_decomposition_for_polyring(polyring):
"""
Decompose a polycyclic ring into all possible bicyclic combinations: `bicyclics_merged_from_ring_pair`
and return a `ring_occurances_dict` that contains all single ring tuples as keys and the number of times
they appear each bicyclic submolecule. These bicyclic and single rings are used
later in the heuristic polycyclic thermo algorithm.
"""
submol, _ = convert_ring_to_sub_molecule(polyring)
sssr = submol.get_deterministic_sssr()
ring_pair_with_common_atoms_list = []
ring_occurances_dict = {}
# Initialize ringOccuranceDict
for ring in sssr:
ring_occurances_dict[tuple(ring)] = 0
ring_num = len(sssr)
for i in range(ring_num):
for j in range(i + 1, ring_num):
if common_atoms(sssr[i], sssr[j]):
# Copy the SSSR's again because these ones are going to be merged into bicyclics
# and manipulated (aromatic bonds have to be screened and changed to single if needed)
sssr_i, sssr_j, merged_ring = get_copy_from_two_rings_with_common_atoms(sssr[i], sssr[j])
ring_pair_with_common_atoms_list.append([sssr_i, sssr_j, merged_ring])
# Save the single ring SSSRs that appear in bicyclics using the original copy
# because they will be manipulated (differently) in _add_poly_ring_correction_thermo_data_from_heuristic
ring_occurances_dict[tuple(sssr[i])] += 1
ring_occurances_dict[tuple(sssr[j])] += 1
bicyclics_merged_from_ring_pair = []
# pre-process 2-ring cores
for ringA, ringB, merged_ring in ring_pair_with_common_atoms_list:
submol_a = Molecule(atoms=ringA)
submol_b = Molecule(atoms=ringB)
is_a_aromatic = is_aromatic_ring(submol_a)
is_b_aromatic = is_aromatic_ring(submol_b)
# if ringA and ringB are both aromatic or not aromatic
# don't need to do anything extra
if is_a_aromatic and is_b_aromatic:
pass
elif not is_a_aromatic and not is_b_aromatic:
aromatic_bonds_in_a = find_aromatic_bonds_from_sub_molecule(submol_a)
for aromaticBond_inA in aromatic_bonds_in_a:
aromaticBond_inA.set_order_num(1)
aromatic_bonds_in_b = find_aromatic_bonds_from_sub_molecule(submol_b)
for aromaticBond_inB in aromatic_bonds_in_b:
aromaticBond_inB.set_order_num(1)
elif is_a_aromatic:
aromatic_bonds_in_b = find_aromatic_bonds_from_sub_molecule(submol_b)
for aromaticBond_inB in aromatic_bonds_in_b:
# Make sure the aromatic bond in ringB is in ringA, and both ringB atoms are in ringA
# If so, preserve the B bond status, otherwise change to single bond order
if ((aromaticBond_inB.atom1 in submol_a.atoms) and
(aromaticBond_inB.atom2 in submol_a.atoms) and
(submol_a.has_bond(aromaticBond_inB.atom1, aromaticBond_inB.atom2))):
pass
else:
aromaticBond_inB.set_order_num(1)
else:
aromatic_bonds_in_a = find_aromatic_bonds_from_sub_molecule(submol_a)
for aromaticBond_inA in aromatic_bonds_in_a:
if ((aromaticBond_inA.atom1 in submol_b.atoms) and
(aromaticBond_inA.atom2 in submol_b.atoms) and
(submol_b.has_bond(aromaticBond_inA.atom1, aromaticBond_inA.atom2))):
pass
else:
aromaticBond_inA.set_order_num(1)
merged_ring.saturate_unfilled_valence(update=True)
bicyclics_merged_from_ring_pair.append(merged_ring)
return bicyclics_merged_from_ring_pair, ring_occurances_dict
def split_bicyclic_into_single_rings(bicyclic_submol):
"""
Splits a given bicyclic submolecule into two individual single
ring submolecules (a list of `Molecule`s ).
"""
sssr = bicyclic_submol.get_deterministic_sssr()
return [convert_ring_to_sub_molecule(sssr[0])[0],
convert_ring_to_sub_molecule(sssr[1])[0]]
def saturate_ring_bonds(ring_submol):
"""
Given a ring submolelcule (`Molecule`), makes a deep copy and converts non-single bonds
into single bonds, returns a new saturated submolecule (`Molecule`)
"""
atoms_mapping = {}
for atom in ring_submol.atoms:
if atom not in atoms_mapping:
atoms_mapping[atom] = atom.copy()
mol0 = Molecule(atoms=list(atoms_mapping.values()))
already_saturated = True
for atom in ring_submol.atoms:
for bonded_atom, bond in atom.edges.items():
if bonded_atom in ring_submol.atoms:
if bond.order > 1.0 and not bond.is_benzene():
already_saturated = False
if not mol0.has_bond(atoms_mapping[atom], atoms_mapping[bonded_atom]):
bond_order = 1.0
if bond.is_benzene():
bond_order = 1.5
mol0.add_bond(Bond(atoms_mapping[atom], atoms_mapping[bonded_atom], order=bond_order))
mol0.saturate_unfilled_valence()
mol0.update_atomtypes()
mol0.update_multiplicity()
mol0.update_connectivity_values()
return mol0, already_saturated
################################################################################
class ThermoDepository(Database):
"""
A class for working with the RMG thermodynamics depository.
"""
def __init__(self, label='', name='', short_desc='', long_desc='', metal=None, site=None, facet=None):
Database.__init__(self, label=label, name=name, short_desc=short_desc, long_desc=long_desc, metal=metal, site=site, facet=facet)
def load_entry(self, index, label, molecule, thermo, reference=None, referenceType='', shortDesc='', longDesc='',
rank=None, metal=None, site=None, facet=None):
"""
Method for parsing entries in database files.
Note that these argument names are retained for backward compatibility.
"""
entry = Entry(
index=index,
label=label,
item=Molecule().from_adjacency_list(molecule),
data=thermo,
reference=reference,
reference_type=referenceType,
short_desc=shortDesc,
long_desc=longDesc.strip(),
rank=rank,
metal=metal,
site=site,
facet=facet,
)
self.entries[label] = entry
return entry
def save_entry(self, f, entry):
"""
Write the given `entry` in the thermo database to the file object `f`.
"""
return save_entry(f, entry)
################################################################################
class ThermoLibrary(Database):
"""
A class for working with a RMG thermodynamics library.
"""
def __init__(self, label='', name='', solvent=None, short_desc='', long_desc='', metal=None, site=None, facet=None):
Database.__init__(self, label=label, name=name, short_desc=short_desc, long_desc=long_desc,
metal=metal, site=site, facet=facet)
def load_entry(self,
index,
label,
molecule,
thermo,
reference=None,
referenceType='',
shortDesc='',
longDesc='',
rank=None,
metal=None,
facet=None,
site=None,
):
"""
Method for parsing entries in database files.
Note that these argument names are retained for backward compatibility.
"""
try:
molecule = Molecule().from_adjacency_list(molecule)
except TypeError:
molecule = Fragment().from_adjacency_list(molecule)
# Internal checks for adding entry to the thermo library
if label in list(self.entries.keys()):
raise DatabaseError('Found a duplicate molecule with label {0} in the thermo library {1}. '
'Please correct your library.'.format(label, self.name))
for entry in self.entries.values():
if molecule.is_isomorphic(entry.item):
if molecule.multiplicity == entry.item.multiplicity:
raise DatabaseError('Adjacency list and multiplicity of {0} matches that of '
'existing molecule {1} in thermo library {2}. Please '
'correct your library.'.format(label, entry.label, self.name))
self.entries[label] = Entry(
index=index,
label=label,
item=molecule,
data=thermo,
reference=reference,
reference_type=referenceType,
short_desc=shortDesc,
long_desc=longDesc.strip(),
rank=rank,
metal=metal,
facet=facet,
site=site,
)
def save_entry(self, f, entry):
"""
Write the given `entry` in the thermo database to the file object `f`.
"""
return save_entry(f, entry)
def generate_old_library_entry(self, data):
"""
Return a list of values used to save entries to the old-style RMG
thermo database based on the thermodynamics object `data`.
"""
return generate_old_library_entry(data)
def process_old_library_entry(self, data):
"""
Process a list of parameters `data` as read from an old-style RMG
thermo database, returning the corresponding thermodynamics object.
"""
return process_old_library_entry(data)
################################################################################
class ThermoGroups(Database):
"""
A class for working with an RMG thermodynamics group additivity database.
"""
def __init__(self, label='', name='', short_desc='', long_desc='', metal=None, site=None, facet=None):
Database.__init__(self, label=label, name=name, short_desc=short_desc, long_desc=long_desc,
metal=metal, site=site, facet=facet)
def load_entry(self,
index,
label,
group,
thermo,
reference=None,
referenceType='',
shortDesc='',
longDesc='',
rank=None,
metal=None,
facet=None,
site=None,
):
"""
Method for parsing entries in database files.
Note that these argument names are retained for backward compatibility.
"""
if (group[0:3].upper() == 'OR{' or
group[0:4].upper() == 'AND{' or
group[0:7].upper() == 'NOT OR{' or
group[0:8].upper() == 'NOT AND{'):
item = make_logic_node(group)
else:
item = Group().from_adjacency_list(group)
self.entries[label] = Entry(
index=index,
label=label,
item=item,
data=thermo,
reference=reference,
reference_type=referenceType,
short_desc=shortDesc,
long_desc=longDesc.strip(),
rank=rank,
metal=metal,
facet=facet,
site=site,
)
def save_entry(self, f, entry):
"""
Write the given `entry` in the thermo database to the file object `f`.
"""
return save_entry(f, entry)
def generate_old_library_entry(self, data):
"""
Return a list of values used to save entries to the old-style RMG
thermo database based on the thermodynamics object `data`.
"""
return generate_old_library_entry(data)
def process_old_library_entry(self, data):
"""
Process a list of parameters `data` as read from an old-style RMG
thermo database, returning the corresponding thermodynamics object.
"""
return process_old_library_entry(data)
def copy_data(self, source, destination):
"""
This method copys the ThermoData object and all meta data
from source to destination
Args:
source: The entry for which data is being copied
destination: The entry for which data is being overwritten
"""
destination.data = source.data
destination.reference = source.reference
destination.short_desc = source.short_desc
destination.long_desc = source.long_desc
destination.rank = source.rank
destination.reference_type = source.reference_type
destination.metal = source.metal
destination.facet = source.facet
destination.site = source.site
def remove_group(self, group_to_remove):
"""
Removes a group that is in a tree from the database. For thermo
groups we also, need to re-point any unicode thermo_data that may
have pointed to the entry.
Returns the removed group
"""
# First call base class method
Database.remove_group(self, group_to_remove)
parent_r = group_to_remove.parent
# look for other pointers that point toward entry
for entry in self.entries.values():
if isinstance(entry.data, str):
if entry.data == group_to_remove.label:
# if the entryToRemove.data is also a pointer, then copy
if isinstance(group_to_remove.data, str):
entry.data = group_to_remove.data
# if the parent points toward entry and the data is
# not a base string, we need to copy the data to the parent
elif entry is parent_r:
self.copy_data(group_to_remove, parent_r)
# otherwise, point toward entryToRemove's parent
else:
entry.data = str(parent_r.label)
return group_to_remove
################################################################################
class ThermoDatabase(object):
"""
A class for working with the RMG thermodynamics database.
"""
def __init__(self):
self.depository = {}
self.libraries = {}
self.surface = {}
self.groups = {}
self.library_order = []
self.local_context = {
'ThermoData': ThermoData,
'Wilhoit': Wilhoit,
'NASAPolynomial': NASAPolynomial,
'NASA': NASA,
}
self.global_context = {}
# Use Pt111 binding energies as default
self.binding_energies = {
'H': rmgpy.quantity.Energy(-2.75368,'eV/molecule'),
'C': rmgpy.quantity.Energy(-7.02516,'eV/molecule'),
'N': rmgpy.quantity.Energy(-4.63225,'eV/molecule'),
'O': rmgpy.quantity.Energy(-3.81153,'eV/molecule'),
}
def __reduce__(self):
"""
A helper function used when pickling a ThermoDatabase object.
"""
d = {
'depository': self.depository,
'libraries': self.libraries,
'groups': self.groups,
'library_order': self.library_order,
'surface' : self.surface,
}
return ThermoDatabase, (), d
def __setstate__(self, d):
"""
A helper function used when unpickling a ThermoDatabase object.
"""
self.depository = d['depository']
self.libraries = d['libraries']
self.groups = d['groups']
self.library_order = d['library_order']
self.surface = d['surface']
def load(self, path, libraries=None, depository=True, surface=False):
"""
Load the thermo database from the given `path` on disk, where `path`
points to the top-level folder of the thermo database.
"""
if depository:
self.load_depository(os.path.join(path, 'depository'))
else:
self.depository = {}
self.load_libraries(os.path.join(path, 'libraries'), libraries)
self.load_groups(os.path.join(path, 'groups'))
if surface:
self.load_surface()
def load_depository(self, path):
"""
Load the thermo database from the given `path` on disk, where `path`
points to the top-level folder of the thermo database.
"""
self.depository = {
'stable': ThermoDepository().load(os.path.join(path, 'stable.py'),
self.local_context, self.global_context),
'radical': ThermoDepository().load(os.path.join(path, 'radical.py'),
self.local_context, self.global_context)
}
def load_libraries(self, path, libraries=None):
"""
Load the thermo database from the given `path` on disk, where `path`
points to the top-level folder of the thermo database.
If no libraries are given, all are loaded.
"""
self.libraries = {}
self.library_order = []
if libraries is None:
for (root, dirs, files) in os.walk(os.path.join(path)):
for f in files:
name, ext = os.path.splitext(f)
if ext.lower() == '.py':
logging.info('Loading thermodynamics library from {0} in {1}...'.format(f, root))
library = ThermoLibrary()
library.load(os.path.join(root, f), self.local_context, self.global_context)
library.label = os.path.splitext(f)[0]
self.libraries[library.label] = library
self.library_order.append(library.label)
else:
for libraryName in libraries:
f = f'{libraryName}.py'
if os.path.isfile(libraryName):
logging.info(f'Loading thermodynamics library from an external location: {libraryName}..')
library = ThermoLibrary()
library.load(libraryName, self.local_context, self.global_context)
library.label = os.path.splitext(os.path.split(libraryName)[-1])[0]
self.libraries[library.label] = library
self.library_order.append(library.label)
elif os.path.exists(os.path.join(path, f)):
logging.info(f'Loading thermodynamics library from {f} in {path}...')
library = ThermoLibrary()
library.load(os.path.join(path, f), self.local_context, self.global_context)
library.label = os.path.splitext(f)[0]
self.libraries[library.label] = library
self.library_order.append(library.label)
else:
raise DatabaseError('Library {} not found in {}... Please check if your library is '
'correctly placed'.format(libraryName, path))
def load_surface(self):
"""
Load the metal database from the given `path` on disk, where `path`
points to the top-level folder of the thermo database.
"""
MetalDB = MetalDatabase()
MetalDB.load(os.path.join(settings['database.directory'], 'surface'))
self.surface = {
'metal': MetalDB
}
def load_groups(self, path):
"""
Load the thermo database from the given `path` on disk, where `path`
points to the top-level folder of the thermo database.
"""
logging.info('Loading thermodynamics group database from {0}...'.format(path))
categories = [
'group',
'ring',
'radical',
'polycyclic',
'other',
'longDistanceInteraction_cyclic',
'longDistanceInteraction_noncyclic',
'adsorptionPt111',
]
self.groups = {
category: ThermoGroups(label=category).load(os.path.join(path, category + '.py'),
self.local_context, self.global_context)
for category in categories
}
self.record_ring_generic_nodes()
self.record_polycylic_generic_nodes()
def save(self, path):
"""