licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
1353
""" adv_time(se::AbstractCompactSourceElement, obs::AbstractAcousticObserver) Calculate the time an acoustic wave emmited by source `se` at time `se.Ο„` is recieved by observer `obs`. """ adv_time(se::AbstractCompactSourceElement, obs::AbstractAcousticObserver) function adv_time(se::AbstractCompactSourceElement, obs::StationaryAcousticObserver) Ο„ = source_time(se) rv = obs(Ο„) .- position(se) r = norm_cs_safe(rv) t = Ο„ + r/speed_of_sound(se) return t end function adv_time(se::AbstractCompactSourceElement, obs::ConstVelocityAcousticObserver) # Source time of the source element. Ο„ = source_time(se) # Ambient speed of sound of the source element. c0 = speed_of_sound(se) # Location of the observer at the source time. x = obs(Ο„) # Vector from the source to the observer at the source time. rv = x .- position(se) # Distance from the source to the observer at the source time. r = norm_cs_safe(rv) # Speed of the observer divided by speed of sound. Mo = norm_cs_safe(obs.v)/c0 # Unit vector pointing from the source to the observer. rhat = rv/r # Velocity of observer dotted with rhat at the source time. Mor = dot_cs_safe(obs.v, rhat)/c0 # Now get the observer time. t = Ο„ + r/c0*((Mor + sqrt(Mor^2 + 1 - Mo^2))/(1 - Mo^2)) return t end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
9761
abstract type AbstractBoundaryLayer end struct TrippedN0012BoundaryLayer{TAlphaStall} <: AbstractBoundaryLayer alphastar0::TAlphaStall end TrippedN0012BoundaryLayer() = TrippedN0012BoundaryLayer(12.5*pi/180) struct UntrippedN0012BoundaryLayer{TAlphaStall} <: AbstractBoundaryLayer alphastar0::TAlphaStall end UntrippedN0012BoundaryLayer() = UntrippedN0012BoundaryLayer(12.5*pi/180) struct ITrip1N0012BoundaryLayer{TAlphaStall} <: AbstractBoundaryLayer alphastar0::TAlphaStall end ITrip1N0012BoundaryLayer() = ITrip1N0012BoundaryLayer(12.5*pi/180) struct ITrip2N0012BoundaryLayer{TAlphaStall} <: AbstractBoundaryLayer alphastar0::TAlphaStall end ITrip2N0012BoundaryLayer() = ITrip2N0012BoundaryLayer(12.5*pi/180) struct ITrip3N0012BoundaryLayer{TAlphaStall} <: AbstractBoundaryLayer alphastar0::TAlphaStall end ITrip3N0012BoundaryLayer() = ITrip3N0012BoundaryLayer(12.5*pi/180) alpha_stall(bl::AbstractBoundaryLayer, Re_c) = bl.alphastar0 alpha_zerolift(bl::AbstractBoundaryLayer) = zero(bl.alphastar0) is_top_suction(bl::AbstractBoundaryLayer, alphastar) = alphastar >= alpha_zerolift(bl) function bl_thickness_0(::TrippedN0012BoundaryLayer, Re_c) # Equation 2 from the BPM report. logRe_c = log10(Re_c) return 10^(1.892 - 0.9045*logRe_c + 0.0596*logRe_c^2) end function disp_thickness_0(::Union{TrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer}, Re_c) # Equation 3 from the BPM report. if Re_c ≀ 0.3e6 return 0.0601*Re_c^(-0.114) else logRe_c = log10(Re_c) return 10^(3.411 - 1.5397*logRe_c + 0.1059*logRe_c^2) end end function disp_thickness_0(::ITrip2N0012BoundaryLayer, Re_c) # Equation 3 from the BPM report, multiplied by 0.6 as is done in the code listing in the BPM report appendix. if Re_c ≀ 0.3e6 return 0.6*0.0601*Re_c^(-0.114) else logRe_c = log10(Re_c) return 0.6*10^(3.411 - 1.5397*logRe_c + 0.1059*logRe_c^2) end end function bl_thickness_0(::Union{UntrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer,ITrip3N0012BoundaryLayer}, Re_c) # Equation 5 from the BPM report. logRe_c = log10(Re_c) return 10^(1.6569 - 0.9045*logRe_c + 0.0596*logRe_c^2) end function bl_thickness_0(::ITrip2N0012BoundaryLayer, Re_c) # Equation 5 from the BPM report, multiplied by 0.6 as is done in the code listing in the BPM report appendix. logRe_c = log10(Re_c) return 0.6*10^(1.6569 - 0.9045*logRe_c + 0.0596*logRe_c^2) end function disp_thickness_0(::Union{UntrippedN0012BoundaryLayer,ITrip3N0012BoundaryLayer}, Re_c) # Equation 6 from the BPM report. logRe_c = log10(Re_c) return 10^(3.0187 - 1.5397*logRe_c + 0.1059*logRe_c^2) end function _bl_thickness_p(::Union{TrippedN0012BoundaryLayer,UntrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer,ITrip2N0012BoundaryLayer,ITrip3N0012BoundaryLayer}, alphastar) # Equation 8 from the BPM report. alphastar_deg = alphastar*180/pi return 10^(-0.04175*alphastar_deg + 0.00106*alphastar_deg^2) end function _disp_thickness_p(::Union{TrippedN0012BoundaryLayer,UntrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer,ITrip2N0012BoundaryLayer}, alphastar) # Equation 9 from the BPM report. alphastar_deg = alphastar*180/pi return 10^(-0.0432*alphastar_deg + 0.00113*alphastar_deg^2) end function _disp_thickness_p(::ITrip3N0012BoundaryLayer, alphastar) # Equation 9 from the BPM report, multiplied by 1.48 as is done in the BPM report appendix. alphastar_deg = alphastar*180/pi return 1.48*10^(-0.0432*alphastar_deg + 0.00113*alphastar_deg^2) end function _bl_thickness_s(::TrippedN0012BoundaryLayer, alphastar) T = typeof(alphastar) # Equation 11 from the BPM report. # The report defines the suction-side boundary layer parameters for alphastar values from 0Β° to 25Β°. # But what about negative angles of attack? # The NACA0012 airfoil is symmetric, but if the angle of attack goes negative, I guess the pressure and suction sides would switch. # So I'll check that the angle of attack is always positive here. alphastar_deg = alphastar*180/pi if alphastar_deg < 0 return T(NaN) elseif alphastar_deg ≀ 5 return 10^(0.0311*alphastar_deg) elseif alphastar_deg ≀ 12.5 return 0.3468*10^(0.1231*alphastar_deg) elseif alphastar_deg ≀ 25 return 5.718*10^(0.0258*alphastar_deg) else # What should I do for angles of attack greater than 25Β°? # Maybe just keep the same thickness? return 5.718*10^(0.0258*25*pi/180)*one(T) end end function _disp_thickness_s(::Union{TrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer}, alphastar) T = typeof(alphastar) # Equation 12 from the BPM report. alphastar_deg = alphastar*180/pi if alphastar_deg < 0 # throw(DomainError(alphastar, "negative alphastar argument invalid")) return T(NaN) elseif alphastar_deg ≀ 5 return 10^(0.0679*alphastar_deg) elseif alphastar_deg ≀ 12.5 return 0.381*10^(0.1516*alphastar_deg) elseif alphastar_deg ≀ 25 return 14.296*10^(0.0258*alphastar_deg) else # What should I do for angles of attack greater than 25Β°? # Maybe just keep the same thickness? return 14.296*10^(0.0258*25)*one(T) end end function _bl_thickness_s(::Union{UntrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer,ITrip2N0012BoundaryLayer,ITrip3N0012BoundaryLayer}, alphastar) T = typeof(alphastar) # Equation 14 from the BPM report. alphastar_deg = alphastar*180/pi if alphastar_deg < 0 # throw(DomainError(alphastar, "negative alphastar argument invalid")) return T(NaN) elseif alphastar_deg ≀ 7.5 return 10^(0.03114*alphastar_deg) elseif alphastar_deg ≀ 12.5 return 0.0303*10^(0.2336*alphastar_deg) elseif alphastar_deg ≀ 25 return 12*10^(0.0258*alphastar_deg) else # What should I do for angles of attack greater than 25Β°? # Maybe just keep the same thickness? return 12*10^(0.0258*25*pi/180)*one(T) end end function _disp_thickness_s(::Union{UntrippedN0012BoundaryLayer,ITrip2N0012BoundaryLayer,ITrip3N0012BoundaryLayer}, alphastar) T = typeof(alphastar) # Equation 15 from the BPM report. alphastar_deg = alphastar*180/pi if alphastar_deg < 0 # throw(DomainError(alphastar, "negative alphastar argument invalid")) return T(NaN) elseif alphastar_deg ≀ 7.5 return 10^(0.0679*alphastar_deg) elseif alphastar_deg ≀ 12.5 return 0.0162*10^(0.3066*alphastar_deg) elseif alphastar_deg ≀ 25 return 52.42*10^(0.0258*alphastar_deg) else # What should I do for angles of attack greater than 25Β°? # Maybe just keep the same thickness? return 52.42*10^(0.0258*25)*one(T) end end function _disp_thickness_top(bl::Union{TrippedN0012BoundaryLayer,UntrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer,ITrip2N0012BoundaryLayer,ITrip3N0012BoundaryLayer}, alphastar) # Switch sign on alphastar and call the "opposite" `disp_thickness_*` routine if the top surface isn't the suction surface. return ifelse(is_top_suction(bl, alphastar), _disp_thickness_s(bl, alphastar), _disp_thickness_p(bl, -alphastar)) end function _disp_thickness_bot(bl::Union{TrippedN0012BoundaryLayer,UntrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer,ITrip2N0012BoundaryLayer,ITrip3N0012BoundaryLayer}, alphastar) return ifelse(is_top_suction(bl, alphastar), _disp_thickness_p(bl, alphastar), _disp_thickness_s(bl, -alphastar)) end function _bl_thickness_top(bl::Union{TrippedN0012BoundaryLayer,UntrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer,ITrip2N0012BoundaryLayer,ITrip3N0012BoundaryLayer}, alphastar) # Switch sign on alphastar and call the "opposite" `disp_thickness_*` routine if the top surface isn't the suction surface. return ifelse(is_top_suction(bl, alphastar), _bl_thickness_s(bl, alphastar), _bl_thickness_p(bl, -alphastar)) end function _bl_thickness_bot(bl::Union{TrippedN0012BoundaryLayer,UntrippedN0012BoundaryLayer,ITrip1N0012BoundaryLayer,ITrip2N0012BoundaryLayer,ITrip3N0012BoundaryLayer}, alphastar) return ifelse(is_top_suction(bl, alphastar), _bl_thickness_p(bl, alphastar), _bl_thickness_s(bl, -alphastar)) end function disp_thickness_bot(bl::AbstractBoundaryLayer, Re_c, alphastar) # (Ξ΄^*_p/Ξ΄^*_0)*(Ξ΄^*_0/c) return _disp_thickness_bot(bl, alphastar)*disp_thickness_0(bl, Re_c) end function disp_thickness_top(bl::AbstractBoundaryLayer, Re_c, alphastar) return _disp_thickness_top(bl, alphastar)*disp_thickness_0(bl, Re_c) end function disp_thickness_s(bl::AbstractBoundaryLayer, Re_c, alphastar) return ifelse(is_top_suction(bl, alphastar), disp_thickness_top(bl, Re_c, alphastar), disp_thickness_bot(bl, Re_c, alphastar)) end function disp_thickness_p(bl::AbstractBoundaryLayer, Re_c, alphastar) return ifelse(is_top_suction(bl, alphastar), disp_thickness_bot(bl, Re_c, alphastar), disp_thickness_top(bl, Re_c, alphastar)) end function bl_thickness_bot(bl::AbstractBoundaryLayer, Re_c, alphastar) # (Ξ΄_p/Ξ΄_0)*(Ξ΄_0/c) return _bl_thickness_bot(bl, alphastar)*bl_thickness_0(bl, Re_c) end function bl_thickness_top(bl::AbstractBoundaryLayer, Re_c, alphastar) return _bl_thickness_top(bl, alphastar)*bl_thickness_0(bl, Re_c) end function bl_thickness_s(bl::AbstractBoundaryLayer, Re_c, alphastar) return ifelse(is_top_suction(bl, alphastar), bl_thickness_top(bl, Re_c, alphastar), bl_thickness_bot(bl, Re_c, alphastar)) end function bl_thickness_p(bl::AbstractBoundaryLayer, Re_c, alphastar) return ifelse(is_top_suction(bl, alphastar), bl_thickness_bot(bl, Re_c, alphastar), bl_thickness_top(bl, Re_c, alphastar)) end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
16844
function calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_lblvs=false, do_tip_vortex=false, blade_tip=nothing, do_tebvs=false, h=nothing, Psi=nothing, use_Ualpha=false) if do_tebvs if do_tip_vortex combined_calc = :with_tip else combined_calc = :no_tip end else combined_calc = :none end M_c = 0.8*M # How we're going to set this up: # # * Source starts at the origin, moving in the -x direction with velocity U. # c0 = U/M # Hmm... how about the location stuff? # I want the source element at the origin, so I guess that's r = 0, and ΞΈ doesn't matter. r = 0.0 ΞΈ = 0.0 # Hmm... what about the twist? # I want the chord line to be at an angle `alphastar` with the negative-x axis. # But how does it work "by default"? # Let's look at the doc strings. # OK, so, if `twist_about_positive_y` is true, then initially the unit vector pointing from leading edge to trailing edge will be pointed in the negative z direction, then rotated about the positive y axis by an amount Ο†. # I want the blade to be aligned with the x axis, with the chord unit vector in the positive x axis direction. twist_about_positive_y = true # So then I think I want to rotate it by this much: Ο• = 3*pi/2 + alphastar # Ο• = 3*pi/2 # OK, so now, how about the velocities? # Well, we're starting out in the blade fixed-frame, so the velocity should include everything, including induction. # So, from the perspective of the source element, the total velocity is `M_c*c0` in the positive x direction. # No velocity in the other directions. vn = M_c*c0 vr = 0.0 vc = 0.0 # Ah, now I've decided that's not right. # I want the chord line to be aligned with the x axis, so I'll need to rotate the velocity to take into account the angle of attack. # So that means the normal velocity would be # vn = M_c*c0*cos(alphastar) # vr = 0.0 # vc = M_c*c0*sin(alphastar) # We're starting at Ο„ = 0, and the time step doesn't matter yet. Ο„ = 0.0 Δτ = 1.0 if use_Ualpha se_tblte = AcousticAnalogies.TBLTESourceElement{AcousticAnalogies.BPMDirectivity,false,AcousticAnalogies.NoMachCorrection,true}(c0, nu, r, ΞΈ, L, chord, Ο•, M_c*c0, alphastar, Ο„, Δτ, bl, twist_about_positive_y) if do_lblvs se_lblvs = AcousticAnalogies.LBLVSSourceElement{AcousticAnalogies.BPMDirectivity,false,true}(c0, nu, r, ΞΈ, L, chord, Ο•, M_c*c0, alphastar, Ο„, Δτ, bl, twist_about_positive_y) end if do_tip_vortex se_tip = AcousticAnalogies.TipVortexSourceElement{AcousticAnalogies.BPMDirectivity,false,true}(c0, r, ΞΈ, L, chord, Ο•, M_c*c0, alphastar, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) end if do_tebvs se_tebvs = AcousticAnalogies.TEBVSSourceElement{AcousticAnalogies.BPMDirectivity,false,true}(c0, nu, r, ΞΈ, L, chord, Ο•, h, Psi, M_c*c0, alphastar, Ο„, Δτ, bl, twist_about_positive_y) end if combined_calc == :no_tip se_combined = AcousticAnalogies.CombinedNoTipBroadbandSourceElement{AcousticAnalogies.BPMDirectivity,false,AcousticAnalogies.NoMachCorrection,true}(c0, nu, r, ΞΈ, L, chord, Ο•, h, Psi, M_c*c0, alphastar, Ο„, Δτ, bl, twist_about_positive_y) elseif combined_calc == :with_tip se_combined = AcousticAnalogies.CombinedWithTipBroadbandSourceElement{AcousticAnalogies.BPMDirectivity,false,AcousticAnalogies.NoMachCorrection,true}(c0, nu, r, ΞΈ, L, chord, Ο•, h, Psi, M_c*c0, alphastar, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) end else se_tblte = AcousticAnalogies.TBLTESourceElement{AcousticAnalogies.BPMDirectivity,false,AcousticAnalogies.NoMachCorrection,true}(c0, nu, r, ΞΈ, L, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) if do_lblvs se_lblvs = AcousticAnalogies.LBLVSSourceElement{AcousticAnalogies.BPMDirectivity,false,true}(c0, nu, r, ΞΈ, L, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) end if do_tip_vortex se_tip = AcousticAnalogies.TipVortexSourceElement{AcousticAnalogies.BPMDirectivity,false,true}(c0, r, ΞΈ, L, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) end if do_tebvs se_tebvs = AcousticAnalogies.TEBVSSourceElement{AcousticAnalogies.BPMDirectivity,false,true}(c0, nu, r, ΞΈ, L, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) end if combined_calc == :no_tip se_combined = AcousticAnalogies.CombinedNoTipBroadbandSourceElement{AcousticAnalogies.BPMDirectivity,false,AcousticAnalogies.NoMachCorrection,true}(c0, nu, r, ΞΈ, L, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) elseif combined_calc == :with_tip se_combined = AcousticAnalogies.CombinedWithTipBroadbandSourceElement{AcousticAnalogies.BPMDirectivity,false,AcousticAnalogies.NoMachCorrection,true}(c0, nu, r, ΞΈ, L, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) end end # Let's check that things are what we expect. @assert se_tblte.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_tblte.y1dot β‰ˆ [0.0, 0.0, 0.0] @assert se_tblte.y1dot_fluid β‰ˆ [M_c*c0, 0.0, 0.0] # @assert se_tblte.y1dot_fluid β‰ˆ [M_c*c0*cos(alphastar), 0.0, M_c*c0*sin(alphastar)] @assert se_tblte.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_tblte.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_tblte.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_tblte), alphastar; atol=1e-12) if do_lblvs # Let's check that things are what we expect. @assert se_lblvs.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_lblvs.y1dot β‰ˆ [0.0, 0.0, 0.0] @assert se_lblvs.y1dot_fluid β‰ˆ [M_c*c0, 0.0, 0.0] # @assert se_lblvs.y1dot_fluid β‰ˆ [M_c*c0*cos(alphastar), 0.0, M_c*c0*sin(alphastar)] @assert se_lblvs.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_lblvs.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_lblvs.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_lblvs), alphastar; atol=1e-12) end if do_tip_vortex # Let's check that things are what we expect. @assert se_tip.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_tip.y1dot β‰ˆ [0.0, 0.0, 0.0] @assert se_tip.y1dot_fluid β‰ˆ [M_c*c0, 0.0, 0.0] # @assert se_tip.y1dot_fluid β‰ˆ [M_c*c0*cos(alphastar), 0.0, M_c*c0*sin(alphastar)] @assert se_tip.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_tip.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_tip.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_tip), alphastar; atol=1e-12) end if do_tebvs # Let's check that things are what we expect. @assert se_tebvs.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_tebvs.y1dot β‰ˆ [0.0, 0.0, 0.0] @assert se_tebvs.y1dot_fluid β‰ˆ [M_c*c0, 0.0, 0.0] # @assert se_tebvs.y1dot_fluid β‰ˆ [M_c*c0*cos(alphastar), 0.0, M_c*c0*sin(alphastar)] @assert se_tebvs.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_tebvs.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_tebvs.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_tebvs), alphastar; atol=1e-12) end if combined_calc != :none # Let's check that things are what we expect. @assert se_combined.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_combined.y1dot β‰ˆ [0.0, 0.0, 0.0] @assert se_combined.y1dot_fluid β‰ˆ [M_c*c0, 0.0, 0.0] # @assert se_combined.y1dot_fluid β‰ˆ [M_c*c0*cos(alphastar), 0.0, M_c*c0*sin(alphastar)] @assert se_combined.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_combined.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_combined.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_combined), alphastar; atol=1e-12) end # Now we want to transform the source element into the global frame, which just means we make it move with speed `U` in the negative x direction. trans = ConstantVelocityTransformation(Ο„, [0.0, 0.0, 0.0], [-U, 0.0, 0.0]) # No, that's not right, I want it to move in the direction of the velocity, which isn't aligned with the x axis any more. # trans = ConstantVelocityTransformation(Ο„, [0.0, 0.0, 0.0], [-U*cos(alphastar), 0.0, -U*sin(alphastar)]) se_tblte_global = trans(se_tblte) if do_lblvs se_lblvs_global = trans(se_lblvs) end if do_tip_vortex se_tip_global = trans(se_tip) end if do_tebvs se_tebvs_global = trans(se_tebvs) end if combined_calc != :none se_combined_global = trans(se_combined) end # Will that change the angle of attack? # Originally the total velocity was `Vtotal = se_tblte.y1dot_fluid - se_tblte.y1dot = [M_c*c0, 0, 0]`, and now it will be `[M_c*c0 - U, 0, 0] - [-U, 0, 0] = [M_c*c0, 0, 0]`. # So nope, which is good. :-) # Oh, and I'm only changing the magnitude of the velocity, not the direction. @assert se_tblte_global.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_tblte_global.y1dot β‰ˆ [-U, 0.0, 0.0] # @assert se_tblte_global.y1dot β‰ˆ [-U*cos(alphastar), 0.0, -U*sin(alphastar)] @assert se_tblte_global.y1dot_fluid β‰ˆ [M_c*c0 - U, 0.0, 0.0] # @assert se_tblte_global.y1dot_fluid β‰ˆ [(M_c*c0 - U)*cos(alphastar), 0.0, (M_c*c0 - U)*sin(alphastar)] @assert se_tblte_global.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_tblte_global.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_tblte_global.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_tblte_global), alphastar; atol=1e-12) if do_lblvs @assert se_lblvs_global.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_lblvs_global.y1dot β‰ˆ [-U, 0.0, 0.0] # @assert se_lblvs_global.y1dot β‰ˆ [-U*cos(alphastar), 0.0, -U*sin(alphastar)] @assert se_lblvs_global.y1dot_fluid β‰ˆ [M_c*c0 - U, 0.0, 0.0] # @assert se_lblvs_global.y1dot_fluid β‰ˆ [(M_c*c0 - U)*cos(alphastar), 0.0, (M_c*c0 - U)*sin(alphastar)] @assert se_lblvs_global.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_lblvs_global.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_lblvs_global.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_lblvs_global), alphastar; atol=1e-12) end if do_tip_vortex @assert se_tip_global.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_tip_global.y1dot β‰ˆ [-U, 0.0, 0.0] # @assert se_tip_global.y1dot β‰ˆ [-U*cos(alphastar), 0.0, -U*sin(alphastar)] @assert se_tip_global.y1dot_fluid β‰ˆ [M_c*c0 - U, 0.0, 0.0] # @assert se_tip_global.y1dot_fluid β‰ˆ [(M_c*c0 - U)*cos(alphastar), 0.0, (M_c*c0 - U)*sin(alphastar)] @assert se_tip_global.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_tip_global.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_tip_global.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_tip_global), alphastar; atol=1e-12) end if do_tebvs @assert se_tebvs_global.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_tebvs_global.y1dot β‰ˆ [-U, 0.0, 0.0] # @assert se_tebvs_global.y1dot β‰ˆ [-U*cos(alphastar), 0.0, -U*sin(alphastar)] @assert se_tebvs_global.y1dot_fluid β‰ˆ [M_c*c0 - U, 0.0, 0.0] # @assert se_tebvs_global.y1dot_fluid β‰ˆ [(M_c*c0 - U)*cos(alphastar), 0.0, (M_c*c0 - U)*sin(alphastar)] @assert se_tebvs_global.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_tebvs_global.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_tebvs_global.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_tebvs_global), alphastar; atol=1e-12) end if combined_calc != :none @assert se_combined_global.y0dot β‰ˆ [0.0, 0.0, 0.0] @assert se_combined_global.y1dot β‰ˆ [-U, 0.0, 0.0] # @assert se_combined_global.y1dot β‰ˆ [-U*cos(alphastar), 0.0, -U*sin(alphastar)] @assert se_combined_global.y1dot_fluid β‰ˆ [M_c*c0 - U, 0.0, 0.0] # @assert se_combined_global.y1dot_fluid β‰ˆ [(M_c*c0 - U)*cos(alphastar), 0.0, (M_c*c0 - U)*sin(alphastar)] @assert se_combined_global.span_uvec β‰ˆ [0.0, 1.0, 0.0] @assert se_combined_global.chord_uvec β‰ˆ [cos(alphastar), 0.0, -sin(alphastar)] # @assert se_combined_global.chord_uvec β‰ˆ [1.0, 0.0, 0.0] @assert isapprox(AcousticAnalogies.angle_of_attack(se_combined_global), alphastar; atol=1e-12) end # If the angle of attack is negative, then the pressure and suction sides of the airfoil section switch, and so the coordinate system does too. if (alphastar - AcousticAnalogies.alpha_zerolift(bl)) < 0 Ξ¦_e *= -1 end # What about the observer? # That's the tricky part. # We know the final position of the observer is this. x_obs_final = [r_e*cos(ΞΈ_e), r_e*sin(ΞΈ_e)*cos(Ξ¦_e), r_e*sin(ΞΈ_e)*sin(Ξ¦_e)] # This polar coordinate system is actually defined from the perspective of the fluid velocity, not the source element chord direction. # So need to take into acount that. # x_obs_final = [r_e*cos(ΞΈ_e)*cos(alphastar), r_e*sin(ΞΈ_e)*cos(Ξ¦_e), r_e*sin(ΞΈ_e)*sin(Ξ¦_e)*sin(alphastar)] # And we can use the distance from the initial position of the source to the final position of the observer to get the distance the acoustic wave travels, and then the final time. t_final = Ο„ + norm(x_obs_final - se_tblte_global.y0dot)/c0 # And then we can use that to get the initial position of the observer, which is moving with the same velocity as the source. x_obs_initial = x_obs_final - se_tblte_global.y1dot*(t_final - Ο„) # So now I should be able to create the observer object thingy. obs = AcousticAnalogies.ConstVelocityAcousticObserver(Ο„, x_obs_initial, se_tblte_global.y1dot) # And now I should check if I get the expected final time. @assert AcousticAnalogies.adv_time(se_tblte_global, obs) β‰ˆ t_final if do_lblvs @assert AcousticAnalogies.adv_time(se_lblvs_global, obs) β‰ˆ t_final end if do_tip_vortex @assert AcousticAnalogies.adv_time(se_tip_global, obs) β‰ˆ t_final end if do_tebvs @assert AcousticAnalogies.adv_time(se_tebvs_global, obs) β‰ˆ t_final end if combined_calc != :none @assert AcousticAnalogies.adv_time(se_combined_global, obs) β‰ˆ t_final end # So now I should be able to do a noise prediction. freqs = AcousticMetrics.ExactThirdOctaveCenterBands(0.2, 20e3) tblte_out = AcousticAnalogies.noise(se_tblte_global, obs, freqs) tblte_s_out = AcousticAnalogies.pbs_suction(tblte_out) tblte_p_out = AcousticAnalogies.pbs_pressure(tblte_out) tblte_alpha_out = AcousticAnalogies.pbs_alpha(tblte_out) SPL_s_jl = 10.0 .* log10.(tblte_s_out./((20e-6)^2)) SPL_p_jl = 10.0 .* log10.(tblte_p_out./((20e-6)^2)) SPL_alpha_jl = 10.0 .* log10.(tblte_alpha_out./((20e-6)^2)) if do_lblvs lblvs_out = AcousticAnalogies.noise(se_lblvs_global, obs, freqs) SPL_lbl_vs = 10.0 .* log10.(lblvs_out./((20e-6)^2)) end if do_tip_vortex tip_out = AcousticAnalogies.noise(se_tip_global, obs, freqs) SPL_tip = 10.0 .* log10.(tip_out./((20e-6)^2)) end if do_tebvs tebvs_out = AcousticAnalogies.noise(se_tebvs_global, obs, freqs) SPL_teb = 10.0 .* log10.(tebvs_out./((20e-6)^2)) end if combined_calc != :none combined_out = AcousticAnalogies.noise(se_combined_global, obs, freqs) end @assert AcousticAnalogies.doppler(tblte_out) β‰ˆ 1 if do_lblvs @assert AcousticAnalogies.doppler(lblvs_out) β‰ˆ 1 end if do_tip_vortex @assert AcousticAnalogies.doppler(tip_out) β‰ˆ 1 end if do_tebvs @assert AcousticAnalogies.doppler(tebvs_out) β‰ˆ 1 end if combined_calc != :none @assert AcousticAnalogies.doppler(combined_out) β‰ˆ 1 end if combined_calc in (:no_tip, :with_tip) @assert all(pbs_suction(combined_out) .β‰ˆ tblte_s_out) @assert all(pbs_pressure(combined_out) .β‰ˆ tblte_p_out) @assert all(pbs_alpha(combined_out) .β‰ˆ tblte_alpha_out) @assert all(pbs_teb(combined_out) .β‰ˆ tebvs_out) end if combined_calc in (:with_tip,) @assert all(pbs_tip(combined_out) .β‰ˆ tip_out) end res = (freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl) if do_lblvs res = (res..., SPL_lbl_vs) end if do_tip_vortex res = (res..., SPL_tip) end if do_tebvs res = (res..., SPL_teb) end return res end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
55426
import FillArrays: getindex_value # Normal implementation is this from FillArrays.jl: # # @inline getindex_value(F::Fill) = F.value # # But that breaks with CCBlade. # Why? # Because, since a FillArrays.Fill <: AbstractArray, it calls this: # # function Base.getproperty(obj::AbstractVector{<:Section}, sym::Symbol) # return getfield.(obj, sym) # end # # which eventually calls FillArrays.getindex_value again, leading to recursion and a stack overflow. # # This is type piracy :-(. # But it may also be type piracy to extend Base.getproperty in CCBlade.jl, since CCBlade.jl doesn't own Base.getproperty or AbstractVector. @inline getindex_value(F::Fill{<:Union{CCBlade.Section,CCBlade.OperatingPoint,CCBlade.Outputs}}) = getfield(F, :value) # Normal implementation is this from FillArrays.jl: # # @inline axes(F::Fill) = F.axes # # But that hits # # function Base.getproperty(obj::AbstractVector{<:Section}, sym::Symbol) # return getfield.(obj, sym) # end # # from CCBlade. # This is type piracy :-(. # But it may also be type piracy to extend Base.getproperty in CCBlade.jl, since CCBlade.jl doesn't own Base.getproperty or AbstractVector. @inline Base.axes(F::Fill{<:Union{CCBlade.Section,CCBlade.OperatingPoint,CCBlade.Outputs}}) = getfield(F, :axes) function _standard_ccblade_transform(rotor::CCBlade.Rotor, sections::AbstractVector{<:CCBlade.Section}, ops::AbstractVector{<:CCBlade.OperatingPoint}, period, num_src_times, positive_x_rotation) # Assume the rotor is traveling in the positive x direction, with the first # blade aligned with the positive y axis. Rotor hub is initially at the origin. rot_axis = @SVector [1.0, 0.0, 0.0] blade_axis = @SVector [0.0, 1.0, 0.0] y0_hub = @SVector [0.0, 0.0, 0.0] # m t0 = 0.0 # Get the time of each time step. dt = period/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # Get transformations for each blade element. cos_precone = cos(rotor.precone) # r = SingleFieldStructArray(sections, Val{:r}) # Vx = SingleFieldStructArray(ops, Val{:Vx}) # Vy = SingleFieldStructArray(ops, Val{:Vy}) r = mapview(:r, sections) Vx = mapview(:Vx, ops) Vy = mapview(:Vy, ops) if positive_x_rotation rot_trans = SteadyRotXTransformation.(t0, Vy./(r.*cos_precone), 0.0) # size (num_radial,) else rot_trans = SteadyRotXTransformation.(t0, -Vy./(r.*cos_precone), 0.0) # size (num_radial,) end const_vel_trans = ConstantVelocityTransformation.(t0, Ref(y0_hub), Ref(rot_axis).*Vx./cos_precone) # size (num_radial,) # Reshape things to get broadcasting to work. rot_trans_rs = reshape(rot_trans, 1, :) const_vel_trans_rs = reshape(const_vel_trans, 1, :) # Now get all the transformations. trans = compose.(src_times, const_vel_trans_rs, rot_trans_rs) # size (num_times, num_radial) return src_times, dt, trans end """ CompactF1ASourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, area_per_chord2, Ο„, positive_x_rotation=true) Construct a source element to be used with the compact form of Farassat's formulation 1A from CCBlade objects. The source element's position is calculated from `section.r`, `rotor.precone`, and the `ΞΈ` argument using ```julia sΞΈ, cΞΈ = sincos(ΞΈ) spc, cpc = sincos(precone) y0dot = [r*spc, r*cpc*cΞΈ, r*cpc*sΞΈ] ``` where `y0dot` is the position of the source element. # Arguments - `rotor::CCBlade.Rotor`: CCBlade rotor object, needed for the precone angle.precone. - `section::CCBlade.Section`: CCBlade section object, needed for the radial location and chord length of the element. - `op::CCBlade.OperatingPoint`: CCBlade operating point, needed for atmospheric properties. - `out::CCBlade.Outputs`: CCBlade outputs object, needed for the loading. - `ΞΈ`: polar coordinate of the element, in radians. - `Ξ”r`: length of the element. - `area_per_chord2`: cross-sectional area divided by the chord squared of the element. - `Ο„`: source time of the element. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function CompactF1ASourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, area_per_chord2, Ο„, positive_x_rotation) ρ0 = op.rho c0 = op.asound r = section.r precone = rotor.precone Np = out.Np Tp = out.Tp Ξ› = area_per_chord2*section.chord^2 # Thinking about the geometry here: # y^ . . # | . . # | . . # | . . # |Ο†. . # |.--------->x . sΞΈ, cΞΈ = sincos(ΞΈ) spc, cpc = sincos(precone) y0dot = @SVector [r*spc, r*cpc*cΞΈ, r*cpc*sΞΈ] T = eltype(y0dot) y1dot = @SVector zeros(T, 3) y2dot = @SVector zeros(T, 3) y3dot = @SVector zeros(T, 3) # The sign convention is a little tricky. We want the load on the fluid in # the blade coordinate system, which is a coordinate system that is rotating # and translating with blades, and assumes that the axis of rotation is at # the origin, aligned with the positive x axis. A positive rotation is # righthanded (so, say, if the blade is aligned with the y axis and rotating # with a positive rate, it is rotating toward the z axis) For the normal # loading, CCBlade gives a positive value when the load *on the blade* is in # the same direction as the axis of rotation (or opposite the freestream # velocity in the normal case). But we need the loading *on the fluid*, # which is in the opposite direction, hence we need to switch the sign on # Np. # For the circumferential loading, CCBlade gives a positive value when it # opposes the motion of the blade. So, in our hypothetical coordinate # system, let's say the blade is pointed along the y axis and rotating with # a positive rate. Then the blade is moving toward the positive z axis, and # since the circumferential loading opposes the blade motion, the load on # the blade would be pointed in the negative z direction. So that means the # load on the fluid would be in the positive z direction, and we don't need # to switch the sign. # So after all that, the takeaway is that we'll start out with a loading # vector [-Np, 0, Tp], then rotate it about the positive z-axis by an amount # `-precone`, then rotate it about the x axis by an amount `ΞΈ`. # But, what if I decide the blade is rotating around the negative x-axis? # The normal loading will still be in the same direction. # The precone and theta stuff can still work the same way. # I think the only thing that would switch is the circumferential loading. fn = -Np*cpc fr = Np*spc if positive_x_rotation fc = Tp else fc = -Tp end f0dot = @SVector [fn, cΞΈ*fr - sΞΈ*fc, sΞΈ*fr + cΞΈ*fc] T = eltype(f0dot) f1dot = @SVector zeros(T, 3) u = @SVector [spc, cpc*cΞΈ, cpc*sΞΈ] return CompactF1ASourceElement(ρ0, c0, Ξ”r, Ξ›, y0dot, y1dot, y2dot, y3dot, f0dot, f1dot, Ο„, u) end """ f1a_source_elements_ccblade(rotor::CCBlade.Rotor, sections::Vector{CCBlade.Section}, ops::Vector{CCBlade.OperatingPoint}, outputs::Vector{CCBlade.Outputs}, area_per_chord2::Vector{AbstractFloat}, period, num_src_times, positive_x_rotation) Construct and return an array of CompactF1ASourceElement objects from CCBlade structs. # Arguments - `rotor`: CCBlade rotor object. - `sections`: `Vector` of CCBlade section object. - `ops`: `Vector` of CCBlade operating point. - `outputs`::`Vector` of CCBlade output objects. - `area_per_chord2`: cross-sectional area divided by the chord squared of the element at each CCBlade.section. Should be a Vector{AbstractFloat}, same length as `sections`, `ops`, `outputs`. - `period`: length of the source time over which the returned source elements will evaluated. - `num_src_times`: number of source times. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function f1a_source_elements_ccblade(rotor, sections, ops, outputs, area_per_chord2, period, num_src_times, positive_x_rotation) # Need to know the radial spacing. (CCBlade doesn't use thisβ€”when # integrating stuff [loading to get torque and thrust] it uses the # trapezoidal rule and passes in the radial locations, and assumes that # integrands go to zero at the hub and tip.) Kind of lame that I have to # calcluate it here, but whatever. Maybe I should use StaticArrays for this? # Ah, no, I don't know the length at compile time. dradii = get_ccblade_dradii(rotor, sections) # Get the transformation that will put the source elements in the "standard" CCBlade.jl reference frame (moving axially in the positive x axis direction, rotating about the positive x axis or negative x axis, first blade initially aligned with the positive y axis). src_times, dt, trans = _standard_ccblade_transform(rotor, sections, ops, period, num_src_times, positive_x_rotation) # This is just an array of the angular offsets of each blade. First blade is # aligned with the y axis, next one is offset 2*pi/B radians, etc.. num_blades = rotor.B ΞΈs = 2*pi/num_blades.*(0:(num_blades-1)) .* ifelse(positive_x_rotation, 1, -1) # Reshape for broadcasting. Goal is to make everything work for a size of (num_times, # num_radial, num_blades). # trans_rs = reshape(trans, size(trans)..., 1) ΞΈs_rs = reshape(ΞΈs, 1, 1, :) sections_rs = reshape(sections, 1, :, 1) ops_rs = reshape(ops, 1, :, 1) outputs_rs = reshape(outputs, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) area_per_chord2_rs = reshape(area_per_chord2, 1, :, 1) # src_times = reshape(src_times, :, 1, 1) # This one isn't necessary. # Construct and transform the source elements. ses = CompactF1ASourceElement.(Ref(rotor), sections_rs, ops_rs, outputs_rs, ΞΈs_rs, dradii_rs, area_per_chord2_rs, src_times, positive_x_rotation) .|> trans return ses end function _get_position_velocity_span_uvec_chord_uvec(theta, precone, pitch, r, ΞΈ, W, phi, positive_x_rotation) sΞΈ, cΞΈ = sincos(ΞΈ) spc, cpc = sincos(precone) stwist, ctwist = sincos(theta + pitch) # The way this will work: # # * We're going to assume that the rotor blade is moving axially in the positive x direction, and rotating about the x axis. # * The "first" blade is initially aligned with the positive y axis. # * Then we'll rotate the element about the positive z-axis by an amount `-precone` to acount for the precone. # * Then we'll rotate the element about the positive x-axis by an amount `ΞΈ`. # # Those transformations will be applied to the blade element position, but also other vectors associated with the element. # In matrix form the precone transformation would be # # [ cos(-precone), -sin(-precone), 0 ] # [ sin(-precone), cos(-precone), 0 ] # [ 0, 0, 1 ] # # or equivalently # # [ cos(precone), sin(precone), 0 ] # [-sin(precone), cos(precone), 0 ] # [ 0, 0, 1 ] # # And the ΞΈ rotation about the x axis would be # # [ 1, 0 , 0 ] # [ 0, cos(ΞΈ), -sin(ΞΈ) ] # [ 0, sin(ΞΈ), cos(ΞΈ) ] # # So, to get the position, we start out with a vector # # [0] # [r] # [0] # # And then multiply that by the precone rotation matrix and ΞΈ rotation matrix. # # [ cos(precone), sin(precone), 0 ] [0] [ r*sin(precone) ] # [-sin(precone), cos(precone), 0 ] [r] = [ r*cos(precone) ] # [ 0, 0, 1 ] [0] [ 0 ] # # [ 1, 0 , 0 ] [ r*sin(precone) ] [ r*sin(precone) ] # [ 0, cos(ΞΈ), -sin(ΞΈ) ] [ r*cos(precone) ] = [ r*cos(precone)*cos(ΞΈ) ] # [ 0, sin(ΞΈ), cos(ΞΈ) ] [ 0 ] [ r*cos(precone)*sin(ΞΈ) ] y0dot = @SVector [r*spc, r*cpc*cΞΈ, r*cpc*sΞΈ] # In the blade-fixed frame, the source isn't moving, since the blade-fixed reference frame is moving with the source. y1dot = @SVector zeros(eltype(y0dot), 3) # Vx = op.Vx # u = out.u # Vy = op.Vy # v = out.v sphi, cphi = sincos(phi) Vx_plus_u = W*sphi Vy_minus_v = W*cphi # The `span_uvec` is a unit vector pointing from the hub to the tip, along the blade element's radial length. # So that's just the same as the position vector, but without the r factor. span_uvec = @SVector [spc, cpc*cΞΈ, cpc*sΞΈ] if positive_x_rotation # Now, what is the velocity of the fluid in the blade-fixed frame? # In our coordinate system, the rotor is rotating about the x axis, moving in the x axis direction. # So that means it appears that the axial freestream velocity Vx is in the negative x axis direction. # And the induced velocity `u` has the same sign convention as Vx. # So the total axial velocity of the fluid is `(-Vx - u)`. # # For the tangential velocity, we're imagining the blade is initially aligned with the y axis, rotating about the positive x axis. # So that means the blade is moving toward the z axis. # So, from the perspective of the blade, the `Vy` velocity is in the negative z axis direction. # But the sign convention for the induced tangential velocity `v` is that # it's positive when it opposes `Vy`, so the total tangential velocity of the fluid is `(-Vy + v)`. # # So, finally, the fluid velocity vector we need to rotate is # # [-Vx - u ] # [ 0 ] # [-Vy + v ] # # and when I do all that I get # # [ (-Vx - u)*cos(precone) ] # [ (Vx + u)*sin(precone)*cos(ΞΈ) - (-Vy + v)*sin(ΞΈ) ] # [ (Vx + u)*sin(precone)*sin(ΞΈ) + (-Vy + v)*cos(ΞΈ) ] # y1dot_fluid = @SVector [(-Vx - u)*cpc, (Vx + u)*spc*cΞΈ - (-Vy + v)*sΞΈ, (Vx + u)*spc*sΞΈ + (-Vy + v)*cΞΈ] y1dot_fluid = @SVector [-Vx_plus_u*cpc, Vx_plus_u*spc*cΞΈ - (-Vy_minus_v)*sΞΈ, Vx_plus_u*spc*sΞΈ + (-Vy_minus_v)*cΞΈ] # Finally the `chord_uvec` is a unit vector pointing from the leading edge to the trailing edge. # In our initial coordinate system (i.e., not accounting for the precone or # ΞΈ rotations) we're imagining the blade is rotating about the x axis, # aligned with the y axis, and so is moving in the direction of the z axis. # So that means if the twist is zero, then the leading edge is headed in the # z axis direction, and a vector pointing from leading edge to trailing edge # would be in the negative z axis direction. Then, to account for the twist, # we would rotate it about the positive y axis. And then do the usual # precone and ΞΈ rotations. # So, a rotation about the y axis is # # [ cos(twist) 0 sin(twist) ] # [ 0 1 0 ] # [-sin(twist) 0 cos(twist) ] # # So, start with # # [ 0 ] # [ 0 ] # [-1 ] # # then # # [ cos(twist) 0 sin(twist) ] [ 0 ] [-sin(twist) ] # [ 0 1 0 ] [ 0 ] = [ 0 ] # [-sin(twist) 0 cos(twist) ] [-1 ] [-cos(twist) ] # # Now do the precone transformation # # [ cos(precone), sin(precone), 0 ] [-sin(twist) ] [-sin(twist)*cos(precone) ] # [-sin(precone), cos(precone), 0 ] [ 0 ] = [ sin(twist)*sin(precone) ] # [ 0, 0, 1 ] [-cos(twist) ] [-cos(twist) ] # # Finally do the ΞΈ transformation # # [ 1, 0 , 0 ] [-sin(twist)*cos(precone) ] [-sin(twist)*cos(precone) ] # [ 0, cos(ΞΈ), -sin(ΞΈ) ] [ sin(twist)*sin(precone) ] = [ sin(twist)*sin(precone)*cos(ΞΈ) + cos(twist)*sin(ΞΈ) ] # [ 0, sin(ΞΈ), cos(ΞΈ) ] [-cos(twist) ] [ sin(twist)*sin(precone)*sin(ΞΈ) - cos(twist)*cos(ΞΈ) ] chord_uvec = @SVector [-stwist*cpc, stwist*spc*cΞΈ + ctwist*sΞΈ, stwist*spc*sΞΈ - ctwist*cΞΈ] else # But, what if I want to assume that the blade is rotating in the opposite direction, i.e., about the negative x axis? # For the velocity, the direction of the axial velocity is unchanged: we're still moving in the positive x direction, so the axial velocity from the perspective of the blade element will be in the negative x direction. # So the total axial velocity of the fluid is `(-Vx - u)`. # # For the tangential velocity, we're rotating about the negative x axis now, so since the blade is initially aligned with the y axis, it is moving in the negative z direction. # So that means the freestream tangential velocity appears to be in the opposite direction, aka the positive z direction. # But the induced tangential velocity is in the opposite direction of the freestream tangential velocity, so the total velocity in the tangential direction is `(Vy - v)`. # # So the fluid velocity vector we want to rotate is # # [-Vx - u ] # [ 0 ] # [ Vy - v ] # # The theta and precone stuff doesn't change, so we'll do all the same stuff. # First we do the precone: # # [ cos(precone), sin(precone), 0 ] [-Vx - u] [ (-Vx - u)*cos(precone) ] [ (-Vx - u)*cos(precone) ] # [-sin(precone), cos(precone), 0 ] [ 0 ] = [ (-Vx - u)*(-sin(precone)) ] = [ ( Vx + u)*sin(precone) ] # [ 0, 0, 1 ] [ Vy - v] [ Vy - v ] [ Vy - v ] # # then do the theta rotation. # # [ 1, 0 , 0 ] [ (-Vx - u)*cos(precone) ] [ (-Vx - u)*cos(precone) ] # [ 0, cos(ΞΈ), -sin(ΞΈ) ] [ ( Vx + u)*sin(precone) ] = [ ( Vx + u)*sin(precone)*cos(ΞΈ) - (Vy - v)*sin(ΞΈ) ] # [ 0, sin(ΞΈ), cos(ΞΈ) ] [ Vy - v ] [ ( Vx + u)*sin(precone)*sin(ΞΈ) + (Vy - v)*cos(ΞΈ) ] # y1dot_fluid = @SVector [(-Vx - u)*cpc, (Vx + u)*spc*cΞΈ - (Vy - v)*sΞΈ, (Vx + u)*spc*sΞΈ + (Vy - v)*cΞΈ] y1dot_fluid = @SVector [-Vx_plus_u*cpc, Vx_plus_u*spc*cΞΈ - Vy_minus_v*sΞΈ, Vx_plus_u*spc*sΞΈ + Vy_minus_v*cΞΈ] # # That should be the same thing as the opposite case, but with the sign on (Vy - v) switched. # Yep, good. # # For the chord_uvec, I want to start with a unit vector pointing in the positive z axis, then do a negative-twist rotation about the positive y axis. # So start with # # [ 0 ] # [ 0 ] # [ 1 ] # # then # # [ cos(-twist) 0 sin(-twist) ] [ 0 ] [ sin(-twist) ] # [ 0 1 0 ] [ 0 ] = [ 0 ] # [-sin(-twist) 0 cos(-twist) ] [ 1 ] [ cos(-twist) ] # # Now do the precone transformation # # [ cos(precone), sin(precone), 0 ] [ sin(-twist) ] [ sin(-twist)*cos(precone) ] # [-sin(precone), cos(precone), 0 ] [ 0 ] = [-sin(-twist)*sin(precone) ] # [ 0, 0, 1 ] [ cos(-twist) ] [ cos(-twist) ] # # Finally do the ΞΈ transformation # # [ 1, 0 , 0 ] [ sin(-twist)*cos(precone) ] [ sin(-twist)*cos(precone) ] # [ 0, cos(ΞΈ), -sin(ΞΈ) ] [-sin(-twist)*sin(precone) ] = [-sin(-twist)*sin(precone)*cos(ΞΈ) - cos(-twist)*sin(ΞΈ) ] # [ 0, sin(ΞΈ), cos(ΞΈ) ] [ cos(-twist) ] [-sin(-twist)*sin(precone)*sin(ΞΈ) + cos(-twist)*cos(ΞΈ) ] # # Now handle the `-twist`, # # [ sin(-twist)*cos(precone) ] [-sin(twist)*cos(precone) ] # [-sin(-twist)*sin(precone)*cos(ΞΈ) - cos(-twist)*sin(ΞΈ) ] = [ sin(twist)*sin(precone)*cos(ΞΈ) - cos(twist)*sin(ΞΈ) ] # [-sin(-twist)*sin(precone)*sin(ΞΈ) + cos(-twist)*cos(ΞΈ) ] [ sin(twist)*sin(precone)*sin(ΞΈ) + cos(twist)*cos(ΞΈ) ] chord_uvec = @SVector [-stwist*cpc, stwist*spc*cΞΈ - ctwist*sΞΈ, stwist*spc*sΞΈ + ctwist*cΞΈ] end chord_cross_span_to_get_top_uvec = positive_x_rotation return y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec end """ TBLTESourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) Construct a source element to be used to predict turbulent boundary layer-trailing edge (TBLTE) noise. The source element's position is calculated from `section.r`, `rotor.precone`, and the `ΞΈ` argument using ```julia sΞΈ, cΞΈ = sincos(ΞΈ) spc, cpc = sincos(precone) y0dot = [r*spc, r*cpc*cΞΈ, r*cpc*sΞΈ] ``` where `y0dot` is the position of the source element. # Arguments - `rotor::CCBlade.Rotor`: CCBlade rotor object, needed for the precone angle. - `section::CCBlade.Section`: CCBlade section object, needed for the radial location and chord length of the element. - `op::CCBlade.OperatingPoint`: CCBlade operating point, needed for atmospheric properties. - `out::CCBlade.Outputs`: CCBlade outputs object, needed for the loading. - `ΞΈ`: polar coordinate of the element, in radians. - `Ξ”r`: length of the element, in meters. - `Ο„`: source time of the element, in seconds. - `Δτ`: source time duration, in seconds. - `bl`: `AcousticAnalogies.AbstractBoundaryLayer`, needed for boundary layer properties. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function TBLTESourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) return TBLTESourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(rotor, section, op, out, ΞΈ, Ξ”r, Ο„, Δτ, bl, positive_x_rotation) end function TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) where {TDirect,TUInduction,TMachCorrection,TDoppler} y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec( section.theta, rotor.precone, op.pitch, section.r, ΞΈ, out.W, out.phi, positive_x_rotation) nu = op.mu/op.rho return TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(op.asound, nu, Ξ”r, section.chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end """ tblte_source_elements_ccblade(rotor::CCBlade.Rotor, sections::Vector{CCBlade.Section}, ops::Vector{CCBlade.OperatingPoint}, outputs::Vector{CCBlade.Outputs}, bls::Vector{AbstractBoundaryLayer}, period, num_src_times, positive_x_rotation) Construct and return an array of TBLTESourceElement objects from CCBlade structs. # Arguments - `rotor`: CCBlade rotor object. - `sections`: `Vector` of CCBlade section object. - `ops`: `Vector` of CCBlade operating point. - `outputs`: `Vector` of CCBlade output objects. - `bls`::`Vector` of boundary layer `AbstractBoundaryLayer` `structs`. - `period`: length of the source time over which the returned source elements will evaluated. - `num_src_times`: number of source times. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function tblte_source_elements_ccblade(rotor, sections, ops, outputs, bls, period, num_src_times, positive_x_rotation) return tblte_source_elements_ccblade(BrooksBurleyDirectivity, true, PrandtlGlauertMachCorrection, true, rotor, sections, ops, outputs, bls, period, num_src_times, positive_x_rotation) end function tblte_source_elements_ccblade(TDirect::Type{<:AbstractDirectivity}, TUInduction::Bool, TMachCorrection::Type{<:AbstractMachCorrection}, TDoppler::Bool, rotor, sections, ops, outputs, bls, period, num_src_times, positive_x_rotation) # Need to know the radial spacing. (CCBlade doesn't use thisβ€”when # integrating stuff [loading to get torque and thrust] it uses the # trapezoidal rule and passes in the radial locations, and assumes that # integrands go to zero at the hub and tip.) Kind of lame that I have to # calcluate it here, but whatever. Maybe I should use StaticArrays for this? # Ah, no, I don't know the length at compile time. dradii = get_ccblade_dradii(rotor, sections) # Get the transformation that will put the source elements in the "standard" CCBlade.jl reference frame (moving axially in the positive x axis direction, rotating about the positive x axis, first blade initially aligned with the positive y axis). src_times, dt, trans = _standard_ccblade_transform(rotor, sections, ops, period, num_src_times, positive_x_rotation) # This is just an array of the angular offsets of each blade. First blade is # aligned with the y axis, next one is offset 2*pi/B radians, etc.. num_blades = rotor.B ΞΈs = 2*pi/num_blades.*(0:(num_blades-1)) .* ifelse(positive_x_rotation, 1, -1) # Reshape for broadcasting. Goal is to make everything work for a size of (num_times, # num_radial, num_blades). # trans_rs = reshape(trans, size(trans)..., 1) ΞΈs_rs = reshape(ΞΈs, 1, 1, :) sections_rs = reshape(sections, 1, :, 1) ops_rs = reshape(ops, 1, :, 1) outputs_rs = reshape(outputs, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # src_times = reshape(src_times, :, 1, 1) # This one isn't necessary. # Construct and transform the source elements. ses = TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}.(Ref(rotor), sections_rs, ops_rs, outputs_rs, ΞΈs_rs, dradii_rs, src_times, Ref(dt), bls_rs, positive_x_rotation) .|> trans return ses end """ LBLVSSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) Construct a source element to be used to predict laminary boundary layer-vortex shedding (LBLVS) noise. The source element's position is calculated from `section.r`, `rotor.precone`, and the `ΞΈ` argument using ```julia sΞΈ, cΞΈ = sincos(ΞΈ) spc, cpc = sincos(precone) y0dot = [r*spc, r*cpc*cΞΈ, r*cpc*sΞΈ] ``` where `y0dot` is the position of the source element. # Arguments - `rotor::CCBlade.Rotor`: CCBlade rotor object, needed for the precone angle. - `section::CCBlade.Section`: CCBlade section object, needed for the radial location and chord length of the element. - `op::CCBlade.OperatingPoint`: CCBlade operating point, needed for atmospheric properties. - `out::CCBlade.Outputs`: CCBlade outputs object, needed for the loading. - `ΞΈ`: polar coordinate of the element, in radians. - `Ξ”r`: length of the element, in meters. - `Ο„`: source time of the element, in seconds. - `Δτ`: source time duration, in seconds. - `bl`: `AcousticAnalogies.AbstractBoundaryLayer`, needed for boundary layer properties. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function LBLVSSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) return LBLVSSourceElement{BrooksBurleyDirectivity,true,true}(rotor, section, op, out, ΞΈ, Ξ”r, Ο„, Δτ, bl, positive_x_rotation) end function LBLVSSourceElement{TDirect,TUInduction,TDoppler}(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) where {TDirect,TUInduction,TDoppler} y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec( section.theta, rotor.precone, op.pitch, section.r, ΞΈ, out.W, out.phi, positive_x_rotation) nu = op.mu/op.rho return LBLVSSourceElement{TDirect,TUInduction,TDoppler}(op.asound, nu, Ξ”r, section.chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end """ lblvs_source_elements_ccblade(rotor::CCBlade.Rotor, sections::Vector{CCBlade.Section}, ops::Vector{CCBlade.OperatingPoint}, outputs::Vector{CCBlade.Outputs}, bls::Vector{AbstractBoundaryLayer}, period, num_src_times, positive_x_rotation) Construct and return an array of LBLVSSourceElement objects from CCBlade structs. # Arguments - `rotor`: CCBlade rotor object. - `sections`: `Vector` of CCBlade section object. - `ops`: `Vector` of CCBlade operating point. - `outputs`: `Vector` of CCBlade output objects. - `bls`::`Vector` of boundary layer `AbstractBoundaryLayer` `structs`. - `period`: length of the source time over which the returned source elements will evaluated. - `num_src_times`: number of source times. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function lblvs_source_elements_ccblade(rotor, sections, ops, outputs, bls, period, num_src_times, positive_x_rotation) return lblvs_source_elements_ccblade(BrooksBurleyDirectivity, true, true, rotor, sections, ops, outputs, bls, period, num_src_times, positive_x_rotation) end function lblvs_source_elements_ccblade(TDirect::Type{<:AbstractDirectivity}, TUInduction::Bool, TDoppler::Bool, rotor, sections, ops, outputs, bls, period, num_src_times, positive_x_rotation) # Need to know the radial spacing. (CCBlade doesn't use thisβ€”when # integrating stuff [loading to get torque and thrust] it uses the # trapezoidal rule and passes in the radial locations, and assumes that # integrands go to zero at the hub and tip.) Kind of lame that I have to # calcluate it here, but whatever. Maybe I should use StaticArrays for this? # Ah, no, I don't know the length at compile time. dradii = get_ccblade_dradii(rotor, sections) # Get the transformation that will put the source elements in the "standard" CCBlade.jl reference frame (moving axially in the positive x axis direction, rotating about the positive x axis, first blade initially aligned with the positive y axis). src_times, dt, trans = _standard_ccblade_transform(rotor, sections, ops, period, num_src_times, positive_x_rotation) # This is just an array of the angular offsets of each blade. First blade is # aligned with the y axis, next one is offset 2*pi/B radians, etc.. num_blades = rotor.B ΞΈs = 2*pi/num_blades.*(0:(num_blades-1)) .* ifelse(positive_x_rotation, 1, -1) # Reshape for broadcasting. Goal is to make everything work for a size of (num_times, # num_radial, num_blades). # trans_rs = reshape(trans, size(trans)..., 1) ΞΈs_rs = reshape(ΞΈs, 1, 1, :) sections_rs = reshape(sections, 1, :, 1) ops_rs = reshape(ops, 1, :, 1) outputs_rs = reshape(outputs, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # src_times = reshape(src_times, :, 1, 1) # This one isn't necessary. # Construct and transform the source elements. ses = LBLVSSourceElement{TDirect,TUInduction,TDoppler}.(Ref(rotor), sections_rs, ops_rs, outputs_rs, ΞΈs_rs, dradii_rs, src_times, Ref(dt), bls_rs, positive_x_rotation) .|> trans return ses end """ TipVortexSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, Ο„, Δτ, bl::AbstractBoundaryLayer, blade_tip::AbstractBladeTip, positive_x_rotation) Construct a source element to be used to predict tip vortex noise. The source element's position is calculated from `section.r`, `rotor.precone`, and the `ΞΈ` argument using ```julia sΞΈ, cΞΈ = sincos(ΞΈ) spc, cpc = sincos(precone) y0dot = [r*spc, r*cpc*cΞΈ, r*cpc*sΞΈ] ``` where `y0dot` is the position of the source element. # Arguments - `rotor::CCBlade.Rotor`: CCBlade rotor object, needed for the precone angle. - `section::CCBlade.Section`: CCBlade section object, needed for the radial location and chord length of the element. - `op::CCBlade.OperatingPoint`: CCBlade operating point, needed for atmospheric properties. - `out::CCBlade.Outputs`: CCBlade outputs object, needed for the loading. - `ΞΈ`: polar coordinate of the element, in radians. - `Ξ”r`: length of the element, in meters. - `Ο„`: source time of the element, in seconds. - `Δτ`: source time duration, in seconds. - `bl`: `AcousticAnalogies.AbstractBoundaryLayer`, needed for boundary layer properties. - `blade_tip`: `AcousticAnalogies.AbstractBladeTip` - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function TipVortexSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, Ο„, Δτ, bl::AbstractBoundaryLayer, blade_tip::AbstractBladeTip, positive_x_rotation) return TipVortexSourceElement{BrooksBurleyDirectivity,true,true}(rotor, section, op, out, ΞΈ, Ξ”r, Ο„, Δτ, bl, blade_tip, positive_x_rotation) end function TipVortexSourceElement{TDirect,TUInduction,TDoppler}(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, Ο„, Δτ, bl::AbstractBoundaryLayer, blade_tip::AbstractBladeTip, positive_x_rotation) where {TDirect,TUInduction,TDoppler} y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec( section.theta, rotor.precone, op.pitch, section.r, ΞΈ, out.W, out.phi, positive_x_rotation) return TipVortexSourceElement{TDirect,TUInduction,TDoppler}(op.asound, Ξ”r, section.chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end """ tip_vortex_source_elements_ccblade(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, output::CCBlade.Outputs, bl::AbstractBoundaryLayer, blade_tip::AbstractBladeTip, period, num_src_times, positive_x_rotation) Construct and return an array of TipVortexSourceElement objects from CCBlade structs. Note that unlike the other `*_source_elements_ccblade` functions, `tip_vortex_source_elements_ccblade` expects scalar arguments instead of vectors for `section`, `op`, etc. as a blade only has one tip. # Arguments - `rotor`: CCBlade rotor object. - `section`: CCBlade section object at the blade tip. - `op`: CCBlade operating point object at the blade tip. - `output`: CCBlade output object at the blade tip. - `Ξ”r`: radial spacing. - `bl`:: Boundary layer `struct` at the blade tip. - `blade_tip`: `AcousticAnalogies.AbstractBladeTip` - `period`: length of the source time over which the returned source elements will evaluated. - `num_src_times`: number of source times. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function tip_vortex_source_elements_ccblade(rotor, section, op, output, Ξ”r, bl, blade_tip, period, num_src_times, positive_x_rotation) return tip_vortex_source_elements_ccblade(BrooksBurleyDirectivity, true, true, rotor, section, op, output, Ξ”r, bl, blade_tip, period, num_src_times, positive_x_rotation) end function tip_vortex_source_elements_ccblade(TDirect::Type{<:AbstractDirectivity}, TUInduction::Bool, TDoppler::Bool, rotor, section, op, output, Ξ”r, bl, blade_tip, period, num_src_times, positive_x_rotation) # Ugh, hate doing this. # Wish there was a way to make a allocation-free array-like thingy from a scaler. # But I doubt it makes any difference. # sections = [section] # ops = [op] # Good news! # Learned about the FillArrays.jl package. sections = Fill(section, 1) ops = Fill(op, 1) # But that breaks with CCBlade.jl. # So back to 1D arrays. # sections = [section] # ops = [op] # Get the transformation that will put the source elements in the "standard" CCBlade.jl reference frame (moving axially in the positive x axis direction, rotating about the positive x axis, first blade initially aligned with the positive y axis). src_times, dt, trans = _standard_ccblade_transform(rotor, sections, ops, period, num_src_times, positive_x_rotation) # This is just an array of the angular offsets of each blade. First blade is # aligned with the y axis, next one is offset 2*pi/B radians, etc.. num_blades = rotor.B ΞΈs = 2*pi/num_blades.*(0:(num_blades-1)) .* ifelse(positive_x_rotation, 1, -1) # Reshape for broadcasting. Goal is to make everything work for a size of (num_times, num_radial, num_blades). # But this will really be (num_times, 1, num_blades). # trans_rs = reshape(trans, size(trans)..., 1) ΞΈs_rs = reshape(ΞΈs, 1, 1, :) # sections_rs = reshape(sections, 1, 1) # ops_rs = reshape(ops, 1, 1) # outputs = reshape(outputs, 1, :, 1) # dradii = reshape(dradii, 1, :, 1) # bls = reshape(bls, 1, :, 1) # src_times = reshape(src_times, :, 1, 1) # This one isn't necessary. # Construct and transform the source elements. # ses = TipVortexSourceElement.(Ref(rotor), sections_rs, ops_rs, Ref(output), ΞΈs_rs, Ref(Ξ”r), src_times, Ref(dt), Ref(bl), positive_x_rotation) .|> trans_rs # So Θs_rs has size (1, 1, num_blades), src_times has size (num_src_times,), trans has size (num_src_times, 1). # So that should all work out. ses = TipVortexSourceElement{TDirect,TUInduction,TDoppler}.(Ref(rotor), Ref(section), Ref(op), Ref(output), ΞΈs_rs, Ref(Ξ”r), src_times, Ref(dt), Ref(bl), Ref(blade_tip), positive_x_rotation) .|> trans return ses end """ TEBVSSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) Construct a source element to be used to predict trailing edge bluntness-vortex shedding (TEBVS) noise. The source element's position is calculated from `section.r`, `rotor.precone`, and the `ΞΈ` argument using ```julia sΞΈ, cΞΈ = sincos(ΞΈ) spc, cpc = sincos(precone) y0dot = [r*spc, r*cpc*cΞΈ, r*cpc*sΞΈ] ``` where `y0dot` is the position of the source element. # Arguments - `rotor::CCBlade.Rotor`: CCBlade rotor object, needed for the precone angle. - `section::CCBlade.Section`: CCBlade section object, needed for the radial location and chord length of the element. - `op::CCBlade.OperatingPoint`: CCBlade operating point, needed for atmospheric properties. - `out::CCBlade.Outputs`: CCBlade outputs object, needed for the loading. - `ΞΈ`: polar coordinate of the element, in radians. - `Ξ”r`: length of the element, in meters. - `h`: trailing edge thickness (m) - `Psi`: solid angle between the blade surfaces immediately upstream of the trailing edge (rad) - `Ο„`: source time of the element, in seconds. - `Δτ`: source time duration, in seconds. - `bl`: `AcousticAnalogies.AbstractBoundaryLayer`, needed for boundary layer properties. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function TEBVSSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) return TEBVSSourceElement{BrooksBurleyDirectivity,true,true}(rotor, section, op, out, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl, positive_x_rotation) end function TEBVSSourceElement{TDirect,TUInduction,TDoppler}(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) where {TDirect,TUInduction,TDoppler} y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec( section.theta, rotor.precone, op.pitch, section.r, ΞΈ, out.W, out.phi, positive_x_rotation) nu = op.mu/op.rho return TEBVSSourceElement{TDirect,TUInduction,TDoppler}(op.asound, nu, Ξ”r, section.chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end """ tebvs_source_elements_ccblade(rotor::CCBlade.Rotor, sections::Vector{CCBlade.Section}, ops::Vector{CCBlade.OperatingPoint}, outputs::Vector{CCBlade.Outputs}, hs, Psis, bls::Vector{AbstractBoundaryLayer}, period, num_src_times, positive_x_rotation) Construct and return an array of TEBVSSourceElement objects from CCBlade structs. # Arguments - `rotor`: CCBlade rotor object. - `sections`: `Vector` of CCBlade section object. - `ops`: `Vector` of CCBlade operating point. - `outputs`: `Vector` of CCBlade output objects. - `hs`: `Vector` of trailing edge thicknesses - `Psis`: `Vector` of solid angles between the blade surfaces immediately upstream of the trailing edge (rad) - `bls`::`Vector` of boundary layer `AbstractBoundaryLayer` `structs`. - `period`: length of the source time over which the returned source elements will evaluated. - `num_src_times`: number of source times. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function tebvs_source_elements_ccblade(rotor, sections, ops, outputs, hs, Psis, bls, period, num_src_times, positive_x_rotation) return tebvs_source_elements_ccblade(BrooksBurleyDirectivity, true, true, rotor, sections, ops, outputs, hs, Psis, bls, period, num_src_times, positive_x_rotation) end function tebvs_source_elements_ccblade(TDirect::Type{<:AbstractDirectivity}, TUInduction::Bool, TDoppler::Bool, rotor, sections, ops, outputs, hs, Psis, bls, period, num_src_times, positive_x_rotation) # Need to know the radial spacing. (CCBlade doesn't use thisβ€”when # integrating stuff [loading to get torque and thrust] it uses the # trapezoidal rule and passes in the radial locations, and assumes that # integrands go to zero at the hub and tip.) Kind of lame that I have to # calcluate it here, but whatever. Maybe I should use StaticArrays for this? # Ah, no, I don't know the length at compile time. dradii = get_ccblade_dradii(rotor, sections) # Get the transformation that will put the source elements in the "standard" CCBlade.jl reference frame (moving axially in the positive x axis direction, rotating about the positive x axis, first blade initially aligned with the positive y axis). src_times, dt, trans = _standard_ccblade_transform(rotor, sections, ops, period, num_src_times, positive_x_rotation) # This is just an array of the angular offsets of each blade. First blade is # aligned with the y axis, next one is offset 2*pi/B radians, etc.. num_blades = rotor.B ΞΈs = 2*pi/num_blades.*(0:(num_blades-1)) .* ifelse(positive_x_rotation, 1, -1) # Reshape for broadcasting. Goal is to make everything work for a size of (num_times, # num_radial, num_blades). # trans_rs = reshape(trans, size(trans)..., 1) ΞΈs_rs = reshape(ΞΈs, 1, 1, :) sections_rs = reshape(sections, 1, :, 1) ops_rs = reshape(ops, 1, :, 1) outputs_rs = reshape(outputs, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) hs_rs = reshape(hs, 1, :, 1) Psis_rs = reshape(Psis, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # src_times = reshape(src_times, :, 1, 1) # This one isn't necessary. # Construct and transform the source elements. ses = TEBVSSourceElement{TDirect,TUInduction,TDoppler}.(Ref(rotor), sections_rs, ops_rs, outputs_rs, ΞΈs_rs, dradii_rs, hs_rs, Psis_rs, src_times, Ref(dt), bls_rs, positive_x_rotation) .|> trans return ses end """ CombinedNoTipBroadbandSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) Construct a source element for predicting turbulent boundary layer-trailing edge (TBLTE), laminar boundary layer-vortex shedding (LBLVS) noise, and trailing edge bluntness-vortex shedding (TEBVS) noise using the BPM/Brooks and Burley method from CCBlade structs. The source element's position is calculated from `section.r`, `rotor.precone`, and the `ΞΈ` argument using ```julia sΞΈ, cΞΈ = sincos(ΞΈ) spc, cpc = sincos(precone) y0dot = [r*spc, r*cpc*cΞΈ, r*cpc*sΞΈ] ``` where `y0dot` is the position of the source element. # Arguments - `rotor::CCBlade.Rotor`: CCBlade rotor object, needed for the precone angle. - `section::CCBlade.Section`: CCBlade section object, needed for the radial location and chord length of the element. - `op::CCBlade.OperatingPoint`: CCBlade operating point, needed for atmospheric properties. - `out::CCBlade.Outputs`: CCBlade outputs object, needed for the loading. - `ΞΈ`: polar coordinate of the element, in radians. - `Ξ”r`: length of the element, in meters. - `h`: trailing edge thickness (m) - `Psi`: solid angle between the blade surfaces immediately upstream of the trailing edge (rad) - `Ο„`: source time of the element, in seconds. - `Δτ`: source time duration, in seconds. - `bl`: `AcousticAnalogies.AbstractBoundaryLayer`, needed for boundary layer properties. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function CombinedNoTipBroadbandSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) return CombinedNoTipBroadbandSourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(rotor, section, op, out, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl, positive_x_rotation) end function CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl::AbstractBoundaryLayer, positive_x_rotation) where {TDirect,TUInduction,TMachCorrection,TDoppler} y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec( section.theta, rotor.precone, op.pitch, section.r, ΞΈ, out.W, out.phi, positive_x_rotation) nu = op.mu/op.rho return CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(op.asound, nu, Ξ”r, section.chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end """ CombinedWithTipBroadbandSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl::AbstractBoundaryLayer, blade_tip::AbstractBladeTip, positive_x_rotation) Construct a source element for predicting turbulent boundary layer-trailing edge (TBLTE), laminar boundary layer-vortex shedding (LBLVS) noise, trailing edge bluntness-vortex shedding (TEBVS), and tip vortex noise using the BPM/Brooks and Burley method from CCBlade structs. The source element's position is calculated from `section.r`, `rotor.precone`, and the `ΞΈ` argument using ```julia sΞΈ, cΞΈ = sincos(ΞΈ) spc, cpc = sincos(precone) y0dot = [r*spc, r*cpc*cΞΈ, r*cpc*sΞΈ] ``` where `y0dot` is the position of the source element. # Arguments - `rotor::CCBlade.Rotor`: CCBlade rotor object, needed for the precone angle. - `section::CCBlade.Section`: CCBlade section object, needed for the radial location and chord length of the element. - `op::CCBlade.OperatingPoint`: CCBlade operating point, needed for atmospheric properties. - `out::CCBlade.Outputs`: CCBlade outputs object, needed for the loading. - `ΞΈ`: polar coordinate of the element, in radians. - `Ξ”r`: length of the element, in meters. - `h`: trailing edge thickness (m) - `Psi`: solid angle between the blade surfaces immediately upstream of the trailing edge (rad) - `Ο„`: source time of the element, in seconds. - `Δτ`: source time duration, in seconds. - `bl`: `AcousticAnalogies.AbstractBoundaryLayer`, needed for boundary layer properties. - `blade_tip`: Blade tip struct, i.e. an AbstractBladeTip. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function CombinedWithTipBroadbandSourceElement(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl::AbstractBoundaryLayer, blade_tip::AbstractBladeTip, positive_x_rotation) return CombinedWithTipBroadbandSourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(rotor, section, op, out, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl, blade_tip, positive_x_rotation) end function CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(rotor::CCBlade.Rotor, section::CCBlade.Section, op::CCBlade.OperatingPoint, out::CCBlade.Outputs, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl::AbstractBoundaryLayer, blade_tip::AbstractBladeTip, positive_x_rotation) where {TDirect,TUInduction,TMachCorrection,TDoppler} y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec( section.theta, rotor.precone, op.pitch, section.r, ΞΈ, out.W, out.phi, positive_x_rotation) nu = op.mu/op.rho return CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(op.asound, nu, Ξ”r, section.chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end """ combined_broadband_source_elements_ccblade(rotor::CCBlade.Rotor, sections::Vector{CCBlade.Section}, ops::Vector{CCBlade.OperatingPoint}, outputs::Vector{CCBlade.Outputs}, hs::Vector{Float64}, Psis::Vector{Float64}, bls::Vector{AbstractBoundaryLayer}, blade_tip::AbstractBladeTip, period, num_src_times, positive_x_rotation) Construct and return an array of broadband prediction source element objects from CCBlade structs. # Arguments - `rotor`: CCBlade rotor object. - `sections`: `Vector` of CCBlade section object. - `ops`: `Vector` of CCBlade operating point. - `outputs`: `Vector` of CCBlade output objects. - `hs`: `Vector` of trailing edge thicknesses (m) - `Psis`: `Vector` of solid angles between the blade surfaces immediately upstream of the trailing edge (rad) - `bls`::`Vector` of boundary layer `AbstractBoundaryLayer` `structs`. - `blade_tip`: Blade tip struct, i.e. an AbstractBladeTip. - `period`: length of the source time over which the returned source elements will evaluated. - `num_src_times`: number of source times. - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise. """ function combined_broadband_source_elements_ccblade(rotor, sections, ops, outputs, hs, Psis, bls, blade_tip, period, num_src_times, positive_x_rotation) return combined_broadband_source_elements_ccblade(BrooksBurleyDirectivity, true, PrandtlGlauertMachCorrection, true, rotor, sections, ops, outputs, hs, Psis, bls, blade_tip, period, num_src_times, positive_x_rotation) end function combined_broadband_source_elements_ccblade(TDirect::Type{<:AbstractDirectivity}, TUInduction::Bool, TMachCorrection::Type{<:AbstractMachCorrection}, TDoppler::Bool, rotor, sections, ops, outputs, hs, Psis, bls::AbstractVector{<:AbstractBoundaryLayer}, blade_tip, period, num_src_times, positive_x_rotation) # Need to know the radial spacing. (CCBlade doesn't use thisβ€”when # integrating stuff [loading to get torque and thrust] it uses the # trapezoidal rule and passes in the radial locations, and assumes that # integrands go to zero at the hub and tip.) Kind of lame that I have to # calcluate it here, but whatever. Maybe I should use StaticArrays for this? # Ah, no, I don't know the length at compile time. dradii = get_ccblade_dradii(rotor, sections) # Get the transformation that will put the source elements in the "standard" CCBlade.jl reference frame (moving axially in the positive x axis direction, rotating about the positive x axis, first blade initially aligned with the positive y axis). # Will be size (num_times, num_radial), so we'll need to adjust for the no tip/with tip stuff. src_times, dt, trans = _standard_ccblade_transform(rotor, sections, ops, period, num_src_times, positive_x_rotation) # This is just an array of the angular offsets of each blade. First blade is # aligned with the y axis, next one is offset 2*pi/B radians, etc.. num_blades = rotor.B ΞΈs = 2*pi/num_blades.*(0:(num_blades-1)) .* ifelse(positive_x_rotation, 1, -1) # Reshape for broadcasting. Goal is to make everything work for a size of (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) sections_rs = reshape(sections, 1, :, 1) ops_rs = reshape(ops, 1, :, 1) outputs_rs = reshape(outputs, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) hs_rs = reshape(hs, 1, :, 1) Psis_rs = reshape(Psis, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # src_times = reshape(src_times, :, 1, 1) # This one isn't necessary. # So, I want to create some structs for all the non-blade tip elements, and the blade tip elements. # So I just need to slice things appropriately. sections_rs_no_tip = @view sections_rs[:, begin:end-1, :] ops_rs_no_tip = @view ops_rs[:, begin:end-1, :] outputs_rs_no_tip = @view outputs_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] trans_no_tip = @view trans[:, begin:end-1] sections_rs_with_tip = @view sections_rs[:, end:end, :] ops_rs_with_tip = @view ops_rs[:, end:end, :] outputs_rs_with_tip = @view outputs_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] hs_rs_with_tip = @view hs_rs[:, end:end, :] Psis_rs_with_tip = @view Psis_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] trans_with_tip = @view trans[:, end:end] # Construct and transform the source elements. ses_no_tip = CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}.(Ref(rotor), sections_rs_no_tip, ops_rs_no_tip, outputs_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, hs_rs_no_tip, Psis_rs_no_tip, src_times, Ref(dt), bls_rs_no_tip, positive_x_rotation) .|> trans_no_tip ses_with_tip = CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}.(Ref(rotor), sections_rs_with_tip, ops_rs_with_tip, outputs_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, hs_rs_with_tip, Psis_rs_with_tip, src_times, Ref(dt), bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans_with_tip return ses_no_tip, ses_with_tip end """ get_ccblade_dradii(rotor::CCBlade.Rotor, sections::Vector{CCBlade.Section}) Construct and return a Vector of the lengths of each CCBlade section. """ function get_ccblade_dradii(rotor, sections) radii = mapview(:r, sections) dradii = get_dradii(radii, rotor.Rhub, rotor.Rtip) return dradii end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
44954
struct CombinedNoTipBroadbandSourceElement{ TDirect<:AbstractDirectivity,TUInduction,TMachCorrection,TDoppler, Tc0,Tnu,TΞ”r,Tchord,Th,TPsi,Ty0dot,Ty1dot,Ty1dot_fluid,TΟ„,TΔτ,Tspan_uvec,Tchord_uvec,Tbl } <: AbstractBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler} # Speed of sound, m/s. c0::Tc0 # Kinematic viscosity, m^2/s nu::Tnu # Radial/spanwise length of element, m. Ξ”r::TΞ”r # chord length of element, m. chord::Tchord # Trailing edge thickness, m. h::Th # Solid angle between blade surfaces immediately upstream of the trailing edge, rad. Psi::TPsi # Source position, m. y0dot::Ty0dot # Source velocity, m/s. y1dot::Ty1dot # Fluid velocity, m/s. y1dot_fluid::Ty1dot_fluid # Source time, s. Ο„::TΟ„ # Time step size, i.e. the amount of time this source element "exists" at with these properties, s. Δτ::TΔτ # Radial/spanwise unit vector, aka unit vector aligned with the element's span direction. span_uvec::Tspan_uvec # Chordwise unit vector, aka unit vector aligned with the element's chord line, pointing from leading edge to trailing edge. chord_uvec::Tchord_uvec # Boundary layer struct, i.e. an AbstractBoundaryLayer. bl::Tbl # `Bool` indicating chord_uvecΓ—span_uvec will give a vector pointing from bottom side (usually pressure side) to top side (usually suction side) if `true`, or the opposite if `false`. chord_cross_span_to_get_top_uvec::Bool function CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, Ξ”r, chord, h, Psi, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, chord_cross_span_to_get_top_uvec::Bool) where {TDirect<:AbstractDirectivity,TUInduction,TMachCorrection,TDoppler} return new{ TDirect,TUInduction,TMachCorrection,TDoppler, typeof(c0), typeof(nu), typeof(Ξ”r), typeof(chord), typeof(h), typeof(Psi), typeof(y0dot), typeof(y1dot), typeof(y1dot_fluid), typeof(Ο„), typeof(Δτ), typeof(span_uvec), typeof(chord_uvec), typeof(bl) }(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), use the Prandtl-Glauert mach number correction, and Doppler-shift. function CombinedNoTipBroadbandSourceElement(c0, nu, Ξ”r, chord, h, Psi, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, chord_cross_span_to_get_top_uvec) return CombinedNoTipBroadbandSourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end """ CombinedNoTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) Construct a source element for predicting turbulent boundary layer-trailing edge (TBLTE), laminar boundary layer-vortex shedding (LBLVS) noise, and trailing edge bluntness-vortex shedding (TEBVS) noise using the BPM/Brooks and Burley method, using position and velocity data expressed in a cylindrical coordinate system. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. Likewise, the `vn`, `vr`, and `vc` arguments are used to define the normal, radial, and circumferential velocity of the fluid (in a reference frame moving with the element) in the same cylindrical coordinate system. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - h: trailing edge thickness (m) - Psi: solid angle between the blade surfaces immediately upstream of the trailing edge (rad) - vn: normal velocity of fluid (m/s) - vr: radial velocity of fluid (m/s) - vc: circumferential velocity of the fluid (m/s) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) where {TDirect,TUInduction,TMachCorrection,TDoppler} sΞΈ, cΞΈ = sincos(ΞΈ) sΟ•, cΟ• = sincos(Ο•) y0dot = @SVector [0, r*cΞΈ, r*sΞΈ] T = eltype(y0dot) y1dot = @SVector zeros(T, 3) y1dot_fluid = @SVector [vn, vr*cΞΈ - vc*sΞΈ, vr*sΞΈ + vc*cΞΈ] span_uvec = @SVector [0, cΞΈ, sΞΈ] if twist_about_positive_y chord_uvec = @SVector [-sΟ•, cΟ•*sΞΈ, -cΟ•*cΞΈ] else chord_uvec = @SVector [-sΟ•, -cΟ•*sΞΈ, cΟ•*cΞΈ] end chord_cross_span_to_get_top_uvec = twist_about_positive_y return CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), use the Prandtl-Glauert mach number correction, and Doppler-shift. function CombinedNoTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) return CombinedNoTipBroadbandSourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) end """ CombinedNoTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) Construct a source element for predicting turbulent boundary layer-trailing edge (TBLTE), laminar boundary layer-vortex shedding (LBLVS) noise, and trailing edge bluntness-vortex shedding (TEBVS) noise using the BPM/Brooks and Burley method, using the velocity magnitude `U` and angle of attack `Ξ±`. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. The `U` and `Ξ±` arguments are the velocity magnitude normal to the source element length and the angle of attack, respectively. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - h: trailing edge thickness (m) - Psi: solid angle between the blade surfaces immediately upstream of the trailing edge (rad) - U: velocity magnitude (m/s) - Ξ±: angle of attack (rad) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) where {TDirect,TUInduction,TMachCorrection,TDoppler} precone = 0 pitch = 0 phi = Ο• - Ξ± y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec(Ο•, precone, pitch, r, ΞΈ, U, phi, twist_about_positive_y) return CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), use the PrandtlGlauertMachCorrection, and Doppler-shift. function CombinedNoTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y::Bool) return CombinedNoTipBroadbandSourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) end """ (trans::KinematicTransformation)(se::CombinedNoTipBroadbandSourceElement) Transform the position and orientation of a source element according to the coordinate system transformation `trans`. """ function (trans::KinematicTransformation)(se::CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}) where {TDirect,TUInduction,TMachCorrection,TDoppler} linear_only = false y0dot, y1dot = trans(se.Ο„, se.y0dot, se.y1dot, linear_only) y0dot, y1dot_fluid = trans(se.Ο„, se.y0dot, se.y1dot_fluid, linear_only) linear_only = true span_uvec = trans(se.Ο„, se.span_uvec, linear_only) chord_uvec = trans(se.Ο„, se.chord_uvec, linear_only) return CombinedNoTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(se.c0, se.nu, se.Ξ”r, se.chord, se.h, se.Psi, y0dot, y1dot, y1dot_fluid, se.Ο„, se.Δτ, span_uvec, chord_uvec, se.bl, se.chord_cross_span_to_get_top_uvec) end """ CombinedNoTipOutput(G_s, G_p, G_alpha, G_teb, cbands, dt, t) Output of the combined broadband noise calculation not including tip vortex noise: the acoustic pressure autospectrum centered at time `t` over observer duration `dt` and observer frequencies `cbands` for the TBLTE suction side `G_s`, TBLTE pressure side `G_p`, TBLTE separation noise `G_alpha`, and trailing edge bluntness noise `G_teb`. """ struct CombinedNoTipOutput{NO,TF,TG<:AbstractVector{TF},TFreqs<:AcousticMetrics.AbstractProportionalBands{NO,:center},TDTime,TTime} <: AcousticMetrics.AbstractProportionalBandSpectrum{NO,TF} G_s::TG G_p::TG G_alpha::TG G_lblvs::TG G_teb::TG cbands::TFreqs dt::TDTime t::TTime function CombinedNoTipOutput(G_s::TG, G_p::TG, G_alpha::TG, G_lblvs, G_teb::TG, cbands::AcousticMetrics.AbstractProportionalBands{NO,:center}, dt, t) where {NO,TG} ncbands = length(cbands) length(G_s) == ncbands || throw(ArgumentError("length(G_s) must match length(cbands)")) length(G_p) == ncbands || throw(ArgumentError("length(G_p) must match length(cbands)")) length(G_alpha) == ncbands || throw(ArgumentError("length(G_alpha) must match length(cbands)")) length(G_lblvs) == ncbands || throw(ArgumentError("length(G_lblvs) must match length(cbands)")) length(G_teb) == ncbands || throw(ArgumentError("length(G_teb) must match length(cbands)")) dt > zero(dt) || throw(ArgumentError("dt must be positive")) return new{NO,eltype(TG),TG,typeof(cbands),typeof(dt),typeof(t)}(G_s, G_p, G_alpha, G_lblvs, G_teb, cbands, dt, t) end end @inline function Base.getindex(pbs::CombinedNoTipOutput, i::Int) @boundscheck checkbounds(pbs, i) return @inbounds pbs.G_s[i] + pbs.G_p[i] + pbs.G_alpha[i] + +pbs.G_lblvs[i] + pbs.G_teb[i] end @inline AcousticMetrics.has_observer_time(pbs::CombinedNoTipOutput) = true @inline AcousticMetrics.observer_time(pbs::CombinedNoTipOutput) = pbs.t @inline AcousticMetrics.timestep(pbs::CombinedNoTipOutput) = pbs.dt @inline AcousticMetrics.time_scaler(pbs::CombinedNoTipOutput, period) = timestep(pbs)/period function noise(se::CombinedNoTipBroadbandSourceElement, obs::AbstractAcousticObserver, t_obs, freqs::AcousticMetrics.AbstractProportionalBands{3, :center}) # Position of the observer: x_obs = obs(t_obs) # Need the angle of attack. alphastar = angle_of_attack(se) # Need the directivity functions. top_is_suction = is_top_suction(se.bl, alphastar) r_er, Dl, Dh = directivity(se, x_obs, top_is_suction) # Need the fluid velocity normal to the span. # Brooks and Burley 2001 are a bit ambiguous on whether it should include induction, or just the freestream and rotation. # # * In the nomenclature section: `U` is "flow speed normal to span (`U_mn` with `mn` suppressed). # So that's one point for "no induction." # * In some discussion after equation (8), "The Mach number, `M = U/c0`, represents that component of velocity `U` normal to the span...". # Hard to say one way or the other. # * In equation (12), `U_mn` is the velocity without induction. # So that's another point for "no induction." # * Equation (14) defines `V_tot` as the velocity including the freestream, rotation, and induction. # And then it defines `U` as the part of `V_tot` normal to the span. # So that's a point for "yes induction." # * In the directivity function definitions in equations (19) and (20), `M_tot` is used in the denominator, which seems to make it clear *that* velocity should include induction, since `V_tot` always includes induction. # # So, at the moment, the TBLTESourceElement type has a parameter TUInduction which, when true, will include induction in the flow speed normal to the span, and not otherwise. U = speed_normal_to_span(se) # Reynolds number based on chord and the flow speed normal to span. Re_c = U*se.chord/se.nu # Also need the displacement thicknesses for the pressure and suction sides. deltastar_s = disp_thickness_s(se.bl, Re_c, alphastar)*se.chord deltastar_p = disp_thickness_p(se.bl, Re_c, alphastar)*se.chord # Need the boundary layer thickness for the pressure side for LBL-VS noise. delta_p = bl_thickness_p(se.bl, Re_c, alphastar)*se.chord # Now that we've decided on the directivity functions and the displacement thickness, and we know the correct value of `top_is_suction` we should be able to switch the sign on `alphastar` if it's negative, and reference it to the zero-lift value, as the BPM report does. alphastar_positive = abs_cs_safe(alphastar - alpha_zerolift(se.bl)) # Mach number of the flow speed normal to span. M = U/se.c0 # This stuff is used to decide if the blade element is stalled or not. alphastar0 = alpha_stall(se.bl, Re_c) gamma0_deg = gamma0(M) deep_stall = (alphastar_positive*180/pi) > min(gamma0_deg, alphastar0*180/pi) # if deep_stall # println("deep_stall! M = $(M), alphastar_positive*180/pi = $(alphastar_positive*180/pi), gamma0_deg = $(gamma0_deg), alphastar0*180/pi = $(alphastar0*180/pi)") # println("forcing deep_stall == false") # deep_stall = false # end St_peak_p = St_1(M) St_peak_alpha = St_2(St_peak_p, alphastar_positive) St_peak_s = 0.5*(St_peak_p + St_peak_alpha) Re_deltastar_p = U*deltastar_p/se.nu k_1 = K_1(Re_c) k_2 = K_2(Re_c, M, alphastar_positive) Ξ”k_1 = DeltaK_1(alphastar_positive, Re_deltastar_p) deltastar_s_U = deltastar_s/U deltastar_p_U = deltastar_p/U # Stuff for LBLVS noise. delta_p_U = delta_p/U St_p_p = St_peak_prime(St_1_prime(Re_c), alphastar_positive) Re_c_over_Re_c0 = Re_c / Re_c0(alphastar_positive) g2 = G2(Re_c_over_Re_c0) g3 = G3(alphastar_positive) # Brooks and Burley 2001 recommend a Prandtl-Glauert style Mach number correction, but only for the TBLTE noise. # But whether or not it's included is dependent on the TMachCorrection type parameter for the source element. m_corr = mach_correction(se, M) # Equation 73 from the BPM report. deltastar_avg = 0.5*(deltastar_p + deltastar_s) h_over_deltastar_avg = se.h/deltastar_avg h_U = se.h/U St_3pp = St_3prime_peak(h_over_deltastar_avg, se.Psi) g4 = G4(h_over_deltastar_avg, se.Psi) # The Brooks and Burley autospectrums appear to be scaled by the usual squared reference pressure (20 ΞΌPa)^2, but I'd like things in dimensional units, so multiply through by that. pref2 = 4e-10 G_s_scaler = (deltastar_s*M^5*se.Ξ”r*Dh)/(r_er^2)*m_corr G_s = _tble_te_s.(freqs, deltastar_s_U, Re_c, St_peak_s, k_1, G_s_scaler, deep_stall).*pref2 G_p_scaler = (deltastar_p*M^5*se.Ξ”r*Dh)/(r_er^2)*m_corr G_p = _tble_te_p.(freqs, deltastar_p_U, Re_c, St_peak_p, k_1, Ξ”k_1, G_p_scaler, deep_stall).*pref2 G_alpha_scaler_l = (deltastar_s*M^5*se.Ξ”r*Dl)/(r_er^2)*m_corr G_alpha_scaler_h = G_s_scaler G_alpha = _tble_te_alpha.(freqs, Re_c, deltastar_s_U, St_peak_alpha, k_2, G_alpha_scaler_l, G_alpha_scaler_h, deep_stall).*pref2 G_lbl_vs_scaler = (delta_p*M^5*se.Ξ”r*Dh)/(r_er^2) G_lbl_vs = _lbl_vs.(freqs, delta_p_U, St_p_p, g2, g3, G_lbl_vs_scaler) .* pref2 G_teb_vs_scaler = (se.h*(M^5.5)*se.Ξ”r*Dh)/(r_er^2) G_teb_vs = _teb_vs.(freqs, h_U, h_over_deltastar_avg, St_3pp, se.Psi, g4, G_teb_vs_scaler) .* pref2 # Also need the Doppler shift for this source-observer combination. doppler = doppler_factor(se, obs, t_obs) # Get the doppler-shifted time step and proportional bands. dt = se.Δτ/doppler freqs_obs = AcousticMetrics.center_bands(freqs, doppler) @assert AcousticMetrics.freq_scaler(freqs_obs) β‰ˆ doppler # All done. return CombinedNoTipOutput(G_s, G_p, G_alpha, G_lbl_vs, G_teb_vs, freqs_obs, dt, t_obs) end struct CombinedWithTipBroadbandSourceElement{ TDirect<:AbstractDirectivity,TUInduction,TMachCorrection,TDoppler, Tc0,Tnu,TΞ”r,Tchord,Th,TPsi,Ty0dot,Ty1dot,Ty1dot_fluid,TΟ„,TΔτ,Tspan_uvec,Tchord_uvec,Tbl,Tblade_tip } <: AbstractBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler} # Speed of sound, m/s. c0::Tc0 # Kinematic viscosity, m^2/s nu::Tnu # Radial/spanwise length of element, m. Ξ”r::TΞ”r # chord length of element, m. chord::Tchord # Trailing edge thickness, m. h::Th # Solid angle between blade surfaces immediately upstream of the trailing edge, rad. Psi::TPsi # Source position, m. y0dot::Ty0dot # Source velocity, m/s. y1dot::Ty1dot # Fluid velocity, m/s. y1dot_fluid::Ty1dot_fluid # Source time, s. Ο„::TΟ„ # Time step size, i.e. the amount of time this source element "exists" at with these properties, s. Δτ::TΔτ # Radial/spanwise unit vector, aka unit vector aligned with the element's span direction. span_uvec::Tspan_uvec # Chordwise unit vector, aka unit vector aligned with the element's chord line, pointing from leading edge to trailing edge. chord_uvec::Tchord_uvec # Boundary layer struct, i.e. an AbstractBoundaryLayer. bl::Tbl # Blade tip struct, i.e. and AbstractBladeTip blade_tip::Tblade_tip # `Bool` indicating chord_uvecΓ—span_uvec will give a vector pointing from bottom side (usually pressure side) to top side (usually suction side) if `true`, or the opposite if `false`. chord_cross_span_to_get_top_uvec::Bool function CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, Ξ”r, chord, h, Psi, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, blade_tip, chord_cross_span_to_get_top_uvec::Bool) where {TDirect<:AbstractDirectivity,TUInduction,TMachCorrection,TDoppler} return new{ TDirect,TUInduction,TMachCorrection,TDoppler, typeof(c0), typeof(nu), typeof(Ξ”r), typeof(chord), typeof(h), typeof(Psi), typeof(y0dot), typeof(y1dot), typeof(y1dot_fluid), typeof(Ο„), typeof(Δτ), typeof(span_uvec), typeof(chord_uvec), typeof(bl), typeof(blade_tip) }(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), use the Prandtl-Glauert mach number correction, and Doppler-shift. function CombinedWithTipBroadbandSourceElement(c0, nu, Ξ”r, chord, h, Psi, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, blade_tip, chord_cross_span_to_get_top_uvec) return CombinedWithTipBroadbandSourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end """ CombinedWithTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) Construct a source element for predicting turbulent boundary layer-trailing edge (TBLTE), laminar boundary layer-vortex shedding (LBLVS) noise, trailing edge bluntness-vortex shedding (TEBVS) noise, and tip vortex noise using the BPM/Brooks and Burley method, using position and velocity data expressed in a cylindrical coordinate system. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. Likewise, the `vn`, `vr`, and `vc` arguments are used to define the normal, radial, and circumferential velocity of the fluid (in a reference frame moving with the element) in the same cylindrical coordinate system. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - h: trailing edge thickness (m) - Psi: solid angle between the blade surfaces immediately upstream of the trailing edge (rad) - vn: normal velocity of fluid (m/s) - vr: radial velocity of fluid (m/s) - vc: circumferential velocity of the fluid (m/s) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - blade_tip: Blade tip struct, i.e. an AbstractBladeTip. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) where {TDirect,TUInduction,TMachCorrection,TDoppler} sΞΈ, cΞΈ = sincos(ΞΈ) sΟ•, cΟ• = sincos(Ο•) y0dot = @SVector [0, r*cΞΈ, r*sΞΈ] T = eltype(y0dot) y1dot = @SVector zeros(T, 3) y1dot_fluid = @SVector [vn, vr*cΞΈ - vc*sΞΈ, vr*sΞΈ + vc*cΞΈ] span_uvec = @SVector [0, cΞΈ, sΞΈ] if twist_about_positive_y chord_uvec = @SVector [-sΟ•, cΟ•*sΞΈ, -cΟ•*cΞΈ] else chord_uvec = @SVector [-sΟ•, -cΟ•*sΞΈ, cΟ•*cΞΈ] end chord_cross_span_to_get_top_uvec = twist_about_positive_y return CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), use the Prandtl-Glauert mach number correction, and Doppler-shift. function CombinedWithTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) return CombinedWithTipBroadbandSourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) end """ CombinedWithTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) Construct a source element for predicting turbulent boundary layer-trailing edge (TBLTE), laminar boundary layer-vortex shedding (LBLVS) noise, trailing edge bluntness-vortex shedding (TEBVS), and tip vortex noise using the BPM/Brooks and Burley method, using the velocity magnitude `U` and angle of attack `Ξ±`. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. The `U` and `Ξ±` arguments are the velocity magnitude normal to the source element length and the angle of attack, respectively. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - h: trailing edge thickness (m) - Psi: solid angle between the blade surfaces immediately upstream of the trailing edge (rad) - U: velocity magnitude (m/s) - Ξ±: angle of attack (rad) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - blade_tip: Blade tip struct, i.e. an AbstractBladeTip - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) where {TDirect,TUInduction,TMachCorrection,TDoppler} precone = 0 pitch = 0 phi = Ο• - Ξ± y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec(Ο•, precone, pitch, r, ΞΈ, U, phi, twist_about_positive_y) return CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), use the PrandtlGlauertMachCorrection, and Doppler-shift. function CombinedWithTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, blade_tip, twist_about_positive_y::Bool) return CombinedWithTipBroadbandSourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) end """ (trans::KinematicTransformation)(se::CombinedWithTipBroadbandSourceElement) Transform the position and orientation of a source element according to the coordinate system transformation `trans`. """ function (trans::KinematicTransformation)(se::CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}) where {TDirect,TUInduction,TMachCorrection,TDoppler} linear_only = false y0dot, y1dot = trans(se.Ο„, se.y0dot, se.y1dot, linear_only) y0dot, y1dot_fluid = trans(se.Ο„, se.y0dot, se.y1dot_fluid, linear_only) linear_only = true span_uvec = trans(se.Ο„, se.span_uvec, linear_only) chord_uvec = trans(se.Ο„, se.chord_uvec, linear_only) return CombinedWithTipBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(se.c0, se.nu, se.Ξ”r, se.chord, se.h, se.Psi, y0dot, y1dot, y1dot_fluid, se.Ο„, se.Δτ, span_uvec, chord_uvec, se.bl, se.blade_tip, se.chord_cross_span_to_get_top_uvec) end """ CombinedWithTipOutput(G_s, G_p, G_alpha, G_teb, G_tip, cbands, dt, t) Output of the combined broadband noise calculation: the acoustic pressure autospectrum centered at time `t` over observer duration `dt` and observer frequencies `cbands` for the TBLTE suction side `G_s`, TBLTE pressure side `G_p`, TBLTE separation noise `G_alpha`, trailing edge bluntness noise `G_teb`, and tip vortex noise `G_tip`. """ struct CombinedWithTipOutput{NO,TF,TG<:AbstractVector{TF},TFreqs<:AcousticMetrics.AbstractProportionalBands{NO,:center},TDTime,TTime} <: AcousticMetrics.AbstractProportionalBandSpectrum{NO,TF} G_s::TG G_p::TG G_alpha::TG G_lblvs::TG G_teb::TG G_tip::TG cbands::TFreqs dt::TDTime t::TTime function CombinedWithTipOutput(G_s::TG, G_p::TG, G_alpha::TG, G_lblvs, G_teb::TG, G_tip::TG, cbands::AcousticMetrics.AbstractProportionalBands{NO,:center}, dt, t) where {NO,TG} ncbands = length(cbands) length(G_s) == ncbands || throw(ArgumentError("length(G_s) must match length(cbands)")) length(G_p) == ncbands || throw(ArgumentError("length(G_p) must match length(cbands)")) length(G_alpha) == ncbands || throw(ArgumentError("length(G_alpha) must match length(cbands)")) length(G_lblvs) == ncbands || throw(ArgumentError("length(G_lblvs) must match length(cbands)")) length(G_teb) == ncbands || throw(ArgumentError("length(G_teb) must match length(cbands)")) length(G_tip) == ncbands || throw(ArgumentError("length(G_tip) must match length(cbands)")) dt > zero(dt) || throw(ArgumentError("dt must be positive")) return new{NO,eltype(TG),TG,typeof(cbands),typeof(dt),typeof(t)}(G_s, G_p, G_alpha, G_lblvs, G_teb, G_tip, cbands, dt, t) end end @inline function Base.getindex(pbs::CombinedWithTipOutput, i::Int) @boundscheck checkbounds(pbs, i) return @inbounds pbs.G_s[i] + pbs.G_p[i] + pbs.G_alpha[i] + pbs.G_teb[i] + pbs.G_tip[i] end @inline AcousticMetrics.has_observer_time(pbs::CombinedWithTipOutput) = true @inline AcousticMetrics.observer_time(pbs::CombinedWithTipOutput) = pbs.t @inline AcousticMetrics.timestep(pbs::CombinedWithTipOutput) = pbs.dt @inline AcousticMetrics.time_scaler(pbs::CombinedWithTipOutput, period) = timestep(pbs)/period function noise(se::CombinedWithTipBroadbandSourceElement, obs::AbstractAcousticObserver, t_obs, freqs::AcousticMetrics.AbstractProportionalBands{3, :center}) # Position of the observer: x_obs = obs(t_obs) # Need the angle of attack. alphastar = angle_of_attack(se) # Need the angle of attack, including the possible tip correction. alphatip = tip_vortex_alpha_correction(se.blade_tip, alphastar) # Need the directivity functions. # But we have two angles of attack: one that includes a tip vortex correction, one that doesn't. # But the angle of attack is only used to determine the value of `top_is_suction`, which in turn only depends on if the angle of attack is greater or less than the zero-lift angle of attack. # And the tip vortex alpha correction is designed to not change that. # So no worries about which alpha to use. top_is_suction = is_top_suction(se.bl, alphastar) r_er, Dl, Dh = directivity(se, x_obs, top_is_suction) # Need the fluid velocity normal to the span. # Brooks and Burley 2001 are a bit ambiguous on whether it should include induction, or just the freestream and rotation. # # * In the nomenclature section: `U` is "flow speed normal to span (`U_mn` with `mn` suppressed). # So that's one point for "no induction." # * In some discussion after equation (8), "The Mach number, `M = U/c0`, represents that component of velocity `U` normal to the span...". # Hard to say one way or the other. # * In equation (12), `U_mn` is the velocity without induction. # So that's another point for "no induction." # * Equation (14) defines `V_tot` as the velocity including the freestream, rotation, and induction. # And then it defines `U` as the part of `V_tot` normal to the span. # So that's a point for "yes induction." # * In the directivity function definitions in equations (19) and (20), `M_tot` is used in the denominator, which seems to make it clear *that* velocity should include induction, since `V_tot` always includes induction. # # So, at the moment, the TBLTESourceElement type has a parameter TUInduction which, when true, will include induction in the flow speed normal to the span, and not otherwise. U = speed_normal_to_span(se) # Reynolds number based on chord and the flow speed normal to span. Re_c = U*se.chord/se.nu # Also need the displacement thicknesses for the pressure and suction sides. deltastar_s = disp_thickness_s(se.bl, Re_c, alphastar)*se.chord deltastar_p = disp_thickness_p(se.bl, Re_c, alphastar)*se.chord # Need the boundary layer thickness for the pressure side for LBL-VS noise. delta_p = bl_thickness_p(se.bl, Re_c, alphastar)*se.chord # Now that we've decided on the directivity functions and the displacement thickness, and we know the correct value of `top_is_suction` we should be able to switch the sign on `alphastar` if it's negative, and reference it to the zero-lift value, as the BPM report does. alphastar_positive = abs_cs_safe(alphastar - alpha_zerolift(se.bl)) # Now that we've decided on the directivity functions and we know the correct value of `top_is_suction` we should be able to switch the sign on `alphastar` if it's negative, and reference it to the zero-lift value, as the BPM report does. alphatip_positive = abs_cs_safe(alphatip - alpha_zerolift(se.bl)) # Mach number of the flow speed normal to span. M = U/se.c0 # This stuff is used to decide if the blade element is stalled or not. alphastar0 = alpha_stall(se.bl, Re_c) gamma0_deg = gamma0(M) deep_stall = (alphastar_positive*180/pi) > min(gamma0_deg, alphastar0*180/pi) # if deep_stall # println("deep_stall! M = $(M), alphastar_positive*180/pi = $(alphastar_positive*180/pi), gamma0_deg = $(gamma0_deg), alphastar0*180/pi = $(alphastar0*180/pi)") # println("forcing deep_stall == false") # deep_stall = false # end St_peak_p = St_1(M) St_peak_alpha = St_2(St_peak_p, alphastar_positive) St_peak_s = 0.5*(St_peak_p + St_peak_alpha) Re_deltastar_p = U*deltastar_p/se.nu k_1 = K_1(Re_c) k_2 = K_2(Re_c, M, alphastar_positive) Ξ”k_1 = DeltaK_1(alphastar_positive, Re_deltastar_p) deltastar_s_U = deltastar_s/U deltastar_p_U = deltastar_p/U # Stuff for LBLVS noise. delta_p_U = delta_p/U St_p_p = St_peak_prime(St_1_prime(Re_c), alphastar_positive) Re_c_over_Re_c0 = Re_c / Re_c0(alphastar_positive) g2 = G2(Re_c_over_Re_c0) g3 = G3(alphastar_positive) # Brooks and Burley 2001 recommend a Prandtl-Glauert style Mach number correction, but only for the TBLTE noise. # But whether or not it's included is dependent on the TMachCorrection type parameter for the source element. m_corr = mach_correction(se, M) # Equation 73 from the BPM report. deltastar_avg = 0.5*(deltastar_p + deltastar_s) h_over_deltastar_avg = se.h/deltastar_avg h_U = se.h/U St_3pp = St_3prime_peak(h_over_deltastar_avg, se.Psi) g4 = G4(h_over_deltastar_avg, se.Psi) # Need the maximum mach number near the tip vortex. M_max = tip_vortex_max_mach_number(se.blade_tip, M, alphatip_positive) # Now we can find the maximum speed near the tip vortex. U_max = M_max * se.c0 # Get the tip vortex size. l = tip_vortex_size_c(se.blade_tip, alphatip_positive) * se.chord # The Brooks and Burley autospectrums appear to be scaled by the usual squared reference pressure (20 ΞΌPa)^2, but I'd like things in dimensional units, so multiply through by that. pref2 = 4e-10 G_s_scaler = (deltastar_s*M^5*se.Ξ”r*Dh)/(r_er^2)*m_corr G_s = _tble_te_s.(freqs, deltastar_s_U, Re_c, St_peak_s, k_1, G_s_scaler, deep_stall).*pref2 G_p_scaler = (deltastar_p*M^5*se.Ξ”r*Dh)/(r_er^2)*m_corr G_p = _tble_te_p.(freqs, deltastar_p_U, Re_c, St_peak_p, k_1, Ξ”k_1, G_p_scaler, deep_stall).*pref2 G_alpha_scaler_l = (deltastar_s*M^5*se.Ξ”r*Dl)/(r_er^2)*m_corr G_alpha_scaler_h = G_s_scaler G_alpha = _tble_te_alpha.(freqs, Re_c, deltastar_s_U, St_peak_alpha, k_2, G_alpha_scaler_l, G_alpha_scaler_h, deep_stall).*pref2 G_lbl_vs_scaler = (delta_p*M^5*se.Ξ”r*Dh)/(r_er^2) G_lbl_vs = _lbl_vs.(freqs, delta_p_U, St_p_p, g2, g3, G_lbl_vs_scaler) .* pref2 G_teb_vs_scaler = (se.h*(M^5.5)*se.Ξ”r*Dh)/(r_er^2) G_teb_vs = _teb_vs.(freqs, h_U, h_over_deltastar_avg, St_3pp, se.Psi, g4, G_teb_vs_scaler) .* pref2 l_U_max = l/U_max G_tip_scaler = (M^2*M_max^3*l^2*Dh/r_er^2) G_tip = _tip.(freqs, l_U_max, G_tip_scaler) .* pref2 # Also need the Doppler shift for this source-observer combination. doppler = doppler_factor(se, obs, t_obs) # Get the doppler-shifted time step and proportional bands. dt = se.Δτ/doppler freqs_obs = AcousticMetrics.center_bands(freqs, doppler) # @assert AcousticMetrics.freq_scaler(freqs_obs) β‰ˆ doppler # All done. return CombinedWithTipOutput(G_s, G_p, G_alpha, G_lbl_vs, G_teb_vs, G_tip, freqs_obs, dt, t_obs) end function pbs_suction(pbs::Union{TBLTEOutput,CombinedNoTipOutput,CombinedWithTipOutput}) t = AcousticMetrics.observer_time(pbs) dt = AcousticMetrics.timestep(pbs) cbands = AcousticMetrics.center_bands(pbs) return AcousticMetrics.ProportionalBandSpectrumWithTime(pbs.G_s, cbands, dt, t) end function pbs_pressure(pbs::Union{TBLTEOutput,CombinedNoTipOutput,CombinedWithTipOutput}) t = AcousticMetrics.observer_time(pbs) dt = AcousticMetrics.timestep(pbs) cbands = AcousticMetrics.center_bands(pbs) return AcousticMetrics.ProportionalBandSpectrumWithTime(pbs.G_p, cbands, dt, t) end function pbs_alpha(pbs::Union{TBLTEOutput,CombinedNoTipOutput,CombinedWithTipOutput}) t = AcousticMetrics.observer_time(pbs) dt = AcousticMetrics.timestep(pbs) cbands = AcousticMetrics.center_bands(pbs) return AcousticMetrics.ProportionalBandSpectrumWithTime(pbs.G_alpha, cbands, dt, t) end function pbs_lblvs(pbs::Union{TBLTEOutput,CombinedNoTipOutput,CombinedWithTipOutput}) t = AcousticMetrics.observer_time(pbs) dt = AcousticMetrics.timestep(pbs) cbands = AcousticMetrics.center_bands(pbs) return AcousticMetrics.ProportionalBandSpectrumWithTime(pbs.G_lblvs, cbands, dt, t) end function pbs_teb(pbs::Union{CombinedNoTipOutput,CombinedWithTipOutput}) t = AcousticMetrics.observer_time(pbs) dt = AcousticMetrics.timestep(pbs) cbands = AcousticMetrics.center_bands(pbs) return AcousticMetrics.ProportionalBandSpectrumWithTime(pbs.G_teb, cbands, dt, t) end function pbs_tip(pbs::CombinedWithTipOutput) t = AcousticMetrics.observer_time(pbs) dt = AcousticMetrics.timestep(pbs) cbands = AcousticMetrics.center_bands(pbs) return AcousticMetrics.ProportionalBandSpectrumWithTime(pbs.G_tip, cbands, dt, t) end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
674
const CompactSourceElement = CompactF1ASourceElement Base.@deprecate CompactSourceElement CompactF1ASourceElement Base.@deprecate f1a(se::CompactF1ASourceElement, obs::AbstractAcousticObserver, t_obs) noise(se::CompactF1ASourceElement, obs::AbstractAcousticObserver, t_obs) Base.@deprecate f1a(se::CompactF1ASourceElement, obs::AbstractAcousticObserver) noise(se::CompactF1ASourceElement, obs::AbstractAcousticObserver) Base.@deprecate source_elements_ccblade(rotor, sections, ops, outputs, area_per_chord2, period, num_src_times, positive_x_rotation) f1a_source_elements_ccblade(rotor, sections, ops, outputs, area_per_chord2, period, num_src_times, positive_x_rotation)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
17163
struct CompactF1ASourceElement{ Tρ0,Tc0,TΞ”r,TΞ›,Ty0dot,Ty1dot,Ty2dot,Ty3dot,Tf0dot,Tf1dot,TΟ„,Tspan_uvec } <: AbstractCompactSourceElement # Density. ρ0::Tρ0 # Speed of sound. c0::Tc0 # Radial length of element. Ξ”r::TΞ”r # Cross-sectional area. Ξ›::TΞ› # Source position and its time derivatives. y0dot::Ty0dot y1dot::Ty1dot y2dot::Ty2dot y3dot::Ty3dot # Load *on the fluid*, and its time derivative. f0dot::Tf0dot f1dot::Tf1dot # Source time. Ο„::TΟ„ # orientation of the element. Only used for WriteVTK. span_uvec::Tspan_uvec end """ CompactF1ASourceElement(ρ0, c0, r, ΞΈ, Ξ”r, Ξ›, fn, fr, fc, Ο„) Construct a source element to be used with the compact form of Farassat's formulation 1A, using position and loading data expressed in a cylindrical coordinate system. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. Likewise, the `fn`, `fr`, and `fc` arguments are used to define the normal, radial, and circumferential loading per unit span *on the fluid* (in a reference frame moving with the element) in the same cylindrical coordinate system. The cylindrical coordinate system is defined as follows: * The normal axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - ρ0: Ambient air density (kg/m^3) - c0: Ambient speed of sound (m/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - Ξ›: cross-sectional area of the element (m^2) - fn: normal load per unit span *on the fluid* (N/m) - fr: radial load *on the fluid* (N/m) - fc: circumferential load *on the fluid* (N/m) - Ο„: source time (s) """ function CompactF1ASourceElement(ρ0, c0, r, ΞΈ, Ξ”r, Ξ›, fn, fr, fc, Ο„) s, c = sincos(ΞΈ) y0dot = @SVector [0, r*c, r*s] T = eltype(y0dot) y1dot = @SVector zeros(T, 3) y2dot = @SVector zeros(T, 3) y3dot = @SVector zeros(T, 3) f0dot = @SVector [fn, c*fr - s*fc, s*fr + c*fc] T = eltype(f0dot) f1dot = @SVector zeros(T, 3) span_uvec = @SVector [0, c, s] return CompactF1ASourceElement(ρ0, c0, Ξ”r, Ξ›, y0dot, y1dot, y2dot, y3dot, f0dot, f1dot, Ο„, span_uvec) end """ CompactF1ASourceElement(ρ0, c0, r, ΞΈ, Ξ”r, Ξ›, fn, fndot, fr, frdot, fc, fcdot, Ο„) Construct a source element to be used with the compact form of Farassat's formulation 1A, using position and loading data expressed in a cylindrical coordinate system. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. Likewise, the `fn`, `fr`, and `fc` arguments are used to define the normal, radial, and circumferential loading per unit span *on the fluid* (in a reference frame moving with the element) in the same cylindrical coordinate system. The `fndot`, `frdot`, and `fcdot` arguments are the time-derivative of the normal, radial, and circumferential loading per unit span, again *on the fluid* and in a reference frame moving with the element, in the cylindrical coordinate system. The cylindrical coordinate system is defined as follows: * The normal axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - ρ0: Ambient air density (kg/m^3) - c0: Ambient speed of sound (m/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - Ξ›: cross-sectional area of the element (m^2) - fn: normal load per unit span *on the fluid* (N/m) - fndot: time derivative of the normal load per unit span *on the fluid* (N/(m*s)) - fr: radial load *on the fluid* (N/m) - frdot: time derivative of the radial load *on the fluid* (N/(m*s)) - fc: circumferential load *on the fluid* (N/m) - fcdot: time derivative of the circumferential load *on the fluid* (N/(m*s)) - Ο„: source time (s) """ function CompactF1ASourceElement(ρ0, c0, r, ΞΈ, Ξ”r, Ξ›, fn, fndot, fr, frdot, fc, fcdot, Ο„) s, c = sincos(ΞΈ) y0dot = @SVector [0, r*c, r*s] T = eltype(y0dot) y1dot = @SVector zeros(T, 3) y2dot = @SVector zeros(T, 3) y3dot = @SVector zeros(T, 3) f0dot = @SVector [fn, c*fr - s*fc, s*fr + c*fc] f1dot = @SVector [fndot, c*frdot - s*fcdot, s*frdot + c*fcdot] span_uvec = @SVector [0, c, s] return CompactF1ASourceElement(ρ0, c0, Ξ”r, Ξ›, y0dot, y1dot, y2dot, y3dot, f0dot, f1dot, Ο„, span_uvec) end """ (trans::KinematicTransformation)(se::CompactF1ASourceElement) Transform the position and forces of a source element according to the coordinate system transformation `trans`. """ function (trans::KinematicTransformation)(se::CompactF1ASourceElement) linear_only = false y0dot, y1dot, y2dot, y3dot = trans(se.Ο„, se.y0dot, se.y1dot, se.y2dot, se.y3dot, linear_only) linear_only = true f0dot, f1dot= trans(se.Ο„, se.f0dot, se.f1dot, linear_only) span_uvec = trans(se.Ο„, se.span_uvec, linear_only) return CompactF1ASourceElement(se.ρ0, se.c0, se.Ξ”r, se.Ξ›, y0dot, y1dot, y2dot, y3dot, f0dot, f1dot, se.Ο„, span_uvec) end """ Output of the F1A calculation: the acoustic pressure value at time `t`, broken into monopole component `p_m` and dipole component `p_d`. """ struct F1AOutput{Tt,Tp_m,Tp_d} t::Tt p_m::Tp_m p_d::Tp_d end """ noise(se::CompactF1ASourceElement, obs::AbstractAcousticObserver, t_obs) Calculate the acoustic pressure emitted by source element `se` and recieved by observer `obs` at time `t_obs`, returning an [`F1AOutput`](@ref) object. The correct value for `t_obs` can be found using [`adv_time`](@ref). """ function noise(se::CompactF1ASourceElement, obs::AbstractAcousticObserver, t_obs) x_obs = obs(t_obs) rv = x_obs .- se.y0dot r = norm_cs_safe(rv) rhat = rv/r rv1dot = -se.y1dot r1dot = dot_cs_safe(rhat, rv1dot) rv2dot = -se.y2dot r2dot = (dot_cs_safe(rv1dot, rv1dot) + dot_cs_safe(rv, rv2dot) - r1dot*r1dot)/r rv3dot = -se.y3dot Mr = dot_cs_safe(-rv1dot/se.c0, rhat) rhat1dot = -1.0/(r*r)*r1dot*rv + 1.0/r*rv1dot Mr1dot = (dot_cs_safe(rv2dot, rhat) + dot_cs_safe(rv1dot, rhat1dot))/(-se.c0) rhat2dot = (2.0/(r^3)*r1dot*r1dot*rv .- 1.0/(r^2)*r2dot*rv .- 2.0/(r^2)*r1dot*rv1dot .+ 1.0/r*rv2dot) Mr2dot = (dot_cs_safe(rv3dot, rhat) .+ 2.0*dot_cs_safe(rv2dot, rhat1dot) .+ dot_cs_safe(rv1dot, rhat2dot))/(-se.c0) # Rnm = r^(-n)*(1.0 - Mr)^(-m) R10 = 1.0/r R01 = 1.0/(1.0 - Mr) R11 = R10*R01 R02 = R01*R01 R21 = R11*R10 # Rnm1dot = d/dt(Rnm) = (-n*R10*r1dot + m*R01*Mr1dot)*Rnm R10dot = -R10*r1dot*R10 R01dot = R01*Mr1dot*R01 R11dot = (-R10*r1dot + R01*Mr1dot)*R11 R11dotdot = (-R10dot*r1dot - R10*r2dot + R01dot*Mr1dot + R01*Mr2dot)*R11 + (-R10*r1dot + R01*Mr1dot)*R11dot # Monopole coefficient. C1A = R02*R11dotdot + R01*R01dot*R11dot # Monople acoustic pressure! p_m = se.ρ0/(4.0*pi)*se.Ξ›*C1A*se.Ξ”r # Dipole coefficients. D1A = R01*R11*rhat E1A = R01*(R11dot*rhat + R11*rhat1dot) + se.c0*R21*rhat # Dipole acoustic pressure! p_d = (dot_cs_safe(se.f1dot, D1A) + dot_cs_safe(se.f0dot, E1A))*se.Ξ”r/(4.0*pi*se.c0) return F1AOutput(t_obs, p_m, p_d) end """ noise(se::CompactF1ASourceElement, obs::AbstractAcousticObserver) Calculate the acoustic pressure emitted by source element `se` and recieved by observer `obs`, returning an [`F1AOutput`](@ref) object. """ function noise(se::CompactF1ASourceElement, obs::AbstractAcousticObserver) t_obs = adv_time(se, obs) return noise(se, obs, t_obs) end """ common_obs_time(apth::AbstractArray{<:F1AOutput}, period, n, axis=1) Return a suitable time range for the collection of F1A acoustic pressures in `apth`. The time range will begin near the latest start time of the acoustic pressures in `apth`, and be an `AbstractVector` (really a `StepRangeLen`) of size `n` and of time length `period`. `axis` indicates which axis of `apth` the time for a source varies. """ function common_obs_time(apth, period, n, axis=1) # Make a single field struct array that behaves like a time array. 4%-6% # faster than creating the array with getproperty. t_obs = mapview(:t, apth) # Get the first time for all the sources (returns a view β™₯). t_starts = selectdim(t_obs, axis, 1) # Find the latest first time. t_common_start = ksmax(t_starts, 30/period) # Get the common observer time. dt = period/n t_common = t_common_start .+ (0:n-1)*dt return t_common end struct F1APressureTimeHistory{IsEven,Tp_m,Tp_d,Tdt,Tt0} <: AcousticMetrics.AbstractPressureTimeHistory{IsEven} p_m::Tp_m p_d::Tp_d dt::Tdt t0::Tt0 function F1APressureTimeHistory{IsEven}(p_m, p_d, dt, t0) where {IsEven} n_p_m = length(p_m) n_p_d = length(p_d) n_p_m == n_p_d || throw(ArgumentError("length(p_m) is not the same as length(p_d)")) iseven(n_p_m) == IsEven || throw(ArgumentError("IsEven is not consistent with length(p_m) and length(p_d)")) return new{IsEven, typeof(p_m), typeof(p_d), typeof(dt), typeof(t0)}(p_m, p_d, dt, t0) end end function F1APressureTimeHistory(p_m, p_d, dt, t0) ie = iseven(length(p_m)) return F1APressureTimeHistory{ie}(p_m, p_d, dt, t0) end """ F1APressureTimeHistory([T=Float64,] n, dt, t0) Construct an `F1APressureTimeHistory` `struct` suitable for containing an acoustic prediction of length `n`, starting at time `t0` with time step `dt`. """ function F1APressureTimeHistory(::Type{T}, n, dt, t0) where {T} p_m = Vector{T}(undef, n) p_d = Vector{T}(undef, n) return F1APressureTimeHistory{iseven(n)}(p_m, p_d, dt, t0) end function F1APressureTimeHistory(n, dt, t0) p_m = Vector{Float64}(undef, n) p_d = Vector{Float64}(undef, n) return F1APressureTimeHistory{iseven(n)}(p_m, p_d, dt, t0) end """ F1APressureTimeHistory(apth::AbstractArray{<:F1AOutput}, period::AbstractFloat, n::Integer, axis::Integer=1) Construct an `F1APressureTimeHistory` `struct` suitable for containing an acoustic prediction from an array of `F1AOutput` `struct`. The elapsed time and length of the returned `F1APressureTimeHistory` will be `period` and `n`, respectively. `axis` indicates which axis the `apth` `struct`s time varies. (`period`, `n`, `axis` are passed to [`common_obs_time`](@ref).) """ function F1APressureTimeHistory(apth::AbstractArray{<:F1AOutput}, period, n, axis=1) # Get the common observer time. t_common = common_obs_time(apth, period, n, axis) # Allocate output arrays. T = typeof(first(apth).p_m) p_m = Vector{T}(undef, n) T = typeof(first(apth).p_d) p_d = Vector{T}(undef, n) # Create the output apth. dt = step(t_common) t0 = first(t_common) apth_out = F1APressureTimeHistory{iseven(n)}(p_m, p_d, dt, t0) return apth_out end @inline AcousticMetrics.pressure(ap::F1APressureTimeHistory) = ap.p_m + ap.p_d @inline pressure_monopole(ap::F1APressureTimeHistory) = ap.p_m @inline pressure_dipole(ap::F1APressureTimeHistory) = ap.p_d apth_monopole(ap::F1APressureTimeHistory) = AcousticMetrics.PressureTimeHistory(pressure_monopole(ap), AcousticMetrics.timestep(ap), AcousticMetrics.starttime(ap)) apth_dipole(ap::F1APressureTimeHistory) = AcousticMetrics.PressureTimeHistory(pressure_dipole(ap), AcousticMetrics.timestep(ap), AcousticMetrics.starttime(ap)) """ combine!(apth_out::F1APressureTimeHistory, apth::AbstractArray{<:F1AOutput}, time_axis; f_interp=akima) Combine the acoustic pressures of multiple sources (`apth`) into a single acoustic pressure time history `apth_out`. The input acoustic pressures `apth` are interpolated onto the time grid returned by `time(apth_out)`. The interpolation is performed by the function `f_intep(xpt, ypt, x)`, where `xpt` and `ytp` are the input grid and function values, respectively, and `x` is the output grid. `time_axis` is an integer indicating the time_axis of the `apth` array along which time varies. For example, if `time_axis == 1` and `apth` is a three-dimensional array, then `apth[:, i, j]` would be the `F1AOutput` objects of the `i`, `j` source element for all time. But if `time_axis == 3`, then `apth[i, j, :]` would be the `F1AOutput` objects of the `i`, `j` source element for all time. """ function combine!(apth_out, apth, time_axis; f_interp=akima) # This makes no difference compared to passing in a cache (an object with # working arrays that I'd copy stuff to) to this function (sometimes a # speedup of <1%, sometimes a slowdown of <1%). I'm sure it'd be worse if I # didn't pass in the cache. But it's nice to not have to worry about passing # it in. # But now I'm using FlexiMaps.mapview. t_obs = mapview(:t, apth) p_m = mapview(:p_m, apth) p_d = mapview(:p_d, apth) # Unpack the output arrays for clarity. t_common = AcousticMetrics.time(apth_out) p_m_interp = pressure_monopole(apth_out) p_d_interp = pressure_dipole(apth_out) # dimsAPTH = [axes(t_obs)...] dimsAPTH = axes(t_obs) ndimsAPTH = ndims(t_obs) alldims = 1:ndimsAPTH otherdims = setdiff(alldims, time_axis) itershape = tuple(dimsAPTH[otherdims]...) # idx = Any[first(ind) for ind in axes(t_obs)] # idx[time_axis] = Colon() # Create an array we'll use to index pbs_in, with a `Colon()` for the time_axis position and integers of the first value for all the others. idx = [ifelse(d==time_axis, Colon(), first(ind)) for (d, ind) in enumerate(axes(t_obs))] nidx = length(otherdims) indices = CartesianIndices(itershape) # Zero out the output arrays. fill!(p_m_interp, zero(eltype(p_m_interp))) fill!(p_d_interp, zero(eltype(p_d_interp))) # Loop through the indices. for I in indices for i in 1:nidx idx[otherdims[i]] = I.I[i] end # Now I have the current indices of the source that I want to interpolate. # p_m_interp .+= f_interp(t_obs[idx...], p_m[idx...], t_common) # p_d_interp .+= f_interp(t_obs[idx...], p_d[idx...], t_common) # Let's be cool and use views. t_obs_v = @view t_obs[idx...] p_m_v = @view p_m[idx...] p_d_v = @view p_d[idx...] p_m_interp .+= f_interp(t_obs_v, p_m_v, t_common) p_d_interp .+= f_interp(t_obs_v, p_d_v, t_common) end return apth_out end """ combine(apth::AbstractArray{<:F1AOutput}, period::AbstractFloat, n::Integer, time_axis=1; f_interp=akima) Combine the acoustic pressures of multiple sources (`apth`) into a single acoustic pressure time history on a time grid of size `n` extending over time length `period`. `time_axis` is an integer indicating the time_axis of the `apth` array along which time varies. For example, if `time_axis == 1` and `apth` is a three-dimensional array, then `apth[:, i, j]` would be the `F1AOutput` objects of the `i`, `j` source element for all time. But if `time_axis == 3`, then `apth[i, j, :]` would be the `F1AOutput` objects of the `i`, `j` source element for all time. """ function combine(apth, period, n::Integer, axis::Integer=1; f_interp=akima) # Get the common observer time. t_common = common_obs_time(apth, period, n, axis) # Construct a julienned array that will give me the time history of each source when we iterate over it. alongs = (d == axis ? JuliennedArrays.True() : JuliennedArrays.False() for d in 1:ndims(apth)) apth_ja = JuliennedArrays.Slices(apth, alongs...) p_m_interp = mapreduce(+, apth_ja) do p t_obs = mapview(:t, p) p_m = mapview(:p_m, p) out = f_interp(t_obs, p_m, t_common) return out end p_d_interp = mapreduce(+, apth_ja) do p t_obs = mapview(:t, p) p_d = mapview(:p_d, p) out = f_interp(t_obs, p_d, t_common) return out end return F1APressureTimeHistory(p_m_interp, p_d_interp, step(t_common), first(t_common)) end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
18079
function St_1_prime(Re_c) # Equation 55 in the BPM report. T = typeof(Re_c) if Re_c ≀ 1.3e5 return 0.18*one(T) elseif Re_c ≀ 4.0e5 return 0.001756*Re_c^(0.3931) else return 0.28*one(T) end end function St_peak_prime(St_1_p, alphastar) # Equation 56 in the BPM report. alphastar_deg = alphastar*180/pi return St_1_p*10.0^(-0.04*alphastar_deg) end function G1(St_prime_over_St_peak_prime) # Equation 57 in the BPM report. e = St_prime_over_St_peak_prime if e ≀ 0.5974 return 39.8*log10(e) - 11.12 elseif e ≀ 0.8545 98.409*log10(e) + 2.0 elseif e ≀ 1.17 return -5.076 + sqrt(2.484 - 506.25*log10(e)^2) elseif e ≀ 1.674 return -98.409*log10(e) + 2.0 else return -39.8*log10(e) - 11.12 end end function Re_c0(alphastar) # Equation 59 in the BPM report. alphastar_deg = alphastar*180/pi if alphastar_deg ≀ 3.0 return 10.0^(0.215*alphastar_deg + 4.978) else return 10.0^(0.120*alphastar_deg + 5.263) end end function G2(Re_c_over_Re_c0) # Equation 58 in the BPM report. d = Re_c_over_Re_c0 if d ≀ 0.3237 return 77.852*log10(d) + 15.328 elseif d ≀ 0.5689 return 65.188*log10(d) + 9.125 elseif d ≀ 1.7579 return -114.052*log10(d)^2 elseif d ≀ 3.0889 return -65.188*log10(d) + 9.125 else return -77.852*log10(d) + 15.328 end end function G3(alphastar) alphastar_deg = alphastar*180/pi return 171.04 - 3.03*alphastar_deg end function LBL_VS(freq, nu, L, chord, U, M, M_c, r_e, theta_e, phi_e, alphastar, bl) Re_c = U*chord/nu delta_p = bl_thickness_p(bl, Re_c, alphastar)*chord # Equation (54) from the BPM report. St_prime = freq*delta_p/U St_p_p = St_peak_prime(St_1_prime(Re_c), alphastar) St_prime_over_St_peak_prime = St_prime/St_p_p Re_c_over_Re_c0 = Re_c / Re_c0(alphastar) # SPL = 10*log10(delta_p*M^5*L*Dbar_h(theta_e, phi_e, M, M_c)/r_e^2) + G1(St_prime_over_St_peak_prime) + G2(Re_c_over_Re_c0) + G3(alphastar) # Brooks and Burley AIAA 2001-2210 style. H_l = 10^(0.1*(G1(St_prime_over_St_peak_prime) + G2(Re_c_over_Re_c0) + G3(alphastar))) G_lbl_vs = (delta_p*M^5*L*Dbar_h(theta_e, phi_e, M, M_c))/(r_e^2)*H_l SPL = 10*log10(G_lbl_vs) return SPL end struct LBLVSSourceElement{ TDirect<:AbstractDirectivity,TUInduction,TDoppler, Tc0,Tnu,TΞ”r,Tchord,Ty0dot,Ty1dot,Ty1dot_fluid,TΟ„,TΔτ,Tspan_uvec,Tchord_uvec,Tbl } <: AbstractBroadbandSourceElement{TDirect,TUInduction,NoMachCorrection,TDoppler} # Speed of sound, m/s. c0::Tc0 # Kinematic viscosity, m^2/s nu::Tnu # Radial/spanwise length of element, m. Ξ”r::TΞ”r # chord length of element, m. chord::Tchord # Source position, m. y0dot::Ty0dot # Source velocity, m/s. y1dot::Ty1dot # Fluid velocity, m/s. y1dot_fluid::Ty1dot_fluid # Source time, s. Ο„::TΟ„ # Time step size, i.e. the amount of time this source element "exists" with these properties, s. Δτ::TΔτ # Radial/spanwise unit vector, aka unit vector aligned with the element's span direction. span_uvec::Tspan_uvec # Chordwise unit vector, aka unit vector aligned with the element's chord line, pointing from leading edge to trailing edge. chord_uvec::Tchord_uvec # Boundary layer struct, i.e. an AbstractBoundaryLayer. bl::Tbl # `Bool` indicating chord_uvecΓ—span_uvec will give a vector pointing from bottom side (usually pressure side) to top side (usually suction side) if `true`, or the opposite if `false`. chord_cross_span_to_get_top_uvec::Bool function LBLVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, Ξ”r, chord, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, chord_cross_span_to_get_top_uvec::Bool) where {TDirect<:AbstractDirectivity,TUInduction,TDoppler} return new{ TDirect,TUInduction,TDoppler, typeof(c0), typeof(nu), typeof(Ξ”r), typeof(chord), typeof(y0dot), typeof(y1dot), typeof(y1dot_fluid), typeof(Ο„), typeof(Δτ), typeof(span_uvec), typeof(chord_uvec), typeof(bl) }(c0, nu, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), and Doppler-shift. function LBLVSSourceElement(c0, nu, Ξ”r, chord, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, chord_cross_span_to_get_top_uvec) return LBLVSSourceElement{BrooksBurleyDirectivity,true,true}(c0, nu, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end """ LBLVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) Construct a source element for predicting laminar boundary layer-vortex shedding (LBLVS) noise using the BPM/Brooks and Burley method, using position and velocity data expressed in a cylindrical coordinate system. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. Likewise, the `vn`, `vr`, and `vc` arguments are used to define the normal, radial, and circumferential velocity of the fluid (in a reference frame moving with the element) in the same cylindrical coordinate system. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - vn: normal velocity of fluid (m/s) - vr: radial velocity of fluid (m/s) - vc: circumferential velocity of the fluid (m/s) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function LBLVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) where {TDirect,TUInduction,TDoppler} sΞΈ, cΞΈ = sincos(ΞΈ) sΟ•, cΟ• = sincos(Ο•) y0dot = @SVector [0, r*cΞΈ, r*sΞΈ] T = eltype(y0dot) y1dot = @SVector zeros(T, 3) y1dot_fluid = @SVector [vn, vr*cΞΈ - vc*sΞΈ, vr*sΞΈ + vc*cΞΈ] span_uvec = @SVector [0, cΞΈ, sΞΈ] if twist_about_positive_y chord_uvec = @SVector [-sΟ•, cΟ•*sΞΈ, -cΟ•*cΞΈ] else chord_uvec = @SVector [-sΟ•, -cΟ•*sΞΈ, cΟ•*cΞΈ] end chord_cross_span_to_get_top_uvec = twist_about_positive_y return LBLVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), and Doppler-shift. function LBLVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) return LBLVSSourceElement{BrooksBurleyDirectivity,true,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) end """ LBLVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) Construct a source element for predicting laminar boundary layer-vortex shedding (LBLVS) noise using the BPM/Brooks and Burley method, using the velocity magnitude `U` and angle of attack `Ξ±`. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. The `U` and `Ξ±` arguments are the velocity magnitude normal to the source element length and the angle of attack, respectively. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - U: velocity magnitude (m/s) - Ξ±: angle of attack (rad) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function LBLVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) where {TDirect,TUInduction,TDoppler} precone = 0 pitch = 0 phi = Ο• - Ξ± y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec(Ο•, precone, pitch, r, ΞΈ, U, phi, twist_about_positive_y::Bool) return LBLVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), and Doppler-shift. function LBLVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) return LBLVSSourceElement{BrooksBurleyDirectivity,true,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) end """ (trans::KinematicTransformation)(se::LBLVSSourceElement) Transform the position and orientation of a source element according to the coordinate system transformation `trans`. """ function (trans::KinematicTransformation)(se::LBLVSSourceElement{TDirect,TUInduction,TDoppler}) where {TDirect,TUInduction,TDoppler} linear_only = false y0dot, y1dot = trans(se.Ο„, se.y0dot, se.y1dot, linear_only) y0dot, y1dot_fluid = trans(se.Ο„, se.y0dot, se.y1dot_fluid, linear_only) linear_only = true span_uvec = trans(se.Ο„, se.span_uvec, linear_only) chord_uvec = trans(se.Ο„, se.chord_uvec, linear_only) return LBLVSSourceElement{TDirect,TUInduction,TDoppler}(se.c0, se.nu, se.Ξ”r, se.chord, y0dot, y1dot, y1dot_fluid, se.Ο„, se.Δτ, span_uvec, chord_uvec, se.bl, se.chord_cross_span_to_get_top_uvec) end function _lbl_vs(freq, delta_p_U, St_p_p, g2, g3, scaler) # St_prime = freq*deltastar_p/U # St_prime_over_St_peak_prime = St_prime/St_p_p # H_l = 10^(0.1*(G1(St_prime_over_St_peak_prime) + g2 + g3)) St_prime = freq*delta_p_U St_prime_over_St_peak_prime = St_prime/St_p_p # return 10^(0.1*(G1(St_prime_over_St_peak_prime) + g2 + g3)) H_l = 10^(0.1*(G1(St_prime_over_St_peak_prime) + g2 + g3)) # G_lbl_vs = (deltastar_p*M^5*Ξ”r*Dh)/(r_er^2)*H_l G_lbl_vs = scaler*H_l # LBLVS = 10.0*log10((dpr*M^5*L*Dh)/rc^2)+G1+G2+G3 # 10*log10((deltastar_p*M^5*Ξ”r*Dh)/(r_er^2)*(10^(0.1*(G1(St_prime_over_St_peak_prime) + g2 + g3))) # 10*log10((deltastar_p*M^5*Ξ”r*Dh)/(r_er^2)) + 10*log10((10^(0.1*(G1(St_prime_over_St_peak_prime) + g2 + g3)))) # 10*log10((deltastar_p*M^5*Ξ”r*Dh)/(r_er^2)) + 10*(0.1*(G1(St_prime_over_St_peak_prime) + g2 + g3)) # 10*log10((deltastar_p*M^5*Ξ”r*Dh)/(r_er^2)) + G1(St_prime_over_St_peak_prime) + g2 + g3 return G_lbl_vs end function noise(se::LBLVSSourceElement, obs::AbstractAcousticObserver, t_obs, freqs::AcousticMetrics.AbstractProportionalBands{3, :center}) # Position of the observer: x_obs = obs(t_obs) # Need the angle of attack. alphastar = angle_of_attack(se) # Need the directivity functions. top_is_suction = is_top_suction(se.bl, alphastar) r_er, Dl, Dh = directivity(se, x_obs, top_is_suction) # Need the fluid velocity normal to the span. # Brooks and Burley 2001 are a bit ambiguous on whether it should include induction, or just the freestream and rotation. # # * In the nomenclature section: `U` is "flow speed normal to span (`U_mn` with `mn` suppressed). # So that's one point for "no induction." # * In some discussion after equation (8), "The Mach number, `M = U/c0`, represents that component of velocity `U` normal to the span...". # Hard to say one way or the other. # * In equation (12), `U_mn` is the velocity without induction. # So that's another point for "no induction." # * Equation (14) defines `V_tot` as the velocity including the freestream, rotation, and induction. # And then it defines `U` as the part of `V_tot` normal to the span. # So that's a point for "yes induction." # * In the directivity function definitions in equations (19) and (20), `M_tot` is used in the denominator, which seems to make it clear *that* velocity should include induction, since `V_tot` always includes induction. # # So, at the moment, the TBLTESourceElement type has a parameter TUInduction which, when true, will include induction in the flow speed normal to the span, and not otherwise. U = speed_normal_to_span(se) # Reynolds number based on chord and the flow speed normal to span. Re_c = U*se.chord/se.nu # Need the boundary layer thickness for the pressure side for LBL-VS noise. # deltastar_p = disp_thickness_p(se.bl, Re_c, alphastar)*se.chord delta_p = bl_thickness_p(se.bl, Re_c, alphastar)*se.chord # Now that we've decided on the directivity functions and the displacement thickness, and we know the correct value of `top_is_suction` we should be able to switch the sign on `alphastar` if it's negative, and reference it to the zero-lift value, as the BPM report does. alphastar_positive = abs_cs_safe(alphastar - alpha_zerolift(se.bl)) # Mach number of the flow speed normal to span. M = U/se.c0 delta_p_U = delta_p/U St_p_p = St_peak_prime(St_1_prime(Re_c), alphastar_positive) Re_c_over_Re_c0 = Re_c / Re_c0(alphastar_positive) g2 = G2(Re_c_over_Re_c0) g3 = G3(alphastar_positive) # The Brooks and Burley autospectrums appear to be scaled by the usual squared reference pressure (20 ΞΌPa)^2, but I'd like things in dimensional units, so multiply through by that. pref2 = 4e-10 # G = (delta_p*M^5*se.Ξ”r*Dh)/(r_er^2) .* _Hl.(freq, delta_p_U, St_p_p, g2, g3) .* pref2 G_lbl_vs_scaler = (delta_p*M^5*se.Ξ”r*Dh)/(r_er^2) G_lbl_vs = _lbl_vs.(freqs, delta_p_U, St_p_p, g2, g3, G_lbl_vs_scaler) .* pref2 # Also need the Doppler shift for this source-observer combination. doppler = doppler_factor(se, obs, t_obs) # Get the doppler-shifted time step and proportional bands. dt = se.Δτ/doppler freqs_obs = AcousticMetrics.center_bands(freqs, doppler) # All done. return AcousticMetrics.ProportionalBandSpectrumWithTime(G_lbl_vs, freqs_obs, dt, t_obs) end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
1346
""" Supertype for an object that recieves a noise prediction when combined with an acoustic analogy source; computational equivalent of a microphone. (obs::AbstractAcousticObserver)(t) Calculate the position of the acoustic observer at time `t`. """ abstract type AbstractAcousticObserver end """ StationaryAcousticObserver(x) Construct an acoustic observer that does not move with position `x` (m). """ struct StationaryAcousticObserver{Tx} <: AbstractAcousticObserver x::Tx end """ velocity(t_obs, obs::StationaryAcousticObserver) Return the velocity of `obs` at time `t_obs` (hintβ€”will always be zero ☺) """ @inline velocity(t_obs, obs::StationaryAcousticObserver) = zero(obs.x) """ ConstVelocityAcousticObserver(t0, x0, v) Construct an acoustic observer moving with a constant velocity `v`, located at `x0` at time `t0`. """ struct ConstVelocityAcousticObserver{Tt0,Tx0,Tv} <: AbstractAcousticObserver t0 ::Tt0 x0::Tx0 v::Tv end function (obs::StationaryAcousticObserver)(t) return obs.x end function (obs::ConstVelocityAcousticObserver)(t) return obs.x0 .+ (t - obs.t0).*obs.v end """ velocity(t_obs, obs::ConstVelocityAcousticObserver) Return the velocity of `obs` at time `t_obs` (hintβ€”will always be the same) """ @inline velocity(t_obs, obs::ConstVelocityAcousticObserver) = obs.v
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
32945
abstract type AbstractTimeDerivMethod end struct NoTimeDerivMethod <: AbstractTimeDerivMethod end struct SecondOrderFiniteDiff <: AbstractTimeDerivMethod end abstract type AbstractRadialInterpMethod end struct FLOWLinearInterp <: AbstractRadialInterpMethod end struct FLOWAkimaInterp <: AbstractRadialInterpMethod end """ Struct for holding data from an OpenFAST (AeroDyn?) output file. # Fields: * `time`: vector of simulation times with size `(num_times,)` * `dtime_dtau`: vector of derivative of simulation times with respect to non-dimensional/computational time with size `(num_times,)` * `v`: vector of freestream velocity time history with size `(num_times,)` * `azimuth`: vector of azimuth angle time history with size `(num_times,)` * `omega`: vector of rotation rate time history with size `(num_times,)` * `pitch`: array of pitch angle time history with size `(num_times, num_blades)` * `radii`: vector of blade radial locations with size `(num_radial,)` * `radii_mid`: vector of cell-centered/midpoint blade radial locations with size `(num_radial-1,)` * `cs_area`: vector of cross-sectional areas with size `(num_radial,)`. * `cs_area_mid`: vector of cell-centered/midpoint cross-sectional areas with size `(num_radial-1,)`. * `axial_loading`: array of axial loading time history with size `(num_times, num_radial, num_blades)` * `axial_loading_mid`: array of axial loading time history at cell-centered blade radial locations with size `(num_times, num_radial-1, num_blades)` * `axial_loading_mid_dot`: array of axial loading temporal derivative time history at cell-centered blade radial locations with size `(num_times, num_radial-1, num_blades)` * `circum_loading`: array of circumferential loading time history with size `(num_times, num_radial, num_blades)` * `circum_loading_mid`: array of circum loading time history at cell-centered blade radial locations with size `(num_times, num_radial-1, num_blades)` * `circum_loading_mid_dot`: array of circum loading temporal derivative time history at cell-centered blade radial locations with size `(num_times, num_radial-1, num_blades)` """ struct OpenFASTData{TRadialInterpMethod,TTimeDerivMethod, TTime,TdTimedTau,TV,TAzimuth,TOmega,TPitch, TRadii,TRadiiMid,TDRadii, TCSArea,TCSAreaMid, TAxialLoading,TAxialLoadingMid,TAxialLoadingMidDot, TCircumLoading,TCircumLoadingMid,TCircumLoadingMidDot} time::TTime dtime_dtau::TdTimedTau v::TV azimuth::TAzimuth omega::TOmega pitch::TPitch radii::TRadii radii_mid::TRadiiMid dradii::TDRadii cs_area::TCSArea cs_area_mid::TCSAreaMid axial_loading::TAxialLoading axial_loading_mid::TAxialLoadingMid axial_loading_mid_dot::TAxialLoadingMidDot circum_loading::TCircumLoading circum_loading_mid::TCircumLoadingMid circum_loading_mid_dot::TCircumLoadingMidDot num_blades::Int function OpenFASTData{ TRadialInterpMethod,TTimeDerivMethod, TTime,TdTimedTau,TV,TAzimuth,TOmega,TPitch, TRadii,TRadiiMid,TDRadii, TCSArea,TCSAreaMid, TAxialLoading,TAxialLoadingMid,TAxialLoadingMidDot, TCircumLoading,TCircumLoadingMid,TCircumLoadingMidDot}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot) where { TRadialInterpMethod,TTimeDerivMethod, TTime,TdTimedTau,TV,TAzimuth,TOmega,TPitch, TRadii,TRadiiMid,TDRadii, TCSArea,TCSAreaMid, TAxialLoading,TAxialLoadingMid,TAxialLoadingMidDot, TCircumLoading,TCircumLoadingMid,TCircumLoadingMidDot} num_times = length(time) num_radial = length(radii) num_radial_mid = num_radial - 1 # Figure out what num_blades is. if pitch !== nothing num_blades = size(pitch, 2) elseif axial_loading !== nothing num_blades = size(axial_loading, 3) elseif axial_loading_mid !== nothing num_blades = size(axial_loading_mid, 3) elseif axial_loading_mid_dot !== nothing num_blades = size(axial_loading_mid_dot, 3) elseif circum_loading !== nothing num_blades = size(circum_loading, 3) elseif circum_loading_mid !== nothing num_blades = size(circum_loading_mid, 3) elseif circum_loading_mid_dot !== nothing num_blades = size(circum_loading_mid_dot, 3) else num_blades = 0 end if dtime_dtau !== nothing size(dtime_dtau) == (num_times,) || throw(ArgumentError("size(dtime_dtau) = $(size(dtime_dtau)) does not match size(time) = $(size(time))")) end if v !== nothing size(v) == (num_times,) || throw(ArgumentError("size(v) = $(size(v)) does not match size(time) = $(size(time))")) end if azimuth !== nothing size(azimuth) == (num_times,) || throw(ArgumentError("size(azimuth) = $(size(azimuth)) does not match size(time) = $(size(time))")) end if omega !== nothing size(omega) == (num_times,) || throw(ArgumentError("size(omega) = $(size(omega)) does not match size(time) = $(size(time))")) end if pitch !== nothing size(pitch) == (num_times, num_blades) || throw(ArgumentError("size(pitch) = $(size(pitch)) not consistent with size(time) = $(size(time)) and/or size(axial_loading) = $(size(axial_loading))")) end if radii_mid !== nothing size(radii_mid) == (num_radial_mid,) || throw(ArgumentError("size(radii_mid) = $(size(radii_mid)) not consistent with length(radii)-1 = $(num_radial_mid)")) end if dradii !== nothing size(dradii) == (num_radial_mid,) || throw(ArgumentError("size(dradii) = $(size(dradii)) not consistent with length(radii)-1 = $(num_radial_mid)")) end if cs_area !== nothing size(cs_area) == (num_radial,) || throw(ArgumentError("size(cs_area) = $(size(cs_area)) not consistent with length(radii) = $(num_radial)")) end if cs_area_mid !== nothing size(cs_area_mid) == (num_radial_mid,) || throw(ArgumentError("size(cs_area_mid) = $(size(cs_area_mid)) not consistent with length(radii)-1 = $(num_radial_mid)")) end if axial_loading !== nothing size(axial_loading) == (num_times, num_radial, num_blades) || throw(ArgumentError("size(axial_loading) = $(size(axial_loading)) not consistent with size(time) = $(size(time)), length(radii) = $(num_radial), blade count = $(num_blades)")) end if axial_loading_mid !== nothing size(axial_loading_mid) == (num_times, num_radial_mid, num_blades) || throw(ArgumentError("size(axial_loading_mid) = $(size(axial_loading_mid)) not consistent with size(time) = $(size(time)), length(radii)-1 = $(num_radial_mid), blade count = $(num_blades)")) end if axial_loading_mid_dot !== nothing size(axial_loading_mid_dot) == (num_times, num_radial_mid, num_blades) || throw(ArgumentError("size(axial_loading_mid_dot) = $(size(axial_loading_mid_dot)) not consistent with size(time) = $(size(time)), length(radii)-1 = $(num_radial_mid), blade count = $(num_blades)")) end if circum_loading !== nothing size(circum_loading) == (num_times, num_radial, num_blades) || throw(ArgumentError("size(circum_loading) = $(size(circum_loading)) not consistent with size(time) = $(size(time)), length(radii) = $(num_radial), blade count = $(num_blades)")) end if circum_loading_mid !== nothing size(circum_loading_mid) == (num_times, num_radial_mid, num_blades) || throw(ArgumentError("size(circum_loading_mid) = $(size(circum_loading_mid)) not consistent with size(time) = $(size(time)), length(radii)-1 = $(num_radial_mid), blade count = $(num_blades)")) end if circum_loading_mid_dot !== nothing size(circum_loading_mid_dot) == (num_times, num_radial_mid, num_blades) || throw(ArgumentError("size(circum_loading_mid_dot) = $(size(circum_loading_mid_dot)) not consistent with size(time) = $(size(time)), length(radii)-1 = $(num_radial_mid), blade count = $(num_blades)")) end return new{TRadialInterpMethod,TTimeDerivMethod, typeof(time),typeof(dtime_dtau),typeof(v),typeof(azimuth),typeof(omega),typeof(pitch), typeof(radii),typeof(radii_mid),typeof(dradii), typeof(cs_area),typeof(cs_area_mid), typeof(axial_loading),typeof(axial_loading_mid),typeof(axial_loading_mid_dot), typeof(circum_loading),typeof(circum_loading_mid),typeof(circum_loading_mid_dot)}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot, num_blades) end end function OpenFASTData{TRadialInterpMethod,TTimeDerivMethod}(time, v, azimuth, omega, pitch, radii, cs_area, axial_loading, circum_loading) where {TRadialInterpMethod<:AbstractRadialInterpMethod,TTimeDerivMethod<:AbstractTimeDerivMethod} dtime_dtau = similar(time) # Find the blade element midpoint locations. radii_mid = 0.5 .* (@view(radii[begin:end-1]) .+ @view(radii[begin+1:end])) # Find the radial spacing. dradii = @view(radii[begin+1:end]) .- @view(radii[begin:end-1]) if cs_area !== nothing cs_area_mid = similar(cs_area, length(cs_area)-1) else cs_area_mid = nothing end if axial_loading !== nothing axial_loading_mid = similar(axial_loading, size(axial_loading, 1), size(axial_loading, 2)-1, size(axial_loading, 3)) axial_loading_mid_dot = zero(axial_loading_mid) else axial_loading_mid = axial_loading_mid_dot = nothing end if circum_loading !== nothing circum_loading_mid = similar(circum_loading, size(circum_loading, 1), size(circum_loading, 2)-1, size(circum_loading, 3)) circum_loading_mid_dot = zero(circum_loading_mid) else circum_loading_mid = circum_loading_mid_dot = nothing end return OpenFASTData{TRadialInterpMethod,TTimeDerivMethod}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot) end function OpenFASTData{TRadialInterpMethod,TTimeDerivMethod}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot) where {TRadialInterpMethod,TTimeDerivMethod} return OpenFASTData{TRadialInterpMethod,TTimeDerivMethod, typeof(time),typeof(dtime_dtau),typeof(v),typeof(azimuth),typeof(omega),typeof(pitch), typeof(radii),typeof(radii_mid),typeof(dradii), typeof(cs_area),typeof(cs_area_mid), typeof(axial_loading),typeof(axial_loading_mid),typeof(axial_loading_mid_dot), typeof(circum_loading),typeof(circum_loading_mid),typeof(circum_loading_mid_dot)}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot) end function _get_num_blades(fmt, column_names) # Match the format against the column names. ms = match.(fmt, column_names) # Remove any non-matches, for which `match` returns `nothing`. ms_only_matches = filter(x->!isnothing(x), ms) # Now, get all the sorted, unique blade indices, converting them from strings to Ints. blade_idxs = parse.(Int, unique(sort(getindex.(ms_only_matches, :blade)))) # The blade indices appear to start at 1, so the highest blade index is the number of blades. num_blades = maximum(blade_idxs) # But check that the blade indices are what we assumed. @assert all(blade_idxs .== 1:num_blades) return num_blades, ms_only_matches end function _get_num_blades_num_radial(fmt, column_names) # Let's figure out how many blades and radial stations there are. # First, apply the loading regular expression to each column name: ms = match.(fmt, column_names) # Remove any non-matches, for which `match` returns `nothing`. ms_only_matches = filter(x->!isnothing(x), ms) # Now, get all the sorted, unique blade indices, converting them from strings to Ints. blade_idxs = parse.(Int, unique(sort(getindex.(ms_only_matches, :blade)))) # The blade indices appear to start at 1, so the highest blade index is the number of blades. num_blades = maximum(blade_idxs) # But check that the blade indices are what we assumed. @assert all(blade_idxs .== 1:num_blades) # Now do the same thing for the radial indices. radial_idxs = parse.(Int, unique(sort(getindex.(ms_only_matches, :radial)))) num_radial = maximum(radial_idxs) @assert all(radial_idxs .== 1:num_radial) return num_blades, num_radial, ms_only_matches end function interpolate_to_cell_centers!(data::OpenFASTData{FLOWLinearInterp}) if (data.cs_area !== nothing) && (data.cs_area_mid !== nothing) data.cs_area_mid .= FLOWMath.linear.(Ref(data.radii), Ref(data.cs_area), data.radii_mid) end if (data.axial_loading !== nothing) && (data.axial_loading_mid !== nothing) for bidx in 1:size(data.axial_loading_mid, 3) for tidx in 1:size(data.axial_loading_mid, 1) data.axial_loading_mid[tidx, :, bidx] .= FLOWMath.linear.(Ref(data.radii), Ref(@view(data.axial_loading[tidx, :, bidx])), data.radii_mid) end end end if (data.circum_loading !== nothing) && (data.circum_loading_mid !== nothing) for bidx in 1:size(data.circum_loading_mid, 3) for tidx in 1:size(data.circum_loading_mid, 1) data.circum_loading_mid[tidx, :, bidx] .= FLOWMath.linear.(Ref(data.radii), Ref(@view(data.circum_loading[tidx, :, bidx])), data.radii_mid) end end end return nothing end function interpolate_to_cell_centers!(data::OpenFASTData{FLOWAkimaInterp}) if (data.cs_area !== nothing) && (data.cs_area_mid !== nothing) spline_cs_area = FLOWMath.Akima(data.radii, data.cs_area) data.cs_area_mid .= spline_cs_area.(data.radii_mid) end if (data.axial_loading !== nothing) && (data.axial_loading_mid !== nothing) for bidx in 1:size(data.axial_loading_mid, 3) for tidx in 1:size(data.axial_loading_mid, 1) spline_axial = FLOWMath.Akima(data.radii, @view(data.axial_loading[tidx, :, bidx])) data.axial_loading_mid[tidx, :, bidx] .= spline_axial.(data.radii_mid) end end end if (data.circum_loading !== nothing) && (data.circum_loading_mid !== nothing) for bidx in 1:size(data.circum_loading_mid, 3) for tidx in 1:size(data.circum_loading_mid, 1) spline_circum = FLOWMath.Akima(data.radii, @view(data.circum_loading[tidx, :, bidx])) data.circum_loading_mid[tidx, :, bidx] .= spline_circum.(data.radii_mid) end end end return nothing end function calculate_loading_dot!(data::OpenFASTData{TRadialInterpMethod,NoTimeDerivMethod}) where {TRadialInterpMethod} if data.axial_loading_mid_dot !== nothing fill!(data.axial_loading_mid_dot, 0) end if data.circum_loading_mid_dot !== nothing fill!(data.circum_loading_mid_dot, 0) end return nothing end function _finite_diff_2nd_order!(df_dtau, f) # `f` is the input array, which we assume is of size `(num_times, num_radial, num_blades)`. # `df_dtau` is the derivative wrt `tau`, the non-dimensional time. @views begin # These stencils are in Tannehill, Anderson, Pletcher, "Computational Fluid Mechanics and Heat Transfer," 2nd edition, page 50. # First do the interior points. df_dtau[begin+1:end-1, :, :] .= 0.5 .* (f[begin+2:end, :, :] .- f[begin:end-2, :, :]) # Then the left boundary. df_dtau[begin, :, :] .= 0.5 .* (-3 .* f[begin, :, :] .+ 4 .* f[begin+1, :, :] .- f[begin+2, :, :]) # Then the right boundary. df_dtau[end, :, :] .= 0.5 .* (3 .* f[end, :, :] .- 4 .* f[end-1, :, :] .+ f[end-2, :, :]) end return nothing end function calculate_loading_dot!(data::OpenFASTData{TRadialInterpMethod,SecondOrderFiniteDiff}) where {TRadialInterpMethod} # First get dt/dΟ„. _finite_diff_2nd_order!(data.dtime_dtau, data.time) if (data.axial_loading_mid !== nothing) && (data.axial_loading_mid_dot !== nothing) # Now get the derivatitve of the axial loading wrt tau, the non-dimensional time. _finite_diff_2nd_order!(data.axial_loading_mid_dot, data.axial_loading_mid) # Now get the derivative of the axial loading with respect to the dimensional time via `dfdt = df/dΟ„*dΟ„/dt = (df/dΟ„)/(dt/dΟ„) data.axial_loading_mid_dot ./= data.dtime_dtau end if (data.circum_loading_mid !== nothing) && (data.circum_loading_mid_dot !== nothing) # Now get the derivatitve of the circum loading wrt tau, the non-dimensional time. _finite_diff_2nd_order!(data.circum_loading_mid_dot, data.circum_loading_mid) # Now get the derivative of the circum loading with respect to the dimensional time via `dfdt = df/dΟ„*dΟ„/dt = (df/dΟ„)/(dt/dΟ„) data.circum_loading_mid_dot ./= data.dtime_dtau end return nothing end """ read_openfast_file(fname, radii, cs_area=nothing; header_keyword="Time", has_units_header=true, time_column_name="Time", freestream_vel_column_name="Wind1VelX", azimuth_column_name="Azimuth", omega_column_name="RotSpeed", pitch_fmt=r"BlPitch(?<blade>[[:digit:]]+)", axial_loading_fmt=r"AB(?<blade>[[:digit:]]+)N(?<radial>[[:digit:]]+)Fxl", circum_loading_fmt=r"AB(?<blade>[[:digit:]]+)N(?<radial>[[:digit:]]+)Fyl", radial_interp_method=FLOWLinearInterp, time_deriv_method=SecondOrderFiniteDiff) Read an OpenFAST output file and return a [`OpenFASTData`](@ref) object. The `Azimuth` and `BlPitch` columns are assumed to be in degrees and will be converted to radians. Likewise, the `RotSpeed` column is assumed to be in revolutions per minute and will be converted to radians per second. # Arguments * `fname`: name of the OpenFAST output file to read * `radii`: `Vector` of blade radial coordinates * `cs_area`: `Vector` of radial distribution of cross-sectional areas, or `nothing` to ignore * `header_keyword="Time"`: string at the beginning of the header line (maybe always "Time"?) * `has_units_header=true`: if true, assume the file has a line directly after the header line with the units of each column * `time_column_name=header_keyword`: name of time column in file. Set to `nothing` to skip. * `freestream_vel_column_name`: name of the freestream velocity column in the file. Set to `nothing` to skip. * `azimuth_column_name`: name of the azimuth column in the file. Set to `nothing` to skip. * `omega_column_name`: name of the omega (rotation rate) Set to `nothing` to skip. * `pitch_fmt`: Format for finding all pitch columns in the file. Should be a regex with a capture group named `blade` for the blade index, or `nothing` to skip. * `axial_loading_fmt`: Format for finding all axial loading columns in the file. Should be a regex with a captures groups named `blade` and `radial` for the blade and radial indices, or `nothing` to skip. * `circum_loading_fmt`: Format for finding all radial loading columns in the file. Should be a regex with a captures groups named `blade` and `radial` for the blade and radial indices, or `nothing` to skip. * `radial_interp_method`: `<:AbstractRadialInterpMethod` indicating method used to interpolate loading from blade element "interfaces" to midpoints. * `time_deriv_method`: `<:AbstractTimeDerivMethod` indicating the method used to calculate the loading time derivatives. * `average_freestream_vel=false`: Store possibily unsteady freestream velocity in the `OpenFASTData` object if `false`, store average value otherwise. * `average_omega=false`: Store possibily unsteady omega (rotation rate) in the `OpenFASTData` object if `false`, store average value otherwise. """ function read_openfast_file(fname, radii, cs_area=nothing; header_keyword="Time", has_units_header=true, time_column_name=header_keyword, freestream_vel_column_name="Wind1VelX", azimuth_column_name="Azimuth", omega_column_name="RotSpeed", pitch_fmt=r"BlPitch(?<blade>[[:digit:]]+)", axial_loading_fmt=r"AB(?<blade>[[:digit:]]+)N(?<radial>[[:digit:]]+)Fxl", circum_loading_fmt=r"AB(?<blade>[[:digit:]]+)N(?<radial>[[:digit:]]+)Fyl", radial_interp_method=FLOWLinearInterp, time_deriv_method=SecondOrderFiniteDiff, average_freestream_vel=true, average_omega=true) num_radial = length(radii) # Remove leading and trailing whitespace from header keyword. header_keyword_s = strip(header_keyword) # Find the first line that starts with `header_keyword_s`, which is where the header starts. idx_header = 0 found_header = false for line in eachline(fname) idx_header += 1 if startswith(strip(line), header_keyword_s) found_header = true break end end # If we didn't find a header, throw an error. if !found_header throw(ArgumentError("Unable to find header (line starting with \"$(header_keyword_s)\") in $(fname)")) end # Decide what to do with the units header. if has_units_header # If we have a units header, then we'll want to start reading right after it. skipto = idx_header + 2 else # If there is no units header, then we don't need to skip anything and we'll just start reading directly after the header. skipto = idx_header + 1 end # Read the file into a dataframe. df = CSV.read(fname, DataFrames.DataFrame; header=idx_header, skipto=skipto) # The number of times is equal to the number of rows in the dataframe. num_times = DataFrames.nrow(df) # This gives us all the column names in the dataframe. colnames = DataFrames.names(df) if time_column_name === nothing time = nothing else time = df[!, time_column_name] end if freestream_vel_column_name === nothing v = nothing else v_tmp = df[!, freestream_vel_column_name] if average_freestream_vel v = Fill(mean(v_tmp), length(v_tmp)) else v = v_tmp end end if azimuth_column_name === nothing azimuth = nothing else azimuth = df[!, azimuth_column_name] .* (pi/180) end if omega_column_name === nothing omega = nothing else omega_tmp = df[!, omega_column_name] .* (2*pi/60) if average_omega omega = Fill(mean(omega_tmp), length(omega_tmp)) else omega = omega_tmp end end if pitch_fmt === nothing pitch = nothing else # Get the number of blades and the pitch column names according to the pitch format. pitch_num_blades, pitch_matches = _get_num_blades(pitch_fmt, colnames) # Decide on an element type for the pitch, then read in the pitch. TF_pitch = promote_type(eltype.(getproperty.(Ref(df), getproperty.(pitch_matches, :match)))...) pitch = Array{TF_pitch, 2}(undef, num_times, pitch_num_blades) for m in pitch_matches b = parse(Int, m[:blade]) pitch[:, b] .= df[!, m.match] .* (pi/180) end end if axial_loading_fmt === nothing axial_loading = nothing else # Get the number of blades and radial stations according to the axial loading format. axial_num_blades, axial_num_radial, axial_matches = _get_num_blades_num_radial(axial_loading_fmt, colnames) # Decide on an element type for the axial loading, then read in the axial loading. TF_axial = promote_type(eltype.(getproperty.(Ref(df), getproperty.(axial_matches, :match)))...) axial_loading = Array{TF_axial, 3}(undef, num_times, axial_num_radial, axial_num_blades) for m in axial_matches b = parse(Int, m[:blade]) r = parse(Int, m[:radial]) axial_loading[:, r, b] .= df[!, m.match] end end if circum_loading_fmt === nothing circum_loading = nothing else # Get the number of blades and radial stations according to the circumferential loading format. circum_num_blades, circum_num_radial, circum_matches = _get_num_blades_num_radial(circum_loading_fmt, colnames) # Decide on an element type for the circumferential loading. TF_circum = promote_type(eltype.(getproperty.(Ref(df), getproperty.(circum_matches, :match)))...) circum_loading = Array{TF_circum, 3}(undef, num_times, circum_num_radial, circum_num_blades) for m in circum_matches b = parse(Int, m[:blade]) r = parse(Int, m[:radial]) circum_loading[:, r, b] .= df[!, m.match] end end # Create the openfast data struct. data = OpenFASTData{radial_interp_method,time_deriv_method}(time, v, azimuth, omega, pitch, radii, cs_area, axial_loading, circum_loading) # Interpolate the loading to the cell centers. interpolate_to_cell_centers!(data) # Calculate the loading time derivatives. calculate_loading_dot!(data) return data end """ f1a_source_elements_openfast(data::OpenFASTData, rho0, c0, area_per_chord2::Vector, positive_x_rotation::Bool=true) Construct and return an array of `CompactF1ASourceElement` objects from OpenFAST data. # Arguments - `data`: OpenFAST data object. - `rho0`: Ambient air density (kg/m^3) - `c0`: Ambient speed of sound (m/s) - `positive_x_rotation`: rotate blade around the positive-x axis if `true`, negative-x axis otherwise """ function f1a_source_elements_openfast(data::OpenFASTData, rho0, c0, positive_x_rotation::Bool=true) # if length(area_per_chord2) != length(data.radii_mid) # throw(ArgumentError("length of area_per_chord2 = $(length(area_per_chord2)) should be equal to length(data.radii_mid) = $(length(data.radii_mid))")) # end # OK, what's the coordinate system here? # Well, I guess I can decide. # For CCBlade, I've been assuming that the blade elements are translating in the positive x direction, rotating about the positive x axis if `positive_x_rotation` is `true`, negative x axis otherwise. # So for consistency let's say I do the same here. # Then that would mean the freestream velocity would be pointed in the negative x direction. # The velocity in the example OpenFAST file is always positive, so, I'll need to keep that in mind. # For the position of the blade elements, we'll initially be aligned with the y axis, and I'm assuming that the radial locations are all positive, so no sign switch necessary there. # But what to do about the loading? # What is the loading sign convention? # Well, for the axial loading, I would expect that the axial loading on the fluid would oppose the freestream velocity for a wind turbine. # So, if the blades are translating in the positive x direction, the axial loading on the fluid would also be in the positive x direction. # I can see that the axial loading in the openfast file is all positive, so no sign switch is necessary. # For the circumferential loading, for a wind turbine, I would expect the loading on the blade to be in the same direction as the blade rotation, so the loading on the fluid would be opposite the blade's rotation. # So, if the first blade is initially aligned with the y axis, rotating around the positive x axis, then the blade would initially be moving in the positive z direction, and so the loading on the fluid should be in the negative z direction. # And it looks like the circumferential loading in the OpenFAST file is negative, so no sign switch necessary. # But if the blade is rotating about the negative x axis, then the loading on the blade would be in the negative direction, and thus the loading on the fluid would be in the positive direction, and so we'd need to switch the sign. # Now, let's get some transformation stuff going. # We're going to be translating in the positive x direction. # Oh, but what do we do about the fact that the axial velocity isn't necessarily constant? # Well, what I need is the position and velocity in the axial direction. # It would also be nice to get the acceleration and jerk, too. # OK, I have the velocity, but the position is the tricky part. # But I should be able to just integrate it, I suppose. # So let's do that. # We'll assume the position at the first time is at the origin. # Now we need to integrate the velocity. # (This assumes the hub starts at the origin. # If that's not the case, just add `x0` to it, where `x0` is the axial position at the first time level.) x = FLOWMath.cumtrapz(data.time, data.v) # So now we have the axial position and axial velocity as a function of data.time. # Now we should be able to create transformations that take that into account. # There will be one for each data.time level. # For each entry in `data.time`, i.e. for `data.time[i]`, it will start at `[x[i], 0, 0]` and have velocity `[v[i], 0, 0]`. # This won't take into account the effect the possibily non-constant velocity has on the acceleration or jerk. # const_vel_trans = ConstantVelocityTransformation.(data.time, SVector{3,typeof(x)}.(x, 0, 0), SVector{3,typeof(x)}.(data.v, 0, 0)) # Next, we need to figure out the rotation stuff. # We actually have both a time history of omega and azimuthal angles. # So we could create a bunch of rotational transformations that have the correct azimuth offset and omega. # But it wouldn't take into account the effect the time derivative of omega has on the things we care about: the derivatives of position and loading. # I would need to do some work on that. # Also, I'm going to assume that omega and azimuth are always positive, and so I'll switch their signs if we are rotating about the negative x axis. # rot_trans = SteadyRotXTransformation.(data.time, data.omega.*ifelse(positive_x_rotation, 1, -1), data.azimuth.*ifelse(positive_x_rotation, 1, -1)) # So, want everything to have shape (num_times, num_radial_mid, num_blades). radii_mid_rs = reshape(data.radii_mid, 1, :) dradii_rs = reshape(data.dradii, 1, :) num_blades = data.num_blades thetas = 2*pi/num_blades.*(0:(num_blades-1)) .* ifelse(positive_x_rotation, 1, -1) thetas_rs = reshape(thetas, 1, 1, :) # cs_area_rs = reshape(cs_area, 1, :) cs_area_rs = reshape(data.cs_area_mid, 1, :) # All the loading arrays are in the right shape, and no sign switch is necessary. fn = data.axial_loading_mid fndot = data.axial_loading_mid_dot # The OpenFAST file doesn't have any data for the loading in the radial direction (which should be quite small of course). fr = zero(eltype(fn)) frdot = zero(eltype(fn)) fc = data.circum_loading_mid fcdot = data.circum_loading_mid_dot # Now we should be able to do all this. # This is a bit too cute, but I can't help myself. ses = (CompactF1ASourceElement.(rho0, c0, radii_mid_rs, thetas_rs, dradii_rs, cs_area_rs, fn, fndot, fr, frdot, fc.*ifelse(positive_x_rotation, 1, -1), fcdot.*ifelse(positive_x_rotation, 1, -1), data.time) .|> compose.(data.time, ConstantVelocityTransformation.(data.time, SVector{3,eltype(x)}.(x, 0, 0), SVector{3,eltype(data.v)}.(data.v, 0, 0)), SteadyRotXTransformation.(data.time, data.omega.*ifelse(positive_x_rotation, 1, -1), data.azimuth.*ifelse(positive_x_rotation, 1, -1)) ) ) return ses end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
29144
function K_1(Re_c) # Equation (47) in the BPM paper. if Re_c < 2.47e5 return -4.31*log10(Re_c) + 156.3 elseif Re_c < 8.0e5 return -9.0*log10(Re_c) + 181.6 else return 128.5*one(Re_c) end end function DeltaK_1(alphastar, Re_deltastar_p) # Equation (48) in the BPM report. T = promote_type(typeof(alphastar), typeof(Re_deltastar_p)) alphastar_deg = alphastar*180/pi if Re_deltastar_p < 5000 return alphastar_deg*(1.43*log10(Re_deltastar_p) - 5.29) else return zero(T) end end function St_1(M) # Equation (31) from the BPM report. return 0.02*M^(-0.6) end function A_min(a) # Equation (35) from the BPM report. if a < 0.204 return sqrt(67.552 - 886.788*a^2) - 8.219 elseif a ≀ 0.244 return -32.665*a + 3.981 else return -142.795*a^3 + 103.656*a^2 - 57.757*a + 6.006 end end function A_max(a) # Equation (36) from the BPM report. if a < 0.13 return sqrt(67.552 - 886.788*a^2) - 8.219 elseif a ≀ 0.321 return -15.901*a + 1.098 else return -4.669*a^3 + 3.491*a^2 - 16.699*a + 1.149 end end function A(St_over_St_peak, Re_c) # Equation (37) from the BPM report. a = abs_cs_safe(log10(St_over_St_peak)) # Equation (38) from the BPM report. if Re_c < 9.52e4 a0 = 0.57*one(Re_c) elseif Re_c ≀ 8.57e5 a0 = (-9.57e-13)*(Re_c - 8.57e5)^2 + 1.13 else a0 = 1.13*one(Re_c) end # Equation (39) from the BPM report. A_min_a0 = A_min(a0) A_max_a0 = A_max(a0) A_R = (-20 - A_min_a0)/(A_max_a0 - A_min_a0) # Equation (40) from the BPM report. A_min_a = A_min(a) A_max_a = A_max(a) return A_min_a + A_R*(A_max_a - A_min_a) end function B_min(b) # Equation (41) from the BPM report. if b < 0.13 return sqrt(16.888 - 886.788*b^2) - 4.109 elseif b ≀ 0.145 return -83.607*b + 8.138 else return -817.810*b^3 + 355.201*b^2 - 135.024*b + 10.619 end end function B_max(b) # Equation (42) from the BPM report. if b < 0.10 return sqrt(16.888 - 886.788*b^2) - 4.109 elseif b ≀ 0.187 return -31.330*b + 1.854 else return -80.541*b^3 + 44.174*b^2 - 39.381*b + 2.344 end end function B(St_over_St_peak, Re_c) # Equation (43) from the BPM report. b = abs_cs_safe(log10(St_over_St_peak)) # Equation (44) from the BPM report. if Re_c < 9.52e4 b0 = 0.30*one(Re_c) elseif Re_c ≀ 8.57e5 b0 = (-4.48e-13)*(Re_c - 8.57e5)^2 + 0.56 else b0 = 0.56*one(Re_c) end # Equation (45) from the BPM report. B_min_b0 = B_min(b0) B_max_b0 = B_max(b0) B_R = (-20 - B_min_b0)/(B_max_b0 - B_min_b0) # Equation (46) from the BPM report. B_min_b = B_min(b) B_max_b = B_max(b) return B_min_b + B_R*(B_max_b - B_min_b) end function St_2(St_1, alphastar) # Equation (34) from the BPM report. T = promote_type(typeof(St_1), typeof(alphastar)) alphastar_deg = alphastar*180/pi if alphastar_deg < 1.333 return St_1*one(T) elseif alphastar_deg ≀ 12.5 return St_1*10.0^(0.0054*(alphastar_deg - 1.333)^2) else return St_1*4.72*one(T) end end function gamma(M) # Equation (50) from the BPM report. gamma_deg = 27.094*M + 3.31 return gamma_deg end function gamma0(M) # Equation (50) from the BPM report. gamma0_deg = 23.43*M + 4.651 return gamma0_deg end function beta(M) # Equation (50) from the BPM report. beta_deg = 72.65*M + 10.74 return beta_deg end function beta0(M) # Equation (50) from the BPM report. beta0_deg = -34.19*M - 13.82 return beta0_deg end function K_2(Re_c, M, alphastar) T = promote_type(typeof(Re_c), typeof(M), typeof(alphastar)) alphastar_deg = alphastar*180/pi k_1 = K_1(Re_c)*one(T) # Equation (50) from the BPM report. # gamma_deg, gamma0_deg, beta_deg, beta0_deg = gammas_betas(M) gamma_deg = gamma(M) gamma0_deg = gamma0(M) beta_deg = beta(M) beta0_deg = beta0(M) # Equation (49) from the BPM report. if alphastar_deg < gamma0_deg - gamma_deg return k_1 - 1000 # elseif alphastar_deg ≀ gamma0_deg + gamma_deg elseif alphastar_deg ≀ gamma0_deg + sqrt(-(gamma_deg/beta_deg)^2*(-12 - beta0_deg)^2 + gamma_deg^2) return k_1 + sqrt(beta_deg^2 - (beta_deg/gamma_deg)^2*(alphastar_deg - gamma0_deg)^2) + beta0_deg else return k_1 - 12 end end function St_1prime(Re_c) # Equation (55) from the BPM report. T = typeof(Re_c) if Re_c < 1.3e5 return 0.18*one(T) elseif Re_c ≀ 4.0e5 return 0.001756*Re_c^(0.3931) else return 0.28*one(T) end end function Dbar_h(theta_e, phi_e, M, M_c) # Equation (B1) from the BPM report. return (2*sin(0.5*theta_e)^2*sin(phi_e)^2)/((1 + M*cos(theta_e))*(1 + (M - M_c)*cos(theta_e))^2) end function Dbar_l(theta_e, phi_e, M) # Equation (B2) from the BPM report. return (sin(theta_e)^2*sin(phi_e)^2)/((1 + M*cos(theta_e))^4) end function TBL_TE_s(freq, nu, L, chord, U, M, M_c, r_e, theta_e, phi_e, alphastar, bl) T = promote_type(typeof(freq), typeof(nu), typeof(L), typeof(chord), typeof(U), typeof(M), typeof(M_c), typeof(r_e), typeof(theta_e), typeof(phi_e), typeof(alphastar)) Re_c = U*chord/nu alphastar0 = alpha_stall(bl, Re_c) gamma0_deg = gamma0(M) if alphastar*180/pi > min(gamma0_deg, alphastar0*180/pi) # SPL_s = -100*one(T) G_s = 10^(0.1*(-100))*one(T) else D = Dbar_h(theta_e, phi_e, M, M_c) deltastar_s = disp_thickness_top(bl, Re_c, alphastar)*chord St_s = freq*deltastar_s/U St_peak_p = St_1(M) St_peak_alpha = St_2(St_peak_p, alphastar) St_peak_s = 0.5*(St_peak_p + St_peak_alpha) A_s = A(St_s/St_peak_s, Re_c) k_1 = K_1(Re_c) # SPL_s = 10*log10((deltastar_s*M^5*L*D)/(r_e^2)) + A_s + k_1 - 3 # Brooks and Burley AIAA 2001-2210 style. H_s = 10^(0.1*(A_s + k_1 - 3)) G_s = (deltastar_s*M^5*L*D)/(r_e^2)*H_s end SPL_s = 10*log10(G_s) return SPL_s end function TBL_TE_p(freq, nu, L, chord, U, M, M_c, r_e, theta_e, phi_e, alphastar, bl) T = promote_type(typeof(freq), typeof(nu), typeof(L), typeof(chord), typeof(U), typeof(M), typeof(M_c), typeof(r_e), typeof(theta_e), typeof(phi_e), typeof(alphastar)) Re_c = U*chord/nu alphastar0 = alpha_stall(bl, Re_c) gamma0_deg = gamma0(M) if alphastar*180/pi > min(gamma0_deg, alphastar0*180/pi) # SPL_p = -100*one(T) G_p = 10^(0.1*(-100))*one(T) else D = Dbar_h(theta_e, phi_e, M, M_c) deltastar_p = disp_thickness_bot(bl, Re_c, alphastar)*chord k_1 = K_1(Re_c) St_p = freq*deltastar_p/U St_peak_p = St_1(M) A_p = A(St_p/St_peak_p, Re_c) Re_deltastar_p = U*deltastar_p/nu Ξ”k_1 = DeltaK_1(alphastar, Re_deltastar_p) # SPL_p = 10*log10((deltastar_p*M^5*L*D)/(r_e^2)) + A_p + k_1 - 3 + Ξ”k_1 # Brooks and Burley AIAA 2001-2210 style. H_p = 10^(0.1*(A_p + k_1 - 3 + Ξ”k_1)) G_p = (deltastar_p*M^5*L*D)/(r_e^2)*H_p end SPL_p = 10*log10(G_p) return SPL_p end function TBL_TE_alpha(freq, nu, L, chord, U, M, M_c, r_e, theta_e, phi_e, alphastar, bl) Re_c = U*chord/nu alphastar0 = alpha_stall(bl, Re_c) gamma0_deg = gamma0(M) deltastar_s = disp_thickness_top(bl, Re_c, alphastar)*chord St_s = freq*deltastar_s/U St_peak_p = St_1(M) St_peak_alpha = St_2(St_peak_p, alphastar) k2 = K_2(Re_c, M, alphastar) if alphastar*180/pi > min(gamma0_deg, alphastar0*180/pi) D = Dbar_l(theta_e, phi_e, M) A_prime = A(St_s/St_peak_alpha, 3*Re_c) # SPL_alpha = 10*log10((deltastar_s*M^5*L*D)/(r_e^2)) + A_prime + k2 # Brooks and Burley AIAA 2001-2210 style. H_alpha = 10^(0.1*(A_prime + k2)) G_alpha = (deltastar_s*M^5*L*D)/(r_e^2)*H_alpha else D = Dbar_h(theta_e, phi_e, M, M_c) B_alpha = B(St_s/St_peak_alpha, Re_c) # SPL_alpha = 10*log10((deltastar_s*M^5*L*D)/(r_e^2)) + B_alpha + k2 # Brooks and Burley AIAA 2001-2210 style. H_alpha = 10^(0.1*(B_alpha + k2)) G_alpha = (deltastar_s*M^5*L*D)/(r_e^2)*H_alpha end SPL_alpha = 10*log10(G_alpha) return SPL_alpha end function TBL_TE(freq, nu, L, chord, U, M, M_c, r_e, theta_e, phi_e, alphastar, bl) SPL_s = TBL_TE_s(freq, nu, L, chord, U, M, M_c, r_e, theta_e, phi_e, alphastar, bl) SPL_p = TBL_TE_p(freq, nu, L, chord, U, M, M_c, r_e, theta_e, phi_e, alphastar, bl) SPL_alpha = TBL_TE_alpha(freq, nu, L, chord, U, M, M_c, r_e, theta_e, phi_e, alphastar, bl) return SPL_s, SPL_p, SPL_alpha end abstract type AbstractMachCorrection end struct NoMachCorrection <: AbstractMachCorrection end struct PrandtlGlauertMachCorrection <: AbstractMachCorrection end struct TBLTESourceElement{ TDirect<:AbstractDirectivity,TUInduction,TMachCorrection,TDoppler, Tc0,Tnu,TΞ”r,Tchord,Ty0dot,Ty1dot,Ty1dot_fluid,TΟ„,TΔτ,Tspan_uvec,Tchord_uvec,Tbl } <: AbstractBroadbandSourceElement{TDirect,TUInduction,TMachCorrection,TDoppler} # Speed of sound, m/s. c0::Tc0 # Kinematic viscosity, m^2/s nu::Tnu # Radial/spanwise length of element, m. Ξ”r::TΞ”r # chord length of element, m. chord::Tchord # Source position, m. y0dot::Ty0dot # Source velocity, m/s. y1dot::Ty1dot # Fluid velocity, m/s. y1dot_fluid::Ty1dot_fluid # Source time, s. Ο„::TΟ„ # Time step size, i.e. the amount of time this source element "exists" with these properties, s. Δτ::TΔτ # Radial/spanwise unit vector, aka unit vector aligned with the element's span direction. span_uvec::Tspan_uvec # Chordwise unit vector, aka unit vector aligned with the element's chord line, pointing from leading edge to trailing edge. chord_uvec::Tchord_uvec # Boundary layer struct, i.e. an AbstractBoundaryLayer. bl::Tbl # `Bool` indicating chord_uvecΓ—span_uvec will give a vector pointing from bottom side (usually pressure side) to top side (usually suction side) if `true`, or the opposite if `false`. chord_cross_span_to_get_top_uvec::Bool function TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, Ξ”r, chord, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, chord_cross_span_to_get_top_uvec::Bool) where {TDirect<:AbstractDirectivity,TUInduction,TMachCorrection,TDoppler} return new{ TDirect,TUInduction,TMachCorrection,TDoppler, typeof(c0), typeof(nu), typeof(Ξ”r), typeof(chord), typeof(y0dot), typeof(y1dot), typeof(y1dot_fluid), typeof(Ο„), typeof(Δτ), typeof(span_uvec), typeof(chord_uvec), typeof(bl) }(c0, nu, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), use the PrandtlGlauertMachCorrection, and Doppler-shift. function TBLTESourceElement(c0, nu, Ξ”r, chord, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, chord_cross_span_to_get_top_uvec::Bool) return TBLTESourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(c0, nu, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end """ TBLTESourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) Construct a source element for predicting turbulent boundary layer-trailing edge (TBLTE) noise using the BPM/Brooks and Burley method, using position and velocity data expressed in a cylindrical coordinate system. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. Likewise, the `vn`, `vr`, and `vc` arguments are used to define the normal, radial, and circumferential velocity of the fluid (in a reference frame moving with the element) in the same cylindrical coordinate system. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - vn: normal velocity of fluid (m/s) - vr: radial velocity of fluid (m/s) - vc: circumferential velocity of the fluid (m/s) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y::Bool) where {TDirect,TUInduction,TMachCorrection,TDoppler} sΞΈ, cΞΈ = sincos(ΞΈ) sΟ•, cΟ• = sincos(Ο•) y0dot = @SVector [0, r*cΞΈ, r*sΞΈ] T = eltype(y0dot) y1dot = @SVector zeros(T, 3) y1dot_fluid = @SVector [vn, vr*cΞΈ - vc*sΞΈ, vr*sΞΈ + vc*cΞΈ] span_uvec = @SVector [0, cΞΈ, sΞΈ] if twist_about_positive_y chord_uvec = @SVector [-sΟ•, cΟ•*sΞΈ, -cΟ•*cΞΈ] else chord_uvec = @SVector [-sΟ•, -cΟ•*sΞΈ, cΟ•*cΞΈ] end chord_cross_span_to_get_top_uvec = twist_about_positive_y return TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec::Bool) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), use the PrandtlGlauertMachCorrection, and Doppler-shift. function TBLTESourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y::Bool) return TBLTESourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) end """ TBLTESourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) Construct a source element for predicting turbulent boundary layer-trailing edge (TBLTE) noise using the BPM/Brooks and Burley method, using the velocity magnitude `U` and angle of attack `Ξ±`. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. The `U` and `Ξ±` arguments are the velocity magnitude normal to the source element length and the angle of attack, respectively. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - U: velocity magnitude (m/s) - Ξ±: angle of attack (rad) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) where {TDirect,TUInduction,TMachCorrection,TDoppler} precone = 0 pitch = 0 phi = Ο• - Ξ± y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec(Ο•, precone, pitch, r, ΞΈ, U, phi, twist_about_positive_y) return TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(c0, nu, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), use the PrandtlGlauertMachCorrection, and Doppler-shift. function TBLTESourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y::Bool) return TBLTESourceElement{BrooksBurleyDirectivity,true,PrandtlGlauertMachCorrection,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) end """ (trans::KinematicTransformation)(se::TBLTESourceElement) Transform the position and orientation of a source element according to the coordinate system transformation `trans`. """ function (trans::KinematicTransformation)(se::TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}) where {TDirect,TUInduction,TMachCorrection,TDoppler} linear_only = false y0dot, y1dot = trans(se.Ο„, se.y0dot, se.y1dot, linear_only) y0dot, y1dot_fluid = trans(se.Ο„, se.y0dot, se.y1dot_fluid, linear_only) linear_only = true span_uvec = trans(se.Ο„, se.span_uvec, linear_only) chord_uvec = trans(se.Ο„, se.chord_uvec, linear_only) return TBLTESourceElement{TDirect,TUInduction,TMachCorrection,TDoppler}(se.c0, se.nu, se.Ξ”r, se.chord, y0dot, y1dot, y1dot_fluid, se.Ο„, se.Δτ, span_uvec, chord_uvec, se.bl, se.chord_cross_span_to_get_top_uvec) end doppler(pbs::AcousticMetrics.AbstractProportionalBandSpectrum) = AcousticMetrics.freq_scaler(pbs) """ Output of the turbulent boundary layer-trailing edge (TBL-TE) calculation: the acoustic pressure autospectrum centered at time `t` over observer duration `dt` and observer frequencies `cbands` for the suction side `G_s`, pressure side `G_p`, and the separation `G_alpha`. """ struct TBLTEOutput{NO,TF,TG<:AbstractVector{TF},TFreqs<:AcousticMetrics.AbstractProportionalBands{NO,:center},TDTime,TTime} <: AcousticMetrics.AbstractProportionalBandSpectrum{NO,TF} G_s::TG G_p::TG G_alpha::TG cbands::TFreqs dt::TDTime t::TTime function TBLTEOutput(G_s::TG, G_p::TG, G_alpha::TG, cbands::AcousticMetrics.AbstractProportionalBands{NO,:center}, dt, t) where {NO,TG} ncbands = length(cbands) length(G_s) == ncbands || throw(ArgumentError("length(G_s) must match length(cbands)")) length(G_p) == ncbands || throw(ArgumentError("length(G_p) must match length(cbands)")) length(G_alpha) == ncbands || throw(ArgumentError("length(G_alpha) must match length(cbands)")) dt > zero(dt) || throw(ArgumentError("dt must be positive")) return new{NO,eltype(TG),TG,typeof(cbands),typeof(dt),typeof(t)}(G_s, G_p, G_alpha, cbands, dt, t) end end @inline function Base.getindex(pbs::TBLTEOutput, i::Int) @boundscheck checkbounds(pbs, i) return @inbounds pbs.G_s[i] + pbs.G_p[i] + pbs.G_alpha[i] end @inline AcousticMetrics.has_observer_time(pbs::TBLTEOutput) = true @inline AcousticMetrics.observer_time(pbs::TBLTEOutput) = pbs.t @inline AcousticMetrics.timestep(pbs::TBLTEOutput) = pbs.dt @inline AcousticMetrics.time_scaler(pbs::TBLTEOutput, period) = timestep(pbs)/period function _tble_te_s(freq, deltastar_s_U, Re_c, St_peak_s, k_1, scaler, deep_stall) St_s = freq*deltastar_s_U A_s = A(St_s/St_peak_s, Re_c) # SPL_s = 10*log10((deltastar_s*M^5*L*Dh)/(r_er^2)) + A_s + k_1 - 3 # Brooks and Burley AIAA 2001-2210 style. H_s = 10^(0.1*(A_s + k_1 - 3)) # G_s = (deltastar_s*M^5*Ξ”r*Dh)/(r_er^2)*H_s G_s = scaler*H_s return ifelse(deep_stall, 10^(0.1*(-100))*one(typeof(G_s)), G_s) end function _tble_te_p(freq, deltastar_p_U, Re_c, St_peak_p, k_1, Ξ”k_1, scaler, deep_stall) St_p = freq*deltastar_p_U A_p = A(St_p/St_peak_p, Re_c) # SPL_p = 10*log10((deltastar_p*M^5*L*Dh)/(r_er^2)) + A_p + k_1 - 3 + Ξ”k_1 # Brooks and Burley AIAA 2001-2210 style. H_p = 10^(0.1*(A_p + k_1 - 3 + Ξ”k_1)) # G_p = (deltastar_p*M^5*Ξ”r*Dh)/(r_er^2)*H_p G_p = scaler*H_p return ifelse(deep_stall, 10^(0.1*(-100))*one(typeof(G_p)), G_p) end function _tble_te_alpha(freq, Re_c, deltastar_s_U, St_peak_alpha, k_2, scaler_l, scaler_h, deep_stall) # Don't know if this is really necessary. T = promote_type(typeof(freq), typeof(Re_c), typeof(deltastar_s_U), typeof(St_peak_alpha), typeof(k_2), typeof(scaler_l), typeof(scaler_h)) St_s = freq*deltastar_s_U A_prime_stall = A(St_s/St_peak_alpha, 3*Re_c) # SPL_alpha = 10*log10((deltastar_s*M^5*L*D)/(r_er^2)) + A_prime + k_2 # Brooks and Burley AIAA 2001-2210 style. H_alpha_stall = 10^(0.1*(A_prime_stall + k_2)) # G_alpha_stall = (deltastar_s*M^5*Ξ”r*Dl)/(r_er^2)*H_alpha_stall G_alpha_stall = scaler_l*H_alpha_stall*one(T) B_alpha = B(St_s/St_peak_alpha, Re_c) # SPL_alpha = 10*log10((deltastar_s*M^5*L*Dh)/(r_er^2)) + B_alpha + k_2 # Brooks and Burley AIAA 2001-2210 style. H_alpha = 10^(0.1*(B_alpha + k_2)) # G_alpha = (deltastar_s*M^5*Ξ”r*Dh)/(r_er^2)*H_alpha G_alpha = scaler_h*H_alpha*one(T) return ifelse(deep_stall, G_alpha_stall, G_alpha) end # Should use traits or something for this. function mach_correction(se::AbstractBroadbandSourceElement{TDirect,TUInduction,NoMachCorrection}, M) where {TDirect,TUInduction} return one(typeof(M)) end function mach_correction(se::AbstractBroadbandSourceElement{TDirect,TUInduction,PrandtlGlauertMachCorrection}, M) where {TDirect,TUInduction} return 1/(1 - M^2) end function noise(se::TBLTESourceElement, obs::AbstractAcousticObserver, t_obs, freqs::AcousticMetrics.AbstractProportionalBands{3, :center}) # Position of the observer: x_obs = obs(t_obs) # Need the angle of attack. alphastar = angle_of_attack(se) # Need the directivity functions. top_is_suction = is_top_suction(se.bl, alphastar) r_er, Dl, Dh = directivity(se, x_obs, top_is_suction) # Need the fluid velocity normal to the span. # Brooks and Burley 2001 are a bit ambiguous on whether it should include induction, or just the freestream and rotation. # # * In the nomenclature section: `U` is "flow speed normal to span (`U_mn` with `mn` suppressed). # So that's one point for "no induction." # * In some discussion after equation (8), "The Mach number, `M = U/c0`, represents that component of velocity `U` normal to the span...". # Hard to say one way or the other. # * In equation (12), `U_mn` is the velocity without induction. # So that's another point for "no induction." # * Equation (14) defines `V_tot` as the velocity including the freestream, rotation, and induction. # And then it defines `U` as the part of `V_tot` normal to the span. # So that's a point for "yes induction." # * In the directivity function definitions in equations (19) and (20), `M_tot` is used in the denominator, which seems to make it clear *that* velocity should include induction, since `V_tot` always includes induction. # # So, at the moment, the TBLTESourceElement type has a parameter TUInduction which, when true, will include induction in the flow speed normal to the span, and not otherwise. U = speed_normal_to_span(se) # Reynolds number based on chord and the flow speed normal to span. Re_c = U*se.chord/se.nu # Also need the displacement thicknesses for the pressure and suction sides. deltastar_s = disp_thickness_s(se.bl, Re_c, alphastar)*se.chord deltastar_p = disp_thickness_p(se.bl, Re_c, alphastar)*se.chord # Now that we've decided on the directivity functions and the displacement thickness, and we know the correct value of `top_is_suction` we should be able to switch the sign on `alphastar` if it's negative, and reference it to the zero-lift value, as the BPM report does. alphastar_positive = abs_cs_safe(alphastar - alpha_zerolift(se.bl)) # Mach number of the flow speed normal to span. M = U/se.c0 # This stuff is used to decide if the blade element is stalled or not. alphastar0 = alpha_stall(se.bl, Re_c) gamma0_deg = gamma0(M) deep_stall = (alphastar_positive*180/pi) > min(gamma0_deg, alphastar0*180/pi) St_peak_p = St_1(M) St_peak_alpha = St_2(St_peak_p, alphastar_positive) St_peak_s = 0.5*(St_peak_p + St_peak_alpha) Re_deltastar_p = U*deltastar_p/se.nu k_1 = K_1(Re_c) k_2 = K_2(Re_c, M, alphastar_positive) Ξ”k_1 = DeltaK_1(alphastar_positive, Re_deltastar_p) deltastar_s_U = deltastar_s/U deltastar_p_U = deltastar_p/U # Brooks and Burley 2001 recommend a Prandtl-Glauert style Mach number correction. # But whether or not it's included is dependent on the TMachCorrection type parameter for the source element. m_corr = mach_correction(se, M) # The Brooks and Burley autospectrums appear to be scaled by the usual squared reference pressure (20 ΞΌPa)^2, but I'd like things in dimensional units, so multiply through by that. pref2 = 4e-10 G_s_scaler = (deltastar_s*M^5*se.Ξ”r*Dh)/(r_er^2)*m_corr G_s = _tble_te_s.(freqs, deltastar_s_U, Re_c, St_peak_s, k_1, G_s_scaler, deep_stall).*pref2 G_p_scaler = (deltastar_p*M^5*se.Ξ”r*Dh)/(r_er^2)*m_corr G_p = _tble_te_p.(freqs, deltastar_p_U, Re_c, St_peak_p, k_1, Ξ”k_1, G_p_scaler, deep_stall).*pref2 G_alpha_scaler_l = (deltastar_s*M^5*se.Ξ”r*Dl)/(r_er^2)*m_corr G_alpha_scaler_h = G_s_scaler G_alpha = _tble_te_alpha.(freqs, Re_c, deltastar_s_U, St_peak_alpha, k_2, G_alpha_scaler_l, G_alpha_scaler_h, deep_stall).*pref2 # Also need the Doppler shift for this source-observer combination. doppler = doppler_factor(se, obs, t_obs) # Get the doppler-shifted time step and proportional bands. dt = se.Δτ/doppler freqs_obs = AcousticMetrics.center_bands(freqs, doppler) # All done. return TBLTEOutput(G_s, G_p, G_alpha, freqs_obs, dt, t_obs) end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
20676
function St_3prime_peak(h_over_deltastar_avg, Psi) Psi_deg = Psi*180/pi # Equation 72 from the BPM report. if h_over_deltastar_avg < 0.2 return 0.1*(h_over_deltastar_avg) + 0.095 - 0.00243*Psi_deg else return (0.212 - 0.0045*Psi_deg)/(1 + 0.235/h_over_deltastar_avg - 0.0132/(h_over_deltastar_avg^2)) end end function G4(h_over_deltastar_avg, Psi) Psi_deg = Psi*180/pi # Equation 74 from the BPM report. if h_over_deltastar_avg ≀ 5 return 17.5*log10(h_over_deltastar_avg) + 157.5 - 1.114*Psi_deg else return 169.7 - 1.114*Psi_deg end end function G5_Psi14(h_over_deltastar_avg, St_3prime_over_St_3prime_peak) # Equation 77 from the BPM report. Ξ· = log10(St_3prime_over_St_3prime_peak) # Equation 78 from the BPM report. if h_over_deltastar_avg < 0.25 ΞΌ = 0.1211*one(h_over_deltastar_avg) elseif h_over_deltastar_avg < 0.62 ΞΌ = -0.2175*h_over_deltastar_avg + 0.1755 elseif h_over_deltastar_avg < 1.15 ΞΌ = -0.0308*h_over_deltastar_avg + 0.0596 else ΞΌ = 0.0242*one(h_over_deltastar_avg) end # Equation 79 from the BPM report. if h_over_deltastar_avg < 0.02 m = zero(h_over_deltastar_avg) elseif h_over_deltastar_avg ≀ 0.5 m = 68.724*h_over_deltastar_avg - 1.35 elseif h_over_deltastar_avg ≀ 0.62 m = 308.475*h_over_deltastar_avg - 121.23 elseif h_over_deltastar_avg < 1.15 m = 224.811*h_over_deltastar_avg - 69.354 elseif h_over_deltastar_avg < 1.2 m = 1583.28*h_over_deltastar_avg - 1631.592 else m = 268.344*one(h_over_deltastar_avg) end # This is in the code listing in the BPM report appendix. if m < 0 m = zero(h_over_deltastar_avg) end # Equation 80 from the BPM report. Ξ·_0 = -sqrt((m^2*ΞΌ^4)/(6.25 + m^2*ΞΌ^2)) # Equation 81 from the BPM report. k = 2.5*sqrt(1 - (Ξ·_0/ΞΌ)^2) - 2.5 - m*Ξ·_0 # Equation 76 from the BPM report. if Ξ· < Ξ·_0 return m*Ξ· + k elseif Ξ· < 0 return 2.5*sqrt(1 - (Ξ·/ΞΌ)^2) - 2.5 elseif Ξ· < 0.03616 return sqrt(1.5625 - 1194.99*Ξ·^2) - 1.25*one(h_over_deltastar_avg) else return -155.543*Ξ· + 4.375*one(h_over_deltastar_avg) end end function G5_Psi0(h_over_deltastar_avg, St_3prime_over_St_3prime_peak) # Equation 82 from the BPM report. h_over_deltastar_avg_prime = 6.724*h_over_deltastar_avg^2 - 4.019*h_over_deltastar_avg + 1.107 return G5_Psi14(h_over_deltastar_avg_prime, St_3prime_over_St_3prime_peak) end function G5(h_over_deltastar_avg, Psi, St_3prime_over_St_3prime_peak) Psi_deg = 180/pi*Psi # Equation 75 from the BPM report. G5_0 = G5_Psi0(h_over_deltastar_avg, St_3prime_over_St_3prime_peak) G5_14 = G5_Psi14(h_over_deltastar_avg, St_3prime_over_St_3prime_peak) g5 = G5_0 + 0.0714*Psi_deg*(G5_14 - G5_0) # This check is in the code listing in the BPM report appendix: if g5 > 0 return zero(g5) else return g5 end end function BLUNT(freq, nu, L, chord, h, Psi, U, M, M_c, r_e, theta_e, phi_e, alphastar, bl) Re_c = U*chord/nu # deltastar_s = disp_thickness_s(bl, Re_c, alphastar)*chord # deltastar_p = disp_thickness_p(bl, Re_c, alphastar)*chord deltastar_top = disp_thickness_top(bl, Re_c, alphastar)*chord deltastar_bot = disp_thickness_bot(bl, Re_c, alphastar)*chord top_is_suction = alphastar > alpha_zerolift(bl) deltastar_s, deltastar_p = ifelse(top_is_suction, (deltastar_top, deltastar_bot), (deltastar_bot, deltastar_top)) # Equation 73 from the BPM report. deltastar_avg = 0.5*(deltastar_p + deltastar_s) h_over_deltastar_avg = h/deltastar_avg D = Dbar_h(theta_e, phi_e, M, M_c) # Equation 71 from the BPM report. St_3p = freq*h/U St_3prime_over_St_3prime_peak = St_3p/St_3prime_peak(h_over_deltastar_avg, Psi) g5temp = G5(h_over_deltastar_avg, Psi, St_3prime_over_St_3prime_peak) # This next check is in the code listing in the BPM report appendix. # Need to find G5 for h_over_deltastar_avg = 0.25 for the F4TEMP variable. f4temp = G5_Psi14(0.25, St_3prime_over_St_3prime_peak) # if g5 > f4temp # g5 = f4temp # end g5 = ifelse(g5temp > f4temp, f4temp, g5temp) # Equation 70 from the BPM report. # SPL_blunt = 10*log10((h*(M^5.5)*L*D)/(r_e^2)) + G4(h_over_deltastar_avg, Psi) + g5 # Brooks and Burley AIAA 2001-2210 style. H_b = 10^(0.1*(G4(h_over_deltastar_avg, Psi) + g5)) G_bte = (h*(M^5.5)*L*D)/(r_e^2)*H_b SPL_blunt = 10*log10(G_bte) return SPL_blunt end struct TEBVSSourceElement{ TDirect<:AbstractDirectivity,TUInduction,TDoppler, Tc0,Tnu,TΞ”r,Tchord,Th,TPsi,Ty0dot,Ty1dot,Ty1dot_fluid,TΟ„,TΔτ,Tspan_uvec,Tchord_uvec,Tbl } <: AbstractBroadbandSourceElement{TDirect,TUInduction,NoMachCorrection,TDoppler} # Speed of sound, m/s. c0::Tc0 # Kinematic viscosity, m^2/s nu::Tnu # Radial/spanwise length of element, m. Ξ”r::TΞ”r # chord length of element, m. chord::Tchord # Trailing edge thickness, m. h::Th # Solid angle between blade surfaces immediately upstream of the trailing edge, rad. Psi::TPsi # Source position, m. y0dot::Ty0dot # Source velocity, m/s. y1dot::Ty1dot # Fluid velocity, m/s. y1dot_fluid::Ty1dot_fluid # Source time, s. Ο„::TΟ„ # Time step size, i.e. the amount of time this source element "exists" with these properties, s. Δτ::TΔτ # Radial/spanwise unit vector, aka unit vector aligned with the element's span direction. span_uvec::Tspan_uvec # Chordwise unit vector, aka unit vector aligned with the element's chord line, pointing from leading edge to trailing edge. chord_uvec::Tchord_uvec # Boundary layer struct, i.e. an AbstractBoundaryLayer. bl::Tbl # `Bool` indicating chord_uvecΓ—span_uvec will give a vector pointing from bottom side (usually pressure side) to top side (usually suction side) if `true`, or the opposite if `false`. chord_cross_span_to_get_top_uvec::Bool function TEBVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, Ξ”r, chord, h, Psi, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, chord_cross_span_to_get_top_uvec::Bool) where {TDirect<:AbstractDirectivity,TUInduction,TDoppler} return new{ TDirect,TUInduction,TDoppler, typeof(c0), typeof(nu), typeof(Ξ”r), typeof(chord), typeof(h), typeof(Psi), typeof(y0dot), typeof(y1dot), typeof(y1dot_fluid), typeof(Ο„), typeof(Δτ), typeof(span_uvec), typeof(chord_uvec), typeof(bl) }(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), and Doppler-shift. function TEBVSSourceElement(c0, nu, Ξ”r, chord, h, Psi, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, chord_cross_span_to_get_top_uvec) return TEBVSSourceElement{BrooksBurleyDirectivity,true,true}(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end """ TEBVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) Construct a source element for predicting trailing edge bluntness-vortex shedding (TEBVS) noise using the BPM/Brooks and Burley method, using position and velocity data expressed in a cylindrical coordinate system. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. Likewise, the `vn`, `vr`, and `vc` arguments are used to define the normal, radial, and circumferential velocity of the fluid (in a reference frame moving with the element) in the same cylindrical coordinate system. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - h: trailing edge thickness (m) - Psi: solid angle between the blade surfaces immediately upstream of the trailing edge (rad) - vn: normal velocity of fluid (m/s) - vr: radial velocity of fluid (m/s) - vc: circumferential velocity of the fluid (m/s) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function TEBVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) where {TDirect,TUInduction,TDoppler} sΞΈ, cΞΈ = sincos(ΞΈ) sΟ•, cΟ• = sincos(Ο•) y0dot = @SVector [0, r*cΞΈ, r*sΞΈ] T = eltype(y0dot) y1dot = @SVector zeros(T, 3) y1dot_fluid = @SVector [vn, vr*cΞΈ - vc*sΞΈ, vr*sΞΈ + vc*cΞΈ] span_uvec = @SVector [0, cΞΈ, sΞΈ] if twist_about_positive_y chord_uvec = @SVector [-sΟ•, cΟ•*sΞΈ, -cΟ•*cΞΈ] else chord_uvec = @SVector [-sΟ•, -cΟ•*sΞΈ, cΟ•*cΞΈ] end chord_cross_span_to_get_top_uvec = twist_about_positive_y return TEBVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), and Doppler-shift. function TEBVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) return TEBVSSourceElement{BrooksBurleyDirectivity,true,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) end """ TEBVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) Construct a source element for predicting trailing edge bluntness-vortex shedding (TEBVS) noise using the BPM/Brooks and Burley method, using the velocity magnitude `U` and angle of attack `Ξ±`. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. The `U` and `Ξ±` arguments are the velocity magnitude normal to the source element length and the angle of attack, respectively. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - nu: Kinematic viscosity (m^2/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - h: trailing edge thickness (m) - Psi: solid angle between the blade surfaces immediately upstream of the trailing edge (rad) - U: velocity magnitude (m/s) - Ξ±: angle of attack (rad) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function TEBVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) where {TDirect,TUInduction,TDoppler} precone = 0 pitch = 0 phi = Ο• - Ξ± y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec(Ο•, precone, pitch, r, ΞΈ, U, phi, twist_about_positive_y) return TEBVSSourceElement{TDirect,TUInduction,TDoppler}(c0, nu, Ξ”r, chord, h, Psi, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), and Doppler-shift. function TEBVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) return TEBVSSourceElement{BrooksBurleyDirectivity,true,true}(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, Ξ±, Ο„, Δτ, bl, twist_about_positive_y) end """ (trans::KinematicTransformation)(se::TEBVSSourceElement) Transform the position and orientation of a source element according to the coordinate system transformation `trans`. """ function (trans::KinematicTransformation)(se::TEBVSSourceElement{TDirect,TUInduction,TDoppler}) where {TDirect,TUInduction,TDoppler} linear_only = false y0dot, y1dot = trans(se.Ο„, se.y0dot, se.y1dot, linear_only) y0dot, y1dot_fluid = trans(se.Ο„, se.y0dot, se.y1dot_fluid, linear_only) linear_only = true span_uvec = trans(se.Ο„, se.span_uvec, linear_only) chord_uvec = trans(se.Ο„, se.chord_uvec, linear_only) return TEBVSSourceElement{TDirect,TUInduction,TDoppler}(se.c0, se.nu, se.Ξ”r, se.chord, se.h, se.Psi, y0dot, y1dot, y1dot_fluid, se.Ο„, se.Δτ, span_uvec, chord_uvec, se.bl, se.chord_cross_span_to_get_top_uvec) end function _teb_vs(freq, h_U, h_over_deltastar_avg, St_3pp, Psi, g4, G_teb_vs_scaler) # Equation 71 from the BPM report. St_3p = freq*h_U St_3prime_over_St_3prime_peak = St_3p/St_3pp g5temp = G5(h_over_deltastar_avg, Psi, St_3prime_over_St_3prime_peak) # This next check is in the code listing in the BPM report appendix. # Need to find G5 for h_over_deltastar_avg = 0.25 for the F4TEMP variable. f4temp = G5_Psi14(0.25, St_3prime_over_St_3prime_peak) g5 = ifelse(g5temp > f4temp, f4temp, g5temp) # Equation 70 from the BPM report. # SPL_blunt = 10*log10((h*(M^5.5)*L*D)/(r_e^2)) + G4(h_over_deltastar_avg, Psi) + g5 # Brooks and Burley AIAA 2001-2210 style. H_b = 10^(0.1*(g4 + g5)) G_bte = G_teb_vs_scaler*H_b return G_bte end function noise(se::TEBVSSourceElement, obs::AbstractAcousticObserver, t_obs, freqs::AcousticMetrics.AbstractProportionalBands{3, :center}) # Position of the observer: x_obs = obs(t_obs) # Need the angle of attack. alphastar = angle_of_attack(se) # Need the directivity functions. top_is_suction = is_top_suction(se.bl, alphastar) r_er, Dl, Dh = directivity(se, x_obs, top_is_suction) # Need the fluid velocity normal to the span. # Brooks and Burley 2001 are a bit ambiguous on whether it should include induction, or just the freestream and rotation. # # * In the nomenclature section: `U` is "flow speed normal to span (`U_mn` with `mn` suppressed). # So that's one point for "no induction." # * In some discussion after equation (8), "The Mach number, `M = U/c0`, represents that component of velocity `U` normal to the span...". # Hard to say one way or the other. # * In equation (12), `U_mn` is the velocity without induction. # So that's another point for "no induction." # * Equation (14) defines `V_tot` as the velocity including the freestream, rotation, and induction. # And then it defines `U` as the part of `V_tot` normal to the span. # So that's a point for "yes induction." # * In the directivity function definitions in equations (19) and (20), `M_tot` is used in the denominator, which seems to make it clear *that* velocity should include induction, since `V_tot` always includes induction. # # So, at the moment, the TBLTESourceElement type has a parameter TUInduction which, when true, will include induction in the flow speed normal to the span, and not otherwise. U = speed_normal_to_span(se) # Reynolds number based on chord and the flow speed normal to span. Re_c = U*se.chord/se.nu # Also need the displacement thicknesses for the pressure and suction sides. deltastar_s = disp_thickness_s(se.bl, Re_c, alphastar)*se.chord deltastar_p = disp_thickness_p(se.bl, Re_c, alphastar)*se.chord # Now that we've decided on the directivity functions and the displacement thickness, and we know the correct value of `top_is_suction` we should be able to switch the sign on `alphastar` if it's negative, and reference it to the zero-lift value, as the BPM report does. alphastar_positive = abs_cs_safe(alphastar - alpha_zerolift(se.bl)) # Mach number of the flow speed normal to span. M = U/se.c0 # Equation 73 from the BPM report. deltastar_avg = 0.5*(deltastar_p + deltastar_s) h_over_deltastar_avg = se.h/deltastar_avg h_U = se.h/U St_3pp = St_3prime_peak(h_over_deltastar_avg, se.Psi) g4 = G4(h_over_deltastar_avg, se.Psi) # The Brooks and Burley autospectrums appear to be scaled by the usual squared reference pressure (20 ΞΌPa)^2, but I'd like things in dimensional units, so multiply through by that. pref2 = 4e-10 G_teb_vs_scaler = (se.h*(M^5.5)*se.Ξ”r*Dh)/(r_er^2) G_teb_vs = _teb_vs.(freqs, h_U, h_over_deltastar_avg, St_3pp, se.Psi, g4, G_teb_vs_scaler) .* pref2 # Also need the Doppler shift for this source-observer combination. doppler = doppler_factor(se, obs, t_obs) # Get the doppler-shifted time step and proportional bands. dt = se.Δτ/doppler freqs_obs = AcousticMetrics.center_bands(freqs, doppler) # All done. return AcousticMetrics.ProportionalBandSpectrumWithTime(G_teb_vs, freqs_obs, dt, t_obs) end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
18998
abstract type AbstractTipAlphaCorrection end struct NoTipAlphaCorrection <: AbstractTipAlphaCorrection end struct BPMTipAlphaCorrection <: AbstractTipAlphaCorrection end # struct BMTipAlphaCorrection{TCorrection} <: AbstractTipAlphaCorrection # correction::TCorrection # function BMTipAlphaCorrection(aspect_ratio) # correction = BPM._tip_vortex_alpha_correction_nonsmooth(aspect_ratio) # return new{typeof(correction)}(correction) # end # end # struct SmoothBMTipAlphaCorrection{TCorrection} <: AbstractTipAlphaCorrection # correction::TCorrection # function SmoothBMTipAlphaCorrection(aspect_ratio) # correction = BPM._tip_vortex_alpha_correction_smooth(aspect_ratio) # return new{typeof(correction)}(correction) # end # end abstract type AbstractBladeTip{TTipAlphaCorrection} end alpha_zerolift(blade_tip::AbstractBladeTip) = blade_tip.alpha0lift tip_alpha_correction(blade_tip::AbstractBladeTip) = blade_tip.tip_alpha_correction struct RoundedTip{TTipAlphaCorrection,TAlpha0Lift} <: AbstractBladeTip{TTipAlphaCorrection} tip_alpha_correction::TTipAlphaCorrection alpha0lift::TAlpha0Lift function RoundedTip(tip_alpha_correction::TTipAlphaCorrection, alpha0lift::TAlpha0Lift) where {TTipAlphaCorrection<:AbstractTipAlphaCorrection,TAlpha0Lift} return new{TTipAlphaCorrection, TAlpha0Lift}(tip_alpha_correction, alpha0lift) end end RoundedTip(alpha0lift=0.0) = RoundedTip(NoTipAlphaCorrection(), alpha0lift) struct FlatTip{TTipAlphaCorrection,TAlpha0Lift} <: AbstractBladeTip{TTipAlphaCorrection} tip_alpha_correction::TTipAlphaCorrection alpha0lift::TAlpha0Lift function FlatTip(tip_alpha_correction::TTipAlphaCorrection, alpha0lift::TAlpha0Lift) where {TTipAlphaCorrection<:AbstractTipAlphaCorrection,TAlpha0Lift} return new{TTipAlphaCorrection, TAlpha0Lift}(tip_alpha_correction, alpha0lift) end end FlatTip(alpha0lift=0.0) = FlatTip(NoTipAlphaCorrection(), alpha0lift) function tip_vortex_alpha_correction(blade_tip::AbstractBladeTip{NoTipAlphaCorrection}, alphatip) return alphatip end function tip_vortex_alpha_correction(blade_tip::AbstractBladeTip{BPMTipAlphaCorrection}, alphatip) # Referencing the tip vortex angle of attack correction to the zero-lift angle of attack ensures that the correction will never cause the angle of attack to drop below the zero-lift value, assuming the correction factor (0.71 here) is between 0 and 1. return 0.71*(alphatip - alpha_zerolift(blade_tip)) + alpha_zerolift(blade_tip) # return 0.71*alphatip + (1 - 0.71)*alpha_zerolift(blade_tip) end # function tip_vortex_alpha_correction(blade_tip::AbstractBladeTip{<:Union{BMTipAlphaCorrection,SmoothBMTipAlphaCorrection}}, alphatip) # return tip_alpha_correction(blade_tip).correction * (alphatip - alpha_zerolift(blade_tip)) + alpha_zerolift(blade_tip) # end function tip_vortex_size_c(::RoundedTip, alphatip) # Equation 63 in the BPM report. alphatip_deg = alphatip*180/pi return 0.008*alphatip_deg end function tip_vortex_size_c(::FlatTip, alphatip) alphatip_deg = alphatip*180/pi # Equation 67 in the BPM report. if alphatip_deg < 2 return 0.0230 + 0.0169*alphatip_deg else return 0.0378 + 0.0095*alphatip_deg end end function tip_vortex_max_mach_number(::AbstractBladeTip, M, alphatip) alphatip_deg = alphatip*180/pi # Equation 64 in the BPM report. M_max = (1 + 0.036*alphatip_deg)*M return M_max end function TIP(freq, chord, M, M_c, U_max, M_max, r_e, theta_e, phi_e, alphatip, blade_tip::AbstractBladeTip) l = tip_vortex_size_c(blade_tip, alphatip) * chord # Equation 62 in the BPM report. St_pp = freq*l/U_max D = Dbar_h(theta_e, phi_e, M, M_c) # Equation 61 in the BPM report. # SPL_tip = 10*log10(M^2*M_max^3*l^2*D/r_e^2) - 30.5*(log10(St_pp) + 0.3)^2 + 126 # Brooks and Burley AIAA 2001-2210 style. H_t = 10^(0.1*(-30.5*(log10(St_pp) + 0.3)^2 + 126)) G_tip = (M^2*M_max^3*l^2*D/r_e^2)*H_t SPL_tip = 10*log10(G_tip) return SPL_tip end struct TipVortexSourceElement{ TDirect<:AbstractDirectivity,TUInduction,TDoppler, Tc0,TΞ”r,Tchord,Ty0dot,Ty1dot,Ty1dot_fluid,TΟ„,TΔτ,Tspan_uvec,Tchord_uvec,Tbl,Tblade_tip } <: AbstractBroadbandSourceElement{TDirect,TUInduction,NoMachCorrection,TDoppler} # Speed of sound, m/s. # c0 c0::Tc0 # Radial/spanwise length of element, m. Ξ”r::TΞ”r # chord length of element, m. chord::Tchord # Source position, m. y0dot::Ty0dot # Source velocity, m/s. y1dot::Ty1dot # Fluid velocity, m/s. y1dot_fluid::Ty1dot_fluid # Source time, s. Ο„::TΟ„ # Time step size, i.e. the amount of time this source element "exists" with these properties, s. Δτ::TΔτ # Radial/spanwise unit vector, aka unit vector aligned with the element's span direction. span_uvec::Tspan_uvec # Chordwise unit vector, aka unit vector aligned with the element's chord line, pointing from leading edge to trailing edge. chord_uvec::Tchord_uvec # Boundary layer struct, i.e. an AbstractBoundaryLayer. bl::Tbl # Blade tip struct, i.e. an AbstractBladeTip. blade_tip::Tblade_tip # `Bool` indicating chord_uvecΓ—span_uvec will give a vector pointing from bottom side (usually pressure side) to top side (usually suction side) if `true`, or the opposite if `false`. chord_cross_span_to_get_top_uvec::Bool function TipVortexSourceElement{TDirect,TUInduction,TDoppler}(c0, Ξ”r, chord, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, blade_tip, chord_cross_span_to_get_top_uvec::Bool) where {TDirect<:AbstractDirectivity,TUInduction,TDoppler} return new{ TDirect,TUInduction,TDoppler, typeof(c0), typeof(Ξ”r), typeof(chord), typeof(y0dot), typeof(y1dot), typeof(y1dot_fluid), typeof(Ο„), typeof(Δτ), typeof(span_uvec), typeof(chord_uvec), typeof(bl), typeof(blade_tip) }(c0, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), and Doppler-shift. function TipVortexSourceElement(c0, Ξ”r, chord, y0dot::AbstractVector, y1dot::AbstractVector, y1dot_fluid::AbstractVector, Ο„, Δτ, span_uvec::AbstractVector, chord_uvec::AbstractVector, bl, blade_tip, chord_cross_span_to_get_top_uvec) return TipVortexSourceElement{BrooksBurleyDirectivity,true,true}(c0, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end """ TipVortexSourceElement(c0, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) Construct a source element for predicting turbulent boundary layer-trailing edge (TBLTE) noise using the BPM/Brooks and Burley method, using position and velocity data expressed in a cylindrical coordinate system. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. Likewise, the `vn`, `vr`, and `vc` arguments are used to define the normal, radial, and circumferential velocity of the fluid (in a reference frame moving with the element) in the same cylindrical coordinate system. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - vn: normal velocity of fluid (m/s) - vr: radial velocity of fluid (m/s) - vc: circumferential velocity of the fluid (m/s) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - blade_tip: Blade tip struct, i.e. an AbstractBladeTip. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function TipVortexSourceElement{TDirect,TUInduction,TDoppler}(c0, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) where {TDirect,TUInduction,TDoppler} sΞΈ, cΞΈ = sincos(ΞΈ) sΟ•, cΟ• = sincos(Ο•) y0dot = @SVector [0, r*cΞΈ, r*sΞΈ] T = eltype(y0dot) y1dot = @SVector zeros(T, 3) y1dot_fluid = @SVector [vn, vr*cΞΈ - vc*sΞΈ, vr*sΞΈ + vc*cΞΈ] span_uvec = @SVector [0, cΞΈ, sΞΈ] if twist_about_positive_y chord_uvec = @SVector [-sΟ•, cΟ•*sΞΈ, -cΟ•*cΞΈ] else chord_uvec = @SVector [-sΟ•, -cΟ•*sΞΈ, cΟ•*cΞΈ] end chord_cross_span_to_get_top_uvec = twist_about_positive_y return TipVortexSourceElement{TDirect,TUInduction,TDoppler}(c0, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), and Doppler-shift. function TipVortexSourceElement(c0, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) return TipVortexSourceElement{BrooksBurleyDirectivity,true,true}(c0, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) end """ TipVortexSourceElement(c0, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) Construct a source element for predicting tip vortex noise using the BPM/Brooks and Burley method, using the velocity magnitude `U` and angle of attack `Ξ±`. The `r` and `ΞΈ` arguments are used to define the radial and circumferential position of the source element in a cylindrical coordinate system. The `U` and `Ξ±` arguments are the velocity magnitude normal to the source element length and the angle of attack, respectively. The cylindrical coordinate system is defined as follows: * The normal/axial direction is in the positive x axis * The circumferential/azimuth angle `ΞΈ` is defined such that `ΞΈ = 0` means the radial direction is aligned with the positive y axis, and a positive `ΞΈ` indicates a right-handed rotation around the positive x axis. The `twist_about_positive_y` is a `Bool` controling how the `Ο•` argument is handled, which in turn controls the orientation of a unit vector defining `chord_uvec` indicating the orientation of the chord line, from leading edge to trailing edge. If `twist_about_positive_y` is `true`, `chord_uvec` will initially be pointed in the negative-z direction, and then rotated around the positive y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the positive x axis.) If `twist_about_positive_y` is `false`, `chord_uvec` will initially be pointed in the positive-z direction, and then rotated around the negative y axis by an amount `Ο•` before being rotated by the azimuth angle `ΞΈ`. (This would typcially be appropriate for a source element rotating around the negative x axis.) Note that, for a proper noise prediction, the source element needs to be transformed into the "global" frame, aka, the reference frame of the fluid. This can be done easily with the transformations provided by the `KinematicCoordinateTransformations` package, or manually by modifying the components of the source element struct. # Arguments - c0: Ambient speed of sound (m/s) - r: radial coordinate of the element in the blade-fixed coordinate system (m) - ΞΈ: angular offest of the element in the blade-fixed coordinate system (rad) - Ξ”r: length of the element (m) - chord: chord length of blade element (m) - Ο•: twist of blade element (rad) - U: velocity magnitude (m/s) - Ξ±: angle of attack (rad) - Ο„: source time (s) - Δτ: source time duration (s) - bl: Boundary layer struct, i.e. an AbstractBoundaryLayer. - blade_tip: Blade tip struct, i.e. an AbstractBladeTip. - twist_about_positive_y: if `true`, apply twist Ο• about positive y axis, negative y axis otherwise """ function TipVortexSourceElement{TDirect,TUInduction,TDoppler}(c0, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) where {TDirect,TUInduction,TDoppler} precone = 0 pitch = 0 phi = Ο• - Ξ± y0dot, y1dot, y1dot_fluid, span_uvec, chord_uvec, chord_cross_span_to_get_top_uvec = _get_position_velocity_span_uvec_chord_uvec(Ο•, precone, pitch, r, ΞΈ, U, phi, twist_about_positive_y) return TipVortexSourceElement{TDirect,TUInduction,TDoppler}(c0, Ξ”r, chord, y0dot, y1dot, y1dot_fluid, Ο„, Δτ, span_uvec, chord_uvec, bl, blade_tip, chord_cross_span_to_get_top_uvec) end # Default to using the `BrooksBurleyDirectivity` directivity function, include induction in the flow speed normal to span (TUInduction == true), and Doppler-shift. function TipVortexSourceElement(c0, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) return TipVortexSourceElement{BrooksBurleyDirectivity,true,true}(c0, r, ΞΈ, Ξ”r, chord, Ο•, U, Ξ±, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) end """ (trans::KinematicTransformation)(se::TipVortexSourceElement) Transform the position and orientation of a source element according to the coordinate system transformation `trans`. """ function (trans::KinematicTransformation)(se::TipVortexSourceElement{TDirect,TUInduction,TDoppler}) where {TDirect,TUInduction,TDoppler} linear_only = false y0dot, y1dot = trans(se.Ο„, se.y0dot, se.y1dot, linear_only) y0dot, y1dot_fluid = trans(se.Ο„, se.y0dot, se.y1dot_fluid, linear_only) linear_only = true span_uvec = trans(se.Ο„, se.span_uvec, linear_only) chord_uvec = trans(se.Ο„, se.chord_uvec, linear_only) return TipVortexSourceElement{TDirect,TUInduction,TDoppler}(se.c0, se.Ξ”r, se.chord, y0dot, y1dot, y1dot_fluid, se.Ο„, se.Δτ, span_uvec, chord_uvec, se.bl, se.blade_tip, se.chord_cross_span_to_get_top_uvec) end function _tip(freq, l_U_max, scaler) St_pp = freq*l_U_max H_t = 10^(0.1*(-30.5*(log10(St_pp) + 0.3)^2 + 126)) # G_tip = (M^2*M_max^3*l^2*D/r_e^2)*H_t G_tip = scaler*H_t return G_tip end function noise(se::TipVortexSourceElement, obs::AbstractAcousticObserver, t_obs, freqs::AcousticMetrics.AbstractProportionalBands{3, :center}) # Position of the observer: x_obs = obs(t_obs) # Need the angle of attack, including the possible tip correction. alphatip = tip_vortex_alpha_correction(se.blade_tip, angle_of_attack(se)) # Need the directivity functions. top_is_suction = is_top_suction(se.bl, alphatip) r_er, Dl, Dh = directivity(se, x_obs, top_is_suction) # Need the fluid velocity normal to the span. # Brooks and Burley 2001 are a bit ambiguous on whether it should include induction, or just the freestream and rotation. # # * In the nomenclature section: `U` is "flow speed normal to span (`U_mn` with `mn` suppressed). # So that's one point for "no induction." # * In some discussion after equation (8), "The Mach number, `M = U/c0`, represents that component of velocity `U` normal to the span...". # Hard to say one way or the other. # * In equation (12), `U_mn` is the velocity without induction. # So that's another point for "no induction." # * Equation (14) defines `V_tot` as the velocity including the freestream, rotation, and induction. # And then it defines `U` as the part of `V_tot` normal to the span. # So that's a point for "yes induction." # * In the directivity function definitions in equations (19) and (20), `M_tot` is used in the denominator, which seems to make it clear *that* velocity should include induction, since `V_tot` always includes induction. # # So, at the moment, the TBLTESourceElement type has a parameter TUInduction which, when true, will include induction in the flow speed normal to the span, and not otherwise. U = speed_normal_to_span(se) # Now that we've decided on the directivity functions and we know the correct value of `top_is_suction` we should be able to switch the sign on `alphastar` if it's negative, and reference it to the zero-lift value, as the BPM report does. alphatip_positive = abs_cs_safe(alphatip - alpha_zerolift(se.bl)) # Mach number of the flow speed normal to span. M = U/se.c0 # Need the maximum mach number near the tip vortex. M_max = tip_vortex_max_mach_number(se.blade_tip, M, alphatip_positive) # Now we can find the maximum speed near the tip vortex. U_max = M_max * se.c0 # Get the tip vortex size. l = tip_vortex_size_c(se.blade_tip, alphatip_positive) * se.chord # The Brooks and Burley autospectrums appear to be scaled by the usual squared reference pressure (20 ΞΌPa)^2, but I'd like things in dimensional units, so multiply through by that. pref2 = 4e-10 l_U_max = l/U_max G_tip_scaler = (M^2*M_max^3*l^2*Dh/r_er^2) G_tip = _tip.(freqs, l_U_max, G_tip_scaler) .* pref2 # Also need the Doppler shift for this source-observer combination. doppler = doppler_factor(se, obs, t_obs) # Get the doppler-shifted time step and proportional bands. dt = se.Δτ/doppler freqs_obs = AcousticMetrics.center_bands(freqs, doppler) # All done. return AcousticMetrics.ProportionalBandSpectrumWithTime(G_tip, freqs_obs, dt, t_obs) end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
824
""" get_dradii(radii, Rhub, Rtip) Compute the spacing between blade elements given the radial locations of the element midpoints in `radii` and the hub and tip radius in `Rhub` and `Rtip`, respectively. Assume the interfaces between elements are midway between adjacent element's midpoints. """ function get_dradii(radii, Rhub, Rtip) # How do I get the radial spacing? Well, for the inner elements, I'll just # assume that the interfaces are midway in between the centers. r_interface = 0.5.*(radii[begin:end-1] .+ radii[begin+1:end]) # Then just say that the blade begins at Rhub, and ends at Rtip. r_interface = vcat([Rhub], r_interface, [Rtip]) # And now the distance between interfaces is the spacing. dradii = r_interface[begin+1:end] .- r_interface[begin:end-1] return dradii end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
17184
""" endpoints(se::AbstractCompactSourceElement) Return the Tuple containing the endpoint locations of the compact source element `se`. """ function endpoints(se::AbstractCompactSourceElement) p1 = se.y0dot - 0.5*se.Ξ”r*orientation(se) p2 = se.y0dot + 0.5*se.Ξ”r*orientation(se) # Don't like the idea of having a billion SVectors, so convert them to plain # Vectors. Maybe not necessary. return (Vector(p1), Vector(p2)) end """ to_vtp(name::AbstractString, ses::AbstractArray{<:AbstractCompactSourceElement}) Construct and return a VTK polygonal (.vtp) data file object for an array of `AbstractCompactSourceElement` with name `name.vtp` (i.e., the `name` argument should not contain a file extension). """ function to_vtp(name, ses::AbstractArray{<:AbstractCompactSourceElement}) # This will be an array of the same size as ses, with each entry a # length-two tuple of the endpoints. points_all = AcousticAnalogies.endpoints.(ses) # This is an array of shape (2, size(ses)...) that has the global ID of each # point. Need to use `collect` to create an actual Array since we're going # to modify its elements. line_ids = reshape(1:(2*length(ses)), 2, size(ses)...) |> collect # Now I need to loop over each point... points = Vector{Vector{Float64}}() for I in CartesianIndices(points_all) for (j, p_current) in enumerate(points_all[I]) # Is the current point in points? k = findfirst(p -> all(p .β‰ˆ p_current), points) if k === nothing # p_current is not in points, so add it. push!(points, p_current) k = length(points) end line_ids[j, I] = k end end # This converts the points Vector{Vector} into a Matrix. Should be # size (num_dims, num_unique_points) where `num_dims` should be 3 (number of # spatial dimensions), and num_unique_points is the number of unique points. points = hcat(points...) # `line_ids` is an Array of shape (2, size(ses)...) Need to reshape that to # (2, length(ses)). line_ids = reshape(line_ids, 2, length(ses)) # Now create the array of VTK lines. lines = [WriteVTK.MeshCell(WriteVTK.PolyData.Lines(), line) for line in eachcol(line_ids)] vtkfile = WriteVTK.vtk_grid(name, points, lines) _write_data_to_vtk!(vtkfile, ses) return vtkfile end function _write_data_to_vtk!(vtkfile, ses::AbstractArray{<:CompactF1ASourceElement}) # Now need to add the cell data. I would have expected to have to flatten # these arrays, but apparently that's not necessary. vtkfile["Length", WriteVTK.VTKCellData()] = mapview(:Ξ”r, ses) vtkfile["CSArea", WriteVTK.VTKCellData()] = mapview(:Ξ›, ses) vtkfile["Position", WriteVTK.VTKCellData()] = hcat(mapview(:y0dot, ses)...) vtkfile["Velocity", WriteVTK.VTKCellData()] = hcat(mapview(:y1dot, ses)...) vtkfile["Acceleration", WriteVTK.VTKCellData()] = hcat(mapview(:y2dot, ses)...) vtkfile["Jerk", WriteVTK.VTKCellData()] = hcat(mapview(:y3dot, ses)...) vtkfile["Loading", WriteVTK.VTKCellData()] = hcat(mapview(:f0dot, ses)...) vtkfile["LoadingDot", WriteVTK.VTKCellData()] = hcat(mapview(:f1dot, ses)...) end function _write_data_to_vtk!(vtkfile, ses::AbstractArray{<:Union{TBLTESourceElement,LBLVSSourceElement,TipVortexSourceElement}}) # Now need to add the cell data. I would have expected to have to flatten # these arrays, but apparently that's not necessary. vtkfile["Length", WriteVTK.VTKCellData()] = mapview(:Ξ”r, ses) vtkfile["Chord", WriteVTK.VTKCellData()] = mapview(:chord, ses) vtkfile["Position", WriteVTK.VTKCellData()] = hcat(mapview(:y0dot, ses)...) vtkfile["Velocity", WriteVTK.VTKCellData()] = hcat(mapview(:y1dot, ses)...) vtkfile["FluidVelocity", WriteVTK.VTKCellData()] = hcat(mapview(:y1dot_fluid, ses)...) vtkfile["SpanUnitVector", WriteVTK.VTKCellData()] = hcat(mapview(:span_uvec, ses)...) vtkfile["ChordUnitVector", WriteVTK.VTKCellData()] = hcat(mapview(:chord_uvec, ses)...) end function _write_data_to_vtk!(vtkfile, ses::AbstractArray{<:Union{TEBVSSourceElement,CombinedNoTipBroadbandSourceElement,CombinedWithTipBroadbandSourceElement}}) # Now need to add the cell data. I would have expected to have to flatten # these arrays, but apparently that's not necessary. vtkfile["Length", WriteVTK.VTKCellData()] = mapview(:Ξ”r, ses) vtkfile["Chord", WriteVTK.VTKCellData()] = mapview(:chord, ses) vtkfile["TrailingEdgeThickness", WriteVTK.VTKCellData()] = mapview(:h, ses) vtkfile["TrailingEdgeAngle", WriteVTK.VTKCellData()] = mapview(:Psi, ses) vtkfile["Position", WriteVTK.VTKCellData()] = hcat(mapview(:y0dot, ses)...) vtkfile["Velocity", WriteVTK.VTKCellData()] = hcat(mapview(:y1dot, ses)...) vtkfile["FluidVelocity", WriteVTK.VTKCellData()] = hcat(mapview(:y1dot_fluid, ses)...) vtkfile["SpanUnitVector", WriteVTK.VTKCellData()] = hcat(mapview(:span_uvec, ses)...) vtkfile["ChordUnitVector", WriteVTK.VTKCellData()] = hcat(mapview(:chord_uvec, ses)...) end function to_vtu(name, obs::AbstractAcousticObserver, t; sphere_radius=1.0, n=10) # Get the current position of the observer. x = obs(t) # Create a sphere at the observer position with the specified radius. s = Meshes.Sphere(tuple(x...), sphere_radius) # Discretize the sphere. mesh = Meshes.simplexify(Meshes.discretize(s, Meshes.RegularDiscretization(n))) # This gets a fancy Unitful vector of Points that represent the verticies of the discretized sphere. verts = Meshes.vertices(mesh) # This gets the connectivity of the discretized sphere. connec = Meshes.elements(Meshes.topology(mesh)) # This converts the fancy `verts` into a plain old Matrix{Float64}. points = stack(p -> Meshes.ustrip.(Meshes.to(p)), verts) # This creates VTK cells that we can eventually write out, converting the Meshes.jl connectivity into VTK MeshCells. cells = [WriteVTK.MeshCell(WriteVTK.VTKCellTypes.VTK_TRIANGLE, Meshes.indices(c)) for c in connec] # Now we can finally create a VTK file. vtkfile = WriteVTK.vtk_grid(name, points, cells) return vtkfile end r""" to_paraview_collection(name::AbstractString, ses::NTuple{N, AbstractArray{<:AbstractCompactSourceElement}}; time_axes::NTuple{N, Int64}=ntuple(i->1, N), block_names=["block$(b)" for b in 1:N], observers=(), observer_names=nothing, observer_radii=nothing) Construct and write out a ParaView collection data file (`.pvd`) object for a tuple of arrays of `CompactF1ASourceElement`s with name `name.pvd` (i.e., the `name` argument should not contain a file extension). `time_axes` is a tuple of time axis indices, one for each entry of `ses`, indicating the axis over which the source time for the source elements in `ses` vary. `block_names` is a `Vector` of strings, one for each entry in `ses`, that will be used to name each `ses` entry in the multiblock VTK file. `observers` should be an iterable of `AbstractAcousticObserver` objects that will also be written out to the paraview file as discretized spheres. `observer_names` can either be an iterable of Strings that will be used to name each VTK observer file, or `nothing`, in which case each observer will be named `observer<int>`. `observer_radii` can either be an iterable of Float64 representing the radius of each observer sphere, or `nothing`, in which case a suitible radius will be calculated. One VTK PolyData (`.vtp`) file will be written for each valid index along `time_axis` for each array in the `ses` tuple. Returns a list of filenames written out by [WriteVTK.jl](https://github.com/jipolanco/WriteVTK.jl). """ function to_paraview_collection(name, ses::NTuple{N, AbstractArray{<:AbstractCompactSourceElement}}; time_axes::NTuple{N, Int64}=ntuple(i->1, N), block_names=["block$(b)" for b in 1:N], observers=(), observer_names=nothing, observer_radii=nothing) where {N} # Check that the size of each array in the `ses` is the the same along the time axis. # This will get the length of each array in `ses` along the time axis. time_axis_lengths = size.(ses, time_axes) # Now check if they're the same. if !all(time_axis_lengths .== first(time_axis_lengths)) throw(ArgumentError("length of each array in ses tuple must be the same along the time axis. Length of each: $(time_axis_lengths)")) end time_axis_len = first(time_axis_lengths) # Also check that the block names are unique. length(unique(block_names)) == N || throw(ArgumentError("entries in block_names = $(block_names) must be unique")) if length(observers) > 0 if observer_names === nothing obs_names = ["observer$(i)" for i in 1:length(observers)] else # Check that the number of observers matches the number of observer names. length(observer_names) == length(observers) || throw(ArgumentError("length of observer_names does not match length of observers")) # Check that the observer names are unique. length(unique(observer_names)) == length(observer_names) || throw(ArgumentError("entries in observer_names = $(observer_names) must be unique")) # Also should check that the observer names aren't the same as the source element block names. all_names = vcat(block_names, observer_names) length(unique(all_names)) == length(all_names) || throw(ArgumentError("observer_names = $(observer_names) shares entries with block_names = $(block_names)")) obs_names = observer_names end if observer_radii === nothing # Check out this sorcery. # (xmin, xmax) = mapreduce(x->extrema(getindex.(getproperty.(x, :y0dot), 1)), (a, b)->(min(a[1], b[1]), max(a[2], b[2])), ses) # (ymin, ymax) = mapreduce(x->extrema(getindex.(getproperty.(x, :y0dot), 2)), (a, b)->(min(a[1], b[1]), max(a[2], b[2])), ses) # (zmin, zmax) = mapreduce(x->extrema(getindex.(getproperty.(x, :y0dot), 3)), (a, b)->(min(a[1], b[1]), max(a[2], b[2])), ses) # But could I do it in one line? # That would mean I'd need to have a function that could take in a vector, then compare it to another vector. # ((xmin, ymin, zmin), (xmax, ymax, zmax)) = mapreduce( # (a, b)->((min(a[1][1], b[1][1]), # min(a[1][2], b[1][2]), # min(a[1][3], b[1][3])), # (max(a[2][1], b[2][1]), # max(a[2][2], b[2][2]), # max(a[2][3], b[2][3]))), ses) do x # xmin, xmax = extrema(getindex.(getproperty.(x, :y0dot), 1)) # ymin, ymax = extrema(getindex.(getproperty.(x, :y0dot), 2)) # zmin, zmax = extrema(getindex.(getproperty.(x, :y0dot), 3)) # return ((xmin, ymin, zmin), (xmax, ymax, zmax)) # end # Still kind of annoying that I have to iterate over each source element array three times. # How to avoid that? # It would come down to not using extrema. # I'd need a version of extrema that iterates over each vector, keeping track of the minimum and maximum of each element. ((xmin, ymin, zmin), (xmax, ymax, zmax)) = mapreduce( (a, b)->((min(a[1][1], b[1][1]), min(a[1][2], b[1][2]), min(a[1][3], b[1][3])), (max(a[2][1], b[2][1]), max(a[2][2], b[2][2]), max(a[2][3], b[2][3]))), ses) do X mins = (Inf, Inf, Inf) maxs = (-Inf, -Inf, -Inf) for x in X y0dot = x.y0dot mins = (min(y0dot[1], mins[1]), min(y0dot[2], mins[2]), min(y0dot[3], mins[3])) maxs = (max(y0dot[1], maxs[1]), max(y0dot[2], maxs[2]), max(y0dot[3], maxs[3])) end return mins, maxs end # Now find the diagonal of the boundary box. r = sqrt((xmax - xmin)^2 + (ymax - ymin)^2 + (zmax - zmin)^2) # Set the observer radii to be a fraction of that boundary box diagonal obs_radii = fill(0.02*r, length(observers)) else # Check that the length of observer_radii matches observers. length(observer_radii) == length(observers) || throw(ArgumentError("length of observer_radii does not match length of observers")) obs_radii = observer_radii end else obs_names = nothing obs_radii = nothing end outfiles = WriteVTK.paraview_collection(name) do pvd for tidx in 1:time_axis_len # We want to check that the source times for all elements we write out for this time index `tidx` is the same. # So get the time for the first element in the first array, and compare later. ses_first = first(ses) time_axis_first = first(time_axes) axes_first = axes(ses_first) idx_first = [d == time_axis_first ? axes_first[d][tidx] : axes_first[d][begin] for d in 1:ndims(ses_first)] t = source_time(ses_first[idx_first...]) # We will create a multiblock VTK file for each time step, with one block for each array in `ses`. name_mb = format(FormatExpr("{}-{:08d}"), name, tidx) WriteVTK.vtk_multiblock(name_mb) do vtm for (i, (sesi, time_axis)) in enumerate(zip(ses, time_axes)) # This will give me each valid index allong the time axis for `sesi`. time_indices = axes(sesi, time_axis) # This will give me a `:` for each dimension of `sesi` except for the dimension corresponding to `time_axis`. idx = [d == time_axis ? time_indices[tidx] : Colon() for d in 1:ndims(sesi)] # Now we can grab all the source elements we want. sesiv = @view sesi[idx...] # Now check if all the source times are what we expect. all(source_time.(sesiv) .β‰ˆ t) || thow(ArgumentError("ses[$i][$(idx)] does not have all source elements with source time $(t)")) # Now create a VTK file for the source elements we've selected. namei = format(FormatExpr("{}-{}-{:08d}"), name, block_names[i], tidx) vtkfile = to_vtp(namei, sesiv) # And add it to the multiblock file. WriteVTK.multiblock_add_block(vtm, vtkfile) end for (obs, obs_name, obs_radius) in zip(observers, obs_names, obs_radii) # Now also need to write out the observers. namei = format(FormatExpr("{}-{}-{:08d}"), name, obs_name, tidx) vtkfile = to_vtu(namei, obs, t; sphere_radius=obs_radius) WriteVTK.multiblock_add_block(vtm, vtkfile) end # Now add the the multiblock file to the paraview collection. pvd[t] = vtm end end end return outfiles end """ to_paraview_collection(name::AbstractString, ses::AbstractArray{<:AbstractCompactSourceElement}; time_axis::Integer=1) Construct and write out a ParaView collection data file (`.pvd`) object for an array of `AbstractCompactSourceElement`s with name `name.pvd` (i.e., the `name` argument should not contain a file extension). `time_axis` indicates the time_axis of `ses` over which the source time for the source elements in `ses` vary. One VTK PolyData (`.vtp`) file will be written for each valid index along `time_axis`. Returns a list of filenames written out by [WriteVTK.jl](https://github.com/jipolanco/WriteVTK.jl). """ function to_paraview_collection(name, ses::AbstractArray{<:AbstractCompactSourceElement}; time_axis=1) outfiles = WriteVTK.paraview_collection(name) do pvd # These are the time indices, i.e., the ones we actually want to iterate # over. time_indices = axes(ses, time_axis) # idx is all the indicies, including the time one that we want to iterate # over, and the others that we want to grab all at once. They're all colons # right now, but the time one will be replaced with each index in `indices` # in the `for i in indices` loop below. idx = [d == time_axis ? first(time_indices) : Colon() for d in 1:ndims(ses)] for (i, it) in enumerate(time_indices) idx[time_axis] = it namei = format(FormatExpr("{}{:08d}"), name, i) sesi = @view ses[idx...] vtkfile = to_vtp(namei, sesi) # Assume that all the times in sesi are the same. They should be if the # user specified the correct time_axis. I suppose I could check that and # issue a warning. t = first(sesi).Ο„ pvd[t] = vtkfile end end return outfiles end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
2044
module AdvancedTimeTests using AcousticAnalogies using LinearAlgebra: norm using NLsolve using StaticArrays using Test @testset "Advanced time tests" begin # Goal is to verify that the code can solve the equation # # R(t) = t - (Ο„ + |x(t) - y|/c0) = 0 # # for t, where Ο„ and y are the source time and position, t and x are the # observer time and position, and c0 is the (constant) speed of sound. # Create a source element for the test. # The only things about the source element that matters to the advanced # time calculation is the time and position, and the speed of sound. Ο„ = 2.5 y = @SVector [-4.0, 3.0, 6.0] c0 = 2.0 dummy0 = 1.0 dummy3 = @SVector [0.0, 0.0, 0.0] se = CompactF1ASourceElement(dummy0, c0, dummy0, dummy0, y, dummy3, dummy3, dummy3, dummy3, dummy3, Ο„, dummy3) # Define a function that takes a source element and an observer and compares # the advanced time solution to one found by NLsolve. function compare_to_nlsolve(se, obs) # Create the residual equation that we'll solve. nlsolve assumes the # residual function takes in and returns arrays. R(t) = [t[1] - (se.Ο„ + norm(obs(t[1]) .- se.y0dot)/se.c0)] # Solve the advanced time equation. result = nlsolve(R, [1.0], autodiff=:forward) if !converged(result) @error "nlsolve advanced time calculation did not converge:\n$(result)" end t_obs = result.zero[1] # Check that we can get the right answer. @test adv_time(se, obs) β‰ˆ t_obs return nothing end @testset "Stationary observer" begin x0 = @SVector [-3.0, 2.0, 8.5] obs = StationaryAcousticObserver(x0) compare_to_nlsolve(se, obs) end @testset "Constant velocity observer" begin t0 = 3.5 x0 = @SVector [-2.0, 3.5, 6.25] v = @SVector [-1.5, 1.5, 3.25] obs = ConstVelocityAcousticObserver(t0, x0, v) compare_to_nlsolve(se, obs) end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
5596
module ANOPP2Comparison # const DO_PLOTS = false using FLOWMath: FLOWMath using Test: Test # if DO_PLOTS # import Plots # end using Printf: @sprintf include(joinpath(@__DIR__, "anopp2_run.jl")) using .ANOPP2Run: get_results Test.@testset "ANOPP2 Comparison" begin function compare_results(; stationary_observer, theta, f_interp, rpm, irpm) t, p_thickness_interp, p_loading_interp, p_monopole_a2_interp, p_dipole_a2_interp = get_results(; stationary_observer, theta, f_interp, rpm, irpm) # Now compare the results from the two codes. max_aerr_thickness = maximum(abs.(p_thickness_interp - p_monopole_a2_interp)) p_thickness_ref = maximum(p_monopole_a2_interp) - minimum(p_monopole_a2_interp) max_aerr_thickness_scaled = max_aerr_thickness / p_thickness_ref tol = 0.01 Test.@test max_aerr_thickness_scaled < tol if ! (max_aerr_thickness_scaled < tol) println("stationary_observer = $(stationary_observer), theta = $(theta*180.0/pi) deg, rpm = $(rpm), thickness aerr_scaled = $(max_aerr_thickness_scaled)") end p_loading_ref = maximum(p_dipole_a2_interp) - minimum(p_dipole_a2_interp) max_aerr_loading = maximum(abs.(p_loading_interp - p_dipole_a2_interp)) max_aerr_loading_scaled = max_aerr_loading / p_loading_ref tol = 0.01 if theta β‰ˆ 0.0 tol = 0.01 else if rpm β‰ˆ 200.0 # The 200.0 RPM case is strange. The thrust and torque # are actually negative, and the loading noise looks # especially different from what ANOPP2 predicts. tol = 0.045 else tol = 0.01 end end Test.@test max_aerr_loading_scaled < tol if ! (max_aerr_loading_scaled < tol) println("stationary_observer = $(stationary_observer), theta = $(theta*180.0/pi) deg, rpm = $(rpm), loading aerr_scaled = $(max_aerr_loading_scaled)") end # if DO_PLOTS # # Create a plot. # p_apth = Plots.plot(legend=:topleft, foreground_color_legend=nothing, background_color_legend=nothing) # # Plot original data. # Plots.plot!(p_apth, obs_time, p_thickness, label="thickness", seriescolor=:blue, markershape=:x) # Plots.plot!(p_apth, obs_time, p_loading, label="loading", seriescolor=:red, markershape=:x) # Plots.plot!(p_apth, t_a2, p_monopole_a2, label="ANOPP2 monopole", seriescolor=:blue, markershape=:+, markerstrokecolor=:blue) # Plots.plot!(p_apth, t_a2, p_dipole_a2, label="ANOPP2 dipole", seriescolor=:red, markershape=:+, markerstrokecolor=:red) # # Plot interpolated data. # Plots.plot!(p_apth, t, p_thickness_interp, label="thickness, interp", seriescolor=:blue, markershape=:star4, markerstrokecolor=:blue, markercolor=nothing) # Plots.plot!(p_apth, t, p_loading_interp, label="loading, interp", seriescolor=:red, markershape=:star4, markerstrokecolor=:red, markercolor=nothing) # Plots.plot!(p_apth, t, p_monopole_a2_interp, label="ANOPP2 monopole, interp", seriescolor=:blue, markershape=:star6, markerstrokecolor=:blue, markercolor=nothing) # Plots.plot!(p_apth, t, p_dipole_a2_interp, label="ANOPP2 dipole, interp", seriescolor=:red, markershape=:star6, markerstrokecolor=:red, markercolor=nothing) # # Make the plot look good. # if theta β‰ˆ 0.0 # Plots.ylims!(p_apth, apth_ylims_xrotor[irpm]) # end # Plots.xlims!(p_apth, (0.0, 1.0)) # Plots.xlabel!(p_apth, "t/t_blade_pass") # Plots.ylabel!(p_apth, "acoustic pressure, Pa") # # Save the plot. # theta_int = Int(round(theta*180.0/pi)) # if stationary_observer # if f_interp === FLOWMath.akima # Plots.savefig(p_apth, "p_apth_$(@sprintf "%04d" Int(round(rpm[irpm])))rpm_theta$(theta_int)_akima.png") # elseif f_interp === FLOWMath.linear # Plots.savefig(p_apth, "p_apth_$(@sprintf "%04d" Int(round(rpm[irpm])))rpm_theta$(theta_int)_linear.png") # else # Plots.savefig(p_apth, "p_apth_$(@sprintf "%04d" Int(round(rpm[irpm])))rpm_theta$(theta_int)_other.png") # end # else # if f_interp === FLOWMath.akima # Plots.savefig(p_apth, "p_apth_const_vel_$(@sprintf "%04d" Int(round(rpm[irpm])))rpm_theta$(theta_int)_akima.png") # elseif f_interp === FLOWMath.linear # Plots.savefig(p_apth, "p_apth_const_vel_$(@sprintf "%04d" Int(round(rpm[irpm])))rpm_theta$(theta_int)_linear.png") # else # Plots.savefig(p_apth, "p_apth_const_vel_$(@sprintf "%04d" Int(round(rpm[irpm])))rpm_theta$(theta_int)_other.png") # end # end # end end # Actually run the tests. for f_interp in [FLOWMath.akima, FLOWMath.linear] for theta in [0.0, -45.0*pi/180.0] for stationary_observer in [true, false] for (i, rpm) in enumerate(200.0:200.0:2200.0) # rev/min # get_results(stationary_observer=stationary_observer, theta=theta, f_interp=f_interp, rpm=rpm, irpm=i) compare_results(; stationary_observer=stationary_observer, theta=theta, f_interp=f_interp, rpm=rpm, irpm=i) end end end end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
5541
module ANOPP2Run using AcousticMetrics: AcousticMetrics import AcousticAnalogies, DelimitedFiles, FLOWMath using StaticArrays: @SVector, SVector using KinematicCoordinateTransformations: KinematicCoordinateTransformations, compose using Printf: @sprintf using LinearAlgebra: Γ— using FileIO: load include(joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "constants.jl")) using .CCBladeTestCaseConstants ccbc = CCBladeTestCaseConstants # This is a function that will do the AcousticAnalogies.jl noise calculation with the new # observer stuff. function cf1a_noise(num_blades, v, omega, radii, dradii, cs_area, fn, fc, stationary_observer, theta, f_interp) t0 = 0.0 rot_axis = @SVector [0.0, 0.0, 1.0] blade_axis = @SVector [0.0, 1.0, 0.0] x0 = SVector{3}([cos(theta), 0.0, sin(theta)].*100.0.*12.0.*0.0254) # 100 ft in meters y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = SVector{3}(v.*rot_axis) num_src_times = 256 num_obs_times = 2*num_src_times # Blade Passing Period. bpp = 2*pi/omega/num_blades src_time_range = 5.0*bpp obs_time_range = 4.0*bpp if stationary_observer obs = AcousticAnalogies.StationaryAcousticObserver(x0) else obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0, x0, v0_hub) end rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, omega, 0.0) global_trans = KinematicCoordinateTransformations.ConstantLinearMap(hcat(rot_axis, blade_axis, rot_axisΓ—blade_axis)) const_vel_trans = KinematicCoordinateTransformations.ConstantVelocityTransformation(t0, y0_hub, v0_hub) # This is just an array of the angular offsets of each blade. ΞΈs = 2*pi/num_blades.*(0:(num_blades-1)) dt = src_time_range/(num_src_times - 1) src_times = t0 .+ (0:num_src_times-1).*dt ΞΈs = reshape(ΞΈs, 1, 1, :) radii = reshape(radii, 1, :, 1) dradii = reshape(dradii, 1, :, 1) cs_area = reshape(cs_area, 1, :, 1) fn = reshape(fn, 1, :, 1) fc = reshape(fc, 1, :, 1) src_times = reshape(src_times, :, 1, 1) # This isn't really necessary. # Get all the transformations! trans = compose.(src_times, Ref(const_vel_trans), compose.(src_times, Ref(global_trans), Ref(rot_trans))) # Transform the source elements. ses = AcousticAnalogies.CompactF1ASourceElement.(ccbc.rho, ccbc.c0, radii, ΞΈs, dradii, cs_area, -fn, 0.0, fc, src_times) .|> trans # Do the acoustics. apth = AcousticAnalogies.noise.(ses, Ref(obs)) # Combine all the acoustic pressure time histories into one. apth_total = AcousticAnalogies.combine(apth, obs_time_range, num_obs_times, 1; f_interp=f_interp) return AcousticMetrics.time(apth_total), AcousticAnalogies.pressure_monopole(apth_total), AcousticAnalogies.pressure_dipole(apth_total) end function get_results(; stationary_observer, theta, f_interp, rpm, irpm) apth_ylims_xrotor = [ (-0.0001, 0.0001), (-0.0005, 0.0005), (-0.0020, 0.0020), (-0.005, 0.005), (-0.010, 0.010), (-0.020, 0.020), (-0.05, 0.05), (-0.10, 0.10), (-0.20, 0.20), (-0.5, 0.5), (-1.0, 1.0)] dradii = AcousticAnalogies.get_dradii(ccbc.radii, ccbc.Rhub, ccbc.Rtip) cs_area = ccbc.area_over_chord_squared .* ccbc.chord.^2 omega = rpm*(2*pi/60.0) # Get the normal and circumferential loading from the CCBlade output. fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega$(@sprintf "%02d" irpm)-outputs.jld2") data_d = load(fname) fn = data_d["Np"] fc = data_d["Tp"] # Blade passing period. bpp = 2*pi/omega/ccbc.num_blades # Calculate the noise with AcousticAnalogies.jl. obs_time, p_thickness, p_loading = cf1a_noise(ccbc.num_blades, ccbc.v, omega, ccbc.radii, dradii, cs_area, fn, fc, stationary_observer, theta, f_interp) t0 = obs_time[1] # Nondimensionalize the observer time with the blade passing period. obs_time = (obs_time .- t0)./bpp # Read the ANOPP2 data. if theta β‰ˆ 0.0 if stationary_observer fname = joinpath(@__DIR__, "gen_test_data", "anopp2_omega$(@sprintf "%02d" irpm).csv") data = DelimitedFiles.readdlm(fname, ',') else fname = joinpath(@__DIR__, "gen_test_data", "anopp2_const_vel_omega$(@sprintf "%02d" irpm).csv") data = DelimitedFiles.readdlm(fname, ',') end else theta_int = Int(round(theta*180.0/pi)) if stationary_observer fname = joinpath(@__DIR__, "gen_test_data", "anopp2_omega$(@sprintf "%02d" irpm)_theta$(theta_int).csv") data = DelimitedFiles.readdlm(fname, ',') else fname = joinpath(@__DIR__, "gen_test_data", "anopp2_const_vel_omega$(@sprintf "%02d" irpm)_theta$(theta_int).csv") data = DelimitedFiles.readdlm(fname, ',') end end t_a2 = data[:, 1] p_monopole_a2 = data[:, 2] p_dipole_a2 = data[:, 3] # Nondimensionalize the observer time with the blade passing period. t_a2 = (t_a2 .- t0)./bpp # Let's interpolate both the AcousticAnalogies.jl and ANOPP2 data onto a common time # domain. t = range(0.0, 1.0, length=128) p_thickness_interp = FLOWMath.akima(obs_time, p_thickness, t) p_loading_interp = FLOWMath.akima(obs_time, p_loading, t) p_monopole_a2_interp = FLOWMath.akima(t_a2, p_monopole_a2, t) p_dipole_a2_interp = FLOWMath.akima(t_a2, p_dipole_a2, t) return t, p_thickness_interp, p_loading_interp, p_monopole_a2_interp, p_dipole_a2_interp end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
21795
module BoundaryLayerTests using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: AcousticMetrics using DelimitedFiles: DelimitedFiles using FLOWMath: linear using Test @testset "boundary layer thickness" begin @testset "zero angle of attack" begin @testset "untripped" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure06-bl_thickness-untripped.csv") bpm_untripped = DelimitedFiles.readdlm(fname, ',') Re_c_1e6 = bpm_untripped[:, 1] delta0_c = bpm_untripped[:, 2] # Get the AcousticAnalogies.jl implementation. Re_c_1e6_jl = range(minimum(Re_c_1e6), maximum(Re_c_1e6); length=50) delta0_c_jl = AcousticAnalogies.bl_thickness_0.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), Re_c_1e6_jl.*1e6) # Interpolate the BPM report data onto the uniform Re spacing. delta0_c_interp = linear(Re_c_1e6, delta0_c, Re_c_1e6_jl) # Find the scaled error. vmin, vmax = extrema(delta0_c) err = abs.(delta0_c_jl .- delta0_c_interp)/(vmax - vmin) @test maximum(err) < 0.041 end @testset "tripped" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure06-bl_thickness-tripped.csv") bpm_tripped = DelimitedFiles.readdlm(fname, ',') Re_c_1e6 = bpm_tripped[:, 1] delta0_c = bpm_tripped[:, 2] # Get the AcousticAnalogies.jl implementation. Re_c_1e6_jl = range(minimum(Re_c_1e6), maximum(Re_c_1e6); length=50) delta0_c_jl = AcousticAnalogies.bl_thickness_0.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), Re_c_1e6_jl.*1e6) # Interpolate the BPM report data onto the uniform Re spacing. delta0_c_interp = linear(Re_c_1e6, delta0_c, Re_c_1e6_jl) # Find the scaled error. vmin, vmax = extrema(delta0_c) err = abs.(delta0_c_jl .- delta0_c_interp)/(vmax - vmin) @test maximum(err) < 0.0086 end end @testset "non-zero angle of attack, tripped" begin @testset "pressure side" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure07-bl_thickness-pressure_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] delta_bpm = bpm_pressure_side[:, 2] # Get the AcousticAnalogies.jl implementation. alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) delta_jl = AcousticAnalogies._bl_thickness_p.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) # Interpolate the BPM report data onto the uniform alpha spacing. delta_bpm_interp = linear(alpha_deg, delta_bpm, alpha_deg_jl) # Find the scaled error. vmin, vmax = extrema(delta_bpm) err = abs.(delta_jl .- delta_bpm_interp)./(vmax - vmin) @test maximum(err) < 0.032 end @testset "suction side" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure07-bl_thickness-suction_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] delta_bpm = bpm_pressure_side[:, 2] # Get the AcousticAnalogies.jl implementation. alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) delta_jl = AcousticAnalogies._bl_thickness_s.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) # Interpolate the BPM report data onto the uniform alpha spacing. delta_bpm_interp = linear(alpha_deg, delta_bpm, alpha_deg_jl) # Find the scaled error. vmin, vmax = extrema(delta_bpm) err = abs.(delta_jl .- delta_bpm_interp)./(vmax - vmin) @test maximum(err) < 0.023 end end @testset "non-zero angle of attack, untripped" begin @testset "pressure side" begin # Non-zero boundary layer thickness for the pressure side is the same for tripped and untripped, so getting the data for the tripped case. # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure07-bl_thickness-pressure_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] delta_bpm = bpm_pressure_side[:, 2] # Get the AcousticAnalogies.jl implementation. alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) delta_jl = AcousticAnalogies._bl_thickness_p.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) # Interpolate the BPM report data onto the uniform alpha spacing. delta_bpm_interp = linear(alpha_deg, delta_bpm, alpha_deg_jl) # Find the scaled error. vmin, vmax = extrema(delta_bpm) err = abs.(delta_jl .- delta_bpm_interp)./(vmax - vmin) @test maximum(err) < 0.032 end @testset "suction side" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure08-bl_thickness-suction_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] delta_bpm = bpm_pressure_side[:, 2] # Get the AcousticAnalogies.jl implementation. alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) delta_jl = AcousticAnalogies._bl_thickness_s.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) # Interpolate the BPM report data onto the uniform alpha spacing. delta_bpm_interp = linear(alpha_deg, delta_bpm, alpha_deg_jl) # Find the scaled error. vmin, vmax = extrema(delta_bpm) err = abs.(delta_jl .- delta_bpm_interp)./(vmax - vmin) @test maximum(err) < 0.028 end end @testset "positive/negative angle of attack" begin for bl in [AcousticAnalogies.TrippedN0012BoundaryLayer(), AcousticAnalogies.UntrippedN0012BoundaryLayer()] for Re_c in (range(0.04, 3.0; length=30)) .* 10^6 for alphastar_deg in 0:30 alphastar = alphastar_deg*pi/180 # For a positive angle of attack, the pressure side should be the bottom side. delta_p = AcousticAnalogies.bl_thickness_p(bl, Re_c, alphastar) delta_bot = AcousticAnalogies.bl_thickness_bot(bl, Re_c, alphastar) @test delta_p β‰ˆ delta_bot # For a positive angle of attack, the suction side should be the top side. delta_s = AcousticAnalogies.bl_thickness_s(bl, Re_c, alphastar) delta_top = AcousticAnalogies.bl_thickness_top(bl, Re_c, alphastar) @test delta_s β‰ˆ delta_top # But if we switch the sign on alpha, the top and bottom switch too. delta_bot_neg = AcousticAnalogies.bl_thickness_bot(bl, Re_c, -alphastar) @test delta_bot_neg β‰ˆ delta_s delta_top_neg = AcousticAnalogies.bl_thickness_top(bl, Re_c, -alphastar) @test delta_top_neg β‰ˆ delta_p # But the value of the pressure and suction sides should never change. delta_p_neg = AcousticAnalogies.bl_thickness_p(bl, Re_c, -alphastar) @test delta_p_neg β‰ˆ delta_p delta_s_neg = AcousticAnalogies.bl_thickness_s(bl, Re_c, -alphastar) @test delta_s_neg β‰ˆ delta_s end end end end @testset "ITrip1N0012BoundaryLayer" begin bl = AcousticAnalogies.ITrip1N0012BoundaryLayer() bl_untripped = AcousticAnalogies.UntrippedN0012BoundaryLayer() bl_tripped = AcousticAnalogies.TrippedN0012BoundaryLayer() for Re_c in (range(0.04, 3.0; length=30)) .* 10^6 for alphastar in (-30:30) .* (pi/180) # Should use the untripped pressure-side and suction-side boundary layer thickness. @test AcousticAnalogies.bl_thickness_p(bl, Re_c, alphastar) β‰ˆ AcousticAnalogies.bl_thickness_p(bl_untripped, Re_c, alphastar) @test AcousticAnalogies.bl_thickness_s(bl, Re_c, alphastar) β‰ˆ AcousticAnalogies.bl_thickness_s(bl_untripped, Re_c, alphastar) # Should use the tripped displacement thickness. @test AcousticAnalogies.disp_thickness_p(bl, Re_c, alphastar) β‰ˆ AcousticAnalogies.disp_thickness_p(bl_tripped, Re_c, alphastar) @test AcousticAnalogies.disp_thickness_s(bl, Re_c, alphastar) β‰ˆ AcousticAnalogies.disp_thickness_s(bl_tripped, Re_c, alphastar) end end end @testset "ITrip2N0012BoundaryLayer" begin bl = AcousticAnalogies.ITrip2N0012BoundaryLayer() bl_untripped = AcousticAnalogies.UntrippedN0012BoundaryLayer() bl_tripped = AcousticAnalogies.TrippedN0012BoundaryLayer() for Re_c in (range(0.04, 3.0; length=30)) .* 10^6 for alphastar in (-30:30) .* (pi/180) # boundary layer thickness should be untripped multiplied by 0.6. @test AcousticAnalogies.bl_thickness_p(bl, Re_c, alphastar) β‰ˆ 0.6*AcousticAnalogies.bl_thickness_p(bl_untripped, Re_c, alphastar) @test AcousticAnalogies.bl_thickness_s(bl, Re_c, alphastar) β‰ˆ 0.6*AcousticAnalogies.bl_thickness_s(bl_untripped, Re_c, alphastar) # The pressure-side displacement thickness should be tripped multiplied by 0.6. @test AcousticAnalogies.disp_thickness_p(bl, Re_c, alphastar) β‰ˆ 0.6*AcousticAnalogies.disp_thickness_p(bl_tripped, Re_c, alphastar) # The suction-side displacement thickness should be the tripped zero-alpha displacement thickness multipled by 0.6 multiplied by the untripped suction-side to zero-alpha displacement thickness ratio. @test AcousticAnalogies.disp_thickness_s(bl, Re_c, alphastar) β‰ˆ AcousticAnalogies.disp_thickness_s(bl_tripped, Re_c, 0) * 0.6 * AcousticAnalogies.disp_thickness_s(bl_untripped, Re_c, alphastar) / AcousticAnalogies.disp_thickness_s(bl_untripped, Re_c, 0) end end end @testset "ITrip3N0012BoundaryLayer" begin bl = AcousticAnalogies.ITrip3N0012BoundaryLayer() bl_untripped = AcousticAnalogies.UntrippedN0012BoundaryLayer() bl_tripped = AcousticAnalogies.TrippedN0012BoundaryLayer() for Re_c in (range(0.04, 3.0; length=30)) .* 10^6 for alphastar in (-30:30) .* (pi/180) # boundary layer thickness should be untripped. @test AcousticAnalogies.bl_thickness_p(bl, Re_c, alphastar) β‰ˆ AcousticAnalogies.bl_thickness_p(bl_untripped, Re_c, alphastar) @test AcousticAnalogies.bl_thickness_s(bl, Re_c, alphastar) β‰ˆ AcousticAnalogies.bl_thickness_s(bl_untripped, Re_c, alphastar) # The pressure-side displacement thickness should be untripped multiplied by 1.48. @test AcousticAnalogies.disp_thickness_p(bl, Re_c, alphastar) β‰ˆ 1.48*AcousticAnalogies.disp_thickness_p(bl_untripped, Re_c, alphastar) # The suction-side displacement thickness should be the untripped. @test AcousticAnalogies.disp_thickness_s(bl, Re_c, alphastar) β‰ˆ AcousticAnalogies.disp_thickness_s(bl_untripped, Re_c, alphastar) end end end end @testset "displacement thickness" begin @testset "zero angle of attack" begin @testset "tripped" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure06-disp_thickness-tripped.csv") bpm_tripped = DelimitedFiles.readdlm(fname, ',') Re_c_1e6 = bpm_tripped[:, 1] deltastar0_c = bpm_tripped[:, 2] # Get the AcousticAnalogies.jl implementation. Re_c_1e6_jl = range(minimum(Re_c_1e6), maximum(Re_c_1e6); length=50) deltastar0_c_jl = AcousticAnalogies.disp_thickness_0.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), Re_c_1e6_jl.*1e6) # Interpolate the BPM report data onto the uniform Re spacing. deltastar0_c_interp = linear(Re_c_1e6, deltastar0_c, Re_c_1e6_jl) # Find the scaled error. vmin, vmax = extrema(deltastar0_c) err = abs.(deltastar0_c_jl .- deltastar0_c_interp)/(vmax - vmin) @test maximum(err) < 0.05 end @testset "untripped" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure06-disp_thickness-untripped.csv") bpm_untripped = DelimitedFiles.readdlm(fname, ',') Re_c_1e6 = bpm_untripped[:, 1] deltastar0_c = bpm_untripped[:, 2] # Get the AcousticAnalogies.jl implementation. Re_c_1e6_jl = range(minimum(Re_c_1e6), maximum(Re_c_1e6); length=50) deltastar0_c_jl = AcousticAnalogies.disp_thickness_0.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), Re_c_1e6_jl.*1e6) # Interpolate the BPM report data onto the uniform Re spacing. deltastar0_c_interp = linear(Re_c_1e6, deltastar0_c, Re_c_1e6_jl) # Find the scaled error. vmin, vmax = extrema(deltastar0_c) err = abs.(deltastar0_c_jl .- deltastar0_c_interp)/(vmax - vmin) @test maximum(err) < 0.02 end end @testset "non-zero angle of attack, tripped" begin @testset "pressure side" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure07-pressure_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] deltastar_bpm = bpm_pressure_side[:, 2] # Get the AcousticAnalogies.jl implementation. alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._disp_thickness_p.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) # Interpolate the BPM report data onto the uniform alpha spacing. deltastar_bpm_interp = linear(alpha_deg, deltastar_bpm, alpha_deg_jl) # Find the scaled error. vmin, vmax = extrema(deltastar_bpm) err = abs.(deltastar_jl .- deltastar_bpm_interp)./(vmax - vmin) @test maximum(err) < 0.06 end @testset "suction side" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure07-suction_side.csv") bpm_suction_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_suction_side[:, 1] deltastar_bpm = bpm_suction_side[:, 2] # Get the AcousticAnalogies.jl implementation. alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._disp_thickness_s.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) # Interpolate the BPM report data onto the uniform alpha spacing. deltastar_bpm_interp = linear(alpha_deg, deltastar_bpm, alpha_deg_jl) # Find the scaled error. vmin, vmax = extrema(deltastar_bpm) err = abs.(deltastar_jl .- deltastar_bpm_interp)./(vmax - vmin) @test maximum(err) < 0.04 end end @testset "non-zero angle of attack, untripped" begin @testset "boundary layer thickness, pressure side" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure08-bl_thickness-pressure_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] delta_bpm = bpm_pressure_side[:, 2] # Get the AcousticAnalogies.jl implementation. alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) delta_jl = AcousticAnalogies._bl_thickness_p.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) # Interpolate the BPM report onto the uniform alpha spacing. delta_bpm_interp = linear(alpha_deg, delta_bpm, alpha_deg_jl) # Find the scaled error. vmin, vmax = extrema(delta_bpm) err = abs.(delta_jl .- delta_bpm_interp)./(vmax - vmin) @test maximum(err) < 0.037 end @testset "displacement thickness, pressure side" begin # Get the digitized data from the BPM report plot. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure08-pressure_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] deltastar_bpm = bpm_pressure_side[:, 2] # Get the AcousticAnalogies.jl implementation. alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._disp_thickness_p.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) # Interpolate the BPM report onto the uniform alpha spacing. deltastar_bpm_interp = linear(alpha_deg, deltastar_bpm, alpha_deg_jl) # Find the scaled error. vmin, vmax = extrema(deltastar_bpm) err = abs.(deltastar_jl .- deltastar_bpm_interp)./(vmax - vmin) # This is dumb. Maybe I have a bug? @test maximum(err) < 0.11 end @testset "displacement thinckness, suction side" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure08-suction_side.csv") bpm_suction_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_suction_side[:, 1] deltastar_bpm = bpm_suction_side[:, 2] alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._disp_thickness_s.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) deltastar_bpm_interp = linear(alpha_deg, deltastar_bpm, alpha_deg_jl) vmin, vmax = extrema(deltastar_bpm) err = abs.(deltastar_jl .- deltastar_bpm_interp)./(vmax - vmin) # This is dumb. Maybe I have a bug? @test maximum(err) < 0.081 end end @testset "positive/negative angle of attack" begin for bl in [AcousticAnalogies.TrippedN0012BoundaryLayer(), AcousticAnalogies.UntrippedN0012BoundaryLayer()] for Re_c in (range(0.04, 3.0; length=30)) .* 10^6 for alphastar_deg in 0:30 alphastar = alphastar_deg*pi/180 # For a positive angle of attack, the pressure side should be the bottom side. deltastar_p = AcousticAnalogies.disp_thickness_p(bl, Re_c, alphastar) deltastar_bot = AcousticAnalogies.disp_thickness_bot(bl, Re_c, alphastar) @test deltastar_p β‰ˆ deltastar_bot # For a positive angle of attack, the suction side should be the top side. deltastar_s = AcousticAnalogies.disp_thickness_s(bl, Re_c, alphastar) deltastar_top = AcousticAnalogies.disp_thickness_top(bl, Re_c, alphastar) @test deltastar_s β‰ˆ deltastar_top # But if we switch the sign on alpha, the top and bottom switch too. deltastar_bot_neg = AcousticAnalogies.disp_thickness_bot(bl, Re_c, -alphastar) @test deltastar_bot_neg β‰ˆ deltastar_s deltastar_top_neg = AcousticAnalogies.disp_thickness_top(bl, Re_c, -alphastar) @test deltastar_top_neg β‰ˆ deltastar_p # But the value of the pressure and suction sides should never change. deltastar_p_neg = AcousticAnalogies.disp_thickness_p(bl, Re_c, -alphastar) @test deltastar_p_neg β‰ˆ deltastar_p deltastar_s_neg = AcousticAnalogies.disp_thickness_s(bl, Re_c, -alphastar) @test deltastar_s_neg β‰ˆ deltastar_s end end end end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
698
module BPMITRTests using SafeTestsets: @safetestset using Test: @testset @testset "BPM.jl comparisons" begin @safetestset "figure 22b" begin include("itr_figure22b_bpmjl.jl") end @safetestset "figure 23c" begin include("itr_figure23c_bpmjl.jl") end @safetestset "figure 24b" begin include("itr_figure24b_bpmjl.jl") end end @testset "PAS/ROTONET/BARC comparisons" begin @safetestset "figure 22b" begin include("itr_figure22b_barc.jl") end @safetestset "figure 23c" begin include("itr_figure23c_barc.jl") end @safetestset "figure 24b" begin include("itr_figure24b_barc.jl") end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
25867
module BPMShapeFunctionTests using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: AcousticMetrics using DelimitedFiles: DelimitedFiles using FLOWMath: linear using Test @testset "shape functions" begin @testset "TBL-TE" begin @testset "St_1" begin @test isapprox(AcousticAnalogies.St_1(0.093), 0.081; atol=0.0022) @test isapprox(AcousticAnalogies.St_1(0.116), 0.071; atol=0.002) @test isapprox(AcousticAnalogies.St_1(0.163), 0.059; atol=0.0004) @test isapprox(AcousticAnalogies.St_1(0.209), 0.051; atol=0.0002) end @testset "K_1" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure77.csv") bpm = DelimitedFiles.readdlm(fname, ',') Re_c_bpm = bpm[:, 1] K_1_bpm = bpm[:, 2] Re_c_jl = range(minimum(Re_c_bpm), maximum(Re_c_bpm); length=50) K_1_jl = AcousticAnalogies.K_1.(Re_c_jl) K_1_interp = linear(Re_c_bpm, K_1_bpm, Re_c_jl) vmin, vmax = extrema(K_1_bpm) err = abs.(K_1_jl .- K_1_interp)./(vmax - vmin) @test maximum(err) < 0.012 end @testset "A" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure78-A_min.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_St_peak_bpm = bpm[:, 1] A = bpm[:, 2] St_St_peak_jl = range(minimum(St_St_peak_bpm), maximum(St_St_peak_bpm); length=50) A_jl = AcousticAnalogies.A.(St_St_peak_jl, 9.5e4) # Interpolate: A_interp = linear(St_St_peak_bpm, A, St_St_peak_jl) # Check error. vmin, vmax = extrema(A) err = abs.(A_jl .- A_interp)./(vmax - vmin) @test maximum(err) < 0.057 fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure78-A_max.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_St_peak_bpm = bpm[:, 1] A = bpm[:, 2] St_St_peak_jl = range(minimum(St_St_peak_bpm), maximum(St_St_peak_bpm); length=50) A_jl = AcousticAnalogies.A.(St_St_peak_jl, 8.58e5) # Interpolate: A_interp = linear(St_St_peak_bpm, A, St_St_peak_jl) # Check error. vmin, vmax = extrema(A) err = abs.(A_jl .- A_interp)./(vmax - vmin) @test maximum(err) < 0.021 end @testset "B" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure78-B_min.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_St_peak_bpm = bpm[:, 1] B = bpm[:, 2] St_St_peak_jl = range(minimum(St_St_peak_bpm), maximum(St_St_peak_bpm); length=50) B_jl = AcousticAnalogies.B.(St_St_peak_jl, 9.5e4) # Interpolate: B_interp = linear(St_St_peak_bpm, B, St_St_peak_jl) # Check error. vmin, vmax = extrema(B) err = abs.(B_jl .- B_interp)./(vmax - vmin) @test maximum(err) < 0.057 fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure78-B_max.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_St_peak_bpm = bpm[:, 1] B = bpm[:, 2] St_St_peak_jl = range(minimum(St_St_peak_bpm), maximum(St_St_peak_bpm); length=50) B_jl = AcousticAnalogies.B.(St_St_peak_jl, 8.58e5) # Interpolate: B_interp = linear(St_St_peak_bpm, B, St_St_peak_jl) # Check error. vmin, vmax = extrema(B) err = abs.(B_jl .- B_interp)./(vmax - vmin) @test maximum(err) < 0.020 end @testset "St_2" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure80-M0.093.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] St_2 = bpm[:, 2] alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) St_2_jl = AcousticAnalogies.St_2.(AcousticAnalogies.St_1(0.093), alpha_deg_jl.*pi/180) # Interpolate: St_2_interp = linear(alpha_deg, St_2, alpha_deg_jl) # Check error. vmin, vmax = extrema(St_2) err = abs.(St_2_jl .- St_2_interp)./(vmax - vmin) @test maximum(err) < 0.023 fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure80-M0.209.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] St_2 = bpm[:, 2] alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) St_2_jl = AcousticAnalogies.St_2.(AcousticAnalogies.St_1(0.209), alpha_deg_jl.*pi/180) # Interpolate: St_2_interp = linear(alpha_deg, St_2, alpha_deg_jl) # Check error. vmin, vmax = extrema(St_2) err = abs.(St_2_jl .- St_2_interp)./(vmax - vmin) @test maximum(err) < 0.011 end @testset "K_2" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure82-M0.093.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] K_2_K_1 = bpm[:, 2] alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=200) K_2_K_1_jl = AcousticAnalogies.K_2.(1e6, 0.093, alpha_deg_jl.*pi/180) .- AcousticAnalogies.K_1(1e6) # Interpolate: K_2_K_1_interp = linear(alpha_deg, K_2_K_1, alpha_deg_jl) # Check error. vmin, vmax = extrema(K_2_K_1) err = abs.(K_2_K_1_jl .- K_2_K_1_interp)./(vmax - vmin) # The curve is almost vertical at low angles of attack, so a small error in the digitization results in big differences. @test maximum(err[2:end]) < 0.027 fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure82-M0.116.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] K_2_K_1 = bpm[:, 2] alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=200) K_2_K_1_jl = AcousticAnalogies.K_2.(1e6, 0.116, alpha_deg_jl.*pi/180) .- AcousticAnalogies.K_1(1e6) # Interpolate: K_2_K_1_interp = linear(alpha_deg, K_2_K_1, alpha_deg_jl) # Check error. vmin, vmax = extrema(K_2_K_1) err = abs.(K_2_K_1_jl .- K_2_K_1_interp)./(vmax - vmin) # There's a branch for low angles of attack that sets K_2 - K_1 to # -1000, but I can't see that in the digitized plots, so the first # point is bad. @test K_2_K_1_jl[1] β‰ˆ -1000 @test maximum(err[2:end]) < 0.022 fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure82-M0.163.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] K_2_K_1 = bpm[:, 2] alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=200) K_2_K_1_jl = AcousticAnalogies.K_2.(1e6, 0.163, alpha_deg_jl.*pi/180) .- AcousticAnalogies.K_1(1e6) # Interpolate: K_2_K_1_interp = linear(alpha_deg, K_2_K_1, alpha_deg_jl) # Check error. vmin, vmax = extrema(K_2_K_1) err = abs.(K_2_K_1_jl .- K_2_K_1_interp)./(vmax - vmin) # There's a branch for low angles of attack that sets K_2 - K_1 to # -1000, but I can't see that in the digitized plots, so the first # point is bad. @test K_2_K_1_jl[1] β‰ˆ -1000.0 @test maximum(err[2:end]) < 0.020 fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure82-M0.209.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] K_2_K_1 = bpm[:, 2] alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=200) K_2_K_1_jl = AcousticAnalogies.K_2.(1e6, 0.209, alpha_deg_jl.*pi/180) .- AcousticAnalogies.K_1(1e6) # Interpolate: K_2_K_1_interp = linear(alpha_deg, K_2_K_1, alpha_deg_jl) # Check error. vmin, vmax = extrema(K_2_K_1) err = abs.(K_2_K_1_jl .- K_2_K_1_interp)./(vmax - vmin) @test maximum(err) < 0.024 end end @testset "LBL-VS" begin @testset "St_1_prime" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure86-St_1_prime.csv") bpm = DelimitedFiles.readdlm(fname, ',') Re_c_bpm = bpm[:, 1] St_1_prime_bpm = bpm[:, 2] Re_c_jl = 10.0.^(range(4, 7; length=100)) St_1_prime_jl = AcousticAnalogies.St_1_prime.(Re_c_jl) St_1_prime_interp = linear(Re_c_bpm, St_1_prime_bpm, Re_c_jl) vmin, vmax = extrema(St_1_prime_bpm) err = abs.(St_1_prime_interp .- St_1_prime_jl)./(vmax - vmin) @test maximum(err) < 0.04 end @testset "G1" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure85-G1.csv") bpm = DelimitedFiles.readdlm(fname, ',') e_bpm = bpm[:, 1] G1_bpm = bpm[:, 2] e_jl = 10.0.^(range(-1, 1; length=101)) G1_jl = AcousticAnalogies.G1.(e_jl) G1_interp = linear(e_jl, G1_jl, e_bpm) vmin, vmax = extrema(G1_bpm) err = abs.(G1_interp .- G1_bpm)./(vmax - vmin) @test maximum(err) < 0.033 end @testset "St_peak_prime_alphastar" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure87.csv") bpm = DelimitedFiles.readdlm(fname, ',') alphastar_bpm = bpm[:, 1] St_peak_ratio_bpm = bpm[:, 2] St_1_prime = 0.25 # Just make up a value, since we're multiplying and then dividing by it anyway. alphastar_jl = range(0.0*pi/180, 7.0*pi/180; length=21) St_peak_ratio_jl = AcousticAnalogies.St_peak_prime.(St_1_prime, alphastar_jl)./St_1_prime St_peak_ratio_interp = linear(alphastar_jl.*180/pi, St_peak_ratio_jl, alphastar_bpm) vmin, vmax = extrema(St_peak_ratio_bpm) err = abs.(St_peak_ratio_interp .- St_peak_ratio_bpm)./(vmax - vmin) @test maximum(err) < 0.031 end @testset "G2" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure89.csv") bpm = DelimitedFiles.readdlm(fname, ',') Re_ratio_bpm = bpm[:, 1] G2_bpm = bpm[:, 2] Re_ratio_jl = 10.0.^range(-1, 1, length=51) G2_jl = AcousticAnalogies.G2.(Re_ratio_jl) G2_interp = linear(Re_ratio_jl, G2_jl, Re_ratio_bpm) vmin, vmax = extrema(G2_interp) err = abs.(G2_interp .- G2_bpm)./(vmax - vmin) @test maximum(err) < 0.024 end @testset "G2 + G3" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure88-G2-alpha0.csv") alphastar = 0.0*pi/180 bpm = DelimitedFiles.readdlm(fname, ',') Re_c_bpm = bpm[:, 1] G2_bpm = bpm[:, 2] Re_c_jl = 10.0.^range(log10(first(Re_c_bpm)), log10(last(Re_c_bpm)), length=51) Re_c0 = AcousticAnalogies.Re_c0(alphastar) Re_ratio_jl = Re_c_jl./Re_c0 G2_jl = AcousticAnalogies.G2.(Re_ratio_jl) .+ AcousticAnalogies.G3.(alphastar) G2_interp = linear(Re_c_jl, G2_jl, Re_c_bpm) vmin, vmax = extrema(G2_interp) err = abs.(G2_interp .- G2_bpm)./(vmax - vmin) @test maximum(err) < 0.013 fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure88-G2-alpha6.csv") alphastar = 6.0*pi/180 bpm = DelimitedFiles.readdlm(fname, ',') Re_c_bpm = bpm[:, 1] G2_bpm = bpm[:, 2] Re_c_jl = 10.0.^range(log10(first(Re_c_bpm)), log10(last(Re_c_bpm)), length=51) Re_c0 = AcousticAnalogies.Re_c0(alphastar) Re_ratio_jl = Re_c_jl./Re_c0 G2_jl = AcousticAnalogies.G2.(Re_ratio_jl) .+ AcousticAnalogies.G3.(alphastar) G2_interp = linear(Re_c_jl, G2_jl, Re_c_bpm) vmin, vmax = extrema(G2_interp) err = abs.(G2_interp .- G2_bpm)./(vmax - vmin) @test maximum(err) < 0.030 end end @testset "TEB-VS" begin @testset "St_3prime_peak" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure95-0Psi.csv") bpm = DelimitedFiles.readdlm(fname, ',') h_over_deltastar_0Psi = bpm[:, 1] St_3prime_peak_0Psi = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure95-14Psi.csv") bpm = DelimitedFiles.readdlm(fname, ',') h_over_deltastar_14Psi = bpm[:, 1] St_3prime_peak_14Psi = bpm[:, 2] h_over_deltastar_jl = 10.0.^(range(-1, 1; length=101)) St_3prime_peak_0Psi_jl = AcousticAnalogies.St_3prime_peak.(h_over_deltastar_jl, 0.0*pi/180) St_3prime_peak_14Psi_jl = AcousticAnalogies.St_3prime_peak.(h_over_deltastar_jl, 14.0*pi/180) St_3prime_peak_0Psi_interp = linear(h_over_deltastar_jl, St_3prime_peak_0Psi_jl, h_over_deltastar_0Psi) vmin, vmax = extrema(St_3prime_peak_0Psi) err = abs.(St_3prime_peak_0Psi_interp .- St_3prime_peak_0Psi)./(vmax - vmin) @test maximum(err) < 0.070 St_3prime_peak_14Psi_interp = linear(h_over_deltastar_jl, St_3prime_peak_14Psi_jl, h_over_deltastar_14Psi) vmin, vmax = extrema(St_3prime_peak_14Psi) err = abs.(St_3prime_peak_14Psi_interp .- St_3prime_peak_14Psi)./(vmax - vmin) @test maximum(err) < 0.049 end @testset "G4" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure96-0Psi.csv") bpm = DelimitedFiles.readdlm(fname, ',') h_over_deltastar_0Psi = bpm[:, 1] G4_0Psi = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure96-14Psi.csv") bpm = DelimitedFiles.readdlm(fname, ',') h_over_deltastar_14Psi = bpm[:, 1] G4_14Psi = bpm[:, 2] h_over_deltastar_jl = 10.0.^(range(-1, 1; length=51)) G4_0Psi_jl = AcousticAnalogies.G4.(h_over_deltastar_jl, 0.0*pi/180) G4_14Psi_jl = AcousticAnalogies.G4.(h_over_deltastar_jl, 14.0*pi/180) G4_0Psi_interp = linear(h_over_deltastar_jl, G4_0Psi_jl, h_over_deltastar_0Psi) vmin, vmax = extrema(G4_0Psi) err = abs.(G4_0Psi_interp .- G4_0Psi)./(vmax - vmin) @test maximum(err) < 0.033 G4_14Psi_interp = linear(h_over_deltastar_jl, G4_14Psi_jl, h_over_deltastar_14Psi) vmin, vmax = extrema(G4_14Psi) err = abs.(G4_14Psi_interp .- G4_14Psi)./(vmax - vmin) @test maximum(err) < 0.024 end @testset "G5, Psi = 14Β°" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p25.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p25 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p25 = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p43.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p43 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p43 = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p50.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p50 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p50 = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p54.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p54 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p54 = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p62.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p62 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p62 = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar1p20.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_1p20 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg1p20 = bpm[:, 2] St_3prime_over_St_3prime_peak_jl = 10.0.^(range(-1, 10; length=1001)) G5_14Psi_h_over_deltastar_avg0p25_jl = AcousticAnalogies.G5_Psi14.(0.25, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg0p43_jl = AcousticAnalogies.G5_Psi14.(0.43, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg0p50_jl = AcousticAnalogies.G5_Psi14.(0.50, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg0p54_jl = AcousticAnalogies.G5_Psi14.(0.54, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg0p62_jl = AcousticAnalogies.G5_Psi14.(0.62, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg1p20_jl = AcousticAnalogies.G5_Psi14.(1.20, St_3prime_over_St_3prime_peak_jl) interp = linear(St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p25_jl, St_3prime_over_St_3prime_peak_0p25) vmin, vmax = extrema(G5_14Psi_h_over_deltastar_avg0p25) err = abs.(interp .- G5_14Psi_h_over_deltastar_avg0p25)/(vmax - vmin) @test maximum(err) < 0.074 interp = linear(St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p43_jl, St_3prime_over_St_3prime_peak_0p43) vmin, vmax = extrema(G5_14Psi_h_over_deltastar_avg0p43) err = abs.(interp .- G5_14Psi_h_over_deltastar_avg0p43)/(vmax - vmin) @test maximum(err) < 0.072 interp = linear(St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p50_jl, St_3prime_over_St_3prime_peak_0p50) vmin, vmax = extrema(G5_14Psi_h_over_deltastar_avg0p50) err = abs.(interp .- G5_14Psi_h_over_deltastar_avg0p50)/(vmax - vmin) @test maximum(err) < 0.072 interp = linear(St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p54_jl, St_3prime_over_St_3prime_peak_0p54) vmin, vmax = extrema(G5_14Psi_h_over_deltastar_avg0p54) err = abs.(interp .- G5_14Psi_h_over_deltastar_avg0p54)/(vmax - vmin) @test maximum(err) < 0.074 interp = linear(St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p62_jl, St_3prime_over_St_3prime_peak_0p62) vmin, vmax = extrema(G5_14Psi_h_over_deltastar_avg0p62) err = abs.(interp .- G5_14Psi_h_over_deltastar_avg0p62)/(vmax - vmin) @test maximum(err) < 0.073 interp = linear(St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg1p20_jl, St_3prime_over_St_3prime_peak_1p20) vmin, vmax = extrema(G5_14Psi_h_over_deltastar_avg1p20) err = abs.(interp .- G5_14Psi_h_over_deltastar_avg1p20)/(vmax - vmin) # The lower end of this case is really bad. # Not sure why. :-( @test maximum(err[1:22]) < 0.31 @test maximum(err[23:end]) < 0.087 end @testset "G5, Psi = 0Β°" begin fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p25.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p25 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg0p25 = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p43.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p43 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg0p43 = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p50.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p50 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg0p50 = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p54.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p54 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg0p54 = bpm[:, 2] # fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p62.csv") # bpm = DelimitedFiles.readdlm(fname, ',') # St_3prime_over_St_3prime_peak_0p62 = bpm[:, 1] # G5_0Psi_h_over_deltastar_avg0p62 = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar1p20.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_1p20 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg1p20 = bpm[:, 2] St_3prime_over_St_3prime_peak_jl = 10.0.^(range(-1, 10; length=1001)) G5_0Psi_h_over_deltastar_avg0p25_jl = AcousticAnalogies.G5_Psi0.(0.25, St_3prime_over_St_3prime_peak_jl) G5_0Psi_h_over_deltastar_avg0p43_jl = AcousticAnalogies.G5_Psi0.(0.43, St_3prime_over_St_3prime_peak_jl) G5_0Psi_h_over_deltastar_avg0p50_jl = AcousticAnalogies.G5_Psi0.(0.50, St_3prime_over_St_3prime_peak_jl) G5_0Psi_h_over_deltastar_avg0p54_jl = AcousticAnalogies.G5_Psi0.(0.54, St_3prime_over_St_3prime_peak_jl) # G5_0Psi_h_over_deltastar_avg0p62_jl = AcousticAnalogies.G5_Psi0.(0.62, St_3prime_over_St_3prime_peak_jl) G5_0Psi_h_over_deltastar_avg1p20_jl = AcousticAnalogies.G5_Psi0.(1.20, St_3prime_over_St_3prime_peak_jl) interp = linear(St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p25_jl, St_3prime_over_St_3prime_peak_0p25) vmin, vmax = extrema(G5_0Psi_h_over_deltastar_avg0p25) err = abs.(interp .- G5_0Psi_h_over_deltastar_avg0p25)/(vmax - vmin) @test maximum(err) < 0.030 interp = linear(St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p43_jl, St_3prime_over_St_3prime_peak_0p43) vmin, vmax = extrema(G5_0Psi_h_over_deltastar_avg0p43) err = abs.(interp .- G5_0Psi_h_over_deltastar_avg0p43)/(vmax - vmin) @test maximum(err) < 0.026 interp = linear(St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p50_jl, St_3prime_over_St_3prime_peak_0p50) vmin, vmax = extrema(G5_0Psi_h_over_deltastar_avg0p50) err = abs.(interp .- G5_0Psi_h_over_deltastar_avg0p50)/(vmax - vmin) @test maximum(err) < 0.037 interp = linear(St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p54_jl, St_3prime_over_St_3prime_peak_0p54) vmin, vmax = extrema(G5_0Psi_h_over_deltastar_avg0p54) err = abs.(interp .- G5_0Psi_h_over_deltastar_avg0p54)/(vmax - vmin) @test maximum(err) < 0.037 # interp = linear(St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p62_jl, St_3prime_over_St_3prime_peak_0p62) # vmin, vmax = extrema(G5_0Psi_h_over_deltastar_avg0p62) # err = abs.(interp .- G5_0Psi_h_over_deltastar_avg0p62)/(vmax - vmin) # @test maximum(err) < 0.073 interp = linear(St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg1p20_jl, St_3prime_over_St_3prime_peak_1p20) vmin, vmax = extrema(G5_0Psi_h_over_deltastar_avg1p20) err = abs.(interp .- G5_0Psi_h_over_deltastar_avg1p20)/(vmax - vmin) @test maximum(err) < 0.045 end end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
11602
module BPMWriteVTKTest using AcousticAnalogies using CCBlade """ XROTORAirfoilConfig(A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) `struct` that holds all the required parameters for XROTOR's approach to handling airfoil lift and drag polars. # Arguments - `A0`: zero lift angle of attack, radians. - `DCLDA`: lift curve slope, 1/radians. - `CLMAX`: stall Cl. - `CLMIN`: negative stall Cl. - `DCL_STALL`: CL increment from incipient to total stall. - `DCLDA_STALL`: stalled lift curve slope, 1/radian. - `CDMIN`: minimum Cd. - `CLDMIN`: Cl at minimum Cd. - `DCDCL2`: d(Cd)/d(Cl**2). - `REREF`: Reynolds Number at which Cd values apply. - `REXP`: Exponent for Re scaling of Cd: Cd ~ Re**exponent - `MCRIT`: Critical Mach number. """ struct XROTORAirfoilConfig{TF} A0::TF # = 0. # zero lift angle of attack radians DCLDA::TF # = 6.28 # lift curve slope /radian CLMAX::TF # = 1.5 # stall Cl CLMIN::TF # = -0.5 # negative stall Cl DCL_STALL::TF # = 0.1 # CL increment from incipient to total stall DCLDA_STALL::TF # = 0.1 # stalled lift curve slope /radian CDMIN::TF # = 0.013 # minimum Cd CLDMIN::TF # = 0.5 # Cl at minimum Cd DCDCL2::TF # = 0.004 # d(Cd)/d(Cl**2) REREF::TF # = 200000. # Reynolds Number at which Cd values apply REXP::TF # = -0.4 # Exponent for Re scaling of Cd: Cd ~ Re**exponent MCRIT::TF # = 0.8 # Critical Mach number end function XROTORAirfoilConfig(; A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) return XROTORAirfoilConfig(A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) end """ af_xrotor(alpha, Re, Mach, config::XROTORAirfoilConfig) Return a tuple of the lift and drag coefficients for a given angle of attach `alpha` (in radians), Reynolds number `Re`, and Mach number `Mach`. """ function af_xrotor(alpha, Re, Mach, config::XROTORAirfoilConfig) # C------------------------------------------------------------ # C CL(alpha) function # C Note that in addition to setting CLIFT and its derivatives # C CLMAX and CLMIN (+ and - stall CL's) are set in this routine # C In the compressible range the stall CL is reduced by a factor # C proportional to Mcrit-Mach. Stall limiting for compressible # C cases begins when the compressible drag added CDC > CDMstall # C------------------------------------------------------------ # C CD(alpha) function - presently CD is assumed to be a sum # C of profile drag + stall drag + compressibility drag # C In the linear lift range drag is CD0 + quadratic function of CL-CLDMIN # C In + or - stall an additional drag is added that is proportional # C to the extent of lift reduction from the linear lift value. # C Compressible drag is based on adding drag proportional to # C (Mach-Mcrit_eff)^MEXP # C------------------------------------------------------------ # C CM(alpha) function - presently CM is assumed constant, # C varying only with Mach by Prandtl-Glauert scaling # C------------------------------------------------------------ # C # INCLUDE 'XROTOR.INC' # LOGICAL STALLF # DOUBLE PRECISION ECMIN, ECMAX # C # C---- Factors for compressibility drag model, HHY 10/23/00 # C Mcrit is set by user # C Effective Mcrit is Mcrit_eff = Mcrit - CLMFACTOR*(CL-CLDmin) - DMDD # C DMDD is the delta Mach to get CD=CDMDD (usually 0.0020) # C Compressible drag is CDC = CDMFACTOR*(Mach-Mcrit_eff)^MEXP # C CDMstall is the drag at which compressible stall begins # A0 = config.A0 DCLDA = config.DCLDA CLMAX = config.CLMAX CLMIN = config.CLMIN DCL_STALL = config.DCL_STALL DCLDA_STALL = config.DCLDA_STALL CDMIN = config.CDMIN CLDMIN = config.CLDMIN DCDCL2 = config.DCDCL2 REREF = config.REREF REXP = config.REXP MCRIT = config.MCRIT CDMFACTOR = 10.0 CLMFACTOR = 0.25 MEXP = 3.0 CDMDD = 0.0020 CDMSTALL = 0.1000 # C # C---- Prandtl-Glauert compressibility factor # MSQ = W*W*VEL^2/VSO^2 # MSQ_W = 2.0*W*VEL^2/VSO^2 # if (MSQ>1.0) # # WRITE(*,*) # # & 'CLFUNC: Local Mach number limited to 0.99, was ', MSQ # MSQ = 0.99 # # MSQ_W = 0. # end MSQ = Mach*Mach if MSQ > 1.0 MSQ = 0.99 Mach = sqrt(MSQ) end PG = 1.0 / sqrt(1.0 - MSQ) # PG_W = 0.5*MSQ_W * PG^3 # C # C---- Mach number and dependence on velocity # Mach = sqrt(MSQ) # MACH_W = 0.0 # IF(Mach.NE.0.0) MACH_W = 0.5*MSQ_W/Mach # if ! (mach β‰ˆ 0.0) # MACH_W = 0.5*MSQ_W/Mach # end # C # C # C------------------------------------------------------------ # C--- Generate CL from dCL/dAlpha and Prandtl-Glauert scaling CLA = DCLDA*PG *(alpha-A0) # CLA_ALF = DCLDA*PG # CLA_W = DCLDA*PG_W*(ALF-A0) # C # C--- Effective CLmax is limited by Mach effects # C reduces CLmax to match the CL of onset of serious compressible drag CLMX = CLMAX CLMN = CLMIN DMSTALL = (CDMSTALL/CDMFACTOR)^(1.0/MEXP) CLMAXM = max(0.0, (MCRIT+DMSTALL-Mach)/CLMFACTOR) + CLDMIN CLMAX = min(CLMAX,CLMAXM) CLMINM = min(0.0,-(MCRIT+DMSTALL-Mach)/CLMFACTOR) + CLDMIN CLMIN = max(CLMIN,CLMINM) # C # C--- CL limiter function (turns on after +-stall ECMAX = exp( min(200.0, (CLA-CLMAX)/DCL_STALL) ) ECMIN = exp( min(200.0, (CLMIN-CLA)/DCL_STALL) ) CLLIM = DCL_STALL * log( (1.0+ECMAX)/(1.0+ECMIN) ) CLLIM_CLA = ECMAX/(1.0+ECMAX) + ECMIN/(1.0+ECMIN) # c # c if(CLLIM.GT.0.001) then # c write(*,999) 'cla,cllim,ecmax,ecmin ',cla,cllim,ecmax,ecmin # c endif # c 999 format(a,2(1x,f10.6),3(1x,d12.6)) # C # C--- Subtract off a (nearly unity) fraction of the limited CL function # C This sets the dCL/dAlpha in the stalled regions to 1-FSTALL of that # C in the linear lift range FSTALL = DCLDA_STALL/DCLDA CLIFT = CLA - (1.0-FSTALL)*CLLIM # CL_ALF = CLA_ALF - (1.0-FSTALL)*CLLIM_CLA*CLA_ALF # CL_W = CLA_W - (1.0-FSTALL)*CLLIM_CLA*CLA_W # C # STALLF = false # IF(CLIFT.GT.CLMAX) STALLF = .TRUE. # IF(CLIFT.LT.CLMIN) STALLF = .TRUE. # STALLF = (CLIFT > CLMAX) || (CLIFT < CLMIN) # C # C # C------------------------------------------------------------ # C--- CM from CMCON and Prandtl-Glauert scaling # CMOM = PG*CMCON # CM_AL = 0.0 # CM_W = PG_W*CMCON # C # C # C------------------------------------------------------------ # C--- CD from profile drag, stall drag and compressibility drag # C # C---- Reynolds number scaling factor if (Re < 0.0) RCORR = 1.0 # RCORR_REY = 0.0 else RCORR = (Re/REREF)^REXP # RCORR_REY = REXP/Re end # C # C--- In the basic linear lift range drag is a function of lift # C CD = CD0 (constant) + quadratic with CL) CDRAG = (CDMIN + DCDCL2*(CLIFT-CLDMIN)^2 ) * RCORR # CD_ALF = ( 2.0*DCDCL2*(CLIFT-CLDMIN)*CL_ALF) * RCORR # CD_W = ( 2.0*DCDCL2*(CLIFT-CLDMIN)*CL_W ) * RCORR # CD_REY = CDRAG*RCORR_REY # C # C--- Post-stall drag added FSTALL = DCLDA_STALL/DCLDA DCDX = (1.0-FSTALL)*CLLIM/(PG*DCLDA) # c write(*,*) 'cla,cllim,fstall,pg,dclda ',cla,cllim,fstall,pg,dclda DCD = 2.0* DCDX^2 # DCD_ALF = 4.0* DCDX * (1.0-FSTALL)*CLLIM_CLA*CLA_ALF/(PG*DCLDA) # DCD_W = 4.0* DCDX * ( (1.0-FSTALL)*CLLIM_CLA*CLA_W/(PG*DCLDA) - DCD/PG*PG_W ) # c write(*,*) 'alf,cl,dcd,dcd_alf,dcd_w ',alf,clift,dcd,dcd_alf,dcd_w # C # C--- Compressibility drag (accounts for drag rise above Mcrit with CL effects # C CDC is a function of a scaling factor*(M-Mcrit(CL))^MEXP # C DMDD is the Mach difference corresponding to CD rise of CDMDD at MCRIT DMDD = (CDMDD/CDMFACTOR)^(1.0/MEXP) CRITMACH = MCRIT-CLMFACTOR*abs(CLIFT-CLDMIN) - DMDD # CRITMACH_ALF = -CLMFACTOR*ABS(CL_ALF) # CRITMACH_W = -CLMFACTOR*ABS(CL_W) if (Mach < CRITMACH) CDC = 0.0 # CDC_ALF = 0.0 # CDC_W = 0.0 else CDC = CDMFACTOR*(Mach-CRITMACH)^MEXP # CDC_W = MEXP*MACH_W*CDC/Mach - MEXP*CRITMACH_W *CDC/CRITMACH # CDC_ALF = - MEXP*CRITMACH_ALF*CDC/CRITMACH end # c write(*,*) 'critmach,mach ',critmach,mach # c write(*,*) 'cdc,cdc_w,cdc_alf ',cdc,cdc_w,cdc_alf # C FAC = 1.0 # FAC_W = 0.0 # C--- Although test data does not show profile drag increases due to Mach # # C you could use something like this to add increase drag by Prandtl-Glauert # C (or any function you choose) # cc FAC = PG # cc FAC_W = PG_W # C--- Total drag terms CDRAG = FAC*CDRAG + DCD + CDC # CD_ALF = FAC*CD_ALF + DCD_ALF + CDC_ALF # CD_W = FAC*CD_W + FAC_W*CDRAG + DCD_W + CDC_W # CD_REY = FAC*CD_REY # C return CLIFT, CDRAG end function main(; positive_x_rotation) # Define the blade geometry. B = 2 Rhub = 0.10 Rtip = 1.1684 # meters radii = Rhub .+ range(0.0, 1.0, length=31).*(Rtip - Rhub) radii = 0.5.*(radii[2:end] .+ radii[1:end-1]) cs_area_over_chord_squared = 0.064 chord = [ 0.35044 , 0.28260 , 0.22105 , 0.17787 , 0.14760, 0.12567 , 0.10927 , 0.96661E-01 , 0.86742E-01 , 0.78783E-01 , 0.72287E-01 , 0.66906E-01 , 0.62387E-01 , 0.58541E-01 , 0.55217E-01 , 0.52290E-01 , 0.49645E-01 , 0.47176E-01 , 0.44772E-01 , 0.42326E-01 , 0.39732E-01 , 0.36898E-01 , 0.33752E-01 , 0.30255E-01 , 0.26401E-01 , 0.22217E-01 , 0.17765E-01 , 0.13147E-01 , 0.85683E-02 , 0.47397E-02].*Rtip theta = [ 40.005, 34.201, 28.149, 23.753, 20.699, 18.516, 16.890, 15.633, 14.625, 13.795, 13.094, 12.488, 11.956, 11.481, 11.053, 10.662, 10.303, 9.9726, 9.6674, 9.3858, 9.1268, 8.8903, 8.6764, 8.4858, 8.3193, 8.1783, 8.0638, 7.9769, 7.9183, 7.8889].*(pi/180) # Define the operating point. rpm = 2200.0 omega = rpm*(2*pi/60.0) rho = 1.226 # kg/m^3 c0 = 340.0 # m/s mu = 0.1780e-4 # kg/(m*s) pitch = 0.0 # rad Vinf = 5.0 # m/s # Create an airfoil interpolation object. xrotor_config = XROTORAirfoilConfig( A0=0.0, DCLDA=6.2800, CLMAX=1.5, CLMIN=-0.5, DCLDA_STALL=0.1, DCL_STALL=0.1, MCRIT=0.8, CDMIN=0.13e-1, CLDMIN=0.5, DCDCL2=0.4e-2, REREF=0.2e6, REXP=-0.4) airfoil_interp(a, r, m) = af_xrotor(a, r, m, xrotor_config) # Create the CCBlade.jl structs. rotor = Rotor(Rhub, Rtip, B) sections = Section.(radii, chord, theta, Ref(airfoil_interp)) ops = OperatingPoint.(Vinf, omega.*radii, rho, pitch, mu, c0) outs = solve.(Ref(rotor), sections, ops) # Create the AcousticAnalogies.jl source elements. bpp = 60/(rpm*B) period = 2*bpp num_source_times = 64 alphastar0 = 12.5*pi/180 ses = tblte_source_elements_ccblade(rotor, sections, ops, outs, fill(TrippedN0012BoundaryLayer(), length(radii)), period, num_source_times, positive_x_rotation) @show size(ses) if positive_x_rotation name = "two_blade_example_tblte_pos_x_rotation" else name = "two_blade_example_tblte_neg_x_rotation" end outfiles = AcousticAnalogies.to_paraview_collection(name, ses) return outfiles end end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
143411
module BroadbandSourceElementTests using AcousticAnalogies using AcousticAnalogies: calculate_bpm_test using AcousticMetrics: AcousticMetrics using CCBlade using DelimitedFiles: DelimitedFiles using FileIO: load using FLOWMath: linear using KinematicCoordinateTransformations: KinematicCoordinateTransformations, compose using StaticArrays using JLD2 using Test using LinearAlgebra: norm, dot, cross include("gen_test_data/gen_ccblade_data/constants.jl") using .CCBladeTestCaseConstants ccbc = CCBladeTestCaseConstants @testset "Twist and rotation tests" begin # So, the way this should work: first do the twist, then do the theta rotation. # The twist could be either about the positive y axis or negative y axis. # Then the theta rotation is always about the x axis. c0 = 1.1 nu = 1.2 r = 2.0 Ξ”r = 0.1 chord = 1.3 h = 1.4 Psi = 1.5 vn = 2.0 vr = 3.0 vc = 4.0 Ο„ = 0.1 Δτ = 0.02 bl = 2.0 # should be a boundary layer struct, but doesn't matter for these tests. blade_tip = 3.0 # should be a blade tip struct, but doesn't matter for these tests. for setype in [TBLTESourceElement, LBLVSSourceElement, TEBVSSourceElement, TipVortexSourceElement, CombinedNoTipBroadbandSourceElement, CombinedWithTipBroadbandSourceElement] for twist_about_positive_y in [true, false] if setype == CombinedWithTipBroadbandSourceElement se_0twist0theta = setype(c0, nu, r, 0.0, Ξ”r, chord, 0.0, h, Psi, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) elseif setype == TipVortexSourceElement se_0twist0theta = setype(c0, r, 0.0, Ξ”r, chord, 0.0, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) elseif setype in (TEBVSSourceElement, CombinedNoTipBroadbandSourceElement) se_0twist0theta = setype(c0, nu, r, 0.0, Ξ”r, chord, 0.0, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) else se_0twist0theta = setype(c0, nu, r, 0.0, Ξ”r, chord, 0.0, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) end for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) for Ο• in [5, 10, 65, 95, 260, 270, 290].*(pi/180) # The angle of attack depends on the twist and the fluid velocity if twist_about_positive_y alpha_check = Ο• - atan(-vn, -vc) else alpha_check = Ο• - atan(-vn, vc) end if setype == CombinedWithTipBroadbandSourceElement se = setype(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) |> trans_theta elseif setype == TipVortexSourceElement se = setype(c0, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) |> trans_theta elseif setype in (TEBVSSourceElement, CombinedNoTipBroadbandSourceElement) se = setype(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) |> trans_theta else se = setype(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) |> trans_theta end # Adjust the angles of attack to always be between -pi and pi. alpha_check = rem2pi(alpha_check+pi, RoundNearest) - pi alpha = rem2pi(AcousticAnalogies.angle_of_attack(se)+pi, RoundNearest) - pi @test alpha β‰ˆ alpha_check for field in fieldnames(setype) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if field != :chord_uvec @test getproperty(se, field) β‰ˆ getproperty(se_0twist0theta, field) end end if twist_about_positive_y # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -Ο•) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, Ο•) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check # Make sure we get the same thing if we specify the velocity via a velocity magnitude and angle of attack. # But need to make sure we use vr == 0. if setype == CombinedWithTipBroadbandSourceElement se_no_vr = setype(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, 0.0, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) elseif setype == TipVortexSourceElement se_no_vr = setype(c0, r, ΞΈ, Ξ”r, chord, Ο•, vn, 0.0, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) elseif setype in (TEBVSSourceElement, CombinedNoTipBroadbandSourceElement) se_no_vr = setype(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, 0.0, vc, Ο„, Δτ, bl, twist_about_positive_y) else se_no_vr = setype(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, 0.0, vc, Ο„, Δτ, bl, twist_about_positive_y) end # Removing vr, the radial velocity component, shouldn't change the angle of attack. alpha_no_vr = rem2pi(AcousticAnalogies.angle_of_attack(se_no_vr)+pi, RoundNearest) - pi @test alpha_no_vr β‰ˆ alpha_check # Now create a source element using the velocity magnitude and angle of attack, check that we get the same thing. U = sqrt(vn^2 + vc^2) if setype == CombinedWithTipBroadbandSourceElement se_from_U_Ξ± = setype(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, alpha_no_vr, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) elseif setype == TipVortexSourceElement se_from_U_Ξ± = setype(c0, r, ΞΈ, Ξ”r, chord, Ο•, U, alpha_no_vr, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) elseif setype in (TEBVSSourceElement, CombinedNoTipBroadbandSourceElement) se_from_U_Ξ± = setype(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, U, alpha_no_vr, Ο„, Δτ, bl, twist_about_positive_y) else se_from_U_Ξ± = setype(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, U, alpha_no_vr, Ο„, Δτ, bl, twist_about_positive_y) end for field in fieldnames(setype) @test getproperty(se_from_U_Ξ±, field) β‰ˆ getproperty(se_no_vr, field) end end end end end end @testset "TBLTESourceElement twist and rotation tests, CCBlade" begin # Create the CCBlade objects. Ο„ = 0.1 Δτ = 0.02 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11.jld2") # out, section_loaded, Ξ”r, op, rotor0precone = nothing, nothing, nothing, nothing, nothing # jldopen(ccblade_fname, "r") do f # out = f["outs"][1] # section_loaded = f["sections"][1] # Ξ”r = f["sections"][2].r - f["sections"][1].r # op = f["ops"][1] # rotor0precone = f["rotor"] # @test rotor0precone.precone β‰ˆ 0.0 # end ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11-outputs.jld2") outs_d = load(ccblade_fname) section_loaded = CCBlade.Section(first(ccbc.radii), first(ccbc.chord), first(ccbc.theta)*pi/180, nothing) Ξ”r = ccbc.radii[2] - ccbc.radii[1] op = CCBlade.OperatingPoint(ccbc.v, outs_d["omega"]*first(ccbc.radii), ccbc.rho, ccbc.pitch, ccbc.mu, ccbc.c0) rotor0precone = CCBlade.Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades) out = CCBlade.Outputs(outs_d["Np"][1], outs_d["Tp"][1], outs_d["a"][1], outs_d["ap"][1], outs_d["u"][1], outs_d["v"][1], outs_d["phi"][1], outs_d["alpha"][1], outs_d["W"][1], outs_d["cl"][1], outs_d["cd"][1], outs_d["cn"][1], outs_d["ct"][1], outs_d["F"][1], outs_d["G"][1]) @test rotor0precone.precone β‰ˆ 0.0 for positive_x_rotation in [true, false] for twist in [5, 10, 65, 95, 260, 270, 290].*(pi/180) section = CCBlade.Section(section_loaded.r, section_loaded.chord, twist, section_loaded.af) se_0theta0precone = TBLTESourceElement(rotor0precone, section, op, out, 0.0, Ξ”r, Ο„, Δτ, bl, positive_x_rotation) for precone in [5, 10, 65, 95, 260, 270, 290].*(pi/180) rotor = CCBlade.Rotor(rotor0precone.Rhub, rotor0precone.Rtip, rotor0precone.B; turbine=rotor0precone.turbine, precone=precone) # This is tricky: in my "normal" coordinate system, the blade is rotating around the x axis, moving axially in the positive x direction, and is initially aligned with the y axis. # That means that the precone should be a rotation around the negative z axis. # And so to undo it, we want a positive rotation around the positive z axis. trans_precone = KinematicCoordinateTransformations.SteadyRotZTransformation(Ο„, 0.0, precone) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) # Create a transformation that reverses the theta and precone rotations. # The precone happens first, then theta. # So to reverse it we need to do theta, then precone. trans = KinematicCoordinateTransformations.compose(Ο„, trans_precone, trans_theta) # Create a source element with the theta and precone rotations, then undo it. se = TBLTESourceElement(rotor, section, op, out, ΞΈ, Ξ”r, Ο„, Δτ, bl, positive_x_rotation) |> trans # Check that we got the same thing: for field in fieldnames(TBLTESourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if !(field in (:chord_uvec, :bl)) @test getproperty(se, field) β‰ˆ getproperty(se_0theta0precone, field) end end if positive_x_rotation # If we're doing a positive-x rotation, we're applying the twist about the positive y axis. # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -twist) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're doing a negative-x rotation, we're applying the twist about the negative y axis. # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, twist) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end end @testset "CCBlade TBLTESourceElement complete test" begin for positive_x_rotation in [true, false] omega = 2200*(2*pi/60) # Create the CCBlade objects. rotor = Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades; turbine=false) sections = Section.(ccbc.radii, ccbc.chord, ccbc.theta, nothing) ops = simple_op.(ccbc.v, omega, ccbc.radii, ccbc.rho; asound=ccbc.c0) # What actually matters in the output structs are just W and phi. phi = range(45.0, 10.0; length=length(sections)) .* (pi/180) W = range(10.0, 11.0; length=length(sections)) outs = Outputs.(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, phi, 0.0, W, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) # Set the source time stuff. num_blade_passes = 3 steps_per_blade_pass = 8 num_src_times = num_blade_passes*steps_per_blade_pass bpp = 2*pi/omega/ccbc.num_blades src_time_range = num_blade_passes*bpp # Finally get all the source elements. bls = [AcousticAnalogies.TrippedN0012BoundaryLayer()] ses_helper = tblte_source_elements_ccblade(rotor, sections, ops, outs, bls, src_time_range, num_src_times, positive_x_rotation) # Now need to get the source elements the "normal" way. # First get the transformation objects. rot_axis = @SVector [1.0, 0.0, 0.0] blade_axis = @SVector [0.0, 1.0, 0.0] y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = ccbc.v.*rot_axis t0 = 0.0 if positive_x_rotation rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, omega, 0.0) else rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, -omega, 0.0) end const_vel_trans = KinematicCoordinateTransformations.ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Need the source times. dt = src_time_range/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # This is just an array of the angular offsets of each blade. ΞΈs = 2*pi/ccbc.num_blades.*(0:(ccbc.num_blades-1)) # Radial spacing. dradii = get_dradii(ccbc.radii, ccbc.Rhub, ccbc.Rtip) # Need the kinematic viscosity. nus = getproperty.(ops, :mu) ./ getproperty.(ops, :rho) # Also need the velocity in each direction. if positive_x_rotation vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. -W*cos(phi) else vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. W*cos(phi) end # Reshape stuff for broadcasting. radii_rs = reshape(ccbc.radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) phi_rs = reshape(phi, 1, :, 1) W_rs = reshape(W, 1, :, 1) src_times_rs = reshape(src_times, :, 1, 1) # This isn't really necessary. ΞΈs_rs = reshape(ΞΈs, 1, 1, :) nus_rs = reshape(nus, 1, :, 1) twist_rs = reshape(getproperty.(sections, :theta), 1, :, 1) chord_rs = reshape(getproperty.(sections, :chord), 1, :, 1) vn_rs = reshape(vn, 1, :, 1) vr_rs = reshape(vr, 1, :, 1) vc_rs = reshape(vc, 1, :, 1) # Get all the transformations. trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Transform the source elements. ses = TBLTESourceElement.(ccbc.c0, nus_rs, radii_rs, ΞΈs_rs, dradii_rs, chord_rs, twist_rs, vn_rs, vr_rs, vc_rs, src_times_rs, dt, bls, positive_x_rotation) .|> trans # Now check that we got the same thing. for field in fieldnames(TBLTESourceElement) if !(field in (:bl,)) @test all(getproperty.(ses_helper, field) .β‰ˆ getproperty.(ses, field)) end end end end @testset "LBLVSSourceElement twist and rotation tests" begin # So, the way this should work: first do the twist, then do the theta rotation. # The twist could be either about the positive y axis or negative y axis. # Then the theta rotation is always about the x axis. c0 = 1.1 nu = 1.2 r = 2.0 Ξ”r = 0.1 chord = 1.3 vn = 2.0 vr = 3.0 vc = 4.0 Ο„ = 0.1 Δτ = 0.02 bl = 2.0 # should be a boundary layer struct, but doesn't matter for these tests. for twist_about_positive_y in [true, false] se_0twist0theta = LBLVSSourceElement(c0, nu, r, 0.0, Ξ”r, chord, 0.0, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) for Ο• in [5, 10, 65, 95, 260, 270, 290].*(pi/180) # The angle of attack depends on the twist and the fluid velocity if twist_about_positive_y alpha_check = Ο• - atan(-vn, -vc) else alpha_check = Ο• - atan(-vn, vc) end se = LBLVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) |> trans_theta # Adjust the angles of attack to always be between -pi and pi. alpha_check = rem2pi(alpha_check+pi, RoundNearest) - pi alpha = rem2pi(AcousticAnalogies.angle_of_attack(se)+pi, RoundNearest) - pi @test alpha β‰ˆ alpha_check for field in fieldnames(LBLVSSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if field != :chord_uvec @test getproperty(se, field) β‰ˆ getproperty(se_0twist0theta, field) end end if twist_about_positive_y # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -Ο•) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, Ο•) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end @testset "LBLVSSourceElement twist and rotation tests, CCBlade" begin # Create the CCBlade objects. Ο„ = 0.1 Δτ = 0.02 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11.jld2") # out, section_loaded, Ξ”r, op, rotor0precone = nothing, nothing, nothing, nothing, nothing # jldopen(ccblade_fname, "r") do f # out = f["outs"][1] # section_loaded = f["sections"][1] # Ξ”r = f["sections"][2].r - f["sections"][1].r # op = f["ops"][1] # rotor0precone = f["rotor"] # @test rotor0precone.precone β‰ˆ 0.0 # end ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11-outputs.jld2") outs_d = load(ccblade_fname) section_loaded = CCBlade.Section(first(ccbc.radii), first(ccbc.chord), first(ccbc.theta)*pi/180, nothing) Ξ”r = ccbc.radii[2] - ccbc.radii[1] op = CCBlade.OperatingPoint(ccbc.v, outs_d["omega"]*first(ccbc.radii), ccbc.rho, ccbc.pitch, ccbc.mu, ccbc.c0) rotor0precone = CCBlade.Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades) out = CCBlade.Outputs(outs_d["Np"][1], outs_d["Tp"][1], outs_d["a"][1], outs_d["ap"][1], outs_d["u"][1], outs_d["v"][1], outs_d["phi"][1], outs_d["alpha"][1], outs_d["W"][1], outs_d["cl"][1], outs_d["cd"][1], outs_d["cn"][1], outs_d["ct"][1], outs_d["F"][1], outs_d["G"][1]) @test rotor0precone.precone β‰ˆ 0.0 for positive_x_rotation in [true, false] for twist in [5, 10, 65, 95, 260, 270, 290].*(pi/180) section = CCBlade.Section(section_loaded.r, section_loaded.chord, twist, section_loaded.af) se_0theta0precone = LBLVSSourceElement(rotor0precone, section, op, out, 0.0, Ξ”r, Ο„, Δτ, bl, positive_x_rotation) for precone in [5, 10, 65, 95, 260, 270, 290].*(pi/180) rotor = CCBlade.Rotor(rotor0precone.Rhub, rotor0precone.Rtip, rotor0precone.B; turbine=rotor0precone.turbine, precone=precone) # This is tricky: in my "normal" coordinate system, the blade is rotating around the x axis, moving axially in the positive x direction, and is initially aligned with the y axis. # That means that the precone should be a rotation around the negative z axis. # And so to undo it, we want a positive rotation around the positive z axis. trans_precone = KinematicCoordinateTransformations.SteadyRotZTransformation(Ο„, 0.0, precone) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) # Create a transformation that reverses the theta and precone rotations. # The precone happens first, then theta. # So to reverse it we need to do theta, then precone. trans = KinematicCoordinateTransformations.compose(Ο„, trans_precone, trans_theta) # Create a source element with the theta and precone rotations, then undo it. se = LBLVSSourceElement(rotor, section, op, out, ΞΈ, Ξ”r, Ο„, Δτ, bl, positive_x_rotation) |> trans # Check that we got the same thing: for field in fieldnames(LBLVSSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if !(field in (:chord_uvec, :bl)) @test getproperty(se, field) β‰ˆ getproperty(se_0theta0precone, field) end end if positive_x_rotation # If we're doing a positive-x rotation, we're applying the twist about the positive y axis. # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -twist) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're doing a negative-x rotation, we're applying the twist about the negative y axis. # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, twist) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end end @testset "CCBlade LBLVSSourceElement complete test" begin for positive_x_rotation in [true, false] omega = 2200*(2*pi/60) # Create the CCBlade objects. rotor = Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades; turbine=false) sections = Section.(ccbc.radii, ccbc.chord, ccbc.theta, nothing) ops = simple_op.(ccbc.v, omega, ccbc.radii, ccbc.rho; asound=ccbc.c0) # What actually matters in the output structs are just W and phi. phi = range(45.0, 10.0; length=length(sections)) .* (pi/180) W = range(10.0, 11.0; length=length(sections)) outs = Outputs.(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, phi, 0.0, W, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) # Set the source time stuff. num_blade_passes = 3 steps_per_blade_pass = 8 num_src_times = num_blade_passes*steps_per_blade_pass bpp = 2*pi/omega/ccbc.num_blades src_time_range = num_blade_passes*bpp # Finally get all the source elements. bls = [AcousticAnalogies.TrippedN0012BoundaryLayer()] ses_helper = lblvs_source_elements_ccblade(rotor, sections, ops, outs, bls, src_time_range, num_src_times, positive_x_rotation) # Now need to get the source elements the "normal" way. # First get the transformation objects. rot_axis = @SVector [1.0, 0.0, 0.0] blade_axis = @SVector [0.0, 1.0, 0.0] y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = ccbc.v.*rot_axis t0 = 0.0 if positive_x_rotation rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, omega, 0.0) else rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, -omega, 0.0) end const_vel_trans = KinematicCoordinateTransformations.ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Need the source times. dt = src_time_range/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # This is just an array of the angular offsets of each blade. ΞΈs = 2*pi/ccbc.num_blades.*(0:(ccbc.num_blades-1)) # Radial spacing. dradii = get_dradii(ccbc.radii, ccbc.Rhub, ccbc.Rtip) # Need the kinematic viscosity. nus = getproperty.(ops, :mu) ./ getproperty.(ops, :rho) # Also need the velocity in each direction. if positive_x_rotation vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. -W*cos(phi) else vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. W*cos(phi) end # Reshape stuff for broadcasting. radii_rs = reshape(ccbc.radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) phi_rs = reshape(phi, 1, :, 1) W_rs = reshape(W, 1, :, 1) src_times_rs = reshape(src_times, :, 1, 1) # This isn't really necessary. ΞΈs_rs = reshape(ΞΈs, 1, 1, :) nus_rs = reshape(nus, 1, :, 1) twist_rs = reshape(getproperty.(sections, :theta), 1, :, 1) chord_rs = reshape(getproperty.(sections, :chord), 1, :, 1) vn_rs = reshape(vn, 1, :, 1) vr_rs = reshape(vr, 1, :, 1) vc_rs = reshape(vc, 1, :, 1) # Get all the transformations. trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Transform the source elements. ses = LBLVSSourceElement.(ccbc.c0, nus_rs, radii_rs, ΞΈs_rs, dradii_rs, chord_rs, twist_rs, vn_rs, vr_rs, vc_rs, src_times_rs, dt, bls, positive_x_rotation) .|> trans # Now check that we got the same thing. for field in fieldnames(LBLVSSourceElement) if !(field in (:bl,)) @test all(getproperty.(ses_helper, field) .β‰ˆ getproperty.(ses, field)) end end end end @testset "TEBVSSourceElement twist and rotation tests" begin # So, the way this should work: first do the twist, then do the theta rotation. # The twist could be either about the positive y axis or negative y axis. # Then the theta rotation is always about the x axis. c0 = 1.1 nu = 1.2 r = 2.0 Ξ”r = 0.1 chord = 1.3 vn = 2.0 vr = 3.0 vc = 4.0 Ο„ = 0.1 Δτ = 0.02 h = 0.1 Psi = 0.2 bl = 2.0 # should be a boundary layer struct, but doesn't matter for these tests. for twist_about_positive_y in [true, false] se_0twist0theta = TEBVSSourceElement(c0, nu, r, 0.0, Ξ”r, chord, 0.0, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) for Ο• in [5, 10, 65, 95, 260, 270, 290].*(pi/180) # The angle of attack depends on the twist and the fluid velocity if twist_about_positive_y alpha_check = Ο• - atan(-vn, -vc) else alpha_check = Ο• - atan(-vn, vc) end se = TEBVSSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) |> trans_theta # Adjust the angles of attack to always be between -pi and pi. alpha_check = rem2pi(alpha_check+pi, RoundNearest) - pi alpha = rem2pi(AcousticAnalogies.angle_of_attack(se)+pi, RoundNearest) - pi @test alpha β‰ˆ alpha_check for field in fieldnames(TEBVSSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if field != :chord_uvec @test getproperty(se, field) β‰ˆ getproperty(se_0twist0theta, field) end end if twist_about_positive_y # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -Ο•) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, Ο•) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end @testset "TEBVSSourceElement twist and rotation tests, CCBlade" begin # Create the CCBlade objects. Ο„ = 0.1 Δτ = 0.02 h = 0.1 Psi = 0.2 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11.jld2") # out, section_loaded, Ξ”r, op, rotor0precone = nothing, nothing, nothing, nothing, nothing # jldopen(ccblade_fname, "r") do f # out = f["outs"][1] # section_loaded = f["sections"][1] # Ξ”r = f["sections"][2].r - f["sections"][1].r # op = f["ops"][1] # rotor0precone = f["rotor"] # @test rotor0precone.precone β‰ˆ 0.0 # end ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11-outputs.jld2") outs_d = load(ccblade_fname) section_loaded = CCBlade.Section(first(ccbc.radii), first(ccbc.chord), first(ccbc.theta)*pi/180, nothing) Ξ”r = ccbc.radii[2] - ccbc.radii[1] op = CCBlade.OperatingPoint(ccbc.v, outs_d["omega"]*first(ccbc.radii), ccbc.rho, ccbc.pitch, ccbc.mu, ccbc.c0) rotor0precone = CCBlade.Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades) out = CCBlade.Outputs(outs_d["Np"][1], outs_d["Tp"][1], outs_d["a"][1], outs_d["ap"][1], outs_d["u"][1], outs_d["v"][1], outs_d["phi"][1], outs_d["alpha"][1], outs_d["W"][1], outs_d["cl"][1], outs_d["cd"][1], outs_d["cn"][1], outs_d["ct"][1], outs_d["F"][1], outs_d["G"][1]) @test rotor0precone.precone β‰ˆ 0.0 for positive_x_rotation in [true, false] for twist in [5, 10, 65, 95, 260, 270, 290].*(pi/180) section = CCBlade.Section(section_loaded.r, section_loaded.chord, twist, section_loaded.af) se_0theta0precone = TEBVSSourceElement(rotor0precone, section, op, out, 0.0, Ξ”r, h, Psi, Ο„, Δτ, bl, positive_x_rotation) for precone in [5, 10, 65, 95, 260, 270, 290].*(pi/180) rotor = CCBlade.Rotor(rotor0precone.Rhub, rotor0precone.Rtip, rotor0precone.B; turbine=rotor0precone.turbine, precone=precone) # This is tricky: in my "normal" coordinate system, the blade is rotating around the x axis, moving axially in the positive x direction, and is initially aligned with the y axis. # That means that the precone should be a rotation around the negative z axis. # And so to undo it, we want a positive rotation around the positive z axis. trans_precone = KinematicCoordinateTransformations.SteadyRotZTransformation(Ο„, 0.0, precone) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) # Create a transformation that reverses the theta and precone rotations. # The precone happens first, then theta. # So to reverse it we need to do theta, then precone. trans = KinematicCoordinateTransformations.compose(Ο„, trans_precone, trans_theta) # Create a source element with the theta and precone rotations, then undo it. se = TEBVSSourceElement(rotor, section, op, out, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl, positive_x_rotation) |> trans # Check that we got the same thing: for field in fieldnames(TEBVSSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if !(field in (:chord_uvec, :bl)) @test getproperty(se, field) β‰ˆ getproperty(se_0theta0precone, field) end end if positive_x_rotation # If we're doing a positive-x rotation, we're applying the twist about the positive y axis. # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -twist) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're doing a negative-x rotation, we're applying the twist about the negative y axis. # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, twist) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end end @testset "CCBlade TEBVSSourceElement complete test" begin for positive_x_rotation in [true, false] omega = 2200*(2*pi/60) # Create the CCBlade objects. rotor = Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades; turbine=false) sections = Section.(ccbc.radii, ccbc.chord, ccbc.theta, nothing) ops = simple_op.(ccbc.v, omega, ccbc.radii, ccbc.rho; asound=ccbc.c0) # What actually matters in the output structs are just W and phi. phi = range(45.0, 10.0; length=length(sections)) .* (pi/180) W = range(10.0, 11.0; length=length(sections)) outs = Outputs.(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, phi, 0.0, W, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) # Set the source time stuff. num_blade_passes = 3 steps_per_blade_pass = 8 num_src_times = num_blade_passes*steps_per_blade_pass bpp = 2*pi/omega/ccbc.num_blades src_time_range = num_blade_passes*bpp # Finally get all the source elements. bls = [AcousticAnalogies.TrippedN0012BoundaryLayer()] hs = range(0.1, 0.2; length=length(sections)) Psis = range(0.2, 0.3; length=length(sections)) ses_helper = tebvs_source_elements_ccblade(rotor, sections, ops, outs, hs, Psis, bls, src_time_range, num_src_times, positive_x_rotation) # Now need to get the source elements the "normal" way. # First get the transformation objects. rot_axis = @SVector [1.0, 0.0, 0.0] blade_axis = @SVector [0.0, 1.0, 0.0] y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = ccbc.v.*rot_axis t0 = 0.0 if positive_x_rotation rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, omega, 0.0) else rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, -omega, 0.0) end const_vel_trans = KinematicCoordinateTransformations.ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Need the source times. dt = src_time_range/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # This is just an array of the angular offsets of each blade. ΞΈs = 2*pi/ccbc.num_blades.*(0:(ccbc.num_blades-1)) # Radial spacing. dradii = get_dradii(ccbc.radii, ccbc.Rhub, ccbc.Rtip) # Need the kinematic viscosity. nus = getproperty.(ops, :mu) ./ getproperty.(ops, :rho) # Also need the velocity in each direction. if positive_x_rotation vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. -W*cos(phi) else vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. W*cos(phi) end # Reshape stuff for broadcasting. radii_rs = reshape(ccbc.radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) phi_rs = reshape(phi, 1, :, 1) W_rs = reshape(W, 1, :, 1) src_times_rs = reshape(src_times, :, 1, 1) # This isn't really necessary. ΞΈs_rs = reshape(ΞΈs, 1, 1, :) nus_rs = reshape(nus, 1, :, 1) twist_rs = reshape(getproperty.(sections, :theta), 1, :, 1) chord_rs = reshape(getproperty.(sections, :chord), 1, :, 1) vn_rs = reshape(vn, 1, :, 1) vr_rs = reshape(vr, 1, :, 1) vc_rs = reshape(vc, 1, :, 1) h_rs = reshape(hs, 1, :, 1) Psi_rs = reshape(Psis, 1, :, 1) # Get all the transformations. trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Transform the source elements. ses = TEBVSSourceElement.(ccbc.c0, nus_rs, radii_rs, ΞΈs_rs, dradii_rs, chord_rs, twist_rs, h_rs, Psi_rs, vn_rs, vr_rs, vc_rs, src_times_rs, dt, bls, positive_x_rotation) .|> trans # Now check that we got the same thing. for field in fieldnames(TEBVSSourceElement) if !(field in (:bl,)) @test all(getproperty.(ses_helper, field) .β‰ˆ getproperty.(ses, field)) end end end end @testset "TipVortexSourceElement twist and rotation tests" begin # So, the way this should work: first do the twist, then do the theta rotation. # The twist could be either about the positive y axis or negative y axis. # Then the theta rotation is always about the x axis. c0 = 1.1 # nu = 1.2 r = 2.0 Ξ”r = 0.1 chord = 1.3 vn = 2.0 vr = 3.0 vc = 4.0 Ο„ = 0.1 Δτ = 0.02 bl = 2.0 # should be a boundary layer struct, but doesn't matter for these tests. blade_tip = 3.0 # should be a blade tip struct, but doesn't matter for these tests. for twist_about_positive_y in [true, false] se_0twist0theta = TipVortexSourceElement(c0, r, 0.0, Ξ”r, chord, 0.0, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) for Ο• in [5, 10, 65, 95, 260, 270, 290].*(pi/180) # The angle of attack depends on the twist and the fluid velocity if twist_about_positive_y alpha_check = Ο• - atan(-vn, -vc) else alpha_check = Ο• - atan(-vn, vc) end se = TipVortexSourceElement(c0, r, ΞΈ, Ξ”r, chord, Ο•, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) |> trans_theta # Adjust the angles of attack to always be between -pi and pi. alpha_check = rem2pi(alpha_check+pi, RoundNearest) - pi alpha = rem2pi(AcousticAnalogies.angle_of_attack(se)+pi, RoundNearest) - pi @test alpha β‰ˆ alpha_check for field in fieldnames(TipVortexSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if field != :chord_uvec @test getproperty(se, field) β‰ˆ getproperty(se_0twist0theta, field) end end if twist_about_positive_y # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -Ο•) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, Ο•) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end @testset "TipVortexSourceElement twist and rotation tests, CCBlade" begin # Create the CCBlade objects. Ο„ = 0.1 Δτ = 0.02 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() blade_tip = AcousticAnalogies.RoundedTip() # ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11.jld2") # out, section_loaded, Ξ”r, op, rotor0precone = nothing, nothing, nothing, nothing, nothing # jldopen(ccblade_fname, "r") do f # out = f["outs"][1] # section_loaded = f["sections"][1] # Ξ”r = f["sections"][2].r - f["sections"][1].r # op = f["ops"][1] # rotor0precone = f["rotor"] # @test rotor0precone.precone β‰ˆ 0.0 # end ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11-outputs.jld2") outs_d = load(ccblade_fname) section_loaded = CCBlade.Section(first(ccbc.radii), first(ccbc.chord), first(ccbc.theta)*pi/180, nothing) Ξ”r = ccbc.radii[2] - ccbc.radii[1] op = CCBlade.OperatingPoint(ccbc.v, outs_d["omega"]*first(ccbc.radii), ccbc.rho, ccbc.pitch, ccbc.mu, ccbc.c0) rotor0precone = CCBlade.Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades) out = CCBlade.Outputs(outs_d["Np"][1], outs_d["Tp"][1], outs_d["a"][1], outs_d["ap"][1], outs_d["u"][1], outs_d["v"][1], outs_d["phi"][1], outs_d["alpha"][1], outs_d["W"][1], outs_d["cl"][1], outs_d["cd"][1], outs_d["cn"][1], outs_d["ct"][1], outs_d["F"][1], outs_d["G"][1]) @test rotor0precone.precone β‰ˆ 0.0 for positive_x_rotation in [true, false] for twist in [5, 10, 65, 95, 260, 270, 290].*(pi/180) section = CCBlade.Section(section_loaded.r, section_loaded.chord, twist, section_loaded.af) se_0theta0precone = TipVortexSourceElement(rotor0precone, section, op, out, 0.0, Ξ”r, Ο„, Δτ, bl, blade_tip, positive_x_rotation) for precone in [5, 10, 65, 95, 260, 270, 290].*(pi/180) rotor = CCBlade.Rotor(rotor0precone.Rhub, rotor0precone.Rtip, rotor0precone.B; turbine=rotor0precone.turbine, precone=precone) # This is tricky: in my "normal" coordinate system, the blade is rotating around the x axis, moving axially in the positive x direction, and is initially aligned with the y axis. # That means that the precone should be a rotation around the negative z axis. # And so to undo it, we want a positive rotation around the positive z axis. trans_precone = KinematicCoordinateTransformations.SteadyRotZTransformation(Ο„, 0.0, precone) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) # Create a transformation that reverses the theta and precone rotations. # The precone happens first, then theta. # So to reverse it we need to do theta, then precone. trans = KinematicCoordinateTransformations.compose(Ο„, trans_precone, trans_theta) # Create a source element with the theta and precone rotations, then undo it. se = TipVortexSourceElement(rotor, section, op, out, ΞΈ, Ξ”r, Ο„, Δτ, bl, blade_tip, positive_x_rotation) |> trans # Check that we got the same thing: for field in fieldnames(TipVortexSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if !(field in (:chord_uvec, :bl, :blade_tip)) @test getproperty(se, field) β‰ˆ getproperty(se_0theta0precone, field) end end if positive_x_rotation # If we're doing a positive-x rotation, we're applying the twist about the positive y axis. # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -twist) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're doing a negative-x rotation, we're applying the twist about the negative y axis. # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, twist) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end end @testset "CCBlade TipVortexSourceElement complete test" begin for positive_x_rotation in [true, false] omega = 2200*(2*pi/60) # Create the CCBlade objects. rotor = Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades; turbine=false) sections = Section.(ccbc.radii, ccbc.chord, ccbc.theta, nothing) ops = simple_op.(ccbc.v, omega, ccbc.radii, ccbc.rho; asound=ccbc.c0) # What actually matters in the output structs are just W and phi. phi = range(45.0, 10.0; length=length(sections)) .* (pi/180) W = range(10.0, 11.0; length=length(sections)) outs = Outputs.(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, phi, 0.0, W, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) # Radial spacing. dradii = get_dradii(ccbc.radii, ccbc.Rhub, ccbc.Rtip) # Set the source time stuff. num_blade_passes = 3 steps_per_blade_pass = 8 num_src_times = num_blade_passes*steps_per_blade_pass bpp = 2*pi/omega/ccbc.num_blades src_time_range = num_blade_passes*bpp # Finally get all the source elements. bl = AcousticAnalogies.TrippedN0012BoundaryLayer() blade_tip = AcousticAnalogies.RoundedTip() ses_helper = tip_vortex_source_elements_ccblade(rotor, sections[end], ops[end], outs[end], dradii[end], bl, blade_tip, src_time_range, num_src_times, positive_x_rotation) # Now need to get the source elements the "normal" way. # First get the transformation objects. rot_axis = @SVector [1.0, 0.0, 0.0] blade_axis = @SVector [0.0, 1.0, 0.0] y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = ccbc.v.*rot_axis t0 = 0.0 if positive_x_rotation rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, omega, 0.0) else rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, -omega, 0.0) end const_vel_trans = KinematicCoordinateTransformations.ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Need the source times. dt = src_time_range/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # This is just an array of the angular offsets of each blade. ΞΈs = 2*pi/ccbc.num_blades.*(0:(ccbc.num_blades-1)) # Need the kinematic viscosity. # nus = getproperty.(ops, :mu) ./ getproperty.(ops, :rho) # Also need the velocity in each direction. if positive_x_rotation vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. -W*cos(phi) else vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. W*cos(phi) end # Reshape stuff for broadcasting. ΞΈs_rs = reshape(ΞΈs, 1, 1, :) # Get all the transformations. trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Transform the source elements. ses = TipVortexSourceElement.(ccbc.c0, ccbc.radii[end], ΞΈs_rs, dradii[end], sections[end].chord, sections[end].theta, vn[end], vr[end], vc[end], src_times, dt, Ref(bl), Ref(blade_tip), positive_x_rotation) .|> trans # Now check that we got the same thing. for field in fieldnames(TipVortexSourceElement) if !(field in (:bl, :blade_tip)) @test all(getproperty.(ses_helper, field) .β‰ˆ getproperty.(ses, field)) end end end end @testset "CombinedNoTipBroadbandSourceElement twist and rotation tests" begin # So, the way this should work: first do the twist, then do the theta rotation. # The twist could be either about the positive y axis or negative y axis. # Then the theta rotation is always about the x axis. c0 = 1.1 nu = 1.2 r = 2.0 Ξ”r = 0.1 chord = 1.3 vn = 2.0 vr = 3.0 vc = 4.0 Ο„ = 0.1 Δτ = 0.02 h = 0.1 Psi = 0.2 bl = 2.0 # should be a boundary layer struct, but doesn't matter for these tests. for twist_about_positive_y in [true, false] se_0twist0theta = CombinedNoTipBroadbandSourceElement(c0, nu, r, 0.0, Ξ”r, chord, 0.0, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) for Ο• in [5, 10, 65, 95, 260, 270, 290].*(pi/180) # The angle of attack depends on the twist and the fluid velocity if twist_about_positive_y alpha_check = Ο• - atan(-vn, -vc) else alpha_check = Ο• - atan(-vn, vc) end se = CombinedNoTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, twist_about_positive_y) |> trans_theta # Adjust the angles of attack to always be between -pi and pi. alpha_check = rem2pi(alpha_check+pi, RoundNearest) - pi alpha = rem2pi(AcousticAnalogies.angle_of_attack(se)+pi, RoundNearest) - pi @test alpha β‰ˆ alpha_check for field in fieldnames(CombinedNoTipBroadbandSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if field != :chord_uvec @test getproperty(se, field) β‰ˆ getproperty(se_0twist0theta, field) end end if twist_about_positive_y # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -Ο•) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, Ο•) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end @testset "CombinedNoTipBroadbandSourceElement twist and rotation tests, CCBlade" begin # Create the CCBlade objects. Ο„ = 0.1 Δτ = 0.02 h = 0.1 Psi = 0.2 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11.jld2") # out, section_loaded, Ξ”r, op, rotor0precone = nothing, nothing, nothing, nothing, nothing # jldopen(ccblade_fname, "r") do f # out = f["outs"][1] # section_loaded = f["sections"][1] # Ξ”r = f["sections"][2].r - f["sections"][1].r # op = f["ops"][1] # rotor0precone = f["rotor"] # @test rotor0precone.precone β‰ˆ 0.0 # end ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11-outputs.jld2") outs_d = load(ccblade_fname) section_loaded = CCBlade.Section(first(ccbc.radii), first(ccbc.chord), first(ccbc.theta)*pi/180, nothing) Ξ”r = ccbc.radii[2] - ccbc.radii[1] op = CCBlade.OperatingPoint(ccbc.v, outs_d["omega"]*first(ccbc.radii), ccbc.rho, ccbc.pitch, ccbc.mu, ccbc.c0) rotor0precone = CCBlade.Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades) out = CCBlade.Outputs(outs_d["Np"][1], outs_d["Tp"][1], outs_d["a"][1], outs_d["ap"][1], outs_d["u"][1], outs_d["v"][1], outs_d["phi"][1], outs_d["alpha"][1], outs_d["W"][1], outs_d["cl"][1], outs_d["cd"][1], outs_d["cn"][1], outs_d["ct"][1], outs_d["F"][1], outs_d["G"][1]) @test rotor0precone.precone β‰ˆ 0.0 for positive_x_rotation in [true, false] for twist in [5, 10, 65, 95, 260, 270, 290].*(pi/180) section = CCBlade.Section(section_loaded.r, section_loaded.chord, twist, section_loaded.af) se_0theta0precone = CombinedNoTipBroadbandSourceElement(rotor0precone, section, op, out, 0.0, Ξ”r, h, Psi, Ο„, Δτ, bl, positive_x_rotation) for precone in [5, 10, 65, 95, 260, 270, 290].*(pi/180) rotor = CCBlade.Rotor(rotor0precone.Rhub, rotor0precone.Rtip, rotor0precone.B; turbine=rotor0precone.turbine, precone=precone) # This is tricky: in my "normal" coordinate system, the blade is rotating around the x axis, moving axially in the positive x direction, and is initially aligned with the y axis. # That means that the precone should be a rotation around the negative z axis. # And so to undo it, we want a positive rotation around the positive z axis. trans_precone = KinematicCoordinateTransformations.SteadyRotZTransformation(Ο„, 0.0, precone) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) # Create a transformation that reverses the theta and precone rotations. # The precone happens first, then theta. # So to reverse it we need to do theta, then precone. trans = KinematicCoordinateTransformations.compose(Ο„, trans_precone, trans_theta) # Create a source element with the theta and precone rotations, then undo it. se = CombinedNoTipBroadbandSourceElement(rotor, section, op, out, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl, positive_x_rotation) |> trans # Check that we got the same thing: for field in fieldnames(CombinedNoTipBroadbandSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if !(field in (:chord_uvec, :bl)) @test getproperty(se, field) β‰ˆ getproperty(se_0theta0precone, field) end end if positive_x_rotation # If we're doing a positive-x rotation, we're applying the twist about the positive y axis. # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -twist) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're doing a negative-x rotation, we're applying the twist about the negative y axis. # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, twist) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end end @testset "CombinedWithTipBroadbandSourceElement twist and rotation tests" begin # So, the way this should work: first do the twist, then do the theta rotation. # The twist could be either about the positive y axis or negative y axis. # Then the theta rotation is always about the x axis. c0 = 1.1 nu = 1.2 r = 2.0 Ξ”r = 0.1 chord = 1.3 vn = 2.0 vr = 3.0 vc = 4.0 Ο„ = 0.1 Δτ = 0.02 h = 0.1 Psi = 0.2 bl = 2.0 # should be a boundary layer struct, but doesn't matter for these tests. blade_tip = 3.0 # should be a blade tip struct, but doesn't matter for these tests. for twist_about_positive_y in [true, false] se_0twist0theta = CombinedWithTipBroadbandSourceElement(c0, nu, r, 0.0, Ξ”r, chord, 0.0, h, Psi, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) for Ο• in [5, 10, 65, 95, 260, 270, 290].*(pi/180) # The angle of attack depends on the twist and the fluid velocity if twist_about_positive_y alpha_check = Ο• - atan(-vn, -vc) else alpha_check = Ο• - atan(-vn, vc) end se = CombinedWithTipBroadbandSourceElement(c0, nu, r, ΞΈ, Ξ”r, chord, Ο•, h, Psi, vn, vr, vc, Ο„, Δτ, bl, blade_tip, twist_about_positive_y) |> trans_theta # Adjust the angles of attack to always be between -pi and pi. alpha_check = rem2pi(alpha_check+pi, RoundNearest) - pi alpha = rem2pi(AcousticAnalogies.angle_of_attack(se)+pi, RoundNearest) - pi @test alpha β‰ˆ alpha_check for field in fieldnames(CombinedWithTipBroadbandSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if field != :chord_uvec @test getproperty(se, field) β‰ˆ getproperty(se_0twist0theta, field) end end if twist_about_positive_y # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -Ο•) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, Ο•) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end @testset "CombinedWithTipBroadbandSourceElement twist and rotation tests, CCBlade" begin # Create the CCBlade objects. Ο„ = 0.1 Δτ = 0.02 h = 0.1 Psi = 0.2 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() blade_tip = AcousticAnalogies.RoundedTip() # ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11.jld2") # out, section_loaded, Ξ”r, op, rotor0precone = nothing, nothing, nothing, nothing, nothing # jldopen(ccblade_fname, "r") do f # out = f["outs"][1] # section_loaded = f["sections"][1] # Ξ”r = f["sections"][2].r - f["sections"][1].r # op = f["ops"][1] # rotor0precone = f["rotor"] # @test rotor0precone.precone β‰ˆ 0.0 # end ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11-outputs.jld2") outs_d = load(ccblade_fname) section_loaded = CCBlade.Section(first(ccbc.radii), first(ccbc.chord), first(ccbc.theta)*pi/180, nothing) Ξ”r = ccbc.radii[2] - ccbc.radii[1] op = CCBlade.OperatingPoint(ccbc.v, outs_d["omega"]*first(ccbc.radii), ccbc.rho, ccbc.pitch, ccbc.mu, ccbc.c0) rotor0precone = CCBlade.Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades) out = CCBlade.Outputs(outs_d["Np"][1], outs_d["Tp"][1], outs_d["a"][1], outs_d["ap"][1], outs_d["u"][1], outs_d["v"][1], outs_d["phi"][1], outs_d["alpha"][1], outs_d["W"][1], outs_d["cl"][1], outs_d["cd"][1], outs_d["cn"][1], outs_d["ct"][1], outs_d["F"][1], outs_d["G"][1]) @test rotor0precone.precone β‰ˆ 0.0 for positive_x_rotation in [true, false] for twist in [5, 10, 65, 95, 260, 270, 290].*(pi/180) section = CCBlade.Section(section_loaded.r, section_loaded.chord, twist, section_loaded.af) se_0theta0precone = CombinedWithTipBroadbandSourceElement(rotor0precone, section, op, out, 0.0, Ξ”r, h, Psi, Ο„, Δτ, bl, blade_tip, positive_x_rotation) for precone in [5, 10, 65, 95, 260, 270, 290].*(pi/180) rotor = CCBlade.Rotor(rotor0precone.Rhub, rotor0precone.Rtip, rotor0precone.B; turbine=rotor0precone.turbine, precone=precone) # This is tricky: in my "normal" coordinate system, the blade is rotating around the x axis, moving axially in the positive x direction, and is initially aligned with the y axis. # That means that the precone should be a rotation around the negative z axis. # And so to undo it, we want a positive rotation around the positive z axis. trans_precone = KinematicCoordinateTransformations.SteadyRotZTransformation(Ο„, 0.0, precone) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) # Create a transformation that reverses the theta and precone rotations. # The precone happens first, then theta. # So to reverse it we need to do theta, then precone. trans = KinematicCoordinateTransformations.compose(Ο„, trans_precone, trans_theta) # Create a source element with the theta and precone rotations, then undo it. se = CombinedWithTipBroadbandSourceElement(rotor, section, op, out, ΞΈ, Ξ”r, h, Psi, Ο„, Δτ, bl, blade_tip, positive_x_rotation) |> trans # Check that we got the same thing: for field in fieldnames(CombinedWithTipBroadbandSourceElement) # The twist changes the unit vector in the chord direction, but nothing else, so ignore that for now. if !(field in (:chord_uvec, :bl, :blade_tip)) @test getproperty(se, field) β‰ˆ getproperty(se_0theta0precone, field) end end if positive_x_rotation # If we're doing a positive-x rotation, we're applying the twist about the positive y axis. # If we're applying the twist about the positive y axis, then we need to do a negative rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, -twist) chord_uvec_check = @SVector [0.0, 0.0, -1.0] else # If we're doing a negative-x rotation, we're applying the twist about the negative y axis. # If we're applying the twist about the negative y axis, then we need to do a positive rotation about the y axis to undo it. trans_phi = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, twist) chord_uvec_check = @SVector [0.0, 0.0, 1.0] end se_no_twist = se |> trans_phi @test se_no_twist.chord_uvec β‰ˆ chord_uvec_check end end end end end @testset "CCBlade combined broadband source elements complete test" begin for positive_x_rotation in [true, false] omega = 2200*(2*pi/60) # Create the CCBlade objects. rotor = Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades; turbine=false) sections = Section.(ccbc.radii, ccbc.chord, ccbc.theta, nothing) ops = simple_op.(ccbc.v, omega, ccbc.radii, ccbc.rho; asound=ccbc.c0) # What actually matters in the output structs are just W and phi. phi = range(45.0, 10.0; length=length(sections)) .* (pi/180) W = range(10.0, 11.0; length=length(sections)) outs = Outputs.(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, phi, 0.0, W, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) # Set the source time stuff. num_blade_passes = 3 steps_per_blade_pass = 8 num_src_times = num_blade_passes*steps_per_blade_pass bpp = 2*pi/omega/ccbc.num_blades src_time_range = num_blade_passes*bpp # Finally get all the source elements. # bls = [AcousticAnalogies.TrippedN0012BoundaryLayer()] # bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # bls = Fill(AcousticAnalogies.TrippedN0012BoundaryLayer(), num_radial) bls = fill(AcousticAnalogies.TrippedN0012BoundaryLayer(), length(sections)) hs = range(0.1, 0.2; length=length(sections)) Psis = range(0.2, 0.3; length=length(sections)) blade_tip = AcousticAnalogies.RoundedTip() ses_no_tip_helper, ses_with_tip_helper = combined_broadband_source_elements_ccblade(rotor, sections, ops, outs, hs, Psis, bls, blade_tip, src_time_range, num_src_times, positive_x_rotation) # Now need to get the source elements the "normal" way. # First get the transformation objects. rot_axis = @SVector [1.0, 0.0, 0.0] blade_axis = @SVector [0.0, 1.0, 0.0] y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = ccbc.v.*rot_axis t0 = 0.0 if positive_x_rotation rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, omega, 0.0) else rot_trans = KinematicCoordinateTransformations.SteadyRotXTransformation(t0, -omega, 0.0) end const_vel_trans = KinematicCoordinateTransformations.ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Need the source times. dt = src_time_range/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # This is just an array of the angular offsets of each blade. ΞΈs = 2*pi/ccbc.num_blades.*(0:(ccbc.num_blades-1)) # Radial spacing. dradii = get_dradii(ccbc.radii, ccbc.Rhub, ccbc.Rtip) # Need the kinematic viscosity. nus = getproperty.(ops, :mu) ./ getproperty.(ops, :rho) # Also need the velocity in each direction. if positive_x_rotation vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. -W*cos(phi) else vn = @. -W*sin(phi) vr = zeros(eltype(vn), length(vn)) vc = @. W*cos(phi) end # Reshape stuff for broadcasting. radii_rs = reshape(ccbc.radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) phi_rs = reshape(phi, 1, :, 1) W_rs = reshape(W, 1, :, 1) # src_times_rs = reshape(src_times, :, 1, 1) # This isn't really necessary. ΞΈs_rs = reshape(ΞΈs, 1, 1, :) nus_rs = reshape(nus, 1, :, 1) twist_rs = reshape(getproperty.(sections, :theta), 1, :, 1) chord_rs = reshape(getproperty.(sections, :chord), 1, :, 1) hs_rs = reshape(hs, 1, :, 1) Psis_rs = reshape(Psis, 1, :, 1) vn_rs = reshape(vn, 1, :, 1) vr_rs = reshape(vr, 1, :, 1) vc_rs = reshape(vc, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # Get all the transformations. trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Now need to split things into the with tip and no tip stuff. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] phi_rs_no_tip = @view phi_rs[:, begin:end-1, :] W_rs_no_tip = @view W_rs[:, begin:end-1, :] nus_rs_no_tip = @view nus_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] vn_rs_no_tip = @view vn_rs[:, begin:end-1, :] vr_rs_no_tip = @view vr_rs[:, begin:end-1, :] vc_rs_no_tip = @view vc_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] phi_rs_with_tip = @view phi_rs[:, end:end, :] W_rs_with_tip = @view W_rs[:, end:end, :] nus_rs_with_tip = @view nus_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] chord_rs_with_tip = @view chord_rs[:, end:end, :] hs_rs_with_tip = @view hs_rs[:, end:end, :] Psis_rs_with_tip = @view Psis_rs[:, end:end, :] vn_rs_with_tip = @view vn_rs[:, end:end, :] vr_rs_with_tip = @view vr_rs[:, end:end, :] vc_rs_with_tip = @view vc_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] # Transform the source elements. ses_no_tip = CombinedNoTipBroadbandSourceElement.(ccbc.c0, nus_rs_no_tip, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord_rs_no_tip, twist_rs_no_tip, hs_rs_no_tip, Psis_rs_no_tip, vn_rs_no_tip, vr_rs_no_tip, vc_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement.(ccbc.c0, nus_rs_with_tip, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord_rs_with_tip, twist_rs_with_tip, hs_rs_with_tip, Psis_rs_with_tip, vn_rs_with_tip, vr_rs_with_tip, vc_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # Now check that we got the same thing. for field in fieldnames(CombinedNoTipBroadbandSourceElement) if !(field in (:bl,)) @test all(getproperty.(ses_no_tip_helper, field) .β‰ˆ getproperty.(ses_no_tip, field)) end end for field in fieldnames(CombinedWithTipBroadbandSourceElement) if !(field in (:bl, :blade_tip)) @test all(getproperty.(ses_with_tip_helper, field) .β‰ˆ getproperty.(ses_with_tip, field)) end end end end @testset "directivity function tests" begin # None of this stuff matters for the directivity functions. c0 = 2.0 nu = 3.0 dr = 0.1 chord = 1.1 Ο„ = 0.2 dΟ„ = 0.01 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() chord_cross_span_to_get_top_uvec = true # This stuff actually matters. # Need the fluid velocity to be zero so we can ignore the denominator. y1dot = @SVector [0.0, 0.0, 0.0] y1dot_fluid = @SVector [0.0, 0.0, 0.0] y0dot = @SVector [0.0, 0.0, 0.0] chord_uvec = [1.0, 0.0, 0.0] span_uvec = [0.0, 1.0, 0.0] # Create a source element. se = AcousticAnalogies.TBLTESourceElement(c0, nu, dr, chord, y0dot, y1dot, y1dot_fluid, Ο„, dΟ„, span_uvec, chord_uvec, bl, chord_cross_span_to_get_top_uvec) # Now, create an observer at different places, and check that we get the correct directivity function. for x_er in [-5.0, -3.0, 1.5, 4.0] for y_er in [-5.0, -3.0, 1.5, 4.0] for z_er in [-5.0, -3.0, 1.5, 4.0] x = @SVector [x_er, y_er, z_er] obs = AcousticAnalogies.StationaryAcousticObserver(x) r_er_check = sqrt(x_er^2 + y_er^2 + z_er^2) Θ_er = acos(x_er/r_er_check) Ξ¦_er = acos(y_er/sqrt(y_er^2 + z_er^2)) # Observer time doesn't matter since the observer is stationary. t_obs = 7.0 x_obs = obs(t_obs) Dl_check = (sin(Θ_er)^2) * (sin(Ξ¦_er)^2) Dh_check = 2*(sin(0.5*Θ_er)^2) * (sin(Ξ¦_er)^2) top_is_suction = true r_er, Dl, Dh = AcousticAnalogies.directivity(se, obs(t_obs), top_is_suction) @test r_er β‰ˆ r_er_check @test Dl β‰ˆ Dl_check @test Dh β‰ˆ Dh_check # Now, rotate and translate both the source and the observer. # The directivity functions should be the same. # Time parameter for the steady rotations doesn't matter because the rotation rate is zero. trans1 = KinematicCoordinateTransformations.SteadyRotXTransformation(t_obs, 0.0, 3.0*pi/180) trans2 = KinematicCoordinateTransformations.SteadyRotYTransformation(t_obs, 0.0, 4.0*pi/180) trans3 = KinematicCoordinateTransformations.SteadyRotZTransformation(t_obs, 0.0, 5.0*pi/180) # Time parameter for the constant velocity transformations doesn't matter because the velocity is zero. x_trans = @SVector [2.0, 3.0, 4.0] v_trans = @SVector [0.0, 0.0, 0.0] trans4 = KinematicCoordinateTransformations.ConstantVelocityTransformation(t_obs, x_trans, v_trans) # Transform the source and observer. trans = compose(t_obs, trans4, compose(t_obs, trans3, compose(t_obs, trans2, trans1))) se_trans = trans(se) obs_trans = AcousticAnalogies.StationaryAcousticObserver(trans(t_obs, obs(t_obs))) # Check that the directivity functions didn't change. r_er, Dl, Dh = AcousticAnalogies.directivity(se_trans, obs_trans(t_obs), top_is_suction) @test r_er β‰ˆ r_er_check @test Dl β‰ˆ Dl_check @test Dh β‰ˆ Dh_check end end end end @testset "angle of attack test" begin @testset "TBLTESourceElement" begin for twist_about_positive_y in [true, false] # None of this stuff matters for the angle of attack. c0 = 2.0 nu = 3.0 dr = 0.1 chord = 1.1 dΟ„ = 0.01 r = 0.5 omega = 101.0 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # We'll create a random transformation to check that rotating and displacing the source doesn't change the angle of attack. # Time parameter for the steady rotations doesn't matter because the rotation rate is zero. Ο„ = 0.2 trans1 = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, 3.0*pi/180) trans2 = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, 4.0*pi/180) trans3 = KinematicCoordinateTransformations.SteadyRotZTransformation(Ο„, 0.0, 5.0*pi/180) # Time parameter for the constant velocity transformations doesn't matter because the velocity is zero. x_trans = @SVector [2.0, 3.0, 4.0] v_trans = @SVector [0.0, 0.0, 0.0] trans4 = KinematicCoordinateTransformations.ConstantVelocityTransformation(Ο„, x_trans, v_trans) # Combine all the transformations into one. trans = compose(Ο„, trans4, compose(Ο„, trans3, compose(Ο„, trans2, trans1))) # This stuff does matter for angle of attack. Vx = 5.5 u = 0.1*Vx Vy = omega*r v = 0.05*Vy # So, let's say I'm in the usual frame of reference: moving axially in the positive x direction, rotating about the positive x axis if `twist_about_positive_y` is `true`, negative x axis if `twist_about_positive_y` is `false`, initially aligned with the y axis. # Then, from the perspective of the blade element, the fluid velocity in the axial direction (`x`) is `-(Vx + u)`, and the velocity in the tangential direction is `(-Vy + v)`. # # vr shouldn't matter at all, so check that. for use_induction in [true, false] for vr in [0.0, 2.1, -2.1] for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) for twist in [5, 10, 65, 95, 260, 270, 290].*(pi/180) for vn_sign in [1, -1] for vc_sign in [1, -1] vn = -(Vx + u)*vn_sign vc = (-Vy + v)*vc_sign se = AcousticAnalogies.TBLTESourceElement{AcousticAnalogies.BrooksBurleyDirectivity,use_induction,AcousticAnalogies.NoMachCorrection,true}(c0, nu, r, ΞΈ, dr, chord, twist, vn, vr, vc, Ο„, dΟ„, bl, twist_about_positive_y) # And then the angle of attack will be `twist - atan(-vn, -vc)`, where `twist` is the twist of the blade, `vn` is the velocity in the axial direction, and `vc` is the velocity in the circumferential/tangential direction. # But we need to switch the direction of the velocity vector, since I'm thinking of them in opposite directions (eg the angle of attack is zero when the velocity and chordwise vector from trailing edge to leading edge are exactly opposite). # The rem2pi will give us back an equivalent angle in the interval [-Ο€, Ο€]. if twist_about_positive_y # If the twist is about the positive y axis, then the assumption is that the twist and velocity angles are zero when they are aligned with positive z axis. # In the "usual" operation, the axial component of the blade-fixed frame velocity will be in the negative x direction, and the circumferential component of the blade-fixed frame velocity will be in the negative z direction. # So we need to switch both of those signs to get the correct angle. angle_of_attack_check = rem2pi(twist - atan(-vn, -vc), RoundNearest) else # If the twist is about the negative y axis, then the assumption is the twist and velocity angles are zero when they are aligned with the negative z axis. # In then "usual" operation, the axial component of the blade-fixed frame velocity will be in the negative x direction, and the circumferential component of the blade fixed frame velocity will be in the positive z direction. # So we need to switch the sign of the axial component, but not the circumferential. angle_of_attack_check = rem2pi(twist - atan(-vn, vc), RoundNearest) end @test AcousticAnalogies.angle_of_attack(se) β‰ˆ angle_of_attack_check if use_induction # Flow speed normal to span, including induction: U_check = sqrt(vn^2 + vc^2) else # Flow speed normal to span, not including induction: U_check = sqrt(Vx^2 + Vy^2) end if use_induction # If we're including induction in the flow speed normal to span calculation, we can check it now. @test AcousticAnalogies.speed_normal_to_span(se) β‰ˆ U_check end # Apply the random transformation we created. se_trans = trans(se) # Make sure we get the same angle of attack as before. @test AcousticAnalogies.angle_of_attack(se_trans) β‰ˆ angle_of_attack_check # Now, instead of doing a transformation that just displaces the source element, let's do one that changes the velocity. # So, how are we going to transform the source element into the fluid frame? # Well, first we say we're rotating around the x axix at a rate Ο‰ or -Ο‰, depending on the value of `twist_about_positive_y` # Oh, but wait. # We're switching the sign. # Hmm... what to do about that? # Well, the definition of the fluid frame is one that has the "freestream velocity" as zero. # So that, I think, means we need to remove the axial and circumferential (rotational) velocity. # So remove Vx and Vy. # I should be able to do that. # So, first, let's think about getting rid of Vy. # If we rotate about the positive x axis, then that will increase the velocity in the z direction (since the blade is initially aligned with the y axis). # If we rotate about the negative x axis, then that will decrease the velocity in the z direction (again, since the blade is initially aligned with the y axis). # OK, then. trans_rot = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, omega*vc_sign, 0.0) # Now, for the x velocity, we just want to remove the Vx. x0 = @SVector [0.0, 0.0, 0.0] v0 = @SVector [Vx*vn_sign, 0.0, 0.0] trans_freestream = KinematicCoordinateTransformations.ConstantVelocityTransformation(Ο„, x0, v0) # Now compose the two transformations, and apply them to the source element. trans_global = compose(Ο„, trans_freestream, trans_rot) se_global = trans_global(se) # The angle of attack should be the same. @test AcousticAnalogies.angle_of_attack(se_global) β‰ˆ angle_of_attack_check # Also, we should know what the source element and fluid velocities are, right? y1dot_check = @SVector [Vx*vn_sign, Vy*vc_sign*(-sin(ΞΈ)), Vy*vc_sign*(cos(ΞΈ))] y1dot_fluid_check = @SVector [-u*vn_sign, vr*cos(ΞΈ) + v*vc_sign*(-sin(ΞΈ)), vr*sin(ΞΈ) + v*vc_sign*(cos(ΞΈ))] @test se_global.y1dot β‰ˆ y1dot_check @test se_global.y1dot_fluid β‰ˆ y1dot_fluid_check # The flow speed normal to span, including induction or not, shouldn't have changed, so check that. @test AcousticAnalogies.speed_normal_to_span(se_global) β‰ˆ U_check end end end end end end end end @testset "TBLTESourceElement, CCBlade" begin # Create the CCBlade objects. Ο„ = 0.1 Δτ = 0.02 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11.jld2") # out, section, Ξ”r, op, rotor = nothing, nothing, nothing, nothing, nothing # jldopen(ccblade_fname, "r") do f # out = f["outs"][1] # section = f["sections"][1] # Ξ”r = f["sections"][2].r - f["sections"][1].r # op = f["ops"][1] # rotor = f["rotor"] # @test rotor.precone β‰ˆ 0.0 # @test op.pitch β‰ˆ 0.0 # end ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11-outputs.jld2") outs_d = load(ccblade_fname) section = CCBlade.Section(first(ccbc.radii), first(ccbc.chord), first(ccbc.theta)*pi/180, nothing) Ξ”r = ccbc.radii[2] - ccbc.radii[1] op = CCBlade.OperatingPoint(ccbc.v, outs_d["omega"]*first(ccbc.radii), ccbc.rho, ccbc.pitch, ccbc.mu, ccbc.c0) rotor = CCBlade.Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades) out = CCBlade.Outputs(outs_d["Np"][1], outs_d["Tp"][1], outs_d["a"][1], outs_d["ap"][1], outs_d["u"][1], outs_d["v"][1], outs_d["phi"][1], outs_d["alpha"][1], outs_d["W"][1], outs_d["cl"][1], outs_d["cd"][1], outs_d["cn"][1], outs_d["ct"][1], outs_d["F"][1], outs_d["G"][1]) @test rotor.precone β‰ˆ 0.0 @test op.pitch β‰ˆ 0.0 for positive_x_rotation in [true, false] for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) se = AcousticAnalogies.TBLTESourceElement(rotor, section, op, out, ΞΈ, Ξ”r, Ο„, Δτ, bl, positive_x_rotation) # The `chord_uvec` vector points from leading edge to trailing edge. # So we should be able to use that to figure out the angle it makes with the tangential/rotation direction. # The tangential/rotation direction can be found by crossing the the rotation axis with the position vector. # Then I can dot the chord with that direction, and the forward velocity axis, then use the arctan function to get the angle. if positive_x_rotation rot_axis = @SVector [1, 0, 0] else rot_axis = @SVector [-1, 0, 0] end tan_axis_tmp = cross(rot_axis, se.y0dot) tan_axis = tan_axis_tmp / norm(tan_axis_tmp) forward_axis = @SVector [1, 0, 0] # I'm visualizing the chord vector as going from trailing edge to leading edge, but it's leading edge to trailing edge in the TBLTESourceElement struct, so switch that. te_to_le = -se.chord_uvec twist_check = atan(dot(te_to_le, forward_axis), dot(te_to_le, tan_axis)) @test twist_check β‰ˆ section.theta # The angle of attack that AcousticAnalogies.jl calculates should match what CCBlade.jl has. @test AcousticAnalogies.angle_of_attack(se) β‰ˆ out.alpha # Now, rotate and translate the source, which shouldn't change the twist or angle of attack, as long as we don't do anything that would change the velocity. # Time parameter for the steady rotations doesn't matter because the rotation rate is zero. trans1 = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, 3.0*pi/180) trans2 = KinematicCoordinateTransformations.SteadyRotYTransformation(Ο„, 0.0, 4.0*pi/180) trans3 = KinematicCoordinateTransformations.SteadyRotZTransformation(Ο„, 0.0, 5.0*pi/180) # Time parameter for the constant velocity transformations doesn't matter because the velocity is zero. x_trans = @SVector [2.0, 3.0, 4.0] v_trans = @SVector [0.0, 0.0, 0.0] trans4 = KinematicCoordinateTransformations.ConstantVelocityTransformation(Ο„, x_trans, v_trans) # Transform the source. trans = compose(Ο„, trans4, compose(Ο„, trans3, compose(Ο„, trans2, trans1))) se_trans = trans(se) # Angle of attack should still be the same. @test AcousticAnalogies.angle_of_attack(se_trans) β‰ˆ out.alpha # It'd be nice to check the twist too, but if that was wrong, the angle of attack would be wrong too. # And there are other tests already for `chord_uvec`. # Could I put the source element in the "fluid/global" frame now? # I'd need to know the forward velocity and rotation rate. # Well, the forward velocity would be Vx. Vx = op.Vx # And the rotation rate would be Vy/r. omega = op.Vy / section.r # Now, need to undo the rotation, which depends on `positive_x_rotation`. if positive_x_rotation # If we're rotating about the positive x axis, need to apply a rotation around the negative x axis to undo it. trans_rot = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, -omega, 0.0) else # If we're rotating about the negative x axis, need to apply a rotation around the positive x axis to undo it. trans_rot = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, omega, 0.0) end # Now, I'm assuming that the freestream/axial velocity is in the -x direction, so to undo that, move it in the positive x direction. x0 = @SVector [0.0, 0.0, 0.0] v0 = @SVector [Vx, 0.0, 0.0] trans_freestream = KinematicCoordinateTransformations.ConstantVelocityTransformation(Ο„, x0, v0) # Now compose the two transformations, and apply them to the original source element. trans_global = compose(Ο„, trans_freestream, trans_rot) se_global = trans_global(se) # The angle of attack should be the same. @test AcousticAnalogies.angle_of_attack(se_global) β‰ˆ out.alpha end end end end @testset "BPM Report tests" begin @testset "BPM Figure 11a" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure11-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] # This is in kHz. SPL_s = bpm[:, 2] # At zero angle of attack the pressure and suction side predictions are the same. f_p = f_s SPL_p = SPL_s for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.029 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.029 # These should all be very negative, since alphastar is zero: @test all(SPL_alpha_jl .< -100) end end end @testset "BPM Figure 11d" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # Mach number, corresponds to U = 31.7 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure11-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] # This is in kHz. SPL_s = bpm[:, 2] # At zero angle of attack the pressure and suction side predictions are the same. f_p = f_s SPL_p = SPL_s for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.015 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.015 # These should all be very negative, since alphastar is zero: @test all(SPL_alpha_jl .< -100) end end end @testset "BPM Figure 12a" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 1.5*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure12-U71.3-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure12-U71.3-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure12-U71.3-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.022 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.017 SPL_alpha_jl_interp = linear(freqs, SPL_alpha_jl, f_alpha.*1e3) vmin, vmax = extrema(SPL_alpha) err = abs.(SPL_alpha_jl_interp .- SPL_alpha)./(vmax - vmin) @test maximum(err) < 0.037 end end end @testset "BPM Figure 26a" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure26-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # At zero angle of attack the pressure and suction side predictions are the same. f_p = f_s SPL_p = SPL_s for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.015 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.015 # These should all be very negative, since alphastar is zero: @test all(SPL_alpha_jl .< -100) end end end @testset "BPM Figure 26d" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # Mach number, corresponds to U = 31.7 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure26-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # At zero angle of attack the pressure and suction side predictions are the same. f_p = f_s SPL_p = SPL_s for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl, use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.032 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.032 # These should all be very negative, since alphastar is zero: @test all(SPL_alpha_jl .< -100) end end end @testset "BPM Figure 28a" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 6.7*pi/180 # Using the tripped boundary layer in this case. bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-a-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-a-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.036 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.075 SPL_alpha_jl_interp = linear(freqs, SPL_alpha_jl, f_alpha.*1e3) vmin, vmax = extrema(SPL_alpha) err = abs.(SPL_alpha_jl_interp .- SPL_alpha)./(vmax - vmin) @test maximum(err) < 0.039 end end end @testset "BPM Figure 28d" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 6.7*pi/180 # Using the tripped boundary layer in this case. bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-d-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-d-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.021 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.042 SPL_alpha_jl_interp = linear(freqs, SPL_alpha_jl, f_alpha.*1e3) vmin, vmax = extrema(SPL_alpha) err = abs.(SPL_alpha_jl_interp .- SPL_alpha)./(vmax - vmin) @test maximum(err) < 0.040 end end end @testset "BPM Figure 38d" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 2.54e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 # Using the tripped boundary layer in this case. bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure38-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # At zero angle of attack the pressure and suction side predictions are the same. f_p = f_s SPL_p = SPL_s for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.026 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.026 # These should all be very negative, since alphastar is zero: @test all(SPL_alpha_jl .< -100) end end end @testset "BPM Figure 39d" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 2.54e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 4.8*pi/180 # Using the tripped boundary layer in this case. bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure39-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure39-d-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure39-d-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.036 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.043 SPL_alpha_jl_interp = linear(freqs, SPL_alpha_jl, f_alpha.*1e3) vmin, vmax = extrema(SPL_alpha) err = abs.(SPL_alpha_jl_interp .- SPL_alpha)./(vmax - vmin) @test maximum(err) < 0.039 end end end @testset "BPM Figure 45a" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 1.5*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure45-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure45-a-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure45-a-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure45-a-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_lblvs=true, use_Ualpha=use_Ualpha) # Now compare... # The agreement with these ones aren't so great. # Might be better if I grabbed the listing in the BPM appendix? SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.037 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.058 SPL_alpha_jl_interp = linear(freqs, SPL_alpha_jl, f_alpha.*1e3) vmin, vmax = extrema(SPL_alpha) err = abs.(SPL_alpha_jl_interp .- SPL_alpha)./(vmax - vmin) @test maximum(err) < 0.091 SPL_lbl_vs_jl_interp = linear(freqs, SPL_lbl_vs_jl, f_lbl_vs.*1e3) vmin, vmax = extrema(SPL_lbl_vs) err = abs.(SPL_lbl_vs_jl_interp .- SPL_lbl_vs)./(vmax - vmin) @test maximum(err) < 0.053 end end end @testset "BPM Figure 48c" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 22.86e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure48-c-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_lblvs=true, use_Ualpha=use_Ualpha) # Now compare... SPL_lbl_vs_jl_interp = linear(freqs, SPL_lbl_vs_jl, f_lbl_vs.*1e3) vmin, vmax = extrema(SPL_lbl_vs) err = abs.(SPL_lbl_vs_jl_interp .- SPL_lbl_vs)./(vmax - vmin) @test maximum(err) < 0.083 end end end @testset "BPM Figure 54a" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 15.24e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 2.7*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure54-a-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_lblvs=true, use_Ualpha=use_Ualpha) SPL_lbl_vs_jl_interp = linear(freqs, SPL_lbl_vs_jl, f_lbl_vs.*1e3) vmin, vmax = extrema(SPL_lbl_vs) err = abs.(SPL_lbl_vs_jl_interp .- SPL_lbl_vs)./(vmax - vmin) @test maximum(err) < 0.026 end end end @testset "BPM Figure 59c" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure59-c-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_lblvs=true, use_Ualpha=use_Ualpha) # Now compare... SPL_lbl_vs_jl_interp = linear(freqs, SPL_lbl_vs_jl, f_lbl_vs.*1e3) vmin, vmax = extrema(SPL_lbl_vs) err = abs.(SPL_lbl_vs_jl_interp .- SPL_lbl_vs)./(vmax - vmin) @test maximum(err) < 0.11 end end end @testset "BPM Figure 60c" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 3.3*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure60-c-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_lblvs=true, use_Ualpha=use_Ualpha) # Now compare... SPL_lbl_vs_jl_interp = linear(freqs, SPL_lbl_vs_jl, f_lbl_vs.*1e3) vmin, vmax = extrema(SPL_lbl_vs) err = abs.(SPL_lbl_vs_jl_interp .- SPL_lbl_vs)./(vmax - vmin) @test maximum(err) < 0.12 end end end @testset "BPM Figure 60d" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 3.3*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure60-d-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_lblvs=true, use_Ualpha=use_Ualpha) SPL_lbl_vs_jl_interp = linear(freqs, SPL_lbl_vs_jl, f_lbl_vs.*1e3) vmin, vmax = extrema(SPL_lbl_vs) err = abs.(SPL_lbl_vs_jl_interp .- SPL_lbl_vs)./(vmax - vmin) @test maximum(err) < 0.026 end end end @testset "BPM Figure 65d" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 5.08e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure65-d-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_lblvs=true, use_Ualpha=use_Ualpha) SPL_lbl_vs_jl_interp = linear(freqs, SPL_lbl_vs_jl, f_lbl_vs.*1e3) vmin, vmax = extrema(SPL_lbl_vs) err = abs.(SPL_lbl_vs_jl_interp .- SPL_lbl_vs)./(vmax - vmin) @test maximum(err) < 0.021 end end end @testset "BPM Figure 66b" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 5.08e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 4.2*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure66-b-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_lblvs=true, use_Ualpha=use_Ualpha) SPL_lbl_vs_jl_interp = linear(freqs, SPL_lbl_vs_jl, f_lbl_vs.*1e3) vmin, vmax = extrema(SPL_lbl_vs) err = abs.(SPL_lbl_vs_jl_interp .- SPL_lbl_vs)./(vmax - vmin) @test length(err) == 3 @test err[1] < 0.089 @test err[2] < 0.373 @test err[3] < 0.746 end end end @testset "BPM Figure 69a" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 5.08e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 15.4*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure69-a-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] for angle_of_attack_sign in [1, -1] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl) # Now compare... @test all(SPL_s_jl .β‰ˆ -100) @test all(SPL_p_jl .β‰ˆ -100) SPL_alpha_jl_interp = linear(freqs, SPL_alpha_jl, f_alpha.*1e3) vmin, vmax = extrema(SPL_alpha) err = abs.(SPL_alpha_jl_interp .- SPL_alpha)./(vmax - vmin) @test maximum(err) < 0.033 end end @testset "BPM Figure 91" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 30.48e-2 # span in meters chord = 15.24e-2 # chord in meters speedofsound = 340.46 U = 71.3 # freestream velocity in m/s # M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report M = U/speedofsound r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 # alphatip = 0.71*10.8*pi/180 alphastar = 10.8*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() # blade_tip = AcousticAnalogies.RoundedTip{AcousticAnalogies.BPMTipAlphaCorrection}() blade_tip = AcousticAnalogies.RoundedTip(AcousticAnalogies.BPMTipAlphaCorrection(), 0.0) fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure91-tip.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_tip = bpm[:, 1] SPL_tip = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_tip_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_tip_vortex=true, blade_tip=blade_tip, use_Ualpha=use_Ualpha) SPL_tip_jl_interp = linear(freqs, SPL_tip_jl, f_tip.*1e3) vmin, vmax = extrema(SPL_tip) err = abs.(SPL_tip_jl_interp .- SPL_tip)./(vmax - vmin) @test maximum(err) < 0.047 end end end @testset "BPM Figure 98b" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 69.5 # freestream velocity in m/s M = U/340.46 h = 1.1e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. # Figures 98 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-b-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_tebvs=true, h=h, Psi=Psi, use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.053 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.053 SPL_teb_vs_jl_interp = linear(freqs, SPL_teb_vs_jl, f_teb_vs.*1e3) vmin, vmax = extrema(SPL_teb_vs) err = abs.(SPL_teb_vs_jl_interp .- SPL_teb_vs)./(vmax - vmin) # Last two points are off. # Not sure why. @test maximum(err[1:end-2]) < 0.052 @test maximum(err[1:end-2]) < 0.052 @test maximum(err[1:end-1]) < 0.060 @test maximum(err) < 0.171 end end end @testset "BPM Figure 98c" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 69.5 # freestream velocity in m/s M = U/340.46 h = 1.9e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. # Figures 98 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-c-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_tebvs=true, h=h, Psi=Psi, use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.053 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.053 SPL_teb_vs_jl_interp = linear(freqs, SPL_teb_vs_jl, f_teb_vs.*1e3) vmin, vmax = extrema(SPL_teb_vs) err = abs.(SPL_teb_vs_jl_interp .- SPL_teb_vs)./(vmax - vmin) # Last two points are off. # Not sure why. @test maximum(err[1:end-2]) < 0.040 @test maximum(err[1:end-1]) < 0.189 @test err[end] < 0.111 end end end @testset "BPM Figure 98d" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 69.5 # freestream velocity in m/s M = U/340.46 h = 2.5e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. # Figures 98 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-d-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_tebvs=true, h=h, Psi=Psi, use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.053 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.053 SPL_teb_vs_jl_interp = linear(freqs, SPL_teb_vs_jl, f_teb_vs.*1e3) vmin, vmax = extrema(SPL_teb_vs) err = abs.(SPL_teb_vs_jl_interp .- SPL_teb_vs)./(vmax - vmin) # Last two points are off. # Not sure why. @test maximum(err[1:end-2]) < 0.044 @test err[end-1] < 0.089 @test err[end] < 0.089 end end end @testset "BPM Figure 99b" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 38.6 # freestream velocity in m/s M = U/340.46 h = 1.1e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_tebvs=true, h=h, Psi=Psi, use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.077 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.077 SPL_teb_vs_jl_interp = linear(freqs, SPL_teb_vs_jl, f_teb_vs.*1e3) vmin, vmax = extrema(SPL_teb_vs) err = abs.(SPL_teb_vs_jl_interp .- SPL_teb_vs)./(vmax - vmin) # Last two points are off. # Not sure why. @test maximum(err[1:end-2]) < 0.091 @test err[ end-1] < 0.251 @test err[ end ] < 0.400 end end end @testset "BPM Figure 99c" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 38.6 # freestream velocity in m/s M = U/340.46 h = 1.9e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. # Figures 99 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-c-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_tebvs=true, h=h, Psi=Psi, use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.077 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.077 SPL_teb_vs_jl_interp = linear(freqs, SPL_teb_vs_jl, f_teb_vs.*1e3) vmin, vmax = extrema(SPL_teb_vs) err = abs.(SPL_teb_vs_jl_interp .- SPL_teb_vs)./(vmax - vmin) # Last two points are off. # Not sure why. @test maximum(err[1:end-2]) < 0.057 @test err[ end-1] < 0.070 @test err[ end ] < 0.256 end end end @testset "BPM Figure 99d" begin nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 38.6 # freestream velocity in m/s M = U/340.46 h = 2.5e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Now, need to get the data from the BPM report. # Figures 99 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-d-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] for angle_of_attack_sign in [1, -1] for use_Ualpha in [false, true] freqs, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, angle_of_attack_sign*alphastar, bl; do_tebvs=true, h=h, Psi=Psi, use_Ualpha=use_Ualpha) # Now compare... SPL_s_jl_interp = linear(freqs, SPL_s_jl, f_s.*1e3) vmin, vmax = extrema(SPL_s) err = abs.(SPL_s_jl_interp .- SPL_s)./(vmax - vmin) @test maximum(err) < 0.077 SPL_p_jl_interp = linear(freqs, SPL_p_jl, f_p.*1e3) vmin, vmax = extrema(SPL_p) err = abs.(SPL_p_jl_interp .- SPL_p)./(vmax - vmin) @test maximum(err) < 0.077 SPL_teb_vs_jl_interp = linear(freqs, SPL_teb_vs_jl, f_teb_vs.*1e3) vmin, vmax = extrema(SPL_teb_vs) err = abs.(SPL_teb_vs_jl_interp .- SPL_teb_vs)./(vmax - vmin) # Last two points are off. # Not sure why. @test maximum(err[1:end-3]) < 0.047 @test err[end-2] < 0.068 @test err[end-1] < 0.213 @test err[end] < 0.225 end end end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
4220
module CombineTests using AcousticAnalogies using FLOWMath: akima, linear # using Random using Test @testset "Combine F1AOutput tests" begin # Goal is to verify that the code can faithfully combine two acoustic # pressures on different time "grids" onto a single common grid. fa(t) = sin(2*pi*t) + 0.2*cos(4*pi*(t-0.1)) fb(t) = cos(6*pi*t) + 0.3*sin(8*pi*(t-0.2)) n = 101 t1 = collect(range(0.0, 1.0, length=n)) dt = t1[2] - t1[1] # Add a bit of random noise to the time grid. Make sure that the amount of # randomness isn't large enough to make the time values non-monotonically # increasing (i.e., they don't overlap). # t1 .+= 0.49.*dt.*(1 .- 2 .* rand(size(t1)...)) # Annoyed by the randomness. # Let's make sure we have the same amount of "noise" for each test. wiggle1 = 0.49.*dt.*(cos.(2.0*pi.*t1)) t1 .+= wiggle1 t2 = collect(range(0.1, 1.1, length=n)) dt = t2[2] - t2[1] # t2 .+= 0.49.*dt.*(1 .- 2 .* rand(size(t2)...)) # Annoyed by the randomness. # Let's make sure we have the same amount of "noise" for each test. wiggle2 = 0.45.*dt.*(cos.(4.0*pi.*t2)) t2 .+= wiggle2 # Now I need a bunch of acoustic pressures. apth1 = @. F1AOutput(t1, fa(t1), 2*fa(t1)) apth2 = @. F1AOutput(t2, fb(t2), 3*fb(t2)) # Calculate the "exact" answer by coming up with a common time, then # evaluating the test functions directly on the common time grid. period = 0.5 n_out = 51 t_start = max(t1[1], t2[1]) t_common = t_start .+ (0:n_out-1).*(period/n_out) p_m = @. fa(t_common)+fb(t_common) p_d = @. 2*fa(t_common)+3*fb(t_common) even_length = iseven(n_out) apth_test = F1APressureTimeHistory{even_length}(p_m, p_d, step(t_common), first(t_common)) function combine_test_axis1(f_interp) # Put all the acoustic pressures in one array. apth = hcat(apth1, apth2) # Combine. axis = 1 apth_out = combine(apth, period, n_out, axis, f_interp=f_interp) # Now find the scaled absolute error between the two approaches. p_m_min, p_m_max = extrema(apth_test.p_m) err = @. abs(apth_out.p_m - apth_test.p_m)/(p_m_max - p_m_min) err_max = maximum(err) @test err_max < 0.01 p_d_min, p_d_max = extrema(apth_test.p_d) err = @. abs(apth_out.p_d - apth_test.p_d)/(p_d_max - p_d_min) err_max = maximum(err) @test err_max < 0.01 # Do it with the mutating version aka combine!. apth_out2 = F1APressureTimeHistory(apth, period, n_out, axis) combine!(apth_out2, apth, axis; f_interp=f_interp) @test all(apth_out2.p_m .β‰ˆ apth_out.p_m) @test all(apth_out2.p_d .β‰ˆ apth_out.p_d) @test apth_out2.dt β‰ˆ apth_out.dt @test apth_out2.t0 β‰ˆ apth_out.t0 return nothing end function combine_test_axis2(f_interp) # Put all the acoustic pressures in one array. apth = permutedims(hcat(apth1, apth2)) # Combine. axis = 2 apth_out = combine(apth, period, n_out, axis, f_interp=f_interp) # Now find the scaled absolute error between the two approaches. p_m_min, p_m_max = extrema(apth_test.p_m) err = @. abs(apth_out.p_m - apth_test.p_m)/(p_m_max - p_m_min) err_max = maximum(err) @test err_max < 0.01 p_d_min, p_d_max = extrema(apth_test.p_d) err = @. abs(apth_out.p_d - apth_test.p_d)/(p_d_max - p_d_min) err_max = maximum(err) @test err_max < 0.01 # Do it with the mutating version aka combine!. apth_out2 = F1APressureTimeHistory(apth, period, n_out, axis) combine!(apth_out2, apth, axis; f_interp=f_interp) @test all(apth_out2.p_m .β‰ˆ apth_out.p_m) @test all(apth_out2.p_d .β‰ˆ apth_out.p_d) @test apth_out2.dt β‰ˆ apth_out.dt @test apth_out2.t0 β‰ˆ apth_out.t0 return nothing end @testset "linear interpolation" begin combine_test_axis1(linear) combine_test_axis2(linear) end @testset "Akima spline interpolation" begin combine_test_axis1(akima) combine_test_axis2(akima) end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
7956
module CompactF1AConstructorTests using AcousticAnalogies using CCBlade using FileIO: load using KinematicCoordinateTransformations using StaticArrays using JLD2 using Test include("gen_test_data/gen_ccblade_data/constants.jl") using .CCBladeTestCaseConstants ccbc = CCBladeTestCaseConstants @testset "CCBlade private utils tests" begin Ξ”r = (ccbc.Rtip - ccbc.Rhub)/10 r = (ccbc.Rhub+0.5*Ξ”r):Ξ”r:(ccbc.Rtip-0.5*Ξ”r) precone = 3*pi/180 rotor = Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades; precone=precone, turbine=false) dummy = similar(r) sections = Section.(r, dummy, dummy, dummy) @test all(AcousticAnalogies.get_ccblade_dradii(rotor, sections) .β‰ˆ Ξ”r) end @testset "Constructor rotation tests" begin @testset "CompactF1ASourceElement" begin ρ0 = 1.1 c0 = 1.2 r = 2.0 Ξ”r = 0.1 Ξ› = 0.2 fn = 2.0 fr = 3.0 fc = 4.0 Ο„ = 0.1 se_0theta = CompactF1ASourceElement(ρ0, c0, r, 0.0, Ξ”r, Ξ›, fn, fr, fc, Ο„) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) # Create a transformation that will undo the ΞΈ rotation. trans = KinematicCoordinateTransformations.SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) # Create a source element with the theta rotation, then undo it. se = CompactF1ASourceElement(ρ0, c0, r, ΞΈ, Ξ”r, Ξ›, fn, fr, fc, Ο„) |> trans # Check that we got the same thing: for field in fieldnames(CompactF1ASourceElement) @test getproperty(se, field) β‰ˆ getproperty(se_0theta, field) end end end @testset "CompactF1ASourceElement, CCBlade" begin # Create the CCBlade objects. area_per_chord2 = 0.1 Ο„ = 0.1 ccblade_fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11-outputs.jld2") outs_d = load(ccblade_fname) section = CCBlade.Section(first(ccbc.radii), first(ccbc.chord), first(ccbc.theta)*pi/180, nothing) Ξ”r = ccbc.radii[2] - ccbc.radii[1] op = CCBlade.OperatingPoint(ccbc.v, outs_d["omega"]*first(ccbc.radii), ccbc.rho, ccbc.pitch, ccbc.mu, ccbc.c0) rotor0precone = CCBlade.Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades) out = CCBlade.Outputs(outs_d["Np"][1], outs_d["Tp"][1], outs_d["a"][1], outs_d["ap"][1], outs_d["u"][1], outs_d["v"][1], outs_d["phi"][1], outs_d["alpha"][1], outs_d["W"][1], outs_d["cl"][1], outs_d["cd"][1], outs_d["cn"][1], outs_d["ct"][1], outs_d["F"][1], outs_d["G"][1]) @test rotor0precone.precone β‰ˆ 0.0 Rhub = rotor0precone.Rhub Rtip = rotor0precone.Rtip num_blades = rotor0precone.B turbine = rotor0precone.turbine for positive_x_rotation in [true, false] se_0theta0precone = CompactF1ASourceElement(rotor0precone, section, op, out, 0.0, Ξ”r, area_per_chord2, Ο„, positive_x_rotation) for precone in [5, 10, 65, 95, 260, 270, 290].*(pi/180) rotor = CCBlade.Rotor(Rhub, Rtip, num_blades; turbine=turbine, precone=precone) # This is tricky: in my "normal" coordinate system, the blade is rotating around the x axis, moving axially in the positive x direction, and is initially aligned with the y axis. # That means that the precone should be a rotation around the negative z axis. # And so to undo it, we want a positive rotation around the positive z axis. trans_precone = SteadyRotZTransformation(Ο„, 0.0, precone) for ΞΈ in [5, 10, 65, 95, 260, 270, 290].*(pi/180) trans_theta = SteadyRotXTransformation(Ο„, 0.0, -ΞΈ) # Create a transformation that reverses the theta and precone rotations. # The precone happens first, then theta. # So to reverse it we need to do theta, then precone. trans = KinematicCoordinateTransformations.compose(Ο„, trans_precone, trans_theta) # Create a source element with the theta and precone rotations, then undo it. se = CompactF1ASourceElement(rotor, section, op, out, ΞΈ, Ξ”r, area_per_chord2, Ο„, positive_x_rotation) |> trans # Check that we got the same thing: for field in fieldnames(CompactF1ASourceElement) @test getproperty(se, field) β‰ˆ getproperty(se_0theta0precone, field) end end end end end end @testset "CCBlade CompactF1ASourceElement complete test" begin for positive_x_rotation in [true, false] # omega = 2200*(2*pi/60) # Read in the loading data. # data = readdlm("gen_test_data/gen_ccblade_data/ccblade_omega11.csv", ',') # Np = data[:, 1] # Tp = data[:, 2] # Read in the loading data. fname = joinpath(@__DIR__, "gen_test_data", "gen_ccblade_data", "ccblade_omega11-outputs.jld2") data_d = load(fname) omega = data_d["omega"] Np = data_d["Np"] Tp = data_d["Tp"] # Create the CCBlade objects. rotor = Rotor(ccbc.Rhub, ccbc.Rtip, ccbc.num_blades; turbine=false) sections = Section.(ccbc.radii, ccbc.chord, ccbc.theta, nothing) ops = simple_op.(ccbc.v, omega, ccbc.radii, ccbc.rho; asound=ccbc.c0) # Only care about getting the loading into the CCBlade Output structs. dummies = fill(0.0, 13) outs = Outputs.(Np, Tp, dummies...) # Set the source time stuff. num_blade_passes = 3 steps_per_blade_pass = 8 num_src_times = num_blade_passes*steps_per_blade_pass bpp = 2*pi/omega/ccbc.num_blades src_time_range = num_blade_passes*bpp # Finally get all the source elements. aoc2 = fill(ccbc.area_over_chord_squared, length(sections)) ses_helper = f1a_source_elements_ccblade(rotor, sections, ops, outs, aoc2, src_time_range, num_src_times, positive_x_rotation) # Now need to get the source elements the "normal" way. First get the # transformation objects. rot_axis = @SVector [1.0, 0.0, 0.0] blade_axis = @SVector [0.0, 1.0, 0.0] y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = ccbc.v.*rot_axis t0 = 0.0 if positive_x_rotation rot_trans = SteadyRotXTransformation(t0, omega, 0.0) else rot_trans = SteadyRotXTransformation(t0, -omega, 0.0) end const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Need the source times. dt = src_time_range/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # This is just an array of the angular offsets of each blade. ΞΈs = 2*pi/ccbc.num_blades.*(0:(ccbc.num_blades-1)) # Radial spacing. dradii = get_dradii(ccbc.radii, ccbc.Rhub, ccbc.Rtip) # Reshape stuff for broadcasting. radii = reshape(ccbc.radii, 1, :, 1) dradii = reshape(dradii, 1, :, 1) cs_area = reshape(ccbc.area_over_chord_squared.*ccbc.chord.^2, 1, :, 1) Np = reshape(Np, 1, :, 1) Tp = reshape(Tp, 1, :, 1) src_times = reshape(src_times, :, 1, 1) # This isn't really necessary. ΞΈs = reshape(ΞΈs, 1, 1, :) # Get all the transformations. trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Transform the source elements. if positive_x_rotation ses = CompactF1ASourceElement.(ccbc.rho, ccbc.c0, radii, ΞΈs, dradii, cs_area, -Np, 0.0, Tp, src_times) .|> trans else ses = CompactF1ASourceElement.(ccbc.rho, ccbc.c0, radii, ΞΈs, dradii, cs_area, -Np, 0.0, -Tp, src_times) .|> trans end for field in fieldnames(CompactF1ASourceElement) @test all(getproperty.(ses_helper, field) .β‰ˆ getproperty.(ses, field)) end end end end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
9799
module DopplerTests using AcousticAnalogies: AcousticAnalogies using KinematicCoordinateTransformations: KinematicTransformation, SteadyRotXTransformation, SteadyRotYTransformation, SteadyRotZTransformation, ConstantVelocityTransformation, compose using StaticArrays: SVector using Test struct DummyElement{TDoppler,Ty0dot,Ty1dot,Ttime,TSoS} <: AcousticAnalogies.AbstractBroadbandSourceElement{AcousticAnalogies.BPMDirectivity,false, AcousticAnalogies.NoMachCorrection,TDoppler} # Source position and its time derivatives. y0dot::Ty0dot y1dot::Ty1dot # Source time. Ο„::Ttime # speed of sound c0::TSoS end function DummyElement{TDoppler}(y0dot, y1dot, Ο„, c0) where {TDoppler} return DummyElement{TDoppler,typeof(y0dot),typeof(y1dot),typeof(Ο„),typeof(c0)}(y0dot, y1dot, Ο„, c0) end function DummyElement{TDoppler}(se::DummyElement) where {TDoppler} return DummyElement{TDoppler,typeof(se.y0dot),typeof(se.y1dot),typeof(se.Ο„),typeof(se.c0)}(se.y0dot, se.y1dot, se.Ο„, se.c0) end """ (trans::KinematicTransformation)(se::DummyElement) Transform the position and orientation of a source element according to the coordinate system transformation `trans`. """ function (trans::KinematicTransformation)(se::DummyElement{TDoppler,Ty0dot,Ty1dot,Ttime,TSoS}) where {TDoppler,Ty0dot,Ty1dot,Ttime,TSoS} linear_only = false y0dot, y1dot = trans(se.Ο„, se.y0dot, se.y1dot, linear_only) return DummyElement{TDoppler,Ty0dot,Ty1dot,Ttime,TSoS}(y0dot, y1dot, se.Ο„, se.c0) end @testset "Doppler shift" begin @testset "no motion" begin @testset "stationary observer" begin obs = AcousticAnalogies.StationaryAcousticObserver(SVector(1.2, 2.3, 3.4)) se = DummyElement{true}(SVector(3.0, 4.3, 5.0), SVector(0.0, 0.0, 0.0), 10.0, 340.0) @test AcousticAnalogies.doppler_factor(se, obs) β‰ˆ 1.0 @test AcousticAnalogies.doppler_factor(DummyElement{false}(se), obs) β‰ˆ 1.0 end @testset "\"moving\" observer" begin # Should get the same thing with a `ConstVelocityAcousticObserver` that's not moving. obs = AcousticAnalogies.ConstVelocityAcousticObserver(8.0, SVector(1.2, 2.3, 3.4), SVector(0.0, 0.0, 0.0)) se = DummyElement{true}(SVector(3.0, 4.3, 5.0), SVector(0.0, 0.0, 0.0), 10.0, 340.0) @test AcousticAnalogies.doppler_factor(se, obs) β‰ˆ 1.0 @test AcousticAnalogies.doppler_factor(DummyElement{false}(se), obs) β‰ˆ 1.0 end end @testset "moving source" begin @testset "stationary observer" begin for mach_vector in -0.9:0.1:0.9 c0 = 343.0 # Observer time doesn't matter since the observer isn't moving. t_obs = 6.5 x_obs = SVector(1.2, 2.3, 3.4) obs = AcousticAnalogies.StationaryAcousticObserver(x_obs) y0dot = SVector(1.2, 2.3, -3.4) y1dot = SVector(0.0, 0.0, mach_vector*c0) Ο„ = 10.0 se = DummyElement{true}(y0dot, y1dot, Ο„, c0) doppler_factor_expected = 1/(1 - mach_vector) @test AcousticAnalogies.doppler_factor(se, obs) β‰ˆ doppler_factor_expected @test AcousticAnalogies.doppler_factor(DummyElement{false}(se), obs) β‰ˆ 1.0 # Now, rotate and translate both the source and the observer. # The Doppler shift factor should be the same, assuming we don't change the motion of the source and observer. # Time parameter for the steady rotations doesn't matter because the rotation rate is zero. trans1 = SteadyRotXTransformation(t_obs, 0.0, 3.0*pi/180) trans2 = SteadyRotYTransformation(t_obs, 0.0, 4.0*pi/180) trans3 = SteadyRotZTransformation(t_obs, 0.0, 5.0*pi/180) x_trans = SVector(2.0, 3.0, 4.0) v_trans = SVector(0.0, 0.0, 0.0) # Time parameter for the constant velocity transformations doesn't matter because the velocity is zero. trans4 = ConstantVelocityTransformation(t_obs, x_trans, v_trans) # Transform the source and observer. trans = compose(t_obs, trans4, compose(t_obs, trans3, compose(t_obs, trans2, trans1))) se_trans = trans(se) obs_trans = AcousticAnalogies.StationaryAcousticObserver(trans(t_obs, obs(t_obs))) # Now we should still get the same Doppler factor. @test AcousticAnalogies.doppler_factor(se_trans, obs_trans) β‰ˆ doppler_factor_expected @test AcousticAnalogies.doppler_factor(DummyElement{false}(se_trans), obs_trans) β‰ˆ 1.0 end end @testset "\"moving\" observer" begin for mach_vector in -0.9:0.1:0.9 c0 = 343.0 # Observer time doesn't matter since the observer isn't moving. t_obs = 6.5 x_obs = SVector(1.2, 2.3, 3.4) v_obs = SVector(0.0, 0.0, 0.0) obs = AcousticAnalogies.ConstVelocityAcousticObserver(t_obs, x_obs, v_obs) y0dot = SVector(1.2, 2.3, -3.4) y1dot = SVector(0.0, 0.0, mach_vector*c0) Ο„ = 10.0 se = DummyElement{true}(y0dot, y1dot, Ο„, c0) doppler_factor_expected = 1/(1 - mach_vector) @test AcousticAnalogies.doppler_factor(se, obs) β‰ˆ doppler_factor_expected @test AcousticAnalogies.doppler_factor(DummyElement{false}(se), obs) β‰ˆ 1.0 # Now, rotate and translate both the source and the observer. # The Doppler shift factor should be the same, assuming we don't change the motion of the source and observer. # Time parameter for the steady rotations doesn't matter because the rotation rate is zero. trans1 = SteadyRotXTransformation(t_obs, 0.0, 3.0*pi/180) trans2 = SteadyRotYTransformation(t_obs, 0.0, 4.0*pi/180) trans3 = SteadyRotZTransformation(t_obs, 0.0, 5.0*pi/180) x_trans = SVector(2.0, 3.0, 4.0) v_trans = SVector(0.0, 0.0, 0.0) # Time parameter for the constant velocity transformations doesn't matter because the velocity is zero. trans4 = ConstantVelocityTransformation(t_obs, x_trans, v_trans) # Transform the source and observer. trans = compose(t_obs, trans4, compose(t_obs, trans3, compose(t_obs, trans2, trans1))) se_trans = trans(se) obs_trans = AcousticAnalogies.ConstVelocityAcousticObserver(t_obs, trans(t_obs, obs(t_obs), AcousticAnalogies.velocity(t_obs, obs))...) # Now we should still get the same Doppler factor. @test AcousticAnalogies.doppler_factor(se_trans, obs_trans) β‰ˆ doppler_factor_expected @test AcousticAnalogies.doppler_factor(DummyElement{false}(se_trans), obs_trans) β‰ˆ 1.0 end end @testset "actual moving observer" begin for mach_vector_obs in -0.9:0.1:0.9 for mach_vector_src in -0.9:0.1:0.9 c0 = 343.0 t_obs = 10.0 # Need to move the observer farther from the source for cases where they're moving towards each other, since the Doppler factor will change if they cross and move past each other. x_obs = SVector(1.2, 2.3, 340.0) v_obs = SVector(0.0, 0.0, mach_vector_obs*c0) obs = AcousticAnalogies.ConstVelocityAcousticObserver(t_obs, x_obs, v_obs) y0dot = SVector(1.2, 2.3, -3.4) y1dot = SVector(0.0, 0.0, mach_vector_src*c0) Ο„ = 10.0 se = DummyElement{true}(y0dot, y1dot, Ο„, c0) doppler_factor_expected = (1 - mach_vector_obs)/(1 - mach_vector_src) @test AcousticAnalogies.doppler_factor(se, obs) β‰ˆ doppler_factor_expected @test AcousticAnalogies.doppler_factor(DummyElement{false}(se), obs) β‰ˆ 1.0 # Now, rotate and translate both the source and the observer. # The Doppler shift factor should be the same, assuming we don't change the motion of the source and observer. # Time parameter for the steady rotations doesn't matter because the rotation rate is zero. trans1 = SteadyRotXTransformation(t_obs, 0.0, 3.0*pi/180) trans2 = SteadyRotYTransformation(t_obs, 0.0, 4.0*pi/180) trans3 = SteadyRotZTransformation(t_obs, 0.0, 5.0*pi/180) x_trans = SVector(2.0, 3.0, 4.0) v_trans = SVector(0.0, 0.0, 0.0) # Time parameter for the constant velocity transformations doesn't matter because the velocity is zero. trans4 = ConstantVelocityTransformation(t_obs, x_trans, v_trans) # Transform the source and observer. trans = compose(t_obs, trans4, compose(t_obs, trans3, compose(t_obs, trans2, trans1))) se_trans = trans(se) obs_trans = AcousticAnalogies.ConstVelocityAcousticObserver(t_obs, trans(t_obs, obs(t_obs), AcousticAnalogies.velocity(t_obs, obs))...) # Now we should still get the same Doppler factor. @test AcousticAnalogies.doppler_factor(se_trans, obs_trans) β‰ˆ doppler_factor_expected @test AcousticAnalogies.doppler_factor(DummyElement{false}(se_trans), obs_trans) β‰ˆ 1.0 end end end end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
4288
module F1ATests using AcousticAnalogies using FLOWMath using LinearAlgebra: norm using NLsolve using Polynomials using Test function f1_integrand(se, obs, t) c0 = se.c0 # Need to get the retarded time. R(Ο„) = [t - (Ο„[1] + norm(obs(t) .- se.y0dot(Ο„[1]))/c0)] result = nlsolve(R, [-0.1], autodiff=:forward) if !converged(result) @error "nlsolve retarded time calculation did not converge:\n$(result)" end Ο„ = result.zero[1] # Position of source at the retarted time. y = se.y0dot(Ο„) # Position vector from source to observer. rv = obs(t) .- y # Distance from source to observer. r = AcousticAnalogies.norm_cs_safe(rv) # Unit vector pointing from source to observer. rhat = rv./r # First time derivative of rv. rv1dot = -se.y1dot(Ο„) # Mach number of the velocity of the source in the direction of the # observer. Mr = AcousticAnalogies.dot_cs_safe(-rv1dot/se.c0, rhat) # Now evaluate the integrand. p_m_integrand = se.ρ0/(4*pi)*se.Ξ›*se.Ξ”r/(r*(1 - Mr)) # Loading at the retarded time. f0dot = se.f0dot(Ο„) p_d_integrand_ff = (1/(4*pi*c0))*AcousticAnalogies.dot_cs_safe(f0dot, rhat)/(r*(1 - Mr))*se.Ξ”r p_d_integrand_nf = (1/(4*pi*c0))*AcousticAnalogies.dot_cs_safe(f0dot, rhat)*c0/(r^2*(1 - Mr))*se.Ξ”r return Ο„, p_m_integrand, p_d_integrand_ff, p_d_integrand_nf end @testset "F1A tests" begin # rho = 1.226 # kg/m^3 rho = 1.226e6 # kg/m^3 c0 = 340.0 # m/s Rtip = 1.1684 # meters radii = 0.99932*Rtip dradii = (0.99932 - 0.99660)*Rtip # m area_over_chord_squared = 0.064 chord = 0.47397E-02 * Rtip Ξ› = area_over_chord_squared * chord^2 theta = 90.0*pi/180.0 x0 = [cos(theta), 0.0, sin(theta)].*100.0.*12.0.*0.0254 # 100 ft in meters obs = StationaryAcousticObserver(x0) # Need the position and velocity of the source as a function of # source/retarded time. How do I want it to move? I want it to rotate around # an axis on the origin, pointing in the x direction. rpm = 2200 omega = 2*pi/60*rpm period = 60/rpm fn = 180.66763939805125 fc = 19.358679206883078 y0dot(Ο„) = [0, radii*cos(omega*Ο„), radii*sin(omega*Ο„)] y1dot(Ο„) = [0, -omega*radii*sin(omega*Ο„), omega*radii*cos(omega*Ο„)] y2dot(Ο„) = [0, -omega^2*radii*cos(omega*Ο„), -omega^2*radii*sin(omega*Ο„)] y3dot(Ο„) = [0, omega^3*radii*sin(omega*Ο„), -omega^3*radii*cos(omega*Ο„)] f0dot(Ο„) = [-fn, -sin(omega*Ο„)*fc, cos(omega*Ο„)*fc] f1dot(Ο„) = [0, -omega*cos(omega*Ο„)*fc, -omega*sin(omega*Ο„)*fc] u(Ο„) = y0dot(Ο„)./radii sef1 = CompactF1ASourceElement(rho, c0, dradii, Ξ›, y0dot, y1dot, nothing, nothing, f0dot, nothing, 0.0, u) t = 0.0 dt = period*0.5^4 Ο„0, pmi0, pdiff0, pdinf0 = f1_integrand(sef1, obs, t) sef1a = CompactF1ASourceElement(rho, c0, dradii, Ξ›, y0dot(Ο„0), y1dot(Ο„0), y2dot(Ο„0), y3dot(Ο„0), f0dot(Ο„0), f1dot(Ο„0), Ο„0, u(Ο„0)) apth = noise(sef1a, obs) err_prev_pm = nothing err_prev_pd = nothing dt_prev = nothing dt_curr = dt first_time = true err_pm = [] err_pd = [] dts = [] ooa_pm = [] ooa_pd = [] for n in 1:7 Ο„_1, pmi_1, pdiff_1, pdinf_1 = f1_integrand(sef1, obs, t-dt_curr) Ο„1, pmi1, pdiff1, pdinf1 = f1_integrand(sef1, obs, t+dt_curr) p_m_f1 = (pmi_1 - 2*pmi0 + pmi1)/(dt_curr^2) p_d_f1 = (pdiff1 - pdiff_1)/(2*dt_curr) + pdinf0 err_curr_pm = abs(p_m_f1 - apth.p_m) err_curr_pd = abs(p_d_f1 - apth.p_d) if first_time first_time = false else push!(ooa_pm, log(err_curr_pm/err_prev_pm)/log(dt_curr/dt_prev)) push!(ooa_pd, log(err_curr_pd/err_prev_pd)/log(dt_curr/dt_prev)) end push!(dts, dt_curr) push!(err_pm, err_curr_pm) push!(err_pd, err_curr_pd) dt_prev = dt_curr err_prev_pm = err_curr_pm err_prev_pd = err_curr_pd dt_curr = 0.5*dt_curr end # Fit a line through the errors on a log-log plot, then check that the slope # is second-order. l = fit(log.(dts), log.(err_pm), 1) @test isapprox(l.coeffs[2], 2, atol=0.1) l = fit(log.(dts), log.(err_pd), 1) @test isapprox(l.coeffs[2], 2, atol=0.1) end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
5325
module ForwardDiffTests using AcousticAnalogies using ForwardDiff using KinematicCoordinateTransformations using StaticArrays using CCBlade using AcousticMetrics using Test using LinearAlgebra function guided_example(x) Rx::eltype(x) = 0.0 Rhub = x[1] Rtip = x[2] num_blades = 2 radii = [ 0.92904E-01, 0.11751, 0.15631, 0.20097, 0.24792 , 0.29563, 0.34336, 0.39068, 0.43727 , 0.48291, 0.52741, 0.57060, 0.61234 , 0.65249, 0.69092, 0.72752, 0.76218 , 0.79479, 0.82527, 0.85352, 0.87947 , 0.90303, 0.92415, 0.94275, 0.95880 , 0.97224, 0.98304, 0.99117, 0.99660 , 0.99932] .* Rtip ΞΈs = 2pi / num_blades .* (0:(num_blades-1)) .+ Rx dradii = get_dradii(radii, Rhub, Rtip) rho = 1.226 # kg/m^3 c0 = 340.0 # m/s v = x[3] omega = x[4] # rad/s cs_area_over_chord_squared = 0.064 chord = x[5:34] .* Rtip cs_area = cs_area_over_chord_squared .* chord.^2 fn = [32.87810395677037, 99.05130471878633, 190.1751697055377, 275.9492967565419, 358.14423433748146, 439.64679797145624, 520.1002808148281, 599.1445046901513, 676.2358818769462, 751.3409657831587, 824.2087672338118, 894.4465814696498, 961.9015451678036, 1026.0112737521583, 1086.2610633094212, 1141.4900032393818, 1190.3376703335655, 1230.8999662260915, 1260.375390697363, 1275.354422403355, 1271.8827617273287, 1245.9059108698596, 1193.9967137923225, 1113.9397490286995, 1005.273267675585, 869.4101036003673, 709.8100230053759, 532.1946243370355, 346.53986082379265, 180.66763939805125] .+ Rx fc = [26.09881302938423, 55.5216259955307, 75.84767780212506, 84.84509232798283, 89.73045068624886, 93.02999477395113, 95.4384273852926, 97.31647535460424, 98.81063179767507, 100.07617771995163, 101.17251941705561, 102.11543878532882, 102.94453631586998, 103.63835661864168, 104.18877957193807, 104.51732850056433, 104.54735678589765, 104.1688287897138, 103.20319203286938, 101.46246817378582, 99.11692436681635, 96.49009546562475, 93.45834266417528, 89.49783586366624, 83.87176811707455, 75.83190739325453, 64.88004605331857, 50.98243352318318, 34.85525518071079, 19.358679206883078] .+ Rx period = 2pi / omega num_src_times = 64 dt = 2 * period / (num_src_times-1) src_times = (0:num_src_times-1) .* dt ΞΈs = reshape(ΞΈs, 1, 1, :) radii = reshape(radii, 1, :, 1) dradii = reshape(dradii, 1, :, 1) cs_area = reshape(cs_area, 1, :, 1) fn = reshape(fn, 1, :, 1) fc = reshape(fc, 1, :, 1) src_times = reshape(src_times, :, 1, 1) # This isn't really necessary. ses = CompactF1ASourceElement.(rho, c0, radii, ΞΈs, dradii, cs_area, -fn, 0.0, fc, src_times) t0 = 0.0 # Time at which the angle between the source and target coordinate systems is equal to offest. offset = 0.0 # Angular offset between the source and target cooridante systems at t0. rot_trans = SteadyRotXTransformation(t0, omega, offset) rot_axis = @SVector [0.0, 0.0, 1.0] blade_axis = @SVector [0.0, 1.0, 0.0] global_trans = ConstantLinearMap(hcat(rot_axis, blade_axis, rot_axisΓ—blade_axis)) y0_hub = @SVector [0.0, 0.0, 0.0] # Position of the hub at time t0 v0_hub = SVector{3}(v.*rot_axis) # Constant velocity of the hub in the global reference frame const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) trans = compose.(src_times, Ref(const_vel_trans), compose.(src_times, Ref(global_trans), Ref(rot_trans))) ses = ses .|> trans x0 = @SVector [100*12*0.0254, 0.0, 0.0] # 100 ft in meters obs = StationaryAcousticObserver(x0) obs_time = adv_time.(ses, Ref(obs)) apth = noise.(ses, Ref(obs), obs_time) bpp = period/num_blades # blade passing period obs_time_range = 2 * bpp num_obs_times = 128 apth_total = combine(apth, obs_time_range, num_obs_times, 1) oaspl_from_apth = AcousticMetrics.OASPL(apth_total) nbs = AcousticMetrics.MSPSpectrumAmplitude(apth_total) oaspl_from_nbs = AcousticMetrics.OASPL(nbs) return vcat(oaspl_from_apth, oaspl_from_nbs) end ### Just run the guided example through ForwardDiff without errors. # May want to make more comprehensive later. For now pretty much everything # is affected by Dual numbers here, except for the loads are still Floats # for now. @testset "ForwardDiff test" begin Rhub = 0.10 Rtip = 1.1684 v = 0.0 # m/s omega = 2200 * 2pi/60 # rad/s chord_normalized = [0.35044 , 0.28260 , 0.22105 , 0.17787 , 0.14760, 0.12567 , 0.10927 , 0.96661E-01 , 0.86742E-01 , 0.78783E-01 , 0.72287E-01 , 0.66906E-01 , 0.62387E-01 , 0.58541E-01 , 0.55217E-01 , 0.52290E-01 , 0.49645E-01 , 0.47176E-01 , 0.44772E-01 , 0.42326E-01 , 0.39732E-01 , 0.36898E-01 , 0.33752E-01 , 0.30255E-01 , 0.26401E-01 , 0.22217E-01 , 0.17765E-01 , 0.13147E-01 , 0.85683E-02 , 0.47397E-02] x0 = vcat(Rhub, Rtip, v, omega, chord_normalized) J = ForwardDiff.jacobian(guided_example, x0) end end #module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
13837
module iea3p4 using AcousticAnalogies using AcousticMetrics using ColorSchemes: colorschemes using GLMakie using DelimitedFiles using KinematicCoordinateTransformations using LinearAlgebra: Γ— using StaticArrays using AcousticMetrics using Statistics using Interpolations ## Start of user-defined inputs # Set number of blades, usually 3 for modern wind turbines num_blades = 3 # number of blades # Set the hub radius in m, it is specified in the ElastoDyn main input file of OpenFAST Rhub = 2. # Set the blade spanwise grid in m and the corresponding chord, also in m. The two arrays # are specified in the AeroDyn15 blade input file BlSpn = [0.0000e+00, 2.1692e+00, 4.3385e+00, 6.5077e+00, 8.6770e+00, 1.0846e+01, 1.3015e+01, 1.5184e+01, 1.7354e+01, 1.9523e+01, 2.1692e+01, 2.3861e+01, 2.6031e+01, 2.8200e+01, 3.0369e+01, 3.2538e+01, 3.4708e+01, 3.6877e+01, 3.9046e+01, 4.1215e+01, 4.3385e+01, 4.5554e+01, 4.7723e+01, 4.9892e+01, 5.2062e+01, 5.4231e+01, 5.6400e+01, 5.8570e+01, 6.0739e+01, 6.2908e+01] Chord = [2.600e+00, 2.645e+00, 3.020e+00, 3.437e+00, 3.781e+00, 4.036e+00, 4.201e+00, 4.284e+00, 4.288e+00, 4.223e+00, 4.098e+00, 3.923e+00, 3.709e+00, 3.468e+00, 3.220e+00, 2.986e+00, 2.770e+00, 2.581e+00, 2.412e+00, 2.266e+00, 2.142e+00, 2.042e+00, 1.964e+00, 1.909e+00, 1.870e+00, 1.807e+00, 1.666e+00, 1.387e+00, 9.172e-01, 1.999e-01] # path to the OpenFAST .out file. The file must contain these channels: # Time (always available) # Wind1VelX from InflowWind # RotSpeed from ElastoDyn # Nodal outputs Fxl and Fyl from AeroDyn15 file_path = joinpath(@__DIR__, "gen_test_data", "openfast_data", "IEA-3.4-130-RWT.out") # Observer location set at the IEC-prescribed location (turbine height on the ground), # The microphone is stationary in the global coordinate frame HH = 110. # m # Compute the blade locations in radial coordinates, m RSpn = BlSpn .+ Rhub x0 = @SVector [HH .+ RSpn[end], 0.0, -HH] # ambient air density and speed of sound. rho = 1.225 # kg/m^3 c0 = 340.0 # m/s ## End of user-defined inputs ## Start of computations # Compute the mid-section locations in radial coordinates, m radii = 0.5.*(RSpn[begin:end-1] .+ RSpn[begin+1:end]) # Compute the length of each section along blade span, m dradii = RSpn[begin+1:end] .- RSpn[begin:end-1] # Compute the blade angles ΞΈs = 2*pi/num_blades.*(0:(num_blades-1)) # Create a linear interpolation object to interpolate chord onto the radial mid-points itp = LinearInterpolation(RSpn, Chord) # Perform interpolation chord = itp(radii) # Cross-sectional area of each element in m**2. This is taking a bit of a shortcut cs_area_over_chord_squared = 0.064 cs_area = cs_area_over_chord_squared.*chord.^2 # Code to parse the data from the OpenFAST .out file # Function to parse a line of data, converting strings to floats function parse_line(line) # Split the line by whitespace and filter out any empty strings elements = filter(x -> !isempty(x), split(line)) # Convert elements to Float64 return map(x -> parse(Float64, x), elements) end # Initialize an empty array to store the data data = [] # Open the file and read the data, skipping the first 8 lines open(file_path) do file # Skip the first 8 lines (header and description) for i in 1:8 readline(file) end # Read the rest of the lines and parse them for line in eachline(file) push!(data, parse_line(line)) end end # Convert the data to an array of arrays (matrix) data = reduce(hcat, data) time = data[1, :] avg_wind_speed = mean(data[2, :]) sim_length_s = time[end] - time[1] # s @show length(time) # Reopen the file and read the lines lines = open(file_path) do f readlines(f) end # Find the index of the line that contains the column headers header_index = findfirst(x -> startswith(x, "Time"), lines) # Extract the headers headers = split(lines[header_index], '\t') id_b1_Fx = findfirst(x -> x == "AB1N001Fxl", headers) id_b2_Fx = findfirst(x -> x == "AB2N001Fxl", headers) id_b3_Fx = findfirst(x -> x == "AB3N001Fxl", headers) id_b1_Fy = findfirst(x -> x == "AB1N001Fyl", headers) id_b2_Fy = findfirst(x -> x == "AB2N001Fyl", headers) id_b3_Fy = findfirst(x -> x == "AB3N001Fyl", headers) id_rot_speed = findfirst(x -> x == "RotSpeed", headers) n_elems = length(radii) Fx_b1_locs = data[id_b1_Fx:id_b1_Fx+n_elems,:] Fy_b1_locs = data[id_b1_Fy:id_b1_Fy+n_elems,:] Fx_b2_locs = data[id_b2_Fx:id_b2_Fx+n_elems,:] Fy_b2_locs = data[id_b2_Fy:id_b2_Fy+n_elems,:] Fx_b3_locs = data[id_b3_Fx:id_b3_Fx+n_elems,:] Fy_b3_locs = data[id_b3_Fy:id_b3_Fy+n_elems,:] # Reinterpolate onto the mid-sections Fx_b1 = Array{Float64}(undef, 29, 6001) Fx_b2 = Array{Float64}(undef, 29, 6001) Fx_b3 = Array{Float64}(undef, 29, 6001) Fy_b1 = Array{Float64}(undef, 29, 6001) Fy_b2 = Array{Float64}(undef, 29, 6001) Fy_b3 = Array{Float64}(undef, 29, 6001) for j in axes(Fx_b1_locs, 2) itp = LinearInterpolation(RSpn, Fx_b1_locs[:, j], extrapolation_bc=Line()) Fx_b1[:, j] = itp(radii) end for j in axes(Fx_b2_locs, 2) itp = LinearInterpolation(RSpn, Fx_b2_locs[:, j], extrapolation_bc=Line()) Fx_b2[:, j] = itp(radii) end for j in axes(Fx_b3_locs, 2) itp = LinearInterpolation(RSpn, Fx_b3_locs[:, j], extrapolation_bc=Line()) Fx_b3[:, j] = itp(radii) end for j in axes(Fy_b1_locs, 2) itp = LinearInterpolation(RSpn, Fy_b1_locs[:, j], extrapolation_bc=Line()) Fy_b1[:, j] = itp(radii) end for j in axes(Fy_b2_locs, 2) itp = LinearInterpolation(RSpn, Fy_b2_locs[:, j], extrapolation_bc=Line()) Fy_b2[:, j] = itp(radii) end for j in axes(Fy_b3_locs, 2) itp = LinearInterpolation(RSpn, Fy_b3_locs[:, j], extrapolation_bc=Line()) Fy_b3[:, j] = itp(radii) end # Extract the mean rotor speed omega_rpm = mean(data[id_rot_speed,:]) # Let's plot the unsteady loading 1 of every 500 timesteps # x-axis is the span position (mid-sections) # times are indicated by the colorbar on the right of the plot. @assert size(Fx_b1) == size(Fx_b2) == size(Fx_b3) == size(Fy_b1) == size(Fy_b2) == size(Fy_b3) ntimes_loading = size(Fx_b1, 2) fig = Figure() ax11 = fig[1, 1] = Axis(fig, xlabel="Span Position (m)", ylabel="Fx (N/m)", title="blade 1") ax21 = fig[2, 1] = Axis(fig, xlabel="Span Position (m)", ylabel="Fy (N/m)") ax12 = fig[1, 2] = Axis(fig, xlabel="Span Position (m)", ylabel="Fx (N/m)", title="blade 2") ax22 = fig[2, 2] = Axis(fig, xlabel="Span Position (m)", ylabel="Fy (N/m)") ax13 = fig[1, 3] = Axis(fig, xlabel="Span Position (m)", ylabel="Fx (N/m)", title="blade 3") ax23 = fig[2, 3] = Axis(fig, xlabel="Span Position (m)", ylabel="Fy (N/m)") bpp = 60/omega_rpm/num_blades colormap = colorschemes[:viridis] for tidx in 1:500:ntimes_loading cidx = (time[tidx] - time[1])/sim_length_s l1 = lines!(ax11, radii, Fx_b1[:,tidx], label ="b1", color=colormap[cidx]) l1 = lines!(ax12, radii, Fx_b2[:,tidx], label ="b2", color=colormap[cidx]) l1 = lines!(ax13, radii, Fx_b3[:,tidx], label ="b3", color=colormap[cidx]) l2 = lines!(ax21, radii, Fy_b1[:,tidx], label ="b1", color=colormap[cidx]) l2 = lines!(ax22, radii, Fy_b2[:,tidx], label ="b2", color=colormap[cidx]) l2 = lines!(ax23, radii, Fy_b3[:,tidx], label ="b3", color=colormap[cidx]) end linkxaxes!(ax21, ax11) linkxaxes!(ax21, ax11) linkxaxes!(ax12, ax11) linkxaxes!(ax22, ax11) linkxaxes!(ax13, ax11) linkxaxes!(ax23, ax11) linkyaxes!(ax12, ax11) linkyaxes!(ax13, ax11) linkyaxes!(ax22, ax21) linkyaxes!(ax23, ax21) hidexdecorations!(ax11, grid=false) hidexdecorations!(ax12, grid=false) hidexdecorations!(ax13, grid=false) hideydecorations!(ax12, grid=false) hideydecorations!(ax13, grid=false) hideydecorations!(ax22, grid=false) hideydecorations!(ax23, grid=false) save(joinpath(@__DIR__, "gen_test_data", "openfast_data", "Fx_t-all_time.png"), fig) # To do F1A correctly, we need to put all source elements in a coordinate system that # moves with the fluid, i.e. one in which the fluid appears stationary. # So, to do that, we have the blades translating in the # negative x direction at the average horizontal wind speed. v = -avg_wind_speed # m/s omega = omega_rpm * 2*pi/60 # rad/s # some reshaping, ses[i, j, k] holds the CompactSourceElement at src_time[i], radii[j], and blade number k ΞΈs = reshape(ΞΈs, 1, 1, :) radii = reshape(radii, 1, :, 1) dradii = reshape(dradii, 1, :, 1) cs_area = reshape(cs_area, 1, :, 1) src_times = reshape(time, :, 1, 1) # This isn't really necessary. fx = cat(transpose(Fx_b1), transpose(Fx_b2), transpose(Fx_b3), dims=3) fc = cat(transpose(Fy_b1), transpose(Fy_b2), transpose(Fy_b3), dims=3) # source elements, with negative Fx ses = CompactSourceElement.(rho, c0, radii, ΞΈs, dradii, cs_area, -fx, 0.0, fc, src_times) t0 = 0.0 # Time at which the angle between the source and target coordinate systems is equal to offest. offset = 0.0 # Angular offset between the source and target coordinate systems at t0. # steady rotation around the x axis rot_trans = SteadyRotXTransformation(t0, omega, offset) # orient the rotation axis of the blades as it is the global frame rot_axis = @SVector [1.0, 0.0, 0.0] # rotation axis aligned along global x-axis blade_axis = @SVector [0.0, 0.0, 1.0] # blade 1 pointing up, along z-axis global_trans = ConstantLinearMap(hcat(rot_axis, blade_axis, rot_axisΓ—blade_axis)) # blade to move with the appropriate forward velocity, and # start from the desired location in the global reference frame y0_hub = @SVector [0.0, 0.0, 0.0] # Position of the hub at time t0 v0_hub = SVector{3}(v.*rot_axis) # Constant velocity of the hub in the global reference frame const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # combine these three transformations into one, and then use that on the SourceElements trans = compose.(src_times, Ref(const_vel_trans), compose.(src_times, Ref(global_trans), Ref(rot_trans))) # trans will perform the three transformations from right to left (rot_trans, global_trans, const_vel_trans) ses = ses .|> trans # The ses object now describes how each blade element source is moving through the global reference # frame over the time src_time. As it does this, it will emit acoustics that can be sensed by an acoustic observer # (a human, or a microphone). The exact "amount" of acoustics the observer will experience depends # on the relative location and motion between each source and the observer. # This creates an acoustic observer moving with constant velocity v0_hub that is at location `x0` at time `t0`. obs = ConstVelocityAcousticObserver(t0, x0, v0_hub) # Now, in order to perform the F1A calculation, # we need to know when each acoustic disturbance emitted # by the source arrives at the observer. This is referred # to an advanced time calculation, and is done this way: apth = f1a.(ses, Ref(obs)) # We now have a noise prediction for each of the individual source elements in ses at the acoustic observer obs. # What we ultimately want is the total noise prediction at obsβ€”we want to add all the acoustic pressures in apth together. # But we can't add them directly, yet, since the observer times are not all the same. What we need to do # is first interpolate the apth of each source onto a common observer time grid, and then add them up. # We'll do this using the AcousticAnalogies.combine function. period = 2*pi/omega bpp = period/num_blades # blade passing period obs_time_range = sim_length_s/60*omega_rpm*bpp # Note that we need to be careful to avoid extrapolation in the `combine` calculation. # That won't happen in this case, since obs_time_range/sim_length_s is 1/3, so the observer time # range is much less than the source time range. # The observer time range is 1/3 of the source time range, and we're using the same number of # simulation times, so that means the observer time step is 1/3 that of the source time step. num_obs_times = length(time) apth_total = combine(apth, obs_time_range, num_obs_times, 1) # The loading data is unsteady, so we may need to be careful to window the time history # to avoid problems with discontinuities going from the begining/end of the pressure time history.. # We can now have a look at the total acoustic pressure time history at the observer: fig = Figure() ax1 = fig[1, 1] = Axis(fig, xlabel="time, s", ylabel="monopole, Pa") ax2 = fig[2, 1] = Axis(fig, xlabel="time, s", ylabel="dipole, Pa") ax3 = fig[3, 1] = Axis(fig, xlabel="time, s", ylabel="total, Pa") l1 = lines!(ax1, time, apth_total.p_m) l2 = lines!(ax2, time, apth_total.p_d) l3 = lines!(ax3, time, apth_total.p_m.+apth_total.p_d) hidexdecorations!(ax1, grid=false) hidexdecorations!(ax2, grid=false) save(joinpath(@__DIR__, "gen_test_data", "openfast_data", "openfast-apth_total.png"), fig) # The plot shows that the monopole/thickness noise is much lower than the dipole/loading noise. # Wind turbine blades are relatively slender, which would tend to reduce thickness noise. # Also the observer is downstream of the rotation plane, which is where loading noise is traditionally # thought to dominate (monopole/thickness noise is more significant in the rotor rotation plane, usually). # We now calculate the overall sound pressure level from the acoustic pressure time history. oaspl_from_apth = AcousticMetrics.OASPL(apth_total) # Next, we calculate the narrowband spectrum. nbs = AcousticMetrics.MSPSpectrumAmplitude(apth_total) # Finally, walculate the overall A-weighted sound pressure level from the narrowband spectrum. oaspl_from_nbs = AcousticMetrics.OASPL(nbs) (oaspl_from_apth, oaspl_from_nbs) # As a last step, we create VTK files that one can visualize in Paraview (or similar software) name = joinpath(@__DIR__, "gen_test_data", "openfast_data", "vtk", "iea3p4_vtk") mkpath(dirname(name)) outfiles = AcousticAnalogies.to_paraview_collection(name, ses) end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
12074
using AcousticAnalogies using AcousticMetrics: AcousticMetrics using DelimitedFiles: readdlm using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, ConstantVelocityTransformation using FileIO: load using FLOWMath: akima using StaticArrays: @SVector using Test data = load(joinpath(@__DIR__, "gen_bpmjl_data", "figure22b.jld2")) rho = data["rho"] asound = data["asound"] mu = data["mu"] Vinf = data["Vinf"] omega = data["omega"] B = data["B"] Rhub = data["Rhub"] Rtip = data["Rtip"] radii = data["radii"] chord = data["chord"] twist = data["twist"] alpha = data["alpha"] U = data["U"] hs = data["hs"] num_src_times_blade_pass = data["num_src_times_blade_pass"] Psis = data["Psis"] nu = mu/rho num_radial = length(radii) dradii = AcousticAnalogies.get_dradii(radii, Rhub, Rtip) # Get the source time, which will be one blade pass worth of time, each blade pass with `num_src_times_blade_pass` steps per blade pass. bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) num_blade_pass = 1 period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # Now let's define the coordinate system. # I'm going to do my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # And the blades will be rotating about the positive x axis at a rate of `omega`. rot_trans = SteadyRotXTransformation(t0, omega, 0.0) # The hub/rotation axis of the blades will start at the origin at time `t0`, and translate in the positive x direction at a speed of `Vinf`. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] # m/s const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Now I can put the two transformations together: trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) # Paper doesn't specify the microphone used for Figure 22, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 22. # For the coordinate system, I'm doing my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane, so this should be good. # But it will of course be moving with the same freestream in the positive x direction. r_obs = 2.27 # meters theta_obs = -35*pi/180 # The observer is moving in the positive x direction at Vinf, at the origin at time t0. t0_obs = 0.0 x0_obs = @SVector [r_obs*sin(theta_obs), r_obs*cos(theta_obs), 0.0] v_obs = @SVector [Vinf, 0.0, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # In the text describing Figure 22, "For these predictions, the trip flag was set to β€œtripped”, due to the rough surface quality of the blade." bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # In the Figure 22 caption, "for these predictions, bluntness thickness H was set to 0.8 mm and trailing edge angle Ξ¨ was set to 16 degrees." h = 0.8e-3 # meters Psi = 16*pi/180 # radians # I don't see any discussion for what type of tip was used for the tip vortex noise. # The flat tip seems to match the PAS+ROTONET+BARC predictions well. blade_tip = AcousticAnalogies.FlatTip() # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) hs_rs = reshape(hs, 1, :, 1) Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) # bls_rs = reshape(bls, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] # bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] chord_rs_with_tip = @view chord_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] hs_rs_with_tip = @view hs_rs[:, end:end, :] Psis_rs_with_tip = @view Psis_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] # bls_rs_with_tip = @view bls_rs[:, end:end, :] positive_x_rotation = true ses_no_tip = CombinedNoTipBroadbandSourceElement.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord_rs_no_tip, twist_rs_no_tip, hs_rs_no_tip, Psis_rs_no_tip, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, Ref(bl), positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord_rs_with_tip, twist_rs_with_tip, hs_rs_with_tip, Psis_rs_with_tip, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, Ref(bl), Ref(blade_tip), positive_x_rotation) .|> trans # It's more convinient to cat all the sources together. ses = cat(ses_no_tip, ses_with_tip; dims=2) # The predictions in Figure 22b appear to be on 1/3 octave, ranging from about 200 Hz to 60,000 Hz. # But let's expand the range of source frequencies to account for Doppler shifting. freqs_src = AcousticMetrics.ExactProportionalBands{3, :center}(10.0, 200000.0) freqs_obs = AcousticMetrics.ExactProportionalBands{3, :center}(200.0, 60000.0) # Now we can do a noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) # This seperates out the noise prediction for each source-observer combination into the different sources. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_lblvss = AcousticAnalogies.pbs_lblvs.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Now, need to combine each broadband noise prediction. # The time axis the axis over which the time varies for each source. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) # Now I need to account for the fact that Figure 22b is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_lblvs = pbs_lblvs .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_lblvs = 10 .* log10.(nb_lblvs./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) # Now I should be able to compare to the BARC data. # Need to read it in first. data_pressure_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-TBL-TE-pressure-2.csv"), ',') freq_pressure_barc = data_pressure_barc[:, 1] spl_pressure_barc = data_pressure_barc[:, 2] data_suction_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-TBL-TE-suction-2.csv"), ',') freq_suction_barc = data_suction_barc[:, 1] spl_suction_barc = data_suction_barc[:, 2] data_separation_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-separation-2.csv"), ',') freq_separation_barc = data_separation_barc[:, 1] spl_separation_barc = data_separation_barc[:, 2] data_lblvs_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-LBLVS.csv"), ',') freq_lblvs_barc = data_lblvs_barc[:, 1] spl_lblvs_barc = data_lblvs_barc[:, 2] data_teb_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-BVS.csv"), ',') freq_teb_barc = data_teb_barc[:, 1] spl_teb_barc = data_teb_barc[:, 2] data_tip_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-tip_vortex_shedding.csv"), ',') freq_tip_barc = data_tip_barc[:, 1] spl_tip_barc = data_tip_barc[:, 2] # Interpolate the AcousticAnalogies.jl data onto the frequencies from the BARC CSV file. spl_pressure_interp = akima(freqs_obs, spl_pressure, freq_pressure_barc) spl_suction_interp = akima(freqs_obs, spl_suction, freq_suction_barc) spl_separation_interp = akima(freqs_obs, spl_alpha, freq_separation_barc) spl_lblvs_interp = akima(freqs_obs, spl_lblvs, freq_lblvs_barc) spl_teb_interp = akima(freqs_obs, spl_teb, freq_teb_barc) spl_tip_interp = akima(freqs_obs, spl_tip, freq_tip_barc) # Now compare. @test maximum(abs.(spl_pressure_interp .- spl_pressure_barc)) < 0.543 # Lower frequencies don't line up as well as higher. # Not sure why. @test abs(spl_suction_interp[1] - spl_suction_barc[1]) < 3.59 @test abs(spl_suction_interp[2] - spl_suction_barc[2]) < 2.71 @test abs(spl_suction_interp[3] - spl_suction_barc[3]) < 1.24 @test maximum(abs.(spl_suction_interp[4:end] .- spl_suction_barc[4:end])) < 0.462 # Lower frequencies don't line up as well as higher. # Not sure why. @test all(abs.(spl_separation_interp[1:12] .- spl_separation_barc[1:12]) .< [8.54, 7.63, 7.48, 6.82, 6.51, 6.60, 5.99, 4.87, 4.21, 2.58, 1.29, 0.299]) @test maximum(abs.(spl_separation_interp[13:end] .- spl_separation_barc[13:end])) < 0.466 @test all(abs.(spl_teb_interp .- spl_teb_barc) .< [0.134, 0.349, 0.424, 0.133, 0.187, 0.603, 0.244, 2.60]) @test all(abs.(spl_tip_interp .- spl_tip_barc) .< [0.0641, 0.0426, 0.170, 0.0923, 0.116, 0.231, 0.228, 0.160, 0.121])
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
14401
using AcousticAnalogies using AcousticMetrics: AcousticMetrics using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, SteadyRotYTransformation, SteadyRotZTransformation, ConstantVelocityTransformation using FileIO: load using FLOWMath: Akima using StaticArrays using Test # tip vortex noise correction data based on "Airfoil Tip Vortex Formation Noise" # Copied from BPM.jl (would like to add BPM.jl as a dependency if it's registered in General some day). const bm_tip_alpha_aspect_data = [2.0,2.67,4.0,6.0,12.0,24.0] const bm_tip_alpha_aratio_data = [0.54,0.62,0.71,0.79,0.89,0.95] const bm_tip_alpha_aspect_ratio_correction = Akima(bm_tip_alpha_aspect_data, bm_tip_alpha_aratio_data) function bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) # compute tip lift curve slope if aspect_ratio < 2.0 aratio = 0.5*one(aspect_ratio) elseif 2.0 <= aspect_ratio <= 24.0 aratio = bm_tip_alpha_aspect_ratio_correction(aspect_ratio) elseif aspect_ratio > 24.0 aratio = 1.0*one(aspect_ratio) end return aratio end struct BMTipAlphaCorrection{TCorrection} <: AbstractTipAlphaCorrection correction::TCorrection function BMTipAlphaCorrection(aspect_ratio) # correction = BPM._tip_vortex_alpha_correction_nonsmooth(aspect_ratio) correction = bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) return new{typeof(correction)}(correction) end end function AcousticAnalogies.tip_vortex_alpha_correction(blade_tip::AbstractBladeTip{<:BMTipAlphaCorrection}, alphatip) a0l = AcousticAnalogies.alpha_zerolift(blade_tip) correction_factor = AcousticAnalogies.tip_alpha_correction(blade_tip).correction return correction_factor * (alphatip - a0l) + a0l end data = load(joinpath(@__DIR__, "gen_bpmjl_data", "figure22b.jld2")) rho = data["rho"] asound = data["asound"] mu = data["mu"] Vinf = data["Vinf"] omega = data["omega"] B = data["B"] Rhub = data["Rhub"] Rtip = data["Rtip"] radii = data["radii"] chord = data["chord"] twist = data["twist"] alpha = data["alpha"] U = data["U"] hs = data["hs"] Psis = data["Psis"] num_src_times_blade_pass = data["num_src_times_blade_pass"] tripped_flags = data["tripped_flags"] num_radial = length(radii) nu = mu/rho dradii = AcousticAnalogies.get_dradii(radii, Rhub, Rtip) # Get some transform stuff. bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) num_blade_pass = 1 period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # I don't see any discussion for what type of tip was used for the tip vortex noise. # FlatTip with no CCBlade.jl tip correction or BPM-style tip correction seems to match the BARC predictions well. # blade_tip = AcousticAnalogies.FlatTip(AcousticAnalogies.NoTipAlphaCorrection()) # BPM.jl uses a different tip alpha correction which appears to require the blade aspect ratio, defined as the blade radius divided by the average chord. cbar = sum(chord .* dradii) / (Rtip - Rhub) aspect_ratio = Rtip/cbar alpha0lift = 0.0 blade_tip = AcousticAnalogies.FlatTip(BMTipAlphaCorrection(aspect_ratio), alpha0lift) # Getting the coordinate system consistent with BPM.jl is a bit tricky. # Here's a bit of code from BPM.jl: # # # Calculate the trailing edge position relative to the hub # xs = sin(beta)*d - cos(beta)*(c - c1) # zs = cos(beta)*d + sin(beta)*(c - c1) # # OK, so that shows me that the blade is initially aligned with the z axis, rotating to the positive x direction. # And I know the blades are rotating about the positive y axis. # So that's the answer for the BPM.jl coordinate system: # # * freestream in the positive y axis direction. # * first blade initially aligned with the positive z axis, rotating about the positive y axis. # # Now, what do I need to do with AcousticAnalogies to make that happen? # I want the blades to be translating in the negative y direction, rotating about the positive y axis. # I usually start with the blades rotating about either the positive or negative x axis, moving in the direction of the positive x axis. # I think the answer is, # # * start out with the blades rotating about the negative x axis, moving in the direction of the positive x axis # * rotate 90Β° about the negative z axis. # After this, the blades will be moving in the negative y direction, rotating about the positive y axis, which is good. # But I want the first blade to be aligned with the positive z axis, and stopping here would mean it's aligned with the positive x axis. # * rotate 90Β° about the negative y axis. # This will put the first blade in line with the positive z axis. # So, let's do what we said we need to do. # Start with a rotation about the negative x axis. positive_x_rotation = false rot_trans = SteadyRotXTransformation(t0, omega*ifelse(positive_x_rotation, 1, -1), 0) # Then translate along the positive x axis. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Then a 90Β° rotation about the negative z axis. trans_z90deg = SteadyRotZTransformation(0.0, 0.0, -0.5*pi) # Then a 90Β° rotation about the negative y axis. trans_y90deg = SteadyRotYTransformation(0.0, 0.0, -0.5*pi) # Put them all together: trans = compose.(src_times, Ref(trans_y90deg), compose.(src_times, Ref(trans_z90deg), compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)))) # Use the M_c = 0.8*M that BPM.jl and the BPM report use. U = @. 0.8*sqrt(Vinf^2 + (omega*radii)^2) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) .* ifelse(positive_x_rotation, 1, -1) bls = [ifelse(tf, AcousticAnalogies.TrippedN0012BoundaryLayer(), AcousticAnalogies.UntrippedN0012BoundaryLayer()) for tf in tripped_flags] # Need to do the LBLVS with the untripped boundary layer to match what BPM.jl is doing. # bls_lblvs = fill(AcousticAnalogies.UntrippedN0012BoundaryLayer(), num_radial) bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() r_obs = 2.27 # meters theta_obs = -35*pi/180 # So, the docstring for BPM.jl says that `V` argument is the wind velocity in the y direction. # So I guess we should assume that the blades are rotating about the y axis. # And if the freestream velocity is in the positive y axis, then, from the perspective of the fluid, the blades are translating in the negative y direction. # And I want the observer to be downstream/behind the blades, so that would mean they would have a positive y position. # So I want to rotate the observer around the positive x axis, so I'm going to switch the sign on `theta_obs`. t0_obs = 0.0 x0_obs = [0.0, r_obs*sin(-theta_obs), r_obs*cos(-theta_obs)] # The observer is moving in the same direction as the blades, which is the negative y axis. v_obs = @SVector [0.0, -Vinf, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) hs_rs = reshape(hs, 1, :, 1) Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # bls_untripped_rs = reshape(bls_lblvs, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] chord_rs_with_tip = @view chord_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] hs_rs_with_tip = @view hs_rs[:, end:end, :] Psis_rs_with_tip = @view Psis_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] direct = AcousticAnalogies.BPMDirectivity use_UInduction = false use_Doppler = false mach_correction = AcousticAnalogies.NoMachCorrection ses_no_tip = CombinedNoTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord_rs_no_tip, twist_rs_no_tip, hs_rs_no_tip, Psis_rs_no_tip, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord_rs_with_tip, twist_rs_with_tip, hs_rs_with_tip, Psis_rs_with_tip, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # Need to do the LBLVS with the untripped boundary layer to match what BPM.jl is doing. lblvs_ses_untripped = AcousticAnalogies.LBLVSSourceElement{direct,use_UInduction,use_Doppler}.(asound, nu, radii_rs, ΞΈs_rs, dradii_rs, chord_rs, twist_rs, Us_rs, alphas_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # # Write out the source elements. # pvd_no_tip = AcousticAnalogies.to_paraview_collection(joinpath(@__DIR__, "figure22b-no_tip"), ses_no_tip) # pvd_with_tip = AcousticAnalogies.to_paraview_collection(joinpath(@__DIR__, "figure22b-with_tip"), ses_with_tip) # pvd_all = AcousticAnalogies.to_paraview_collection(joinpath(@__DIR__, "figure22b-all"), (ses_no_tip, ses_with_tip); observers=(obs,)) # Put the source elements together: ses = cat(ses_no_tip, ses_with_tip; dims=2) # Define the frequencies we'd like to evaluate. # BPM.jl uses the approximate 1/3rd-octave bands. freqs_obs = AcousticMetrics.ApproximateThirdOctaveCenterBands(100.0, 40000.0) freqs_src = freqs_obs # Now do the noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss_untripped = AcousticAnalogies.noise.(lblvs_ses_untripped, Ref(obs), Ref(freqs_src)) # Separate out each source. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Combine each noise prediction. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs_untripped = AcousticMetrics.combine(pbs_lblvss_untripped, freqs_obs, time_axis) # Now I need to account for the fact that Figure 22b is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # (Dividing the MSP by Ξ”f_pbs aka the 1/3 octave spacing is like getting a power-spectral density, then multiplying by the narrowband spacing Ξ”f_nb gives us the MSP associated with the narrowband.) # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs nb_lblvs_untripped = pbs_lblvs_untripped .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) spl_lblvs_untripped = 10 .* log10.(nb_lblvs_untripped./(pref^2)) # Read in the BPM.jl data. freq_bpmjl = data["freqs"] spl_pressure_bpmjl = data["spl_nb_pressure"] spl_suction_bpmjl = data["spl_nb_suction"] spl_separation_bpmjl = data["spl_nb_separation"] spl_lblvs_bpmjl = data["spl_nb_lblvs"] spl_blunt_bpmjl = data["spl_nb_blunt"] spl_tip_bpmjl = data["spl_nb_tip"] # The frequencies in the CSV file should match the observer frequencies we're using. @test all(freqs_obs .β‰ˆ freq_bpmjl) # Only look at the SPLs that are actually significant, i.e. greater than 10 dB. @test maximum(abs.(spl_pressure[spl_pressure_bpmjl .> 10] .- spl_pressure_bpmjl[spl_pressure_bpmjl .> 10])) < 0.77 @test maximum(abs.(spl_suction[spl_suction_bpmjl .> 10] .- spl_suction_bpmjl[spl_suction_bpmjl .> 10])) < 0.78 @test maximum(abs.(spl_alpha[spl_separation_bpmjl .> 10] .- spl_separation_bpmjl[spl_separation_bpmjl .> 10])) < 0.78 @test maximum(abs.(spl_lblvs_untripped[spl_lblvs_bpmjl .> 10] .- spl_lblvs_bpmjl[spl_lblvs_bpmjl .> 10])) < 0.81 @test maximum(abs.(spl_teb[spl_blunt_bpmjl .> 10] .- spl_blunt_bpmjl[spl_blunt_bpmjl .> 10])) < 0.81 @test maximum(abs.(spl_tip[spl_tip_bpmjl .> 10] .- spl_tip_bpmjl[spl_tip_bpmjl .> 10])) < 1.25
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
13844
using AcousticAnalogies using AcousticMetrics: AcousticMetrics using DelimitedFiles: readdlm using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, ConstantVelocityTransformation using FileIO: load using FLOWMath: akima using StaticArrays: @SVector using Test data = load(joinpath(@__DIR__, "gen_bpmjl_data", "figure23c.jld2")) rho = data["rho"] asound = data["asound"] mu = data["mu"] Vinf = data["Vinf"] omega = data["omega"] B = data["B"] Rhub = data["Rhub"] Rtip = data["Rtip"] radii = data["radii"] chord = data["chord"] twist = data["twist"] alpha = data["alpha"] U = data["U"] hs = data["hs"] num_src_times_blade_pass = data["num_src_times_blade_pass"] Psis = data["Psis"] nu = mu/rho num_radial = length(radii) dradii = AcousticAnalogies.get_dradii(radii, Rhub, Rtip) # Get the source time, which will be one blade pass worth of time, each blade pass with `num_src_times_blade_pass` steps per blade pass. bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) num_blade_pass = 1 period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # Now let's define the coordinate system. # I'm going to do my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # And the blades will be rotating about the positive x axis at a rate of `omega`. rot_trans = SteadyRotXTransformation(t0, omega, 0.0) # The hub/rotation axis of the blades will start at the origin at time `t0`, and translate in the positive x direction at a speed of `Vinf`. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] # m/s const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Now I can put the two transformations together: trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) # Paper doesn't specify the microphone used for Figure 23, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 23. # For the coordinate system, I'm doing my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane, so this should be good. # But it will of course be moving with the same freestream in the positive x direction. r_obs = 2.27 # meters theta_obs = -35*pi/180 # The observer is moving in the positive x direction at Vinf, at the origin at time t0. t0_obs = 0.0 x0_obs = @SVector [r_obs*sin(theta_obs), r_obs*cos(theta_obs), 0.0] v_obs = @SVector [Vinf, 0.0, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # So, for the boundary layer, we want to use untripped for the 95% of the blade from the hub to almost tip, and then tripped for the last 5% of the blade at the tip. num_untripped = Int(round(0.95*num_radial)) num_tripped = num_radial - num_untripped bls_untripped = fill(AcousticAnalogies.UntrippedN0012BoundaryLayer(), num_untripped) bls_tripped = fill(AcousticAnalogies.TrippedN0012BoundaryLayer(), num_tripped) bls = vcat(bls_untripped, bls_tripped) # Now, the other trick: need to only include LBLVS noise for elements where the Reynolds number is < 160000. # So, we need the Reynolds number for each section. Re_c = @. U * chord / nu # So now we want to extract the radial stations that meet that < 160000 condition. low_Re_c = 160000 mask_low_Re_c = Re_c .< low_Re_c # And we're also going to use the untripped boundary layer for the LBLVS source. bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() # In the Figure 23 caption, "for these predictions, bluntness thickness H was set to 0.5 mm and trailing edge angle Ξ¨ was set to 14 degrees." h = 0.5e-3 # meters Psi = 14*pi/180 # radians # I don't see any discussion for what type of tip was used for the tip vortex noise. # The flat tip seems to match the PAS+ROTONET+BARC predictions well. blade_tip = AcousticAnalogies.FlatTip() # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) hs_rs = reshape(hs, 1, :, 1) Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] chord_rs_with_tip = @view chord_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] hs_rs_with_tip = @view hs_rs[:, end:end, :] Psis_rs_with_tip = @view Psis_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] positive_x_rotation = true ses_no_tip = CombinedNoTipBroadbandSourceElement.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord_rs_no_tip, twist_rs_no_tip, hs_rs_no_tip, Psis_rs_no_tip, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord_rs_with_tip, twist_rs_with_tip, hs_rs_with_tip, Psis_rs_with_tip, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # It's more convinient to cat all the sources together. ses = cat(ses_no_tip, ses_with_tip; dims=2) # Need to do the LBLVS stuff separately. # Grab the parts of the inputs that correspond to the low Reynolds number stations. radii_lblvs = @view radii[mask_low_Re_c] dradii_lblvs = @view dradii[mask_low_Re_c] chord_lblvs = @view chord[mask_low_Re_c] twist_lblvs = @view twist[mask_low_Re_c] hs_lblvs = @view hs[mask_low_Re_c] Psis_lblvs = @view Psis[mask_low_Re_c] Us_lblvs = @view U[mask_low_Re_c] alphas_lblvs = @view alpha[mask_low_Re_c] # And do the reshaping. radii_lblvs_rs = reshape(radii_lblvs, 1, :, 1) dradii_lblvs_rs = reshape(dradii_lblvs, 1, :, 1) chord_lblvs_rs = reshape(chord_lblvs, 1, :, 1) twist_lblvs_rs = reshape(twist_lblvs, 1, :, 1) hs_lblvs_rs = reshape(hs_lblvs, 1, :, 1) Psis_lblvs_rs = reshape(Psis_lblvs, 1, :, 1) Us_lblvs_rs = reshape(Us_lblvs, 1, :, 1) alphas_lblvs_rs = reshape(alphas_lblvs, 1, :, 1) # Now we can create the source elements. ses_lblvs = LBLVSSourceElement.(asound, nu, radii_lblvs_rs, ΞΈs_rs, dradii_lblvs_rs, chord_lblvs_rs, twist_lblvs_rs, Us_lblvs_rs, alphas_lblvs_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # The predictions in Figure 23c appear to be on 1/3 octave, ranging from about 200 Hz to 60,000 Hz. # But let's expand the range of source frequencies to account for Doppler shifting. freqs_src = AcousticMetrics.ExactProportionalBands{3, :center}(10.0, 200000.0) freqs_obs = AcousticMetrics.ExactProportionalBands{3, :center}(200.0, 60000.0) # Now we can do a noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(ses_lblvs, Ref(obs), Ref(freqs_src)) # This seperates out the noise prediction for each source-observer combination into the different sources. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Now, need to combine each broadband noise prediction. # The time axis the axis over which the time varies for each source. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) # Now I need to account for the fact that Figure 23c is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_lblvs = pbs_lblvs .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_lblvs = 10 .* log10.(nb_lblvs./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) # Now I should be able to compare to the BARC data. # Need to read it in first. data_pressure_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-TBL-TE-pressure.csv"), ',') freq_pressure_barc = data_pressure_barc[:, 1] spl_pressure_barc = data_pressure_barc[:, 2] data_suction_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-TBL-TE-suction.csv"), ',') freq_suction_barc = data_suction_barc[:, 1] spl_suction_barc = data_suction_barc[:, 2] data_separation_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-separation.csv"), ',') freq_separation_barc = data_separation_barc[:, 1] spl_separation_barc = data_separation_barc[:, 2] data_lblvs_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-LBLVS.csv"), ',') freq_lblvs_barc = data_lblvs_barc[:, 1] spl_lblvs_barc = data_lblvs_barc[:, 2] data_teb_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-BVS.csv"), ',') freq_teb_barc = data_teb_barc[:, 1] spl_teb_barc = data_teb_barc[:, 2] data_tip_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-tip_vortex_shedding.csv"), ',') freq_tip_barc = data_tip_barc[:, 1] spl_tip_barc = data_tip_barc[:, 2] # Interpolate the AcousticAnalogies.jl data onto the frequencies from the BARC CSV file. spl_pressure_interp = akima(freqs_obs, spl_pressure, freq_pressure_barc) spl_suction_interp = akima(freqs_obs, spl_suction, freq_suction_barc) spl_separation_interp = akima(freqs_obs, spl_alpha, freq_separation_barc) spl_lblvs_interp = akima(freqs_obs, spl_lblvs, freq_lblvs_barc) spl_teb_interp = akima(freqs_obs, spl_teb, freq_teb_barc) spl_tip_interp = akima(freqs_obs, spl_tip, freq_tip_barc) # Now compare. @test all(abs.(spl_pressure_interp .- spl_pressure_barc) .< [1.918, 1.880, 1.484, 1.65, 1.496, 1.170, 1.043, 0.729, 0.406, 0.406, 1.49, 1.142, 1.131]) @test all(abs.(spl_suction_interp .- spl_suction_barc) .< [2.193, 2.066, 1.984, 1.961, 1.686, 1.423, 1.255, 1.060, 0.339, 0.101, 0.149, 0.749, 1.363, 1.220, 1.547, 1.979]) @test all(abs.(spl_separation_interp .- spl_separation_barc) .< [17.002, 14.84, 12.09, 10.20, 9.42, 8.371, 7.763, 7.504, 7.099, 6.124, 5.307, 2.843, 2.326, 2.560, 2.583, 2.088, 1.448, 0.628, 0.112, 0.873, 1.971]) @test all(abs.(spl_lblvs_interp .- spl_lblvs_barc) .< [3.369, 3.795, 3.758, 3.797, 3.765, 3.749, 3.545, 3.927, 3.922, 3.652, 3.571]) @test all(abs.(spl_teb_interp .- spl_teb_barc) .< [0.274, 0.135, 0.211, 0.127, 0.0584, 2.200, 2.981]) @test all(abs.(spl_tip_interp .- spl_tip_barc) .< [0.590, 0.659, 0.625, 0.460, 0.240, 0.467, 0.434, 0.0235, 0.0468])
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
15166
using AcousticAnalogies using AcousticMetrics: AcousticMetrics using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, SteadyRotYTransformation, SteadyRotZTransformation, ConstantVelocityTransformation using FileIO: load using FLOWMath: Akima using StaticArrays: @SVector using Test # tip vortex noise correction data based on "Airfoil Tip Vortex Formation Noise" # Copied from BPM.jl (would like to add BPM.jl as a dependency if it's registered in General some day). const bm_tip_alpha_aspect_data = [2.0,2.67,4.0,6.0,12.0,24.0] const bm_tip_alpha_aratio_data = [0.54,0.62,0.71,0.79,0.89,0.95] const bm_tip_alpha_aspect_ratio_correction = Akima(bm_tip_alpha_aspect_data, bm_tip_alpha_aratio_data) function bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) # compute tip lift curve slope if aspect_ratio < 2.0 aratio = 0.5*one(aspect_ratio) elseif 2.0 <= aspect_ratio <= 24.0 aratio = bm_tip_alpha_aspect_ratio_correction(aspect_ratio) elseif aspect_ratio > 24.0 aratio = 1.0*one(aspect_ratio) end return aratio end struct BMTipAlphaCorrection{TCorrection} <: AbstractTipAlphaCorrection correction::TCorrection function BMTipAlphaCorrection(aspect_ratio) # correction = BPM._tip_vortex_alpha_correction_nonsmooth(aspect_ratio) correction = bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) return new{typeof(correction)}(correction) end end function AcousticAnalogies.tip_vortex_alpha_correction(blade_tip::AbstractBladeTip{<:BMTipAlphaCorrection}, alphatip) a0l = AcousticAnalogies.alpha_zerolift(blade_tip) correction_factor = AcousticAnalogies.tip_alpha_correction(blade_tip).correction return correction_factor * (alphatip - a0l) + a0l end data = load(joinpath(@__DIR__, "gen_bpmjl_data", "figure23c.jld2")) rho = data["rho"] asound = data["asound"] mu = data["mu"] Vinf = data["Vinf"] omega = data["omega"] B = data["B"] Rhub = data["Rhub"] Rtip = data["Rtip"] radii = data["radii"] chord = data["chord"] twist = data["twist"] alpha = data["alpha"] U = data["U"] hs = data["hs"] Psis = data["Psis"] num_src_times_blade_pass = data["num_src_times_blade_pass"] tripped_flags = data["tripped_flags"] lblvs_flags = data["lblvs_flags"] num_radial = length(radii) nu = mu/rho dradii = AcousticAnalogies.get_dradii(radii, Rhub, Rtip) # Get some transform stuff. bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) num_blade_pass = 1 period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # I don't see any discussion for what type of tip was used for the tip vortex noise. # FlatTip with no CCBlade.jl tip correction or BPM-style tip correction seems to match the BARC predictions well. # blade_tip = AcousticAnalogies.FlatTip(AcousticAnalogies.NoTipAlphaCorrection()) # BPM.jl uses a different tip alpha correction which appears to require the blade aspect ratio, defined as the blade radius divided by the average chord. cbar = sum(chord .* dradii) / (Rtip - Rhub) aspect_ratio = Rtip/cbar alpha0lift = 0.0 blade_tip = AcousticAnalogies.FlatTip(BMTipAlphaCorrection(aspect_ratio), alpha0lift) # Getting the coordinate system consistent with BPM.jl is a bit tricky. # Here's a bit of code from BPM.jl: # # # Calculate the trailing edge position relative to the hub # xs = sin(beta)*d - cos(beta)*(c - c1) # zs = cos(beta)*d + sin(beta)*(c - c1) # # OK, so that shows me that the blade is initially aligned with the z axis, rotating to the positive x direction. # And I know the blades are rotating about the positive y axis. # So that's the answer for the BPM.jl coordinate system: # # * freestream in the positive y axis direction. # * first blade initially aligned with the positive z axis, rotating about the positive y axis. # # Now, what do I need to do with AcousticAnalogies to make that happen? # I want the blades to be translating in the negative y direction, rotating about the positive y axis. # I usually start with the blades rotating about either the positive or negative x axis, moving in the direction of the positive x axis. # I think the answer is, # # * start out with the blades rotating about the negative x axis, moving in the direction of the positive x axis # * rotate 90Β° about the negative z axis. # After this, the blades will be moving in the negative y direction, rotating about the positive y axis, which is good. # But I want the first blade to be aligned with the positive z axis, and stopping here would mean it's aligned with the positive x axis. # * rotate 90Β° about the negative y axis. # This will put the first blade in line with the positive z axis. # So, let's do what we said we need to do. # Start with a rotation about the negative x axis. positive_x_rotation = false rot_trans = SteadyRotXTransformation(t0, omega*ifelse(positive_x_rotation, 1, -1), 0) # Then translate along the positive x axis. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Then a 90Β° rotation about the negative z axis. trans_z90deg = SteadyRotZTransformation(0.0, 0.0, -0.5*pi) # Then a 90Β° rotation about the negative y axis. trans_y90deg = SteadyRotYTransformation(0.0, 0.0, -0.5*pi) # Put them all together: trans = compose.(src_times, Ref(trans_y90deg), compose.(src_times, Ref(trans_z90deg), compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)))) # Use the M_c = 0.8*M that BPM.jl and the BPM report use. U = @. 0.8*sqrt(Vinf^2 + (omega*radii)^2) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) .* ifelse(positive_x_rotation, 1, -1) bls = [ifelse(tf, AcousticAnalogies.TrippedN0012BoundaryLayer(), AcousticAnalogies.UntrippedN0012BoundaryLayer()) for tf in tripped_flags] # Need to do the LBLVS with the untripped boundary layer to match what BPM.jl is doing. # bls_lblvs = fill(AcousticAnalogies.UntrippedN0012BoundaryLayer(), num_radial) bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() r_obs = 2.27 # meters theta_obs = -35*pi/180 # So, the docstring for BPM.jl says that `V` argument is the wind velocity in the y direction. # So I guess we should assume that the blades are rotating about the y axis. # And if the freestream velocity is in the positive y axis, then, from the perspective of the fluid, the blades are translating in the negative y direction. # And I want the observer to be downstream/behind the blades, so that would mean they would have a positive y position. # So I want to rotate the observer around the positive x axis, so I'm going to switch the sign on `theta_obs`. t0_obs = 0.0 x0_obs = [0.0, r_obs*sin(-theta_obs), r_obs*cos(-theta_obs)] # The observer is moving in the same direction as the blades, which is the negative y axis. v_obs = @SVector [0.0, -Vinf, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) hs_rs = reshape(hs, 1, :, 1) Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # bls_untripped_rs = reshape(bls_lblvs, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] chord_rs_with_tip = @view chord_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] hs_rs_with_tip = @view hs_rs[:, end:end, :] Psis_rs_with_tip = @view Psis_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] direct = AcousticAnalogies.BPMDirectivity use_UInduction = false use_Doppler = false mach_correction = AcousticAnalogies.NoMachCorrection ses_no_tip = CombinedNoTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord_rs_no_tip, twist_rs_no_tip, hs_rs_no_tip, Psis_rs_no_tip, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord_rs_with_tip, twist_rs_with_tip, hs_rs_with_tip, Psis_rs_with_tip, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # Need to do the LBLVS with the untripped boundary layer to match what BPM.jl is doing, and only where `lblvs_flags` is true. # So extract the radial locations where that's true. radii_lblvs = @view radii[lblvs_flags] dradii_lblvs = @view dradii[lblvs_flags] chord_lblvs = @view chord[lblvs_flags] twist_lblvs = @view twist[lblvs_flags] Us_lblvs = @view U[lblvs_flags] alphas_lblvs = @view alpha[lblvs_flags] # bls_lblvs = @view bls_lblvs[lblvs_flags] # Now do the usual reshaping. radii_lblvs_rs = reshape(radii_lblvs, 1, :, 1) dradii_lblvs_rs = reshape(dradii_lblvs, 1, :, 1) chord_lblvs_rs = reshape(chord_lblvs, 1, :, 1) twist_lblvs_rs = reshape(twist_lblvs, 1, :, 1) Us_lblvs_rs = reshape(Us_lblvs, 1, :, 1) alphas_lblvs_rs = reshape(alphas_lblvs, 1, :, 1) # bls_lblvs_rs = reshape(bls_lblvs, 1, :, 1) # Now we can construct the lblvs source elements. lblvs_ses = AcousticAnalogies.LBLVSSourceElement{direct,use_UInduction,use_Doppler}.(asound, nu, radii_lblvs_rs, ΞΈs_rs, dradii_lblvs_rs, chord_lblvs_rs, twist_lblvs_rs, Us_lblvs_rs, alphas_lblvs_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # Write out the source elements. # pvd_no_tip = AcousticAnalogies.to_paraview_collection(joinpath(@__DIR__, "figure23c-no_tip"), ses_no_tip) # pvd_with_tip = AcousticAnalogies.to_paraview_collection(joinpath(@__DIR__, "figure23c-with_tip"), ses_with_tip) # pvd_all = AcousticAnalogies.to_paraview_collection(joinpath(@__DIR__, "figure23c-all"), (ses_no_tip, ses_with_tip, lblvs_ses); observers=(obs,)) # Put the source elements together: ses = cat(ses_no_tip, ses_with_tip; dims=2) # Define the frequencies we'd like to evaluate. # BPM.jl uses the approximate 1/3rd-octave bands. freqs_obs = AcousticMetrics.ApproximateThirdOctaveCenterBands(100.0, 40000.0) freqs_src = freqs_obs # Now do the noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(lblvs_ses, Ref(obs), Ref(freqs_src)) # Separate out each source. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Combine each noise prediction. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) # Now I need to account for the fact that Figure 23c is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # (Dividing the MSP by Ξ”f_pbs aka the 1/3 octave spacing is like getting a power-spectral density, then multiplying by the narrowband spacing Ξ”f_nb gives us the MSP associated with the narrowband.) # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs nb_lblvs = pbs_lblvs .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) spl_lblvs = 10 .* log10.(nb_lblvs./(pref^2)) # Read in the BPM.jl data. freq_bpmjl = data["freqs"] spl_pressure_bpmjl = data["spl_nb_pressure"] spl_suction_bpmjl = data["spl_nb_suction"] spl_separation_bpmjl = data["spl_nb_separation"] spl_lblvs_bpmjl = data["spl_nb_lblvs"] spl_blunt_bpmjl = data["spl_nb_blunt"] spl_tip_bpmjl = data["spl_nb_tip"] # The frequencies in the CSV file should match the observer frequencies we're using. @test all(freqs_obs .β‰ˆ freq_bpmjl) # Only look at the SPLs that are actually significant, i.e. greater than 10 dB. @test maximum(abs.(spl_pressure[spl_pressure_bpmjl .> 10] .- spl_pressure_bpmjl[spl_pressure_bpmjl .> 10])) < 0.826 @test maximum(abs.(spl_suction[spl_suction_bpmjl .> 10] .- spl_suction_bpmjl[spl_suction_bpmjl .> 10])) < 0.774 @test maximum(abs.(spl_alpha[spl_separation_bpmjl .> 10] .- spl_separation_bpmjl[spl_separation_bpmjl .> 10])) < 0.771 @test maximum(abs.(spl_teb[spl_blunt_bpmjl .> 10] .- spl_blunt_bpmjl[spl_blunt_bpmjl .> 10])) < 0.792 @test maximum(abs.(spl_tip[spl_tip_bpmjl .> 10] .- spl_tip_bpmjl[spl_tip_bpmjl .> 10])) < 1.26 @test maximum(abs.(spl_lblvs[spl_lblvs_bpmjl .> 10] .- spl_lblvs_bpmjl[spl_lblvs_bpmjl .> 10])) < 0.811
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
12706
using AcousticAnalogies using AcousticMetrics: AcousticMetrics using DelimitedFiles: readdlm using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, ConstantVelocityTransformation using FileIO: load using FLOWMath: akima using StaticArrays: @SVector using Test data = load(joinpath(@__DIR__, "gen_bpmjl_data", "figure24b.jld2")) rho = data["rho"] asound = data["asound"] mu = data["mu"] Vinf = data["Vinf"] omega = data["omega"] B = data["B"] Rhub = data["Rhub"] Rtip = data["Rtip"] radii = data["radii"] chord = data["chord"] twist = data["twist"] alpha = data["alpha"] U = data["U"] hs = data["hs"] num_src_times_blade_pass = data["num_src_times_blade_pass"] Psis = data["Psis"] nu = mu/rho num_radial = length(radii) dradii = AcousticAnalogies.get_dradii(radii, Rhub, Rtip) # Get the source time, which will be one blade pass worth of time, each blade pass with `num_src_times_blade_pass` steps per blade pass. bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) num_blade_pass = 1 period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # Now let's define the coordinate system. # I'm going to do my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # And the blades will be rotating about the positive x axis at a rate of `omega`. rot_trans = SteadyRotXTransformation(t0, omega, 0.0) # The hub/rotation axis of the blades will start at the origin at time `t0`, and translate in the positive x direction at a speed of `Vinf`. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] # m/s const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Now I can put the two transformations together: trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) # Paper doesn't specify the microphone used for Figure 24, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 23. # For the coordinate system, I'm doing my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane, so this should be good. # But it will of course be moving with the same freestream in the positive x direction. r_obs = 2.27 # meters theta_obs = -35*pi/180 # The observer is moving in the positive x direction at Vinf, at the origin at time t0. t0_obs = 0.0 x0_obs = @SVector [r_obs*sin(theta_obs), r_obs*cos(theta_obs), 0.0] v_obs = @SVector [Vinf, 0.0, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # So, for the boundary layer, we want to use untripped for the 95% of the blade from the hub to almost tip, and then tripped for the last 5% of the blade at the tip. num_untripped = Int(round(0.95*num_radial)) num_tripped = num_radial - num_untripped bls_untripped = fill(AcousticAnalogies.UntrippedN0012BoundaryLayer(), num_untripped) bls_tripped = fill(AcousticAnalogies.TrippedN0012BoundaryLayer(), num_tripped) bls = vcat(bls_untripped, bls_tripped) # And we're also going to use the untripped boundary layer for the LBLVS source. bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() # In the Figure 24 caption, "for these predictions, bluntness thickness H was set to 0.5 mm and trailing edge angle Ξ¨ was set to 14 degrees." h = 0.5e-3 # meters Psi = 14*pi/180 # radians # I don't see any discussion for what type of tip was used for the tip vortex noise. # The flat tip seems to match the PAS+ROTONET+BARC predictions well. blade_tip = AcousticAnalogies.FlatTip() # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) hs_rs = reshape(hs, 1, :, 1) Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] chord_rs_with_tip = @view chord_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] hs_rs_with_tip = @view hs_rs[:, end:end, :] Psis_rs_with_tip = @view Psis_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] positive_x_rotation = true ses_no_tip = CombinedNoTipBroadbandSourceElement.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord_rs_no_tip, twist_rs_no_tip, hs_rs_no_tip, Psis_rs_no_tip, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord_rs_with_tip, twist_rs_with_tip, hs_rs_with_tip, Psis_rs_with_tip, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # It's more convinient to cat all the sources together. ses = cat(ses_no_tip, ses_with_tip; dims=2) # The LBLVS uses a different boundary layer, and all radial stations. ses_lblvs = LBLVSSourceElement.(asound, nu, radii_rs, ΞΈs_rs, dradii_rs, chord_rs, twist_rs, Us_rs, alphas_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # The predictions in Figure 24b appear to be on 1/3 octave, ranging from about 200 Hz to 60,000 Hz. # But let's expand the range of source frequencies to account for Doppler shifting. freqs_src = AcousticMetrics.ExactProportionalBands{3, :center}(10.0, 200000.0) freqs_obs = AcousticMetrics.ExactProportionalBands{3, :center}(200.0, 60000.0) # Now we can do a noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(ses_lblvs, Ref(obs), Ref(freqs_src)) # This seperates out the noise prediction for each source-observer combination into the different sources. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Now, need to combine each broadband noise prediction. # The time axis the axis over which the time varies for each source. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) # Now I need to account for the fact that Figure 24b is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_lblvs = pbs_lblvs .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_lblvs = 10 .* log10.(nb_lblvs./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) # Now I should be able to compare to the BARC data. # Need to read it in first. data_pressure_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-TBL-TE-pressure.csv"), ',') freq_pressure_barc = data_pressure_barc[:, 1] spl_pressure_barc = data_pressure_barc[:, 2] data_suction_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-TBL-TE-suction.csv"), ',') freq_suction_barc = data_suction_barc[:, 1] spl_suction_barc = data_suction_barc[:, 2] data_separation_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-separation.csv"), ',') freq_separation_barc = data_separation_barc[:, 1] spl_separation_barc = data_separation_barc[:, 2] data_lblvs_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-LBLVS.csv"), ',') freq_lblvs_barc = data_lblvs_barc[:, 1] spl_lblvs_barc = data_lblvs_barc[:, 2] data_teb_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-BVS.csv"), ',') freq_teb_barc = data_teb_barc[:, 1] spl_teb_barc = data_teb_barc[:, 2] data_tip_barc = readdlm(joinpath(@__DIR__, "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-tip_vortex_shedding.csv"), ',') freq_tip_barc = data_tip_barc[:, 1] spl_tip_barc = data_tip_barc[:, 2] # Interpolate the AcousticAnalogies.jl data onto the frequencies from the BARC CSV file. spl_pressure_interp = akima(freqs_obs, spl_pressure, freq_pressure_barc) spl_suction_interp = akima(freqs_obs, spl_suction, freq_suction_barc) spl_separation_interp = akima(freqs_obs, spl_alpha, freq_separation_barc) spl_lblvs_interp = akima(freqs_obs, spl_lblvs, freq_lblvs_barc) spl_teb_interp = akima(freqs_obs, spl_teb, freq_teb_barc) spl_tip_interp = akima(freqs_obs, spl_tip, freq_tip_barc) # Now compare. @test all(abs.(spl_pressure_interp .- spl_pressure_barc) .< [2.839, 2.365, 1.971, 1.892, 1.368, 0.801, 0.567, 0.145, 0.571, 0.746, 0.925, 0.760]) @test all(abs.(spl_suction_interp .- spl_suction_barc) .< [0.291, 0.527, 0.447, 0.854, 0.818, 0.503, 0.247, 0.229, 0.105, 0.469, 0.563, 0.702, 0.947, 1.224]) @test all(abs.(spl_separation_interp .- spl_separation_barc) .< [12.876, 10.398, 8.513, 7.067, 6.679, 5.426, 4.791, 4.325, 3.330, 1.307, 1.565, 1.437, 0.881, 0.384, 0.0727, 0.643, 1.357, 1.596, 1.886]) @test all(abs.(spl_lblvs_interp .- spl_lblvs_barc) .< [28.442, 24.625, 20.380, 16.315, 12.763, 8.731, 5.498, 2.812, 0.964, 0.390, 0.628, 0.743, 0.903, 0.0362, 0.0262, 1.801, 3.430, 5.011, 4.375, 3.376]) @test all(abs.(spl_teb_interp .- spl_teb_barc) .< [0.134, 0.306, 0.459, 0.106, 0.139, 0.809]) @test all(abs.(spl_tip_interp .- spl_tip_barc) .< [0.862, 0.839, 0.843, 0.545, 0.429, 0.616, 0.382, 0.135])
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
14194
using AcousticAnalogies using AcousticMetrics: AcousticMetrics using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, SteadyRotYTransformation, SteadyRotZTransformation, ConstantVelocityTransformation using FileIO: load using FLOWMath: Akima using StaticArrays: @SVector using Test # tip vortex noise correction data based on "Airfoil Tip Vortex Formation Noise" # Copied from BPM.jl (would like to add BPM.jl as a dependency if it's registered in General some day). const bm_tip_alpha_aspect_data = [2.0,2.67,4.0,6.0,12.0,24.0] const bm_tip_alpha_aratio_data = [0.54,0.62,0.71,0.79,0.89,0.95] const bm_tip_alpha_aspect_ratio_correction = Akima(bm_tip_alpha_aspect_data, bm_tip_alpha_aratio_data) function bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) # compute tip lift curve slope if aspect_ratio < 2.0 aratio = 0.5*one(aspect_ratio) elseif 2.0 <= aspect_ratio <= 24.0 aratio = bm_tip_alpha_aspect_ratio_correction(aspect_ratio) elseif aspect_ratio > 24.0 aratio = 1.0*one(aspect_ratio) end return aratio end struct BMTipAlphaCorrection{TCorrection} <: AbstractTipAlphaCorrection correction::TCorrection function BMTipAlphaCorrection(aspect_ratio) # correction = BPM._tip_vortex_alpha_correction_nonsmooth(aspect_ratio) correction = bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) return new{typeof(correction)}(correction) end end function AcousticAnalogies.tip_vortex_alpha_correction(blade_tip::AbstractBladeTip{<:BMTipAlphaCorrection}, alphatip) a0l = AcousticAnalogies.alpha_zerolift(blade_tip) correction_factor = AcousticAnalogies.tip_alpha_correction(blade_tip).correction return correction_factor * (alphatip - a0l) + a0l end data = load(joinpath(@__DIR__, "gen_bpmjl_data", "figure24b.jld2")) rho = data["rho"] asound = data["asound"] mu = data["mu"] Vinf = data["Vinf"] omega = data["omega"] B = data["B"] Rhub = data["Rhub"] Rtip = data["Rtip"] radii = data["radii"] chord = data["chord"] twist = data["twist"] alpha = data["alpha"] U = data["U"] hs = data["hs"] Psis = data["Psis"] num_src_times_blade_pass = data["num_src_times_blade_pass"] tripped_flags = data["tripped_flags"] num_radial = length(radii) nu = mu/rho dradii = AcousticAnalogies.get_dradii(radii, Rhub, Rtip) # Get some transform stuff. bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) num_blade_pass = 1 period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # I don't see any discussion for what type of tip was used for the tip vortex noise. # FlatTip with no CCBlade.jl tip correction or BPM-style tip correction seems to match the BARC predictions well. # blade_tip = AcousticAnalogies.FlatTip(AcousticAnalogies.NoTipAlphaCorrection()) # BPM.jl uses a different tip alpha correction which appears to require the blade aspect ratio, defined as the blade radius divided by the average chord. cbar = sum(chord .* dradii) / (Rtip - Rhub) aspect_ratio = Rtip/cbar alpha0lift = 0.0 blade_tip = AcousticAnalogies.FlatTip(BMTipAlphaCorrection(aspect_ratio), alpha0lift) # Getting the coordinate system consistent with BPM.jl is a bit tricky. # Here's a bit of code from BPM.jl: # # # Calculate the trailing edge position relative to the hub # xs = sin(beta)*d - cos(beta)*(c - c1) # zs = cos(beta)*d + sin(beta)*(c - c1) # # OK, so that shows me that the blade is initially aligned with the z axis, rotating to the positive x direction. # And I know the blades are rotating about the positive y axis. # So that's the answer for the BPM.jl coordinate system: # # * freestream in the positive y axis direction. # * first blade initially aligned with the positive z axis, rotating about the positive y axis. # # Now, what do I need to do with AcousticAnalogies to make that happen? # I want the blades to be translating in the negative y direction, rotating about the positive y axis. # I usually start with the blades rotating about either the positive or negative x axis, moving in the direction of the positive x axis. # I think the answer is, # # * start out with the blades rotating about the negative x axis, moving in the direction of the positive x axis # * rotate 90Β° about the negative z axis. # After this, the blades will be moving in the negative y direction, rotating about the positive y axis, which is good. # But I want the first blade to be aligned with the positive z axis, and stopping here would mean it's aligned with the positive x axis. # * rotate 90Β° about the negative y axis. # This will put the first blade in line with the positive z axis. # So, let's do what we said we need to do. # Start with a rotation about the negative x axis. positive_x_rotation = false rot_trans = SteadyRotXTransformation(t0, omega*ifelse(positive_x_rotation, 1, -1), 0) # Then translate along the positive x axis. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Then a 90Β° rotation about the negative z axis. trans_z90deg = SteadyRotZTransformation(0.0, 0.0, -0.5*pi) # Then a 90Β° rotation about the negative y axis. trans_y90deg = SteadyRotYTransformation(0.0, 0.0, -0.5*pi) # Put them all together: trans = compose.(src_times, Ref(trans_y90deg), compose.(src_times, Ref(trans_z90deg), compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)))) # Use the M_c = 0.8*M that BPM.jl and the BPM report use. U = @. 0.8*sqrt(Vinf^2 + (omega*radii)^2) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) .* ifelse(positive_x_rotation, 1, -1) bls = [ifelse(tf, AcousticAnalogies.TrippedN0012BoundaryLayer(), AcousticAnalogies.UntrippedN0012BoundaryLayer()) for tf in tripped_flags] # Need to do the LBLVS with the untripped boundary layer to match what BPM.jl is doing. bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() r_obs = 2.27 # meters theta_obs = -35*pi/180 # So, the docstring for BPM.jl says that `V` argument is the wind velocity in the y direction. # So I guess we should assume that the blades are rotating about the y axis. # And if the freestream velocity is in the positive y axis, then, from the perspective of the fluid, the blades are translating in the negative y direction. # And I want the observer to be downstream/behind the blades, so that would mean they would have a positive y position. # So I want to rotate the observer around the positive x axis, so I'm going to switch the sign on `theta_obs`. t0_obs = 0.0 x0_obs = [0.0, r_obs*sin(-theta_obs), r_obs*cos(-theta_obs)] # The observer is moving in the same direction as the blades, which is the negative y axis. v_obs = @SVector [0.0, -Vinf, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) hs_rs = reshape(hs, 1, :, 1) Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # bls_untripped_rs = reshape(bls_lblvs, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] chord_rs_with_tip = @view chord_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] hs_rs_with_tip = @view hs_rs[:, end:end, :] Psis_rs_with_tip = @view Psis_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] direct = AcousticAnalogies.BPMDirectivity use_UInduction = false use_Doppler = false mach_correction = AcousticAnalogies.NoMachCorrection ses_no_tip = CombinedNoTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord_rs_no_tip, twist_rs_no_tip, hs_rs_no_tip, Psis_rs_no_tip, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord_rs_with_tip, twist_rs_with_tip, hs_rs_with_tip, Psis_rs_with_tip, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # Now we can construct the lblvs source elements. lblvs_ses = AcousticAnalogies.LBLVSSourceElement{direct,use_UInduction,use_Doppler}.(asound, nu, radii_rs, ΞΈs_rs, dradii_rs, chord_rs, twist_rs, Us_rs, alphas_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # Write out the source elements. # pvd_no_tip = AcousticAnalogies.to_paraview_collection(joinpath(@__DIR__, "figure24b-no_tip"), ses_no_tip) # pvd_with_tip = AcousticAnalogies.to_paraview_collection(joinpath(@__DIR__, "figure24b-with_tip"), ses_with_tip) # pvd_all = AcousticAnalogies.to_paraview_collection(joinpath(@__DIR__, "figure24b-all"), (ses_no_tip, ses_with_tip, lblvs_ses); observers=(obs,)) # Put the source elements together: ses = cat(ses_no_tip, ses_with_tip; dims=2) # Define the frequencies we'd like to evaluate. # BPM.jl uses the approximate 1/3rd-octave bands. freqs_obs = AcousticMetrics.ApproximateThirdOctaveCenterBands(100.0, 40000.0) freqs_src = freqs_obs # Now do the noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(lblvs_ses, Ref(obs), Ref(freqs_src)) # Separate out each source. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Combine each noise prediction. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) # Now I need to account for the fact that Figure 23c is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # (Dividing the MSP by Ξ”f_pbs aka the 1/3 octave spacing is like getting a power-spectral density, then multiplying by the narrowband spacing Ξ”f_nb gives us the MSP associated with the narrowband.) # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs nb_lblvs = pbs_lblvs .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) spl_lblvs = 10 .* log10.(nb_lblvs./(pref^2)) # Read in the BPM.jl data. freq_bpmjl = data["freqs"] spl_pressure_bpmjl = data["spl_nb_pressure"] spl_suction_bpmjl = data["spl_nb_suction"] spl_separation_bpmjl = data["spl_nb_separation"] spl_lblvs_bpmjl = data["spl_nb_lblvs"] spl_blunt_bpmjl = data["spl_nb_blunt"] spl_tip_bpmjl = data["spl_nb_tip"] # The frequencies in the CSV file should match the observer frequencies we're using. @test all(freqs_obs .β‰ˆ freq_bpmjl) # Only look at the SPLs that are actually significant, i.e. greater than 0 dB. @test maximum(abs.(spl_pressure[spl_pressure_bpmjl .> 0] .- spl_pressure_bpmjl[spl_pressure_bpmjl .> 0])) < 0.496 @test maximum(abs.(spl_suction[spl_suction_bpmjl .> 0] .- spl_suction_bpmjl[spl_suction_bpmjl .> 0])) < 0.476 @test maximum(abs.(spl_alpha[spl_separation_bpmjl .> 0] .- spl_separation_bpmjl[spl_separation_bpmjl .> 0])) < 0.479 @test maximum(abs.(spl_teb[spl_blunt_bpmjl .> 0] .- spl_blunt_bpmjl[spl_blunt_bpmjl .> 0])) < 0.489 @test maximum(abs.(spl_tip[spl_tip_bpmjl .> 0] .- spl_tip_bpmjl[spl_tip_bpmjl .> 0])) < 0.874 @test maximum(abs.(spl_lblvs[spl_lblvs_bpmjl .> 0] .- spl_lblvs_bpmjl[spl_lblvs_bpmjl .> 0])) < 0.499
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
1261
module OpenFASTHelperTests using SafeTestsets: @safetestset using Test: @testset @testset "OpenFAST reader tests" begin @testset "reading" begin @safetestset "default" begin include("openfast_reading_default.jl") end @safetestset "different time column name" begin include("openfast_reading_different_time_column_name.jl") end @safetestset "no units header" begin include("openfast_reading_no_units_header.jl") end end @testset "radial interpolation" begin @safetestset "linear" begin include("openfast_radial_interpolation_linear.jl") end @safetestset "akima" begin include("openfast_radial_interpolation_akima.jl") end end @testset "time derivatives" begin @safetestset "constant time step" begin include("openfast_time_derivatives_constant_time_step.jl") end @safetestset "non-constant time step" begin include("openfast_time_derivatives_nonconstant_time_step.jl") end @safetestset "no time diff" begin include("openfast_time_derivatives_nonconstant_time_step_no_diff.jl") end end end end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
2426
using AcousticAnalogies using Test T = 2.5 t0 = 0.3 R = 2.3 num_times = 64 num_radial = 30 num_blades = 3 cs(r) = 0.1*sin(2*pi*r/R + 0.1*pi) + 0.2*cos(4*pi*r/R + 0.2*pi) fn(t, r, b) = 0.2*sin(2*pi/T*t*r/R*b + 0.1*pi) + 0.3*cos(4*pi/T*t*r/R*b + 0.2*pi) fc(t, r, b) = 0.4*sin(2*pi/T*t*r/R*b + 0.3*pi) + 0.5*cos(4*pi/T*t*r/R*b + 0.4*pi) dt = T/num_times time = t0 .+ (0:(num_times-1)) .* dt radii = range(0.2*R, R; length=num_radial) radii_mid = 0.5 .* (@view(radii[1:end-1]) .+ @view(radii[2:end])) dradii = nothing dtime_dtau = v = azimuth = omega = pitch = nothing axial_loading_mid_dot = circum_loading_mid_dot = nothing r = reshape(radii, 1, :) b = reshape(1:num_blades, 1, 1, :) cs_area = @. cs(radii) axial_loading = @. fn(time, r, b) circum_loading = @. fc(time, r, b) cs_area_mid = similar(cs_area, num_radial-1) axial_loading_mid = similar(axial_loading, num_times, num_radial-1, num_blades) circum_loading_mid = similar(circum_loading, num_times, num_radial-1, num_blades) data = OpenFASTData{FLOWAkimaInterp,SecondOrderFiniteDiff}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot) interpolate_to_cell_centers!(data) r_mid = reshape(radii_mid, 1, :) cs_area_mid_exact = @. cs(radii_mid) axial_loading_mid_exact = @. fn(time, r_mid, b) circum_loading_mid_exact = @. fc(time, r_mid, b) csm_min, csm_max = extrema(cs_area_mid_exact) csm_err = maximum(abs.((data.cs_area_mid .- cs_area_mid_exact)./(csm_max - csm_min))) @test csm_err < 0.00105 alm_min = reshape(minimum(axial_loading_mid_exact; dims=2), num_times, 1, num_blades) alm_max = reshape(maximum(axial_loading_mid_exact; dims=2), num_times, 1, num_blades) # @show maximum(abs.((data.axial_loading_mid .- axial_loading_mid_exact)./(alm_max .- alm_min))) alm_err = maximum(abs.((data.axial_loading_mid .- axial_loading_mid_exact)./(alm_max .- alm_min))) @test alm_err < 0.033 clm_min = reshape(minimum(circum_loading_mid_exact; dims=2), num_times, 1, num_blades) clm_max = reshape(maximum(circum_loading_mid_exact; dims=2), num_times, 1, num_blades) # @show maximum(abs.((data.circum_loading_mid .- circum_loading_mid_exact)./(clm_max .- clm_min))) clm_err = maximum(abs.((data.circum_loading_mid .- circum_loading_mid_exact)./(clm_max .- clm_min))) @test clm_err < 0.033
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
2231
using AcousticAnalogies using Test T = 2.5 t0 = 0.3 R = 2.3 num_times = 64 num_radial = 30 num_blades = 3 cs(r) = 0.1*sin(2*pi*r/R + 0.1*pi) + 0.2*cos(4*pi*r/R + 0.2*pi) fn(t, r, b) = 0.2*sin(2*pi/T*t*r/R*b + 0.1*pi) + 0.3*cos(4*pi/T*t*r/R*b + 0.2*pi) fc(t, r, b) = 0.4*sin(2*pi/T*t*r/R*b + 0.3*pi) + 0.5*cos(4*pi/T*t*r/R*b + 0.4*pi) dt = T/num_times time = t0 .+ (0:(num_times-1)) .* dt radii = range(0.2*R, R; length=num_radial) radii_mid = 0.5 .* (@view(radii[1:end-1]) .+ @view(radii[2:end])) dradii = nothing dtime_dtau = v = azimuth = omega = pitch = nothing axial_loading_mid_dot = circum_loading_mid_dot = nothing r = reshape(radii, 1, :) b = reshape(1:num_blades, 1, 1, :) cs_area = @. cs(radii) axial_loading = @. fn(time, r, b) circum_loading = @. fc(time, r, b) cs_area_mid = similar(cs_area, num_radial-1) axial_loading_mid = similar(axial_loading, num_times, num_radial-1, num_blades) circum_loading_mid = similar(circum_loading, num_times, num_radial-1, num_blades) data = OpenFASTData{FLOWLinearInterp,SecondOrderFiniteDiff}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot) interpolate_to_cell_centers!(data) r_mid = reshape(radii_mid, 1, :) cs_area_mid_exact = @. cs(radii_mid) axial_loading_mid_exact = @. fn(time, r_mid, b) circum_loading_mid_exact = @. fc(time, r_mid, b) csm_min, csm_max = extrema(cs_area_mid_exact) csm_err = maximum(abs.((data.cs_area_mid .- cs_area_mid_exact)./(csm_max - csm_min))) @test csm_err < 0.00664 alm_min = reshape(minimum(axial_loading_mid_exact; dims=2), num_times, 1, num_blades) alm_max = reshape(maximum(axial_loading_mid_exact; dims=2), num_times, 1, num_blades) alm_err = maximum(abs.((data.axial_loading_mid .- axial_loading_mid_exact)./(alm_max .- alm_min))) @test alm_err < 0.069 clm_min = reshape(minimum(circum_loading_mid_exact; dims=2), num_times, 1, num_blades) clm_max = reshape(maximum(circum_loading_mid_exact; dims=2), num_times, 1, num_blades) clm_err = maximum(abs.((data.circum_loading_mid .- circum_loading_mid_exact)./(clm_max .- clm_min))) @test clm_err < 0.063
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
1220
using AcousticAnalogies using Statistics: mean using Test fname = joinpath(@__DIR__, "gen_test_data", "openfast_data", "IEA-3.4-130-RWT-small.out") num_radial = 30 radii = range(0.2, 1.0; length=num_radial) data = read_openfast_file(fname, radii) num_times = length(data.time) num_blades = size(data.pitch, 2) num_radial = size(data.axial_loading, 2) @test size(data.time) == (num_times,) @test size(data.v) == (num_times,) @test size(data.azimuth) == (num_times,) @test size(data.omega) == (num_times,) @test size(data.pitch) == (num_times, num_blades) @test size(data.axial_loading) == (num_times, num_radial, num_blades) @test size(data.circum_loading) == (num_times, num_radial, num_blades) @test all(data.time .β‰ˆ (60.0:0.01:60.1)) @test all(data.v .β‰ˆ 7) @test all(data.pitch .β‰ˆ 0*pi/180) # Just some coarse tests. @test mean(data.omega) β‰ˆ 8.126818181818182*(2*pi/60) @test mean(data.axial_loading) β‰ˆ 1632.1274949494953 @test mean(data.circum_loading) β‰ˆ -217.45748949494939 # Make sure the averaging of the freestream velocity and omega works. data2 = read_openfast_file(fname, radii; average_freestream_vel=true, average_omega=true) @test all(data2.v .β‰ˆ 7) @test all(data2.omega .β‰ˆ 8.126818181818182*(2*pi/60))
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
1280
using AcousticAnalogies using Statistics: mean using Test fname = joinpath(@__DIR__, "gen_test_data", "openfast_data", "IEA-3.4-130-RWT-small-FooTime.out") num_radial = 30 radii = range(0.2, 1.0; length=num_radial) data = read_openfast_file(fname, radii; header_keyword="FooTime") num_times = length(data.time) num_blades = size(data.pitch, 2) num_radial = size(data.axial_loading, 2) @test size(data.time) == (num_times,) @test size(data.v) == (num_times,) @test size(data.azimuth) == (num_times,) @test size(data.omega) == (num_times,) @test size(data.pitch) == (num_times, num_blades) @test size(data.axial_loading) == (num_times, num_radial, num_blades) @test size(data.circum_loading) == (num_times, num_radial, num_blades) @test all(data.time .β‰ˆ (60.0:0.01:60.1)) @test all(data.v .β‰ˆ 7) @test all(data.pitch .β‰ˆ 0*pi/180) # Just some coarse tests. @test mean(data.omega) β‰ˆ 8.126818181818182*(2*pi/60) @test mean(data.axial_loading) β‰ˆ 1632.1274949494953 @test mean(data.circum_loading) β‰ˆ -217.45748949494939 # Make sure the averaging of the freestream velocity and omega works. data2 = read_openfast_file(fname, radii; header_keyword="FooTime", average_freestream_vel=true, average_omega=true) @test all(data2.v .β‰ˆ 7) @test all(data2.omega .β‰ˆ 8.126818181818182*(2*pi/60))
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
1304
using AcousticAnalogies using Statistics: mean using Test fname = joinpath(@__DIR__, "gen_test_data", "openfast_data", "IEA-3.4-130-RWT-small-no_units.out") num_radial = 30 radii = range(0.2, 1.0; length=num_radial) data = read_openfast_file(fname, radii; has_units_header=false) num_times = length(data.time) num_blades = size(data.pitch, 2) num_radial = size(data.axial_loading, 2) @test size(data.time) == (num_times,) @test size(data.v) == (num_times,) @test size(data.azimuth) == (num_times,) @test size(data.omega) == (num_times,) @test size(data.pitch) == (num_times, num_blades) @test size(data.axial_loading) == (num_times, num_radial, num_blades) @test size(data.circum_loading) == (num_times, num_radial, num_blades) @test all(data.time .β‰ˆ (60.0:0.01:60.1)) @test all(data.v .β‰ˆ 7) @test all(data.pitch .β‰ˆ 0) @test all(data.pitch .β‰ˆ 0*pi/180) # Just some coarse tests. @test mean(data.omega) β‰ˆ 8.126818181818182*(2*pi/60) @test mean(data.axial_loading) β‰ˆ 1632.1274949494953 @test mean(data.circum_loading) β‰ˆ -217.45748949494939 # Make sure the averaging of the freestream velocity and omega works. data2 = read_openfast_file(fname, radii; has_units_header=false, average_freestream_vel=true, average_omega=true) @test all(data2.v .β‰ˆ 7) @test all(data2.omega .β‰ˆ 8.126818181818182*(2*pi/60))
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
2560
using AcousticAnalogies using Polynomials: fit using Test v = azimuth = omega = pitch = nothing dradii = nothing cs_area = cs_area_mid = nothing axial_loading = circum_loading = nothing T = 2.5 t0 = 0.3 fn(t, r, b) = 0.2*sin(2*pi/T*t*r*b + 0.1*pi) + 0.3*cos(4*pi/T*t*r*b + 0.2*pi) fndot(t, r, b) = 0.2*2*pi/T*r*b*cos(2*pi/T*t*r*b + 0.1*pi) - 0.3*4*pi/T*r*b*sin(4*pi/T*t*r*b + 0.2*pi) fc(t, r, b) = 0.4*sin(2*pi/T*t*r*b + 0.3*pi) + 0.5*cos(4*pi/T*t*r*b + 0.4*pi) fcdot(t, r, b) = 0.4*2*pi/T*r*b*cos(2*pi/T*t*r*b + 0.3*pi) - 0.5*4*pi/T*r*b*sin(4*pi/T*t*r*b + 0.4*pi) # r = reshape(range(1.0, 2.0; length=5), 1, :) radii = range(1.0, 2.0; length=5) radii_mid = 0.5 .* (@view(radii[1:end-1]) .+ @view(radii[2:end])) r = reshape(radii_mid, 1, :) b = reshape(1:3, 1, 1, :) errs_fn_l2 = Vector{Float64}() errs_fc_l2 = Vector{Float64}() dts = Vector{Float64}() for N in 120:10:150 dt = T/N push!(dts, dt) time = t0 .+ (0:(N-1)) .* dt dtime_dtau = similar(time) axial_loading_mid = fn.(time, r, b) circum_loading_mid = fc.(time, r, b) axial_loading_mid_dot = similar(axial_loading_mid) circum_loading_mid_dot = similar(circum_loading_mid) # data = OpenFASTData{SecondOrderFiniteDiff}(time, v, azimuth, omega, pitch, axial_loading_mid, circum_loading_mid) data = OpenFASTData{FLOWLinearInterp,SecondOrderFiniteDiff}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot) AcousticAnalogies.calculate_loading_dot!(data) @test all(data.dtime_dtau .β‰ˆ dt) err_fn_l2 = sqrt(sum((data.axial_loading_mid_dot .- fndot.(time, r, b)).^2) / length(data.axial_loading_mid_dot)) push!(errs_fn_l2, err_fn_l2) err_fc_l2 = sqrt(sum((data.circum_loading_mid_dot .- fcdot.(time, r, b)).^2) / length(data.circum_loading_mid_dot)) push!(errs_fc_l2, err_fc_l2) end # err β‰ˆ dt^p # err2/err1 β‰ˆ (dt2^p)/(dt1^p) = (dt2/dt1)^p # log(err2/err1) β‰ˆ log((dt2/dt1)^p) = p*log(dt2/dt1) # p β‰ˆ log(err2/err1)/log(dt2/dt1) β‰ˆ (log(err2) - log(err1))/(log(dt2) - log(dt1)) # Fit a line through the errors on a log-log plot, then check that the slope is 2 (second-order). l_fn = fit(log.(dts), log.(errs_fn_l2), 1) @test isapprox(l_fn.coeffs[2], 2, atol=0.02) # Fit a line through the errors on a log-log plot, then check that the slope is 2 (second-order). l_fc = fit(log.(dts), log.(errs_fc_l2), 1) @test isapprox(l_fc.coeffs[2], 2, atol=0.02)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
2639
using AcousticAnalogies using Polynomials: fit using Test v = azimuth = omega = pitch = nothing cs_area = cs_area_mid = nothing axial_loading = circum_loading = nothing dradii = nothing T = 2.5 t0 = 0.3 fn(t, r, b) = 0.2*sin(2*pi/T*t*r*b + 0.1*pi) + 0.3*cos(4*pi/T*t*r*b + 0.2*pi) fndot(t, r, b) = 0.2*2*pi/T*r*b*cos(2*pi/T*t*r*b + 0.1*pi) - 0.3*4*pi/T*r*b*sin(4*pi/T*t*r*b + 0.2*pi) fc(t, r, b) = 0.4*sin(2*pi/T*t*r*b + 0.3*pi) + 0.5*cos(4*pi/T*t*r*b + 0.4*pi) fcdot(t, r, b) = 0.4*2*pi/T*r*b*cos(2*pi/T*t*r*b + 0.3*pi) - 0.5*4*pi/T*r*b*sin(4*pi/T*t*r*b + 0.4*pi) # r = reshape(range(1.0, 2.0; length=5), 1, :) radii = range(1.0, 2.0; length=5) radii_mid = 0.5 .* (@view(radii[1:end-1]) .+ @view(radii[2:end])) r = reshape(radii_mid, 1, :) b = reshape(1:3, 1, 1, :) errs_fn_l2 = Vector{Float64}() errs_fc_l2 = Vector{Float64}() Ns = 120:10:150 for N in Ns dt = T/N time1 = t0 .+ (0:(N-1)) .* dt wiggle = 0.49.*dt.*(cos.(2.0*pi./T.*time1)) time = time1 .+ wiggle dtime_dtau = similar(time) axial_loading_mid = fn.(time, r, b) circum_loading_mid = fc.(time, r, b) axial_loading_mid_dot = similar(axial_loading_mid) circum_loading_mid_dot = similar(circum_loading_mid) # data = OpenFASTData{SecondOrderFiniteDiff}(time, v, azimuth, omega, pitch, axial_loading_mid, circum_loading_mid) data = OpenFASTData{FLOWLinearInterp,SecondOrderFiniteDiff}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot) AcousticAnalogies.calculate_loading_dot!(data) err_fn_l2 = sqrt(sum((data.axial_loading_mid_dot .- fndot.(time, r, b)).^2) / length(data.axial_loading_mid_dot)) push!(errs_fn_l2, err_fn_l2) err_fc_l2 = sqrt(sum((data.circum_loading_mid_dot .- fcdot.(time, r, b)).^2) / length(data.circum_loading_mid_dot)) push!(errs_fc_l2, err_fc_l2) end # err β‰ˆ dt^p = (T/N)^p # err2/err1 β‰ˆ ((T/N2)^p)/((T/N1)^p) = ((T/N2)/(T/N1))^p = (N1/N2)^p # log(err2/err1) β‰ˆ log((N1/N2)^p) = p*log(N1/N2) # p β‰ˆ log(err2/err1)/log(N1/N2) β‰ˆ (log(err2) - log(err1))/(log(N1) - log(N2)) = -(log(err2) - log(err1))/(log(N2) - log(N1)) # Fit a line through the errors on a log-log plot, then check that the slope is -2 (second-order). l_fn = fit(log.(Ns), log.(errs_fn_l2), 1) @test isapprox(-l_fn.coeffs[2], 2, atol=0.02) # Fit a line through the errors on a log-log plot, then check that the slope is -2 (second-order). l_fc = fit(log.(Ns), log.(errs_fc_l2), 1) @test isapprox(-l_fc.coeffs[2], 2, atol=0.02)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
1506
using AcousticAnalogies using Polynomials: fit using Test v = azimuth = omega = pitch = nothing cs_area = cs_area_mid = nothing axial_loading = circum_loading = nothing dradii = nothing T = 2.5 t0 = 0.3 fn(t, r, b) = 0.2*sin(2*pi/T*t*r*b + 0.1*pi) + 0.3*cos(4*pi/T*t*r*b + 0.2*pi) fndot(t, r, b) = 0.2*2*pi/T*r*b*cos(2*pi/T*t*r*b + 0.1*pi) - 0.3*4*pi/T*r*b*sin(4*pi/T*t*r*b + 0.2*pi) fc(t, r, b) = 0.4*sin(2*pi/T*t*r*b + 0.3*pi) + 0.5*cos(4*pi/T*t*r*b + 0.4*pi) fcdot(t, r, b) = 0.4*2*pi/T*r*b*cos(2*pi/T*t*r*b + 0.3*pi) - 0.5*4*pi/T*r*b*sin(4*pi/T*t*r*b + 0.4*pi) # r = reshape(range(1.0, 2.0; length=5), 1, :) radii = range(1.0, 2.0; length=5) radii_mid = 0.5 .* (@view(radii[1:end-1]) .+ @view(radii[2:end])) r = reshape(radii_mid, 1, :) b = reshape(1:3, 1, 1, :) N = 120 dt = T/N time1 = t0 .+ (0:(N-1)) .* dt wiggle = 0.49.*dt.*(cos.(2.0*pi./T.*time1)) time = time1 .+ wiggle dtime_dtau = similar(time) axial_loading_mid = fn.(time, r, b) circum_loading_mid = fc.(time, r, b) axial_loading_mid_dot = similar(axial_loading_mid) circum_loading_mid_dot = similar(circum_loading_mid) data = OpenFASTData{FLOWLinearInterp,NoTimeDerivMethod}( time, dtime_dtau, v, azimuth, omega, pitch, radii, radii_mid, dradii, cs_area, cs_area_mid, axial_loading, axial_loading_mid, axial_loading_mid_dot, circum_loading, circum_loading_mid, circum_loading_mid_dot) AcousticAnalogies.calculate_loading_dot!(data) @test all(data.axial_loading_mid_dot .β‰ˆ 0) @test all(data.circum_loading_mid_dot .β‰ˆ 0)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
1113
module AcousticAnalogiesTests all_tests = isempty(ARGS) || ("all" in ARGS) if "adv_time" in ARGS || all_tests include("adv_time_tests.jl") end if "combine" in ARGS || all_tests include("combine_tests.jl") end if "f1a" in ARGS || all_tests include("f1a_tests.jl") end if "f1a_constructor" in ARGS || all_tests include("compact_f1a_constructor_tests.jl") end if "anopp2" in ARGS || all_tests include("anopp2_comparison.jl") end if "forwarddiff" in ARGS || all_tests include("forwarddiff_test.jl") end if "doppler" in ARGS || all_tests include("doppler_tests.jl") end if "boundary_layers" in ARGS || all_tests include("boundary_layer_tests.jl") end if "bpm_shape_functions" in ARGS || all_tests include("bpm_shape_function_tests.jl") end if "broadband_source_elements" in ARGS || all_tests include("broadband_source_element_tests.jl") end if "writevtk" in ARGS || all_tests include("writevtk_tests.jl") end if "openfast" in ARGS || all_tests include("openfast_helper_tests.jl") end if "bpm_itr" in ARGS || all_tests include("bpm_itr_tests.jl") end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
4918
module WriteVTKTests using AcousticAnalogies using Format: format, FormatExpr using JLD2: JLD2 using SHA: sha1 using StaticArrays: @SVector using Test @testset "WriteVTK tests" begin @testset "Compact F1A source elements" begin fname = joinpath(@__DIR__, "writevtk", "cf1a.jld2") ses = nothing JLD2.jldopen(fname, "r") do file ses = file["ses"] end name = "cf1a" pvd = AcousticAnalogies.to_paraview_collection(name, ses) for i in 1:size(ses, 1) fname = format(FormatExpr("{}{:08d}.vtp"), name, i) sha_str = bytes2hex(open(sha1, fname)) sha_str_check = bytes2hex(open(sha1, joinpath("writevtk", fname))) @test sha_str == sha_str_check end if !Sys.iswindows() fname = "$(name).pvd" sha_str = bytes2hex(open(sha1, fname)) sha_str_check = bytes2hex(open(sha1, joinpath(@__DIR__, "writevtk", fname))) @test sha_str == sha_str_check end end @testset "Compact F1A source elements, with observers" begin fname = joinpath(@__DIR__, "writevtk", "cf1a.jld2") ses = nothing JLD2.jldopen(fname, "r") do file ses = file["ses"] end obs1 = AcousticAnalogies.ConstVelocityAcousticObserver(0.0, @SVector([0, 2.0, 0]), @SVector([5.0, 0.0, 0.0])) obs2 = AcousticAnalogies.StationaryAcousticObserver(@SVector [0, 2.5, 0]) obs = [obs1, obs2] name = "cf1a_with_observers" pvd = AcousticAnalogies.to_paraview_collection(name, (ses,); observers=obs) for i in 1:size(ses, 1) fname = format(FormatExpr("{}-block1-{:08d}.vtp"), name, i) sha_str = bytes2hex(open(sha1, fname)) sha_str_check = bytes2hex(open(sha1, joinpath(@__DIR__, "writevtk", fname))) @test sha_str == sha_str_check # The source element files for this test case with observers should be the same as the case without the observers. name2 = "cf1a" fname2 = format(FormatExpr("{}{:08d}.vtp"), name2, i) sha_str_check = bytes2hex(open(sha1, joinpath(@__DIR__, "writevtk", fname))) @test sha_str == sha_str_check for j in 1:length(obs) fname = format(FormatExpr("{}-observer$(j)-{:08d}.vtu"), name, i) sha_str = bytes2hex(open(sha1, fname)) sha_str_check = bytes2hex(open(sha1, joinpath(@__DIR__, "writevtk", fname))) # @test sha_str == sha_str_check end end if !Sys.iswindows() fname = "$(name).pvd" sha_str = bytes2hex(open(sha1, fname)) sha_str_check = bytes2hex(open(sha1, joinpath(@__DIR__, "writevtk", fname))) @test sha_str == sha_str_check end end @testset "Compact F1A source elements, multiblock, with observers" begin fname = joinpath(@__DIR__, "writevtk", "cf1a.jld2") ses = nothing JLD2.jldopen(fname, "r") do file ses = file["ses"] end # Split the array into "blocks." ses_mb = tuple([ses[:, :, b] for b in 1:size(ses, 3)]...) obs1 = AcousticAnalogies.ConstVelocityAcousticObserver(0.0, @SVector([0, 2.0, 0]), @SVector([5.0, 0.0, 0.0])) obs2 = AcousticAnalogies.StationaryAcousticObserver(@SVector [0, 2.5, 0]) obs = [obs1, obs2] name = "cf1a_mb_with_observers" pvd = AcousticAnalogies.to_paraview_collection(name, ses_mb; observers=obs) for i in 1:size(ses, 1) for b in 1:length(ses_mb) fname = format(FormatExpr("{}-block$(b)-{:08d}.vtp"), name, i) sha_str = bytes2hex(open(sha1, fname)) sha_str_check = bytes2hex(open(sha1, joinpath(@__DIR__, "writevtk", fname))) @test sha_str == sha_str_check end for j in 1:length(obs) fname = format(FormatExpr("{}-observer$(j)-{:08d}.vtu"), name, i) sha_str = bytes2hex(open(sha1, fname)) sha_str_check = bytes2hex(open(sha1, joinpath(@__DIR__, "writevtk", fname))) # @test sha_str == sha_str_check # The observers for this case should be identical to the observers from the single-block case. fname2 = format(FormatExpr("cf1a_with_observers-observer$(j)-{:08d}.vtu"), i) sha_str_check = bytes2hex(open(sha1, joinpath(@__DIR__, "writevtk", fname2))) # @test sha_str == sha_str_check end end if !Sys.iswindows() fname = "$(name).pvd" sha_str = bytes2hex(open(sha1, fname)) sha_str_check = bytes2hex(open(sha1, joinpath(@__DIR__, "writevtk", fname))) @test sha_str == sha_str_check end end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
41045
module ITRWithBPMJL using Accessors: Accessors using AcousticMetrics: AcousticMetrics using BPM: BPM using CCBlade: CCBlade # using DelimitedFiles: writedlm using JLD2: JLD2 using FileIO: save function get_airfoil(; af_fname, cr75, Re_exp) (info, Re, Mach, alpha, cl, cd) = CCBlade.parsefile(af_fname, false) # Extend the angle of attack with the Viterna method. (alpha, cl, cd) = CCBlade.viterna(alpha, cl, cd, cr75) af = CCBlade.AlphaAF(alpha, cl, cd, info, Re, Mach) # Reynolds number correction. The 0.6 factor seems to match the NACA 0012 # drag data from airfoiltools.com. reynolds = CCBlade.SkinFriction(Re, Re_exp) # Mach number correction. mach = CCBlade.PrandtlGlauert() # Rotational stall delay correction. Need some parameters from the CL curve. m, alpha0 = CCBlade.linearliftcoeff(af, 1.0, 1.0) # dummy values for Re and Mach # Create the Du Selig and Eggers correction. rotation = CCBlade.DuSeligEggers(1.0, 1.0, 1.0, m, alpha0) # The usual hub and tip loss correction. tip = CCBlade.PrandtlTipHub() return af, mach, reynolds, rotation, tip end function from_cell_centers_to_interfaces(cc_vals::Vector) N = length(cc_vals) b = cc_vals[:] b[1] = 0.25*cc_vals[1] + 0.25*cc_vals[2] A = zeros(N, N) for i in 1:N-1 A[i, i] = 0.5 A[i+1, i] = 0.5 end A[N, N] = 0.5 a = A\b @assert all(A*a .β‰ˆ b) interface_vals = zeros(N+1) interface_vals[1] = 1.5*cc_vals[1] - 0.5*cc_vals[2] interface_vals[2:end] .= a @assert all(0.5.*(interface_vals[1:end-1] .+ interface_vals[2:end]) .β‰ˆ cc_vals) return interface_vals end function do_figure22b() # Pettingill et al., "Acoustic And Performance Characteristics of an Ideally Twisted Rotor in Hover", 2021 # Parameters from Table 1 B = 4 # number of blades Rtip = 0.1588 # meters chord = 0.2*Rtip # Standard day: Tamb = 15 + 273.15 # 15Β°C in Kelvin pamb = 101325.0 # Pa R = 287.052874 # J/(kg*K) rho = pamb/(R*Tamb) asound = sqrt(1.4*R*Tamb) # CCBlade.jl defines pitch/collective as "the thing added to the twist to get the orientation of the chord line," but the paper appears to use "the angle of the chord line at the tip." collective0 = 6.9*pi/180 # The Figure 23 caption says Θ_tip = 7 deg, but I think that "actually" means 6.9Β°. # And yes, collective is 0 here, which is a bit silly, I guess, but is consistent with the definition of twist down below. collective = 6.9 .* (pi/180) .- collective0 mu = rho*1.4502e-5 Vinf = 0.001*asound # Figure 22 caption says Ξ©_c = 5465 RPM. rpm = 5465.0 omega = rpm * (2*pi/60) # Get "cell-centered" radial locations. num_radial = 50 r_Rtip_ = range(0.2, 1.0; length=num_radial+1) r_Rtip = 0.5 .* (r_Rtip_[2:end] .+ r_Rtip_[1:end-1]) radii = r_Rtip .* Rtip Rhub = r_Rtip_[1]*Rtip # From Pettingill Equation (1), and value for Θ_tip in Table 1. Θ_tip = 6.9 * pi/180 twist = Θ_tip ./ (r_Rtip) # NACA 0012 airfoil stuff. af_fname = joinpath(@__DIR__, "airfoils", "xf-n0012-il-500000.dat") Re_exp = 0.6 cr75 = chord / Rtip af, mach_correction, reynolds_correction, rotation_correction, tip_correction = get_airfoil(; af_fname, cr75, Re_exp) tip_correction = nothing precone = 0.0 turbine = false rotor = CCBlade.Rotor(Rhub, Rtip, B; precone=precone, turbine=turbine, mach=mach_correction, re=reynolds_correction, rotation=rotation_correction, tip=tip_correction) sections = CCBlade.Section.(radii, chord, twist, Ref(af)) ops = CCBlade.OperatingPoint.(Vinf, omega.*radii, rho, collective, mu, asound) outs = CCBlade.solve.(Ref(rotor), sections, ops) # BPM.jl uses the M_c = 0.8*M assumption from the BPM report, so modify the W field of each CCBlade.Outputs struct to match that. lens = Accessors.@optic _.W outs_bpm_Mc = Accessors.set.(outs, Ref(lens), 0.8.*sqrt.(getproperty.(ops, :Vx).^2 .+ getproperty.(ops, :Vy).^2)) @assert all(getproperty.(outs_bpm_Mc, :W) .β‰ˆ 0.8.*sqrt.(getproperty.(ops, :Vx).^2 .+ getproperty.(ops, :Vy).^2)) # Paper doesn't specify the microphone used for Figure 22, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 22. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane. r_obs = 2.27 # meters theta_obs = -35*pi/180 # So, the docstring for BPM.jl says that `V` argument is the wind velocity in the y direction. # So I guess we should assume that the blades are rotating about the y axis. # And if the freestream velocity is in the positive y axis, then, from the perspective of the fluid, the blades are translating in the negative y direction. # And I want the observer to be downstream/behind the blades, so that would mean they would have a positive y position. # So I want to rotate the observer around the positive x axis, so I'm going to switch the sign on `theta_obs`. t0_obs = 0.0 x0_obs = [0.0, r_obs*sin(-theta_obs), r_obs*cos(-theta_obs)] # Get the components of the observer position in a form that BPM.jl uses. ox = x0_obs[1] oy = x0_obs[2] oz = x0_obs[3] # Radial locations. rs = getproperty.(sections, :r) # BPM.jl docstring says we need the angle of attack in degrees. # But it expects them at the interfaces, not cell centers. alphas_deg = getproperty.(outs_bpm_Mc, :alpha) .* (180/pi) rs_interface = from_cell_centers_to_interfaces(rs) alphas_deg_interface = from_cell_centers_to_interfaces(alphas_deg) # Do the same thing for the chord. # What other inputs do we need? # So the distance from the pitch axis to the leading edge is used, apparently, to locate the trailing edge. # Let's make sure that's true. # Here's the relevant code # # # Calculate the trailing edge position relative to the hub # xs = sin(beta)*d - cos(beta)*(c - c1) # zs = cos(beta)*d + sin(beta)*(c - c1) # # `beta` is an azimuthal angle, and `d` is the radial distance of the blade element relative to the hub. # So let's say that's zero. # Then, I guess, `xs = (c - c1)` and `zs = r` # So it looks like the twist is being ignored, I think. # But, at any rate, if I set c1 = c, that effect is ignored. chords = getproperty.(sections, :chord) chords_interface = from_cell_centers_to_interfaces(chords) c1s = chords_interface # In the text describing Figure 22, "For these predictions, the trip flag was set to β€œtripped”, due to the rough surface quality of the blade." tripped_flags = true # In the Figure 22 caption, "for these predictions, bluntness thickness H was set to 0.8 mm and trailing edge angle Ξ¨ was set to 16 degrees." h = 0.8e-3 # meters Psi = 16*pi/180 # radians hs = fill(h, length(rs_interface)) Psis = fill(Psi, length(rs_interface)) Psis_deg = Psis .* 180/pi # Also need kinematic viscosity. nu = mu/rho # Number of azimuthal stations per blade pass, I think. num_betas = 20 # Save the inputs. data = Dict( "rho"=>rho, "asound"=>asound, "mu"=>mu, "Vinf"=>Vinf, "omega"=>omega, "B"=>B, "Rhub"=>rotor.Rhub, "Rtip"=>rotor.Rtip, "radii"=>getproperty.(sections, :r), "chord"=>getproperty.(sections, :chord), "twist"=>getproperty.(sections, :theta), "alpha"=>getproperty.(outs, :alpha), "U"=>getproperty.(outs, :W), "hs"=>hs[begin:end-1], "Psis"=>Psis[begin:end-1], "tripped_flags"=>fill(tripped_flags, length(sections)), "num_src_times_blade_pass"=>num_betas) # save("figure22b-inputs.jld2", data_inputs) # Now we can start doing the predictions. oaspl_pressure, spl_pressure = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=true, turbulent_suction=false, turbulent_separation=false, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_suction, spl_suction = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=true, turbulent_separation=false, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_separation, spl_separation = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=false, turbulent_separation=true, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_lblvs, spl_lblvs = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=false, turbulent_separation=false, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=true, round=false, nbeta=num_betas, smooth=false) oaspl_blunt, spl_blunt = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=false, turbulent_separation=false, blunt=true, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_tip, spl_tip = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; blunt=false, weighted=false, trip=tripped_flags, tip=true, laminar=false, turbulent_pressure=false, turbulent_suction=false, turbulent_separation=false, round=false, nbeta=num_betas, smooth=false) # header = "BPM.default_f,spl_pressure,spl_suction,spl_separation,spl_lblvs,spl_blunt,spl_tip\n" # data = hcat(BPM.default_f, spl_pressure, spl_suction, spl_separation, spl_lblvs, spl_blunt, spl_tip) # fname = joinpath(@__DIR__, "figure22b.csv") # open(fname, "w") do f # write(f, header) # writedlm(f, data, ',') # end # Now I'd like to do the narrowband SPL like the Pettingill et al. paper does, instead of 1/3 octave SPL. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # (Dividing the MSP by Ξ”f_pbs aka the 1/3 octave spacing is like getting a power-spectral density, then multiplying by the narrowband spacing Ξ”f_nb gives us the MSP associated with the narrowband.) # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # First, I'll confirm that the frequencies BPM.jl are using are the ApproximateThirdOctaveCenterBands. # This will give me those center bands: cbands_approx3rdcenter = AcousticMetrics.ApproximateThirdOctaveCenterBands(first(BPM.default_f), last(BPM.default_f)) @assert maximum(abs.(BPM.default_f .- cbands_approx3rdcenter)) < 1e-10 # So then I need to get the spacing associated with the proportional bands. # So get the lower and upper "edges" of the bands. freqs_l = AcousticMetrics.lower_bands(cbands_approx3rdcenter) freqs_u = AcousticMetrics.upper_bands(cbands_approx3rdcenter) # And then the spacing for each band. df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing, which is 20 Hz. df_nb = 20.0 # So, if spl = 10*log10(msp/pref^2), and I want to multiply the msp by df_nb/df_pbs, then # # spl_nb = 10*log10((msp*df_nb/df_pbs)/pref^2) = 10*(log10(msp/pref^2) + log10(df_nb/df_pbs)) # spl_nb = 10*log10(msp/pref^2) + 10*log10(df_nb/df_pbs) # spl_nb = spl + 10*log10(df_nb/df_pbs) # # That's easy. spl_nb_pressure = @. spl_pressure + 10*log10(df_nb/df_pbs) spl_nb_suction = @. spl_suction + 10*log10(df_nb/df_pbs) spl_nb_separation = @. spl_separation + 10*log10(df_nb/df_pbs) spl_nb_lblvs = @. spl_lblvs + 10*log10(df_nb/df_pbs) spl_nb_blunt = @. spl_blunt + 10*log10(df_nb/df_pbs) spl_nb_tip = @. spl_tip + 10*log10(df_nb/df_pbs) data["freqs"] = BPM.default_f data["spl_nb_pressure"] = spl_nb_pressure data["spl_nb_suction"] = spl_nb_suction data["spl_nb_separation"] = spl_nb_separation data["spl_nb_lblvs"] = spl_nb_lblvs data["spl_nb_blunt"] = spl_nb_blunt data["spl_nb_tip"] = spl_nb_tip save(joinpath(@__DIR__, "figure22b.jld2"), data) return nothing end function do_figure23c() # Pettingill et al., "Acoustic And Performance Characteristics of an Ideally Twisted Rotor in Hover", 2021 # Parameters from Table 1 B = 4 # number of blades Rtip = 0.1588 # meters chord = 0.2*Rtip # Standard day: Tamb = 15 + 273.15 # 15Β°C in Kelvin pamb = 101325.0 # Pa R = 287.052874 # J/(kg*K) rho = pamb/(R*Tamb) asound = sqrt(1.4*R*Tamb) # CCBlade.jl defines pitch/collective as "the thing added to the twist to get the orientation of the chord line," but the paper appears to use "the angle of the chord line at the tip." collective0 = 6.9*pi/180 # The Figure 23 caption says Θ_tip = 7 deg, but I think that "actually" means 6.9Β°. # And yes, collective is 0 here, which is a bit silly, I guess, but is consistent with the definition of twist down below. collective = 6.9 .* (pi/180) .- collective0 mu = rho*1.4502e-5 Vinf = 0.001*asound # Figure 23 caption says Ξ©_c = 5510 RPM. rpm = 5510.0 omega = rpm * (2*pi/60) # Get "cell-centered" radial locations. num_radial = 50 r_Rtip_ = range(0.2, 1.0; length=num_radial+1) r_Rtip = 0.5 .* (r_Rtip_[2:end] .+ r_Rtip_[1:end-1]) radii = r_Rtip .* Rtip Rhub = r_Rtip_[1]*Rtip # From Pettingill Equation (1), and value for Θ_tip in Table 1. Θ_tip = 6.9 * pi/180 twist = Θ_tip ./ (r_Rtip) # NACA 0012 airfoil stuff. af_fname = joinpath(@__DIR__, "airfoils", "xf-n0012-il-500000.dat") Re_exp = 0.6 cr75 = chord / Rtip af, mach_correction, reynolds_correction, rotation_correction, tip_correction = get_airfoil(; af_fname, cr75, Re_exp) tip_correction = nothing precone = 0.0 turbine = false rotor = CCBlade.Rotor(Rhub, Rtip, B; precone=precone, turbine=turbine, mach=mach_correction, re=reynolds_correction, rotation=rotation_correction, tip=tip_correction) sections = CCBlade.Section.(radii, chord, twist, Ref(af)) ops = CCBlade.OperatingPoint.(Vinf, omega.*radii, rho, collective, mu, asound) outs = CCBlade.solve.(Ref(rotor), sections, ops) # BPM.jl uses the M_c = 0.8*M assumption from the BPM report, so modify the W field of each CCBlade.Outputs struct to match that. lens = Accessors.@optic _.W outs_bpm_Mc = Accessors.set.(outs, Ref(lens), 0.8.*sqrt.(getproperty.(ops, :Vx).^2 .+ getproperty.(ops, :Vy).^2)) @assert all(getproperty.(outs_bpm_Mc, :W) .β‰ˆ 0.8.*sqrt.(getproperty.(ops, :Vx).^2 .+ getproperty.(ops, :Vy).^2)) # Paper doesn't specify the microphone used for Figure 23, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 23. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane. r_obs = 2.27 # meters theta_obs = -35*pi/180 # So, the docstring for BPM.jl says that `V` argument is the wind velocity in the y direction. # So I guess we should assume that the blades are rotating about the y axis. # And if the freestream velocity is in the positive y axis, then, from the perspective of the fluid, the blades are translating in the negative y direction. # And I want the observer to be downstream/behind the blades, so that would mean they would have a positive y position. # So I want to rotate the observer around the positive x axis, so I'm going to switch the sign on `theta_obs`. t0_obs = 0.0 x0_obs = [0.0, r_obs*sin(-theta_obs), r_obs*cos(-theta_obs)] # Get the components of the observer position in a form that BPM.jl uses. ox = x0_obs[1] oy = x0_obs[2] oz = x0_obs[3] # Radial locations. rs = getproperty.(sections, :r) # BPM.jl docstring says we need the angle of attack in degrees. # But it expects them at the interfaces, not cell centers. rs_interface = from_cell_centers_to_interfaces(rs) alphas_deg = getproperty.(outs_bpm_Mc, :alpha) .* (180/pi) alphas_deg_interface = from_cell_centers_to_interfaces(alphas_deg) # Do the same thing for the chord. # What other inputs do we need? # So the distance from the pitch axis to the leading edge is used, apparently, to locate the trailing edge. # Let's make sure that's true. # Here's the relevant code # # # Calculate the trailing edge position relative to the hub # xs = sin(beta)*d - cos(beta)*(c - c1) # zs = cos(beta)*d + sin(beta)*(c - c1) # # `beta` is an azimuthal angle, and `d` is the radial distance of the blade element relative to the hub. # So let's say that's zero. # Then, I guess, `xs = (c - c1)` and `zs = r` # So it looks like the twist is being ignored, I think. # But, at any rate, if I set c1 = c, that effect is ignored. chords = getproperty.(sections, :chord) chords_interface = from_cell_centers_to_interfaces(chords) c1s = chords_interface # So, for the boundary layer, we want to use untripped for the 95% of the blade from the hub to almost tip, and then tripped for the last 5% of the blade at the tip. # So what are those section indices? num_untripped = Int(round(0.95*num_radial)) num_tripped = num_radial - num_untripped _tripped_flags = vcat(fill(false, num_untripped), fill(true, num_tripped)) @assert length(_tripped_flags) == num_radial # This is working with num_radial, the number of cell-centers, not interfaces. # I think this is the right thing to do though, because it looks like the last value of the `trip` argument is not used by BPM.jl. # But I'll add an extra `true` just to be consistent. tripped_flags = vcat(_tripped_flags, _tripped_flags[end:end]) # Now, the other trick: need to only include LBLVS noise for elements where the Reynolds number is < 160000. # So, we need the Reynolds number for each section. Re_c = rho * getproperty(outs_bpm_Mc, :W) .* getproperty.(sections, :chord) / mu # So now we just need to decide which radial stations have the low or high Re_c values. low_Re_c = 160000 _lblvs_flags = Re_c .< low_Re_c # Again, this is working with num_radial-length arrays, which are dealing with cell-centered quantities. # Again, the last value is ignored, but I'll add a value to be consistent. lblvs_flags = vcat(_lblvs_flags, _lblvs_flags[end:end]) # In the Figure 23 caption, "for these predictions, bluntness thickness H was set to 0.5 mm and trailing edge angle Ξ¨ was set to 14 degrees." h = 0.5e-3 # meters Psi = 14*pi/180 # radians hs = fill(h, length(rs_interface)) Psis = fill(Psi, length(rs_interface)) Psis_deg = Psis .* 180/pi # Also need kinematic viscosity. nu = mu/rho # Number of azimuthal stations per blade pass, I think. num_betas = 20 # Save the inputs. data = Dict( "rho"=>rho, "asound"=>asound, "mu"=>mu, "Vinf"=>Vinf, "omega"=>omega, "B"=>B, "Rhub"=>rotor.Rhub, "Rtip"=>rotor.Rtip, "radii"=>getproperty.(sections, :r), "chord"=>getproperty.(sections, :chord), "twist"=>getproperty.(sections, :theta), "alpha"=>getproperty.(outs, :alpha), "U"=>getproperty.(outs, :W), "hs"=>hs[begin:end-1], "Psis"=>Psis[begin:end-1], "tripped_flags"=>tripped_flags[begin:end-1], "lblvs_flags"=>lblvs_flags[begin:end-1], "num_src_times_blade_pass"=>num_betas) # Now we can start doing the predictions. oaspl_pressure, spl_pressure = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=true, turbulent_suction=false, turbulent_separation=false, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_suction, spl_suction = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=true, turbulent_separation=false, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_separation, spl_separation = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=false, turbulent_separation=true, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_lblvs, spl_lblvs = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=false, turbulent_separation=false, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=lblvs_flags, round=false, nbeta=num_betas, smooth=false) oaspl_blunt, spl_blunt = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=false, turbulent_separation=false, blunt=true, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_tip, spl_tip = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; blunt=false, weighted=false, trip=tripped_flags, tip=true, laminar=false, turbulent_pressure=false, turbulent_suction=false, turbulent_separation=false, round=false, nbeta=num_betas, smooth=false) # Now I'd like to do the narrowband SPL like the Pettingill et al. paper does, instead of 1/3 octave SPL. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # (Dividing the MSP by Ξ”f_pbs aka the 1/3 octave spacing is like getting a power-spectral density, then multiplying by the narrowband spacing Ξ”f_nb gives us the MSP associated with the narrowband.) # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # First, I'll confirm that the frequencies BPM.jl are using are the ApproximateThirdOctaveCenterBands. # This will give me those center bands: cbands_approx3rdcenter = AcousticMetrics.ApproximateThirdOctaveCenterBands(first(BPM.default_f), last(BPM.default_f)) @assert maximum(abs.(BPM.default_f .- cbands_approx3rdcenter)) < 1e-10 # So then I need to get the spacing associated with the proportional bands. # So get the lower and upper "edges" of the bands. freqs_l = AcousticMetrics.lower_bands(cbands_approx3rdcenter) freqs_u = AcousticMetrics.upper_bands(cbands_approx3rdcenter) # And then the spacing for each band. df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing, which is 20 Hz. df_nb = 20.0 # So, if spl = 10*log10(msp/pref^2), and I want to multiply the msp by df_nb/df_pbs, then # # spl_nb = 10*log10((msp*df_nb/df_pbs)/pref^2) = 10*(log10(msp/pref^2) + log10(df_nb/df_pbs)) # spl_nb = 10*log10(msp/pref^2) + 10*log10(df_nb/df_pbs) # spl_nb = spl + 10*log10(df_nb/df_pbs) # # That's easy. spl_nb_pressure = @. spl_pressure + 10*log10(df_nb/df_pbs) spl_nb_suction = @. spl_suction + 10*log10(df_nb/df_pbs) spl_nb_separation = @. spl_separation + 10*log10(df_nb/df_pbs) spl_nb_lblvs = @. spl_lblvs + 10*log10(df_nb/df_pbs) spl_nb_blunt = @. spl_blunt + 10*log10(df_nb/df_pbs) spl_nb_tip = @. spl_tip + 10*log10(df_nb/df_pbs) data["freqs"] = BPM.default_f data["spl_nb_pressure"] = spl_nb_pressure data["spl_nb_suction"] = spl_nb_suction data["spl_nb_separation"] = spl_nb_separation data["spl_nb_lblvs"] = spl_nb_lblvs data["spl_nb_blunt"] = spl_nb_blunt data["spl_nb_tip"] = spl_nb_tip save(joinpath(@__DIR__, "figure23c.jld2"), data) return nothing end function do_figure24b() # Pettingill et al., "Acoustic And Performance Characteristics of an Ideally Twisted Rotor in Hover", 2021 # Parameters from Table 1 B = 4 # number of blades Rtip = 0.1588 # meters chord = 0.2*Rtip # From the first paragraph on page 3, the rotor was designed to produce 11.12 N of thrust. # Using that and the value of the design thrust coefficient in Table 1 to get the density and speed of sound. # omega_target = 5500.0 * (2*pi/60) # thrust_target = 11.12 # Newtons # CT_target = 0.0137 # Mtip_target = 0.27 # asound = omega_target*Rtip/Mtip_target # rho = thrust_target/(CT_target * (pi*Rtip^2) * (omega_target*Rtip)^2) # Standard day: Tamb = 15 + 273.15 # 15Β°C in Kelvin pamb = 101325.0 # Pa R = 287.052874 # J/(kg*K) rho = pamb/(R*Tamb) asound = sqrt(1.4*R*Tamb) # CCBlade.jl defines pitch/collective as "the thing added to the twist to get the orientation of the chord line," but the paper appears to use "the angle of the chord line at the tip." collective0 = 6.9*pi/180 # The Figure 24 caption says Θ_tip = 7 deg, but I think that "actually" means 6.9Β°. # And yes, collective is 0 here, which is a bit silly, I guess, but is consistent with the definition of twist down below. collective = 6.9 .* (pi/180) .- collective0 mu = rho*1.4502e-5 Vinf = 0.001*asound # Figure 24 caption says Ξ©_c = 2938 RPM. rpm = 2938.0 omega = rpm * (2*pi/60) # Get "cell-centered" radial locations. num_radial = 50 r_Rtip_ = range(0.2, 1.0; length=num_radial+1) r_Rtip = 0.5 .* (r_Rtip_[2:end] .+ r_Rtip_[1:end-1]) radii = r_Rtip .* Rtip Rhub = r_Rtip_[1]*Rtip # From Pettingill Equation (1), and value for Θ_tip in Table 1. Θ_tip = 6.9 * pi/180 twist = Θ_tip ./ (r_Rtip) # NACA 0012 airfoil stuff. af_fname = joinpath(@__DIR__, "airfoils", "xf-n0012-il-500000.dat") Re_exp = 0.6 cr75 = chord / Rtip af, mach_correction, reynolds_correction, rotation_correction, tip_correction = get_airfoil(; af_fname, cr75, Re_exp) tip_correction = nothing precone = 0.0 turbine = false rotor = CCBlade.Rotor(Rhub, Rtip, B; precone=precone, turbine=turbine, mach=mach_correction, re=reynolds_correction, rotation=rotation_correction, tip=tip_correction) sections = CCBlade.Section.(radii, chord, twist, Ref(af)) ops = CCBlade.OperatingPoint.(Vinf, omega.*radii, rho, collective, mu, asound) outs = CCBlade.solve.(Ref(rotor), sections, ops) # BPM.jl uses the M_c = 0.8*M assumption from the BPM report, so modify the W field of each CCBlade.Outputs struct to match that. lens = Accessors.@optic _.W outs_bpm_Mc = Accessors.set.(outs, Ref(lens), 0.8.*sqrt.(getproperty.(ops, :Vx).^2 .+ getproperty.(ops, :Vy).^2)) @assert all(getproperty.(outs_bpm_Mc, :W) .β‰ˆ 0.8.*sqrt.(getproperty.(ops, :Vx).^2 .+ getproperty.(ops, :Vy).^2)) # Paper doesn't specify the microphone used for Figure 24, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 24. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane. r_obs = 2.27 # meters theta_obs = -35*pi/180 # So, the docstring for BPM.jl says that `V` argument is the wind velocity in the y direction. # So I guess we should assume that the blades are rotating about the y axis. # And if the freestream velocity is in the positive y axis, then, from the perspective of the fluid, the blades are translating in the negative y direction. # And I want the observer to be downstream/behind the blades, so that would mean they would have a positive y position. # So I want to rotate the observer around the positive x axis, so I'm going to switch the sign on `theta_obs`. t0_obs = 0.0 x0_obs = [0.0, r_obs*sin(-theta_obs), r_obs*cos(-theta_obs)] # Get the components of the observer position in a form that BPM.jl uses. ox = x0_obs[1] oy = x0_obs[2] oz = x0_obs[3] # Radial locations. rs = getproperty.(sections, :r) # BPM.jl docstring says we need the angle of attack in degrees. # But it expects them at the interfaces, not cell centers. alphas_deg = getproperty.(outs_bpm_Mc, :alpha) .* (180/pi) rs_interface = from_cell_centers_to_interfaces(rs) alphas_deg_interface = from_cell_centers_to_interfaces(alphas_deg) # Do the same thing for the chord. # What other inputs do we need? # So the distance from the pitch axis to the leading edge is used, apparently, to locate the trailing edge. # Let's make sure that's true. # Here's the relevant code # # # Calculate the trailing edge position relative to the hub # xs = sin(beta)*d - cos(beta)*(c - c1) # zs = cos(beta)*d + sin(beta)*(c - c1) # # `beta` is an azimuthal angle, and `d` is the radial distance of the blade element relative to the hub. # So let's say that's zero. # Then, I guess, `xs = (c - c1)` and `zs = r` # So it looks like the twist is being ignored, I think. # But, at any rate, if I set c1 = c, that effect is ignored. chords = getproperty.(sections, :chord) chords_interface = from_cell_centers_to_interfaces(chords) c1s = chords_interface # So, for the boundary layer, we want to use untripped for the 95% of the blade from the hub to almost tip, and then tripped for the last 5% of the blade at the tip. # So what are those section indices? num_untripped = Int(round(0.95*num_radial)) num_tripped = num_radial - num_untripped _tripped_flags = vcat(fill(false, num_untripped), fill(true, num_tripped)) @assert length(_tripped_flags) == num_radial # This is working with num_radial, the number of cell-centers, not interfaces. # I think this is the right thing to do though, because it looks like the last value of the `trip` argument is not used by BPM.jl. # But I'll add an extra entry at the end, just to be consistent. tripped_flags = vcat(_tripped_flags, _tripped_flags[end:end]) # In the Figure 24 caption, "for these predictions, bluntness thickness H was set to 0.5 mm and trailing edge angle Ξ¨ was set to 14 degrees." h = 0.5e-3 # meters Psi = 14*pi/180 # radians hs = fill(h, length(rs_interface)) Psis_deg = fill(Psi*180/pi, length(rs_interface)) # Also need kinematic viscosity. nu = mu/rho # Number of azimuthal stations per blade pass, I think. num_betas = 20 # Save the inputs in a dict that we'll write out later. data = Dict( "rho"=>rho, "asound"=>asound, "mu"=>mu, "Vinf"=>Vinf, "omega"=>omega, "B"=>B, "Rhub"=>rotor.Rhub, "Rtip"=>rotor.Rtip, "radii"=>getproperty.(sections, :r), "chord"=>getproperty.(sections, :chord), "twist"=>getproperty.(sections, :theta), "alpha"=>getproperty.(outs, :alpha), "U"=>getproperty.(outs, :W), "hs"=>hs[begin:end-1], "Psis"=>fill(Psi, length(sections)), "tripped_flags"=>tripped_flags[begin:end-1], "num_src_times_blade_pass"=>num_betas) # save(joinpath(@__DIR__, "figure24b-inputs.jld2"), data_inputs) # Now we can start doing the predictions. oaspl_pressure, spl_pressure = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=true, turbulent_suction=false, turbulent_separation=false, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_suction, spl_suction = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=true, turbulent_separation=false, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_separation, spl_separation = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=false, turbulent_separation=true, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_lblvs, spl_lblvs = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=false, turbulent_separation=false, blunt=false, weighted=false, trip=tripped_flags, tip=false, laminar=true, round=false, nbeta=num_betas, smooth=false) oaspl_blunt, spl_blunt = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; turbulent_pressure=false, turbulent_suction=false, turbulent_separation=false, blunt=true, weighted=false, trip=tripped_flags, tip=false, laminar=false, round=false, nbeta=num_betas, smooth=false) oaspl_tip, spl_tip = BPM.sound_pressure_levels( ox, oy, oz, Vinf, omega, B, rs_interface, chords_interface, c1s, hs, alphas_deg_interface, Psis_deg, nu, asound; blunt=false, weighted=false, trip=tripped_flags, tip=true, laminar=false, turbulent_pressure=false, turbulent_suction=false, turbulent_separation=false, round=false, nbeta=num_betas, smooth=false) # Now I'd like to do the narrowband SPL like the Pettingill et al. paper does, instead of 1/3 octave SPL. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # (Dividing the MSP by Ξ”f_pbs aka the 1/3 octave spacing is like getting a power-spectral density, then multiplying by the narrowband spacing Ξ”f_nb gives us the MSP associated with the narrowband.) # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # First, I'll confirm that the frequencies BPM.jl are using are the ApproximateThirdOctaveCenterBands. # This will give me those center bands: cbands_approx3rdcenter = AcousticMetrics.ApproximateThirdOctaveCenterBands(first(BPM.default_f), last(BPM.default_f)) @assert maximum(abs.(BPM.default_f .- cbands_approx3rdcenter)) < 1e-10 # So then I need to get the spacing associated with the proportional bands. # So get the lower and upper "edges" of the bands. freqs_l = AcousticMetrics.lower_bands(cbands_approx3rdcenter) freqs_u = AcousticMetrics.upper_bands(cbands_approx3rdcenter) # And then the spacing for each band. df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing, which is 20 Hz. df_nb = 20.0 # So, if spl = 10*log10(msp/pref^2), and I want to multiply the msp by df_nb/df_pbs, then # # spl_nb = 10*log10((msp*df_nb/df_pbs)/pref^2) = 10*(log10(msp/pref^2) + log10(df_nb/df_pbs)) # spl_nb = 10*log10(msp/pref^2) + 10*log10(df_nb/df_pbs) # spl_nb = spl + 10*log10(df_nb/df_pbs) # # That's easy. spl_nb_pressure = @. spl_pressure + 10*log10(df_nb/df_pbs) spl_nb_suction = @. spl_suction + 10*log10(df_nb/df_pbs) spl_nb_separation = @. spl_separation + 10*log10(df_nb/df_pbs) spl_nb_lblvs = @. spl_lblvs + 10*log10(df_nb/df_pbs) spl_nb_blunt = @. spl_blunt + 10*log10(df_nb/df_pbs) spl_nb_tip = @. spl_tip + 10*log10(df_nb/df_pbs) data["freqs"] = BPM.default_f data["spl_nb_pressure"] = spl_nb_pressure data["spl_nb_suction"] = spl_nb_suction data["spl_nb_separation"] = spl_nb_separation data["spl_nb_lblvs"] = spl_nb_lblvs data["spl_nb_blunt"] = spl_nb_blunt data["spl_nb_tip"] = spl_nb_tip save(joinpath(@__DIR__, "figure24b.jld2"), data) return nothing end function doit() do_figure22b() do_figure23c() do_figure24b() end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
5506
module GenANOPP2Data import ANOPP2, DelimitedFiles using Printf: @sprintf include("gen_ccblade_data/constants.jl") """ get_dradii(radii, Rhub, Rtip) Compute the spacing between blade elements given the radial locations of the element midpoints in `radii` and the hub and tip radius in `Rhub` and `Rtip`, respectively. """ function get_dradii(radii, Rhub, Rtip) # How do I get the radial spacing? Well, for the inner elements, I'll just # assume that the interfaces are midway in between the centers. r_interface = 0.5.*(radii[1:end-1] .+ radii[2:end]) # Then just say that the blade begins at Rhub, and ends at Rtip. r_interface = vcat([Rhub], r_interface, [Rtip]) # And now the distance between interfaces is the spacing. dradii = r_interface[2:end] .- r_interface[1:end-1] return dradii end function omega_sweep_with_acoustics(; stationary_observer, theta) dradii = get_dradii(radii, Rhub, Rtip) cs_area = area_over_chord_squared .* chord.^2 rpm = 200.0:200.0:2200.0 # rev/min for i in eachindex(rpm) omega = rpm[i]*(2*pi/60.0) # Get the normal and circumferential loading from the CCBlade output. data = DelimitedFiles.readdlm("gen_ccblade_data/ccblade_omega$(@sprintf "%02d" i).csv", ',') fn = data[:, 1] fc = data[:, 2] # Calculate the noise with ANOPP2. t_monopole, p_monopole, t_dipole, p_dipole = anopp2_noise(num_blades, v, omega, radii, dradii, chord, fn, fc, stationary_observer, theta) # Check that the two times are the same. max_diff = maximum(abs.(t_monopole .- t_dipole)) if max_diff > 1e-10 msg = """ time vectors associated with the monopole and dipole sources appear to differ" t_monopole = $(t_monopole) t_dipole = $(t_dipole) """ @warn msg end # Write the data. data = hcat(t_monopole, p_monopole, p_dipole) if theta β‰ˆ 0.0 if stationary_observer DelimitedFiles.writedlm("anopp2_omega$(@sprintf "%02d" i).csv", data, ',') else DelimitedFiles.writedlm("anopp2_const_vel_omega$(@sprintf "%02d" i).csv", data, ',') end else theta_int = Int(round(theta*180.0/pi)) if stationary_observer DelimitedFiles.writedlm("anopp2_omega$(@sprintf "%02d" i)_theta$(theta_int).csv", data, ',') else DelimitedFiles.writedlm("anopp2_const_vel_omega$(@sprintf "%02d" i)_theta$(theta_int).csv", data, ',') end end end end function anopp2_noise(num_blades, v, omega, radii, dradii, chord, fn, fc, stationary_observer, theta) num_radial = length(radii) t0 = 0.0 rot_axis = [0.0, 0.0, 1.0] blade_axis = [0.0, 1.0, 0.0] x0 = ANOPP2.A2_RK[cos(theta), 0.0, sin(theta)].*100.0.*12.0.*0.0254 # 100 ft in meters y0_hub = [0.0, 0.0, 0.0] # m v0_hub = v.*rot_axis num_src_times = 256 num_obs_times = 2*num_src_times # Now let's see if I can write out the ANOPP2 data. atm_conf = ANOPP2.writerspy.write_atm_files(density=rho, temperature=c0^2/(gam*R), pressure=rho*c0^2/gam) atm_t = ANOPP2.a2_atm_create(atm_conf) adl_confs = ANOPP2.writerspy.write_adl_files( num_blades=num_blades, num_radial=num_radial, num_src_times=num_src_times, aauc=area_over_chord_squared, omega=omega, radii=radii, dradii=dradii, chord=chord, fn=fn, fc=fc) surf_ts = [ANOPP2.a2_geo_create(adl_conf) for adl_conf in adl_confs] fp_conf = ANOPP2.writerspy.write_flightpath_files(rot_axis=rot_axis, blade_axis=blade_axis, v0_hub=v0_hub, y0_hub=y0_hub) fp_t = ANOPP2.a2_fp_create(fp_conf, atm_t) if stationary_observer # This just says the observer frame of reference is centered at the # global origin, and is not moving. obs_conf = ANOPP2.writerspy.write_observer_files(x=[0.0, 0.0, 0.0], v=[0.0, 0.0, 0.0]) else # This just says the observer frame of reference is centered at the # global origin, and is moving with the same constant velocity as the hub. obs_conf = ANOPP2.writerspy.write_observer_files(x=[0.0, 0.0, 0.0], v=v0_hub) end obs_t = ANOPP2.a2_obs_create(obs_conf) ANOPP2.a2_obs_new_node(obs_t, x0) nnodes = ANOPP2.a2_obs_number_of_nodes(obs_t) f1a_conf = ANOPP2.writerspy.write_f1a_files(num_src_times=num_src_times, num_recep_times=num_obs_times, omega=omega) f1a_input_ts = vcat(surf_ts, atm_t) f1a_t, results_ts = ANOPP2.a2_exec_create_functional_module(f1a_conf, f1a_input_ts, obs_t) ANOPP2.a2_exec_execute_functional_module(f1a_t, atm_t, fp_t) t_monopole = Vector{Float64}[] t_dipole = Vector{Float64}[] p_monopole = Vector{Float64}[] p_dipole = Vector{Float64}[] for (j, results_t) in enumerate(results_ts) time, apth, nltype, cs, ife = ANOPP2.a2_obs_get_apth(obs_t, results_t, 1, 0) name = rstrip(ANOPP2.a2_obs_get_result_name(obs_t, results_t)) if endswith(name, "Monopole") push!(t_monopole, time) push!(p_monopole, apth) elseif endswith(name, "Dipole") push!(t_dipole, time) push!(p_dipole, apth) end end p_monopole_total = p_monopole[1] .+ p_monopole[2] p_dipole_total = p_dipole[1] .+ p_dipole[2] return t_monopole[1], p_monopole_total, t_dipole[1], p_dipole_total end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
2293
module GenCCBladeData using CCBlade: CCBlade using FileIO: save using JLD2: JLD2 using Printf: @sprintf include("constants.jl") include("xrotor_airfoil.jl") # Most of this is taken from <developer.nasa.gov:dingraha/CROTORCCBladeComparisons.jl.git> #' This is the function that will iterate over the RPM values and do the computation. function omega_sweep() #' I ended up extracting and CROTOR airfoil code and using it with CCBlade to make #' sure we're actually doing an "apples-to-apples" comparsion. This is a Julia #' `struct` that holds all the parameters needed for the CROTOR airfoil routine. #' The `af_xrotor` routine takes the `XROTORAirfoilConfig` `struct` and #' an angle of attack, Reynolds number, and Mach number and returns a lift and #' drag coefficient. xrotor_config = XROTORAirfoilConfig( A0=0.0, DCLDA=6.2800, CLMAX=1.5, CLMIN=-0.5, DCLDA_STALL=0.1, DCL_STALL=0.1, MCRIT=0.8, CDMIN=0.13e-1, CLDMIN=0.5, DCDCL2=0.4e-2, REREF=0.2e6, REXP=-0.4) airfoil_interp(a, r, m) = af_xrotor(a, r, m, xrotor_config) theta_rad = CCBladeTestCaseConstants.theta .* pi/180.0 rotor = CCBlade.Rotor(CCBladeTestCaseConstants.Rhub, CCBladeTestCaseConstants.Rtip, CCBladeTestCaseConstants.num_blades) sections = CCBlade.Section.(CCBladeTestCaseConstants.radii, CCBladeTestCaseConstants.chord, theta_rad, airfoil_interp) rpm = 200.0:200.0:2200.0 # rev/min for i in eachindex(rpm) omega = rpm[i]*(2*pi/60.0) ops = CCBlade.OperatingPoint.(CCBladeTestCaseConstants.v, omega.*CCBladeTestCaseConstants.radii, CCBladeTestCaseConstants.rho, CCBladeTestCaseConstants.pitch, CCBladeTestCaseConstants.mu, CCBladeTestCaseConstants.c0) outs = CCBlade.solve.(Ref(rotor), sections, ops) outs_d = Dict{String,Any}(string(f)=>getproperty.(outs, f) for f in fieldnames(eltype(outs))) outs_d["omega"] = omega save("ccblade_omega$(@sprintf "%02d" i)-outputs.jld2", outs_d) # data = DelimitedFiles.readdlm("ccblade_omega$(@sprintf "%02d" i).csv", ',') # @show maximum(abs.(getproperty.(outs, :Np) .- data[:, 1])) # @show maximum(abs.(getproperty.(outs, :Tp) .- data[:, 2])) end return nothing end if ! isinteractive() omega_sweep() end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
1504
module CCBladeTestCaseConstants # Christopher J Miller's (GRC-LTV) CROTOR blade design. const gam = 1.4 const R = 287.058 # J/(kg*K) const rho = 1.226 # kg/m^3 const c0 = 340.0 # m/s const mu = 0.1780e-4 # kg/(m*s) const Rtip = 1.1684 # meters const Rhub = 0.10 # meters const radii = [ 0.92904E-01, 0.11751, 0.15631, 0.20097, 0.24792 , 0.29563, 0.34336, 0.39068, 0.43727 , 0.48291, 0.52741, 0.57060, 0.61234 , 0.65249, 0.69092, 0.72752, 0.76218 , 0.79479, 0.82527, 0.85352, 0.87947 , 0.90303, 0.92415, 0.94275, 0.95880 , 0.97224, 0.98304, 0.99117, 0.99660 , 0.99932].*Rtip const chord = [ 0.35044 , 0.28260 , 0.22105 , 0.17787 , 0.14760, 0.12567 , 0.10927 , 0.96661E-01 , 0.86742E-01 , 0.78783E-01 , 0.72287E-01 , 0.66906E-01 , 0.62387E-01 , 0.58541E-01 , 0.55217E-01 , 0.52290E-01 , 0.49645E-01 , 0.47176E-01 , 0.44772E-01 , 0.42326E-01 , 0.39732E-01 , 0.36898E-01 , 0.33752E-01 , 0.30255E-01 , 0.26401E-01 , 0.22217E-01 , 0.17765E-01 , 0.13147E-01 , 0.85683E-02 , 0.47397E-02].*Rtip const theta = [ 40.005, 34.201, 28.149, 23.753, 20.699, 18.516, 16.890, 15.633, 14.625, 13.795, 13.094, 12.488, 11.956, 11.481, 11.053, 10.662, 10.303, 9.9726, 9.6674, 9.3858, 9.1268, 8.8903, 8.6764, 8.4858, 8.3193, 8.1783, 8.0638, 7.9769, 7.9183, 7.8889, ] # deg const num_blades = 2 const v = 5.0 # m/s const area_over_chord_squared = 0.064 const pitch = 0.0 # rad end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
9104
""" XROTORAirfoilConfig(A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) `struct` that holds all the required parameters for XROTOR's approach to handling airfoil lift and drag polars. # Arguments - `A0`: zero lift angle of attack, radians. - `DCLDA`: lift curve slope, 1/radians. - `CLMAX`: stall Cl. - `CLMIN`: negative stall Cl. - `DCL_STALL`: CL increment from incipient to total stall. - `DCLDA_STALL`: stalled lift curve slope, 1/radian. - `CDMIN`: minimum Cd. - `CLDMIN`: Cl at minimum Cd. - `DCDCL2`: d(Cd)/d(Cl**2). - `REREF`: Reynolds Number at which Cd values apply. - `REXP`: Exponent for Re scaling of Cd: Cd ~ Re**exponent - `MCRIT`: Critical Mach number. """ struct XROTORAirfoilConfig{TF} A0::TF # = 0. # zero lift angle of attack radians DCLDA::TF # = 6.28 # lift curve slope /radian CLMAX::TF # = 1.5 # stall Cl CLMIN::TF # = -0.5 # negative stall Cl DCL_STALL::TF # = 0.1 # CL increment from incipient to total stall DCLDA_STALL::TF # = 0.1 # stalled lift curve slope /radian CDMIN::TF # = 0.013 # minimum Cd CLDMIN::TF # = 0.5 # Cl at minimum Cd DCDCL2::TF # = 0.004 # d(Cd)/d(Cl**2) REREF::TF # = 200000. # Reynolds Number at which Cd values apply REXP::TF # = -0.4 # Exponent for Re scaling of Cd: Cd ~ Re**exponent MCRIT::TF # = 0.8 # Critical Mach number end function XROTORAirfoilConfig(; A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) return XROTORAirfoilConfig(A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) end """ af_xrotor(alpha, Re, Mach, config::XROTORAirfoilConfig) Return a tuple of the lift and drag coefficients for a given angle of attach `alpha` (in radians), Reynolds number `Re`, and Mach number `Mach`. """ function af_xrotor(alpha, Re, Mach, config::XROTORAirfoilConfig) # C------------------------------------------------------------ # C CL(alpha) function # C Note that in addition to setting CLIFT and its derivatives # C CLMAX and CLMIN (+ and - stall CL's) are set in this routine # C In the compressible range the stall CL is reduced by a factor # C proportional to Mcrit-Mach. Stall limiting for compressible # C cases begins when the compressible drag added CDC > CDMstall # C------------------------------------------------------------ # C CD(alpha) function - presently CD is assumed to be a sum # C of profile drag + stall drag + compressibility drag # C In the linear lift range drag is CD0 + quadratic function of CL-CLDMIN # C In + or - stall an additional drag is added that is proportional # C to the extent of lift reduction from the linear lift value. # C Compressible drag is based on adding drag proportional to # C (Mach-Mcrit_eff)^MEXP # C------------------------------------------------------------ # C CM(alpha) function - presently CM is assumed constant, # C varying only with Mach by Prandtl-Glauert scaling # C------------------------------------------------------------ # C # INCLUDE 'XROTOR.INC' # LOGICAL STALLF # DOUBLE PRECISION ECMIN, ECMAX # C # C---- Factors for compressibility drag model, HHY 10/23/00 # C Mcrit is set by user # C Effective Mcrit is Mcrit_eff = Mcrit - CLMFACTOR*(CL-CLDmin) - DMDD # C DMDD is the delta Mach to get CD=CDMDD (usually 0.0020) # C Compressible drag is CDC = CDMFACTOR*(Mach-Mcrit_eff)^MEXP # C CDMstall is the drag at which compressible stall begins # A0 = config.A0 DCLDA = config.DCLDA CLMAX = config.CLMAX CLMIN = config.CLMIN DCL_STALL = config.DCL_STALL DCLDA_STALL = config.DCLDA_STALL CDMIN = config.CDMIN CLDMIN = config.CLDMIN DCDCL2 = config.DCDCL2 REREF = config.REREF REXP = config.REXP MCRIT = config.MCRIT CDMFACTOR = 10.0 CLMFACTOR = 0.25 MEXP = 3.0 CDMDD = 0.0020 CDMSTALL = 0.1000 # C # C---- Prandtl-Glauert compressibility factor # MSQ = W*W*VEL^2/VSO^2 # MSQ_W = 2.0*W*VEL^2/VSO^2 # if (MSQ>1.0) # # WRITE(*,*) # # & 'CLFUNC: Local Mach number limited to 0.99, was ', MSQ # MSQ = 0.99 # # MSQ_W = 0. # end MSQ = Mach*Mach if MSQ > 1.0 MSQ = 0.99 Mach = sqrt(MSQ) end PG = 1.0 / sqrt(1.0 - MSQ) # PG_W = 0.5*MSQ_W * PG^3 # C # C---- Mach number and dependence on velocity # Mach = sqrt(MSQ) # MACH_W = 0.0 # IF(Mach.NE.0.0) MACH_W = 0.5*MSQ_W/Mach # if ! (mach β‰ˆ 0.0) # MACH_W = 0.5*MSQ_W/Mach # end # C # C # C------------------------------------------------------------ # C--- Generate CL from dCL/dAlpha and Prandtl-Glauert scaling CLA = DCLDA*PG *(alpha-A0) # CLA_ALF = DCLDA*PG # CLA_W = DCLDA*PG_W*(ALF-A0) # C # C--- Effective CLmax is limited by Mach effects # C reduces CLmax to match the CL of onset of serious compressible drag CLMX = CLMAX CLMN = CLMIN DMSTALL = (CDMSTALL/CDMFACTOR)^(1.0/MEXP) CLMAXM = max(0.0, (MCRIT+DMSTALL-Mach)/CLMFACTOR) + CLDMIN CLMAX = min(CLMAX,CLMAXM) CLMINM = min(0.0,-(MCRIT+DMSTALL-Mach)/CLMFACTOR) + CLDMIN CLMIN = max(CLMIN,CLMINM) # C # C--- CL limiter function (turns on after +-stall ECMAX = exp( min(200.0, (CLA-CLMAX)/DCL_STALL) ) ECMIN = exp( min(200.0, (CLMIN-CLA)/DCL_STALL) ) CLLIM = DCL_STALL * log( (1.0+ECMAX)/(1.0+ECMIN) ) CLLIM_CLA = ECMAX/(1.0+ECMAX) + ECMIN/(1.0+ECMIN) # c # c if(CLLIM.GT.0.001) then # c write(*,999) 'cla,cllim,ecmax,ecmin ',cla,cllim,ecmax,ecmin # c endif # c 999 format(a,2(1x,f10.6),3(1x,d12.6)) # C # C--- Subtract off a (nearly unity) fraction of the limited CL function # C This sets the dCL/dAlpha in the stalled regions to 1-FSTALL of that # C in the linear lift range FSTALL = DCLDA_STALL/DCLDA CLIFT = CLA - (1.0-FSTALL)*CLLIM # CL_ALF = CLA_ALF - (1.0-FSTALL)*CLLIM_CLA*CLA_ALF # CL_W = CLA_W - (1.0-FSTALL)*CLLIM_CLA*CLA_W # C # STALLF = false # IF(CLIFT.GT.CLMAX) STALLF = .TRUE. # IF(CLIFT.LT.CLMIN) STALLF = .TRUE. # STALLF = (CLIFT > CLMAX) || (CLIFT < CLMIN) # C # C # C------------------------------------------------------------ # C--- CM from CMCON and Prandtl-Glauert scaling # CMOM = PG*CMCON # CM_AL = 0.0 # CM_W = PG_W*CMCON # C # C # C------------------------------------------------------------ # C--- CD from profile drag, stall drag and compressibility drag # C # C---- Reynolds number scaling factor if (Re < 0.0) RCORR = 1.0 # RCORR_REY = 0.0 else RCORR = (Re/REREF)^REXP # RCORR_REY = REXP/Re end # C # C--- In the basic linear lift range drag is a function of lift # C CD = CD0 (constant) + quadratic with CL) CDRAG = (CDMIN + DCDCL2*(CLIFT-CLDMIN)^2 ) * RCORR # CD_ALF = ( 2.0*DCDCL2*(CLIFT-CLDMIN)*CL_ALF) * RCORR # CD_W = ( 2.0*DCDCL2*(CLIFT-CLDMIN)*CL_W ) * RCORR # CD_REY = CDRAG*RCORR_REY # C # C--- Post-stall drag added FSTALL = DCLDA_STALL/DCLDA DCDX = (1.0-FSTALL)*CLLIM/(PG*DCLDA) # c write(*,*) 'cla,cllim,fstall,pg,dclda ',cla,cllim,fstall,pg,dclda DCD = 2.0* DCDX^2 # DCD_ALF = 4.0* DCDX * (1.0-FSTALL)*CLLIM_CLA*CLA_ALF/(PG*DCLDA) # DCD_W = 4.0* DCDX * ( (1.0-FSTALL)*CLLIM_CLA*CLA_W/(PG*DCLDA) - DCD/PG*PG_W ) # c write(*,*) 'alf,cl,dcd,dcd_alf,dcd_w ',alf,clift,dcd,dcd_alf,dcd_w # C # C--- Compressibility drag (accounts for drag rise above Mcrit with CL effects # C CDC is a function of a scaling factor*(M-Mcrit(CL))^MEXP # C DMDD is the Mach difference corresponding to CD rise of CDMDD at MCRIT DMDD = (CDMDD/CDMFACTOR)^(1.0/MEXP) CRITMACH = MCRIT-CLMFACTOR*abs(CLIFT-CLDMIN) - DMDD # CRITMACH_ALF = -CLMFACTOR*ABS(CL_ALF) # CRITMACH_W = -CLMFACTOR*ABS(CL_W) if (Mach < CRITMACH) CDC = 0.0 # CDC_ALF = 0.0 # CDC_W = 0.0 else CDC = CDMFACTOR*(Mach-CRITMACH)^MEXP # CDC_W = MEXP*MACH_W*CDC/Mach - MEXP*CRITMACH_W *CDC/CRITMACH # CDC_ALF = - MEXP*CRITMACH_ALF*CDC/CRITMACH end # c write(*,*) 'critmach,mach ',critmach,mach # c write(*,*) 'cdc,cdc_w,cdc_alf ',cdc,cdc_w,cdc_alf # C FAC = 1.0 # FAC_W = 0.0 # C--- Although test data does not show profile drag increases due to Mach # # C you could use something like this to add increase drag by Prandtl-Glauert # C (or any function you choose) # cc FAC = PG # cc FAC_W = PG_W # C--- Total drag terms CDRAG = FAC*CDRAG + DCD + CDC # CD_ALF = FAC*CD_ALF + DCD_ALF + CDC_ALF # CD_W = FAC*CD_W + FAC_W*CDRAG + DCD_W + CDC_W # CD_REY = FAC*CD_REY # C return CLIFT, CDRAG end
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
11646
module GenWriteVTKTestData using AcousticAnalogies using CCBlade using JLD2: JLD2 """ XROTORAirfoilConfig(A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) `struct` that holds all the required parameters for XROTOR's approach to handling airfoil lift and drag polars. # Arguments - `A0`: zero lift angle of attack, radians. - `DCLDA`: lift curve slope, 1/radians. - `CLMAX`: stall Cl. - `CLMIN`: negative stall Cl. - `DCL_STALL`: CL increment from incipient to total stall. - `DCLDA_STALL`: stalled lift curve slope, 1/radian. - `CDMIN`: minimum Cd. - `CLDMIN`: Cl at minimum Cd. - `DCDCL2`: d(Cd)/d(Cl**2). - `REREF`: Reynolds Number at which Cd values apply. - `REXP`: Exponent for Re scaling of Cd: Cd ~ Re**exponent - `MCRIT`: Critical Mach number. """ struct XROTORAirfoilConfig{TF} A0::TF # = 0. # zero lift angle of attack radians DCLDA::TF # = 6.28 # lift curve slope /radian CLMAX::TF # = 1.5 # stall Cl CLMIN::TF # = -0.5 # negative stall Cl DCL_STALL::TF # = 0.1 # CL increment from incipient to total stall DCLDA_STALL::TF # = 0.1 # stalled lift curve slope /radian CDMIN::TF # = 0.013 # minimum Cd CLDMIN::TF # = 0.5 # Cl at minimum Cd DCDCL2::TF # = 0.004 # d(Cd)/d(Cl**2) REREF::TF # = 200000. # Reynolds Number at which Cd values apply REXP::TF # = -0.4 # Exponent for Re scaling of Cd: Cd ~ Re**exponent MCRIT::TF # = 0.8 # Critical Mach number end function XROTORAirfoilConfig(; A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) return XROTORAirfoilConfig(A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) end """ af_xrotor(alpha, Re, Mach, config::XROTORAirfoilConfig) Return a tuple of the lift and drag coefficients for a given angle of attach `alpha` (in radians), Reynolds number `Re`, and Mach number `Mach`. """ function af_xrotor(alpha, Re, Mach, config::XROTORAirfoilConfig) # C------------------------------------------------------------ # C CL(alpha) function # C Note that in addition to setting CLIFT and its derivatives # C CLMAX and CLMIN (+ and - stall CL's) are set in this routine # C In the compressible range the stall CL is reduced by a factor # C proportional to Mcrit-Mach. Stall limiting for compressible # C cases begins when the compressible drag added CDC > CDMstall # C------------------------------------------------------------ # C CD(alpha) function - presently CD is assumed to be a sum # C of profile drag + stall drag + compressibility drag # C In the linear lift range drag is CD0 + quadratic function of CL-CLDMIN # C In + or - stall an additional drag is added that is proportional # C to the extent of lift reduction from the linear lift value. # C Compressible drag is based on adding drag proportional to # C (Mach-Mcrit_eff)^MEXP # C------------------------------------------------------------ # C CM(alpha) function - presently CM is assumed constant, # C varying only with Mach by Prandtl-Glauert scaling # C------------------------------------------------------------ # C # INCLUDE 'XROTOR.INC' # LOGICAL STALLF # DOUBLE PRECISION ECMIN, ECMAX # C # C---- Factors for compressibility drag model, HHY 10/23/00 # C Mcrit is set by user # C Effective Mcrit is Mcrit_eff = Mcrit - CLMFACTOR*(CL-CLDmin) - DMDD # C DMDD is the delta Mach to get CD=CDMDD (usually 0.0020) # C Compressible drag is CDC = CDMFACTOR*(Mach-Mcrit_eff)^MEXP # C CDMstall is the drag at which compressible stall begins # A0 = config.A0 DCLDA = config.DCLDA CLMAX = config.CLMAX CLMIN = config.CLMIN DCL_STALL = config.DCL_STALL DCLDA_STALL = config.DCLDA_STALL CDMIN = config.CDMIN CLDMIN = config.CLDMIN DCDCL2 = config.DCDCL2 REREF = config.REREF REXP = config.REXP MCRIT = config.MCRIT CDMFACTOR = 10.0 CLMFACTOR = 0.25 MEXP = 3.0 CDMDD = 0.0020 CDMSTALL = 0.1000 # C # C---- Prandtl-Glauert compressibility factor # MSQ = W*W*VEL^2/VSO^2 # MSQ_W = 2.0*W*VEL^2/VSO^2 # if (MSQ>1.0) # # WRITE(*,*) # # & 'CLFUNC: Local Mach number limited to 0.99, was ', MSQ # MSQ = 0.99 # # MSQ_W = 0. # end MSQ = Mach*Mach if MSQ > 1.0 MSQ = 0.99 Mach = sqrt(MSQ) end PG = 1.0 / sqrt(1.0 - MSQ) # PG_W = 0.5*MSQ_W * PG^3 # C # C---- Mach number and dependence on velocity # Mach = sqrt(MSQ) # MACH_W = 0.0 # IF(Mach.NE.0.0) MACH_W = 0.5*MSQ_W/Mach # if ! (mach β‰ˆ 0.0) # MACH_W = 0.5*MSQ_W/Mach # end # C # C # C------------------------------------------------------------ # C--- Generate CL from dCL/dAlpha and Prandtl-Glauert scaling CLA = DCLDA*PG *(alpha-A0) # CLA_ALF = DCLDA*PG # CLA_W = DCLDA*PG_W*(ALF-A0) # C # C--- Effective CLmax is limited by Mach effects # C reduces CLmax to match the CL of onset of serious compressible drag CLMX = CLMAX CLMN = CLMIN DMSTALL = (CDMSTALL/CDMFACTOR)^(1.0/MEXP) CLMAXM = max(0.0, (MCRIT+DMSTALL-Mach)/CLMFACTOR) + CLDMIN CLMAX = min(CLMAX,CLMAXM) CLMINM = min(0.0,-(MCRIT+DMSTALL-Mach)/CLMFACTOR) + CLDMIN CLMIN = max(CLMIN,CLMINM) # C # C--- CL limiter function (turns on after +-stall ECMAX = exp( min(200.0, (CLA-CLMAX)/DCL_STALL) ) ECMIN = exp( min(200.0, (CLMIN-CLA)/DCL_STALL) ) CLLIM = DCL_STALL * log( (1.0+ECMAX)/(1.0+ECMIN) ) CLLIM_CLA = ECMAX/(1.0+ECMAX) + ECMIN/(1.0+ECMIN) # c # c if(CLLIM.GT.0.001) then # c write(*,999) 'cla,cllim,ecmax,ecmin ',cla,cllim,ecmax,ecmin # c endif # c 999 format(a,2(1x,f10.6),3(1x,d12.6)) # C # C--- Subtract off a (nearly unity) fraction of the limited CL function # C This sets the dCL/dAlpha in the stalled regions to 1-FSTALL of that # C in the linear lift range FSTALL = DCLDA_STALL/DCLDA CLIFT = CLA - (1.0-FSTALL)*CLLIM # CL_ALF = CLA_ALF - (1.0-FSTALL)*CLLIM_CLA*CLA_ALF # CL_W = CLA_W - (1.0-FSTALL)*CLLIM_CLA*CLA_W # C # STALLF = false # IF(CLIFT.GT.CLMAX) STALLF = .TRUE. # IF(CLIFT.LT.CLMIN) STALLF = .TRUE. # STALLF = (CLIFT > CLMAX) || (CLIFT < CLMIN) # C # C # C------------------------------------------------------------ # C--- CM from CMCON and Prandtl-Glauert scaling # CMOM = PG*CMCON # CM_AL = 0.0 # CM_W = PG_W*CMCON # C # C # C------------------------------------------------------------ # C--- CD from profile drag, stall drag and compressibility drag # C # C---- Reynolds number scaling factor if (Re < 0.0) RCORR = 1.0 # RCORR_REY = 0.0 else RCORR = (Re/REREF)^REXP # RCORR_REY = REXP/Re end # C # C--- In the basic linear lift range drag is a function of lift # C CD = CD0 (constant) + quadratic with CL) CDRAG = (CDMIN + DCDCL2*(CLIFT-CLDMIN)^2 ) * RCORR # CD_ALF = ( 2.0*DCDCL2*(CLIFT-CLDMIN)*CL_ALF) * RCORR # CD_W = ( 2.0*DCDCL2*(CLIFT-CLDMIN)*CL_W ) * RCORR # CD_REY = CDRAG*RCORR_REY # C # C--- Post-stall drag added FSTALL = DCLDA_STALL/DCLDA DCDX = (1.0-FSTALL)*CLLIM/(PG*DCLDA) # c write(*,*) 'cla,cllim,fstall,pg,dclda ',cla,cllim,fstall,pg,dclda DCD = 2.0* DCDX^2 # DCD_ALF = 4.0* DCDX * (1.0-FSTALL)*CLLIM_CLA*CLA_ALF/(PG*DCLDA) # DCD_W = 4.0* DCDX * ( (1.0-FSTALL)*CLLIM_CLA*CLA_W/(PG*DCLDA) - DCD/PG*PG_W ) # c write(*,*) 'alf,cl,dcd,dcd_alf,dcd_w ',alf,clift,dcd,dcd_alf,dcd_w # C # C--- Compressibility drag (accounts for drag rise above Mcrit with CL effects # C CDC is a function of a scaling factor*(M-Mcrit(CL))^MEXP # C DMDD is the Mach difference corresponding to CD rise of CDMDD at MCRIT DMDD = (CDMDD/CDMFACTOR)^(1.0/MEXP) CRITMACH = MCRIT-CLMFACTOR*abs(CLIFT-CLDMIN) - DMDD # CRITMACH_ALF = -CLMFACTOR*ABS(CL_ALF) # CRITMACH_W = -CLMFACTOR*ABS(CL_W) if (Mach < CRITMACH) CDC = 0.0 # CDC_ALF = 0.0 # CDC_W = 0.0 else CDC = CDMFACTOR*(Mach-CRITMACH)^MEXP # CDC_W = MEXP*MACH_W*CDC/Mach - MEXP*CRITMACH_W *CDC/CRITMACH # CDC_ALF = - MEXP*CRITMACH_ALF*CDC/CRITMACH end # c write(*,*) 'critmach,mach ',critmach,mach # c write(*,*) 'cdc,cdc_w,cdc_alf ',cdc,cdc_w,cdc_alf # C FAC = 1.0 # FAC_W = 0.0 # C--- Although test data does not show profile drag increases due to Mach # # C you could use something like this to add increase drag by Prandtl-Glauert # C (or any function you choose) # cc FAC = PG # cc FAC_W = PG_W # C--- Total drag terms CDRAG = FAC*CDRAG + DCD + CDC # CD_ALF = FAC*CD_ALF + DCD_ALF + CDC_ALF # CD_W = FAC*CD_W + FAC_W*CDRAG + DCD_W + CDC_W # CD_REY = FAC*CD_REY # C return CLIFT, CDRAG end function main() rpm = 2200.0 omega = rpm*(2*pi/60.0) B = 2 Rhub = 0.10 Rtip = 1.1684 # meters # radii = [ # 0.92904E-01, 0.11751, 0.15631, 0.20097, # 0.24792 , 0.29563, 0.34336, 0.39068, # 0.43727 , 0.48291, 0.52741, 0.57060, # 0.61234 , 0.65249, 0.69092, 0.72752, # 0.76218 , 0.79479, 0.82527, 0.85352, # 0.87947 , 0.90303, 0.92415, 0.94275, # 0.95880 , 0.97224, 0.98304, 0.99117, # 0.99660 , 0.99932].*Rtip radii = Rhub .+ range(0.0, 1.0, length=31).*(Rtip - Rhub) radii = 0.5.*(radii[2:end] .+ radii[1:end-1]) cs_area_over_chord_squared = 0.064 chord = [ 0.35044 , 0.28260 , 0.22105 , 0.17787 , 0.14760, 0.12567 , 0.10927 , 0.96661E-01 , 0.86742E-01 , 0.78783E-01 , 0.72287E-01 , 0.66906E-01 , 0.62387E-01 , 0.58541E-01 , 0.55217E-01 , 0.52290E-01 , 0.49645E-01 , 0.47176E-01 , 0.44772E-01 , 0.42326E-01 , 0.39732E-01 , 0.36898E-01 , 0.33752E-01 , 0.30255E-01 , 0.26401E-01 , 0.22217E-01 , 0.17765E-01 , 0.13147E-01 , 0.85683E-02 , 0.47397E-02].*Rtip theta = [ 40.005, 34.201, 28.149, 23.753, 20.699, 18.516, 16.890, 15.633, 14.625, 13.795, 13.094, 12.488, 11.956, 11.481, 11.053, 10.662, 10.303, 9.9726, 9.6674, 9.3858, 9.1268, 8.8903, 8.6764, 8.4858, 8.3193, 8.1783, 8.0638, 7.9769, 7.9183, 7.8889].*(pi/180) rho = 1.226 # kg/m^3 c0 = 340.0 # m/s mu = 0.1780e-4 # kg/(m*s) pitch = 0.0 xrotor_config = XROTORAirfoilConfig( A0=0.0, DCLDA=6.2800, CLMAX=1.5, CLMIN=-0.5, DCLDA_STALL=0.1, DCL_STALL=0.1, MCRIT=0.8, CDMIN=0.13e-1, CLDMIN=0.5, DCDCL2=0.4e-2, REREF=0.2e6, REXP=-0.4) airfoil_interp(a, r, m) = af_xrotor(a, r, m, xrotor_config) rotor = Rotor(Rhub, Rtip, B) sections = Section.(radii, chord, theta, Ref(airfoil_interp)) Vinf = 5.0 # m/s ops = OperatingPoint.(Vinf, omega.*radii, rho, pitch, mu, c0) outs = solve.(Ref(rotor), sections, ops) bpp = 60/(rpm*B) period = 2*bpp num_source_times = 64 ses = source_elements_ccblade(rotor, sections, ops, outs, fill(cs_area_over_chord_squared, length(radii)), period, num_source_times) name = "cf1a" JLD2.jldopen("$(name).jld2", "w") do file file["ses"] = ses end pvd = AcousticAnalogies.to_paraview_collection(name, ses) end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
code
616
module ConvertCF1AData using AcousticAnalogies using JLD2: JLD2 function to_cf1a(se) return CompactF1ASourceElement(se.ρ0, se.c0, se.Ξ”r, se.Ξ›, se.y0dot, se.y1dot, se.y2dot, se.y3dot, se.f0dot, se.f1dot, se.Ο„, se.u) end function doit() ses = nothing JLD2.jldopen(joinpath(@__DIR__, "cf1a-old.jld2"), "r") do file # Renaming CompactSourceElement to CompactF1ASourceElement breaks reconstructing the source elements from the jld2file. ses = to_cf1a.(file["ses"]) end JLD2.jldopen(joinpath(@__DIR__, "cf1a.jld2"), "w") do file file["ses"] = ses end end end # module
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
3190
# AcousticAnalogies.jl Documentation [![Tests](https://github.com/OpenMDAO/AcousticAnalogies.jl/actions/workflows/test.yaml/badge.svg)](https://github.com/OpenMDAO/AcousticAnalogies.jl/actions/workflows/test.yaml) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://OpenMDAO.github.io/AcousticAnalogies.jl/dev) **Summary**: A pure-Julia package for propeller/rotor blade noise prediction with acoustic analogies. **What's an acoustic analogy?** * TL;DR answer: An acoustic analogy is a noise prediction approach that takes information from one area of the fluid domain (e.g., a propeller blade surface, or a fictitious surface surrounding a complicated flow) and calculates the acoustics radiated by the flow. The particular acoustic analogy implemented in `AcousticAnalogies.jl` is especially well-suited for predicting tonal propeller/rotor noise, and has features that ease its inclusion in gradient-based optimizations. * Mathy answer: An acoustic analogy is a clever rearrangement of the Navier-Stokes equations, the governing equations of fluid flow, into a form that looks like the classical inhomogeneous wave equation. The inhomogeneous term represents sources of sound in the flow. The wave equation can be solved using the appropriate [Green's function](https://en.wikipedia.org/wiki/Green%27s_function#Table_of_Green's_functions), which requires the evaluation of two surface integrals and a volume integral (usually neglected). If the integration surface is taken to be a solid surface in the fluid domain (e.g., a propeller blade), we can use the acoustic analogy solution to predict the acoustics caused by the motion of and loading on the integration surface. **Features**: * Implementation of L. Lopes' compact form of Farassat's formulation 1A (see [http://dx.doi.org/10.2514/6.2015-2673](http://dx.doi.org/10.2514/6.2015-2673) or [http://dx.doi.org/10.2514/1.C034048](http://dx.doi.org/10.2514/1.C034048) for details). * Implementation of Brooks & Burley's rotor broadband noise prediction method [http://dx.doi.org/10.2514/6.2001-2210](http://dx.doi.org/10.2514/6.2001-2210). * Support for stationary or constant-velocity moving observers, with an explict calculation for the latter from D. Casalino [http://dx.doi.org/10.1016/S0022-460X(02)00986-0](http://dx.doi.org/10.1016/S0022-460X(02)00986-0). * Thoroughly tested: unit tests for everything, and multiple comparisons of the entire calculation to equivalent methods in NASA's ANOPP2 code. * Convenient, fast coordinate system transformations through [KinematicCoordinateTransformations.jl](https://github.com/OpenMDAO/KinematicCoordinateTransformations.jl). * Written in pure Julia, and compatible with automatic differentiation (AD) tools like [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl). * Comprehensive docs (TODO). * Fast! **Installation** ```julia-repl ] add AcousticAnalogies ``` **Usage** See the docs. # Software Quality Assurance * This repository contains extensive tests run by GitHub Actions. * This repository only allows signed commits to be merged into the `main` branch.
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
100
```@meta CurrentModule = AADocs ``` # API Reference ```@autodocs Modules = [AcousticAnalogies] ```
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
23595
```@meta CurrentModule = AADocs ``` # Software Quality Assurance, Cont. ## Brooks, Pope, and Marcolini Airfoil Self-Noise Tests The [Brooks, Pope, and Marcolini (BPM) report on airfoil self-noise](https://ntrs.nasa.gov/citations/19890016302) forms the basis of the [Brooks and Burley broadband noise modeling approach](https://doi.org/10.2514/6.2001-2210) that is implemented in AcousticAnalogies.jl. ### Boundary Layer Tests ```@example bpm_bl_thickness using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles # using FLOWMath: linear using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Re_c/10^6", ylabel="Ξ΄_0/c", xscale=log10, yscale=log10, xminorticksvisible=true, yminorticksvisible=true, xminorticks=IntervalsBetween(9), yminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), yticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure06-bl_thickness-tripped.csv") bpm_tripped = DelimitedFiles.readdlm(fname, ',') Re_c_1e6 = bpm_tripped[:, 1] deltastar0_c = bpm_tripped[:, 2] scatter!(ax1, Re_c_1e6, deltastar0_c, markersize=4, label="tripped, BPM report", color=colors[1]) Re_c_1e6_jl = range(minimum(Re_c_1e6), maximum(Re_c_1e6); length=50) deltastar0_c_jl = AcousticAnalogies.bl_thickness_0.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), Re_c_1e6_jl.*1e6) lines!(ax1, Re_c_1e6_jl, deltastar0_c_jl, label="tripped, Julia", color=colors[1]) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure06-bl_thickness-untripped.csv") bpm_untripped = DelimitedFiles.readdlm(fname, ',') Re_c_1e6 = bpm_untripped[:, 1] deltastar0_c = bpm_untripped[:, 2] scatter!(ax1, Re_c_1e6, deltastar0_c, markersize=4, label="untripped, BPM report", color=colors[2]) Re_c_1e6_jl = range(minimum(Re_c_1e6), maximum(Re_c_1e6); length=50) deltastar0_c_jl = AcousticAnalogies.bl_thickness_0.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), Re_c_1e6_jl.*1e6) lines!(ax1, Re_c_1e6_jl, deltastar0_c_jl, label="untripped, Julia", color=colors[2]) xlims!(ax1, 0.04, 3) ylims!(ax1, 0.01, 0.2) axislegend(ax1) save("19890016302-figure06-bl_thickness.png", fig) ``` ![](19890016302-figure06-bl_thickness.png) ```@example bpm_disp_thickness using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Re_c/10^6", ylabel="Ξ΄_0^*/c", xscale=log10, yscale=log10, xminorticksvisible=true, yminorticksvisible=true, xminorticks=IntervalsBetween(9), yminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), yticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure06-disp_thickness-tripped.csv") bpm_tripped = DelimitedFiles.readdlm(fname, ',') Re_c_1e6 = bpm_tripped[:, 1] deltastar0_c = bpm_tripped[:, 2] scatter!(ax1, Re_c_1e6, deltastar0_c, markersize=4, label="tripped, BPM report", color=colors[1]) Re_c_1e6_jl = range(minimum(Re_c_1e6), maximum(Re_c_1e6); length=50) deltastar0_c_jl = AcousticAnalogies.disp_thickness_0.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), Re_c_1e6_jl.*1e6) lines!(ax1, Re_c_1e6_jl, deltastar0_c_jl, label="tripped, Julia", color=colors[1]) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure06-disp_thickness-untripped.csv") bpm_untripped = DelimitedFiles.readdlm(fname, ',') Re_c_1e6 = bpm_untripped[:, 1] deltastar0_c = bpm_untripped[:, 2] scatter!(ax1, Re_c_1e6, deltastar0_c, markersize=4, label="untripped, BPM report", color=colors[2]) Re_c_1e6_jl = range(minimum(Re_c_1e6), maximum(Re_c_1e6); length=50) deltastar0_c_jl = AcousticAnalogies.disp_thickness_0.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), Re_c_1e6_jl.*1e6) lines!(ax1, Re_c_1e6_jl, deltastar0_c_jl, label="untripped, Julia", color=colors[2]) xlims!(ax1, 0.04, 3) ylims!(ax1, 0.001, 0.03) axislegend(ax1) save("19890016302-figure06-disp_thickness.png", fig) ``` ![](19890016302-figure06-disp_thickness.png) ```@example bpm_bl_thickness_tripped using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="alpha, deg.", ylabel="Ξ΄/Ξ΄_0", yscale=log10, yminorticksvisible=true, yminorticks=IntervalsBetween(9), yticks=LogTicks(IntegerTicks()) ) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure07-bl_thickness-pressure_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] delta_bpm = bpm_pressure_side[:, 2] scatter!(ax1, alpha_deg, delta_bpm, color=colors[1], markersize=4, label="pressure side, BPM report") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) delta_jl = AcousticAnalogies._bl_thickness_p.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, delta_jl; color=colors[1], label="pressure side, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure07-bl_thickness-suction_side.csv") bpm_suction_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_suction_side[:, 1] delta_bpm = bpm_suction_side[:, 2] scatter!(ax1, alpha_deg, delta_bpm, markersize=4, color=colors[2], label="suction side, BPM report") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) delta_jl = AcousticAnalogies._bl_thickness_s.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, delta_jl; color=colors[2], label="suction side, Julia") xlims!(ax1, 0, 25) ylims!(ax1, 0.2, 20) axislegend(ax1, position=:lt) save("19890016302-figure07-bl_thickness.png", fig) ``` ![](19890016302-figure07-bl_thickness.png) ```@example bpm_disp_thickness_star_tripped using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="alpha, deg.", ylabel="Ξ΄^*/Ξ΄_0^*", yscale=log10, yminorticksvisible=true, yminorticks=IntervalsBetween(9), yticks=LogTicks(IntegerTicks()) ) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure07-pressure_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] deltastar_bpm = bpm_pressure_side[:, 2] scatter!(ax1, alpha_deg, deltastar_bpm, color=colors[1], markersize=4, label="pressure side, BPM report") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._disp_thickness_p.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, deltastar_jl; color=colors[1], label="pressure side, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure07-suction_side.csv") bpm_suction_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_suction_side[:, 1] deltastar_bpm = bpm_suction_side[:, 2] scatter!(ax1, alpha_deg, deltastar_bpm, markersize=4, color=colors[2], label="suction side, BPM report") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._disp_thickness_s.(Ref(AcousticAnalogies.TrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, deltastar_jl; color=colors[2], label="suction side, Julia") xlims!(ax1, 0, 25) ylims!(ax1, 0.2, 200) axislegend(ax1, position=:lt) save("19890016302-figure07.png", fig) ``` ![](19890016302-figure07.png) ```@example bpm_bl_thickness_untripped using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="alpha, deg.", ylabel="Ξ΄/Ξ΄_0", yscale=log10, yminorticksvisible=true, yminorticks=IntervalsBetween(9), yticks=LogTicks(IntegerTicks()) ) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure08-bl_thickness-pressure_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] deltastar_bpm = bpm_pressure_side[:, 2] scatter!(ax1, alpha_deg, deltastar_bpm, color=colors[1], markersize=4, label="pressure side, BPM report") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._bl_thickness_p.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, deltastar_jl; color=colors[1], label="pressure side, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure08-bl_thickness-suction_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] deltastar_bpm = bpm_pressure_side[:, 2] scatter!(ax1, alpha_deg, deltastar_bpm, color=colors[2], markersize=4, label="suction side, BPM report") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._bl_thickness_s.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, deltastar_jl; color=colors[2], label="suction side, Julia") xlims!(ax1, 0, 25) ylims!(ax1, 0.2, 40) axislegend(ax1, position=:lt) save("19890016302-figure08-bl_thickness.png", fig) ``` ![](19890016302-figure08-bl_thickness.png) ```@example bpm_disp_thickness_star_untripped using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="alpha, deg.", ylabel="Ξ΄^*/Ξ΄_0^*", yscale=log10, yminorticksvisible=true, yminorticks=IntervalsBetween(9), yticks=LogTicks(IntegerTicks()) ) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure08-pressure_side.csv") bpm_pressure_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_pressure_side[:, 1] deltastar_bpm = bpm_pressure_side[:, 2] scatter!(ax1, alpha_deg, deltastar_bpm, color=colors[1], markersize=4, label="pressure side, BPM report") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._disp_thickness_p.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, deltastar_jl; color=colors[1], label="pressure side, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure08-suction_side.csv") bpm_suction_side = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm_suction_side[:, 1] deltastar_bpm = bpm_suction_side[:, 2] scatter!(ax1, alpha_deg, deltastar_bpm, markersize=4, color=colors[2], label="suction side, BPM report") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) deltastar_jl = AcousticAnalogies._disp_thickness_s.(Ref(AcousticAnalogies.UntrippedN0012BoundaryLayer()), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, deltastar_jl; color=colors[2], label="suction side, Julia") xlims!(ax1, 0, 25) ylims!(ax1, 0.2, 200) axislegend(ax1, position=:lt) save("19890016302-figure08.png", fig) ``` ![](19890016302-figure08.png) ### Turbulent Boundary Layer-Trailing Edge Shape Function Tests ```@example bpm_K_1 using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Re_c", ylabel="Peak scaled SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure77.csv") bpm = DelimitedFiles.readdlm(fname, ',') Re_c_bpm = bpm[:, 1] K_1_bpm = bpm[:, 2] scatter!(ax1, Re_c_bpm, K_1_bpm, color=colors[1], markersize=8, label="BPM report") Re_c_jl = range(minimum(Re_c_bpm), maximum(Re_c_bpm); length=50) K_1_jl = AcousticAnalogies.K_1.(Re_c_jl) lines!(ax1, Re_c_jl, K_1_jl, color=colors[1], label="Julia") xlims!(ax1, 10^4, 10^7) ylims!(ax1, 110.0, 150.0) axislegend(ax1, position=:lt) save("19890016302-figure77.png", fig) ``` ![](19890016302-figure77.png) ```@example bpm_A using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Strouhal number ratio, St/St_peak", ylabel="Function A level, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure78-A_min.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_St_peak_bpm = bpm[:, 1] A = bpm[:, 2] scatter!(ax1, St_St_peak_bpm, A, color=colors[1], markersize=8, label="A_min, BPM report") St_St_peak_jl = range(minimum(St_St_peak_bpm), maximum(St_St_peak_bpm); length=50) A_jl = AcousticAnalogies.A.(St_St_peak_jl, 9.5e4) lines!(ax1, St_St_peak_jl, A_jl, color=colors[1], label="A_min, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure78-A_max.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_St_peak_bpm = bpm[:, 1] A = bpm[:, 2] scatter!(ax1, St_St_peak_bpm, A, color=colors[2], markersize=8, label="A_max, BPM report") St_St_peak_jl = range(minimum(St_St_peak_bpm), maximum(St_St_peak_bpm); length=50) A_jl = AcousticAnalogies.A.(St_St_peak_jl, 8.58e5) lines!(ax1, St_St_peak_jl, A_jl, color=colors[2], label="A_max, Julia") xlims!(ax1, 0.1, 20) ylims!(ax1, -20.0, 0.0) axislegend(ax1, position=:lt) save("19890016302-figure78-A.png", fig) ``` ![](19890016302-figure78-A.png) ```@example bpm_B using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Strouhal number ratio, St/St_peak", ylabel="Function B level, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure78-B_min.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_St_peak_bpm = bpm[:, 1] B = bpm[:, 2] scatter!(ax1, St_St_peak_bpm, B, color=colors[1], markersize=8, label="B_min, BPM report") St_St_peak_jl = range(0.5, 2; length=50) B_jl = AcousticAnalogies.B.(St_St_peak_jl, 9.5e4) lines!(ax1, St_St_peak_jl, B_jl, color=colors[1], label="B_min, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure78-B_max.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_St_peak_bpm = bpm[:, 1] B = bpm[:, 2] scatter!(ax1, St_St_peak_bpm, B, color=colors[2], markersize=8, label="B_max, BPM report") St_St_peak_jl = range(0.2, 4; length=50) B_jl = AcousticAnalogies.B.(St_St_peak_jl, 8.58e5) lines!(ax1, St_St_peak_jl, B_jl, color=colors[2], label="B_max, Julia") xlims!(ax1, 0.1, 20) ylims!(ax1, -20.0, 0.0) axislegend(ax1, position=:lt) save("19890016302-figure78-B.png", fig) ``` ![](19890016302-figure78-B.png) ```@example bpm_St_2 using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Angle of attack Ξ±^*, deg", ylabel="Peak Strouhal number, St_peak", yscale=log10, yminorticksvisible=true, yminorticks=IntervalsBetween(9), yticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure80-M0.093.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] St_2 = bpm[:, 2] scatter!(ax1, alpha_deg, St_2, color=colors[1], markersize=8, label="St_2 for M = 0.093, BPM") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) St_2_jl = AcousticAnalogies.St_2.(AcousticAnalogies.St_1(0.093), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, St_2_jl, color=colors[1], label="St_2 for M = 0.093, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure80-M0.209.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] St_2 = bpm[:, 2] scatter!(ax1, alpha_deg, St_2, color=colors[2], markersize=8, label="St_2 for M = 0.209, BPM") alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=50) St_2_jl = AcousticAnalogies.St_2.(AcousticAnalogies.St_1(0.209), alpha_deg_jl.*pi/180) lines!(ax1, alpha_deg_jl, St_2_jl, color=colors[2], label="St_2 for M = 0.209, Julia") xlims!(ax1, 0.0, 25.0) ylims!(ax1, 0.01, 1) axislegend(ax1, position=:lt) save("19890016302-figure80.png", fig) ``` ![](19890016302-figure80.png) ```@example bpm_K_2_K_1 using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Angle of attack Ξ±_*, deg", ylabel="Extracted scaled levels minus K_1, dB") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure82-M0.093.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] K_2_K_1 = bpm[:, 2] scatter!(ax1, alpha_deg, K_2_K_1, color=colors[1], markersize=8, label="M = 0.093, BPM", marker='o') alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=200) K_2_K_1_jl = AcousticAnalogies.K_2.(1e6, 0.093, alpha_deg_jl.*pi/180) .- AcousticAnalogies.K_1(1e6) lines!(ax1, alpha_deg_jl, K_2_K_1_jl, color=colors[1], label="M = 0.093, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure82-M0.116.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] K_2_K_1 = bpm[:, 2] scatter!(ax1, alpha_deg, K_2_K_1, color=colors[2], markersize=8, label="M = 0.116, BPM", marker='o') alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=200) K_2_K_1_jl = AcousticAnalogies.K_2.(1e6, 0.116, alpha_deg_jl.*pi/180) .- AcousticAnalogies.K_1(1e6) lines!(ax1, alpha_deg_jl, K_2_K_1_jl, color=colors[2], label="M = 0.116, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure82-M0.163.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] K_2_K_1 = bpm[:, 2] scatter!(ax1, alpha_deg, K_2_K_1, color=colors[3], markersize=8, label="M = 0.163, BPM", marker='o') alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=200) K_2_K_1_jl = AcousticAnalogies.K_2.(1e6, 0.163, alpha_deg_jl.*pi/180) .- AcousticAnalogies.K_1(1e6) lines!(ax1, alpha_deg_jl, K_2_K_1_jl, color=colors[3], label="M = 0.163, Julia") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure82-M0.209.csv") bpm = DelimitedFiles.readdlm(fname, ',') alpha_deg = bpm[:, 1] K_2_K_1 = bpm[:, 2] scatter!(ax1, alpha_deg, K_2_K_1, color=colors[4], markersize=8, label="M = 0.209, BPM", marker='o') alpha_deg_jl = range(minimum(alpha_deg), maximum(alpha_deg); length=200) K_2_K_1_jl = AcousticAnalogies.K_2.(1e6, 0.209, alpha_deg_jl.*pi/180) .- AcousticAnalogies.K_1(1e6) lines!(ax1, alpha_deg_jl, K_2_K_1_jl, color=colors[4], label="M = 0.209, Julia") xlims!(ax1, 0.0, 25.0) ylims!(ax1, -20, 20) axislegend(ax1, position=:lt) save("19890016302-figure82.png", fig) ``` ![](19890016302-figure82.png)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
21656
```@meta CurrentModule = AADocs ``` # Software Quality Assurance, Cont. ## Brooks, Pope, and Marcolini Airfoil Self-Noise Tests, Cont. ### Laminar Boundary Layer-Vortex Shedding Tests ```@example bpm_St_1_prime using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles # using FLOWMath: linear using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Re_c", ylabel="Peak Strouhal number, St'_peak", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), yscale=log10, yminorticksvisible=true, yminorticks=IntervalsBetween(9), yticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure86-St_1_prime.csv") bpm = DelimitedFiles.readdlm(fname, ',') Re_c_bpm = bpm[:, 1] St_1_prime_bpm = bpm[:, 2] scatter!(ax1, Re_c_bpm, St_1_prime_bpm, color=colors[1], markersize=4, label="BPM") Re_c_jl = 10.0.^(range(4, 7; length=100)) St_1_prime_jl = AcousticAnalogies.St_1_prime.(Re_c_jl) lines!(ax1, Re_c_jl, St_1_prime_jl, color=colors[1], label="Julia") xlims!(ax1, 1e4, 1e7) ylims!(ax1, 0.01, 1) axislegend(ax1, position=:lt) save("19890016302-figure86.png", fig) ``` ![](19890016302-figure86.png) ```@example bpm_lbl_vs_G1 using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles # using FLOWMath: linear using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="St'/St'_peak", ylabel="Function G_1 level, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure85-G1.csv") bpm = DelimitedFiles.readdlm(fname, ',') e_bpm = bpm[:, 1] G1_bpm = bpm[:, 2] scatter!(ax1, e_bpm, G1_bpm, color=colors[1], markersize=4, label="BPM") e_jl = 10.0.^(range(-1, 1; length=101)) G1_jl = AcousticAnalogies.G1.(e_jl) lines!(ax1, e_jl, G1_jl, color=colors[1], label="Julia") xlims!(ax1, 0.1, 10) ylims!(ax1, -30, 0) axislegend(ax1, position=:lt) save("19890016302-figure85.png", fig) ``` ![](19890016302-figure85.png) ```@example bpm_lbl_vs_St_peak_prime_alphastar using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles # using FLOWMath: linear using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="alpha^*, deg", ylabel="St'_peak/St'_1", yscale=log10, yminorticksvisible=true, yminorticks=IntervalsBetween(9), yticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure87.csv") bpm = DelimitedFiles.readdlm(fname, ',') alphastar_bpm = bpm[:, 1] St_peak_ratio_bpm = bpm[:, 2] scatter!(ax1, alphastar_bpm, St_peak_ratio_bpm, color=colors[1], markersize=4, label="BPM") St_1_prime = 0.25 # Just make up a value, since we're multiplying and then dividing by it anyway. alphastar_jl = range(0.0*pi/180, 7.0*pi/180; length=21) St_peak_ratio_jl = AcousticAnalogies.St_peak_prime.(St_1_prime, alphastar_jl)./St_1_prime lines!(ax1, alphastar_jl.*180/pi, St_peak_ratio_jl, color=colors[1], label="Julia") xlims!(ax1, 0, 7) ylims!(ax1, 0.5, 2) axislegend(ax1, position=:lt) save("19890016302-figure87.png", fig) ``` ![](19890016302-figure87.png) ```@example bpm_lbl_vs_G2_alphastar using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles # using FLOWMath: linear using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Re_c/Re_c0", ylabel="G2 + G3", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure88-G2-alpha0.csv") alphastar = 0.0*pi/180 bpm = DelimitedFiles.readdlm(fname, ',') Re_c_bpm = bpm[:, 1] G2_bpm = bpm[:, 2] scatter!(ax1, Re_c_bpm, G2_bpm, color=colors[1], markersize=4, label="BPM - Ξ±^* = $(alphastar*180/pi)Β°") Re_c_jl = 10.0.^range(log10(first(Re_c_bpm)), log10(last(Re_c_bpm)), length=51) Re_c0 = AcousticAnalogies.Re_c0(alphastar) Re_ratio_jl = Re_c_jl./Re_c0 # G2_jl = AcousticAnalogies.G2.(Re_ratio_jl) .+ 171.04 .- 3.03*(alphastar*180/pi) G2_jl = AcousticAnalogies.G2.(Re_ratio_jl) .+ AcousticAnalogies.G3.(alphastar) lines!(ax1, Re_c_jl, G2_jl, color=colors[1], label="Julia - Ξ±^* = $(alphastar*180/pi)Β°") fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure88-G2-alpha6.csv") alphastar = 6.0*pi/180 bpm = DelimitedFiles.readdlm(fname, ',') Re_c_bpm = bpm[:, 1] G2_bpm = bpm[:, 2] scatter!(ax1, Re_c_bpm, G2_bpm, color=colors[2], markersize=4, label="BPM - Ξ±^* = $(alphastar*180/pi)Β°") Re_c_jl = 10.0.^range(log10(first(Re_c_bpm)), log10(last(Re_c_bpm)), length=51) Re_c0 = AcousticAnalogies.Re_c0(alphastar) Re_ratio_jl = Re_c_jl./Re_c0 # G2_jl = AcousticAnalogies.G2.(Re_ratio_jl) .+ 171.04 .- 3.03*(alphastar*180/pi) G2_jl = AcousticAnalogies.G2.(Re_ratio_jl) .+ AcousticAnalogies.G3.(alphastar) lines!(ax1, Re_c_jl, G2_jl, color=colors[2], label="Julia - Ξ±^* = $(alphastar*180/pi)Β°") xlims!(ax1, 10^4, 10^7) ylims!(ax1, 125, 175) axislegend(ax1, position=:lt) save("19890016302-figure88.png", fig) ``` ![](19890016302-figure88.png) ```@example bpm_lbl_vs_G2 using AcousticAnalogies: AcousticAnalogies using ColorSchemes: colorschemes using DelimitedFiles: DelimitedFiles # using FLOWMath: linear using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) colors = colorschemes[:tab10] fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Re_c/Re_c0", ylabel="G2", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks())) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure89.csv") bpm = DelimitedFiles.readdlm(fname, ',') Re_ratio_bpm = bpm[:, 1] G2_bpm = bpm[:, 2] scatter!(ax1, Re_ratio_bpm, G2_bpm, color=colors[1], markersize=4, label="BPM") Re_ratio_jl = 10.0.^range(-1, 1, length=51) G2_jl = AcousticAnalogies.G2.(Re_ratio_jl) lines!(ax1, Re_ratio_jl, G2_jl, color=colors[1], label="Julia") xlims!(ax1, 0.1, 100) ylims!(ax1, -45, 5) axislegend(ax1, position=:lt) save("19890016302-figure89.png", fig) ``` ![](19890016302-figure89.png) ### Trailing Edge Bluntness-Vortex Shedding Tests ```@example bpm_figure95 using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure95-0Psi.csv") bpm = DelimitedFiles.readdlm(fname, ',') h_over_deltastar_0Psi = bpm[:, 1] St_3prime_peak_0Psi = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure95-14Psi.csv") bpm = DelimitedFiles.readdlm(fname, ',') h_over_deltastar_14Psi = bpm[:, 1] St_3prime_peak_14Psi = bpm[:, 2] h_over_deltastar_jl = 10.0.^(range(-1, 1; length=51)) St_3prime_peak_0Psi_jl = AcousticAnalogies.St_3prime_peak.(h_over_deltastar_jl, 0.0*pi/180) St_3prime_peak_14Psi_jl = AcousticAnalogies.St_3prime_peak.(h_over_deltastar_jl, 14.0*pi/180) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Thickness ratio, h/Ξ΄^*", ylabel="Peak Strouhal number, St'''_peak", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), yscale=log10, yminorticksvisible=true, yminorticks=IntervalsBetween(9), yticks=LogTicks(IntegerTicks()), title="Figure 95") scatter!(ax1, h_over_deltastar_0Psi, St_3prime_peak_0Psi; marker='o', label="Ξ¨ = 0Β°, BPM") lines!(ax1, h_over_deltastar_jl, St_3prime_peak_0Psi_jl; label="Ξ¨ = 0Β°, Julia") scatter!(ax1, h_over_deltastar_14Psi, St_3prime_peak_14Psi; marker='o', label="Ξ¨ = 14Β°, BPM") lines!(ax1, h_over_deltastar_jl, St_3prime_peak_14Psi_jl; label="Ξ¨ = 14Β°, Julia") xlims!(ax1, 0.2, 10.0) ylims!(ax1, 0.05, 0.3) axislegend(ax1, position=:rt) save("19890016302-figure95.png", fig) ``` ![](19890016302-figure95.png) ```@example bpm_figure96 using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure96-0Psi.csv") bpm = DelimitedFiles.readdlm(fname, ',') h_over_deltastar_0Psi = bpm[:, 1] G4_0Psi = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure96-14Psi.csv") bpm = DelimitedFiles.readdlm(fname, ',') h_over_deltastar_14Psi = bpm[:, 1] G4_14Psi = bpm[:, 2] h_over_deltastar_jl = 10.0.^(range(-1, 1; length=51)) G4_0Psi_jl = AcousticAnalogies.G4.(h_over_deltastar_jl, 0.0*pi/180) G4_14Psi_jl = AcousticAnalogies.G4.(h_over_deltastar_jl, 14.0*pi/180) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Thickness ratio, h/Ξ΄^*", ylabel="Scaled peak SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 96") scatter!(ax1, h_over_deltastar_0Psi, G4_0Psi; marker='o', label="Ξ¨ = 0Β°, BPM") lines!(ax1, h_over_deltastar_jl, G4_0Psi_jl; label="Ξ¨ = 0Β°, Julia") scatter!(ax1, h_over_deltastar_14Psi, G4_14Psi; marker='o', label="Ξ¨ = 14Β°, BPM") lines!(ax1, h_over_deltastar_jl, G4_14Psi_jl; label="Ξ¨ = 14Β°, Julia") xlims!(ax1, 0.1, 10.0) ylims!(ax1, 110, 180) axislegend(ax1, position=:lt) save("19890016302-figure96.png", fig) ``` ![](19890016302-figure96.png) ```@example bpm_figure97a using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p25.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p25 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p25 = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p43.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p43 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p43 = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p50.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p50 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p50 = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p54.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p54 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p54 = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar0p62.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p62 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg0p62 = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi14-h_over_deltastar1p20.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_1p20 = bpm[:, 1] G5_14Psi_h_over_deltastar_avg1p20 = bpm[:, 2] St_3prime_over_St_3prime_peak_jl = 10.0.^(range(-1, 10; length=1001)) G5_14Psi_h_over_deltastar_avg0p25_jl = AcousticAnalogies.G5_Psi14.(0.25, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg0p43_jl = AcousticAnalogies.G5_Psi14.(0.43, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg0p50_jl = AcousticAnalogies.G5_Psi14.(0.50, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg0p54_jl = AcousticAnalogies.G5_Psi14.(0.54, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg0p62_jl = AcousticAnalogies.G5_Psi14.(0.62, St_3prime_over_St_3prime_peak_jl) G5_14Psi_h_over_deltastar_avg1p20_jl = AcousticAnalogies.G5_Psi14.(1.20, St_3prime_over_St_3prime_peak_jl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Strouhal ratio, St'''/St'''_peak", ylabel="G_5, Ξ¨=14Β°", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 97a") scatter!(ax1, St_3prime_over_St_3prime_peak_0p25, G5_14Psi_h_over_deltastar_avg0p25; label="h/Ξ΄^* = 0.25, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p25_jl; label="h/Ξ΄^* = 0.25, Julia") scatter!(ax1, St_3prime_over_St_3prime_peak_0p43, G5_14Psi_h_over_deltastar_avg0p43; label="h/Ξ΄^* = 0.43, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p43_jl; label="h/Ξ΄^* = 0.43, Julia") scatter!(ax1, St_3prime_over_St_3prime_peak_0p50, G5_14Psi_h_over_deltastar_avg0p50; label="h/Ξ΄^* = 0.50, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p50_jl; label="h/Ξ΄^* = 0.50, Julia") scatter!(ax1, St_3prime_over_St_3prime_peak_0p54, G5_14Psi_h_over_deltastar_avg0p54; label="h/Ξ΄^* = 0.54, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p54_jl; label="h/Ξ΄^* = 0.54, Julia") scatter!(ax1, St_3prime_over_St_3prime_peak_0p62, G5_14Psi_h_over_deltastar_avg0p62; label="h/Ξ΄^* = 0.62, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg0p62_jl; label="h/Ξ΄^* = 0.62, Julia") scatter!(ax1, St_3prime_over_St_3prime_peak_1p20, G5_14Psi_h_over_deltastar_avg1p20; label="h/Ξ΄^* = 1.20, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_14Psi_h_over_deltastar_avg1p20_jl; label="h/Ξ΄^* = 1.20, Julia") xlims!(ax1, 0.1, 10.0) ylims!(ax1, -30, 10) axislegend(ax1, position=:rt) save("19890016302-figure97a.png", fig) ``` ![](19890016302-figure97a.png) ```@example bpm_figure97b using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p25.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p25 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg0p25 = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p43.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p43 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg0p43 = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p50.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p50 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg0p50 = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p54.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_0p54 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg0p54 = bpm[:, 2] # fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar0p62.csv") # bpm = DelimitedFiles.readdlm(fname, ',') # St_3prime_over_St_3prime_peak_0p62 = bpm[:, 1] # G5_0Psi_h_over_deltastar_avg0p62 = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure97-Psi0-h_over_deltastar1p20.csv") bpm = DelimitedFiles.readdlm(fname, ',') St_3prime_over_St_3prime_peak_1p20 = bpm[:, 1] G5_0Psi_h_over_deltastar_avg1p20 = bpm[:, 2] St_3prime_over_St_3prime_peak_jl = 10.0.^(range(-1, 10; length=1001)) G5_0Psi_h_over_deltastar_avg0p25_jl = AcousticAnalogies.G5_Psi0.(0.25, St_3prime_over_St_3prime_peak_jl) G5_0Psi_h_over_deltastar_avg0p43_jl = AcousticAnalogies.G5_Psi0.(0.43, St_3prime_over_St_3prime_peak_jl) G5_0Psi_h_over_deltastar_avg0p50_jl = AcousticAnalogies.G5_Psi0.(0.50, St_3prime_over_St_3prime_peak_jl) G5_0Psi_h_over_deltastar_avg0p54_jl = AcousticAnalogies.G5_Psi0.(0.54, St_3prime_over_St_3prime_peak_jl) # G5_0Psi_h_over_deltastar_avg0p62_jl = AcousticAnalogies.G5_Psi0.(0.62, St_3prime_over_St_3prime_peak_jl) G5_0Psi_h_over_deltastar_avg1p20_jl = AcousticAnalogies.G5_Psi0.(1.20, St_3prime_over_St_3prime_peak_jl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="Strouhal ratio, St'''/St'''_peak", ylabel="G_5, Ξ¨=0Β°", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 97b") scatter!(ax1, St_3prime_over_St_3prime_peak_0p25, G5_0Psi_h_over_deltastar_avg0p25; label="h/Ξ΄^* = 0.25, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p25_jl; label="h/Ξ΄^* = 0.25, Julia") scatter!(ax1, St_3prime_over_St_3prime_peak_0p43, G5_0Psi_h_over_deltastar_avg0p43; label="h/Ξ΄^* = 0.43, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p43_jl; label="h/Ξ΄^* = 0.43, Julia") scatter!(ax1, St_3prime_over_St_3prime_peak_0p50, G5_0Psi_h_over_deltastar_avg0p50; label="h/Ξ΄^* = 0.50, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p50_jl; label="h/Ξ΄^* = 0.50, Julia") scatter!(ax1, St_3prime_over_St_3prime_peak_0p54, G5_0Psi_h_over_deltastar_avg0p54; label="h/Ξ΄^* = 0.54, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p54_jl; label="h/Ξ΄^* = 0.54, Julia") # scatter!(ax1, St_3prime_over_St_3prime_peak_0p62, G5_0Psi_h_over_deltastar_avg0p62; label="h/Ξ΄^* = 0.62, BPM", marker='o') # lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg0p62_jl; label="h/Ξ΄^* = 0.62, Julia") scatter!(ax1, St_3prime_over_St_3prime_peak_1p20, G5_0Psi_h_over_deltastar_avg1p20; label="h/Ξ΄^* = 1.20, BPM", marker='o') lines!(ax1, St_3prime_over_St_3prime_peak_jl, G5_0Psi_h_over_deltastar_avg1p20_jl; label="h/Ξ΄^* = 1.20, Julia") xlims!(ax1, 0.1, 10.0) ylims!(ax1, -30, 10) axislegend(ax1, position=:rt) save("19890016302-figure97b.png", fig) ``` ![](19890016302-figure97b.png)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
74299
```@meta CurrentModule = AADocs ``` # Software Quality Assurance, Cont. ## Brooks, Pope, and Marcolini Airfoil Self-Noise Tests, Cont. ### Airfoil Self-Noise Predictions ```@example bpm_figure11_a using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure11-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # At zero angle of attack the pressure and suction side predictions are the same. f_p = f_s SPL_p = SPL_s nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 11 (a) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure11-a.png", fig) ``` ![](19890016302-figure11-a.png) ```@example bpm_figure11_b using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure11-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # At zero angle of attack the pressure and suction side predictions are the same. f_p = f_s SPL_p = SPL_s nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 55.5 # freestream velocity in m/s # M = 0.163 # Mach number, corresponds to U = 55.5 m/s in BPM report M = U/340.46 r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M D_h = AcousticAnalogies.Dbar_h(ΞΈ_e, Ξ¦_e, M, M_c) alphastar = 0.0 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 11 (b) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 30, 70) axislegend(ax1, position=:rt) save("19890016302-figure11-b.png", fig) ``` ![](19890016302-figure11-b.png) ```@example bpm_figure11_c using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure11-c-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # At zero angle of attack the pressure and suction side predictions are the same. f_p = f_s SPL_p = SPL_s nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 39.6 # freestream velocity in m/s # M = 0.116 # Mach number, corresponds to U = 36.6 m/s in BPM report M = U/340.46 r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M D_h = AcousticAnalogies.Dbar_h(ΞΈ_e, Ξ¦_e, M, M_c) alphastar = 0.0 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 11 (c) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 20, 60) axislegend(ax1, position=:rt) save("19890016302-figure11-c.png", fig) ``` ![](19890016302-figure11-c.png) ```@example bpm_figure11_d using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure11-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # At zero angle of attack the pressure and suction side predictions are the same. f_p = f_s SPL_p = SPL_s nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # Mach number, corresponds to U = 31.7 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M D_h = AcousticAnalogies.Dbar_h(ΞΈ_e, Ξ¦_e, M, M_c) alphastar = 0.0 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 11 (d) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 20, 60) axislegend(ax1, position=:rt) save("19890016302-figure11-d.png", fig) ``` ![](19890016302-figure11-d.png) ```@example bpm_figure12_a using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure12-U71.3-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure12-U71.3-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure12-U71.3-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 1.5*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 12 (a) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure12-a.png", fig) ``` ![](19890016302-figure12-a.png) ```@example bpm_figure12_b using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure12-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure12-b-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure12-b-TBL-TE-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 36.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 1.5*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 12 (b) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 20, 60) axislegend(ax1, position=:rt) save("19890016302-figure12-b.png", fig) ``` ![](19890016302-figure12-b.png) ```@example bpm_figure26_a using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure26-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Pressure and suction sides are the same for zero angle of attack. f_p = f_s SPL_p = SPL_s nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 26 (a) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") # scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure26-a.png", fig) ``` ![](19890016302-figure26-a.png) ```@example bpm_figure26_b using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure26-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Pressure and suction sides are the same for zero angle of attack. f_p = f_s SPL_p = SPL_s nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 55.5 # freestream velocity in m/s M = 0.163 # Mach number, corresponds to U = 55.5 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 26 (b) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") # scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 30, 70) axislegend(ax1, position=:rt) save("19890016302-figure26-b.png", fig) ``` ![](19890016302-figure26-b.png) ```@example bpm_figure26_c using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure26-c-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Pressure and suction sides are the same for zero angle of attack. f_p = f_s SPL_p = SPL_s nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 26 (c) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 20, 60) axislegend(ax1, position=:rt) save("19890016302-figure26-c.png", fig) ``` ![](19890016302-figure26-c.png) ```@example bpm_figure26_d using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure26-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Pressure and suction sides are the same for zero angle of attack. f_p = f_s SPL_p = SPL_s nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # Mach number, corresponds to U = 31.7 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 26 (d) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") # scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 20, 60) axislegend(ax1, position=:rt) save("19890016302-figure26-d.png", fig) ``` ![](19890016302-figure26-d.png) ```@example bpm_figure28_a using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-a-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-a-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 6.7*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 28 (a) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure28-a.png", fig) ``` ![](19890016302-figure28-a.png) ```@example bpm_figure28_b using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-b-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-b-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 55.5 # freestream velocity in m/s M = 0.163 # Mach number, corresponds to U = 55.5 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 6.7*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 28 (b) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 30, 70) axislegend(ax1, position=:rt) save("19890016302-figure28-b.png", fig) ``` ![](19890016302-figure28-b.png) ```@example bpm_figure28_c using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-c-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-c-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-c-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 6.7*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 28 (c) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 30, 70) axislegend(ax1, position=:rt) save("19890016302-figure28-c.png", fig) ``` ![](19890016302-figure28-c.png) ```@example bpm_figure28_d using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-d-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure28-d-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 6.7*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="figure 28 (d) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 30, 70) axislegend(ax1, position=:rt) save("19890016302-figure28-d.png", fig) ``` ![](19890016302-figure28-d.png) ```@example bpm_figure38_d using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure38-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure38-d-TBL-TE-pressure.csv") # bpm = DelimitedFiles.readdlm(fname, ',') # f_p = bpm[:, 1] # SPL_p = bpm[:, 2] # # fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure38-d-separation.csv") # bpm = DelimitedFiles.readdlm(fname, ',') # f_alpha = bpm[:, 1] # SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 2.54e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="figure 38 (d) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") # scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") # lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") # # scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") # lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 20, 60) axislegend(ax1, position=:rt) save("19890016302-figure38-d.png", fig) ``` ![](19890016302-figure38-d.png) ```@example bpm_figure39_d using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure39-d-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure39-d-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure39-d-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 2.54e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 4.8*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="figure 39 (d) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 20, 60) axislegend(ax1, position=:rt) save("19890016302-figure39-d.png", fig) ``` ![](19890016302-figure39-d.png) ```@example bpm_figure45_a using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure45-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure45-a-TBL-TE-pressure.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure45-a-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure45-a-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 30.48e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 1.5*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_lblvs=true) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 45 (a) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") scatter!(ax1, f_lbl_vs, SPL_lbl_vs; marker='β—‡', label="LBL-VS, BPM") scatterlines!(ax1, f_jl./1e3, SPL_lbl_vs_jl; marker='β—‡', label="LBL-VS, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure45-a.png", fig) ``` ![](19890016302-figure45-a.png) ```@example bpm_figure48_c using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure48-c-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 22.86e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_lblvs=true) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 48 (c) - U = $U m/s") scatter!(ax1, f_lbl_vs, SPL_lbl_vs; marker=:diamond, label="LBL-VS, BPM") lines!(ax1, f_jl./1e3, SPL_lbl_vs_jl; label="LBL-VS, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 20, 60) axislegend(ax1, position=:rt) save("19890016302-figure48-c.png", fig) ``` ![](19890016302-figure48-c.png) ```@example bpm_figure54_a using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure54-a-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 15.24e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 2.7*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_lblvs=true) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 54 (a) - U = $U m/s") scatter!(ax1, f_lbl_vs, SPL_lbl_vs; marker=:diamond, label="LBL-VS, BPM") lines!(ax1, f_jl./1e3, SPL_lbl_vs_jl; label="LBL-VS, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 50, 90) axislegend(ax1, position=:rt) save("19890016302-figure54-a.png", fig) ``` ![](19890016302-figure54-a.png) ```@example bpm_figure59_c using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure59-c-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_lblvs=true) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 59 (c) - U = $U m/s") scatter!(ax1, f_lbl_vs, SPL_lbl_vs; marker=:diamond, label="LBL-VS, BPM") lines!(ax1, f_jl./1e3, SPL_lbl_vs_jl; label="LBL-VS, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure59-c.png", fig) ``` ![](19890016302-figure59-c.png) ```@example bpm_figure60_c using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure60-c-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 3.3*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_lblvs=true) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 60 (c) - U = $U m/s") scatter!(ax1, f_lbl_vs, SPL_lbl_vs; marker=:diamond, label="LBL-VS, BPM") lines!(ax1, f_jl./1e3, SPL_lbl_vs_jl; label="LBL-VS, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure60-c.png", fig) ``` ![](19890016302-figure60-c.png) ```@example bpm_figure60_d using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure60-d-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 10.16e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 3.3*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_lblvs=true) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 60 (d) - U = $U m/s") scatter!(ax1, f_lbl_vs, SPL_lbl_vs; marker=:diamond, label="LBL-VS, BPM") lines!(ax1, f_jl./1e3, SPL_lbl_vs_jl; label="LBL-VS, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure60-d.png", fig) ``` ![](19890016302-figure60-d.png) ```@example bpm_figure65_d using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure65-d-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 5.08e-2 # chord in meters U = 31.7 # freestream velocity in m/s M = 0.093 # mach number, corresponds to u = 31.7 m/s in bpm report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 0.0*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_lblvs=true) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 65 (d) - U = $U m/s") scatter!(ax1, f_lbl_vs, SPL_lbl_vs; marker=:diamond, label="LBL-VS, BPM") lines!(ax1, f_jl./1e3, SPL_lbl_vs_jl; label="LBL-VS, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 50, 90) axislegend(ax1, position=:rt) save("19890016302-figure65-d.png", fig) ``` ![](19890016302-figure65-d.png) ```@example bpm_figure66_b using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure66-b-LBL-VS.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_lbl_vs = bpm[:, 1] SPL_lbl_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 5.08e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 4.2*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_lbl_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_lblvs=true) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 66 (b) - U = $U m/s") scatter!(ax1, f_lbl_vs, SPL_lbl_vs; marker=:diamond, label="LBL-VS, BPM") scatterlines!(ax1, f_jl./1e3, SPL_lbl_vs_jl; label="LBL-VS, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 30, 70) axislegend(ax1, position=:rt) save("19890016302-figure66-b.png", fig) ``` ![](19890016302-figure66-b.png) ```@example bpm_figure69_a using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure69-a-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 5.08e-2 # chord in meters U = 71.3 # freestream velocity in m/s M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 15.4*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 69 (a) - U = $U m/s") # scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") # scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 60, 100) axislegend(ax1, position=:rt) save("19890016302-figure69-a.png", fig) ``` ![](19890016302-figure69-a.png) ```@example bpm_figure69_b using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) # TBL-TE suction and pressure aren't significant sources for this case (deep stall). fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure69-b-separation.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_alpha = bpm[:, 1] SPL_alpha = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 5.08e-2 # chord in meters U = 39.6 # freestream velocity in m/s M = 0.116 # Mach number, corresponds to U = 39.6 m/s in BPM report r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 15.4*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 69 (b) - U = $U m/s") # scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") # scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_alpha, SPL_alpha; marker='β–³', label="separation, BPM") lines!(ax1, f_jl./1e3, SPL_alpha_jl; label="separation, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure69-b.png", fig) ``` ![](19890016302-figure69-b.png) ```@example bpm_figure91 using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure91-tip.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_tip = bpm[:, 1] SPL_tip = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 30.48e-2 # span in meters chord = 15.24e-2 # chord in meters speedofsound = 340.46 U = 71.3 # freestream velocity in m/s # M = 0.209 # Mach number, corresponds to U = 71.3 m/s in BPM report M = U/speedofsound M_c = 0.8*M # speedofsound = U/M r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 alphastar = 10.8*pi/180 bl = AcousticAnalogies.UntrippedN0012BoundaryLayer() blade_tip = AcousticAnalogies.RoundedTip(AcousticAnalogies.BPMTipAlphaCorrection(), 0.0) f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_tip_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_tip_vortex=true, blade_tip=blade_tip) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 91") scatter!(ax1, f_tip, SPL_tip; marker='o', label="Tip, BPM") lines!(ax1, f_jl./1e3, SPL_tip_jl; label="Tip, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 90) axislegend(ax1, position=:rt) save("19890016302-figure91.png", fig) ``` ![](19890016302-figure91.png) ```@example bpm_figure98_b using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) # Figures 98 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-b-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 69.5 # freestream velocity in m/s M = U/340.46 h = 1.1e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_tebvs=true, h=h, Psi=Psi) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 98 (b) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_teb_vs, SPL_teb_vs; marker='β—Ί', label="Bluntness, BPM") lines!(ax1, f_jl./1e3, SPL_teb_vs_jl; label="Bluntness, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:rt) save("19890016302-figure98-b.png", fig) ``` ![](19890016302-figure98-b.png) ```@example bpm_figure98_c using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) # Figures 98 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-c-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 69.5 # freestream velocity in m/s M = U/340.46 h = 1.9e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_tebvs=true, h=h, Psi=Psi) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 98 (c) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_teb_vs, SPL_teb_vs; marker='β—Ί', label="Bluntness, BPM") lines!(ax1, f_jl./1e3, SPL_teb_vs_jl; label="Bluntness, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:lt) save("19890016302-figure98-c.png", fig) ``` ![](19890016302-figure98-c.png) ```@example bpm_figure98_d using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) # Figures 98 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-a-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure98-d-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 69.5 # freestream velocity in m/s M = U/340.46 h = 2.5e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_tebvs=true, h=h, Psi=Psi) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 98 (d) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_teb_vs, SPL_teb_vs; marker='β—Ί', label="Bluntness, BPM") lines!(ax1, f_jl./1e3, SPL_teb_vs_jl; label="Bluntness, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 40, 80) axislegend(ax1, position=:lt) save("19890016302-figure98-d.png", fig) ``` ![](19890016302-figure98-d.png) ```@example bpm_figure99_b using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) # Figures 99 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 38.6 # freestream velocity in m/s M = U/340.46 h = 1.1e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_tebvs=true, h=h, Psi=Psi) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 99 (b) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_teb_vs, SPL_teb_vs; marker='β—Ί', label="Bluntness, BPM") lines!(ax1, f_jl./1e3, SPL_teb_vs_jl; label="Bluntness, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 30, 70) axislegend(ax1, position=:rt) save("19890016302-figure99-b.png", fig) ``` ![](19890016302-figure99-b.png) ```@example bpm_figure99_c using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) # Figures 99 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-c-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 38.6 # freestream velocity in m/s M = U/340.46 h = 1.9e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_tebvs=true, h=h, Psi=Psi) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 99 (c) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_teb_vs, SPL_teb_vs; marker='β—Ί', label="Bluntness, BPM") lines!(ax1, f_jl./1e3, SPL_teb_vs_jl; label="Bluntness, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 30, 70) axislegend(ax1, position=:rt) save("19890016302-figure99-c.png", fig) ``` ![](19890016302-figure99-c.png) ```@example bpm_figure99_d using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: ExactThirdOctaveCenterBands using DelimitedFiles: DelimitedFiles using GLMakie # https://docs.makie.org/stable/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) # Figures 99 a-d only differ in trailing edge bluntness, so the other sources are all the same. # And TBL-TE is the only significant source, other than bluntness. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_s = bpm[:, 1] SPL_s = bpm[:, 2] # Suction and pressure are the same for zero angle of attack. fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-b-TBL-TE-suction.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_p = bpm[:, 1] SPL_p = bpm[:, 2] fname = joinpath(@__DIR__, "..", "..", "test", "bpm_data", "brooks_airfoil_self_noise_and_prediction_1989", "19890016302-figure99-d-bluntness.csv") bpm = DelimitedFiles.readdlm(fname, ',') f_teb_vs = bpm[:, 1] SPL_teb_vs = bpm[:, 2] nu = 1.4529e-5 # kinematic viscosity, m^2/s L = 45.72e-2 # span in meters chord = 60.96e-2 # chord in meters U = 38.6 # freestream velocity in m/s M = U/340.46 h = 2.5e-3 # trailing edge bluntness in meters Psi = 14*pi/180 # bluntness angle in radians r_e = 1.22 # radiation distance in meters ΞΈ_e = 90*pi/180 Ξ¦_e = 90*pi/180 M_c = 0.8*M alphastar = 0.0*pi/180 bl = AcousticAnalogies.TrippedN0012BoundaryLayer() f_jl, SPL_s_jl, SPL_p_jl, SPL_alpha_jl, SPL_teb_vs_jl = AcousticAnalogies.calculate_bpm_test(nu, L, chord, U, M, r_e, ΞΈ_e, Ξ¦_e, alphastar, bl; do_tebvs=true, h=h, Psi=Psi) fig = Figure() ax1 = fig[1, 1] = Axis(fig; xlabel="frequency, kHz", ylabel="SPL_1/3, dB", xscale=log10, xminorticksvisible=true, xminorticks=IntervalsBetween(9), xticks=LogTicks(IntegerTicks()), title="Figure 99 (d) - U = $U m/s") scatter!(ax1, f_s, SPL_s; marker='o', label="TBL-TE suction side, BPM") lines!(ax1, f_jl./1e3, SPL_s_jl; label="TBL-TE suction side, Julia") scatter!(ax1, f_p, SPL_p; marker='β–‘', label="TBL-TE pressure side, BPM") lines!(ax1, f_jl./1e3, SPL_p_jl; label="TBL-TE pressure side, Julia") scatter!(ax1, f_teb_vs, SPL_teb_vs; marker='β—Ί', label="Bluntness, BPM") lines!(ax1, f_jl./1e3, SPL_teb_vs_jl; label="Bluntness, Julia") xlims!(ax1, 0.2, 20.0) ylims!(ax1, 30, 70) axislegend(ax1, position=:rt) save("19890016302-figure99-d.png", fig) ``` ![](19890016302-figure99-d.png)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
5922
```@meta CurrentModule = AADocs ``` # Compact Formulation 1A CCBlade.jl Example AcousticAnalogies.jl contains routines that take in types defined by [CCBlade.jl](https://github.com/byuflowlab/CCBlade.jl), a blade element momentum theory (BEMT) code and construct the types used by AcousticAnalogies.jl for acoustic predictions. This makes it simple to go from a BEMT aerodynamic prediction of a propeller or rotor to an acoustic prediction. First step is to load up `CCBlade.jl`. ```@example first_example using CCBlade: parsefile, viterna, AlphaAF, SkinFriction, PrandtlGlauert, DuSeligEggers, PrandtlTipHub, Rotor, Section, OperatingPoint, solve, linearliftcoeff nothing # hide ``` Then we'll define some parameters we'll need to create the CCBlade.jl types. First some atmospheric properties: ```@example first_example gam = 1.4 R = 287.058 # J/(kg*K) rho = 1.226 # kg/m^3 c0 = 340.0 # m/s mu = 0.1780e-4 # kg/(m*s) nothing # hide ``` And some blade geometry parameters: ```@example first_example num_blades = 3 num_radial = 30 precone = 0.0 # rad Rtip = 0.5*24*0.0254 # blade radius, m Rhub = 0.2*Rtip # hub radius, m r_ = range(Rhub, Rtip, length=num_radial+1) # blade element interfaces radii = 0.5.*(r_[2:end] .+ r_[1:end-1]) # blade element centers, m c = 1.5*0.0254 # (constant) chord, m chord = fill(c, num_radial) # chord, m D = 2*Rtip # blade diameter, m P = 16*0.0254 # propeller pitch, m twist = @. atan(P/(pi*D*radii/Rtip)) # twist, rad area_over_chord_squared = 0.08217849116518001 # Cross-sectional area per chord^2 for NACA0012. nothing # hide ``` We also need airfoil lift and drag coefficients as a function of angle of attack. CCBlade.jl has routines for interpolating and correcting airfoil lift and drag data. Here we're starting with [NACA0012 airfoil data from airfoiltools.com](http://airfoiltools.com/polar/details?polar=xf-n0012-il-500000): ```@example first_example af_fname = joinpath(@__DIR__, "assets", "xf-n0012-il-500000.dat") info, Re, Mach, alpha, cl, cd = parsefile(af_fname, false) # Extend the angle of attack with the Viterna method. cr75 = c/Rtip (alpha, cl, cd) = viterna(alpha, cl, cd, cr75) af = AlphaAF(alpha, cl, cd, info, Re, Mach) # Reynolds number correction. The 0.6 factor seems to match the NACA 0012 # drag data from airfoiltools.com. reynolds = SkinFriction(Re, 0.6) # Mach number correction. mach = PrandtlGlauert() # Rotational stall delay correction. Need some parameters from the CL curve. m, alpha0 = linearliftcoeff(af, 1.0, 1.0) # dummy values for Re and Mach # Create the Du Selig and Eggers correction. rotation = DuSeligEggers(1.0, 1.0, 1.0, m, alpha0) # The usual hub and tip loss correction. tip = PrandtlTipHub() nothing # hide ``` Finally, the freestream velocity and the rotor rotation rate: ```@example first_example v = 0.11*c0 # m/s omega = 7100 * 2*pi/60 # rad/s pitch = 0.0 # rad nothing # hide ``` Now we have enough information to create the CCBlade.jl `structs` we'll need. ```@example first_example rotor = Rotor(Rhub, Rtip, num_blades; precone=precone, turbine=false, mach=mach, re=reynolds, rotation=rotation, tip=tip) sections = Section.(radii, chord, twist, Ref(af)) ops = OperatingPoint.(v, omega.*radii, rho, pitch, mu, c0) nothing # hide ``` And we can use CCBlade.jl to solve the BEMT equations. ```@example first_example outs = solve.(Ref(rotor), sections, ops) nothing # hide ``` And then make some plots. ```@example first_example using GLMakie fig1 = Figure() ax1_1 = fig1[1, 1] = Axis(fig1, xlabel="radii/Rtip", ylabel="normal load/span, N/m") ax1_2 = fig1[2, 1] = Axis(fig1, xlabel="radii/Rtip", ylabel="circum load/span, N/m") lines!(ax1_1, radii./Rtip, getproperty.(outs, :Np)) lines!(ax1_2, radii./Rtip, getproperty.(outs, :Tp)) hidexdecorations!(ax1_1, grid=false) save("ccblade_example-ccblade_loads.png", fig1) nothing # hide ``` ![](ccblade_example-ccblade_loads.png) Now we can use the CCBlade.jl `structs` to create AcousticAnalogies.jl source elements. The key function is [`f1a_source_elements_ccblade`](@ref): ```@docs f1a_source_elements_ccblade ``` So let's try that: ```@example first_example using AcousticAnalogies: f1a_source_elements_ccblade, ConstVelocityAcousticObserver, noise, combine, pressure_monopole, pressure_dipole bpp = 2*pi/omega/num_blades # blade passing period positive_x_rotation = true ses = f1a_source_elements_ccblade(rotor, sections, ops, outs, [area_over_chord_squared], 4*bpp, 64, positive_x_rotation) nothing # hide ``` Now we can use the source elements to perform an acoustic prediction, after we decide on an acoustic observer location. ```@example first_example using AcousticMetrics # Sideline microphone location in meters. x_obs = [0.0, 2.3033, 2.6842] v_obs = [v, 0.0, 0.0] obs = ConstVelocityAcousticObserver(0.0, x_obs, v_obs) apth = noise.(ses, Ref(obs)) apth_total = combine(apth, 2*bpp, 64) nothing # hide ``` And finally plot the acoustic pressure time history. ```@example first_example fig2 = Figure() ax2_1 = fig2[1, 1] = Axis(fig2, xlabel="time, blade passes", ylabel="acoustic pressure, monopole, Pa") ax2_2 = fig2[2, 1] = Axis(fig2, xlabel="time, blade passes", ylabel="acoustic pressure, dipole, Pa") ax2_3 = fig2[3, 1] = Axis(fig2, xlabel="time, blade passes", ylabel="acoustic pressure, total, Pa") t = AcousticMetrics.time(apth_total) t_nondim = (t .- t[1])./bpp lines!(ax2_1, t_nondim, pressure_monopole(apth_total)) lines!(ax2_2, t_nondim, pressure_dipole(apth_total)) lines!(ax2_3, t_nondim, AcousticMetrics.pressure(apth_total)) hidexdecorations!(ax2_1, grid=false) hidexdecorations!(ax2_2, grid=false) save("ccblade_example-apth.png", fig2) nothing # hide ``` ![](ccblade_example-apth.png)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
17175
```@meta CurrentModule = AADocs ``` # [Compact Formulation 1A Guided Example](@id guided_example) There are four steps to predicting propeller/rotor noise with AcousticAnalogies.jl. 1. Define the blade's motion and loading as a function of source time 2. Perform the advanced time calculation 3. Propagate the acoustics caused by each blade section to the acoustic observer(s) using the F1A formulation 4. Combine all the acoustic pressures resulting from step 3 into one acoustic pressure time history ## 1. Define the Blade ### The Blade-Fixed Reference Frame We need to know what the blade is doing aerodynamically before we can predict how loud it is. Specifically, we need to know at each radial station along each blade the * position * velocity * acceleration * jerk (time derivative of acceleration) * cross-sectional area * loading per unit span all as a function of time. We'll do this first in a reference frame moving with the blades, i.e., translating and rotating with the blade geometry, that we'll call the blade-fixed reference frame. First step is to load up `AcousticAnalogies.jl`: ```@example first_example using AcousticAnalogies ``` So, for this example we'll imagine that we have a blade with radial stations that look like this: ```@example first_example num_blades = 2 # number of blades Rhub = 0.10 # meters Rtip = 1.1684 # meters radii = [ 0.92904E-01, 0.11751, 0.15631, 0.20097, 0.24792 , 0.29563, 0.34336, 0.39068, 0.43727 , 0.48291, 0.52741, 0.57060, 0.61234 , 0.65249, 0.69092, 0.72752, 0.76218 , 0.79479, 0.82527, 0.85352, 0.87947 , 0.90303, 0.92415, 0.94275, 0.95880 , 0.97224, 0.98304, 0.99117, 0.99660 , 0.99932].*Rtip nothing # hide ``` `radii` is a `Vector` of the distance of each blade element's center from the propeller hub, in meters. Each of the `num_blades` blades have the same radial coordinates in the blade-fixed frame, but different angular coordinates: blade number `2` will be offset `180Β°` from blade number `1`. ```@example first_example ΞΈs = 2*pi/num_blades.*(0:(num_blades-1)) nothing # hide ``` So now we know where each blade element is in the blade-fixed frame: in polar coordinates, element at radial index `j` and blade `k` is at `radii[j]`, `ΞΈs[k]`. We'll also need the length of each blade element. There is a convenience function in `AcousticAnalogies.jl` called `get_dradii` that calculates each blade element's length from the element centers and the hub and tip location: ```@example first_example dradii = get_dradii(radii, Rhub, Rtip) ``` The compact F1A calculation also requires the cross-sectional area of each element. In many types of propeller codes, the cross-sectional shape at each radial station is defined as having a certain standard shape (e.g., circular near the hub, a given airfoil shape elsewhere). If we know the cross-sectional area for each relevant airfoil shape with a chord length of one, we can find the cross-sectional area for any chord length by multiplying by the squared chord length. In this example we'll assume the blade uses the same airfoil shape at each radial station, and that this airfoil has a cross-sectional area per unit chord squared of `0.064`. After defining the chord length for each radial station, we find the cross-sectional area in units of meters squared: ```@example first_example cs_area_over_chord_squared = 0.064 chord = [ 0.35044 , 0.28260 , 0.22105 , 0.17787 , 0.14760, 0.12567 , 0.10927 , 0.96661E-01 , 0.86742E-01 , 0.78783E-01 , 0.72287E-01 , 0.66906E-01 , 0.62387E-01 , 0.58541E-01 , 0.55217E-01 , 0.52290E-01 , 0.49645E-01 , 0.47176E-01 , 0.44772E-01 , 0.42326E-01 , 0.39732E-01 , 0.36898E-01 , 0.33752E-01 , 0.30255E-01 , 0.26401E-01 , 0.22217E-01 , 0.17765E-01 , 0.13147E-01 , 0.85683E-02 , 0.47397E-02].*Rtip cs_area = cs_area_over_chord_squared.*chord.^2 nothing # hide ``` Next, we need the loading on the blade. `AcousticAnalogies.jl` needs us to specify the loading at each radial station as a 3D vector in units of loading per unit span. But for now, let's imagine that we've run some type of propeller aerodynamic code (I used [CCBlade.jl](https://github.com/byuflowlab/CCBlade.jl), FYI) and have the normal and circumferential loading as a function of radial position along the blade. The loading is in units of force per unit span (here, Newtons/meter). ```@example first_example fn = [32.87810395677037, 99.05130471878633, 190.1751697055377, 275.9492967565419, 358.14423433748146, 439.64679797145624, 520.1002808148281, 599.1445046901513, 676.2358818769462, 751.3409657831587, 824.2087672338118, 894.4465814696498, 961.9015451678036, 1026.0112737521583, 1086.2610633094212, 1141.4900032393818, 1190.3376703335655, 1230.8999662260915, 1260.375390697363, 1275.354422403355, 1271.8827617273287, 1245.9059108698596, 1193.9967137923225, 1113.9397490286995, 1005.273267675585, 869.4101036003673, 709.8100230053759, 532.1946243370355, 346.53986082379265, 180.66763939805125] fc = [26.09881302938423, 55.5216259955307, 75.84767780212506, 84.84509232798283, 89.73045068624886, 93.02999477395113, 95.4384273852926, 97.31647535460424, 98.81063179767507, 100.07617771995163, 101.17251941705561, 102.11543878532882, 102.94453631586998, 103.63835661864168, 104.18877957193807, 104.51732850056433, 104.54735678589765, 104.1688287897138, 103.20319203286938, 101.46246817378582, 99.11692436681635, 96.49009546562475, 93.45834266417528, 89.49783586366624, 83.87176811707455, 75.83190739325453, 64.88004605331857, 50.98243352318318, 34.85525518071079, 19.358679206883078] nothing # hide ``` We also need to decide on some atmospheric properties, specifically the ambient air density and speed of sound. ```@example first_example rho = 1.226 # kg/m^3 c0 = 340.0 # m/s nothing # hide ``` And we need to decide on some operating point parameters. Let's assume that the blade is moving forward at `5.0 m/s` and rotating at `2200 rev/min`. ```@example first_example v = 0.0 # m/s omega = 2200 * 2*pi/60 # rad/s nothing # hide ``` We also need to decide over what time period we're going to calculate the blades' acoustics. Let's do one rotation of the blade: ```@example first_example period = 2*pi/omega num_src_times = 64 dt = 2*period/(num_src_times-1) src_times = (0:num_src_times-1).*dt nothing # hide ``` So at this point we have all the information needed to define the source elements in a frame of reference that's moving with the blade, i.e., rotating at a rate of `omega` and moving forward at a speed of `v` defined above. Let's do that. We want one source element for each radial station along the blade at each `src_time` and each of the `num_blades` blades. Sounds kind of complicated, but luckily Julia's broadcasting makes this easy. What we'd like is an array `ses` of `CompactF1ASourceElement` types that has `size` `(num_src_times, num_radial, num_blades)`, where `ses[i, j, k]` holds the `CompactF1ASourceElement` at `src_time[i]`, `radii[j]`, and blade number `k`. So let's reshape the input arrays to make that happen. ```@example first_example ΞΈs = reshape(ΞΈs, 1, 1, :) radii = reshape(radii, 1, :, 1) dradii = reshape(dradii, 1, :, 1) cs_area = reshape(cs_area, 1, :, 1) fn = reshape(fn, 1, :, 1) fc = reshape(fc, 1, :, 1) src_times = reshape(src_times, :, 1, 1) # This isn't really necessary. nothing # hide ``` Now, the last thing we need to think about is the coordinate system we're defining these quantities in. Again, right now we are in the blade-fixed frame, which means the coordinate system is rotating with the blades at a rate of `omega` and translating with a velocity `v` in the positive x direction. The `CompactF1ASourceElement` constructor we'll use allows us to specify each source element's location in terms of `r` and `ΞΈ`, where `r` is the distance from the origin and `ΞΈ` is the polar angle from the positive y axis, rotating toward the positive `z` axis. So the `radii` and `ΞΈs` arrays are set up correctly. Now, one of the tricky aspects of using an acoustic analogy is getting the direction of the loading on the integration surface (or line in the case of a compact formulation) right. An acoustic analogy requires the loading *on the fluid*, not on the solid body. One might expect that we just need to switch the sign on the `fn` and `fc` arrays above. That's true for the `fn` array, which represents the loading in the axial direction: if we imagine our propeller is moving in the positive x direction, the propeller would be pushing on the fluid in the negative x direction in normal operation. But what about the circumferential loading? In the blade-fixed frame, we assume the propeller is rotating about the x axis in a positive (i.e., right-handed) sense. So, if we imagine the situation for `ΞΈ=0`, the blade will be initially along the positive y axis, rotating toward the positive z axis. What direction will the circumferential loading on the fluid be? It will be positive, pointing in the same direction as the positive z axis. So we don't need to switch the sign on the `fc` array. So let's create all the source elements: ```@example first_example ses = CompactF1ASourceElement.(rho, c0, radii, ΞΈs, dradii, cs_area, -fn, 0.0, fc, src_times) size(ses) ``` The size of the source element array ended up like we wanted: `(num_src_times, num_radial, num_blades)`. ### The Global Reference Frame At this point we have an array of `CompactF1ASourceElement` that describes the what each blade element "source" is doing from the perspective of the blade-fixed reference frame. But in order to perform the F1A calculation, we need to move the sources from the blade-fixed frame to the global reference frame, i.e., the one for which the fluid medium (air) appears to be stationary. This involves just setting the position and loading components of each `CompactF1ASourceElement` to the correct values (`y0dot` through `y3dot` and `f0dot` and `f1dot`). This could be done manually, but it's easier to use the [KinematicCoordinateTransformations.jl](https://github.com/OpenMDAO/KinematicCoordinateTransformations.jl) package. The first transformation we need to perform is a steady rotation around the x axis. So we create a `SteadyRotXTransformation`: ```@example first_example using KinematicCoordinateTransformations t0 = 0.0 # Time at which the angle between the source and target coordinate systems is equal to offest. offset = 0.0 # Angular offset between the source and target cooridante systems at t0. rot_trans = SteadyRotXTransformation(t0, omega, offset) nothing # hide ``` Next, we need to orient the rotation axis of the blades as it is the global frame. For example, let's say that it's pointed in the global positive z-axis direction, and the first blade is pointed in the positive y-axis direction. Then we can perform this transformation using the `ConstantLinearMap` transformation: ```@example first_example using LinearAlgebra: Γ— using StaticArrays rot_axis = @SVector [0.0, 0.0, 1.0] blade_axis = @SVector [0.0, 1.0, 0.0] global_trans = ConstantLinearMap(hcat(rot_axis, blade_axis, rot_axisΓ—blade_axis)) nothing # hide ``` Finally, we need the blade to move with the appropriate forward velocity, and start from the desired location in the global reference frame: ```@example first_example y0_hub = @SVector [0.0, 0.0, 0.0] # Position of the hub at time t0 v0_hub = SVector{3}(v.*rot_axis) # Constant velocity of the hub in the global reference frame const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) nothing # hide ``` Now we could apply each of these transformations to the `SourceElement` array. But it's more efficient to combine these three transformations into one, and then use that on the `SourceElements` using `compose`. ```@example first_example trans = compose.(src_times, Ref(const_vel_trans), compose.(src_times, Ref(global_trans), Ref(rot_trans))) nothing # hide ``` Now `trans` will perform the three transformations from right to left (`rot_trans`, `global_trans`, `const_vel_trans`). Now we use it on `ses`: ```@example first_example ses = ses .|> trans nothing # hide ``` So now the `ses` has been transformed from the blade-fixed reference frame to the global reference frame. We could have created the source elements and transformed them all in one line, too, which is pretty slick: ```@example first_example ses = AcousticAnalogies.CompactF1ASourceElement.(rho, c0, radii, ΞΈs, dradii, cs_area, -fn, 0.0, fc, src_times) .|> trans nothing # hide ``` ## 2. Perform the Advanced Time Calculation The `ses` object now describes how each blade element source is moving through the global reference frame over the time `src_time`. As it does this, it will emit acoustics that can be sensed by an acoustic observer (a human, or a microphone). The exact "amount" of acoustics the observer will experience depends on the relative location and motion between each source and the observer. So we'll need to define our acoustic observer before we can calculate the noise heard by it. For this example, we'll assume that our acoustic observer is stationary in the global frame. ```@example first_example x0 = @SVector [100*12*0.0254, 0.0, 0.0] # 100 ft in meters obs = StationaryAcousticObserver(x0) nothing # hide ``` Now, in order to perform the F1A calculation, we need to know when each acoustic disturbance emitted by the source arrives at the observer. This is referred to an advanced time calculation, and is done this way: ```@example first_example obs_time = adv_time.(ses, Ref(obs)) nothing # hide ``` That returns an array the same size of `ses` of the time each acoustic disturbance reaches the observer `obs`: ```@example first_example @show size(obs_time) nothing # hide ``` ## 3. Perform the F1A Calculation We're finally ready to do the compact F1A calculation! ```@example first_example apth = noise.(ses, Ref(obs), obs_time) nothing # hide ``` When called this way (notice the `.` after `noise`), the `noise` routine returns an array of `F1AOutput` `struct`s, the same size as `ses` and `obs_time`. Each `F1AOutput` `struct` has three components: the observer time `t`, the thickness/monopole part of the acoustic pressure `p_m`, and the loading/dipole part of the acoustic pressure `p_d`. ## 4. Combine the Acoustic Pressures We now have a noise prediction for each of the individual source elements in `ses` at the acoustic observer `obs`. What we ultimately want is the *total* noise prediction at `obs`β€”we want to add all the acoustic pressures in `apth` together. But we can't add them directly, yet, since the observer times are not all the same. What we need to do is first interpolate the `apth` of each source onto a common observer time grid, and then add them up. We'll do this using the `AcousticAnalogies.combine` function. ```@example first_example bpp = period/num_blades # blade passing period obs_time_range = 2*bpp num_obs_times = 128 apth_total = combine(apth, obs_time_range, num_obs_times, 1) nothing # hide ``` `combine` returns a single `F1AAcousticPressure` `struct` made up of `Vector`sβ€”it is an "struct of arrays" and not an "array of structs" like `apth`: ```@example first_example @show typeof(apth) typeof(apth_total) nothing # hide ``` We can now have a look at the total acoustic pressure time history at the observer: ```@example first_example using AcousticMetrics using GLMakie fig = Figure() ax1 = fig[1, 1] = Axis(fig, xlabel="time, blade passes", ylabel="monopole, Pa") ax2 = fig[2, 1] = Axis(fig, xlabel="time, blade passes", ylabel="dipole, Pa") ax3 = fig[3, 1] = Axis(fig, xlabel="time, blade passes", ylabel="total, Pa") t_nondim = (AcousticMetrics.time(apth_total) .- AcousticMetrics.starttime(apth_total))./bpp l1 = lines!(ax1, t_nondim, apth_total.p_m) l2 = lines!(ax2, t_nondim, apth_total.p_d) l3 = lines!(ax3, t_nondim, apth_total.p_m.+apth_total.p_d) hidexdecorations!(ax1, grid=false) hidexdecorations!(ax2, grid=false) save("first_example-apth_total.png", fig) nothing # hide ``` ![](first_example-apth_total.png) We can now post-process the total acoustic pressure time history in `apth_total` in any way we'd like. # AcousticMetrics.jl Support The [`combine`](@ref) function returns a `F1AAcousticPressure` `struct`, which subtypes the `AbstractAcousticPressure` type from the AcousticMetrics.jl package. Because of this, any of the acoustic metric functions defined in AcousticMetrics.jl relevant to `AbstractAcousticPressure` objects can be used with the `F1AAcousticPressure` returned by `combine`: ```@example first_example using AcousticMetrics # Calculate the overall sound pressure level from the acoustic pressure time history. oaspl_from_apth = AcousticMetrics.OASPL(apth_total) # Calculate the narrowband spectrum of mean-squared pressure. nbs = AcousticMetrics.MSPSpectrumAmplitude(apth_total) # Calculate the OASPL from the NBS. oaspl_from_nbs = AcousticMetrics.OASPL(nbs) (oaspl_from_apth, oaspl_from_nbs) ``` The two approaches to calculate the OASPL give essentially the same result.
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
2941
```@meta CurrentModule = AADocs ``` # AcousticAnalogies.jl Documentation **Summary**: A pure-Julia package for propeller/rotor blade noise prediction with acoustic analogies. **What's an acoustic analogy?** * TL;DR answer: An acoustic analogy is a noise prediction approach that takes information from one area of the fluid domain (e.g., a propeller blade surface, or a fictitious surface surrounding a complicated flow) and calculates the acoustics radiated by the flow. The particular acoustic analogy implemented in `AcousticAnalogies.jl` is especially well-suited for predicting tonal propeller/rotor noise, and has features that ease its inclusion in gradient-based optimizations. * Mathy answer: An acoustic analogy is a clever rearrangement of the Navier-Stokes equations, the governing equations of fluid flow, into a form that looks like the classical inhomogeneous wave equation. The inhomogeneous term represents sources of sound in the flow. The wave equation can be solved using the appropriate [Green's function](https://en.wikipedia.org/wiki/Green%27s_function#Table_of_Green's_functions), which requires the evaluation of two surface integrals and a volume integral (usually neglected). If the integration surface is taken to be a solid surface in the fluid domain (e.g., a propeller blade), we can use the acoustic analogy solution to predict the acoustics caused by the motion of and loading on the integration surface. **Features**: * Implementation of L. Lopes' compact form of Farassat's formulation 1A (see [http://dx.doi.org/10.2514/6.2015-2673](http://dx.doi.org/10.2514/6.2015-2673) or [http://dx.doi.org/10.2514/1.C034048](http://dx.doi.org/10.2514/1.C034048) for details). * Implementation of Brooks & Burley's rotor broadband noise prediction method [http://dx.doi.org/10.2514/6.2001-2210](http://dx.doi.org/10.2514/6.2001-2210). * Support for stationary or constant-velocity moving observers, with an explict calculation for the latter from D. Casalino [http://dx.doi.org/10.1016/S0022-460X(02)00986-0](http://dx.doi.org/10.1016/S0022-460X(02)00986-0). * Thoroughly tested: unit tests for everything, and multiple comparisons of the entire calculation to equivalent methods in NASA's ANOPP2 code. * Convenient, fast coordinate system transformations through [KinematicCoordinateTransformations.jl](https://github.com/OpenMDAO/KinematicCoordinateTransformations.jl). * Written in pure Julia, and compatible with automatic differentiation (AD) tools like [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl). * Comprehensive docs (TODO). * Fast! **Installation** ```julia-repl ] add AcousticAnalogies ``` **Usage** See the docs. # Software Quality Assurance * This repository contains extensive tests run by GitHub Actions. * This repository only allows signed commits to be merged into the `main` branch.
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
46999
```@meta CurrentModule = AADocs ``` # Software Quality Assurance, Cont. ## BPM.jl Comparisons for the Pettingill et al. Ideally Twisted Rotor See [here](http://dx.doi.org/10.2514/6.2021-1928) or [here](https://ntrs.nasa.gov/citations/20205003328) for details on the Ideally Twisted Rotor. ### Figure 22b ```@example figure22b using AcousticAnalogies using AcousticMetrics: AcousticMetrics using GLMakie using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, SteadyRotYTransformation, SteadyRotZTransformation, ConstantVelocityTransformation using FileIO: load using FLOWMath: Akima using StaticArrays: @SVector # Copied from BPM.jl (would like to add BPM.jl as a dependency if it's registered in General some day). # tip vortex noise correction data based on "Airfoil Tip Vortex Formation Noise" const bm_tip_alpha_aspect_data = [2.0,2.67,4.0,6.0,12.0,24.0] const bm_tip_alpha_aratio_data = [0.54,0.62,0.71,0.79,0.89,0.95] const bm_tip_alpha_aspect_ratio_correction = Akima(bm_tip_alpha_aspect_data, bm_tip_alpha_aratio_data) function bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) # compute tip lift curve slope if aspect_ratio < 2.0 aratio = 0.5*one(aspect_ratio) elseif 2.0 <= aspect_ratio <= 24.0 aratio = bm_tip_alpha_aspect_ratio_correction(aspect_ratio) elseif aspect_ratio > 24.0 aratio = 1.0*one(aspect_ratio) end return aratio end struct BMTipAlphaCorrection{TCorrection} <: AbstractTipAlphaCorrection correction::TCorrection function BMTipAlphaCorrection(aspect_ratio) # correction = BPM._tip_vortex_alpha_correction_nonsmooth(aspect_ratio) correction = bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) return new{typeof(correction)}(correction) end end function AcousticAnalogies.tip_vortex_alpha_correction(blade_tip::AbstractBladeTip{<:BMTipAlphaCorrection}, alphatip) a0l = AcousticAnalogies.alpha_zerolift(blade_tip) correction_factor = AcousticAnalogies.tip_alpha_correction(blade_tip).correction return correction_factor * (alphatip - a0l) + a0l end # Pettingill et al., "Acoustic And Performance Characteristics of an Ideally Twisted Rotor in Hover", 2021 # Parameters from Table 1 B = 4 # number of blades Rtip = 0.1588 # meters chord = 0.2*Rtip # Standard day: Tamb = 15 + 273.15 # 15Β°C in Kelvin pamb = 101325.0 # Pa R = 287.052874 # J/(kg*K) rho = pamb/(R*Tamb) asound = sqrt(1.4*R*Tamb) # Dynamic and kinematic viscosity mu = rho*1.4502e-5 nu = mu/rho # This is a hover case, so the freestream velocity should be zero. # CCBlade.jl will run with a zero freestream, but I've found that it compares a bit better with experiment if I give it a small non-zero value. Vinf = 0.001*asound # Figure 22 caption says Ξ©_c = 5465 RPM. rpm = 5465.0 omega = rpm * (2*pi/60) # Get "cell-centered" radial locations, and also the radial spacing. num_radial = 50 r_Rtip_ = range(0.2, 1.0; length=num_radial+1) r_Rtip = 0.5 .* (r_Rtip_[2:end] .+ r_Rtip_[1:end-1]) radii = r_Rtip .* Rtip dradii = (r_Rtip_[2:end] .- r_Rtip_[1:end-1]) .* Rtip Rhub = r_Rtip_[1]*Rtip # From Pettingill Equation (1), and value for Θ_tip in Table 1. Θ_tip = 6.9 * pi/180 twist = Θ_tip ./ (r_Rtip) # Need some aerodynamic quantities. # Got these using CCBlade.jl: see `AcousticAnalogies.jl/test/gen_bpmjl_data/itr_with_bpmjl.jl`. data_bpmjl = load(joinpath(@__DIR__, "..", "..", "test", "gen_bpmjl_data", "figure22b.jld2")) # Angle of attack at each radial station, radians. alpha = data_bpmjl["alpha"] # Flow speed normal to span at each radial station, m/s. U = data_bpmjl["U"] # In the Figure 22 caption, "for these predictions, bluntness thickness H was set to 0.8 mm and trailing edge angle Ξ¨ was set to 16 degrees." h = 0.8e-3 # meters Psi = 16*pi/180 # radians # We'll run for 1 blade pass, 20 time steps per blade pass. num_blade_pass = 1 num_src_times_blade_pass = 20 bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # BPM.jl uses a different tip alpha correction which appears to require the blade aspect ratio. # Need to find the blade aspect ratio of the ITR to apply the tip vortex angle of attack correction. # The aspect ratio is defined as the blade tip radius divided by the average chord, but the chord is constant for this case. aspect_ratio = Rtip / chord # Now we can create the tip object. alpha0lift = 0.0 blade_tip = AcousticAnalogies.FlatTip(BMTipAlphaCorrection(aspect_ratio), alpha0lift) # Start with a rotation about the negative x axis. positive_x_rotation = false rot_trans = SteadyRotXTransformation(t0, omega*ifelse(positive_x_rotation, 1, -1), 0) # Then translate along the positive x axis. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Then a 90Β° rotation about the negative z axis. trans_z90deg = SteadyRotZTransformation(0.0, 0.0, -0.5*pi) # Then a 90Β° rotation about the negative y axis. trans_y90deg = SteadyRotYTransformation(0.0, 0.0, -0.5*pi) # Put them all together: trans = compose.(src_times, Ref(trans_y90deg), compose.(src_times, Ref(trans_z90deg), compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)))) # Use the M_c = 0.8*M that BPM report and BPM.jl use. U = @. 0.8*sqrt(Vinf^2 + (omega*radii)^2) # In the text describing Figure 22, "For these predictions, the trip flag was set to β€œtripped”, due to the rough surface quality of the blade." # So we'll use a tripped boundary layer for all radial stations along the blade. bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # Need to do the LBLVS with the untripped boundary layer to match what BPM.jl is doing. # BPM.jl uses the untripped boundary layer properties for the laminar boundary layer-vortex shedding noise source, so do that here too. bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() # Paper doesn't specify the microphone used for Figure 22, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 22. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane. r_obs = 2.27 # meters theta_obs = -35*pi/180 # So, the docstring for BPM.jl says that `V` argument is the wind velocity in the y direction. # So I guess we should assume that the blades are rotating about the y axis. # And if the freestream velocity is in the positive y axis, then, from the perspective of the fluid, the blades are translating in the negative y direction. # And I want the observer to be downstream/behind the blades, so that would mean they would have a positive y position. # So I want to rotate the observer around the positive x axis, so I'm going to switch the sign on `theta_obs`. t0_obs = 0.0 x0_obs = @SVector [0.0, r_obs*sin(-theta_obs), r_obs*cos(-theta_obs)] # The observer is moving in the same direction as the blades, which is the negative y axis. v_obs = @SVector [0.0, -Vinf, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) .* ifelse(positive_x_rotation, 1, -1) # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) # chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) # hs_rs = reshape(hs, 1, :, 1) # Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) # bls_rs = reshape(bls, 1, :, 1) # bls_untripped_rs = reshape(bls_untripped, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] # chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] # hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] # Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] # bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] # chord_rs_with_tip = @view chord_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] # hs_rs_with_tip = @view hs_rs[:, end:end, :] # Psis_rs_with_tip = @view Psis_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] # bls_rs_with_tip = @view bls_rs[:, end:end, :] direct = AcousticAnalogies.BPMDirectivity use_UInduction = false use_Doppler = false mach_correction = AcousticAnalogies.NoMachCorrection ses_no_tip = CombinedNoTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord, twist_rs_no_tip, h, Psi, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, Ref(bl), positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord, twist_rs_with_tip, h, Psi, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, Ref(bl), Ref(blade_tip), positive_x_rotation) .|> trans # Put the source elements together: ses = cat(ses_no_tip, ses_with_tip; dims=2) # Need to do the LBLVS with the untripped boundary layer to match what BPM.jl is doing. lblvs_ses = AcousticAnalogies.LBLVSSourceElement{direct,use_UInduction,use_Doppler}.(asound, nu, radii_rs, ΞΈs_rs, dradii_rs, chord, twist_rs, Us_rs, alphas_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # Define the frequencies we'd like to evaluate. # BPM.jl uses the approximate 1/3rd-octave bands. freqs_obs = AcousticMetrics.ApproximateThirdOctaveCenterBands(100.0, 40000.0) freqs_src = freqs_obs # Now do the noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(lblvs_ses, Ref(obs), Ref(freqs_src)) # Separate out each source. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Combine each noise prediction. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) # Now I need to account for the fact that Figure 22b is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # (Dividing the MSP by Ξ”f_pbs aka the 1/3 octave spacing is like getting a power-spectral density, then multiplying by the narrowband spacing Ξ”f_nb gives us the MSP associated with the narrowband.) # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs nb_lblvs_untripped = pbs_lblvs .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) spl_lblvs_untripped = 10 .* log10.(nb_lblvs_untripped./(pref^2)) # Finally, let's get the BPM.jl predictions for this case, which we've run and saved previously in a JLD2/HDF5 file. freq_bpmjl = data_bpmjl["freqs"] spl_pressure_bpmjl = data_bpmjl["spl_nb_pressure"] spl_suction_bpmjl = data_bpmjl["spl_nb_suction"] spl_separation_bpmjl = data_bpmjl["spl_nb_separation"] spl_lblvs_bpmjl = data_bpmjl["spl_nb_lblvs"] spl_blunt_bpmjl = data_bpmjl["spl_nb_blunt"] spl_tip_bpmjl = data_bpmjl["spl_nb_tip"] # Now let's plot. fig = Figure() ax1 = fig[2, 1] = Axis(fig, xlabel="frequency, Hz", ylabel="SPL (dB Ref: 20 ΞΌPa), Ξ”f = 20 Hz", xscale=log10, xticks=[10^3, 10^4], xminorticksvisible=true, xminorgridvisible=true, xminorticks=IntervalsBetween(9), yticks=10:10:70)#, aspect=3) s_pressure = scatter!(ax1, freq_bpmjl, spl_pressure_bpmjl, color=:blue, marker=:rtriangle) s_suction = scatter!(ax1, freq_bpmjl, spl_suction_bpmjl, color=:red, marker=:ltriangle) s_separation = scatter!(ax1, freq_bpmjl, spl_separation_bpmjl, color=:yellow, marker=:diamond) s_lblvs = scatter!(ax1, freq_bpmjl, spl_lblvs_bpmjl, color=:purple, marker=:rect) s_blunt = scatter!(ax1, freq_bpmjl, spl_blunt_bpmjl, color=:green, marker=:star6) s_tip = scatter!(ax1, freq_bpmjl, spl_tip_bpmjl, color=:cyan, marker=:circle) l_pressure = lines!(ax1, freqs_obs, spl_pressure, color=:blue) l_suction = lines!(ax1, freqs_obs, spl_suction, color=:red) l_alpha = lines!(ax1, freqs_obs, spl_alpha, color=:yellow) l_lblvs = lines!(ax1, freqs_obs, spl_lblvs_untripped, color=:purple) l_teb = lines!(ax1, freqs_obs, spl_teb, color=:green) l_tip = lines!(ax1, freqs_obs, spl_tip, color=:cyan) xlims!(ax1, 2e2, 6e4) ylims!(ax1, 10.0, 70.0) leg = Legend(fig[1, 1], [ [s_pressure, l_pressure], [s_suction, l_suction], [s_separation, l_alpha], [s_lblvs, l_lblvs], [s_blunt, l_teb], [s_tip, l_tip], ], [ "TBLTE-Pressure", "TBLTE-Suction", "Separation", "LBLVS", "BVS", "Tip", ]; orientation=:horizontal, tellwidth=false, tellheight=true, nbanks=2) text!(ax1, 210, 62; text="markers: CCBlade.jl+BPM.jl\nlines: CCBlade.jl+AcousticAnalogies.jl") save("figure22b-spl-bpmjl.png", fig) ``` ![](figure22b-spl-bpmjl.png) ### Figure 23c ```@example figure23c using AcousticAnalogies using AcousticMetrics: AcousticMetrics using GLMakie using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, SteadyRotYTransformation, SteadyRotZTransformation, ConstantVelocityTransformation using FileIO: load using FLOWMath: Akima using StaticArrays: @SVector # Copied from BPM.jl (would like to add BPM.jl as a dependency if it's registered in General some day). # tip vortex noise correction data based on "Airfoil Tip Vortex Formation Noise" const bm_tip_alpha_aspect_data = [2.0,2.67,4.0,6.0,12.0,24.0] const bm_tip_alpha_aratio_data = [0.54,0.62,0.71,0.79,0.89,0.95] const bm_tip_alpha_aspect_ratio_correction = Akima(bm_tip_alpha_aspect_data, bm_tip_alpha_aratio_data) function bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) # compute tip lift curve slope if aspect_ratio < 2.0 aratio = 0.5*one(aspect_ratio) elseif 2.0 <= aspect_ratio <= 24.0 aratio = bm_tip_alpha_aspect_ratio_correction(aspect_ratio) elseif aspect_ratio > 24.0 aratio = 1.0*one(aspect_ratio) end return aratio end struct BMTipAlphaCorrection{TCorrection} <: AbstractTipAlphaCorrection correction::TCorrection function BMTipAlphaCorrection(aspect_ratio) # correction = BPM._tip_vortex_alpha_correction_nonsmooth(aspect_ratio) correction = bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) return new{typeof(correction)}(correction) end end function AcousticAnalogies.tip_vortex_alpha_correction(blade_tip::AbstractBladeTip{<:BMTipAlphaCorrection}, alphatip) a0l = AcousticAnalogies.alpha_zerolift(blade_tip) correction_factor = AcousticAnalogies.tip_alpha_correction(blade_tip).correction return correction_factor * (alphatip - a0l) + a0l end # Pettingill et al., "Acoustic And Performance Characteristics of an Ideally Twisted Rotor in Hover", 2021 # Parameters from Table 1 B = 4 # number of blades Rtip = 0.1588 # meters chord = 0.2*Rtip # Standard day: Tamb = 15 + 273.15 # 15Β°C in Kelvin pamb = 101325.0 # Pa R = 287.052874 # J/(kg*K) rho = pamb/(R*Tamb) asound = sqrt(1.4*R*Tamb) # Dynamic and kinematic viscosity mu = rho*1.4502e-5 nu = mu/rho # This is a hover case, so the freestream velocity should be zero. # CCBlade.jl will run with a zero freestream, but I've found that it compares a bit better with experiment if I give it a small non-zero value. Vinf = 0.001*asound # Figure 23 caption says Ξ©_c = 5510 RPM. rpm = 5510.0 omega = rpm * (2*pi/60) # Get "cell-centered" radial locations, and also the radial spacing. num_radial = 50 r_Rtip_ = range(0.2, 1.0; length=num_radial+1) r_Rtip = 0.5 .* (r_Rtip_[2:end] .+ r_Rtip_[1:end-1]) radii = r_Rtip .* Rtip dradii = (r_Rtip_[2:end] .- r_Rtip_[1:end-1]) .* Rtip Rhub = r_Rtip_[1]*Rtip # From Pettingill Equation (1), and value for Θ_tip in Table 1. Θ_tip = 6.9 * pi/180 twist = Θ_tip ./ (r_Rtip) # Need some aerodynamic quantities. # Got these using CCBlade.jl: see `AcousticAnalogies.jl/test/gen_bpmjl_data/itr_with_bpmjl.jl`. data_bpmjl = load(joinpath(@__DIR__, "..", "..", "test", "gen_bpmjl_data", "figure23c.jld2")) # Angle of attack at each radial station, radians. alpha = data_bpmjl["alpha"] # Flow speed normal to span at each radial station, m/s. U = data_bpmjl["U"] # In the Figure 23 caption, "for these predictions, bluntness thickness H was set to 0.5 mm and trailing edge angle Ξ¨ was set to 14 degrees." h = 0.5e-3 # meters Psi = 14*pi/180 # radians # We'll run for 1 blade pass, 20 time steps per blade pass. num_blade_pass = 1 num_src_times_blade_pass = 20 bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # BPM.jl uses a different tip alpha correction which appears to require the blade aspect ratio. # Need to find the blade aspect ratio of the ITR to apply the tip vortex angle of attack correction. # The aspect ratio is defined as the blade tip radius divided by the average chord, but the chord is constant for this case. aspect_ratio = Rtip / chord # Now we can create the tip object. alpha0lift = 0.0 blade_tip = AcousticAnalogies.FlatTip(BMTipAlphaCorrection(aspect_ratio), alpha0lift) # Start with a rotation about the negative x axis. positive_x_rotation = false rot_trans = SteadyRotXTransformation(t0, omega*ifelse(positive_x_rotation, 1, -1), 0) # Then translate along the positive x axis. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Then a 90Β° rotation about the negative z axis. trans_z90deg = SteadyRotZTransformation(0.0, 0.0, -0.5*pi) # Then a 90Β° rotation about the negative y axis. trans_y90deg = SteadyRotYTransformation(0.0, 0.0, -0.5*pi) # Put them all together: trans = compose.(src_times, Ref(trans_y90deg), compose.(src_times, Ref(trans_z90deg), compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)))) # Use the M_c = 0.8*M that BPM report and BPM.jl use. U = @. 0.8*sqrt(Vinf^2 + (omega*radii)^2) # For the boundary layer we want to use untripped for the 95% of the blade from the hub to almost tip, and then tripped for the last 5% of the blade at the tip. # First figure out how many of each we'll actually have with the `num_radial = 50` radial stations. num_untripped = Int(round(0.95*num_radial)) num_tripped = num_radial - num_untripped # Now create a length-`num_radial` vector of untripped and then tripped boundary layer objects. bls = vcat(fill(AcousticAnalogies.UntrippedN0012BoundaryLayer(), num_untripped), fill(AcousticAnalogies.TrippedN0012BoundaryLayer(), num_tripped)) # Now, the other trick: for this case, we're only going to include the LBLVS source where the local Reynolds number (with the chord as the length scale) is < 160000. low_Re_c = 160000.0 # So we need the Reynolds number for each section. Re_c = U .* chord / nu # Now we'll get a length-`num_radial` vector of Bools indicating if that criteria is satisfied or not. lblvs_flags = Re_c .< low_Re_c # Also we'll always be using the untripped boundary layer for LBLVS, like BPM.jl does. bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() # Paper doesn't specify the microphone used for Figure 23, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 23. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane. r_obs = 2.27 # meters theta_obs = -35*pi/180 # So, the docstring for BPM.jl says that `V` argument is the wind velocity in the y direction. # So I guess we should assume that the blades are rotating about the y axis. # And if the freestream velocity is in the positive y axis, then, from the perspective of the fluid, the blades are translating in the negative y direction. # And I want the observer to be downstream/behind the blades, so that would mean they would have a positive y position. # So I want to rotate the observer around the positive x axis, so I'm going to switch the sign on `theta_obs`. t0_obs = 0.0 x0_obs = @SVector [0.0, r_obs*sin(-theta_obs), r_obs*cos(-theta_obs)] # The observer is moving in the same direction as the blades, which is the negative y axis. v_obs = @SVector [0.0, -Vinf, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) .* ifelse(positive_x_rotation, 1, -1) # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) # chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) # hs_rs = reshape(hs, 1, :, 1) # Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] direct = AcousticAnalogies.BPMDirectivity use_UInduction = false use_Doppler = false mach_correction = AcousticAnalogies.NoMachCorrection ses_no_tip = CombinedNoTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord, twist_rs_no_tip, h, Psi, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord, twist_rs_with_tip, h, Psi, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # Put the source elements together: ses = cat(ses_no_tip, ses_with_tip; dims=2) # Need to do the LBLVS with the untripped boundary layer to match what BPM.jl is doing, and only where `lblvs_flags` is true. # So extract the radial locations where that's true. radii_lblvs = @view radii[lblvs_flags] dradii_lblvs = @view dradii[lblvs_flags] twist_lblvs = @view twist[lblvs_flags] Us_lblvs = @view U[lblvs_flags] alphas_lblvs = @view alpha[lblvs_flags] # Now do the usual reshaping. radii_lblvs_rs = reshape(radii_lblvs, 1, :, 1) dradii_lblvs_rs = reshape(dradii_lblvs, 1, :, 1) twist_lblvs_rs = reshape(twist_lblvs, 1, :, 1) Us_lblvs_rs = reshape(Us_lblvs, 1, :, 1) alphas_lblvs_rs = reshape(alphas_lblvs, 1, :, 1) # Now we can construct the lblvs source elements. lblvs_ses = AcousticAnalogies.LBLVSSourceElement{direct,use_UInduction,use_Doppler}.(asound, nu, radii_lblvs_rs, ΞΈs_rs, dradii_lblvs_rs, chord, twist_lblvs_rs, Us_lblvs_rs, alphas_lblvs_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # Define the frequencies we'd like to evaluate. # BPM.jl uses the approximate 1/3rd-octave bands. freqs_obs = AcousticMetrics.ApproximateThirdOctaveCenterBands(100.0, 40000.0) freqs_src = freqs_obs # Now do the noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(lblvs_ses, Ref(obs), Ref(freqs_src)) # Separate out each source. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Combine each noise prediction. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) # Now I need to account for the fact that Figure 23c is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # (Dividing the MSP by Ξ”f_pbs aka the 1/3 octave spacing is like getting a power-spectral density, then multiplying by the narrowband spacing Ξ”f_nb gives us the MSP associated with the narrowband.) # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs nb_lblvs_untripped = pbs_lblvs .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) spl_lblvs_untripped = 10 .* log10.(nb_lblvs_untripped./(pref^2)) # Finally, let's get the BPM.jl predictions for this case, which we've run and saved previously in a JLD2/HDF5 file. freq_bpmjl = data_bpmjl["freqs"] spl_pressure_bpmjl = data_bpmjl["spl_nb_pressure"] spl_suction_bpmjl = data_bpmjl["spl_nb_suction"] spl_separation_bpmjl = data_bpmjl["spl_nb_separation"] spl_lblvs_bpmjl = data_bpmjl["spl_nb_lblvs"] spl_blunt_bpmjl = data_bpmjl["spl_nb_blunt"] spl_tip_bpmjl = data_bpmjl["spl_nb_tip"] # Now let's plot. fig = Figure() ax1 = fig[2, 1] = Axis(fig, xlabel="frequency, Hz", ylabel="SPL (dB Ref: 20 ΞΌPa), Ξ”f = 20 Hz", xscale=log10, xticks=[10^3, 10^4], xminorticksvisible=true, xminorgridvisible=true, xminorticks=IntervalsBetween(9), yticks=10:10:70)#, aspect=3) s_pressure = scatter!(ax1, freq_bpmjl, spl_pressure_bpmjl, color=:blue, marker=:rtriangle) s_suction = scatter!(ax1, freq_bpmjl, spl_suction_bpmjl, color=:red, marker=:ltriangle) s_separation = scatter!(ax1, freq_bpmjl, spl_separation_bpmjl, color=:yellow, marker=:diamond) s_lblvs = scatter!(ax1, freq_bpmjl, spl_lblvs_bpmjl, color=:purple, marker=:rect) s_blunt = scatter!(ax1, freq_bpmjl, spl_blunt_bpmjl, color=:green, marker=:star6) s_tip = scatter!(ax1, freq_bpmjl, spl_tip_bpmjl, color=:cyan, marker=:circle) l_pressure = lines!(ax1, freqs_obs, spl_pressure, color=:blue) l_suction = lines!(ax1, freqs_obs, spl_suction, color=:red) l_alpha = lines!(ax1, freqs_obs, spl_alpha, color=:yellow) l_lblvs = lines!(ax1, freqs_obs, spl_lblvs_untripped, color=:purple) l_teb = lines!(ax1, freqs_obs, spl_teb, color=:green) l_tip = lines!(ax1, freqs_obs, spl_tip, color=:cyan) xlims!(ax1, 2e2, 6e4) ylims!(ax1, 10.0, 70.0) leg = Legend(fig[1, 1], [ [s_pressure, l_pressure], [s_suction, l_suction], [s_separation, l_alpha], [s_lblvs, l_lblvs], [s_blunt, l_teb], [s_tip, l_tip], ], [ "TBLTE-Pressure", "TBLTE-Suction", "Separation", "LBLVS", "BVS", "Tip", ]; orientation=:horizontal, tellwidth=false, tellheight=true, nbanks=2) text!(ax1, 210, 62; text="markers: CCBlade.jl+BPM.jl\nlines: CCBlade.jl+AcousticAnalogies.jl") save("figure23c-spl-bpmjl.png", fig) ``` ![](figure23c-spl-bpmjl.png) ### Figure 24b ```@example figure24b using AcousticAnalogies using AcousticMetrics: AcousticMetrics using GLMakie using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, SteadyRotYTransformation, SteadyRotZTransformation, ConstantVelocityTransformation using FileIO: load using FLOWMath: Akima using StaticArrays: @SVector # Copied from BPM.jl (would like to add BPM.jl as a dependency if it's registered in General some day). # tip vortex noise correction data based on "Airfoil Tip Vortex Formation Noise" const bm_tip_alpha_aspect_data = [2.0,2.67,4.0,6.0,12.0,24.0] const bm_tip_alpha_aratio_data = [0.54,0.62,0.71,0.79,0.89,0.95] const bm_tip_alpha_aspect_ratio_correction = Akima(bm_tip_alpha_aspect_data, bm_tip_alpha_aratio_data) function bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) # compute tip lift curve slope if aspect_ratio < 2.0 aratio = 0.5*one(aspect_ratio) elseif 2.0 <= aspect_ratio <= 24.0 aratio = bm_tip_alpha_aspect_ratio_correction(aspect_ratio) elseif aspect_ratio > 24.0 aratio = 1.0*one(aspect_ratio) end return aratio end struct BMTipAlphaCorrection{TCorrection} <: AbstractTipAlphaCorrection correction::TCorrection function BMTipAlphaCorrection(aspect_ratio) # correction = BPM._tip_vortex_alpha_correction_nonsmooth(aspect_ratio) correction = bm_tip_vortex_alpha_correction_nonsmooth(aspect_ratio) return new{typeof(correction)}(correction) end end function AcousticAnalogies.tip_vortex_alpha_correction(blade_tip::AbstractBladeTip{<:BMTipAlphaCorrection}, alphatip) a0l = AcousticAnalogies.alpha_zerolift(blade_tip) correction_factor = AcousticAnalogies.tip_alpha_correction(blade_tip).correction return correction_factor * (alphatip - a0l) + a0l end # Pettingill et al., "Acoustic And Performance Characteristics of an Ideally Twisted Rotor in Hover", 2021 # Parameters from Table 1 B = 4 # number of blades Rtip = 0.1588 # meters chord = 0.2*Rtip # Standard day: Tamb = 15 + 273.15 # 15Β°C in Kelvin pamb = 101325.0 # Pa R = 287.052874 # J/(kg*K) rho = pamb/(R*Tamb) asound = sqrt(1.4*R*Tamb) # Dynamic and kinematic viscosity mu = rho*1.4502e-5 nu = mu/rho # This is a hover case, so the freestream velocity should be zero. # CCBlade.jl will run with a zero freestream, but I've found that it compares a bit better with experiment if I give it a small non-zero value. Vinf = 0.001*asound # Figure 24 caption says Ξ©_c = 2938 RPM. rpm = 2938.0 omega = rpm * (2*pi/60) # Get "cell-centered" radial locations, and also the radial spacing. num_radial = 50 r_Rtip_ = range(0.2, 1.0; length=num_radial+1) r_Rtip = 0.5 .* (r_Rtip_[2:end] .+ r_Rtip_[1:end-1]) radii = r_Rtip .* Rtip dradii = (r_Rtip_[2:end] .- r_Rtip_[1:end-1]) .* Rtip Rhub = r_Rtip_[1]*Rtip # From Pettingill Equation (1), and value for Θ_tip in Table 1. Θ_tip = 6.9 * pi/180 twist = Θ_tip ./ (r_Rtip) # Need some aerodynamic quantities. # Got these using CCBlade.jl: see `AcousticAnalogies.jl/test/gen_bpmjl_data/itr_with_bpmjl.jl`. data_bpmjl = load(joinpath(@__DIR__, "..", "..", "test", "gen_bpmjl_data", "figure24b.jld2")) # Angle of attack at each radial station, radians. alpha = data_bpmjl["alpha"] # Flow speed normal to span at each radial station, m/s. U = data_bpmjl["U"] # In the Figure 24 caption, "for these predictions, bluntness thickness H was set to 0.5 mm and trailing edge angle Ξ¨ was set to 14 degrees." h = 0.5e-3 # meters Psi = 14*pi/180 # radians # We'll run for 1 blade pass, 20 time steps per blade pass. num_blade_pass = 1 num_src_times_blade_pass = 20 # Get the time levels we'll run. # First, get the blade passing period. bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) # Now we can get the total period of source time we'll run over. period_src = num_blade_pass*bpp # And th number of source times. num_src_times = num_src_times_blade_pass * num_blade_pass # We know the total time period and number of source times, so we can get the time step. dt = period_src/num_src_times # We'll arbitrarily start at time 0.0 seconds. t0 = 0.0 # And now we can finally get each source time. src_times = t0 .+ (0:num_src_times-1).*dt # BPM.jl uses a different tip alpha correction which appears to require the blade aspect ratio. # Need to find the blade aspect ratio of the ITR to apply the tip vortex angle of attack correction. # The aspect ratio is defined as the blade tip radius divided by the average chord, but the chord is constant for this case. aspect_ratio = Rtip / chord # Now we can create the tip object. alpha0lift = 0.0 blade_tip = AcousticAnalogies.FlatTip(BMTipAlphaCorrection(aspect_ratio), alpha0lift) # Start with a rotation about the negative x axis. positive_x_rotation = false rot_trans = SteadyRotXTransformation(t0, omega*ifelse(positive_x_rotation, 1, -1), 0) # Then translate along the positive x axis. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Then a 90Β° rotation about the negative z axis. trans_z90deg = SteadyRotZTransformation(0.0, 0.0, -0.5*pi) # Then a 90Β° rotation about the negative y axis. trans_y90deg = SteadyRotYTransformation(0.0, 0.0, -0.5*pi) # Put them all together: trans = compose.(src_times, Ref(trans_y90deg), compose.(src_times, Ref(trans_z90deg), compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)))) # Use the M_c = 0.8*M that BPM report and BPM.jl use. U = @. 0.8*sqrt(Vinf^2 + (omega*radii)^2) # For the boundary layer we want to use untripped for the 95% of the blade from the hub to almost tip, and then tripped for the last 5% of the blade at the tip. # First figure out how many of each we'll actually have with the `num_radial = 50` radial stations. num_untripped = Int(round(0.95*num_radial)) num_tripped = num_radial - num_untripped # Now create a length-`num_radial` vector of untripped and then tripped boundary layer objects. bls = vcat(fill(AcousticAnalogies.UntrippedN0012BoundaryLayer(), num_untripped), fill(AcousticAnalogies.TrippedN0012BoundaryLayer(), num_tripped)) # Also we'll always be using the untripped boundary layer for LBLVS, like BPM.jl does. bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() # Paper doesn't specify the microphone used for Figure 24, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 23. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane. r_obs = 2.27 # meters theta_obs = -35*pi/180 # So, the docstring for BPM.jl says that `V` argument is the wind velocity in the y direction. # So I guess we should assume that the blades are rotating about the y axis. # And if the freestream velocity is in the positive y axis, then, from the perspective of the fluid, the blades are translating in the negative y direction. # And I want the observer to be downstream/behind the blades, so that would mean they would have a positive y position. # So I want to rotate the observer around the positive x axis, so I'm going to switch the sign on `theta_obs`. t0_obs = 0.0 x0_obs = @SVector [0.0, r_obs*sin(-theta_obs), r_obs*cos(-theta_obs)] # The observer is moving in the same direction as the blades, which is the negative y axis. v_obs = @SVector [0.0, -Vinf, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) .* ifelse(positive_x_rotation, 1, -1) # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) # chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) # hs_rs = reshape(hs, 1, :, 1) # Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] # Use the directivity functions from the BPM report. direct = AcousticAnalogies.BPMDirectivity # Don't include induction for the velocity scale U. use_UInduction = false # Don't doppler-shift the source frequencies and source time steps to get observer frequencies & timesteps. use_Doppler = false # Don't use the Prandtl-Glauret Mach number correction that Brooks & Burley recommend. mach_correction = AcousticAnalogies.NoMachCorrection ses_no_tip = CombinedNoTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord, twist_rs_no_tip, h, Psi, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement{direct,use_UInduction,mach_correction,use_Doppler}.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord, twist_rs_with_tip, h, Psi, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # Put the source elements together: ses = cat(ses_no_tip, ses_with_tip; dims=2) # Need to do the LBLVS with the untripped boundary layer to match what BPM.jl is doing. lblvs_ses = AcousticAnalogies.LBLVSSourceElement{direct,use_UInduction,use_Doppler}.(asound, nu, radii_rs, ΞΈs_rs, dradii_rs, chord, twist_rs, Us_rs, alphas_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # Define the frequencies we'd like to evaluate. # BPM.jl uses the approximate 1/3rd-octave bands. freqs_obs = AcousticMetrics.ApproximateThirdOctaveCenterBands(100.0, 40000.0) freqs_src = freqs_obs # Now do the noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(lblvs_ses, Ref(obs), Ref(freqs_src)) # Separate out each source. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Combine each noise prediction. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) # Now I need to account for the fact that Figure 24b is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # (Dividing the MSP by Ξ”f_pbs aka the 1/3 octave spacing is like getting a power-spectral density, then multiplying by the narrowband spacing Ξ”f_nb gives us the MSP associated with the narrowband.) # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs nb_lblvs_untripped = pbs_lblvs .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) spl_lblvs_untripped = 10 .* log10.(nb_lblvs_untripped./(pref^2)) # Finally, let's get the BPM.jl predictions for this case, which we've run and saved previously in a JLD2/HDF5 file. freq_bpmjl = data_bpmjl["freqs"] spl_pressure_bpmjl = data_bpmjl["spl_nb_pressure"] spl_suction_bpmjl = data_bpmjl["spl_nb_suction"] spl_separation_bpmjl = data_bpmjl["spl_nb_separation"] spl_lblvs_bpmjl = data_bpmjl["spl_nb_lblvs"] spl_blunt_bpmjl = data_bpmjl["spl_nb_blunt"] spl_tip_bpmjl = data_bpmjl["spl_nb_tip"] # Now let's plot. fig = Figure() ax1 = fig[2, 1] = Axis(fig, xlabel="frequency, Hz", ylabel="SPL (dB Ref: 20 ΞΌPa), Ξ”f = 20 Hz", xscale=log10, xticks=[10^3, 10^4], xminorticksvisible=true, xminorgridvisible=true, xminorticks=IntervalsBetween(9), yticks=10:10:70)#, aspect=3) s_pressure = scatter!(ax1, freq_bpmjl, spl_pressure_bpmjl, color=:blue, marker=:rtriangle) s_suction = scatter!(ax1, freq_bpmjl, spl_suction_bpmjl, color=:red, marker=:ltriangle) s_separation = scatter!(ax1, freq_bpmjl, spl_separation_bpmjl, color=:yellow, marker=:diamond) s_lblvs = scatter!(ax1, freq_bpmjl, spl_lblvs_bpmjl, color=:purple, marker=:rect) s_blunt = scatter!(ax1, freq_bpmjl, spl_blunt_bpmjl, color=:green, marker=:star6) s_tip = scatter!(ax1, freq_bpmjl, spl_tip_bpmjl, color=:cyan, marker=:circle) l_pressure = lines!(ax1, freqs_obs, spl_pressure, color=:blue) l_suction = lines!(ax1, freqs_obs, spl_suction, color=:red) l_alpha = lines!(ax1, freqs_obs, spl_alpha, color=:yellow) l_lblvs = lines!(ax1, freqs_obs, spl_lblvs_untripped, color=:purple) l_teb = lines!(ax1, freqs_obs, spl_teb, color=:green) l_tip = lines!(ax1, freqs_obs, spl_tip, color=:cyan) xlims!(ax1, 2e2, 6e4) ylims!(ax1, 0.0, 50.0) leg = Legend(fig[1, 1], [ [s_pressure, l_pressure], [s_suction, l_suction], [s_separation, l_alpha], [s_lblvs, l_lblvs], [s_blunt, l_teb], [s_tip, l_tip], ], [ "TBLTE-Pressure", "TBLTE-Suction", "Separation", "LBLVS", "BVS", "Tip", ]; orientation=:horizontal, tellwidth=false, tellheight=true, nbanks=2) text!(ax1, 210, 44; text="markers: CCBlade.jl+BPM.jl\nlines: CCBlade.jl+AcousticAnalogies.jl") save("figure24b-spl-bpmjl.png", fig) ``` ![](figure24b-spl-bpmjl.png)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
43930
```@meta CurrentModule = AADocs ``` # Software Quality Assurance, Cont. ## PAS/ROTONET/BARC Comparisons for the Pettingill et al. Ideally Twisted Rotor See [here](http://dx.doi.org/10.2514/6.2021-1928) or [here](https://ntrs.nasa.gov/citations/20205003328) for details on the Ideally Twisted Rotor. ### Figure 22b ```@example figure22b using AcousticAnalogies using AcousticMetrics: AcousticMetrics using DelimitedFiles: readdlm using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, ConstantVelocityTransformation using FileIO: load using GLMakie using StaticArrays: @SVector # Pettingill et al., "Acoustic And Performance Characteristics of an Ideally Twisted Rotor in Hover", 2021 # Parameters from Table 1 B = 4 # number of blades Rtip = 0.1588 # meters chord = 0.2*Rtip # Standard day: Tamb = 15 + 273.15 # 15Β°C in Kelvin pamb = 101325.0 # Pa R = 287.052874 # J/(kg*K) rho = pamb/(R*Tamb) asound = sqrt(1.4*R*Tamb) # Dynamic and kinematic viscosity mu = rho*1.4502e-5 nu = mu/rho # This is a hover case, so the freestream velocity should be zero. # CCBlade.jl will run with a zero freestream, but I've found that it compares a bit better with experiment if I give it a small non-zero value. Vinf = 0.001*asound # Figure 22 caption says Ξ©_c = 5465 RPM. rpm = 5465.0 omega = rpm * (2*pi/60) # Get "cell-centered" radial locations, and also the radial spacing. num_radial = 50 r_Rtip_ = range(0.2, 1.0; length=num_radial+1) r_Rtip = 0.5 .* (r_Rtip_[2:end] .+ r_Rtip_[1:end-1]) radii = r_Rtip .* Rtip dradii = (r_Rtip_[2:end] .- r_Rtip_[1:end-1]) .* Rtip Rhub = r_Rtip_[1]*Rtip # From Pettingill Equation (1), and value for Θ_tip in Table 1. Θ_tip = 6.9 * pi/180 twist = Θ_tip ./ (r_Rtip) # Need some aerodynamic quantities. # Got these using CCBlade.jl: see `AcousticAnalogies.jl/test/gen_bpmjl_data/itr_with_bpmjl.jl`. data_ccblade = load(joinpath(@__DIR__, "..", "..", "test", "gen_bpmjl_data", "figure22b.jld2")) # Angle of attack at each radial station, radians. alpha = data_ccblade["alpha"] # Flow speed normal to span at each radial station, m/s. U = data_ccblade["U"] # In the text describing Figure 22, "For these predictions, the trip flag was set to β€œtripped”, due to the rough surface quality of the blade." bl = AcousticAnalogies.TrippedN0012BoundaryLayer() # But we're going to use the untripped boundary layer for the LBL-VS noise. bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() # In the Figure 22 caption, "for these predictions, bluntness thickness H was set to 0.8 mm and trailing edge angle Ξ¨ was set to 16 degrees." h = 0.8e-3 # meters Psi = 16*pi/180 # radians # We'll run for 1 blade pass, 20 time steps per blade pass. num_blade_pass = 1 num_src_times_blade_pass = 20 bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # I don't see any discussion for what type of tip was used for the tip vortex noise. # The flat tip seems to match the PAS+ROTONET+BARC predictions well. blade_tip = AcousticAnalogies.FlatTip() # Now let's define the coordinate system. # I'm going to do my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # And the blades will be rotating about the positive x axis at a rate of `omega`. rot_trans = SteadyRotXTransformation(t0, omega, 0.0) # The hub/rotation axis of the blades will start at the origin at time `t0`, and translate in the positive x direction at a speed of `Vinf`. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] # m/s const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Now I can put the two transformations together: trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) # Paper doesn't specify the microphone used for Figure 22, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 22. # For the coordinate system, I'm doing my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane, so this should be good. # But it will of course be moving with the same freestream in the positive x direction. r_obs = 2.27 # meters theta_obs = -35*pi/180 # The observer is moving in the positive x direction at Vinf, at the origin at time t0. t0_obs = 0.0 x0_obs = @SVector [r_obs*sin(theta_obs), r_obs*cos(theta_obs), 0.0] v_obs = @SVector [Vinf, 0.0, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) # chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) # hs_rs = reshape(hs, 1, :, 1) # Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) # bls_rs = reshape(bls, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] # chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] # hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] # Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] # chord_rs_with_tip = @view chord_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] # hs_rs_with_tip = @view hs_rs[:, end:end, :] # Psis_rs_with_tip = @view Psis_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] positive_x_rotation = true ses_no_tip = CombinedNoTipBroadbandSourceElement.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord, twist_rs_no_tip, h, Psi, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, Ref(bl), positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord, twist_rs_with_tip, h, Psi, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, Ref(bl), Ref(blade_tip), positive_x_rotation) .|> trans # It's more convinient to cat all the sources together. ses = cat(ses_no_tip, ses_with_tip; dims=2) # Do the LBLVS prediction with the untripped boundary layer. ses_lblvs = LBLVSSourceElement.(asound, nu, radii_rs, ΞΈs_rs, dradii_rs, chord, twist_rs, Us_rs, alphas_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # The predictions in Figure 22b appear to be on 1/3 octave, ranging from about 200 Hz to 60,000 Hz. # But let's expand the range of source frequencies to account for Doppler shifting. freqs_src = AcousticMetrics.ExactProportionalBands{3, :center}(10.0, 200000.0) freqs_obs = AcousticMetrics.ExactProportionalBands{3, :center}(200.0, 60000.0) # Now we can do a noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(ses_lblvs, Ref(obs), Ref(freqs_src)) # This seperates out the noise prediction for each source-observer combination into the different sources. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) # pbs_lblvss = AcousticAnalogies.pbs_lblvs.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Now, need to combine each broadband noise prediction. # The time axis the axis over which the time varies for each source. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) # Now I need to account for the fact that Figure 22b is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_lblvs = pbs_lblvs .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_lblvs = 10 .* log10.(nb_lblvs./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) # Now I should be able to compare to the BARC data. # Need to read it in first. data_pressure_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-TBL-TE-pressure-2.csv"), ',') freq_pressure_barc = data_pressure_barc[:, 1] spl_pressure_barc = data_pressure_barc[:, 2] data_suction_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-TBL-TE-suction-2.csv"), ',') freq_suction_barc = data_suction_barc[:, 1] spl_suction_barc = data_suction_barc[:, 2] data_separation_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-separation-2.csv"), ',') freq_separation_barc = data_separation_barc[:, 1] spl_separation_barc = data_separation_barc[:, 2] # data_lblvs_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-LBLVS.csv"), ',') # freq_lblvs_barc = data_lblvs_barc[:, 1] # spl_lblvs_barc = data_lblvs_barc[:, 2] data_teb_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-BVS.csv"), ',') freq_teb_barc = data_teb_barc[:, 1] spl_teb_barc = data_teb_barc[:, 2] data_tip_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure22b-tip_vortex_shedding.csv"), ',') freq_tip_barc = data_tip_barc[:, 1] spl_tip_barc = data_tip_barc[:, 2] # Now let's plot. fig = Figure() ax1 = fig[2, 1] = Axis(fig, xlabel="frequency, Hz", ylabel="SPL (dB Ref: 20 ΞΌPa), Ξ”f = 20 Hz", xscale=log10, xticks=[10^3, 10^4], xminorticksvisible=true, xminorgridvisible=true, xminorticks=IntervalsBetween(9), yticks=10:10:70)#, aspect=3) s_pressure = scatter!(ax1, freq_pressure_barc, spl_pressure_barc, color=:blue, marker=:rtriangle) s_suction = scatter!(ax1, freq_suction_barc, spl_suction_barc, color=:red, marker=:ltriangle) s_separation = scatter!(ax1, freq_separation_barc, spl_separation_barc, color=:yellow, marker=:diamond) # s_lblvs = scatter!(ax1, freq_lblvs_barc, spl_lblvs_barc, color=:purple, marker=:rect) s_blunt = scatter!(ax1, freq_teb_barc, spl_teb_barc, color=:green, marker=:star6) s_tip = scatter!(ax1, freq_tip_barc, spl_tip_barc, color=:cyan, marker=:circle) l_pressure = lines!(ax1, freqs_obs, spl_pressure, color=:blue) l_suction = lines!(ax1, freqs_obs, spl_suction, color=:red) l_alpha = lines!(ax1, freqs_obs, spl_alpha, color=:yellow) # l_lblvs = lines!(ax1, freqs_obs, spl_lblvs, color=:purple) l_teb = lines!(ax1, freqs_obs, spl_teb, color=:green) l_tip = lines!(ax1, freqs_obs, spl_tip, color=:cyan) xlims!(ax1, 2e2, 6e4) ylims!(ax1, 10.0, 70.0) leg = Legend(fig[1, 1], [ [s_pressure, l_pressure], [s_suction, l_suction], [s_separation, l_alpha], # [s_lblvs, l_lblvs], [s_blunt, l_teb], [s_tip, l_tip], ], [ "TBLTE-Pressure", "TBLTE-Suction", "Separation", # "LBLVS", "BVS", "Tip", ]; orientation=:horizontal, tellwidth=false, tellheight=true, nbanks=2) text!(ax1, 210, 62; text="markers: CCBlade.jl+BPM.jl\nlines: CCBlade.jl+AcousticAnalogies.jl") save("figure22b-spl-barc.png", fig) ``` ![](figure22b-spl-barc.png) ### Figure 23c ```@example figure23c using AcousticAnalogies using AcousticMetrics: AcousticMetrics using DelimitedFiles: readdlm using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, ConstantVelocityTransformation using FileIO: load using GLMakie using StaticArrays: @SVector # Pettingill et al., "Acoustic And Performance Characteristics of an Ideally Twisted Rotor in Hover", 2021 # Parameters from Table 1 B = 4 # number of blades Rtip = 0.1588 # meters chord = 0.2*Rtip # Standard day: Tamb = 15 + 273.15 # 15Β°C in Kelvin pamb = 101325.0 # Pa R = 287.052874 # J/(kg*K) rho = pamb/(R*Tamb) asound = sqrt(1.4*R*Tamb) # Dynamic and kinematic viscosity mu = rho*1.4502e-5 nu = mu/rho # This is a hover case, so the freestream velocity should be zero. # CCBlade.jl will run with a zero freestream, but I've found that it compares a bit better with experiment if I give it a small non-zero value. Vinf = 0.001*asound # Figure 23 caption says Ξ©_c = 5510 RPM. rpm = 5510.0 omega = rpm * (2*pi/60) # Get "cell-centered" radial locations, and also the radial spacing. num_radial = 50 r_Rtip_ = range(0.2, 1.0; length=num_radial+1) r_Rtip = 0.5 .* (r_Rtip_[2:end] .+ r_Rtip_[1:end-1]) radii = r_Rtip .* Rtip dradii = (r_Rtip_[2:end] .- r_Rtip_[1:end-1]) .* Rtip Rhub = r_Rtip_[1]*Rtip # From Pettingill Equation (1), and value for Θ_tip in Table 1. Θ_tip = 6.9 * pi/180 twist = Θ_tip ./ (r_Rtip) # Need some aerodynamic quantities. # Got these using CCBlade.jl: see `AcousticAnalogies.jl/test/gen_bpmjl_data/itr_with_bpmjl.jl`. data_ccblade = load(joinpath(@__DIR__, "..", "..", "test", "gen_bpmjl_data", "figure23c.jld2")) # Angle of attack at each radial station, radians. alpha = data_ccblade["alpha"] # Flow speed normal to span at each radial station, m/s. U = data_ccblade["U"] # So, for the boundary layer, we want to use untripped for the 95% of the blade from the hub to almost tip, and then tripped for the last 5% of the blade at the tip. num_untripped = Int(round(0.95*num_radial)) num_tripped = num_radial - num_untripped bls_untripped = fill(AcousticAnalogies.UntrippedN0012BoundaryLayer(), num_untripped) bls_tripped = fill(AcousticAnalogies.TrippedN0012BoundaryLayer(), num_tripped) bls = vcat(bls_untripped, bls_tripped) # Now, the other trick: need to only include LBLVS noise for elements where the Reynolds number is < 160000. # So, we need the Reynolds number for each section. Re_c = @. U * chord / nu # So now we want to extract the radial stations that meet that < 160000 condition. low_Re_c = 160000 mask_low_Re_c = Re_c .< low_Re_c # And we're also going to use the untripped boundary layer for the LBLVS source. bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() # In the Figure 23 caption, "for these predictions, bluntness thickness H was set to 0.5 mm and trailing edge angle Ξ¨ was set to 14 degrees." h = 0.5e-3 # meters Psi = 14*pi/180 # radians # We'll run for 1 blade pass, 20 time steps per blade pass. num_blade_pass = 1 num_src_times_blade_pass = 20 bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) period_src = num_blade_pass*bpp num_src_times = num_src_times_blade_pass * num_blade_pass t0 = 0.0 dt = period_src/num_src_times src_times = t0 .+ (0:num_src_times-1).*dt # I don't see any discussion for what type of tip was used for the tip vortex noise. # The flat tip seems to match the PAS+ROTONET+BARC predictions well. blade_tip = AcousticAnalogies.FlatTip() # Now let's define the coordinate system. # I'm going to do my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # And the blades will be rotating about the positive x axis at a rate of `omega`. rot_trans = SteadyRotXTransformation(t0, omega, 0.0) # The hub/rotation axis of the blades will start at the origin at time `t0`, and translate in the positive x direction at a speed of `Vinf`. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] # m/s const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Now I can put the two transformations together: trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) # Paper doesn't specify the microphone used for Figure 22, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 22. # For the coordinate system, I'm doing my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane, so this should be good. # But it will of course be moving with the same freestream in the positive x direction. r_obs = 2.27 # meters theta_obs = -35*pi/180 # The observer is moving in the positive x direction at Vinf, at the origin at time t0. t0_obs = 0.0 x0_obs = @SVector [r_obs*sin(theta_obs), r_obs*cos(theta_obs), 0.0] v_obs = @SVector [Vinf, 0.0, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) # chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) # hs_rs = reshape(hs, 1, :, 1) # Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] # chord_rs_no_tip = @view chord_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] # hs_rs_no_tip = @view hs_rs[:, begin:end-1, :] # Psis_rs_no_tip = @view Psis_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] # chord_rs_with_tip = @view chord_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] # hs_rs_with_tip = @view hs_rs[:, end:end, :] # Psis_rs_with_tip = @view Psis_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] positive_x_rotation = true ses_no_tip = CombinedNoTipBroadbandSourceElement.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord, twist_rs_no_tip, h, Psi, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord, twist_rs_with_tip, h, Psi, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # It's more convinient to cat all the sources together. ses = cat(ses_no_tip, ses_with_tip; dims=2) # Need to do the LBLVS stuff separately. # Grab the parts of the inputs that correspond to the low Reynolds number stations. radii_lblvs = @view radii[mask_low_Re_c] dradii_lblvs = @view dradii[mask_low_Re_c] # chord_lblvs = @view chord[mask_low_Re_c] twist_lblvs = @view twist[mask_low_Re_c] # hs_lblvs = @view hs[mask_low_Re_c] # Psis_lblvs = @view Psis[mask_low_Re_c] Us_lblvs = @view U[mask_low_Re_c] alphas_lblvs = @view alpha[mask_low_Re_c] # And do the reshaping. radii_lblvs_rs = reshape(radii_lblvs, 1, :, 1) dradii_lblvs_rs = reshape(dradii_lblvs, 1, :, 1) # chord_lblvs_rs = reshape(chord_lblvs, 1, :, 1) twist_lblvs_rs = reshape(twist_lblvs, 1, :, 1) # hs_lblvs_rs = reshape(hs_lblvs, 1, :, 1) # Psis_lblvs_rs = reshape(Psis_lblvs, 1, :, 1) Us_lblvs_rs = reshape(Us_lblvs, 1, :, 1) alphas_lblvs_rs = reshape(alphas_lblvs, 1, :, 1) # Now we can create the source elements. ses_lblvs = LBLVSSourceElement.(asound, nu, radii_lblvs_rs, ΞΈs_rs, dradii_lblvs_rs, chord, twist_lblvs_rs, Us_lblvs_rs, alphas_lblvs_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # Now we can create the source elements. ses_lblvs = LBLVSSourceElement.(asound, nu, radii_lblvs_rs, ΞΈs_rs, dradii_lblvs_rs, chord, twist_lblvs_rs, Us_lblvs_rs, alphas_lblvs_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # The predictions in Figure 23c appear to be on 1/3 octave, ranging from about 200 Hz to 60,000 Hz. # But let's expand the range of source frequencies to account for Doppler shifting. freqs_src = AcousticMetrics.ExactProportionalBands{3, :center}(10.0, 200000.0) freqs_obs = AcousticMetrics.ExactProportionalBands{3, :center}(200.0, 60000.0) # Now we can do a noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(ses_lblvs, Ref(obs), Ref(freqs_src)) # This seperates out the noise prediction for each source-observer combination into the different sources. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Now, need to combine each broadband noise prediction. # The time axis the axis over which the time varies for each source. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) # Now I need to account for the fact that Figure 23c is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_lblvs = pbs_lblvs .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_lblvs = 10 .* log10.(nb_lblvs./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) # Now I should be able to compare to the BARC data. # Need to read it in first. data_pressure_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-TBL-TE-pressure.csv"), ',') freq_pressure_barc = data_pressure_barc[:, 1] spl_pressure_barc = data_pressure_barc[:, 2] data_suction_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-TBL-TE-suction.csv"), ',') freq_suction_barc = data_suction_barc[:, 1] spl_suction_barc = data_suction_barc[:, 2] data_separation_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-separation.csv"), ',') freq_separation_barc = data_separation_barc[:, 1] spl_separation_barc = data_separation_barc[:, 2] data_lblvs_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-LBLVS.csv"), ',') freq_lblvs_barc = data_lblvs_barc[:, 1] spl_lblvs_barc = data_lblvs_barc[:, 2] data_teb_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-BVS.csv"), ',') freq_teb_barc = data_teb_barc[:, 1] spl_teb_barc = data_teb_barc[:, 2] data_tip_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure23c-tip_vortex_shedding.csv"), ',') freq_tip_barc = data_tip_barc[:, 1] spl_tip_barc = data_tip_barc[:, 2] # Now let's plot. fig = Figure() ax1 = fig[2, 1] = Axis(fig, xlabel="frequency, Hz", ylabel="SPL (dB Ref: 20 ΞΌPa), Ξ”f = 20 Hz", xscale=log10, xticks=[10^3, 10^4], xminorticksvisible=true, xminorgridvisible=true, xminorticks=IntervalsBetween(9), yticks=10:10:70)#, aspect=3) s_pressure = scatter!(ax1, freq_pressure_barc, spl_pressure_barc, color=:blue, marker=:rtriangle) s_suction = scatter!(ax1, freq_suction_barc, spl_suction_barc, color=:red, marker=:ltriangle) s_separation = scatter!(ax1, freq_separation_barc, spl_separation_barc, color=:yellow, marker=:diamond) s_lblvs = scatter!(ax1, freq_lblvs_barc, spl_lblvs_barc, color=:purple, marker=:rect) s_blunt = scatter!(ax1, freq_teb_barc, spl_teb_barc, color=:green, marker=:star6) s_tip = scatter!(ax1, freq_tip_barc, spl_tip_barc, color=:cyan, marker=:circle) l_pressure = lines!(ax1, freqs_obs, spl_pressure, color=:blue) l_suction = lines!(ax1, freqs_obs, spl_suction, color=:red) l_alpha = lines!(ax1, freqs_obs, spl_alpha, color=:yellow) l_lblvs = lines!(ax1, freqs_obs, spl_lblvs, color=:purple) l_teb = lines!(ax1, freqs_obs, spl_teb, color=:green) l_tip = lines!(ax1, freqs_obs, spl_tip, color=:cyan) xlims!(ax1, 2e2, 6e4) ylims!(ax1, 10.0, 70.0) leg = Legend(fig[1, 1], [ [s_pressure, l_pressure], [s_suction, l_suction], [s_separation, l_alpha], [s_lblvs, l_lblvs], [s_blunt, l_teb], [s_tip, l_tip], ], [ "TBLTE-Pressure", "TBLTE-Suction", "Separation", "LBLVS", "BVS", "Tip", ]; orientation=:horizontal, tellwidth=false, tellheight=true, nbanks=2) text!(ax1, 210, 62; text="markers: CCBlade.jl+BPM.jl\nlines: CCBlade.jl+AcousticAnalogies.jl") save("figure23c-spl-barc.png", fig) ``` ![](figure23c-spl-barc.png) ### Figure 24b ```@example figure24b using AcousticAnalogies using AcousticMetrics: AcousticMetrics using DelimitedFiles: readdlm using KinematicCoordinateTransformations: compose, SteadyRotXTransformation, ConstantVelocityTransformation using FileIO: load using GLMakie using StaticArrays: @SVector # Pettingill et al., "Acoustic And Performance Characteristics of an Ideally Twisted Rotor in Hover", 2021 # Parameters from Table 1 B = 4 # number of blades Rtip = 0.1588 # meters chord = 0.2*Rtip # Standard day: Tamb = 15 + 273.15 # 15Β°C in Kelvin pamb = 101325.0 # Pa R = 287.052874 # J/(kg*K) rho = pamb/(R*Tamb) asound = sqrt(1.4*R*Tamb) # Dynamic and kinematic viscosity mu = rho*1.4502e-5 nu = mu/rho # This is a hover case, so the freestream velocity should be zero. # CCBlade.jl will run with a zero freestream, but I've found that it compares a bit better with experiment if I give it a small non-zero value. Vinf = 0.001*asound # Figure 24 caption says Ξ©_c = 2938 RPM. rpm = 2938.0 omega = rpm * (2*pi/60) # Get "cell-centered" radial locations, and also the radial spacing. num_radial = 50 r_Rtip_ = range(0.2, 1.0; length=num_radial+1) r_Rtip = 0.5 .* (r_Rtip_[2:end] .+ r_Rtip_[1:end-1]) radii = r_Rtip .* Rtip dradii = (r_Rtip_[2:end] .- r_Rtip_[1:end-1]) .* Rtip Rhub = r_Rtip_[1]*Rtip # From Pettingill Equation (1), and value for Θ_tip in Table 1. Θ_tip = 6.9 * pi/180 twist = Θ_tip ./ (r_Rtip) # Need some aerodynamic quantities. # Got these using CCBlade.jl: see `AcousticAnalogies.jl/test/gen_bpmjl_data/itr_with_bpmjl.jl`. data_ccblade = load(joinpath(@__DIR__, "..", "..", "test", "gen_bpmjl_data", "figure24b.jld2")) # Angle of attack at each radial station, radians. alpha = data_ccblade["alpha"] # Flow speed normal to span at each radial station, m/s. U = data_ccblade["U"] # In the Figure 24 caption, "for these predictions, bluntness thickness H was set to 0.5 mm and trailing edge angle Ξ¨ was set to 14 degrees." h = 0.5e-3 # meters Psi = 14*pi/180 # radians # We'll run for 1 blade pass, 20 time steps per blade pass. num_blade_pass = 1 num_src_times_blade_pass = 20 # Get the time levels we'll run. # First, get the blade passing period. bpp = 1/(B/(2*pi)*omega) # 1/(B blade_passes/rev * 1 rev / (2*pi rad) * omega rad/s) # Now we can get the total period of source time we'll run over. period_src = num_blade_pass*bpp # And the number of source times. num_src_times = num_src_times_blade_pass * num_blade_pass # We know the total time period and number of source times, so we can get the time step. dt = period_src/num_src_times # We'll arbitrarily start at time 0.0 seconds. t0 = 0.0 # And now we can finally get each source time. src_times = t0 .+ (0:num_src_times-1).*dt # Now let's define the coordinate system. # I'm going to do my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # And the blades will be rotating about the positive x axis at a rate of `omega`. rot_trans = SteadyRotXTransformation(t0, omega, 0.0) # The hub/rotation axis of the blades will start at the origin at time `t0`, and translate in the positive x direction at a speed of `Vinf`. y0_hub = @SVector [0.0, 0.0, 0.0] # m v0_hub = @SVector [Vinf, 0.0, 0.0] # m/s const_vel_trans = ConstantVelocityTransformation(t0, y0_hub, v0_hub) # Now I can put the two transformations together: trans = compose.(src_times, Ref(const_vel_trans), Ref(rot_trans)) # Azimuthal offset for each blade. ΞΈs = (0:(B-1)) .* (2*pi/B) # For the boundary layer we want to use untripped for the 95% of the blade from the hub to almost tip, and then tripped for the last 5% of the blade at the tip. # First figure out how many of each we'll actually have with the `num_radial = 50` radial stations. num_untripped = Int(round(0.95*num_radial)) num_tripped = num_radial - num_untripped # Now create a length-`num_radial` vector of untripped and then tripped boundary layer objects. bls = vcat(fill(AcousticAnalogies.UntrippedN0012BoundaryLayer(), num_untripped), fill(AcousticAnalogies.TrippedN0012BoundaryLayer(), num_tripped)) # But we'll always use the untripped boundary layer with LBLVS. bl_lblvs = AcousticAnalogies.UntrippedN0012BoundaryLayer() # I don't see any discussion for what type of tip was used for the tip vortex noise. # The flat tip seems to match the PAS+ROTONET+BARC predictions well. blade_tip = AcousticAnalogies.FlatTip() # Paper doesn't specify the microphone used for Figure 24, but earlier at the beginning of "C. Noise Characteristics and Trends" there is this: # > For the purposes of this paper, presented acoustic spectra will correspond to an observer located βˆ’35Β° below the plane of the rotor (microphone 5). # So I'll just assume that holds for Figure 24. # For the coordinate system, I'm doing my usual thing, which is to have the freestream velocity pointed in the negative x direction, and thus the blades will be translating in the positive x direction. # The observer (microphone 5) is 35 deg behind/downstream of the rotor rotation plane, so this should be good. # But it will of course be moving with the same freestream in the positive x direction. r_obs = 2.27 # meters theta_obs = -35*pi/180 # The observer is moving in the positive x direction at Vinf, at the origin at time t0. t0_obs = 0.0 x0_obs = @SVector [r_obs*sin(theta_obs), r_obs*cos(theta_obs), 0.0] v_obs = @SVector [Vinf, 0.0, 0.0] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) # Reshape the inputs to the source element constructors so that everything will line up with (num_times, num_radial, num_blades). ΞΈs_rs = reshape(ΞΈs, 1, 1, :) radii_rs = reshape(radii, 1, :, 1) dradii_rs = reshape(dradii, 1, :, 1) # chord_rs = reshape(chord, 1, :, 1) twist_rs = reshape(twist, 1, :, 1) # hs_rs = reshape(hs, 1, :, 1) # Psis_rs = reshape(Psis, 1, :, 1) Us_rs = reshape(U, 1, :, 1) alphas_rs = reshape(alpha, 1, :, 1) bls_rs = reshape(bls, 1, :, 1) # Separate things into tip and no-tip. radii_rs_no_tip = @view radii_rs[:, begin:end-1, :] dradii_rs_no_tip = @view dradii_rs[:, begin:end-1, :] twist_rs_no_tip = @view twist_rs[:, begin:end-1, :] Us_rs_no_tip = @view Us_rs[:, begin:end-1, :] alphas_rs_no_tip = @view alphas_rs[:, begin:end-1, :] bls_rs_no_tip = @view bls_rs[:, begin:end-1, :] radii_rs_with_tip = @view radii_rs[:, end:end, :] dradii_rs_with_tip = @view dradii_rs[:, end:end, :] twist_rs_with_tip = @view twist_rs[:, end:end, :] Us_rs_with_tip = @view Us_rs[:, end:end, :] alphas_rs_with_tip = @view alphas_rs[:, end:end, :] bls_rs_with_tip = @view bls_rs[:, end:end, :] positive_x_rotation = true ses_no_tip = CombinedNoTipBroadbandSourceElement.(asound, nu, radii_rs_no_tip, ΞΈs_rs, dradii_rs_no_tip, chord, twist_rs_no_tip, h, Psi, Us_rs_no_tip, alphas_rs_no_tip, src_times, dt, bls_rs_no_tip, positive_x_rotation) .|> trans ses_with_tip = CombinedWithTipBroadbandSourceElement.(asound, nu, radii_rs_with_tip, ΞΈs_rs, dradii_rs_with_tip, chord, twist_rs_with_tip, h, Psi, Us_rs_with_tip, alphas_rs_with_tip, src_times, dt, bls_rs_with_tip, Ref(blade_tip), positive_x_rotation) .|> trans # Put the source elements together: ses = cat(ses_no_tip, ses_with_tip; dims=2) # Need to do the LBLVS with the untripped boundary layer. ses_lblvs = AcousticAnalogies.LBLVSSourceElement.(asound, nu, radii_rs, ΞΈs_rs, dradii_rs, chord, twist_rs, Us_rs, alphas_rs, src_times, dt, Ref(bl_lblvs), positive_x_rotation) .|> trans # The predictions in Figure 24b appear to be on 1/3 octave, ranging from about 200 Hz to 60,000 Hz. # But let's expand the range of source frequencies to account for Doppler shifting. freqs_src = AcousticMetrics.ExactProportionalBands{3, :center}(10.0, 200000.0) freqs_obs = AcousticMetrics.ExactProportionalBands{3, :center}(200.0, 60000.0) # Now we can do a noise prediction. bpm_outs = AcousticAnalogies.noise.(ses, Ref(obs), Ref(freqs_src)) pbs_lblvss = AcousticAnalogies.noise.(ses_lblvs, Ref(obs), Ref(freqs_src)) # This seperates out the noise prediction for each source-observer combination into the different sources. pbs_tblte_ps = AcousticAnalogies.pbs_pressure.(bpm_outs) pbs_tblte_ss = AcousticAnalogies.pbs_suction.(bpm_outs) pbs_tblte_alphas = AcousticAnalogies.pbs_alpha.(bpm_outs) pbs_tebs = AcousticAnalogies.pbs_teb.(bpm_outs) pbs_tips = AcousticAnalogies.pbs_tip.(bpm_outs[:, end:end, :]) # Now, need to combine each broadband noise prediction. # The time axis the axis over which the time varies for each source. time_axis = 1 pbs_pressure = AcousticMetrics.combine(pbs_tblte_ps, freqs_obs, time_axis) pbs_suction = AcousticMetrics.combine(pbs_tblte_ss, freqs_obs, time_axis) pbs_alpha = AcousticMetrics.combine(pbs_tblte_alphas, freqs_obs, time_axis) pbs_teb = AcousticMetrics.combine(pbs_tebs, freqs_obs, time_axis) pbs_tip = AcousticMetrics.combine(pbs_tips, freqs_obs, time_axis) pbs_lblvs = AcousticMetrics.combine(pbs_lblvss, freqs_obs, time_axis) # Now I need to account for the fact that Figure 24b is actually comparing to narrowband experimental data with a frequency spacing of 20 Hz. # So, to do that, I need to multiply the mean-squared pressure by Ξ”f_nb/Ξ”f_pbs, where `Ξ”f_nb` is the 20 Hz narrowband and `Ξ”f_pbs` is the bandwidth of each 1/3-octave proportional band. # I think the paper describes that, right? # Right, here's something: # # > The current prediction method is limited to one-third octave bands, but it is compared to the narrowband experiment with Ξ”f = 20 Hz. # > This is done by dividing the energy from the one-third octave bands by the number of bands in Ξ”f = 20 Hz. # # So, `Ξ”f_pbs/Ξ”f_nb` would represent the number of `Ξ”f_nb`-width bands that could fit in a proportional band of bin width `Ξ”f_pbs`. # And then I'm dividing by that. # So that seems like the right thing. # So, first thing is to get the proportional band spacing. freqs_l = AcousticMetrics.lower_bands(freqs_obs) freqs_u = AcousticMetrics.upper_bands(freqs_obs) df_pbs = freqs_u .- freqs_l # Also need the experimental narrowband spacing. df_nb = 20.0 # Now multiply each by that. nb_pressure = pbs_pressure .* df_nb ./ df_pbs nb_suction = pbs_suction .* df_nb ./ df_pbs nb_alpha = pbs_alpha .* df_nb ./ df_pbs nb_lblvs = pbs_lblvs .* df_nb ./ df_pbs nb_teb = pbs_teb .* df_nb ./ df_pbs nb_tip = pbs_tip .* df_nb ./ df_pbs # Now I want the SPL, which should just be this: pref = 20e-6 spl_pressure = 10 .* log10.(nb_pressure./(pref^2)) spl_suction = 10 .* log10.(nb_suction./(pref^2)) spl_alpha = 10 .* log10.(nb_alpha./(pref^2)) spl_lblvs = 10 .* log10.(nb_lblvs./(pref^2)) spl_teb = 10 .* log10.(nb_teb./(pref^2)) spl_tip = 10 .* log10.(nb_tip./(pref^2)) # Now I should be able to compare to the BARC data. # Need to read it in first. data_pressure_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-TBL-TE-pressure.csv"), ',') freq_pressure_barc = data_pressure_barc[:, 1] spl_pressure_barc = data_pressure_barc[:, 2] data_suction_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-TBL-TE-suction.csv"), ',') freq_suction_barc = data_suction_barc[:, 1] spl_suction_barc = data_suction_barc[:, 2] data_separation_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-separation.csv"), ',') freq_separation_barc = data_separation_barc[:, 1] spl_separation_barc = data_separation_barc[:, 2] data_lblvs_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-LBLVS.csv"), ',') freq_lblvs_barc = data_lblvs_barc[:, 1] spl_lblvs_barc = data_lblvs_barc[:, 2] data_teb_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-BVS.csv"), ',') freq_teb_barc = data_teb_barc[:, 1] spl_teb_barc = data_teb_barc[:, 2] data_tip_barc = readdlm(joinpath(@__DIR__, "..", "..", "test", "bpm_data", "pettingill_acoustic_performance_characteristics_of_ideally_twisted_rotor_in_hover_2021", "figure24b-tip_vortex_shedding.csv"), ',') freq_tip_barc = data_tip_barc[:, 1] spl_tip_barc = data_tip_barc[:, 2] # Now let's plot. fig = Figure() ax1 = fig[2, 1] = Axis(fig, xlabel="frequency, Hz", ylabel="SPL (dB Ref: 20 ΞΌPa), Ξ”f = 20 Hz", xscale=log10, xticks=[10^3, 10^4], xminorticksvisible=true, xminorgridvisible=true, xminorticks=IntervalsBetween(9), yticks=10:10:70)#, aspect=3) s_pressure = scatter!(ax1, freq_pressure_barc, spl_pressure_barc, color=:blue, marker=:rtriangle) s_suction = scatter!(ax1, freq_suction_barc, spl_suction_barc, color=:red, marker=:ltriangle) s_separation = scatter!(ax1, freq_separation_barc, spl_separation_barc, color=:yellow, marker=:diamond) s_lblvs = scatter!(ax1, freq_lblvs_barc, spl_lblvs_barc, color=:purple, marker=:rect) s_blunt = scatter!(ax1, freq_teb_barc, spl_teb_barc, color=:green, marker=:star6) s_tip = scatter!(ax1, freq_tip_barc, spl_tip_barc, color=:cyan, marker=:circle) l_pressure = lines!(ax1, freqs_obs, spl_pressure, color=:blue) l_suction = lines!(ax1, freqs_obs, spl_suction, color=:red) l_alpha = lines!(ax1, freqs_obs, spl_alpha, color=:yellow) l_lblvs = lines!(ax1, freqs_obs, spl_lblvs, color=:purple) l_teb = lines!(ax1, freqs_obs, spl_teb, color=:green) l_tip = lines!(ax1, freqs_obs, spl_tip, color=:cyan) xlims!(ax1, 2e2, 6e4) ylims!(ax1, 0.0, 50.0) leg = Legend(fig[1, 1], [ [s_pressure, l_pressure], [s_suction, l_suction], [s_separation, l_alpha], [s_lblvs, l_lblvs], [s_blunt, l_teb], [s_tip, l_tip], ], [ "TBLTE-Pressure", "TBLTE-Suction", "Separation", "LBLVS", "BVS", "Tip", ]; orientation=:horizontal, tellwidth=false, tellheight=true, nbanks=2) text!(ax1, 210, 44; text="markers: CCBlade.jl+BPM.jl\nlines: CCBlade.jl+AcousticAnalogies.jl") save("figure24b-spl-barc.png", fig) ``` ![](figure24b-spl-barc.png)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
23995
```@meta CurrentModule = AADocs ``` # Compact Formulation 1A OpenFAST Example ## Introduction This example loads a .out file generated by the popular aeroserohydroelastic solver [OpenFAST](https://github.com/OpenFAST/openfast), which is released by the U.S. National Renewable Energy Laboratory to simulate wind turbines, and then constructs the types used by AcousticAnalogies.jl for acoustic predictions. The example simulates the acoustic emissions of the 3.4MW land-based reference wind turbine released by the International Wind Energy Agency. The OpenFAST model is available at https://github.com/IEAWindTask37/IEA-3.4-130-RWT. We start by loading Julia dependencies, which are available in the General registry ```@example first_example using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: AcousticMetrics using ColorSchemes: colorschemes using FillArrays: FillArrays, getindex_value using GLMakie using KinematicCoordinateTransformations: SteadyRotYTransformation using StaticArrays: @SVector nothing # hide ``` ## Inputs Next, we set the user-defined inputs: * number of blades, usually 3 for modern wind turbines * hub radius in m, it is specified in the ElastoDyn main input file of OpenFAST * blade spanwise grid in m and the corresponding chord, also in m. The two arrays are specified in the AeroDyn15 blade input file * Observer location in the global coordinate frame (located at the rotor center, x points downwind, z points vertically up, and y points sideways). In this case we picked the IEC-prescribed location (turbine height on the ground) by specifying the hub height of 110 m. * Air density and speed of sound * Path to the OpenFAST .out file. The file must contain these channels: Time (always available), Wind1VelX from InflowWind, RotSpeed from ElastoDyn, Nodal outputs Fxl and Fyl from AeroDyn15. the file is available in the repo under `test/gen_test_data/openfast_data`. ```@example first_example # num_blades = 3 Rhub = 2. BlSpn = [0.0000e+00, 2.1692e+00, 4.3385e+00, 6.5077e+00, 8.6770e+00, 1.0846e+01, 1.3015e+01, 1.5184e+01, 1.7354e+01, 1.9523e+01, 2.1692e+01, 2.3861e+01, 2.6031e+01, 2.8200e+01, 3.0369e+01, 3.2538e+01, 3.4708e+01, 3.6877e+01, 3.9046e+01, 4.1215e+01, 4.3385e+01, 4.5554e+01, 4.7723e+01, 4.9892e+01, 5.2062e+01, 5.4231e+01, 5.6400e+01, 5.8570e+01, 6.0739e+01, 6.2908e+01] Chord = [2.600e+00, 2.645e+00, 3.020e+00, 3.437e+00, 3.781e+00, 4.036e+00, 4.201e+00, 4.284e+00, 4.288e+00, 4.223e+00, 4.098e+00, 3.923e+00, 3.709e+00, 3.468e+00, 3.220e+00, 2.986e+00, 2.770e+00, 2.581e+00, 2.412e+00, 2.266e+00, 2.142e+00, 2.042e+00, 1.964e+00, 1.909e+00, 1.870e+00, 1.807e+00, 1.666e+00, 1.387e+00, 9.172e-01, 1.999e-01] file_path = joinpath(@__DIR__, "..", "..", "test", "gen_test_data", "openfast_data", "IEA-3.4-130-RWT.out") HH = 110. # m RSpn = BlSpn .+ Rhub x0 = @SVector [HH .+ RSpn[end], 0.0, -HH] rho = 1.225 # kg/m^3 c0 = 340.0 # m/s nothing # hide ``` For the monopole/thickness noise, we need the cross-sectional area at each radial station. If we know the cross-sectional area per chord squared, we can find the cross-sectional area this way: ```@example first_example # Cross-sectional area of each element in m**2. This is taking a bit of a shortcutβ€”the value of `cs_area_over_chord_squared` does not actually correspond to the IEAWindTask37 turbine blade. cs_area_over_chord_squared = 0.064 cs_area = cs_area_over_chord_squared .* Chord.^2 nothing # hide ``` Next, we'll use the [`read_openfast_file`](@ref) function to read the OpenFAST output file: ```@example first_example # Read the data from the file and create an `OpenFASTData` object, a simple struct with fields like `time`, `omega`, `axial_loading`, etc. data = AcousticAnalogies.read_openfast_file(file_path, RSpn, cs_area; average_freestream_vel=true, average_omega=true) nothing # hide ``` That will read the data in the file, but also do a bit of processing necessary for an acoustic prediction. Specifically, it will... * interpolate the cross-sectional area and loading from the blade element interfaces to the cell centers, * use second-order finite differences to differentiate the loading with respect to time, * average the freestream velocity and RPM (if `average_freestream_vel` or `average_omega` keyword arguments are `true`) The [`read_openfast_file` doc string](@ref read_openfast_file) has more information. The output of `read_openfast_file` is a `OpenFASTData` `struct` that has fields like `time`, `omega`, `axial_loading`, etc. that are read from the output file, and also fields like `radii_mid`, `circum_loading_mid_dot` that are created after the output file is read. Check out the [`OpenFASTData` doc string](@ref OpenFASTData) for a list of all the fields. We can get the averaged rotation rate value from the `OpenFASTData` `struct` this way: ```@example first_example omega_avg = getindex_value(data.omega) @show omega_avg nothing # hide ``` (When averaging rotation rate or freestream velocity, `read_openfast_file` uses a [`Fill`](https://juliaarrays.github.io/FillArrays.jl/stable/#FillArrays.Fill) `struct` from the [`FillArrays.jl`](https://github.com/JuliaArrays/FillArrays.jl) package to lazily represent the average `omega` value as a length-`num_times` `Vector`, and [`getindex_value`](https://juliaarrays.github.io/FillArrays.jl/stable/#FillArrays.getindex_value) is a function from `FillArrays.jl` that returns that single averaged value. Could have also just indexed the `data.omega` array at the first value, or last, etc..) ```@example first_example @show data.omega[1] data.omega[8] data.omega[end] nothing # hide ``` Before we actually try an acoustic prediction, let's have a look at the loading. We'll use the Makie plotting package to make the plots, and only plot 1 out of every 500 time steps (as seen in the `for tidx` line): ```@example first_example ntimes_loading = size(data.axial_loading_mid, 1) fig = Figure() ax11 = fig[1, 1] = Axis(fig, xlabel="Span Position (m)", ylabel="Fx (N/m)", title="blade 1") ax21 = fig[2, 1] = Axis(fig, xlabel="Span Position (m)", ylabel="Fy (N/m)") ax12 = fig[1, 2] = Axis(fig, xlabel="Span Position (m)", ylabel="Fx (N/m)", title="blade 2") ax22 = fig[2, 2] = Axis(fig, xlabel="Span Position (m)", ylabel="Fy (N/m)") ax13 = fig[1, 3] = Axis(fig, xlabel="Span Position (m)", ylabel="Fx (N/m)", title="blade 3") ax23 = fig[2, 3] = Axis(fig, xlabel="Span Position (m)", ylabel="Fy (N/m)") num_blades = data.num_blades colormap = colorschemes[:viridis] time = data.time sim_length_s = time[end] - time[begin] for tidx in 1:500:ntimes_loading cidx = (time[tidx] - time[1])/sim_length_s l1 = lines!(ax11, data.radii_mid, data.axial_loading_mid[tidx,:,1], label ="b1", color=colormap[cidx]) l1 = lines!(ax12, data.radii_mid, data.axial_loading_mid[tidx,:,2], label ="b2", color=colormap[cidx]) l1 = lines!(ax13, data.radii_mid, data.axial_loading_mid[tidx,:,3], label ="b3", color=colormap[cidx]) l2 = lines!(ax21, data.radii_mid, data.circum_loading_mid[tidx,:,1], label ="b1", color=colormap[cidx]) l2 = lines!(ax22, data.radii_mid, data.circum_loading_mid[tidx,:,2], label ="b2", color=colormap[cidx]) l2 = lines!(ax23, data.radii_mid, data.circum_loading_mid[tidx,:,3], label ="b3", color=colormap[cidx]) end linkxaxes!(ax21, ax11) linkxaxes!(ax12, ax11) linkxaxes!(ax22, ax11) linkxaxes!(ax13, ax11) linkxaxes!(ax23, ax11) linkyaxes!(ax12, ax11) linkyaxes!(ax13, ax11) linkyaxes!(ax22, ax21) linkyaxes!(ax23, ax21) hidexdecorations!(ax11, grid=false) hidexdecorations!(ax12, grid=false) hidexdecorations!(ax13, grid=false) hideydecorations!(ax12, grid=false) hideydecorations!(ax13, grid=false) hideydecorations!(ax22, grid=false) hideydecorations!(ax23, grid=false) cbar = fig[:, 4] = Colorbar(fig; limits=(time[begin], time[end]), colormap=:viridis, label="time (sec)") save(joinpath(@__DIR__, "openfast_example_loading.png"), fig) nothing # hide ``` ![Loading](openfast_example_loading.png) The x axis of each subplot is the radial position along the blade, from hub to tip. The top three plots show the axial loading, bottom three the circumferential, and there's one column for each blade. And the colorbar indicates the simulation time. The plot shows significant unsteadiness, which is cool to see. We can also plot the loading time derivative in a similar form: ```@example first_example ntimes_loading = size(data.axial_loading_mid_dot, 1) fig = Figure() ax11 = fig[1, 1] = Axis(fig, xlabel="Span Position (m)", ylabel="βˆ‚Fx/βˆ‚t (N/(m*s))", title="blade 1") ax21 = fig[2, 1] = Axis(fig, xlabel="Span Position (m)", ylabel="βˆ‚Fy/βˆ‚t (N/(m*s))") ax12 = fig[1, 2] = Axis(fig, xlabel="Span Position (m)", ylabel="βˆ‚Fx/βˆ‚t (N/(m*s))", title="blade 2") ax22 = fig[2, 2] = Axis(fig, xlabel="Span Position (m)", ylabel="βˆ‚Fy/βˆ‚t (N/(m*s))") ax13 = fig[1, 3] = Axis(fig, xlabel="Span Position (m)", ylabel="βˆ‚Fx/βˆ‚t (N/(m*s))", title="blade 3") ax23 = fig[2, 3] = Axis(fig, xlabel="Span Position (m)", ylabel="βˆ‚Fy/βˆ‚t (N/(m*s))") num_blades = data.num_blades colormap = colorschemes[:viridis] time = data.time sim_length_s = time[end] - time[begin] for tidx in 1:500:ntimes_loading cidx = (time[tidx] - time[1])/sim_length_s l1 = lines!(ax11, data.radii_mid, data.axial_loading_mid_dot[tidx,:,1], label ="b1", color=colormap[cidx]) l1 = lines!(ax12, data.radii_mid, data.axial_loading_mid_dot[tidx,:,2], label ="b2", color=colormap[cidx]) l1 = lines!(ax13, data.radii_mid, data.axial_loading_mid_dot[tidx,:,3], label ="b3", color=colormap[cidx]) l2 = lines!(ax21, data.radii_mid, data.circum_loading_mid_dot[tidx,:,1], label ="b1", color=colormap[cidx]) l2 = lines!(ax22, data.radii_mid, data.circum_loading_mid_dot[tidx,:,2], label ="b2", color=colormap[cidx]) l2 = lines!(ax23, data.radii_mid, data.circum_loading_mid_dot[tidx,:,3], label ="b3", color=colormap[cidx]) end linkxaxes!(ax21, ax11) linkxaxes!(ax12, ax11) linkxaxes!(ax22, ax11) linkxaxes!(ax13, ax11) linkxaxes!(ax23, ax11) linkyaxes!(ax12, ax11) linkyaxes!(ax13, ax11) linkyaxes!(ax22, ax21) linkyaxes!(ax23, ax21) hidexdecorations!(ax11, grid=false) hidexdecorations!(ax12, grid=false) hidexdecorations!(ax13, grid=false) hideydecorations!(ax12, grid=false) hideydecorations!(ax13, grid=false) hideydecorations!(ax22, grid=false) hideydecorations!(ax23, grid=false) cbar = fig[:, 4] = Colorbar(fig; limits=(time[begin], time[end]), colormap=:viridis, label="time (sec)") save(joinpath(@__DIR__, "openfast_example_loading_dot.png"), fig) nothing # hide ``` ![Loading Time Derivative](openfast_example_loading_dot.png) ## Constructing the Source Elements Now, the next step is to turn the OpenFAST data into source elements. This step is pretty easy, since there is a function called [`f1a_source_elements_openfast`](@ref f1a_source_elements_openfast) that takes the `OpenFASTData` `struct` and a few other parameters and will create the source elements for us. But first we need to think about the coordinate system we'd like our source elements to be in. Eventually, we want the turbine blades to be rotating about the positive x axis, with the freestream velocity pointing in the positive x axis direction. But there are two things we need to account for to make that happen: * To do a proper noise prediction, AcousticAnalogies.jl needs the source elements' motion to be defined in a reference frame relative to the ambient fluid, not the ground. Put another way, we need to manipulate the source elements in a way so that it appears that there is no freestream velocityβ€”that the ambient fluid is stationary. So instead of having blade elements that are only rotating about a fixed hub position relative to the ground in a freestream pointed in the positive x direction, we will have the blade elements translate in the *negative* x direction as they rotate, with no freestream velocity. * The `f1a_source_elements_openfast` routine puts the source elements in the Standard AcousticAnalogies.jl Reference Frameβ„’, where the source elements * begin with the hub (rotation center) at coordinate system origin at source time `t = 0`, * rotate about either the positive x or negative x axis (depending on the value of the `positive_x_rotation` argument), * translate in the positive x direction. So, to make all this work, we'll initially have the source elements translate in the positive x direction (as required by `f1a_source_elements_openfast`) and rotate about the *negative* x axis. Then we'll rotate the source elements 180Β° about the y axis, which will mean they will be translating in the negative x axis, rotating about the positive x axis, just like what we intend. So, here's the first step: create the source elements from the `OpenFASTData` `struct`, where they'll be rotating about the negative x axis, translating along the positive x axis. ```@example first_example positive_x_rotation = false ses_before_roty = AcousticAnalogies.f1a_source_elements_openfast(data, rho, c0, positive_x_rotation) nothing # hide ``` The `f1a_source_elements_openfast` returns an array of [`CompactF1ASourceElement`](@ref) `structs`. The array is of size `(num_times, num_radial, num_blades)`, where `ses[i, j, k]` refers to the source element of the `i`th time step, `j`th radial position, and `k`th blade: ```@example first_example @show size(ses_before_roty) nothing # hide ``` Now we'll rotate each source element 180Β° about the positive y axis. ```@example first_example # Create the object from KinematicCoordinateTransformations.jl defining the 180Β° rotation about the y axis. rot180degy = SteadyRotYTransformation(0, 0, pi) # Now rotate the source elements. ses = rot180degy.(ses_before_roty) # Could have combined all that in one line, i.e., # ses = rot180degy.(AcousticAnalogies.f1a_source_elements_openfast(data, rho, c0, positive_x_rotation)) nothing # hide ``` ## Defining the Observer The last thing we need before we can perform the noise prediction is an acoustic observer. The observer is just the computational equivalent of the microphoneβ€”a fictitious, possibly moving point in space that will "receive" the noise produced by each source element. In this case we picked the IEC-prescribed location (turbine height on the ground) by specifying the hub height of 110 m. So we need the observer to be 110 m below the hub. We'll also have the observer positioned downstream of the turbine rotation plane by a certain amount. ```@example first_example x0_obs = @SVector [HH + RSpn[end], 0.0, -HH] nothing # hide ``` (The `@SVector` macro creates a statically-size vector using the [StaticArrays.jl](https://github.com/JuliaArrays/StaticArrays.jl) package, which is good for performance but not required.) Now, just like with the source elements, we need to define the motion of the observer relative to the fluid, not the ground. So, we'll use the same trick that we used with the source elements: have the observer translate in the negative x direction to account for the freestream velocity that's pointed in the positive x direction: ```@example first_example # Get the average freestream velocity from the OpenFAST data. v_avg = getindex_value(data.v) # Create a vector defining the velocity of the observer. v_obs = @SVector [-v_avg, 0, 0] nothing # hide ``` Since the observer is moving, its position is obviously changing. So the `x0_obs` will be the position of the observer at the start of the simulation, at the first source time level of the source elements. We can get that first source time level this way: ```@example first_example t0_obs = data.time[1] nothing # hide ``` Now we have enough information to create the observer object: ```@example first_example obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0_obs, x0_obs, v_obs) nothing # hide ``` That says that we want our observer to start at the location `x0_obs` at time `t0_obs`, and then move with constant velocity `v_obs` forever after. After creating the observer, we can query its location at any time value after this way: ```@example first_example @show obs(t0_obs) # should be equal to `x0_obs` @show obs(t0_obs + 1) nothing # hide ``` ## Visualization with VTK Files That was a lot. How will we know we did all that correctly? The answer is: write out the source elements and observer we just created to VTK files, and then visualize them with our favorite visualization software (ParaView at the moment). The function we want is [`to_paraview_collection`](@ref). Using it is simple: ```@example first_example AcousticAnalogies.to_paraview_collection("openfast_example_with_obs", (ses,); observers=(obs,)) nothing # hide ``` (This form of `to_paraview_collection` expects multiple arrays of source elements and multiple observers. But here we just have one array of source elements (`ses`) and one observer (`obs`), so we wrap each in a single-entry tuple, i.e., `(ses,)` and `(obs,)`.) That will write out a bunch of VTK files showing the motion of the source elements and the observer, all starting with the `name` argument to the function (`openfast_example_with_obs` here). The one to focus on is `openfast_example_with_obs.pvd`, a [ParaView data file](https://www.paraview.org/Wiki/ParaView/Data_formats#PVD_File_Format) that describes how all the many VTK files that `to_paraview_collection` writes out fit together. The VTK files for the source elements will also contain all the data defined in the source element `struct`s (the loading, cross-sectional area, etc.). That's really handy for checking that the loading is in the correct direction (remember, it needs to be the loading on the fluid, i.e. exactly opposite the loading on the blades). To that end, here's an animation of the blades and observer, with the blades colored by the loading per unit span in the y direction: ![LoadingY, Iso](assets/openfast_example_with_obs-iso_view-loading_y-0to6000-compressed.gif) Things look pretty good: the observer (i.e. the gray sphere) and the blades are all translating in the negative x direction, and the blades are rotating about the positive x axis. (The gray smearing along the path of the observer is an artifact of the compression process the `gif` went through to make the file smaller.) The y-component of the loading also appears to be in the correction direction: for a wind turbine, we'd expect the loading on the fluid to oppose the motion of the blade in the circumferential direction, which is what the animation shows. One thing that is troubling about the previous animation is the location of the observer relative to the blades in the y direction. Since the rotor hub starts at the origin and moves along the negative x axis, and since y component of the observer position is always zero, the observer should only be offset in the x and z directions relative to the hub path. That's hard to see in the previous animation, but if we switch our perspective to be looking directly downstream (i.e., looking in the positive-x direction), everything appears as it should be: ![LoadingY, Downstream](assets/openfast_example_with_obs-downstream_view-loading_y-0to6000-compressed.gif) Both the blade hub and the observer appear to be moving in the `y=0` plane. ## Noise Prediction Now we're finally ready to do a noise prediction! The relevant function for that is [`noise`](@ref), which takes in a source element and observer and returns an [`F1AOutput`](@ref) `struct`, representing the acoustic pressure experienced by the observer due to the source: ```@example first_example apth = AcousticAnalogies.noise.(ses, Ref(obs)) nothing # hide ``` Notice that we used a `.` after the `noise` function, which [broadcasts](https://docs.julialang.org/en/v1/manual/arrays/#Broadcasting) the `noise` call over all source element-observer combinations. (The `Ref(obs)` makes the single observer `struct` act as a scalar during broadcasting, meaning the same observer object is passed to each `noise` call.) Because of the broadcasting, `apth` is an `Array` of `F1AOutput` `structs` with the same size as `ses`: ```@example first_example @show size(ses) size(apth) nothing # hide ``` We now have a noise prediction for each of the individual source elements in `ses` at the acoustic observer obsβ€”specifically, `apth[i, j, k]` represents the acoustic pressure for the `i` time step, `j` radial location, and `k` blade. What we ultimately want is the total noise prediction at `obs`β€”we want to add all the acoustic pressures for each time level in `apth` together. But we can't add them directly, yet, since the observer timesβ€”the time at which each source's noise reaches the observerβ€”are not all the same. What we need to do is first interpolate the acoustic pressure time history of each source onto a common series of observer time levels, and then add them up. We'll do this using the [`combine`](@ref) function. First, we need to decide on the length of the observer time series and how many points it will contain. If the motion and loading of the blades was steady, then one blade pass would be sufficient, but for this example that is not the case, so we'll use a longer observer time: ```@example first_example rev_period = 2*pi/omega_avg bpp = rev_period/num_blades # blade passing period omega_rpm = omega_avg * 60/(2*pi) obs_time_range = sim_length_s/60*omega_rpm*bpp num_obs_times = length(data.time) nothing # hide ``` So that says that we'll have an output observer time length of `obs_time_range` with `num_obs_times` points. Note that we need to be careful to avoid extrapolation in the `combine` calculation, which will happen if the observer time specified via the `obs_time_range` and `num_obs_times` arguments to `combine` extends past the times contained in the `apth` array. That won't happen in this case, since `obs_time_range/sim_length_s` is 1/3, so the observer time range is much less than the source time range. Now we call `combine` to get the total acoustic pressure time history: ```@example first_example time_axis = 1 apth_total = AcousticAnalogies.combine(apth, obs_time_range, num_obs_times, time_axis) nothing # hide ``` With that, we're finally able to plot the acoustic pressure time history: ```@example first_example fig = Figure() ax1 = fig[1, 1] = Axis(fig, xlabel="time, s", ylabel="monopole, Pa") ax2 = fig[2, 1] = Axis(fig, xlabel="time, s", ylabel="dipole, Pa") ax3 = fig[3, 1] = Axis(fig, xlabel="time, s", ylabel="total, Pa") l1 = lines!(ax1, time, apth_total.p_m) l2 = lines!(ax2, time, apth_total.p_d) l3 = lines!(ax3, time, apth_total.p_m.+apth_total.p_d) hidexdecorations!(ax1, grid=false) hidexdecorations!(ax2, grid=false) save(joinpath(@__DIR__, "openfast-apth_total.png"), fig) nothing # hide ``` ![Acoustic Pressure Time History](openfast-apth_total.png) The plot shows that the monopole/thickness noise is much lower than the dipole/loading noise. Wind turbine blades are relatively slender, which would tend to reduce thickness noise. Also the observer is downstream of the rotation plane, which is where loading noise is traditionally thought to dominate (monopole/thickness noise is more significant in the rotor rotation plane, usually). (Although we didn't use the actual cross-sectional area for the blades, which directly affects the monopole/thickness noise.) We now calculate the overall sound pressure level from the acoustic pressure time history. Next, we will calculate the narrowband spectrum. Finally, we will calculate the overall sound pressure level from the narrowband spectrum. ```@example first_example oaspl_from_apth = AcousticMetrics.OASPL(apth_total) nbs = AcousticMetrics.MSPSpectrumAmplitude(apth_total) oaspl_from_nbs = AcousticMetrics.OASPL(nbs) @show oaspl_from_apth oaspl_from_nbs nothing # hide ``` The OASPL values calculated from the acoustic pressure time history and the narrowband spectrum are the same, as they should be according to [Parseval's theorem](https://en.wikipedia.org/wiki/Parseval%27s_theorem).
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
20224
```@meta CurrentModule = AADocs ``` # Software Quality Assurance ## Tests AcousticAnalogies.jl uses the usual Julia testing framework to implement and run tests. The tests can be run locally after installing AcousticAnalogies.jl, and are also run automatically on GitHub Actions. To run the tests locally, from the Julia REPL, type `]` to enter the Pkg prompt, then ```julia-repl (jl_jncZ1E) pkg> test AcousticAnalogies Testing Running tests... Test Summary: | Pass Total Time Advanced time tests | 2 2 7.0s Test Summary: | Pass Total Time Combine F1AOutput tests | 8 8 2.7s Test Summary: | Pass Total Time F1A tests | 2 2 5.9s Test Summary: | Pass Total Time CCBlade private utils tests | 1 1 0.3s Test Summary: | Pass Total Time CCBlade CompactF1ASourceElement test | 12 12 3.4s Test Summary: | Pass Total Time ANOPP2 Comparison | 176 176 5.9s Test Summary: | Time ForwardDiff test | None 14.1s Testing AcousticAnalogies tests passed (jl_jncZ1E) pkg> ``` (The output associated with installing all the dependencies the tests need isn't shown above.) Here is a description of each category of test: ### Advanced Time Tests The F1A calculation is concerned with roughly two types of objects: acoustic sources and acoustic observers. Acoustic sources are things that make noise, and, for AcousticAnalogies.jl, would typically be a portion of some type of aerodynamic lifting surface (like a propeller blade). An acoustic observer is just a fancy name for a person or microphone that will hear the noise emitted by the source. Both the source and observer may be stationary, but more likely will be moving. During the F1A calculation, we need to know the time at which an acoustic wave emitted by the source encounters the observer. Mathematically, we need to solve the equation ```math R(t) = t - \left( \tau + \frac{|\vec{x}(t) - \vec{y}(Ο„)|}{c_0} \right) = 0 ``` where * ``Ο„`` is the time the source has emitted an acoustic disturbance * ``t`` is the time the observer encounters the acoustic disturbance * ``\vec{y}`` is the position of the source * ``\vec{x}`` is the position of the observer * ``c_0`` is the speed of sound AcousticAnalogies.jl currently uses an advanced time approach to solving this equation. This means we start with knowledge of ``\tau`` and then calculate ``t``β€”we "advance" the source time to the observer time by adding the amount of time it takes for the acoustic disturbance to travel from ``y`` to ``x``. Now, the ``R(t) = 0`` equation is quite easy to solve if the observer is stationary. In that case, ``x`` is not a function of ``t``, and so solving for ``t`` just involves moving everything in the parenthesis to the right-hand side. But if the observer is moving, things are more complicated. It may be impossible to solve for ``t`` explicitly in that case. It turns out, however, that there is an explicit solution for ``t`` in the advanced time approach if the observer is moving at a constant rate (see D. Casolino [http://dx.doi.org/10.1016/S0022-460X(02)00986-0](http://dx.doi.org/10.1016/S0022-460X(02)00986-0)). The constant velocity case is actually quite handy, since it's what we need to compare to wind tunnel data. So, how do we test that we've implemented the solution to the ``R(t) = 0`` advanced time equation correctly? In AcousticAnalogies.jl, we just use the nonlinear solver provided by [NLsolve.jl](https://github.com/JuliaNLSolvers/NLsolve.jl), and compare its solution to AcousticAnalogies.jl. Here's how to do that: ```@example adv_time_tests using AcousticAnalogies: AcousticAnalogies using LinearAlgebra: norm using NLsolve: NLsolve using StaticArrays # Create a source element for the test. # The only things about the source element that matters to the advanced # time calculation is the time and position, and the speed of sound. # So everything else will be take on dummy values. Ο„ = 2.5 y = @SVector [-4.0, 3.0, 6.0] c0 = 2.0 dummy0 = 1.0 dummy3 = @SVector [0.0, 0.0, 0.0] se = AcousticAnalogies.CompactF1ASourceElement(dummy0, c0, dummy0, dummy0, y, dummy3, dummy3, dummy3, dummy3, dummy3, Ο„, dummy3) # Define a function that solves the advanced time equation using `nlsolve. function adv_time_nlsolve(se, obs) # Create the residual equation that we'll solve. # nlsolve assumes the residual function takes in and returns arrays. R(t) = [t[1] - (se.Ο„ + norm(obs(t[1]) .- se.y0dot)/se.c0)] # Solve the advanced time equation. result = NLsolve.nlsolve(R, [1.0], autodiff=:forward) if !NLsolve.converged(result) @error "nlsolve advanced time calculation did not converge:\n$(result)" end t_obs = result.zero[1] return t_obs end # Let's try it out. # First, a stationary observer: x0 = @SVector [-3.0, 2.0, 8.5] obs = AcousticAnalogies.StationaryAcousticObserver(x0) t_exact = AcousticAnalogies.adv_time(se, obs) t_nlsolve = adv_time_nlsolve(se, obs) println("stationary observer, exact: $(t_exact), nlsorve: $(t_nlsolve), difference = $(t_exact - t_nlsolve)") # Next, a constant velocity observer: t0 = 3.5 x0 = @SVector [-2.0, 3.5, 6.25] v = @SVector [-1.5, 1.5, 3.25] obs = AcousticAnalogies.ConstVelocityAcousticObserver(t0, x0, v) t_exact = AcousticAnalogies.adv_time(se, obs) t_nlsolve = adv_time_nlsolve(se, obs) println("constant velocity observer, exact: $(t_exact), nlsorve: $(t_nlsolve), difference = $(t_exact - t_nlsolve)") ``` Almost identical results, so things are good! ### Combine `F1AOutput` Tests The function `noise(se::CompactF1ASourceElement, obs::AcousticObserver)` uses Farassat's formulation 1A to perform a prediction of the noise experienced by one observer `obs` due to one acoustic source `se`. Typically we will not have just one source, however. For example, the [guided example in the docs](@ref guided_example) uses 30 "source elements" to model each propeller blade. But we're interested in the acoustics experienced by `obs` due to **all** of the source elements, not just one. So, we need to combine the output of `noise` for one observer and all of the source elements. In AcousticAnalogies.jl, this is done by interpolating the time history of each source element's acoustics (the "pressure time history") onto a common chunk of time, and then adding them up. No big deal. But, how do we test the "interpolating and adding" routine, aka [`AcousticAnalogies.combine`](@ref)? That's pretty simple, actually: we just define some arbitrary functions that we'll use to create some pressure time histories, add them using the `combine` routine, and then compare that result to those created via evaluating those arbitrary functions on the same time grid used by the `combine` routine. If those match, then the test passes, and everything in the `combine` routine should be good. Let's try that: ```@example combine_test using AcousticAnalogies: AcousticAnalogies using AcousticMetrics: AcousticMetrics using GLMakie using Random # Goal is to verify that the code can faithfully combine two acoustic pressures on different time "grids" onto a single common grid. # These will be our made up functions: fa(t) = sin(2*pi*t) + 0.2*cos(4*pi*(t-0.1)) fb(t) = cos(6*pi*t) + 0.3*sin(8*pi*(t-0.2)) # Now we'll make some made up time grids. n = 101 t1 = collect(range(0.0, 1.0, length=n)) dt = t1[2] - t1[1] # Add a bit of random noise to the time grid. # Make sure that the amount of # randomness isn't large enough to make the time values non-monotonically increasing (i.e., they don't overlap). noise = 0.49.*dt.*(1 .- 2 .* rand(size(t1)...)) t1 .+= noise t2 = collect(range(0.1, 1.1, length=n)) dt = t2[2] - t2[1] t2 .+= 0.49.*dt.*(1 .- 2 .* rand(size(t2)...)) # Now let's create a bunch of pressure time histories on the time grids we just defined. apth1 = @. AcousticAnalogies.F1AOutput(t1, fa(t1), 2*fa(t1)) apth2 = @. AcousticAnalogies.F1AOutput(t2, fb(t2), 3*fb(t2)) # Calculate the "exact" answer by coming up with a common time, then evaluating the test functions directly on the common time grid. period = 0.5 n_out = 51 t_start = max(t1[1], t2[1]) t_common = t_start .+ (0:n_out-1).*(period/n_out) p_m = @. fa(t_common)+fb(t_common) p_d = @. 2*fa(t_common)+3*fb(t_common) even_length = iseven(n_out) apth_test = AcousticAnalogies.F1APressureTimeHistory{even_length}(p_m, p_d, step(t_common), first(t_common)) # Put all the acoustic pressures in one array. apth = hcat(apth1, apth2) # Combine. apth_out = AcousticAnalogies.combine(apth, period, n_out) # Plot the two solutions. fig2 = Figure() ax2_1 = fig2[1, 1] = Axis(fig2, xlabel="time", ylabel="acoustic pressure, monopole") ax2_2 = fig2[2, 1] = Axis(fig2, xlabel="time", ylabel="acoustic pressure, dipole") scatter!(ax2_1, AcousticMetrics.time(apth_out), AcousticAnalogies.pressure_monopole(apth_out); marker=:x, label="AcousticAnalogies.combine") scatter!(ax2_2, AcousticMetrics.time(apth_out), AcousticAnalogies.pressure_dipole(apth_out); marker=:x) lines!(ax2_1, AcousticMetrics.time(apth_test), AcousticAnalogies.pressure_monopole(apth_test); label="Exact") lines!(ax2_2, AcousticMetrics.time(apth_test), AcousticAnalogies.pressure_dipole(apth_test)) hidexdecorations!(ax2_1, grid=false) axislegend(ax2_1; merge=true, unique=true, framevisible=false, bgcolor=:transparent, position=:rt) save("combine_test.png", fig2) nothing # hide ``` ![](combine_test.png) Right on top of each other. ### F1A Tests The most complicated part of AcousticAnalogies.jl is the implementation of the F1A calculation itself. For example, the compact form of the F1A dipole term as implemented in AcousticAnalogies.jl (neglecting surface deformation) is ```math 4 \pi c_0 p_d = \int_{L=0} \left[ \left( \dot{\vec{f}} \cdot \vec{D}_{1A} + \vec{f} \cdot \vec{E}_{1A} \right) dr \right] ``` where * ``p_d`` is the "dipole" part of the acoustic pressure * ``\vec{f}`` is the loading per unit span on the source element * ``\vec{\dot{f}}`` is the source-time derivative of the loading per unit span on the source element * ``dr`` is the differential length of the source element * ``c_0`` is the ambient speed of sound * ``\vec{D}_{1A}`` and ``\vec{E}_{1A}`` are complicated functions of the position, velocity, and acceleration of the source element * ``L = 0`` indicates the integration is performed over some curve defined by ``L = 0``. How are we going to test that we have all that implemented properly? Well, it turns out that Farassat's original formulation (F1) is much simpler than F1A: ```math 4 \pi c_0 p_d = \frac{\partial}{\partial t} \int_{L=0} \left( \vec{f} \cdot \vec{B}_{1}\right) dr + \int_{L=0}\left( \vec{f} \cdot \vec{C}_1 \right) dr ``` where ``\vec{B}_1`` and ``\vec{C}_1`` are again functions of the position of the source element and time derivatives of the same. It might not look that much simpler, but it is, because: * The F1 integrands don't depend on ``\dot{\vec{f}}`` * ``\vec{D}_{1A}`` and ``\vec{E}_{1A}`` from F1A are more complicated than ``\vec{B}_1`` and ``\vec{C}_1``, and involve higher-order time derivatives But the key thing to understand about F1 and F1A is that they are equivalentβ€”going from F1A to F1 involves some fancy math (moving the derivative with respect to the observer time $t$ inside the integral), but should give the same answer. The only trick is this: how will we evaluate the derivatives with respect to the observer time ``t`` in the F1 expressions? What we'll do here is just use standard second-order-accurate finite difference approximations, i.e., ```math \frac{\partial g}{\partial t} = \frac{g(t+\Delta t) - g(t-\Delta t)}{2 \Delta t} + \mathcal{O}(\Delta t^2) ``` where the notation ``\mathcal{O}(\Delta t^2)`` indicates that the error associated with the finite difference approximation should be proportional to ``\Delta t^2``. But this means that we can't expect our F1 calculation to exactly match F1A. So, what to do about that? What we can expect is that, if F1A and F1 have been implemented properly, the difference between them should go to zero at a second-order rate. So we can systematically reduce the time step size ``\Delta t`` used to evaluate F1, and check that goes to zero at the expected rate. If it does, that proves that the only error between the two codes is due to the finite difference approximation, and gives us strong evidence that both F1A and F1 have been implemented properly. So, let's try it out! First we'll need a function that evaluates the f1 integrands ```@example f1a_tests using AcousticAnalogies using LinearAlgebra: norm using NLsolve using Polynomials using GLMakie function f1_integrand(se, obs, t) c0 = se.c0 # Need to get the retarded time. R(Ο„) = [t - (Ο„[1] + norm(obs(t) .- se.y0dot(Ο„[1]))/c0)] result = nlsolve(R, [-0.1], autodiff=:forward) if !converged(result) @error "nlsolve retarded time calculation did not converge:\n$(result)" end Ο„ = result.zero[1] # Position of source at the retarted time. y = se.y0dot(Ο„) # Position vector from source to observer. rv = obs(t) .- y # Distance from source to observer. r = AcousticAnalogies.norm_cs_safe(rv) # Unit vector pointing from source to observer. rhat = rv./r # First time derivative of rv. rv1dot = -se.y1dot(Ο„) # Mach number of the velocity of the source in the direction of the # observer. Mr = AcousticAnalogies.dot_cs_safe(-rv1dot/se.c0, rhat) # Now evaluate the integrand. p_m_integrand = se.ρ0/(4*pi)*se.Ξ›*se.Ξ”r/(r*(1 - Mr)) # Loading at the retarded time. f0dot = se.f0dot(Ο„) p_d_integrand_ff = (1/(4*pi*c0))*AcousticAnalogies.dot_cs_safe(f0dot, rhat)/(r*(1 - Mr))*se.Ξ”r p_d_integrand_nf = (1/(4*pi*c0))*AcousticAnalogies.dot_cs_safe(f0dot, rhat)*c0/(r^2*(1 - Mr))*se.Ξ”r return Ο„, p_m_integrand, p_d_integrand_ff, p_d_integrand_nf end ``` The `f1_integrand` function takes a source element `se`, and acoustic observer `obs`, and an observer time `t` and finds the source time and intermediate stuff that will eventually want to differentiate using the finite difference approximation. Now we need to make up a source and observer that we can test this out with: ```@example f1a_tests # https://docs.makie.org/v0.19/examples/blocks/axis/index.html#logticks struct IntegerTicks end Makie.get_tickvalues(::IntegerTicks, vmin, vmax) = ceil(Int, vmin) : floor(Int, vmax) function doit() # Scale up the density to make the error bigger. rho = 1.226e6 # kg/m^3 c0 = 340.0 # m/s Rtip = 1.1684 # meters radii = 0.99932*Rtip dradii = (0.99932 - 0.99660)*Rtip # m area_over_chord_squared = 0.064 chord = 0.47397E-02 * Rtip Ξ› = area_over_chord_squared * chord^2 theta = 90.0*pi/180.0 x0 = [cos(theta), 0.0, sin(theta)].*100.0.*12.0.*0.0254 # 100 ft in meters obs = StationaryAcousticObserver(x0) # Need the position and velocity of the source as a function of # source/retarded time. How do I want it to move? I want it to rotate around # an axis on the origin, pointing in the x direction. rpm = 2200 omega = 2*pi/60*rpm period = 60/rpm fn = 180.66763939805125 fc = 19.358679206883078 y0dot(Ο„) = [0, radii*cos(omega*Ο„), radii*sin(omega*Ο„)] y1dot(Ο„) = [0, -omega*radii*sin(omega*Ο„), omega*radii*cos(omega*Ο„)] y2dot(Ο„) = [0, -omega^2*radii*cos(omega*Ο„), -omega^2*radii*sin(omega*Ο„)] y3dot(Ο„) = [0, omega^3*radii*sin(omega*Ο„), -omega^3*radii*cos(omega*Ο„)] f0dot(Ο„) = [-fn, -sin(omega*Ο„)*fc, cos(omega*Ο„)*fc] f1dot(Ο„) = [0, -omega*cos(omega*Ο„)*fc, -omega*sin(omega*Ο„)*fc] u(Ο„) = y0dot(Ο„)./radii sef1 = CompactF1ASourceElement(rho, c0, dradii, Ξ›, y0dot, y1dot, nothing, nothing, f0dot, nothing, 0.0, u) t = 0.0 dt = period*0.5^4 Ο„0, pmi0, pdiff0, pdinf0 = f1_integrand(sef1, obs, t) sef1a = CompactF1ASourceElement(rho, c0, dradii, Ξ›, y0dot(Ο„0), y1dot(Ο„0), y2dot(Ο„0), y3dot(Ο„0), f0dot(Ο„0), f1dot(Ο„0), Ο„0, u(Ο„0)) apth = noise(sef1a, obs) err_prev_pm = nothing err_prev_pd = nothing dt_prev = nothing dt_curr = dt first_time = true err_pm = Vector{Float64}() err_pd = Vector{Float64}() dts = Vector{Float64}() ooa_pm = Vector{Float64}() ooa_pd = Vector{Float64}() # Gradually reduce time step size, recording the error and order-of-accuracy each time. for n in 1:7 Ο„_1, pmi_1, pdiff_1, pdinf_1 = f1_integrand(sef1, obs, t-dt_curr) Ο„1, pmi1, pdiff1, pdinf1 = f1_integrand(sef1, obs, t+dt_curr) p_m_f1 = (pmi_1 - 2*pmi0 + pmi1)/(dt_curr^2) p_d_f1 = (pdiff1 - pdiff_1)/(2*dt_curr) + pdinf0 err_curr_pm = abs(p_m_f1 - apth.p_m) err_curr_pd = abs(p_d_f1 - apth.p_d) if first_time first_time = false else push!(ooa_pm, log(err_curr_pm/err_prev_pm)/log(dt_curr/dt_prev)) push!(ooa_pd, log(err_curr_pd/err_prev_pd)/log(dt_curr/dt_prev)) end push!(dts, dt_curr) push!(err_pm, err_curr_pm) push!(err_pd, err_curr_pd) dt_prev = dt_curr err_prev_pm = err_curr_pm err_prev_pd = err_curr_pd dt_curr = 0.5*dt_curr end # Fit a line through the errors on a log-log plot, then check that the slope # is second-order. l = fit(log.(dts), log.(err_pm), 1) println("monopole term convergence rate = $(l.coeffs[2])") l = fit(log.(dts), log.(err_pd), 1) println("dipole term convergence rate = $(l.coeffs[2])") # Plot the error and observered order of accuracy. fig = Figure() ax1 = fig[1, 1] = Axis(fig, xlabel="time step size", ylabel="error", xscale=log10, xticks=LogTicks(IntegerTicks()), yscale=log10) ax2 = fig[2, 1] = Axis(fig, xlabel="time step size", ylabel="convergence rate", xscale=log10, xticks=LogTicks(IntegerTicks())) linkxaxes!(ax2, ax1) lines!(ax1, dts, err_pm, label="monopole term") lines!(ax1, dts, err_pd, label="dipole term") lines!(ax2, dts[2:end], ooa_pm, label="monopole term") lines!(ax2, dts[2:end], ooa_pd, label="dipole term") ylims!(ax2, -0.1, 3.1) axislegend(ax1; merge=true, unique=true, framevisible=false, bgcolor=:transparent, position=:lt) save("f1a_test.png", fig) end doit() ``` ![](f1a_test.png) The convergence rate of the error (the bottom plot) is extremely close to 2, which is what we're looking for. ### ANOPP2 Comparisons The AcousticAnalogies.jl test suite includes comparisons to ANOPP2 predictions. Tests for a hypothetical isolated rotor are performed over a range of RPMs, with both stationary and moving observers. Here is an example using a moving observer: ```@example anopp2 using GLMakie using FLOWMath: akima include(joinpath(@__DIR__, "..", "..", "test", "anopp2_run.jl")) using .ANOPP2Run rpm = 2200.0 t, p_thickness, p_loading, p_monopole_a2, p_dipole_a2 = ANOPP2Run.get_results(; stationary_observer=false, theta=0.0, f_interp=akima, rpm=rpm, irpm=11) fig = Figure() ax1 = fig[1, 1] = Axis(fig, xlabel="time, blade passes", ylabel="acoustic pressure, monopole, Pa") ax2 = fig[2, 1] = Axis(fig, xlabel="time, blade passes", ylabel="acoustic pressure, dipole, Pa") lines!(ax1, t, p_thickness, label="AcousticAnalogies.jl") scatter!(ax1, t, p_monopole_a2, label="ANOPP2", markersize=6) lines!(ax2, t, p_loading) scatter!(ax2, t, p_dipole_a2, markersize=6) hidexdecorations!(ax1, grid=false) axislegend(ax1; merge=true, unique=true, framevisible=false, bgcolor=:transparent, position=:lt) save("anopp2_comparison.png", fig) ``` ![](anopp2_comparison.png) The difference between the two codes' predictions is very small (less than 1% error). ### Brooks, Pope & Marcolini Tests ## Signed Commits The AcousticAnalogies.jl GitHub repository requires all commits to the `main` branch to be signed. See the [GitHub docs on signing commits](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification) for more information. ## Reporting Bugs Users can use the [GitHub Issues](https://docs.github.com/en/issues/tracking-your-work-with-issues/about-issues) feature to report bugs and submit feature requests.
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
12822
```@meta CurrentModule = AADocs ``` # WriteVTK.jl Support ```@setup vtk_example """ XROTORAirfoilConfig(A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) `struct` that holds all the required parameters for XROTOR's approach to handling airfoil lift and drag polars. # Arguments - `A0`: zero lift angle of attack, radians. - `DCLDA`: lift curve slope, 1/radians. - `CLMAX`: stall Cl. - `CLMIN`: negative stall Cl. - `DCL_STALL`: CL increment from incipient to total stall. - `DCLDA_STALL`: stalled lift curve slope, 1/radian. - `CDMIN`: minimum Cd. - `CLDMIN`: Cl at minimum Cd. - `DCDCL2`: d(Cd)/d(Cl**2). - `REREF`: Reynolds Number at which Cd values apply. - `REXP`: Exponent for Re scaling of Cd: Cd ~ Re**exponent - `MCRIT`: Critical Mach number. """ struct XROTORAirfoilConfig{TF} A0::TF # = 0. # zero lift angle of attack radians DCLDA::TF # = 6.28 # lift curve slope /radian CLMAX::TF # = 1.5 # stall Cl CLMIN::TF # = -0.5 # negative stall Cl DCL_STALL::TF # = 0.1 # CL increment from incipient to total stall DCLDA_STALL::TF # = 0.1 # stalled lift curve slope /radian CDMIN::TF # = 0.013 # minimum Cd CLDMIN::TF # = 0.5 # Cl at minimum Cd DCDCL2::TF # = 0.004 # d(Cd)/d(Cl**2) REREF::TF # = 200000. # Reynolds Number at which Cd values apply REXP::TF # = -0.4 # Exponent for Re scaling of Cd: Cd ~ Re**exponent MCRIT::TF # = 0.8 # Critical Mach number end function XROTORAirfoilConfig(; A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) return XROTORAirfoilConfig(A0, DCLDA, CLMAX, CLMIN, DCL_STALL, DCLDA_STALL, CDMIN, CLDMIN, DCDCL2, REREF, REXP, MCRIT) end """ af_xrotor(alpha, Re, Mach, config::XROTORAirfoilConfig) Return a tuple of the lift and drag coefficients for a given angle of attach `alpha` (in radians), Reynolds number `Re`, and Mach number `Mach`. """ function af_xrotor(alpha, Re, Mach, config::XROTORAirfoilConfig) # C------------------------------------------------------------ # C CL(alpha) function # C Note that in addition to setting CLIFT and its derivatives # C CLMAX and CLMIN (+ and - stall CL's) are set in this routine # C In the compressible range the stall CL is reduced by a factor # C proportional to Mcrit-Mach. Stall limiting for compressible # C cases begins when the compressible drag added CDC > CDMstall # C------------------------------------------------------------ # C CD(alpha) function - presently CD is assumed to be a sum # C of profile drag + stall drag + compressibility drag # C In the linear lift range drag is CD0 + quadratic function of CL-CLDMIN # C In + or - stall an additional drag is added that is proportional # C to the extent of lift reduction from the linear lift value. # C Compressible drag is based on adding drag proportional to # C (Mach-Mcrit_eff)^MEXP # C------------------------------------------------------------ # C CM(alpha) function - presently CM is assumed constant, # C varying only with Mach by Prandtl-Glauert scaling # C------------------------------------------------------------ # C # INCLUDE 'XROTOR.INC' # LOGICAL STALLF # DOUBLE PRECISION ECMIN, ECMAX # C # C---- Factors for compressibility drag model, HHY 10/23/00 # C Mcrit is set by user # C Effective Mcrit is Mcrit_eff = Mcrit - CLMFACTOR*(CL-CLDmin) - DMDD # C DMDD is the delta Mach to get CD=CDMDD (usually 0.0020) # C Compressible drag is CDC = CDMFACTOR*(Mach-Mcrit_eff)^MEXP # C CDMstall is the drag at which compressible stall begins # A0 = config.A0 DCLDA = config.DCLDA CLMAX = config.CLMAX CLMIN = config.CLMIN DCL_STALL = config.DCL_STALL DCLDA_STALL = config.DCLDA_STALL CDMIN = config.CDMIN CLDMIN = config.CLDMIN DCDCL2 = config.DCDCL2 REREF = config.REREF REXP = config.REXP MCRIT = config.MCRIT CDMFACTOR = 10.0 CLMFACTOR = 0.25 MEXP = 3.0 CDMDD = 0.0020 CDMSTALL = 0.1000 # C # C---- Prandtl-Glauert compressibility factor # MSQ = W*W*VEL^2/VSO^2 # MSQ_W = 2.0*W*VEL^2/VSO^2 # if (MSQ>1.0) # # WRITE(*,*) # # & 'CLFUNC: Local Mach number limited to 0.99, was ', MSQ # MSQ = 0.99 # # MSQ_W = 0. # end MSQ = Mach*Mach if MSQ > 1.0 MSQ = 0.99 Mach = sqrt(MSQ) end PG = 1.0 / sqrt(1.0 - MSQ) # PG_W = 0.5*MSQ_W * PG^3 # C # C---- Mach number and dependence on velocity # Mach = sqrt(MSQ) # MACH_W = 0.0 # IF(Mach.NE.0.0) MACH_W = 0.5*MSQ_W/Mach # if ! (mach β‰ˆ 0.0) # MACH_W = 0.5*MSQ_W/Mach # end # C # C # C------------------------------------------------------------ # C--- Generate CL from dCL/dAlpha and Prandtl-Glauert scaling CLA = DCLDA*PG *(alpha-A0) # CLA_ALF = DCLDA*PG # CLA_W = DCLDA*PG_W*(ALF-A0) # C # C--- Effective CLmax is limited by Mach effects # C reduces CLmax to match the CL of onset of serious compressible drag CLMX = CLMAX CLMN = CLMIN DMSTALL = (CDMSTALL/CDMFACTOR)^(1.0/MEXP) CLMAXM = max(0.0, (MCRIT+DMSTALL-Mach)/CLMFACTOR) + CLDMIN CLMAX = min(CLMAX,CLMAXM) CLMINM = min(0.0,-(MCRIT+DMSTALL-Mach)/CLMFACTOR) + CLDMIN CLMIN = max(CLMIN,CLMINM) # C # C--- CL limiter function (turns on after +-stall ECMAX = exp( min(200.0, (CLA-CLMAX)/DCL_STALL) ) ECMIN = exp( min(200.0, (CLMIN-CLA)/DCL_STALL) ) CLLIM = DCL_STALL * log( (1.0+ECMAX)/(1.0+ECMIN) ) CLLIM_CLA = ECMAX/(1.0+ECMAX) + ECMIN/(1.0+ECMIN) # c # c if(CLLIM.GT.0.001) then # c write(*,999) 'cla,cllim,ecmax,ecmin ',cla,cllim,ecmax,ecmin # c endif # c 999 format(a,2(1x,f10.6),3(1x,d12.6)) # C # C--- Subtract off a (nearly unity) fraction of the limited CL function # C This sets the dCL/dAlpha in the stalled regions to 1-FSTALL of that # C in the linear lift range FSTALL = DCLDA_STALL/DCLDA CLIFT = CLA - (1.0-FSTALL)*CLLIM # CL_ALF = CLA_ALF - (1.0-FSTALL)*CLLIM_CLA*CLA_ALF # CL_W = CLA_W - (1.0-FSTALL)*CLLIM_CLA*CLA_W # C # STALLF = false # IF(CLIFT.GT.CLMAX) STALLF = .TRUE. # IF(CLIFT.LT.CLMIN) STALLF = .TRUE. # STALLF = (CLIFT > CLMAX) || (CLIFT < CLMIN) # C # C # C------------------------------------------------------------ # C--- CM from CMCON and Prandtl-Glauert scaling # CMOM = PG*CMCON # CM_AL = 0.0 # CM_W = PG_W*CMCON # C # C # C------------------------------------------------------------ # C--- CD from profile drag, stall drag and compressibility drag # C # C---- Reynolds number scaling factor if (Re < 0.0) RCORR = 1.0 # RCORR_REY = 0.0 else RCORR = (Re/REREF)^REXP # RCORR_REY = REXP/Re end # C # C--- In the basic linear lift range drag is a function of lift # C CD = CD0 (constant) + quadratic with CL) CDRAG = (CDMIN + DCDCL2*(CLIFT-CLDMIN)^2 ) * RCORR # CD_ALF = ( 2.0*DCDCL2*(CLIFT-CLDMIN)*CL_ALF) * RCORR # CD_W = ( 2.0*DCDCL2*(CLIFT-CLDMIN)*CL_W ) * RCORR # CD_REY = CDRAG*RCORR_REY # C # C--- Post-stall drag added FSTALL = DCLDA_STALL/DCLDA DCDX = (1.0-FSTALL)*CLLIM/(PG*DCLDA) # c write(*,*) 'cla,cllim,fstall,pg,dclda ',cla,cllim,fstall,pg,dclda DCD = 2.0* DCDX^2 # DCD_ALF = 4.0* DCDX * (1.0-FSTALL)*CLLIM_CLA*CLA_ALF/(PG*DCLDA) # DCD_W = 4.0* DCDX * ( (1.0-FSTALL)*CLLIM_CLA*CLA_W/(PG*DCLDA) - DCD/PG*PG_W ) # c write(*,*) 'alf,cl,dcd,dcd_alf,dcd_w ',alf,clift,dcd,dcd_alf,dcd_w # C # C--- Compressibility drag (accounts for drag rise above Mcrit with CL effects # C CDC is a function of a scaling factor*(M-Mcrit(CL))^MEXP # C DMDD is the Mach difference corresponding to CD rise of CDMDD at MCRIT DMDD = (CDMDD/CDMFACTOR)^(1.0/MEXP) CRITMACH = MCRIT-CLMFACTOR*abs(CLIFT-CLDMIN) - DMDD # CRITMACH_ALF = -CLMFACTOR*ABS(CL_ALF) # CRITMACH_W = -CLMFACTOR*ABS(CL_W) if (Mach < CRITMACH) CDC = 0.0 # CDC_ALF = 0.0 # CDC_W = 0.0 else CDC = CDMFACTOR*(Mach-CRITMACH)^MEXP # CDC_W = MEXP*MACH_W*CDC/Mach - MEXP*CRITMACH_W *CDC/CRITMACH # CDC_ALF = - MEXP*CRITMACH_ALF*CDC/CRITMACH end # c write(*,*) 'critmach,mach ',critmach,mach # c write(*,*) 'cdc,cdc_w,cdc_alf ',cdc,cdc_w,cdc_alf # C FAC = 1.0 # FAC_W = 0.0 # C--- Although test data does not show profile drag increases due to Mach # # C you could use something like this to add increase drag by Prandtl-Glauert # C (or any function you choose) # cc FAC = PG # cc FAC_W = PG_W # C--- Total drag terms CDRAG = FAC*CDRAG + DCD + CDC # CD_ALF = FAC*CD_ALF + DCD_ALF + CDC_ALF # CD_W = FAC*CD_W + FAC_W*CDRAG + DCD_W + CDC_W # CD_REY = FAC*CD_REY # C return CLIFT, CDRAG end ``` AcousticAnalogies.jl can write out [`CompactF1ASourceElement`](@ref) `structs` to VTK files, allowing us to easily visualize the state and motion of the acoustic sources in popular visualization tools (e.g. [ParaView](https://www.paraview.org/)). This is very useful for checking that the motion, loading, coordinate system, etc. is what we expect. To write out VTK files, we just need to pass an array of source elements to the [`AcousticAnalogies.to_paraview_collection`](@ref) function. We'll use [`CCBlade.jl`](https://github.com/byuflowlab/CCBlade.jl) to calculate the aerodynamic loads, and the CCBlade.jl helper routines that AcousticAnalogies.jl provides to create the source elements from the CCBlade.jl data. ```@example vtk_example using AcousticAnalogies using CCBlade # Define the blade geometry. B = 2 Rhub = 0.10 Rtip = 1.1684 # meters radii = Rhub .+ range(0.0, 1.0, length=31).*(Rtip - Rhub) radii = 0.5.*(radii[2:end] .+ radii[1:end-1]) cs_area_over_chord_squared = 0.064 chord = [ 0.35044 , 0.28260 , 0.22105 , 0.17787 , 0.14760, 0.12567 , 0.10927 , 0.96661E-01 , 0.86742E-01 , 0.78783E-01 , 0.72287E-01 , 0.66906E-01 , 0.62387E-01 , 0.58541E-01 , 0.55217E-01 , 0.52290E-01 , 0.49645E-01 , 0.47176E-01 , 0.44772E-01 , 0.42326E-01 , 0.39732E-01 , 0.36898E-01 , 0.33752E-01 , 0.30255E-01 , 0.26401E-01 , 0.22217E-01 , 0.17765E-01 , 0.13147E-01 , 0.85683E-02 , 0.47397E-02].*Rtip theta = [ 40.005, 34.201, 28.149, 23.753, 20.699, 18.516, 16.890, 15.633, 14.625, 13.795, 13.094, 12.488, 11.956, 11.481, 11.053, 10.662, 10.303, 9.9726, 9.6674, 9.3858, 9.1268, 8.8903, 8.6764, 8.4858, 8.3193, 8.1783, 8.0638, 7.9769, 7.9183, 7.8889].*(pi/180) # Define the operating point. rpm = 2200.0 omega = rpm*(2*pi/60.0) rho = 1.226 # kg/m^3 c0 = 340.0 # m/s mu = 0.1780e-4 # kg/(m*s) pitch = 0.0 # rad Vinf = 5.0 # m/s # Create an airfoil interpolation object. xrotor_config = XROTORAirfoilConfig( A0=0.0, DCLDA=6.2800, CLMAX=1.5, CLMIN=-0.5, DCLDA_STALL=0.1, DCL_STALL=0.1, MCRIT=0.8, CDMIN=0.13e-1, CLDMIN=0.5, DCDCL2=0.4e-2, REREF=0.2e6, REXP=-0.4) airfoil_interp(a, r, m) = af_xrotor(a, r, m, xrotor_config) # Create the CCBlade.jl structs. rotor = Rotor(Rhub, Rtip, B) sections = Section.(radii, chord, theta, Ref(airfoil_interp)) ops = OperatingPoint.(Vinf, omega.*radii, rho, pitch, mu, c0) outs = solve.(Ref(rotor), sections, ops) # Create the AcousticAnalogies.jl source elements. bpp = 60/(rpm*B) period = 2*bpp num_source_times = 64 positive_x_rotation = true ses = f1a_source_elements_ccblade(rotor, sections, ops, outs, fill(cs_area_over_chord_squared, length(radii)), period, num_source_times, positive_x_rotation) @show size(ses) ``` `ses` is an array of source elements of shape `(num_source_times, num_radial, B)`, where `num_source_times` is the number of time steps over which the source elements are defined, `num_radial` is the number of radial elements each blade is subdivided into, and `B` is the number of blades. Now that we have an array of source elements, we can write them out to VTK files. ```@example vtk_example name = "two_blade_example" outfiles = AcousticAnalogies.to_paraview_collection(name, ses) ``` This will write out one polygonal VTK (`.vtp`) file per time step, along with a ParaView collection (`.pvd`) file that allows us to open all of the `.vtp` files at once. Here's an example visualization of the above example, showing an animation of the loading in the `y` direction, which is normal to the rotation axis of the rotor. ![Loading Animation](assets/two_blade_example-y_loading.gif)
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "Apache-2.0" ]
0.8.1
c14d0b2e7f19374017a2b5b6dfe48c5723c791ae
docs
84
Airfoil data is from http://airfoiltools.com/polar/details?polar=xf-n0012-il-500000
AcousticAnalogies
https://github.com/OpenMDAO/AcousticAnalogies.jl.git
[ "MIT" ]
1.0.0
ad84a76cb2b4ccf86ad91c0c44b76acd326e0f2a
code
1082
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENCE in the project root. # ------------------------------------------------------------------ module RankAggregation using Tables """ AggregationMethod A rank aggregation method. """ abstract type AggregationMethod end """ rank(objects, scores, method; rev=false) Rank `objects` stored in a tabular format on the basis of `scores` columns and with an aggregation `method`. """ function rank(objects, scores::NTuple{N,Symbol}, method::AggregationMethod=TauModel(); rev=false) where {N} r = rank_impl(objects, scores, method) rev ? length(r) .- r .+ 1 : r end rank(objects, score::Symbol, method::AggregationMethod=TauModel(); rev=false) = rank(objects, (score,), method, rev=rev) rank_impl(::Any, ::NTuple{N,Symbol}, ::AggregationMethod) where {N} = @error "not implemented" #------------------ # IMPLEMENTATIONS #------------------ include("tau_model.jl") export AggregationMethod, TauModel, rank end # module
RankAggregation
https://github.com/JuliaML/RankAggregation.jl.git
[ "MIT" ]
1.0.0
ad84a76cb2b4ccf86ad91c0c44b76acd326e0f2a
code
1025
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENCE in the project root. # ------------------------------------------------------------------ """ TauModel() Probabilistic rank aggregation with the Tau model. ## References * Journel 2002. Combining Knowledge From Diverse Sources: An Alternative to Traditional Data Independence Hypotheses. """ struct TauModel <: AggregationMethod end function rank_impl(objects, scores::NTuple{N,Symbol}, method::TauModel) where {N} # score columns cols = [] for col in propertynames(objects) if col ∈ scores push!(cols, getproperty(objects, col)) end end # conditional probabilities S = reduce(hcat, cols) P = S ./ sum(S, dims=1) n = size(P, 1) # uniform prior xβ‚’ = (1 - 1/n) / (1/n) # odds with no redundancy X = (1 .- P) ./ P x = xβ‚’ * prod(X/xβ‚’, dims=2) # posterior probabilities p = 1 ./ (1 .+ x) # final rank sortperm(vec(p), rev=true) end
RankAggregation
https://github.com/JuliaML/RankAggregation.jl.git
[ "MIT" ]
1.0.0
ad84a76cb2b4ccf86ad91c0c44b76acd326e0f2a
code
412
using RankAggregation using DataFrames using Test @testset "RankAggregation.jl" begin objects = DataFrame(object=[:a,:b,:c], score1=[0.9, 0.7, 0.5], score2=[0.8, 0.9, 0.4]) @test rank(objects, :score1) == [1,2,3] @test rank(objects, :score2) == [2,1,3] @test rank(objects, (:score1,:score2)) == [1,2,3] @test rank(objects, :score2, rev=true) == [2,3,1] end
RankAggregation
https://github.com/JuliaML/RankAggregation.jl.git
[ "MIT" ]
1.0.0
ad84a76cb2b4ccf86ad91c0c44b76acd326e0f2a
docs
2577
<p align="center"> <img src="docs/RankAggregation.png" height="200"><br> <a href="https://travis-ci.org/JuliaEarth/RankAggregation.jl"> <img src="https://travis-ci.org/JuliaEarth/RankAggregation.jl.svg?branch=master"> </a> <a href="https://codecov.io/gh/JuliaEarth/RankAggregation.jl"> <img src="https://codecov.io/gh/JuliaEarth/RankAggregation.jl/branch/master/graph/badge.svg"> </a> <a href="LICENSE"> <img src="https://img.shields.io/badge/license-MIT-blue.svg"> </a> </p> Given a set of objects (e.g. rows of a table) with scores given by different scoring methods (e.g. columns), how to rank the objects? This problem is known in the literature as the rank aggregation problem. The problem is trivial when there is only one score for each object (one column), but ranking objects on the basis of multiple (conflicting) scores is challenging. This package provides algorithms to aggregate multiple scores stored in a tabular format (see [Tables.jl](https://github.com/JuliaData/Tables.jl)) into a final rank vector. ## Installation Get the latest stable release with Julia's package manager: ```julia ] add RankAggregation ``` ## Usage Given a table with scores `score1` and `score2` for objects `a`, `b`, and `c`: ```julia julia> using DataFrames julia> using RankAggregation julia> objects = DataFrame(object=[:a,:b,:c], score1=[0.9, 0.7, 0.5], score2=[0.8, 0.9, 0.4]) 3Γ—3 DataFrame β”‚ Row β”‚ object β”‚ score1 β”‚ score2 β”‚ β”‚ β”‚ Symbol β”‚ Float64 β”‚ Float64 β”‚ β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1 β”‚ a β”‚ 0.9 β”‚ 0.8 β”‚ β”‚ 2 β”‚ b β”‚ 0.7 β”‚ 0.9 β”‚ β”‚ 3 β”‚ c β”‚ 0.5 β”‚ 0.4 β”‚ ``` rank the objects using: ```julia julia> rank(objects, :score1) 3-element Array{Int64,1}: 1 2 3 julia> rank(objects, :score2) 3-element Array{Int64,1}: 2 1 3 julia> rank(objects, (:score1,:score2)) 3-element Array{Int64,1}: 1 2 3 ``` Optionally, specify the aggregation method: ```julia julia> rank(objects, (:score1,:score2), TauModel()) 3-element Array{Int64,1}: 1 2 3 ``` and the reverse option: ```julia julia> rank(objects, (:score1,:score2), rev=true) 3-element Array{Int64,1}: 3 2 1 ``` ## Aggregation Methods | Method | References | |--------|------------| | `TauModel` | Journel 2002. Combining Knowledge From Diverse Sources: An Alternative to Traditional Data Independence Hypotheses. | ## Contributing Contributions are very welcome, as are feature requests and suggestions. Please [open an issue](https://github.com/JuliaEarth/RankAggregation.jl/issues) if you encounter any problems.
RankAggregation
https://github.com/JuliaML/RankAggregation.jl.git
[ "MIT" ]
0.2.0
b007cfc7f9bee9a958992d2301e9c5b63f332a90
code
6241
module ILUZero using LinearAlgebra, SparseArrays import LinearAlgebra.ldiv!, LinearAlgebra.\, SparseArrays.nnz export ILU0Precon, \, forward_substitution!, backward_substitution!, nnz, ldiv!, ilu0, ilu0! # ILU0 type definition struct ILU0Precon{T <: Any, N <: Integer, M<: Any} <: Factorization{T} m::N n::N l_colptr::Vector{N} l_rowval::Vector{N} l_nzval::Vector{T} u_colptr::Vector{N} u_rowval::Vector{N} u_nzval::Vector{T} l_map::Vector{N} u_map::Vector{N} wrk::Vector{M} end # Allocates ILU0Precon type function ILU0Precon(A::SparseMatrixCSC{T,N}, b_type = T) where {T <: Any,N <: Integer} m, n = size(A) # Determine number of elements in lower/upper lnz = 0 unz = 0 @inbounds for i = 1:n for j = A.colptr[i]:A.colptr[i + 1] - 1 if A.rowval[j] > i lnz += 1 else unz += 1 end end end # Preallocate variables l_colptr = zeros(N, n + 1) u_colptr = zeros(N, n + 1) l_nzval = zeros(T, lnz) u_nzval = zeros(T, unz) l_rowval = zeros(Int64, lnz) u_rowval = zeros(Int64, unz) l_map = Vector{N}(undef, lnz) u_map = Vector{N}(undef, unz) wrk = zeros(b_type, n) l_colptr[1] = 1 u_colptr[1] = 1 # Map elements of A to lower and upper triangles, fill out colptr, and fill out rowval lit = 1 uit = 1 @inbounds for i = 1:n l_colptr[i + 1] = l_colptr[i] u_colptr[i + 1] = u_colptr[i] for j = A.colptr[i]:A.colptr[i + 1] - 1 if A.rowval[j] > i l_colptr[i + 1] += 1 l_rowval[lit] = A.rowval[j] l_map[lit] = j lit += 1 else u_colptr[i + 1] += 1 u_rowval[uit] = A.rowval[j] u_map[uit] = j uit += 1 end end end return ILU0Precon(m, n, l_colptr, l_rowval, l_nzval, u_colptr, u_rowval, u_nzval, l_map, u_map, wrk) end # Updates ILU0Precon type in-place based on matrix A function ilu0!(LU::ILU0Precon{T,N}, A::SparseMatrixCSC{T,N}) where {T <: Any,N <: Integer} m = LU.m n = LU.n l_colptr = LU.l_colptr l_rowval = LU.l_rowval l_nzval = LU.l_nzval u_colptr = LU.u_colptr u_rowval = LU.u_rowval u_nzval = LU.u_nzval l_map = LU.l_map u_map = LU.u_map # Redundant data or better speed... speed is chosen, but this might be changed. # This shouldn't be inbounded either. for i = 1:length(l_map) l_nzval[i] = A.nzval[l_map[i]] end for i = 1:length(u_map) u_nzval[i] = A.nzval[u_map[i]] end @inbounds for i = 1:m - 1 m_inv = inv(u_nzval[u_colptr[i + 1] - 1]) for j = l_colptr[i]:l_colptr[i + 1] - 1 l_nzval[j] = l_nzval[j] * m_inv end for j = u_colptr[i + 1]:u_colptr[i + 2] - 2 multiplier = u_nzval[j] qn = j + 1 rn = l_colptr[i + 1] pn = l_colptr[u_rowval[j]] while pn < l_colptr[u_rowval[j] + 1] && l_rowval[pn] <= i + 1 while qn < u_colptr[i + 2] && u_rowval[qn] < l_rowval[pn] qn += 1 end if qn < u_colptr[i + 2] && l_rowval[pn] == u_rowval[qn] u_nzval[qn] -= l_nzval[pn] * multiplier end pn += 1 end while pn < l_colptr[u_rowval[j] + 1] while rn < l_colptr[i + 2] && l_rowval[rn] < l_rowval[pn] rn += 1 end if rn < l_colptr[i + 2] && l_rowval[pn] == l_rowval[rn] l_nzval[rn] -= l_nzval[pn] * multiplier end pn += 1 end end end return end # Constructs ILU0Precon type based on matrix A function ilu0(A::SparseMatrixCSC{T,N}, arg...) where {T <: Any,N <: Integer} LU = ILU0Precon(A, arg...) ilu0!(LU, A) return LU end # Solves L\b and stores the solution in y function forward_substitution!(y, LU::ILU0Precon{T,N,M}, b) where {T, N <: Integer, M} n = LU.n l_colptr = LU.l_colptr l_rowval = LU.l_rowval l_nzval = LU.l_nzval for i in eachindex(y) y[i] = zero(M) end @inbounds for i = 1:n y[i] += b[i] for j = l_colptr[i]:l_colptr[i + 1] - 1 y[l_rowval[j]] -= l_nzval[j] * y[i] end end return y end # Solves U\y and stores the solution in x function backward_substitution!(x, LU::ILU0Precon, y) n = LU.n u_colptr = LU.u_colptr u_rowval = LU.u_rowval u_nzval = LU.u_nzval wrk = LU.wrk wrk .= y @inbounds for i = n:-1:1 x[i] = u_nzval[u_colptr[i + 1] - 1] \ wrk[i] for j = u_colptr[i]:u_colptr[i + 1] - 2 wrk[u_rowval[j]] -= u_nzval[j] * x[i] end end return x end # Solves LU\b overwriting x function ldiv!(x::AbstractVector{M}, LU::ILU0Precon{T,N,M}, b::AbstractVector{M}) where {T,N <: Integer,M} (length(b) == LU.n) || throw(DimensionMismatch()) n = LU.n l_colptr = LU.l_colptr l_rowval = LU.l_rowval l_nzval = LU.l_nzval u_colptr = LU.u_colptr u_rowval = LU.u_rowval u_nzval = LU.u_nzval wrk = LU.wrk for i in eachindex(wrk) wrk[i] = zero(M) end @inbounds for i = 1:n wrk[i] += b[i] for j = l_colptr[i]:l_colptr[i + 1] - 1 wrk[l_rowval[j]] -= l_nzval[j] * wrk[i] end end @inbounds for i = n:-1:1 x[i] = u_nzval[u_colptr[i + 1] - 1] \ wrk[i] for j = u_colptr[i]:u_colptr[i + 1] - 2 wrk[u_rowval[j]] -= u_nzval[j] * x[i] end end return x end # Solves LU\b overwriting b function ldiv!(LU::ILU0Precon{T,N}, b::AbstractVector{T}) where {T <: Any,N <: Integer} ldiv!(b, LU, b) end # Returns LU\b function \(LU::ILU0Precon{T,N}, b::Vector{T}) where {T <: Any,N <: Integer} length(b) == LU.n || throw(DimensionMismatch()) x = zeros(T, length(b)) ldiv!(x, LU, b) end # Returns the number of nonzero function nnz(LU::ILU0Precon{T,N}) where {T <: Any,N <: Integer} return length(LU.l_nzval) + length(LU.u_nzval) end end
ILUZero
https://github.com/mcovalt/ILUZero.jl.git
[ "MIT" ]
0.2.0
b007cfc7f9bee9a958992d2301e9c5b63f332a90
code
1271
# Start Test Script using ILUZero, LinearAlgebra, SparseArrays, Test function cg(A, b; M=I) n = size(A, 1) x = zeros(n) r = copy(b) z = zeros(n) ldiv!(z, M, r) p = copy(z) Ξ³ = dot(r, z) k = 0 tired = false solved = false while !(solved || tired) Ap = A * p Ξ± = Ξ³ / dot(p, Ap) x = x + Ξ± * p r = r - Ξ± * Ap ldiv!(z, M, r) Ξ³_new = dot(r, z) Ξ² = Ξ³_new / Ξ³ Ξ³ = Ξ³_new p = z + Ξ² * p k = k + 1 tired = k > n solved = norm(r) ≀ 1e-8 * norm(b) end return x, k end function test_solve() n = 100 tA = sprandn(n, n, .1) + 10.0 * I A = tA' * tA ilu_prec = ilu0(A) b = rand(n) x1, k1 = cg(A, b) println("No preconditioning: ", k1, " iterations") x2, k2 = cg(A, b, M=ilu_prec) println("Preconditioned: ", k2, " iterations") return k1 > k2 end function test_substitutions() n = 100 tA = sprandn(n, n, .1) + 10.0 * I A = tA' * tA ilu_prec = ilu0(A) b = rand(n) x = ilu_prec \ b x1 = zeros(n) x2 = zeros(n) forward_substitution!(x1, ilu_prec, b) backward_substitution!(x2, ilu_prec, x1) return (x2 == x) end @test test_solve() @test test_substitutions()
ILUZero
https://github.com/mcovalt/ILUZero.jl.git
[ "MIT" ]
0.2.0
b007cfc7f9bee9a958992d2301e9c5b63f332a90
docs
2152
# ILUZero.jl `ILUZero.jl` is a Julia implementation of incomplete LU factorization with zero level of fill-in. It allows for non-allocating updates of the factorization. The module is compatible with [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl). ## Requirements * Julia 1.0 and up ## Installation ```julia julia> ] pkg> add ILUZero ``` ## Why use ILUZero.jl? You probably shouldn't. Julia's built in factorization methods are much better. Julia uses [SuiteSparse](http://faculty.cse.tamu.edu/davis/suitesparse.html) for sparse matrix factorization which factorizes at about nearly the same speed and results in similarly sized preconditioners which are *much* more robust. In addition, Julia uses heuristics to determine a good factorization scheme for your matrix automatically. Due to the zero-fill of this package, however, factorization should be a bit faster and preconditioners can be preallocated if updated by a matrix of identical sparsity. ## How to use ```julia julia> using ILUZero ``` * `LU = ilu0(A)`: Create a factorization based on a sparse matrix `A` * `ilu0!(LU, A)`: Update factorization `LU` in-place based on a sparse matrix `A`. This assumes the original factorization was created with another sparse matrix with the exact same sparsity pattern as `A`. No check is made for this. * To solve for `x` in `(LU)x=b`, use the same methods as you typically would: `\` or `ldiv!(x, LU, b)`. See [the docs](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/) for further information. * There's also: - Forward substitution: `forward_substitution!(y, LU, b)` solves `L\b` and stores the solution in y. - Backward substitution: `backward_substitution!(x, LU, y)` solves `U\y` and stores the solution in x. - Nonzero count: `nnz(LU)` will return the number of nonzero entries in `LU`. ## Performance ```julia julia> using ILUZero julia> using BenchmarkTools, LinearAlgebra, SparseArrays julia> A = sprand(1000, 1000, 5 / 1000) + 10I julia> fact = @btime ilu0(A) 107.600 ΞΌs (16 allocations: 160.81 KiB) julia> updated_fact = @btime ilu0!($fact, $A) 71.500 ΞΌs (0 allocations: 0 bytes) ```
ILUZero
https://github.com/mcovalt/ILUZero.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
416
using Clang.Generators using libwebp_jll cd(@__DIR__) include_dir = joinpath(libwebp_jll.artifact_dir, "include", "webp") options = load_options(joinpath(@__DIR__, "generator.toml")) args = get_default_args() push!(args, "-I$include_dir") headers = [ joinpath(include_dir, header) for header in readdir(include_dir) if endswith(header, ".h") ] ctx = create_context(headers, args, options) build!(ctx)
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
284
module WebP using ColorTypes using FileIO using FixedPointNumbers using ImageCore include(joinpath(@__DIR__, "Wrapper.jl")) using .Wrapper include(joinpath(@__DIR__, "decoding.jl")) include(joinpath(@__DIR__, "encoding.jl")) include(joinpath(@__DIR__, "fileio_interface.jl")) end
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
32930
module Wrapper using libwebp_jll export libwebp_jll using CEnum struct WebPRGBABuffer rgba::Ptr{UInt8} stride::Cint size::Csize_t end struct WebPYUVABuffer y::Ptr{UInt8} u::Ptr{UInt8} v::Ptr{UInt8} a::Ptr{UInt8} y_stride::Cint u_stride::Cint v_stride::Cint a_stride::Cint y_size::Csize_t u_size::Csize_t v_size::Csize_t a_size::Csize_t end @cenum WEBP_CSP_MODE::UInt32 begin MODE_RGB = 0 MODE_RGBA = 1 MODE_BGR = 2 MODE_BGRA = 3 MODE_ARGB = 4 MODE_RGBA_4444 = 5 MODE_RGB_565 = 6 MODE_rgbA = 7 MODE_bgrA = 8 MODE_Argb = 9 MODE_rgbA_4444 = 10 MODE_YUV = 11 MODE_YUVA = 12 MODE_LAST = 13 end struct var"##Ctag#243" data::NTuple{80, UInt8} end function Base.getproperty(x::Ptr{var"##Ctag#243"}, f::Symbol) f === :RGBA && return Ptr{WebPRGBABuffer}(x + 0) f === :YUVA && return Ptr{WebPYUVABuffer}(x + 0) return getfield(x, f) end function Base.getproperty(x::var"##Ctag#243", f::Symbol) r = Ref{var"##Ctag#243"}(x) ptr = Base.unsafe_convert(Ptr{var"##Ctag#243"}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{var"##Ctag#243"}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct WebPDecBuffer data::NTuple{120, UInt8} end function Base.getproperty(x::Ptr{WebPDecBuffer}, f::Symbol) f === :colorspace && return Ptr{WEBP_CSP_MODE}(x + 0) f === :width && return Ptr{Cint}(x + 4) f === :height && return Ptr{Cint}(x + 8) f === :is_external_memory && return Ptr{Cint}(x + 12) f === :u && return Ptr{var"##Ctag#243"}(x + 16) f === :pad && return Ptr{NTuple{4, UInt32}}(x + 96) f === :private_memory && return Ptr{Ptr{UInt8}}(x + 112) return getfield(x, f) end function Base.getproperty(x::WebPDecBuffer, f::Symbol) r = Ref{WebPDecBuffer}(x) ptr = Base.unsafe_convert(Ptr{WebPDecBuffer}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{WebPDecBuffer}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end mutable struct WebPIDecoder end struct WebPBitstreamFeatures width::Cint height::Cint has_alpha::Cint has_animation::Cint format::Cint pad::NTuple{5, UInt32} end struct WebPDecoderOptions bypass_filtering::Cint no_fancy_upsampling::Cint use_cropping::Cint crop_left::Cint crop_top::Cint crop_width::Cint crop_height::Cint use_scaling::Cint scaled_width::Cint scaled_height::Cint use_threads::Cint dithering_strength::Cint flip::Cint alpha_dithering_strength::Cint pad::NTuple{5, UInt32} end struct WebPDecoderConfig input::WebPBitstreamFeatures output::WebPDecBuffer options::WebPDecoderOptions end function WebPGetDecoderVersion() ccall((:WebPGetDecoderVersion, libwebp), Cint, ()) end function WebPGetInfo(data, data_size, width, height) ccall((:WebPGetInfo, libwebp), Cint, (Ptr{UInt8}, Csize_t, Ptr{Cint}, Ptr{Cint}), data, data_size, width, height) end function WebPDecodeRGBA(data, data_size, width, height) ccall((:WebPDecodeRGBA, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{Cint}, Ptr{Cint}), data, data_size, width, height) end function WebPDecodeARGB(data, data_size, width, height) ccall((:WebPDecodeARGB, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{Cint}, Ptr{Cint}), data, data_size, width, height) end function WebPDecodeBGRA(data, data_size, width, height) ccall((:WebPDecodeBGRA, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{Cint}, Ptr{Cint}), data, data_size, width, height) end function WebPDecodeRGB(data, data_size, width, height) ccall((:WebPDecodeRGB, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{Cint}, Ptr{Cint}), data, data_size, width, height) end function WebPDecodeBGR(data, data_size, width, height) ccall((:WebPDecodeBGR, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{Cint}, Ptr{Cint}), data, data_size, width, height) end function WebPDecodeYUV(data, data_size, width, height, u, v, stride, uv_stride) ccall((:WebPDecodeYUV, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{Cint}, Ptr{Cint}, Ptr{Ptr{UInt8}}, Ptr{Ptr{UInt8}}, Ptr{Cint}, Ptr{Cint}), data, data_size, width, height, u, v, stride, uv_stride) end function WebPDecodeRGBAInto(data, data_size, output_buffer, output_buffer_size, output_stride) ccall((:WebPDecodeRGBAInto, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{UInt8}, Csize_t, Cint), data, data_size, output_buffer, output_buffer_size, output_stride) end function WebPDecodeARGBInto(data, data_size, output_buffer, output_buffer_size, output_stride) ccall((:WebPDecodeARGBInto, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{UInt8}, Csize_t, Cint), data, data_size, output_buffer, output_buffer_size, output_stride) end function WebPDecodeBGRAInto(data, data_size, output_buffer, output_buffer_size, output_stride) ccall((:WebPDecodeBGRAInto, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{UInt8}, Csize_t, Cint), data, data_size, output_buffer, output_buffer_size, output_stride) end function WebPDecodeRGBInto(data, data_size, output_buffer, output_buffer_size, output_stride) ccall((:WebPDecodeRGBInto, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{UInt8}, Csize_t, Cint), data, data_size, output_buffer, output_buffer_size, output_stride) end function WebPDecodeBGRInto(data, data_size, output_buffer, output_buffer_size, output_stride) ccall((:WebPDecodeBGRInto, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{UInt8}, Csize_t, Cint), data, data_size, output_buffer, output_buffer_size, output_stride) end function WebPDecodeYUVInto(data, data_size, luma, luma_size, luma_stride, u, u_size, u_stride, v, v_size, v_stride) ccall((:WebPDecodeYUVInto, libwebp), Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{UInt8}, Csize_t, Cint, Ptr{UInt8}, Csize_t, Cint, Ptr{UInt8}, Csize_t, Cint), data, data_size, luma, luma_size, luma_stride, u, u_size, u_stride, v, v_size, v_stride) end function WebPIsPremultipliedMode(mode) ccall((:WebPIsPremultipliedMode, libwebp), Cint, (WEBP_CSP_MODE,), mode) end function WebPIsAlphaMode(mode) ccall((:WebPIsAlphaMode, libwebp), Cint, (WEBP_CSP_MODE,), mode) end function WebPIsRGBMode(mode) ccall((:WebPIsRGBMode, libwebp), Cint, (WEBP_CSP_MODE,), mode) end function WebPInitDecBufferInternal(arg1, arg2) ccall((:WebPInitDecBufferInternal, libwebp), Cint, (Ptr{WebPDecBuffer}, Cint), arg1, arg2) end function WebPInitDecBuffer(buffer) ccall((:WebPInitDecBuffer, libwebp), Cint, (Ptr{WebPDecBuffer},), buffer) end function WebPFreeDecBuffer(buffer) ccall((:WebPFreeDecBuffer, libwebp), Cvoid, (Ptr{WebPDecBuffer},), buffer) end @cenum VP8StatusCode::UInt32 begin VP8_STATUS_OK = 0 VP8_STATUS_OUT_OF_MEMORY = 1 VP8_STATUS_INVALID_PARAM = 2 VP8_STATUS_BITSTREAM_ERROR = 3 VP8_STATUS_UNSUPPORTED_FEATURE = 4 VP8_STATUS_SUSPENDED = 5 VP8_STATUS_USER_ABORT = 6 VP8_STATUS_NOT_ENOUGH_DATA = 7 end function WebPINewDecoder(output_buffer) ccall((:WebPINewDecoder, libwebp), Ptr{WebPIDecoder}, (Ptr{WebPDecBuffer},), output_buffer) end function WebPINewRGB(csp, output_buffer, output_buffer_size, output_stride) ccall((:WebPINewRGB, libwebp), Ptr{WebPIDecoder}, (WEBP_CSP_MODE, Ptr{UInt8}, Csize_t, Cint), csp, output_buffer, output_buffer_size, output_stride) end function WebPINewYUVA(luma, luma_size, luma_stride, u, u_size, u_stride, v, v_size, v_stride, a, a_size, a_stride) ccall((:WebPINewYUVA, libwebp), Ptr{WebPIDecoder}, (Ptr{UInt8}, Csize_t, Cint, Ptr{UInt8}, Csize_t, Cint, Ptr{UInt8}, Csize_t, Cint, Ptr{UInt8}, Csize_t, Cint), luma, luma_size, luma_stride, u, u_size, u_stride, v, v_size, v_stride, a, a_size, a_stride) end function WebPINewYUV(luma, luma_size, luma_stride, u, u_size, u_stride, v, v_size, v_stride) ccall((:WebPINewYUV, libwebp), Ptr{WebPIDecoder}, (Ptr{UInt8}, Csize_t, Cint, Ptr{UInt8}, Csize_t, Cint, Ptr{UInt8}, Csize_t, Cint), luma, luma_size, luma_stride, u, u_size, u_stride, v, v_size, v_stride) end function WebPIDelete(idec) ccall((:WebPIDelete, libwebp), Cvoid, (Ptr{WebPIDecoder},), idec) end function WebPIAppend(idec, data, data_size) ccall((:WebPIAppend, libwebp), VP8StatusCode, (Ptr{WebPIDecoder}, Ptr{UInt8}, Csize_t), idec, data, data_size) end function WebPIUpdate(idec, data, data_size) ccall((:WebPIUpdate, libwebp), VP8StatusCode, (Ptr{WebPIDecoder}, Ptr{UInt8}, Csize_t), idec, data, data_size) end function WebPIDecGetRGB(idec, last_y, width, height, stride) ccall((:WebPIDecGetRGB, libwebp), Ptr{UInt8}, (Ptr{WebPIDecoder}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), idec, last_y, width, height, stride) end function WebPIDecGetYUVA(idec, last_y, u, v, a, width, height, stride, uv_stride, a_stride) ccall((:WebPIDecGetYUVA, libwebp), Ptr{UInt8}, (Ptr{WebPIDecoder}, Ptr{Cint}, Ptr{Ptr{UInt8}}, Ptr{Ptr{UInt8}}, Ptr{Ptr{UInt8}}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), idec, last_y, u, v, a, width, height, stride, uv_stride, a_stride) end function WebPIDecGetYUV(idec, last_y, u, v, width, height, stride, uv_stride) ccall((:WebPIDecGetYUV, libwebp), Ptr{UInt8}, (Ptr{WebPIDecoder}, Ptr{Cint}, Ptr{Ptr{UInt8}}, Ptr{Ptr{UInt8}}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), idec, last_y, u, v, width, height, stride, uv_stride) end function WebPIDecodedArea(idec, left, top, width, height) ccall((:WebPIDecodedArea, libwebp), Ptr{WebPDecBuffer}, (Ptr{WebPIDecoder}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), idec, left, top, width, height) end function WebPGetFeaturesInternal(arg1, arg2, arg3, arg4) ccall((:WebPGetFeaturesInternal, libwebp), VP8StatusCode, (Ptr{UInt8}, Csize_t, Ptr{WebPBitstreamFeatures}, Cint), arg1, arg2, arg3, arg4) end function WebPGetFeatures(data, data_size, features) ccall((:WebPGetFeatures, libwebp), VP8StatusCode, (Ptr{UInt8}, Csize_t, Ptr{WebPBitstreamFeatures}), data, data_size, features) end function WebPInitDecoderConfigInternal(arg1, arg2) ccall((:WebPInitDecoderConfigInternal, libwebp), Cint, (Ptr{WebPDecoderConfig}, Cint), arg1, arg2) end function WebPInitDecoderConfig(config) ccall((:WebPInitDecoderConfig, libwebp), Cint, (Ptr{WebPDecoderConfig},), config) end function WebPIDecode(data, data_size, config) ccall((:WebPIDecode, libwebp), Ptr{WebPIDecoder}, (Ptr{UInt8}, Csize_t, Ptr{WebPDecoderConfig}), data, data_size, config) end function WebPDecode(data, data_size, config) ccall((:WebPDecode, libwebp), VP8StatusCode, (Ptr{UInt8}, Csize_t, Ptr{WebPDecoderConfig}), data, data_size, config) end mutable struct WebPDemuxer end @cenum WebPMuxAnimDispose::UInt32 begin WEBP_MUX_DISPOSE_NONE = 0 WEBP_MUX_DISPOSE_BACKGROUND = 1 end struct WebPData bytes::Ptr{UInt8} size::Csize_t end @cenum WebPMuxAnimBlend::UInt32 begin WEBP_MUX_BLEND = 0 WEBP_MUX_NO_BLEND = 1 end struct WebPIterator frame_num::Cint num_frames::Cint x_offset::Cint y_offset::Cint width::Cint height::Cint duration::Cint dispose_method::WebPMuxAnimDispose complete::Cint fragment::WebPData has_alpha::Cint blend_method::WebPMuxAnimBlend pad::NTuple{2, UInt32} private_::Ptr{Cvoid} end struct WebPChunkIterator chunk_num::Cint num_chunks::Cint chunk::WebPData pad::NTuple{6, UInt32} private_::Ptr{Cvoid} end struct WebPAnimInfo canvas_width::UInt32 canvas_height::UInt32 loop_count::UInt32 bgcolor::UInt32 frame_count::UInt32 pad::NTuple{4, UInt32} end struct WebPAnimDecoderOptions color_mode::WEBP_CSP_MODE use_threads::Cint padding::NTuple{7, UInt32} end function WebPGetDemuxVersion() ccall((:WebPGetDemuxVersion, libwebp), Cint, ()) end @cenum WebPDemuxState::Int32 begin WEBP_DEMUX_PARSE_ERROR = -1 WEBP_DEMUX_PARSING_HEADER = 0 WEBP_DEMUX_PARSED_HEADER = 1 WEBP_DEMUX_DONE = 2 end function WebPDemuxInternal(arg1, arg2, arg3, arg4) ccall((:WebPDemuxInternal, libwebp), Ptr{WebPDemuxer}, (Ptr{WebPData}, Cint, Ptr{WebPDemuxState}, Cint), arg1, arg2, arg3, arg4) end function WebPDemux(data) ccall((:WebPDemux, libwebp), Ptr{WebPDemuxer}, (Ptr{WebPData},), data) end function WebPDemuxPartial(data, state) ccall((:WebPDemuxPartial, libwebp), Ptr{WebPDemuxer}, (Ptr{WebPData}, Ptr{WebPDemuxState}), data, state) end function WebPDemuxDelete(dmux) ccall((:WebPDemuxDelete, libwebp), Cvoid, (Ptr{WebPDemuxer},), dmux) end @cenum WebPFormatFeature::UInt32 begin WEBP_FF_FORMAT_FLAGS = 0 WEBP_FF_CANVAS_WIDTH = 1 WEBP_FF_CANVAS_HEIGHT = 2 WEBP_FF_LOOP_COUNT = 3 WEBP_FF_BACKGROUND_COLOR = 4 WEBP_FF_FRAME_COUNT = 5 end function WebPDemuxGetI(dmux, feature) ccall((:WebPDemuxGetI, libwebp), UInt32, (Ptr{WebPDemuxer}, WebPFormatFeature), dmux, feature) end function WebPDemuxGetFrame(dmux, frame_number, iter) ccall((:WebPDemuxGetFrame, libwebp), Cint, (Ptr{WebPDemuxer}, Cint, Ptr{WebPIterator}), dmux, frame_number, iter) end function WebPDemuxNextFrame(iter) ccall((:WebPDemuxNextFrame, libwebp), Cint, (Ptr{WebPIterator},), iter) end function WebPDemuxPrevFrame(iter) ccall((:WebPDemuxPrevFrame, libwebp), Cint, (Ptr{WebPIterator},), iter) end function WebPDemuxReleaseIterator(iter) ccall((:WebPDemuxReleaseIterator, libwebp), Cvoid, (Ptr{WebPIterator},), iter) end function WebPDemuxGetChunk(dmux, fourcc, chunk_number, iter) ccall((:WebPDemuxGetChunk, libwebp), Cint, (Ptr{WebPDemuxer}, Ptr{Cchar}, Cint, Ptr{WebPChunkIterator}), dmux, fourcc, chunk_number, iter) end function WebPDemuxNextChunk(iter) ccall((:WebPDemuxNextChunk, libwebp), Cint, (Ptr{WebPChunkIterator},), iter) end function WebPDemuxPrevChunk(iter) ccall((:WebPDemuxPrevChunk, libwebp), Cint, (Ptr{WebPChunkIterator},), iter) end function WebPDemuxReleaseChunkIterator(iter) ccall((:WebPDemuxReleaseChunkIterator, libwebp), Cvoid, (Ptr{WebPChunkIterator},), iter) end mutable struct WebPAnimDecoder end function WebPAnimDecoderOptionsInitInternal(arg1, arg2) ccall((:WebPAnimDecoderOptionsInitInternal, libwebp), Cint, (Ptr{WebPAnimDecoderOptions}, Cint), arg1, arg2) end function WebPAnimDecoderOptionsInit(dec_options) ccall((:WebPAnimDecoderOptionsInit, libwebp), Cint, (Ptr{WebPAnimDecoderOptions},), dec_options) end function WebPAnimDecoderNewInternal(arg1, arg2, arg3) ccall((:WebPAnimDecoderNewInternal, libwebp), Ptr{WebPAnimDecoder}, (Ptr{WebPData}, Ptr{WebPAnimDecoderOptions}, Cint), arg1, arg2, arg3) end function WebPAnimDecoderNew(webp_data, dec_options) ccall((:WebPAnimDecoderNew, libwebp), Ptr{WebPAnimDecoder}, (Ptr{WebPData}, Ptr{WebPAnimDecoderOptions}), webp_data, dec_options) end function WebPAnimDecoderGetInfo(dec, info) ccall((:WebPAnimDecoderGetInfo, libwebp), Cint, (Ptr{WebPAnimDecoder}, Ptr{WebPAnimInfo}), dec, info) end function WebPAnimDecoderGetNext(dec, buf, timestamp) ccall((:WebPAnimDecoderGetNext, libwebp), Cint, (Ptr{WebPAnimDecoder}, Ptr{Ptr{UInt8}}, Ptr{Cint}), dec, buf, timestamp) end function WebPAnimDecoderHasMoreFrames(dec) ccall((:WebPAnimDecoderHasMoreFrames, libwebp), Cint, (Ptr{WebPAnimDecoder},), dec) end function WebPAnimDecoderReset(dec) ccall((:WebPAnimDecoderReset, libwebp), Cvoid, (Ptr{WebPAnimDecoder},), dec) end function WebPAnimDecoderGetDemuxer(dec) ccall((:WebPAnimDecoderGetDemuxer, libwebp), Ptr{WebPDemuxer}, (Ptr{WebPAnimDecoder},), dec) end function WebPAnimDecoderDelete(dec) ccall((:WebPAnimDecoderDelete, libwebp), Cvoid, (Ptr{WebPAnimDecoder},), dec) end @cenum WebPImageHint::UInt32 begin WEBP_HINT_DEFAULT = 0 WEBP_HINT_PICTURE = 1 WEBP_HINT_PHOTO = 2 WEBP_HINT_GRAPH = 3 WEBP_HINT_LAST = 4 end struct WebPConfig lossless::Cint quality::Cfloat method::Cint image_hint::WebPImageHint target_size::Cint target_PSNR::Cfloat segments::Cint sns_strength::Cint filter_strength::Cint filter_sharpness::Cint filter_type::Cint autofilter::Cint alpha_compression::Cint alpha_filtering::Cint alpha_quality::Cint pass::Cint show_compressed::Cint preprocessing::Cint partitions::Cint partition_limit::Cint emulate_jpeg_size::Cint thread_level::Cint low_memory::Cint near_lossless::Cint exact::Cint use_delta_palette::Cint use_sharp_yuv::Cint qmin::Cint qmax::Cint end @cenum WebPEncCSP::UInt32 begin WEBP_YUV420 = 0 WEBP_YUV420A = 4 WEBP_CSP_UV_MASK = 3 WEBP_CSP_ALPHA_BIT = 4 end # typedef int ( * WebPWriterFunction ) ( const uint8_t * data , size_t data_size , const WebPPicture * picture ) const WebPWriterFunction = Ptr{Cvoid} struct WebPAuxStats coded_size::Cint PSNR::NTuple{5, Cfloat} block_count::NTuple{3, Cint} header_bytes::NTuple{2, Cint} residual_bytes::NTuple{3, NTuple{4, Cint}} segment_size::NTuple{4, Cint} segment_quant::NTuple{4, Cint} segment_level::NTuple{4, Cint} alpha_data_size::Cint layer_data_size::Cint lossless_features::UInt32 histogram_bits::Cint transform_bits::Cint cache_bits::Cint palette_size::Cint lossless_size::Cint lossless_hdr_size::Cint lossless_data_size::Cint pad::NTuple{2, UInt32} end @cenum WebPEncodingError::UInt32 begin VP8_ENC_OK = 0 VP8_ENC_ERROR_OUT_OF_MEMORY = 1 VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY = 2 VP8_ENC_ERROR_NULL_PARAMETER = 3 VP8_ENC_ERROR_INVALID_CONFIGURATION = 4 VP8_ENC_ERROR_BAD_DIMENSION = 5 VP8_ENC_ERROR_PARTITION0_OVERFLOW = 6 VP8_ENC_ERROR_PARTITION_OVERFLOW = 7 VP8_ENC_ERROR_BAD_WRITE = 8 VP8_ENC_ERROR_FILE_TOO_BIG = 9 VP8_ENC_ERROR_USER_ABORT = 10 VP8_ENC_ERROR_LAST = 11 end # typedef int ( * WebPProgressHook ) ( int percent , const WebPPicture * picture ) const WebPProgressHook = Ptr{Cvoid} struct WebPPicture use_argb::Cint colorspace::WebPEncCSP width::Cint height::Cint y::Ptr{UInt8} u::Ptr{UInt8} v::Ptr{UInt8} y_stride::Cint uv_stride::Cint a::Ptr{UInt8} a_stride::Cint pad1::NTuple{2, UInt32} argb::Ptr{UInt32} argb_stride::Cint pad2::NTuple{3, UInt32} writer::WebPWriterFunction custom_ptr::Ptr{Cvoid} extra_info_type::Cint extra_info::Ptr{UInt8} stats::Ptr{WebPAuxStats} error_code::WebPEncodingError progress_hook::WebPProgressHook user_data::Ptr{Cvoid} pad3::NTuple{3, UInt32} pad4::Ptr{UInt8} pad5::Ptr{UInt8} pad6::NTuple{8, UInt32} memory_::Ptr{Cvoid} memory_argb_::Ptr{Cvoid} pad7::NTuple{2, Ptr{Cvoid}} end struct WebPMemoryWriter mem::Ptr{UInt8} size::Csize_t max_size::Csize_t pad::NTuple{1, UInt32} end function WebPGetEncoderVersion() ccall((:WebPGetEncoderVersion, libwebp), Cint, ()) end function WebPEncodeRGB(rgb, width, height, stride, quality_factor, output) ccall((:WebPEncodeRGB, libwebp), Csize_t, (Ptr{UInt8}, Cint, Cint, Cint, Cfloat, Ptr{Ptr{UInt8}}), rgb, width, height, stride, quality_factor, output) end function WebPEncodeBGR(bgr, width, height, stride, quality_factor, output) ccall((:WebPEncodeBGR, libwebp), Csize_t, (Ptr{UInt8}, Cint, Cint, Cint, Cfloat, Ptr{Ptr{UInt8}}), bgr, width, height, stride, quality_factor, output) end function WebPEncodeRGBA(rgba, width, height, stride, quality_factor, output) ccall((:WebPEncodeRGBA, libwebp), Csize_t, (Ptr{UInt8}, Cint, Cint, Cint, Cfloat, Ptr{Ptr{UInt8}}), rgba, width, height, stride, quality_factor, output) end function WebPEncodeBGRA(bgra, width, height, stride, quality_factor, output) ccall((:WebPEncodeBGRA, libwebp), Csize_t, (Ptr{UInt8}, Cint, Cint, Cint, Cfloat, Ptr{Ptr{UInt8}}), bgra, width, height, stride, quality_factor, output) end function WebPEncodeLosslessRGB(rgb, width, height, stride, output) ccall((:WebPEncodeLosslessRGB, libwebp), Csize_t, (Ptr{UInt8}, Cint, Cint, Cint, Ptr{Ptr{UInt8}}), rgb, width, height, stride, output) end function WebPEncodeLosslessBGR(bgr, width, height, stride, output) ccall((:WebPEncodeLosslessBGR, libwebp), Csize_t, (Ptr{UInt8}, Cint, Cint, Cint, Ptr{Ptr{UInt8}}), bgr, width, height, stride, output) end function WebPEncodeLosslessRGBA(rgba, width, height, stride, output) ccall((:WebPEncodeLosslessRGBA, libwebp), Csize_t, (Ptr{UInt8}, Cint, Cint, Cint, Ptr{Ptr{UInt8}}), rgba, width, height, stride, output) end function WebPEncodeLosslessBGRA(bgra, width, height, stride, output) ccall((:WebPEncodeLosslessBGRA, libwebp), Csize_t, (Ptr{UInt8}, Cint, Cint, Cint, Ptr{Ptr{UInt8}}), bgra, width, height, stride, output) end @cenum WebPPreset::UInt32 begin WEBP_PRESET_DEFAULT = 0 WEBP_PRESET_PICTURE = 1 WEBP_PRESET_PHOTO = 2 WEBP_PRESET_DRAWING = 3 WEBP_PRESET_ICON = 4 WEBP_PRESET_TEXT = 5 end function WebPConfigInitInternal(arg1, arg2, arg3, arg4) ccall((:WebPConfigInitInternal, libwebp), Cint, (Ptr{WebPConfig}, WebPPreset, Cfloat, Cint), arg1, arg2, arg3, arg4) end function WebPConfigInit(config) ccall((:WebPConfigInit, libwebp), Cint, (Ptr{WebPConfig},), config) end function WebPConfigPreset(config, preset, quality) ccall((:WebPConfigPreset, libwebp), Cint, (Ptr{WebPConfig}, WebPPreset, Cfloat), config, preset, quality) end function WebPConfigLosslessPreset(config, level) ccall((:WebPConfigLosslessPreset, libwebp), Cint, (Ptr{WebPConfig}, Cint), config, level) end function WebPValidateConfig(config) ccall((:WebPValidateConfig, libwebp), Cint, (Ptr{WebPConfig},), config) end function WebPMemoryWriterInit(writer) ccall((:WebPMemoryWriterInit, libwebp), Cvoid, (Ptr{WebPMemoryWriter},), writer) end function WebPMemoryWriterClear(writer) ccall((:WebPMemoryWriterClear, libwebp), Cvoid, (Ptr{WebPMemoryWriter},), writer) end function WebPMemoryWrite(data, data_size, picture) ccall((:WebPMemoryWrite, libwebp), Cint, (Ptr{UInt8}, Csize_t, Ptr{WebPPicture}), data, data_size, picture) end function WebPPictureInitInternal(arg1, arg2) ccall((:WebPPictureInitInternal, libwebp), Cint, (Ptr{WebPPicture}, Cint), arg1, arg2) end function WebPPictureInit(picture) ccall((:WebPPictureInit, libwebp), Cint, (Ptr{WebPPicture},), picture) end function WebPPictureAlloc(picture) ccall((:WebPPictureAlloc, libwebp), Cint, (Ptr{WebPPicture},), picture) end function WebPPictureFree(picture) ccall((:WebPPictureFree, libwebp), Cvoid, (Ptr{WebPPicture},), picture) end function WebPPictureCopy(src, dst) ccall((:WebPPictureCopy, libwebp), Cint, (Ptr{WebPPicture}, Ptr{WebPPicture}), src, dst) end function WebPPlaneDistortion(src, src_stride, ref, ref_stride, width, height, x_step, type, distortion, result) ccall((:WebPPlaneDistortion, libwebp), Cint, (Ptr{UInt8}, Csize_t, Ptr{UInt8}, Csize_t, Cint, Cint, Csize_t, Cint, Ptr{Cfloat}, Ptr{Cfloat}), src, src_stride, ref, ref_stride, width, height, x_step, type, distortion, result) end function WebPPictureDistortion(src, ref, metric_type, result) ccall((:WebPPictureDistortion, libwebp), Cint, (Ptr{WebPPicture}, Ptr{WebPPicture}, Cint, Ptr{Cfloat}), src, ref, metric_type, result) end function WebPPictureCrop(picture, left, top, width, height) ccall((:WebPPictureCrop, libwebp), Cint, (Ptr{WebPPicture}, Cint, Cint, Cint, Cint), picture, left, top, width, height) end function WebPPictureView(src, left, top, width, height, dst) ccall((:WebPPictureView, libwebp), Cint, (Ptr{WebPPicture}, Cint, Cint, Cint, Cint, Ptr{WebPPicture}), src, left, top, width, height, dst) end function WebPPictureIsView(picture) ccall((:WebPPictureIsView, libwebp), Cint, (Ptr{WebPPicture},), picture) end function WebPPictureRescale(picture, width, height) ccall((:WebPPictureRescale, libwebp), Cint, (Ptr{WebPPicture}, Cint, Cint), picture, width, height) end function WebPPictureImportRGB(picture, rgb, rgb_stride) ccall((:WebPPictureImportRGB, libwebp), Cint, (Ptr{WebPPicture}, Ptr{UInt8}, Cint), picture, rgb, rgb_stride) end function WebPPictureImportRGBA(picture, rgba, rgba_stride) ccall((:WebPPictureImportRGBA, libwebp), Cint, (Ptr{WebPPicture}, Ptr{UInt8}, Cint), picture, rgba, rgba_stride) end function WebPPictureImportRGBX(picture, rgbx, rgbx_stride) ccall((:WebPPictureImportRGBX, libwebp), Cint, (Ptr{WebPPicture}, Ptr{UInt8}, Cint), picture, rgbx, rgbx_stride) end function WebPPictureImportBGR(picture, bgr, bgr_stride) ccall((:WebPPictureImportBGR, libwebp), Cint, (Ptr{WebPPicture}, Ptr{UInt8}, Cint), picture, bgr, bgr_stride) end function WebPPictureImportBGRA(picture, bgra, bgra_stride) ccall((:WebPPictureImportBGRA, libwebp), Cint, (Ptr{WebPPicture}, Ptr{UInt8}, Cint), picture, bgra, bgra_stride) end function WebPPictureImportBGRX(picture, bgrx, bgrx_stride) ccall((:WebPPictureImportBGRX, libwebp), Cint, (Ptr{WebPPicture}, Ptr{UInt8}, Cint), picture, bgrx, bgrx_stride) end function WebPPictureARGBToYUVA(picture, arg2) ccall((:WebPPictureARGBToYUVA, libwebp), Cint, (Ptr{WebPPicture}, WebPEncCSP), picture, arg2) end function WebPPictureARGBToYUVADithered(picture, colorspace, dithering) ccall((:WebPPictureARGBToYUVADithered, libwebp), Cint, (Ptr{WebPPicture}, WebPEncCSP, Cfloat), picture, colorspace, dithering) end function WebPPictureSharpARGBToYUVA(picture) ccall((:WebPPictureSharpARGBToYUVA, libwebp), Cint, (Ptr{WebPPicture},), picture) end function WebPPictureSmartARGBToYUVA(picture) ccall((:WebPPictureSmartARGBToYUVA, libwebp), Cint, (Ptr{WebPPicture},), picture) end function WebPPictureYUVAToARGB(picture) ccall((:WebPPictureYUVAToARGB, libwebp), Cint, (Ptr{WebPPicture},), picture) end function WebPCleanupTransparentArea(picture) ccall((:WebPCleanupTransparentArea, libwebp), Cvoid, (Ptr{WebPPicture},), picture) end function WebPPictureHasTransparency(picture) ccall((:WebPPictureHasTransparency, libwebp), Cint, (Ptr{WebPPicture},), picture) end function WebPBlendAlpha(picture, background_rgb) ccall((:WebPBlendAlpha, libwebp), Cvoid, (Ptr{WebPPicture}, UInt32), picture, background_rgb) end function WebPEncode(config, picture) ccall((:WebPEncode, libwebp), Cint, (Ptr{WebPConfig}, Ptr{WebPPicture}), config, picture) end mutable struct WebPMux end @cenum WebPChunkId::UInt32 begin WEBP_CHUNK_VP8X = 0 WEBP_CHUNK_ICCP = 1 WEBP_CHUNK_ANIM = 2 WEBP_CHUNK_ANMF = 3 WEBP_CHUNK_DEPRECATED = 4 WEBP_CHUNK_ALPHA = 5 WEBP_CHUNK_IMAGE = 6 WEBP_CHUNK_EXIF = 7 WEBP_CHUNK_XMP = 8 WEBP_CHUNK_UNKNOWN = 9 WEBP_CHUNK_NIL = 10 end struct WebPMuxFrameInfo bitstream::WebPData x_offset::Cint y_offset::Cint duration::Cint id::WebPChunkId dispose_method::WebPMuxAnimDispose blend_method::WebPMuxAnimBlend pad::NTuple{1, UInt32} end struct WebPMuxAnimParams bgcolor::UInt32 loop_count::Cint end struct WebPAnimEncoderOptions anim_params::WebPMuxAnimParams minimize_size::Cint kmin::Cint kmax::Cint allow_mixed::Cint verbose::Cint padding::NTuple{4, UInt32} end @cenum WebPMuxError::Int32 begin WEBP_MUX_OK = 1 WEBP_MUX_NOT_FOUND = 0 WEBP_MUX_INVALID_ARGUMENT = -1 WEBP_MUX_BAD_DATA = -2 WEBP_MUX_MEMORY_ERROR = -3 WEBP_MUX_NOT_ENOUGH_DATA = -4 end function WebPGetMuxVersion() ccall((:WebPGetMuxVersion, libwebp), Cint, ()) end function WebPNewInternal(arg1) ccall((:WebPNewInternal, libwebp), Ptr{WebPMux}, (Cint,), arg1) end function WebPMuxNew() ccall((:WebPMuxNew, libwebp), Ptr{WebPMux}, ()) end function WebPMuxDelete(mux) ccall((:WebPMuxDelete, libwebp), Cvoid, (Ptr{WebPMux},), mux) end function WebPMuxCreateInternal(arg1, arg2, arg3) ccall((:WebPMuxCreateInternal, libwebp), Ptr{WebPMux}, (Ptr{WebPData}, Cint, Cint), arg1, arg2, arg3) end function WebPMuxCreate(bitstream, copy_data) ccall((:WebPMuxCreate, libwebp), Ptr{WebPMux}, (Ptr{WebPData}, Cint), bitstream, copy_data) end function WebPMuxSetChunk(mux, fourcc, chunk_data, copy_data) ccall((:WebPMuxSetChunk, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{Cchar}, Ptr{WebPData}, Cint), mux, fourcc, chunk_data, copy_data) end function WebPMuxGetChunk(mux, fourcc, chunk_data) ccall((:WebPMuxGetChunk, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{Cchar}, Ptr{WebPData}), mux, fourcc, chunk_data) end function WebPMuxDeleteChunk(mux, fourcc) ccall((:WebPMuxDeleteChunk, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{Cchar}), mux, fourcc) end function WebPMuxSetImage(mux, bitstream, copy_data) ccall((:WebPMuxSetImage, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{WebPData}, Cint), mux, bitstream, copy_data) end function WebPMuxPushFrame(mux, frame, copy_data) ccall((:WebPMuxPushFrame, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{WebPMuxFrameInfo}, Cint), mux, frame, copy_data) end function WebPMuxGetFrame(mux, nth, frame) ccall((:WebPMuxGetFrame, libwebp), WebPMuxError, (Ptr{WebPMux}, UInt32, Ptr{WebPMuxFrameInfo}), mux, nth, frame) end function WebPMuxDeleteFrame(mux, nth) ccall((:WebPMuxDeleteFrame, libwebp), WebPMuxError, (Ptr{WebPMux}, UInt32), mux, nth) end function WebPMuxSetAnimationParams(mux, params) ccall((:WebPMuxSetAnimationParams, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{WebPMuxAnimParams}), mux, params) end function WebPMuxGetAnimationParams(mux, params) ccall((:WebPMuxGetAnimationParams, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{WebPMuxAnimParams}), mux, params) end function WebPMuxSetCanvasSize(mux, width, height) ccall((:WebPMuxSetCanvasSize, libwebp), WebPMuxError, (Ptr{WebPMux}, Cint, Cint), mux, width, height) end function WebPMuxGetCanvasSize(mux, width, height) ccall((:WebPMuxGetCanvasSize, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{Cint}, Ptr{Cint}), mux, width, height) end function WebPMuxGetFeatures(mux, flags) ccall((:WebPMuxGetFeatures, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{UInt32}), mux, flags) end function WebPMuxNumChunks(mux, id, num_elements) ccall((:WebPMuxNumChunks, libwebp), WebPMuxError, (Ptr{WebPMux}, WebPChunkId, Ptr{Cint}), mux, id, num_elements) end function WebPMuxAssemble(mux, assembled_data) ccall((:WebPMuxAssemble, libwebp), WebPMuxError, (Ptr{WebPMux}, Ptr{WebPData}), mux, assembled_data) end mutable struct WebPAnimEncoder end function WebPAnimEncoderOptionsInitInternal(arg1, arg2) ccall((:WebPAnimEncoderOptionsInitInternal, libwebp), Cint, (Ptr{WebPAnimEncoderOptions}, Cint), arg1, arg2) end function WebPAnimEncoderOptionsInit(enc_options) ccall((:WebPAnimEncoderOptionsInit, libwebp), Cint, (Ptr{WebPAnimEncoderOptions},), enc_options) end function WebPAnimEncoderNewInternal(arg1, arg2, arg3, arg4) ccall((:WebPAnimEncoderNewInternal, libwebp), Ptr{WebPAnimEncoder}, (Cint, Cint, Ptr{WebPAnimEncoderOptions}, Cint), arg1, arg2, arg3, arg4) end function WebPAnimEncoderNew(width, height, enc_options) ccall((:WebPAnimEncoderNew, libwebp), Ptr{WebPAnimEncoder}, (Cint, Cint, Ptr{WebPAnimEncoderOptions}), width, height, enc_options) end function WebPAnimEncoderAdd(enc, frame, timestamp_ms, config) ccall((:WebPAnimEncoderAdd, libwebp), Cint, (Ptr{WebPAnimEncoder}, Ptr{WebPPicture}, Cint, Ptr{WebPConfig}), enc, frame, timestamp_ms, config) end function WebPAnimEncoderAssemble(enc, webp_data) ccall((:WebPAnimEncoderAssemble, libwebp), Cint, (Ptr{WebPAnimEncoder}, Ptr{WebPData}), enc, webp_data) end function WebPAnimEncoderGetError(enc) ccall((:WebPAnimEncoderGetError, libwebp), Ptr{Cchar}, (Ptr{WebPAnimEncoder},), enc) end function WebPAnimEncoderDelete(enc) ccall((:WebPAnimEncoderDelete, libwebp), Cvoid, (Ptr{WebPAnimEncoder},), enc) end @cenum WebPFeatureFlags::UInt32 begin ANIMATION_FLAG = 2 XMP_FLAG = 4 EXIF_FLAG = 8 ALPHA_FLAG = 16 ICCP_FLAG = 32 ALL_VALID_FLAGS = 62 end function WebPDataInit(webp_data) ccall((:WebPDataInit, libwebp), Cvoid, (Ptr{WebPData},), webp_data) end function WebPDataClear(webp_data) ccall((:WebPDataClear, libwebp), Cvoid, (Ptr{WebPData},), webp_data) end function WebPDataCopy(src, dst) ccall((:WebPDataCopy, libwebp), Cint, (Ptr{WebPData}, Ptr{WebPData}), src, dst) end function WebPMalloc(size) ccall((:WebPMalloc, libwebp), Ptr{Cvoid}, (Csize_t,), size) end function WebPFree(ptr) ccall((:WebPFree, libwebp), Cvoid, (Ptr{Cvoid},), ptr) end const WEBP_DECODER_ABI_VERSION = 0x0209 const WEBP_DEMUX_ABI_VERSION = 0x0107 const WEBP_ENCODER_ABI_VERSION = 0x020f const WEBP_MAX_DIMENSION = 16383 const WEBP_MUX_ABI_VERSION = 0x0108 # Skipping MacroDefinition: WEBP_INLINE inline # Skipping MacroDefinition: WEBP_EXTERN extern __attribute__ ( ( visibility ( "default" ) ) ) # exports const PREFIXES = ["WebP"] for name in names(@__MODULE__; all=true), prefix in PREFIXES if startswith(string(name), prefix) @eval export $name end end end # module
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
2404
function decode( ::Type{TColor}, data::AbstractVector{UInt8}; transpose = false )::Matrix{TColor} where {TColor <: Colorant} TDecodedColor = TColor if TColor == ARGB{N0f8} webp_decode_fn = Wrapper.WebPDecodeARGB elseif TColor == BGR{N0f8} webp_decode_fn = Wrapper.WebPDecodeBGR elseif TColor == BGRA{N0f8} webp_decode_fn = Wrapper.WebPDecodeBGRA elseif TColor == RGB{N0f8} webp_decode_fn = Wrapper.WebPDecodeRGB elseif TColor == RGBA{N0f8} webp_decode_fn = Wrapper.WebPDecodeRGBA elseif TColor == Gray{N0f8} webp_decode_fn = Wrapper.WebPDecodeRGB TDecodedColor = RGB{N0f8} else throw(ArgumentError("Unsupported color type: $TColor")) end width = Ref{Int32}(-1) height = Ref{Int32}(-1) decoded_data_ptr = webp_decode_fn(pointer(data), length(data), width, height) decoded_data_size = (sizeof(TDecodedColor), Int(width[]), Int(height[])) decoded_data = unsafe_wrap(Array{UInt8, 3}, decoded_data_ptr, decoded_data_size) image_view = colorview(TDecodedColor, normedview(decoded_data)) if TDecodedColor == TColor image = transpose ? collect(image_view) : permutedims(image_view, (2, 1)) else image = if transpose TColor.(image_view) else TColor.(PermutedDimsArray(image_view, (2, 1))) end end Wrapper.WebPFree(decoded_data_ptr) return image end function decode( data::AbstractVector{UInt8}; kwargs... )::Union{Matrix{RGB{N0f8}}, Matrix{RGBA{N0f8}}} bitstream_features = Ref{Wrapper.WebPBitstreamFeatures}() # WebPGetFeatures is not available in libwebp dynamic library, but WebPGetFeaturesInternal is equivalent: https://github.com/webmproject/libwebp/blob/v1.4.0/src/webp/decode.h#L441 Wrapper.WebPGetFeaturesInternal( pointer(data), length(data), bitstream_features, Wrapper.WEBP_DECODER_ABI_VERSION ) has_alpha = bitstream_features[].has_alpha != 0 TColor = has_alpha ? RGBA{N0f8} : RGB{N0f8} return decode(TColor, data; kwargs...) end function read_webp( ::Type{CT}, f::Union{AbstractString, IO}; kwargs... )::Matrix{CT} where {CT <: Colorant} return decode(CT, Base.read(f); kwargs...) end function read_webp( f::Union{AbstractString, IO}; kwargs... )::Union{Matrix{RGB{N0f8}}, Matrix{RGBA{N0f8}}} return decode(Base.read(f); kwargs...) end
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
1854
function encode( image::AbstractMatrix{TColor}; lossy = false, quality::Real = 75, transpose = false )::Vector{UInt8} where {TColor <: Colorant} if lossy && !(0 ≀ quality ≀ 100) throw(ArgumentError("Quality $quality is not in the range from 0 to 100.")) end if TColor == BGR{N0f8} webp_encode_fn = lossy ? Wrapper.WebPEncodeBGR : Wrapper.WebPEncodeLosslessBGR elseif TColor == BGRA{N0f8} webp_encode_fn = lossy ? Wrapper.WebPEncodeBGRA : Wrapper.WebPEncodeLosslessBGRA elseif TColor == RGB{N0f8} webp_encode_fn = lossy ? Wrapper.WebPEncodeRGB : Wrapper.WebPEncodeLosslessRGB elseif TColor == RGBA{N0f8} webp_encode_fn = lossy ? Wrapper.WebPEncodeRGBA : Wrapper.WebPEncodeLosslessRGBA else throw(ArgumentError("Unsupported color type: $TColor")) end if !transpose # TODO the kwarg transpose is quite confusing/misleading image = permutedims(image, (2, 1)) end width, height = size(image) stride = width * sizeof(TColor) output_ptr = Ref{Ptr{UInt8}}() if lossy quality_factor = Float32(quality) output_length = webp_encode_fn( pointer(image), width, height, stride, quality_factor, output_ptr ) else output_length = webp_encode_fn(pointer(image), width, height, stride, output_ptr) end output_view = unsafe_wrap(Vector{UInt8}, output_ptr[], output_length) output = collect(output_view) Wrapper.WebPFree(output_ptr[]) return output end function write_webp(file_path::AbstractString, image::AbstractMatrix{<:Colorant}; kwargs...) open(file_path, "w") do io write_webp(io, image; kwargs...) end return nothing end function write_webp(io::IO, image::AbstractMatrix{<:Colorant}; kwargs...) write(io, encode(image; kwargs...)) return nothing end
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
449
fileio_load(f::File{format"WebP"}; kwargs...) = read_webp(f.filename; kwargs...) fileio_load(s::Stream{format"WebP"}; kwargs...) = read_webp(s.io; kwargs...) function fileio_save(f::File{format"WebP"}, image::AbstractMatrix{<:Colorant}; kwargs...) return write_webp(f.filename, image; kwargs...) end function fileio_save(s::Stream{format"WebP"}, image::AbstractMatrix{<:Colorant}; kwargs...) return write_webp(s.io, image; kwargs...) end
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
2217
using ColorTypes using FixedPointNumbers using Downloads using Test using WebP @testset "Decoding" begin webp_galleries = ( lossy = ( url = "https://www.gstatic.com/webp/gallery", data = Dict( "1.webp" => (368, 550), "2.webp" => (404, 550), "3.webp" => (720, 1280), "4.webp" => (772, 1024), "5.webp" => (752, 1024), ), ), lossless = ( url = "https://www.gstatic.com/webp/gallery3", data = Dict( "1_webp_ll.webp" => (301, 400), "2_webp_ll.webp" => (395, 386), "3_webp_ll.webp" => (600, 800), "4_webp_ll.webp" => (163, 421), "5_webp_ll.webp" => (300, 300), ), ), ) for gallery in webp_galleries for (filename, image_size) in gallery.data mktempdir() do tmp_dir_path file_path = joinpath(tmp_dir_path, filename) Downloads.download(joinpath(gallery.url, filename), file_path) for kwargs in (NamedTuple(), (transpose = true,), (transpose = false,)) if hasproperty(kwargs, :transpose) && kwargs.transpose expected_image_size = reverse(image_size) else expected_image_size = image_size end @testset "WebP.read_webp($(joinpath(gallery.url, filename)); $kwargs)" begin image = WebP.read_webp(file_path; kwargs...) @test size(image) == expected_image_size end for TColor in [ ARGB{N0f8}, BGR{N0f8}, BGRA{N0f8}, RGB{N0f8}, RGBA{N0f8}, Gray{N0f8} ] @testset "WebP.read_webp($TColor, $(joinpath(gallery.url, filename)); $kwargs)" begin image = WebP.read_webp(TColor, file_path; kwargs...) @test size(image) == expected_image_size end end end end end end end
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
1898
using Test using TestImages using WebP @testset "Encoding" begin kwargs_combos = (NamedTuple(), (transpose = true,), (transpose = false,)) image_rgb = testimage("lighthouse") for TColor in [RGB, BGR, RGBA, BGRA] image = TColor.(image_rgb) for kwargs in kwargs_combos if hasproperty(kwargs, :transpose) && kwargs.transpose input_image = permutedims(image, (2, 1)) else input_image = image end @testset "Lossless" begin @testset "WebP.encode(::Matrix{$TColor}; $kwargs)" begin data = WebP.encode(input_image; kwargs...) output = WebP.decode(data) @test size(output) == size(image) end end @testset "Lossy" begin @testset "encode throws ArgumentError for quality outside range" begin @test_throws ArgumentError WebP.encode( input_image; lossy = true, quality = -1 ) @test_throws ArgumentError WebP.encode( input_image; lossy = true, quality = 101 ) end qualities = [1, 10, 50, 100] quality_types = [Int, Float32, Float64] for quality in qualities, TQuality in quality_types input_kwargs = merge( kwargs, (lossy = true, quality = TQuality(quality)) ) @testset "WebP.encode(::Matrix{$TColor}; $input_kwargs)" begin data = WebP.encode(input_image; input_kwargs...) output = WebP.decode(data) @test size(output) == size(image) end end end end end end
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
1564
using FileIO using Test using TestImages using WebP @testset "FileIO interface" begin expected_image = testimage("lighthouse") mktempdir() do tmp_dir_path file_path = joinpath(tmp_dir_path, "lighthouse.webp") @testset "File{format\"WebP\"}" begin f = File{format"WebP"}(file_path) @testset "fileio_load" begin WebP.write_webp(file_path, expected_image) image = WebP.fileio_load(f) @test size(image) == size(expected_image) end @testset "fileio_save" begin WebP.fileio_save(f, expected_image) image = WebP.read_webp(file_path) @test size(image) == size(expected_image) end end @testset "Stream{format\"WebP\"}" begin s = Stream{format"WebP"}(IOBuffer()) @testset "fileio_load" begin WebP.write_webp(file_path, expected_image) open(file_path, "r") do io s = Stream{format"WebP"}(io) image = WebP.fileio_load(s) @test size(image) == size(expected_image) end end @testset "fileio_save" begin open(file_path, "w") do io s = Stream{format"WebP"}(io) WebP.fileio_save(s, expected_image) end image = WebP.read_webp(file_path) @test size(image) == size(expected_image) end end end end
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
code
208
using Test @testset "WebP.jl" begin include(joinpath(@__DIR__, "decoding_tests.jl")) include(joinpath(@__DIR__, "encoding_tests.jl")) include(joinpath(@__DIR__, "fileio_interface_tests.jl")) end
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
f1f6d497ff84039deeb37f264396dac0c2250497
docs
1499
# WebP [![Build Status](https://github.com/stemann/WebP.jl/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/stemann/WebP.jl/actions/workflows/CI.yml?query=branch%3Amaster) [![Coverage](https://codecov.io/gh/stemann/WebP.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/stemann/WebP.jl) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) WebP.jl is a Julia library for handling [WebP](https://developers.google.com/speed/webp) images. WebP provides both lossy and lossless compression of images, and may offer smaller file sizes compared to JPEG and PNG. The core functionality of this package is supported by the [libwebp](https://developers.google.com/speed/webp/docs/api) C library. ## Usage This package provides functions for reading and writing WebP image files, * `WebP.read_webp` * `WebP.write_webp` as well as functions for decoding and encoding WebP image data, * `WebP.decode` * `WebP.encode` ### Reading and writing An image may be written, ```julia using TestImages using WebP image = testimage("lighthouse") WebP.write_webp("lighthouse.webp", image) ``` and subsequently read, ```julia image = WebP.read_webp("lighthouse.webp") ``` ### Decoding and encoding An image may be encoded, ```julia using TestImages using WebP image = testimage("lighthouse") data = WebP.encode(image) # data is a Vector{UInt8} ``` and subsequently decoded, ```julia image = WebP.decode(data) ```
WebP
https://github.com/stemann/WebP.jl.git
[ "MIT" ]
0.1.2
45f2d31d22d8bf962eaab74cf800127b4d307c61
code
248
using Documenter using FrankenTuples makedocs(modules=[FrankenTuples], sitename="FrankenTuples.jl", authors="Alex Arslan", pages=["index.md"]) deploydocs(repo="github.com/ararslan/FrankenTuples.jl.git", target="build")
FrankenTuples
https://github.com/ararslan/FrankenTuples.jl.git
[ "MIT" ]
0.1.2
45f2d31d22d8bf962eaab74cf800127b4d307c61
code
12976
module FrankenTuples export FrankenTuple, ftuple, @ftuple, ftcall """ FrankenTuple{T<:Tuple, names, NT<:Tuple} A `FrankenTuple` contains a `Tuple` of type `T` and a `NamedTuple` with names `names` and types `NT`. It acts like a cross between the two, like a partially-named tuple. The named portion of a `FrankenTuple` can be accessed using `NamedTuple`, and the unnamed portion can be accessed with `Tuple`. # Examples ```jldoctest julia> ft = FrankenTuple((1, 2), (a=1, b=2)) FrankenTuple((1, 2), (a = 1, b = 2)) julia> Tuple(ft) (1, 2) julia> NamedTuple(ft) (a = 1, b = 2) ``` """ struct FrankenTuple{T<:Tuple,names,NT<:Tuple} t::T nt::NamedTuple{names,NT} FrankenTuple{T,names,NT}(t, nt) where {T<:Tuple,names,NT<:Tuple} = new{T,names,NT}(t, nt) FrankenTuple{T}(t::Tuple) where {T<:Tuple} = new{T,(),Tuple{}}(t, NamedTuple()) FrankenTuple{T,names,NT}(nt::NamedTuple) where {T<:Tuple,names,NT<:Tuple} = new{T,names,NT}((), nt) FrankenTuple{T,names,NT}(ft::FrankenTuple) where {T<:Tuple,names,NT<:Tuple} = new{T,names,NT}(convert(T, getfield(ft, :t)), convert(NamedTuple{names,NT}, getfield(ft, :nt))) end FrankenTuple(t::T, nt::NamedTuple{names,NT}) where {T<:Tuple,names,NT<:Tuple} = FrankenTuple{T,names,NT}(t, nt) FrankenTuple() = FrankenTuple{Tuple{},(),Tuple{}}((), NamedTuple()) FrankenTuple(t::Tuple) = FrankenTuple(t, NamedTuple()) FrankenTuple(nt::NamedTuple) = FrankenTuple((), nt) FrankenTuple(ft::FrankenTuple) = ft """ Tuple(ft::FrankenTuple) Access the `Tuple` part of a `FrankenTuple`, i.e. the "plain," unnamed portion. """ Base.Tuple(ft::FrankenTuple) = getfield(ft, :t) """ NamedTuple(ft::FrankenTuple) Access the `NamedTuple` part of a `FrankenTuple`, i.e. the named portion. """ Base.NamedTuple(ft::FrankenTuple) = getfield(ft, :nt) function Base.show(io::IO, ft::FrankenTuple) print(io, "FrankenTuple(") show(io, Tuple(ft)) print(io, ", ") show(io, NamedTuple(ft)) print(io, ')') nothing end Base.show(io::IO, ft::FrankenTuple{Tuple{},(),Tuple{}}) = print(io, "FrankenTuple()") Base.convert(::Type{FrankenTuple{T,names,NT}}, t::Tuple) where {T<:Tuple,names,NT<:Tuple} = FrankenTuple{T,names,NT}(convert(T, t), NamedTuple()) Base.convert(::Type{FrankenTuple{T,names,NT}}, nt::NamedTuple) where {T<:Tuple,names,NT<:Tuple} = FrankenTuple{T,names,NT}((), convert(NamedTuple{names,NT}, nt)) """ isempty(ft::FrankenTuple) Determine whether the given `FrankenTuple` is empty, i.e. has at least 1 element. """ Base.isempty(ft::FrankenTuple) = false Base.isempty(ft::FrankenTuple{Tuple{},(),Tuple{}}) = true """ length(ft::FrankenTuple) Compute the number of elements in `ft`. """ Base.length(ft::FrankenTuple) = length(Tuple(ft)) + length(NamedTuple(ft)) Base.length(ft::FrankenTuple{Tuple{},(),Tuple{}}) = 0 Base.length(ft::FrankenTuple{<:Tuple,(),Tuple{}}) = length(Tuple(ft)) Base.length(ft::FrankenTuple{Tuple{},names}) where {names} = length(names) """ getindex(ft::FrankenTuple, i) Retrieve the value of `ft` at the given index `i`. When `i::Integer`, this gets the value at index `i` in iteration order. When `i::Symbol`, this gets the value from the named section with name `i`. (`getproperty` can also be used for the `Symbol` case.) # Examples ```jldoctest julia> ftuple(1, 2; a=3, b=4)[3] 3 julia> ftuple(1, 2; a=3, b=4)[:a] 3 ``` """ function Base.getindex(ft::FrankenTuple, i::Integer) t = Tuple(ft) n = length(t) if i <= n getfield(t, i) else getfield(NamedTuple(ft), i - n) end end Base.getindex(ft::FrankenTuple, x::Symbol) = getfield(NamedTuple(ft), x) Base.getproperty(ft::FrankenTuple, x::Symbol) = getfield(NamedTuple(ft), x) """ firstindex(ft::FrankenTuple) Retrieve the first index of `ft`, which is always 1. """ Base.firstindex(ft::FrankenTuple) = 1 """ lastindex(ft::FrankenTuple) Retrieve the last index of `ft`, which is equivalent to its `length`. """ Base.lastindex(ft::FrankenTuple) = length(ft) """ first(ft::FrankenTuple) Get the first value in `ft` in iteration order. `ft` must be non-empty. """ Base.first(ft::FrankenTuple) = @inbounds ft[1] Base.first(ft::FrankenTuple{Tuple{},(),Tuple{}}) = throw(ArgumentError("FrankenTuple must be non-empty")) """ Base.tail(ft::FrankenTuple) Return the tail portion of `ft`: a new `FrankenTuple` with the first element of `ft` removed. `ft` must be non-empty. # Examples ```jldoctest julia> Base.tail(ftuple(a=4, b=5)) FrankenTuple((), (b = 5,)) ``` """ Base.tail(ft::FrankenTuple) = _tail(Tuple(ft), NamedTuple(ft)) # TODO: Should be able to get rid of the helper after VERSION >= v"1.1.0-DEV.553" _tail(t::Tuple{}, nt::NamedTuple{(),Tuple{}}) = throw(ArgumentError("FrankenTuple must be non-empty")) _tail(t::Tuple{}, nt::NamedTuple{names,<:Tuple}) where {names} = FrankenTuple(t, NamedTuple{Base.tail(names)}(nt)) _tail(t::Tuple, nt::NamedTuple) = FrankenTuple(Base.tail(t), nt) """ iterate(ft::FrankenTuple[, state]) Iterate over `ft`. This yields the values of the unnamed section first, then the values of the named section. # Examples ```jldoctest julia> ft = @ftuple (1, a=3, 2, b=4) FrankenTuple((1, 2), (a = 3, b = 4)) julia> collect(ft) 4-element Array{Int64,1}: 1 2 3 4 ``` """ Base.iterate(ft::FrankenTuple, state...) = iterate(Iterators.flatten((Tuple(ft), NamedTuple(ft))), state...) """ keys(ft::FrankenTuple) Get the keys of the given `FrankenTuple`, i.e. the set of valid indices into `ft`. The unnamed section of `ft` has 1-based integer keys and the named section is keyed by name, given as `Symbol`s. # Examples ```jldoctest julia> keys(ftuple(1, 2; a=3, b=4)) (1, 2, :a, :b) ``` """ Base.keys(ft::FrankenTuple) = (keys(Tuple(ft))..., keys(NamedTuple(ft))...) Base.keys(ft::FrankenTuple{Tuple{},(),Tuple{}}) = () Base.keys(ft::FrankenTuple{Tuple{},N,<:Tuple}) where {N} = N Base.keys(ft::FrankenTuple{<:Tuple,(),Tuple{}}) = keys(Tuple(ft)) """ values(ft::FrankenTuple) Get the values of the given `FrankenTuple` in iteration order. The values for the unnamed section appear before that of the named section. # Examples ```jldoctest julia> values(ftuple(1, 2; a=3, b=4)) (1, 2, 3, 4) ``` """ Base.values(ft::FrankenTuple) = (Tuple(ft)..., NamedTuple(ft)...) Base.values(ft::FrankenTuple{Tuple{},(),Tuple{}}) = () Base.values(ft::FrankenTuple{Tuple{},names,<:Tuple}) where {names} = values(NamedTuple(ft)) Base.values(ft::FrankenTuple{<:Tuple,(),Tuple{}}) = Tuple(ft) """ pairs(ft::FrankenTuple) Construct a `Pairs` iterator that associates the `keys` of `ft` with its `values`. # Examples ```jldoctest julia> collect(pairs(ftuple(1, 2; a=3, b=4))) 4-element Array{Pair{Any,Int64},1}: 1 => 1 2 => 2 :a => 3 :b => 4 ``` """ Base.pairs(ft::FrankenTuple) = Iterators.Pairs(ft, keys(ft)) """ eltype(ft::FrankenTuple) Determine the element type of `ft`. This is the immediate supertype of the elements in `ft` if they are not homogeneously typed. # Examples ```jldoctest julia> eltype(ftuple(1, 2; a=3, b=4)) Int64 julia> eltype(ftuple(0x0, 1)) Integer julia> eltype(ftuple(a=2.0, b=0x1)) Real julia> eltype(ftuple()) Union{} ``` """ Base.eltype(::Type{FrankenTuple{T,names,V}}) where {T<:Tuple,names,V<:Tuple} = Base.promote_typejoin(eltype(T), eltype(V)) """ empty(ft::FrankenTuple) Construct an empty `FrankenTuple`. """ Base.empty(@nospecialize ft::FrankenTuple) = FrankenTuple() if VERSION >= v"1.8.0-DEV.1254" # https://github.com/JuliaLang/julia/pull/43695 _default_world() = Base.get_world_counter() else _default_world() = typemax(UInt) end if VERSION < v"1.2.0-DEV.217" function Base.hasmethod(@nospecialize(f), ::Type{FrankenTuple{T,names,NT}}; world=_default_world()) where {T,names,NT} hasmethod(f, T; world=world) || return false m = which(f, T) kws = Base.kwarg_decl(m, Core.kwftype(typeof(f))) for kw in kws endswith(String(kw), "...") && return true end issubset(names, kws) end else function Base.hasmethod(@nospecialize(f), ::Type{FrankenTuple{T,names,NT}}; world=_default_world()) where {T,names,NT} hasmethod(f, T, names; world=world) end end function Base.hasmethod(@nospecialize(f), ::Type{FrankenTuple{T,(),Tuple{}}}; world=_default_world()) where {T} hasmethod(f, T; world=world) end function Base.hasmethod(@nospecialize(f), ::Type{FrankenTuple{T,names}}; world=_default_world()) where {T,names} NT = Tuple{Iterators.repeated(Any, length(names))...} hasmethod(f, FrankenTuple{T,names,NT}; world=world) end """ hasmethod(f, ft::Type{<:FrankenTuple}) Determine whether the function `f` has a method with positional argument types matching those in the unnamed portion of `ft` and with keyword arguments named in accordance with those in the named portion of `ft`. Note that the types in the named portion of `ft` do not factor into determining the existence of a matching method because keyword arguments to not participate in dispatch. Similarly, calling `hasmethod` with a `FrankenTuple` with an empty named portion will still return `true` if the positional arguments match, even if `f` only has methods that accept keyword arguments. This ensures agreement with the behavior of `hasmethod` on `Tuple`s. More generally, the names in the `FrankenTuple` must be a subset of the keyword argument names in the matching method, _except_ when the method accepts a variable number of keyword arguments (e.g. `kwargs...`). In that case, the names in the method must be a subset of the `FrankenTuple`'s names. # Examples ```jldoctest julia> f(x::Int; y=3, z=4) = x + y + z; julia> hasmethod(f, FrankenTuple{Tuple{Int},(:y,)}) true julia> hasmethod(f, FrankenTuple{Tuple{Int},(:a,)}) # no keyword `a` false julia> g(; a, b, kwargs...) = +(a, b, kwargs...); julia> hasmethod(g, FrankenTuple{Tuple{},(:a,:b,:c,:d)}) # g accepts arbitrarily many kwargs true ``` """ Base.hasmethod(::Any, ::Type{<:FrankenTuple}) """ ftuple(args...; kwargs...) Construct a [`FrankenTuple`](@ref) from the given positional and keyword arguments. # Examples ```jldoctest julia> ftuple(1, 2) FrankenTuple((1, 2), NamedTuple()) julia> ftuple(1, 2, a=3, b=4) FrankenTuple((1, 2), (a = 3, b = 4)) ``` """ function ftuple(args...; kwargs...) @static if VERSION < v"1.7.0-DEV.1017" nt = kwargs.data else # NOTE: We don't use this unconditionally because the `NamedTuple` constructor # method that accepts arbitrary key-value iterators requires 1.6.0-DEV.877 nt = NamedTuple(kwargs) end FrankenTuple(args, nt) end """ @ftuple (x...; y...) @ftuple (a, x=t, b, y=u) Construct a [`FrankenTuple`](@ref) from the given tuple expression, which can contain both positional and named elements. The tuple can be "sectioned" in the same manner as a function signature, with positional elements separated from the named elements by a semicolon, or positional and named elements can be intermixed, occurring in any order. # Examples ```jldoctest julia> @ftuple (1, 2; a=3, b=4) FrankenTuple((1, 2), (a = 3, b = 4)) julia> @ftuple (1, a=3, 2, b=4) FrankenTuple((1, 2), (a = 3, b = 4)) ``` """ macro ftuple(ex::Expr) ex.head === :tuple || throw(ArgumentError("@ftuple: expected tuple expression")) # () if isempty(ex.args) t = Expr(:tuple) nt = Expr(:call, :NamedTuple) # (a, b; x=t, y=u) elseif ex.args[1] isa Expr && ex.args[1].head === :parameters t = Expr(:tuple) length(ex.args) > 1 && append!(t.args, ex.args[2:end]) nt = Expr(:tuple) for kw in ex.args[1].args @assert kw isa Expr && kw.head === :kw push!(nt.args, Expr(:(=), esc(kw.args[1]), kw.args[2])) end # (a, x=t, b, y=u) else t = Expr(:tuple) nt = Expr(:tuple) for arg in ex.args if arg isa Expr && arg.head === :(=) push!(nt.args, esc(arg)) else push!(t.args, arg) end end if nt == Expr(:tuple) # No named elements found nt = Expr(:call, :NamedTuple) end end :(FrankenTuple($t, $nt)) end # XXX: I'm not convinced that I like this or think it's useful in any way, but it's cute """ ftcall(f::Function, ft::FrankenTuple) Call the function `f` using the unnamed portion of `ft` as its positional arguments and the named portion of `ft` as its keyword arguments. # Examples ```jldoctest julia> ftcall(mapreduce, ftuple(abs2, -, 1:4; init=0)) -30 ``` """ ftcall(f, ft::FrankenTuple) = f(Tuple(ft)...; NamedTuple(ft)...) ftcall(f, ft::FrankenTuple{Tuple{},(),Tuple{}}) = f() end # module
FrankenTuples
https://github.com/ararslan/FrankenTuples.jl.git
[ "MIT" ]
0.1.2
45f2d31d22d8bf962eaab74cf800127b4d307c61
code
3404
using FrankenTuples using Test @testset "It's alive!" begin x = ftuple(1, 2, a=3, b=4) @test x == FrankenTuple((1, 2), (a=3, b=4)) @test x == FrankenTuple(x) @test !isempty(x) @test length(x) == 4 @test Tuple(x) == (1, 2) @test NamedTuple(x) == (a=3, b=4) @test sprint(show, x) == "FrankenTuple((1, 2), (a = 3, b = 4))" @test x == @ftuple (1, 2; a=3, b=4) @test x == @ftuple (1, a=3, b=4, 2) @test keys(x) == (1, 2, :a, :b) @test values(x) == (1, 2, 3, 4) @test eltype(x) == Int @test first(x) == 1 @test Base.tail(x) == ftuple(2, a=3, b=4) y = FrankenTuple{Tuple{Float64,Float64},(:a,:b),Tuple{Float64,Float64}}(x) @test y == ftuple(1.0, 2.0, a=3.0, b=4.0) t = ftuple(1, 2) @test t == FrankenTuple((1, 2)) @test length(t) == 2 @test Tuple(t) == (1, 2) @test NamedTuple(t) == NamedTuple() @test t == convert(FrankenTuple{Tuple{Int,Int},(),Tuple{}}, (1, 2)) @test sprint(show, t) == "FrankenTuple((1, 2), NamedTuple())" @test t == @ftuple (1, 2) @test keys(t) == keys(Tuple(t)) @test values(t) == (1, 2) @test first(t) == 1 @test Base.tail(t) == ftuple(2) nt = ftuple(a=3, b=4) @test nt == FrankenTuple((a=3, b=4)) @test length(nt) == 2 @test Tuple(nt) == () @test NamedTuple(nt) == (a=3, b=4) @test nt == convert(FrankenTuple{Tuple{},(:a,:b),Tuple{Int,Int}}, (a=3, b=4)) @test sprint(show, nt) == "FrankenTuple((), (a = 3, b = 4))" @test nt == @ftuple (a=3, b=4) @test keys(nt) == (:a, :b) @test values(nt) == (3, 4) @test first(nt) == 3 @test Base.tail(nt) == ftuple(b=4) e = empty(x) @test e == FrankenTuple() @test isempty(e) @test length(e) == 0 @test sprint(show, e) == "FrankenTuple()" @test e == @ftuple () @test keys(e) == values(e) == () @test_throws ArgumentError first(e) @test_throws ArgumentError Base.tail(e) @test eltype(ftuple(1, 2.0, a=3, b=4.0f0)) == Real end @testset "Indexing and iteration" begin x = ftuple(1, 2, a=3, b=4) @test x.a == x[:a] == 3 @test x.b == x[:b] == 4 for i = 1:4 @test x[i] == i end for (i, t) in enumerate(x) @test t == i end @test collect(pairs(x)) == [1 => 1, 2 => 2, :a => 3, :b => 4] @test firstindex(x) == 1 @test lastindex(x) == 4 end @testset "☎" begin @test ftcall(sum, ftuple(abs2, [1 2; 3 4]; dims=2)) == reshape([5, 25], (2, 1)) @test ftcall(string, ftuple()) == "" @test ftcall(+, ftuple(1, 2)) == 3 @test ftcall((; k...)->sum(values(k)), ftuple(a=3.0, b=0x4)) == 7.0 end f(x::Int; y=3) = x + y g(; b, c, a) = a + b + c h(x::String; a, kwargs...) = x * a @testset "hasmethod" begin @test hasmethod(f, typeof(ftuple(1, y=2))) @test hasmethod(f, typeof(ftuple(1))) # Agreement with using a plain Tuple @test !hasmethod(f, typeof(ftuple(1, a=3))) @test hasmethod(f, FrankenTuple{Tuple{Int},(:y,)}) # Omitting NamedTuple types @test hasmethod(g, typeof(ftuple(a=1, b=2, c=3))) @test hasmethod(g, typeof(ftuple(a=1, b=2))) @test !hasmethod(g, FrankenTuple{Tuple{},(:a,:b,:d)}) @test hasmethod(g, FrankenTuple{Tuple{},(:a,:b,:c)}) @test hasmethod(h, FrankenTuple{Tuple{String},(:a,:b,:c,:d)}) @test !hasmethod(h, FrankenTuple{Tuple{Int},(:a,)}) @test !hasmethod(f, FrankenTuple{Tuple{Int},(:y,)}, world=typemin(UInt)) end
FrankenTuples
https://github.com/ararslan/FrankenTuples.jl.git
[ "MIT" ]
0.1.2
45f2d31d22d8bf962eaab74cf800127b4d307c61
docs
1097
# FrankenTuples.jl [![Build status](https://github.com/ararslan/FrankenTuples.jl/workflows/CI/badge.svg)](https://github.com/ararslan/FrankenTuples.jl/actions?query=workflow%3ACI+branch%3Amain) [![codecov](https://codecov.io/gh/ararslan/FrankenTuples.jl/branch/main/graph/badge.svg?token=G47EaAAqKi)](https://codecov.io/gh/ararslan/FrankenTuples.jl) [![][docs-latest-img]][docs-latest-url] This package defines a type, `FrankenTuple`, which is like a cross between a `Tuple` and a `NamedTuple`; it contains both positional and named elements. > _Accursed creator! Why did you form a monster so hideous that even you turned from me in disgust?_ A function call has the form `f(args...; kwargs...)`. Take away the function, and you get `(args...; kwargs...)`, a tuple with both positional and named elements. No one Base type currently models this, so `FrankenTuple` was created as an experiment to see if and when this precise structure could be useful. [docs-latest-img]: https://img.shields.io/badge/docs-latest-blue.svg [docs-latest-url]: http://ararslan.github.io/FrankenTuples.jl/latest/
FrankenTuples
https://github.com/ararslan/FrankenTuples.jl.git
[ "MIT" ]
0.1.2
45f2d31d22d8bf962eaab74cf800127b4d307c61
docs
1152
```@meta DocTestSetup = :(using FrankenTuples) CurrentModule = FrankenTuples ``` # FrankenTuples.jl The FrankenTuples package defines a type, `FrankenTuple`, which is a creature not unlike Frankenstein's monster. It is comprised of both a `Tuple` and a `NamedTuple` to facilitate situations in which some but not all elements of a tuple are named, e.g. `(1, 2; a=3, b=4)`, and thus acts like a cross between the two. ## Type and Constructors ```@docs FrankenTuples.FrankenTuple FrankenTuples.ftuple FrankenTuples.@ftuple ``` ## API `FrankenTuple`s adhere as closely as makes sense to the API for `Tuple`s and `NamedTuple`s. ```@docs Base.Tuple Base.NamedTuple Base.length Base.isempty Base.iterate Base.keys Base.values Base.pairs Base.getindex Base.firstindex Base.lastindex Base.first Base.tail Base.empty Base.eltype ``` ## Additional Methods These are some additional ways to use `FrankenTuple`s. The most interesting of these is perhaps `hasmethod`, which permits looking for methods that have particular keyword arguments. This is not currently possible with the generic method in Base. ```@docs Base.hasmethod FrankenTuples.ftcall ```
FrankenTuples
https://github.com/ararslan/FrankenTuples.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
4974
using SLEEF using BenchmarkTools using JLD, DataStructures using Printf const RETUNE = false const VERBOSE = true const DETAILS = false const test_types = (Float64, Float32) # Which types do you want to bench? const bench = ("Base", "SLEEF") const suite = BenchmarkGroup() for n in bench suite[n] = BenchmarkGroup([n]) end bench_reduce(f::Function, X) = mapreduce(x -> reinterpret(Unsigned,x), |, f(x) for x in X) using Base.Math.IEEEFloat MRANGE(::Type{Float64}) = 10000000 MRANGE(::Type{Float32}) = 10000 IntF(::Type{Float64}) = Int64 IntF(::Type{Float32}) = Int32 x_trig(::Type{T}) where {T<:IEEEFloat} = begin x_trig = T[] for i = 1:10000 s = reinterpret(T, reinterpret(IntF(T), T(pi)/4 * i) - IntF(T)(20)) e = reinterpret(T, reinterpret(IntF(T), T(pi)/4 * i) + IntF(T)(20)) d = s while d <= e append!(x_trig, d) d = reinterpret(T, reinterpret(IntF(T), d) + IntF(T)(1)) end end x_trig = append!(x_trig, -10:0.0002:10) x_trig = append!(x_trig, -MRANGE(T):200.1:MRANGE(T)) end x_exp(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(-10:0.0002:10, -1000:0.1:1000)) x_exp2(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(-10:0.0002:10, -120:0.023:1000, -1000:0.02:2000)) x_exp10(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(-10:0.0002:10, -35:0.023:1000, -300:0.01:300)) x_expm1(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(-10:0.0002:10, -1000:0.021:1000, -1000:0.023:1000, 10.0.^-(0:0.02:300), -10.0.^-(0:0.02:300), 10.0.^(0:0.021:300), -10.0.^-(0:0.021:300))) x_log(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(0.0001:0.0001:10, 0.001:0.1:10000, 1.1.^(-1000:1000), 2.1.^(-1000:1000))) x_log10(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(0.0001:0.0001:10, 0.0001:0.1:10000)) x_log1p(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(0.0001:0.0001:10, 0.0001:0.1:10000, 10.0.^-(0:0.02:300), -10.0.^-(0:0.02:300))) x_atrig(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(-1:0.00002:1)) x_atan(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(-10:0.0002:10, -10000:0.2:10000, -10000:0.201:10000)) x_cbrt(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(-10000:0.2:10000, 1.1.^(-1000:1000), 2.1.^(-1000:1000))) x_trigh(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(-10:0.0002:10, -1000:0.02:1000)) x_asinhatanh(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(-10:0.0002:10, -1000:0.02:1000)) x_acosh(::Type{T}) where {T<:IEEEFloat} = map(T, vcat(1:0.0002:10, 1:0.02:1000)) x_pow(::Type{T}) where {T<:IEEEFloat} = begin xx1 = map(Tuple{T,T}, [(x,y) for x = -100:0.20:100, y = 0.1:0.20:100])[:] xx2 = map(Tuple{T,T}, [(x,y) for x = -100:0.21:100, y = 0.1:0.22:100])[:] xx3 = map(Tuple{T,T}, [(x,y) for x = 2.1, y = -1000:0.1:1000]) xx = vcat(xx1, xx2, xx2) end import Base.atanh for f in (:atanh,) @eval begin ($f)(x::Float64) = ccall($(string(f)), Float64, (Float64,), x) ($f)(x::Float32) = ccall($(string(f,"f")), Float32, (Float32,), x) end end const micros = OrderedDict( "sin" => x_trig, "cos" => x_trig, "tan" => x_trig, "asin" => x_atrig, "acos" => x_atrig, "atan" => x_atan, "exp" => x_exp, "exp2" => x_exp2, "exp10" => x_exp10, "expm1" => x_expm1, "log" => x_log, "log2" => x_log10, "log10" => x_log10, "log1p" => x_log1p, "sinh" => x_trigh, "cosh" => x_trigh, "tanh" => x_trigh, "asinh" => x_asinhatanh, "acosh" => x_acosh, "atanh" => x_asinhatanh, "cbrt" => x_cbrt ) for n in bench for (f,x) in micros suite[n][f] = BenchmarkGroup([f]) for T in test_types fex = Expr(:., Symbol(n), QuoteNode(Symbol(f))) suite[n][f][string(T)] = @benchmarkable bench_reduce($fex, $(x(T))) end end end tune_params = joinpath(@__DIR__, "params.jld") if !isfile(tune_params) || RETUNE tune!(suite; verbose=VERBOSE, seconds = 2) save(tune_params, "suite", params(suite)) println("Saving tuned parameters.") else println("Loading pretuned parameters.") loadparams!(suite, load(tune_params, "suite"), :evals, :samples) end println("Running micro benchmarks...") results = run(suite; verbose=VERBOSE, seconds = 2) printstyled("Benchmarks: median ratio SLEEF/Base\n", color = :blue) for f in keys(micros) printstyled(string(f) color = :magenta) for T in test_types println() print("time: ", ) tratio = ratio(median(results["SLEEF"][f][string(T)]), median(results["Base"][f][string(T)])).time tcolor = tratio > 3 ? :red : tratio < 1.5 ? :green : :blue printstyled(@sprintf("%.2f",tratio), " ", string(T), color = tcolor) if DETAILS printstyled("details SLEEF/Base\n", color=:blue) println(results["SLEEF"][f][string(T)]) println(results["Base"][f][string(T)]) println() end end println("\n") end
SLEEF
https://github.com/musm/SLEEF.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
5440
module SLEEF # export sin, cos, tan, asin, acos, atan, sincos, sinh, cosh, tanh, # asinh, acosh, atanh, log, log2, log10, log1p, ilogb, exp, exp2, exp10, expm1, ldexp, cbrt, pow # fast variants (within 3 ulp) # export sin_fast, cos_fast, tan_fast, sincos_fast, asin_fast, acos_fast, atan_fast, atan2_fast, log_fast, cbrt_fast using Base.Math: uinttype, @horner, exponent_bias, exponent_mask, significand_bits, IEEEFloat, exponent_raw_max ## constants const MLN2 = 6.931471805599453094172321214581765680755001343602552541206800094933936219696955e-01 # log(2) const MLN2E = 1.442695040888963407359924681001892137426645954152985934135449406931 # log2(e) const M_PI = 3.141592653589793238462643383279502884 # pi const PI_2 = 1.570796326794896619231321691639751442098584699687552910487472296153908203143099 # pi/2 const PI_4 = 7.853981633974483096156608458198757210492923498437764552437361480769541015715495e-01 # pi/4 const M_1_PI = 0.318309886183790671537767526745028724 # 1/pi const M_2_PI = 0.636619772367581343075535053490057448 # 2/pi const M_4_PI = 1.273239544735162686151070106980114896275677165923651589981338752471174381073817 # 4/pi const MSQRT2 = 1.414213562373095048801688724209698078569671875376948073176679737990732478462102 # sqrt(2) const M1SQRT2 = 7.071067811865475244008443621048490392848359376884740365883398689953662392310596e-01 # 1/sqrt(2) const M2P13 = 1.259921049894873164767210607278228350570251464701507980081975112155299676513956 # 2^1/3 const M2P23 = 1.587401051968199474751705639272308260391493327899853009808285761825216505624206 # 2^2/3 const MLOG10_2 = 3.3219280948873623478703194294893901758648313930 const MDLN10E(::Type{Float64}) = Double(0.4342944819032518, 1.098319650216765e-17) # log10(e) const MDLN10E(::Type{Float32}) = Double(0.4342945f0, -1.010305f-8) const MDLN2E(::Type{Float64}) = Double(1.4426950408889634, 2.0355273740931033e-17) # log2(e) const MDLN2E(::Type{Float32}) = Double(1.442695f0, 1.925963f-8) const MDLN2(::Type{Float64}) = Double(0.693147180559945286226764, 2.319046813846299558417771e-17) # log(2) const MDLN2(::Type{Float32}) = Double(0.69314718246459960938f0, -1.904654323148236017f-9) const MDPI(::Type{Float64}) = Double(3.141592653589793, 1.2246467991473532e-16) # pi const MDPI(::Type{Float32}) = Double(3.1415927f0, -8.742278f-8) const MDPI2(::Type{Float64}) = Double(1.5707963267948966, 6.123233995736766e-17) # pi/2 const MDPI2(::Type{Float32}) = Double(1.5707964f0, -4.371139f-8) const MD2P13(::Type{Float64}) = Double(1.2599210498948732, -2.589933375300507e-17) # 2^1/3 const MD2P13(::Type{Float32}) = Double(1.2599211f0, -2.4018702f-8) const MD2P23(::Type{Float64}) = Double(1.5874010519681996, -1.0869008194197823e-16) # 2^2/3 const MD2P23(::Type{Float32}) = Double(1.587401f0, 1.9520385f-8) # Split pi into four parts (each is 26 bits) const PI_A(::Type{Float64}) = 3.1415926218032836914 const PI_B(::Type{Float64}) = 3.1786509424591713469e-08 const PI_C(::Type{Float64}) = 1.2246467864107188502e-16 const PI_D(::Type{Float64}) = 1.2736634327021899816e-24 const PI_A(::Type{Float32}) = 3.140625f0 const PI_B(::Type{Float32}) = 0.0009670257568359375f0 const PI_C(::Type{Float32}) = 6.2771141529083251953f-7 const PI_D(::Type{Float32}) = 1.2154201256553420762f-10 const PI_XD(::Type{Float32}) = 1.2141754268668591976f-10 const PI_XE(::Type{Float32}) = 1.2446743939339977025f-13 # split 2/pi into upper and lower parts const M_2_PI_H = 0.63661977236758138243 const M_2_PI_L = -3.9357353350364971764e-17 # Split log(10) into upper and lower parts const L10U(::Type{Float64}) = 0.30102999566383914498 const L10L(::Type{Float64}) = 1.4205023227266099418e-13 const L10U(::Type{Float32}) = 0.3010253906f0 const L10L(::Type{Float32}) = 4.605038981f-6 # Split log(2) into upper and lower parts const L2U(::Type{Float64}) = 0.69314718055966295651160180568695068359375 const L2L(::Type{Float64}) = 0.28235290563031577122588448175013436025525412068e-12 const L2U(::Type{Float32}) = 0.693145751953125f0 const L2L(::Type{Float32}) = 1.428606765330187045f-06 const TRIG_MAX(::Type{Float64}) = 1e14 const TRIG_MAX(::Type{Float32}) = 1f7 const SQRT_MAX(::Type{Float64}) = 1.3407807929942596355e154 const SQRT_MAX(::Type{Float32}) = 18446743523953729536f0 include("utils.jl") # utility functions include("double.jl") # Dekker style double double functions include("priv.jl") # private math functions include("exp.jl") # exponential functions include("log.jl") # logarithmic functions include("trig.jl") # trigonometric and inverse trigonometric functions include("hyp.jl") # hyperbolic and inverse hyperbolic functions include("misc.jl") # miscallenous math functions including pow and cbrt # fallback definitions for func in (:sin, :cos, :tan, :sincos, :asin, :acos, :atan, :sinh, :cosh, :tanh, :asinh, :acosh, :atanh, :log, :log2, :log10, :log1p, :exp, :exp2, :exp10, :expm1, :cbrt, :sin_fast, :cos_fast, :tan_fast, :sincos_fast, :asin_fast, :acos_fast, :atan_fast, :atan2_fast, :log_fast, :cbrt_fast) @eval begin $func(a::Float16) = Float16.($func(Float32(a))) $func(x::Real) = $func(float(x)) end end for func in (:atan, :hypot) @eval begin $func(y::Real, x::Real) = $func(promote(float(y), float(x))...) $func(a::Float16, b::Float16) = Float16($func(Float32(a), Float32(b))) end end ldexp(x::Float16, q::Int) = Float16(ldexpk(Float32(x), q)) end
SLEEF
https://github.com/musm/SLEEF.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
7399
import Base: -, <, copysign, flipsign, convert struct Double{T<:IEEEFloat} <: Number hi::T lo::T end Double(x::T) where {T<:IEEEFloat} = Double(x, zero(T)) (::Type{T})(x::Double{T}) where {T<:IEEEFloat} = x.hi + x.lo @inline trunclo(x::Float64) = reinterpret(Float64, reinterpret(UInt64, x) & 0xffff_ffff_f800_0000) # clear lower 27 bits (leave upper 26 bits) @inline trunclo(x::Float32) = reinterpret(Float32, reinterpret(UInt32, x) & 0xffff_f000) # clear lowest 12 bits (leave upper 12 bits) @inline function splitprec(x::IEEEFloat) hx = trunclo(x) hx, x - hx end @inline function dnormalize(x::Double{T}) where {T} r = x.hi + x.lo Double(r, (x.hi - r) + x.lo) end @inline flipsign(x::Double{T}, y::T) where {T<:IEEEFloat} = Double(flipsign(x.hi, y), flipsign(x.lo, y)) @inline scale(x::Double{T}, s::T) where {T<:IEEEFloat} = Double(s * x.hi, s * x.lo) @inline (-)(x::Double{T}) where {T<:IEEEFloat} = Double(-x.hi, -x.lo) @inline function (<)(x::Double{T}, y::Double{T}) where {T<:IEEEFloat} x.hi < y.hi end @inline function (<)(x::Double{T}, y::Number) where {T<:IEEEFloat} x.hi < y end @inline function (<)(x::Number, y::Double{T}) where {T<:IEEEFloat} x < y.hi end # quick-two-sum x+y @inline function dadd(x::T, y::T) where {T<:IEEEFloat} #WARNING |x| >= |y| s = x + y Double(s, (x - s) + y) end @inline function dadd(x::T, y::Double{T}) where {T<:IEEEFloat} #WARNING |x| >= |y| s = x + y.hi Double(s, (x - s) + y.hi + y.lo) end @inline function dadd(x::Double{T}, y::T) where {T<:IEEEFloat} #WARNING |x| >= |y| s = x.hi + y Double(s, (x.hi - s) + y + x.lo) end @inline function dadd(x::Double{T}, y::Double{T}) where {T<:IEEEFloat} #WARNING |x| >= |y| s = x.hi + y.hi Double(s, (x.hi - s) + y.hi + y.lo + x.lo) end @inline function dsub(x::Double{T}, y::Double{T}) where {T<:IEEEFloat} #WARNING |x| >= |y| s = x.hi - y.hi Double(s, (x.hi - s) - y.hi - y.lo + x.lo) end @inline function dsub(x::Double{T}, y::T) where {T<:IEEEFloat} #WARNING |x| >= |y| s = x.hi - y Double(s, (x.hi - s) - y + x.lo) end @inline function dsub(x::T, y::Double{T}) where {T<:IEEEFloat} #WARNING |x| >= |y| s = x - y.hi Double(s, (x - s) - y.hi - y.lo) end @inline function dsub(x::T, y::T) where {T<:IEEEFloat} #WARNING |x| >= |y| s = x - y Double(s, (x - s) - y) end # two-sum x+y NO BRANCH @inline function dadd2(x::T, y::T) where {T<:IEEEFloat} s = x + y v = s - x Double(s, (x - (s - v)) + (y - v)) end @inline function dadd2(x::T, y::Double{T}) where {T<:IEEEFloat} s = x + y.hi v = s - x Double(s, (x - (s - v)) + (y.hi - v) + y.lo) end @inline dadd2(x::Double{T}, y::T) where {T<:IEEEFloat} = dadd2(y, x) @inline function dadd2(x::Double{T}, y::Double{T}) where {T<:IEEEFloat} s = x.hi + y.hi v = s - x.hi Double(s, (x.hi - (s - v)) + (y.hi - v) + x.lo + y.lo) end @inline function dsub2(x::T, y::T) where {T<:IEEEFloat} s = x - y v = s - x Double(s, (x - (s - v)) + (-y - v)) end @inline function dsub2(x::T, y::Double{T}) where {T<:IEEEFloat} s = x - y.hi v = s - x Double(s, (x - (s - v)) + (-y.hi - v) - y.lo) end @inline function dsub2(x::Double{T}, y::T) where {T<:IEEEFloat} s = x.hi - y v = s - x.hi Double(s, (x.hi - (s - v)) + (-y - v) + x.lo) end @inline function dsub2(x::Double{T}, y::Double{T}) where {T<:IEEEFloat} s = x.hi - y.hi v = s - x.hi Double(s, (x.hi - (s - v)) + (-y.hi - v) + x.lo - y.lo) end if FMA_FAST # two-prod-fma @inline function dmul(x::T, y::T) where {T<:IEEEFloat} z = x * y Double(z, fma(x, y, -z)) end @inline function dmul(x::Double{T}, y::T) where {T<:IEEEFloat} z = x.hi * y Double(z, fma(x.hi, y, -z) + x.lo * y) end @inline dmul(x::T, y::Double{T}) where {T<:IEEEFloat} = dmul(y, x) @inline function dmul(x::Double{T}, y::Double{T}) where {T<:IEEEFloat} z = x.hi * y.hi Double(z, fma(x.hi, y.hi, -z) + x.hi * y.lo + x.lo * y.hi) end # x^2 @inline function dsqu(x::T) where {T<:IEEEFloat} z = x * x Double(z, fma(x, x, -z)) end @inline function dsqu(x::Double{T}) where {T<:IEEEFloat} z = x.hi * x.hi Double(z, fma(x.hi, x.hi, -z) + x.hi * (x.lo + x.lo)) end # sqrt(x) @inline function dsqrt(x::Double{T}) where {T<:IEEEFloat} zhi = _sqrt(x.hi) Double(zhi, (x.lo + fma(-zhi, zhi, x.hi)) / (zhi + zhi)) end # x/y @inline function ddiv(x::Double{T}, y::Double{T}) where {T<:IEEEFloat} invy = 1 / y.hi zhi = x.hi * invy Double(zhi, (fma(-zhi, y.hi, x.hi) + fma(-zhi, y.lo, x.lo)) * invy) end @inline function ddiv(x::T, y::T) where {T<:IEEEFloat} ry = 1 / y r = x * ry Double(r, fma(-r, y, x) * ry) end # 1/x @inline function drec(x::T) where {T<:IEEEFloat} zhi = 1 / x Double(zhi, fma(-zhi, x, one(T)) * zhi) end @inline function drec(x::Double{T}) where {T<:IEEEFloat} zhi = 1 / x.hi Double(zhi, (fma(-zhi, x.hi, one(T)) + -zhi * x.lo) * zhi) end else #two-prod x*y @inline function dmul(x::T, y::T) where {T<:IEEEFloat} hx, lx = splitprec(x) hy, ly = splitprec(y) z = x * y Double(z, ((hx * hy - z) + lx * hy + hx * ly) + lx * ly) end @inline function dmul(x::Double{T}, y::T) where {T<:IEEEFloat} hx, lx = splitprec(x.hi) hy, ly = splitprec(y) z = x.hi * y Double(z, (hx * hy - z) + lx * hy + hx * ly + lx * ly + x.lo * y) end @inline dmul(x::T, y::Double{T}) where {T<:IEEEFloat} = dmul(y, x) @inline function dmul(x::Double{T}, y::Double{T}) where {T<:IEEEFloat} hx, lx = splitprec(x.hi) hy, ly = splitprec(y.hi) z = x.hi * y.hi Double(z, (((hx * hy - z) + lx * hy + hx * ly) + lx * ly) + x.hi * y.lo + x.lo * y.hi) end # x^2 @inline function dsqu(x::T) where {T<:IEEEFloat} hx, lx = splitprec(x) z = x * x Double(z, (hx * hx - z) + lx * (hx + hx) + lx * lx) end @inline function dsqu(x::Double{T}) where {T<:IEEEFloat} hx, lx = splitprec(x.hi) z = x.hi * x.hi Double(z, (hx * hx - z) + lx * (hx + hx) + lx * lx + x.hi * (x.lo + x.lo)) end # sqrt(x) @inline function dsqrt(x::Double{T}) where {T<:IEEEFloat} c = _sqrt(x.hi) u = dsqu(c) Double(c, (x.hi - u.hi - u.lo + x.lo) / (c + c)) end # x/y @inline function ddiv(x::Double{T}, y::Double{T}) where {T<:IEEEFloat} invy = 1 / y.hi c = x.hi * invy u = dmul(c, y.hi) Double(c, ((((x.hi - u.hi) - u.lo) + x.lo) - c * y.lo) * invy) end @inline function ddiv(x::T, y::T) where {T<:IEEEFloat} ry = 1 / y r = x * ry hx, lx = splitprec(r) hy, ly = splitprec(y) Double(r, (((-hx * hy + r * y) - lx * hy - hx * ly) - lx * ly) * ry) end # 1/x @inline function drec(x::T) where {T<:IEEEFloat} c = 1 / x u = dmul(c, x) Double(c, (one(T) - u.hi - u.lo) * c) end @inline function drec(x::Double{T}) where {T<:IEEEFloat} c = 1 / x.hi u = dmul(c, x.hi) Double(c, (one(T) - u.hi - u.lo - c * x.lo) * c) end end
SLEEF
https://github.com/musm/SLEEF.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
5009
# exported exponential functions """ ldexp(a, n) Computes `a Γ— 2^n` """ ldexp(x::Union{Float32,Float64}, q::Int) = ldexpk(x, q) const max_exp2(::Type{Float64}) = 1024 const max_exp2(::Type{Float32}) = 128f0 const min_exp2(::Type{Float64}) = -1075 const min_exp2(::Type{Float32}) = -150f0 @inline function exp2_kernel(x::Float64) c11 = 0.4434359082926529454e-9 c10 = 0.7073164598085707425e-8 c9 = 0.1017819260921760451e-6 c8 = 0.1321543872511327615e-5 c7 = 0.1525273353517584730e-4 c6 = 0.1540353045101147808e-3 c5 = 0.1333355814670499073e-2 c4 = 0.9618129107597600536e-2 c3 = 0.5550410866482046596e-1 c2 = 0.2402265069591012214 c1 = 0.6931471805599452862 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 end @inline function exp2_kernel(x::Float32) c6 = 0.1535920892f-3 c5 = 0.1339262701f-2 c4 = 0.9618384764f-2 c3 = 0.5550347269f-1 c2 = 0.2402264476f0 c1 = 0.6931471825f0 return @horner x c1 c2 c3 c4 c5 c6 end """ exp2(x) Compute the base-`2` exponential of `x`, that is `2Λ£`. """ function exp2(d::T) where {T<:Union{Float32,Float64}} q = round(d) qi = unsafe_trunc(Int, q) s = d - q u = exp2_kernel(s) u = T(dnormalize(dadd(T(1.0), dmul(u,s)))) u = ldexp2k(u, qi) d > max_exp2(T) && (u = T(Inf)) d < min_exp2(T) && (u = T(0.0)) return u end const max_exp10(::Type{Float64}) = 3.08254715559916743851e2 # log 2^1023*(2-2^-52) const max_exp10(::Type{Float32}) = 38.531839419103626f0 # log 2^127 *(2-2^-23) const min_exp10(::Type{Float64}) = -3.23607245338779784854769e2 # log10 2^-1075 const min_exp10(::Type{Float32}) = -45.15449934959718f0 # log10 2^-150 @inline function exp10_kernel(x::Float64) c11 = 0.2411463498334267652e-3 c10 = 0.1157488415217187375e-2 c9 = 0.5013975546789733659e-2 c8 = 0.1959762320720533080e-1 c7 = 0.6808936399446784138e-1 c6 = 0.2069958494722676234e0 c5 = 0.5393829292058536229e0 c4 = 0.1171255148908541655e1 c3 = 0.2034678592293432953e1 c2 = 0.2650949055239205876e1 c1 = 0.2302585092994045901e1 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 end @inline function exp10_kernel(x::Float32) c6 = 0.2064004987f0 c5 = 0.5417877436f0 c4 = 0.1171286821f1 c3 = 0.2034656048f1 c2 = 0.2650948763f1 c1 = 0.2302585125f1 return @horner x c1 c2 c3 c4 c5 c6 end """ exp10(x) Compute the base-`10` exponential of `x`, that is `10Λ£`. """ function exp10(d::T) where {T<:Union{Float32,Float64}} q = round(T(MLOG10_2) * d) qi = unsafe_trunc(Int, q) s = muladd(q, -L10U(T), d) s = muladd(q, -L10L(T), s) u = exp10_kernel(s) u = T(dnormalize(dadd(T(1.0), dmul(u,s)))) u = ldexp2k(u, qi) d > max_exp10(T) && (u = T(Inf)) d < min_exp10(T) && (u = T(0.0)) return u end const max_expm1(::Type{Float64}) = 7.09782712893383996732e2 # log 2^1023*(2-2^-52) const max_expm1(::Type{Float32}) = 88.72283905206835f0 # log 2^127 *(2-2^-23) const min_expm1(::Type{Float64}) = -37.42994775023704434602223 const min_expm1(::Type{Float32}) = -17.3286790847778338076068394f0 """ expm1(x) Compute `eΛ£- 1` accurately for small values of `x`. """ function expm1(x::T) where {T<:Union{Float32,Float64}} u = T(dadd2(expk2(Double(x)), -T(1.0))) x > max_expm1(T) && (u = T(Inf)) x < min_expm1(T) && (u = -T(1.0)) isnegzero(x) && (u = T(-0.0)) return u end const max_exp(::Type{Float64}) = 709.78271114955742909217217426 # log 2^1023*(2-2^-52) const max_exp(::Type{Float32}) = 88.72283905206835f0 # log 2^127 *(2-2^-23) const min_exp(::Type{Float64}) = -7.451332191019412076235e2 # log 2^-1075 const min_exp(::Type{Float32}) = -103.97208f0 # β‰ˆ log 2^-150 @inline function exp_kernel(x::Float64) c11 = 2.08860621107283687536341e-09 c10 = 2.51112930892876518610661e-08 c9 = 2.75573911234900471893338e-07 c8 = 2.75572362911928827629423e-06 c7 = 2.4801587159235472998791e-05 c6 = 0.000198412698960509205564975 c5 = 0.00138888888889774492207962 c4 = 0.00833333333331652721664984 c3 = 0.0416666666666665047591422 c2 = 0.166666666666666851703837 c1 = 0.50 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 end @inline function exp_kernel(x::Float32) c6 = 0.000198527617612853646278381f0 c5 = 0.00139304355252534151077271f0 c4 = 0.00833336077630519866943359f0 c3 = 0.0416664853692054748535156f0 c2 = 0.166666671633720397949219f0 c1 = 0.5f0 return @horner x c1 c2 c3 c4 c5 c6 end """ exp(x) Compute the base-`e` exponential of `x`, that is `eΛ£`. """ function exp(d::T) where {T<:Union{Float32,Float64}} q = round(T(MLN2E) * d) qi = unsafe_trunc(Int, q) s = muladd(q, -L2U(T), d) s = muladd(q, -L2L(T), s) u = exp_kernel(s) u = s * s * u + s + 1 u = ldexp2k(u, qi) d > max_exp(T) && (u = T(Inf)) d < min_exp(T) && (u = T(0)) return u end
SLEEF
https://github.com/musm/SLEEF.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
2423
# exported hyperbolic functions over_sch(::Type{Float64}) = 710.0 over_sch(::Type{Float32}) = 89f0 """ sinh(x) Compute hyperbolic sine of `x`. """ function sinh(x::T) where {T<:Union{Float32,Float64}} u = abs(x) d = expk2(Double(u)) d = dsub(d, drec(d)) u = T(d) * T(0.5) u = abs(x) > over_sch(T) ? T(Inf) : u u = isnan(u) ? T(Inf) : u u = flipsign(u, x) u = isnan(x) ? T(NaN) : u return u end """ cosh(x) Compute hyperbolic cosine of `x`. """ function cosh(x::T) where {T<:Union{Float32,Float64}} u = abs(x) d = expk2(Double(u)) d = dadd(d, drec(d)) u = T(d) * T(0.5) u = abs(x) > over_sch(T) ? T(Inf) : u u = isnan(u) ? T(Inf) : u u = isnan(x) ? T(NaN) : u return u end over_th(::Type{Float64}) = 18.714973875 over_th(::Type{Float32}) = 18.714973875f0 """ tanh(x) Compute hyperbolic tangent of `x`. """ function tanh(x::T) where {T<:Union{Float32,Float64}} u = abs(x) d = expk2(Double(u)) e = drec(d) d = ddiv(dsub(d, e), dadd(d, e)) u = T(d) u = abs(x) > over_th(T) ? T(1.0) : u u = isnan(u) ? T(1) : u u = flipsign(u, x) u = isnan(x) ? T(NaN) : u return u end """ asinh(x) Compute the inverse hyperbolic sine of `x`. """ function asinh(x::T) where {T<:Union{Float32,Float64}} y = abs(x) d = y > 1 ? drec(x) : Double(y, T(0.0)) d = dsqrt(dadd2(dsqu(d), T(1.0))) d = y > 1 ? dmul(d, y) : d d = logk2(dnormalize(dadd(d, x))) y = T(d) y = (abs(x) > SQRT_MAX(T) || isnan(y)) ? flipsign(T(Inf), x) : y y = isnan(x) ? T(NaN) : y y = isnegzero(x) ? T(-0.0) : y return y end """ acosh(x) Compute the inverse hyperbolic cosine of `x`. """ function acosh(x::T) where {T<:Union{Float32,Float64}} d = logk2(dadd2(dmul(dsqrt(dadd2(x, T(1.0))), dsqrt(dsub2(x, T(1.0)))), x)) y = T(d) y = (x > SQRT_MAX(T) || isnan(y)) ? T(Inf) : y y = x == T(1.0) ? T(0.0) : y y = x < T(1.0) ? T(NaN) : y y = isnan(x) ? T(NaN) : y return y end """ atanh(x) Compute the inverse hyperbolic tangent of `x`. """ function atanh(x::T) where {T<:Union{Float32,Float64}} u = abs(x) d = logk2(ddiv(dadd2(T(1.0), u), dsub2(T(1.0), u))) u = u > T(1.0) ? T(NaN) : (u == T(1.0) ? T(Inf) : T(d) * T(0.5)) u = isinf(x) || isnan(u) ? T(NaN) : u u = flipsign(u, x) u = isnan(x) ? T(NaN) : u return u end
SLEEF
https://github.com/musm/SLEEF.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
4736
# exported logarithmic functions const FP_ILOGB0 = typemin(Int) const FP_ILOGBNAN = typemin(Int) const INT_MAX = typemax(Int) """ ilogb(x) Returns the integral part of the logarithm of `abs(x)`, using base 2 for the logarithm. In other words, this computes the binary exponent of `x` such that x = significand Γ— 2^exponent, where `significand ∈ [1, 2)`. * Exceptional cases (where `Int` is the machine wordsize) * `x = 0` returns `FP_ILOGB0` * `x = Β±Inf` returns `INT_MAX` * `x = NaN` returns `FP_ILOGBNAN` """ function ilogb(x::T) where {T<:Union{Float32,Float64}} e = ilogbk(abs(x)) x == 0 && (e = FP_ILOGB0) isnan(x) && (e = FP_ILOGBNAN) isinf(x) && (e = INT_MAX) return e end """ log10(x) Returns the base `10` logarithm of `x`. """ function log10(a::T) where {T<:Union{Float32,Float64}} x = T(dmul(logk(a), MDLN10E(T))) isinf(a) && (x = T(Inf)) (a < 0 || isnan(a)) && (x = T(NaN)) a == 0 && (x = T(-Inf)) return x end """ log2(x) Returns the base `2` logarithm of `x`. """ function log2(a::T) where {T<:Union{Float32,Float64}} u = T(dmul(logk(a), MDLN2E(T))) isinf(a) && (u = T(Inf)) (a < 0 || isnan(a)) && (u = T(NaN)) a == 0 && (u = T(-Inf)) return u end const over_log1p(::Type{Float64}) = 1e307 const over_log1p(::Type{Float32}) = 1f38 """ log1p(x) Accurately compute the natural logarithm of 1+x. """ function log1p(a::T) where {T<:Union{Float32,Float64}} x = T(logk2(dadd2(a, T(1.0)))) a > over_log1p(T) && (x = T(Inf)) a < -1 && (x = T(NaN)) a == -1 && (x = T(-Inf)) isnegzero(a) && (x = T(-0.0)) return x end @inline function log_kernel(x::Float64) c7 = 0.1532076988502701353 c6 = 0.1525629051003428716 c5 = 0.1818605932937785996 c4 = 0.2222214519839380009 c3 = 0.2857142932794299317 c2 = 0.3999999999635251990 c1 = 0.6666666666667333541 return @horner x c1 c2 c3 c4 c5 c6 c7 end @inline function log_kernel(x::Float32) c3 = 0.3027294874f0 c2 = 0.3996108174f0 c1 = 0.6666694880f0 return @horner x c1 c2 c3 end """ log(x) Compute the natural logarithm of `x`. The inverse of the natural logarithm is the natural expoenential function `exp(x)` """ function log(d::T) where {T<:Union{Float32,Float64}} o = d < floatmin(T) o && (d *= T(Int64(1) << 32) * T(Int64(1) << 32)) e = ilogb2k(d * T(1.0/0.75)) m = ldexp3k(d, -e) o && (e -= 64) x = ddiv(dadd2(T(-1.0), m), dadd2(T(1.0), m)) x2 = x.hi*x.hi t = log_kernel(x2) s = dmul(MDLN2(T), T(e)) s = dadd(s, scale(x, T(2.0))) s = dadd(s, x2*x.hi*t) r = T(s) isinf(d) && (r = T(Inf)) (d < 0 || isnan(d)) && (r = T(NaN)) d == 0 && (r = -T(Inf)) return r end # First we split the argument to its mantissa `m` and integer exponent `e` so # that `d = m \times 2^e`, where `m \in [0.5, 1)` then we apply the polynomial # approximant on this reduced argument `m` before putting back the exponent # in. This first part is done with the help of the private function # `ilogbk(x)` and we put the exponent back using # `\log(m \times 2^e) = \log(m) + \log 2^e = \log(m) + e\times MLN2 # The polynomial we evaluate is based on coefficients from # `log_2(x) = 2\sum_{n=0}^\infty \frac{1}{2n+1} \bigl(\frac{x-1}{x+1}^{2n+1}\bigr)` # That being said, since this converges faster when the argument is close to # 1, we multiply `m` by `2` and subtract 1 for the exponent `e` when `m` is # less than `sqrt(2)/2` @inline function log_fast_kernel(x::Float64) c8 = 0.153487338491425068243146 c7 = 0.152519917006351951593857 c6 = 0.181863266251982985677316 c5 = 0.222221366518767365905163 c4 = 0.285714294746548025383248 c3 = 0.399999999950799600689777 c2 = 0.6666666666667778740063 c1 = 2.0 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 end @inline function log_fast_kernel(x::Float32) c5 = 0.2392828464508056640625f0 c4 = 0.28518211841583251953125f0 c3 = 0.400005877017974853515625f0 c2 = 0.666666686534881591796875f0 c1 = 2f0 return @horner x c1 c2 c3 c4 c5 end """ log_fast(x) Compute the natural logarithm of `x`. The inverse of the natural logarithm is the natural expoenential function `exp(x)` """ function log_fast(d::T) where {T<:Union{Float32,Float64}} o = d < floatmin(T) o && (d *= T(Int64(1) << 32) * T(Int64(1) << 32)) e = ilogb2k(d * T(1.0/0.75)) m = ldexp3k(d, -e) o && (e -= 64) x = (m - 1) / (m + 1) x2 = x * x t = log_fast_kernel(x2) x = x * t + T(MLN2) * e isinf(d) && (x = T(Inf)) (d < 0 || isnan(d)) && (x = T(NaN)) d == 0 && (x = -T(Inf)) return x end
SLEEF
https://github.com/musm/SLEEF.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
2860
""" pow(x, y) Exponentiation operator, returns `x` raised to the power `y`. """ function pow(x::T, y::T) where {T<:Union{Float32,Float64}} yi = unsafe_trunc(Int, y) yisint = yi == y yisodd = isodd(yi) && yisint result = expk(dmul(logk(abs(x)), y)) result = isnan(result) ? T(Inf) : result result *= (x > 0 ? T(1.0) : (!yisint ? T(NaN) : (yisodd ? -T(1.0) : T(1.0)))) efx = flipsign(abs(x) - 1, y) isinf(y) && (result = efx < 0 ? T(0.0) : (efx == 0 ? T(1.0) : T(Inf))) (isinf(x) || x == 0) && (result = (yisodd ? _sign(x) : T(1.0)) * ((x == 0 ? -y : y) < 0 ? T(0.0) : T(Inf))) (isnan(x) || isnan(y)) && (result = T(NaN)) (y == 0 || x == 1) && (result = T(1.0)) return result end let global cbrt_fast global cbrt c6d = -0.640245898480692909870982 c5d = 2.96155103020039511818595 c4d = -5.73353060922947843636166 c3d = 6.03990368989458747961407 c2d = -3.85841935510444988821632 c1d = 2.2307275302496609725722 c6f = -0.601564466953277587890625f0 c5f = 2.8208892345428466796875f0 c4f = -5.532182216644287109375f0 c3f = 5.898262500762939453125f0 c2f = -3.8095417022705078125f0 c1f = 2.2241256237030029296875f0 global @inline cbrt_kernel(x::Float64) = @horner x c1d c2d c3d c4d c5d c6d global @inline cbrt_kernel(x::Float32) = @horner x c1f c2f c3f c4f c5f c6f """ cbrt_fast(x) Return `x^{1/3}`. """ function cbrt_fast(d::T) where {T<:Union{Float32,Float64}} e = ilogbk(abs(d)) + 1 d = ldexp2k(d, -e) r = (e + 6144) % 3 q = r == 1 ? T(M2P13) : T(1) q = r == 2 ? T(M2P23) : q q = ldexp2k(q, (e + 6144) Γ· 3 - 2048) q = flipsign(q, d) d = abs(d) x = cbrt_kernel(d) y = x * x y = y * y x -= (d * y - x) * T(1 / 3) y = d * x * x y = (y - T(2 / 3) * y * (y * x - 1)) * q end """ cbrt(x) Return `x^{1/3}`. The prefix operator `βˆ›` is equivalent to `cbrt`. """ function cbrt(d::T) where {T<:Union{Float32,Float64}} e = ilogbk(abs(d)) + 1 d = ldexp2k(d, -e) r = (e + 6144) % 3 q2 = r == 1 ? MD2P13(T) : Double(T(1)) q2 = r == 2 ? MD2P23(T) : q2 q2 = flipsign(q2, d) d = abs(d) x = cbrt_kernel(d) y = x * x y = y * y x -= (d * y - x) * T(1 / 3) z = x u = dsqu(x) u = dsqu(u) u = dmul(u, d) u = dsub(u, x) y = T(u) y = -T(2 / 3) * y * z v = dadd(dsqu(z), y) v = dmul(v, d) v = dmul(v, q2) z = ldexp2k(T(v), (e + 6144) Γ· 3 - 2048) isinf(d) && (z = flipsign(T(Inf), q2.hi)) d == 0 && (z = flipsign(T(0), q2.hi)) return z end end """ hypot(x,y) Compute the hypotenuse `\\sqrt{x^2+y^2}` avoiding overflow and underflow. """ function hypot(x::T, y::T) where {T<:IEEEFloat} x = abs(x) y = abs(y) if x < y x, y = y, x end r = (x == 0) ? y : y / x x * sqrt(T(1.0) + r * r) end
SLEEF
https://github.com/musm/SLEEF.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
9650
# private math functions """ A helper function for `ldexpk` First note that `r = (q >> n) << n` clears the lowest n bits of q, i.e. returns 2^n where n is the largest integer such that q >= 2^n For numbers q less than 2^m the following code does the same as the above snippet `r = ( (q>>v + q) >> n - q>>v ) << n` For numbers larger than or equal to 2^v this subtracts 2^n from q for q>>n times. The function returns q(input) := q(output) + offset*r In the code for ldexpk we actually use `m = ( (m>>n + m) >> n - m>>m ) << (n-2)`. So that x has to be multplied by u four times `x = x*u*u*u*u` to put the value of the offset exponent amount back in. """ @inline function _split_exponent(q, n, v, offset) m = q >> v m = (((m + q) >> n) - m) << (n - offset) q = q - (m << offset) m, q end @inline split_exponent(::Type{Float64}, q::Int) = _split_exponent(q, UInt(9), UInt(31), UInt(2)) @inline split_exponent(::Type{Float32}, q::Int) = _split_exponent(q, UInt(6), UInt(31), UInt(2)) """ ldexpk(a, n) Computes `a Γ— 2^n`. """ @inline function ldexpk(x::T, q::Int) where {T<:Union{Float32,Float64}} bias = exponent_bias(T) emax = exponent_raw_max(T) m, q = split_exponent(T, q) m += bias m = ifelse(m < 0, 0, m) m = ifelse(m > emax, emax, m) q += bias u = integer2float(T, m) x = x * u * u * u * u u = integer2float(T, q) x * u end @inline function ldexp2k(x::T, e::Int) where {T<:Union{Float32,Float64}} x * pow2i(T, e >> 1) * pow2i(T, e - (e >> 1)) end @inline function ldexp3k(x::T, e::Int) where {T<:Union{Float32,Float64}} reinterpret(T, reinterpret(Unsigned, x) + (Int64(e) << significand_bits(T)) % uinttype(T)) end # threshold values for `ilogbk` const threshold_exponent(::Type{Float64}) = 300 const threshold_exponent(::Type{Float32}) = 64 """ ilogbk(x) -> Int Returns the integral part of the logarithm of `|x|`, using 2 as base for the logarithm; in other words this returns the binary exponent of `x` so that x = significand Γ— 2^exponent where `significand ∈ [1, 2)`. """ @inline function ilogbk(d::T) where {T<:Union{Float32,Float64}} m = d < T(2)^-threshold_exponent(T) d = ifelse(m, d * T(2)^threshold_exponent(T), d) q = float2integer(d) & exponent_raw_max(T) q = ifelse(m, q - (threshold_exponent(T) + exponent_bias(T)), q - exponent_bias(T)) end # similar to ilogbk, but argument has to be a normalized float value @inline function ilogb2k(d::T) where {T<:Union{Float32,Float64}} (float2integer(d) & exponent_raw_max(T)) - exponent_bias(T) end let global atan2k_fast global atan2k c20d = 1.06298484191448746607415e-05 c19d = -0.000125620649967286867384336 c18d = 0.00070557664296393412389774 c17d = -0.00251865614498713360352999 c16d = 0.00646262899036991172313504 c15d = -0.0128281333663399031014274 c14d = 0.0208024799924145797902497 c13d = -0.0289002344784740315686289 c12d = 0.0359785005035104590853656 c11d = -0.041848579703592507506027 c10d = 0.0470843011653283988193763 c9d = -0.0524914210588448421068719 c8d = 0.0587946590969581003860434 c7d = -0.0666620884778795497194182 c6d = 0.0769225330296203768654095 c5d = -0.0909090442773387574781907 c4d = 0.111111108376896236538123 c3d = -0.142857142756268568062339 c2d = 0.199999999997977351284817 c1d = -0.333333333333317605173818 c9f = -0.00176397908944636583328247f0 c8f = 0.0107900900766253471374512f0 c7f = -0.0309564601629972457885742f0 c6f = 0.0577365085482597351074219f0 c5f = -0.0838950723409652709960938f0 c4f = 0.109463557600975036621094f0 c3f = -0.142626821994781494140625f0 c2f = 0.199983194470405578613281f0 c1f = -0.333332866430282592773438f0 global @inline atan2k_fast_kernel(x::Float64) = @horner x c1d c2d c3d c4d c5d c6d c7d c8d c9d c10d c11d c12d c13d c14d c15d c16d c17d c18d c19d c20d global @inline atan2k_fast_kernel(x::Float32) = @horner x c1f c2f c3f c4f c5f c6f c7f c8f c9f @inline function atan2k_fast(y::T, x::T) where {T<:Union{Float32,Float64}} q = 0 if x < 0 x = -x q = -2 end if y > x t = x; x = y y = -t q += 1 end s = y / x t = s * s u = atan2k_fast_kernel(t) t = u * t * s + s q * T(PI_2) + t end global @inline atan2k_kernel(x::Double{Float64}) = @horner x.hi c1d c2d c3d c4d c5d c6d c7d c8d c9d c10d c11d c12d c13d c14d c15d c16d c17d c18d c19d c20d global @inline atan2k_kernel(x::Double{Float32}) = dadd(c1f, x.hi * (@horner x.hi c2f c3f c4f c5f c6f c7f c8f c9f)) @inline function atan2k(y::Double{T}, x::Double{T}) where {T<:Union{Float32,Float64}} q = 0 if x < 0 x = -x q = -2 end if y > x t = x; x = y y = -t q += 1 end s = ddiv(y, x) t = dsqu(s) t = dnormalize(t) u = atan2k_kernel(t) t = dmul(t, u) t = dmul(s, dadd(T(1.0), t)) T <: Float64 && abs(s.hi) < 1e-200 && (t = s) t = dadd(dmul(T(q), MDPI2(T)), t) return t end end const under_expk(::Type{Float64}) = -1000.0 const under_expk(::Type{Float32}) = -104f0 @inline function expk_kernel(x::Float64) c10 = 2.51069683420950419527139e-08 c9 = 2.76286166770270649116855e-07 c8 = 2.75572496725023574143864e-06 c7 = 2.48014973989819794114153e-05 c6 = 0.000198412698809069797676111 c5 = 0.0013888888939977128960529 c4 = 0.00833333333332371417601081 c3 = 0.0416666666665409524128449 c2 = 0.166666666666666740681535 c1 = 0.500000000000000999200722 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 end @inline function expk_kernel(x::Float32) c5 = 0.00136324646882712841033936f0 c4 = 0.00836596917361021041870117f0 c3 = 0.0416710823774337768554688f0 c2 = 0.166665524244308471679688f0 c1 = 0.499999850988388061523438f0 return @horner x c1 c2 c3 c4 c5 end @inline function expk(d::Double{T}) where {T<:Union{Float32,Float64}} q = round(T(d) * T(MLN2E)) qi = unsafe_trunc(Int, q) s = dadd(d, -q * L2U(T)) s = dadd(s, -q * L2L(T)) s = dnormalize(s) u = expk_kernel(T(s)) t = dadd(s, dmul(dsqu(s), u)) t = dadd(T(1.0), t) u = ldexpk(T(t), qi) (d.hi < under_expk(T)) && (u = T(0.0)) return u end @inline function expk2_kernel(x::Double{Float64}) c11 = 0.1602472219709932072e-9 c10 = 0.2092255183563157007e-8 c9 = 0.2505230023782644465e-7 c8 = 0.2755724800902135303e-6 c7 = 0.2755731892386044373e-5 c6 = 0.2480158735605815065e-4 c5 = 0.1984126984148071858e-3 c4 = 0.1388888888886763255e-2 c3 = 0.8333333333333347095e-2 c2 = 0.4166666666666669905e-1 c1 = 0.1666666666666666574e0 u = @horner x.hi c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 return dadd(dmul(x, u), c1) end @inline function expk2_kernel(x::Double{Float32}) c5 = 0.1980960224f-3 c4 = 0.1394256484f-2 c3 = 0.8333456703f-2 c2 = 0.4166637361f-1 c1 = 0.166666659414234244790680580464f0 u = @horner x.hi c2 c3 c4 c5 return dadd(dmul(x, u), c1) end @inline function expk2(d::Double{T}) where {T<:Union{Float32,Float64}} q = round(T(d) * T(MLN2E)) qi = unsafe_trunc(Int, q) s = dadd(d, -q * L2U(T)) s = dadd(s, -q * L2L(T)) t = expk2_kernel(s) t = dadd(dmul(s, t), T(0.5)) t = dadd(s, dmul(dsqu(s), t)) t = dadd(T(1.0), t) t = Double(ldexp2k(t.hi, qi), ldexp2k(t.lo, qi)) (d.hi < under_expk(T)) && (t = Double(T(0.0))) return t end @inline function logk2_kernel(x::Float64) c8 = 0.13860436390467167910856 c7 = 0.131699838841615374240845 c6 = 0.153914168346271945653214 c5 = 0.181816523941564611721589 c4 = 0.22222224632662035403996 c3 = 0.285714285511134091777308 c2 = 0.400000000000914013309483 c1 = 0.666666666666664853302393 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 end @inline function logk2_kernel(x::Float32) c4 = 0.240320354700088500976562f0 c3 = 0.285112679004669189453125f0 c2 = 0.400007992982864379882812f0 c1 = 0.666666686534881591796875f0 return @horner x c1 c2 c3 c4 end @inline function logk2(d::Double{T}) where {T<:Union{Float32,Float64}} e = ilogbk(d.hi * T(1.0/0.75)) m = scale(d, pow2i(T, -e)) x = ddiv(dsub2(m, T(1.0)), dadd2(m, T(1.0))) x2 = dsqu(x) t = logk2_kernel(x2.hi) s = dmul(MDLN2(T), T(e)) s = dadd(s, scale(x, T(2.0))) s = dadd(s, dmul(dmul(x2, x), t)) return s end @inline function logk_kernel(x::Double{Float64}) c10 = 0.116255524079935043668677 c9 = 0.103239680901072952701192 c8 = 0.117754809412463995466069 c7 = 0.13332981086846273921509 c6 = 0.153846227114512262845736 c5 = 0.181818180850050775676507 c4 = 0.222222222230083560345903 c3 = 0.285714285714249172087875 c2 = 0.400000000000000077715612 c1 = Double(0.666666666666666629659233, 3.80554962542412056336616e-17) dadd2(dmul(x, @horner x.hi c2 c3 c4 c5 c6 c7 c8 c9 c10), c1) end @inline function logk_kernel(x::Double{Float32}) c4 = 0.240320354700088500976562f0 c3 = 0.285112679004669189453125f0 c2 = 0.400007992982864379882812f0 c1 = Double(0.66666662693023681640625f0, 3.69183861259614332084311f-9) dadd2(dmul(x, @horner x.hi c2 c3 c4), c1) end @inline function logk(d::T) where {T<:Union{Float32,Float64}} o = d < floatmin(T) o && (d *= T(Int64(1) << 32) * T(Int64(1) << 32)) e = ilogb2k(d * T(1.0/0.75)) m = ldexp3k(d, -e) o && (e -= 64) x = ddiv(dsub2(m, T(1.0)), dadd2(T(1.0), m)) x2 = dsqu(x) t = logk_kernel(x2) s = dmul(MDLN2(T), T(e)) s = dadd(s, scale(x, T(2.0))) s = dadd(s, dmul(dmul(x2, x), t)) return s end
SLEEF
https://github.com/musm/SLEEF.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
21723
# exported trigonometric functions """ sin(x) Compute the sine of `x`, where the output is in radians. """ function sin end """ cos(x) Compute the cosine of `x`, where the output is in radians. """ function cos end @inline function sincos_kernel(x::Double{Float64}) c8 = 2.72052416138529567917983e-15 c7 = -7.64292594113954471900203e-13 c6 = 1.60589370117277896211623e-10 c5 = -2.5052106814843123359368e-08 c4 = 2.75573192104428224777379e-06 c3 = -0.000198412698412046454654947 c2 = 0.00833333333333318056201922 c1 = -0.166666666666666657414808 return dadd(c1, x.hi * (@horner x.hi c2 c3 c4 c5 c6 c7 c8)) end @inline function sincos_kernel(x::Double{Float32}) c4 = 2.6083159809786593541503f-06 c3 = -0.0001981069071916863322258f0 c2 = 0.00833307858556509017944336f0 c1 = -0.166666597127914428710938f0 return dadd(c1, x.hi * (@horner x.hi c2 c3 c4)) end function sin(d::T) where {T<:Float64} qh = trunc(d * (T(M_1_PI) / (1 << 24))) ql = round(d * T(M_1_PI) - qh * (1 << 24)) s = dadd2(d, qh * (-PI_A(T) * (1 << 24))) s = dadd2(s, ql * (-PI_A(T) )) s = dadd2(s, qh * (-PI_B(T) * (1 << 24))) s = dadd2(s, ql * (-PI_B(T) )) s = dadd2(s, qh * (-PI_C(T) * (1 << 24))) s = dadd2(s, ql * (-PI_C(T) )) s = dadd2(s, (qh * (1 << 24) + ql) * - PI_D(T)) t = s s = dsqu(s) w = sincos_kernel(s) v = dmul(t, dadd(T(1.0), dmul(w, s))) u = T(v) qli = unsafe_trunc(Int, ql) qli & 1 != 0 && (u = -u) !isinf(d) && (isnegzero(d) || abs(d) > TRIG_MAX(T)) && (u = T(-0.0)) return u end function sin(d::T) where {T<:Float32} q = round(d * T(M_1_PI)) s = dadd2(d, q * -PI_A(T)) s = dadd2(s, q * -PI_B(T)) s = dadd2(s, q * -PI_C(T)) s = dadd2(s, q * -PI_D(T)) t = s s = dsqu(s) w = sincos_kernel(s) v = dmul(t, dadd(T(1.0), dmul(w, s))) u = T(v) qi = unsafe_trunc(Int, q) qi & 1 != 0 && (u = -u) !isinf(d) && (isnegzero(d) || abs(d) > TRIG_MAX(T)) && (u = T(-0.0)) return u end function cos(d::T) where {T<:Float64} d = abs(d) qh = trunc(d * (T(M_1_PI) / (1 << 23)) - T(0.5) * (T(M_1_PI) / (1 << 23))) ql = 2*round(d * T(M_1_PI) - T(0.5) - qh * (1 << 23)) + 1 s = dadd2(d, qh * (-PI_A(T)* T(0.5) * (1 << 24))) s = dadd2(s, ql * (-PI_A(T)* T(0.5) )) s = dadd2(s, qh * (-PI_B(T)* T(0.5) * (1 << 24))) s = dadd2(s, ql * (-PI_B(T)* T(0.5) )) s = dadd2(s, qh * (-PI_C(T)* T(0.5) * (1 << 24))) s = dadd2(s, ql * (-PI_C(T)* T(0.5) )) s = dadd2(s, (qh * (1 << 24) + ql) * (-PI_D(T) * T(0.5))) t = s s = dsqu(s) w = sincos_kernel(s) v = dmul(t, dadd(T(1.0), dmul(w, s))) u = T(v) qli = unsafe_trunc(Int, ql) qli & 2 == 0 && (u = -u) !isinf(d) && (d > TRIG_MAX(T)) && (u = T(0.0)) return u end function cos(d::T) where {T<:Float32} d = abs(d) q = 1 + 2*round(d * T(M_1_PI) - T(0.5)) s = dadd2(d, q * -PI_A(T)* T(0.5)) s = dadd2(s, q * -PI_B(T)* T(0.5)) s = dadd2(s, q * -PI_C(T)* T(0.5)) s = dadd2(s, q * -PI_D(T)* T(0.5)) t = s s = dsqu(s) w = sincos_kernel(s) v = dmul(t, dadd(T(1.0), dmul(w, s))) u = T(v) qi = unsafe_trunc(Int, q) qi & 2 == 0 && (u = -u) !isinf(d) && (d > TRIG_MAX(T)) && (u = T(0.0)) return u end """ sin_fast(x) Compute the sine of `x`, where the output is in radians. """ function sin_fast end """ cos_fast(x) Compute the cosine of `x`, where the output is in radians. """ function cos_fast end # Argument is first reduced to the domain 0 < s < Ο€/4 # We return the correct sign using `q & 1 != 0` i.e. q is odd (this works for # positive and negative q) and if this condition is true we flip the sign since # we are now in the negative branch of sin(x). Recall that q is just the integer # part of d/Ο€ and thus we can determine the correct sign using this information. @inline function sincos_fast_kernel(x::Float64) c9 = -7.97255955009037868891952e-18 c8 = 2.81009972710863200091251e-15 c7 = -7.64712219118158833288484e-13 c6 = 1.60590430605664501629054e-10 c5 = -2.50521083763502045810755e-08 c4 = 2.75573192239198747630416e-06 c3 = -0.000198412698412696162806809 c2 = 0.00833333333333332974823815 c1 = -0.166666666666666657414808 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 c9 end @inline function sincos_fast_kernel(x::Float32) c4 = 2.6083159809786593541503f-06 c3 = -0.0001981069071916863322258f0 c2 = 0.00833307858556509017944336f0 c1 = -0.166666597127914428710938f0 return @horner x c1 c2 c3 c4 end function sin_fast(d::T) where {T<:Float64} t = d qh = trunc(d * (T(M_1_PI) / (1 << 24))) ql = round(d * T(M_1_PI) - qh * (1 << 24)) d = muladd(qh , -PI_A(T) * (1 << 24) , d) d = muladd(ql , -PI_A(T) , d) d = muladd(qh , -PI_B(T) * (1 << 24) , d) d = muladd(ql , -PI_B(T) , d) d = muladd(qh , -PI_C(T) * (1 << 24) , d) d = muladd(ql , -PI_C(T) , d) d = muladd(qh * (1 << 24) + ql, -PI_D(T), d) s = d * d qli = unsafe_trunc(Int, ql) qli & 1 != 0 && (d = -d) u = sincos_fast_kernel(s) u = muladd(s, u * d, d) !isinf(t) && (isnegzero(t) || abs(t) > TRIG_MAX(T)) && (u = T(-0.0)) return u end function sin_fast(d::T) where {T<:Float32} t = d q = round(d * T(M_1_PI)) d = muladd(q , -PI_A(T), d) d = muladd(q , -PI_B(T), d) d = muladd(q , -PI_C(T), d) d = muladd(q , -PI_D(T), d) s = d * d qli = unsafe_trunc(Int, q) qli & 1 != 0 && (d = -d) u = sincos_fast_kernel(s) u = muladd(s, u * d, d) !isinf(t) && (isnegzero(t) || abs(t) > TRIG_MAX(T)) && (u = T(-0.0)) return u end function cos_fast(d::T) where {T<:Float64} t = d qh = trunc(d * (T(M_1_PI) / (1 << 23)) - T(0.5) * (T(M_1_PI) / (1 << 23))) ql = 2*round(d * T(M_1_PI) - T(0.5) - qh * (1 << 23)) + 1 d = muladd(qh , -PI_A(T) * T(0.5) * (1 << 24) , d) d = muladd(ql , -PI_A(T) * T(0.5) , d) d = muladd(qh , -PI_B(T) * T(0.5) * (1 << 24) , d) d = muladd(ql , -PI_B(T) * T(0.5) , d) d = muladd(qh , -PI_C(T) * T(0.5) * (1 << 24) , d) d = muladd(ql , -PI_C(T) * T(0.5) , d) d = muladd(qh * (1 << 24) + ql, -PI_D(T) * T(0.5), d) s = d * d qli = unsafe_trunc(Int, ql) qli & 2 == 0 && (d = -d) u = sincos_fast_kernel(s) u = muladd(s, u * d, d) !isinf(t) && (abs(t) > TRIG_MAX(T)) && (u = T(0.0)) return u end function cos_fast(d::T) where {T<:Float32} t = d q = 1 + 2*round(d * T(M_1_PI) - T(0.5)) d = muladd(q, -PI_A(T) * T(0.5), d) d = muladd(q, -PI_B(T) * T(0.5), d) d = muladd(q, -PI_C(T) * T(0.5), d) d = muladd(q, -PI_D(T) * T(0.5), d) s = d * d qi = unsafe_trunc(Int, q) qi & 2 == 0 && (d = -d) u = sincos_fast_kernel(s) u = muladd(s, u * d, d) !isinf(t) && (abs(t) > TRIG_MAX(T)) && (u = T(0.0)) return u end """ sincos(x) Compute the sin and cosine of `x` simultaneously, where the output is in radians, returning a tuple. """ function sincos end """ sincos_fast(x) Compute the sin and cosine of `x` simultaneously, where the output is in radians, returning a tuple. """ function sincos_fast end @inline function sincos_a_kernel(x::Float64) a6 = 1.58938307283228937328511e-10 a5 = -2.50506943502539773349318e-08 a4 = 2.75573131776846360512547e-06 a3 = -0.000198412698278911770864914 a2 = 0.0083333333333191845961746 a1 = -0.166666666666666130709393 return @horner x a1 a2 a3 a4 a5 a6 end @inline function sincos_a_kernel(x::Float32) a3 = -0.000195169282960705459117889f0 a2 = 0.00833215750753879547119141f0 a1 = -0.166666537523269653320312f0 return @horner x a1 a2 a3 end @inline function sincos_b_kernel(x::Float64) b7 = -1.13615350239097429531523e-11 b6 = 2.08757471207040055479366e-09 b5 = -2.75573144028847567498567e-07 b4 = 2.48015872890001867311915e-05 b3 = -0.00138888888888714019282329 b2 = 0.0416666666666665519592062 b1 = -0.50 return @horner x b1 b2 b3 b4 b5 b6 b7 end @inline function sincos_b_kernel(x::Float32) b5 = -2.71811842367242206819355f-07 b4 = 2.47990446951007470488548f-05 b3 = -0.00138888787478208541870117f0 b2 = 0.0416666641831398010253906f0 b1 = -0.5f0 return @horner x b1 b2 b3 b4 b5 end function sincos_fast(d::T) where {T<:Float64} s = d qh = trunc(d * ((2 * T(M_1_PI)) / (1 << 24))) ql = round(d * (2 * T(M_1_PI)) - qh * (1 << 24)) s = muladd(qh, -PI_A(T) * T(0.5) * (1 << 24), s) s = muladd(ql, -PI_A(T) * T(0.5), s) s = muladd(qh, -PI_B(T) * T(0.5) * (1 << 24), s) s = muladd(ql, -PI_B(T) * T(0.5), s) s = muladd(qh, -PI_C(T) * T(0.5) * (1 << 24), s) s = muladd(ql, -PI_C(T) * T(0.5), s) s = muladd(qh * (1 << 24) + ql, -PI_D(T) * 0.5, s) t = s s = s * s u = sincos_a_kernel(s) u = u * s * t rx = t + u isnegzero(d) && (rx = T(-0.0)) u = sincos_b_kernel(s) ry = u * s + T(1.0) qli = unsafe_trunc(Int, ql) qli & 1 != 0 && (s = ry; ry = rx; rx = s) qli & 2 != 0 && (rx = -rx) (qli + 1) & 2 != 0 && (ry = -ry) abs(d) > TRIG_MAX(T) && (rx = ry = T(0.0)) isinf(d) && (rx = ry = T(NaN)) return (rx, ry) end function sincos_fast(d::T) where {T<:Float32} s = d q = round(d * (2 * T(M_1_PI))) s = muladd(q, -PI_A(T) * T(0.5), s) s = muladd(q, -PI_B(T) * T(0.5), s) s = muladd(q, -PI_C(T) * T(0.5), s) s = muladd(q, -PI_D(T) * T(0.5), s) t = s s = s * s u = sincos_a_kernel(s) u = u * s * t rx = t + u isnegzero(d) && (rx = T(-0.0)) u = sincos_b_kernel(s) ry = u * s + T(1.0) qi = unsafe_trunc(Int, q) qi & 1 != 0 && (s = ry; ry = rx; rx = s) qi & 2 != 0 && (rx = -rx) (qi + 1) & 2 != 0 && (ry = -ry) abs(d) > TRIG_MAX(T) && (rx = ry = T(0.0)) isinf(d) && (rx = ry = T(NaN)) return (rx, ry) end function sincos(d::T) where {T<:Float64} qh = trunc(d * ((2 * T(M_1_PI)) / (1 << 24))) ql = round(d * (2 * T(M_1_PI)) - qh * (1 << 24)) s = dadd2(d, qh * (-PI_A(T) * T(0.5) * (1 << 24))) s = dadd2(s, ql * (-PI_A(T) * T(0.5) )) s = dadd2(s, qh * (-PI_B(T) * T(0.5) * (1 << 24))) s = dadd2(s, ql * (-PI_B(T) * T(0.5) )) s = dadd2(s, qh * (-PI_C(T) * T(0.5) * (1 << 24))) s = dadd2(s, ql * (-PI_C(T) * T(0.5) )) s = dadd2(s, (qh * (1 << 24) + ql) * (-PI_D(T) * T(0.5))) t = s s = dsqu(s) sx = T(s) u = sincos_a_kernel(sx) u *= sx * t.hi v = dadd(t, u) rx = T(v) isnegzero(d) && (rx = T(-0.0)) u = sincos_b_kernel(sx) v = dadd(T(1.0), dmul(sx, u)) ry = T(v) qli = unsafe_trunc(Int, ql) qli & 1 != 0 && (u = ry; ry = rx; rx = u) qli & 2 != 0 && (rx = -rx) (qli + 1) & 2 != 0 && (ry = -ry) abs(d) > TRIG_MAX(T) && (rx = ry = T(0.0)) isinf(d) && (rx = ry = T(NaN)) return (rx, ry) end function sincos(d::T) where {T<:Float32} q = round(d * (2 * T(M_1_PI))) s = dadd2(d, q * (-PI_A(T) * T(0.5))) s = dadd2(s, q * (-PI_B(T) * T(0.5))) s = dadd2(s, q * (-PI_C(T) * T(0.5))) s = dadd2(s, q * (-PI_D(T) * T(0.5))) t = s s = dsqu(s) sx = T(s) u = sincos_a_kernel(sx) u *= sx * t.hi v = dadd(t, u) rx = T(v) isnegzero(d) && (rx = T(-0.0)) u = sincos_b_kernel(sx) v = dadd(T(1.0), dmul(sx, u)) ry = T(v) qi = unsafe_trunc(Int, q) qi & 1 != 0 && (u = ry; ry = rx; rx = u) qi & 2 != 0 && (rx = -rx) (qi + 1) & 2 != 0 && (ry = -ry) abs(d) > TRIG_MAX(T) && (rx = ry = T(0.0)) isinf(d) && (rx = ry = T(NaN)) return (rx, ry) end """ tan(x) Compute the tangent of `x`, where the output is in radians. """ function tan end """ tan_fast(x) Compute the tangent of `x`, where the output is in radians. """ function tan_fast end @inline function tan_fast_kernel(x::Float64) c16 = 9.99583485362149960784268e-06 c15 = -4.31184585467324750724175e-05 c14 = 0.000103573238391744000389851 c13 = -0.000137892809714281708733524 c12 = 0.000157624358465342784274554 c11 = -6.07500301486087879295969e-05 c10 = 0.000148898734751616411290179 c9 = 0.000219040550724571513561967 c8 = 0.000595799595197098359744547 c7 = 0.00145461240472358871965441 c6 = 0.0035923150771440177410343 c5 = 0.00886321546662684547901456 c4 = 0.0218694899718446938985394 c3 = 0.0539682539049961967903002 c2 = 0.133333333334818976423364 c1 = 0.333333333333320047664472 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 end @inline function tan_fast_kernel(x::Float32) c7 = 0.00446636462584137916564941f0 c6 = -8.3920182078145444393158f-05 c5 = 0.0109639242291450500488281f0 c4 = 0.0212360303848981857299805f0 c3 = 0.0540687143802642822265625f0 c2 = 0.133325666189193725585938f0 c1 = 0.33333361148834228515625f0 return @horner x c1 c2 c3 c4 c5 c6 c7 end function tan_fast(d::T) where {T<:Float64} qh = trunc(d * (2 * T(M_1_PI)) / (1 << 24)) ql = round(d * (2 * T(M_1_PI)) - qh * (1 << 24)) x = muladd(qh, -PI_A(T) * T(0.5) * (1 << 24), d) x = muladd(ql, -PI_A(T) * T(0.5), x) x = muladd(qh, -PI_B(T) * T(0.5) * (1 << 24), x) x = muladd(ql, -PI_B(T) * T(0.5), x) x = muladd(qh, -PI_C(T) * T(0.5) * (1 << 24), x) x = muladd(ql, -PI_C(T) * T(0.5), x) x = muladd(qh * (1 << 24) + ql, -PI_D(T) * T(0.5), x) s = x * x qli = unsafe_trunc(Int, ql) qli & 1 != 0 && (x = -x) u = tan_fast_kernel(s) u = muladd(s, u * x, x) qli & 1 != 0 && (u = T(1.0) / u) !isinf(d) && (isnegzero(d) || abs(d) > TRIG_MAX(T)) && (u = T(-0.0)) return u end function tan_fast(d::T) where {T<:Float32} q = round(d * (2 * T(M_1_PI))) x = d x = muladd(q, -PI_A(T) * T(0.5), x) x = muladd(q, -PI_B(T) * T(0.5), x) x = muladd(q, -PI_C(T) * T(0.5), x) x = muladd(q, -PI_D(T) * T(0.5), x) s = x * x qi = unsafe_trunc(Int, q) qi & 1 != 0 && (x = -x) u = tan_fast_kernel(s) u = muladd(s, u * x, x) qi & 1 != 0 && (u = T(1.0) / u) !isinf(d) && (isnegzero(d) || abs(d) > TRIG_MAX(T)) && (u = T(-0.0)) return u end @inline function tan_kernel(x::Double{Float64}) c15 = 1.01419718511083373224408e-05 c14 = -2.59519791585924697698614e-05 c13 = 5.23388081915899855325186e-05 c12 = -3.05033014433946488225616e-05 c11 = 7.14707504084242744267497e-05 c10 = 8.09674518280159187045078e-05 c9 = 0.000244884931879331847054404 c8 = 0.000588505168743587154904506 c7 = 0.00145612788922812427978848 c6 = 0.00359208743836906619142924 c5 = 0.00886323944362401618113356 c4 = 0.0218694882853846389592078 c3 = 0.0539682539781298417636002 c2 = 0.133333333333125941821962 c1 = 0.333333333333334980164153 return dadd(c1, x.hi * (@horner x.hi c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15)) end @inline function tan_kernel(x::Double{Float32}) c7 = 0.00446636462584137916564941f0 c6 = -8.3920182078145444393158f-05 c5 = 0.0109639242291450500488281f0 c4 = 0.0212360303848981857299805f0 c3 = 0.0540687143802642822265625f0 c2 = 0.133325666189193725585938f0 c1 = 0.33333361148834228515625f0 return dadd(c1, x.hi * (@horner x.hi c2 c3 c4 c5 c6 c7)) end function tan(d::T) where {T<:Float64} qh = trunc(d * (T(M_2_PI)) / (1 << 24)) s = dadd2(dmul(Double(T(M_2_PI_H), T(M_2_PI_L)), d), (d < 0 ? T(-0.5) : T(0.5)) - qh * (1 << 24)) ql = trunc(T(s)) s = dadd2(d, qh * (-PI_A(T) * T(0.5) * (1 << 24))) s = dadd2(s, ql * (-PI_A(T) * T(0.5) )) s = dadd2(s, qh * (-PI_B(T) * T(0.5) * (1 << 24))) s = dadd2(s, ql * (-PI_B(T) * T(0.5) )) s = dadd2(s, qh * (-PI_C(T) * T(0.5) * (1 << 24))) s = dadd2(s, ql * (-PI_C(T) * T(0.5) )) s = dadd2(s, (qh * (1 << 24) + ql) * (-PI_D(T) * T(0.5))) qli = unsafe_trunc(Int, ql) qli & 1 != 0 && (s = -s) t = s s = dsqu(s) u = tan_kernel(s) x = dadd(T(1.0), dmul(u, s)) x = dmul(t, x) qli & 1 != 0 && (x = drec(x)) v = T(x) !isinf(d) && (isnegzero(d) || abs(d) > TRIG_MAX(T)) && (v = T(-0.0)) return v end function tan(d::T) where {T<:Float32} q = round(d * (T(M_2_PI))) s = dadd2(d, q * -PI_A(T) * T(0.5)) s = dadd2(s, q * -PI_B(T) * T(0.5)) s = dadd2(s, q * -PI_C(T) * T(0.5)) s = dadd2(s, q * -PI_XD(T) * T(0.5)) s = dadd2(s, q * -PI_XE(T) * T(0.5)) qi = unsafe_trunc(Int, q) qi & 1 != 0 && (s = -s) t = s s = dsqu(s) s = dnormalize(s) u = tan_kernel(s) x = dadd(T(1.0), dmul(u, s)) x = dmul(t, x) qi & 1 != 0 && (x = drec(x)) v = T(x) !isinf(d) && (isnegzero(d) || abs(d) > TRIG_MAX(T)) && (v = T(-0.0)) return v end """ atan(x) Compute the inverse tangent of `x`, where the output is in radians. """ function atan(x::T) where {T<:Union{Float32,Float64}} u = T(atan2k(Double(abs(x)), Double(T(1)))) isinf(x) && (u = T(PI_2)) flipsign(u, x) end @inline function atan_fast_kernel(x::Float64) c19 = -1.88796008463073496563746e-05 c18 = 0.000209850076645816976906797 c17 = -0.00110611831486672482563471 c16 = 0.00370026744188713119232403 c15 = -0.00889896195887655491740809 c14 = 0.016599329773529201970117 c13 = -0.0254517624932312641616861 c12 = 0.0337852580001353069993897 c11 = -0.0407629191276836500001934 c10 = 0.0466667150077840625632675 c9 = -0.0523674852303482457616113 c8 = 0.0587666392926673580854313 c7 = -0.0666573579361080525984562 c6 = 0.0769219538311769618355029 c5 = -0.090908995008245008229153 c4 = 0.111111105648261418443745 c3 = -0.14285714266771329383765 c2 = 0.199999999996591265594148 c1 = -0.333333333333311110369124 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 c17 c18 c19 end @inline function atan_fast_kernel(x::Float32) c8 = 0.00282363896258175373077393f0 c7 = -0.0159569028764963150024414f0 c6 = 0.0425049886107444763183594f0 c5 = -0.0748900920152664184570312f0 c4 = 0.106347933411598205566406f0 c3 = -0.142027363181114196777344f0 c2 = 0.199926957488059997558594f0 c1 = -0.333331018686294555664062f0 return @horner x c1 c2 c3 c4 c5 c6 c7 c8 end """ atan_fast(x) Compute the inverse tangent of `x`, where the output is in radians. """ function atan_fast(x::T) where {T<:Union{Float32,Float64}} q = 0 if signbit(x) x = -x q = 2 end if x > 1 x = 1 / x q |= 1 end t = x * x u = atan_fast_kernel(t) t = x + x * t * u q & 1 != 0 && (t = T(PI_2) - t) q & 2 != 0 && (t = -t) return t end const under_atan2(::Type{Float64}) = 5.5626846462680083984e-309 const under_atan2(::Type{Float32}) = 2.9387372783541830947f-39 """ atan(x, y) Compute the inverse tangent of `x/y`, using the signs of both `x` and `y` to determine the quadrant of the return value. """ function atan(x::T, y::T) where {T<:Union{Float32,Float64}} abs(y) < under_atan2(T) && (x *= T(Int64(1) << 53); y *= T(Int64(1) << 53)) r = T(atan2k(Double(abs(x)), Double(y))) r = flipsign(r, y) if isinf(y) || y == 0 r = T(PI_2) - (isinf(y) ? _sign(y) * T(PI_2) : T(0.0)) end if isinf(x) r = T(PI_2) - (isinf(y) ? _sign(y) * T(PI_4) : T(0.0)) end if x == 0 r = _sign(y) == -1 ? T(M_PI) : T(0.0) end return isnan(y) || isnan(x) ? T(NaN) : flipsign(r, x) end """ atan2_fast(x, y) Compute the inverse tangent of `x/y`, using the signs of both `x` and `y` to determine the quadrant of the return value. """ function atan_fast(x::T, y::T) where {T<:Union{Float32,Float64}} r = atan2k_fast(abs(x), y) r = flipsign(r, y) if isinf(y) || y == 0 r = T(PI_2) - (isinf(y) ? _sign(y) * T(PI_2) : T(0)) end if isinf(x) r = T(PI_2) - (isinf(y) ? _sign(y) * T(PI_4) : T(0)) end if x == 0 r = _sign(y) == -1 ? T(M_PI) : T(0) end return isnan(y) || isnan(x) ? T(NaN) : flipsign(r, x) end """ asin(x) Compute the inverse sine of `x`, where the output is in radians. """ function asin(x::T) where {T<:Union{Float32,Float64}} d = atan2k(Double(abs(x)), dsqrt(dmul(dadd(T(1), x), dsub(T(1), x)))) u = T(d) abs(x) == 1 && (u = T(PI_2)) flipsign(u, x) end """ asin_fast(x) Compute the inverse sine of `x`, where the output is in radians. """ function asin_fast(x::T) where {T<:Union{Float32,Float64}} flipsign(atan2k_fast(abs(x), _sqrt((1 + x) * (1 - x))), x) end """ acos(x) Compute the inverse cosine of `x`, where the output is in radians. """ function acos(x::T) where {T<:Union{Float32,Float64}} d = atan2k(dsqrt(dmul(dadd(T(1), x), dsub(T(1), x))), Double(abs(x))) d = flipsign(d, x) abs(x) == 1 && (d = Double(T(0))) signbit(x) && (d = dadd(MDPI(T), d)) return T(d) end """ acos_fast(x) Compute the inverse cosine of `x`, where the output is in radians. """ function acos_fast(x::T) where {T<:Union{Float32,Float64}} flipsign(atan2k_fast(_sqrt((1 + x) * (1 - x)), abs(x)), x) + (signbit(x) ? T(M_PI) : T(0)) end
SLEEF
https://github.com/musm/SLEEF.jl.git
[ "MIT" ]
0.5.2
512b75d09aab52e93192e68de612fc472f001979
code
1449
## utility functions mainly used by the private math functions in priv.jl function is_fma_fast end for T in (Float32, Float64) @eval is_fma_fast(::Type{$T}) = $(muladd(nextfloat(one(T)), nextfloat(one(T)), -nextfloat(one(T), 2)) != zero(T)) end const FMA_FAST = is_fma_fast(Float64) && is_fma_fast(Float32) @inline isnegzero(x::T) where {T<:AbstractFloat} = x === T(-0.0) @inline ispinf(x::T) where {T<:AbstractFloat} = x == T(Inf) @inline isninf(x::T) where {T<:AbstractFloat} = x == T(-Inf) # _sign emits better native code than sign but does not properly handle the Inf/NaN cases @inline _sign(d::T) where {T<:AbstractFloat} = flipsign(one(T), d) @inline integer2float(::Type{Float64}, m::Int) = reinterpret(Float64, (m % Int64) << significand_bits(Float64)) @inline integer2float(::Type{Float32}, m::Int) = reinterpret(Float32, (m % Int32) << significand_bits(Float32)) @inline float2integer(d::Float64) = (reinterpret(Int64, d) >> significand_bits(Float64)) % Int @inline float2integer(d::Float32) = (reinterpret(Int32, d) >> significand_bits(Float32)) % Int @inline pow2i(::Type{T}, q::Int) where {T<:Union{Float32,Float64}} = integer2float(T, q + exponent_bias(T)) # sqrt without the domain checks which we don't need since we handle the checks ourselves if VERSION < v"0.7-" _sqrt(x::T) where {T<:Union{Float32,Float64}} = Base.sqrt_llvm_fast(x) else _sqrt(x::T) where {T<:Union{Float32,Float64}} = Base.sqrt_llvm(x) end
SLEEF
https://github.com/musm/SLEEF.jl.git