-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVortexStepMethodMakieExt.jl
More file actions
1310 lines (1114 loc) · 47.2 KB
/
Copy pathVortexStepMethodMakieExt.jl
File metadata and controls
1310 lines (1114 loc) · 47.2 KB
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
module VortexStepMethodMakieExt
using Makie, VortexStepMethod, LinearAlgebra, Statistics, DelimitedFiles
import VortexStepMethod: calculate_filaments_for_plotting
export plot_geometry, plot_distribution, plot_polars, save_plot, show_plot,
plot_polar_data, plot_combined_analysis
# Set this extension as the active plotting backend when loaded (only if not already set)
function __init__()
isnothing(VortexStepMethod._PLOT_BACKEND[]) &&
(VortexStepMethod._PLOT_BACKEND[] = VortexStepMethod.MakieBackend())
end
# Global storage for panel mesh observables (for dynamic plotting)
const PANEL_MESH_OBSERVABLES = Ref{Union{Nothing,Dict}}(nothing)
"""
plot!(ax, panel::VortexStepMethod.Panel; use_observables=false, kwargs...)
Plot a single `Panel` as a `mesh`.
The corner points are ordered as: LE1, TE1, TE2, LE2.
This creates two triangles: (LE1, TE1, TE2) and (LE1, TE2, LE2).
If `use_observables=true`, creates observables for dynamic updates.
"""
function Makie.plot!(ax, panel::VortexStepMethod.Panel; color=(:red, 0.2), R_b_w=nothing, T_b_w=nothing,
use_observables=false, kwargs...)
plots = []
points = [Point3f(panel.corner_points[:, i]) for i in 1:4]
if !isnothing(R_b_w) && !isnothing(T_b_w)
points = [Point3f(R_b_w * p + T_b_w) for p in points]
end
if use_observables
# Create observables for dynamic updates
vertices_obs = Observable(points)
faces_obs = Observable([Makie.GLTriangleFace(1, 2, 3), Makie.GLTriangleFace(1, 3, 4)])
border_obs = Observable([points..., points[1]])
p = mesh!(ax, vertices_obs, faces_obs; color, transparency=true, kwargs...)
push!(plots, p)
p = lines!(ax, border_obs; color=:black, transparency=true, kwargs...)
push!(plots, p)
# Note: Observables are stored at the body level, not individual panel level
# Individual panels need their parent body for proper tracking
else
# Static plotting (original behavior)
faces = [Makie.GLTriangleFace(1, 2, 3), Makie.GLTriangleFace(1, 3, 4)]
p = mesh!(ax, points, faces; color, transparency=true, kwargs...)
push!(plots, p)
border_points = [points..., points[1]]
p = lines!(ax, border_points; color=:black, transparency=true, kwargs...)
push!(plots, p)
end
return plots
end
"""
plot!(ax, body::VortexStepMethod.BodyAerodynamics; use_observables=false, kwargs...)
Plot a `BodyAerodynamics` object by plotting each of its panels.
If `use_observables=true`, creates observables for dynamic updates keyed by (body_id, panel_index).
Otherwise, creates static plots (original behavior).
"""
function Makie.plot!(ax, body::VortexStepMethod.BodyAerodynamics; color=(:red, 0.2), R_b_w=nothing, T_b_w=nothing,
use_observables=false, kwargs...)
plots = []
if use_observables
# Initialize global storage if needed
if isnothing(PANEL_MESH_OBSERVABLES[])
PANEL_MESH_OBSERVABLES[] = Dict()
end
body_id = objectid(body)
# Create observables for each panel
for (panel_idx, panel) in enumerate(body.panels)
# Compute initial points
points = [Point3f(panel.corner_points[:, i]) for i in 1:4]
if !isnothing(R_b_w) && !isnothing(T_b_w)
points = [Point3f(R_b_w * p + T_b_w) for p in points]
end
# Create observables
vertices_obs = Observable(points)
faces_obs = Observable([Makie.GLTriangleFace(1, 2, 3), Makie.GLTriangleFace(1, 3, 4)])
border_obs = Observable([points..., points[1]])
# Plot using observables
p = mesh!(ax, vertices_obs, faces_obs; color, transparency=true, kwargs...)
push!(plots, p)
p = lines!(ax, border_obs; color=:black, transparency=true, kwargs...)
push!(plots, p)
# Store observables with stable key
PANEL_MESH_OBSERVABLES[][(body_id, panel_idx)] = (
vertices=vertices_obs,
border=border_obs,
faces=faces_obs
)
end
else
# Static plotting (original behavior)
for panel in body.panels
p = Makie.plot!(ax, panel; color, R_b_w, T_b_w, use_observables=false, kwargs...)
push!(plots, p)
end
end
return plots
end
"""
plot!(body::VortexStepMethod.BodyAerodynamics; R_b_w=nothing, T_b_w=nothing)
Update existing body aerodynamics plot observables with current geometry.
This updates all panels in the body using their current corner_points.
Requires that `plot(body; use_observables=true)` or `plot!(ax, body; use_observables=true)`
was called first to create the observables.
"""
function Makie.plot!(body::VortexStepMethod.BodyAerodynamics; R_b_w=nothing, T_b_w=nothing, kwargs...)
# Check if observables exist
if isnothing(PANEL_MESH_OBSERVABLES[])
error("No panel observables found. Call plot(body; use_observables=true) first.")
end
body_id = objectid(body)
# Update each panel using stable (body_id, panel_idx) key
for (panel_idx, panel) in enumerate(body.panels)
key = (body_id, panel_idx)
if !haskey(PANEL_MESH_OBSERVABLES[], key)
error("No observables found for body $body_id panel $panel_idx. " *
"Call plot(body; use_observables=true) first.")
end
# Get observables for this panel
obs = PANEL_MESH_OBSERVABLES[][key]
# Recompute vertices from current panel.corner_points
points = [Point3f(panel.corner_points[:, i]) for i in 1:4]
if !isnothing(R_b_w) && !isnothing(T_b_w)
points = [Point3f(R_b_w * p + T_b_w) for p in points]
end
# Update observables
obs.vertices[] = points
obs.border[] = [points..., points[1]]
end
return nothing
end
function Makie.plot(panel::VortexStepMethod.Panel; size=(1200, 800),
R_b_w=nothing, T_b_w=nothing, color=(:red, 0.2), kwargs...)
fig = Figure(; size)
ax = Axis3(fig[1, 1]; aspect=:data,
xlabel="X", ylabel="Y", zlabel="Z",
azimuth=9 / 8 * π, zoommode=:cursor, viewmode=:fit,
)
# Create observables for panel geometry
points = [Point3f(panel.corner_points[:, i]) for i in 1:4]
if !isnothing(R_b_w) && !isnothing(T_b_w)
points = [Point3f(R_b_w * p + T_b_w) for p in points]
end
vertices_obs = Observable(points)
faces_obs = Observable([Makie.GLTriangleFace(1, 2, 3), Makie.GLTriangleFace(1, 3, 4)])
# Plot mesh using observables
mesh!(ax, vertices_obs, faces_obs; color, transparency=true, kwargs...)
# Plot border
border_obs = Observable([points..., points[1]])
lines!(ax, border_obs; color=:black, transparency=true, kwargs...)
# Store observables globally for updates
panel_id = objectid(panel)
if isnothing(PANEL_MESH_OBSERVABLES[])
PANEL_MESH_OBSERVABLES[] = Dict()
end
PANEL_MESH_OBSERVABLES[][panel_id] = (
vertices=vertices_obs,
border=border_obs,
faces=faces_obs
)
return fig
end
function Makie.plot(body_aero::VortexStepMethod.BodyAerodynamics; size=(1200, 800),
limitmargin=0.1, R_b_w=nothing, T_b_w=nothing, color=(:red, 0.2),
kwargs...)
fig = Figure(; size)
ax = Axis3(fig[1, 1]; aspect=:data,
xlabel="X", ylabel="Y", zlabel="Z",
azimuth=9 / 8 * π, zoommode=:cursor, viewmode=:fit,
xautolimitmargin=(limitmargin, limitmargin),
yautolimitmargin=(limitmargin, limitmargin),
zautolimitmargin=(limitmargin, limitmargin),
)
# Initialize global storage if needed
if isnothing(PANEL_MESH_OBSERVABLES[])
PANEL_MESH_OBSERVABLES[] = Dict()
end
body_id = objectid(body_aero)
# Create observables for each panel using stable (body_id, panel_idx) key
for (panel_idx, panel) in enumerate(body_aero.panels)
# Compute initial points
points = [Point3f(panel.corner_points[:, i]) for i in 1:4]
if !isnothing(R_b_w) && !isnothing(T_b_w)
points = [Point3f(R_b_w * p + T_b_w) for p in points]
end
# Create observables
vertices_obs = Observable(points)
faces_obs = Observable([Makie.GLTriangleFace(1, 2, 3), Makie.GLTriangleFace(1, 3, 4)])
border_obs = Observable([points..., points[1]])
# Plot using observables
mesh!(ax, vertices_obs, faces_obs; color, transparency=true, kwargs...)
lines!(ax, border_obs; color=:black, transparency=true, kwargs...)
# Store observables with stable key
PANEL_MESH_OBSERVABLES[][(body_id, panel_idx)] = (
vertices=vertices_obs,
border=border_obs,
faces=faces_obs
)
end
return fig
end
function _active_backend_prefers_vector_output(makie=Makie)
isdefined(makie, :current_backend) || return false
backend = try
makie.current_backend()
catch
return false
end
return nameof(backend) == :CairoMakie
end
"""
save_plot(fig, save_path, title; data_type=nothing)
Save a Makie figure to a file.
# Arguments
- `fig`: Makie Figure object
- `save_path`: Path to save the plot
- `title`: Title of the plot
# Keyword arguments
- `data_type`: File extension. If `nothing`, defaults to `".pdf"` when the
active Makie backend is CairoMakie and `".png"` otherwise.
"""
function VortexStepMethod.save_plot(fig::Makie.Figure, save_path, title; data_type=nothing)
if isnothing(data_type)
data_type = _active_backend_prefers_vector_output() ? ".pdf" : ".png"
end
isnothing(save_path) && throw(ArgumentError("save_path should be provided"))
!isdir(save_path) && mkpath(save_path)
sanitized_title = replace(replace(String(title), ' ' => '_'), '%' => "pct")
full_path = joinpath(save_path, sanitized_title * data_type)
fallback_path = joinpath(save_path, sanitized_title * ".png")
@debug "Attempting to save figure to: $full_path"
@debug "Current working directory: $(pwd())"
try
save(full_path, fig)
@debug "Figure saved as $data_type"
if isfile(full_path)
@debug "File successfully saved to $full_path"
@debug "File size: $(filesize(full_path)) bytes"
else
@info "File does not exist after save attempt: $full_path"
end
catch e
# GLMakie cannot export vector formats such as PDF/SVG directly.
# If that happens, save as PNG so batch example runs keep working.
if e isa MethodError && lowercase(data_type) in (".pdf", ".svg")
@warn "Vector export format $data_type is not supported by the active Makie backend; falling back to PNG" requested_path=full_path fallback_path=fallback_path
save(fallback_path, fig)
@debug "Figure saved as PNG fallback"
return nothing
end
@error "Error saving figure: $e"
@error "Error type: $(typeof(e))"
rethrow(e)
end
end
"""
show_plot(fig; dpi=130)
Display a Makie figure.
# Arguments
- `fig`: Makie Figure object
# Keyword arguments
- `dpi`: Dots per inch for the figure (default: 130) - currently unused in Makie
"""
function VortexStepMethod.show_plot(fig::Makie.Figure; dpi=130)
isinteractive() && display(fig)
end
"""
plot_line_segment_makie!(ax, segment, color, label; width=3)
Plot a line segment in 3D with arrow using Makie.
# Arguments
- `ax`: Makie Axis3
- `segment`: Array of two points defining the segment
- `color`: Color of the segment
- `label`: Label for the legend
# Keyword Arguments
- `width`: Line width (default: 3)
"""
function plot_line_segment_makie!(ax, segment, color, label; width=3)
# Plot line
lines!(ax, [Point3f(segment[1]), Point3f(segment[2])];
color=color, linewidth=width, label=label)
# Plot arrow
dir = segment[2] - segment[1]
arrows3d!(ax, [Point3f(segment[1])], [Point3f(dir)];
color=color, shaftradius=0.01, tipradius=0.03, tiplength=0.1)
end
"""
set_axes_equal_makie!(ax, panels; zoom=1.8)
Set 3D Makie axis to equal scale based on panel data.
# Arguments
- `ax`: Makie Axis3
- `panels`: Array of panels
- `zoom`: zoom factor (default: 1.8)
"""
function set_axes_equal_makie!(ax, panels; zoom=1.8)
# Calculate bounds from all panels
all_x = Float64[]
all_y = Float64[]
all_z = Float64[]
for panel in panels
for i in 1:4
push!(all_x, panel.corner_points[1, i])
push!(all_y, panel.corner_points[2, i])
push!(all_z, panel.corner_points[3, i])
end
end
x_range = (maximum(all_x) - minimum(all_x)) / zoom
y_range = (maximum(all_y) - minimum(all_y)) / zoom
z_range = (maximum(all_z) - minimum(all_z)) / zoom
max_range = max(x_range, y_range, z_range)
x_mid = mean([maximum(all_x), minimum(all_x)])
y_mid = mean([maximum(all_y), minimum(all_y)])
z_mid = mean([maximum(all_z), minimum(all_z)])
limits!(ax,
x_mid - max_range / 2, x_mid + max_range / 2,
y_mid - max_range / 2, y_mid + max_range / 2,
z_mid - max_range / 2, z_mid + max_range / 2)
end
"""
create_geometry_plot_makie(body_aero::BodyAerodynamics, title,
view_elevation, view_azimuth; zoom=1.8)
Create a 3D Makie plot of wing geometry including panels and filaments.
# Arguments
- `body_aero`: struct of type BodyAerodynamics
- `title`: plot title
- `view_elevation`: initial view elevation angle [°]
- `view_azimuth`: initial view azimuth angle [°]
# Keyword arguments
- `zoom`: zoom factor (default: 1.8)
"""
function create_geometry_plot_makie(body_aero::BodyAerodynamics, title,
view_elevation, view_azimuth; zoom=0.5)
panels = body_aero.panels
va = getfield(body_aero, :_va)
# Create figure
fig = Figure(size=(1400, 1400))
ax = Axis3(fig[1, 1];
title=title,
xlabel="x", ylabel="y", zlabel="z",
aspect=:data,
azimuth=deg2rad(view_azimuth),
elevation=deg2rad(view_elevation))
# Plot panels
legend_used = Dict{String,Bool}()
for (i, panel) in enumerate(panels)
# Panel edges
corners = [Point3f(panel.corner_points[:, j]) for j in 1:4]
push!(corners, corners[1])
lines!(ax, corners; color=:grey, linewidth=1,
label=i == 1 ? "Panel Edges" : nothing)
# Control points
scatter!(ax, [Point3f(panel.control_point)];
color=:green, markersize=10,
label=i == 1 ? "Control Points" : nothing)
# Aerodynamic centers
scatter!(ax, [Point3f(panel.aero_center)];
color=:blue, markersize=10,
label=i == 1 ? "Aerodynamic Centers" : nothing)
# Plot filaments
filaments = calculate_filaments_for_plotting(panel)
legends = ["Bound Vortex", "side1", "side2", "wake_1", "wake_2"]
for (filament, legend) in zip(filaments, legends)
x1, x2, color = filament
show_legend = !get(legend_used, legend, false)
plot_line_segment_makie!(ax, [x1, x2], color,
show_legend ? legend : nothing)
legend_used[legend] = true
end
end
# Plot velocity vector
max_chord = maximum(panel.chord for panel in panels)
va_mag = norm(va)
va_vector_begin = -2 * max_chord * va / va_mag
va_vector_end = va_vector_begin + 1.5 * va / va_mag
plot_line_segment_makie!(ax, [va_vector_begin, va_vector_end], :lightblue, "va")
# Set equal axes
set_axes_equal_makie!(ax, panels; zoom)
# Add legend
axislegend(ax; position=:lt)
return fig
end
"""
plot_geometry(body_aero::BodyAerodynamics, title, ::MakieBackend;
data_type=nothing, save_path=nothing,
is_save=false, is_show=false,
view_elevation=15, view_azimuth=-120, use_tex=false)
Makie backend implementation of [`plot_geometry`](@ref).
# Arguments:
- `body_aero`: the BodyAerodynamics to plot
- `title`: plot title
# Keyword arguments:
- `data_type`: File extension (default: `nothing`; delegated to `save_plot` backend-aware default)
- `save_path`: Path for saving (default: nothing)
- `is_save`: Whether to save (default: false)
- `is_show`: Whether to display (default: false)
- `view_elevation`: View elevation angle in degrees (default: 15)
- `view_azimuth`: View azimuth angle in degrees (default: -120)
- `use_tex`: Ignored for Makie (default: false)
"""
function VortexStepMethod.plot_geometry(body_aero::BodyAerodynamics, title,
::VortexStepMethod.MakieBackend;
data_type=nothing,
save_path=nothing,
is_save=false,
is_show=false,
view_elevation=15,
view_azimuth=-120,
use_tex=false)
if is_save
# Angled view
fig = create_geometry_plot_makie(body_aero, "$(title)_angled_view", 15, -120)
save_plot(fig, save_path, "$(title)_angled_view", data_type=data_type)
# Top view
fig = create_geometry_plot_makie(body_aero, "$(title)_top_view", 90, 0)
save_plot(fig, save_path, "$(title)_top_view", data_type=data_type)
# Front view
fig = create_geometry_plot_makie(body_aero, "$(title)_front_view", 0, 0)
save_plot(fig, save_path, "$(title)_front_view", data_type=data_type)
# Side view
fig = create_geometry_plot_makie(body_aero, "$(title)_side_view", 0, -90)
save_plot(fig, save_path, "$(title)_side_view", data_type=data_type)
end
fig = create_geometry_plot_makie(body_aero, title, view_elevation, view_azimuth)
if is_show && isinteractive()
display(fig)
end
return fig
end
"""
plot_distribution(y_coordinates_list, results_list, label_list, ::MakieBackend;
title="spanwise_distribution", data_type=nothing,
save_path=nothing, is_save=false, is_show=true, use_tex=false)
Makie backend implementation of [`plot_distribution`](@ref).
# Arguments
- `y_coordinates_list`: List of spanwise coordinates
- `results_list`: List of result dictionaries
- `label_list`: List of labels for different results
# Keyword arguments
- `title`: Plot title (default: "spanwise_distribution")
- `data_type`: File extension (default: `nothing`; delegated to `save_plot` backend-aware default)
- `save_path`: Path to save plots (default: nothing)
- `is_save`: Whether to save (default: false)
- `is_show`: Whether to display (default: true)
- `use_tex`: Ignored for Makie (default: false)
"""
function VortexStepMethod.plot_distribution(y_coordinates_list, results_list, label_list,
::VortexStepMethod.MakieBackend;
title="spanwise_distribution",
data_type=nothing,
save_path=nothing,
is_save=false,
is_show=true,
use_tex=false)
length(results_list) == length(label_list) || throw(ArgumentError(
"Number of results ($(length(results_list))) must match labels ($(length(label_list)))"
))
# Create figure with 3x3 grid
fig = Figure(size=(1600, 1000))
Label(fig[0, :], title, fontsize=20)
# Row 1: CL, CD, Gamma
ax_cl = Axis(fig[1, 1], title="CL Distribution",
xlabel="Spanwise Position y/b", ylabel="Lift Coefficient CL")
ax_cd = Axis(fig[1, 2], title="CD Distribution",
xlabel="Spanwise Position y/b", ylabel="Drag Coefficient CD")
ax_gamma = Axis(fig[1, 3], title="Γ Distribution",
xlabel="Spanwise Position y/b", ylabel="Circulation Γ")
# Row 2: Alpha geometric, alpha at ac, alpha uncorrected
ax_alpha_geo = Axis(fig[2, 1], title="α Geometric",
xlabel="Spanwise Position y/b", ylabel="Angle of Attack α (deg)")
ax_alpha_ac = Axis(fig[2, 2], title="α result (corrected to aerodynamic center)",
xlabel="Spanwise Position y/b", ylabel="Angle of Attack α (deg)")
ax_alpha_unc = Axis(fig[2, 3], title="α Uncorrected (if VSM, at control point)",
xlabel="Spanwise Position y/b", ylabel="Angle of Attack α (deg)")
# Row 3: Force components
ax_fx = Axis(fig[3, 1], title="Force in x direction",
xlabel="Spanwise Position y/b", ylabel="Fx")
ax_fy = Axis(fig[3, 2], title="Force in y direction",
xlabel="Spanwise Position y/b", ylabel="Fy")
ax_fz = Axis(fig[3, 3], title="Force in z direction",
xlabel="Spanwise Position y/b", ylabel="Fz")
# Plot CL
for (y_coords, results, label) in zip(y_coordinates_list, results_list, label_list)
value = round(results["cl"], digits=2)
lines!(ax_cl, Vector(y_coords), Vector(results["cl_distribution"]),
label="$label CL: $value")
end
# Plot CD
for (y_coords, results, label) in zip(y_coordinates_list, results_list, label_list)
value = round(results["cd"], digits=2)
lines!(ax_cd, Vector(y_coords), Vector(results["cd_distribution"]),
label="$label CD: $value")
end
# Plot Gamma
for (y_coords, results, label) in zip(y_coordinates_list, results_list, label_list)
lines!(ax_gamma, Vector(y_coords), Vector(results["gamma_distribution"]),
label=label)
end
# Plot alpha geometric
for (y_coords, results, label) in zip(y_coordinates_list, results_list, label_list)
lines!(ax_alpha_geo, Vector(y_coords), Vector(results["alpha_geometric"]),
label=label)
end
# Plot alpha at ac
for (y_coords, results, label) in zip(y_coordinates_list, results_list, label_list)
lines!(ax_alpha_ac, Vector(y_coords), Vector(results["alpha_at_ac"]),
label=label)
end
# Plot alpha uncorrected
for (y_coords, results, label) in zip(y_coordinates_list, results_list, label_list)
lines!(ax_alpha_unc, Vector(y_coords), Vector(results["alpha_uncorrected"]),
label=label)
end
# Plot force components
force_axes = [ax_fx, ax_fy, ax_fz]
components = ["x", "y", "z"]
for (idx, (ax, comp)) in enumerate(zip(force_axes, components))
for (y_coords, results, label) in zip(y_coordinates_list, results_list, label_list)
forces = results["F_distribution"][idx, :]
if length(y_coords) != length(forces)
@warn "Dimension mismatch" length(y_coords) length(forces) comp
continue
end
total_force = round(results["F$comp"], digits=2)
lines!(ax, Vector(y_coords), Vector(forces),
label="$label ΣF$comp: $total_force N")
end
end
# Shared legend at bottom of grid
Legend(fig[4, :], ax_gamma;
orientation=:horizontal, tellwidth=false, tellheight=true)
# Save and show
if is_save
save_plot(fig, save_path, title, data_type=data_type)
end
if is_show && isinteractive()
display(fig)
end
return fig
end
"""
generate_polar_data(solver, body_aero::BodyAerodynamics, angle_range;
angle_type="angle_of_attack", angle_of_attack=0.0,
side_slip=0.0, v_a=10.0)
Generate polar data for aerodynamic analysis over a range of angles.
# Arguments
- `solver`: Aerodynamic solver object
- `body_aero`: Wing aerodynamics struct
- `angle_range`: Range of angles to analyze
# Keyword arguments
- `angle_type`: Type of angle variation ("angle_of_attack" or "side_slip")
- `angle_of_attack`: Initial angle of attack [°]
- `side_slip`: Initial side slip angle [°]
- `v_a`: Norm of apparent wind speed [m/s]
# Returns
- Tuple of polar data array and Reynolds number
"""
"""
plot_polars(solver_list, body_aero_list, label_list, ::MakieBackend;
literature_path_list=String[],
angle_range=range(0, 20, 2), angle_type="angle_of_attack",
angle_of_attack=0.0, side_slip=0.0, v_a=10.0,
title="polar", data_type=nothing, save_path=nothing,
is_save=true, is_show=true, use_tex=false)
Makie backend implementation of [`plot_polars`](@ref).
# Arguments
- `solver_list`: List of aerodynamic solvers
- `body_aero_list`: List of wing aerodynamics objects
- `label_list`: List of labels for each configuration
# Keyword arguments
- `literature_path_list`: Optional paths to literature data files
- `angle_range`: Range of angles in degrees
- `angle_type`: "angle_of_attack" or "side_slip" (default: angle_of_attack)
- `angle_of_attack`: AoA [°] (default: 0.0)
- `side_slip`: Side slip angle [°] (default: 0.0)
- `v_a`: Wind speed [m/s] (default: 10.0)
- `title`: Plot title
- `data_type`: File extension (default: `nothing`; delegated to `save_plot` backend-aware default)
- `save_path`: Path to save (default: nothing)
- `is_save`: Whether to save (default: true)
- `is_show`: Whether to display (default: true)
- `use_tex`: Ignored for Makie (default: false)
- `cl_over_cd`: Plot CL/CD vs angle instead of CL vs CD (default: true)
"""
function VortexStepMethod.plot_polars(
solver_list,
body_aero_list,
label_list,
::VortexStepMethod.MakieBackend;
literature_path_list=String[],
angle_range=range(0, 20, 2),
angle_type="angle_of_attack",
angle_of_attack=0.0,
side_slip=0.0,
v_a=10.0,
title="polar",
data_type=nothing,
save_path=nothing,
is_save=true,
is_show=true,
use_tex=false,
cl_over_cd=true,
show_moments=false,
)
# Validate inputs
total_cases = length(body_aero_list) + length(literature_path_list)
if total_cases != length(label_list) || length(solver_list) != length(body_aero_list)
throw(ArgumentError("Mismatch in solvers/cases/labels"))
end
main_title = replace(title, " " => "_")
# Generate polar data
polar_data_list = []
cm_data_list = []
labels_with_re = copy(label_list)
for (i, (solver, body_aero)) in enumerate(zip(solver_list, body_aero_list))
result = VortexStepMethod.generate_polar_data(
solver, body_aero, angle_range;
angle_type, angle_of_attack, side_slip, v_a
)
push!(polar_data_list, result.polar_data)
push!(cm_data_list, (cmx=result.cmx, cmy=result.cmy,
cmz=result.cmz))
labels_with_re[i] = "$(label_list[i]) Re = $(round(Int64, result.rey*1e-5))e5"
end
# Load literature data if provided
if !isempty(literature_path_list)
for path in literature_path_list
lit = VortexStepMethod.extract_literature_polar_data(
readdlm(path, ','), path; angle_type)
push!(polar_data_list, lit.polar_data)
push!(cm_data_list, (cmx=lit.cmx, cmy=lit.cmy,
cmz=lit.cmz))
end
end
# Number of computational results
n_solvers = length(solver_list)
if show_moments
# 2x3 layout: CL, CD, CS, CMx, CMy, CMz
fig = Figure(size=(1800, 1000))
ax_cl = Axis(fig[1, 1], title="CL vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CL")
ax_cd = Axis(fig[1, 2], title="CD vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CD")
ax_cs = Axis(fig[1, 3], title="CS vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CS")
ax_cmx = Axis(fig[2, 1], title="CMx vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CMx")
ax_cmy = Axis(fig[2, 2], title="CMy vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CMy")
ax_cmz = Axis(fig[2, 3], title="CMz vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CMz")
for ax in (ax_cl, ax_cd, ax_cs, ax_cmx, ax_cmy, ax_cmz)
ax.yticklabelspace = 36.0
ax.xticklabelspace = 24.0
end
for (i, (polar_data, cm, label)) in enumerate(
zip(polar_data_list, cm_data_list, labels_with_re))
marker = i <= n_solvers ? :star5 : :circle
markersize = i <= n_solvers ? 12 : 8
angles = polar_data[1]
scatterlines!(ax_cl, angles, polar_data[2];
label=label, marker=marker, markersize=markersize)
scatterlines!(ax_cd, angles, polar_data[3];
label=label, marker=marker, markersize=markersize)
scatterlines!(ax_cs, angles, polar_data[4];
label=label, marker=marker, markersize=markersize)
if !all(isnan, cm.cmx)
scatterlines!(ax_cmx, angles,
Float64.(cm.cmx);
label=label, marker=marker,
markersize=markersize)
end
if !all(isnan, cm.cmy)
scatterlines!(ax_cmy, angles,
Float64.(cm.cmy);
label=label, marker=marker,
markersize=markersize)
end
if !all(isnan, cm.cmz)
scatterlines!(ax_cmz, angles,
Float64.(cm.cmz);
label=label, marker=marker,
markersize=markersize)
end
end
Legend(fig[3, 1:3], ax_cl;
orientation=:horizontal, tellwidth=false,
tellheight=true)
else
# 2x2 layout: CL, CD, CS, CL/CD or CL-vs-CD
fig = Figure(size=(1400, 1400))
ax_cl = Axis(fig[1, 1], title="CL vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CL")
ax_cd = Axis(fig[1, 2], title="CD vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CD")
ax_cs = Axis(fig[2, 1], title="CS vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CS")
ax_fourth = if cl_over_cd
Axis(fig[2, 2], title="CL/CD vs $angle_type [°]",
xlabel="$angle_type [°]", ylabel="CL/CD")
else
Axis(fig[2, 2], title="CL vs CD",
xlabel="CD", ylabel="CL")
end
for (i, (polar_data, label)) in enumerate(
zip(polar_data_list, labels_with_re))
marker = i <= n_solvers ? :star5 : :circle
markersize = i <= n_solvers ? 12 : 8
scatterlines!(ax_cl, polar_data[1], polar_data[2];
label=label, marker=marker,
markersize=markersize)
scatterlines!(ax_cd, polar_data[1], polar_data[3];
label=label, marker=marker,
markersize=markersize)
scatterlines!(ax_cs, polar_data[1], polar_data[4];
label=label, marker=marker,
markersize=markersize)
if cl_over_cd
cl_cd = polar_data[2] ./ polar_data[3]
scatterlines!(ax_fourth, polar_data[1], cl_cd;
label=label, marker=marker,
markersize=markersize)
else
scatterlines!(ax_fourth, polar_data[3],
polar_data[2];
label=label, marker=marker,
markersize=markersize)
end
end
Legend(fig[3, :], ax_cl;
orientation=:horizontal, tellwidth=false,
tellheight=true)
end
# Save and show
if is_save && !isnothing(save_path)
save_plot(fig, save_path, main_title; data_type)
end
if is_show && isinteractive()
display(fig)
end
return fig
end
"""
plot_polar_data(body_aero::BodyAerodynamics, ::MakieBackend;
alphas=collect(deg2rad.(-5:0.3:25)),
delta_tes=collect(deg2rad.(-5:0.3:25)),
is_show=true, use_tex=false)
Makie backend implementation of [`plot_polar_data`](@ref).
# Arguments
- `body_aero`: Wing aerodynamics struct
# Keyword arguments
- `alphas`: Range of AoA values in radians (default: `deg2rad.(-5:0.3:25)`)
- `delta_tes`: Range of trailing edge angles in radians (default: `deg2rad.(-5:0.3:25)`)
- `is_show`: Whether to display (default: true)
- `use_tex`: Ignored for Makie (default: false)
"""
function VortexStepMethod.plot_polar_data(body_aero::BodyAerodynamics,
::VortexStepMethod.MakieBackend;
alphas=collect(deg2rad.(-5:0.3:25)),
delta_tes=collect(deg2rad.(-5:0.3:25)),
is_show=true,
use_tex=false)
if body_aero.panels[1].aero_model == POLAR_MATRICES
# Create figure with 3 subplots
fig = Figure(size=(1500, 600))
# Get interpolation functions
interp_data = [
(body_aero.panels[1].cl_interp, "Cl"),
(body_aero.panels[1].cd_interp, "Cd"),
(body_aero.panels[1].cm_interp, "Cm")
]
# Create each subplot
for (idx, (interp, label)) in enumerate(interp_data)
ax = Axis3(fig[1, idx];
title="$label vs α and δ",
xlabel="δ [rad]",
ylabel="α [rad]",
zlabel=label,
azimuth=1.275 * π)
# Create interpolation matrix
interp_matrix = [interp(alpha, delta_te)
for delta_te in delta_tes, alpha in alphas]
# Create wireframe
wireframe!(ax, delta_tes, alphas, interp_matrix;
color=:blue, linewidth=0.5, transparency=true)
end
if is_show && isinteractive()
display(fig)
end
return fig
else
throw(ArgumentError(
"Plotting polar data for $(body_aero.panels[1].aero_model) not implemented."
))
end
end
"""
plot_combined_analysis(solver, body_aero, results, ::MakieBackend;
solver_label="VSM",
angle_range=range(0,20,length=20),
angle_type="angle_of_attack",
angle_of_attack=0.0, side_slip=0.0, v_a=10.0,
title="Combined Analysis",
view_elevation=15, view_azimuth=-120,
is_show=true, use_tex=false,
literature_path_list=String[],
data_type=".png", save_path=nothing, is_save=false)
Makie backend implementation of [`plot_combined_analysis`](@ref).
# Arguments
- `solver`: Aerodynamic solver
- `body_aero`: BodyAerodynamics object
- `results`: Solution dictionary from solve()
# Keyword arguments
- `labels`: Optional label string or label vector. If a vector with length
`length(solver)+length(literature_path_list)` is provided, the tail is used
for literature labels; otherwise literature labels default to file basenames.
- `solver_label`: Backward-compatible alias for `labels`.
- `angle_range`: Range of angles for polars (default: range(0,20,length=20))
- `angle_type`: "angle_of_attack" or "side_slip" (default: "angle_of_attack")
- `angle_of_attack`: AoA in degrees (default: 0.0)
- `side_slip`: Side slip in degrees (default: 0.0)
- `v_a`: Wind speed in m/s (default: 10.0)
- `title`: Overall figure title (default: "Combined Analysis")
- `view_elevation`: Geometry view elevation in degrees (default: 15)
- `view_azimuth`: Geometry view azimuth in degrees (default: -120)
- `is_show`: Display figure (default: true)
- `use_tex`: Ignored for Makie (default: false)
- `literature_path_list`: Paths to literature CSV files (default: String[])
- `data_type`: File extension (default: ".png", also supports ".jpeg")
- `save_path`: Directory path to save files (default: nothing)
- `is_save`: Save plots to files (default: false)
- `cl_over_cd`: Plot CL/CD vs angle instead of CL vs CD (default: true)
- `angle_of_attack_for_spanwise_distribution`: AoA for spanwise plots (default: 5.0)
"""
function VortexStepMethod.plot_combined_analysis(
solver,
body_aero,
results,
::VortexStepMethod.MakieBackend;
solver_label="VSM",
labels=nothing,
angle_range=range(0, 20, length=20),
angle_type="angle_of_attack",
angle_of_attack=0.0,
side_slip=0.0,
v_a=10.0,
title="Combined Analysis",
view_elevation=15,
view_azimuth=-120,
is_show=true,
use_tex=false,
literature_path_list=String[],
data_type=".png",