-
Notifications
You must be signed in to change notification settings - Fork 10
/
ctml_writer.py
executable file
·3201 lines (2769 loc) · 104 KB
/
ctml_writer.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 python
##
# @file ctml_writer.py
#
# Cantera .cti input file processor
# @defgroup pygroup Cantera Python Interface
#
# The functions and classes in this module process Cantera .cti input
# files and produce CTML files. It can be imported as a module, or used
# as a script.
#
# script usage:
#
# python ctml_writer.py infile.cti
#
# This will produce CTML file 'infile.xml'
# This file is part of Cantera. See License.txt in the top-level directory or
# at http://www.cantera.org/license.txt for license and copyright information.
from __future__ import print_function
import sys
# Python 2/3 compatibility
try:
basestring
except NameError:
basestring = str
def _printerr(*args):
# All debug and error output should go to stderr
print(*args, file=sys.stderr)
class CTI_Error(Exception):
"""Exception raised if an error is encountered while
parsing the input file.
@ingroup pygroup"""
def __init__(self, msg):
_printerr('\n\n***** Error parsing input file *****\n\n')
_printerr(msg)
_printerr()
indent = ['',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ']
#-----------------------------------------------------
class XMLnode(object):
"""This is a minimal class to allow easy creation of an XML tree
from Python. It can write XML, but cannot read it."""
__slots__ = ('_name', '_value', '_attribs', '_children', '_childmap')
def __init__(self, name="--", value = ""):
"""Create a new node. Usually this only needs to be explicitly
called to create the root element. Method addChild calls this
constructor to create the new child node."""
self._name = name
# convert 'value' to a string if it is not already, and
# strip leading whitespace
if not isinstance(value, str):
self._value = repr(value).lstrip()
else:
self._value = value.lstrip()
self._attribs = {} # dictionary of attributes
self._children = [] # list of child nodes
self._childmap = {} # dictionary of child nodes
def name(self):
"""The tag name of the node."""
return self._name
def nChildren(self):
"""Number of child elements."""
return len(self._children)
def addChild(self, name, value=""):
"""Add a child with tag 'name', and set its value if the value
parameter is supplied."""
# create a new node for the child
c = XMLnode(name = name, value = value)
# add it to the list of children, and to the dictionary
# of children
self._children.append(c)
self._childmap[name] = c
return c
def addComment(self, comment):
"""Add a comment."""
self.addChild(name = '_comment_', value = comment)
def value(self):
"""A string containing the element value."""
return self._value
def child(self, name=""):
"""The child node with specified name."""
return self._childmap[name]
def children(self):
""" An iterator over the child nodes """
for c in self._children:
yield c
def __getitem__(self, key):
"""Get an attribute using the syntax node[key]"""
return self._attribs[key]
def __setitem__(self, key, value):
"""Set a new attribute using the syntax node[key] = value."""
self._attribs[key] = value
def __call__(self):
"""Allows getting the value using the syntax 'node()'"""
return self._value
def write(self, filename):
"""Write out the XML tree to a file."""
s = ['<?xml version="1.0"?>\n']
self._write(s, 0)
s.append('\n')
if isinstance(filename, str):
with open(filename, 'w') as f:
f.write(''.join(s))
else:
filename.write(''.join(s))
def write_comment(self, s, level):
s.append('\n'+indent[level]+'<!--')
value = self._value
if value:
if value[0] != ' ':
value = ' '+value
if value[-1] != ' ':
value += ' '
s.append(value+'-->')
def write_attribs(self, s):
for a in self._attribs:
s.append(' '+a+'="'+self._attribs[a]+'"')
def write_value(self, s, level):
indnt = indent[level]
vv = self._value.lstrip()
ieol = vv.find('\n')
if ieol >= 0:
while True:
ieol = vv.find('\n')
if ieol >= 0:
s.extend(('\n ', indnt, vv[:ieol]))
vv = vv[ieol+1:].lstrip()
else:
s.extend(('\n ',indnt,vv))
break
else:
s.append(self._value)
def _write(self, s, level = 0):
"""Internal method used to write the XML representation of each node."""
if not self.name:
return
# handle comments
if self._name == '_comment_':
self.write_comment(s, level)
return
indnt = indent[level]
# write the opening tag and attributes
s.extend((indnt, '<', self._name))
self.write_attribs(s)
if not self._value and not self._children:
s.append('/>')
else:
s.append('>')
if self._value:
self.write_value(s, level)
for c in self._children:
s.append('\n')
c._write(s, level + 2)
if self._children:
s.extend(('\n', indnt))
s.extend(('</', self._name, '>'))
#--------------------------------------------------
# constants that can be used in .cti files
OneAtm = 1.01325e5
OneBar = 1.0e5
# Conversion from eV to J/kmol (electronCharge * Navrog)
eV = 9.64853364595687e7
# Electron Mass in kg
ElectronMass = 9.10938291e-31
import math, copy
# default units
_ulen = 'm'
_umol = 'kmol'
_umass = 'kg'
_utime = 's'
_ue = 'J/kmol'
_uenergy = 'J'
_upres = 'Pa'
# used to convert reaction pre-exponentials
_length = {'cm':0.01, 'm':1.0, 'mm':0.001}
_moles = {'kmol':1.0, 'mol':0.001, 'molec':1.0/6.02214129e26}
_time = {'s':1.0, 'min':60.0, 'hr':3600.0}
# default std state pressure
_pref = 1.0e5 # 1 bar
_name = 'noname'
# these lists store top-level entries
_elements = []
_species = []
_speciesnames = []
_phases = []
_reactions = []
_interactions = []
_beps = []
_atw = {}
_enames = {}
_valsp = ''
_valrxn = ''
_valexport = ''
_valfmt = ''
# default for Motz & Wise correction
_motz_wise = None
def enable_motz_wise():
global _motz_wise
_motz_wise = True
def disable_motz_wise():
global _motz_wise
_motz_wise = False
def export_species(filename, fmt = 'CSV'):
global _valexport
global _valfmt
_valexport = filename
_valfmt = fmt
def validate(species = 'yes', reactions = 'yes'):
"""
Enable or disable validation of species and reactions.
:param species:
Set to ``'yes'`` (default) or ``'no'``.
:param reactions:
Set to ``'yes'`` (default) or ``'no'``. This controls duplicate reaction checks
and validation of rate expressions for some reaction types.
"""
global _valsp
global _valrxn
_valsp = species
_valrxn = reactions
def isnum(a):
"""True if a is an integer or floating-point number."""
if isinstance(a, (int, float)):
return 1
else:
return 0
def is_local_species(name):
"""true if the species named 'name' is defined in this file"""
if name in _speciesnames:
return 1
return 0
def dataset(nm):
"Set the dataset name. Invoke this to change the name of the XML file."
global _name
_name = nm
def standard_pressure(p0):
"""Set the default standard-state pressure."""
global _pref
_pref = p0
def units(length = '', quantity = '', mass = '', time = '',
act_energy = '', energy = '', pressure = ''):
"""
Set the default units.
:param length:
The default units for length. Default: ``'m'``
:param mass:
The default units for mass. Default: ``'kg'``
:param quantity:
The default units to specify number of molecules. Default: ``'kmol'``
:param time:
The default units for time. Default: ``'s'``
:param energy:
The default units for energies. Default: ``'J'``
:param act_energy:
The default units for activation energies. Default: ``'K'``
:param pressure:
The default units for pressure. Default: ``'Pa'``
"""
global _ulen, _umol, _ue, _utime, _umass, _uenergy, _upres
if length: _ulen = length
if quantity: _umol = quantity
if act_energy: _ue = act_energy
if time: _utime = time
if mass: _umass = mass
if energy: _uenergy = energy
if pressure: _upres = pressure
def ufmt(base, n):
"""return a string representing a unit to a power n."""
if n == 0: return ''
if n == 1: return '-'+base
if n == -1: return '/'+base
if n > 0: return '-'+base+str(n)
if n < 0: return '/'+base+str(-n)
def write(outName=None):
"""write the CTML file."""
x = XMLnode("ctml")
v = x.addChild("validate")
v["species"] = _valsp
v["reactions"] = _valrxn
if _elements:
ed = x.addChild("elementData")
for e in _elements:
e.build(ed)
for ph in _phases:
ph.build(x)
s = species_set(name = _name, species = _species)
s.build(x)
r = x.addChild('reactionData')
r['id'] = 'reaction_data'
if _motz_wise is not None:
r['motz_wise'] = str(_motz_wise).lower()
for rx in _reactions:
rx.build(r)
i = x.addChild('interactionData')
i['id'] = 'interaction_data'
for interaction in _interactions:
interaction.build(i)
b = x.addChild('bepData')
b['id'] = 'bep_data'
for bep in _beps:
bep.build(b)
if outName == 'STDOUT':
x.write(sys.stdout)
elif outName is not None:
x.write(outName)
elif _name != 'noname':
x.write(_name+'.xml')
else:
print(x)
if _valexport:
f = open(_valexport,'w')
for s in _species:
s.export(f, _valfmt)
f.close()
def addFloat(x, nm, val, fmt='', defunits=''):
"""
Add a child element to XML element x representing a
floating-point number.
"""
u = ''
s = ''
if isnum(val):
fval = float(val)
if fmt:
s = fmt % fval
else:
s = repr(fval)
xc = x.addChild(nm, s)
if defunits:
xc['units'] = defunits
else:
v = val[0]
u = val[1]
if fmt:
s = fmt % v
else:
s = repr(v)
xc = x.addChild(nm, s)
xc['units'] = u
def getAtomicComp(atoms):
if isinstance(atoms, dict): return atoms
a = atoms.replace(',',' ')
toks = a.split()
d = {}
for t in toks:
b = t.split(':')
try:
d[b[0]] = int(b[1])
except ValueError:
d[b[0]] = float(b[1])
return d
def getReactionSpecies(s):
"""Take a reaction string and return a
dictionary mapping species names to stoichiometric
coefficients. If any species appears more than once,
the returned stoichiometric coefficient is the sum.
>>> s = 'CH3 + 3 H + 5.2 O2 + 0.7 H'
>>> getReactionSpecies(s)
>>> {'CH3':1, 'H':3.7, 'O2':5.2}
"""
# Normalize formatting of falloff third bodies so that there is always a
# space following the '+', e.g. '(+M)' -> '(+ M)'
s = s.replace(' (+', ' (+ ')
# get rid of the '+' signs separating species. Only plus signs
# surrounded by spaces are replaced, so that plus signs may be
# used in species names (e.g. 'Ar3+')
toks = s.replace(' + ',' ').split()
d = {}
n = 1.0
for t in toks:
# try to convert the token to a number.
try:
n = float(t)
if n < 0.0:
raise CTI_Error("negative stoichiometric coefficient:"
+s)
#if t > '0' and t < '9':
# n = int(t)
#else:
# token isn't a number, so it must be a species name
except:
# already seen this token so increment its value by the last
# value of n
if t in d:
d[t] += n
else:
# first time this token has been seen, so set its value to n
d[t] = n
# reset n to 1.0 for species that do not specify a stoichiometric
# coefficient
n = 1
return d
class element(object):
""" An atomic element or isotope. """
def __init__(self, symbol = '',
atomic_mass = 0.01,
atomic_number = 0):
"""
:param symbol:
The symbol for the element or isotope.
:param atomic_mass:
The atomic mass in amu.
"""
self._sym = symbol
self._atw = atomic_mass
self._num = atomic_number
_elements.append(self)
def build(self, db):
e = db.addChild("element")
e["name"] = self._sym
e["atomicWt"] = repr(self._atw)
e["atomicNumber"] = repr(self._num)
class species_set(object):
def __init__(self, name = '', species = []):
self._s = species
self._name = name
#self.type = SPECIES_SET
def build(self, p):
p.addComment(' species definitions ')
sd = p.addChild("speciesData")
sd["id"] = "species_data"
for s in self._s:
#if s.type == SPECIES:
s.build(sd)
#else:
# raise 'wrong object type in species_set: '+s.__class__
class species(object):
"""A constituent of a phase or interface."""
def __init__(self,
name = 'missing name!',
atoms = '',
note = '',
thermo = None,
transport = None,
charge = -999,
size = 1.0):
"""
:param name:
The species name (or formula). The name may be arbitrarily long,
although usually a relatively short, abbreviated name is most
convenient. Required parameter.
:param atoms:
The atomic composition, specified by a string containing
space-delimited ``<element>:<atoms>`` pairs. The number of atoms may be
either an integer or a floating-point number.
:param note:
A user-defined comment. Not evaluated by Cantera itself.
:param thermo:
The parameterization to use to compute the reference-state
thermodynamic properties. This must be one of the entry types
described in `Thermodynamic Property Models
<https://cantera.org/science/science-species.html#sec-thermo-models>`__.
To specify multiple parameterizations, each for a different temperature range,
group them in parentheses.
:param transport:
An entry specifying parameters to compute this species'
contribution to the transport properties. This must be one of the
entry types described in `Species Transport Coefficients
<https://cantera.org/science/science-species.html#species-transport-coefficients>`__,
and must be consistent with the transport model of the phase into which
the species is imported. To specify parameters for multiple
transport models, group the entries in parentheses.
:param size:
The species "size". Currently used only for surface species,
where it represents the number of sites occupied.
:param charge:
The charge, in multiples of :math:`|e|`. If not specified, the
charge will be calculated from the number of "atoms" of element
``E``, which represents an electron.
"""
self._name = name
self._atoms = getAtomicComp(atoms)
self._comment = note
if thermo:
self._thermo = thermo
else:
self._thermo = const_cp()
self._transport = transport
chrg = 0
self._charge = charge
if 'E' in self._atoms:
chrg = -self._atoms['E']
if self._charge != -999:
if self._charge != chrg:
raise CTI_Error('specified charge inconsistent with number of electrons')
else:
self._charge = chrg
self._size = size
_species.append(self)
_speciesnames.append(name)
for e in self._atoms.keys():
_enames[e] = 1
def export(self, f, fmt = 'CSV'):
if fmt == 'CSV':
s = self._name+','
for e in _enames:
if e in self._atoms:
s += repr(self._atoms[e])+','
else:
s += '0,'
f.write(s)
if isinstance(self._thermo, thermo):
self._thermo.export(f, fmt)
else:
nt = len(self._thermo)
for n in range(nt):
self._thermo[n].export(f, fmt)
f.write('\n')
def build(self, p):
hdr = ' species '+self._name+' '
p.addComment(hdr)
s = p.addChild("species")
s["name"] = self._name
a = ''
for e in self._atoms.keys():
a += e+':'+str(self._atoms[e])+' '
s.addChild("atomArray",a)
if self._comment:
s.addChild("note",self._comment)
if self._charge != -999:
s.addChild("charge",self._charge)
if self._size != 1.0:
s.addChild("size",self._size)
if self._thermo:
t = s.addChild("thermo")
if isinstance(self._thermo, thermo):
self._thermo.build(t)
else:
nt = len(self._thermo)
for n in range(nt):
self._thermo[n].build(t)
if self._transport:
t = s.addChild("transport")
if isinstance(self._transport, transport):
self._transport.build(t)
else:
nt = len(self._transport)
for n in range(nt):
self._transport[n].build(t)
class thermo(object):
"""Base class for species standard-state thermodynamic properties."""
def _build(self, p):
return p.addChild("thermo")
def export(self, f, fmt = 'CSV'):
pass
class Mu0_table(thermo):
"""Properties are computed by specifying a table of standard
chemical potentials vs. T."""
def __init__(self, Trange = (0.0, 0.0),
h298 = 0.0,
mu0 = None,
p0 = -1.0):
self._t = Trange
self._h298 = h298
self._mu0 = mu0
self._pref = p0
def build(self, t):
n = t.addChild("Mu0")
n['Tmin'] = repr(self._t[0])
n['Tmax'] = repr(self._t[1])
if self._pref <= 0.0:
n['P0'] = repr(_pref)
else:
n['P0'] = repr(self._pref)
energy_units = _uenergy+'/'+_umol
addFloat(n,"H298", self._h298, defunits = energy_units)
n.addChild("numPoints", len(self._mu0))
mustr = ''
tstr = ''
col = 0
for v in self._mu0:
mu0 = v[1]
t = v[0]
tstr += '%17.9E, ' % t
mustr += '%17.9E, ' % mu0
col += 1
if col == 3:
tstr = tstr[:-2]+'\n'
mustr = mustr[:-2]+'\n'
col = 0
u = n.addChild("floatArray", mustr)
u["size"] = "numPoints"
u["name"] = "Mu0Values"
u = n.addChild("floatArray", tstr)
u["size"] = "numPoints"
u["name"] = "Mu0Temperatures"
class NASA(thermo):
"""The 7-coefficient NASA polynomial parameterization."""
def __init__(self, Trange = (0.0, 0.0), coeffs = [], p0 = -1.0):
r"""
:param Trange:
The temperature range over which the parameterization is valid.
This must be entered as a sequence of two temperature values.
Required.
:param coeffs:
List of seven coefficients :math:`(a_0, \ldots , a_6)`
:param p0:
The reference-state pressure, usually 1 atm or 1 bar. If omitted,
the default value is used, which is set by the ``standard_pressure``
directive.
"""
self._t = Trange
self._pref = p0
if len(coeffs) != 7:
raise CTI_Error('NASA coefficient list must have length = 7')
self._coeffs = coeffs
def export(self, f, fmt='CSV'):
if fmt == 'CSV':
s = 'NASA,'+str(self._t[0])+','+str(self._t[1])+','
for i in range(7):
s += '%17.9E, ' % self._coeffs[i]
f.write(s)
def build(self, t):
n = t.addChild("NASA")
n['Tmin'] = repr(self._t[0])
#n['Tmid'] = repr(self._t[1])
n['Tmax'] = repr(self._t[1])
if self._pref <= 0.0:
n['P0'] = repr(_pref)
else:
n['P0'] = repr(self._pref)
s = ''
for i in range(4):
s += '%17.9E, ' % self._coeffs[i]
s += '\n'
s += '%17.9E, %17.9E, %17.9E' % (self._coeffs[4],
self._coeffs[5], self._coeffs[6])
#if i > 0 and 3*((i+1)/3) == i: s += '\n'
#s = s[:-2]
u = n.addChild("floatArray", s)
u["size"] = "7"
u["name"] = "coeffs"
class NASA9(thermo):
"""NASA9 polynomial parameterization for a single temperature region."""
def __init__(self, Trange = (0.0, 0.0),
coeffs = [], p0 = -1.0):
r"""
:param Trange:
The temperature range over which the parameterization is valid.
This must be entered as a sequence of two temperature values.
Required.
:param coeffs:
List of nine coefficients :math:`(a_0, \ldots , a_8)`
:param p0:
The reference-state pressure, usually 1 atm or 1 bar. If omitted,
the default value is used, which is set by the ``standard_pressure``
directive.
"""
self._t = Trange # Range of the polynomial representation
self._pref = p0 # Reference pressure
if len(coeffs) != 9:
raise CTI_Error('NASA9 coefficient list must have length = 9')
self._coeffs = coeffs
def export(self, f, fmt='CSV'):
if fmt == 'CSV':
s = 'NASA9,'+str(self._t[0])+','+str(self._t[1])+','
for i in range(9):
s += '%17.9E, ' % self._coeffs[i]
f.write(s)
def build(self, t):
n = t.addChild("NASA9")
n['Tmin'] = repr(self._t[0])
n['Tmax'] = repr(self._t[1])
if self._pref <= 0.0:
n['P0'] = repr(_pref)
else:
n['P0'] = repr(self._pref)
s = ''
for i in range(4):
s += '%17.9E, ' % self._coeffs[i]
s += '\n'
s += '%17.9E, %17.9E, %17.9E, %17.9E,' % (self._coeffs[4], self._coeffs[5],
self._coeffs[6], self._coeffs[7])
s += '\n'
s += '%17.9E' % (self._coeffs[8])
u = n.addChild("floatArray", s)
u["size"] = "9"
u["name"] = "coeffs"
class activityCoefficients(object):
pass
class pureFluidParameters(activityCoefficients):
"""
"""
def __init__(self, species = None, a_coeff = [], b_coeff = 0):
"""
"""
self._species = species
self._acoeff = a_coeff
self._bcoeff = b_coeff
def build(self,a):
f= a.addChild("pureFluidParameters")
f['species'] = self._species
s = '%10.4E, %10.4E \n' % (self._acoeff[0], self._acoeff[1])
ac = f.addChild("a_coeff",s)
ac["units"] = _upres+'-'+_ulen+'6/'+_umol+'2'
ac["model"] = "linear_a"
s = '%0.2f \n' % self._bcoeff
bc = f.addChild("b_coeff",s)
bc["units"] = _ulen+'3/'+_umol
class crossFluidParameters(activityCoefficients):
def __init__(self, species = None, a_coeff = [], b_coeff = []):
self._species1, self._species2 = species.split(' ')
self._acoeff = a_coeff
self._bcoeff = b_coeff
def build(self,a):
f= a.addChild("crossFluidParameters")
f["species2"] = self._species2
f["species1"] = self._species1
s = '%10.4E, %10.4E \n' % (self._acoeff[0], self._acoeff[1])
ac = f.addChild("a_coeff",s)
ac["units"] = _upres+'-'+_ulen+'6/'+_umol+'2'
ac["model"] = "linear_a"
if self._bcoeff:
s = '%0.2f \n' % self._bcoeff
bc = f.addChild("b_coeff",s)
bc["units"] = _ulen+'3/'+_umol
class Shomate(thermo):
"""Shomate polynomial parameterization."""
def __init__(self, Trange = (0.0, 0.0), coeffs = [], p0 = -1.0):
r"""
:param Trange:
The temperature range over which the parameterization is valid.
This must be entered as a sequence of two temperature values.
Required input.
:param coeffs:
Sequence of seven coefficients :math:`(A, \ldots ,G)`
:param p0:
The reference-state pressure, usually 1 atm or 1 bar. If omitted,
the default value set by the ``standard_pressure`` directive is used.
"""
self._t = Trange
self._pref = p0
if len(coeffs) != 7:
raise CTI_Error('Shomate coefficient list must have length = 7')
self._coeffs = coeffs
def build(self, t):
n = t.addChild("Shomate")
n['Tmin'] = repr(self._t[0])
n['Tmax'] = repr(self._t[1])
if self._pref <= 0.0:
n['P0'] = repr(_pref)
else:
n['P0'] = repr(self._pref)
s = ''
for i in range(4):
s += '%17.9E, ' % self._coeffs[i]
s += '\n'
s += '%17.9E, %17.9E, %17.9E' % (self._coeffs[4],
self._coeffs[5], self._coeffs[6])
u = n.addChild("floatArray", s)
u["size"] = "7"
u["name"] = "coeffs"
class Adsorbate(thermo):
"""Adsorbed species characterized by a binding energy and a set of
vibrational frequencies."""
def __init__(self, Trange = (0.0, 0.0),
binding_energy = 0.0,
frequencies = [], p0 = -1.0):
self._t = Trange
self._pref = p0
self._freqs = frequencies
self._be = binding_energy
def build(self, t):
n = t.addChild("adsorbate")
n['Tmin'] = repr(self._t[0])
n['Tmax'] = repr(self._t[1])
if self._pref <= 0.0:
n['P0'] = repr(_pref)
else:
n['P0'] = repr(self._pref)
energy_units = _uenergy+'/'+_umol
addFloat(n,'binding_energy',self._be, defunits = energy_units)
s = ""
nfreq = len(self._freqs)
for i in range(nfreq):
s += '%17.9E, ' % self._freqs[i]
s += '\n'
u = n.addChild("floatArray", s)
u["size"] = repr(nfreq)
u["name"] = "freqs"
class const_cp(thermo):
"""Constant specific heat."""
def __init__(self,
t0 = 298.15, cp0 = 0.0, h0 = 0.0, s0 = 0.0,
tmax = 5000.0, tmin = 100.0):
"""
:param t0:
Temperature parameter T0. Default: 298.15 K.
:param cp0:
Reference-state molar heat capacity (constant). Default: 0.0.
:param h0:
Reference-state molar enthalpy at temperature T0. Default: 0.0.
:param s0:
Reference-state molar entropy at temperature T0. Default: 0.0.
"""
self._t = [tmin, tmax]
self._c = [t0, h0, s0, cp0]
def build(self, t):
#t = self._build(p)
c = t.addChild('const_cp')
if self._t[0] >= 0.0: c['Tmin'] = repr(self._t[0])
if self._t[1] >= 0.0: c['Tmax'] = repr(self._t[1])
energy_units = _uenergy+'/'+_umol
addFloat(c,'t0',self._c[0], defunits = 'K')
addFloat(c,'h0',self._c[1], defunits = energy_units)
addFloat(c,'s0',self._c[2], defunits = energy_units+'/K')
addFloat(c,'cp0',self._c[3], defunits = energy_units+'/K')
class transport(object):
pass
class gas_transport(transport):
"""
Species-specific Transport coefficients for gas-phase transport models.
"""
def __init__(self, geom,
diam = 0.0, well_depth = 0.0, dipole = 0.0,
polar = 0.0, rot_relax = 0.0, acentric_factor = None,
disp_coeff = 0.0, quad_polar = 0.0):
"""
:param geom:
A string specifying the molecular geometry. One of ``atom``,
``linear``, or ``nonlinear``. Required.
:param diam:
The Lennard-Jones collision diameter in Angstroms. Required.
:param well_depth:
The Lennard-Jones well depth in Kelvin. Required.
:param dipole:
The permanent dipole moment in Debye. Default: 0.0
:param polar:
The polarizability in A^3. Default: 0.0
:param rot_relax:
The rotational relaxation collision number at 298 K. Dimensionless.
Default: 0.0
:param w_ac:
Pitzer's acentric factor. Dimensionless.
Default: 0.0
:param disp_coeff:
The dispersion coefficient in A^5
Default: 0.0
:param quad_polar:
The quadrupole polarizability