-
Notifications
You must be signed in to change notification settings - Fork 225
/
main.py
2612 lines (2262 loc) · 136 KB
/
main.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-2021 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. #
# #
###############################################################################
"""
This module contains the main execution functionality for Reaction Mechanism
Generator (RMG).
"""
import copy
import gc
import logging
import marshal
import os
import resource
import shutil
import sys
import time
import warnings
from copy import deepcopy
import h5py
import numpy as np
import psutil
import yaml
from cantera import ck2cti
from scipy.optimize import brute
import rmgpy.util as util
from rmgpy.rmg.model import Species, CoreEdgeReactionModel
from rmgpy.rmg.pdep import PDepNetwork
from rmgpy import settings
from rmgpy.chemkin import ChemkinWriter
from rmgpy.constraints import fails_species_constraints
from rmgpy.data.base import Entry
from rmgpy.data.kinetics.family import TemplateReaction
from rmgpy.data.kinetics.library import KineticsLibrary, LibraryReaction
from rmgpy.data.rmg import RMGDatabase
from rmgpy.exceptions import ForbiddenStructureException, DatabaseError, CoreError, InputError
from rmgpy.kinetics.diffusionLimited import diffusion_limiter
from rmgpy.kinetics import ThirdBody
from rmgpy.molecule import Molecule
from rmgpy.qm.main import QMDatabaseWriter
from rmgpy.reaction import Reaction
from rmgpy.rmg.listener import SimulationProfileWriter, SimulationProfilePlotter
from rmgpy.rmg.output import OutputHTMLWriter
from rmgpy.rmg.pdep import PDepReaction
from rmgpy.rmg.settings import ModelSettings
from rmgpy.solver.base import TerminationTime, TerminationConversion
from rmgpy.solver.simple import SimpleReactor
from rmgpy.stats import ExecutionStatsWriter
from rmgpy.thermo.thermoengine import submit
from rmgpy.tools.plot import plot_sensitivity
from rmgpy.tools.uncertainty import Uncertainty, process_local_results
from rmgpy.yml import RMSWriter
from rmgpy.rmg.reactors import Reactor
################################################################################
# This module uses the HDF5 data format, which can cause problems on files systems that use NFS (common for network
# mounted file systems. The following sets an environment variable that prevents file locking that would otherwise
# cause a problem for NFS.
os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE'
solvent = None
# Maximum number of user defined processors
maxproc = 1
class RMG(util.Subject):
"""
A representation of a Reaction Mechanism Generator (RMG) job. The
attributes are:
=================================== ================================================
Attribute Description
=================================== ================================================
`input_file` The path to the input file
`profiler` A cProfile.Profile object for time profiling RMG
----------------------------------- ------------------------------------------------
`database_directory` The directory containing the RMG database
`thermo_libraries` The thermodynamics libraries to load
`reaction_libraries` The kinetics libraries to load
`statmech_libraries` The statistical mechanics libraries to load
`seed_mechanisms` The seed mechanisms included in the model
`kinetics_families` The kinetics families to use for reaction generation
`kinetics_depositories` The kinetics depositories to use for looking up kinetics in each family
`kinetics_estimator` The method to use to estimate kinetics: 'group additivity' or 'rate rules'
`solvent` If solvation estimates are required, the name of the solvent.
----------------------------------- ------------------------------------------------
`reaction_model` The core-edge reaction model generated by this job
`reaction_systems` A list of the reaction systems used in this job
`database` The RMG database used in this job
----------------------------------- ------------------------------------------------
`model_settings_list` List of ModelSettings objects containing information related to how to manage species/reaction movement
`simulator_settings_list` List of SimulatorSettings objects containing information on how to run simulations
`init_react_tuples` List of name tuples of species to react at beginning of run
`trimolecular` ``True`` to consider reactions between three species (i.e., if trimolecular reaction families are present)
`unimolecular_threshold` Array of flags indicating whether a species is above the unimolecular reaction threshold
`bimolecular_threshold` Array of flags indicating whether two species are above the bimolecular reaction threshold
`trimolecular_threshold` Array of flags indicating whether three species are above the trimolecular reaction threshold
`unimolecular_react` Array of flags indicating whether a species should react unimolecularly in the enlarge step
`bimolecular_react` Array of flags indicating whether two species should react in the enlarge step
`trimolecular_react` Array of flags indicating whether three species should react in the enlarge step
`termination` A list of termination targets (i.e :class:`TerminationTime` and :class:`TerminationConversion` objects)
`species_constraints` Dictates the maximum number of atoms, carbons, electrons, etc. generated by RMG
----------------------------------- ------------------------------------------------
`output_directory` The directory used to save output files
`verbosity` The level of logging verbosity for console output
`units` The unit system to use to save output files (currently must be 'si')
`generate_output_html` ``True`` to draw pictures of the species and reactions, saving a visualized model in an output HTML file. ``False`` otherwise
`generate_plots` ``True`` to generate plots of the job execution statistics after each iteration, ``False`` otherwise
`verbose_comments` ``True`` to keep the verbose comments for database estimates, ``False`` otherwise
`save_edge_species` ``True`` to save chemkin and HTML files of the edge species, ``False`` otherwise
`keep_irreversible` ``True`` to keep ireversibility of library reactions as is ('<=>' or '=>'). ``False`` (default) to force all library reactions to be reversible ('<=>')
`trimolecular_product_reversible` ``True`` (default) to allow families with trimolecular products to react in the reverse direction, ``False`` otherwise
`pressure_dependence` Whether to process unimolecular (pressure-dependent) reaction networks
`quantum_mechanics` Whether to apply quantum mechanical calculations instead of group additivity to certain molecular types.
`ml_estimator` To use thermo estimation with machine learning
`ml_settings` Settings for ML estimation
`walltime` The maximum amount of CPU time in the form DD:HH:MM:SS to expend on this job; used to stop gracefully so we can still get profiling information
`max_iterations` The maximum number of RMG iterations allowed, after which the job will terminate
`kinetics_datastore` ``True`` if storing details of each kinetic database entry in text file, ``False`` otherwise
----------------------------------- ------------------------------------------------
`initialization_time` The time at which the job was initiated, in seconds since the epoch (i.e. from time.time())
`done` Whether the job has completed (there is nothing new to add)
=================================== ================================================
"""
def __init__(self, input_file=None, output_directory=None, profiler=None, stats_file=None):
super(RMG, self).__init__()
self.input_file = input_file
self.output_directory = output_directory
self.profiler = profiler
self.clear()
self.model_settings_list = []
self.simulator_settings_list = []
self.max_iterations = None
self.Tmin = 0.0
self.Tmax = 0.0
self.Pmin = 0.0
self.Pmax = 0.0
self.database = None
def clear(self):
"""
Clear all loaded information about the job (except the file paths).
"""
self.database_directory = None
self.thermo_libraries = None
self.transport_libraries = None
self.reaction_libraries = None
self.statmech_libraries = None
self.seed_mechanisms = None
self.kinetics_families = None
self.kinetics_depositories = None
self.kinetics_estimator = 'group additivity'
self.solvent = None
self.diffusion_limiter = None
self.surface_site_density = None
self.binding_energies = None
self.coverage_dependence = False
self.reaction_model = None
self.reaction_systems = None
self.database = None
self.reaction_system = None
self.model_settings_list = []
self.simulator_settings_list = []
self.balance_species = None
self.filter_reactions = False
self.init_react_tuples = []
self.trimolecular = False
self.unimolecular_react = None
self.bimolecular_react = None
self.trimolecular_react = None
self.unimolecular_threshold = None
self.bimolecular_threshold = None
self.trimolecular_threshold = None
self.termination = []
self.done = False
self.verbosity = logging.INFO
self.units = 'si'
self.generate_output_html = None
self.generate_plots = None
self.save_simulation_profiles = None
self.verbose_comments = None
self.save_edge_species = None
self.keep_irreversible = None
self.trimolecular_product_reversible = None
self.pressure_dependence = None
self.quantum_mechanics = None
self.ml_estimator = None
self.ml_settings = None
self.species_constraints = {}
self.walltime = '00:00:00:00'
self.save_seed_modulus = -1
self.max_iterations = None
self.initialization_time = 0
self.kinetics_datastore = None
self.restart = False
self.core_seed_path = None
self.edge_seed_path = None
self.filters_path = None
self.species_map_path = None
self.name = 'Seed'
self.generate_seed_each_iteration = True
self.save_seed_to_database = False
self.thermo_central_database = None
self.uncertainty = None
self.exec_time = []
def load_input(self, path=None):
"""
Load an RMG job from the input file located at `input_file`, or
from the `input_file` attribute if not given as a parameter.
"""
from rmgpy.rmg.input import read_input_file
if path is None:
path = self.input_file
read_input_file(path, self)
self.reaction_model.kinetics_estimator = self.kinetics_estimator
# If the output directory is not yet set, then set it to the same
# directory as the input file by default
if not self.output_directory:
self.output_directory = os.path.dirname(path)
if self.pressure_dependence:
self.pressure_dependence.output_file = self.output_directory
self.reaction_model.pressure_dependence = self.pressure_dependence
if self.solvent:
self.reaction_model.solvent_name = self.solvent
if self.surface_site_density:
self.reaction_model.surface_site_density = self.surface_site_density
self.reaction_model.core.phase_system.phases["Surface"].site_density = self.surface_site_density.value_si
self.reaction_model.edge.phase_system.phases["Surface"].site_density = self.surface_site_density.value_si
self.reaction_model.coverage_dependence = self.coverage_dependence
self.reaction_model.verbose_comments = self.verbose_comments
self.reaction_model.save_edge_species = self.save_edge_species
if self.quantum_mechanics:
self.reaction_model.quantum_mechanics = self.quantum_mechanics
for reaction_system in self.reaction_systems:
self.reaction_model.reaction_systems.append(reaction_system)
def load_thermo_input(self, path=None):
"""
Load an Thermo Estimation job from a thermo input file located at `input_file`, or
from the `input_file` attribute if not given as a parameter.
"""
from rmgpy.rmg.input import read_thermo_input_file
if path is None:
path = self.input_file
if not self.output_directory:
self.output_directory = os.path.dirname(path)
read_thermo_input_file(path, self)
if self.quantum_mechanics:
self.reaction_model.quantum_mechanics = self.quantum_mechanics
def check_input(self):
"""
Check for a few common mistakes in the input file.
"""
if self.pressure_dependence:
for index, reaction_system in enumerate(self.reaction_systems):
if reaction_system.T:
logging.info(reaction_system.T)
assert (reaction_system.T.value_si < self.pressure_dependence.Tmax.value_si), "Reaction system T is above pressure_dependence range."
assert (reaction_system.T.value_si > self.pressure_dependence.Tmin.value_si), "Reaction system T is below pressure_dependence range."
else:
assert (reaction_system.Trange[1].value_si < self.pressure_dependence.Tmax.value_si), "Reaction system T is above pressure_dependence range."
assert (reaction_system.Trange[0].value_si > self.pressure_dependence.Tmin.value_si), "Reaction system T is below pressure_dependence range."
if reaction_system.P:
assert (reaction_system.P.value_si < self.pressure_dependence.Pmax.value_si), "Reaction system P is above pressure_dependence range."
assert (reaction_system.P.value_si > self.pressure_dependence.Pmin.value_si), "Reaction system P is below pressure_dependence range."
else:
assert (reaction_system.Prange[1].value_si < self.pressure_dependence.Pmax.value_si), "Reaction system P is above pressure_dependence range."
assert (reaction_system.Prange[0].value_si > self.pressure_dependence.Pmin.value_si), "Reaction system P is below pressure_dependence range."
assert any([not s.reactive for s in reaction_system.initial_mole_fractions.keys()]), \
"Pressure Dependence calculations require at least one inert (nonreacting) species for the bath gas."
def check_libraries(self):
"""
Check unwanted use of libraries:
Liquid phase libraries in Gas phase simulation.
Loading a Liquid phase library obtained in another solvent than the one defined in the input file.
Other checks can be added here.
"""
# Liquid phase simulation checks
if self.solvent:
# check thermo librairies
for libIter in self.database.thermo.libraries.keys():
if self.database.thermo.libraries[libIter].solvent:
if not self.solvent == self.database.thermo.libraries[libIter].solvent:
raise DatabaseError("Thermo library '{2}' was obtained in '{1}' and cannot be used with this "
"liquid phase simulation in '{0}' "
.format(self.solvent,
self.database.thermo.libraries[libIter].solvent,
self.database.thermo.libraries[libIter].name))
# Check kinetic librairies
for libIter in self.database.kinetics.libraries.keys():
if self.database.kinetics.libraries[libIter].solvent:
if not self.solvent == self.database.kinetics.libraries[libIter].solvent:
raise DatabaseError("Kinetics library '{2}' was obtained in '{1}' and cannot be used with this "
"liquid phase simulation in '{0}'"
.format(self.solvent,
self.database.kinetics.libraries[libIter].solvent,
self.database.kinetics.libraries[libIter].name))
# Gas phase simulation checks
else:
# check thermo librairies
for libIter in self.database.thermo.libraries.keys():
if self.database.thermo.libraries[libIter].solvent:
raise DatabaseError("Thermo library '{1}' was obtained in '{0}' solvent and cannot be used in gas "
"phase simulation"
.format(self.database.thermo.libraries[libIter].solvent,
self.database.thermo.libraries[libIter].name))
# Check kinetic librairies
for libIter in self.database.kinetics.libraries.keys():
if self.database.kinetics.libraries[libIter].solvent:
raise DatabaseError("Kinetics library '{1}' was obtained in '{0}' solvent and cannot be used in "
"gas phase simulation"
.format(self.database.kinetics.libraries[libIter].solvent,
self.database.kinetics.libraries[libIter].name))
def save_input(self, path=None):
"""
Save an RMG job to the input file located at `path`.
"""
from rmgpy.rmg.input import save_input_file
save_input_file(path, self)
def load_database(self):
self.database = RMGDatabase()
self.database.load(
path=self.database_directory,
thermo_libraries=self.thermo_libraries,
transport_libraries=self.transport_libraries,
reaction_libraries=[library for library, option in self.reaction_libraries],
seed_mechanisms=self.seed_mechanisms,
kinetics_families=self.kinetics_families,
kinetics_depositories=self.kinetics_depositories,
# frequenciesLibraries = self.statmech_libraries,
depository=False, # Don't bother loading the depository information, as we don't use it
)
# Turn off reversibility for families with three products if desired
if not self.trimolecular_product_reversible:
for family in self.database.kinetics.families.values():
if len(family.forward_template.products) > 2:
family.reversible = False
family.reverse_template = None
family.reverse_recipe = None
family.reverse = None
# Determine if trimolecular families are present
for family in self.database.kinetics.families.values():
if len(family.forward_template.reactants) > 2:
logging.info('Trimolecular reactions are turned on')
self.trimolecular = True
break
# Only check products if we want to react them
if not self.trimolecular and self.trimolecular_product_reversible:
for family in self.database.kinetics.families.values():
if len(family.forward_template.products) > 2:
logging.info('Trimolecular reactions are turned on')
self.trimolecular = True
break
# check libraries
self.check_libraries()
# set global binding energies variable
if self.binding_energies:
self.database.thermo.set_binding_energies(self.binding_energies)
# set global variable solvent
if self.solvent:
global solvent
solvent = self.solvent
if self.kinetics_estimator == 'rate rules':
if '!training' not in self.kinetics_depositories:
logging.info('Adding rate rules from training set in kinetics families...')
# Temporarily remove species constraints for the training reactions
copy_species_constraints = copy.copy(self.species_constraints)
self.species_constraints = {}
for family in self.database.kinetics.families.values():
if not family.auto_generated:
family.add_rules_from_training(thermo_database=self.database.thermo)
# If requested by the user, write a text file for each kinetics family detailing the source of each entry
if self.kinetics_datastore:
logging.info(
'Writing sources of kinetic entries in family {0} to text file'.format(family.label))
path = os.path.join(self.output_directory, 'kinetics_database', family.label + '.txt')
with open(path, 'w') as f:
for template_label, entries in family.rules.entries.items():
f.write("Template [{0}] uses the {1} following source(s):\n".format(template_label,
str(len(entries))))
for entry_index, entry in enumerate(entries):
f.write(str(entry_index+1) + ". " + entry.short_desc + "\n" + entry.long_desc + "\n")
f.write('\n')
f.write('\n')
self.species_constraints = copy_species_constraints
else:
logging.info('Training set explicitly not added to rate rules in kinetics families...')
logging.info('Filling in rate rules in kinetics families by averaging...')
for family in self.database.kinetics.families.values():
if not family.auto_generated:
family.fill_rules_by_averaging_up(verbose=self.verbose_comments)
def initialize(self, **kwargs):
"""
Initialize an RMG job using the command-line arguments `args` as returned
by the :mod:`argparse` package.
"""
# Save initialization time
self.initialization_time = time.time()
# Log start timestamp
logging.info('RMG execution initiated at ' + time.asctime() + '\n')
# Print out RMG header
self.log_header()
# Read input file
self.load_input(self.input_file)
if kwargs.get('restart', ''):
import rmgpy.rmg.input
rmgpy.rmg.input.restart_from_seed(path=kwargs['restart'])
# Check input file
self.check_input()
# Properly set filter_reactions to initialize flags properly
if len(self.model_settings_list) > 0:
self.filter_reactions = self.model_settings_list[0].filter_reactions
# Make output subdirectories
util.make_output_subdirectory(self.output_directory, 'pdep')
util.make_output_subdirectory(self.output_directory, 'solver')
util.make_output_subdirectory(self.output_directory, 'kinetics_database')
# Specifies if details of kinetic database entries should be stored according to user
try:
self.kinetics_datastore = kwargs['kinetics_datastore']
except KeyError:
self.kinetics_datastore = False
global maxproc
try:
maxproc = kwargs['maxproc']
except KeyError:
pass
if maxproc > psutil.cpu_count():
raise ValueError("""Invalid input for user defined maximum number of processes {0};
should be an integer and smaller or equal to your available number of
processors {1}""".format(maxproc, psutil.cpu_count()))
# Load databases
self.load_database()
for spec in self.initial_species:
self.reaction_model.add_species_to_edge(spec)
for reaction_system in self.reaction_systems:
if isinstance(reaction_system, Reactor):
reaction_system.finish_termination_criteria()
# Load restart seed mechanism (if specified)
if self.restart:
# Copy the restart files to a separate folder so that the job does not overwrite it
restart_dir = os.path.join(self.output_directory, 'previous_restart')
core_restart = os.path.join(restart_dir, 'restart')
edge_restart = os.path.join(restart_dir, 'restart_edge')
filters_restart = os.path.join(restart_dir, 'filters')
util.make_output_subdirectory(self.output_directory, 'previous_restart')
shutil.copytree(self.core_seed_path, core_restart)
shutil.copytree(self.edge_seed_path, edge_restart)
os.mkdir(filters_restart)
shutil.copyfile(self.filters_path, os.path.join(filters_restart, 'filters.h5'))
shutil.copyfile(self.species_map_path, os.path.join(filters_restart, 'species_map.yml'))
# Load the seed mechanism to get the core and edge species
self.database.kinetics.load_libraries(restart_dir, libraries=['restart', 'restart_edge'])
self.seed_mechanisms.append('restart')
self.reaction_libraries.append(('restart_edge', False))
# Set trimolecular reactant flags of reaction systems
if self.trimolecular:
for reaction_system in self.reaction_systems:
reaction_system.trimolecular = True
# Do all liquid-phase startup things:
if self.solvent:
solvent_data = self.database.solvation.get_solvent_data(self.solvent)
if not self.reaction_model.core.phase_system.in_nose:
self.reaction_model.core.phase_system.phases["Default"].set_solvent(solvent_data)
self.reaction_model.edge.phase_system.phases["Default"].set_solvent(solvent_data)
diffusion_limiter.enable(solvent_data, self.database.solvation)
logging.info("Setting solvent data for {0}".format(self.solvent))
# Set solvent viscosity for reaction filtering
for reaction_system in self.reaction_systems:
if reaction_system.T:
reaction_system.viscosity = solvent_data.get_solvent_viscosity(reaction_system.T.value_si)
try:
self.walltime = kwargs['walltime']
except KeyError:
pass
try:
self.max_iterations = kwargs['max_iterations']
except KeyError:
pass
data = self.walltime.split(':')
if not len(data) == 4:
raise ValueError('Invalid format for wall time {0}; should be DD:HH:MM:SS.'.format(self.walltime))
self.walltime = int(data[-1]) + 60 * int(data[-2]) + 3600 * int(data[-3]) + 86400 * int(data[-4])
# Initialize reaction model
# Seed mechanisms: add species and reactions from seed mechanism
# DON'T generate any more reactions for the seed species at this time
for seed_mechanism in self.seed_mechanisms:
self.reaction_model.add_seed_mechanism_to_core(seed_mechanism, react=False)
# Reaction libraries: add species and reactions from reaction library to the edge so
# that RMG can find them if their rates are large enough
for library, option in self.reaction_libraries:
self.reaction_model.add_reaction_library_to_edge(library)
# Also always add in a few bath gases (since RMG-Java does)
for label, smiles in [('Ar', '[Ar]'), ('He', '[He]'), ('Ne', '[Ne]'), ('N2', 'N#N')]:
molecule = Molecule().from_smiles(smiles)
spec, is_new = self.reaction_model.make_new_species(molecule, label=label, reactive=False)
if is_new:
self.initial_species.append(spec)
# Perform species constraints and forbidden species checks on input species
for spec in self.initial_species:
if self.database.forbidden_structures.is_molecule_forbidden(spec.molecule[0]):
if 'allowed' in self.species_constraints and 'input species' in self.species_constraints['allowed']:
logging.warning('Input species {0} is globally forbidden. It will behave as an inert unless found '
'in a seed mechanism or reaction library.'.format(spec.label))
else:
raise ForbiddenStructureException("Input species {0} is globally forbidden. You may explicitly "
"allow it, but it will remain inert unless found in a seed "
"mechanism or reaction library.".format(spec.label))
if fails_species_constraints(spec):
if 'allowed' in self.species_constraints and 'input species' in self.species_constraints['allowed']:
self.species_constraints['explicitlyAllowedMolecules'].append(spec.molecule[0])
else:
raise ForbiddenStructureException("Species constraints forbids input species {0}. Please "
"reformulate constraints, remove the species, or explicitly "
"allow it.".format(spec.label))
# For liquidReactor, checks whether the solvent is listed as one of the initial species.
if self.solvent:
solvent_structure_list = self.database.solvation.get_solvent_structure(self.solvent)
for spc in solvent_structure_list:
self.database.solvation.check_solvent_in_initial_species(self, spc)
# Check to see if user has input Singlet O2 into their input file or libraries
# This constraint is special in that we only want to check it once in the input instead of every time a species is made
if 'allowSingletO2' in self.species_constraints and self.species_constraints['allowSingletO2']:
pass
else:
# Here we get a list of all species that from the user input
all_inputted_species = [spec for spec in self.initial_species]
# Because no iterations have taken place, the only things in the core are from seed mechanisms
all_inputted_species.extend(self.reaction_model.core.species)
# Because no iterations have taken place, the only things in the edge are from reaction libraries
all_inputted_species.extend(self.reaction_model.edge.species)
O2Singlet = Molecule().from_smiles('O=O')
for spec in all_inputted_species:
if spec.is_isomorphic(O2Singlet):
raise ForbiddenStructureException("Species constraints forbids input species {0} RMG expects the "
"triplet form of oxygen for correct usage in reaction families. "
"Please change your input to SMILES='[O][O]' If you actually "
"want to use the singlet state, set the allowSingletO2=True "
"inside of the Species Constraints block in your input file."
.format(spec.label))
for spec in self.initial_species:
submit(spec, self.solvent)
# Add nonreactive species (e.g. bath gases) to core first
# This is necessary so that the PDep algorithm can identify the bath gas
for spec in self.initial_species:
if not spec.reactive:
self.reaction_model.enlarge(spec)
for spec in self.initial_species:
if spec.reactive:
self.reaction_model.enlarge(spec)
# chatelak: store constant SPC indices in the reactor attributes if any constant SPC provided in the input file
# advantages to write it here: this is run only once (as species indexes does not change over the generation)
if self.solvent is not None:
for index, reaction_system in enumerate(self.reaction_systems):
if not isinstance(reaction_system, Reactor) and reaction_system.const_spc_names is not None: # if no constant species provided do nothing
reaction_system.get_const_spc_indices(
self.reaction_model.core.species) # call the function to identify indices in the solver
self.initialize_reaction_threshold_and_react_flags()
if self.filter_reactions and self.init_react_tuples:
self.react_init_tuples()
self.reaction_model.initialize_index_species_dict()
self.initialize_seed_mech()
def register_listeners(self):
"""
Attaches listener classes depending on the options
found in the RMG input file.
"""
self.attach(ChemkinWriter(self.output_directory))
self.attach(RMSWriter(self.output_directory))
if self.generate_output_html:
self.attach(OutputHTMLWriter(self.output_directory))
if self.quantum_mechanics:
self.attach(QMDatabaseWriter())
self.attach(ExecutionStatsWriter(self.output_directory))
if self.save_simulation_profiles:
for index, reaction_system in enumerate(self.reaction_systems):
if isinstance(reaction_system, Reactor):
typ = type(reaction_system)
raise InputError(f"save_simulation_profiles=True not compatible with reactor of type {typ}")
reaction_system.attach(SimulationProfileWriter(
self.output_directory, index, self.reaction_model.core.species))
reaction_system.attach(SimulationProfilePlotter(
self.output_directory, index, self.reaction_model.core.species))
def execute(self, initialize=True, **kwargs):
"""
Execute an RMG job using the command-line arguments `args` as returned
by the :mod:`argparse` package.
``initialize`` is a ``bool`` type flag used to determine whether to call self.initialize()
"""
if initialize:
self.initialize(**kwargs)
# register listeners
self.register_listeners()
self.done = False
# determine min and max values for T and P (don't determine P values for liquid reactors)
self.Tmin = min([x.Trange[0].value_si if x.Trange else x.T.value_si for x in self.reaction_systems])
self.Tmax = max([x.Trange[1].value_si if x.Trange else x.T.value_si for x in self.reaction_systems])
try:
self.Pmin = min([x.Prange[0].value_si if hasattr(x, 'Prange') and x.Prange else x.P.value_si for x in self.reaction_systems])
self.Pmax = max([x.Prange[1].value_si if hasattr(x, 'Prange') and x.Prange else x.P.value_si for x in self.reaction_systems])
except AttributeError:
pass
self.rmg_memories = []
logging.info('Initialization complete. Starting model generation.\n')
# Initiate first reaction discovery step after adding all core species
for index, reaction_system in enumerate(self.reaction_systems):
# Initialize memory object to track conditions for ranged reactors
self.rmg_memories.append(RMG_Memory(reaction_system, self.balance_species))
self.rmg_memories[index].generate_cond()
log_conditions(self.rmg_memories, index)
# Update react flags
if self.filter_reactions:
# Run the reaction system to update threshold and react flags
reaction_system.initialize_model(
core_species=self.reaction_model.core.species,
core_reactions=self.reaction_model.core.reactions,
edge_species=[],
edge_reactions=[],
pdep_networks=self.reaction_model.network_list,
atol=self.simulator_settings_list[0].atol,
rtol=self.simulator_settings_list[0].rtol,
filter_reactions=True,
conditions=self.rmg_memories[index].get_cond(),
)
self.update_reaction_threshold_and_react_flags(
rxn_sys_unimol_threshold=reaction_system.unimolecular_threshold,
rxn_sys_bimol_threshold=reaction_system.bimolecular_threshold,
rxn_sys_trimol_threshold=reaction_system.trimolecular_threshold,
)
logging.info('Generating initial reactions for reaction system {0}...'.format(index + 1))
else:
# If we're not filtering reactions, then we only need to react
# the first reaction system since they share the same core
if index > 0:
continue
logging.info('Generating initial reactions...')
# React core species to enlarge edge
self.reaction_model.enlarge(react_edge=True,
unimolecular_react=self.unimolecular_react,
bimolecular_react=self.bimolecular_react,
trimolecular_react=self.trimolecular_react)
if not np.isinf(self.model_settings_list[0].thermo_tol_keep_spc_in_edge):
self.reaction_model.set_thermodynamic_filtering_parameters(
self.Tmax,
thermo_tol_keep_spc_in_edge=self.model_settings_list[0].thermo_tol_keep_spc_in_edge,
min_core_size_for_prune=self.model_settings_list[0].min_core_size_for_prune,
maximum_edge_species=self.model_settings_list[0].maximum_edge_species,
reaction_systems=self.reaction_systems
)
if not np.isinf(self.model_settings_list[0].thermo_tol_keep_spc_in_edge):
self.reaction_model.thermo_filter_down(maximum_edge_species=self.model_settings_list[0].maximum_edge_species)
logging.info('Completed initial enlarge edge step.\n')
self.save_everything()
if self.generate_seed_each_iteration:
self.make_seed_mech()
max_num_spcs_hit = False # default
for q, model_settings in enumerate(self.model_settings_list):
if len(self.simulator_settings_list) > 1:
simulator_settings = self.simulator_settings_list[q]
else: # if they only provide one input for simulator use that everytime
simulator_settings = self.simulator_settings_list[0]
self.filter_reactions = model_settings.filter_reactions
logging.info('Beginning model generation stage {0}...\n'.format(q + 1))
self.done = False
# Main RMG loop
while not self.done:
# iteration number starts at 0. Increment it before entering make_seed_mech
self.reaction_model.iteration_num += 1
self.done = True
if self.generate_seed_each_iteration:
self.make_seed_mech()
all_terminated = True
num_core_species = len(self.reaction_model.core.species)
prunable_species = self.reaction_model.edge.species[:]
prunable_networks = self.reaction_model.network_list[:]
for index, reaction_system in enumerate(self.reaction_systems):
reaction_system.prunable_species = prunable_species # these lines reset pruning for a new cycle
reaction_system.prunable_networks = prunable_networks
reaction_system.reset_max_edge_species_rate_ratios()
for p in range(reaction_system.n_sims):
reactor_done = True
objects_to_enlarge = []
conditions = self.rmg_memories[index].get_cond()
if conditions and self.solvent:
T = conditions['T']
# Set solvent viscosity
solvent_data = self.database.solvation.get_solvent_data(self.solvent)
reaction_system.viscosity = solvent_data.get_solvent_viscosity(T)
self.reaction_system = reaction_system
# Conduct simulation
logging.info('Conducting simulation of reaction system %s...' % (index + 1))
prune = True
self.reaction_model.adjust_surface()
if num_core_species < model_settings.min_core_size_for_prune:
# Turn pruning off if we haven't reached minimum core size.
prune = False
try:
if isinstance(reaction_system, Reactor):
terminated,resurrected,obj,unimolecular_threshold,bimolecular_threshold,trimolecular_threshold,max_edge_species_rate_ratios,t,x = reaction_system.simulate(model_settings=model_settings,
simulator_settings=simulator_settings,
conditions=self.rmg_memories[index].get_cond()
)
reaction_system.unimolecular_threshold = unimolecular_threshold
reaction_system.bimolecular_threshold = bimolecular_threshold
reaction_system.trimolecular_threshold = trimolecular_threshold
if hasattr(reaction_system,"max_edge_species_rate_ratios"):
max_edge_species_rate_ratios_temp = np.zeros(len(max_edge_species_rate_ratios))
for i in range(len(max_edge_species_rate_ratios)):
if i < len(reaction_system.max_edge_species_rate_ratios):
max_edge_species_rate_ratios_temp[i] = max(reaction_system.max_edge_species_rate_ratios[i],max_edge_species_rate_ratios[i])
else:
max_edge_species_rate_ratios_temp[i] = max_edge_species_rate_ratios[i]
reaction_system.max_edge_species_rate_ratios = max_edge_species_rate_ratios_temp
else:
reaction_system.max_edge_species_rate_ratios = max_edge_species_rate_ratios
new_surface_species = []
new_surface_reactions = []
obj_temp = []
for item in obj:
if hasattr(item,"name"):
obj_temp.append(self.reaction_model.edge.phase_system.species_dict[item.name])
else: #Reaction
for val in item.reactants:
obj_temp.append(self.reaction_model.edge.phase_system.species_dict[val.name])
for val in item.products:
obj_temp.append(self.reaction_model.edge.phase_system.species_dict[val.name])
obj = obj_temp
else:
terminated, resurrected, obj, new_surface_species, new_surface_reactions, t, x = reaction_system.simulate(
core_species=self.reaction_model.core.species,
core_reactions=self.reaction_model.core.reactions,
edge_species=self.reaction_model.edge.species,
edge_reactions=self.reaction_model.edge.reactions,
surface_species=self.reaction_model.surface.species,
surface_reactions=self.reaction_model.surface.reactions,
pdep_networks=self.reaction_model.network_list,
prune=prune,
model_settings=model_settings,
simulator_settings=simulator_settings,
conditions=self.rmg_memories[index].get_cond()
)
except:
logging.error("Model core reactions:")
if len(self.reaction_model.core.reactions) > 5:
logging.error("Too many to print in detail")
else:
from arkane.output import prettify
logging.error(prettify(repr(self.reaction_model.core.reactions)))
if not self.generate_seed_each_iteration: # Then we haven't saved the seed mechanism yet
self.make_seed_mech() # Just in case the user wants to restart from this
raise
self.rmg_memories[index].add_t_conv_N(t, x, len(obj))
self.rmg_memories[index].generate_cond()
log_conditions(self.rmg_memories, index)
reactor_done = self.reaction_model.add_new_surface_objects(obj, new_surface_species,
new_surface_reactions, reaction_system)
all_terminated = all_terminated and terminated
logging.info('')
# If simulation is invalid, note which species should be added to
# the core
if obj != [] and not (obj is None):
objects_to_enlarge = self.process_to_species_networks(obj)
reactor_done = False
# Enlarge objects identified by the simulation for enlarging
# These should be Species or Network objects
logging.info('')
objects_to_enlarge = list(set(objects_to_enlarge))
# Add objects to enlarge to the core first
for objectToEnlarge in objects_to_enlarge:
self.reaction_model.enlarge(objectToEnlarge)
if model_settings.filter_reactions:
# Run a raw simulation to get updated reaction system threshold values
# Run with the same conditions as with pruning off
temp_model_settings = deepcopy(model_settings)
temp_model_settings.tol_keep_in_edge = 0
if not resurrected:
try:
if isinstance(reaction_system, Reactor):
terminated,obj,unimolecular_threshold,bimolecular_threshold,trimolecular_threshold,max_edge_species_rate_ratios,t,x = reaction_system.simulate(model_settings=model_settings,
simulator_settings=simulator_settings,
conditions=self.rmg_memories[index].get_cond()
)
reaction_system.unimolecular_threshold = unimolecular_threshold
reaction_system.bimolecular_threshold = bimolecular_threshold
reaction_system.trimolecular_threshold = trimolecular_threshold
if hasattr(reaction_system,"max_edge_species_rate_ratios"):
max_edge_species_rate_ratios_temp = np.zeros(len(max_edge_species_rate_ratios))
for i in range(len(max_edge_species_rate_ratios)):
if i < len(reaction_system.max_edge_species_rate_ratios):
max_edge_species_rate_ratios_temp[i] = max(reaction_system.max_edge_species_rate_ratios[i],max_edge_species_rate_ratios[i])
else:
max_edge_species_rate_ratios_temp[i] = max_edge_species_rate_ratios[i]
reaction_system.max_edge_species_rate_ratios = max_edge_species_rate_ratios_temp
else:
reaction_system.max_edge_species_rate_ratios = max_edge_species_rate_ratios
new_surface_species = []
new_surface_reactions = []
resurrected = False
obj_temp = []
for item in obj:
if hasattr(item,"name"):
obj_temp.append(self.reaction_model.edge.phase_system.species_dict[item.name])
else: #Reaction
for val in item.reactants:
obj_temp.append(self.reaction_model.edge.phase_system.species_dict[val.name])
for val in item.products:
obj_temp.append(self.reaction_model.edge.phase_system.species_dict[val.name])
obj = obj_temp
else:
reaction_system.simulate(
core_species=self.reaction_model.core.species,
core_reactions=self.reaction_model.core.reactions,
edge_species=[],
edge_reactions=[],
surface_species=self.reaction_model.surface.species,
surface_reactions=self.reaction_model.surface.reactions,
pdep_networks=self.reaction_model.network_list,
model_settings=temp_model_settings,
simulator_settings=simulator_settings,
conditions=self.rmg_memories[index].get_cond()
)
except:
self.update_reaction_threshold_and_react_flags(
rxn_sys_unimol_threshold=reaction_system.unimolecular_threshold,
rxn_sys_bimol_threshold=reaction_system.bimolecular_threshold,
rxn_sys_trimol_threshold=reaction_system.trimolecular_threshold,
skip_update=True)
logging.warning('Reaction thresholds/flags for Reaction System {0} was not updated '
'due to simulation failure'.format(index + 1))
else:
self.update_reaction_threshold_and_react_flags(
rxn_sys_unimol_threshold=reaction_system.unimolecular_threshold,
rxn_sys_bimol_threshold=reaction_system.bimolecular_threshold,
rxn_sys_trimol_threshold=reaction_system.trimolecular_threshold
)
else:
self.update_reaction_threshold_and_react_flags(
rxn_sys_unimol_threshold=reaction_system.unimolecular_threshold,
rxn_sys_bimol_threshold=reaction_system.bimolecular_threshold,
rxn_sys_trimol_threshold=reaction_system.trimolecular_threshold,
skip_update=True
)
logging.warning('Reaction thresholds/flags for Reaction System {0} was not updated due '
'to resurrection'.format(index + 1))
logging.info('')
else:
self.update_reaction_threshold_and_react_flags()
if not np.isinf(model_settings.thermo_tol_keep_spc_in_edge):
self.reaction_model.set_thermodynamic_filtering_parameters(
self.Tmax,
thermo_tol_keep_spc_in_edge=model_settings.thermo_tol_keep_spc_in_edge,
min_core_size_for_prune=model_settings.min_core_size_for_prune,
maximum_edge_species=model_settings.maximum_edge_species,
reaction_systems=self.reaction_systems