-
-
Notifications
You must be signed in to change notification settings - Fork 341
/
onedim.py
1678 lines (1385 loc) · 63.9 KB
/
onedim.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
# This file is part of Cantera. See License.txt in the top-level directory or
# at https://cantera.org/license.txt for license and copyright information.
from math import erf
from email.utils import formatdate
import warnings
import numpy as np
from ._cantera import *
from .composite import Solution, SolutionArray
from . import __version__, __git_commit__
class FlameBase(Sim1D):
""" Base class for flames with a single flow domain """
__slots__ = ('gas',)
_other = ()
def __init__(self, domains, gas, grid=None):
"""
:param gas:
object to use to evaluate all gas properties and reaction rates
:param grid:
array of initial grid points
"""
if grid is None:
grid = np.linspace(0.0, 0.1, 6)
self.flame.grid = grid
super().__init__(domains)
self.gas = gas
self.flame.P = gas.P
def other_components(self, domain=None):
"""
The method returns simulation components that are specific to a class
derived from `FlameBase` or a specific *domain* within the `FlameBase`
simulation object. Entries may include:
* ``grid``: grid point positions along the flame [m]
* ``velocity``: normal velocity [m/s]
* ``spread_rate``: tangential velocity gradient [1/s]
* ``lambda``: radial pressure gradient [N/m^4]
* ``eField``: electric field strength
:param domain: Index of a specific domain within the `Sim1D.domains`
list. The default is to return other columns of the `Sim1D` object.
"""
if domain is None:
return self._other
dom = self.domains[self.domain_index(domain)]
if isinstance(dom, Inlet1D):
return tuple([e for e in self._other
if e not in {'grid', 'lambda', 'eField'}])
elif isinstance(dom, (IdealGasFlow, IonFlow)):
return self._other
else:
return ()
def set_refine_criteria(self, ratio=10.0, slope=0.8, curve=0.8, prune=0.0):
"""
Set the criteria used for grid refinement.
:param ratio:
additional points will be added if the ratio of the spacing on
either side of a grid point exceeds this value
:param slope:
maximum difference in value between two adjacent points, scaled by
the maximum difference in the profile (0.0 < slope < 1.0). Adds
points in regions of high slope.
:param curve:
maximum difference in slope between two adjacent intervals, scaled
by the maximum difference in the profile (0.0 < curve < 1.0). Adds
points in regions of high curvature.
:param prune:
if the slope or curve criteria are satisfied to the level of
'prune', the grid point is assumed not to be needed and is removed.
Set prune significantly smaller than 'slope' and 'curve'. Set to
zero to disable pruning the grid.
>>> f.set_refine_criteria(ratio=3.0, slope=0.1, curve=0.2, prune=0)
"""
super().set_refine_criteria(self.flame, ratio, slope, curve, prune)
def get_refine_criteria(self):
"""
Get a dictionary of the criteria used for grid refinement. The items in
the dictionary are the ``ratio``, ``slope``, ``curve``, and ``prune``,
as defined in `~FlameBase.set_refine_criteria`.
>>> f.set_refine_criteria(ratio=3.0, slope=0.1, curve=0.2, prune=0)
>>> f.get_refine_criteria()
{'ratio': 3.0, 'slope': 0.1, 'curve': 0.2, 'prune': 0.0}
"""
return super().get_refine_criteria(self.flame)
def set_initial_guess(self, *args, data=None, group=None, **kwargs):
"""
Set the initial guess for the solution, and load restart data if
provided. Derived classes extend this function to set approximations
for the temperature and composition profiles.
:param data:
Restart data, which are typically based on an earlier simulation
result. Restart data may be specified using a `SolutionArray`,
pandas' DataFrame, or previously saved CSV or HDF container files.
Note that restart data do not overwrite boundary conditions.
DataFrame input requires a working installation of pandas, whereas
HDF input requires an installation of h5py. These packages can be
installed using pip or conda (`pandas` and `h5py`, respectively).
:param key:
Group identifier within a HDF container file (only used in
combination with HDF restart data).
"""
super().set_initial_guess(*args, data=data, group=group, **kwargs)
if not data:
return
# load restart data into SolutionArray
if isinstance(data, SolutionArray):
# already a solution array
arr = data
elif isinstance(data, str):
if data.endswith('.hdf5') or data.endswith('.h5'):
# data source identifies a HDF file
arr = SolutionArray(self.gas, extra=self.other_components())
arr.read_hdf(data, group=group)
elif data.endswith('.csv'):
# data source identifies a CSV file
arr = SolutionArray(self.gas, extra=self.other_components())
arr.read_csv(data)
else:
raise ValueError(
"'{}' does not identify CSV or HDF file.".format(data)
)
else:
# data source is a pandas DataFrame
arr = SolutionArray(self.gas, extra=self.other_components())
arr.from_pandas(data)
# get left and right boundaries
left = self.domains[0]
right = self.domains[2]
if isinstance(left, Inlet1D) and isinstance(right, Inlet1D):
# find stagnation plane
i = np.flatnonzero(self.velocity > 0)[-1]
# adjust temperatures
grid = arr.grid
xi = (grid - grid[0]) / (grid[-1] - grid[0])
T = arr.T
T += (left.T - T[0]) * (1 - xi) + (right.T - T[-1]) * xi
arr.TP = T, self.P
# adjust velocities
u = arr.velocity
self.gas.TPY = left.T, self.P, left.Y
u[:i] = u[:i] * left.mdot / self.gas.density / u[0]
self.gas.TPY = right.T, self.P, right.Y
u[i:] = - u[i:] * right.mdot / self.gas.density / u[-1]
arr.velocity = u
elif isinstance(left, Inlet1D):
# adjust temperatures
T = arr.T
arr.TP = T + left.T - T[0], self.P
# adjust velocities
if self.flame.flow_type != "Free Flame":
self.gas.TPY = left.T, self.P, left.Y
u0 = left.mdot / self.gas.density
arr.velocity *= u0 / arr.velocity[0]
self.from_solution_array(arr)
def set_profile(self, component, positions, values):
"""
Set an initial estimate for a profile of one component.
:param component:
component name or index
:param positions:
sequence of relative positions, from 0 on the left to 1 on the right
:param values:
sequence of values at the relative positions specified in *positions*
>>> f.set_profile('T', [0.0, 0.2, 1.0], [400.0, 800.0, 1500.0])
"""
super().set_profile(self.flame, component, positions, values)
@property
def max_grid_points(self):
"""
Get/Set the maximum number of grid points used in the solution of
this flame.
"""
return super().get_max_grid_points(self.flame)
@max_grid_points.setter
def max_grid_points(self, npmax):
super().set_max_grid_points(self.flame, npmax)
@property
def transport_model(self):
"""
Get/Set the transport model used by the `Solution` object used for this
simulation.
"""
return self.gas.transport_model
@transport_model.setter
def transport_model(self, model):
self.gas.transport_model = model
self.flame.set_transport(self.gas)
@property
def energy_enabled(self):
""" Get/Set whether or not to solve the energy equation."""
return self.flame.energy_enabled
@energy_enabled.setter
def energy_enabled(self, enable):
self.flame.energy_enabled = enable
@property
def soret_enabled(self):
"""
Get/Set whether or not to include diffusive mass fluxes due to the
Soret effect. Enabling this option works only when using the
multicomponent transport model.
"""
return self.flame.soret_enabled
@soret_enabled.setter
def soret_enabled(self, enable):
self.flame.soret_enabled = enable
@property
def radiation_enabled(self):
"""
Get/Set whether or not to include radiative heat transfer
"""
return self.flame.radiation_enabled
@radiation_enabled.setter
def radiation_enabled(self, enable):
self.flame.radiation_enabled = enable
def set_boundary_emissivities(self, e_left, e_right):
"""
.. deprecated:: 2.5
To be deprecated with version 2.5, and removed thereafter.
Replaced by property `boundary_emissivities`.
"""
warnings.warn("Method 'set_boundary_emissivities' to be removed after "
"Cantera 2.5. Replaced by property "
"'boundary_emissivities'", DeprecationWarning)
self.flame.boundary_emissivities = e_left, e_right
@property
def boundary_emissivities(self):
""" Set/get boundary emissivities. """
return self.flame.boundary_emissivities
@boundary_emissivities.setter
def boundary_emissivities(self, epsilon):
if len(epsilon) != 2:
raise ValueError("Boundary emissivities must both be set at the same time.")
self.flame.boundary_emissivities = epsilon[0], epsilon[1]
@property
def grid(self):
""" Array of grid point positions along the flame. """
return self.flame.grid
@property
def P(self):
""" Get/Set the pressure of the flame [Pa] """
return self.flame.P
@P.setter
def P(self, P):
self.flame.P = P
@property
def T(self):
""" Array containing the temperature [K] at each grid point. """
return self.profile(self.flame, 'T')
@property
def u(self):
"""
Array containing the velocity [m/s] normal to the flame at each point.
.. deprecated:: 2.5
To be deprecated with version 2.5, and removed thereafter.
Replaced by property `velocity`.
"""
warnings.warn("Property 'u' to be removed after Cantera 2.5. "
"Replaced by property 'velocity'",
DeprecationWarning)
return self.profile(self.flame, 'velocity')
@property
def velocity(self):
"""
Array containing the velocity [m/s] normal to the flame at each point.
"""
return self.profile(self.flame, 'velocity')
@property
def V(self):
"""
Array containing the tangential velocity gradient [1/s] at each point.
.. deprecated:: 2.5
To be deprecated with version 2.5, and removed thereafter.
Replaced by property `spread_rate`.
"""
warnings.warn("Property 'V' to be removed after Cantera 2.5. "
"Replaced by property 'spread_rate'",
DeprecationWarning)
return self.profile(self.flame, 'spread_rate')
@property
def spread_rate(self):
"""
Array containing the tangential velocity gradient [1/s] (e.g. radial
velocity divided by radius) at each point.
"""
return self.profile(self.flame, 'spread_rate')
@property
def L(self):
"""
Array containing the radial pressure gradient (1/r)(dP/dr) [N/m^4] at
each point. Note: This value is named 'lambda' in the C++ code.
"""
return self.profile(self.flame, 'lambda')
def elemental_mass_fraction(self, m):
r"""
Get the elemental mass fraction :math:`Z_{\mathrm{mass},m}` of element
:math:`m` at each grid point, which is defined as:
.. math:: Z_{\mathrm{mass},m} = \sum_k \frac{a_{m,k} M_m}{M_k} Y_k
with :math:`a_{m,k}` being the number of atoms of element :math:`m` in
species :math:`k`, :math:`M_m` the atomic weight of element :math:`m`,
:math:`M_k` the molecular weight of species :math:`k`, and :math:`Y_k`
the mass fraction of species :math:`k`.
:param m:
Base element, may be specified by name or by index.
>>> phase.elemental_mass_fraction('H')
[1.0, ..., 0.0]
"""
vals = np.empty(self.flame.n_points)
for i in range(self.flame.n_points):
self.set_gas_state(i)
vals[i] = self.gas.elemental_mass_fraction(m)
return vals
def elemental_mole_fraction(self, m):
r"""
Get the elemental mole fraction :math:`Z_{\mathrm{mole},m}` of element
:math:`m` at each grid point, which is defined as:
.. math:: Z_{\mathrm{mole},m} = \sum_k \frac{a_{m,k}}{\sum_j a_{j,k}} X_k
with :math:`a_{m,k}` being the number of atoms of element :math:`m` in
species :math:`k` and :math:`X_k` the mole fraction of species
:math:`k`.
:param m:
Base element, may be specified by name or by index.
>>> phase.elemental_mole_fraction('H')
[1.0, ..., 0.0]
"""
vals = np.empty(self.flame.n_points)
for i in range(self.flame.n_points):
self.set_gas_state(i)
vals[i] = self.gas.elemental_mole_fraction(m)
return vals
def solution(self, component, point=None):
"""
Get the solution at one point or for the full flame domain (if
`point=None`) for the specified *component*. The *component* can be
specified by name or index.
"""
if point is None:
return self.profile(self.flame, component)
else:
return self.value(self.flame, component, point)
def set_gas_state(self, point):
"""
Set the state of the the Solution object used for calculations,
`self.gas`, to the temperature and composition at the point with index
*point*.
"""
k0 = self.flame.component_index(self.gas.species_name(0))
Y = [self.solution(k, point)
for k in range(k0, k0 + self.gas.n_species)]
self.gas.set_unnormalized_mass_fractions(Y)
self.gas.TP = self.value(self.flame, 'T', point), self.P
def write_csv(self, filename, species='X', quiet=True):
"""
Write the velocity, temperature, density, and species profiles
to a CSV file.
:param filename:
Output file name
:param species:
Attribute to use obtaining species profiles, e.g. ``X`` for
mole fractions or ``Y`` for mass fractions.
"""
# save data
cols = ('extra', 'T', 'D', species)
self.to_solution_array().write_csv(filename, cols=cols)
if not quiet:
print("Solution saved to '{0}'.".format(filename))
def to_solution_array(self, domain=None):
"""
Return the solution vector as a `SolutionArray` object.
Derived classes define default values for *other*.
"""
if domain is None:
domain = self.flame
else:
domain = self.domains[self.domain_index(domain)]
other = self.other_components(domain)
states, other_cols, meta = super().collect_data(domain, other)
n_points = np.array(states[0]).size
if n_points:
arr = SolutionArray(self.phase(domain), n_points,
extra=other_cols, meta=meta)
arr.TPY = states
return arr
else:
return SolutionArray(self.phase(domain), meta=meta)
def from_solution_array(self, arr, domain=None):
"""
Restore the solution vector from a `SolutionArray` object.
Derived classes define default values for *other*.
"""
if domain is None:
domain = self.flame
else:
domain = self.domains[self.domain_index(domain)]
other = self.other_components(domain)
states = arr.TPY
other_cols = {e: getattr(arr, e) for e in other
if e in arr._extra}
meta = arr.meta
super().restore_data(domain, states, other_cols, meta)
def to_pandas(self, species='X'):
"""
Return the solution vector as a `pandas.DataFrame`.
:param species:
Attribute to use obtaining species profiles, e.g. ``X`` for
mole fractions or ``Y`` for mass fractions.
This method uses `to_solution_array` and requires a working pandas
installation. Use pip or conda to install `pandas` to enable this
method.
"""
cols = ('extra', 'T', 'D', species)
return self.to_solution_array().to_pandas(cols=cols)
def from_pandas(self, df, restore_boundaries=True, settings=None):
"""
Restore the solution vector from a `pandas.DataFrame`.
:param df:
`pandas.DataFrame` containing data to be restored
:param restore_boundaries:
Boolean flag to indicate whether boundaries should be restored
(default is ``True``)
:param settings:
dictionary containing simulation settings
(see `FlameBase.settings`)
This method is intendend for loading of data that were previously
exported by `to_pandas`. The method uses `from_solution_array` and
requires a working pandas installation. The package 'pandas' can be
installed using pip or conda.
"""
arr = SolutionArray(self.gas, extra=self.other_components())
arr.from_pandas(df)
self.from_solution_array(arr, restore_boundaries=restore_boundaries,
settings=settings)
def write_hdf(self, filename, *args, group=None, species='X', mode='a',
description=None, compression=None, compression_opts=None,
quiet=True, **kwargs):
"""
Write the solution vector to a HDF container file.
The `write_hdf` method preserves the stucture of a `FlameBase`-derived
object (such as `FreeFlame`). Each simulation is saved as a *group*,
whereas individual domains are saved as subgroups. In addition to
datasets, information on `Sim1D.settings` and `Domain1D.settings` is
saved in form of HDF attributes. The internal HDF file structure is
illustrated for a `FreeFlame` output as:::
/ Group
/group0 Group
/group0/Sim1D_type Attribute
...
/group0/flame Group
/group0/flame/Domain1D_type Attribute
...
/group0/flame/T Dataset
...
/group0/flame/phase Group
/group0/products Group
/group0/products/Domain1D_type Attribute
...
/group0/products/T Dataset
...
/group0/products/phase Group
/group0/reactants Group
/group0/reactants/Domain1D_type Attribute
...
/group0/reactants/T Dataset
...
/group0/reactants/phase Group
where ``group0`` is the default name for the top level HDF entry, and
``reactants``, ``flame`` and ``products`` correspond to domain names.
Note that it is possible to save multiple solutions to a single HDF
container file.
:param filename:
HDF container file containing data to be restored
:param group:
Identifier for the group in the container file. A group may contain
multiple `SolutionArray` objects.
:param species:
Attribute to use obtaining species profiles, e.g. ``X`` for
mole fractions or ``Y`` for mass fractions.
:param mode:
Mode h5py uses to open the output file {'a' to read/write if file
exists, create otherwise (default); 'w' to create file, truncate if
exists; 'r+' to read/write, file must exist}.
:param description:
Custom comment describing the dataset to be stored.
:param compression:
Pre-defined h5py compression filters {None, 'gzip', 'lzf', 'szip'}
used for data compression.
:param compression_opts:
Options for the h5py compression filter; for 'gzip', this
corresponds to the compression level {None, 0-9}.
:param quiet:
Suppress message confirming successful file output.
Additional arguments (i.e. *args* and *kwargs*) are passed on to
`SolutionArray.collect_data`. The method exports data using
`SolutionArray.write_hdf` via `to_solution_array` and requires a working
installation of h5py (`h5py` can be installed using pip or conda).
"""
cols = ('extra', 'T', 'D', species)
meta = self.settings
meta['date'] = formatdate(localtime=True)
meta['cantera_version'] = __version__
meta['git_commit'] = __git_commit__
if description is not None:
meta['description'] = description
for i in range(3):
arr = self.to_solution_array(domain=self.domains[i])
group = arr.write_hdf(filename, *args, group=group, cols=cols,
subgroup=self.domains[i].name,
attrs=meta, mode=mode, append=(i > 0),
compression=compression,
compression_opts=compression_opts,
**kwargs)
meta = {}
mode = 'a'
if not quiet:
msg = "Solution saved to '{0}' as group '{1}'."
print(msg.format(filename, group))
def read_hdf(self, filename, group=None, restore_boundaries=True):
"""
Restore the solution vector from a HDF container file.
:param filename:
HDF container file containing data to be restored
:param group:
String identifying the HDF group containing the data
:param restore_boundaries:
Boolean flag to indicate whether boundaries should be restored
(default is ``True``)
The method imports data using `SolutionArray.read_hdf` via
`from_solution_array` and requires a working installation of h5py
(`h5py` can be installed using pip or conda).
"""
if restore_boundaries:
domains = range(3)
else:
domains = [1]
for d in domains:
arr = SolutionArray(self.phase(d), extra=self.other_components(d))
meta = arr.read_hdf(filename, group=group,
subgroup=self.domains[d].name)
self.from_solution_array(arr, domain=d)
self.settings = meta
return meta
@property
def settings(self):
""" Return a dictionary listing simulation settings """
out = {'Sim1D_type': type(self).__name__}
out['transport_model'] = self.transport_model
out['energy_enabled'] = self.energy_enabled
out['soret_enabled'] = self.soret_enabled
out['radiation_enabled'] = self.radiation_enabled
out['fixed_temperature'] = self.fixed_temperature
out.update(self.get_refine_criteria())
out['max_time_step_count'] = self.max_time_step_count
out['max_grid_points'] = self.get_max_grid_points(self.flame)
return out
@settings.setter
def settings(self, s):
# simple setters
attr = {'transport_model',
'energy_enabled', 'soret_enabled', 'radiation_enabled',
'fixed_temperature',
'max_time_step_count', 'max_grid_points'}
attr = attr & set(s.keys())
for key in attr:
setattr(self, key, s[key])
# refine criteria
refine = {k: v for k, v in s.items()
if k in ['ratio', 'slope', 'curve', 'prune']}
if refine:
self.set_refine_criteria(**refine)
def _trim(docstring):
"""Remove block indentation from a docstring."""
if not docstring:
return ''
lines = docstring.splitlines()
# Determine minimum indentation (first line doesn't count):
indent = 999
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < 999:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Return a single string, with trailing and leading blank lines stripped
return '\n'.join(trimmed).strip('\n')
def _array_property(attr, size=None):
"""
Generate a property that retrieves values at each point in the flame. The
'size' argument is the attribute name of the gas object used to set the
leading dimension of the resulting array.
"""
def getter(self):
if size is None:
# 1D array for scalar property
vals = np.empty(self.flame.n_points)
else:
# 2D array
vals = np.empty((getattr(self.gas, size), self.flame.n_points))
for i in range(self.flame.n_points):
self.set_gas_state(i)
vals[...,i] = getattr(self.gas, attr)
return vals
if size is None:
extradoc = "\nReturns an array of length `n_points`."
else:
extradoc = "\nReturns an array of size `%s` x `n_points`." % size
doc = _trim(getattr(Solution, attr).__doc__) +'\n' + extradoc
return property(getter, doc=doc)
# Add scalar properties to FlameBase
for _attr in ['density', 'density_mass', 'density_mole', 'volume_mass',
'volume_mole', 'int_energy_mole', 'int_energy_mass', 'h',
'enthalpy_mole', 'enthalpy_mass', 's', 'entropy_mole',
'entropy_mass', 'g', 'gibbs_mole', 'gibbs_mass', 'cv',
'cv_mole', 'cv_mass', 'cp', 'cp_mole', 'cp_mass',
'isothermal_compressibility', 'thermal_expansion_coeff',
'viscosity', 'thermal_conductivity', 'heat_release_rate']:
setattr(FlameBase, _attr, _array_property(_attr))
FlameBase.volume = _array_property('v') # avoid confusion with velocity gradient 'V'
FlameBase.int_energy = _array_property('u') # avoid collision with velocity 'u'
# Add properties with values for each species
for _attr in ['X', 'Y', 'concentrations', 'partial_molar_enthalpies',
'partial_molar_entropies', 'partial_molar_int_energies',
'chemical_potentials', 'electrochemical_potentials', 'partial_molar_cp',
'partial_molar_volumes', 'standard_enthalpies_RT',
'standard_entropies_R', 'standard_int_energies_RT',
'standard_gibbs_RT', 'standard_cp_R', 'creation_rates',
'destruction_rates', 'net_production_rates', 'mix_diff_coeffs',
'mix_diff_coeffs_mass', 'mix_diff_coeffs_mole', 'thermal_diff_coeffs']:
setattr(FlameBase, _attr, _array_property(_attr, 'n_species'))
# Add properties with values for each reaction
for _attr in ['forward_rates_of_progress', 'reverse_rates_of_progress', 'net_rates_of_progress',
'equilibrium_constants', 'forward_rate_constants', 'reverse_rate_constants',
'delta_enthalpy', 'delta_gibbs', 'delta_entropy',
'delta_standard_enthalpy', 'delta_standard_gibbs',
'delta_standard_entropy', 'heat_production_rates']:
setattr(FlameBase, _attr, _array_property(_attr, 'n_reactions'))
class FreeFlame(FlameBase):
"""A freely-propagating flat flame."""
__slots__ = ('inlet', 'flame', 'outlet')
_other = ('grid', 'velocity')
def __init__(self, gas, grid=None, width=None):
"""
A domain of type IdealGasFlow named 'flame' will be created to represent
the flame and set to free flow. The three domains comprising the stack
are stored as ``self.inlet``, ``self.flame``, and ``self.outlet``.
:param grid:
A list of points to be used as the initial grid. Not recommended
unless solving only on a fixed grid; Use the `width` parameter
instead.
:param width:
Defines a grid on the interval [0, width] with internal points
determined automatically by the solver.
"""
self.inlet = Inlet1D(name='reactants', phase=gas)
self.outlet = Outlet1D(name='products', phase=gas)
if not hasattr(self, 'flame'):
# Create flame domain if not already instantiated by a child class
self.flame = IdealGasFlow(gas, name='flame')
self.flame.set_free_flow()
if width is not None:
grid = np.array([0.0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8, 1.0]) * width
super().__init__((self.inlet, self.flame, self.outlet), gas, grid)
# Setting X needs to be deferred until linked to the flow domain
self.inlet.T = gas.T
self.inlet.X = gas.X
def set_initial_guess(self, locs=[0.0, 0.3, 0.5, 1.0], data=None, group=None):
"""
Set the initial guess for the solution. By default, the adiabatic flame
temperature and equilibrium composition are computed for the inlet gas
composition. Alternatively, a previously calculated result can be
supplied as an initial guess via 'data' and 'key' inputs (see
`FlameBase.set_initial_guess`).
:param locs:
A list of four locations to define the temperature and mass fraction
profiles. Profiles rise linearly between the second and third
location. Locations are given as a fraction of the entire domain
"""
super().set_initial_guess(data=data, group=group)
if data:
# set fixed temperature
Tmid = .75 * self.T[0] + .25 * self.T[-1]
i = np.flatnonzero(data.T < Tmid)[-1]
self.fixed_temperature = data.T[i]
return
self.gas.TPY = self.inlet.T, self.P, self.inlet.Y
if not self.inlet.mdot:
# nonzero initial guess increases likelihood of convergence
self.inlet.mdot = 1.0 * self.gas.density
Y0 = self.inlet.Y
u0 = self.inlet.mdot / self.gas.density
T0 = self.inlet.T
# get adiabatic flame temperature and composition
self.gas.equilibrate('HP')
Teq = self.gas.T
Yeq = self.gas.Y
u1 = self.inlet.mdot / self.gas.density
self.set_profile('velocity', locs, [u0, u0, u1, u1])
self.set_profile('T', locs, [T0, T0, Teq, Teq])
# Pick the location of the fixed temperature point, using an existing
# point if a reasonable choice exists
T = self.T
Tmid = 0.75 * T0 + 0.25 * Teq
i = np.flatnonzero(T < Tmid)[-1] # last point less than Tmid
if Tmid - T[i] < 0.2 * (Tmid - T0):
self.fixed_temperature = T[i]
elif T[i+1] - Tmid < 0.2 * (Teq - Tmid):
self.fixed_temperature = T[i+1]
else:
self.fixed_temperature = Tmid
for n in range(self.gas.n_species):
self.set_profile(self.gas.species_name(n),
locs, [Y0[n], Y0[n], Yeq[n], Yeq[n]])
def solve(self, loglevel=1, refine_grid=True, auto=False):
"""
Solve the problem.
:param loglevel:
integer flag controlling the amount of diagnostic output. Zero
suppresses all output, and 5 produces very verbose output.
:param refine_grid:
if True, enable grid refinement.
:param auto: if True, sequentially execute the different solution stages
and attempt to automatically recover from errors. Attempts to first
solve on the initial grid with energy enabled. If that does not
succeed, a fixed-temperature solution will be tried followed by
enabling the energy equation, and then with grid refinement enabled.
If non-default tolerances have been specified or multicomponent
transport is enabled, an additional solution using these options
will be calculated.
"""
if not auto:
return super().solve(loglevel, refine_grid, auto)
# Use a callback function to check that the domain is actually wide
# enough to contain the flame after each steady-state solve. If the user
# provided a callback, store this so it can called in addition to our
# callback, and restored at the end.
original_callback = self._steady_callback
class DomainTooNarrow(Exception): pass
def check_width(t):
T = self.T
x = self.grid
mRef = (T[-1] - T[0]) / (x[-1] - x[0])
mLeft = (T[1] - T[0]) / (x[1] - x[0]) / mRef
mRight = (T[-3] - T[-1]) / (x[-3] - x[-1]) / mRef
# The domain is considered too narrow if gradient at the left or
# right edge is significant, compared to the average gradient across
# the domain.
if mLeft > 0.02 or mRight > 0.02:
raise DomainTooNarrow()
if original_callback:
return original_callback(t)
else:
return 0.0
self.set_steady_callback(check_width)
for _ in range(12):
try:
super().solve(loglevel, refine_grid, auto)
break
except DomainTooNarrow:
self.flame.grid *= 2
if loglevel > 0:
print('Expanding domain to accommodate flame thickness. '
'New width: {} m'.format(
self.flame.grid[-1] - self.flame.grid[0]))
if refine_grid:
self.refine(loglevel)
self.set_steady_callback(original_callback)
def get_flame_speed_reaction_sensitivities(self):
r"""
Compute the normalized sensitivities of the laminar flame speed
:math:`S_u` with respect to the reaction rate constants :math:`k_i`:
.. math::
s_i = \frac{k_i}{S_u} \frac{dS_u}{dk_i}
"""
def g(sim):
return sim.velocity[0]
Nvars = sum(D.n_components * D.n_points for D in self.domains)
# Index of u[0] in the global solution vector
i_Su = self.inlet.n_components + self.flame.component_index('velocity')
dgdx = np.zeros(Nvars)
dgdx[i_Su] = 1
Su0 = g(self)
def perturb(sim, i, dp):
sim.gas.set_multiplier(1+dp, i)
return self.solve_adjoint(perturb, self.gas.n_reactions, dgdx) / Su0
class IonFlameBase(FlameBase):
@property
def electric_field_enabled(self):
""" Get/Set whether or not to solve the Poisson's equation."""
return self.flame.electric_field_enabled
@electric_field_enabled.setter
def electric_field_enabled(self, enable):
self.flame.electric_field_enabled = enable
@property
def E(self):
"""
Array containing the electric field strength at each point.
"""
return self.profile(self.flame, 'eField')
def solve(self, loglevel=1, refine_grid=True, auto=False, stage=1, enable_energy=True):
self.flame.set_solving_stage(stage)
if stage == 1:
super().solve(loglevel, refine_grid, auto)
if stage == 2:
self.poisson_enabled = True
super().solve(loglevel, refine_grid, auto)
class IonFreeFlame(IonFlameBase, FreeFlame):
"""A freely-propagating flame with ionized gas."""
__slots__ = ('inlet', 'flame', 'outlet')
_other = ('grid', 'velocity', 'eField')
def __init__(self, gas, grid=None, width=None):
if not hasattr(self, 'flame'):
# Create flame domain if not already instantiated by a child class
self.flame = IonFlow(gas, name='flame')
self.flame.set_free_flow()
super().__init__(gas, grid, width)
class BurnerFlame(FlameBase):
"""A burner-stabilized flat flame."""
__slots__ = ('burner', 'flame', 'outlet')
_other = ('grid', 'velocity')
def __init__(self, gas, grid=None, width=None):
"""
:param gas:
`Solution` (using the IdealGas thermodynamic model) used to
evaluate all gas properties and reaction rates.
:param grid:
A list of points to be used as the initial grid. Not recommended
unless solving only on a fixed grid; Use the `width` parameter
instead.
:param width:
Defines a grid on the interval [0, width] with internal points
determined automatically by the solver.
A domain of class `IdealGasFlow` named ``flame`` will be created to
represent the flame and set to axisymmetric stagnation flow. The three
domains comprising the stack are stored as ``self.burner``,
``self.flame``, and ``self.outlet``.