-
Notifications
You must be signed in to change notification settings - Fork 2
/
vsp2jsbsim.py
executable file
·577 lines (507 loc) · 20.6 KB
/
vsp2jsbsim.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
#!/usr/bin/env python3
# tool to convert VSPaero CL and CD output to tables for JSBSim
import json
import sys
import time
def dprint(t, msg=''):
if DEBUG:
if msg != '':
print(msg)
print(t)
def smallNumberCheck(f):
if 'e' in str(f):
return 0.0
else:
return f
with open('./runparams.json', 'r') as p:
params = json.loads(p.read())
od = open('./output/outputData.json', 'w+')
of = open(params['output_file'], 'w+')
stab_file = open(params['stab_file'] + params['vspname'] + '.stab', 'r')
input_base = params['base_file']
input_files = params['files']
wake_iterations = 3
data_order = ['Mach', 'AoA', 'beta', 'CL', 'CDo', 'CDi', 'CDtot', 'CS',
'L/D', 'E', 'CFx', 'CFz', 'CFy', 'CMx', 'CMy', 'CMz', 'T/QS']
input_txt_base = open(input_base + params['vspname'] + '.history', 'r').readlines()
input_txt = {}
for arg in sys.argv:
if '--debug' in arg:
DEBUG = True
else:
DEBUG = False
if arg.startswith('-w'):
wake_iterations = arg[2:]
for f in input_files.keys():
input_txt[f] = {}
for c in input_files[f]:
name = c.split('/')[len(c.split('/')) - 2]
input_txt[f][name] = open(c + params['vspname'] + '.history', 'r').readlines()
db = {'base': {0: []}}
for i in range(len(input_txt_base)):
if input_txt_base[i].startswith('Solver Case:'):
l = i + 2 + wake_iterations
dprint(input_txt_base[l])
t = input_txt_base[l].split(' ')
while '' in t:
t.remove('')
t.remove(t[0])
t[len(t) - 1] = t[len(t) - 1][:-1]
dataset = {}
for n in range(0, len(t)-1):
data_name = data_order[n]
dataset[data_name] = t[n]
db['base'][0].append(dataset)
for s in input_txt.keys():
db[s] = {}
for p in input_txt[s].keys():
db[s][p] = []
for i in range(len(input_txt[s][p])):
if input_txt[s][p][i].startswith('Solver Case:'):
l = i + 2 + wake_iterations
# print(s, p, l)
# print(input_txt[s][p][l])
t = input_txt[s][p][l].split(' ')
while '' in t:
t.remove('')
t.remove(t[0])
t[len(t) - 1] = t[len(t) - 1][:-1]
dataset = {}
for n in range(0, len(t)-1):
data_name = data_order[n]
dataset[data_name] = t[n]
db[s][p].append(dataset)
with open('./output/dataset.json', 'w+') as jf:
jf.write(json.dumps(db, sort_keys=True, indent=4))
outputData = {'CL': {}, 'CDtot': {}, 'CS': {}, 'CMx': {}, 'CMy': {}, 'CMz': {}}
for o in outputData.keys():
outputData[o]['base'] = {}
outputData[o]['base'][0] = {}
for r in input_txt.keys():
outputData[o][r] = {}
for p in input_txt[r].keys():
outputData[o][r][p] = {}
# format: ouputData[datapoint][surface]{position}[beta][mach][AoA]
# db[surface][position][datapoint]
desc = '''Generated by vsp2jsbsim.py
Author: Jüttner Domokos\n
Based on the work of Richard Harrison'''
of.write('<!--\n')
of.write(desc)
of.write('-->\n')
of.write('<aerodynamics>\n\n')
of.write(' <function name="aero/beta-deg-abs">\n')
of.write(' <description>Beta absolute value</description>\n')
of.write(' <abs>\n')
of.write(' <property>aero/beta-deg</property>\n')
of.write(' </abs>\n')
of.write(' </function>\n')
of.write('\n')
of.write(' <function name="aero/pb">\n')
of.write(' <description>PB Denormalization</description>\n')
of.write(' <product>\n')
of.write(' <property>aero/bi2vel</property>\n')
of.write(' <property>velocities/p-aero-rad_sec</property>\n')
of.write(' </product>\n')
of.write(' </function>\n')
of.write('\n')
of.write(' <function name="aero/qb">\n')
of.write(' <description>For denormalization</description>\n')
of.write(' <product>\n')
of.write(' <property>aero/ci2vel</property>\n')
of.write(' <property>velocities/q-aero-rad_sec</property>\n')
of.write(' </product>\n')
of.write(' </function>\n')
of.write('\n')
of.write(' <function name="aero/rb">\n')
of.write(' <description>For denormalization</description>\n')
of.write(' <product>\n')
of.write(' <property>aero/bi2vel</property>\n')
of.write(' <property>velocities/r-aero-rad_sec</property>\n')
of.write(' </product>\n')
of.write('\n')
of.write(' </function>\n')
for datapoint in outputData.keys():
print('#####', datapoint)
of.write(' <!-- ' + datapoint.upper() + ' -->\n')
for run in outputData[datapoint].keys():
print('-', run)
of.write(' <!-- ' + run + ' -->\n')
for pos in outputData[datapoint][run].keys():
betas = []
for d in db[run][pos]:
if d['beta'] not in betas:
betas.append(float(d['beta']))
for d in db[run][pos]:
bv = smallNumberCheck(float("%.5f" % float(d[datapoint])))
try:
if len(str(bv).split('.')[1]) < 5:
bv = str(bv) + '0' * (5 - len(str(bv).split('.')[1]))
except IndexError:
pass
if run != 'base':
basedict = outputData[datapoint]['base'][0]
baseValue = smallNumberCheck(float(basedict[d['beta']]
[d['Mach']][d['AoA']]))
v = smallNumberCheck(float("%.5f" %
(float(bv) - baseValue)))
try:
if not str(v).startswith('-'):
v = ' ' + str(v)
if len(str(v).split('.')[1]) < 5:
v = str(v) + '0' * (5 - len(str(v).split('.')[1]))
except IndexError:
pass
if not str(bv).startswith('-'):
bv = ' ' + str(bv)
try:
if run == 'base':
outputData[datapoint][run][pos][d['beta']][d['Mach']][d['AoA']] = bv
else:
outputData[datapoint][run][pos][d['beta']][d['Mach']][d['AoA']] = v
od.write(json.dumps(outputData, sort_keys=True, indent=4))
except KeyError:
try:
outputData[datapoint][run][pos][d['beta']][d['Mach']] = {}
if run == 'base':
outputData[datapoint][run][pos][d['beta']][d['Mach']][d['AoA']] = bv
else:
outputData[datapoint][run][pos][d['beta']][d['Mach']][d['AoA']] = v
od.write(json.dumps(outputData, sort_keys=True, indent=4))
except KeyError:
outputData[datapoint][run][pos][d['beta']] = {}
outputData[datapoint][run][pos][d['beta']][d['Mach']] = {}
if run == 'base':
outputData[datapoint][run][pos][d['beta']][d['Mach']][d['AoA']] = bv
else:
outputData[datapoint][run][pos][d['beta']][d['Mach']][d['AoA']] = v
od.write(json.dumps(outputData, sort_keys=True, indent=4))
with open('./outputData.json', 'w+') as jf:
jf.write(json.dumps(outputData, sort_keys=True, indent=4))
# parse tables
# ground effect handled seperatly
if run == 'ground_effect':
continue
if run != 'base':
of.write(' <function name="aero/' + datapoint + '_' + run + '_' + str(pos) + '">\n')
else:
of.write(' <function name="aero/' + datapoint + '_' + run + '">\n')
of.write(' <table>\n')
of.write(' <independentVar lookup="row">velocities/mach</independentVar>\n')
of.write(' <independentVar lookup="column">aero/alpha-deg</independentVar>\n')
of.write(' <independentVar lookup="table">aero/beta-deg</independentVar>\n')
for b in outputData[datapoint][run][pos].keys():
of.write(' <tableData breakPoint="' + str(float(b)) + '">\n')
txt_CL = ' '
machs = []
aoa = []
for m in outputData[datapoint][run][pos][b].keys():
if m not in machs:
machs.append(m)
for a in outputData[datapoint][run][pos][b][m].keys():
a = str(float(a))
if len(a.split('.')[0]) < 3:
a = ' ' * (3 - len(a.split('.')[0])) + a
if len(a) < 6:
a += ' ' * (6 - len(a))
if a not in aoa:
txt_CL += a[:-3] + ' '
aoa.append(a)
# print(aoa)
txt_CL = txt_CL[:-1] + '\n'
for m in outputData[datapoint][run][pos][b].keys():
line = ' ' + str(float(m)) + ' '
for c in outputData[datapoint][run][pos][b][m].values():
line += str(c) + ' '
txt_CL += line[:-2] + '\n'
of.write(txt_CL[:-1] + '\n')
of.write(' </tableData>\n\n')
of.write(' </table>\n')
of.write(' </function>\n\n')
# interpolate them
if run != 'base' and run != 'ground_effect':
of.write(' <function name="aero/' + datapoint + '_' + run + '">\n')
of.write(' <interpolate1d>\n')
if run != 'ground_effect':
of.write(' <property>fcs/surfaces/' + run + '-pos-deg</property>\n')
else:
of.write(' <property>position/h-agl-m</property>\n')
lastDeg = None
degList = [float(f) for f in outputData[datapoint][run].keys()]
degList_unsorted = degList
degList.sort()
for deg in degList:
if deg % 1 == 0:
deg = int(deg)
if (lastDeg is None or lastDeg < 0) and deg > 0:
of.write(' <value>0</value> <value>0</value>\n')
of.write(' <value>' + str(deg) + '</value> <property>aero/' + datapoint + '_' + run + '_' + str(deg) + '</property>\n')
lastDeg = deg
if lastDeg < 0:
of.write(' <value>0</value> <value>0</value>\n')
of.write(' </interpolate1d>\n')
of.write(' </function>\n\n')
# for d in outputData.keys():
# ge = outputData[d]['ground_effect']
# alts = [i for i in ge.keys()]
# betas = [i for i in ge[alts[0]].keys()]
# machs = [i for i in ge[betas[0]][alts[0]].keys()]
# aoa = [i for i in ge[betas[0]][alts[0]][machs[0]].keys()]
# of.write(' <function name="aero/' + datapoint + '_' + run + '_' + str(pos) + '">\n')
# of.write(' <table>\n')
# of.write(' <independentVar lookup="row">velocities/mach</independentVar>\n')
# of.write(' <independentVar lookup="column">aero/alpha-deg</independentVar>\n')
# of.write(' <independentVar lookup="table">position/h-agl-m</independentVar>\n')
# for m in machs:
# of.write(' <tableData breakPoint="' + str(float(agl)) + '">\n')
# txt_CL = ' '
# for a in aoa:
# txt_CL += str(a) + ' '
# txt_CL += '\n'
# for a in alts:
# line = ' ' * 6 + a + ' '
# for c in
# machs = []
# aoa = []
# for m in outputData[datapoint][run][pos][b].keys():
# if m not in machs:
# machs.append(m)
# for a in outputData[datapoint][run][pos][b][m].keys():
# a = str(float(a))
# if len(a.split('.')[0]) < 3:
# a = ' ' * (3 - len(a.split('.')[0])) + a
# if len(a) < 6:
# a += ' ' * (6 - len(a))
# if a not in aoa:
# txt_CL += a[:-3] + ' '
# aoa.append(a)
# txt_CL = txt_CL[:-1] + '\n'
# for m in outputData[datapoint][run][pos][b].keys():
# line = ' ' + str(float(m)) + ' '
# for c in outputData[datapoint][run][pos][b][m].values():
# line += str(c) + ' '
# txt_CL += line[:-2] + '\n'
# of.write(txt_CL[:-1] + '\n')
# of.write(' </tableData>\n\n')
# of.write(' </table>\n')
# of.write(' </function>\n\n')
# Stability - pretty much copypase of pinto's stab_format.py
print('##### stability')
data = []
mach = -9999
alpha = -9999
beta = -9999
cmlp = -9999
cmlr = -9999
cmma = -9999
cmmb = -9999
cmmq = -9999
cmnb = -9999
cmnr = -9999
cmnp = -9999
cfyp = -9999
cfyr = -9999
line = stab_file.readline()
def getdata(line):
while ' ' in line:
line = line.replace(' ', ' ')
return line.split(' ')
while line != "":
# print(line)
line_arr = getdata(line)
# gather main info
if line[0:5] == "Mach_":
mach = float(line[21:33])
elif line[0:4] == "AoA_":
alpha = float(line[21:33])
elif line[0:5] == "Beta_":
beta = float(line[21:33])
# gather coefficient info
elif line[0:3] == "CMx":
cmlp = float(line_arr[4]) # wrt p per rad colum
cmlr = float(line_arr[6]) # wrt r per rad column
elif line[0:3] == "CMy":
cmma = float(line_arr[2])
cmmb = float(line_arr[3])
cmmq = float(line_arr[5])
elif line[0:3] == "CMz":
cmnb = float(line_arr[3])
cmnr = float(line_arr[4])
cmnp = float(line_arr[6])
elif line[0:2] == "CS":
cfyp = float(line_arr[4])
cfyr = float(line_arr[6])
# output data
elif line[0:8] == "# Result":
data.append({'mach' : mach,
'alpha' : alpha,
'beta' : beta,
'cmlp' : cmlp,
'cmlr' : cmlr,
'cmma' : cmma,
'cmmb' : cmmb,
'cmmq' : cmmq,
'cmnb' : cmnb,
'cmnr' : cmnr,
'cmnp' : cmnp,
'cfyp' : cfyp,
'cfyr' : cfyr,
})
# reinit values
mach = -9999
alpha = -9999
beta = -9999
cmlp = -9999
cmlr = -9999
cmma = -9999
cmmb = -9999
cmmq = -9999
cmnb = -9999
cmnr = -9999
cmnp = -9999
cfyp = -9999
cfyr = -9999
line = stab_file.readline()
stab_file.close()
# build an array of mach, alpha, and beta values
mach_arr = []
alpha_arr = []
beta_arr = []
false = 0
true = 1
for i in data:
match = false
for j in mach_arr:
if j == i['mach']:
match = true
if not match:
mach_arr.append(i['mach'])
match = false
for j in alpha_arr:
if j == i['alpha']:
match = true
if not match:
alpha_arr.append(i['alpha'])
match = false
for j in beta_arr:
if j == i['beta']:
match = true
break
if not match:
beta_arr.append(i['beta'])
match = false
output_coeffs = {
# not included are: cmmb, cmnb
'cmlp': ['Roll damping derivative', 'aero/pb'],
'cmlr': ['Roll moment due to yaw rate', 'aero/rb'],
'cmmq': ['Pitch damping derivative', 'aero/qb'],
'cmma': ['Pitch moment alpha dot', 'aero/alphadot-rad_sec'],
'cmnp': ['Yaw moment due to roll rate', 'aero/pb'],
'cmnr': ['Yaw damping derivative', 'aero/rb'],
'cfyp': ['Side force due to roll rate', 'aero/pb'],
'cfyr': ['Side force due to yaw rate', 'aero/rb'],
}
# of.write('<?xml version="1.0"?>\n\n')
for coeff in output_coeffs:
dprint(coeff)
of.write(' <function name="aero/s/' + coeff + '">\n')
of.write(' <description>' + output_coeffs[coeff][0] + '</description>\n')
of.write(' <product>\n')
of.write(' <property>' + output_coeffs[coeff][1] + '</property>\n')
of.write(' <table>\n')
of.write(' <independentVar lookup="row">velocities/mach</independentVar>\n')
of.write(' <independentVar lookup="column">aero/alpha-deg</independentVar>\n')
of.write(' <independentVar lookup="table">aero/beta-deg</independentVar>\n')
if coeff not in params['alpha_only'] or true:
of.write(' <tableData breakPoint="' + str(data[0]['beta']) + '">\n')
of.write(' ')
for a in alpha_arr:
a = str(a)
if len(a.split('.')[0]) < 3:
a = ' ' * (3 - len(a.split('.')[0])) + a
of.write(str(a) + ' ')
of.write('\n')
of.write(' ')
mp = str(data[0]['mach'])
if not mp.startswith('-'):
mp = ' ' + mp
if len(mp.split('.')[1]) < 4:
mp += ' ' * (4 - len(mp.split('.')[1]))
of.write(mp)
b_beta = data[0]['beta']
b_mach = data[0]['mach']
for i in data:
if coeff in params['alpha_only'] and i['beta'] != 0:
continue
if b_beta != i['beta']:
b_beta = i['beta']
if coeff not in params['alpha_only']:
of.write('\n </tableData>\n')
of.write(' <tableData breakPoint="' +
str(i['beta']) + '">\n')
of.write(' ')
for a in alpha_arr:
a = str(a)
if len(a.split('.')[0]) < 3:
a = ' ' * (3 - len(a.split('.')[0])) + a
of.write(str(a) + ' ')
if b_mach != i['mach']:
b_mach = i['mach']
of.write('\n ')
mp = str(i['mach'])
if not mp.startswith('-'):
mp = ' ' + mp
if len(mp.split('.')[1]) < 4:
mp += ' ' * (4 - len(mp.split('.')[1]))
of.write(mp)
cf = str(smallNumberCheck(i[coeff]))
if not cf.startswith('-'):
cf = ' ' + cf
if len(cf.split('.')[1]) < 7:
cf += '0' * (7 - len(cf.split('.')[1]))
of.write(' ' + cf)
of.write('\n </tableData>\n')
of.write(' </table>\n')
of.write(' </product>\n')
of.write(' </function>\n\n')
outputitems = {'forces': {'lift': 'CL', 'drag': 'CDtot', 'side': 'CS'},
'moments': {'pitch': 'CMy', 'roll': 'CMx', 'yaw': 'CMz'}}
# AXIS definitions
# for g in outputitems.keys():
# for o in outputitems[g].keys():
# of.write(' <axis name="' + o.upper() + '">\n')
# of.write(' <function name="aero/' + g + '/' + o + '">\n')
# of.write(' <product>\n')
# of.write(' <property>aero/qbar-psf</property>\n')
# of.write(' <property>metrics/Sw-sqft</property>\n')
# if g == 'moments':
# if o == 'pitch' or o == 'roll':
# of.write(' <property>metrics/bw-ft</property>\n')
# elif o == 'yaw':
# of.write(' <property>metrics/cbarw-ft</property>\n')
# of.write(' <sum>\n')
# for r in outputData[outputitems[g][o]].keys():
# of.write(' <property>aero/' + outputitems[g][o] + '_' + r + '</property>\n')
# if g == 'moments':
# if o == 'pitch':
# of.write(' <property>aero/s/cmmq</property>\n')
# # elif o == 'roll':
# elif False:
# of.write(' <property>aero/s/cmlp</property>\n')
# of.write(' <property>aero/s/cmlr</property>\n')
# elif o == 'yaw':
# of.write(' <property>aero/s/cmnp</property>\n')
# of.write(' <property>aero/s/cmnr</property>\n')
# elif g == 'force' and o == 'side':
# of.write(' <property>aero/s/cfyp</property>\n')
# of.write(' <property>aero/s/cfyr</property>\n')
# of.write(' </sum>\n')
# of.write(' </product>\n')
# of.write(' </function>\n')
# of.write(' </axis>\n\n')
with open(params['axis_file'], 'r') as axis:
for l in axis.readlines():
of.write(l)
of.close()
od.close()
print('process time:', time.process_time())