-
-
Notifications
You must be signed in to change notification settings - Fork 111
/
airfoil.py
2153 lines (1813 loc) · 79.6 KB
/
airfoil.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
import aerosandbox.numpy as np
from aerosandbox import AeroSandboxObject
from aerosandbox.geometry.polygon import Polygon
from aerosandbox.geometry.airfoil.airfoil_families import get_NACA_coordinates, get_UIUC_coordinates, \
get_kulfan_coordinates, get_file_coordinates
from aerosandbox.geometry.airfoil.default_airfoil_aerodynamics import default_CL_function, default_CD_function, \
default_CM_function
from aerosandbox.library.aerodynamics import transonic
from aerosandbox.modeling.splines.hermite import linear_hermite_patch, cubic_hermite_patch
from scipy import interpolate
from typing import Callable, Union, Any, Dict, List
import json
from pathlib import Path
import os
class Airfoil(Polygon):
"""
An airfoil. See constructor docstring for usage details.
"""
def __init__(self,
name: str = "Untitled",
coordinates: Union[None, str, np.ndarray] = None,
generate_polars: bool = False,
CL_function: Callable[[float, float, float], float] = None,
CD_function: Callable[[float, float, float], float] = None,
CM_function: Callable[[float, float, float], float] = None,
):
"""
Creates an Airfoil object.
Args:
name: Name of the airfoil [string]. Can also be used to auto-generate coordinates; see docstring for
`coordinates` below.
coordinates: A representation of the coordinates that define the airfoil. Can be one of several types of
input; the following sequence of operations is used to interpret the meaning of the parameter:
If `coordinates` is an Nx2 array of the [x, y] coordinates that define the airfoil, these are used
as-is. Points are expected to be provided in standard airfoil order:
* Points should start on the upper surface at the trailing edge, continue forward over the upper
surface, wrap around the nose, continue aft over the lower surface, and then end at the trailing
edge on the lower surface.
* The trailing edge need not be closed, but many analyses implicitly assume that this gap is small.
* Take care to ensure that the point at the leading edge of the airfoil, usually (0, 0),
is not duplicated.
If `coordinates` is provided as a string, it assumed to be the filepath to a *.dat file containing
the coordinates; we attempt to load coordinates from this.
If the coordinates are not specified and instead left as None, the constructor will attempt to
auto-populate the coordinates based on the `name` parameter provided, in the following order of
priority:
* If `name` is a 4-digit NACA airfoil (e.g. "naca2412"), coordinates will be created based on the
analytical equation.
* If `name` is the name of an airfoil in the UIUC airfoil database (e.g. "s1223", "e216",
"dae11"), coordinates will be loaded from that. Note that the string you provide must be exactly
the name of the associated *.dat file in the UIUC database.
CL_function: A function that gives the sectional lift coefficient of the airfoil as a function of several
parameters.
Must be a callable with that takes exactly these parameters as follows:
>>> def CL_function(alpha, Re, mach)
where:
* `alpha` is the local angle of attack, in degrees
* `Re` is the local Reynolds number
* `mach` is the local Mach number
CD_function: A function that gives the sectional drag coefficient of the airfoil as a function of
several parameters.
Has the exact same syntax as `CL_function`, see above.
CM_function: A function that gives the sectional moment coefficient of the airfoil (about the
quarter-chord) as a function of several parameters.
Has the exact same syntax as `CL_function`, see above.
"""
### Handle the airfoil name
self.name = name
### Handle the coordinates
self.coordinates = None
if coordinates is None: # If no coordinates are given
try: # See if it's a NACA airfoil
self.coordinates = get_NACA_coordinates(name=self.name)
except (ValueError, NotImplementedError):
try: # See if it's in the UIUC airfoil database
self.coordinates = get_UIUC_coordinates(name=self.name)
except FileNotFoundError:
pass
except UnicodeDecodeError:
import warnings
warnings.warn(
f"Airfoil {self.name} was found in the UIUC airfoil database, but could not be parsed.\n"
f"Check for any non-Unicode-compatible characters in the file, or specify the airfoil "
f"coordinates yourself.",
)
else:
try: # If coordinates is a string, assume it's a filepath to a .dat file
self.coordinates = get_file_coordinates(filepath=coordinates)
except (OSError, FileNotFoundError, TypeError, UnicodeDecodeError):
try:
shape = coordinates.shape
assert len(shape) == 2
assert shape[0] == 2 or shape[1] == 2
if not shape[1] == 2:
coordinates = np.transpose(shape)
self.coordinates = coordinates
except AttributeError:
pass
if self.coordinates is None:
import warnings
warnings.warn(
f"Airfoil {self.name} had no coordinates assigned, and could not parse the `coordinates` input!",
stacklevel=2,
)
### Handle getting default polars
if generate_polars:
self.generate_polars()
else:
self.CL_function = default_CL_function
self.CD_function = default_CD_function
self.CM_function = default_CM_function
### Overwrite any default polars with those provided
if CL_function is not None:
self.CL_function = CL_function
if CD_function is not None:
self.CD_function = CD_function
if CM_function is not None:
self.CM_function = CM_function
def __repr__(self) -> str:
return f"Airfoil {self.name} ({self.n_points()} points)"
def __eq__(self, other: "Airfoil") -> bool:
"""
Checks if two airfoils are equal. Two airfoils are equal if they have the same name, coordinates, and
polar functions.
Args:
other: The other airfoil to compare to.
Returns:
True if the two airfoils are equal, False otherwise.
"""
if other is self: # If they're the same object in memory, they're equal
return True
if not type(self) == type(other): # If the types are different, they're not equal
return False
# At this point, we know that the types are the same, so we can compare the attributes
return all([ # If all of these are true, they're equal
self.name == other.name,
np.allclose(self.coordinates, other.coordinates),
self.CL_function is other.CL_function,
self.CD_function is other.CD_function,
self.CM_function is other.CM_function,
])
def has_polars(self) -> bool:
return (
hasattr(self, "CL_function") and
hasattr(self, "CD_function") and
hasattr(self, "CM_function")
)
def generate_polars(self,
alphas=np.linspace(-13, 13, 27),
Res=np.geomspace(1e3, 1e8, 12),
cache_filename: str = None,
xfoil_kwargs: Dict[str, Any] = None,
unstructured_interpolated_model_kwargs: Dict[str, Any] = None,
include_compressibility_effects: bool = True,
transonic_buffet_lift_knockdown: float = 0.3,
make_symmetric_polars: bool = False,
) -> None:
"""
Generates airfoil polar surrogate models (CL, CD, CM functions) from XFoil data and assigns them in-place to
this Airfoil's polar functions.
In other words, when this function is run, the following functions will be added (or overwritten) to the instance:
* Airfoil.CL_function(alpha, Re, mach)
* Airfoil.CD_function(alpha, Re, mach)
* Airfoil.CM_function(alpha, Re, mach)
Where alpha is in degrees.
Warning: In-place operation! Modifies this Airfoil object by setting Airfoil.CL_function, etc. to the new
polars.
Args:
alphas: The range of alphas to sample from XFoil at. Given in degrees.
Res: The range of Reynolds numbers to sample from XFoil at. Dimensionless.
cache_filename: A path-like filename (ideally a "*.json" file) that can be used to cache the XFoil
results, making it much faster to regenerate the results.
* If the file does not exist, XFoil will be run, and a cache file will be created.
* If the file does exist, XFoil will not be run, and the cache file will be read instead.
xfoil_kwargs: Keyword arguments to pass into the AeroSandbox XFoil module. See the aerosandbox.XFoil
constructor for options.
unstructured_interpolated_model_kwargs: Keyword arguments to pass into the UnstructuredInterpolatedModels
that contain the polars themselves. See the aerosandbox.UnstructuredInterpolatedModel constructor for
options.
include_compressibility_effects: Includes compressibility effects in the polars, such as wave drag,
mach tuck, CL effects across normal shocks. Note that accuracy here is dubious in the transonic regime
and above - you should really specify your own CL/CD/CM models
Returns: None (in-place), adds the following functions to the instance:
* Airfoil.CL_function(alpha, Re, mach)
* Airfoil.CD_function(alpha, Re, mach)
* Airfoil.CM_function(alpha, Re, mach)
"""
if self.coordinates is None:
raise ValueError("Cannot generate polars for an airfoil that you don't have the coordinates of!")
### Set defaults
if xfoil_kwargs is None:
xfoil_kwargs = {}
if unstructured_interpolated_model_kwargs is None:
unstructured_interpolated_model_kwargs = {}
xfoil_kwargs = { # See asb.XFoil for the documentation on these.
"verbose" : False,
"max_iter" : 20,
"xfoil_repanel": True,
**xfoil_kwargs
}
unstructured_interpolated_model_kwargs = { # These were tuned heuristically as defaults!
"resampling_interpolator_kwargs": {
"degree" : 0,
# "kernel": "linear",
"kernel" : "multiquadric",
"epsilon" : 3,
"smoothing": 0.01,
# "kernel": "cubic"
},
**unstructured_interpolated_model_kwargs
}
### Retrieve XFoil Polar Data from the cache, if it exists.
data = None
if cache_filename is not None:
try:
with open(cache_filename, "r") as f:
data = {
k: np.array(v)
for k, v in json.load(f).items()
}
except FileNotFoundError:
pass
### Analyze airfoil with XFoil, if needed
if data is None:
### If a cache filename is given, ensure that the directory exists.
if cache_filename is not None:
os.makedirs(os.path.dirname(cache_filename), exist_ok=True)
from aerosandbox.aerodynamics.aero_2D import XFoil
def get_run_data(Re): # Get the data for an XFoil alpha sweep at one specific Re.
run_data = XFoil(
airfoil=self,
Re=Re,
**xfoil_kwargs
).alpha(alphas)
run_data["Re"] = Re * np.ones_like(run_data["alpha"])
return run_data # Data is a dict where keys are figures of merit [str] and values are 1D ndarrays.
from tqdm import tqdm
run_datas = [ # Get a list of dicts, where each dict is the result of an XFoil run at a particular Re.
get_run_data(Re)
for Re in tqdm(
Res,
desc=f"Running XFoil to generate polars for Airfoil '{self.name}':",
)
]
data = { # Merge the dicts into one big database of all runs.
k: np.concatenate(
tuple([run_data[k] for run_data in run_datas])
)
for k in run_datas[0].keys()
}
if make_symmetric_polars: # If the airfoil is known to be symmetric, duplicate all data across alpha.
keys_symmetric_across_alpha = ['CD', 'CDp', 'Re'] # Assumes the rest are antisymmetric
data = {
k: np.concatenate([v, v if k in keys_symmetric_across_alpha else -v])
for k, v in data.items()
}
if cache_filename is not None: # Cache the accumulated data for later use, if it doesn't already exist.
with open(cache_filename, "w+") as f:
json.dump(
{k: v.tolist() for k, v in data.items()},
f,
indent=4
)
### Save the raw data as an instance attribute for later use
self.xfoil_data = data
### Make the interpolators for attached aerodynamics
from aerosandbox.modeling import UnstructuredInterpolatedModel
attached_alphas_to_use = (
alphas[::2] if len(alphas) > 20 else alphas
)
alpha_resample = np.concatenate([
np.linspace(-180, attached_alphas_to_use.min(), 10)[:-1],
attached_alphas_to_use,
np.linspace(attached_alphas_to_use.max(), 180, 10)[1:],
]) # This is the list of points that we're going to resample from the XFoil runs for our InterpolatedModel, using an RBF.
Re_resample = np.concatenate([
Res.min() / 10 ** np.arange(1, 5)[::-1],
Res,
Res.max() * 10 ** np.arange(1, 5),
]) # This is the list of points that we're going to resample from the XFoil runs for our InterpolatedModel, using an RBF.
x_data = {
"alpha": data["alpha"],
"ln_Re": np.log(data["Re"]),
}
x_data_resample = {
"alpha": alpha_resample,
"ln_Re": np.log(Re_resample)
}
CL_attached_interpolator = UnstructuredInterpolatedModel(
x_data=x_data,
y_data=data["CL"],
x_data_resample=x_data_resample,
**unstructured_interpolated_model_kwargs
)
log10_CD_attached_interpolator = UnstructuredInterpolatedModel(
x_data=x_data,
y_data=np.log10(data["CD"]),
x_data_resample=x_data_resample,
**unstructured_interpolated_model_kwargs
)
CM_attached_interpolator = UnstructuredInterpolatedModel(
x_data=x_data,
y_data=data["CM"],
x_data_resample=x_data_resample,
**unstructured_interpolated_model_kwargs
)
### Determine if separated
alpha_stall_positive = np.max(data["alpha"]) # Across all Re
alpha_stall_negative = np.min(data["alpha"]) # Across all Re
def separation_parameter(alpha, Re=0):
"""
Positive if separated, negative if attached.
This will be an input to a tanh() sigmoid blend via asb.numpy.blend(), so a value of 1 means the flow is
~90% separated, and a value of -1 means the flow is ~90% attached.
"""
return 0.5 * np.softmax(
alpha - alpha_stall_positive,
alpha_stall_negative - alpha
)
### Make the interpolators for separated aerodynamics
from aerosandbox.aerodynamics.aero_2D.airfoil_polar_functions import airfoil_coefficients_post_stall
CL_if_separated, CD_if_separated, CM_if_separated = airfoil_coefficients_post_stall(
airfoil=self,
alpha=alpha_resample
)
CD_if_separated = CD_if_separated + np.median(data["CD"])
# The line above effectively ensures that separated CD will never be less than attached CD. Not exactly, but generally close. A good heuristic.
CL_separated_interpolator = UnstructuredInterpolatedModel(
x_data=alpha_resample,
y_data=CL_if_separated
)
log10_CD_separated_interpolator = UnstructuredInterpolatedModel(
x_data=alpha_resample,
y_data=np.log10(CD_if_separated)
)
CM_separated_interpolator = UnstructuredInterpolatedModel(
x_data=alpha_resample,
y_data=CM_if_separated
)
def CL_function(alpha, Re, mach=0):
alpha = np.mod(alpha + 180, 360) - 180 # Keep alpha in the valid range.
CL_attached = CL_attached_interpolator({
"alpha": alpha,
"ln_Re": np.log(Re),
})
CL_separated = CL_separated_interpolator(alpha) # Lift coefficient if separated
CL_mach_0 = np.blend( # Lift coefficient at mach = 0
separation_parameter(alpha, Re),
CL_separated,
CL_attached
)
if include_compressibility_effects:
prandtl_glauert_beta_squared_ideal = 1 - mach ** 2
prandtl_glauert_beta = np.softmax(
prandtl_glauert_beta_squared_ideal,
-prandtl_glauert_beta_squared_ideal,
hardness=2.0 # Empirically tuned to data
) ** 0.5
CL = CL_mach_0 / prandtl_glauert_beta
mach_crit = transonic.mach_crit_Korn(
CL=CL,
t_over_c=self.max_thickness(),
sweep=0,
kappa_A=0.95
)
### Accounts approximately for the lift drop due to buffet.
buffet_factor = np.blend(
40 * (mach - mach_crit - (0.1 / 80) ** (1 / 3) - 0.06) * (mach - 1.1),
1,
transonic_buffet_lift_knockdown
)
### Accounts for the fact that theoretical CL_alpha goes from 2 * pi (subsonic) to 4 (supersonic),
# following linearized supersonic flow on a thin airfoil.
cla_supersonic_ratio_factor = np.blend(
10 * (mach - 1),
4 / (2 * np.pi),
1,
)
return CL * buffet_factor * cla_supersonic_ratio_factor
else:
return CL_mach_0
def CD_function(alpha, Re, mach=0):
alpha = np.mod(alpha + 180, 360) - 180 # Keep alpha in the valid range.
log10_CD_attached = log10_CD_attached_interpolator({
"alpha": alpha,
"ln_Re": np.log(Re),
})
log10_CD_separated = log10_CD_separated_interpolator(alpha)
log10_CD_mach_0 = np.blend(
separation_parameter(alpha, Re),
log10_CD_separated,
log10_CD_attached,
)
if include_compressibility_effects:
CL_attached = CL_attached_interpolator({
"alpha": alpha,
"ln_Re": np.log(Re),
})
CL_separated = CL_separated_interpolator(alpha)
CL_mach_0 = np.blend(
separation_parameter(alpha, Re),
CL_separated,
CL_attached
)
prandtl_glauert_beta_squared_ideal = 1 - mach ** 2
prandtl_glauert_beta = np.softmax(
prandtl_glauert_beta_squared_ideal,
-prandtl_glauert_beta_squared_ideal,
hardness=2.0 # Empirically tuned to data
) ** 0.5
CL = CL_mach_0 / prandtl_glauert_beta
t_over_c = self.max_thickness()
mach_crit = transonic.mach_crit_Korn(
CL=CL,
t_over_c=t_over_c,
sweep=0,
kappa_A=0.92
)
mach_dd = mach_crit + (0.1 / 80) ** (1 / 3)
CD_wave = np.where(
mach < mach_crit,
0,
np.where(
mach < mach_dd,
20 * (mach - mach_crit) ** 4,
np.where(
mach < 0.97,
cubic_hermite_patch(
mach,
x_a=mach_dd,
x_b=0.97,
f_a=20 * (0.1 / 80) ** (4 / 3),
f_b=0.8 * t_over_c,
dfdx_a=0.1,
dfdx_b=0.8 * t_over_c * 8
),
np.where(
mach < 1.1,
cubic_hermite_patch(
mach,
x_a=0.97,
x_b=1.1,
f_a=0.8 * t_over_c,
f_b=0.8 * t_over_c,
dfdx_a=0.8 * t_over_c * 8,
dfdx_b=-0.8 * t_over_c * 8,
),
np.blend(
8 * 2 * (mach - 1.1) / (1.2 - 0.8),
0.8 * 0.8 * t_over_c,
1.2 * 0.8 * t_over_c,
)
)
)
)
)
# CD_wave = transonic.approximate_CD_wave(
# mach=mach,
# mach_crit=mach_crit,
# CD_wave_at_fully_supersonic=0.90 * self.max_thickness()
# )
return 10 ** log10_CD_mach_0 + CD_wave
else:
return 10 ** log10_CD_mach_0
def CM_function(alpha, Re, mach=0):
alpha = np.mod(alpha + 180, 360) - 180 # Keep alpha in the valid range.
CM_attached = CM_attached_interpolator({
"alpha": alpha,
"ln_Re": np.log(Re),
})
CM_separated = CM_separated_interpolator(alpha)
CM_mach_0 = np.blend(
separation_parameter(alpha, Re),
CM_separated,
CM_attached
)
if include_compressibility_effects:
prandtl_glauert_beta_squared_ideal = 1 - mach ** 2
prandtl_glauert_beta = np.softmax(
prandtl_glauert_beta_squared_ideal,
-prandtl_glauert_beta_squared_ideal,
hardness=2.0 # Empirically tuned to data
) ** 0.5
CM = CM_mach_0 / prandtl_glauert_beta
return CM
else:
return CM_mach_0
self.CL_function = CL_function
self.CD_function = CD_function
self.CM_function = CM_function
def get_aero_from_neuralfoil(self,
alpha: Union[float, np.ndarray],
Re: Union[float, np.ndarray],
mach: Union[float, np.ndarray] = 0.,
model_size: str = "large",
control_surfaces: List["ControlSurface"] = None,
control_surface_strategy="polar_modification",
transonic_buffet_lift_knockdown: float = 0.3,
include_360_deg_effects: bool = True,
) -> Dict[str, Union[float, np.ndarray]]:
if self.coordinates is None:
raise ValueError("Cannot do aerodynamic analysis on an airfoil that you don't have the coordinates of!")
if control_surfaces is None:
control_surfaces = []
alpha = np.mod(alpha + 180, 360) - 180 # Enforce periodicity of alpha
##### Evaluate the control surfaces of the airfoil
airfoil = self
effective_d_alpha = 0.
effective_CD_multiplier_from_control_surfaces = 1.
if control_surface_strategy == "polar_modification":
for surf in control_surfaces:
effectiveness = 1 - np.maximum(0, surf.hinge_point + 1e-16) ** 2.751428551177291
# From XFoil-based study at `/AeroSandbox/studies/ControlSurfaceEffectiveness/`
effective_d_alpha += surf.deflection * effectiveness
effective_CD_multiplier_from_control_surfaces *= (
2 + (surf.deflection / 11.5) ** 2 - (1 + (surf.deflection / 11.5) ** 2) ** 0.5
)
# From fit to wind tunnel data from Hoerner, "Fluid Dynamic Drag", 1965. Page 13-13, Figure 32,
# "Variation of section drag coefficient of a horizontal tail surface at constant C_L"
elif control_surface_strategy == "coordinate_modification":
for surf in control_surfaces:
airfoil = airfoil.add_control_surface(
deflection=surf.deflection,
hinge_point_x=surf.hinge_point,
)
else:
raise ValueError("Invalid `control_surface_strategy`!\n"
"Valid options are \"polar_modification\" or \"coordinate_modification\".")
##### Use NeuralFoil to evaluate the incompressible aerodynamics of the airfoil
import neuralfoil as nf
nf_aero = nf.get_aero_from_airfoil(
airfoil=airfoil,
alpha=alpha + effective_d_alpha,
Re=Re,
model_size=model_size
)
CL = nf_aero["CL"]
CD = nf_aero["CD"] * effective_CD_multiplier_from_control_surfaces
CM = nf_aero["CM"]
Cpmin_0 = nf_aero["Cpmin"]
Top_Xtr = nf_aero["Top_Xtr"]
Bot_Xtr = nf_aero["Bot_Xtr"]
##### Extend aerodynamic data to 360 degrees (post-stall) using wind tunnel behavior here.
if include_360_deg_effects:
from aerosandbox.aerodynamics.aero_2D.airfoil_polar_functions import airfoil_coefficients_post_stall
CL_if_separated, CD_if_separated, CM_if_separated = airfoil_coefficients_post_stall(
airfoil=airfoil,
alpha=alpha
)
import aerosandbox.library.aerodynamics as lib_aero
# These values are so high because NeuralFoil extrapolates quite well past stall
alpha_stall_positive = 20
alpha_stall_negative = -20
# This will be an input to a tanh() sigmoid blend via asb.numpy.blend(), so a value of 1 means the flow is
# ~90% separated, and a value of -1 means the flow is ~90% attached.
is_separated = np.softmax(
alpha - alpha_stall_positive,
alpha_stall_negative - alpha
) / 3
CL = np.blend(
is_separated,
CL_if_separated,
CL
)
CD = np.exp(np.blend(
is_separated,
np.log(CD_if_separated + lib_aero.Cf_flat_plate(Re_L=Re, method="turbulent")),
np.log(CD)
))
CM = np.blend(
is_separated,
CM_if_separated,
CM
)
"""
Separated Cpmin_0 model is a very rough fit to Figure 3 of:
Shademan & Naghib-Lahouti, "Effects of aspect ratio and inclination angle on aerodynamic loads of a flat
plate", Advances in Aerodynamics.
https://www.researchgate.net/publication/342316140_Effects_of_aspect_ratio_and_inclination_angle_on_aerodynamic_loads_of_a_flat_plate
"""
Cpmin_0 = np.blend(
is_separated,
-1 - 0.5 * np.sind(alpha) ** 2,
Cpmin_0
)
Top_Xtr = np.blend(
is_separated,
0.5 - 0.5 * np.tanh(10 * np.sind(alpha)),
Top_Xtr
)
Bot_Xtr = np.blend(
is_separated,
0.5 + 0.5 * np.tanh(10 * np.sind(alpha)),
Bot_Xtr
)
###### Add compressibility effects
### Step 1: compute mach_crit, the critical Mach number
"""
Below is a function that computes the critical Mach number from the incompressible Cp_min.
It's based on a Laitone-rule compressibility correction (similar to Prandtl-Glauert or Karman-Tsien, but higher order).
This approach does not admit explicit solution for the Cp0 -> M_crit relation, so we instead regress a
relationship out using symbolic regression. In effect, this is a curve fit to synthetic data.
See fits at: /AeroSandbox/studies/MachFitting/CriticalMach/
"""
Cpmin_0 = np.softmin(
Cpmin_0,
0,
softness=0.001
)
mach_crit = (
1.011571026701678
- Cpmin_0
+ 0.6582431351007195 * (-Cpmin_0) ** 0.6724789439840343
) ** -0.5504677038358711
### Step 2: adjust CL, CD, CM, Cpmin by compressibility effects
gamma = 1.4 # Ratio of specific heats, 1.4 for air (mostly diatomic nitrogen and oxygen)
beta_squared_ideal = 1 - mach ** 2
beta = np.softmax(
beta_squared_ideal,
-beta_squared_ideal,
softness=0.1 # Empirically tuned to data
) ** 0.5
CL = CL / beta
# CD = CD / beta
CM = CM / beta
# Prandtl-Glauert
Cpmin = Cpmin_0 / beta
# Karman-Tsien
# Cpmin = Cpmin_0 / (
# beta
# + mach ** 2 / (1 + beta) * (Cpmin_0 / 2)
# )
# Laitone's rule
# Cpmin = Cpmin_0 / (
# beta
# + (mach ** 2) * (1 + (gamma - 1) / 2 * mach ** 2) / (1 + beta) * (Cpmin_0 / 2)
# )
### Step 3: modify CL based on buffet and supersonic considerations
# Accounts approximately for the lift drop due to buffet.
buffet_factor = np.blend(
40 * (mach - mach_crit - (0.1 / 80) ** (1 / 3) - 0.06) * (mach - 1.1),
1,
transonic_buffet_lift_knockdown
)
# Accounts for the fact that theoretical CL_alpha goes from 2 * pi (subsonic) to 4 (supersonic),
# following linearized supersonic flow on a thin airfoil.
cla_supersonic_ratio_factor = np.blend(
10 * (mach - 1),
4 / (2 * np.pi),
1,
)
CL = CL * buffet_factor * cla_supersonic_ratio_factor
# Step 4: Account for wave drag
mach_dd = mach_crit + (0.1 / 80) ** (1 / 3) # drag divergence Mach number
t_over_c = self.max_thickness()
CD_wave = np.where(
mach < mach_crit,
0,
np.where(
mach < mach_dd,
20 * (mach - mach_crit) ** 4,
np.where(
mach < 0.97,
cubic_hermite_patch(
mach,
x_a=mach_dd,
x_b=0.97,
f_a=20 * (0.1 / 80) ** (4 / 3),
f_b=0.8 * t_over_c,
dfdx_a=0.1,
dfdx_b=0.8 * t_over_c * 8
),
np.where(
mach < 1.1,
cubic_hermite_patch(
mach,
x_a=0.97,
x_b=1.1,
f_a=0.8 * t_over_c,
f_b=0.8 * t_over_c,
dfdx_a=0.8 * t_over_c * 8,
dfdx_b=-0.8 * t_over_c * 8,
),
np.blend(
8 * 2 * (mach - 1.1) / (1.2 - 0.8),
0.8 * 0.8 * t_over_c,
1.2 * 0.8 * t_over_c,
)
)
)
)
)
CD = CD + CD_wave
# Step 5: If beyond M_crit or if separated, move the airfoil aerodynamic center back to x/c = 0.5 (Mach tuck)
if include_360_deg_effects:
has_aerodynamic_center_shift = np.softmax(
is_separated,
(mach - mach_crit) / 0.25,
softness=0.1
)
else:
has_aerodynamic_center_shift = (mach - mach_crit) / 0.25
CM = CM + np.blend(
has_aerodynamic_center_shift,
-0.25 * np.cosd(alpha) * CL - 0.25 * np.sind(alpha) * CD,
0,
)
return {
"CL" : CL,
"CD" : CD,
"CM" : CM,
"Cpmin" : Cpmin,
"Top_Xtr" : Top_Xtr,
"Bot_Xtr" : Bot_Xtr,
"mach_crit": mach_crit,
"mach_dd" : mach_dd,
"Cpmin_0" : Cpmin_0,
}
def plot_polars(self,
alphas: Union[np.ndarray, List[float]] = np.linspace(-20, 20, 500),
Res: Union[np.ndarray, List[float]] = 10 ** np.arange(3, 9),
mach: float = 0.,
show: bool = True,
Re_colors=None,
) -> None:
import matplotlib.pyplot as plt
import aerosandbox.tools.pretty_plots as p
fig, ax = plt.subplots(2, 2, figsize=(8, 7))
plt.sca(ax[0, 0])
plt.title("Lift Coefficient")
plt.xlabel(r"Angle of Attack $\alpha$ [deg]")
plt.ylabel(r"Lift Coefficient $C_L$")
p.set_ticks(5, 1, 0.5, 0.1)
plt.sca(ax[0, 1])
plt.title("Drag Coefficient")
plt.xlabel(r"Angle of Attack $\alpha$ [deg]")
plt.ylabel(r"Drag Coefficient $C_D$")
plt.ylim(bottom=0, top=0.05)
p.set_ticks(5, 1, 0.01, 0.002)
plt.sca(ax[1, 0])
plt.title("Moment Coefficient")
plt.xlabel(r"Angle of Attack $\alpha$ [deg]")
plt.ylabel(r"Moment Coefficient $C_m$")
p.set_ticks(5, 1, 0.05, 0.01)
plt.sca(ax[1, 1])
plt.title("Lift-to-Drag Ratio")
plt.xlabel(r"Angle of Attack $\alpha$ [deg]")
plt.ylabel(r"Lift-to-Drag Ratio $C_L/C_D$")
p.set_ticks(5, 1, 20, 5)
if Re_colors is None:
Re_colors = plt.get_cmap('rainbow')(np.linspace(0, 1, len(Res)))
Re_colors = [
p.adjust_lightness(color, 0.7)
for color in Re_colors
]
for i, Re in enumerate(Res):
kwargs = dict(
alpha=alphas,
Re=Re,
mach=mach
)
plt.sca(ax[0, 0])
plt.plot(
alphas,
self.CL_function(**kwargs),
color=Re_colors[i],
alpha=0.7
)
plt.sca(ax[0, 1])
plt.plot(
alphas,
self.CD_function(**kwargs),
color=Re_colors[i],
alpha=0.7
)
plt.sca(ax[1, 0])
plt.plot(
alphas,
self.CM_function(**kwargs),
color=Re_colors[i],
alpha=0.7
)
plt.sca(ax[1, 1])
plt.plot(
alphas,
self.CL_function(**kwargs) / self.CD_function(**kwargs),
color=Re_colors[i],
alpha=0.7
)
from aerosandbox.tools.string_formatting import eng_string
plt.sca(ax[0, 0])
plt.legend(
title="Reynolds Number",
labels=[eng_string(Re) for Re in Res],
ncol=2,
# Note: `ncol` is old syntax; preserves backwards-compatibility with matplotlib 3.5.x.
# New matplotlib versions use `ncols` instead.
fontsize=8,
loc='lower right'
)
if show:
p.show_plot(
f"Polar Functions for {self.name} Airfoil",
legend=False,
)
def local_camber(self,
x_over_c: Union[float, np.ndarray] = np.linspace(0, 1, 101)
) -> Union[float, np.ndarray]:
"""
Returns the local camber of the airfoil at a given point or points.
Args:
x_over_c: The x/c locations to calculate the camber at [1D array, more generally, an iterable of floats]
Returns:
Local camber of the airfoil (y/c) [1D array].
"""
upper = self.upper_coordinates()[::-1]
lower = self.lower_coordinates()
upper_interpolated = np.interp(
x_over_c,
upper[:, 0],
upper[:, 1],
)
lower_interpolated = np.interp(
x_over_c,
lower[:, 0],
lower[:, 1],