-
Notifications
You must be signed in to change notification settings - Fork 0
/
bkp.script
754 lines (637 loc) · 21.8 KB
/
bkp.script
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
import os
import pandas as pd
import TELocations as teloc
import numpy as np
import re
file_dict = {
'Avg_Vx' : "B00001.dat",
'Avg_Vy' : "B00002.dat",
'Length_of_Avg_V' : "B00003.dat",
'Standard_deviation_of_Vx' : "B00004.dat",
'Standard_deviation_of_Vy' : "B00005.dat",
'Length_of_Standard_deviation_of_V' : "B00006.dat",
'Turbulent_kinetec_energy' : "B00007.dat",
'Reynold_stress_XY' : "B00008.dat",
'Reynold_stress_XX' : "B00009.dat",
'Reynold_stress_YY' : "B00010.dat",
}
davis_dict = {
'Avg_Vx' : 'Avg_Vx' ,
'Avg_Vy' : 'Avg_Vy' ,
'Length_of_Avg_V' : 'Length_of_Avg_V' ,
'Standard_deviation_of_Vx' : 'RMS_Vx' ,
'Standard_deviation_of_Vy' : 'RMS_Vy' ,
'Length_of_Standard_deviation_of_V' : 'Length_of_RMS_V' ,
'Turbulent_kinetec_energy' : 'Turbulent_kinetec_energy' ,
'Reynold_stress_XY' : 'Reynold_stress_XY' ,
'Reynold_stress_XX' : 'Reynold_stress_XX' ,
'Reynold_stress_YY' : 'Reynold_stress_YY' ,
}
need_to_stitch_cases = [
'STE_A6_U20_closed_SS',
'STE_SS_a12_U20',
'STE_SS_a12_U30',
'STE_SS_a12_U35',
'STE_SS_a12_U40',
]
root = './Data'
raw_data_root = '/media/carlos/6E34D2CD34D29783/2015-07_BL/STE_BL_Data/'
data_folders = [f for f in os.listdir(root) \
if os.path.isfile(os.path.join(root,f))
and f.endswith(".p")]
raw_data_folders = [f for f in os.listdir(raw_data_root) \
if os.path.isdir(os.path.join(raw_data_root,f))]
def read_data(root,case,variable):
""" Reads the data. Prioritize reading an existing pickle
of the data"""
import os
import pandas as pd
if os.path.isfile(
os.path.join(root,case)
):
return pd.read_pickle(
os.path.join(root,case)
)
else:
tecplot_file = os.path.join(root,case,file_dict[variable])
return read_tecplot(tecplot_file)
def stitch_cases(frame1_df,frame2_df,case):
import matplotlib.pyplot as plt
te_location = teloc.TELocations[
recognize_case(case)[0]
][1]
y1 = find_nearest(float(te_location[1]),frame1_df.y.unique())
y2 = find_nearest(float(te_location[1]),frame2_df.y.unique())
frame1_df = frame1_df[(frame1_df.y == y1)]
frame2_df = frame2_df[(frame2_df.y == y2)]
frame2_df.x = frame2_df.x +\
frame1_df[
frame1_df.Length_of_Avg_V.max()==\
frame2_df.Length_of_Avg_V.min()
].x
fig = plt.figure()
plt.plot(
frame1_df.x,
frame1_df.Length_of_Avg_V,
)
plt.plot(
frame2_df.x,
frame2_df.Length_of_Avg_V,
)
plt.savefig('test.png')
def read_tecplot(tecplot_file):
"""Reads in (the second frame present in the given) tecplot file,
and returns a pandas data frame
Input:
tecplot formated file
Output:
pandas data frame
"""
# Get available variables
f = open(tecplot_file,'ro')
variables = []
# Do two things:
# 1) Grab the important info from the header
# 2) See where the second frame info starts so that
# it passes it later to the pandas reader
var_string = 0
end_line = 0
final_line = 0
stop_frame_count = False
for line in f:
if not stop_frame_count:
end_line+=1
if 'Frame 2' in line:
stop_frame_count = True
if not var_string:
var_string = re.findall("^VARIABLES[ _A-Za-z0-9,\"=]+",line)
if var_string:
variables = [
v.replace(' ','_').replace("\"","") \
for v in var_string[0].replace("VARIABLES = ",'').\
split(", ")
]
variables = [v for v in variables if len(v)]
final_line += 1
f.close()
lines_to_skip = range(0,3)+range(end_line-1,final_line)
# Put the data into a data frame
data_frame1 = pd.read_table(
tecplot_file,
skiprows = lines_to_skip,
names = variables,
sep = '[ \t]+',
index_col = False,
dtype = np.float
)
# Put the data into a data frame
data_frame2 = pd.read_table(
tecplot_file,
skiprows = range(0,end_line),
names = variables,
sep = '[ \t]+',
index_col = False,
dtype = np.float
)
stitch_cases(data_frame1, data_frame2,case)
data = data_frame1
data = data[
(data.x < data.x.max()*0.90) &\
(data.x > data.x.min()*1.10) &\
(data.y < data.y.max()*0.90) &\
(data.y > data.y.min()*1.10)
]
return data
def pickle_all_data(root,case_name):
""" Meant to be used only once... pickles the (relevant)
TECPLOT data into a single file
Input:
TECPLOT file folder
"""
variables_to_read = [
'Length_of_Avg_V',
'Length_of_Standard_deviation_of_V'
]
for v in variables_to_read:
if v == variables_to_read[0]:
tecplot_file = os.path.join(root,case_name,file_dict[v])
df = read_tecplot(tecplot_file)
else:
tecplot_file = os.path.join(root,case_name,file_dict[v])
df_tmp = read_tecplot(tecplot_file)
try:
df[v] = df_tmp[v]
except KeyError:
df[v] = df_tmp[davis_dict[v]]
df.to_pickle(os.path.join(root,case_name+'.p'))
def find_nearest(to_point,from_array):
""" Finds the nearest available value in a array to a given value
Inputs:
to_point: value to find the nearest to in the array
from_array: array of available values
Returns:
The nearest value found in the array
"""
deltas = np.ones(len(from_array))*1000
for v,i in zip(from_array,range(len(from_array))):
deltas[i] = abs(float(to_point) - float(v))
return from_array[np.argmin(deltas)]
def recognize_case(case_name):
""" Separates the case name folder into its distinctive parameters
used in this campaign
Input: folder name
Output:
the key of the TELocations dictionary it belongs to
case parameters [alpha,side,test_section]
"""
alpha = int(re.findall('[Aa][0-9][0-9]?',case_name)[0]\
.replace('A','').replace('a',''))
try:
side = re.findall('PS',case_name)[0]
except:
side = 'SS'
try:
test_section = re.findall('closed',case_name)[0]
except:
test_section = 'open'
# A complicated search for equal terms in the dictionary keys and
# the case parameters
# (that's what happens when you don't use standard nomenclature)
case_key = ''
for keys,values in zip(
teloc.TELocations.keys(),
teloc.TELocations.values()
):
if test_section == values[0]:
if alpha == int(re.findall('[Aa][0-9][0-9]?',keys)[0]\
.replace('A','').replace('a','')):
if alpha: # Hey, alpha = 0 has no side
if side == re.findall('[PS]S',keys)[0]:
case_key = keys
break
elif alpha==0:
case_key = keys
break
case_parameters = [alpha,side,test_section]
return case_key, case_parameters
def get_bl(case,variable='Length_of_Avg_V'):
""" Get the TE boundary layer information and return it as an array
Input:
tecplot file location
Output:
array of flow velocity values
locations of those velocity vectors
"""
root = './Data'
df = read_data(root,case,variable)
te_location = teloc.TELocations[
recognize_case(case)[0]
][1]
x = find_nearest(float(te_location[0]),df.x.unique())
y = find_nearest(float(te_location[1]),df.y.unique())
data = df[
(df.y == y) &\
(df.x < x)
]
try:
bl_data = np.array(map(float,data[variable].values))
except KeyError:
print root,case,variable
print data.columns
raise
points = -(np.array(map(float,data['x'].values))-te_location[0])
return bl_data,points
def plot_bl(case,variable='Avg_Vy'):
from matplotlib import pyplot as plt
import seaborn as sns
sns.__version__
x,y = get_bl(case,variable)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x,y,'-')
loc_99,vel_99 = find_bl(case)
ax.axhline(y=loc_99,ls='--',color='r',lw=2)
ax.text(0.9*ax.get_xlim()[1],loc_99,'$\\delta_{{99}} ={0:.2f} $ mm'.\
format(loc_99),ha='right',va='bottom')
ax.set_xlabel('$v$ [m/s]')
ax.set_ylabel('$y$ [mm]')
ax.set_ylim(bottom=0)
plt.title(case)
plt.savefig('images/BL_{0}.png'.format(case))
fig.clear()
def plot_surface(case,variable='Avg_Vy'):
from matplotlib import pyplot as plt
import seaborn as sns
sns.set(context="notebook", style="whitegrid",
rc={"axes.axisbelow": False,'image.cmap': 'YlOrRd'})
df = read_data(root,case,variable)
X,Y = np.meshgrid(df.x.unique(),df.y.unique())
Z = df[variable].reshape(X.shape)
te_location = teloc.TELocations[
recognize_case(case)[0]
][1]
bl_data,points = get_bl(case=case,variable=variable)
delta_99,vel_99 = find_bl(case=case,variable=variable)
points = -points+te_location[0]
delta_99 = -delta_99+te_location[0]
levels = np.linspace(float(Z.min()),float(Z.max())+1,30)
fig = plt.figure()
ax = plt.subplot(111,aspect=1)
ax.contourf(X,Y,Z,levels=levels)
C = ax.contour(X, Y, Z, levels=levels,
colors = ('k',),
linewidths = (1,),
)
ax.clabel(C, inline=1, fontsize=10,color='w')
ax.scatter(points,[te_location[1]]*len(points),s=10,color='k')
ax.scatter(delta_99,te_location[1],s=40,color='k')
ax.scatter(delta_99,te_location[1],marker='x',s=80,color='k')
plt.savefig('images/Surface_{0}.png'.format(case))
fig.clear()
def find_bl(case,variable='Length_of_Avg_V'):
vel,loc = get_bl(case,variable)
vel_99 = vel.max()*0.99
for v,l in zip(vel[::-1],loc[::-1]):
if v>vel_99:
delta_99 = l
break
return delta_99,vel_99
#def make_csv(out_file="BL_Data_Info.csv"):
# import pandas as pd
# from re import findall
# from os.path import join
#
# bl_info_DF = pd.DataFrame(
# columns = [
# 'U_inf',
# 'alpha',
# 'Delta_99',
# 'U_99',
# 'Side',
# 'Test_section'
# ])
#
# variable = 'Length_of_Avg_V'
# for case in data_folders:
# alpha = findall("_[aA][0-9][0-9]?",case)[0].\
# replace("_a","").\
# replace("_A","")
# U_inf = findall("_U[0-9][0-9]?",case)[0].replace("_U","")
# if len(findall("[PS]S",case)):
# side = fin
def read_tecplot(tecplot_file):
"""Reads in (the second frame present in the given) tecplot file,
and returns a pandas data frame
Input:
tecplot formated file
Output:
pandas data frame
"""
# Get available variables
f = open(tecplot_file,'ro')
variables = []
# Do two things:
# 1) Grab the important info from the header
# 2) See where the second frame info starts so that
# it passes it later to the pandas reader
var_string = 0
end_line = 0
final_line = 0
stop_frame_count = False
for line in f:
if not stop_frame_count:
end_line+=1
if 'Frame 2' in line:
stop_frame_count = True
if not var_string:
var_string = re.findall("^VARIABLES[ _A-Za-z0-9,\"=]+",line)
if var_string:
variables = [
v.replace(' ','_').replace("\"","") \
for v in var_string[0].replace("VARIABLES = ",'').\
split(", ")
]
variables = [v for v in variables if len(v)]
final_line += 1
f.close()
lines_to_skip = range(0,3)+range(end_line-1,final_line)
# Put the data into a data frame
data_frame1 = pd.read_table(
tecplot_file,
skiprows = lines_to_skip,
names = variables,
sep = '[ \t]+',
index_col = False,
dtype = np.float
)
# Put the data into a data frame
data_frame2 = pd.read_table(
tecplot_file,
skiprows = range(0,end_line),
names = variables,
sep = '[ \t]+',
index_col = False,
dtype = np.float
)
stitch_cases(data_frame1, data_frame2,case)
data = data_frame1
data = data[
(data.x < data.x.max()*0.90) &\
(data.x > data.x.min()*1.10) &\
(data.y < data.y.max()*0.90) &\
(data.y > data.y.min()*1.10)
]
return data
def pickle_all_data(root,case_name):
""" Meant to be used only once... pickles the (relevant)
TECPLOT data into a single file
Input:
TECPLOT file folder
"""
variables_to_read = [
'Length_of_Avg_V',
'Length_of_Standard_deviation_of_V'
]
for v in variables_to_read:
if v == variables_to_read[0]:
tecplot_file = os.path.join(root,case_name,file_dict[v])
df = read_tecplot(tecplot_file)
else:
tecplot_file = os.path.join(root,case_name,file_dict[v])
df_tmp = read_tecplot(tecplot_file)
try:
df[v] = df_tmp[v]
except KeyError:
df[v] = df_tmp[davis_dict[v]]
df.to_pickle(os.path.join(root,case_name+'.p'))
def find_nearest(to_point,from_array):
""" Finds the nearest available value in a array to a given value
Inputs:
to_point: value to find the nearest to in the array
from_array: array of available values
Returns:
The nearest value found in the array
"""
deltas = np.ones(len(from_array))*1000
for v,i in zip(from_array,range(len(from_array))):
deltas[i] = abs(float(to_point) - float(v))
return from_array[np.argmin(deltas)]
def recognize_case(case_name):
""" Separates the case name folder into its distinctive parameters
used in this campaign
Input: folder name
Output:
the key of the TELocations dictionary it belongs to
case parameters [alpha,side,test_section]
"""
alpha = int(re.findall('[Aa][0-9][0-9]?',case_name)[0]\
.replace('A','').replace('a',''))
try:
side = re.findall('PS',case_name)[0]
except:
side = 'SS'
try:
test_section = re.findall('closed',case_name)[0]
except:
test_section = 'open'
# A complicated search for equal terms in the dictionary keys and
# the case parameters
# (that's what happens when you don't use standard nomenclature)
case_key = ''
for keys,values in zip(
teloc.TELocations.keys(),
teloc.TELocations.values()
):
if test_section == values[0]:
if alpha == int(re.findall('[Aa][0-9][0-9]?',keys)[0]\
.replace('A','').replace('a','')):
if alpha: # Hey, alpha = 0 has no side
if side == re.findall('[PS]S',keys)[0]:
case_key = keys
break
elif alpha==0:
case_key = keys
break
case_parameters = [alpha,side,test_section]
return case_key, case_parameters
def get_bl(case,variable='Length_of_Avg_V'):
""" Get the TE boundary layer information and return it as an array
Input:
tecplot file location
Output:
array of flow velocity values
locations of those velocity vectors
"""
root = './Data'
df = read_data(root,case,variable)
te_location = teloc.TELocations[
recognize_case(case)[0]
][1]
x = find_nearest(float(te_location[0]),df.x.unique())
y = find_nearest(float(te_location[1]),df.y.unique())
data = df[
(df.y == y) &\
(df.x < x)
]
try:
bl_data = np.array(map(float,data[variable].values))
except KeyError:
print root,case,variable
print data.columns
raise
points = -(np.array(map(float,data['x'].values))-te_location[0])
return bl_data,points
def plot_bl(case,variable='Avg_Vy'):
from matplotlib import pyplot as plt
import seaborn as sns
sns.__version__
x,y = get_bl(case,variable)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x,y,'-')
loc_99,vel_99 = find_bl(case)
ax.axhline(y=loc_99,ls='--',color='r',lw=2)
ax.text(0.9*ax.get_xlim()[1],loc_99,'$\\delta_{{99}} ={0:.2f} $ mm'.\
format(loc_99),ha='right',va='bottom')
ax.set_xlabel('$v$ [m/s]')
ax.set_ylabel('$y$ [mm]')
ax.set_ylim(bottom=0)
plt.title(case)
plt.savefig('images/BL_{0}.png'.format(case))
fig.clear()
def plot_surface(case,variable='Avg_Vy'):
from matplotlib import pyplot as plt
import seaborn as sns
sns.set(context="notebook", style="whitegrid",
rc={"axes.axisbelow": False,'image.cmap': 'YlOrRd'})
df = read_data(root,case,variable)
X,Y = np.meshgrid(df.x.unique(),df.y.unique())
Z = df[variable].reshape(X.shape)
te_location = teloc.TELocations[
recognize_case(case)[0]
][1]
bl_data,points = get_bl(case=case,variable=variable)
delta_99,vel_99 = find_bl(case=case,variable=variable)
points = -points+te_location[0]
delta_99 = -delta_99+te_location[0]
levels = np.linspace(float(Z.min()),float(Z.max())+1,30)
fig = plt.figure()
ax = plt.subplot(111,aspect=1)
ax.contourf(X,Y,Z,levels=levels)
C = ax.contour(X, Y, Z, levels=levels,
colors = ('k',),
linewidths = (1,),
)
ax.clabel(C, inline=1, fontsize=10,color='w')
ax.scatter(points,[te_location[1]]*len(points),s=10,color='k')
ax.scatter(delta_99,te_location[1],s=40,color='k')
ax.scatter(delta_99,te_location[1],marker='x',s=80,color='k')
plt.savefig('images/Surface_{0}.png'.format(case))
fig.clear()
def find_bl(case,variable='Length_of_Avg_V'):
vel,loc = get_bl(case,variable)
vel_99 = vel.max()*0.99
for v,l in zip(vel[::-1],loc[::-1]):
if v>vel_99:
delta_99 = l
break
return delta_99,vel_99
def make_csv(out_file="BL_Data_Info.csv"):
import pandas as pd
from re import findall
from os.path import join
bl_info_DF = pd.DataFrame(
columns = [
'U_inf',
'alpha',
'Delta_99',
'U_99',
'Side',
'Test_section'
])
variable = 'Length_of_Avg_V'
for case in data_folders:
alpha = findall("_[aA][0-9][0-9]?",case)[0].\
replace("_a","").\
replace("_A","")
U_inf = findall("_U[0-9][0-9]?",case)[0].replace("_U","")
if len(findall("[PS]S",case)):
side = findall("[PS]S",case)[0]
else: side = "NA"
if len(findall("closed",case)):
test_section = findall("closed",case)[0]
else: test_section = "open"
Delta_99,U_99 = find_bl(case,variable=variable)
bl_info_DF = bl_info_DF.append({
'U_inf' : float(U_inf),
'alpha' : float(alpha),
'Delta_99' : float(Delta_99),
'U_99' : float(U_99),
'Side' : side,
'Test_section' : test_section
},ignore_index=True)
if out_file:
bl_info_DF.to_csv(join("outputs",out_file))
return bl_info_DF
def plot_all_deltas(out_file="All_Deltas.png"):
import matplotlib.pyplot as plt
import seaborn as sns
from numpy import argmin,abs
import os
sns.__version__
bl_info_DF = make_csv(out_file='')
bl_info_DF = bl_info_DF.sort("U_inf")
cmap_SS = sns.color_palette("Reds_r",len(bl_info_DF.U_inf.unique()))
cmap_PS = sns.color_palette("Blues_r",len(bl_info_DF.U_inf.unique()))
# Marker defines if open or closed
marker = {
'open' : 'o',
'closed' : 'x',
}
fig,ax = plt.subplots(1,1)
for row_index, row in bl_info_DF.iterrows():
if row.Side == 'SS' or row.Side == 'NA':
cmap = cmap_SS
else:
cmap = cmap_PS
if row.Side=='NA':
label_side = ''
else: label_side = row.Side
label = "$U_\\infty = {0}$ m/s {1}".\
format(row.U_inf,label_side)
ax.scatter(
row.alpha,
row.Delta_99,
color = cmap[
argmin(abs(bl_info_DF.U_inf.unique()-row.U_inf))
],
marker = marker[row.Test_section],
s=75,
label = label
)
ax.annotate(label,
xy=(row.alpha,row.Delta_99),
xytext=(row.alpha+1,row.Delta_99+0.5),
arrowprops=dict(
facecolor='black',
arrowstyle='->',
lw=2
),
)
ax.set_xticks([0,6,12])
ax.set_xlim(-2,16)
ax.set_xlabel("$\\alpha_g$ [deg]")
ax.set_ylabel("$\\delta_{99}$ [mm]")
#ax.legend(loc='best')
plt.savefig(os.path.join('images',out_file))
#df = read_tecplot(os.path.join(root,data_folders[0],'B00001.dat'))
variable = 'Length_of_Standard_deviation_of_V'#'Avg_Vy'
#variable = 'Length_of_Avg_V'
import os
for case in raw_data_folders:
read_tecplot(os.path.join(raw_data_root,case,'B00003.dat'))
# pickle_all_data(raw_data_root,case)
#for case in data_folders:
# plot_bl(case,variable)
#plot_surface(case,variable)
#plot_all_deltas()