forked from ReactionMechanismGenerator/RMG-Py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchemkin.pyx
2383 lines (2110 loc) · 106 KB
/
chemkin.pyx
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
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# #
# Copyright (c) 2002-2020 Prof. William H. Green ([email protected]), #
# Prof. Richard H. West ([email protected]) and the RMG Team ([email protected]) #
# #
# 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 functions for writing of Chemkin input files.
"""
import logging
import math
import os.path
import re
import shutil
import textwrap
import warnings
import numpy as np
import rmgpy.constants as constants
import rmgpy.kinetics as _kinetics
from rmgpy.data.base import Entry
from rmgpy.data.kinetics.family import TemplateReaction
from rmgpy.data.kinetics.library import LibraryReaction
from rmgpy.exceptions import ChemkinError
from rmgpy.molecule.element import get_element
from rmgpy.molecule.util import get_element_count
from rmgpy.quantity import Quantity
from rmgpy.reaction import Reaction
from rmgpy.rmg.pdep import PDepNetwork, PDepReaction
from rmgpy.species import Species
from rmgpy.thermo import NASAPolynomial, NASA
from rmgpy.transport import TransportData
from rmgpy.util import make_output_subdirectory
_chemkin_reaction_count = None
################################################################################
def fortran_float(string):
"""
Parse a Fortran-ish string into a float, like "1.00D 03" or "1.00d+03"
"""
return float(string.replace("e", "E").replace("d", "D").replace("D", "E").replace("E ", "E+"))
def read_thermo_entry(entry, Tmin=0, Tint=0, Tmax=0):
"""
Read a thermodynamics `entry` for one species in a Chemkin file. Returns
the label of the species and the thermodynamics model as a :class:`NASA`
object.
Format specification at http://www2.galcit.caltech.edu/EDL/public/formats/chemkin.html
"""
lines = entry.splitlines()
species = str(lines[0][0:18].split()[0].strip())
comment = lines[0][len(species):24].strip()
formula = {}
for i in [24, 29, 34, 39, 73]:
element, count = lines[0][i:i + 2].strip(), lines[0][i + 2:i + 5].strip()
if element:
try:
count = int(count)
except ValueError:
# Chemkin allows float values for the number of atoms, so try this next.
try:
count = int(float(count))
except ValueError:
logging.info("Trouble reading line '{0}' element segment "
"'{1}'".format(lines[0].strip(),lines[0][i:i+5]))
if count == '' and re.match('\.?0*', element):
if i == 74:
logging.info("Assuming it's spillover from Tint, and ignoring.")
else:
logging.warning("Assuming it's not meant to be there, although it would be "
"good to fix the chemkin file.")
count = 0
else:
raise
if count != 0: # Some people put garbage elements in, with zero count. Ignore these. Allow negative counts though (eg. negative one electron)
formula[element] = count
# Parsing for extended elemental composition syntax, adapted from Cantera ck2cti.py
if lines[0].rstrip().endswith('&'):
complines = []
for i in range(len(lines)-1):
if lines[i].rstrip().endswith('&'):
complines.append(lines[i+1])
else:
break
lines = [lines[0]] + lines[i+1:]
elements = ' '.join(line.rstrip('&\n') for line in complines).split()
formula = {}
for i in range(0, len(elements), 2):
formula[elements[i].capitalize()] = int(elements[i+1])
phase = lines[0][44]
if phase.upper() != 'G':
logging.warning("Was expecting gas phase thermo data for {0}. Skipping thermo data.".format(species))
return species, None, None
# Extract the NASA polynomial coefficients
# Remember that the high-T polynomial comes first!
try:
try:
Tmin = float(lines[0][45:55].strip())
except ValueError:
pass
try:
Tmax = float(lines[0][55:65].strip())
except ValueError:
pass
try:
Tint = float(lines[0][65:73].strip())
except ValueError:
pass
a0_high = fortran_float(lines[1][0:15].strip())
a1_high = fortran_float(lines[1][15:30].strip())
a2_high = fortran_float(lines[1][30:45].strip())
a3_high = fortran_float(lines[1][45:60].strip())
a4_high = fortran_float(lines[1][60:75].strip())
a5_high = fortran_float(lines[2][0:15].strip())
a6_high = fortran_float(lines[2][15:30].strip())
a0_low = fortran_float(lines[2][30:45].strip())
a1_low = fortran_float(lines[2][45:60].strip())
a2_low = fortran_float(lines[2][60:75].strip())
a3_low = fortran_float(lines[3][0:15].strip())
a4_low = fortran_float(lines[3][15:30].strip())
a5_low = fortran_float(lines[3][30:45].strip())
a6_low = fortran_float(lines[3][45:60].strip())
except (IndexError, ValueError) as e:
logging.warning('Error while reading thermo entry for species {0}'.format(species))
logging.warning(str(e))
return species, None, None
# Construct and return the thermodynamics model
thermo = NASA(
polynomials=[
NASAPolynomial(Tmin=(Tmin, "K"), Tmax=(Tint, "K"),
coeffs=[a0_low, a1_low, a2_low, a3_low, a4_low, a5_low, a6_low]),
NASAPolynomial(Tmin=(Tint, "K"), Tmax=(Tmax, "K"),
coeffs=[a0_high, a1_high, a2_high, a3_high, a4_high, a5_high, a6_high])
],
Tmin=(Tmin, "K"),
Tmax=(Tmax, "K"),
)
if comment:
thermo.comment = comment.strip()
return species, thermo, formula
################################################################################
def read_kinetics_entry(entry, species_dict, Aunits, Eunits):
"""
Read a kinetics `entry` for a single reaction as loaded from a Chemkin
file. The associated mapping of labels to species `species_dict` should also
be provided. Returns a :class:`Reaction` object with the reaction and its
associated kinetics.
"""
Afactor = {
'cm^3/(mol*s)': 1.0e6,
'cm^3/(molecule*s)': 1.0e6,
'm^3/(mol*s)': 1.0,
'm^3/(molecule*s)': 1.0,
}[Aunits[2]]
lines = entry.strip().splitlines()
# The first line contains the reaction equation and a set of
# modified Arrhenius parameters
reaction, third_body, kinetics, k_units, k_low_units = _read_kinetics_reaction(
line=lines[0], species_dict=species_dict, Aunits=Aunits, Eunits=Eunits)
if len(lines) == 1 and not third_body:
# If there's only one line then we know to use the high-P limit kinetics as-is
reaction.kinetics = kinetics['arrhenius high']
else:
# There's more kinetics information to be read
kinetics.update({
'chebyshev coefficients': [],
'efficiencies': {},
})
# Note that the subsequent lines could be in any order
for line in lines[1:]:
kinetics = _read_kinetics_line(
line=line, reaction=reaction, species_dict=species_dict, Eunits=Eunits,
kunits=k_units, klow_units=k_low_units,
kinetics=kinetics)
# Decide which kinetics to keep and store them on the reaction object
# Only one of these should be true at a time!
if 'chebyshev' in kinetics:
chebyshev = kinetics['chebyshev']
if chebyshev.Tmin is None or chebyshev.Tmax is None:
raise ChemkinError('Missing TCHEB line for reaction {0}'.format(reaction))
if chebyshev.Pmin is None or chebyshev.Pmax is None:
raise ChemkinError('Missing PCHEB line for reaction {0}'.format(reaction))
index = 0
for t in range(chebyshev.degreeT):
for p in range(chebyshev.degreeP):
chebyshev.coeffs.value_si[t, p] = kinetics[
'chebyshev coefficients'][index]
index += 1
# Don't forget to convert the Chebyshev coefficients to SI units!
# This assumes that s^-1, cm^3/mol*s, etc. are compulsory
chebyshev.coeffs.value_si[0, 0] -= (len(reaction.reactants) - 1) * math.log10(Afactor)
reaction.kinetics = chebyshev
elif 'pressure-dependent arrhenius' in kinetics:
pdep_arrhenius = kinetics['pressure-dependent arrhenius']
# Check for duplicates and combine them to MultiArrhenius objects
duplicates_to_remove = []
duplicates_to_add = []
for index1 in range(len(pdep_arrhenius)):
reaction1 = pdep_arrhenius[index1]
p1, kinetics1 = reaction1
if reaction1 in duplicates_to_remove:
continue
for index2 in range(index1 + 1, len(pdep_arrhenius)):
reaction2 = pdep_arrhenius[index2]
p2, kinetics2 = reaction2
if p1 == p2:
if reaction1 not in duplicates_to_remove:
new_kinetics = _kinetics.MultiArrhenius()
duplicates_to_add.append([p1, new_kinetics])
new_kinetics.arrhenius = [kinetics1]
duplicates_to_remove.append(reaction1)
new_kinetics.arrhenius.append(kinetics2)
duplicates_to_remove.append(reaction2)
for item in duplicates_to_remove:
pdep_arrhenius.remove(item)
pdep_arrhenius.extend(duplicates_to_add)
pdep_arrhenius = sorted(pdep_arrhenius, key=lambda reaction: reaction[0]) # sort by ascending pressures
reaction.kinetics = _kinetics.PDepArrhenius(
pressures=([P for P, arrh in pdep_arrhenius], "atm"),
arrhenius=[arrh for P, arrh in pdep_arrhenius],
)
elif 'troe' in kinetics:
troe = kinetics['troe']
troe.arrheniusHigh = kinetics['arrhenius high']
troe.arrheniusLow = kinetics['arrhenius low']
troe.efficiencies = kinetics['efficiencies']
reaction.kinetics = troe
elif third_body:
reaction.kinetics = _kinetics.ThirdBody(
arrheniusLow=kinetics['arrhenius low'])
reaction.kinetics.efficiencies = kinetics['efficiencies']
elif 'arrhenius low' in kinetics:
reaction.kinetics = _kinetics.Lindemann(
arrheniusHigh=kinetics['arrhenius high'],
arrheniusLow=kinetics['arrhenius low'])
reaction.kinetics.efficiencies = kinetics['efficiencies']
elif 'explicit reverse' in kinetics or reaction.duplicate:
# it's a normal high-P reaction - the extra lines were only either REV (explicit reverse) or DUP (duplicate)
reaction.kinetics = kinetics['arrhenius high']
elif 'sticking coefficient' in kinetics:
reaction.kinetics = kinetics['sticking coefficient']
else:
raise ChemkinError(
'Unable to understand all additional information lines for reaction {0}.'.format(entry))
# These things may *also* be true
if 'sri' in kinetics:
reaction.kinetics.comment += "Warning: SRI parameters from chemkin file ignored on import. "
if 'explicit reverse' in kinetics:
reaction.kinetics.comment += \
"Chemkin file stated explicit reverse rate: {0}".format(kinetics['explicit reverse'])
return reaction
def _read_kinetics_reaction(line, species_dict, Aunits, Eunits):
"""
Parse the first line of of a Chemkin reaction entry.
"""
tokens = line.split()
rmg = True
try:
float(tokens[-6])
except (ValueError, IndexError):
rmg = False
A_uncertainty_type = '+|-'
if rmg:
A = float(tokens[-6])
n = float(tokens[-5])
Ea = float(tokens[-4])
try:
dA = float(tokens[-3])
except ValueError:
A_uncertainty_type = '*|/'
dA = float(tokens[-3][1:])
dn = float(tokens[-2])
dEa = float(tokens[-1])
reaction = ''.join(tokens[:-6])
else:
A = fortran_float(tokens[-3])
n = fortran_float(tokens[-2])
Ea = fortran_float(tokens[-1])
dA = 0.0
dn = 0.0
dEa = 0.0
reaction = ''.join(tokens[:-3])
third_body = False
# Split the reaction equation into reactants and products
reversible = True
reactants, products = reaction.split('=')
if '<=>' in reaction:
reactants = reactants[:-1]
products = products[1:]
elif '=>' in reaction:
products = products[1:]
reversible = False
specific_collider = None
# search for a third body collider, e.g., '(+M)', '(+m)', or a specific species like '(+N2)',
# matching `(+anything_other_than_ending_parenthesis)`:
collider = re.search(r'\(\+[^)]+\)', reactants)
if collider is not None:
collider = collider.group(0) # save string value rather than the object
if collider != re.search(r'\(\+[^)]+\)', products).group(0):
raise ChemkinError(
'Third body colliders in reactants and products of reaction {0} are not identical!'.format(reaction))
extra_parenthesis = collider.count('(') - 1
for i in range(extra_parenthesis):
# allow for species like N2(5) or CH2(T)(15) to be read as specific colliders,
# although currently not implemented in Chemkin. See RMG-Py #1070
collider += ')'
reactants = reactants.replace(collider, '')
products = products.replace(collider, '')
if collider.upper().strip() != "(+M)": # the collider is a specific species, not (+M) or (+m)
if collider.strip()[2:-1] not in species_dict: # stripping spaces, '(+' and ')'
raise ChemkinError(
'Unexpected third body collider "{0}" in reaction {1}.'.format(collider.strip()[2:-1], reaction))
specific_collider = species_dict[collider.strip()[2:-1]]
# Create a new Reaction object for this reaction
reaction = Reaction(reactants=[], products=[], specific_collider=specific_collider, reversible=reversible)
# Convert the reactants and products to Species objects using the species_dict
for reactant in reactants.split('+'):
reactant = reactant.strip()
stoichiometry = 1
if reactant[0].isdigit():
# This allows for reactions to be of the form 2A=B+C instead of A+A=B+C
# The implementation below assumes an integer between 0 and 9, inclusive
stoichiometry = int(reactant[0])
reactant = reactant[1:]
if reactant.upper() == 'M':
# this identifies reactions like 'H+H+M=H2+M' as opposed to 'H+H(+M)=H2(+M)' as identified above
third_body = True
elif reactant not in species_dict:
raise ChemkinError('Unexpected reactant "{0}" in reaction {1}.'.format(reactant, reaction))
else:
reactant_species = species_dict[reactant]
if not reactant_species.reactive:
reactant_species.reactive = True
for i in range(stoichiometry):
reaction.reactants.append(reactant_species)
for product in products.split('+'):
product = product.strip()
stoichiometry = 1
if product[0].isdigit():
# This allows for reactions to be of the form A+B=2C instead of A+B=C+C
# The implementation below assumes an integer between 0 and 9, inclusive
stoichiometry = int(product[0])
product = product[1:]
if product.upper() == 'M':
pass
elif product not in species_dict:
if re.match('[0-9.]+', product):
logging.warning("Looks like reaction {0!r} has fractional stoichiometry, which RMG cannot handle. "
"Ignoring".format(line))
raise ChemkinError('Skip reaction!')
raise ChemkinError(
'Unexpected product "{0}" in reaction {1} from line {2}.'.format(product, reaction, line))
else:
product_species = species_dict[product]
if not product_species.reactive:
product_species.reactive = True
for i in range(stoichiometry):
reaction.products.append(product_species)
# Determine the appropriate units for k(T) and k(T,P) based on the number of reactants
# This assumes elementary kinetics for all reactions
try:
n_react = len(reaction.reactants) + (1 if third_body else 0)
k_units = Aunits[n_react]
k_low_units = Aunits[n_react + 1]
except IndexError:
raise ChemkinError('Invalid number of reactant species for reaction {0}.'.format(reaction))
key = 'arrhenius low' if third_body else 'arrhenius high'
kinetics = {
key: _kinetics.Arrhenius(
A=(A, k_units, A_uncertainty_type, dA),
n=(n, '', '+|-', dn),
Ea=(Ea, Eunits, '+|-', dEa),
T0=(1, "K"),
),
}
return reaction, third_body, kinetics, k_units, k_low_units
def _read_kinetics_line(line, reaction, species_dict, Eunits, kunits, klow_units, kinetics):
"""
Parse the subsequent lines of of a Chemkin reaction entry.
"""
case_preserved_tokens = line.split('/')
line = line.upper()
tokens = line.split('/')
if 'DUP' in line:
# Duplicate reaction
reaction.duplicate = True
elif 'LOW' in line:
# Low-pressure-limit Arrhenius parameters
tokens = tokens[1].split()
kinetics['arrhenius low'] = _kinetics.Arrhenius(
A=(float(tokens[0].strip()), klow_units),
n=float(tokens[1].strip()),
Ea=(float(tokens[2].strip()), Eunits),
T0=(1, "K"),
)
elif 'HIGH' in line:
# What we thought was high, was in fact low-pressure
kinetics['arrhenius low'] = kinetics['arrhenius high']
kinetics['arrhenius low'].A = (
kinetics['arrhenius low'].A.value, klow_units)
# High-pressure-limit Arrhenius parameters
tokens = tokens[1].split()
kinetics['arrhenius high'] = _kinetics.Arrhenius(
A=(float(tokens[0].strip()), kunits),
n=float(tokens[1].strip()),
Ea=(float(tokens[2].strip()), Eunits),
T0=(1, "K"),
)
elif 'TROE' in line:
# Troe falloff parameters
tokens = tokens[1].split()
alpha = float(tokens[0].strip())
T3 = float(tokens[1].strip())
T1 = float(tokens[2].strip())
try:
T2 = float(tokens[3].strip())
except (IndexError, ValueError):
T2 = None
kinetics['troe'] = _kinetics.Troe(
alpha=alpha,
T3=(T3, "K"),
T1=(T1, "K"),
T2=(T2, "K") if T2 is not None else None,
)
elif line.strip().startswith('SRI'):
kinetics['sri'] = True
"""To define an SRI pressure-dependent reaction, in addition to the LOW or HIGH parameters, the
keyword SRI followed by three or five parameters must be included in the following order: a, b,
c, d, and e [Eq. (74)]. The fourth and fifth parameters are options. If only the first three are
stated, then by default d = 1 and e = 0.
"""
# see eg. http://www.dipic.unipd.it/faculty/canu/files/Comb/Docs/chemkinCK.pdf
elif 'CHEB' in line:
# Chebyshev parameters
chebyshev = kinetics.get(
'chebyshev', _kinetics.Chebyshev(kunits=kunits))
kinetics['chebyshev'] = chebyshev
tokens = [t.strip() for t in tokens]
if 'TCHEB' in line:
index = tokens.index('TCHEB')
tokens2 = tokens[index + 1].split()
chebyshev.Tmin = Quantity(float(tokens2[0].strip()), "K")
chebyshev.Tmax = Quantity(float(tokens2[1].strip()), "K")
if 'PCHEB' in line:
index = tokens.index('PCHEB')
tokens2 = tokens[index + 1].split()
chebyshev.Pmin = Quantity(float(tokens2[0].strip()), "atm")
chebyshev.Pmax = Quantity(float(tokens2[1].strip()), "atm")
if 'TCHEB' in line or 'PCHEB' in line:
pass
elif chebyshev.degreeT == 0 or chebyshev.degreeP == 0:
tokens2 = tokens[1].split()
chebyshev.degreeT = int(float(tokens2[0].strip()))
chebyshev.degreeP = int(float(tokens2[1].strip()))
chebyshev.coeffs = np.zeros((chebyshev.degreeT, chebyshev.degreeP), np.float64)
else:
tokens2 = tokens[1].split()
kinetics['chebyshev coefficients'].extend(
[float(t.strip()) for t in tokens2])
elif 'PLOG' in line:
pdep_arrhenius = kinetics.get('pressure-dependent arrhenius', [])
kinetics['pressure-dependent arrhenius'] = pdep_arrhenius
tokens = tokens[1].split()
pdep_arrhenius.append([float(tokens[0].strip()),
_kinetics.Arrhenius(
A=(float(tokens[1].strip()), kunits),
n=float(tokens[2].strip()),
Ea=(float(tokens[3].strip()), Eunits),
T0=(1, "K"),
)])
elif tokens[0].startswith('REV'):
reverse_A = float(tokens[1].split()[0])
kinetics['explicit reverse'] = line.strip()
if reverse_A == 0:
logging.info("Reverse rate is 0 so making irreversible for reaction {0}".format(reaction))
reaction.reversible = False
else:
logging.info("Ignoring explicit reverse rate for reaction {0}".format(reaction))
elif line.strip() == 'STICK':
# Convert what we thought was Arrhenius into StickingCoefficient
k = kinetics['arrhenius high']
kinetics['sticking coefficient'] = _kinetics.StickingCoefficient(
A=k.A.value,
n=k.n,
Ea=k.Ea,
T0=k.T0,
)
del kinetics['arrhenius high']
else:
# Assume a list of collider efficiencies
try:
for collider, efficiency in zip(case_preserved_tokens[0::2], case_preserved_tokens[1::2]):
try:
efficiency = float(efficiency.strip())
except ValueError:
raise ChemkinError("{0!r} doesn't look like a collision efficiency for species {1} in "
"line {2!r}".format(efficiency, collider.strip(), line))
if collider.strip() in species_dict:
kinetics['efficiencies'][species_dict[collider.strip()].molecule[0]] = efficiency
else: # try it with capital letters? Not sure whose malformed chemkin files this is needed for.
kinetics['efficiencies'][species_dict[collider.strip().upper()].molecule[0]] = efficiency
except IndexError:
error_msg = 'Could not read collider efficiencies for reaction: {0}.\n'.format(reaction)
error_msg += 'The following line was parsed incorrectly:\n{0}'.format(line)
error_msg += "\n(Case-preserved tokens: {0!r} )".format(case_preserved_tokens)
raise ChemkinError(error_msg)
return kinetics
def _remove_line_breaks(comments):
"""
This method removes any extra line breaks in reaction comments, so they
can be parsed by read_reaction_comments.
"""
comments = comments.replace('\n', ' ')
new_statement_indicators = ['Reaction index', 'Template reaction', 'Library reaction',
'PDep reaction', 'Flux pairs', 'BM rule fitted to',
'Uncertainty in Total Std:',
'Estimated using', 'Exact match found', 'Average of ',
'Euclidian distance', 'Matched node ', 'Matched reaction ',
'Multiplied by reaction path degeneracy ',
'Kinetics were estimated in this direction',
'dGrxn(298 K) = ', 'Both directions are estimates',
'Other direction matched ', 'Both directions matched ',
'This direction matched an entry in ', 'From training reaction',
'This reaction matched rate rule', 'family: ', 'Warning:',
'Chemkin file stated explicit reverse rate:', 'Ea raised from',
'Fitted to', 'Reaction library',
]
for indicator in new_statement_indicators:
comments = comments.replace(' ' + indicator, '\n' + indicator, 1)
return comments
def read_reaction_comments(reaction, comments, read=True):
"""
Parse the `comments` associated with a given `reaction`. If the comments
come from RMG (Py or Java), parse them and extract the useful information.
Return the reaction object based on the information parsed from these
comments. If `read` if False, the reaction is returned as an "Unclassified"
LibraryReaction.
"""
if not read:
# The chemkin file was not generated by either RMG-Py or RMG-Java, thus, there should be no parsing
# of the comments. Instead, return as an unclassified LibraryReaction.
reaction = LibraryReaction(
index=reaction.index,
reactants=reaction.reactants,
products=reaction.products,
specific_collider=reaction.specific_collider,
kinetics=reaction.kinetics,
reversible=reaction.reversible,
duplicate=reaction.duplicate,
library='Unclassified',
)
return reaction
# the comments could have line breaks that will mess up reading
# we will now combine the lines and separate them based on statements
comments = _remove_line_breaks(comments)
lines = comments.strip().splitlines()
for line in lines:
tokens = line.split()
if 'Reaction index:' in line:
# Don't store the reaction indices
pass
elif 'Template reaction:' in line:
label = str(tokens[-1])
reaction = TemplateReaction(
index=reaction.index,
reactants=reaction.reactants,
products=reaction.products,
specific_collider=reaction.specific_collider,
kinetics=reaction.kinetics,
reversible=reaction.reversible,
duplicate=reaction.duplicate,
family=label,
)
elif 'Library reaction:' in line or 'Seed mechanism:' in line:
label = str(tokens[2])
reaction = LibraryReaction(
index=reaction.index,
reactants=reaction.reactants,
products=reaction.products,
specific_collider=reaction.specific_collider,
kinetics=reaction.kinetics,
reversible=reaction.reversible,
duplicate=reaction.duplicate,
library=label,
)
elif 'PDep reaction:' in line:
network_index = int(tokens[-1][1:])
reaction = PDepReaction(
index=reaction.index,
reactants=reaction.reactants,
products=reaction.products,
specific_collider=reaction.specific_collider,
kinetics=reaction.kinetics,
reversible=reaction.reversible,
duplicate=reaction.duplicate,
network=PDepNetwork(index=network_index),
)
elif 'Flux pairs:' in line:
reaction.pairs = []
for reac_str, prod_str in zip(tokens[2::2], tokens[3::2]):
if reac_str[-1] == ',':
reac_str = reac_str[:-1]
for reactant in reaction.reactants:
if reactant.label == reac_str:
break
else:
raise ChemkinError('Unexpected species identifier {0} encountered in flux pairs '
'for reaction {1}.'.format(reac_str, reaction))
if prod_str[-1] == ';':
prod_str = prod_str[:-1]
for product in reaction.products:
if product.label == prod_str:
break
else:
raise ChemkinError('Unexpected species identifier {0} encountered in flux pairs '
'for reaction {1}.'.format(prod_str, reaction))
reaction.pairs.append((reactant, product))
assert len(reaction.pairs) == max(len(reaction.reactants), len(reaction.products))
elif isinstance(reaction, TemplateReaction) and 'rate rule ' in line:
bracketed_rule = tokens[-1]
templates = bracketed_rule[1:-1].split(';')
reaction.template = templates
# still add kinetic comment
reaction.kinetics.comment += line.strip() + "\n"
elif isinstance(reaction, TemplateReaction) and \
'Multiplied by reaction path degeneracy ' in line:
degen = float(tokens[-1])
reaction.degeneracy = degen
# undo the kinetic manipulation caused by setting degneracy
if reaction.kinetics:
reaction.kinetics.change_rate(1. / degen)
# do not add comment because setting degeneracy does so already
reaction.kinetics.comment += "\n"
elif 'BM rule fitted to' in line:
reaction.kinetics.comment += line.strip() + "\n"
elif 'Uncertainty in Total Std:' in line:
reaction.kinetics.comment += line.strip() + "\n"
elif line.strip() != '':
# Any lines which are commented out but don't have any specific flag are simply kinetics comments
reaction.kinetics.comment += line.strip() + "\n"
# Comment parsing from old RMG-Java chemkin files
elif 'PDepNetwork' in line:
network_index = int(tokens[3][1:])
reaction = PDepReaction(
index=reaction.index,
reactants=reaction.reactants,
products=reaction.products,
specific_collider=reaction.specific_collider,
kinetics=reaction.kinetics,
reversible=reaction.reversible,
duplicate=reaction.duplicate,
network=PDepNetwork(index=network_index)
)
reaction.kinetics.comment = line
elif 'ReactionLibrary:' in line or 'Seed Mechanism:' in line:
label = str(tokens[-1])
reaction = LibraryReaction(
index=reaction.index,
reactants=reaction.reactants,
products=reaction.products,
specific_collider=reaction.specific_collider,
kinetics=reaction.kinetics,
reversible=reaction.reversible,
duplicate=reaction.duplicate,
library=label,
)
reaction.kinetics.comment = line
elif 'exact:' in line or 'estimate:' in line:
index1 = line.find('[')
index2 = line.find(']')
template = [s.strip() for s in line[index1:index2].split(',')]
label = str(tokens[0])
reaction = TemplateReaction(
index=reaction.index,
reactants=reaction.reactants,
products=reaction.products,
specific_collider=reaction.specific_collider,
kinetics=reaction.kinetics,
reversible=reaction.reversible,
duplicate=reaction.duplicate,
family=label,
template=[Entry(label=g) for g in template],
)
reaction.kinetics.comment = line
if (not isinstance(reaction, LibraryReaction)
and not isinstance(reaction, TemplateReaction)
and not isinstance(reaction, PDepReaction)):
reaction = LibraryReaction(
index=reaction.index,
reactants=reaction.reactants,
products=reaction.products,
specific_collider=reaction.specific_collider,
kinetics=reaction.kinetics,
reversible=reaction.reversible,
duplicate=reaction.duplicate,
library='Unclassified',
)
# Clean up line endings on comments so that there aren't any blank commented lines
reaction.kinetics.comment = reaction.kinetics.comment.strip()
return reaction
################################################################################
def load_species_dictionary(path):
"""
Load an RMG dictionary - containing species identifiers and the associated
adjacency lists - from the file located at `path` on disk. Returns a dict
mapping the species identifiers to the loaded species. Resonance isomers
for each species are automatically generated.
"""
species_dict = {}
inerts = [Species().from_smiles(inert) for inert in ('[He]', '[Ne]', 'N#N', '[Ar]')]
with open(path, 'r') as f:
adjlist = ''
for line in f:
if line.strip() == '' and adjlist.strip() != '':
# Finish this adjacency list
species = Species().from_adjacency_list(adjlist)
species.generate_resonance_structures()
label = species.label
for inert in inerts:
if inert.is_isomorphic(species):
species.reactive = False
break
species_dict[label] = species
adjlist = ''
else:
if "InChI" in line:
line = line.split()[0] + '\n'
if '//' in line:
index = line.index('//')
line = line[0:index]
adjlist += line
else: #reach end of file
if adjlist.strip() != '':
species = Species().from_adjacency_list(adjlist)
species.generate_resonance_structures()
label = species.label
for inert in inerts:
if inert.is_isomorphic(species):
species.reactive = False
break
species_dict[label] = species
return species_dict
def remove_comment_from_line(line):
"""
Remove a comment from a line of a Chemkin file or species dictionary file.
Returns the line and the comment.
If the comment is encoded with latin-1, it is converted to utf-8.
"""
try:
index1 = line.index('!')
except ValueError:
index1 = len(line)
try:
index2 = line.index('//')
except ValueError:
index2 = len(line)
index = min(index1, index2)
comment = line[index + 1:-1]
if index < len(line):
line = line[0:index] + '\n'
return line, comment
def load_transport_file(path, species_dict):
"""
Load a Chemkin transport properties file located at `path` and store the
properties on the species in `species_dict`.
"""
with open(path, 'r') as f:
for line0 in f:
line, comment = remove_comment_from_line(line0)
line = line.strip()
if line != '':
# This line contains an entry, so parse it
label = line[0:16].strip()
data = line[16:].split()
species = species_dict[label]
species.transport_data = TransportData(
shapeIndex=int(data[0]),
sigma=(float(data[2]), 'angstrom'),
epsilon=(float(data[1]), 'K'),
dipoleMoment=(float(data[3]), 'De'),
polarizability=(float(data[4]), 'angstrom^3'),
rotrelaxcollnum=float(data[5]),
comment=comment.strip(),
)
def load_chemkin_file(path, dictionary_path=None, transport_path=None, read_comments=True, thermo_path=None,
use_chemkin_names=False, check_duplicates=True):
"""
Load a Chemkin input file located at `path` on disk to `path`, returning lists of the species
and reactions in the Chemkin file. The 'thermo_path' point to a separate thermo file, or, if 'None' is
specified, the function will look for the thermo database within the chemkin mechanism file
"""
species_list = []
species_dict = {}
species_aliases = {}
reaction_list = []
# If the dictionary path is given, then read it and generate Molecule objects
# You need to append an additional adjacency list for nonreactive species, such
# as N2, or else the species objects will not store any structures for the final
# HTML output.
if dictionary_path:
species_dict = load_species_dictionary(dictionary_path)
with open(path, 'r') as f:
previous_line = f.tell()
line0 = f.readline()
while line0 != '':
line = remove_comment_from_line(line0)[0]
line = line.strip()
if 'SPECIES' in line.upper():
# Unread the line (we'll re-read it in readReactionBlock())
f.seek(previous_line)
read_species_block(f, species_dict, species_aliases, species_list)
elif 'THERM' in line.upper() and thermo_path is None:
# Skip this if a thermo file is specified
# Unread the line (we'll re-read it in read_thermo_block())
f.seek(previous_line)
read_thermo_block(f, species_dict)
elif 'REACTIONS' in line.upper():
# Reactions section
# Unread the line (we'll re-read it in readReactionBlock())
f.seek(previous_line)
reaction_list = read_reactions_block(f, species_dict, read_comments=read_comments)
previous_line = f.tell()
line0 = f.readline()
# Read in the thermo data from the thermo file
if thermo_path:
with open(thermo_path, 'r') as f:
line0 = f.readline()
while line0 != '':
line = remove_comment_from_line(line0)[0]
line = line.strip()
if 'THERM' in line.upper():
f.seek(-len(line0), 1)
read_thermo_block(f, species_dict)
break
line0 = f.readline()
# Index the reactions now to have identical numbering as in Chemkin
index = 0
for reaction in reaction_list:
index += 1
reaction.index = index
# Process duplicate reactions
if check_duplicates:
_process_duplicate_reactions(reaction_list)
# If the transport path is given, then read it to obtain the transport
# properties
if transport_path:
load_transport_file(transport_path, species_dict)
if not use_chemkin_names:
# Apply species aliases if known
for spec in species_list:
try:
spec.label = species_aliases[spec.label]
except KeyError:
pass
# Attempt to extract index from species label
indexPattern = re.compile(r'\(\d+\)$')
for spec in species_list:
if indexPattern.search(spec.label):
label, sep, index = spec.label[:-1].rpartition('(')
spec.label = label
spec.index = int(index)
reaction_list.sort(key=lambda reaction: reaction.index)
return species_list, reaction_list
cpdef _process_duplicate_reactions(list reaction_list):
"""
Check for marked (and unmarked!) duplicate reactions
Combine marked duplicate reactions into a single reaction using MultiKinetics
Raise exception for unmarked duplicate reactions
"""
cdef list duplicate_reactions_to_remove = []
cdef list duplicate_reactions_to_add = []
cdef int index1, index2
cdef Reaction reaction, reaction1, reaction2
cdef KineticsModel kinetics
for index1 in range(len(reaction_list)):
reaction1 = reaction_list[index1]
if reaction1 in duplicate_reactions_to_remove:
continue
for index2 in range(index1 + 1, len(reaction_list)):