-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathisolator_injection_run.py
1953 lines (1652 loc) · 71 KB
/
isolator_injection_run.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
"""Simulation driver for the Y2 Isolator case."""
__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 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.discretization import create_discretization_collection
from meshmode.mesh import BTAG_ALL, BTAG_NONE # noqa
from grudge.shortcuts import make_visualizer
from grudge.dof_desc import BoundaryDomainTag
#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,
logmgr_add_device_memory_usage,
)
from mirgecom.navierstokes import ns_operator
from mirgecom.artificial_viscosity import \
av_laplacian_operator, smoothness_indicator
from mirgecom.simutil import (
check_step,
write_visfile,
check_naninf_local,
check_range_local,
get_sim_timestep,
force_evaluation
)
from mirgecom.restart import write_restart_file
from mirgecom.io import make_init_message
from mirgecom.mpi import mpi_entry_point
from mirgecom.integrators import (rk4_step, lsrk54_step, lsrk144_step,
euler_step)
from mirgecom.inviscid import (inviscid_facial_flux_rusanov,
inviscid_facial_flux_hll)
from grudge.shortcuts import compiled_lsrk45_step
from mirgecom.steppers import advance_state
from mirgecom.boundary import (
PrescribedFluidBoundary,
IsothermalWallBoundary,
DummyBoundary,
SymmetryBoundary
)
from mirgecom.eos import IdealSingleGas, PyrometheusMixture
from mirgecom.transport import (SimpleTransport,
PowerLawTransport,
ArtificialViscosityTransport,
ArtificialViscosityTransportDiv)
from mirgecom.gas_model import GasModel, make_fluid_state
from mirgecom.fluid import make_conserved
from mirgecom.limiter import bound_preserving_limiter
from mirgecom.gas_model import make_operator_fluid_states
from mirgecom.navierstokes import grad_cv_operator
#from dataclasses import replace
class SingleLevelFilter(logging.Filter):
"""Filter I/O."""
def __init__(self, passlevel, reject):
"""Initialize the I/O filter."""
self.passlevel = passlevel
self.reject = reject
def filter(self, record):
"""Filter it."""
if self.reject:
return (record.levelno != self.passlevel)
else:
return (record.levelno == self.passlevel)
class MyRuntimeError(RuntimeError):
"""Simple exception to kill the simulation."""
pass
class HeatSource:
r"""Deposit energy from an ignition source."
Internal energy is deposited as a gaussian of the form:
.. math::
e &= e + e_{a}\exp^{(1-r^{2})}\\
Density if modified to keep pressure constant, according to the eos
.. automethod:: __init__
.. automethod:: __call__
"""
def __init__(self, *, dim, center=None, width=1.0,
amplitude=0., amplitude_func=None):
r"""Initialize the spark parameters.
Parameters
----------
center: numpy.ndarray
center of source
amplitude: float
source strength modifier
amplitude_fun: function
variation of amplitude with time
"""
if center is None:
center = np.zeros(shape=(dim,))
self._center = center
self._dim = dim
self._amplitude = amplitude
self._width = width
self._amplitude_func = amplitude_func
def __call__(self, x_vec, state, eos, time, **kwargs):
"""
Create the energy deposition at time *t* and location *x_vec*.
the source at time *t* is created by evaluting the gaussian
with time-dependent amplitude at *t*.
If modify density is true, only adjust the temperature. Pressure
is maintained by adjusting the density.
Parameters
----------
cv: :class:`mirgecom.fluid.ConservedVars`
Fluid conserved quantities
time: float
Current time at which the solution is desired
x_vec: numpy.ndarray
Nodal coordinates
"""
t = time
if self._amplitude_func is not None:
amplitude = self._amplitude*self._amplitude_func(t)
else:
amplitude = self._amplitude
loc = self._center
# coordinates relative to lump center
rel_center = make_obj_array(
[x_vec[i] - loc[i] for i in range(self._dim)]
)
actx = x_vec[0].array_context
r = actx.np.sqrt(np.dot(rel_center, rel_center))
expterm = amplitude * actx.np.exp(-(r**2)/(2*self._width*self._width))
# elevate the local temperature
temperature = state.temperature + expterm
pressure = state.pressure
y = state.species_mass_fractions
# density of this new state
new_mass = eos.get_density(pressure=pressure, temperature=temperature,
species_mass_fractions=y)
# change the density so the pressure stays constant
mass_source = new_mass - state.mass_density
# keep the velocity constant
momentum_source = state.velocity*mass_source
# keep the mass fractions constant
species_mass_source = state.species_mass_fractions*mass_source
# the source term that keeps the energy constant having changed the mass
energy_source = 0.5*np.dot(state.velocity, state.velocity)*mass_source
return make_conserved(dim=self._dim, mass=mass_source,
energy=energy_source,
momentum=momentum_source,
species_mass=species_mass_source)
class SparkSource:
r"""Deposit energy from an ignition source."
Internal energy is deposited as a gaussian of the form:
.. math::
e &= e + e_{a}\exp^{(1-r^{2})}\\
.. automethod:: __init__
.. automethod:: __call__
"""
def __init__(self, *, dim, center=None, width=1.0,
amplitude=0., amplitude_func=None):
r"""Initialize the spark parameters.
Parameters
----------
center: numpy.ndarray
center of source
amplitude: float
source strength modifier
amplitude_fun: function
variation of amplitude with time
"""
if center is None:
center = np.zeros(shape=(dim,))
self._center = center
self._dim = dim
self._amplitude = amplitude
self._width = width
self._amplitude_func = amplitude_func
def __call__(self, x_vec, state, eos, time, **kwargs):
"""
Create the energy deposition at time *t* and location *x_vec*.
the source at time *t* is created by evaluting the gaussian
with time-dependent amplitude at *t*.
If modify density is true, only adjust the temperature. Pressure
is maintained by adjusting the density.
Parameters
----------
state: :class:`mirgecom.GasModle.FluidState`
Fluid state
time: float
Current time at which the solution is desired
x_vec: numpy.ndarray
Nodal coordinates
"""
t = time
if self._amplitude_func is not None:
amplitude = self._amplitude*self._amplitude_func(t)
else:
amplitude = self._amplitude
loc = self._center
# coordinates relative to lump center
rel_center = make_obj_array(
[x_vec[i] - loc[i] for i in range(self._dim)]
)
actx = x_vec[0].array_context
r = actx.np.sqrt(np.dot(rel_center, rel_center))
expterm = amplitude * actx.np.exp(-(r**2)/(2*self._width*self._width))
mass = 0.*state.mass_density
momentum = 0.*state.momentum_density
species_mass = 0.*state.species_mass_density
energy = state.energy_density + state.mass_density*expterm
return make_conserved(dim=self._dim, mass=mass, energy=energy,
momentum=momentum, species_mass=species_mass)
class InitSponge:
r"""Initialize sponge.
.. automethod:: __init__
.. automethod:: __call__
"""
def __init__(self, *, x0, thickness, amplitude):
r"""Initialize the sponge parameters.
Parameters
----------
x0: float
sponge starting x location
thickness: float
sponge extent
amplitude: float
sponge strength modifier
"""
self._x0 = x0
self._thickness = thickness
self._amplitude = amplitude
def __call__(self, x_vec, *, time=0.0):
"""Create the sponge intensity at locations *x_vec*.
Parameters
----------
x_vec: numpy.ndarray
Coordinates at which solution is desired
time: float
Time at which solution is desired. The strength is (optionally)
dependent on time
"""
xpos = x_vec[0]
actx = xpos.array_context
zeros = 0*xpos
x0 = zeros + self._x0
return self._amplitude * actx.np.where(
actx.np.greater(xpos, x0),
(zeros + ((xpos - self._x0)/self._thickness) *
((xpos - self._x0)/self._thickness)),
zeros + 0.0
)
@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=False, casename=None,
lazy=False):
"""Drive the isolator case."""
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)
comm.Barrier()
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
from mirgecom.simutil import get_reasonable_memory_pool
alloc = get_reasonable_memory_pool(cl_ctx, queue)
if lazy:
actx = actx_class(comm, queue, mpi_base_tag=12000, allocator=alloc)
else:
actx = actx_class(comm, queue, allocator=alloc, force_device_scalars=True)
# default i/o junk frequencies
nviz = 500
nhealth = 1
nrestart = 5000
nstatus = 1
nlimit = 0
# default timestepping control
integrator = "rk4"
current_dt = 1e-8
t_final = 1e-7
current_t = 0
current_step = 0
current_cfl = 1.0
constant_cfl = False
force_eval = True
# default health status bounds
health_pres_min = 1.0e-1
health_pres_max = 2.0e6
health_temp_min = 1.0
health_temp_max = 5000
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
inv_num_flux = "rusanov"
# 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
transport_type = 0
# rhs control
use_ignition = 0
use_sponge = True
use_combustion = True
# artificial viscosity control
# 0 - none
# 1 - laplacian diffusion
# 2 - physical viscosity based, rho indicator
# 3 - physical viscosity based, div(velocity) indicator
use_av = 0
sponge_sigma = 1.0
vel_sigma_inj = 5000
# initialize the ignition spark
spark_center = np.zeros(shape=(dim,))
spark_init_loc_x = 0.677
spark_init_loc_y = -0.021
if dim == 3:
spark_center[2] = 0.035/2.
spark_diameter = 0.0025
spark_strength = 20000000.
spark_init_time = 999999999.
spark_duration = 1.e-8
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:
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:
nlimit = int(input_data["nlimit"])
except KeyError:
pass
try:
current_dt = float(input_data["current_dt"])
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:
transport_type = int(input_data["transport"])
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:
integrator = input_data["integrator"]
except KeyError:
pass
try:
inv_num_flux = input_data["inviscid_numerical_flux"]
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:
use_ignition = int(input_data["use_ignition"])
except KeyError:
pass
try:
spark_init_time = float(input_data["ignition_init_time"])
except KeyError:
pass
try:
spark_strength = float(input_data["ignition_strength"])
except KeyError:
pass
try:
spark_duration = float(input_data["ignition_duration"])
except KeyError:
pass
try:
spark_diameter = float(input_data["ignition_diameter"])
except KeyError:
pass
try:
spark_init_loc_x = float(input_data["ignition_loc_x"])
except KeyError:
pass
try:
spark_init_loc_y = float(input_data["ignition_loc_y"])
except KeyError:
pass
try:
use_sponge = bool(input_data["use_sponge"])
except KeyError:
pass
try:
sponge_sigma = float(input_data["sponge_sigma"])
except KeyError:
pass
try:
use_av = int(input_data["use_av"])
except KeyError:
pass
try:
use_combustion = bool(input_data["use_combustion"])
except KeyError:
pass
try:
vel_sigma_inj = float(input_data["vel_sigma_inj"])
except KeyError:
pass
# param sanity check
allowed_integrators = ["rk4", "euler", "lsrk54", "lsrk144", "compiled_lsrk54"]
if integrator not in allowed_integrators:
error_message = "Invalid time integrator: {}".format(integrator)
raise RuntimeError(error_message)
allowed_inv_num_flux = ["rusanov", "hll"]
if inv_num_flux not in allowed_inv_num_flux:
error_message = "Invalid inviscid flux function: {}".format(inv_num_flux)
raise RuntimeError(error_message)
if integrator == "compiled_lsrk54":
print("Setting force_eval = False for pre-compiled time integration")
force_eval = False
s0_sc = np.log10(1.0e-4 / np.power(order, 4))
# use_av=3 specific parameters
# flow stagnation temperature
static_temp = 2076.43
# steepness of the smoothed function
theta_sc = 100
# cutoff, smoothness below this value is ignored
beta_sc = 0.01
gamma_sc = 1.5
if rank == 0:
if use_av == 0:
print("Artificial viscosity disabled")
elif use_av == 1:
print("Artificial viscosity using laplacian diffusion")
print(f"Shock capturing parameters: alpha {alpha_sc}, "
f"s0 {s0_sc}, kappa {kappa_sc}")
elif use_av == 2:
print("Artificial viscosity using modified physical viscosity")
print(f"Shock capturing parameters: alpha {alpha_sc}, "
f"s0 {s0_sc}, Pr 0.75")
elif use_av == 3:
print("Artificial viscosity using modified physical viscosity")
print("Using velocity divergence indicator")
print(f"Shock capturing parameters: alpha {alpha_sc}, "
f"gamma_sc {gamma_sc}"
f"theta_sc {theta_sc}, beta_sc {beta_sc}, Pr 0.75, "
f"stagnation temperature {static_temp}")
if rank == 0:
print("\n#### Simluation control data: ####")
print(f"\tnviz = {nviz}")
print(f"\tnrestart = {nrestart}")
print(f"\tnhealth = {nhealth}")
print(f"\tnstatus = {nstatus}")
print(f"\tcurrent_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: ####\n")
spark_center[0] = spark_init_loc_x
spark_center[1] = spark_init_loc_y
if rank == 0:
print("\n#### Ignition control parameters ####")
print(f"spark center ({spark_center[0]},{spark_center[1]})")
print(f"spark FWHM {spark_diameter}")
print(f"spark strength {spark_strength}")
print(f"ignition time {spark_init_time}")
print(f"ignition duration {spark_duration}")
print("#### Ignition control parameters ####\n")
if use_ignition == 1:
print("spark ignition")
elif use_ignition == 2:
print("heat source ignition")
def _compiled_stepper_wrapper(state, t, dt, rhs):
return compiled_lsrk45_step(actx, state, t, dt, rhs)
timestepper = rk4_step
if integrator == "euler":
timestepper = euler_step
if integrator == "lsrk54":
timestepper = lsrk54_step
if integrator == "lsrk144":
timestepper = lsrk144_step
if integrator == "compiled_lsrk54":
timestepper = _compiled_stepper_wrapper
if inv_num_flux == "rusanov":
inviscid_numerical_flux_func = inviscid_facial_flux_rusanov
if inv_num_flux == "hll":
inviscid_numerical_flux_func = inviscid_facial_flux_hll
# }}}
# 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
if mu_override:
mu = mu_input
else:
mu = mu_mix
kappa = cp*mu/Pr
init_temperature = 300.0
# don't allow limiting on flows without species
if nspecies == 0:
nlimit = 0
limit_species = False
if nlimit > 0:
species_limit_sigma = 1./nlimit/current_dt
limit_species = True
else:
species_limit_sigma = 0.
# Turn off combustion unless EOS supports it
if nspecies < 3:
use_combustion = False
if rank == 0:
print("\n#### Simluation material properties: ####")
print(f"\tPrandtl Number = {Pr}")
print(f"\tnspecies = {nspecies}")
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")
if nlimit > 0:
print(f"\tSpecies mass fractions limited to [0:1] over {nlimit} steps")
transport_alpha = 0.6
transport_beta = 4.093e-7
transport_sigma = 2.0
transport_n = 0.666
if transport_type == 0:
print("\t Simple transport model:")
print("\t\t constant viscosity, species diffusivity")
print(f"\tmu = {mu}")
print(f"\tkappa = {kappa}")
print(f"\tspecies diffusivity = {spec_diff}")
elif transport_type == 1:
print("\t Power law transport model:")
print("\t\t temperature dependent viscosity, species diffusivity")
print(f"\ttransport_alpha = {transport_alpha}")
print(f"\ttransport_beta = {transport_beta}")
print(f"\ttransport_sigma = {transport_sigma}")
print(f"\ttransport_n = {transport_n}")
print(f"\tspecies diffusivity = {spec_diff}")
elif transport_type == 2:
print("\t Pyrometheus transport model:")
print("\t\t temperature/mass fraction dependence")
else:
error_message = "Unknown transport_type {}".format(transport_type)
raise RuntimeError(error_message)
spec_diffusivity = spec_diff * np.ones(nspecies)
if transport_type == 0:
physical_transport_model = SimpleTransport(
viscosity=mu, thermal_conductivity=kappa,
species_diffusivity=spec_diffusivity)
if transport_type == 1:
physical_transport_model = PowerLawTransport(
alpha=transport_alpha, beta=transport_beta,
sigma=transport_sigma, n=transport_n,
species_diffusivity=spec_diffusivity)
if use_av == 0 or use_av == 1:
transport_model = physical_transport_model
elif use_av == 2:
transport_model = ArtificialViscosityTransport(
physical_transport=physical_transport_model,
av_mu=alpha_sc, av_prandtl=0.75)
elif use_av == 3:
transport_model = ArtificialViscosityTransportDiv(
physical_transport=physical_transport_model,
av_mu=alpha_sc, av_prandtl=0.75)
chem_source_tol = 1.e-10
# make the eos
if nspecies < 3:
eos = IdealSingleGas(gamma=gamma, gas_const=r)
species_names = ["air", "fuel"]
else:
from mirgecom.thermochemistry import get_pyrometheus_wrapper_class
from uiuc import Thermochemistry
pyro_mech = get_pyrometheus_wrapper_class(
pyro_class=Thermochemistry, temperature_niter=pyro_temp_iter,
zero_level=chem_source_tol)(actx.np)
eos = PyrometheusMixture(pyro_mech, temperature_guess=init_temperature)
species_names = pyro_mech.species_names
# find name species indicies
for i in range(nspecies):
if species_names[i] == "H2":
i_h2 = i
"""
if species_names[i] == "C2H4":
i_c2h4 = i
if species_names[i] == "O2":
i_ox = i
if species_names[i] == "N2":
i_di = i
"""
transport_alpha = 0.6
transport_beta = 4.093e-7
transport_sigma = 2.0
transport_n = 0.666
transport_lewis = np.ones(nspecies)
if nspecies > 3:
transport_lewis[i_h2] = 0.2
if rank == 0:
if transport_type == 0:
print("\t Simple transport model:")
print("\t\t constant viscosity, species diffusivity")
print(f"\tmu = {mu}")
print(f"\tkappa = {kappa}")
print(f"\tspecies diffusivity = {spec_diff}")
elif transport_type == 1:
print("\t Power law transport model:")
print("\t\t temperature dependent viscosity, species diffusivity")
print(f"\ttransport_alpha = {transport_alpha}")
print(f"\ttransport_beta = {transport_beta}")
print(f"\ttransport_sigma = {transport_sigma}")
print(f"\ttransport_n = {transport_n}")
print(f"\tLewis Number = {transport_lewis}")
elif transport_type == 2:
print("\t Pyrometheus transport model:")
print("\t\t temperature/mass fraction dependence")
else:
error_message = "Unknown transport_type {}".format(transport_type)
raise RuntimeError(error_message)
spec_diffusivity = spec_diff * np.ones(nspecies)
if transport_type == 0:
physical_transport_model = SimpleTransport(
viscosity=mu, thermal_conductivity=kappa,
species_diffusivity=spec_diffusivity)
if transport_type == 1:
physical_transport_model = PowerLawTransport(
alpha=transport_alpha, beta=transport_beta,
sigma=transport_sigma, n=transport_n,
species_diffusivity=spec_diffusivity,
lewis=transport_lewis)
if use_av == 0 or use_av == 1:
transport_model = physical_transport_model
elif use_av == 2:
transport_model = ArtificialViscosityTransport(
physical_transport=physical_transport_model,
av_mu=alpha_sc, av_prandtl=0.75)
elif use_av == 3:
transport_model = ArtificialViscosityTransportDiv(
physical_transport=physical_transport_model,
av_mu=alpha_sc, av_prandtl=0.75)
gas_model = GasModel(eos=eos, transport=transport_model)
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"]
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:
error_message = "Driver only supports restart. Start with -r <filename>"
raise RuntimeError(error_message)
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"])
# will use this later
assert restart_data["num_parts"] == nparts
assert restart_data["nspecies"] == nspecies
assert restart_data["global_nelements"] == target_data["global_nelements"]
else:
logger.warning("No target file specied, using restart as target")
if rank == 0:
logging.info("Making discretization")
dcoll = create_discretization_collection(
actx, volume_meshes=local_mesh, order=order)
from grudge.dof_desc import DISCR_TAG_QUAD
if use_overintegration:
quadrature_tag = DISCR_TAG_QUAD
else:
quadrature_tag = None
if rank == 0:
logging.info("Done making discretization")
vis_timer = None
if logmgr:
logmgr_add_cl_device_info(logmgr, queue)
logmgr_add_device_memory_usage(logmgr, queue)
logmgr.add_watches([
("step.max", "step = {value}, "),
("t_sim.max", "sim time: {value:1.6e} s, "),
("t_step.max", "step walltime: {value:6g} s")
#("t_log.max", "log walltime: {value:6g} s")
])
try:
logmgr.add_watches(["memory_usage_python.max"])
#logmgr.add_watches(["memory_usage_python.max",
# "memory: {value:6g} MByte"])
except KeyError:
pass
try:
logmgr.add_watches(["memory_usage_gpu.max"])
except KeyError:
pass
if use_profiling:
logmgr.add_watches(["pyopencl_array_time.max"])
vis_timer = IntervalTimer("t_vis", "Time spent visualizing")
logmgr.add_quantity(vis_timer)
if rank == 0:
logging.info("Before restart/init")
def get_fluid_state(cv, temperature_seed, smoothness=None):