-
Notifications
You must be signed in to change notification settings - Fork 3
/
pyAVL.py
1866 lines (1497 loc) · 71.9 KB
/
pyAVL.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
"""
pyAVL
pyAVL is a wrapper for Mark Drela's AVL code. The purpose of this
class is to provide an easy to use wrapper for avl for intergration
into other projects.
Developers:
-----------
- Josh Anibal (JLA)
History
-------
v. 0.0 - Initial Class Creation (JLA, 08 2016)
v. 0.1 - Added CDFF and sectional properties for all surfaces (JLA, 12 2017)
v. 1.0 - major refactor (I learned a lot more programming in 7 years) (JLA, 02 2023)
"""
# =============================================================================
# Standard Python modules
# =============================================================================
import os
import time
import copy
from pprint import pprint
from typing import Dict, List, Tuple, Union, Any
import warnings
import glob
from typing import Optional
# =============================================================================
# External Python modules
# =============================================================================
import numpy as np
# =============================================================================
# Extension modules
# =============================================================================
from . import MExt
class AVLSolver(object):
# these at technically parameters, but they are also specified as contraints
# These are not included in the derivatives but you can set and get them still
# In the code these are only used to save the state for mode analysis
# regardless they can be useful for getting the values after a trim solve
state_param_idx_dict = {
"alpha": 0,
"beta": 1,
"roll rate": 2,
"pitch rate": 3,
"yaw rate": 4,
# Not a supported way to set CL as a contraint or get it as an output
# "CL": 5,
}
param_idx_dict = {
# these aero state parameters
"CD0": 6,
"bank": 7,
"elevation": 8,
"heading": 9,
"Mach": 10,
"velocity": 11,
"density": 12,
"grav.acc.": 13,
"turn rad.": 14,
"load fac.": 15,
"X cg": 16,
"Y cg": 17,
"Z cg": 18,
"mass": 19,
"Ixx": 20,
"Iyy": 21,
"Izz": 22,
"Ixy": 23,
"Iyz": 24,
"Izx": 25,
"visc CL_a": 26,
"visc CL_u": 27,
"visc CM_a": 28,
"visc CM_u": 29,
}
# fmt: off
# This dict has the following structure:
# python key: [common block name, fortran varaiable name]
case_var_to_fort_var = {
# lift and drag from surface integration (wind frame)
"CL": ["CASE_R", "CLTOT"],
"CD": ["CASE_R", "CDTOT"],
"CDv": ["CASE_R", "CDVTOT"], # viscous drag
# lift and drag calculated from farfield integration
"CLff": ["CASE_R", "CLFF"],
"CYff": ["CASE_R", "CYFF"],
"CDi": ["CASE_R", "CDFF"], # induced drag
# non-dimensionalized forces
"CX": ["CASE_R", "CXTOT"],
"CY": ["CASE_R", "CYTOT"],
"CZ": ["CASE_R", "CZTOT"],
# non-dimensionalized moments (body frame)
"CR BA": ["CASE_R", "CRTOT"],
"CM": ["CASE_R", "CMTOT"],
"CN BA": ["CASE_R", "CNTOT"],
# non-dimensionalized moments (stablity frame)
"CR SA": ["CASE_R", "CRSAX"],
# "CM SA": ["CASE_R", "CMSAX"], # This is the same in both frames
"CN SA": ["CASE_R", "CNSAX"],
# spanwise efficiency
"e": ["CASE_R", "SPANEF"],
}
ref_var_to_fort_var = {
"Sref": ["CASE_R", "SREF"],
"Cref": ["CASE_R", "CREF"],
"Bref": ["CASE_R", "BREF"],
}
case_derivs_to_fort_var = {
# derivative of coefficents wrt control surface deflections
"CL": ["CASE_R", "CLTOT_D"],
"CD": ["CASE_R", "CDTOT_D"],
"CX": ["CASE_R", "CXTOT_D"],
"CY": ["CASE_R", "CYTOT_D"],
"CZ": ["CASE_R", "CZTOT_D"],
"CR": ["CASE_R", "CRTOT_D"],
"CM": ["CASE_R", "CMTOT_D"],
"CN": ["CASE_R", "CNTOT_D"],
}
case_stab_derivs_to_fort_var = {
# derivative of coefficents wrt alpha
"CL": {
"alpha": ["CASE_R", "CLTOT_AL"],
"beta": ["CASE_R", "CLTOT_BE"],
"roll rate": ["CASE_R", "CLTOT_RX"],
"pitch rate": ["CASE_R", "CLTOT_RY"],
"yaw rate": ["CASE_R", "CLTOT_RZ"],
},
"CD": {
"alpha": ["CASE_R", "CDTOT_AL"],
"beta": ["CASE_R", "CDTOT_BE"],
"roll rate": ["CASE_R", "CDTOT_RX"],
"pitch rate": ["CASE_R", "CDTOT_RY"],
"yaw rate": ["CASE_R", "CDTOT_RZ"],
},
"CY": {
"alpha": ["CASE_R", "CYTOT_AL"],
"beta": ["CASE_R", "CYTOT_BE"],
"roll rate": ["CASE_R", "CYTOT_RX"],
"pitch rate": ["CASE_R", "CYTOT_RY"],
"yaw rate": ["CASE_R", "CYTOT_RZ"],
},
"CR SA": {
"alpha": ["CASE_R", "CRTOT_AL"],
"beta": ["CASE_R", "CRTOT_BE"],
"roll rate": ["CASE_R", "CRTOT_RX"],
"pitch rate": ["CASE_R", "CRTOT_RY"],
"yaw rate": ["CASE_R", "CRTOT_RZ"],
},
"CM": {
"alpha": ["CASE_R", "CMTOT_AL"],
"beta": ["CASE_R", "CMTOT_BE"],
"roll rate": ["CASE_R", "CMTOT_RX"],
"pitch rate": ["CASE_R", "CMTOT_RY"],
"yaw rate": ["CASE_R", "CMTOT_RZ"],
},
"CN SA": {
"alpha": ["CASE_R", "CNTOT_AL"],
"beta": ["CASE_R", "CNTOT_BE"],
"roll rate": ["CASE_R", "CNTOT_RX"],
"pitch rate": ["CASE_R", "CNTOT_RY"],
"yaw rate": ["CASE_R", "CNTOT_RZ"],
},
}
# This dict has the following structure:
# python key: [common block name, fortran varaiable name]
case_surf_var_to_fort_var = {
# surface contributions to total lift and drag from surface integration (wind frame)
"CL": ["SURF_R", "CLSURF"],
"CD": ["SURF_R", "CDSURF"],
"CDv": ["SURF_R", "CDVSURF"], # viscous drag
# non-dimensionalized forces
"CX": ["SURF_R", "CXSURF"],
"CY": ["SURF_R", "CYSURF"],
"CZ": ["SURF_R", "CZSURF"],
# non-dimensionalized moments (body frame)
"CR": ["SURF_R", "CRSURF"],
"CM": ["SURF_R", "CMSURF"],
"CN": ["SURF_R", "CNSURF"],
# forces non-dimentionalized by surface quantities
# uses surface area instead of sref and takes moments about leading edge
"CL surf" : ["SURF_R", "CL_SRF"],
"CD surf" : ["SURF_R", "CD_SRF"],
"CMLE surf" : ["SURF_R", "CMLE_SRF"],
#TODO: add CF_SRF(3,NFMAX), CM_SRF(3,NFMAX)
}
body_geom_to_fort_var = {
"scale": ["BODY_GEOM_R", "XYZSCAL_B"],
"translate": ["BODY_GEOM_R", "XYZTRAN_B"],
"yduplicate": ["BODY_GEOM_R", "YDUPL_B"],
"bfile": ["CASE_C", "BFILES"],
"nvb": ["BODY_GEOM_I", "NVB"],
"bspace": ["BODY_GEOM_R", "BSPACE"],
}
# fmt: on
ad_suffix = "_DIFF"
def __init__(self, geo_file=None, mass_file=None, debug=False, timing=False):
if timing:
start_time = time.time()
# MExt is important for creating multiple instances of the AVL solver that do not share memory
# It is very gross, but I cannot figure out a better way (maybe use install_name_tool to change the dynamic library path to absolute).
# increment this counter for the hours you wasted on trying find a better way
# 7 hours
module_dir = os.path.dirname(os.path.realpath(__file__))
module_name = os.path.basename(module_dir)
avl_lib_so_file = glob.glob(os.path.join(module_dir, "libavl*.so"))[0]
# # get just the file name
avl_lib_so_file = os.path.basename(avl_lib_so_file)
self.avl = MExt.MExt("libavl", module_name, "pyavl_wrapper", lib_so_file=avl_lib_so_file, debug=debug)._module
# this way doesn't work with mulitple isntances fo AVLSolver
# from . import libavl
# self.avl = libavl
if not (geo_file is None):
try:
# check to make sure files exist
file = geo_file
f = open(geo_file, "r")
f.close()
if not (mass_file is None):
file = mass_file
f = open(mass_file, "r")
f.close()
except FileNotFoundError:
raise FileNotFoundError(
f"Could not open the file '{file}' from python. This is usually an issue with the specified file path"
)
self.avl.avl()
if debug:
self.set_avl_fort_arr("CASE_L", "LVERBOSE", True)
if timing:
self.set_avl_fort_arr("CASE_L", "LTIMING", True)
self.avl.loadgeo(geo_file)
if mass_file is not None:
self.avl.loadmass(mass_file)
else:
raise ValueError("neither a geometry file or aircraft object was given")
# todo store the default dict somewhere else
# the control surface contraints get added to this array in the __init__
self.conval_idx_dict = {
"alpha": 0,
"beta": 1,
"roll rate": 2,
"pitch rate": 3,
"yaw rate": 4,
"CL": 5,
"CY": 6,
"CR BA": 7,
"CM": 8,
"CR": 9,
}
# control surfaces added in __init__
#TODO: the keys of this dict aren't used
self.con_var_to_fort_var = {
"alpha": ["CASE_R", "ALFA"],
"beta": ["CASE_R", "BETA"],
}
control_names = self.get_control_names()
self.control_variables = {}
for idx_c_var, c_name in enumerate(control_names):
self.control_variables[c_name] = f"D{idx_c_var+1}"
# set control surface constraint indecies in to con val dict
idx_control_start = np.max([x for x in self.conval_idx_dict.values()]) + 1
for idx_c_var, c_name in enumerate(control_names):
self.conval_idx_dict[c_name] = idx_control_start + idx_c_var
self.con_var_to_fort_var[c_name] = ["CASE_R", "DELCON"]
# the case parameters are stored in a 1d array,
# these indices correspond to the position of each parameter in that arra
self._init_surf_data()
if timing:
print(f"AVL init took {time.time() - start_time} seconds")
def _init_surf_data(self):
self.surf_geom_to_fort_var = {}
surf_names = self.get_surface_names()
self.surf_pannel_to_fort_var = {}
self.con_surf_to_fort_var = {}
for idx_surf, surf_name in enumerate(surf_names):
idx_surf = surf_names.index(surf_name)
slice_idx_surf = (idx_surf,)
slice_surf_all = (idx_surf, slice(None))
# only set unduplicated sufaces
if self.get_avl_fort_arr("SURF_I", "IMAGS", slicer=slice_idx_surf) < 0:
# this is a duplicated surface, skip it
continue
num_sec = self.get_avl_fort_arr("SURF_GEOM_I", "NSEC", slicer=slice_idx_surf)
slice_surf_secs = (idx_surf, slice(None, num_sec))
slice_surf_secs_all = slice_surf_secs + (slice(None),)
nasec = self.get_avl_fort_arr("SURF_GEOM_I", "NASEC", slicer=slice_surf_secs)
# I don't see a case in the code where nasec is not the same for all sections
# but just in case, we'll do a test and throw an error if not
if np.unique(nasec).size != 1:
raise RuntimeError("nasec is not the same for all sections")
nasec = nasec[0]
slice_surf_secs_nasec = slice_surf_secs + (slice(None, nasec),)
self.surf_geom_to_fort_var[surf_name] = {
"scale": ["SURF_GEOM_R", "XYZSCAL", slice_surf_all],
"translate": ["SURF_GEOM_R", "XYZTRAN", slice_surf_all],
"angle": ["SURF_GEOM_R", "ADDINC", slice_idx_surf],
"xyzles": ["SURF_GEOM_R", "XYZLES", slice_surf_secs_all],
"chords": ["SURF_GEOM_R", "CHORDS", slice_surf_secs],
"aincs": ["SURF_GEOM_R", "AINCS", slice_surf_secs],
"xasec": ["SURF_GEOM_R", "XASEC", slice_surf_secs_nasec],
"sasec": ["SURF_GEOM_R", "SASEC", slice_surf_secs_nasec],
"tasec": ["SURF_GEOM_R", "TASEC", slice_surf_secs_nasec],
"clcdsec": ["SURF_GEOM_R", "CLCDSEC", slice_surf_secs_all],
"claf": ["SURF_GEOM_R", "CLAF", slice_surf_secs],
}
self.surf_pannel_to_fort_var[surf_name] = {
"nchordwise": ["SURF_GEOM_I", "NVC", slice_idx_surf],
"cspace": ["SURF_GEOM_R", "CSPACE", slice_idx_surf],
"nspan": ["SURF_GEOM_I", "NVS", slice_idx_surf],
"sspace": ["SURF_GEOM_R", "SSPACE", slice_idx_surf],
"sspaces": ["SURF_GEOM_R", "SSPACES", slice_surf_secs],
"nspans": ["SURF_GEOM_I", "NSPANS", slice_surf_secs],
"yduplicate": ["SURF_GEOM_R", "YDUPL", slice_idx_surf],
"use surface spacing": ["SURF_GEOM_L", "LSURFSPACING", slice_idx_surf],
"component": ["SURF_I", "LSCOMP", slice_idx_surf],
}
icontd_slices = []
idestd_slices = []
xhinged_slices = []
vhinged_slices = []
gaind_slices = []
refld_slices = []
gaing_slices = []
for idx_sec in range(num_sec):
slice_surf = (idx_surf, idx_sec)
num_con_surf = self.get_avl_fort_arr("SURF_GEOM_I", "NSCON", slicer=slice_surf)
slice_surf_con = slice_surf + (slice(None, num_con_surf),)
slice_surf_con_hinge = slice_surf_con + (slice(None),)
num_des_var = self.get_avl_fort_arr("SURF_GEOM_I", "NSDES", slicer=slice_surf)
slice_surf_des_var = slice_surf + (slice(None, num_des_var),)
icontd_slices.append(slice_surf_con)
xhinged_slices.append(slice_surf_con)
vhinged_slices.append(slice_surf_con_hinge)
gaind_slices.append(slice_surf_con)
refld_slices.append(slice_surf_con)
idestd_slices.append(slice_surf_des_var)
gaing_slices.append(slice_surf_des_var)
self.con_surf_to_fort_var[surf_name] = {
"icontd": ["SURF_GEOM_I", "ICONTD", icontd_slices],
"xhinged": ["SURF_GEOM_R", "XHINGED", xhinged_slices],
"vhinged": ["SURF_GEOM_R", "VHINGED", vhinged_slices],
"gaind": ["SURF_GEOM_R", "GAIND", gaind_slices],
"refld": ["SURF_GEOM_R", "REFLD", refld_slices],
"idestd": ["SURF_GEOM_I", "IDESTD", idestd_slices],
"gaing": ["SURF_GEOM_R", "GAING", gaing_slices],
}
def add_constraint(self, var, val, con_var=None):
avl_variables = {
"alpha": "A",
"beta": "B",
"roll rate": "R",
"pitch rate": "P",
"yaw rate": "Y",
}
avl_con_variables = copy.deepcopy(avl_variables)
avl_con_variables.update(
{
"CL": "C",
"CY": "S",
"Cl roll moment": "RM",
"Cm pitch moment": "PM",
"Cn yaw moment": "YM",
}
)
if var in avl_variables:
# save the name of the avl_var
avl_var = avl_variables[var]
elif var in self.control_variables.keys():
avl_var = self.control_variables[var]
elif var in self.control_variables.values():
avl_var = var
else:
raise ValueError(
f"specified variable `{var}` not a valid option. Must be one of the following variables{[key for key in avl_variables]} or control surface name or index{[item for item in self.control_variables.items()]}. Constraints that must be implicitly satisfied (such as `CL`) are set with `add_trim_constraint`."
)
if con_var is None:
avl_con_var = avl_var
elif con_var in avl_con_variables:
avl_con_var = avl_con_variables[con_var]
elif con_var in self.control_variables.keys():
avl_con_var = self.control_variables[con_var]
elif con_var in self.control_variables.values():
avl_con_var = con_var
else:
raise ValueError(
f"specified contraint variable `{con_var}` not a valid option. Must be one of the following variables{[key for key in avl_variables]} or control surface name or index{[item for item in self.control_variables.items()]}."
)
# check that the type of val is correct
if not isinstance(val, (int, float, np.floating, np.integer)):
raise TypeError(f"contraint value must be a int or float for contraint {var}. Got {type(val)}")
self.avl.conset(avl_var, f"{avl_con_var} {val} \n")
def add_trim_condition(self, variable, val):
options = {
"bankAng": ["B"],
"CL": ["C"],
"velocity": ["V"],
"mass": ["M"],
"dens": ["D"],
"G": ["G"],
"X cg": ["X"],
"Y cg": ["Y"],
"Z cg": ["Z"],
}
if not (variable in options):
raise ValueError(
f"constraint variable `{variable}` not a valid option. Must be one of the following {[key for key in options]} "
)
self.avl.trmset("C1", "1 ", options[variable][0], (str(val) + " \n"))
def get_case_total_data(self) -> Dict[str, float]:
"""Get the aerodynamic data for the last run case and return it as a dictionary.
Returns:
Dict[str, float]: Dictionary of aerodynamic data. The keys the aerodyanmic coefficients.
"""
total_data = {}
for key, avl_key in self.case_var_to_fort_var.items():
val = self.get_avl_fort_arr(*avl_key)
# [()] because all the data is stored as a ndarray.
# for scalars this results in a 0-d array.
# It is easier to work with floats so we extract the value with [()]
total_data[key] = val[()]
return total_data
def get_case_coef_derivs(self) -> Dict[str, Dict[str, float]]:
deriv_data = {}
control_names = self.get_control_names()
for key, avl_key in self.case_derivs_to_fort_var.items():
slicer = slice(0, len(control_names))
val_arr = self.get_avl_fort_arr(*avl_key, slicer=slicer)
deriv_data[key] = {}
for idx_control, val in enumerate(val_arr):
control = control_names[idx_control]
deriv_data[key][control] = val[()]
return deriv_data
def get_case_stab_derivs(self) -> Dict[str, Dict[str, float]]:
deriv_data = {}
for func_key, var_dict in self.case_stab_derivs_to_fort_var.items():
deriv_data[func_key] = {}
for var_key, avl_key in var_dict.items():
val_arr = self.get_avl_fort_arr(*avl_key)
deriv_data[func_key][var_key] = val_arr[()]
return deriv_data
def get_reference_data(self) -> Dict[str, float]:
ref_data = {}
for key, avl_key in self.ref_var_to_fort_var.items():
ref_data[key] = self.get_avl_fort_arr(*avl_key)[()]
return ref_data
def set_reference_data(self, ref_data: Dict[str, float]) -> None:
for key, val in ref_data.items():
avl_key = self.ref_var_to_fort_var[key]
self.set_avl_fort_arr(*avl_key, val)
return ref_data
def get_avl_fort_arr(self, common_block, variable, slicer=None):
# this had to be split up into two steps to work
# get the corresponding common block object.
# it must be lowercase because of f2py
common_block = getattr(self.avl, common_block.upper())
# get the value of the variable from the common block
val = getattr(common_block, variable.upper())
# convert from fortran ordering to c ordering
val = val.ravel(order="F").reshape(val.shape[::-1], order="C")
# Apply slicer if provided
if slicer is not None:
val = val[slicer]
return val
def set_avl_fort_arr(self, common_block, variable, val, slicer=None) -> None:
# convert from fortran ordering to c ordering
if isinstance(val, np.ndarray):
val = val.ravel(order="C").reshape(val.shape[::-1], order="F")
# this had to be split up into two steps to work
# get the corresponding common block object.
# it must be lowercase because of f2py
common_block_obj = getattr(self.avl, common_block.upper())
# get the value of the variable from the common block
if slicer is None:
setattr(common_block_obj, variable.upper(), val)
else:
# flip the order of the slicer to match the cordinates of the val
new_slicer = slicer[::-1]
original_val = getattr(common_block_obj, variable.upper())
original_val[new_slicer] = val
setattr(common_block_obj, variable.upper(), original_val)
return
def get_case_surface_data(self) -> Dict[str, Dict[str, float]]:
surf_names = self.get_surface_names()
# add a dictionary for each surface that will be filled later
surf_data = {}
for surf in surf_names:
surf_data[surf] = {}
for key, avl_key in self.case_surf_var_to_fort_var.items():
vals = self.get_avl_fort_arr(*avl_key)
# add the values to corresponding surface dict
for idx_surf, surf_name in enumerate(surf_names):
surf_data[surf_name][key] = vals[idx_surf]
return surf_data
def get_case_parameter(self, param_key: str) -> float:
"""
analogous to ruinont Modify parameters for the oper menu to view parameters.
"""
parvals = self.get_avl_fort_arr("CASE_R", "PARVAL")
# the key could be in one of two dicts
if param_key in self.param_idx_dict:
idx_param = self.param_idx_dict[param_key]
elif param_key in self.state_param_idx_dict:
idx_param = self.state_param_idx_dict[param_key]
else:
raise ValueError(f"param '{param_key}' not in possilbe list\n"
f"{[k for k in self.param_idx_dict] + [k for k in self.state_param_idx_dict]}")
# [0] because pyavl only supports 1 run case
param_val = parvals[0][idx_param]
return param_val
def get_case_constraint(self, con_key: str) -> float:
""" """
convals = self.get_avl_fort_arr("CASE_R", "CONVAL")
# [0] because pyavl only supports 1 run case
con_val = convals[0][self.conval_idx_dict[con_key]]
return con_val
def set_case_parameter(self, param_key: str, param_val: float) -> None:
"""
analogous to ruinont Modify parameters for the oper menu to view parameters.
"""
# warn the user that alpha, beta,
if param_key is ["alpha", "beta", "pb/2V", "qc/2V", "rb/2V", "CL"]:
raise ValueError(
"alpha, beta, pb/2V, qc/2V, rb/2V, and CL are not allowed to be set,\n\
they are calculated during each run based on the contraints. to specify\n\
one of these values use the add_contraint method."
)
parvals = self.get_avl_fort_arr("CASE_R", "PARVAL")
# [0] because pyavl only supports 1 run case
parvals[0][self.param_idx_dict[param_key]] = param_val
self.set_avl_fort_arr("CASE_R", "PARVAL", parvals)
# (1) here because we want to set the first runcase with fortran indexing (the only one)
self.avl.set_params(1)
def get_control_deflections(self) -> Dict[str, float]:
control_surfaces = self.get_control_names()
def_arr = copy.deepcopy(self.get_avl_fort_arr("CASE_R", "DELCON"))
def_dict = {}
for idx_con, con_surf in enumerate(control_surfaces):
def_dict[con_surf] = def_arr[idx_con]
return def_dict
def get_hinge_moments(self) -> Dict[str, float]:
"""
get the hinge moments from the fortran layer and return them as a dictionary
"""
hinge_moments = {}
control_surfaces = self.get_control_names()
mom_array = self.get_avl_fort_arr("CASE_R", "CHINGE")
for idx_con, con_surf in enumerate(control_surfaces):
hinge_moments[con_surf] = mom_array[idx_con]
return hinge_moments
def get_hinge_moments(self) -> Dict[str, float]:
"""
get the hinge moments from the fortran layer and return them as a dictionary
"""
hinge_moments = {}
control_surfaces = self.get_control_names()
mom_array = self.get_avl_fort_arr("CASE_R", "CHINGE")
for idx_con, con_surf in enumerate(control_surfaces):
hinge_moments[con_surf] = mom_array[idx_con]
return hinge_moments
def get_strip_data(self) -> Dict[str, Dict[str, np.ndarray]]:
# fmt: off
var_to_fort_var = {
# geometric quantities
"chord": ["STRP_R", "CHORD"],
"width": ["STRP_R", "WSTRIP"],
"XYZ LE": ["STRP_R", "RLE"], # control point leading edge coordinates
"twist": ["STRP_R", "AINC"],
# strip contributions to total lift and drag from strip integration
"CL": ["STRP_R", "CLSTRP"],
"CD": ["STRP_R", "CDSTRP"],
# strip contributions to non-dimensionalized forces
"CX": ["STRP_R", "CXSTRP"],
"CY": ["STRP_R", "CYSTRP"],
"CZ": ["STRP_R", "CZSTRP"],
# strip contributions to total moments (body frame)
"CM": ["STRP_R", "CMSTRP"],
"CN": ["STRP_R", "CNSTRP"],
"CR": ["STRP_R", "CRSTRP"],
# forces non-dimentionalized by strip quantities
"CL strip" : ["STRP_R", "CL_LSTRP"],
"CD strip" : ["STRP_R", "CD_LSTRP"],
"CF strip" : ["STRP_R", "CF_STRP"], # forces in 3 directions
"CM strip" : ["STRP_R", "CF_STRP"], # moments in 3 directions
}
# fmt: on
surf_names = self.get_surface_names()
# add a dictionary for each surface that will be filled later
strip_data = {}
for surf in surf_names:
strip_data[surf] = {}
for key, avl_key in var_to_fort_var.items():
vals = self.get_avl_fort_arr(*avl_key)
# add the values to corresponding surface dict
for idx_surf, surf_name in enumerate(surf_names):
idx_srp_beg, idx_srp_end = self.get_surface_strip_indices(idx_surf)
strip_data[surf_name][key] = vals[idx_srp_beg:idx_srp_end]
cref = self.get_avl_fort_arr("CASE_R", "CREF")
for surf_key in strip_data:
# add sectional lift and drag
strip_data[surf_key]["lift dist"] = strip_data[surf_key]["CL"] * strip_data[surf_key]["chord"] / cref
strip_data[surf_key]["drag dist"] = strip_data[surf_key]["CD"] * strip_data[surf_key]["chord"] / cref
return strip_data
def get_surface_strip_indices(self, idx_surf):
num_strips = np.trim_zeros(self.get_avl_fort_arr("SURF_I", "NJ"))
idx_srp_beg = np.sum(num_strips[:idx_surf])
idx_srp_end = np.sum(num_strips[: idx_surf + 1])
return idx_srp_beg, idx_srp_end
def executeRun(self):
warnings.warn("executeRun is deprecated, use execute_run instead")
self.execute_run()
def execute_run(self, tol=0.00002):
# run the analysis (equivalent to the avl command `x` in the oper menu)
self.set_avl_fort_arr('CASE_R', 'EXEC_TOL', tol)
self.avl.oper()
def CLSweep(self, start_CL, end_CL, increment=0.1):
CLs = np.arange(start_CL, end_CL + increment, increment)
for cl in CLs:
self.add_trim_condition("CL", cl)
self.execute_run()
def get_control_names(self) -> List[str]:
fort_names = self.get_avl_fort_arr("CASE_C", "DNAME")
control_names = self._convertFortranStringArrayToList(fort_names)
return control_names
def get_surface_names(self, remove_dublicated=False) -> List[str]:
"""get the surface names from the geometry"""
fort_names = self.get_avl_fort_arr("CASE_C", "STITLE")
surf_names = self._convertFortranStringArrayToList(fort_names)
if remove_dublicated:
imags = self.get_avl_fort_arr("SURF_I", "IMAGS")
unique_surf_names = []
for idx_surf, surf_name in enumerate(surf_names):
# get surfaces that have not been duplicated
if imags[idx_surf] > 0:
unique_surf_names.append(surf_names[idx_surf])
return unique_surf_names
else:
return surf_names
def get_body_names(self, remove_dublicated=False) -> List[str]:
"""get the body names from the geometry"""
fort_names = self.get_avl_fort_arr("CASE_C", "BTITLE")
body_names = self._convertFortranStringArrayToList(fort_names)
if remove_dublicated:
# imags = self.get_avl_fort_arr("BODY_GEOM_L", "LDUPL_B")
# print(imags)
unique_body_names = []
for body_name in body_names:
# get bodyaces that have not been duplicated
# HACK: It is best not rely on this but, this is a quick fix for
# bodies which I discourage people from using anyways
if not body_name.endswith("(YDUP)"):
unique_body_names.append(body_name)
return unique_body_names
else:
return body_names
def get_con_surf_param(self, surf_name, idx_slice, param):
# the control surface and design variables need to be handeled differently because the number at each section is variable
if param in self.con_surf_to_fort_var[surf_name].keys():
fort_var = self.con_surf_to_fort_var[surf_name][param]
else:
raise ValueError(
f"param, {param}, not in found for {surf_name}, that has control surface data {self.con_surf_to_fort_var[surf_name].keys()}"
)
param = self.get_avl_fort_arr(fort_var[0], fort_var[1], slicer=fort_var[2][idx_slice])
return param
def set_con_surf_param(self, surf_name, idx_slice, param, val):
# the control surface and design variables need to be handeled differently because the number at each section is variable
if param in self.con_surf_to_fort_var[surf_name].keys():
fort_var = self.con_surf_to_fort_var[surf_name][param]
else:
raise ValueError(
f"param, {param}, not in found for {surf_name}, that has control surface data {self.con_surf_to_fort_var[surf_name].keys()}"
)
# param = self.get_avl_fort_arr(fort_var[0], fort_var[1], slicer=fort_var[2][idx_slice])
self.set_avl_fort_arr(fort_var[0], fort_var[1], val, slicer=fort_var[2][idx_slice])
def get_surface_param(self, surf_name, param):
# check that param is in self.surf_geom_to_fort_var
if param in self.surf_geom_to_fort_var[surf_name].keys():
fort_var = self.surf_geom_to_fort_var[surf_name][param]
elif param in self.surf_pannel_to_fort_var[surf_name].keys():
fort_var = self.surf_pannel_to_fort_var[surf_name][param]
else:
raise ValueError(
f"param, {param}, not in found for {surf_name}, that has geom data {list(self.surf_geom_to_fort_var[surf_name].keys()) + list(self.surf_pannel_to_fort_var[surf_name].keys())}"
)
param = self.get_avl_fort_arr(fort_var[0], fort_var[1], slicer=fort_var[2])
return param
def set_surface_param(self, surf_name, param, val):
if param in self.surf_geom_to_fort_var[surf_name].keys():
fort_var = self.surf_geom_to_fort_var[surf_name][param]
elif param in self.surf_pannel_to_fort_var[surf_name].keys():
fort_var = self.surf_pannel_to_fort_var[surf_name][param]
elif param in self.con_surf_to_fort_var[surf_name].keys():
# the control surface and design variables need to be handeled differently because the number at each section is variable
pass
else:
raise ValueError(
f"param, {param}, not in found for {surf_name}, that has geom data {list(self.surf_geom_to_fort_var[surf_name].keys()) + list(self.surf_pannel_to_fort_var[surf_name].keys())}"
)
self.set_avl_fort_arr(fort_var[0], fort_var[1], val, slicer=fort_var[2])
def get_surface_params(
self,
include_geom: bool = True,
include_panneling: bool = False,
include_con_surf: bool = False,
include_airfoils: bool = False,
) -> Dict[str, Dict[str, Any]]:
"""get the surface level parameters from the geometry
geom_only: only return the geometry parameters of the surface
- xle, yle, zle, chord, twist
"""
surf_names = self.get_surface_names()
unique_surf_names = self.get_surface_names(remove_dublicated=True)
surf_data = {}
for surf_name in unique_surf_names:
surf_data[surf_name] = {}
if include_geom:
for var in self.surf_geom_to_fort_var[surf_name]:
surf_data[surf_name][var] = self.get_surface_param(surf_name, var)
idx_surf = surf_names.index(surf_name)
if include_panneling:
# add panneling parameters if requested
for var in self.surf_pannel_to_fort_var[surf_name]:
surf_data[surf_name][var] = self.get_surface_param(surf_name, var)
if not self.get_avl_fort_arr("SURF_GEOM_L", "LDUPL")[idx_surf]:
surf_data[surf_name].pop("yduplicate")
if include_con_surf:
# add control surface parameters if requested
for var in self.con_surf_to_fort_var[surf_name]:
num_sec = self.get_avl_fort_arr("SURF_GEOM_I", "NSEC")[idx_surf]
slice_data = []
for idx_sec in range(num_sec):
tmp = self.get_con_surf_param(surf_name, idx_sec, var)
slice_data.append(tmp)
surf_data[surf_name][var] = slice_data
if include_airfoils:
afiles = []
num_sec = self.get_avl_fort_arr("SURF_GEOM_I", "NSEC")[idx_surf]
for idx_sec in range(num_sec):
afile = self.__decodeFortranString(self.avl.CASE_C.AFILES[idx_sec, idx_surf])
afiles.append(afile)
surf_data[surf_name]["afiles"] = afiles
return surf_data
def set_surface_params(self, surf_data: Dict[str, Dict[str, any]]) -> None:
"""set the give surface data into the current avl object.
ASSUMES THE CONTROL SURFACE DATA STAYS AT THE SAME LOCATION"""
surf_names = self.get_surface_names()
unique_surf_names = self.get_surface_names(remove_dublicated=True)
for surf_name in surf_data:
if surf_name not in unique_surf_names:
raise ValueError(
f"""surface name, {surf_name}, not found in the current avl object."
Note duplicated surfaces can not be set directly.
Surface in file {unique_surf_names}
{surf_names}"""
)
for var in surf_data[surf_name]:
# do not set the data this way if it is a control surface
if var not in self.con_surf_to_fort_var[surf_name]:
self.set_surface_param(surf_name, var, surf_data[surf_name][var])
else:
idx_surf = surf_names.index(surf_name)
num_sec = self.get_avl_fort_arr("SURF_GEOM_I", "NSEC")[idx_surf]
slice_data = []
for idx_sec in range(num_sec):
self.set_con_surf_param(surf_name, idx_sec, var, surf_data[surf_name][var][idx_sec])
self.avl.update_surfaces()
def get_body_params(self) -> Dict[str, Dict[str, Any]]:
body_names = self.get_body_names()
unique_body_names = self.get_body_names(remove_dublicated=True)
body_data = {}
for body_name in unique_body_names:
idx_body = body_names.index(body_name)
body_data[body_name] = {}
for var, fort_var in self.body_geom_to_fort_var.items():
val = self.get_avl_fort_arr(fort_var[0], fort_var[1], slicer=idx_body) #
if var == "bfile":
val = self.__decodeFortranString(val)
body_data[body_name][var] = val
return body_data
def write_geom_file(self, filename: str):
"""write the current avl geometry to a file"""
with open(filename, "w") as fid:
# write the header
fid.write("# generated using pyAVL\n")
self.__write_header(fid)
surf_data = self.get_surface_params(
include_geom=True, include_panneling=True, include_con_surf=True, include_airfoils=True
)
for surf_name in surf_data:
self.__write_surface(fid, surf_name, surf_data[surf_name])
body_data = self.get_body_params()
for body_name in body_data:
self.__write_body(fid, body_name, body_data[body_name])
def __write_fort_vars(self, fid, common_block: str, fort_var: str, newline: bool = True) -> None:
var = self.get_avl_fort_arr(common_block, fort_var)
out_str = ""
# loop over the variables list and recursively convert the variables to a string and add to the output string
if isinstance(var, np.ndarray):
if var.size == 1:
out_str += str(var[()])
else:
out_str += " ".join([str(item) for item in var])
else:
out_str += str(var)
out_str += " "