-
Notifications
You must be signed in to change notification settings - Fork 10
/
FLOWVLM_rotor.jl
executable file
·2188 lines (1858 loc) · 76.8 KB
/
FLOWVLM_rotor.jl
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
################################################################################
# ROTOR CLASS
################################################################################
"""
`Rotor(CW, r, chord, theta, LE_x, LE_z, B, airfoil)`
Object defining the geometry of a rotor/propeller/wind turbine. This class
behaves as an extension of the WingSystem class, hence all functions of
WingSystem can be applied to a Rotor object.
# Arguments
* CW::Bool : True for clockwise rotation, false for CCW.
* r::Array{Float64,1} : Radius position for the following variables.
* chord::Array{Float64,1} : Chord length.
* theta::Array{Float64,1} : Angle of attack (deg) from the rotor's plane
of rotation.
* LE_x::Array{Float64,1} : x-position of leading edge (positive is ahead
of radial axis relative to rotation).
* LE_z::Array{Float64,1} : z-position of leading edge (height from plane
of rotation).
* B::Int64 : Number of blades.
# Optional Arguments
* airfoils::Array{Tuple{Float64, airfoilprep.Polar},1} : 2D airfoil properties
along blade in the form [ (r_i, Polar_i) ]
with Polar_i describes the airfoil at i-th
radial position r_i (both the airfoil geometry
in Polar_i and r_i must be normalized). At
least root (r=0) and tip (r=1) must be given
so all positions in between can be
extrapolated. This properties are only used
when calling CCBlade and for generating good
loking visuals; ignore if only solving the VLM.
NOTE: r here is the radial position after precone is included in the geometry,
hence the need of explicitely declaring LE_z.
# PROPERTIES
* `sol` : Contains solution fields specific for Rotor types. They are formated
as sol[field_name] = Dict(
"field_name" => output_field_name,
"field_type" => "scalar" or "vector",
"field_data" => data
)
where `data` is an array data[i] = [val1, val2, ...] containing
this field values (scalar or vector) of all control points in the
i-th blade.
<!-- NOTE TO SELF: r is the y-direction on a wing, hence, remember to build the
blade from root in the direction of positive y. -->
"""
mutable struct Rotor
# Initialization variables (USER INPUT)
CW::Bool # True for clockwise rotation
r::FArrWrap # Radius position for the following variables
chord::FArrWrap # Chord length
theta::FArrWrap # Angle of attack (deg) from the rotor's axis
LE_x::FArrWrap # x-position of leading edge
LE_z::FArrWrap # z-position of leading edge (Height from plane
# of rotation)
B::IWrap # Number of blades
# Optional inputs
airfoils::Array{Tuple{FWrap,ap.Polar},1} # 2D airfoil properties along blade
turbine_flag::Bool # Whether this is a wind turbine or a propeller
# Properties
RPM::Any # Current revs per minute
hubR::FWrap # Hub radius
rotorR::FWrap # Rotor radius
m::IWrap # Number of control points (per blade)
sol::Dict{String,Any} # Solution fields for CCBlade (not FLOWVLM)
# Data storage
_wingsystem::WingSystem # Rotor assembly
_r::FArrWrap # Radius of each control point (on one blade)
_chord::FArrWrap # Chord length at each control point
_theta::FArrWrap # Angle of attack (deg) at each control point
_LE_x::FArrWrap
_LE_z::FArrWrap
_polars::Array{ap.Polar, 1} # Polar object at each control point (with x,y
# containing the exact geometric airfoil)
_polarroot::ap.Polar # Polar at the root
_polartip::ap.Polar # Polar at the tip
Rotor(
CW, r, chord, theta, LE_x, LE_z, B,
airfoils=Tuple{FWrap, ap.Polar}[],
turbine_flag=false,
RPM=nothing,
hubR=r[1], rotorR=r[end],
m=0, sol=Dict(),
_wingsystem=WingSystem(),
_r=FWrap[], _chord=FWrap[], _theta=FWrap[],
_LE_x=FWrap[], _LE_z=FWrap[],
_polars=ap.Polar[],
_polarroot=ap.dummy_polar(), _polartip=ap.dummy_polar()
) = new(
CW, r, chord, theta, LE_x, LE_z, B,
airfoils,
turbine_flag,
RPM,
hubR, rotorR,
m, sol,
_wingsystem,
_r, _chord, _theta,
_LE_x, _LE_z,
_polars, _polarroot, _polartip
)
end
# Tip and hub loss correction parameters (eh1, eh2, eh3, maxah)
const nohubcorrection = (1, 0, Inf, 5*eps())
const notipcorrection = (1, 0, Inf, 5*eps())
const hubtiploss_nocorrection = ( nohubcorrection, notipcorrection ) # No correction
const hubtiploss_correction_prandtl = ( (1, 1, 1, 1.0), (1, 1, 1, 1.0) ) # Prandtl hub/tip correction
const hubtiploss_correction_modprandtl = ( (0.6, 5, 0.5, 10), (2, 1, 0.25, 0.05) ) # Modified Prandtl hub/tip correction
"Initializes the geometry of the rotor, discretizing each blade into n lattices"
function initialize(self::Rotor, n::IWrap; r_lat::FWrap=1.0,
central=false, refinement=[], verif=false,
figsize_factor=2/3, genblade_args=[], rfl_args...)
# Checks for arguments consistency
_check(self)
# Flag for calculating airfoils
rfl_flag = size(self.airfoils)[1]!=0
# Generates blade
blade, r, chord, theta, LE_x, LE_z = _generate_blade(self, n; r=r_lat,
central=central, refinement=refinement,
genblade_args...)
self._r, self._chord, self._theta = r, chord, theta
self._LE_x, self._LE_z = LE_x, LE_z
self.m = get_m(blade)
# Verifies correct lattice and blade elements discretization
if verif; _verif_discr(self, blade, r, chord, theta, LE_x, LE_z; figsize_factor=figsize_factor); end;
# Generates airfoil properties at all control points of this blade
if rfl_flag; _calc_airfoils(self, n, r_lat, central, refinement; rfl_args...); end;
# ------------ Generates full rotor -----------------
# Default blade c.s. relative to rotor c.s.
blades_Oaxis = self.CW ? [0 -1 0; 0 0 1; -1.0 0 0] : [0 1 0; 0 0 1; 1.0 0 0]
init_angle = 0.0
d_angle = 2*pi/self.B
for i in 1:self.B
this_blade = i==1 ? blade : copy(blade)
this_angle = init_angle + (i-1)*d_angle # Azumithal angle of this blade
# Sets the blade in the rotor coordinate system, and rotates it
this_Oaxis = [ cos(this_angle) sin(this_angle) 0;
-sin(this_angle) cos(this_angle) 0;
0 0 1]*blades_Oaxis
setcoordsystem(this_blade, [0.0,0,0], this_Oaxis)
# Adds it to the rotor
addwing(self, "Blade$(i)", this_blade; force=true)
end
# Sets the rotor in the global coordinate system
rotor_Oaxis = [-1 0 0; 0 -1 0; 0 0 1.0]
setcoordsystem(self._wingsystem, [0.0,0,0], rotor_Oaxis)
end
"""Given the velocity induced at each control point (Vind = Vwake, no lifting
surface), solves for the Gamma field (circulation) on each blade by looking at
the airfoil polar at the effective angle of attack of every section. It also
includes the fields Ftot, L, D, and S. (WARNING: These Ftot, L, D, and S are
forces per unit length!)
This method solves iteratively until the circulation distribution converges.
NOTE: Vind is expected to be in the global coordinate system.
NOTE: Vind is expected to be formated as Vind[i][j] being the velocity vector
of the j-th control point in the i-th blade.
"""
function solvefromVite(self::Rotor, Vind::Array{Array{T, 1}, 1}, args...;
maxite::Int64=100, tol::Real=0.01, rlx=0.0, optargs...
) where{T<:FArrWrap}
println(rlx)
out = nothing
if "Gamma" in keys(get_blade(self, 1).sol)
prev_sol = [get_blade(self, j).sol["Gamma"] for j in 1:self.B]
else
prev_sol = nothing
end
ite = 0
err = nothing
for i in 1:maxite
if i==1
surfVind = Vind
else
# Adds V induced by lifting surface
surfVind = [[ Vind[j][k] + Vind(self, getControlPoint(get_blade(self, j), k); ign_infvortex=true)
for k in 1:size(Vind[j],1)] for j in 1:size(Vind,1)]
end
out = solvefromV(self, surfVind, args...; optargs...)
this_sol = [get_blade(self, j).sol["Gamma"] for j in 1:self.B]
if prev_sol != nothing
# Checking convergence: Average variation
err = mean( [mean( abs.(prev_sol[j]-this_sol[j])./abs.(prev_sol[j]) ) for j in 1:self.B] )
if err < tol
break
end
# Relaxation
for j in 1:rotor.B
blade = get_blade(rotor, j)
blade.sol["Gamma"][:] = rlx*prev_sol[j] .+ (1-rlx)*this_sol[j]
end
end
prev_sol = this_sol
ite += 1
end
if ite==maxite
@warn "Iterative Rotor solvefromV reached max iterations without converging."*
" maxite:$maxite\t error:$err"
end
return out
end
"""Given the velocity induced at each control point (Vind = Vliftsurface+Vwake),
solves for the Gamma field (circulation) on each blade by looking at the airfoil
polar at the effective angle of attack of every section. It also includes the
fields Ftot, L, D, and S. (WARNING: These Ftot, L, D, and S are
forces per unit length!)
THIS METHOD IS UNSTABLE.
NOTE: Vind is expected to be in the global coordinate system.
NOTE: Vind is expected to be formated as Vind[i][j] being the velocity vector
of the j-th control point in the i-th blade.
"""
function solvefromV(self::Rotor, Vind::Array{Array{T, 1}, 1}, args...;
optargs...) where{T<:FArrWrap}
# ERROR CASES
if size(Vind, 1)!=self.B
error("Expected $(self.B) Vind entries; got $(size(Vind, 1)).")
else
for bi in 1:self.B
if size(Vind[bi],1)!=get_mBlade(self)
error("Expected $(get_mBlade(self)) Vind[$bi] entries;"*
" got $(size(Vind[i],1)).")
end
end
end
return solvefromCCBlade(self, args...; _lookuptable=true, _Vinds=Vind,
optargs...)
end
"Solves for the Gamma field (circulation) on each blade using CCBlade. It also
includes the fields Ftot, L, D, and S. (WARNING: These Ftot, L, D, and S are
forces per unit length!)
If include_comps==true it stores CCBlade-calculated normal and tangential forces
in the Rotor."
function solvefromCCBlade(self::Rotor, Vinf, RPM, rho::FWrap; t::FWrap=0.0,
include_comps::Bool=true, return_performance::Bool=false,
Vref=nothing, sound_spd=nothing, Uinds=nothing,
_lookuptable::Bool=false, _Vinds=nothing,
hubtiploss_correction=hubtiploss_nocorrection,
AR_to_360extrap=true,
debug=false, verbosewarn=true)
setVinf(self, Vinf)
setRPM(self, RPM)
# (Calls a HS to make sure they have been calculated)
_ = getHorseshoe(self, 1)
if sound_spd==nothing && verbosewarn
@warn "No sound speed has been provided. No Mach corrections will be applied."
end
# Calculates distributed load from CCBlade
prfrmnc, gammas, mus_drag = calc_distributedloads(self, Vinf, RPM, rho; t=t,
include_comps=include_comps,
return_performance=return_performance,
Vref=Vref, sound_spd=sound_spd,
Uinds=Uinds,
_lookuptable=_lookuptable, _Vinds=_Vinds,
hubtiploss_correction=hubtiploss_correction,
AR_to_360extrap=AR_to_360extrap,
debug=debug)
# Decomposes load into aerodynamic forces and calculates circulation
gamma, mu_drag = calc_aerodynamicforces(self, rho; overwritegammas=gammas,
overwritemus=mus_drag)
new_gamma = FWrap[]
new_mu = FWrap[]
new_Ftot = FArrWrap[]
new_L = FArrWrap[]
new_D = FArrWrap[]
new_S = FArrWrap[]
# Formats solution fields as a FLOWVLM solution
for i in 1:self.B # Iterates over blades
for j in 1:get_mBlade(self) # Iterates over lattices on blade
push!(new_gamma, gamma[i][j])
push!(new_mu, mu_drag[i][j])
push!(new_Ftot, self.sol["DistributedLoad"]["field_data"][i][j])
push!(new_L, self.sol["Lift"]["field_data"][i][j])
push!(new_D, self.sol["Drag"]["field_data"][i][j])
push!(new_S, self.sol["RadialForce"]["field_data"][i][j])
end
end
# Adds the fields as FLOWVLM solutions
_addsolution(self._wingsystem, "Gamma", new_gamma; t=t)
_addsolution(self._wingsystem, "mu", new_mu; t=t)
# (WARNING: These Ftot, L, D, and S are forces per unit length!)
_addsolution(self._wingsystem, "Ftot", new_Ftot; t=t)
_addsolution(self._wingsystem, "L", new_L; t=t)
_addsolution(self._wingsystem, "D", new_D; t=t)
_addsolution(self._wingsystem, "S", new_S; t=t)
return prfrmnc
end
"Sets Vinf(X,t) as the incoming freestream of this rotor"
function setVinf(self::Rotor, Vinf; keep_sol=false)
_reset(self; keep_sol=keep_sol)
setVinf(self._wingsystem, Vinf; keep_sol=keep_sol)
end
"Sets `RPM` as the revolutions per minutes of this rotor"
function setRPM(self::Rotor, RPM)
_reset(self; keep_Vinf=true)
_resetRotor(self)
self.RPM = RPM
end
"Saves the rotor in VTK legacy format"
function save(self::Rotor, filename::String; addtiproot=true, airfoils=false,
wopwop=false, wopbin=true, wopext="wop",
wopv=1.0, save_horseshoes=true,
args...)
if save_horseshoes
_ = getHorseshoe(self, 1) # Makes sure the wake is calculated right
end
strn = save(self._wingsystem, filename; save_horseshoes=save_horseshoes, args...)
if size(self.airfoils)[1]!=0
strn *= save_loft(self, filename; addtiproot=addtiproot, airfoils=airfoils,
wopwop=wopwop, wopbin=wopbin, wopext=wopext,
wopv=wopv, args...)
end
return strn
end
"""
setcoordsystem(rotor::Rotor, O::Vector, Oaxis::Matrix; user=false)
Redefines the local coordinate system of the rotor, where `O` is the new origin
and `Oaxis` is the matrix of unit vectors. If the user is calling this function,
give `user=true`, otherwise it will not do the automatic translation to blade
coordinate system.
"""
function setcoordsystem(self::Rotor, O::FArrWrap,
Oaxis::FMWrap; user=false, args...)
if user
setcoordsystem(self._wingsystem, O, Oaxis*[-1 0 0; 0 -1 0; 0 0 1.0],args...)
else
setcoordsystem(self._wingsystem, O, Oaxis ,args...)
end
_resetRotor(self; keep_RPM=true)
end
"""
rotate(rotor::Rotor, degs::Real)
Rotates the rotor by `degs` degrees in the direction of rotation (`rotor.CW`).
"""
function rotate(self::Rotor, degs::FWrap)
rotOaxis = gt.rotation_matrix(0.0, 0.0, (-1)^!self.CW*degs)
newOaxis = rotOaxis*self._wingsystem.Oaxis
# setcoordsystem(self._wingsystem, self._wingsystem.O, newOaxis)
setcoordsystem(self, self._wingsystem.O, newOaxis)
end
"Returns the undisturbed freestream at each control point"
function getVinfs(self::Rotor; t::FWrap=0.0, target="CP",
extraVinf=nothing, extraVinfArgs...)
if !(target in keys(VLMSolver.HS_hash))
error("Logic error! Invalid target $target.")
end
_ = getHorseshoe(self, 1; t=t, extraVinf=extraVinf, extraVinfArgs...)
Vinfs = FArrWrap[]
for i in 1:self.B
blade_Vinfs = _calc_inflow(get_blade(self, i), get_RPM(self), t;
target=target)
for V in blade_Vinfs
push!(Vinfs, V)
end
end
# Adds any extra terms
if extraVinf!=nothing
for i in 1:self.B
blade = get_blade(self, i)
for j in 1:get_m(blade)
Vinfs[i][j] += extraVinf(j, t; extraVinfArgs..., wing=blade)
end
end
end
return Vinfs
end
function get_RPM(self::Rotor)
if self.RPM==nothing
error("RPM not defined yet."*
" Call function `setRPM()` before calling this function.")
end
return self.RPM
end
"""
get_mBlade(rotor::Rotor)
Returns the number of horseshoes per blade
"""
function get_mBlade(self::Rotor)
return self.m
end
"Returns the requested blade"
function get_blade(self::Rotor, blade_i::IWrap)
return get_wing(self, blade_i)
end
"""
get_m(rotor::Rotor)
Returns the total number of horseshoes in the rotor
"""
function get_m(self::Rotor)
return get_m(self._wingsystem)
end
"Returns the m-th control point of the system"
function getControlPoint(self::Rotor, m::IWrap)
return getControlPoint(self._wingsystem, m)
end
"Returns the m-th horseshoe of the system in the global coordinate system"
function getHorseshoe(self::Rotor, m::IWrap; t::FWrap=0.0, extraVinf...)
# Checks if horseshoes will be recalculated
flag = true in [get_blade(self, i)._HSs==nothing for i in 1:self.B]
# ERROR CASE IF NEEDS TO CALCULATE HORSESHOES
if flag
if self.RPM==nothing
error("RPM hasn't been defined yet."*
" Call function `setRPM()` before calling this function.")
elseif self._wingsystem.Vinf==nothing
error("Freestream hasn't been define yet, please call function set_Vinf()")
end
end
# If horseshoes will be calculated, it forces to do it now and replaces
# the regular infinite vortex with vortex in the direction of inflow at the
# control point
if flag
for i in 1:self.B # Iterates over blades
blade = get_blade(self, i)
# Case horseshoes haven't been calculated yet
if blade._HSs==nothing
O = blade.O # Center of rotation
# Forces to calculate horseshoes now
_calculateHSs(blade; t=t, extraVinf...)
# Calculates the inflow at each side Ap and Bp of each HS
VAp = _calc_inflow(blade, get_RPM(self), t; target="Ap")
VBp = _calc_inflow(blade, get_RPM(self), t; target="Bp")
# Corrects each infinite vortex (infDA and infDB)
for j in 1:size(blade._HSs)[1] # Iterates over horseshoes
blade._HSs[j][6] = VAp[j]/norm(VAp[j])
blade._HSs[j][7] = VBp[j]/norm(VBp[j])
end
end
end
end
return getHorseshoe(self._wingsystem, m; t=t, extraVinf...)
end
"Saves the lofted surface of the blade"
function save_loft(self::Rotor, filename::String; addtiproot=false, path="",
num=nothing, airfoils=false,
wopwop=false, wopext="wop", wopbin=true, wopv=1.0,
args...)
if wopwop; addtiproot=true; end;
# ERROR CASES
if size(self.airfoils)[1]<2
error("Requested lofted surface, but no airfoil geometry was given.")
elseif size(self._polars)[1]<2
error("Polars not found. Run `initialize()` and try again")
end
strn = ""
suf = "loft"
rfl_suf = "rfl"
CP_index = [] # Stores the CP index in order to hash the points
lines = [] # Contour lines of cross sections
# Iterates over each airfoil creating cross sections
for (i,polar) in enumerate(self._polars)
theta = pi/180*self._theta[i] # Angle of attack
# Actual airfoil contour
x, y = self._chord[i]*polar.x, self._chord[i]*polar.y*(-1)^self.turbine_flag
# Reformats x,y into point
points = [ [x[i], y[i], 0.0] for i in 1:size(x)[1] ]
# Rotates the contour in the right angle of attack
# and orients the airfoil for CCW or CW rotation
Oaxis = [cos(theta) -sin(theta) 0; sin(theta) cos(theta) 0; 0 0 1]
Oaxis = [1 0 0; 0 (-1.0)^self.CW 0; 0 0 (-1.0)^self.CW]*Oaxis
points = gt.countertransform(points, inv(Oaxis), fill(0.0, 3))
# Position of leading edge in FLOVLM blade's c.s.
# Airfoil's x-axis = FLOWVLM blade's x-axis
# Airfoil's y-axis = FLOWVLM blade's z-axis
O = [self._LE_x[i], self._r[i], self._LE_z[i]]
# Reformats the contour into FLOWVLM blade's c.s.
points = [ O+[p[1], p[3], p[2]] for p in points]
# Adds this airfoil
push!(lines, points)
# Adds the CP index as point data for all points in this airfoil
push!(CP_index, [i for p in points])
# Case of root or tip
if addtiproot && (i==1 || i==size(self._polars,1))
root_flg = i==1
ind = root_flg ? 1 : size(self.r,1)
alt_polar = root_flg ? self._polarroot : self._polartip
theta = (-1)^(self.CW)*pi/180*self.theta[ind] # Angle of attack
# Actual airfoil contour
x, y = self.chord[ind]*alt_polar.x, self.chord[ind]*alt_polar.y
# Reformats x,y into point
points = [ [x[i], y[i], 0.0] for i in 1:size(x)[1] ]
# Rotates the contour in the right angle of attack
# and orients the airfoil for CCW or CW rotation
Oaxis = [cos(theta) -sin(theta) 0; sin(theta) cos(theta) 0; 0 0 1]
Oaxis = [1 0 0; 0 (-1.0)^self.CW 0; 0 0 (-1.0)^self.CW]*Oaxis
points = gt.countertransform(points, inv(Oaxis), fill(0.0, 3))
# Position of leading edge in FLOVLM blade's c.s.
# Airfoil's x-axis = FLOWVLM blade's x-axis
# Airfoil's y-axis = FLOWVLM blade's z-axis
O = [(-1)*self.LE_x[ind], self.r[ind], (-1)^(self.CW)*self.LE_z[ind]]
# Reformats the contour into FLOWVLM blade's c.s.
points = [ O+[p[1], p[3], p[2]] for p in points]
if root_flg
lines = vcat([points], lines)
CP_index = vcat([[i for p in points]], CP_index)
else
push!(lines, points)
push!(CP_index, [i for p in points])
end
end
end
# Generates vtk cells from cross sections
sections = [ [(1.0, 1, 1.0, false)] for i in 1:size(lines)[1]-1]
points, vtk_cells, CP_index = gt.multilines2vtkmulticells(lines, sections;
point_datas=CP_index)
# Flips the cells in clockwise rotor to have normals pointing out
if self.CW
vtk_cells = reverse.(vtk_cells)
end
if airfoils || wopwop
line_points, vtk_lines, _ = gt.lines2vtk(lines)
end
# Generates each blade
for i in 1:self.B # Iterates over blades
this_blade = self._wingsystem.wings[i]
# Transforms points from FLOWVLM blade's c.s. to global c.s.
this_points = FArrWrap[ gt.countertransform(p, this_blade.invOaxis,
this_blade.O) for p in points]
if airfoils || wopwop
this_line_points = FArrWrap[ gt.countertransform(p, this_blade.invOaxis,
this_blade.O) for p in line_points]
end
# Formats the point data for generateVTK
data = []
# # Control point indices
# push!(data, Dict(
# "field_name" => "ControlPoint_Index",
# "field_type" => "scalar",
# "field_data" => CP_index
# )
# )
# Stored fields
for (field_name, field) in self.sol # Iterates over fields
if field["field_type"] != "not-vtk"
data_points = [] # Field data associated to each geometric point
for (j,p) in enumerate(this_points) # Iterates over geometric points
CP_i = Int(CP_index[j]) # Hashes the control point index of this geom point
push!(data_points, field["field_data"][i][CP_i])
end
push!(data, Dict(
"field_name" => field["field_name"],
"field_type" => field["field_type"],
"field_data" => data_points
)
)
end
end
# Generates the vtk file
this_name = filename*"_"*self._wingsystem.wing_names[i]*"_"*suf
strn *= gt.generateVTK(this_name, this_points; cells=vtk_cells,
point_data=data, path=path, num=num)
if airfoils
this_linename = filename*"_"*self._wingsystem.wing_names[i]*"_"*rfl_suf
strn *= gt.generateVTK(this_linename, this_line_points; cells=vtk_lines,
path=path, num=num)
end
# Generates PLOT3D-like geometry for PSU-WOPWOP
if wopwop
# PRECALCULATIONS
nc = size(vtk_cells, 1) # Number of cells
CPs = fill(0.0, 3, nc) # Control point of every cell
Ns = fill(0.0, 3, nc) # Normal of every cell
for k in 1:nc
p = [this_points[j+1] for j in vtk_cells[k]] # Points of cell
# NOTE: Here we assume that cells are quadrilaterals
# NOTE: Here the negative sign is necessary because it turns out
# `vtk_cells` are going clockwise
crss1 = -cross(p[2]-p[1], p[3]-p[1])
crss2 = -cross(p[4]-p[3], p[1]-p[3])
# # Area
# A1 = 0.5*norm(crss1) # Area of triangle 1
# A2 = 0.5*norm(crss2) # Area of triangle 2
# A = A1+A2 # Area quadrilateral
# # Normal
# N1 = crss1/(2*A1)
# N2 = crss2/(2*A2)
# N = (A1*N1 + A2*N2)/A
# Normal scaled by area
# NA = N*A
NA = crss1/2 + crss2/2
Ns[:, k] = NA
# Centroid (control point)
for pnt in p
CPs[:, k] .+= pnt
end
CPs[:, k] /= size(p, 1)
end
nHS = get_m(this_blade) # Number of horseshoes
Cs = fill(0.0, 3, nHS) # Midpoints of lifting line
NCs = fill(0.0, 3, nHS) # Ficticious normals to line
lift_points = [] # Lifting line points
lift_vtk_cells = [] # VTK lifting line
for k in 1:nHS
Ap, A, B, Bp, _, _, _, _ = getHorseshoe(this_blade, k)
Cs[:, k] = (A+B)/2
# Estimate the area of every triangle of the horseshoe extending the
# bound vortex to the leading edge
crss1 = cross((Ap-A)/(1-pn), B-A)
crss2 = cross(A-B, (Bp-B)/(1-pn))
NCs[:, k] = crss1/2 + crss2/2
# Unit vector normals
NCs[:, k] /= norm(NCs[:, k])
# Normals scaled by length
NCs[:, k] *= norm(B-A)
push!(lift_vtk_cells, (size(lift_points, 1), size(lift_points, 1)+1))
push!(lift_points, A)
# NOTE: Here I'm assuming the horseshoes are contiguous
if k==nHS
push!(lift_points, B)
end
end
# ----- Root and tip end caps ---------
points_root = [this_line_points[pi+1] for pi in vtk_lines[1]]
points_tip = [this_line_points[pi+1] for pi in vtk_lines[end]]
# Forces end caps to be even number of points
if size(points_root, 1)%2 != 0
points_root = points_root[1:end-1]
end
if size(points_tip, 1)%2 != 0
points_tip = points_tip[1:end-1]
end
npr = size(points_root, 1) # Number of points in root
npt = size(points_tip, 1) # Number of points in tip
ncr = Int(size(points_root, 1)/2)-1 # Number of cells in root
nct = Int(size(points_tip, 1)/2)-1 # Number of cells in tip
# 1-indexed cells
cells_root = [[ci, ci+1, (npr+1)-(ci+1), (npr+1)-ci] for ci in 1:ncr]
cells_tip = [[ci, ci+1, (npt+1)-(ci+1), (npt+1)-ci] for ci in 1:nct]
# Normals scaled by area
# NOTE: Direction of normal vs clockwise nodes?
Nroot = fill(0.0, 3, ncr)
for ci in 1:ncr
p1, p2, p3, p4 = (points_root[pi] for pi in cells_root[ci])
crss1 = cross(p2-p1, p3-p1)
crss2 = cross(p4-p3, p1-p3)
Nroot[:, ci] = crss1/2 + crss2/2
end
Ntip = fill(0.0, 3, nct)
for ci in 1:nct
p1, p2, p3, p4 = (points_tip[pi] for pi in cells_tip[ci])
crss1 = -cross(p2-p1, p3-p1)
crss2 = -cross(p4-p3, p1-p3)
Ntip[:, ci] = crss1/2 + crss2/2
end
# ------------------------------------------------------------------
# ----------------- LOFTED BLADE FOR THICKNESS ---------------------
# ------------------------------------------------------------------
# Create file
f = open(joinpath(path,
this_name*"."*(num!=nothing ? "$(num)." : "")*wopext), "w")
# Binary / ASCII printing
prnt(x) = wopbin ? write(f, x) : print(f, x)
prntln(x) = wopbin ? write(f, x) : print(f, x, "\n")
# Convertion to 4-bytes numbers
# NOTE: 4 bytes = 4*8 bites = 32 bites
fl(x) = Float32(x)
nt(x) = Int32(x)
# Convertion to n-bytes string
st(x::String, n) = x * " "^(n-length(x))
if wopv==0.0
# Patch declaration line
prntln("Patch"*" "^27)
# Number of zones
prntln(nt(1))
# ----------------- FIRST PATCH: LOFT ------------------------------
# imax jmax
imax = self.m-1 + 2*addtiproot
jmax = Int(nc/imax)
prnt(nt(imax))
prntln(nt(jmax))
# imax × jmax floating point x coordinates
# imax × jmax floating point y coordinates
# imax × jmax floating point z coordinates
for k in 1:3
for j in 1:nc
prntln(fl(CPs[k, j]))
end
end
# imax × jmax floating point normal vector x coordinates
# imax × jmax floating point normal vector y coordinates
# imax × jmax floating point normal vector z coordinates
for k in 1:3
for j in 1:nc
prntln(fl(Ns[k, j]))
end
end
elseif wopv==1.0
# Magic number
prntln(nt(42))
# Version number
prnt(nt(1))
prntln(nt(0))
# Units for Tecplot
prntln(st("N/m^2", 32))
# Comments
prntln(st("Geometry input file for PSU-WOPWOP (Format v1.0)\n"*
"------------------------------------------------\n"*
"Created by FLOWVLM (written by Eduardo Alvarez)\n"*
"https://github.com/byuflowlab/FLOWVLM\n"*
"Creation date: $(Dates.now())\n"*
"Units: SI\n"*
"Format: Unstructured grid, face-centered", 1024))
# Format string
prntln(nt(1)) # Geometry file flag
prntln(nt(3)) # Number of zones
prntln(nt(2)) # 1==structured, 2==unstructured
prntln(nt(1)) # Geometry 1==constant, 2==periodic, 3==aperiodic
prntln(nt(2)) # Normal vectors 1==node, 2==face
prntln(nt(1)) # Floating point 1==single, 2==double
prntln(nt(0)) # iblank values 1==included, 0==not
prntln(nt(0)) # WOPWOP secret conspiracy
# ----------------- FIRST PATCH: LOFT ------------------------------
# Name
prntln(st("loft", 32))
# nbNodes
prntln(nt( size(this_points, 1) ))
# nbFaces
prntln(nt( size(vtk_cells, 1) ))
# Connectivity
for cell in vtk_cells
prnt(nt( size(cell, 1) )) # Number of nodes in this cell
# for pi in reverse(cell) # Clockwise node ordering
for pi in cell # NOTE: Turns out that `vtk_cells` are already clockwise
prnt(nt( pi+1 )) # 1-indexed node index
end
if !wopbin; prntln(""); end;
end
# ----------------- SECOND PATCH: ROOT CAP -------------------------
# Name
prntln(st("root", 32))
# nbNodes
prntln(nt( size(points_root, 1) ))
# nbFaces
prntln(nt( size(cells_root, 1) ))
# Connectivity
for cell in cells_root
prnt(nt( size(cell, 1) )) # Number of nodes in this cell
for pi in reverse(cell) # NOTE: Clockwise node ordering
# for pi in cell
prnt(nt( pi )) # 1-indexed node index
end
if !wopbin; prntln(""); end;
end
# ----------------- THIRD PATCH: TIP CAP ---------------------------
# Name
prntln(st("tip", 32))
# nbNodes
prntln(nt( size(points_tip, 1) ))
# nbFaces
prntln(nt( size(cells_tip, 1) ))
# Connectivity
for cell in cells_tip
prnt(nt( size(cell, 1) )) # Number of nodes in this cell
# for pi in reverse(cell) # NOTE: Clockwise node ordering
for pi in cell
prnt(nt( pi )) # 1-indexed node index
end
if !wopbin; prntln(""); end;
end
# ----------------- DATA FIRST PATCH -------------------------------
# nbNodes floating point x coordinates
# nbNodes floating point y coordinates
# nbNodes floating point z coordinates
for k in 1:3
for p in this_points
prntln(fl(p[k]))
end
end
# nbFaces floating point normal vector x coordinates
# nbFaces floating point normal vector y coordinates
# nbFaces floating point normal vector z coordinates
for k in 1:3
for j in 1:size(vtk_cells, 1)
prntln(fl(Ns[k, j]))
end
end
# ----------------- DATA SECOND PATCH -------------------------------
# nbNodes floating point x coordinates
# nbNodes floating point y coordinates
# nbNodes floating point z coordinates
for k in 1:3
for p in points_root
prntln(fl(p[k]))
end
end
# nbFaces floating point normal vector x coordinates
# nbFaces floating point normal vector y coordinates
# nbFaces floating point normal vector z coordinates
for k in 1:3
for j in 1:size(cells_root, 1)
prntln(fl(Nroot[k, j]))
end
end
# ----------------- DATA THIRD PATCH -------------------------------
# nbNodes floating point x coordinates
# nbNodes floating point y coordinates
# nbNodes floating point z coordinates
for k in 1:3
for p in points_tip
prntln(fl(p[k]))
end
end
# nbFaces floating point normal vector x coordinates
# nbFaces floating point normal vector y coordinates
# nbFaces floating point normal vector z coordinates
for k in 1:3
for j in 1:size(cells_tip, 1)
prntln(fl(Ntip[k, j]))
end
end
else
error("Got invalid WOPWOP version $wopv")
end
close(f)
# ------------------------------------------------------------------
# ----------------- LIFTING-LINE COMPACT PATCH FOR LOADING ---------
# ------------------------------------------------------------------
# Create file
f = open(joinpath(path,
this_name*"_compact"*"."*(num!=nothing ? "$(num)." : "")*wopext), "w")
if wopv==0.0
# Patch declaration line
prntln("Patch"*" "^27)
# Number of zones
prntln(nt(1))
# ----------------- FIRST PATCH: LIFTING LINE ---------------------
# imax jmax
prnt(nt(nHS))
prntln(nt(1))
# imax × jmax floating point x coordinates
# imax × jmax floating point y coordinates
# imax × jmax floating point z coordinates
for k in 1:3
for j in 1:nHS
prntln(fl(Cs[k, j]))
end
end
# imax × jmax floating point normal vector x coordinates
# imax × jmax floating point normal vector y coordinates
# imax × jmax floating point normal vector z coordinates
for k in 1:3
for j in 1:nHS
prntln(fl(NCs[k, j]))
end
end