/
DriverInsert.py
1293 lines (1206 loc) · 56.8 KB
/
DriverInsert.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 is a code for using StanShock to get driver insert profile
# Things that need to be inputed:
# Mixture, Mixture properties: dirver and driven section mixture compositions, X4 and X1, and the corresponding .xml file for cantera
# Thermal, Thermodynamic properties: T5, p5, p1, gamma1, gamma4, W4, W1
# Sim, Simulation conditions: discretization sizes (nXCoarse, nXFine), tFinal, tTest
# Geometry, Shock tube geometries: driver and driven section length and diameter
import sys; sys.path.append('../')
from stanShock import dSFdx, stanShock, smoothingFunction
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
import time
import cantera as ct
from scipy.optimize import newton
from scipy.interpolate import interp1d
class InsertOpt:
def __init__(self, Mixture, Thermal, Sim, Geometry, plot = True, saveData = False, GUI = False):
self.Mixture = Mixture
self.Thermal = Thermal
self.Sim = Sim
self.Geometry = Geometry
self.plot = plot
self.saveData = saveData
self.GUI = GUI
# see if backfill option is specified, if not, set to default no backfill
try:
self.Sim['Backfill']
except:
self.Sim['Backfill'] = False
# see if CRV option is specified, if not, set default to no CRV
try:
self.Sim['CRV']
except:
self.Sim['CRV'] = False
def GetInsert(self):
# input thermodynamic and shock tube parameters
fontsize = 12
tFinal = self.Sim['tFinal']
try:
self.Thermal['p5']
have_p5 = True
p5, p1 = self.Thermal['p5'], self.Thermal['p1']
T5 = self.Thermal['T5']
# define driver and driven gases
mech = self.Mixture['mechanism']
gas1 = ct.Solution(mech)
gas4 = ct.Solution(mech)
gas1.X = self.Mixture['X1']
gas4.X = self.Mixture['X4']
# calculate mean molecular weight of driver and driven mixtures
W4 = gas4.mean_molecular_weight
W1 = gas1.mean_molecular_weight
# print([W4, W1])
# calculate specific heat ratios
g4 = gas4.cp / gas4.cv
g1 = gas1.cp / gas1.cv
MachReduction = 0.985 # account for shock wave attenuation
# compute gas dynamics
def res(Ms1):
return p5 / p1 - ((2.0 * g1 * Ms1 ** 2.0 - (g1 - 1.0)) / (g1 + 1.0)) \
* ((-2.0 * (g1 - 1.0) + Ms1 ** 2.0 * (3.0 * g1 - 1.0)) / (2.0 + Ms1 ** 2.0 * (g1 - 1.0)))
Ms1 = newton(res, 2.0)
Ms1 *= MachReduction
T5oT1 = (2.0 * (g1 - 1.0) * Ms1 ** 2.0 + 3.0 - g1) \
* ((3.0 * g1 - 1.0) * Ms1 ** 2.0 - 2.0 * (g1 - 1.0)) \
/ ((g1 + 1.0) ** 2.0 * Ms1 ** 2.0)
T1 = T5 / T5oT1
a1oa4 = np.sqrt(W4 / W1)
p4op1 = (1.0 + 2.0 * g1 / (g1 + 1.0) * (Ms1 ** 2.0 - 1.0)) \
* (1.0 - (g4 - 1.0) / (g4 + 1.0) * a1oa4 * (Ms1 - 1.0 / Ms1)) ** (-2.0 * g4 / (g4 - 1.0))
p4 = p1 * p4op1
except:
# if T5, p5 and p1 are not defined, expect T1, p4 and p1 inputs
T1 = self.Thermal['T1']
p4 = self.Thermal['p4']
p1 = self.Thermal['p1']
mech = self.Mixture['mechanism']
gas1 = ct.Solution(mech)
gas4 = ct.Solution(mech)
have_p5 = False
nXCoarse, nXFine = self.Sim['nXCoarse'], self.Sim['nXFine'] # mesh resolution
LDriver, LDriven = self.Geometry['LDriver'], self.Geometry['LDriven']
DDriver, DDriven = self.Geometry['DDriver'], self.Geometry['DDriven']
plt.close("all")
mpl.rcParams['font.size'] = fontsize
plt.rc('text', usetex=False)
# setup geometry
xLower = -LDriver
xUpper = LDriven
xShock = 0.0
Delta = 10 * (xUpper - xLower) / float(nXFine)
geometry = (nXCoarse, xLower, xUpper, xShock)
DInner = lambda x: np.zeros_like(x)
dDInnerdx = lambda x: np.zeros_like(x)
def DOuter(x): return smoothingFunction(x, xShock, Delta, DDriver, DDriven)
def dDOuterdx(x): return dSFdx(x, xShock, Delta, DDriver, DDriven)
A = lambda x: np.pi / 4.0 * (DOuter(x) ** 2.0 - DInner(x) ** 2.0)
dAdx = lambda x: np.pi / 2.0 * (DOuter(x) * dDOuterdx(x) - DInner(x) * dDInnerdx(x))
dlnAdx = lambda x, t: dAdx(x) / A(x)
# set up the gasses
u1 = 0.0
u4 = 0.0 # initially 0 velocity
T4 = T1 # assumed
gas1.TPX = T1, p1, self.Mixture['X1']
gas4.TPX = T4, p4, self.Mixture['X4']
if self.Sim['CRV']:
try:
# define buffer gas composition
xBuffer = self.Mixture['XBuffer']
# define fraction of buffer section in driven section
frac_buffer = self.Geometry['BufferFraction']
# define buffer gas
gasBuffer = ct.Solution(mech)
gasBuffer.TPX = T4, p1, xBuffer
except:
raise Exception('Buffer gas not defined!!!')
# set up solver parameter
boundaryConditions = ['reflecting', 'reflecting']
state1 = (gas1, u1)
state4 = (gas4, u4)
# setup conditions for compressibility correction
try:
# if no values of multipliers are defined, set the values to 1
self.Sim['alpha']
except:
self.Sim['alpha'] = 1
self.Sim['beta'] = 1
self.Sim['D_mul'] = 1
ss = stanShock(gas1, initializeRiemannProblem=(state4, state1, geometry),
boundaryConditions=boundaryConditions,
cfl=.9,
outputEvery=100,
includeBoundaryLayerTerms=True,
Tw=T1, # assume wall temperature is in thermal eq. with gas
alpha=self.Sim['alpha'],
beta=self.Sim['beta'],
D_mul=self.Sim['D_mul'],
DOuter=DOuter,
dlnAdx=dlnAdx)
# implement backfill if called for
if self.Sim['Backfill']:
try:
# unpack backfill gas composition
xBackfill = self.Mixture['XBackfill']
# define backfill location
LBackfill = self.Geometry['LBackfill']
# define back fill gas stage by stage
for stage in range(0, len(xBackfill)):
gasBackfill = ct.Solution(mech)
gasBackfill.TPX = T4, p4, xBackfill[stage]
l_backfill = LBackfill[stage]
ss.applyDriverBackfill(gasBackfill, l_backfill)
except:
raise Exception('Backfill gas mixture not defined!!!')
# implement CRV if called for
if self.Sim['CRV']:
ss.applyTestGasBuffer(gasBuffer, buffer_fraction=frac_buffer)
# solve
t0 = time.clock()
tTest = self.Sim['tTest']
try: self.Sim['tradeoff']
except: self.Sim['tradeoff'] = 1
tradeoffParam = self.Sim['tradeoff']
eps = 0.01 ** 2.0 + tradeoffParam * 0.01 ** 2.0
# if a p5 is provided, can optimize around the given p5 value
if have_p5:
ss.optimizeDriverInsert(tFinal, p5=p5, tTest=tTest, tradeoffParam=tradeoffParam, eps=eps, maxIter=100)
else:
ss.optimizeDriverInsert(tFinal, tTest=tTest, tradeoffParam=tradeoffParam, eps=eps, maxIter=100)
t1 = time.clock()
print("The process took ", t1 - t0)
# recalculate at higher resolution with the insert
geometry = (nXFine, xLower, xUpper, xShock)
gas1.TPX = T1, p1, self.Mixture['X1']
gas4.TPX = T4, p4, self.Mixture['X4']
if self.Sim['CRV']:
try:
# define buffer gas composition
xBuffer = self.Mixture['XBuffer']
# define fraction of buffer section in driven section
frac_buffer = self.Geometry['BufferFraction']
# define buffer gas
gasBuffer = ct.Solution(mech)
gasBuffer.TPX = T4, p1, xBuffer
except:
raise Exception('Buffer gas not defined!!!')
ss = stanShock(gas1, initializeRiemannProblem=(state4, state1, geometry),
boundaryConditions=boundaryConditions,
cfl=.9,
outputEvery=100,
includeBoundaryLayerTerms=True,
Tw=T1, # assume wall temperature is in thermal eq. with gas
alpha=self.Sim['alpha'],
beta=self.Sim['beta'],
D_mul=self.Sim['D_mul'],
DOuter=DOuter,
DInner=ss.DInner,
dlnAdx=ss.dlnAdx)
# implement backfill if called for
if self.Sim['Backfill']:
try:
# unpack backfill gas composition
xBackfill = self.Mixture['XBackfill']
# define backfill location
LBackfill = self.Geometry['LBackfill']
# define back fill gas stage by stage
for stage in range(0, len(xBackfill)):
gasBackfill = ct.Solution(mech)
gasBackfill.TPX = T4, p4, xBackfill[stage]
l_backfill = LBackfill[stage]
ss.applyDriverBackfill(gasBackfill, l_backfill)
except:
raise Exception('Backfill gas mixture not defined!!!')
# implement CRV if called for
if self.Sim['CRV']:
ss.applyTestGasBuffer(gasBuffer, buffer_fraction=frac_buffer)
ss.addXTDiagram("p")
ss.addXTDiagram("T")
ss.addProbe(max(ss.x)) # end wall probe
t0 = time.clock()
ss.advanceSimulation(tFinal)
t1 = time.clock()
print("The process took ", t1 - t0)
pInsert = np.array(ss.probes[0].p)
tInsert = np.array(ss.probes[0].t)
rInsert = np.array(ss.probes[0].r)
YInsert = np.array(ss.probes[0].Y)
TInsert = np.array(ss.thermoTable.getTemperature(rInsert, pInsert, YInsert))
# TODO: check out figures here:
if self.plot:
if not self.GUI:
ss.plotXTDiagram(ss.XTDiagrams["t"], limits=[min(TInsert), max(TInsert)])
ss.plotXTDiagram(ss.XTDiagrams["p"], limits=[min(pInsert)/1e5, max(pInsert)/1e5])
if self.plot:
if self.plot:
if self.GUI:
self.figT = ss.plotXTDiagram(ss.XTDiagrams["t"], limits=[min(TInsert), max(TInsert)],
saveData=True, outputFigure=True)
else:
ss.plotXTDiagram(ss.XTDiagrams["t"], limits=[min(TInsert), max(TInsert)], saveData=True)
TMatrix = ss.XTDiagram_variableMatrix
timeXT = ss.XTDiagram_T
positionXT = ss.XTDiagram_X
if self.GUI:
self.figP = ss.plotXTDiagram(ss.XTDiagrams["p"],
limits=[min(pInsert) / 1e5, max(pInsert) / 1e5], saveData=True,
outputFigure=True)
else:
ss.plotXTDiagram(ss.XTDiagrams["p"], limits=[min(pInsert) / 1e5, max(pInsert) / 1e5],
saveData=True)
pMatrix = ss.XTDiagram_variableMatrix
self.TMatrix = TMatrix
self.pMatrix = pMatrix
self.timeXT = timeXT
self.positionXT = positionXT
xInsert = ss.x
DOuterInsert = ss.DOuter(ss.x)
DInnerInsert = ss.DInner(ss.x)*39.3701 # inch
# setup geometry of discrete insert
DIn = ss.DInner(ss.x)
xIn = ss.x
x_step = self.Sim['xStep']
disX = xIn[0:-1:x_step]
disD = DIn[0:-1:x_step]
delta = 1
dx = xIn[1] - xIn[0]
def DInner_discrete(x):
DInner_dis = np.zeros(x.shape)
cnt = 0
for X in x:
if np.sum(X > np.array(disX)) < len(disD):
DInner_dis[cnt] = disD[np.sum(X > np.array(disX))]
cnt = cnt + 1
for d in range(0, int(np.floor(len(x) / x_step)) - 1):
LowBond = int(d * x_step - delta)
UpBond = int(d * x_step + delta)
x_loc = x[LowBond:UpBond]
DInner_dis[LowBond:UpBond] = smoothingFunction(x_loc, disX[d], 2 * delta * dx, disD[d], disD[d + 1])
return DInner_dis
# plt.plot(xIn, DIn)#
# plt.plot(xIn, DInner_discrete(xIn), '.')#%%
# plt.plot(xIn[0:-1:x_step], DIn[0:-1:x_step], 'r.')
#plt.xlim((-2, 0))
def dDInnerdx_dis(x):
dDIndx = np.zeros(x.shape)
for d in range(0, int(np.floor(len(x) / x_step)) - 1):
LowBond = int(d * x_step - delta)
UpBond = int(d * x_step + delta)
x_loc = x[LowBond:UpBond]
dDIndx[LowBond:UpBond] = dSFdx(x_loc, disX[d], 2 * delta * dx, disD[d], disD[d + 1])
return dDIndx
A_dis = lambda x: np.pi / 4.0 * (DOuter(x) ** 2.0 - DInner_discrete(x) ** 2.0)
dAdx_dis = lambda x: np.pi / 2.0 * (DOuter(x) * dDOuterdx(x) - DInner_discrete(x) * dDInnerdx_dis(x))
dlnAdx_dis = lambda x, t: dAdx_dis(x) / A(x)
# recalculate at higher resolution with discrete insert
geometry = (nXFine, xLower, xUpper, xShock)
gas1.TPX = T1, p1, self.Mixture['X1']
gas4.TPX = T4, p4, self.Mixture['X4']
if self.Sim['CRV']:
try:
# define buffer gas composition
xBuffer = self.Mixture['XBuffer']
# define fraction of buffer section in driven section
frac_buffer = self.Geometry['BufferFraction']
# define buffer gas
gasBuffer = ct.Solution(mech)
gasBuffer.TPX = T4, p1, xBuffer
except:
raise Exception('Buffer gas not defined!!!')
ss = stanShock(gas1, initializeRiemannProblem=(state4, state1, geometry),
boundaryConditions=boundaryConditions,
cfl=.9,
outputEvery=100,
includeBoundaryLayerTerms=True,
Tw=T1, # assume wall temperature is in thermal eq. with gas
alpha=self.Sim['alpha'],
beta=self.Sim['beta'],
D_mul=self.Sim['D_mul'],
DOuter=DOuter,
DInner=DInner_discrete,
dlnAdx=dlnAdx_dis)
# implement backfill if called for
if self.Sim['Backfill']:
try:
# unpack backfill gas composition
xBackfill = self.Mixture['XBackfill']
# define backfill location
LBackfill = self.Geometry['LBackfill']
# define back fill gas stage by stage
for stage in range(0, len(xBackfill)):
gasBackfill = ct.Solution(mech)
gasBackfill.TPX = T4, p4, xBackfill[stage]
l_backfill = LBackfill[stage]
ss.applyDriverBackfill(gasBackfill, l_backfill)
except:
raise Exception('Backfill gas mixture not defined!!!')
# implement CRV if called for
if self.Sim['CRV']:
ss.applyTestGasBuffer(gasBuffer, buffer_fraction=frac_buffer)
ss.addXTDiagram("p")
ss.addXTDiagram("T")
ss.addProbe(max(ss.x)) # end wall probe
t0 = time.clock()
ss.advanceSimulation(tFinal)
t1 = time.clock()
print("The process took ", t1 - t0)
pInsert_dis = np.array(ss.probes[0].p)
tInsert_dis = np.array(ss.probes[0].t)
rInsert_dis = np.array(ss.probes[0].r)
YInsert_dis = np.array(ss.probes[0].Y)
TInsert_dis = np.array(ss.thermoTable.getTemperature(rInsert_dis, pInsert_dis, YInsert_dis))
if self.plot:
if not self.GUI:
ss.plotXTDiagram(ss.XTDiagrams["t"], limits=[min(TInsert_dis), max(TInsert_dis)])
ss.plotXTDiagram(ss.XTDiagrams["p"], limits=[min(pInsert_dis)/1e5, max(pInsert_dis)/1e5])
xInsert_dis = ss.x
DOuterInsert_dis = ss.DOuter(ss.x)
DInnerInsert_dis = ss.DInner(ss.x)
# recalculate at higher resolution without the insert
gas1.TPX = T1, p1, self.Mixture['X1']
gas4.TPX = T4, p4, self.Mixture['X4']
if self.Sim['CRV']:
try:
# define buffer gas composition
xBuffer = self.Mixture['XBuffer']
# define fraction of buffer section in driven section
frac_buffer = self.Geometry['BufferFraction']
# define buffer gas
gasBuffer = ct.Solution(mech)
gasBuffer.TPX = T4, p1, xBuffer
except:
raise Exception('Buffer gas not defined!!!')
ss = stanShock(gas1, initializeRiemannProblem=(state4, state1, geometry),
boundaryConditions=boundaryConditions,
cfl=.9,
outputEvery=100,
includeBoundaryLayerTerms=True,
Tw=T1, # assume wall temperature is in thermal eq. with gas
alpha=self.Sim['alpha'],
beta=self.Sim['beta'],
D_mul=self.Sim['D_mul'],
DOuter=DOuter,
dlnAdx=dlnAdx)
# implement backfill if called for
if self.Sim['Backfill']:
try:
# unpack backfill gas composition
xBackfill = self.Mixture['XBackfill']
# define backfill location
LBackfill = self.Geometry['LBackfill']
# define back fill gas stage by stage
for stage in range(0, len(xBackfill)):
gasBackfill = ct.Solution(mech)
gasBackfill.TPX = T4, p4, xBackfill[stage]
l_backfill = LBackfill[stage]
ss.applyDriverBackfill(gasBackfill, l_backfill)
except:
raise Exception('Backfill gas mixture not defined!!!')
# implement CRV if called for
if self.Sim['CRV']:
ss.applyTestGasBuffer(gasBuffer, buffer_fraction=frac_buffer)
ss.addXTDiagram("p")
ss.addXTDiagram("T")
ss.addProbe(max(ss.x)) # end wall probe
t0 = time.clock()
ss.advanceSimulation(tFinal)
t1 = time.clock()
print("The process took ", t1 - t0)
pNoInsert = np.array(ss.probes[0].p)
tNoInsert = np.array(ss.probes[0].t)
rNoInsert = np.array(ss.probes[0].r)
YNoInsert = np.array(ss.probes[0].Y)
TNoInsert = np.array(ss.thermoTable.getTemperature(rNoInsert, pNoInsert, YNoInsert))
if self.plot:
if not self.GUI:
ss.plotXTDiagram(ss.XTDiagrams["t"], limits=[min(TNoInsert), max(TNoInsert)])
ss.plotXTDiagram(ss.XTDiagrams["p"], limits=[min(pNoInsert)/1e5, max(pNoInsert)/1e5])
# plot
if self.plot:
plt.figure()
plt.plot(tNoInsert / 1e-3, pNoInsert / 1e5, 'k', label="$\mathrm{No\ Insert}$")
plt.plot(tInsert / 1e-3, pInsert / 1e5, 'r', label="$\mathrm{Optimized\ Insert}$")
plt.plot(tInsert_dis / 1e-3, pInsert_dis / 1e5, '--b', label="$\mathrm{Dummy\ Discrete\ Insert}$")
plt.xlabel("$t\ [\mathrm{ms}]$")
plt.ylabel("$p\ [\mathrm{bar}]$")
plt.legend(loc="best")
plt.tight_layout()
if self.GUI:
self.figEndWallP = plt.gcf()
plt.close(self.figEndWallP)
plt.figure(figsize=(12, 2))
#plt.axis('equal')
plt.xlim((xLower, 0))
plt.ylim((0, DDriver*39.3701+0.2)) # inch
plt.plot(xInsert, DOuterInsert*39.3701, 'k', label="$D_\mathrm{o}$")
plt.plot(xInsert, DInnerInsert, 'r', label="$D_\mathrm{i}$")
plt.plot(xInsert_dis, DInnerInsert_dis*39.3701, 'b', label="$D_\mathrm{dis}$")
plt.plot([xShock, xShock], [-5 , 5], 'k--')
plt.xlabel("$x\ [\mathrm{m}]$")
plt.ylabel("$D\ [\mathrm{inch}]$")
plt.legend(loc="best")
plt.tight_layout()
if self.GUI:
self.figDriver = plt.gcf()
plt.close(self.figDriver)
self.tNoInsert = tNoInsert
self.pNoInsert = pNoInsert
self.tInsert = tInsert
self.pInsert = pInsert
self.tInsert_dis = tInsert_dis
self.pInsert_dis = pInsert_dis
self.xInsert = xInsert
self.xInsert_dis = xInsert_dis
self.DOuterInsert = DOuterInsert
self.DInnerInsert = DInnerInsert
self.DInnerInsert_dis = DInnerInsert_dis
# save driver insert profiles and pressure traces
if self.saveData:
np.savetxt('tNoInsert.csv', tNoInsert, delimiter=',')
np.savetxt('pNoInsert.csv', pNoInsert, delimiter=',')
np.savetxt('tInsert.csv', tInsert, delimiter=',')
np.savetxt('pInsert.csv', pInsert, delimiter=',')
np.savetxt('tInsert_dis.csv', tInsert_dis, delimiter=',')
np.savetxt('pInsert_dis.csv', pInsert_dis, delimiter=',')
np.savetxt('xInsert.csv', xInsert, delimiter=',')
np.savetxt('xInsert_dis.csv', xInsert_dis, delimiter=',')
np.savetxt('DOuterInsert.csv', DOuterInsert, delimiter=',')
np.savetxt('DInnerInsert.csv', DInnerInsert, delimiter=',')
np.savetxt('DInnerInsert_dis.csv', DInnerInsert_dis, delimiter=',')
####################################################################################################################
def SimulateInsertContinuous(self, DOuterInsert, DInnerInsert, xInsert, x_step):
'''
Method to simulate the shock tube flow given a continuous driver insert profile
'''
# input thermodynamic and shock tube parameters
fontsize = 12
tFinal = self.Sim['tFinal']
try:
self.Thermal['p5']
have_p5 = True
p5, p1 = self.Thermal['p5'], self.Thermal['p1']
T5 = self.Thermal['T5']
# define driver and driven gases
mech = self.Mixture['mechanism']
gas1 = ct.Solution(mech)
gas4 = ct.Solution(mech)
gas1.X = self.Mixture['X1']
gas4.X = self.Mixture['X4']
# calculate mean molecular weight of driver and driven mixtures
W4 = gas4.mean_molecular_weight
W1 = gas1.mean_molecular_weight
# print([W4, W1])
# calculate specific heat ratios
g4 = gas4.cp / gas4.cv
g1 = gas1.cp / gas1.cv
MachReduction = 0.985 # account for shock wave attenuation
# compute gas dynamics
def res(Ms1):
return p5 / p1 - ((2.0 * g1 * Ms1 ** 2.0 - (g1 - 1.0)) / (g1 + 1.0)) \
* ((-2.0 * (g1 - 1.0) + Ms1 ** 2.0 * (3.0 * g1 - 1.0)) / (2.0 + Ms1 ** 2.0 * (g1 - 1.0)))
Ms1 = newton(res, 2.0)
Ms1 *= MachReduction
T5oT1 = (2.0 * (g1 - 1.0) * Ms1 ** 2.0 + 3.0 - g1) \
* ((3.0 * g1 - 1.0) * Ms1 ** 2.0 - 2.0 * (g1 - 1.0)) \
/ ((g1 + 1.0) ** 2.0 * Ms1 ** 2.0)
T1 = T5 / T5oT1
a1oa4 = np.sqrt(W4 / W1)
p4op1 = (1.0 + 2.0 * g1 / (g1 + 1.0) * (Ms1 ** 2.0 - 1.0)) \
* (1.0 - (g4 - 1.0) / (g4 + 1.0) * a1oa4 * (Ms1 - 1.0 / Ms1)) ** (-2.0 * g4 / (g4 - 1.0))
p4 = p1 * p4op1
except:
# if T5, p5 and p1 are not defined, expect T1, p4 and p1 inputs
T1 = self.Thermal['T1']
p4 = self.Thermal['p4']
p1 = self.Thermal['p1']
mech = self.Mixture['mechanism']
gas1 = ct.Solution(mech)
gas4 = ct.Solution(mech)
have_p5 = False
nXCoarse, nXFine = self.Sim['nXCoarse'], self.Sim['nXFine'] # mesh resolution
LDriver, LDriven = self.Geometry['LDriver'], self.Geometry['LDriven']
DDriver, DDriven = self.Geometry['DDriver'], self.Geometry['DDriven']
plt.close("all")
mpl.rcParams['font.size'] = fontsize
plt.rc('text', usetex=False)
# setup geometry
xLower = -LDriver
xUpper = LDriven
xShock = 0.0
Delta = 10 * (xUpper - xLower) / float(nXFine)
geometry = (nXFine, xLower, xUpper, xShock)
# ----------------------------------------------------------------------------------------
# First simulate the continuous insert profile
# ----------------------------------------------------------------------------------------
# get geometry of area change from the inputted insert profile:
# set the size of the input arrays to one dimensional for intepolation
xInsert = xInsert.reshape(len(xInsert), )
DOuterInsert = DOuterInsert.reshape(len(DOuterInsert), )
DInnerInsert = DInnerInsert.reshape(len(DInnerInsert), )
# Interpolate to get a function of the discrete insert profile
dx = xInsert[1]-xInsert[0]
xInsert = np.append(xInsert[0]-dx*2, xInsert)
xInsert = np.append(xInsert, xInsert[-1]+dx*2)
DOuterInsert = np.append(DOuterInsert[0], DOuterInsert)
DOuterInsert = np.append(DOuterInsert, DOuterInsert[-1])
DInnerInsert = np.append(DInnerInsert[0], DInnerInsert)
DInnerInsert = np.append(DInnerInsert, DInnerInsert[-1])
DOuter = interp1d(xInsert, DOuterInsert)
# calculate the rate of outer diameter change with x
def dDOuterdx(x):
dDdx = np.zeros_like(x)
i = 0
for xloop in x:
where = np.sum(xloop>xInsert)
dDdx[i] = (DOuterInsert[where]-DOuterInsert[where-1])/(xInsert[where]-xInsert[where-1])
i = i+1
return dDdx
# Interpolate to get a function of the discrete insert profile
DInner = interp1d(xInsert, DInnerInsert)
# calculate the rate of inner diameter change with x
def dDInnerdx(x):
dDdx = np.zeros_like(x)
i = 0
for xloop in x:
where = np.sum(xloop>xInsert)
dDdx[i] = (DInnerInsert[where]-DInnerInsert[where-1])/(xInsert[where]-xInsert[where-1])
i = i+1
return dDdx
# calculate the area profile of the driver section
A = lambda x: np.pi / 4.0 * (DOuter(x) ** 2.0 - DInner(x) ** 2.0)
# calculate the rate of area change with x
dAdx = lambda x: np.pi / 2.0 * (DOuter(x) * dDOuterdx(x) - DInner(x) * dDInnerdx(x))
dlnAdx = lambda x, t: dAdx(x) / A(x)
# set up the gasses
u1 = 0.0
u4 = 0.0 # initially 0 velocity
T4 = T1 # assumed
gas1.TPX = T1, p1, self.Mixture['X1']
gas4.TPX = T4, p4, self.Mixture['X4']
# set up solver parameter
boundaryConditions = ['reflecting', 'reflecting']
state1 = (gas1, u1)
state4 = (gas4, u4)
# setup conditions for compressibility correction
try:
# if no values of multipliers are defined, set the values to 1
self.Sim['alpha']
except:
self.Sim['alpha'] = 1
self.Sim['beta'] = 1
self.Sim['D_mul'] = 1
# recalculate at higher resolution with the insert
gas1.TPX = T1, p1, self.Mixture['X1']
gas4.TPX = T4, p4, self.Mixture['X4']
if self.Sim['CRV']:
try:
# define buffer gas composition
xBuffer = self.Mixture['XBuffer']
# define fraction of buffer section in driven section
frac_buffer = self.Geometry['BufferFraction']
# define buffer gas
gasBuffer = ct.Solution(mech)
gasBuffer.TPX = T4, p1, xBuffer
except:
raise Exception('Buffer gas not defined!!!')
ss = stanShock(gas1, initializeRiemannProblem=(state4, state1, geometry),
boundaryConditions=boundaryConditions,
cfl=.9,
outputEvery=100,
includeBoundaryLayerTerms=True,
Tw=T1, # assume wall temperature is in thermal eq. with gas
alpha=self.Sim['alpha'],
beta=self.Sim['beta'],
D_mul=self.Sim['D_mul'],
DOuter=DOuter,
DInner=DInner,
dlnAdx=dlnAdx)
# implement backfill if called for
if self.Sim['Backfill']:
try:
# unpack backfill gas composition
xBackfill = self.Mixture['XBackfill']
# define backfill location
LBackfill = self.Geometry['LBackfill']
# define back fill gas stage by stage
for stage in range(0, len(xBackfill)):
gasBackfill = ct.Solution(mech)
gasBackfill.TPX = T4, p4, xBackfill[stage]
l_backfill = LBackfill[stage]
ss.applyDriverBackfill(gasBackfill, l_backfill)
except:
raise Exception('Backfill gas mixture not defined!!!')
# implement CRV if called for
if self.Sim['CRV']:
ss.applyTestGasBuffer(gasBuffer, buffer_fraction=frac_buffer)
ss.addXTDiagram("p")
ss.addXTDiagram("T")
ss.addProbe(max(ss.x)) # end wall probe
t0 = time.clock()
ss.advanceSimulation(tFinal)
t1 = time.clock()
print("The process took ", t1 - t0)
pInsert = np.array(ss.probes[0].p)
tInsert = np.array(ss.probes[0].t)
rInsert = np.array(ss.probes[0].r)
YInsert = np.array(ss.probes[0].Y)
TInsert = np.array(ss.thermoTable.getTemperature(rInsert, pInsert, YInsert))
if self.plot:
ss.plotXTDiagram(ss.XTDiagrams["t"], limits=[min(TInsert), max(TInsert)], saveData=True)
TMatrix = ss.XTDiagram_variableMatrix
timeXT = ss.XTDiagram_T
positionXT = ss.XTDiagram_X
ss.plotXTDiagram(ss.XTDiagrams["p"], limits=[min(pInsert) / 1e5, max(pInsert) / 1e5], saveData=True)
pMatrix = ss.XTDiagram_variableMatrix
self.TMatrix = TMatrix
self.pMatrix = pMatrix
self.timeXT = timeXT
self.positionXT = positionXT
'''
# ----------------------------------------------------------------------------------------
# Now simulate discretized insert
# ----------------------------------------------------------------------------------------
# setup geometry of discrete insert
DIn = ss.DInner(ss.x)
xIn = ss.x
disX = xIn[0:-1:x_step]
disD = DIn[0:-1:x_step]
delta = 1
dx = xIn[1] - xIn[0]
def DInner_discrete(x):
DInner_dis = np.zeros_like(x)
cnt = 0
for X in x:
if np.sum(X > np.array(disX)) < len(disD):
DInner_dis[cnt] = disD[np.sum(X > np.array(disX))]
cnt = cnt + 1
for d in range(0, int(np.floor(len(x) / x_step)) - 1):
LowBond = int(d * x_step - delta)
UpBond = int(d * x_step + delta)
x_loc = x[LowBond:UpBond]
try:
DInner_dis[LowBond:UpBond] = smoothingFunction(x_loc, disX[d], 2 * delta * dx, disD[d], disD[d + 1])
except:
DInner_dis[LowBond:UpBond] = smoothingFunction(x_loc, disX[d], 2 * delta * dx, disD[d], 0)
return DInner_dis
# plt.plot(xIn, DIn)#
# plt.plot(xIn, DInner_discrete(xIn), '.')#%%
# plt.plot(xIn[0:-1:x_step], DIn[0:-1:x_step], 'r.')
#plt.xlim((-2, 0))
def dDInnerdx_dis(x):
dDIndx = np.zeros(x.shape)
for d in range(0, int(np.floor(len(x) / x_step)) - 1):
LowBond = int(d * x_step - delta)
UpBond = int(d * x_step + delta)
x_loc = x[LowBond:UpBond]
dDIndx[LowBond:UpBond] = dSFdx(x_loc, disX[d], 2 * delta * dx, disD[d], disD[d + 1])
return dDIndx
A_dis = lambda x: np.pi / 4.0 * (DOuter(x) ** 2.0 - DInner_discrete(x) ** 2.0)
dAdx_dis = lambda x: np.pi / 2.0 * (DOuter(x) * dDOuterdx(x) - DInner_discrete(x) * dDInnerdx_dis(x))
dlnAdx_dis = lambda x, t: dAdx_dis(x) / A(x)
# recalculate at higher resolution with discrete insert
geometry = (nXFine, xLower, xUpper, xShock)
gas1.TPX = T1, p1, self.Mixture['X1']
gas4.TPX = T4, p4, self.Mixture['X4']
ss = stanShock(gas1, initializeRiemannProblem=(state4, state1, geometry),
boundaryConditions=boundaryConditions,
cfl=.9,
outputEvery=100,
includeBoundaryLayerTerms=True,
Tw=T1, # assume wall temperature is in thermal eq. with gas
alpha=self.Sim['alpha'],
beta=self.Sim['beta'],
D_mul=self.Sim['D_mul'],
DOuter=DOuter,
DInner=DInner_discrete,
dlnAdx=dlnAdx_dis)
ss.addXTDiagram("p")
ss.addXTDiagram("T")
ss.addProbe(max(ss.x)) # end wall probe
t0 = time.clock()
ss.advanceSimulation(tFinal)
t1 = time.clock()
print("The process took ", t1 - t0)
pInsert_dis = np.array(ss.probes[0].p)
tInsert_dis = np.array(ss.probes[0].t)
rInsert_dis = np.array(ss.probes[0].r)
YInsert_dis = np.array(ss.probes[0].Y)
TInsert_dis = np.array(ss.thermoTable.getTemperature(rInsert_dis, pInsert_dis, YInsert_dis))
DInnerInsert_dis = ss.DInner(ss.x)
xInsert_dis = ss.x
if self.plot:
ss.plotXTDiagram(ss.XTDiagrams["t"], limits=[min(TInsert_dis), max(TInsert_dis)])
ss.plotXTDiagram(ss.XTDiagrams["p"], limits=[min(pInsert_dis)/1e5, max(pInsert_dis)/1e5])
'''
# ----------------------------------------------------------------------------------------
# Now simulate without insert
# ----------------------------------------------------------------------------------------
# setup geometry of no insert tube
DInner = lambda x: np.zeros_like(x)
dDInnerdx = lambda x: np.zeros_like(x)
def DOuter(x):
return smoothingFunction(x, xShock, Delta, DDriver, DDriven)
def dDOuterdx(x):
return dSFdx(x, xShock, Delta, DDriver, DDriven)
A = lambda x: np.pi / 4.0 * (DOuter(x) ** 2.0 - DInner(x) ** 2.0)
dAdx = lambda x: np.pi / 2.0 * (DOuter(x) * dDOuterdx(x) - DInner(x) * dDInnerdx(x))
dlnAdx = lambda x, t: dAdx(x) / A(x)
gas1.TPX = T1, p1, self.Mixture['X1']
gas4.TPX = T4, p4, self.Mixture['X4']
if self.Sim['CRV']:
try:
# define buffer gas composition
xBuffer = self.Mixture['XBuffer']
# define fraction of buffer section in driven section
frac_buffer = self.Geometry['BufferFraction']
# define buffer gas
gasBuffer = ct.Solution(mech)
gasBuffer.TPX = T4, p1, xBuffer
except:
raise Exception('Buffer gas not defined!!!')
ss = stanShock(gas1, initializeRiemannProblem=(state4, state1, geometry),
boundaryConditions=boundaryConditions,
cfl=.9,
outputEvery=100,
includeBoundaryLayerTerms=True,
Tw=T1, # assume wall temperature is in thermal eq. with gas
alpha=self.Sim['alpha'],
beta=self.Sim['beta'],
D_mul=self.Sim['D_mul'],
DOuter=DOuter,
dlnAdx=dlnAdx)
# implement backfill if called for
if self.Sim['Backfill']:
try:
# unpack backfill gas composition
xBackfill = self.Mixture['XBackfill']
# define backfill location
LBackfill = self.Geometry['LBackfill']
# define back fill gas stage by stage
for stage in range(0, len(xBackfill)):
gasBackfill = ct.Solution(mech)
gasBackfill.TPX = T4, p4, xBackfill[stage]
l_backfill = LBackfill[stage]
ss.applyDriverBackfill(gasBackfill, l_backfill)
except:
raise Exception('Backfill gas mixture not defined!!!')
# implement CRV if called for
if self.Sim['CRV']:
ss.applyTestGasBuffer(gasBuffer, buffer_fraction=frac_buffer)
ss.addXTDiagram("p")
ss.addXTDiagram("T")
ss.addProbe(max(ss.x)) # end wall probe
t0 = time.clock()
ss.advanceSimulation(tFinal)
t1 = time.clock()
print("The process took ", t1 - t0)
pNoInsert = np.array(ss.probes[0].p)
tNoInsert = np.array(ss.probes[0].t)
rNoInsert = np.array(ss.probes[0].r)
YNoInsert = np.array(ss.probes[0].Y)
TNoInsert = np.array(ss.thermoTable.getTemperature(rNoInsert, pNoInsert, YNoInsert))
if self.plot:
ss.plotXTDiagram(ss.XTDiagrams["t"], limits=[min(TNoInsert), max(TNoInsert)])
ss.plotXTDiagram(ss.XTDiagrams["p"], limits=[min(pNoInsert) / 1e5, max(pNoInsert) / 1e5])
# plot
if self.plot:
plt.figure()
plt.plot(tNoInsert / 1e-3, pNoInsert / 1e5, 'k', label="$\mathrm{No\ Insert}$")
plt.plot(tInsert / 1e-3, pInsert / 1e5, 'r', label="$\mathrm{Optimized\ Insert}$")
#plt.plot(tInsert_dis / 1e-3, pInsert_dis / 1e5, '--b', label="$\mathrm{Optimized\ Discrete\ Insert}$")
plt.xlabel("$t\ [\mathrm{ms}]$")
plt.ylabel("$p\ [\mathrm{bar}]$")
plt.legend(loc="best")
plt.tight_layout()
plt.figure()
plt.axis('equal')
plt.xlim((-2, 0.5))
plt.plot(xInsert, DOuterInsert, 'k', label="$D_\mathrm{o}$")
plt.plot(xInsert, DInnerInsert, 'r', label="$D_\mathrm{i}$")
#plt.plot(xInsert_dis, DInnerInsert_dis, 'b', label="$D_\mathrm{dis}$")
plt.plot([xShock, xShock], [-0.8, 0.8], 'k--')
plt.xlabel("$x\ [\mathrm{m}]$")
plt.ylabel("$D\ [\mathrm{m}]$")
plt.legend(loc="best")
plt.tight_layout()
if self.saveData:
np.savetxt('tNoInsert.csv', tNoInsert, delimiter=',')
np.savetxt('pNoInsert.csv', pNoInsert, delimiter=',')
np.savetxt('tInsert.csv', tInsert, delimiter=',')
np.savetxt('pInsert.csv', pInsert, delimiter=',')
#np.savetxt('tInsert_dis.csv', tInsert_dis, delimiter=',')
#np.savetxt('pInsert_dis.csv', pInsert_dis, delimiter=',')
####################################################################################################################
def SimulateInsertDiscrete(self, disX, disD):
'''
Method to simulate the shock tube flow given a discrete driver insert profile
'''
# set up input thermodynamic and shock tube parameters
fontsize = 12
tFinal = self.Sim['tFinal']
try:
self.Thermal['p5']
have_p5 = True
p5, p1 = self.Thermal['p5'], self.Thermal['p1']
T5 = self.Thermal['T5']
# define driver and driven gases
mech = self.Mixture['mechanism']
gas1 = ct.Solution(mech)
gas4 = ct.Solution(mech)
gas1.X = self.Mixture['X1']
gas4.X = self.Mixture['X4']
# calculate mean molecular weight of driver and driven mixtures
W4 = gas4.mean_molecular_weight
W1 = gas1.mean_molecular_weight
# print([W4, W1])
# calculate specific heat ratios
g4 = gas4.cp / gas4.cv
g1 = gas1.cp / gas1.cv
MachReduction = 0.985 # account for shock wave attenuation
# compute gas dynamics
def res(Ms1):
return p5 / p1 - ((2.0 * g1 * Ms1 ** 2.0 - (g1 - 1.0)) / (g1 + 1.0)) \
* ((-2.0 * (g1 - 1.0) + Ms1 ** 2.0 * (3.0 * g1 - 1.0)) / (2.0 + Ms1 ** 2.0 * (g1 - 1.0)))
Ms1 = newton(res, 2.0)
Ms1 *= MachReduction
T5oT1 = (2.0 * (g1 - 1.0) * Ms1 ** 2.0 + 3.0 - g1) \
* ((3.0 * g1 - 1.0) * Ms1 ** 2.0 - 2.0 * (g1 - 1.0)) \
/ ((g1 + 1.0) ** 2.0 * Ms1 ** 2.0)
T1 = T5 / T5oT1
a1oa4 = np.sqrt(W4 / W1)
p4op1 = (1.0 + 2.0 * g1 / (g1 + 1.0) * (Ms1 ** 2.0 - 1.0)) \
* (1.0 - (g4 - 1.0) / (g4 + 1.0) * a1oa4 * (Ms1 - 1.0 / Ms1)) ** (-2.0 * g4 / (g4 - 1.0))
p4 = p1 * p4op1
except:
# if T5, p5 and p1 are not defined, expect T1, p4 and p1 inputs
T1 = self.Thermal['T1']
p4 = self.Thermal['p4']
p1 = self.Thermal['p1']
mech = self.Mixture['mechanism']
gas1 = ct.Solution(mech)
gas4 = ct.Solution(mech)
have_p5 = False
nXFine = self.Sim['nXFine'] # mesh resolution
LDriver, LDriven = self.Geometry['LDriver'], self.Geometry['LDriven']
DDriver, DDriven = self.Geometry['DDriver'], self.Geometry['DDriven']
plt.close("all")
mpl.rcParams['font.size'] = fontsize
plt.rc('text', usetex=True)
# setup geometry
xLower = -LDriver
xUpper = LDriven
xShock = 0.0
Delta = 10 * (xUpper - xLower) / float(nXFine)
# ----------------------------------------------------------------------------------------
# Now simulate discretized insert
# ----------------------------------------------------------------------------------------
# set up geometry of discrete insert
# define tube geometry
def DOuter(x):
return smoothingFunction(x, xShock, Delta, DDriver, DDriven)
# define rate of change in tube geometry
def dDOuterdx(x):
return dSFdx(x, xShock, Delta, DDriver, DDriven)
delta = 1 #setp size for smoothing function between discontinuities in diameter
def DInner_discrete(x):
# initialize insert diameter array
DInner_dis = np.zeros_like(x)
# get the step size between grid points
dx = x[1] - x[0]
# begin loop to calculate insert diameters
cnt = 0
for X in x:
# write all diameter between each length interval to the same diameter of the step
if np.sum(X > np.array(disX)) < len(disD):
DInner_dis[cnt] = disD[np.sum(X > np.array(disX))]
cnt = cnt + 1
# begin loop to insert smoothed profile between diameter steps
for d in range(0, len(disX)):
# find range of smoothing function
LowBond = sum(disX[d] > x) - delta
UpBond = sum(disX[d] > x) + delta
x_loc = x[LowBond:UpBond]
try:
DInner_dis[LowBond:UpBond] = smoothingFunction(x_loc, disX[d], 2 * delta * dx, disD[d], disD[d + 1])
except: # when the loop forwards to the last insert, set the final diameter to zero
DInner_dis[LowBond:UpBond] = smoothingFunction(x_loc, disX[d], 2 * delta * dx, disD[d], 0)
return DInner_dis