-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombustor.py
1877 lines (1590 loc) · 67.9 KB
/
combustor.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 pyopencl as cl
import numpy.linalg as la # noqa
import pyopencl.array as cla # noqa
import math
from pytools.obj_array import make_obj_array
from functools import partial
from meshmode.array_context import (
PyOpenCLArrayContext,
SingleGridWorkBalancingPytatoArrayContext as PytatoPyOpenCLArrayContext
#PytatoPyOpenCLArrayContext
)
from mirgecom.profiling import PyOpenCLProfilingArrayContext
from arraycontext import thaw, freeze, flatten, unflatten, to_numpy, from_numpy
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,
set_sim_state
)
from mirgecom.navierstokes import ns_operator
from mirgecom.artificial_viscosity import (
av_laplacian_operator,
smoothness_indicator
)
from mirgecom.simutil import (
check_step,
generate_and_distribute_mesh,
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.fluid import make_conserved
from mirgecom.steppers import advance_state
from mirgecom.boundary import (
PrescribedFluidBoundary,
IsothermalNoSlipBoundary,
)
import cantera
from mirgecom.eos import 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)
h1 = logging.StreamHandler(sys.stdout)
f1 = SingleLevelFilter(logging.INFO, False)
h1.addFilter(f1)
root_logger = logging.getLogger()
root_logger.addHandler(h1)
h2 = logging.StreamHandler(sys.stderr)
f2 = SingleLevelFilter(logging.INFO, True)
h2.addFilter(f2)
root_logger.addHandler(h2)
logger = logging.getLogger(__name__)
#logger = logging.getLogger("my.logger")
logger.setLevel(logging.DEBUG)
#logger.debug("A DEBUG message")
#logger.info("An INFO message")
#logger.warning("A WARNING message")
#logger.error("An ERROR message")
#logger.critical("A CRITICAL message")
class MyRuntimeError(RuntimeError):
"""Simple exception to kill the simulation."""
pass
def get_mesh(read_mesh=True):
"""Get the mesh."""
from meshmode.mesh.io import read_gmsh
mesh_filename = "data/combustor.msh"
mesh = read_gmsh(mesh_filename, force_ambient_dim=2)
return mesh
def sponge(cv, cv_ref, sigma):
return sigma*(cv_ref - cv)
class InitSponge:
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, *, 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
)
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
def get_y_from_x(x, data):
"""
Return the linearly interpolated the value of y
from the value in data(x,y) at x
"""
if x <= data[0][0]:
y = data[0][1]
elif x >= data[-1][0]:
y = data[-1][1]
else:
ileft = 0
iright = data.shape[0]-1
# find the bracketing points, simple subdivision search
while iright - ileft > 1:
ind = int(ileft+(iright - ileft)/2)
if x < data[ind][0]:
iright = ind
else:
ileft = ind
leftx = data[ileft][0]
rightx = data[iright][0]
lefty = data[ileft][1]
righty = data[iright][1]
dx = rightx - leftx
dy = righty - lefty
y = lefty + (x - leftx)*dy/dx
return y
def get_theta_from_data(data):
"""
Calculate theta = arctan(dy/dx)
Where data[][0] = x and data[][1] = y
"""
theta = data.copy()
for index in range(1, theta.shape[0]-1):
#print(f"index {index}")
theta[index][1] = np.arctan((data[index+1][1]-data[index-1][1]) /
(data[index+1][0]-data[index-1][0]))
theta[0][1] = np.arctan(data[1][1]-data[0][1])/(data[1][0]-data[0][0])
theta[-1][1] = np.arctan(data[-1][1]-data[-2][1])/(data[-1][0]-data[-2][0])
return(theta)
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, geom_top, geom_bottom,
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
):
r"""Initialize mixture parameters.
Parameters
----------
dim: int
specifies the number of dimensions for the solution
nspecies: int
specifies the number of mixture species
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
mass_frac: numpy.ndarray
specifies the mass fraction for each species
"""
# 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._geom_top = geom_top
self._geom_bottom = geom_bottom
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
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]
ytop = 0*x_vec[0]
actx = xpos.array_context
ones = (1.0 + x_vec[0]) - x_vec[0]
xpos_flat = to_numpy(flatten(xpos, actx), actx)
ypos_flat = to_numpy(flatten(ypos, actx), actx)
gamma_guess = self._gamma_guess
#gas_const = eos.gas_const()
ytop_flat = 0*xpos_flat
ybottom_flat = 0*xpos_flat
theta_top_flat = 0*xpos_flat
theta_bottom_flat = 0*xpos_flat
mach_flat = 0*xpos_flat
theta_flat = 0*xpos_flat
throat_height = 1
theta_geom_top = get_theta_from_data(self._geom_top)
theta_geom_bottom = get_theta_from_data(self._geom_bottom)
for inode in range(xpos_flat.size):
ytop_flat[inode] = get_y_from_x(xpos_flat[inode], self._geom_top)
ybottom_flat[inode] = get_y_from_x(xpos_flat[inode], self._geom_bottom)
theta_top_flat[inode] = get_y_from_x(xpos_flat[inode], theta_geom_top)
theta_bottom_flat[inode] = get_y_from_x(xpos_flat[inode],
theta_geom_bottom)
#if ytop_flat[inode] - ybottom_flat[inode] < throat_height:
# throat_height = ytop_flat[inode] - ybottom_flat[inode]
# throat_loc = xpos_flat[inode]
throat_height = self._throat_height
throat_loc = 0.
#print(f"throat height {throat_height}")
for inode in range(xpos_flat.size):
area_ratio = (ytop_flat[inode] - ybottom_flat[inode])/throat_height
theta_flat[inode] = (theta_bottom_flat[inode] +
(theta_top_flat[inode]-theta_bottom_flat[inode]) /
(ytop_flat[inode]-ybottom_flat[inode]) *
(ypos_flat[inode] - ybottom_flat[inode]))
if xpos_flat[inode] < throat_loc:
mach_flat[inode] = getMachFromAreaRatio(area_ratio=area_ratio,
gamma=gamma_guess,
mach_guess=0.01)
elif xpos_flat[inode] > throat_loc:
mach_flat[inode] = getMachFromAreaRatio(area_ratio=area_ratio,
gamma=gamma_guess,
mach_guess=1.01)
else:
mach_flat[inode] = 1.0
ytop = unflatten(xpos, from_numpy(ytop_flat, actx), actx)
ybottom = unflatten(xpos, from_numpy(ybottom_flat, actx), actx)
mach = unflatten(xpos, from_numpy(mach_flat, actx), actx)
theta = unflatten(xpos, from_numpy(theta_flat, actx), actx)
pressure = getIsentropicPressure(
mach=mach,
P0=self._P0,
gamma=gamma_guess
)
temperature = getIsentropicTemperature(
mach=mach,
T0=self._T0,
gamma=gamma_guess
)
# modify the temperature in the near wall region to match the
# isothermal boundaries
sigma = self._temp_sigma
wall_temperature = self._temp_wall
smoothing_top = actx.np.tanh(sigma*(actx.np.abs(ypos-ytop)))
smoothing_bottom = actx.np.tanh(sigma*(actx.np.abs(ypos-ybottom)))
temperature = (wall_temperature +
(temperature - wall_temperature)*smoothing_top*smoothing_bottom)
#print(f"pressure {pressure}")
#print(f"temperature {temperature}")
y = make_obj_array([self._mass_frac[i] * ones
for i in range(self._nspecies)])
#print(f"y {y}")
mass = eos.get_density(pressure, temperature, y)
velocity = mach*np.zeros(self._dim, dtype=object)
mom = mass*velocity
energy = mass*eos.get_internal_energy(temperature, y)
#print(f"energy {energy}")
# the velocity magnitude
cv = make_conserved(dim=self._dim, mass=mass, momentum=mom, energy=energy,
species_mass=mass*y)
#sos = eos.sound_speed(cv)
#print(f"sos {sos}")
velocity[0] = mach*eos.sound_speed(cv, temperature)
# modify the velocity in the near-wall region to have a tanh profile
# this approximates the BL velocity profile
sigma = self._vel_sigma
smoothing_top = actx.np.tanh(sigma*(actx.np.abs(ypos-ytop)))
smoothing_bottom = actx.np.tanh(sigma*(actx.np.abs(ypos-ybottom)))
velocity[0] = velocity[0]*smoothing_top*smoothing_bottom
# split into x and y components
velocity[1] = velocity[0]*actx.np.sin(theta)
velocity[0] = velocity[0]*actx.np.cos(theta)
# zero out the velocity in the cavity region, let the flow develop naturally
# initially in pressure/temperature equilibrium with the exterior flow
zeros = 0*xpos
xc_left = zeros + 0.65163 - 0.000001
xc_right = zeros + 0.72163 + 0.000001
yc_top = zeros - 0.0083245
left_edge = actx.np.greater(xpos, xc_left)
right_edge = actx.np.less(xpos, xc_right)
top_edge = actx.np.less(ypos, yc_top)
inside_cavity = left_edge*right_edge*top_edge
velocity[0] = actx.np.where(inside_cavity, zeros, velocity[0])
# fuel stream initialization
# initially in pressure/temperature equilibrium with the cavity
#inj_left = 0.71
inj_left = 0.7074
#inj_left = 0.65
inj_right = 0.73
inj_top = -0.0226
inj_bottom = -0.025
xc_left = zeros + inj_left
xc_right = zeros + inj_right
yc_top = zeros + inj_top
yc_bottom = zeros + inj_bottom
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)
inside_injector = left_edge*right_edge*top_edge*bottom_edge
inj_y = make_obj_array([self._inj_mass_frac[i] * ones
for i in range(self._nspecies)])
inj_velocity = mach*np.zeros(self._dim, dtype=object)
inj_velocity[0] = self._inj_vel[0]
inj_mach = mach*0. + 1.0
# smooth out the injection profile
# relax to the cavity temperature/pressure/velocity
inj_x0 = 0.712
#inj_fuel_x0 = 0.717
inj_fuel_x0 = 0.7
inj_fuel_y0 = -0.0243245 - 3.e-3
inj_fuel_y1 = -0.0227345 + 3.e-3
inj_sigma = 1500
gamma_guess_inj = self._inj_gamma_guess
# seperate the fuel from the flow, allow the fuel to spill out into the
# cavity ahead of hte injection flow, see if this helps startup
# 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
# bottom extent
inj_tanh = inj_sigma*(inj_fuel_y0 - ypos)
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
# top extent
inj_tanh = inj_sigma*(ypos - inj_fuel_y1)
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
inj_tanh = inj_sigma*(inj_x0 - xpos)
inj_weight = 0.5*(1.0 - actx.np.tanh(inj_tanh))
# transition the mach number from 0 (cavitiy) to 1 (injection)
# assume a smooth transition in gamma, could calculate it
inj_mach = inj_weight
inj_gamma = gamma_guess + (gamma_guess_inj - 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(inj_pressure, inj_temperature, inj_y)
inj_velocity = mach*np.zeros(self._dim, dtype=object)
inj_mom = inj_mass*inj_velocity
inj_energy = inj_mass*eos.get_internal_energy(inj_temperature, inj_y)
#print(f"energy {energy}")
# 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)
#sos = eos.sound_speed(cv)
#print(f"sos {sos}")
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_top = actx.np.tanh(sigma*(actx.np.abs(ypos-self._inj_ytop)))
smoothing_bottom = actx.np.tanh(sigma*(actx.np.abs(ypos-self._inj_ybottom)))
inj_temperature = (wall_temperature +
(inj_temperature - wall_temperature)*smoothing_top*smoothing_bottom)
# compute the density and then energy from the pressure/temperature state
inj_mass = eos.get_density(inj_pressure, inj_temperature, inj_y)
inj_energy = inj_mass*eos.get_internal_energy(inj_temperature, 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_top = actx.np.tanh(sigma*(actx.np.abs(ypos-self._inj_ytop)))
smoothing_bottom = actx.np.tanh(sigma*(actx.np.abs(ypos-self._inj_ybottom)))
inj_velocity[0] = inj_velocity[0]*smoothing_top*smoothing_bottom
# use the species field with fuel added everywhere
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, temperature, y)
energy = mass*eos.get_internal_energy(temperature, 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
)
class UniformModified:
r"""Solution initializer for a uniform flow with boundary layer smoothing.
Similar to the Uniform initializer, except the velocity profile is modified
so that the velocity goes to zero at y(min, max)
The smoothing comes from a hyperbolic tangent with weight sigma
.. automethod:: __init__
.. automethod:: __call__
"""
def __init__(
self, *, dim=1, nspecies=0, pressure=1.0, temperature=2.5,
velocity=None, mass_fracs=None,
temp_wall, temp_sigma, vel_sigma,
ymin=0., ymax=1.0
):
r"""Initialize uniform flow parameters.
Parameters
----------
dim: int
specify the number of dimensions for the flow
nspecies: int
specify the number of species in the flow
temperature: float
specifies the temperature
pressure: float
specifies the pressure
velocity: numpy.ndarray
specifies the flow velocity
temp_wall: float
wall temperature
temp_sigma: float
near-wall temperature relaxation parameter
vel_sigma: float
near-wall velocity relaxation parameter
ymin: flaot
minimum y-coordinate for smoothing
ymax: float
maximum y-coordinate for smoothing
"""
if velocity is not None:
numvel = len(velocity)
myvel = velocity
if numvel > dim:
dim = numvel
elif numvel < dim:
myvel = np.zeros(shape=(dim,))
for i in range(numvel):
myvel[i] = velocity[i]
self._velocity = myvel
else:
self._velocity = np.zeros(shape=(dim,))
if mass_fracs is not None:
self._nspecies = len(mass_fracs)
self._mass_fracs = mass_fracs
else:
self._nspecies = nspecies
self._mass_fracs = np.zeros(shape=(nspecies,))
if self._velocity.shape != (dim,):
raise ValueError(f"Expected {dim}-dimensional inputs.")
self._pressure = pressure
self._temperature = temperature
self._dim = dim
self._temp_wall = temp_wall
self._temp_sigma = temp_sigma
self._vel_sigma = vel_sigma
self._ymin = ymin
self._ymax = ymax
def __call__(self, x_vec, *, eos, **kwargs):
"""
Create a uniform flow solution at locations *x_vec*.
Parameters
----------
x_vec: numpy.ndarray
Nodal coordinates
eos: :class:`mirgecom.eos.IdealSingleGas`
Equation of state class with method to supply gas *gamma*.
"""
ypos = x_vec[1]
actx = ypos.array_context
ymax = 0.0*x_vec[1] + self._ymax
ymin = 0.0*x_vec[1] + self._ymin
ones = (1.0 + x_vec[0]) - x_vec[0]
pressure = self._pressure * ones
temperature = self._temperature * ones
#print(f"{self._pressure}")
#print(f"{self._temperature}")
# modify the temperature in the near wall region to match
# the isothermal boundaries
sigma = self._temp_sigma
wall_temperature = self._temp_wall
smoothing_min = actx.np.tanh(sigma*(actx.np.abs(ypos-ymin)))
smoothing_max = actx.np.tanh(sigma*(actx.np.abs(ypos-ymax)))
temperature = (wall_temperature +
(temperature - wall_temperature)*smoothing_min*smoothing_max)
velocity = make_obj_array([self._velocity[i] * ones
for i in range(self._dim)])
y = make_obj_array([self._mass_fracs[i] * ones
for i in range(self._nspecies)])
if self._nspecies:
mass = eos.get_density(pressure, temperature, y)
else:
mass = pressure/temperature/eos.gas_const()
specmass = mass * y
#print(f"{mass}")
sigma = self._vel_sigma
# modify the velocity profile from uniform
smoothing_max = actx.np.tanh(sigma*(actx.np.abs(ypos-ymax)))
smoothing_min = actx.np.tanh(sigma*(actx.np.abs(ypos-ymin)))
velocity[0] = velocity[0]*smoothing_max*smoothing_min
mom = mass*velocity
if self._nspecies:
internal_energy = mass*eos.get_internal_energy(temperature, y)
else:
internal_energy = pressure/(eos.gamma() - 1)
kinetic_energy = 0.5 * np.dot(mom, mom)/mass
energy = internal_energy + kinetic_energy
return make_conserved(dim=self._dim, mass=mass, energy=energy,
momentum=mom, species_mass=specmass)
@mpi_entry_point
def main(ctx_factory=cl.create_some_context, restart_filename=None,
use_profiling=False, use_logmgr=True, user_input_file=None,
actx_class=PyOpenCLArrayContext, casename=None):
"""Drive the Y0 example."""
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
logmgr = initialize_logmgr(use_logmgr,
filename=f"{casename}.sqlite", 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
actx = actx_class(
queue,
allocator=cl_tools.MemoryPool(cl_tools.ImmediateAllocator(queue)))
# an array context for things that just can't lazy
init_actx = PyOpenCLArrayContext(queue,
allocator=cl_tools.MemoryPool(cl_tools.ImmediateAllocator(queue)))
# default i/o junk frequencies
nviz = 500
nhealth = 1
nrestart = 5000
nstatus = 1
# 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
# 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 = -1.0e-6
health_mass_frac_max = 1.0 + 1.e-6
# discretization and model control
order = 1
alpha_sc = 0.3
s0_sc = -5.0
kappa_sc = 0.5
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:
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:
order = int(input_data["order"])
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
# 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)
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"\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"\tTime integration {integrator}")
print("#### Simluation control data: ####\n")
if rank == 0:
print("\n#### Simluation health check data: ####")
print(f"\tPressure min = {health_pres_min}")
print(f"\tPressure max = {health_pres_max}")
print(f"\tTemperature min = {health_temp_min}")
print(f"\tTemperature max = {health_temp_max}")
print(f"\tMass fraction min = {health_mass_frac_min}")
print(f"\tMass fraction max = {health_mass_frac_max}")
print("#### Simluation health check data: ####\n")
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
mf_n2 = 1.0 - 0.273
mf_c2h4 = 0.5
mf_h2 = 0.5
#mw = mw_o2*mf_o2 + mw_n2*(1.0 - mf_o2)
#r = 8314.59/mw
#
# nozzle inflow #
#
# stagnation tempertuare 2076.43 K
# stagnation pressure 2.745e5 Pa
#