-
Notifications
You must be signed in to change notification settings - Fork 0
/
injector.py
1754 lines (1494 loc) · 61.6 KB
/
injector.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
"""mirgecom driver for the Y0 demonstration.
Note: this example requires a *scaled* version of the Y0
grid. A working grid example is located here:
github.com:/illinois-ceesd/data@y0scaled
"""
__copyright__ = """
Copyright (C) 2020 University of Illinois Board of Trustees
"""
__license__ = """
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.
"""
import logging
import sys
import yaml
import numpy as np
import math
import pyopencl as cl
import numpy.linalg as la # noqa
import pyopencl.array as cla # noqa
from functools import partial
from pytools.obj_array import make_obj_array
from mirgecom.fluid import make_conserved
from arraycontext import thaw, freeze
from meshmode.mesh import BTAG_ALL, BTAG_NONE # noqa
from grudge.eager import EagerDGDiscretization
from grudge.shortcuts import make_visualizer
from grudge.dof_desc import DTAG_BOUNDARY
#from grudge.op import nodal_max, nodal_min
from logpyle import IntervalTimer, set_dt
from mirgecom.logging_quantities import (
initialize_logmgr,
logmgr_add_cl_device_info,
logmgr_set_time
)
from mirgecom.navierstokes import ns_operator
from mirgecom.artificial_viscosity import \
av_laplacian_operator, smoothness_indicator
from mirgecom.simutil import (
generate_and_distribute_mesh,
check_step,
write_visfile,
check_naninf_local,
check_range_local,
get_sim_timestep
)
from mirgecom.restart import write_restart_file
from mirgecom.io import make_init_message
from mirgecom.mpi import mpi_entry_point
import pyopencl.tools as cl_tools
from mirgecom.integrators import (rk4_step, lsrk54_step, lsrk144_step,
euler_step)
from mirgecom.steppers import advance_state
from mirgecom.boundary import (
PrescribedFluidBoundary,
IsothermalWallBoundary,
OutflowBoundary
)
from mirgecom.eos import IdealSingleGas, PyrometheusMixture
from mirgecom.transport import SimpleTransport
from mirgecom.gas_model import GasModel, make_fluid_state
class SingleLevelFilter(logging.Filter):
def __init__(self, passlevel, reject):
self.passlevel = passlevel
self.reject = reject
def filter(self, record):
if self.reject:
return (record.levelno != self.passlevel)
else:
return (record.levelno == self.passlevel)
class MyRuntimeError(RuntimeError):
"""Simple exception to kill the simulation."""
pass
def get_mesh(dim, read_mesh=True):
"""Get the mesh."""
from meshmode.mesh.io import read_gmsh
mesh_filename = "data/isolator.msh"
#mesh = read_gmsh(mesh_filename, force_ambient_dim=dim)
mesh = partial(read_gmsh, filename=mesh_filename, force_ambient_dim=dim)
#mesh = read_gmsh(mesh_filename)
return mesh
def getIsentropicPressure(mach, P0, gamma):
pressure = (1. + (gamma - 1.)*0.5*mach**2)
pressure = P0*pressure**(-gamma / (gamma - 1.))
return pressure
def getIsentropicTemperature(mach, T0, gamma):
temperature = (1. + (gamma - 1.)*0.5*mach**2)
temperature = T0/temperature
return temperature
def getMachFromAreaRatio(area_ratio, gamma, mach_guess=0.01):
error = 1.0e-8
nextError = 1.0e8
g = gamma
M0 = mach_guess
while nextError > error:
R = (((2/(g + 1) + ((g - 1)/(g + 1)*M0*M0))**(((g + 1)/(2*g - 2))))/M0
- area_ratio)
dRdM = (2*((2/(g + 1) + ((g - 1)/(g + 1)*M0*M0))**(((g + 1)/(2*g - 2))))
/ (2*g - 2)*(g - 1)/(2/(g + 1) + ((g - 1)/(g + 1)*M0*M0)) -
((2/(g + 1) + ((g - 1)/(g + 1)*M0*M0))**(((g + 1)/(2*g - 2))))
* M0**(-2))
M1 = M0 - R/dRdM
nextError = abs(R)
M0 = M1
return M1
class InitACTII:
r"""Solution initializer for flow in the ACT-II facility
This initializer creates a physics-consistent flow solution
given the top and bottom geometry profiles and an EOS using isentropic
flow relations.
The flow is initialized from the inlet stagnations pressure, P0, and
stagnation temperature T0.
geometry locations are linearly interpolated between given data points
.. automethod:: __init__
.. automethod:: __call__
"""
def __init__(
self, *, dim=2, nspecies=0,
P0, T0, temp_wall, temp_sigma, vel_sigma, gamma_guess,
mass_frac=None,
inj_pres, inj_temp, inj_vel, inj_mass_frac=None,
inj_gamma_guess,
inj_temp_sigma, inj_vel_sigma,
inj_ytop, inj_ybottom,
inj_mach
):
r"""Initialize mixture parameters.
Parameters
----------
dim: int
specifies the number of dimensions for the solution
P0: float
stagnation pressure
T0: float
stagnation temperature
gamma_guess: float
guesstimate for gamma
temp_wall: float
wall temperature
temp_sigma: float
near-wall temperature relaxation parameter
vel_sigma: float
near-wall velocity relaxation parameter
geom_top: numpy.ndarray
coordinates for the top wall
geom_bottom: numpy.ndarray
coordinates for the bottom wall
"""
# check number of points in the geometry
#top_size = geom_top.size
#bottom_size = geom_bottom.size
if mass_frac is None:
if nspecies > 0:
mass_frac = np.zeros(shape=(nspecies,))
if inj_mass_frac is None:
if nspecies > 0:
inj_mass_frac = np.zeros(shape=(nspecies,))
if inj_vel is None:
inj_vel = np.zeros(shape=(dim,))
self._dim = dim
self._nspecies = nspecies
self._P0 = P0
self._T0 = T0
self._temp_wall = temp_wall
self._temp_sigma = temp_sigma
self._vel_sigma = vel_sigma
self._gamma_guess = gamma_guess
# TODO, calculate these from the geometry files
self._throat_height = 3.61909e-3
self._x_throat = 0.283718298
self._mass_frac = mass_frac
self._inj_P0 = inj_pres
self._inj_T0 = inj_temp
self._inj_vel = inj_vel
self._inj_gamma_guess = inj_gamma_guess
self._temp_sigma_injection = inj_temp_sigma
self._vel_sigma_injection = inj_vel_sigma
self._inj_mass_frac = inj_mass_frac
self._inj_ytop = inj_ytop
self._inj_ybottom = inj_ybottom
self._inj_mach = inj_mach
def __call__(self, discr, x_vec, eos, *, time=0.0):
"""Create the solution state at locations *x_vec*.
Parameters
----------
x_vec: numpy.ndarray
Coordinates at which solution is desired
eos:
Mixture-compatible equation-of-state object must provide
these functions:
`eos.get_density`
`eos.get_internal_energy`
time: float
Time at which solution is desired. The location is (optionally)
dependent on time
"""
if x_vec.shape != (self._dim,):
raise ValueError(f"Position vector has unexpected dimensionality,"
f" expected {self._dim}.")
xpos = x_vec[0]
ypos = x_vec[1]
if self._dim == 3:
zpos = x_vec[2]
actx = xpos.array_context
zeros = 0*xpos
ones = zeros + 1.0
# initialize the bulk to P0, T0, and quiescent
pressure = ones*self._P0
temperature = ones*self._T0
y = ones*self._mass_frac
mass = eos.get_density(pressure=pressure, temperature=temperature,
species_mass_fractions=y)
energy = mass*eos.get_internal_energy(temperature=temperature,
species_mass_fractions=y)
velocity = ones*np.zeros(self._dim, dtype=object)
mom = mass*velocity
# fuel stream initialization
# initially in pressure/temperature equilibrium with the cavity
#inj_left = 0.71
# even with the bottom corner
inj_left = 0.70163
# even with the top corner
#inj_left = 0.7074
#inj_left = 0.65
inj_right = 0.73
inj_top = -0.0226
inj_bottom = -0.025
inj_fore = 0.01/2. + 1.59e-3
inj_aft = 0.01/2. - 1.59e-3
xc_left = zeros + inj_left
xc_right = zeros + inj_right
yc_top = zeros + inj_top
yc_bottom = zeros + inj_bottom
zc_fore = zeros + inj_fore
zc_aft = zeros + inj_aft
yc_center = zeros - 0.0283245 + 4e-3 + 1.59e-3/2.
zc_center = zeros + 0.01/2.
inj_radius = 1.59e-3/2.
#inj_bl_thickness = inj_radius/3.
inj_bl_thickness = -1000
if self._dim == 2:
radius = actx.np.sqrt((ypos - yc_center)**2)
else:
radius = actx.np.sqrt((ypos - yc_center)**2 + (zpos - zc_center)**2)
left_edge = actx.np.greater(xpos, xc_left)
right_edge = actx.np.less(xpos, xc_right)
bottom_edge = actx.np.greater(ypos, yc_bottom)
top_edge = actx.np.less(ypos, yc_top)
aft_edge = ones
fore_edge = ones
if self._dim == 3:
aft_edge = actx.np.greater(zpos, zc_aft)
fore_edge = actx.np.less(zpos, zc_fore)
inside_injector = (left_edge*right_edge*top_edge*bottom_edge *
aft_edge*fore_edge)
inj_y = ones*self._inj_mass_frac
inj_velocity = zeros*np.zeros(self._dim, dtype=object)
inj_velocity[0] = self._inj_vel[0]
inj_mach = self._inj_mach*ones
# smooth out the injection profile
# relax to the cavity temperature/pressure/velocity
inj_x0 = 0.712
#inj_x0 = 100
# the entrace to the injector
#inj_fuel_x0 = 0.7085
#inj_fuel_x0 = 0.705
# back inside the injector
# behind the shock
#inj_fuel_x0 = inj_x0 + 0.002
# infront of the shock
#inj_fuel_x0 = inj_x0 - 0.002
inj_fuel_x0 = 0.712 - 0.002
inj_sigma = 1500
inj_sigma_y = 10000
#gamma_guess_inj = gamma
# left extent
inj_tanh = inj_sigma*(inj_fuel_x0 - xpos)
inj_weight = 0.5*(1.0 - actx.np.tanh(inj_tanh))
for i in range(self._nspecies):
inj_y[i] = y[i] + (inj_y[i] - y[i])*inj_weight
# transition the fuel from 1 at the centerline to 0 at the injector boundary
# radial extent
inj_tanh = inj_sigma_y*(radius - (inj_radius-inj_bl_thickness))
inj_weight = 0.5*(1.0 - actx.np.tanh(inj_tanh))
for i in range(self._nspecies):
inj_y[i] = y[i] + (inj_y[i] - y[i])*inj_weight
# transition the mach number from 0 (cavity) to 1 (injection)
inj_tanh = inj_sigma*(inj_x0 - xpos)
inj_weight = 0.5*(1.0 - actx.np.tanh(inj_tanh))
inj_mach = inj_weight*inj_mach
# assume a smooth transition in gamma, could calculate it
inj_gamma = (self._gamma_guess +
(self._inj_gamma_guess - self._gamma_guess)*inj_weight)
inj_pressure = getIsentropicPressure(
mach=inj_mach,
P0=self._inj_P0,
gamma=inj_gamma
)
inj_temperature = getIsentropicTemperature(
mach=inj_mach,
T0=self._inj_T0,
gamma=inj_gamma
)
inj_mass = eos.get_density(pressure=inj_pressure,
temperature=inj_temperature,
species_mass_fractions=inj_y)
inj_energy = inj_mass*eos.get_internal_energy(temperature=inj_temperature,
species_mass_fractions=inj_y)
inj_velocity = zeros*np.zeros(self._dim, dtype=object)
inj_mom = inj_mass*inj_velocity
# the velocity magnitude
inj_cv = make_conserved(dim=self._dim, mass=inj_mass, momentum=inj_mom,
energy=inj_energy, species_mass=inj_mass*inj_y)
inj_velocity[0] = -inj_mach*eos.sound_speed(inj_cv, inj_temperature)
# relax the pressure at the cavity/injector interface
inj_pressure = pressure + (inj_pressure - pressure)*inj_weight
inj_temperature = (temperature +
(inj_temperature - temperature)*inj_weight)
# we need to calculate the velocity from a prescribed mass flow rate
# this will need to take into account the velocity relaxation at the
# injector walls
#inj_velocity[0] = velocity[0] + (self._inj_vel[0] - velocity[0])*inj_weight
# modify the temperature in the near wall region to match the
# isothermal boundaries
sigma = self._temp_sigma_injection
wall_temperature = self._temp_wall
smoothing_radius = actx.np.tanh(sigma*(actx.np.abs(radius - inj_radius)))
inj_temperature = (wall_temperature +
(inj_temperature - wall_temperature)*smoothing_radius)
inj_mass = eos.get_density(pressure=inj_pressure,
temperature=inj_temperature,
species_mass_fractions=inj_y)
inj_energy = inj_mass*eos.get_internal_energy(temperature=inj_temperature,
species_mass_fractions=inj_y)
# modify the velocity in the near-wall region to have a tanh profile
# this approximates the BL velocity profile
sigma = self._vel_sigma_injection
smoothing_radius = actx.np.tanh(sigma*(actx.np.abs(radius - inj_radius)))
inj_velocity[0] = inj_velocity[0]*smoothing_radius
for i in range(self._nspecies):
y[i] = actx.np.where(inside_injector, inj_y[i], y[i])
#y[i] = inj_y[i]
# recompute the mass and energy (outside the injector) to account for
# the change in mass fraction
mass = eos.get_density(pressure=pressure,
temperature=temperature,
species_mass_fractions=y)
energy = mass*eos.get_internal_energy(temperature=temperature,
species_mass_fractions=y)
mass = actx.np.where(inside_injector, inj_mass, mass)
velocity[0] = actx.np.where(inside_injector, inj_velocity[0], velocity[0])
energy = actx.np.where(inside_injector, inj_energy, energy)
mom = mass*velocity
energy = (energy + np.dot(mom, mom)/(2.0*mass))
return make_conserved(
dim=self._dim,
mass=mass,
momentum=mom,
energy=energy,
species_mass=mass*y
)
@mpi_entry_point
def main(ctx_factory=cl.create_some_context,
restart_filename=None, target_filename=None,
use_profiling=False, use_logmgr=True, user_input_file=None,
use_overintegration=False, actx_class=None, lazy=False, casename=None):
if actx_class is None:
raise RuntimeError("Array context class missing.")
# control log messages
logger = logging.getLogger(__name__)
logger.propagate = False
if (logger.hasHandlers()):
logger.handlers.clear()
# send info level messages to stdout
h1 = logging.StreamHandler(sys.stdout)
f1 = SingleLevelFilter(logging.INFO, False)
h1.addFilter(f1)
logger.addHandler(h1)
# send everything else to stderr
h2 = logging.StreamHandler(sys.stderr)
f2 = SingleLevelFilter(logging.INFO, True)
h2.addFilter(f2)
logger.addHandler(h2)
cl_ctx = ctx_factory()
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
nparts = comm.Get_size()
from mirgecom.simutil import global_reduce as _global_reduce
global_reduce = partial(_global_reduce, comm=comm)
if casename is None:
casename = "mirgecom"
# logging and profiling
log_path = "log_data/"
logname = log_path + casename + ".sqlite"
if rank == 0:
import os
log_dir = os.path.dirname(logname)
if log_dir and not os.path.exists(log_dir):
os.makedirs(log_dir)
logmgr = initialize_logmgr(use_logmgr,
filename=logname, mode="wo", mpi_comm=comm)
if use_profiling:
queue = cl.CommandQueue(cl_ctx,
properties=cl.command_queue_properties.PROFILING_ENABLE)
else:
queue = cl.CommandQueue(cl_ctx)
# main array context for the simulation
if lazy:
actx = actx_class(comm, queue,
allocator=cl_tools.MemoryPool(cl_tools.ImmediateAllocator(queue)),
mpi_base_tag=12000)
else:
actx = actx_class(comm, queue,
allocator=cl_tools.MemoryPool(cl_tools.ImmediateAllocator(queue)),
force_device_scalars=True)
# default i/o junk frequencies
nviz = 500
nhealth = 1
nrestart = 5000
nstatus = 1
# verbosity for what gets written to viz dumps, increase for more stuff
viz_level = 1
# control the time interval for writing viz dumps
viz_interval_type = 0
# default timestepping control
integrator = "rk4"
current_dt = 1e-8
t_final = 1e-6
t_viz_interval = 1.e-7
current_t = 0
t_start = 0
current_step = 0
current_cfl = 0.5
constant_cfl = False
last_viz_interval = 0
# default health status bounds
health_pres_min = 1.0e-1
health_pres_max = 2.0e6
health_temp_min = 1.0
health_temp_max = 4000
health_mass_frac_min = -10
health_mass_frac_max = 10
# discretization and model control
order = 1
alpha_sc = 0.3
s0_sc = -5.0
kappa_sc = 0.5
dim = 2
# material properties
mu = 1.0e-5
spec_diff = 1e-4
mu_override = False # optionally read in from input
nspecies = 0
pyro_temp_iter = 3 # for pyrometheus, number of newton iterations
pyro_temp_tol = 1.e-4 # for pyrometheus, toleranace for temperature residual
# rhs control
#use_sponge = False
use_av = True
use_combustion = True
# ACTII flow properties
total_pres_inflow = 5000
total_temp_inflow = 300
# injection flow properties
total_pres_inj = 50400
total_temp_inj = 300.0
mach_inj = 1.0
# parameters to adjust the shape of the initialization
#vel_sigma = 2000
#temp_sigma = 2500
vel_sigma = 1000
temp_sigma = 1250
# adjusted to match the mass flow rate
vel_sigma_inj = 5000
temp_sigma_inj = 5000
temp_wall = 300
if user_input_file:
input_data = None
if rank == 0:
with open(user_input_file) as f:
input_data = yaml.load(f, Loader=yaml.FullLoader)
input_data = comm.bcast(input_data, root=0)
try:
nviz = int(input_data["nviz"])
except KeyError:
pass
try:
t_viz_interval = float(input_data["t_viz_interval"])
except KeyError:
pass
try:
viz_interval_type = int(input_data["viz_interval_type"])
except KeyError:
pass
try:
nrestart = int(input_data["nrestart"])
except KeyError:
pass
try:
nhealth = int(input_data["nhealth"])
except KeyError:
pass
try:
nstatus = int(input_data["nstatus"])
except KeyError:
pass
try:
constant_cfl = int(input_data["constant_cfl"])
except KeyError:
pass
try:
current_dt = float(input_data["current_dt"])
except KeyError:
pass
try:
current_cfl = float(input_data["current_cfl"])
except KeyError:
pass
try:
t_final = float(input_data["t_final"])
except KeyError:
pass
try:
alpha_sc = float(input_data["alpha_sc"])
except KeyError:
pass
try:
kappa_sc = float(input_data["kappa_sc"])
except KeyError:
pass
try:
s0_sc = float(input_data["s0_sc"])
except KeyError:
pass
try:
mu_input = float(input_data["mu"])
mu_override = True
except KeyError:
pass
try:
spec_diff = float(input_data["spec_diff"])
except KeyError:
pass
try:
nspecies = int(input_data["nspecies"])
except KeyError:
pass
try:
pyro_temp_iter = int(input_data["pyro_temp_iter"])
except KeyError:
pass
try:
pyro_temp_tol = float(input_data["pyro_temp_tol"])
except KeyError:
pass
try:
order = int(input_data["order"])
except KeyError:
pass
try:
dim = int(input_data["dimen"])
except KeyError:
pass
try:
total_pres_inj = float(input_data["total_pres_inj"])
except KeyError:
pass
try:
total_temp_inj = float(input_data["total_temp_inj"])
except KeyError:
pass
try:
mach_inj = float(input_data["mach_inj"])
except KeyError:
pass
try:
integrator = input_data["integrator"]
except KeyError:
pass
try:
health_pres_min = float(input_data["health_pres_min"])
except KeyError:
pass
try:
health_pres_max = float(input_data["health_pres_max"])
except KeyError:
pass
try:
health_temp_min = float(input_data["health_temp_min"])
except KeyError:
pass
try:
health_temp_max = float(input_data["health_temp_max"])
except KeyError:
pass
try:
health_mass_frac_min = float(input_data["health_mass_frac_min"])
except KeyError:
pass
try:
health_mass_frac_max = float(input_data["health_mass_frac_max"])
except KeyError:
pass
try:
vel_sigma = float(input_data["vel_sigma"])
except KeyError:
pass
try:
temp_sigma = float(input_data["temp_sigma"])
except KeyError:
pass
try:
vel_sigma_inj = float(input_data["vel_sigma_inj"])
except KeyError:
pass
try:
temp_sigma_inj = float(input_data["temp_sigma_inj"])
except KeyError:
pass
try:
viz_level = int(input_data["viz_level"])
except KeyError:
pass
#try:
#use_sponge = bool(input_data["use_sponge"])
#except KeyError:
#pass
try:
use_av = bool(input_data["use_av"])
except KeyError:
pass
try:
use_combustion = bool(input_data["use_combustion"])
except KeyError:
pass
# param sanity check
allowed_integrators = ["rk4", "euler", "lsrk54", "lsrk144"]
if integrator not in allowed_integrators:
error_message = "Invalid time integrator: {}".format(integrator)
raise RuntimeError(error_message)
if viz_interval_type > 2:
error_message = "Invalid value for viz_interval_type [0-2]"
raise RuntimeError(error_message)
s0_sc = np.log10(1.0e-4 / np.power(order, 4))
if rank == 0:
print(f"Shock capturing parameters: alpha {alpha_sc}, "
f"s0 {s0_sc}, kappa {kappa_sc}")
if rank == 0:
print("\n#### Simluation control data: ####")
print(f"\tnrestart = {nrestart}")
print(f"\tnhealth = {nhealth}")
print(f"\tnstatus = {nstatus}")
if constant_cfl == 1:
print(f"\tConstant cfl mode, current_cfl = {current_cfl}")
else:
print(f"\tConstant dt mode, current_dt = {current_dt}")
print(f"\tt_final = {t_final}")
print(f"\torder = {order}")
print(f"\tdimen = {dim}")
print(f"\tTime integration {integrator}")
print("#### Simluation control data: ####")
if rank == 0:
print("\n#### Visualization setup: ####")
if viz_level >= 0:
print("\tBasic visualization output enabled.")
print("\t(cv, dv, cfl)")
if viz_level >= 1:
print("\tExtra visualization output enabled for derived quantities.")
print("\t(velocity, mass_fractions, etc.)")
if viz_level >= 2:
print("\tNon-dimensional parameter visualization output enabled.")
print("\t(Re, Pr, etc.)")
if viz_level >= 3:
print("\tDebug visualization output enabled.")
print("\t(rhs, grad_cv, etc.)")
if viz_interval_type == 0:
print(f"\tWriting viz data every {nviz} steps.")
if viz_interval_type == 1:
print(f"\tWriting viz data roughly every {t_viz_interval} seconds.")
if viz_interval_type == 2:
print(f"\tWriting viz data exactly every {t_viz_interval} seconds.")
print("#### Visualization setup: ####")
if rank == 0:
print("\n#### Simluation setup data: ####")
print(f"\ttotal_pres_injection = {total_pres_inj}")
print(f"\ttotal_temp_injection = {total_temp_inj}")
print(f"\tvel_sigma = {vel_sigma}")
print(f"\ttemp_sigma = {temp_sigma}")
print(f"\tvel_sigma_injection = {vel_sigma_inj}")
print(f"\ttemp_sigma_injection = {temp_sigma_inj}")
print("#### Simluation setup data: ####")
timestepper = rk4_step
if integrator == "euler":
timestepper = euler_step
if integrator == "lsrk54":
timestepper = lsrk54_step
if integrator == "lsrk144":
timestepper = lsrk144_step
# }}}
# working gas: O2/N2 #
# O2 mass fraction 0.273
# gamma = 1.4
# cp = 37.135 J/mol-K,
# rho= 1.977 kg/m^3 @298K
gamma = 1.4
mw_o2 = 15.999*2
mw_n2 = 14.0067*2
mf_o2 = 0.273
# viscosity @ 400C, Pa-s
mu_o2 = 3.76e-5
mu_n2 = 3.19e-5
mu_mix = mu_o2*mf_o2 + mu_n2*(1-mu_o2) # 3.3456e-5
mw = mw_o2*mf_o2 + mw_n2*(1.0 - mf_o2)
r = 8314.59/mw
cp = r*gamma/(gamma - 1)
Pr = 0.75
mf_c2h4 = 0.5
mf_h2 = 0.5
if mu_override:
mu = mu_input
else:
mu = mu_mix
# thermal conductivity
kappa = cp*mu/Pr
init_temperature = 300.0
# Turn off combustion unless EOS supports it
if nspecies < 3:
use_combustion = False
if rank == 0:
print("\n#### Simluation material properties: ####")
print(f"\tmu = {mu}")
print(f"\tkappa = {kappa}")
print(f"\tPrandtl Number = {Pr}")
print(f"\tnspecies = {nspecies}")
print(f"\tspecies diffusivity = {spec_diff}")
if nspecies == 0:
print("\tno passive scalars, uniform ideal gas eos")
elif nspecies == 2:
print("\tpassive scalars to track air/fuel mixture, ideal gas eos")
else:
print("\tfull multi-species initialization with pyrometheus eos")
#spec_diffusivity = 0. * np.ones(nspecies)
spec_diffusivity = spec_diff * np.ones(nspecies)
transport_model = SimpleTransport(viscosity=mu, thermal_conductivity=kappa,
species_diffusivity=spec_diffusivity)
#
# isentropic expansion based on the area ratios between the inlet (r=54e-3m) and
# the throat (r=3.167e-3)
#
vel_injection = np.zeros(shape=(dim,))
# make the eos
if nspecies < 3:
eos = IdealSingleGas(gamma=gamma, gas_const=r)
else:
from mirgecom.thermochemistry import get_pyrometheus_wrapper_class
from mirgecom.mechanisms.uiuc import Thermochemistry
pyro_mech = get_pyrometheus_wrapper_class(
pyro_class=Thermochemistry, temperature_niter=pyro_temp_iter)(actx.np)
eos = PyrometheusMixture(pyro_mech, temperature_guess=init_temperature)
species_names = pyro_mech.species_names
gas_model = GasModel(eos=eos, transport=transport_model)
# initialize eos and species mass fractions
y = np.zeros(nspecies)
y_fuel = np.zeros(nspecies)
if nspecies == 2:
y[0] = 1
y_fuel[1] = 1
species_names = ["air", "fuel"]
elif nspecies > 2:
# find name species indicies
for i in range(nspecies):
if species_names[i] == "C2H4":
i_c2h4 = i
if species_names[i] == "H2":
i_h2 = i
if species_names[i] == "O2":
i_ox = i
if species_names[i] == "N2":
i_di = i
# Set the species mass fractions to the free-stream flow
y[i_ox] = mf_o2
y[i_di] = 1. - mf_o2
# Set the species mass fractions to the free-stream flow
y_fuel[i_c2h4] = mf_c2h4
y_fuel[i_h2] = mf_h2
# injection mach number
if nspecies < 3:
gamma_inj = gamma
else:
gamma_inj = 0.5*(1.24 + 1.4)
pres_injection = getIsentropicPressure(mach=mach_inj,
P0=total_pres_inj,
gamma=gamma_inj)
temp_injection = getIsentropicTemperature(mach=mach_inj,
T0=total_temp_inj,
gamma=gamma_inj)
if nspecies < 3:
rho_injection = pres_injection/temp_injection/r
sos = math.sqrt(gamma*pres_injection/rho_injection)
else:
rho_injection = pyro_mech.get_density(p=pres_injection,
temperature=temp_injection,
mass_fractions=y)
gamma_loc = (pyro_mech.get_mixture_specific_heat_cp_mass(temp_injection, y) /
pyro_mech.get_mixture_specific_heat_cv_mass(temp_injection, y))
sos = math.sqrt(gamma_loc*pres_injection/rho_injection)
if rank == 0:
print(f"injection gamma guess {gamma_inj} pyro gamma {gamma_loc}")
vel_injection[0] = -mach_inj*sos
if rank == 0:
print("")
print(f"\tinjector Mach number {mach_inj}")
print(f"\tinjector temperature {temp_injection}")
print(f"\tinjector pressure {pres_injection}")
print(f"\tinjector rho {rho_injection}")
print(f"\tinjector velocity {vel_injection[0]}")
print("#### Simluation initialization data: ####\n")
inj_ymin = -0.0243245
inj_ymax = -0.0227345
bulk_init = InitACTII(dim=dim,
P0=total_pres_inflow, T0=total_temp_inflow,
temp_wall=temp_wall, temp_sigma=temp_sigma,
vel_sigma=vel_sigma, nspecies=nspecies,
mass_frac=y, gamma_guess=gamma, inj_gamma_guess=gamma_inj,
inj_pres=total_pres_inj,
inj_temp=total_temp_inj,
inj_vel=vel_injection, inj_mass_frac=y_fuel,
inj_temp_sigma=temp_sigma_inj,
inj_vel_sigma=vel_sigma_inj,
inj_ytop=inj_ymax, inj_ybottom=inj_ymin,
inj_mach=mach_inj)
viz_path = "viz_data/"
vizname = viz_path + casename
restart_path = "restart_data/"
restart_pattern = (
restart_path + "{cname}-{step:06d}-{rank:04d}.pkl"
)
if restart_filename: # read the grid from restart data
restart_filename = f"{restart_filename}-{rank:04d}.pkl"
from mirgecom.restart import read_restart_data
restart_data = read_restart_data(actx, restart_filename)
current_step = restart_data["step"]
current_t = restart_data["t"]
last_viz_interval = restart_data["last_viz_interval"]
t_start = current_t
local_mesh = restart_data["local_mesh"]
local_nelements = local_mesh.nelements
global_nelements = restart_data["global_nelements"]
restart_order = int(restart_data["order"])
# will use this later
#restart_nspecies = int(restart_data["nspecies"])
assert restart_data["num_parts"] == nparts
assert restart_data["nspecies"] == nspecies
else:
local_mesh, global_nelements = generate_and_distribute_mesh(
comm, get_mesh(dim=dim))
local_nelements = local_mesh.nelements
if target_filename: # read the grid from restart data
target_filename = f"{target_filename}-{rank:04d}.pkl"
from mirgecom.restart import read_restart_data
target_data = read_restart_data(actx, target_filename)
target_order = int(target_data["order"])