-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathmodel.py
More file actions
2212 lines (1896 loc) · 103 KB
/
model.py
File metadata and controls
2212 lines (1896 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env 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. #
# #
###############################################################################
"""
Contains classes for working with the reaction model generated by RMG.
"""
import gc
import itertools
import logging
import os
import numpy as np
import rmgpy.data.rmg
from rmgpy import settings
from rmgpy.constraints import fails_species_constraints, pass_cutting_threshold
from rmgpy.data.kinetics.depository import DepositoryReaction
from rmgpy.data.kinetics.family import KineticsFamily, TemplateReaction
from rmgpy.data.kinetics.library import KineticsLibrary, LibraryReaction
from rmgpy.data.vaporLiquidMassTransfer import vapor_liquid_mass_transfer
from rmgpy.molecule.group import Group
from rmgpy.data.rmg import get_db
from rmgpy.display import display
from rmgpy.exceptions import ForbiddenStructureException
from rmgpy.kinetics import KineticsData, Arrhenius
from rmgpy.quantity import Quantity
from rmgpy.reaction import Reaction
from rmgpy.rmg.pdep import PDepReaction, PDepNetwork
from rmgpy.rmg.react import react_all
from rmgpy.species import Species
from rmgpy.thermo.thermoengine import submit
from rmgpy.rmg.decay import decay_species
from rmgpy.rmg.reactors import PhaseSystem, Phase, Interface, Reactor
from rmgpy.molecule.fragment import Fragment
################################################################################
class ReactionModel:
"""
Represent a generic reaction model. A reaction model consists of `species`,
a list of species, and `reactions`, a list of reactions.
"""
def __init__(self, species=None, reactions=None, phases=None, interfaces={}):
self.species = species or []
self.reactions = reactions or []
if phases is None:
phases = {"Default": Phase(), "Surface": Phase()}
interfaces = {frozenset({"Default", "Surface"}): Interface(list(phases.values()))}
self.phase_system = PhaseSystem(phases, interfaces)
def __reduce__(self):
"""
A helper function used when pickling an object.
"""
return ReactionModel, (self.species, self.reactions)
def merge(self, other):
"""
Return a new :class:`ReactionModel` object that is the union of this
model and `other`.
"""
if not isinstance(other, ReactionModel):
raise ValueError("Expected type ReactionModel for other parameter, got {0}".format(other.__class__))
# Initialize the merged model
final_model = ReactionModel()
# Put the current model into the merged model as-is
final_model.species.extend(self.species)
final_model.reactions.extend(self.reactions)
# Determine which species in other are already in self
common_species = {}
unique_species = []
for spec in other.species:
for spec0 in final_model.species:
if spec.is_isomorphic(spec0):
common_species[spec] = spec0
if spec0.label not in ["Ar", "N2", "Ne", "He"]:
if not spec0.thermo.is_identical_to(spec.thermo):
print("Species {0} thermo from model 1 did not match that of model 2.".format(spec.label))
break
else:
unique_species.append(spec)
# Determine which reactions in other are already in self
common_reactions = {}
unique_reactions = []
for rxn in other.reactions:
for rxn0 in final_model.reactions:
if rxn.is_isomorphic(rxn0, either_direction=True):
common_reactions[rxn] = rxn0
if not rxn0.kinetics.is_identical_to(rxn.kinetics):
print("Reaction {0} kinetics from model 1 did not match that of model 2.".format(str(rxn0)))
break
else:
unique_reactions.append(rxn)
# Add the unique species from other to the final model
final_model.species.extend(unique_species)
# Make sure unique reactions only refer to species in the final model
for rxn in unique_reactions:
for i, reactant in enumerate(rxn.reactants):
try:
rxn.reactants[i] = common_species[reactant]
if rxn.pairs:
for j, pair in enumerate(rxn.pairs):
if reactant in pair:
rxn.pairs[j] = (rxn.reactants[i], pair[1])
except KeyError:
pass
for i, product in enumerate(rxn.products):
try:
rxn.products[i] = common_species[product]
if rxn.pairs:
for j, pair in enumerate(rxn.pairs):
if product in pair:
rxn.pairs[j] = (pair[0], rxn.products[i])
except KeyError:
pass
# Add the unique reactions from other to the final model
final_model.reactions.extend(unique_reactions)
# Return the merged model
return final_model
################################################################################
class CoreEdgeReactionModel:
"""
Represent a reaction model constructed using a rate-based screening
algorithm. The species and reactions in the model itself are called the
*core*; the species and reactions identified as candidates for inclusion in
the model are called the *edge*. The attributes are:
========================= ==============================================================
Attribute Description
========================= ==============================================================
`core` The species and reactions of the current model core
`edge` The species and reactions of the current model edge
`network_dict` A dictionary of pressure-dependent reaction networks (:class:`Network` objects) indexed by source.
`network_list` A list of pressure-dependent reaction networks (:class:`Network` objects)
`network_count` A counter for the number of pressure-dependent networks created
`index_species_dict` A dictionary with a unique index pointing to the species objects
`solvent_name` String describing solvent name for liquid reactions. Empty for non-liquid estimation
`surface_site_density` The surface site density (a SurfaceConcentration quantity) or None if no heterogeneous catalyst.
========================= ==============================================================
"""
def __init__(self, core=None, edge=None, surface=None):
if core is None:
self.core = ReactionModel()
else:
self.core = core
if edge is None:
self.edge = ReactionModel()
else:
self.edge = edge
if surface is None:
self.surface = ReactionModel()
else:
self.surface = surface
# The default tolerances mimic the original RMG behavior; no edge
# pruning takes place, and the simulation is interrupted as soon as
# a species flux higher than the validity
self.network_dict = {}
self.network_list = []
self.network_count = 0
self.species_dict = {}
self.reaction_dict = {}
self.species_cache = [None for i in range(4)]
self.species_counter = 0
self.reaction_counter = 0
self.new_species_list = []
self.new_reaction_list = []
self.output_species_list = []
self.output_reaction_list = []
self.pressure_dependence = None
self.quantum_mechanics = None
self.verbose_comments = False
self.kinetics_estimator = "rate rules"
self.index_species_dict = {}
self.save_edge_species = False
self.iteration_num = 0
self.thermo_tol_keep_spc_in_edge = np.inf
self.Gfmax = np.inf
self.Gmax = np.inf
self.Gmin = -np.inf
self.min_core_size_for_prune = 50
self.maximum_edge_species = 100000
self.Tmax = 0
self.reaction_systems = []
self.new_surface_spcs_add = set()
self.new_surface_rxns_add = set()
self.new_surface_spcs_loss = set()
self.new_surface_rxns_loss = set()
self.solvent_name = ""
self.surface_site_density = None
self.unrealgroups = [
Group().from_adjacency_list(
"""
1 O u0 p2 c0 {2,S} {4,S}
2 O u0 p2 c0 {1,S} {3,S}
3 R!H u1 px c0 {2,S}
4 H u0 p0 c0 {1,S}
"""
)
]
def check_for_existing_species(self, molecule):
"""
Check to see if an existing species contains the same
:class:`molecule.Molecule` as `molecule`. Comparison is done using
isomorphism without consideration of electrons. Therefore, resonance
structures of a species will all match each other.
Returns the matched species if found and `None` otherwise.
"""
# First check cache and return if species is found
for i, spec in enumerate(self.species_cache):
if spec is not None and spec.is_isomorphic(molecule, strict=False):
self.species_cache.pop(i)
self.species_cache.insert(0, spec)
return spec
# If not found in cache, check all species with matching formula
formula = molecule.get_formula()
try:
species_list = self.species_dict[formula]
except KeyError:
pass
else:
for spec in species_list:
if spec.is_isomorphic(molecule, strict=False):
self.species_cache.pop()
self.species_cache.insert(0, spec)
return spec
# At this point we can conclude that the species is new
return None
def make_new_species(self, object, label="", reactive=True, check_existing=True, generate_thermo=True, check_decay=False, check_cut=False):
"""
Formally create a new species from the specified `object`, which can be
either a :class:`Molecule` object or an :class:`rmgpy.species.Species`
object. It is emphasized that `reactive` relates to the :Class:`Species` attribute, while `reactive_structure`
relates to the :Class:`Molecule` attribute.
"""
if isinstance(object, rmgpy.species.Species):
molecule = object.molecule[0]
label = label if label != "" else object.label
reactive = object.reactive
else:
molecule = object
molecule.clear_labeled_atoms()
# If desired, check to ensure that the species is new; return the
# existing species if not new
if check_existing:
spec = self.check_for_existing_species(molecule)
if spec is not None:
return spec, False
# If we're here then we're ready to make the new species
if check_cut:
try:
mols = molecule.cut_molecule(cut_through=False)
except AttributeError:
# it's Molecule object, change it to Fragment and then cut
molecule = Fragment().from_adjacency_list(molecule.to_adjacency_list())
mols = molecule.cut_molecule(cut_through=False)
if len(mols) == 1:
molecule = mols[0]
else:
return [self.make_new_species(mol, check_decay=check_decay) for mol in mols]
try:
spec = Species(label=label, molecule=[molecule], reactive=reactive, thermo=object.thermo, transport_data=object.transport_data)
except AttributeError:
spec = Species(label=label, molecule=[molecule], reactive=reactive)
spec.generate_resonance_structures()
if check_decay:
spcs = decay_species(spec)
if len(spcs) == 1:
spec = spcs[0]
else:
return [self.make_new_species(spc) for spc in spcs]
if reactive:
self.species_counter += 1 # count only reactive species
spec.index = self.species_counter
else:
spec.index = -1
spec.creation_iteration = self.iteration_num
spec.molecular_weight = Quantity(spec.molecule[0].get_molecular_weight() * 1000.0, "amu")
if generate_thermo:
self.generate_thermo(spec)
# If the species still does not have a label, set initial label as the SMILES
# This may change later after getting thermo in self.generate_thermo()
if not spec.label:
spec.label = spec.smiles
# ensure species labels are unique
orilabel = spec.label
label = orilabel
i = 2
while any([label in phase.names for phase in self.edge.phase_system.phases.values()]):
label = orilabel + "-" + str(i)
i += 1
spec.label = label
logging.debug("Creating new species %s", spec.label)
formula = molecule.get_formula()
if formula in self.species_dict:
self.species_dict[formula].append(spec)
else:
self.species_dict[formula] = [spec]
# Since the species is new, add it to the list of new species
self.new_species_list.append(spec)
if spec.reactive:
self.index_species_dict[spec.index] = spec
return spec, True
def check_for_existing_reaction(self, rxn):
"""
Check to see if an existing reaction has the same reactants, products, and
family as `rxn`. Returns :data:`True` or :data:`False` and the matched
reaction (if found).
First, a shortlist of reaction is retrieved that have the same reaction keys
as the parameter reaction.
Next, the reaction ID containing an identifier (e.g. label) of the reactants
and products is compared between the parameter reaction and the each of the
reactions in the shortlist. If a match is found, the discovered reaction is
returned.
If a match is not yet found, the Library (seed mechs, reaction libs)
in the reaction database are iterated over to check if a reaction was overlooked
(a reaction with a different "family" key as the parameter reaction).
"""
# Make sure the reactant and product lists are sorted before performing the check
rxn.reactants.sort()
rxn.products.sort()
# If reactants and products are identical, then something weird happened along
# the way and we got a symmetrical reaction.
if rxn.reactants == rxn.products:
logging.debug("Symmetrical reaction found. Returning no reaction")
return True, None
family_obj = get_family_library_object(rxn.family)
shortlist = self.search_retrieve_reactions(rxn)
# Now use short-list to check for matches. All should be in same forward direction.
# Make sure the reactant and product lists are sorted before performing the check
rxn_id = generate_reaction_id(rxn)
for rxn0 in shortlist:
rxn_id0 = generate_reaction_id(rxn0)
if rxn_id == rxn_id0 and are_identical_species_references(rxn, rxn0):
if isinstance(family_obj, KineticsLibrary) or isinstance(family_obj, KineticsFamily):
if not rxn.duplicate:
return True, rxn0
else:
return True, rxn0
elif isinstance(family_obj, KineticsFamily) and rxn_id == rxn_id0[::-1] and are_identical_species_references(rxn, rxn0):
if not rxn.duplicate:
return True, rxn0
# Now check seed mechanisms
# We want to check for duplicates in *other* seed mechanisms, but allow
# duplicated *within* the same seed mechanism
_, r1_fwd, r2_fwd = generate_reaction_key(rxn)
_, r1_rev, r2_rev = generate_reaction_key(rxn, useProducts=True)
for library in self.reaction_dict:
lib_obj = get_family_library_object(library)
if isinstance(lib_obj, KineticsLibrary) and library != rxn.family:
# First check seed short-list in forward direction
shortlist = self.retrieve(library, r1_fwd, r2_fwd)
for rxn0 in shortlist:
rxn_id0 = generate_reaction_id(rxn0)
if (rxn_id == rxn_id0) or (rxn_id == rxn_id0[::-1]):
if are_identical_species_references(rxn, rxn0):
return True, rxn0
# Now get the seed short-list of the reverse reaction
shortlist = self.retrieve(library, r1_rev, r2_rev)
for rxn0 in shortlist:
if are_identical_species_references(rxn, rxn0):
return True, rxn0
return False, None
def make_new_reaction(self, forward, check_existing=True, generate_thermo=True, generate_kinetics=True, perform_cut=True):
"""
Make a new reaction given a :class:`Reaction` object `forward`.
The reaction is added to the global list of reactions.
Returns the reaction in the direction that corresponds to the
estimated kinetics, along with whether or not the reaction is new to the
global reaction list.
The forward direction is determined using the "is_reverse" attribute of the
reaction's family. If the reaction family is its own reverse, then it is
made such that the forward reaction is exothermic at 298K.
The forward reaction is appended to self.new_reaction_list if it is new.
"""
# Determine the proper species objects for all reactants and products
if forward.family and forward.is_forward:
reactants = [self.make_new_species(reactant, generate_thermo=generate_thermo)[0] for reactant in forward.reactants]
products = []
if perform_cut:
# check if the product is too large so that we can cut
# maybe species do not contain element C
try:
if len(forward.reactants) > len(forward.products) and pass_cutting_threshold(forward.products[0]):
# need to cut
check_cut = True
else:
check_cut = False
except KeyError:
check_cut = False
else:
check_cut = False
for product in forward.products:
spcs = self.make_new_species(product, generate_thermo=generate_thermo, check_decay=True, check_cut=check_cut)
if type(spcs) == tuple:
products.append(spcs[0])
elif type(spcs) == list:
products.extend([spc[0] for spc in spcs])
# change the reaction to irreversible if we cut the product into fragments
if len(products) != 1 and check_cut:
forward.reversible = False
else:
try:
reactants = [self.make_new_species(reactant, generate_thermo=generate_thermo)[0] for reactant in forward.reactants]
products = [self.make_new_species(product, generate_thermo=generate_thermo)[0] for product in forward.products]
except:
logging.error(f"Error when making species in reaction {forward:s} from {forward.family:s}")
raise
if forward.specific_collider is not None:
forward.specific_collider = self.make_new_species(forward.specific_collider)[0]
if forward.pairs is not None:
for pairIndex in range(len(forward.pairs)):
reactant_index = forward.reactants.index(forward.pairs[pairIndex][0])
product_index = forward.products.index(forward.pairs[pairIndex][1])
forward.pairs[pairIndex] = (reactants[reactant_index], products[product_index])
if hasattr(forward, "reverse"):
if forward.reverse:
forward.reverse.pairs[pairIndex] = (products[product_index], reactants[reactant_index])
forward.reactants = reactants
forward.products = products
if check_existing:
found, rxn = self.check_for_existing_reaction(forward)
if found:
return rxn, False
# Generate the reaction pairs if not yet defined
if forward.pairs is None or len(forward.pairs) != max(len(forward.reactants), len(forward.products)):
forward.generate_pairs()
if hasattr(forward, "reverse"):
if forward.reverse:
forward.reverse.generate_pairs()
# Note in the log
if isinstance(forward, TemplateReaction):
logging.debug("Creating new %s template reaction %s", forward.family, forward)
elif isinstance(forward, DepositoryReaction):
logging.debug("Creating new %s reaction %s", forward.get_source(), forward)
elif isinstance(forward, LibraryReaction):
logging.debug("Creating new library reaction %s", forward)
else:
raise Exception("Unrecognized reaction type {0!s}".format(forward.__class__))
self.register_reaction(forward)
forward.index = self.reaction_counter + 1
self.reaction_counter += 1
if generate_kinetics:
if forward.kinetics is None:
self.apply_kinetics_to_reaction(forward)
if isinstance(forward.kinetics, KineticsData):
forward.kinetics = forward.kinetics.to_arrhenius()
# correct barrier heights of estimated kinetics
if isinstance(forward, (TemplateReaction, DepositoryReaction)): # i.e. not LibraryReaction
forward.fix_barrier_height() # also converts ArrheniusEP to Arrhenius.
if self.pressure_dependence and forward.is_unimolecular():
# If this is going to be run through pressure dependence code,
# we need to make sure the barrier is positive.
forward.fix_barrier_height(force_positive=True)
# Since the reaction is new, add it to the list of new reactions
self.new_reaction_list.append(forward)
# Return newly created reaction
return forward, True
def make_new_pdep_reaction(self, forward):
"""
Make a new pressure-dependent reaction based on a list of `reactants` and a
list of `products`. The reaction belongs to the specified `network` and
has pressure-dependent kinetics given by `kinetics`.
No checking for existing reactions is made here. The returned PDepReaction
object is not added to the global list of reactions, as that is intended
to represent only the high-pressure-limit set. The reaction_counter is
incremented, however, since the returned reaction can and will exist in
the model edge and/or core.
"""
# Don't create reverse reaction: all such reactions are treated as irreversible
# The reverse direction will come from a different partial network
# Note that this isn't guaranteed to satisfy thermodynamics (but will probably be close)
forward.reverse = None
forward.reversible = False
# Generate the reaction pairs if not yet defined
if forward.pairs is None:
forward.generate_pairs()
# Set reaction index and increment the counter
forward.index = self.reaction_counter + 1
self.reaction_counter += 1
return forward
def enlarge(self, new_object=None, react_edge=False, unimolecular_react=None, bimolecular_react=None, trimolecular_react=None):
"""
Enlarge a reaction model by processing the objects in the list `new_object`.
If `new_object` is a
:class:`rmg.species.Species` object, then the species is moved from
the edge to the core and reactions generated for that species, reacting
with itself and with all other species in the model core. If `new_object`
is a :class:`rmg.unirxn.network.Network` object, then reactions are
generated for the species in the network with the largest leak flux.
If the `react_edge` flag is `True`, then no new_object is needed,
and instead the algorithm proceeds to react the core species together
to form edge reactions.
"""
num_old_core_species = len(self.core.species)
num_old_core_reactions = len(self.core.reactions)
num_old_edge_species = len(self.edge.species)
num_old_edge_reactions = len(self.edge.reactions)
reactions_moved_from_edge = []
self.new_reaction_list = []
self.new_species_list = []
# Determine number of parallel processes.
from rmgpy.rmg.main import determine_procnum_from_ram
procnum = determine_procnum_from_ram()
if react_edge is False:
# We are adding core species
new_reactions = []
pdep_network = None
object_was_in_edge = False
if isinstance(new_object, Species):
new_species = new_object
object_was_in_edge = new_species in self.edge.species
if not new_species.reactive:
logging.info("NOT generating reactions for unreactive species {0}".format(new_species))
else:
logging.info("Adding species {0} to model core".format(new_species))
display(new_species) # if running in IPython --pylab mode, draws the picture!
# Add new species
if new_species not in self.core.species:
reactions_moved_from_edge = self.add_species_to_core(new_species)
else:
reactions_moved_from_edge = []
elif isinstance(new_object, tuple) and isinstance(new_object[0], PDepNetwork) and self.pressure_dependence:
pdep_network, new_species = new_object
new_reactions.extend(pdep_network.explore_isomer(new_species))
self.process_new_reactions(new_reactions, new_species, pdep_network)
else:
raise TypeError(
"Unable to use object {0} to enlarge reaction model; expecting an object of class "
"rmg.model.Species or rmg.model.PDepNetwork, not {1}".format(new_object, new_object.__class__)
)
# If there are any core species among the unimolecular product channels
# of any existing network, they need to be made included
for network in self.network_list:
network.update_configurations(self)
index = 0
isomers = [isomer.species[0] for isomer in network.isomers]
while index < len(self.core.species):
species = self.core.species[index]
if species in isomers and species not in network.explored:
network.explored.append(species)
continue
for products in network.products:
products = products.species
if len(products) == 1 and products[0] == species:
new_reactions = network.explore_isomer(species)
self.process_new_reactions(new_reactions, species, network)
network.update_configurations(self)
index = 0
break
else:
index += 1
if isinstance(new_object, Species) and object_was_in_edge:
# moved one species from edge to core
num_old_edge_species -= 1
# moved these reactions from edge to core
num_old_edge_reactions -= len(reactions_moved_from_edge)
else:
# Generate reactions between all core species which have not been
# reacted yet and exceed the reaction filter thresholds
rxn_lists, spcs_tuples = react_all(
self.core.species, num_old_core_species, unimolecular_react, bimolecular_react, trimolecular_react=trimolecular_react, procnum=procnum
)
for rxnList, spcTuple in zip(rxn_lists, spcs_tuples):
if rxnList:
# Identify a core species which was used to generate the reaction
# This is only used to determine the reaction direction for processing
spc = spcTuple[0]
self.process_new_reactions(rxnList, spc)
################################################################
# Begin processing the new species and reactions
# Generate thermo for new species
if self.new_species_list:
logging.info("Generating thermo for new species...")
self.apply_thermo_to_species(procnum)
# Do thermodynamic filtering
if not np.isinf(self.thermo_tol_keep_spc_in_edge) and self.new_species_list != []:
self.thermo_filter_species(self.new_species_list)
# Update unimolecular (pressure dependent) reaction networks
if self.pressure_dependence:
# Recalculate k(T,P) values for modified networks
self.update_unimolecular_reaction_networks()
logging.info("")
# Check new core and edge reactions for Chemkin duplicates
# The same duplicate reaction gets brought into the core
# at the same time, so there is no danger in checking all of the edge.
new_core_reactions = self.core.reactions[num_old_core_reactions:]
new_edge_reactions = self.edge.reactions[num_old_edge_reactions:]
checked_reactions = self.core.reactions[:num_old_core_reactions] + self.edge.reactions[:num_old_edge_reactions]
from rmgpy.chemkin import mark_duplicate_reaction
for rxn in new_core_reactions:
mark_duplicate_reaction(rxn, checked_reactions)
checked_reactions.append(rxn)
if self.save_edge_species:
for rxn in new_edge_reactions:
mark_duplicate_reaction(rxn, checked_reactions)
checked_reactions.append(rxn)
self.log_enlarge_summary(
new_core_species=self.core.species[num_old_core_species:],
new_core_reactions=self.core.reactions[num_old_core_reactions:],
reactions_moved_from_edge=reactions_moved_from_edge,
new_edge_species=self.edge.species[num_old_edge_species:],
new_edge_reactions=self.edge.reactions[num_old_edge_reactions:],
react_edge=react_edge,
)
logging.info("")
def add_new_surface_objects(self, obj, new_surface_species, new_surface_reactions, reaction_system):
"""
obj is the list of objects for enlargement coming from simulate
new_surface_species and new_surface_reactions are the current lists of surface species and surface reactions
following simulation
reaction_system is the current reactor
manages surface species and reactions being moved to and from the surface
moves them to appropriate newSurfaceSpc/RxnsAdd/loss sets
returns false if the surface has changed
"""
surf_spcs = set(self.surface.species)
surf_rxns = set(self.surface.reactions)
new_surface_species = set(new_surface_species)
new_surface_reactions = set(new_surface_reactions)
added_rxns = {k for k in obj if isinstance(k, Reaction)}
added_surface_rxns = new_surface_reactions - surf_rxns
added_bulk_rxns = added_rxns - added_surface_rxns
lost_surface_rxns = (surf_rxns - new_surface_reactions) | added_bulk_rxns
added_spcs = {k for k in obj if isinstance(k, Species)} | {
k.get_maximum_leak_species(reaction_system.T.value_si, reaction_system.P.value_si) for k in obj if isinstance(k, PDepNetwork)
}
lost_surface_spcs = (surf_spcs - new_surface_species) | added_spcs
added_surface_spcs = new_surface_species - surf_spcs
self.new_surface_spcs_add = self.new_surface_spcs_add | added_surface_spcs
self.new_surface_rxns_add = self.new_surface_rxns_add | added_surface_rxns
self.new_surface_spcs_loss = self.new_surface_spcs_loss | lost_surface_spcs
self.new_surface_rxns_loss = self.new_surface_rxns_loss | lost_surface_rxns
return not (
self.new_surface_rxns_add != set()
or self.new_surface_rxns_loss != set()
or self.new_surface_spcs_loss != set()
or self.new_surface_spcs_add != set()
)
def adjust_surface(self):
"""
Here we add species intended to be added and remove any species that need to be moved out of the core.
For now we remove reactions from the surface that have become part of a PDepNetwork by
intersecting the set of surface reactions with the core so that all surface reactions are in the core
thus the surface algorithm currently (June 2017) is not implemented for pdep networks
(however it will function fine for non-pdep reactions on a pdep run)
"""
self.surface.species = list(((set(self.surface.species) | self.new_surface_spcs_add) - self.new_surface_spcs_loss) & set(self.core.species))
self.surface.reactions = list(
((set(self.surface.reactions) | self.new_surface_rxns_add) - self.new_surface_rxns_loss) & set(self.core.reactions)
)
self.clear_surface_adjustments()
def clear_surface_adjustments(self):
"""
empties surface tracking varaibles
"""
self.new_surface_spcs_add = set()
self.new_surface_rxns_add = set()
self.new_surface_spcs_loss = set()
self.new_surface_rxns_loss = set()
def process_new_reactions(self, new_reactions, new_species, pdep_network=None, generate_thermo=True, generate_kinetics=True):
"""
Process a list of newly-generated reactions involving the new core
species or explored isomer `new_species` in network `pdep_network`.
Makes a reaction and decides where to put it: core, edge, or PDepNetwork.
"""
for rxn in new_reactions:
rxn, is_new = self.make_new_reaction(rxn, generate_thermo=generate_thermo, generate_kinetics=generate_kinetics)
if rxn is None:
# Skip this reaction because there was something wrong with it
continue
if is_new:
# We've made a new reaction, so make sure the species involved
# are in the core or edge
all_species_in_core = True
# Add the reactant and product species to the edge if necessary
# At the same time, check if all reactants and products are in the core
for spec in rxn.reactants:
if spec not in self.core.species:
all_species_in_core = False
if spec not in self.edge.species:
self.add_species_to_edge(spec)
for spec in rxn.products:
if spec not in self.core.species:
all_species_in_core = False
if spec not in self.edge.species:
self.add_species_to_edge(spec)
isomer_atoms = sum([len(spec.molecule[0].atoms) for spec in rxn.reactants])
# Decide whether or not to handle the reaction as a pressure-dependent reaction
pdep = True
if not self.pressure_dependence:
# The pressure dependence option is turned off entirely
pdep = False
elif self.pressure_dependence.maximum_atoms is not None and self.pressure_dependence.maximum_atoms < isomer_atoms:
# The reaction involves so many atoms that pressure-dependent effects are assumed to be negligible
pdep = False
elif not (rxn.is_isomerization() or rxn.is_dissociation() or rxn.is_association()):
# The reaction is not unimolecular in either direction, so it cannot be pressure-dependent
pdep = False
elif isinstance(rxn, LibraryReaction):
# Try generating the high pressure limit kinetics. If successful, set pdep to ``True``, and vice versa.
pdep = rxn.generate_high_p_limit_kinetics()
elif any([any([x.is_subgraph_isomorphic(q) for q in self.unrealgroups]) for y in rxn.reactants + rxn.products for x in y.molecule]):
pdep = False
# If pressure dependence is on, we only add reactions that are not unimolecular;
# unimolecular reactions will be added after processing the associated networks
if not pdep:
if not is_new:
# The reaction is not new, so it should already be in the core or edge
continue
if all_species_in_core:
self.add_reaction_to_core(rxn)
else:
self.add_reaction_to_edge(rxn)
else:
# Add the reaction to the appropriate unimolecular reaction network
# If pdep_network is not None then that will be the network the
# (path) reactions are added to
# Note that this must be done even with reactions that are not new
# because of the way partial networks are explored
# Since PDepReactions are created as irreversible, not doing so
# would cause you to miss the reverse reactions!
self.add_reaction_to_unimolecular_networks(rxn, new_species=new_species, network=pdep_network)
if isinstance(rxn, LibraryReaction) and not rxn.kinetics.is_pressure_dependent():
# If the reaction came from a library, and it does not have PDep kinetics,
# omit it from the core and edge so that it does not get double-counted with the pdep network
if rxn in self.core.reactions:
self.core.reactions.remove(rxn)
if rxn in self.edge.reactions:
self.edge.reactions.remove(rxn)
def apply_thermo_to_species(self, procnum):
"""
Generate thermo for species. QM calculations are parallelized if requested.
"""
from rmgpy.rmg.input import get_input
quantum_mechanics = get_input("quantum_mechanics")
if quantum_mechanics:
quantum_mechanics.run_jobs(self.new_species_list, procnum=procnum)
# Serial thermo calculation for other methods
for spc in self.new_species_list:
self.generate_thermo(spc, rename=True)
def generate_thermo(self, spc, rename=False):
"""
Generate thermo for species.
"""
if not spc.thermo:
submit(spc, self.solvent_name)
if rename and spc.thermo and spc.thermo.label != "": # check if thermo libraries have a name for it
if isinstance(spc.molecule[0], Fragment):
logging.info("Species {0} NOT renamed {1} but get thermo based on thermo library".format(spc.label, spc.thermo.label))
spc.label = spc.smiles
else:
logging.info("Species {0} renamed {1} based on thermo library name".format(spc.label, spc.thermo.label))
spc.label = spc.thermo.label
if vapor_liquid_mass_transfer.enabled:
spc.get_liquid_volumetric_mass_transfer_coefficient_data()
spc.get_henry_law_constant_data()
spc.generate_energy_transfer_model()
def process_coverage_dependence(self, kinetics):
"""Process the coverage dependence kinetics.
This ensures that species that are used in coverage-dependent kinetic
expressions exist in the model. (Before this is called, they may have
only existed in a reaction libary instance).
If <CoreEdgeReactionModel>self.coverage_dependence is False then
it instead removes any coverage_dependence from the kinetics.
"""
if not self.coverage_dependence:
kinetics.coverage_dependence = None
return
cov_dep = {}
for species, values in kinetics.coverage_dependence.items():
species_in_model, is_new = self.make_new_species(species)
cov_dep[species_in_model] = values
kinetics.coverage_dependence = cov_dep
def apply_kinetics_to_reaction(self, reaction):
"""
retrieve the best kinetics for the reaction and apply it towards the forward
or reverse direction (if reverse, flip the direaction).
"""
from rmgpy.data.rmg import get_db
# Find the reaction kinetics
kinetics, source, entry, is_forward = self.generate_kinetics(reaction)
# Flip the reaction direction if the kinetics are defined in the reverse direction
if not is_forward:
family = get_db("kinetics").families[reaction.family]
reaction.reactants, reaction.products = reaction.products, reaction.reactants
reaction.pairs = [(p, r) for r, p in reaction.pairs]
if family.own_reverse and hasattr(reaction, "reverse"):
if reaction.reverse:
reaction.template = reaction.reverse.template
# replace degeneracy
reaction.degeneracy = reaction.reverse.degeneracy
# We're done with the "reverse" attribute, so delete it to save a bit of memory
reaction.reverse = None
reaction.kinetics = kinetics
def generate_kinetics(self, reaction):
"""
Generate best possible kinetics for the given `reaction` using the kinetics database.
"""
# Only reactions from families should be missing kinetics
assert isinstance(reaction, TemplateReaction)
family = get_family_library_object(reaction.family)
# Get the kinetics for the reaction
kinetics, source, entry, is_forward = family.get_kinetics(
reaction, template_labels=reaction.template, degeneracy=reaction.degeneracy, estimator=self.kinetics_estimator, return_all_kinetics=False
)
# Get the gibbs free energy of reaction at 298 K
G298 = reaction.get_free_energy_of_reaction(298)
gibbs_is_positive = G298 > -1e-8
if family.own_reverse and len(reaction.products) == len(reaction.reactants) and hasattr(reaction, "reverse"):
if reaction.reverse:
# The kinetics family is its own reverse, so we could estimate kinetics in either direction
# First get the kinetics for the other direction
rev_kinetics, rev_source, rev_entry, rev_is_forward = family.get_kinetics(
reaction.reverse,
template_labels=reaction.reverse.template,
degeneracy=reaction.reverse.degeneracy,
estimator=self.kinetics_estimator,
return_all_kinetics=False,
)
# Now decide which direction's kinetics to keep
keep_reverse = False
if entry is not None and rev_entry is None:
# Only the forward has an entry, meaning an exact match in a depository or template
# the reverse must have used an averaged estimated node - so use forward.
reason = "This direction matched an entry in {0}, the other was just an estimate.".format(reaction.family)
elif entry is None and rev_entry is not None:
# Only the reverse has an entry (see above) - use reverse.
keep_reverse = True
reason = "This direction matched an entry in {0}, the other was just an estimate.".format(reaction.family)
elif entry is not None and rev_entry is not None and entry is rev_entry:
# Both forward and reverse have the same source and entry
# Use the one for which the kinetics is the forward kinetics
keep_reverse = gibbs_is_positive and is_forward and rev_is_forward