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
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
code
903
function get_bit(word::Unsigned, word_length::Int, bit_number::Int) Bool(get_bits(word, word_length, bit_number, 1)) end function get_bits(word::T, word_length::Int, start::Int, length::Int) where {T<:Unsigned} T((word >> (word_length - start - length + 1)) & (T(1) << length - T(1))) end function get_twos_complement_num(word::Unsigned, word_length::Int, start::Int, length::Int) value = UInt(get_bits(word, word_length, start, length)) num_shift_bits = sizeof(value) * 8 - length signed(value << num_shift_bits) >> num_shift_bits end function deinterleave(bits::String, columns, rows) String(vec(permutedims(reshape(collect(bits), columns, rows)))) end function invert_every_second_bit(bits::String) reshaped_bits = reshape(collect(bits), 2, length(bits) >> 1) reshaped_bits[2, :] .= ifelse.(reshaped_bits[2, :] .== '1', '0', '1') String(vec(reshaped_bits)) end
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
code
14478
# UInt288 buffer for Galileo E1B # which holds at least a complete Galileo E1B page # plus 10 extra syncronization bits BitIntegers.@define_integers 288 Base.@kwdef struct GalileoE1BConstants <: AbstractGNSSConstants syncro_sequence_length::Int = 250 preamble::UInt16 = 0b0101100000 preamble_length::Int = 10 PI::Float64 = 3.1415926535898 Ω_dot_e::Float64 = 7.2921151467e-5 c::Float64 = 2.99792458e8 μ::Float64 = 3.986004418e14 F::Float64 = -4.442807309e-10 end # Page is splitted in even and odd parts # Cache even part and decode after odd part # Page contains 120 bits struct GalileoE1BCache <: AbstractGNSSCache even_page_part_bits::UInt128 end GalileoE1BCache() = GalileoE1BCache(UInt128(0)) @enum SignalHealth begin signal_ok signal_out_of_service signal_will_be_out_of_service signal_component_currently_in_test end @enum DataValidityStatus begin navigation_data_valid working_without_guarantee end Base.@kwdef struct GalileoE1BData <: AbstractGNSSData WN::Union{Nothing,Int64} = nothing TOW::Union{Nothing,Int64} = nothing t_0e::Union{Nothing,Float64} = nothing M_0::Union{Nothing,Float64} = nothing e::Union{Nothing,Float64} = nothing sqrt_A::Union{Nothing,Float64} = nothing Ω_0::Union{Nothing,Float64} = nothing i_0::Union{Nothing,Float64} = nothing ω::Union{Nothing,Float64} = nothing i_dot::Union{Nothing,Float64} = nothing Ω_dot::Union{Nothing,Float64} = nothing Δn::Union{Nothing,Float64} = nothing C_uc::Union{Nothing,Float64} = nothing C_us::Union{Nothing,Float64} = nothing C_rc::Union{Nothing,Float64} = nothing C_rs::Union{Nothing,Float64} = nothing C_ic::Union{Nothing,Float64} = nothing C_is::Union{Nothing,Float64} = nothing t_0c::Union{Nothing,Float64} = nothing a_f0::Union{Nothing,Float64} = nothing a_f1::Union{Nothing,Float64} = nothing a_f2::Union{Nothing,Float64} = nothing IOD_nav1::Union{Nothing,UInt} = nothing IOD_nav2::Union{Nothing,UInt} = nothing IOD_nav3::Union{Nothing,UInt} = nothing IOD_nav4::Union{Nothing,UInt} = nothing num_pages_after_last_TOW::Int = 0 signal_health_e1b::Union{Nothing,SignalHealth} = nothing signal_health_e5b::Union{Nothing,SignalHealth} = nothing data_validity_status_e1b::Union{Nothing,DataValidityStatus} = nothing data_validity_status_e5b::Union{Nothing,DataValidityStatus} = nothing broadcast_group_delay_e1_e5a::Union{Nothing,Float64} = nothing broadcast_group_delay_e1_e5b::Union{Nothing,Float64} = nothing end function GalileoE1BData( data::GalileoE1BData; WN = data.WN, TOW = data.TOW, t_0e = data.t_0e, M_0 = data.M_0, e = data.e, sqrt_A = data.sqrt_A, Ω_0 = data.Ω_0, i_0 = data.i_0, ω = data.ω, i_dot = data.i_dot, Ω_dot = data.Ω_dot, Δn = data.Δn, C_uc = data.C_uc, C_us = data.C_us, C_rc = data.C_rc, C_rs = data.C_rs, C_ic = data.C_ic, C_is = data.C_is, t_0c = data.t_0c, a_f0 = data.a_f0, a_f1 = data.a_f1, a_f2 = data.a_f2, IOD_nav1 = data.IOD_nav1, IOD_nav2 = data.IOD_nav2, IOD_nav3 = data.IOD_nav3, IOD_nav4 = data.IOD_nav4, num_pages_after_last_TOW = data.num_pages_after_last_TOW, signal_health_e1b = data.signal_health_e1b, signal_health_e5b = data.signal_health_e5b, data_validity_status_e1b = data.data_validity_status_e1b, data_validity_status_e5b = data.data_validity_status_e5b, broadcast_group_delay_e1_e5a = data.broadcast_group_delay_e1_e5a, broadcast_group_delay_e1_e5b = data.broadcast_group_delay_e1_e5b, ) GalileoE1BData( WN, TOW, t_0e, M_0, e, sqrt_A, Ω_0, i_0, ω, i_dot, Ω_dot, Δn, C_uc, C_us, C_rc, C_rs, C_ic, C_is, t_0c, a_f0, a_f1, a_f2, IOD_nav1, IOD_nav2, IOD_nav3, IOD_nav4, num_pages_after_last_TOW, signal_health_e1b, signal_health_e5b, data_validity_status_e1b, data_validity_status_e5b, broadcast_group_delay_e1_e5a, broadcast_group_delay_e1_e5b, ) end function is_ephemeris_decoded(data::GalileoE1BData) !isnothing(data.t_0e) && !isnothing(data.M_0) && !isnothing(data.e) && !isnothing(data.sqrt_A) && !isnothing(data.Ω_0) && !isnothing(data.i_0) && !isnothing(data.ω) && !isnothing(data.i_dot) && !isnothing(data.Ω_dot) && !isnothing(data.Δn) && !isnothing(data.C_uc) && !isnothing(data.C_us) && !isnothing(data.C_rc) && !isnothing(data.C_rs) && !isnothing(data.C_ic) && !isnothing(data.C_is) end function is_clock_correction_decoded(data::GalileoE1BData) !isnothing(data.t_0c) && !isnothing(data.a_f0) && !isnothing(data.a_f1) && !isnothing(data.a_f2) end function is_health_status_decoded(data::GalileoE1BData) !isnothing(data.signal_health_e1b) && !isnothing(data.signal_health_e5b) && !isnothing(data.data_validity_status_e1b) && !isnothing(data.data_validity_status_e5b) end function is_decoding_completed_for_positioning(data::GalileoE1BData) !isnothing(data.TOW) && !isnothing(data.WN) && !isnothing(data.broadcast_group_delay_e1_e5a) && !isnothing(data.broadcast_group_delay_e1_e5b) && is_ephemeris_decoded(data) && is_clock_correction_decoded(data) && is_health_status_decoded(data) end function GalileoE1BDecoderState(prn) GNSSDecoderState( prn, UInt288(0), UInt288(0), GalileoE1BData(), GalileoE1BData(), GalileoE1BConstants(), GalileoE1BCache(), 0, nothing, false, ) end function GNSSDecoderState(system::GalileoE1B, prn) GNSSDecoderState( prn, UInt288(0), UInt288(0), GalileoE1BData(), GalileoE1BData(), GalileoE1BConstants(), GalileoE1BCache(), 0, nothing, false, ) end function decode_syncro_sequence(state::GNSSDecoderState{<:GalileoE1BData}) encoded_bits = bitstring(state.buffer >> state.constants.preamble_length)[sizeof( state.buffer, )*8-state.constants.syncro_sequence_length+state.constants.preamble_length+1:end] deinterleaved_encoded_bits = deinterleave(encoded_bits, 30, 8) inv_deinterleaved_encoded_bits = invert_every_second_bit(deinterleaved_encoded_bits) decoded_bits = viterbi_decode(7, [79, 109], inv_deinterleaved_encoded_bits) bits = parse(UInt128, decoded_bits; base = 2) is_even = !get_bit(bits, 114, 1) is_nominal_page = !get_bit(bits, 114, 2) state = GNSSDecoderState( state; raw_data = GalileoE1BData( state.raw_data; num_pages_after_last_TOW = state.raw_data.num_pages_after_last_TOW + 1, ), ) if is_even state = GNSSDecoderState( state; cache = GalileoE1BCache(is_nominal_page ? bits : UInt128(0)), ) elseif state.cache.even_page_part_bits != 0 && is_nominal_page data = get_bits(state.cache.even_page_part_bits, 114, 3, 112) << 16 + get_bits(bits, 114, 3, 16) bits_to_check_CRC = UInt288(state.cache.even_page_part_bits) << 106 + get_bits(bits, 114, 1, 106) if galCRC24(reverse(digits(UInt8, bits_to_check_CRC; base = 256))) == 0 data_type = get_bits(data, 128, 1, 6) if data_type == 0 if get_bits(data, 128, 7, 2) == 2 # '10' WN = get_bits(data, 128, 97, 12) TOW = get_bits(data, 128, 109, 20) state = GNSSDecoderState( state; raw_data = GalileoE1BData( state.raw_data; WN, TOW, num_pages_after_last_TOW = 1, ), ) end elseif data_type == 1 IOD_nav1 = get_bits(data, 128, 7, 10) t_0e = get_bits(data, 128, 17, 14) * 60 M_0 = get_twos_complement_num(data, 128, 31, 32) * state.constants.PI / 1 << 31 e = get_bits(data, 128, 63, 32) / 1 << 33 sqrt_A = get_bits(data, 128, 95, 32) / 1 << 19 state = GNSSDecoderState( state; raw_data = GalileoE1BData( state.raw_data; IOD_nav1, t_0e, M_0, e, sqrt_A, ), ) elseif data_type == 2 IOD_nav2 = get_bits(data, 128, 7, 10) Ω_0 = get_twos_complement_num(data, 128, 17, 32) * state.constants.PI / 1 << 31 i_0 = get_twos_complement_num(data, 128, 49, 32) * state.constants.PI / 1 << 31 ω = get_twos_complement_num(data, 128, 81, 32) * state.constants.PI / 1 << 31 i_dot = get_twos_complement_num(data, 128, 113, 14) * state.constants.PI / 1 << 43 state = GNSSDecoderState( state; raw_data = GalileoE1BData(state.raw_data; IOD_nav2, Ω_0, i_0, ω, i_dot), ) elseif data_type == 3 IOD_nav3 = get_bits(data, 128, 7, 10) Ω_dot = get_twos_complement_num(data, 128, 17, 24) * state.constants.PI / 1 << 43 Δn = get_twos_complement_num(data, 128, 41, 16) * state.constants.PI / 1 << 43 C_uc = get_twos_complement_num(data, 128, 57, 16) / 1 << 29 C_us = get_twos_complement_num(data, 128, 73, 16) / 1 << 29 C_rc = get_twos_complement_num(data, 128, 89, 16) / 1 << 5 C_rs = get_twos_complement_num(data, 128, 105, 16) / 1 << 5 state = GNSSDecoderState( state; raw_data = GalileoE1BData( state.raw_data; IOD_nav3, Ω_dot, Δn, C_uc, C_us, C_rc, C_rs, ), ) elseif data_type == 4 IOD_nav4 = get_bits(data, 128, 7, 10) C_ic = get_twos_complement_num(data, 128, 23, 16) / 1 << 29 C_is = get_twos_complement_num(data, 128, 39, 16) / 1 << 29 t_0c = get_bits(data, 128, 55, 14) * 60 a_f0 = get_twos_complement_num(data, 128, 69, 31) / 1 << 34 a_f1 = get_twos_complement_num(data, 128, 100, 21) / 1 << 46 a_f2 = get_twos_complement_num(data, 128, 121, 6) / 1 << 59 state = GNSSDecoderState( state; raw_data = GalileoE1BData( state.raw_data; IOD_nav4, C_ic, C_is, t_0c, a_f0, a_f1, a_f2, ), ) elseif data_type == 5 broadcast_group_delay_e1_e5a = get_twos_complement_num(data, 128, 48, 10) / 1 << 32 broadcast_group_delay_e1_e5b = get_twos_complement_num(data, 128, 58, 10) / 1 << 32 signal_health_e5b = SignalHealth(get_bits(data, 128, 68, 2)) signal_health_e1b = SignalHealth(get_bits(data, 128, 70, 2)) data_validity_status_e5b = DataValidityStatus(get_bit(data, 128, 72)) data_validity_status_e1b = DataValidityStatus(get_bit(data, 128, 73)) WN = get_bits(data, 128, 74, 12) TOW = get_bits(data, 128, 86, 20) state = GNSSDecoderState( state; raw_data = GalileoE1BData( state.raw_data; broadcast_group_delay_e1_e5a, broadcast_group_delay_e1_e5b, signal_health_e5b, signal_health_e1b, data_validity_status_e5b, data_validity_status_e1b, WN, TOW, num_pages_after_last_TOW = 1, ), ) elseif data_type == 6 TOW = get_bits(data, 128, 106, 20) state = GNSSDecoderState( state; raw_data = GalileoE1BData( state.raw_data; TOW, num_pages_after_last_TOW = 1, ), ) end end end return state end function validate_data(state::GNSSDecoderState{<:GalileoE1BData}) if is_decoding_completed_for_positioning(state.raw_data) && state.raw_data.IOD_nav1 == state.raw_data.IOD_nav2 == state.raw_data.IOD_nav3 == state.raw_data.IOD_nav4 state = GNSSDecoderState( state; data = state.raw_data, num_bits_after_valid_syncro_sequence = state.data.TOW == state.raw_data.TOW ? state.num_bits_after_valid_syncro_sequence : 10 + ( state.raw_data.num_pages_after_last_TOW + 1 ) * 250, ) end return state end function is_sat_healthy(state::GNSSDecoderState{<:GalileoE1BData}) state.data.signal_health_e1b == signal_ok && state.data.data_validity_status_e1b == navigation_data_valid end
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
code
3905
abstract type AbstractGNSSConstants end abstract type AbstractGNSSData end abstract type AbstractGNSSCache end Base.@kwdef struct GNSSDecoderState{ D<:AbstractGNSSData, C<:AbstractGNSSConstants, CA<:AbstractGNSSCache, B<:Unsigned, } prn::Int raw_buffer::B buffer::B raw_data::D data::D constants::C cache::CA num_bits_buffered::Int = 0 num_bits_after_valid_syncro_sequence::Union{Nothing,Int} = 0 is_shifted_by_180_degrees = false end function GNSSDecoderState( state::GNSSDecoderState; raw_buffer = state.raw_buffer, buffer = state.buffer, raw_data = state.raw_data, data = state.data, cache = state.cache, num_bits_buffered = state.num_bits_buffered, num_bits_after_valid_syncro_sequence = state.num_bits_after_valid_syncro_sequence, is_shifted_by_180_degrees = state.is_shifted_by_180_degrees, ) GNSSDecoderState( state.prn, raw_buffer, buffer, raw_data, data, state.constants, cache, num_bits_buffered, num_bits_after_valid_syncro_sequence, is_shifted_by_180_degrees, ) end function push_bit(state::GNSSDecoderState, current_bit) GNSSDecoderState( state; raw_buffer = state.raw_buffer << true + (current_bit > 0), num_bits_buffered = min(state.num_bits_buffered + 1, sizeof(state.raw_buffer) * 8), ) end function is_enough_buffered_bits_to_decode(state::GNSSDecoderState) state.num_bits_buffered >= state.constants.syncro_sequence_length + state.constants.preamble_length end calc_preamble_mask(state::GNSSDecoderState) = UInt(1) << UInt(state.constants.preamble_length) - UInt(1) function find_preamble(state::GNSSDecoderState) state.raw_buffer & calc_preamble_mask(state) == state.constants.preamble && (state.raw_buffer >> state.constants.syncro_sequence_length) & calc_preamble_mask(state) == state.constants.preamble || state.raw_buffer & calc_preamble_mask(state) == ~state.constants.preamble & calc_preamble_mask(state) && (state.raw_buffer >> state.constants.syncro_sequence_length) & calc_preamble_mask(state) == ~state.constants.preamble & calc_preamble_mask(state) end function complement_buffer_if_necessary(state::GNSSDecoderState) if state.raw_buffer & calc_preamble_mask(state) == ~state.constants.preamble & calc_preamble_mask(state) return GNSSDecoderState( state; buffer = ~state.raw_buffer, is_shifted_by_180_degrees = true, ) else return GNSSDecoderState( state; buffer = state.raw_buffer, is_shifted_by_180_degrees = false, ) end end function decode( state::GNSSDecoderState, bits::T, num_bits::Int; decode_once::Bool = false, ) where {T<:Unsigned} num_bits > sizeof(bits) * 8 || ArgumentError("Number of bits is too large to fit type of bits") for i = num_bits-1:-1:0 current_bit = bits & (T(1) << i) state = push_bit(state, current_bit) if !isnothing(state.num_bits_after_valid_syncro_sequence) state = GNSSDecoderState( state; num_bits_after_valid_syncro_sequence = state.num_bits_after_valid_syncro_sequence + 1, ) end if is_enough_buffered_bits_to_decode(state) && find_preamble(state) state = decode_syncro_sequence(complement_buffer_if_necessary(state)) if !decode_once || !is_decoding_completed_for_positioning(state.data) state = validate_data(state) end state = GNSSDecoderState(state; num_bits_buffered = state.constants.preamble_length) end end return state end
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
code
18785
# UInt320 buffer for GPS L1 (more efficient than UInt312) # which holds at least a complete GPS L1 subframe plus # 8 extra syncronization bíts BitIntegers.@define_integers 320 Base.@kwdef struct GPSL1Constants <: AbstractGNSSConstants syncro_sequence_length::Int = 300 preamble::UInt8 = 0b10001011 preamble_length::Int = 8 word_length::Int = 30 PI::Float64 = 3.1415926535898 Ω_dot_e::Float64 = 7.2921151467e-5 c::Float64 = 2.99792458e8 μ::Float64 = 3.986005e14 F::Float64 = -4.442807633e-10 end struct GPSL1Cache <: AbstractGNSSCache end Base.@kwdef struct GPSL1Data <: AbstractGNSSData last_subframe_id::Int = 0 integrity_status_flag::Union{Nothing,Bool} = nothing TOW::Union{Nothing,Int64} = nothing alert_flag::Union{Nothing,Bool} = nothing anti_spoof_flag::Union{Nothing,Bool} = nothing trans_week::Union{Nothing,Int64} = nothing codeonl2::Union{Nothing,Int64} = nothing ura::Union{Nothing,Float64} = nothing svhealth::Union{Nothing,String} = nothing IODC::Union{Nothing,String} = nothing l2pcode::Union{Nothing,Bool} = nothing T_GD::Union{Nothing,Float64} = nothing t_0c::Union{Nothing,Int64} = nothing a_f2::Union{Nothing,Float64} = nothing a_f1::Union{Nothing,Float64} = nothing a_f0::Union{Nothing,Float64} = nothing IODE_Sub_2::Union{Nothing,String} = nothing C_rs::Union{Nothing,Float64} = nothing Δn::Union{Nothing,Float64} = nothing M_0::Union{Nothing,Float64} = nothing C_uc::Union{Nothing,Float64} = nothing e::Union{Nothing,Float64} = nothing C_us::Union{Nothing,Float64} = nothing sqrt_A::Union{Nothing,Float64} = nothing t_0e::Union{Nothing,Int64} = nothing fit_interval::Union{Nothing,Bool} = nothing AODO::Union{Nothing,Int64} = nothing C_ic::Union{Nothing,Float64} = nothing Ω_0::Union{Nothing,Float64} = nothing C_is::Union{Nothing,Float64} = nothing i_0::Union{Nothing,Float64} = nothing C_rc::Union{Nothing,Float64} = nothing ω::Union{Nothing,Float64} = nothing Ω_dot::Union{Nothing,Float64} = nothing IODE_Sub_3::Union{Nothing,String} = nothing i_dot::Union{Nothing,Float64} = nothing end function GPSL1Data( data::GPSL1Data; last_subframe_id = data.last_subframe_id, integrity_status_flag = data.integrity_status_flag, TOW = data.TOW, alert_flag = data.alert_flag, anti_spoof_flag = data.anti_spoof_flag, trans_week = data.trans_week, codeonl2 = data.codeonl2, ura = data.ura, svhealth = data.svhealth, IODC = data.IODC, l2pcode = data.l2pcode, T_GD = data.T_GD, t_0c = data.t_0c, a_f2 = data.a_f2, a_f1 = data.a_f1, a_f0 = data.a_f0, IODE_Sub_2 = data.IODE_Sub_2, C_rs = data.C_rs, Δn = data.Δn, M_0 = data.M_0, C_uc = data.C_uc, e = data.e, C_us = data.C_us, sqrt_A = data.sqrt_A, t_0e = data.t_0e, fit_interval = data.fit_interval, AODO = data.AODO, C_ic = data.C_ic, Ω_0 = data.Ω_0, C_is = data.C_is, i_0 = data.i_0, C_rc = data.C_rc, ω = data.ω, Ω_dot = data.Ω_dot, IODE_Sub_3 = data.IODE_Sub_3, i_dot = data.i_dot, ) GPSL1Data( last_subframe_id, integrity_status_flag, TOW, alert_flag, anti_spoof_flag, trans_week, codeonl2, ura, svhealth, IODC, l2pcode, T_GD, t_0c, a_f2, a_f1, a_f0, IODE_Sub_2, C_rs, Δn, M_0, C_uc, e, C_us, sqrt_A, t_0e, fit_interval, AODO, C_ic, Ω_0, C_is, i_0, C_rc, ω, Ω_dot, IODE_Sub_3, i_dot, ) end function is_subframe1_decoded(data::GPSL1Data) !isnothing(data.trans_week) && !isnothing(data.codeonl2) && !isnothing(data.ura) && !isnothing(data.svhealth) && !isnothing(data.IODC) && !isnothing(data.l2pcode) && !isnothing(data.T_GD) && !isnothing(data.t_0c) && !isnothing(data.a_f2) && !isnothing(data.a_f1) && !isnothing(data.a_f0) end function is_subframe2_decoded(data::GPSL1Data) !isnothing(data.IODE_Sub_2) && !isnothing(data.C_rs) && !isnothing(data.Δn) && !isnothing(data.M_0) && !isnothing(data.C_uc) && !isnothing(data.e) && !isnothing(data.C_us) && !isnothing(data.sqrt_A) && !isnothing(data.t_0e) && !isnothing(data.fit_interval) && !isnothing(data.AODO) end function is_subframe3_decoded(data::GPSL1Data) !isnothing(data.C_ic) && !isnothing(data.Ω_0) && !isnothing(data.C_is) && !isnothing(data.i_0) && !isnothing(data.C_rc) && !isnothing(data.ω) && !isnothing(data.Ω_dot) && !isnothing(data.IODE_Sub_3) && !isnothing(data.i_dot) end function is_subframe4_decoded(data::GPSL1Data) false end function is_subframe5_decoded(data::GPSL1Data) false end function is_decoding_completed_for_positioning(data::GPSL1Data) !isnothing(data.integrity_status_flag) && !isnothing(data.TOW) && !isnothing(data.alert_flag) && !isnothing(data.anti_spoof_flag) && is_subframe1_decoded(data) && is_subframe2_decoded(data) && is_subframe3_decoded(data) end function GPSL1DecoderState(prn) GNSSDecoderState( prn, UInt320(0), UInt320(0), GPSL1Data(), GPSL1Data(), GPSL1Constants(), GPSL1Cache(), 0, nothing, false, ) end function GNSSDecoderState(system::GPSL1, prn) GNSSDecoderState( prn, UInt320(0), UInt320(0), GPSL1Data(), GPSL1Data(), GPSL1Constants(), GPSL1Cache(), 0, nothing, false, ) end function check_gpsl1_parity(word::Unsigned, prev_29 = false, prev_30 = false) function bit(bit_number) cbit = get_bit(word, 30, bit_number) prev_30 ? !cbit : cbit end # Parity check to verify the data integrity: D_25 = prev_29 ⊻ bit(1) ⊻ bit(2) ⊻ bit(3) ⊻ bit(5) ⊻ bit(6) ⊻ bit(10) ⊻ bit(11) ⊻ bit(12) ⊻ bit(13) ⊻ bit(14) ⊻ bit(17) ⊻ bit(18) ⊻ bit(20) ⊻ bit(23) D_26 = prev_30 ⊻ bit(2) ⊻ bit(3) ⊻ bit(4) ⊻ bit(6) ⊻ bit(7) ⊻ bit(11) ⊻ bit(12) ⊻ bit(13) ⊻ bit(14) ⊻ bit(15) ⊻ bit(18) ⊻ bit(19) ⊻ bit(21) ⊻ bit(24) D_27 = prev_29 ⊻ bit(1) ⊻ bit(3) ⊻ bit(4) ⊻ bit(5) ⊻ bit(7) ⊻ bit(8) ⊻ bit(12) ⊻ bit(13) ⊻ bit(14) ⊻ bit(15) ⊻ bit(16) ⊻ bit(19) ⊻ bit(20) ⊻ bit(22) D_28 = prev_30 ⊻ bit(2) ⊻ bit(4) ⊻ bit(5) ⊻ bit(6) ⊻ bit(8) ⊻ bit(9) ⊻ bit(13) ⊻ bit(14) ⊻ bit(15) ⊻ bit(16) ⊻ bit(17) ⊻ bit(20) ⊻ bit(21) ⊻ bit(23) D_29 = prev_30 ⊻ bit(1) ⊻ bit(3) ⊻ bit(5) ⊻ bit(6) ⊻ bit(7) ⊻ bit(9) ⊻ bit(10) ⊻ bit(14) ⊻ bit(15) ⊻ bit(16) ⊻ bit(17) ⊻ bit(18) ⊻ bit(21) ⊻ bit(22) ⊻ bit(24) D_30 = prev_29 ⊻ bit(3) ⊻ bit(5) ⊻ bit(6) ⊻ bit(8) ⊻ bit(9) ⊻ bit(10) ⊻ bit(11) ⊻ bit(13) ⊻ bit(15) ⊻ bit(19) ⊻ bit(22) ⊻ bit(23) ⊻ bit(24) computed_parity_bits = ( (((D_25 << UInt(1) + D_26) << UInt(1) + D_27) << UInt(1) + D_28) << UInt(1) + D_29 ) << UInt(1) + D_30 computed_parity_bits == get_bits(word, 30, 25, 6) end function get_word(state::GNSSDecoderState{<:GPSL1Data}, word_number::Int) num_words = Int(state.constants.syncro_sequence_length / state.constants.word_length) word = state.buffer >> UInt( state.constants.word_length * (num_words - word_number) + state.constants.preamble_length, ) UInt(word & (UInt(1) << UInt(state.constants.word_length) - UInt(1))) end function can_decode_word(decode_bits::Function, state::GNSSDecoderState, word_number::Int) word = get_word(state, word_number) prev_word = get_word(state, word_number - 1) prev_word_bit_30 = get_bit(prev_word, 30, 30) is_checked_word = word_number != 1 && word_number != 3 if check_gpsl1_parity( word, is_checked_word * get_bit(prev_word, 30, 29), is_checked_word * prev_word_bit_30, ) word_comp = (is_checked_word * prev_word_bit_30) ? ~word : word data = decode_bits(word_comp, state) state = GNSSDecoderState(state; raw_data = data) end return state end function can_decode_two_words( decode_bits::Function, state::GNSSDecoderState, word_number1::Int, word_number2::Int, ) word1 = get_word(state, word_number1) prev_word1 = get_word(state, word_number1 - 1) prev_word1_bit_30 = get_bit(prev_word1, 30, 30) is_checked_word1 = word_number1 != 1 && word_number1 != 3 word2 = get_word(state, word_number2) prev_word2 = get_word(state, word_number2 - 1) prev_word2_bit_30 = get_bit(prev_word2, 30, 30) is_checked_word2 = word_number2 != 1 && word_number2 != 3 if check_gpsl1_parity( word1, is_checked_word1 * get_bit(prev_word1, 30, 29), is_checked_word1 * prev_word1_bit_30, ) && check_gpsl1_parity( word2, is_checked_word2 * get_bit(prev_word2, 30, 29), is_checked_word2 * prev_word2_bit_30, ) word1_comp = (is_checked_word1 * prev_word1_bit_30) ? ~word1 : word1 word2_comp = (is_checked_word2 * prev_word2_bit_30) ? ~word2 : word2 data = decode_bits(word1_comp, word2_comp, state) state = GNSSDecoderState(state; raw_data = data) end return state end function read_tlm_and_how_words(state) state = can_decode_word(state, 1) do tlm_word, state integrity_status_flag = get_bit(tlm_word, 30, 23) GPSL1Data(state.raw_data; integrity_status_flag) end prev_TOW = state.raw_data.TOW state = can_decode_word(state, 2) do how_word, state TOW = get_bits(how_word, 30, 1, 17) * 6 alert_flag = get_bit(how_word, 30, 18) anti_spoof_flag = get_bit(how_word, 30, 19) last_subframe_id = get_bits(how_word, 30, 20, 3) GPSL1Data(state.raw_data; last_subframe_id, TOW, alert_flag, anti_spoof_flag) end if !isnothing(prev_TOW) && prev_TOW + 1 != state.raw_data.TOW # Time of week must be decodable state = GNSSDecoderState(state; raw_data = GPSL1Data(state.raw_data; TOW = nothing)) end state end function decode_syncro_sequence(state::GNSSDecoderState{<:GPSL1Data}) state = read_tlm_and_how_words(state) subframe_id = state.raw_data.last_subframe_id if subframe_id == 1 state = can_decode_word(state, 3) do word3, state trans_week = get_bits(word3, 30, 1, 10) # Codes on L2 Channel codeonl2 = get_bits(word3, 30, 11, 2) # SV Accuracy, user range accuracy ura = get_bits(word3, 30, 13, 4) if ura <= 6 ura = 2^(1 + (ura / 2)) elseif 6 < ura <= 14 ura = 2^(ura - 2) elseif ura == 15 ura = nothing end # Satellite Health svhealth = bitstring(get_bits(word3, 30, 17, 6))[end-5:end] if get_bit(word3, 30, 17) @warn "Bad LNAV Data, SV-Health critical", svhealth end GPSL1Data(state.raw_data; trans_week, codeonl2, ura, svhealth) end state = can_decode_two_words(state, 3, 8) do word3, word8, state # Issue of Data Clock # 2 MSB in Word 2, LSB 8 in Word 8 IODC = bitstring(get_bits(word3, 30, 23, 2))[end-1:end] * bitstring(get_bits(word8, 30, 1, 8))[end-7:end] GPSL1Data(state.raw_data; IODC) end state = can_decode_word(state, 4) do word4, state # True: LNAV Datastream on PCode commanded OFF l2pcode = get_bit(word4, 30, 1) GPSL1Data(state.raw_data; l2pcode) end state = can_decode_word(state, 7) do word7, state # group time differential T_GD = get_twos_complement_num(word7, 30, 17, 8) / 1 << 31 GPSL1Data(state.raw_data; T_GD) end state = can_decode_word(state, 8) do word8, state # Clock data reference t_0c = get_bits(word8, 30, 9, 16) << 4 GPSL1Data(state.raw_data; t_0c) end state = can_decode_word(state, 9) do word9, state # clock correction parameter a_f2 a_f2 = get_twos_complement_num(word9, 30, 1, 8) / 1 << 55 # clock correction parameter a_f1 a_f1 = get_twos_complement_num(word9, 30, 9, 16) / 1 << 43 GPSL1Data(state.raw_data; a_f2, a_f1) end state = can_decode_word(state, 10) do word10, state # Clock data reference a_f0 = get_twos_complement_num(word10, 30, 1, 22) / 1 << 31 GPSL1Data(state.raw_data; a_f0) end elseif subframe_id == 2 state = can_decode_word(state, 3) do word3, state # Issue of ephemeris data IODE_Sub_2 = bitstring(get_bits(word3, 30, 1, 8))[end-7:end] C_rs = get_twos_complement_num(word3, 30, 9, 16) / 1 << 5 GPSL1Data(state.raw_data; IODE_Sub_2, C_rs) end state = can_decode_word(state, 4) do word4, state # Mean motion difference from computed value Δn = get_twos_complement_num(word4, 30, 1, 16) * state.constants.PI / 1 << 43 GPSL1Data(state.raw_data; Δn) end state = can_decode_two_words(state, 4, 5) do word4, word5, state # Mean motion difference from computed value combined_word = UInt(get_bits(word4, 30, 17, 8) << 24 + get_bits(word5, 30, 1, 24)) M_0 = get_twos_complement_num(combined_word, 32, 1, 32) * state.constants.PI / 1 << 31 GPSL1Data(state.raw_data; M_0) end state = can_decode_word(state, 6) do word6, state # Amplitude of the Cosine Harmonic Correction Term to the Argument Latitude C_uc = get_twos_complement_num(word6, 30, 1, 16) / 1 << 29 GPSL1Data(state.raw_data; C_uc) end state = can_decode_two_words(state, 6, 7) do word6, word7, state # Eccentricity e = (get_bits(word6, 30, 17, 8) << 24 + get_bits(word7, 30, 1, 24)) / 1 << 33 GPSL1Data(state.raw_data; e) end state = can_decode_word(state, 8) do word8, state # Amplitude of the Sine Harmonic Correction Term to the Argument of Latitude C_us = get_twos_complement_num(word8, 30, 1, 16) / 1 << 29 GPSL1Data(state.raw_data; C_us) end state = can_decode_two_words(state, 8, 9) do word8, word9, state # Square Root of Semi-Major Axis sqrt_A = (get_bits(word8, 30, 17, 8) << 24 + get_bits(word9, 30, 1, 24)) / 1 << 19 GPSL1Data(state.raw_data; sqrt_A) end state = can_decode_word(state, 10) do word10, state # Reference Time ephemeris t_0e = get_bits(word10, 30, 1, 16) << 4 fit_interval = get_bit(word10, 30, 17) AODO = get_bits(word10, 30, 18, 5) GPSL1Data(state.raw_data; t_0e, fit_interval, AODO) end elseif subframe_id == 3 state = can_decode_word(state, 3) do word3, state # Amplitude of the Cosine Harmonic Correction to Angle of Inclination C_ic = get_twos_complement_num(word3, 30, 1, 16) / 1 << 29 GPSL1Data(state.raw_data; C_ic) end state = can_decode_two_words(state, 3, 4) do word3, word4, state # Longitude of Ascending Node of Orbit Plane at Weekly Epoch combined_word = UInt(get_bits(word3, 30, 17, 8) << 24 + get_bits(word4, 30, 1, 24)) Ω_0 = get_twos_complement_num(combined_word, 32, 1, 32) * state.constants.PI / 1 << 31 GPSL1Data(state.raw_data; Ω_0) end state = can_decode_word(state, 5) do word5, state # Amplitude of the sine harmonic correction term to angle of Inclination C_is = get_twos_complement_num(word5, 30, 1, 16) / 1 << 29 GPSL1Data(state.raw_data; C_is) end state = can_decode_two_words(state, 5, 6) do word5, word6, state # inclination Angle at reference time combined_word = UInt(get_bits(word5, 30, 17, 8) << 24 + get_bits(word6, 30, 1, 24)) i_0 = get_twos_complement_num(combined_word, 32, 1, 32) * state.constants.PI / 1 << 31 GPSL1Data(state.raw_data; i_0) end state = can_decode_word(state, 7) do word7, state # Amplitude of the cosine harmonic correction term to orbit Radius C_rc = get_twos_complement_num(word7, 30, 1, 16) / 1 << 5 GPSL1Data(state.raw_data; C_rc) end state = can_decode_two_words(state, 7, 8) do word7, word8, state # Argument of Perigee combined_word = UInt(get_bits(word7, 30, 17, 8) << 24 + get_bits(word8, 30, 1, 24)) ω = get_twos_complement_num(combined_word, 32, 1, 32) * state.constants.PI / 1 << 31 GPSL1Data(state.raw_data; ω) end state = can_decode_word(state, 9) do word9, state # Amplitude of the cosine harmonic correction term to orbit Radius Ω_dot = get_twos_complement_num(word9, 30, 1, 24) * state.constants.PI / 1 << 43 GPSL1Data(state.raw_data; Ω_dot) end state = can_decode_word(state, 10) do word10, state # Issue of Ephemeris Data IODE_Sub_3 = bitstring(get_bits(word10, 30, 1, 8))[end-7:end] # Rate of Inclination Angle i_dot = get_twos_complement_num(word10, 30, 9, 14) * state.constants.PI / 1 << 43 GPSL1Data(state.raw_data; IODE_Sub_3, i_dot) end end return state end function validate_data(state::GNSSDecoderState{<:GPSL1Data}) if is_decoding_completed_for_positioning(state.raw_data) && state.raw_data.IODC[3:10] == state.raw_data.IODE_Sub_2 == state.raw_data.IODE_Sub_3 state = GNSSDecoderState( state; data = state.raw_data, num_bits_after_valid_syncro_sequence = 8, ) end return state end function is_sat_healthy(state::GNSSDecoderState{<:GPSL1Data}) state.data.svhealth == "000000" end
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
code
2422
@testset "Bit fiddling" begin @test GNSSDecoder.get_bits(0b111, 4, 2, 3) == 0b111 @test GNSSDecoder.get_bits(0b111, 5, 3, 3) == 0b111 @test GNSSDecoder.get_bits(0b111, 5, 3, 2) == 0b11 @test GNSSDecoder.get_bits(0b111, 4, 2, 2) == 0b11 @test GNSSDecoder.get_bits(0b101, 4, 2, 2) == 0b10 @test GNSSDecoder.get_bits(0b101, 3, 1, 2) == 0b10 @test GNSSDecoder.get_bits(0b101, 3, 1, 3) == 0b101 @test GNSSDecoder.get_bit(0b101, 3, 1) == true @test GNSSDecoder.get_bit(0b101, 3, 2) == false @test GNSSDecoder.get_bit(0b101, 3, 3) == true @test GNSSDecoder.get_bit(0b101, 4, 2) == true @test GNSSDecoder.get_bit(0b101, 4, 3) == false @test GNSSDecoder.get_bit(0b101, 4, 4) == true @test GNSSDecoder.get_twos_complement_num(0b000, 3, 1, 3) == 0 @test GNSSDecoder.get_twos_complement_num(0b001, 3, 1, 3) == 1 @test GNSSDecoder.get_twos_complement_num(0b011, 3, 1, 3) == 3 @test GNSSDecoder.get_twos_complement_num(0b111, 3, 1, 3) == -1 @test GNSSDecoder.get_twos_complement_num(0b100, 3, 1, 3) == -4 @test GNSSDecoder.get_twos_complement_num(0b101, 3, 1, 3) == -3 # examplary bits from Galileo specification ex_encoded_bits = "101000000101111110001100111100000101111010100000000110011110001110101000010100000100111101010111011110001000011011111010111001111001100000011111111000100000100111110110000010011100011101100000100101110100100011000110110110010000011100111010" ex_deinterleaved_bits = "100011000001101010101010011100110011000101011010011011110101100101111000100101010101010110001100110011101010010110010000101001101000010000000010000000100001101110011001111010110101110000011000101110111111110111111101111001000101001100100010" @test GNSSDecoder.deinterleave(ex_encoded_bits, 30, 8) == ex_deinterleaved_bits ex_inv_deinterleaved_bits = "110110010100111111111111001001100110010000001111001110100000110000101101110000000000000011011001100110111111000011000101111100111101000101010111010101110100111011001100101111100000100101001101111011101010100010101000101100010000011001110111" @test GNSSDecoder.invert_every_second_bit(ex_deinterleaved_bits) == ex_inv_deinterleaved_bits ex_true_bits = "111111111111000011001100101010100000000000001111001100110101010111100011111011001101111110001010000111000001001101000000" @test viterbi_decode(7, [79, 109], ex_inv_deinterleaved_bits) == ex_true_bits[1:114] end
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
code
3978
BitIntegers.@define_integers 7520 const GALILEO_E1B_DATA = uint7520"0xffea400000b780000261fffff953e562a175eec2f8024501fdf196b047f3c7e186a0787c8f92d3f4f6bca06174fe7ffffe04000003e80000223fffff467ffffea400000b780000261fffff953e47501d3ea73f9e259eff711af5040f3c380c4a28479ff9d09fd56cd0835f4fe7ffffe04000003e80000223fffff467ffffea400000b780000261fffff953e49ca15be1fa79e277cffad182e04f725981eea951fc87cb47f9d7477053f4fe7ffffe04000003e80000223fffff467ffffea400000b780000261fffff953e55001fde50c7aaa6005f5d1b7105173eda116ac037ee7c24bfd57631056f4fe56155760a21263eefb50a07414bf3e4e1a382663d7ec5143e4baa2af24553ebaac4bdd8480b7a8cf5ac12c29b8361163a02f3991246f8b70f14e1af95f4ffcc27e40658eac47e7efb103c05584467e4adcec50490f6ceb30af5ef54253e325965fe54cb87addcae730a7bb6d62f5140cc0aaf27e2933dbd7aa4baff4ff973c0786866e3bc15330d6c0b5cc4dd47406c584373cf274fb8a7e4d88053e863010bdd79c512f473995025f798f1f5edacbba52f17fcb3247448a53a74fe7ffffe04000003e80000223fffff467ffffea400000b780000261fffff953e44f9179e129de3272be2fb1c6ed51710a0d68a5978dd7ecb57e373e75d274fe7ffffe04000003e80000223fffff467ffffea400000b780000261fffff953e47fe1abe4487a12785ffe11bc885571d3a0bea7a17adfc33be8b79b005774feeb312644db4c5166d0ada45be4608d318479ab42bdfd52b2fd7e70a26b753e5c2e1c5dd5b7b9a367ffa9371406076f7c1eeb9877ea61cc1f8d013984cf4fe5ee27a26245b0bd75e5ff09280d4352de9e647845e9e42cf7320f4c2b66d3e988a143e86d7a72aa93f691f5105a6092814ae1e2fc4f4c7bec32d6601574fe00799f25fa0e59c81fa4349fc113ae00fa8a2ff815c9602f1cbeff0340453ef9ec101d800782a105df65047b870e11c4158c6727c2e2575f1d54c986ef4fc2fffc9e8e002884a8012023dff87edcfffb08880053df7001d8a0bffdef53ebaac121c7ccf91a92eff4d1ea30557b91c0228286f89fc4ffee7751605774fc6df8a9cea05d1c45185080230ff4eea30f3a6776db937b62e1b2ecda31653ef65217bd906fadaa919f2b0295062fc4ae09280107ba7c2a3f416ffa008f4fe7ffffe04000003e80000223fffff467ffffea400000b780000261fffff953e4cf0191e3b57a824ef1f0b1746060f2e6a0f2a7cb7857cbbbeb57919076f4fe7ffffe04000003e80000223fffff467ffffea4" @testset "Galileo E1B constructor" begin galileo_e1b = GalileoE1B() @test GalileoE1BDecoderState(21) == GNSSDecoderState(galileo_e1b, 21) end @testset "Galileo E1B test data decoding" begin decoder = GalileoE1BDecoderState(21) test_data = GNSSDecoder.GalileoE1BData(; WN = 1170, TOW = 558041, t_0e = 556800.0, M_0 = 0.03588957467055676, e = 0.0002609505318105221, sqrt_A = 5440.625303268433, Ω_0 = 2.5016390578909675, i_0 = 0.9744856179803416, ω = 0.400715796701369, i_dot = -6.482412875658937e-10, Ω_dot = -5.1184274887640895e-9, Δn = 2.60617998642883e-9, C_uc = 5.239620804786682e-6, C_us = 1.1917203664779663e-5, C_rc = 90.4375, C_rs = 113.6875, C_ic = 7.450580596923828e-9, C_is = 0.0, t_0c = 556800.0, a_f0 = -0.0007140382076613605, a_f1 = -2.2311041902867146e-12, a_f2 = 0.0, IOD_nav1 = 0x0000000000000020, IOD_nav2 = 0x0000000000000020, IOD_nav3 = 0x0000000000000020, IOD_nav4 = 0x0000000000000020, num_pages_after_last_TOW = 1, signal_health_e1b = GNSSDecoder.signal_ok, signal_health_e5b = GNSSDecoder.signal_ok, data_validity_status_e1b = GNSSDecoder.navigation_data_valid, data_validity_status_e5b = GNSSDecoder.navigation_data_valid, broadcast_group_delay_e1_e5a = 2.7939677238464355e-9, broadcast_group_delay_e1_e5b = 3.026798367500305e-9, ) state = decode(decoder, GALILEO_E1B_DATA, 7000) @test state.data == test_data @test state.is_shifted_by_180_degrees == true @test state.num_bits_after_valid_syncro_sequence == 665 @test is_sat_healthy(state) == true state = decode(decoder, ~GALILEO_E1B_DATA, 7000) @test state.data == test_data @test state.is_shifted_by_180_degrees == false @test state.num_bits_after_valid_syncro_sequence == 665 @test is_sat_healthy(state) == true end
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
code
4756
BitIntegers.@define_integers 1536 BitIntegers.@define_integers 320 const GPSL1DATA = uint1536"0x8b010c06ef056f410d000004def4351756ed43ed2357f4afe163920d2f0bff00295b9ebf9f88b010c06ef035644808d518abf98cb9d2094bfe1c3e92dbb769706d42853f19a83172d0e0748b010c06ef014ecffa302d1c9d38430077d85c9473c27eef4e6ac5a0325b0050c0cedc3c47c8b010c06eeff39075aaaac5555556aaaaaaa55555556aaaaaaa55555556aaaaaaa55555559c8b010c06eefd21840aaaab2aaaaabcaaaaaaf2aaaaabcaaaaaaf2aaaaabcaaaaaaf2aaaaabc8b" @testset "GPS L1 constructor" begin gpsl1 = GPSL1() @test GPSL1DecoderState(21) == GNSSDecoderState(gpsl1, 21) end @testset "GPS L1 decoding" begin decoder = GPSL1DecoderState(1) @test decoder.prn == 1 @test decoder.num_bits_buffered == 0 @test isnothing(decoder.num_bits_after_valid_syncro_sequence) @test decoder.raw_buffer == UInt(0) @test decoder.buffer == UInt(0) @test GNSSDecoder.calc_preamble_mask(decoder) == 0b11111111 state = GNSSDecoder.push_bit(decoder, UInt(1)) @test state.num_bits_buffered == 1 @test state.raw_buffer == UInt(1) @test state.buffer == UInt(0) @test isnothing(state.num_bits_after_valid_syncro_sequence) @test GNSSDecoder.is_enough_buffered_bits_to_decode(state) == false @test GNSSDecoder.find_preamble(state) == false constants = GNSSDecoder.GPSL1Constants() @test constants.preamble == 0b10001011 @test constants.preamble_length == 8 @test constants.word_length == 30 @test constants.syncro_sequence_length == 300 raw_buffer = UInt320(constants.preamble) << UInt(300) + UInt320(constants.preamble) state = GNSSDecoder.GNSSDecoderState( 1, raw_buffer, UInt320(0), GNSSDecoder.GPSL1Data(), GNSSDecoder.GPSL1Data(), GNSSDecoder.GPSL1Constants(), GNSSDecoder.GPSL1Cache(), 308, nothing, false, ) @test GNSSDecoder.find_preamble(state) == true @test GNSSDecoder.complement_buffer_if_necessary(state) == GNSSDecoder.GNSSDecoderState( state; buffer = raw_buffer, is_shifted_by_180_degrees = false, ) @test GNSSDecoder.is_enough_buffered_bits_to_decode(state) == true raw_buffer = UInt320(~constants.preamble) << UInt(300) + UInt320(~constants.preamble) state = GNSSDecoder.GNSSDecoderState( 1, raw_buffer, UInt320(0), GNSSDecoder.GPSL1Data(), GNSSDecoder.GPSL1Data(), GNSSDecoder.GPSL1Constants(), GNSSDecoder.GPSL1Cache(), 308, nothing, false, ) @test GNSSDecoder.find_preamble(state) == true @test GNSSDecoder.complement_buffer_if_necessary(state) == GNSSDecoder.GNSSDecoderState( state; buffer = ~raw_buffer, is_shifted_by_180_degrees = true, ) buffer = UInt320(constants.preamble) << UInt(300) + UInt320(constants.preamble) + UInt320(1) << UInt(8) state = GNSSDecoder.GNSSDecoderState( 1, buffer, buffer, GNSSDecoder.GPSL1Data(), GNSSDecoder.GPSL1Data(), GNSSDecoder.GPSL1Constants(), GNSSDecoder.GPSL1Cache(), 308, nothing, false, ) @test GNSSDecoder.get_word(state, 10) == 1 end @testset "GPS L1 test data decoding" begin decoder = GPSL1DecoderState(1) test_data = GNSSDecoder.GPSL1Data(; last_subframe_id = 5, integrity_status_flag = false, TOW = 34945 * 6, alert_flag = false, anti_spoof_flag = true, trans_week = 67, codeonl2 = 1, ura = 2.0, svhealth = "000000", IODC = "0001001000", l2pcode = false, T_GD = -1.0710209608078003e-8, t_0c = 216000, a_f2 = 0.0, a_f1 = -4.774847184307873e-12, a_f0 = -0.00018549291417002678, IODE_Sub_2 = "01001000", C_rs = 70.65625, Δn = 3.930878022562108e-9, M_0 = 2.4393048719362045, C_uc = 3.604218363761902e-6, e = 0.01144192845094949, C_us = 1.3023614883422852e-5, sqrt_A = 5153.7995529174805, t_0e = 216000, fit_interval = false, AODO = 31, C_ic = -1.73225998878479e-7, Ω_0 = 0.0600607702978756, C_is = -2.2351741790771484e-7, i_0 = 0.9781895349147778, C_rc = 136.34375, ω = 0.635978551768012, Ω_dot = -7.383521839035659e-9, IODE_Sub_3 = "01001000", i_dot = -3.4465721349922174e-10, ) state = decode(decoder, GPSL1DATA, 1508) @test state.data == test_data @test is_sat_healthy(state) == true state = decode(decoder, ~GPSL1DATA, 1508) @test state.data == test_data @test is_sat_healthy(state) == true end
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
code
139
using Test, GNSSDecoder, BitIntegers, ViterbiDecoder, GNSSSignals include("bit_fiddling.jl") include("gpsl1.jl") include("galileo_e1b.jl")
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
docs
1050
# GNSSDecoder.jl Decodes various GNSS satellite signals. Currently implemented: * GPS L1 * Galileo E1B ## Usage #### Install: ```julia julia> ] pkg> add GNSSDecoder ``` ### Initialization The decoder must be initialized beforehand. ```julia decoder = GPSL1DecoderState(1) #Initialization of decoder with PRN = 1 ``` ### Decoding Pass bits to decoder as an unsigned integer value and let the decoder decode the message. ```julia for i in 1:iterations # Track signal for example with Tracking.jl track_res = track(signal, track_state, decoder.PRN , sampling_freq) track_state = get_state(track_res) decoder = decode(decoder, get_bits(track_res), get_num_bits(track_res)) end ``` The data can be retrieved by ```julia decoder.data ``` Note that GNSSDecoder decodes each time a complete subframe has been retrieved. `decoder.raw_data` holds the raw data. `decoder.data` hold data that has been checked for consistency. `decoder.num_bits_after_valid_subframe` counts the number of bits after a valid subframe has been retrieved.
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git
[ "MIT" ]
0.1.0
86d1353d0ce2db7c4c59209cfe7e837db9831f5b
code
655
# see documentation at https://juliadocs.github.io/Documenter.jl/stable/ using Documenter, SensitivityAnalysis makedocs( modules = [SensitivityAnalysis], format = Documenter.HTML(; prettyurls = get(ENV, "CI", nothing) == "true"), authors = "Tamás K. Papp", sitename = "SensitivityAnalysis.jl", pages = Any["index.md"] # strict = true, # clean = true, # checkdocs = :exports, ) # Some setup is needed for documentation deployment, see “Hosting Documentation” and # deploydocs() in the Documenter manual for more information. deploydocs( repo = "github.com/tpapp/SensitivityAnalysis.jl.git", push_preview = true )
SensitivityAnalysis
https://github.com/tpapp/SensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
86d1353d0ce2db7c4c59209cfe7e837db9831f5b
code
8131
""" Organize sensitivity / perturbation analysis. See [`perturbation_analysis`](@ref) for a short example, and the documentation for details. """ module SensitivityAnalysis export RELATIVE, ABSOLUTE, perturbation, perturbation_analysis, moment, moment_sensitivity import Accessors using ArgCheck: @argcheck using DocStringExtensions: SIGNATURES import ThreadPools using UnPack: @unpack #### #### changes #### ### ### relative ### struct Relative end Base.show(io::IO, ::Relative) = print(io, "relative change") "Represents a relative change, for inputs (`y = x * (1 + Δ)`) or outputs (`Δ = y / x - 1`)." const RELATIVE = Relative() (::Relative)(x, Δ) = x .* (1 + Δ) difference(::Relative, y, x) = y / x - 1 ### ### absolute ### struct Absolute end Base.show(io::IO, ::Absolute) = print(io, "absolute change") "Represents an absolute, for inputs (`y = x + Δ`) or outputs (`Δ = y - x`)." const ABSOLUTE = Absolute() (::Absolute)(x, Δ) = x + Δ difference(::Absolute, y, x) = y - x #### #### perturbations #### struct Perturbation label metadata lens change captured_errors Δs end function Base.show(io::IO, perturbation::Perturbation) @unpack label, change, captured_errors, Δs = perturbation domain = Δs ≡ nothing ? "default domain" : extrema(Δs) print(io, "perturb $(label) on $(domain), $(change) [capturing $(captured_errors)]") end """ $(SIGNATURES) # Arguments - `label`: Label, used for lookup and printing. - `lens`: For changing an object via the `Accessors.lens` API. - `change`: A change calculator, eg [`ABSOLUTE`](@ref)` or [`RELATIVE`](@ref)`, or a callable with the signature `(x, Δ) -> new_x`. # Keyword arguments - `metadata`: arbitrary metadata (eg for plot styles, etc). Passed through. - `Δs`: an `AbstractVector` or iterable of `Δ` values to be used by `change` above. When `nothing`, a default will be used, see [`perturbation_analysis`](@ref). - `captured_errors`: a type (eg a `Union{DomainError,ArgumentError}`) that is silently captured and converted to `nothing`. These results will show up as `NaN` in moment sensitivities. """ function perturbation(label, lens, change; metadata = nothing, Δs = nothing, captured_errors = DomainError) Perturbation(label, metadata, lens, change, captured_errors, Δs) end """ $(SIGNATURES) Internal function for computing a perturbation of `object` by `Δ`. Captures errors and converts them to `nothing`. """ function _perturbation_with(object, perturbation::Perturbation, Δ) @unpack lens, change, captured_errors = perturbation try Accessors.modify(x -> change(x, Δ), object, lens) catch e if e isa captured_errors nothing else rethrow(e) end end end struct PerturbationAnalysis label object simulate baseline_result default_Δs perturbations_and_results end """ $(SIGNATURES) A container for perturbation analysis. # Arguments - `object`: an opaque object that will be modified by perturbations - `simulate`: a callable on (changed) `object`s that returns a value moments can be calculated from. Should be thread safe. Can return `nothing` in case the simulation fails for whatever reason, in which case moments will use a `NaN` for the corresponding change. # Keyword arguments - `baseline_result`: a simulation result from `object` as is. - `label`: a global label for the whole analysis. - `default_Δs`: when a perturbation has no `Δs` specified, these will be used instead. Defaults to 11 values on ±0.1. # Usage Once an analysis is created, you should `push!` perturbations into it. `label`s should be unique, as they can be used for lookup. ```jldoctest julia> using SensitivityAnalysis, Accessors julia> anls = perturbation_analysis((a = 10.0, ), x -> (b = 2 * x.a, )) perturbation results with default domain (-0.1, 0.1) julia> push!(anls, perturbation("a", @optic(_.a), RELATIVE)) perturbation results with default domain (-0.1, 0.1) perturb a on default domain, relative change [capturing DomainError] julia> moment_sensitivity(anls, "a", moment("b", x -> x.b, ABSOLUTE)) (label = "b (absolute change)", x = -0.1:0.02:0.1, y = [-2.0, -1.5999999999999979, -1.2000000000000028, -0.8000000000000007, -0.3999999999999986, 0.0, 0.3999999999999986, 0.8000000000000007, 1.2000000000000028, 1.6000000000000014, 2.0]) ``` See also [`moment_sensitivity`](@ref). """ function perturbation_analysis(object, simulate; baseline_result = simulate(object), label = nothing, default_Δs = range(-0.1, 0.1; length = 11)) PerturbationAnalysis(label, object, simulate, baseline_result, default_Δs, Vector()) end function Base.show(io::IO, perturbation_analysis::PerturbationAnalysis) @unpack label, default_Δs, perturbations_and_results = perturbation_analysis print(io, "perturbation results") if label ≢ nothing print(io, "for ", label) end print(io, " with default domain $(extrema(default_Δs))") for (p, _) in perturbations_and_results print(io, "\n ", p) end end Broadcast.broadcastable(x::PerturbationAnalysis) = Ref(x) """ $(SIGNATURES) Internal function for calculating `Δs`. """ function _effective_Δs(perturbation_analysis, perturbation) something(perturbation_analysis.default_Δs, perturbation.Δs) end function Base.push!(perturbation_analysis::PerturbationAnalysis, perturbation::Perturbation) @unpack object, simulate, perturbations_and_results = perturbation_analysis results = ThreadPools.tmap(_effective_Δs(perturbation_analysis, perturbation)) do Δ changed_object = _perturbation_with(object, perturbation, Δ) changed_object ≡ nothing && return nothing simulate(changed_object) end push!(perturbations_and_results, perturbation => results) perturbation_analysis end """ $(SIGNATURES) Internal function to look up perturbations by matching `pattern` on their labels. Checks for unique matches. """ function _lookup_perturbation_by_label(perturbation_analysis, pattern::Union{AbstractPattern,AbstractString}) @unpack perturbations_and_results = perturbation_analysis matches = findall(perturbations_and_results) do (p, _) contains(p.label, pattern) end if length(matches) > 1 throw(ArgumentError("multiple labels match $(label)")) elseif isempty(matches) throw(ArgumentError("no labels match $(label)")) else first(matches) end end _lookup_perturbation_by_label(perturbation_analysis, index::Integer) = index #### #### moments #### struct Moment label metadata calculator change end function Base.show(io::IO, moment::Moment) @unpack label, change = moment print(io, label, " (", change, ")") end """ $(SIGNATURES) Define a moment (a univariate statistic from simulation results). # Arguments - `label`: used for printing - `calculator`: a callable on simulation results - `change`: how changes should be interpreted, eg [`ABSOLUTE`](@ref)` or [`RELATIVE`](@ref)`. # Keywoard arguments - `metadata`: passed through unchanged, can be used for plot styles, etc. """ function moment(label, calculator, change; metadata = nothing) Moment(label, metadata, calculator, change) end function _moment_sensitivity(moment, baseline_result, results) @unpack calculator, change = moment m0 = calculator(baseline_result) map(results) do r if r ≡ nothing NaN else difference(change, calculator(r), m0) end end end function moment_sensitivity(perturbation_analysis, index_or_pattern, moment) @unpack baseline_result, perturbations_and_results = perturbation_analysis index = _lookup_perturbation_by_label(perturbation_analysis, index_or_pattern) perturbation, results = perturbations_and_results[index] sensitivity = _moment_sensitivity(moment, baseline_result, results) Δs = _effective_Δs(perturbation_analysis, perturbation) (label = repr(moment), x = Δs, y = sensitivity, metadata = moment.metadata) end end # module
SensitivityAnalysis
https://github.com/tpapp/SensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
86d1353d0ce2db7c4c59209cfe7e837db9831f5b
code
1013
using SensitivityAnalysis, Test, Statistics, UnPack, Accessors struct SimulateNormal{T} μ::T σ::T function SimulateNormal(μ::T, σ::T) where {T} σ > 1.001 && throw(DomainError("let's tigger catch")) new{T}(μ, σ) end end function simulate(object::SimulateNormal) @unpack μ, σ = object N = 10000 x = randn(N) .* σ .+ μ (mean = mean(x), std = std(x)) end results = perturbation_analysis(SimulateNormal(0.0, 1.0), simulate) push!(results, perturbation("μ", @optic(_.μ), ABSOLUTE), perturbation("σ", @optic(_.σ), RELATIVE)) moments = [moment("mean", x -> x.mean, ABSOLUTE; metadata = :meta), moment("std", x -> x.std, RELATIVE)] sens_mu = moment_sensitivity.(results, "μ", moments) let s = sens_mu[1] @test s.label == "mean (absolute change)" @test s.x == results.default_Δs @test length(s.y) ==length(s.x) @test s.metadata ≡ :meta end sens_sigma = moment_sensitivity.(results, "σ", moments) @test isnan(sens_sigma[1].y[end])
SensitivityAnalysis
https://github.com/tpapp/SensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
86d1353d0ce2db7c4c59209cfe7e837db9831f5b
docs
677
# SensitivityAnalysis.jl ![lifecycle](https://img.shields.io/badge/lifecycle-experimental-orange.svg) [![build](https://github.com/tpapp/SensitivityAnalysis.jl/workflows/CI/badge.svg)](https://github.com/tpapp/SensitivityAnalysis.jl/actions?query=workflow%3ACI) [![codecov.io](http://codecov.io/github/tpapp/SensitivityAnalysis.jl/coverage.svg?branch=master)](http://codecov.io/github/tpapp/SensitivityAnalysis.jl?branch=master) [![Documentation](https://img.shields.io/badge/docs-stable-blue.svg)](https://tpapp.github.io/SensitivityAnalysis.jl/stable) [![Documentation](https://img.shields.io/badge/docs-master-blue.svg)](https://tpapp.github.io/SensitivityAnalysis.jl/dev)
SensitivityAnalysis
https://github.com/tpapp/SensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
86d1353d0ce2db7c4c59209cfe7e837db9831f5b
docs
166
# SensitivityAnalysis ## Motivation and a worked example ## Docstrings ```@docs RELATIVE ABSOLUTE perturbation perturbation_analysis moment moment_sensitivity ```
SensitivityAnalysis
https://github.com/tpapp/SensitivityAnalysis.jl.git
[ "MIT" ]
0.2.1
78faddd85f10ff840cbaa98533c82581e01a6ac7
code
638
module GaussianRelations export CenteredGaussianRelation, CenteredPrecisionForm, CenteredCovarianceForm export GaussianRelation, PrecisionForm, CovarianceForm export cov, disintegrate, kleisli, mean, oapply, otimes, params, push, pull using Catlab.ACSetInterface using Catlab.FinSets using Catlab.FinSets: FinDomFunctionVector using Catlab.Theories using Catlab.UndirectedWiringDiagrams using Catlab.WiringDiagramAlgebras using FillArrays using LinearAlgebra using LinearAlgebra: checksquare using Statistics using StatsAPI using StatsAPI: params const DEFAULT_TOLERANCE = 1e-8 include("centered.jl") include("relation.jl") end
GaussianRelations
https://github.com/samuelsonric/GaussianRelations.jl.git
[ "MIT" ]
0.2.1
78faddd85f10ff840cbaa98533c82581e01a6ac7
code
9142
# A centered Gaussian relation. struct CenteredGaussianRelation{T, PT <: AbstractMatrix, ST <: AbstractMatrix} precision::PT support::ST function CenteredGaussianRelation{T}(P::PT, S::ST) where {T, PT <: AbstractMatrix, ST <: AbstractMatrix} m = checksquare(P) n = checksquare(S) @assert m == n new{T, PT, ST}(P, S) end end # A centered Gaussian relation in precision form. const CenteredPrecisionForm = CenteredGaussianRelation{false} # A centered Gaussian relation in covariance form. const CenteredCovarianceForm = CenteredGaussianRelation{true} function CenteredGaussianRelation{T}(relation::CenteredGaussianRelation{T}) where T CenteredGaussianRelation{T}(relation.precision, relation.support) end function CenteredGaussianRelation{T}(relation::CenteredGaussianRelation) where T P, S = params(relation) U, V, D = factorizepsd(P + S) M = solvespp(D, quad(S, V), I, 0I) CenteredGaussianRelation{T}(quad(D, M * V'), quad(I, U')) end function CenteredGaussianRelation{T}(P::AbstractMatrix) where T n = size(P, 1) CenteredGaussianRelation{T}(P, Zeros(n, n)) end function CenteredGaussianRelation{T, PT, ST}(args...; kwargs...) where {T, PT, ST} P, S = params(CenteredGaussianRelation{T}(args...; kwargs...)) CenteredGaussianRelation{T}(convert(PT, P), convert(ST, S)) end function Base.length(relation::CenteredGaussianRelation) size(relation.precision, 1) end function StatsAPI.params(relation::CenteredGaussianRelation, i::Integer) @assert 1 <= i <= 2 params(relation)[i] end function StatsAPI.params(relation::CenteredGaussianRelation) relation.precision, relation.support end function Theories.otimes(left::CenteredGaussianRelation{T}, right::CenteredGaussianRelation{T}) where T P₁, S₁ = params(left) P₂, S₂ = params(right) CenteredGaussianRelation{T}(cat(P₁, P₂, dims=(1, 2)), cat(S₁, S₂, dims=(1, 2))) end function pull(M::AbstractMatrix, relation::CenteredGaussianRelation{T}, ::Val{T}) where T P, S = params(relation) CenteredGaussianRelation{T}(quad(P, M), quad(S, M)) end function pull(M::AbstractMatrix, relation::CenteredGaussianRelation, ::Val{T}) where T CenteredGaussianRelation{!T}(pull(M, CenteredGaussianRelation{T}(relation), Val(T))) end function pull(f::FinFunction, relation::CenteredGaussianRelation{T}, ::Val{T}) where T epi, mono = epi_mono(f) pull_epi(epi, pull_mono(mono, relation, Val(T)), Val(T)) end function pull(f::FinFunction, relation::CenteredGaussianRelation{T}, ::Val) where T f = collect(f) P = relation.precision[f, f] S = relation.support[f, f] CenteredGaussianRelation{T}(P, S) end function pull_epi(f::FinFunction, relation::CenteredGaussianRelation{T, PT, ST}, ::Val{T}) where {T, PT, ST} m = length(dom(f)) n = length(codom(f)) P = zeros(eltype(PT), m, m) S = zeros(eltype(ST), m, m) section = zeros(Int, n) indices = zeros(Int, n) for i in 1:m v = f(i) if iszero(section[v]) section[v] = i else j = indices[v] S[i, i] += 1 S[j, j] += 1 S[i, j] = S[j, i] = -1 end indices[v] = i end P[section, section] .+= relation.precision S[section, section] .+= relation.support CenteredGaussianRelation{T}(P, S) end function pull_epi(f::FinFunction, relation::CenteredGaussianRelation{T, PT, ST}, ::Val) where {T, PT, ST} pull(f, relation, Val(!T)) end function pull_mono(f::FinFunction, relation::CenteredGaussianRelation{T}, ::Val{T}) where T n = length(relation) P, S = params(relation) i₁ = trues(n) i₂ = collect(f) i₁[i₂] .= false P₁₁, P₁₂, P₂₁, P₂₂ = getblocks(P, i₁, i₂) S₁₁, S₁₂, S₂₁, S₂₂ = getblocks(S, i₁, i₂) M = solvespp(P₁₁, S₁₁, P₁₂, S₁₂) CenteredGaussianRelation{T}( P₂₂ + quad(P₁₁, M) - P₂₁ * M - M' * P₁₂, S₂₂ - quad(S₁₁, M)) end function pull_mono(f::FinFunction, relation::CenteredGaussianRelation{T, PT, ST}, ::Val) where {T, PT, ST} pull(f, relation, Val(!T)) end function push(M::AbstractMatrix, relation::CenteredGaussianRelation, ::Val{T}) where T pull(M', relation, Val(!T)) end function push(f::FinFunction, relation::CenteredGaussianRelation{T, PT, ST}, ::Val{T}) where {T, PT, ST} m = length(dom(f)) n = length(codom(f)) P = zeros(eltype(PT), n, n) S = zeros(eltype(ST), n, n) for i in 1:m, j in 1:m P[f(i), f(j)] += relation.precision[i, j] S[f(i), f(j)] += relation.support[i, j] end CenteredGaussianRelation{T}(P, S) end function push(f::FinFunction, relation::CenteredGaussianRelation{T, PT, ST}, ::Val) where {T, PT, ST} epi, mono = epi_mono(f) push_mono(mono, push_epi(epi, relation, Val(!T)), Val(!T)) end function push_epi(f::FinFunction, relation::CenteredGaussianRelation{T, PT, ST}, ::Val{T}) where {T, PT, ST} push(f, relation, Val(T)) end function push_epi(f::FinFunction, relation::CenteredGaussianRelation{T, PT, ST}, ::Val) where {T, PT, ST} m = length(dom(f)) n = length(codom(f)) section = zeros(Int, n) indices = zeros(Int, n) parent = zeros(Int, m) for i in 1:m v = f(i) if iszero(section[v]) section[v] = i else parent[i] = indices[v] end indices[v] = i end P = Matrix{eltype(PT)}(undef, m, m) S = Matrix{eltype(ST)}(undef, m, m) for i₁ in 1:m j₁ = parent[i₁] for i₂ in i₁:m j₂ = parent[i₂] p = relation.precision[i₁, i₂] s = relation.support[i₁, i₂] if !iszero(j₁) p -= relation.precision[j₁, i₂] s -= relation.support[j₁, i₂] end if !iszero(j₂) p -= relation.precision[i₁, j₂] s -= relation.support[i₁, j₂] end if !iszero(j₁) && !iszero(j₂) p += relation.precision[j₁, j₂] s += relation.support[j₁, j₂] end P[i₁, i₂] = p S[i₁, i₂] = s end end P = Symmetric(P) S = Symmetric(S) pull_mono(FinFunction(section, m), CenteredGaussianRelation{T}(P, S), Val(T)) end function push_mono(f::FinFunction, relation::CenteredGaussianRelation{T, PT, ST}, ::Val{T}) where {T, PT, ST} push(f, relation, Val(T)) end function push_mono(f::FinFunction, relation::CenteredGaussianRelation{T, PT, ST}, ::Val) where {T, PT, ST} n = length(codom(f)) indices = collect(f) P = zeros(eltype(PT), n, n) S = Matrix{eltype(ST)}(I, n, n) P[indices, indices] = relation.precision S[indices, indices] = relation.support CenteredGaussianRelation{T}(P, S) end function disintegrate(relation::CenteredGaussianRelation{T}, mask::AbstractVector{Bool}) where T i₁ = !T .⊻ mask i₂ = T .⊻ mask P, S = params(relation) P₁₁, P₁₂, P₂₁, P₂₂ = getblocks(P, i₁, i₂) S₁₁, S₁₂, S₂₁, S₂₂ = getblocks(S, i₁, i₂) M = solvespp(P₁₁, S₁₁, P₁₂, S₁₂) r₁ = CenteredGaussianRelation{T}(P₁₁, S₁₁) r₂ = CenteredGaussianRelation{T}( P₂₂ + quad(P₁₁, M) - P₂₁ * M - M' * P₁₂, S₂₂ - quad(S₁₁, M)) T ? (r₁, r₂, -M') : (r₂, r₁, M) end # Compute matrices M₁₁, M₁₂, M₂₁, and M₂₂ such that # M = [ M₁₁ M₁₂ ] # [ M₂₁ M₂₂ ], # where M is a square matrix. function getblocks(M::AbstractMatrix, i₁::AbstractVector, i₂::AbstractVector) M₁₁ = M[i₁, i₁] M₁₂ = M[i₁, i₂] M₂₁ = M[i₂, i₁] M₂₂ = M[i₂, i₂] M₁₁, M₁₂, M₂₁, M₂₂ end # Solve the saddle point problem # [ A B ] [ x ] = [ e ] # [ B 0 ] [ y ] = [ f ], # where A and B are positive semidefinite, e ∈ col A, and f ∈ col B. function solvespp(A::AbstractMatrix, B::AbstractMatrix, e, f; tol::Real=DEFAULT_TOLERANCE) U, V, D = factorizepsd(B; tol) Uᵀ_A_U = qr(quad(A, U), ColumnNorm()) v = V * (D \ (V' * f)) u = U * (Uᵀ_A_U \ (U' * (e - A * v))) u + v end # Compute a diagonal matrix # D ≻ 0 # and unitary matrix # Q = [ U V ] # such that # A = [ 0 0 ] [ Uᵀ ] # [ U V ] [ 0 D ] [ Vᵀ ], # where A is positive semidefinite. function factorizepsd(A::AbstractMatrix; tol::Real=DEFAULT_TOLERANCE) D, Q = eigen(A) n = count(D .< tol) U = Q[:, 1:n] V = Q[:, n + 1:end] D = Diagonal(D[n + 1:end]) U, V, D end # Compute # Mᵀ A M, # where A is positive semidefinite. function quad(A, M::AbstractMatrix) Symmetric(M' * A * M) end # Factorize a function f: i → k as a composite # f = e ; m, # where e: i → j is a surjection and m: j → k is an injection. function epi_mono(f::FinFunction) epi = zeros(Int, length(codom(f))) mono = zeros(Int, 0) for i in dom(f) j = f(i) if iszero(epi[j]) push!(mono, j) epi[j] = length(mono) end end set = FinSet(length(mono)) epi = FinDomFunctionVector(epi[collect(f)], dom(f), set) mono = FinDomFunctionVector(mono, set, codom(f)) epi, mono end
GaussianRelations
https://github.com/samuelsonric/GaussianRelations.jl.git
[ "MIT" ]
0.2.1
78faddd85f10ff840cbaa98533c82581e01a6ac7
code
6063
# A Gaussian relation. struct GaussianRelation{T, PT, ST} inner::CenteredGaussianRelation{T, PT, ST} function GaussianRelation(inner::CenteredGaussianRelation{T, PT, ST}) where {T, PT, ST} @assert length(inner) >= 1 new{T, PT, ST}(inner) end end # A Gaussian relation in precision form. const PrecisionForm = GaussianRelation{false} # A Gaussian relation in covariance form. const CovarianceForm = GaussianRelation{true} function GaussianRelation{T}(μ::Real, p²::Real) where T GaussianRelation{T}(μ, p², 0) end function GaussianRelation{T}(μ::Real, p²::Real, s²::Real) where T GaussianRelation{T}([μ], [p²;;], [s²;;]) end function GaussianRelation{T}(μ::AbstractVector, P::AbstractMatrix) where T n = length(μ) GaussianRelation{T}(μ, P, Zeros(n, n)) end function GaussianRelation{T}(μ::AbstractVector, P::AbstractMatrix, S::AbstractMatrix) where T kleisli(CenteredGaussianRelation{T}(P, S)) + μ end function GaussianRelation{T}(inner::CenteredGaussianRelation) where T GaussianRelation(CenteredGaussianRelation{T}(inner)) end function GaussianRelation{T}(relation::GaussianRelation) where T GaussianRelation(CenteredGaussianRelation{T}(relation.inner)) end function GaussianRelation{T, PT, ST}(args...; kwargs...) where {T, PT, ST} inner = GaussianRelation{T}(args...; kwargs...).inner GaussianRelation(CenteredGaussianRelation{T, PT, ST}(inner)) end function Base.convert(::Type{GaussianRelation{T, PT, ST}}, relation::GaussianRelation{T}) where {T, PT, ST} GaussianRelation{T, PT, ST}(relation) end function Base.length(relation::GaussianRelation) length(relation.inner) - 1 end function StatsAPI.params(relation::GaussianRelation, i::Integer) @assert 1 <= i <= 3 params(relation)[i] end function StatsAPI.params(relation::GaussianRelation) n = length(relation) marginal, conditional, M = disintegrate(relation.inner, [true; Falses(n)]) params(conditional)..., reshape(M, n) end function Statistics.cov(relation::CovarianceForm) params(relation, 1) end function Statistics.cov(relation::PrecisionForm) cov(CovarianceForm(relation)) end function Statistics.mean(relation::GaussianRelation) params(relation, 3) end function kleisli(relation::CenteredGaussianRelation{T}) where T P, S = params(relation) P = cat(T, P; dims=(1, 2)) S = cat(T, S; dims=(1, 2)) GaussianRelation(CenteredGaussianRelation{T}(P, S)) end function Theories.otimes(left::GaussianRelation, right::GaussianRelation) m = length(left.inner) n = length(right.inner) f = FinDomFunctionVector([1:m; 1; m + 1:m + n - 1], FinSet(m + n), FinSet(m + n - 1)) GaussianRelation(push_epi(f, otimes(left.inner, right.inner), Val(false))) end function Theories.otimes(relations::GaussianRelation{T, PT, ST}...) where {T, PT, ST} init = GaussianRelation(CenteredGaussianRelation{T, PT, ST}([T;;], [T;;])) reduce(otimes, relations; init) end function Base.:+(relation::PrecisionForm, v::AbstractVector) n = length(v) GaussianRelation(pull([1 Zeros(n)'; v Eye(n)], relation.inner, Val(false))) end function Base.:+(relation::CovarianceForm, v::AbstractVector) n = length(v) GaussianRelation(push([1 Zeros(n)'; -v Eye(n)], relation.inner, Val(false))) end function Base.:+(relation::GaussianRelation, v::Real) relation + [v] end function Base.:+(v, relation::GaussianRelation) relation + v end function Base.:\(M, relation::Union{GaussianRelation, CenteredGaussianRelation}) pull(M, relation, Val(false)) end function Base.:*(M, relation::Union{GaussianRelation, CenteredGaussianRelation}) push(M, relation, Val(false)) end function disintegrate(relation::GaussianRelation, mask::AbstractVector{Bool}) marginal, conditional, M = disintegrate(relation.inner, [true; mask]) GaussianRelation(marginal), kleisli(conditional) + M[:, 1], M[:, 2:end] end function pull(M::AbstractMatrix, relation::GaussianRelation, ::Val{T}) where T GaussianRelation(pull(cat(1, M; dims=(1, 2)), relation.inner, Val(T))) end function pull(f::FinFunction, relation::GaussianRelation, ::Val{T}) where T GaussianRelation(pull(oplus(FinFunction([1], 1), f), relation.inner, Val(T))) end function push(M::AbstractMatrix, relation::GaussianRelation, ::Val{T}) where T GaussianRelation(push(cat(1, M; dims=(1, 2)), relation.inner, Val(T))) end function push(f::FinFunction, relation::GaussianRelation, ::Val{T}) where T GaussianRelation(push(oplus(FinFunction([1], 1), f), relation.inner, Val(T))) end function WiringDiagramAlgebras.oapply( diagram::UndirectedWiringDiagram, hom_map::AbstractDict{<:Any, <:GaussianRelation}, ob_map::AbstractDict{<:Any, <:Integer}, ::Val{T}=Val(false); hom_attr::Symbol=:name, ob_attr::Symbol=:variable) where T homs = map(diagram[hom_attr]) do attr hom_map[attr] end obs = map(diagram[ob_attr]) do attr ob_map[attr] end oapply(diagram, homs, obs, Val(T)) end function WiringDiagramAlgebras.oapply( diagram::UndirectedWiringDiagram, homs::AbstractVector{<:GaussianRelation}, obs::AbstractVector{<:Integer}, ::Val{T}=Val(false)) where T q_stop = cumsum(obs[diagram[:outer_junction]]) p_stop = cumsum(obs[diagram[:junction]]) j_stop = cumsum(obs) q_start = q_stop .- obs[diagram[:outer_junction]] .+ 1 p_start = p_stop .- obs[diagram[:junction]] .+ 1 j_start = j_stop .- obs .+ 1 q_map = Vector{Int}(undef, q_stop[end]) p_map = Vector{Int}(undef, p_stop[end]) for q in parts(diagram, :OuterPort) j = diagram[q, :outer_junction] q_map[q_start[q]:q_stop[q]] .= j_start[j]:j_stop[j] end for p in parts(diagram, :Port) j = diagram[p, :junction] p_map[p_start[p]:p_stop[p]] .= j_start[j]:j_stop[j] end q_map = FinFunction(q_map, j_stop[end]) p_map = FinFunction(p_map, j_stop[end]) relation = otimes(homs...) pull(q_map, push(p_map, relation, Val(T)), Val(T)) end
GaussianRelations
https://github.com/samuelsonric/GaussianRelations.jl.git
[ "MIT" ]
0.2.1
78faddd85f10ff840cbaa98533c82581e01a6ac7
code
13069
using Catlab, Catlab.Programs using GaussianRelations using LinearAlgebra using Test function ≅(a, b) isapprox(a, b; atol=1e-8) end @testset "Positive Definite" begin P = [ 5/16 -1/8 0 -1/8 7/12 1/3 0 1/3 1/3 ] C = [ 4 2 -2 2 5 -5 -2 -5 8 ] M = [ 1 2 -1 2 1 2 -1 2 1 ] m = [1, -3, 4] v = [3, 9, -1] mask = [true, true, false] @testset "CenteredPrecisonForm" begin relation = CenteredPrecisionForm{Matrix{Float64}, Matrix{Float64}}(P) marginal, conditional, matrix = disintegrate(relation, mask) @test length(relation) == 3 @test params(relation, 1) ≅ P @test params(kleisli(relation), 1) ≅ P @test params(M * relation, 1) ≅ inv(M * C * M') @test params(M \ relation, 1) ≅ M' * P * M @test params(otimes(relation, relation), 1) ≅ cat(P, P; dims=(1, 2)) @test params(CenteredCovarianceForm(relation), 1) ≅ C @test params(marginal, 1) ≅ inv(C[mask, mask]) @test params(conditional, 1) ≅ P[.!mask, .!mask] @test matrix ≅ -C[.!mask, mask] / C[mask, mask] end @testset "CenteredCovarianceForm" begin relation = CenteredCovarianceForm{Matrix{Float64}, Matrix{Float64}}(C) marginal, conditional, matrix = disintegrate(relation, mask) @test length(relation) == 3 @test params(relation, 1) ≅ C @test params(kleisli(relation), 1) ≅ C @test params(M * relation, 1) ≅ M * C * M' @test params(M \ relation, 1) ≅ inv(M' * P * M) @test params(otimes(relation, relation), 1) ≅ cat(C, C; dims=(1, 2)) @test params(CenteredPrecisionForm(relation), 1) ≅ P @test params(marginal, 1) ≅ C[mask, mask] @test params(conditional, 1) ≅ inv(P[.!mask, .!mask]) @test matrix ≅ -C[.!mask, mask] / C[mask, mask] end @testset "PrecisionForm" begin relation = PrecisionForm{Matrix{Float64}, Matrix{Float64}}(m, P) marginal, conditional, matrix = disintegrate(relation, mask) @test isa(convert(PrecisionForm{Matrix{Float32}, Matrix{Float32}}, relation), PrecisionForm{Matrix{Float32}, Matrix{Float32}}) @test length(relation) == 3 @test cov(relation) ≅ C @test mean(relation) ≅ m @test params(relation, 1) ≅ P @test params(relation, 3) ≅ m @test params(v + relation, 1) ≅ P @test params(v + relation, 3) ≅ v + m @test params(M * relation, 1) ≅ inv(M * C * M') @test params(M * relation, 3) ≅ M * m @test params(M \ relation, 1) ≅ M' * P * M @test params(M \ relation, 3) ≅ inv(M' * P * M) * M' * P * m @test params(otimes(relation, relation, relation), 1) ≅ cat(P, P, P; dims=(1, 2)) @test params(otimes(relation, relation, relation), 3) ≅ [m; m; m] @test params(CovarianceForm(relation), 1) ≅ C @test params(CovarianceForm(relation), 3) ≅ m @test params(marginal, 1) ≅ inv(C[mask, mask]) @test params(marginal, 3) ≅ m[mask] @test params(conditional, 1) ≅ P[.!mask, .!mask] @test params(conditional, 3) ≅ inv(P[.!mask, .!mask]) * P[.!mask, :] * m @test matrix ≅ -C[.!mask, mask] / C[mask, mask] end @testset "CovarianceForm" begin relation = CovarianceForm{Matrix{Float64}, Matrix{Float64}}(m, C) marginal, conditional, matrix = disintegrate(relation, mask) @test isa(convert(CovarianceForm{Matrix{Float32}, Matrix{Float32}}, relation), CovarianceForm{Matrix{Float32}, Matrix{Float32}}) @test length(relation) == 3 @test length(relation) == 3 @test cov(relation) ≅ C @test mean(relation) ≅ m @test params(relation, 1) ≅ C @test params(relation, 3) ≅ m @test params(v + relation, 1) ≅ C @test params(v + relation, 3) ≅ v + m @test params(M * relation, 1) ≅ M * C * M' @test params(M * relation, 3) ≅ M * m @test params(M \ relation, 1) ≅ inv(M' * P * M) @test params(M \ relation, 3) ≅ inv(M' * P * M) * M' * P * m @test params(otimes(relation, relation, relation), 1) ≅ cat(C, C, C; dims=(1, 2)) @test params(otimes(relation, relation, relation), 3) ≅ [m; m; m] @test params(PrecisionForm(relation), 1) ≅ P @test params(PrecisionForm(relation), 3) ≅ m @test params(marginal, 1) ≅ C[mask, mask] @test params(marginal, 3) ≅ m[mask] @test params(conditional, 1) ≅ inv(P[.!mask, .!mask]) @test params(conditional, 3) ≅ inv(P[.!mask, .!mask]) * P[.!mask, :] * m @test matrix ≅ -C[.!mask, mask] / C[mask, mask] end end @testset "Noisy Resistor" begin σ₁ = 1/2 σ₂ = 2/3 R₁ = 2 R₂ = 4 V₀ = 5 M = [-1 1; R₂ R₁] / (R₁ + R₂) @testset "PrecisionForm" begin #= # ϵ₁ ~ N(0, σ₁²) ϵ₁ = PrecisionForm(0, σ₁^-2) # ϵ₂ ~ N(0, σ₂²) ϵ₂ = PrecisionForm(0, σ₂^-2) # [ I₁ ] # [-R₁ 1] [ V₁ ] = ϵ₁ IV₁ = [-R₁ 1] \ ϵ₁ @test nullspace(params(IV₁, 1)) ≅ nullspace([-R₁ 1]) || nullspace(params(IV₁, 1)) ≅ -nullspace([-R₁ 1]) @test all(params([-R₁ 1] * IV₁) .≅ params(ϵ₁)) # [ I₁ ] # [R₂ 1] [ V₂ ] = ϵ₂ + V₀ IV₂ = [R₂ 1] \ (ϵ₂ + V₀) # [ 1 0 ] [ I₁ ] # [ 0 1 ] [ V₁ ] # [ 1 0 ] [ I ] [ I₂ ] # [ 0 1 ] [ V ] = [ V₂ ] IV = [1 0; 0 1; 1 0; 0 1] \ otimes(IV₁, IV₂) @test params(IV, 1) ≅ inv(M * [σ₁^2 0; 0 σ₂^2] * M') @test params(IV, 2) ≅ [0 0; 0 0] @test params(IV, 3) ≅ M * [0; V₀] # IV₁ # / \ # --- I V --- # \ / # IV₂ diagram = @relation (I, V) begin IV₁(I, V) IV₂(I, V) end IV = oapply(diagram, Dict(:IV₁ => IV₁, :IV₂ => IV₂), Dict(:I => 1, :V => 1)) @test params(IV, 1) ≅ inv(M * [σ₁^2 0; 0 σ₂^2] * M') @test params(IV, 2) ≅ [0 0; 0 0] @test params(IV, 3) ≅ M * [0; V₀] =# ############################### # Example 1: A Noisy Resistor # ############################### σ₁ = 1/2 R₁ = 2 # ϵ₁ ~ N(0, σ₁²) ϵ₁ = PrecisionForm(0, σ₁^-2) # Define the noisy resistor using a kernel representation. # [ I₁ ] # [-R₁ 1] [ V₁ ] = ϵ₁ IV₁ = [-R₁ 1] \ ϵ₁ @test nullspace(params(IV₁, 1)) ≅ nullspace([-R₁ 1]) || nullspace(params(IV₁, 1)) ≅ -nullspace([-R₁ 1]) @test all(params([-R₁ 1] * IV₁) .≅ params(ϵ₁)) ################################################# # Example 3: The Noisy Resistor, Interconnected # ################################################# σ₂ = 2/3 R₂ = 4 V₀ = 5 # ϵ₂ ~ N(0, σ₂²) ϵ₂ = PrecisionForm(0, σ₂^-2) # Construct the second resistor. # [ I₁ ] # [R₂ 1] [ V₂ ] = ϵ₂ + V₀ IV₂ = [R₂ 1] \ (ϵ₂ + V₀) # The interconnected system solves the following equation: # [ 1 0 ] [ I₁ ] # [ 0 1 ] [ V₁ ] # [ 1 0 ] [ I ] [ I₂ ] # [ 0 1 ] [ V ] = [ V₂ ] IV = [1 0; 0 1; 1 0; 0 1] \ otimes(IV₁, IV₂) @test params(IV, 1) ≅ inv(M * [σ₁^2 0; 0 σ₂^2] * M') @test params(IV, 2) ≅ [0 0; 0 0] @test params(IV, 3) ≅ M * [0; V₀] # The interconnected system corresponds to the following undirected wiring diagram. # IV₁ # / \ # --- I V --- # \ / # IV₂ diagram = @relation (I, V) begin IV₁(I, V) IV₂(I, V) end # We can also interconnect the systems by applying an operad algebra to the preceding diagram. IV = oapply(diagram, Dict(:IV₁ => IV₁, :IV₂ => IV₂), Dict(:I => 1, :V => 1)) @test params(IV, 1) ≅ inv(M * [σ₁^2 0; 0 σ₂^2] * M') @test params(IV, 2) ≅ [0 0; 0 0] @test params(IV, 3) ≅ M * [0; V₀] # If a system is classical, access its parameters by calling the functions mean and cov. mean(IV) cov(IV) @test mean(IV) ≅ M * [0; V₀] @test cov(IV) ≅ M * [σ₁^2 0; 0 σ₂^2] * M' ################################################## # Example 5: The Noisy Resistor With Constraints # ################################################## # I₂ = 1 amp. I₂ = PrecisionForm(1, 0, 1) # The constrained system solves the following equation: # [ 1 0 ] [ I₁ ] # [ 0 1 ] [ I ] [ V₁ ] # [ 1 0 ] [ V ] = [ I₂ ] IV = [1 0; 0 1; 1 0] \ otimes(IV₁, I₂) # Marginalize over I by computing # [ I ] # V = [0 1] [ V ] V = [0 1] * IV @test params(V, 1) ≅ [σ₁^-2;;] @test params(V, 2) ≅ [0;;] @test params(V, 3) ≅ [R₁] # The constrained system corresponds to the following undirected wiring diagram. # IV₁ # / \ # I V --- # \ # I₂ diagram = @relation (V,) begin IV₁(I, V) I₂(I) end # We can also constrain the system by applying an operad algebra to the preceding diagram. V = oapply(diagram, Dict(:IV₁ => IV₁, :I₂ => I₂), Dict(:I => 1, :V => 1)) @test params(V, 1) ≅ [σ₁^-2;;] @test params(V, 2) ≅ [0;;] @test params(V, 3) ≅ [R₁] end @testset "CovarianceForm" begin ############################### # Example 1: A Noisy Resistor # ############################### σ₁ = 1/2 R₁ = 2 # ϵ₁ ~ N(0, σ₁²) ϵ₁ = CovarianceForm(0, σ₁^2) # Define the noisy resistor using a kernel representation. # [ I₁ ] # [-R₁ 1] [ V₁ ] = ϵ₁ IV₁ = [-R₁ 1] \ ϵ₁ @test nullspace(params(IV₁, 2)) ≅ nullspace([1 R₁]) || nullspace(params(IV₁, 2)) ≅ -nullspace([1 R₁]) @test all(params([-R₁ 1] * IV₁) .≅ params(ϵ₁)) ################################################# # Example 3: The Noisy Resistor, Interconnected # ################################################# σ₂ = 2/3 R₂ = 4 V₀ = 5 # ϵ₂ ~ N(0, σ₂²) ϵ₂ = CovarianceForm(0, σ₂^2) # Construct the second resistor. # [ I₁ ] # [R₂ 1] [ V₂ ] = ϵ₂ + V₀ IV₂ = [R₂ 1] \ (ϵ₂ + V₀) # The interconnected system solves the following equation: # [ 1 0 ] [ I₁ ] # [ 0 1 ] [ V₁ ] # [ 1 0 ] [ I ] [ I₂ ] # [ 0 1 ] [ V ] = [ V₂ ] IV = [1 0; 0 1; 1 0; 0 1] \ otimes(IV₁, IV₂) @test params(IV, 1) ≅ M * [σ₁^2 0; 0 σ₂^2] * M' @test params(IV, 2) ≅ [0 0; 0 0] @test params(IV, 3) ≅ M * [0; V₀] # The interconnected system corresponds to the following undirected wiring diagram. # IV₁ # / \ # --- I V --- # \ / # IV₂ diagram = @relation (I, V) begin IV₁(I, V) IV₂(I, V) end # We can also interconnect the systems by applying an operad algebra to the preceding diagram. IV = oapply(diagram, Dict(:IV₁ => IV₁, :IV₂ => IV₂), Dict(:I => 1, :V => 1)) @test params(IV, 1) ≅ M * [σ₁^2 0; 0 σ₂^2] * M' @test params(IV, 2) ≅ [0 0; 0 0] @test params(IV, 3) ≅ M * [0; V₀] # If a system is classical, access its parameters by calling the functions mean and cov. mean(IV) cov(IV) @test mean(IV) ≅ M * [0; V₀] @test cov(IV) ≅ M * [σ₁^2 0; 0 σ₂^2] * M' ################################################## # Example 5: The Noisy Resistor With Constraints # ################################################## # I₂ = 1 amp. I₂ = CovarianceForm(1, 0) # The constrained system solves the following equation: # [ 1 0 ] [ I₁ ] # [ 0 1 ] [ I ] [ V₁ ] # [ 1 0 ] [ V ] = [ I₂ ] IV = [1 0; 0 1; 1 0] \ otimes(IV₁, I₂) # Marginalize over I by computing # [ I ] # V = [0 1] [ V ] V = [0 1] * IV @test params(V, 1) ≅ [σ₁^2;;] @test params(V, 2) ≅ [0;;] @test params(V, 3) ≅ [R₁] # The constrained system corresponds to the following undirected wiring diagram. # IV₁ # / \ # I V --- # \ # I₂ diagram = @relation (V,) begin IV₁(I, V) I₂(I) end # We can also constrain the system by applying an operad algebra to the preceding diagram. V = oapply(diagram, Dict(:IV₁ => IV₁, :I₂ => I₂), Dict(:I => 1, :V => 1)) @test params(V, 1) ≅ [σ₁^2;;] @test params(V, 2) ≅ [0;;] @test params(V, 3) ≅ [R₁] end end
GaussianRelations
https://github.com/samuelsonric/GaussianRelations.jl.git
[ "MIT" ]
0.2.1
78faddd85f10ff840cbaa98533c82581e01a6ac7
docs
3127
# GaussianRelations.jl [![tests](https://github.com/samuelsonric/GaussianRelations.jl/actions/workflows/tests.yml/badge.svg)](https://github.com/samuelsonric/GaussianRelations.jl/actions/workflows/tests.yml?query=workflow%3Atests) [![codecov](https://codecov.io/gh/samuelsonric/GaussianRelations.jl/graph/badge.svg?token=pVcto1pdzK)](https://codecov.io/gh/samuelsonric/GaussianRelations.jl) GaussianRelations.jl is a Julia library that provides tools for working with Gaussian linear systems. It accompanies the paper [A Categorical Treatment of Open Linear Systems](https://arxiv.org/abs/2403.03934). ## Example: A Noisy Resistor In the paper [Open Stochastic Systems](https://ieeexplore.ieee.org/abstract/document/6255764), Jan Willems defines a Gaussian linear system that he calls the "noisy resistor." <p align="center"> <img src="resistor.png" width="259" height="215"> </p> Using our library, the noisy resistor can be implemented as follows. ```julia using Catlab using GaussianRelations ############################### # Example 1: A Noisy Resistor # ############################### σ₁ = 1/2 R₁ = 2 # ϵ₁ ~ N(0, σ₁²) ϵ₁ = CovarianceForm(0, σ₁^2) # Define the noisy resistor using a kernel representation. # [ I₁ ] # [-R₁ 1] [ V₁ ] = ϵ₁ IV₁ = [-R₁ 1] \ ϵ₁ ################################################# # Example 3: The Noisy Resistor, Interconnected # ################################################# σ₂ = 2/3 R₂ = 4 V₀ = 5 # ϵ₂ ~ N(0, σ₂²) ϵ₂ = CovarianceForm(0, σ₂^2) # Construct the second resistor. # [ I₁ ] # [R₂ 1] [ V₂ ] = ϵ₂ + V₀ IV₂ = [R₂ 1] \ (ϵ₂ + V₀) # The interconnected system solves the following equation: # [ 1 0 ] [ I₁ ] # [ 0 1 ] [ V₁ ] # [ 1 0 ] [ I ] [ I₂ ] # [ 0 1 ] [ V ] = [ V₂ ] IV = [1 0; 0 1; 1 0; 0 1] \ otimes(IV₁, IV₂) # The interconnected system corresponds to the following undirected wiring diagram. # IV₁ # / \ # --- I V --- # \ / # IV₂ diagram = @relation (I, V) begin IV₁(I, V) IV₂(I, V) end # We can also interconnect the systems by applying an operad algebra to the preceding # diagram. IV = oapply(diagram, Dict(:IV₁ => IV₁, :IV₂ => IV₂), Dict(:I => 1, :V => 1)) # If a system is classical, access its parameters by calling the functions mean and cov. mean(IV) cov(IV) ################################################## # Example 5: The Noisy Resistor With Constraints # ################################################## # I₂ = 1 amp. I₂ = CovarianceForm(1, 0) # The constrained system solves the following equation: # [ 1 0 ] [ I₁ ] # [ 0 1 ] [ I ] [ V₁ ] # [ 1 0 ] [ V ] = [ I₂ ] IV = [1 0; 0 1; 1 0] \ otimes(IV₁, I₂) # Marginalize over I by computing # [ I ] # V = [0 1] [ V ] V = [0 1] * IV # The constrained system corresponds to the following undirected wiring diagram. # IV₁ # / \ # I V --- # \ # I₂ diagram = @relation (V,) begin IV₁(I, V) I₂(I) end # We can also constrain the system by applying an operad algebra to the preceding # diagram. V = oapply(diagram, Dict(:IV₁ => IV₁, :I₂ => I₂), Dict(:I => 1, :V => 1)) ```
GaussianRelations
https://github.com/samuelsonric/GaussianRelations.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
667
using Random using RNGTest using BenchmarkTools function pipe_output(f, str_out, str_err) redirect_stdio(stdout="$(str_out).txt", stderr="$(str_err).txt") do f() end end str_(test, name) = "$(test)_$name" str_(test, name, seed) = "$(test)_$(name)_seed=$seed" function smallcrush(rng, name) redirect_stdio(stdout="./BigCrushTestU01_$(name).txt", stderr="stderr_$(name).txt") do RNGTest.smallcrushTestU01(rng) end end function bigcrush(rng, name) redirect_stdio(stdout="./BigCrushTestU01_$(name).txt", stderr="stderr_$(name).txt") do RNGTest.bigcrushTestU01(rng) end end function speed_benchmark(rng, name) end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
348
using Pkg Pkg.activate(".") using RandomNoise using Random using RNGTest include("utils.jl") mmn = Murmur3Noise() open("results/speed_test_Murmur3Noise.txt", "w") do io b = speed_test(mmn) show(io, MIME("text/plain"), b) end io2 = open("results/bigcrush_MurmurNoise.txt", "w") redirect_stdout(io2) do bigcrush(mmn) end close(io2)
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
357
using Pkg Pkg.activate(".") using RandomNoise using Random using RNGTest include("utils.jl") sqn = SquirrelNoise5() open("results/speed_test_SquirrelNoise5.txt", "w") do io b = speed_test(sqn) show(io, MIME("text/plain"), b) end io2 = open("results/bigcrush_SquirrelNoise5.txt", "w") redirect_stdout(io2) do bigcrush(sqn) end close(io2)
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
361
using Pkg Pkg.activate(".") using RandomNoise using Random using RNGTest include("utils.jl") sqn = SquirrelNoise5x2() open("results/speed_test_SquirrelNoise5x3.txt", "w") do io b = speed_test(sqn) show(io, MIME("text/plain"), b) end io2 = open("results/bigcrush_SquirrelNoise5x2.txt", "w") redirect_stdout(io2) do bigcrush(sqn) end close(io2)
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
527
using RNGTest: wrap, bigcrushTestU01 using BenchmarkTools using RandomNoise: AbstractNoise, NoiseRNG using Random function wrap_noise(rng::AbstractNoise{T}) where T return wrap(NoiseRNG(rng), T) end function bigcrush(rng::AbstractNoise) bigcrushTestU01(wrap_noise(rng)) end function speed_test(noise::AbstractNoise{T}, n = 100_000_000) where {T} a = Vector{T}(undef, n) rng = NoiseRNG(noise) rand!(rng, a) return @benchmark rand!($(NoiseRNG(noise)), $a)# setup=(rng=NoiseRNG($noise), a=copy($a)) end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
607
using NoiseRNG using Documenter DocMeta.setdocmeta!(NoiseRNG, :DocTestSetup, :(using NoiseRNG); recursive=true) makedocs(; modules=[NoiseRNG], authors="Cédric Simal, University of Namur", repo="https://github.com/csimal/NoiseRNG.jl/blob/{commit}{path}#{line}", sitename="NoiseRNG.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://csimal.github.io/NoiseRNG.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/csimal/NoiseRNG.jl", devbranch="main", )
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
1413
module DistributionsExt using RandomNoise using RandomNoise: noise_convert import RandomNoise: NoiseMap, noise_getindex isdefined(Base, :get_extension) ? (using Distributions) : (using ..Distributions) """ NoiseMap(rng::AbstractNoise, d::UnivariateDistribution, dim::Integer) Return a `NoiseMap` of dimension `dim` whose elements are samples from the univariate distribution `d`. # Examples ```jldoctest julia> using RandomNoise, Distributions julia> nm1 = NoiseMap(SquirrelNoise5(), Bernoulli(0.5), 1) NoiseMap{Bool, 1, SquirrelNoise5, Bernoulli{Float64}}(SquirrelNoise5(0x00000000), Bernoulli{Float64}(p=0.5)) julia> nm1.(1:10) 10-element BitVector: 0 0 0 0 0 0 0 1 1 0 julia> nm2 = NoiseMap(sqn, Poisson(5), 1) NoiseMap{Int64, 1, SquirrelNoise5, Poisson{Float64}}(SquirrelNoise5(0x00000000), Poisson{Float64}(λ=5.0)) julia> nm2.(1:10) 10-element Vector{Int64}: 7 6 5 6 5 6 6 4 1 8 ``` """ function NoiseMap(rng::R, d::Distributions.UnivariateDistribution, N::Integer = 1) where {R} T = eltype(d) NoiseMap{T,N,R,typeof(d)}(rng, d) end @inline noise_getindex(rng::AbstractNoise, d::Distributions.UnivariateDistribution, i) = Distributions.quantile(d, noise_convert(noise(i,rng), Float64)) # override to guarantee Bool output type @inline noise_getindex(rng::AbstractNoise, d::Distributions.Bernoulli, i) = isless(noise_convert(noise(i,rng), Float64), d.p) end # module
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
1351
module RandomNoise """ AbstractNoise{T} Supertype for random noise functions. `T` indicates the return type. """ abstract type AbstractNoise{T} end """ noise(n, noise::AbstractNoise) Compute noise function `noise` at position `n`. ## Examples ```jldoctest julia> sqn = SquirrelNoise5() SquirrelNoise5(0x00000000) julia> noise(5, sqn) 0x933e65af ``` """ function noise(n::Integer, nf::AbstractNoise{T}) where {T<:Integer} noise(n % T, nf) end function noise(n, nf::AbstractNoise{T}) where {T} noise(_convert(n, T), nf) end export AbstractNoise export noise include("noise/squirrel5.jl") include("noise/murmur3.jl") export SquirrelNoise5, SquirrelNoise5x2, Murmur3Noise include("utils/convert.jl") include("noise_rng.jl") export NoiseRNG include("utils/transforms.jl") export NoiseUniform include("utils/pairing_functions.jl") include("noise_maps.jl") export NoiseMap using Random123 include("noise/random123.jl") export ThreefryNoise, PhiloxNoise @static if Random123.R123_USE_AESNI export AESNINoise, ARSNoise end if !isdefined(Base, :get_extension) using Requires end function __init__() # Optional support for Distributions @static if !isdefined(Base, :get_extension) @require Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f" include("../ext/DistributionsExt.jl") end end end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
2099
import Base: getindex """ NoiseMap{T,N,R,F} An `N`-dimensional infinite stream of random values. # Fields - `noise` an noise function used to generate the base stream of random numbers - `transform` a function that is applied to the output of the noise function to obtain the result Transforms can be - Arbitrary functions - An instance of `NoiseUniform`, in which case, the values are floating point numbers uniformly distributed in the interval [0,1). - An instance of `Distributions.UnivariateDistribution`, in which case the values are samples from that distribution. # Examples ```jldoctest julia> nm = NoiseMap(sqn) NoiseMap{UInt32, 1, SquirrelNoise5, typeof(identity)}(SquirrelNoise5(0x00000000), identity) ``` """ struct NoiseMap{T,N,R<:AbstractNoise,F} noise::R transform::F end NoiseMap{T,N}(rng::R, transform::F) where {T,N,R,F} = NoiseMap{T,N,R,F}(rng, transform) NoiseMap{T}(rng::R, transform::F, N::Integer = 1) where {T,R,F} = NoiseMap{T,N,R,F}(rng, transform) function NoiseMap(rng::R, transform::F, N::Integer = 1) where {R,F} T = typeof(transform(noise(1, rng))) NoiseMap{T,N,R,F}(rng, transform) end NoiseMap(rng, dim::Integer = 1) = NoiseMap(rng, identity, dim) NoiseMap(rng::R, t::NoiseUniform{T}, N::Integer = 1) where {R,T} = NoiseMap{T,N,R,NoiseUniform{T}}(rng, t) @inline (nm::NoiseMap)(n::Integer) = noise_getindex(nm.noise, nm.transform, n) @inline (nm::NoiseMap{T,2})(a, b) where T = nm(pairing2(a,b)) @inline (nm::NoiseMap{T,3})(a, b, c) where T = nm(pairing3(a,b,c)) @inline (nm::NoiseMap{T,4})(a, b, c, d) where T = nm(pairing4(a,b,c,d)) @inline (nm::NoiseMap{T,5})(a,b,c,d,e) where T = nm(pairing5(a,b,c,d,e)) @inline (nm::NoiseMap{T,6})(a,b,c,d,e,f) where T = nm(pairing6(a,b,c,d,e,f)) @inline (nm::NoiseMap{T,7})(a,b,c,d,e,f,g) where T = nm(pairing7(a,b,c,d,e,f,g)) @inline (nm::NoiseMap{T,8})(a,b,c,d,e,f,g,h) where T = nm(pairing8(a,b,c,d,e,f,g,h)) @inline (nm::NoiseMap)(idx::Tuple{Vararg{Integer,N}}) where N = nm(idx...) @inline (nm::NoiseMap)(idx...) = nm(pairing(idx...)) @inline getindex(nm::NoiseMap, idx...) = nm(idx...)
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
2114
import Random import Random: AbstractRNG, rand, UInt52, rng_native_52 # NB. copied from https://github.com/JuliaRandom/RandomNumbers.jl/blob/master/src/common.jl const BitTypes = Union{Bool, UInt8, UInt16, UInt32, UInt64, UInt128, Int8, Int16, Int32, Int64, Int128} """ NoiseRNG{N,T} <: AbstractRNG where {N,T<:AbstractNoise{N}} Wrapper type to use a noise function as a rng for use in `rand()`. ## Fields * `noise::T` : the noise function. * `counter::N = zero(N)` : a counter indicating where the sequence of generated numbers is currently at. ## Examples ```jldoctest julia> rng = NoiseRNG(SquirrelNoise5()) NoiseRNG{UInt32, SquirrelNoise5}(SquirrelNoise5(0x00000000), 0x00000000) julia> rand(rng) 0.08778560161590576 ```` """ mutable struct NoiseRNG{N,T} <: AbstractRNG where {N,T<:AbstractNoise{N}} noise::T counter::N end NoiseRNG(noise::AbstractNoise{N}) where {N} = NoiseRNG(noise, zero(N)) Base.:(==)(rng1::NoiseRNG{N,T}, rng2::NoiseRNG{N,T}) where {N,T} = (rng1.noise == rng2.noise) && (rng1.counter == rng2.counter) Base.copy(rng::NoiseRNG) = NoiseRNG(rng.noise,rng.counter) function Base.copy!(dst::NoiseRNG{N,T}, src::NoiseRNG{N,T}) where {N,T} dst.noise = src.noise dst.counter = src.counter dst end @inline function rand(rng::NoiseRNG{N,T}, ::Type{N}) where {N<:BitTypes,T<:AbstractNoise{N}} rng.counter += one(N) noise(rng.counter-1, rng.noise) end rng_native_52(::NoiseRNG) = UInt64 rand(rng::NoiseRNG, ::Random.SamplerType{T}) where {T<:BitTypes} = rand(rng,T) @inline function rand(rng::NoiseRNG{N1,T}, ::Type{N2}) where {N1<:BitTypes, N2<:BitTypes,T} s1 = sizeof(N1) s2 = sizeof(N2) t = rand(rng,N1) % N2 s1 > s2 && return t for i in 2:(s2 ÷ s1) t |= (rand(rng, N1) % N2) << ((s1 << 3) * (i-1)) end t end @inline function rand(rng::NoiseRNG{N,T}, ::Type{Float64}=Float64) where {N<:Union{UInt64,UInt128},T} noise_convert(rand(rng, UInt64), Float64) end @inline function rand(rng::NoiseRNG{N,T}, ::Type{Float64}=Float64) where {N<:Union{UInt8,UInt16,UInt32}, T} noise_convert(rand(rng, N), Float64) end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
1279
""" Murmur3Noise A 32-bit noise function based on the Murmur3 hash function. ## Fields * `seed::UInt32 = 0` ## Examples ```jldoctest julia> m3n = Murmur3Noise() Murmur3Noise(0x00000000) julia> noise(0, m3n) 0x2362f9de julia> noise(1, m3n) 0xfbf1402a ``` ```jldoctest julia> m3n = Murmur3Noise(42) Murmur3Noise(0x0000002a) julia> noise(0, m3n) 0x379fae8f julia> noise(1, m3n) 0xdea578e3 ``` """ struct Murmur3Noise <: AbstractNoise{UInt32} seed::UInt32 Murmur3Noise(n) = new(n % UInt32) end Murmur3Noise() = Murmur3Noise(UInt32(0)) noise(n::UInt32, mn::Murmur3Noise) = murmur3_noise(n, mn.seed) const MURMUR3_BITS_1 = 0xcc9e2d51 const MURMUR3_BITS_2 = 0x1b873593 const MURMUR3_BITS_3 = 0xe6546b64 const MURMUR3_BITS_4 = 0x85ebca6b const MURMUR3_BITS_5 = 0xc2b2ae35 function murmur3_scramble(k::UInt32) k *= MURMUR3_BITS_1 k = (k << 15) | (k >> 17) k *= MURMUR3_BITS_2 return k end function murmur3_noise(n::UInt32, seed::UInt32) h::UInt32 = seed h ⊻= murmur3_scramble(n) h = (h << 13) | (h >> 19) h = h * UInt32(5) + MURMUR3_BITS_3 h ⊻= UInt32(4) # We're only hashing a single UInt32, so 4 bytes h ⊻= (h >> 16) h *= MURMUR3_BITS_4 h ⊻= (h >> 13) h *= MURMUR3_BITS_5 h ⊻= (h >> 16) return h end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
4249
using Random123: get_key """ ThreefryNoise{N,T,R} <: AbstractNoise{NTuple{N,T}} A noise function based on the Threefry family of CBRNGs. This is a wrapper around [`Threefry2x`](@ref) and [`Threefry4x`](@ref) from [`Random123`](@ref), except it guarrantees immutability. ## Examples ```jldoctest julia> tf = Threefry2x() Threefry2x{UInt64, 20}(0x2e5a37d3f55d93a2, 0xb2eabf28f8527ba2, 0x7c000c9ca153ea29, 0xe5cc75bfdad28187, 0x0000000000000000, 0x0000000000000000, 0) julia> tfn = ThreefryNoise(tf) ThreefryNoise{2, UInt64, 20}((0x7c000c9ca153ea29, 0xe5cc75bfdad28187)) julia> noise(1, tfn) (0xfdef457ec97615d8, 0x9813921752436c1c) ``` """ struct ThreefryNoise{N,T,R} <: AbstractNoise{NTuple{N,T}} key::NTuple{N,T} end ThreefryNoise(tf::Threefry2x{T,R}) where {T,R} = ThreefryNoise{2,T,R}(get_key(tf)) ThreefryNoise(tf::Threefry4x{T,R}) where {T,R} = ThreefryNoise{4,T,R}(get_key(tf)) @inline function noise(n::NTuple{N,T}, tf::ThreefryNoise{N,T,R}) where {N,T,R} threefry(tf.key, n, Val(R)) end """ PhiloxNoise{N,T,R,K} <: AbstractNoise{NTuple{N,T}} A noise function based on the Philox family of CBRNGs. This is a wrapper around [`Philox2x`](@ref) and [`Philox4x`](@ref) from [`Random123`](@ref), except it guarrantees immutability. ## Examples ```jldoctest julia> ph = Philox2x() Philox2x{UInt64, 10}(0x4d6efe7f510f82b6, 0xd79c03fecfefaf49, 0x429f6e3e1bf363f1, 0x0000000000000000, 0x0000000000000000, 0) julia> phn = PhiloxNoise(ph) PhiloxNoise{2, UInt64, 10, Tuple{UInt64}}((0x429f6e3e1bf363f1,)) julia> noise(1, phn) (0x968ebada8eb2b209, 0xd0669e24b96570df) ``` """ struct PhiloxNoise{N,T,R,K} <: AbstractNoise{NTuple{N,T}} key::K end PhiloxNoise(ph::Philox2x{T,R}) where {T,R} = let k = get_key(ph) PhiloxNoise{2,T,R, typeof(k)}(k) end PhiloxNoise(ph::Philox4x{T,R}) where {T,R} = let k = get_key(ph) PhiloxNoise{4,T,R, typeof(k)}(k) end @inline function noise(n::NTuple{N,T}, ph::PhiloxNoise{N,T,R}) where {N,T,R} philox(ph.key, n, Val(R)) end @static if Random123.R123_USE_AESNI """ AESNINoise <: AbstractNoise{UInt128} A wrapper around the [`AESNI1x`](@ref) and [`AESNI4x`](@ref) CRNGs from [`Random123`](@ref). Unlike the RNG variants, this noise function always outputs `UInt128`s. ## Examples ```jldoctest julia> aesni = AESNI1x() ... julia> an = AESNINoise(aesni) AESNINoise((0xcf9fea1bd8f46e10d09b5d0b2f964de2, 0x47ec4f648873a57f5087cb6f801c9664, 0x5ca479961b4836f2933b938dc3bc58e2, 0x8721cdb9db85b42fc0cd82dd53f61150, 0x998817ae1ea9da17c52c6e3805e1ece5, 0xa3028b843a8a9c2a2423463de10f2805, 0x03ae0e8ba0ac850f9a261925be055f18, 0xba5a2952b9f427d91958a2d6837ebbf3, 0x997ca98b232680d99ad2a700838a05d6, 0x9eec9b4c079032c724b6b21ebe64151e, 0x2aa5c0a9b4495be5b3d96922976fdb3c)) julia> noise(1, an) 0x323c251c4b24a822810f49c50f6d9116 ``` """ struct AESNINoise <: AbstractNoise{UInt128} key::NTuple{11,UInt128} end AESNINoise(a::Union{AESNI1x,AESNI4x}) = AESNINoise(get_key(a)) @inline noise(n::UInt128, r::AESNINoise) = aesni(r.key, (n,))[1] """ ARSNoise{R} <: AbstractNoise{UInt128} A wrapper around the [`ARS1x`](@ref) and [`ARS4x`](@ref) CRNGs from [`Random123`](@ref). ## Examples ```jldoctest julia> ars = ARS1x() ARS1x{7}((VecElement{UInt64}(0x0589cb79dfcb3d8e), VecElement{UInt64}(0x5a9b6b4946d5cc90)), (VecElement{UInt64}(0x0000000000000000), VecElement{UInt64}(0x0000000000000000)), (VecElement{UInt64}(0x83db393c26127302), VecElement{UInt64}(0xc39b0808d6985d5e))) julia> arsn = ARSNoise(ars) ARSNoise{1, 7, UInt128}((0xc39b0808d6985d5e83db393c26127302,)) julia> noise(1, arsn) (0x32a70590bb9d50acb18a3c61f2c7fc92,) ``` """ struct ARSNoise{N,R,T} <: AbstractNoise{NTuple{N,T}} key::Tuple{UInt128} end ARSNoise(a::ARS1x{R}) where R = ARSNoise{1,R,UInt128}(get_key(a)) ARSNoise(a::ARS4x{R}) where R = ARSNoise{4,R,UInt32}(get_key(a)) @inline noise(n::NTuple{N,T}, r::ARSNoise{N,R,T}) where {N,R,T} = _convert(ars(r.key, tuple(_to_bits(n)), Val(R))[1], NTuple{N,T}) @inline noise(n::Integer, r::ARSNoise{N,R,T}) where {N,R,T} = _convert(ars(r.key, tuple(n % UInt128), Val(R))[1], NTuple{N,T}) end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
2932
""" SquirrelNoise5 The SquirrelNoise5 32 bits random noise function, originally by Squirrel Eiserloh. See http://eiserloh.net/noise/SquirrelNoise5.hpp for the original C++ code. ## Fields * `seed::UInt32 = 0` seed of the noise function. ## Examples ```jldoctest julia> noise(0,SquirrelNoise5()) 0x16791e00 julia> noise(1,SquirrelNoise5()) 0xc895cb1d julia> noise(0,SquirrelNoise5(32)) 0x9ef5c661 ``` """ struct SquirrelNoise5 <: AbstractNoise{UInt32} seed::UInt32 SquirrelNoise5(n) = new(n % UInt32) end SquirrelNoise5() = SquirrelNoise5(UInt32(0)) Base.:(==)(sqn1::SquirrelNoise5, sqn2::SquirrelNoise5) = sqn1.seed == sqn2.seed const SQ5_BIT_NOISE1 = 0xd2a80a3f const SQ5_BIT_NOISE2 = 0xa884f197 const SQ5_BIT_NOISE3 = 0x6C736F4B const SQ5_BIT_NOISE4 = 0xB79F3ABB const SQ5_BIT_NOISE5 = 0x1b56c4f5 @inline noise(n::UInt32, s::SquirrelNoise5) = squirrel_noise(n, s.seed) @inline function squirrel_noise(n::UInt32, seed::UInt32) # NB. ⊻ == bitwise xor (\xor<TAB> to get the symbol) mangledbits = n mangledbits *= SQ5_BIT_NOISE1 mangledbits += seed mangledbits ⊻= (mangledbits >> 9) mangledbits += SQ5_BIT_NOISE2 mangledbits ⊻= (mangledbits >> 11) mangledbits *= SQ5_BIT_NOISE3 mangledbits ⊻= (mangledbits >> 13) mangledbits += SQ5_BIT_NOISE4 mangledbits ⊻= (mangledbits >> 15) mangledbits *= SQ5_BIT_NOISE5 mangledbits ⊻= (mangledbits >> 17) return mangledbits end """ SquirrelNoise5x2 <: AbstractNoise{UInt64} A 64 bits noise function made by stacking two `SquirrelNoise5()` together. ## Fields * `seed1::UInt32 = 0` the first seed * `seed2::UInt32 = 1` the second seed When constructing an instance with both seeds equal, a `DomainError` will be raised. ## Examples ```jldoctest julia> sqnx2 = SquirrelNoise5x2() SquirrelNoise5x2(0x00000000, 0x00000001) julia> noise(0, sqnx2) 0xd40e6352d9ba8dce julia> noise(1, sqnx2) 0x0f9b5434d68ee534 ``` """ struct SquirrelNoise5x2 <: AbstractNoise{UInt64} seed1::UInt32 seed2::UInt32 function SquirrelNoise5x2(m,n) if m == n throw(DomainError((m,n),"Constructing an instance of SquirrelNoise5x2 with identical seeds ($m). This will harm the quality of the numbers generated.")) end new(m % UInt32,n % UInt32) end end SquirrelNoise5x2() = SquirrelNoise5x2(UInt32(0),UInt32(1)) @inline function noise(n::UInt64, sqnx2::SquirrelNoise5x2) n1 = n % UInt32 n2 = (n >> 32) % UInt32 # scramble the bits to avoid problems with high bits not changing much #= alternative: r1 = squirrel_noise(n1, sqnx2.seed1) r2 = squirrel_noise(n1, sqnx2.seed2) r3 = squirrel_noise(n2, sqnx2.seed1) r4 = squirrel_noise(n2, sqnx2.seed2) r5 = r1 ⊻ r2; r6 = r3 ⊻ r4 =# n3 = squirrel_noise(n1 + n2, 0x00000000) r1 = squirrel_noise(n3, sqnx2.seed1) r2 = squirrel_noise(n3, sqnx2.seed2) (UInt64(r1) << 32) + UInt64(r2) end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
2372
# Convert an integer type to a tuple of integers while keeping as many bits as possible. # The evil pointer fiddling is to make it very fast, as creating new tuples is slower begin local int_types = [Int8, Int16, Int32, Int64, Int128] local uint_types = [UInt8, UInt16, UInt32, UInt64, UInt128] for i in eachindex(uint_types) U = uint_types[i] |> Symbol I = int_types[i] |> Symbol @eval begin @inline function _to_bits(n::Union{$I,$U})::$U n % $U end end end for i in 1:length(uint_types)-1, j in i+1:length(uint_types) U = uint_types[i] |> Symbol I = int_types[i] |> Symbol T = uint_types[j] |> Symbol N = 2^(j-i) @eval begin @inline function _to_bits(n::NTuple{$N,S})::$T where {S <: Union{$U,$I}} unsafe_load(Ptr{$T}(pointer_from_objref(Ref(n)))) end @inline function _convert(n::Integer, ::Type{NTuple{$N,$U}}) unsafe_load(Ptr{NTuple{$N,$U}}(pointer_from_objref(Ref(n % $T)))) end end end @inline function _convert(n::Union{Int64,UInt64}, ::Type{NTuple{4,UInt64}})::NTuple{4,UInt64} (n % UInt64, zero(UInt64), zero(UInt64), zero(UInt64)) end @inline function _convert(n::Integer, ::Type{Tuple{T}}) where T <: Integer (n % T,) end @inline function _convert(n::NTuple{N,<:Integer}, ::Type{S})::S where {N,S<:Integer} _to_bits(n) % S end end """ noise_convert(r::Integer, ::Type{AbstractFloat}) Convert an integer to a floating point number in [0,1). This is intended to be used with random number generators, so the output is uniformly distributed over [0,1). """ function noise_convert end @inline function noise_convert(r::N, ::Type{Float64}) where {N<:Union{UInt8,UInt16,UInt32}} r * exp2(-sizeof(N) << 3) end # NB. copied from https://github.com/JuliaLang/julia/blob/701468127a335d130e968a8a180021e4287abf3f/stdlib/Random/src/Xoshiro.jl#L204-L211 @inline function noise_convert(r::UInt16, ::Type{Float16}) Float16(Float32(r >>> 5) * Float32(0x1.0p-11)) end @inline function noise_convert(r::UInt32, ::Type{Float32}) Float32(r >>> 8) * Float32(0x1.0p-24) end @inline function noise_convert(r::UInt64, ::Type{Float64}) Float64(r >>> 11) * 0x1.0p-53 end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
1046
""" pairing2(i,j) The Hopcroft-Ullman pairing function, which bijectively maps two positive integers to a positive integer. See https://mathworld.wolfram.com/PairingFunction.html """ @inline pairing2(i,j) = div((i+j-2)*(i+j-1),2) + i @inline pairing3(i,j,k) = pairing2(pairing2(i,j),k) @inline pairing4(i,j,k,l) = pairing2(pairing2(i,j),pairing2(k,l)) @inline pairing5(i,j,k,l,m) = pairing2(pairing2(i,j), pairing3(k,l,m)) @inline pairing6(i,j,k,l,m,n) = pairing2(pairing2(i,j), pairing4(k,l,m,n)) @inline pairing7(i,j,k,l,m,n,o) = pairing2(pairing3(i,j,k), pairing4(l,m,n,o)) @inline pairing8(i,j,k,l,m,n,o,p) = pairing2(pairing4(i,j,k,l), pairing4(m,n,o,p)) function pairing(idx...) x = [idx...] n = length(x) while n > 1 k = div(n,2) for i in 1:k x[i] = pairing2(x[2i-1], x[2i]) end if isodd(n) x[k+1] = x[n] n = k+1 else n = k end end return x[1] end pairing(t::Tuple{Vararg{Integer,N}}) where N = pairing(t...)
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
604
@inline function noise_getindex(rng::AbstractNoise, transform, i, ::Type{T}) where T convert(T, transform(noise(i, rng))) end @inline noise_getindex(rng::AbstractNoise, transform, i) = transform(noise(i, rng)) """ NoiseUniform{T} The generic transform for converting the default output of noise functions to uniformly distributed values of type `T`. For floating point numbers, the values are uniformly distributed in the interval [0,1). """ struct NoiseUniform{T<:AbstractFloat} end @inline noise_getindex(rng::AbstractNoise, ::NoiseUniform{T}, i) where T = noise_convert(noise(i,rng), T)
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
2089
import RandomNoise: noise_convert, _to_bits, _convert @testset "Conversion" begin @testset "to_bits" begin uints = [UInt8,UInt16,UInt32,UInt64,UInt128] ints = [Int8,Int16,Int32,Int64,Int128] for (u,i) in zip(uints, ints) @test _to_bits(i(1)) == u(1) end for i in 1:length(uints)-1, j in i+1:length(uints) U = uints[i] I = ints[i] T = uints[j] N = 2^(j-i) @test typeof(_to_bits(tuple(ones(I,N)...))) == T @test typeof(_to_bits(tuple(ones(U,N)...))) == T end end @testset "noise_convert" begin @test typeof(noise_convert(0x01, Float64)) == Float64 @test noise_convert(0x00, Float64) == 0.0 @test noise_convert(typemax(UInt8), Float64) < 1.0 @test typeof(noise_convert(0x0001, Float64)) == Float64 @test noise_convert(0x0000, Float64) == 0.0 @test noise_convert(typemax(UInt16), Float64) < 1.0 @test typeof(noise_convert(0x0000001, Float64)) == Float64 @test noise_convert(0x00000000, Float64) == 0.0 @test noise_convert(typemax(UInt32), Float64) < 1.0 @test typeof(noise_convert(0x0001, Float16)) == Float16 @test noise_convert(0x0000, Float16) == Float16(0.0) @test noise_convert(typemax(UInt16), Float16) < 1.0 @test typeof(noise_convert(0x00000001, Float32)) == Float32 @test noise_convert(0x00000000, Float32) == Float32(0.0) @test noise_convert(typemax(UInt32), Float32) < 1.0 @test typeof(noise_convert(0x0000000000000001, Float64)) == Float64 @test noise_convert(0x0000000000000000, Float64) == 0.0 @test noise_convert(typemax(UInt64), Float64) < 1.0 end @testset "_convert" begin uints = [UInt8,UInt16,UInt32,UInt64,UInt128] ints = [Int8,Int16,Int32,Int64,Int128] for i in 1:length(uints)-1, j in i+1:length(uints) U = uints[i] I = ints[i] T = uints[j] N = 2^(j-i) @test typeof(_convert(T(1), NTuple{N,U})) == NTuple{N,U} @test typeof(_convert(tuple(ones(U,N)...), U)) == U end end end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
415
using RandomNoise: noise_getindex using Distributions @testset "Distributions compat" begin sqn = SquirrelNoise5() @test typeof(NoiseMap(sqn, Normal(0,1))) == NoiseMap{Float64,1,SquirrelNoise5,Normal{Float64}} @test typeof(noise_getindex(sqn, Normal(0,1), 1)) == Float64 @test typeof(noise_getindex(sqn, Bernoulli(0.5), 1)) == Bool @test typeof(noise_getindex(sqn, Poisson(1), 1)) == Int end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
1464
@testset "Noise" begin @testset "SquirrelNoise5" begin @test SquirrelNoise5() == SquirrelNoise5(0x00000000) @test SquirrelNoise5(1) == SquirrelNoise5(0x00000001) sqn = SquirrelNoise5() @test typeof(noise(0,sqn)) == UInt32 @test noise(0x00000000, sqn) == 0x16791e00 @test noise(0, sqn) == 0x16791e00 @test noise(0x00000001,sqn) == 0xc895cb1d @test noise(1, sqn) == 0xc895cb1d sqn1 = SquirrelNoise5(1) @test noise(0x00000000, sqn1) == 0x23f6c851 @test noise(0, sqn1) == 0x23f6c851 @test noise(0x00000001, sqn1) == 0x98b75d40 @test noise(1, sqn1) == 0x98b75d40 end @testset "SquirrelNoise5x2" begin @test SquirrelNoise5x2() == SquirrelNoise5x2(0,1) @test_throws DomainError SquirrelNoise5x2(0,0) sqn = SquirrelNoise5x2() @test typeof(noise(0, sqn)) == UInt64 @test noise(0, sqn) == 0xd40e6352d9ba8dce @test noise(1, sqn) == 0x0f9b5434d68ee534 end @testset "Murmur3Noise" begin @test Murmur3Noise() == Murmur3Noise(0x00000000) @test Murmur3Noise(1) == Murmur3Noise(0x00000001) m3n = Murmur3Noise() @test typeof(noise(0, m3n)) == UInt32 @test noise(0x00000000, m3n) == 0x2362f9de @test noise(0, m3n) == noise(0x00000000, m3n) @test noise(0x00000001, m3n) == 0xfbf1402a @test noise(1, m3n) == noise(0x00000001, m3n) end end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
2071
using RandomNoise: pairing, pairing2, pairing3, pairing4, pairing5, pairing5, pairing6, pairing7, pairing8 @testset "NoiseMap" begin @testset "Constructors" begin sqn = SquirrelNoise5() @test NoiseMap(sqn) == NoiseMap(sqn, identity, 1) @test typeof(NoiseMap(sqn, 2)) == NoiseMap{UInt32,2,SquirrelNoise5,typeof(identity)} @test NoiseMap(sqn, 2) === NoiseMap(sqn, identity, 2) @test NoiseMap(sqn, identity, 2) === NoiseMap{UInt32}(sqn, identity, 2) @test NoiseMap(sqn, identity, 2) === NoiseMap{UInt32,2}(sqn, identity) @test typeof(NoiseMap(sqn, sin)) == NoiseMap{Float64,1,SquirrelNoise5,typeof(sin)} @test typeof(NoiseMap(sqn, NoiseUniform{Float64}())) == NoiseMap{Float64,1,SquirrelNoise5,NoiseUniform{Float64}} end @testset "Indexing" begin @testset "1D Indexing" begin nm = NoiseMap(SquirrelNoise5(), 1) @test typeof(nm(1)) == UInt32 @test nm(1) == noise(1, nm.noise) @test nm[1] == nm(1) end #=@testset "2D Indexing" begin nm = NoiseMap(SquirrelNoise5(), 2) @test nm(1,1) == nm(1) @test nm(1,2) == nm(pairing2(1,2)) @test nm[1,1] == nm(1,1) end @testset "3D Indexing" begin nm = NoiseMap(SquirrelNoise5(), 3) @test nm(1,1,1) == nm(1) @test nm(1,2,3) == nm(pairing3(1,2,3)) @test nm[1,1] == nm(1,1) end =# for (n,p) in zip(2:8, [:pairing2, :pairing3, :pairing4, :pairing5, :pairing6, :pairing7, :pairing8]) @eval begin nm = NoiseMap(SquirrelNoise5(), $n) @test nm(ones(Int,$n)...) == nm(1) @test nm(1:($n)...) == nm($p(1:($n)...)) end end @testset "Default indexing" begin nm = NoiseMap(SquirrelNoise5(), 9) @test nm((1,2,3,4,5,6,7,8,9)) == nm(1,2,3,4,5,6,7,8,9) @test nm(1,2,3,4,5,6,7,8,9) == nm(pairing(1,2,3,4,5,6,7,8,9)) end end end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
1099
const bit_types = [Bool, UInt8, UInt16, UInt32, UInt64, UInt128, Int8, Int16, Int32, Int64, Int128] @testset "NoiseRNG" begin @testset "RNG utils" begin local rng1 = NoiseRNG(SquirrelNoise5()) local rng2 = NoiseRNG(SquirrelNoise5()) @test RandomNoise.rng_native_52(rng1) == UInt64 @test rand(rng1, Random.SamplerType{Bool}()) == rand(rng2, Bool) end @testset "SquirrelNoise5 RNG" begin local rng = NoiseRNG(SquirrelNoise5()) @test typeof(rand(rng)) == Float64 @test copy(rng) == rng @test copy!(copy(rng), rng) == rng end @testset "SquirrelNoise5x2 RNG" begin local rng = NoiseRNG(SquirrelNoise5x2()) @test typeof(rand(rng)) == Float64 @test copy(rng) == rng @test copy!(copy(rng), rng) == rng end @testset "Bit types RNG" begin local rng1 = NoiseRNG(SquirrelNoise5()) #local rng2 = NoiseRNG(HashNoise()) for T in bit_types @test typeof(rand(rng1, T)) == T #@test typeof(rand(rng2, t)) == t end end end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
2415
using RandomNoise: pairing2, pairing3, pairing4, pairing5, pairing6, pairing7, pairing8, pairing @testset "Pairing Functions" begin @testset "pairing2" begin @test typeof(pairing2(1,1)) == Int @test pairing2(1,1) == 1 @test pairing2(1,2) == 2 @test pairing2(2,1) == 3 end @testset "pairing3" begin @test typeof(pairing3(1,1,1)) == Int @test pairing3(1,1,1) == 1 @test pairing3(1,1,2) == 2 @test pairing3(2,1,1) == 6 @test pairing3(1,2,1) == 3 end @testset "pairing4" begin @test typeof(pairing4(1,1,1,1)) == Int @test pairing4(1,1,1,1) == 1 @test pairing4(2,1,1,1) == 6 @test pairing4(1,2,1,1) == 3 @test pairing4(1,1,2,1) == 4 @test pairing4(1,1,1,2) == 2 end @testset "pairing5" begin @test typeof(pairing5(1,1,1,1,1)) == Int @test pairing5(1,1,1,1,1) == 1 @test pairing5(2,1,1,1,1) == 6 @test pairing5(1,2,1,1,1) == 3 @test pairing5(1,1,2,1,1) == 16 @test pairing5(1,1,1,2,1) == 4 @test pairing5(1,1,1,1,2) == 2 end @testset "pairing6" begin @test typeof(pairing6(1,1,1,1,1,1)) == Int @test pairing6(1,1,1,1,1,1) == 1 @test pairing6(2,1,1,1,1,1) == 6 @test pairing6(1,2,1,1,1,1) == 3 @test pairing6(1,1,2,1,1,1) == 16 @test pairing6(1,1,1,2,1,1) == 4 @test pairing6(1,1,1,1,2,1) == 7 @test pairing6(1,1,1,1,1,2) == 2 end @testset "pairing7" begin @test typeof(pairing7(1,1,1,1,1,1,1)) == Int @test pairing7(1,1,1,1,1,1,1) == 1 @test pairing7(2,1,1,1,1,1,1) == 21 @test pairing7(1,2,1,1,1,1,1) == 6 @test pairing7(1,1,2,1,1,1,1) == 3 @test pairing7(1,1,1,2,1,1,1) == 16 @test pairing7(1,1,1,1,2,1,1) == 4 @test pairing7(1,1,1,1,1,2,1) == 7 @test pairing7(1,1,1,1,1,1,2) == 2 end @testset "pairing8" begin @test typeof(pairing8(1,1,1,1,1,1,1,1)) == Int @test pairing8(1,1,1,1,1,1,1,1) == 1 end @testset "pairing" begin @test typeof(pairing(1,1)) == Int @test pairing(1) == 1 @test pairing(1,1) == 1 @test pairing((1,1)) == pairing(1,1) @test pairing(1,2) == pairing2(1,2) @test pairing(1,2,3) == pairing3(1,2,3) @test pairing(1,2,3,4) == pairing4(1,2,3,4) end end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
2005
@testset "Random123" begin @testset "ThreefryNoise" begin @testset "Threefry2x" begin local tf = Threefry2x() local tfn = ThreefryNoise(tf) @test typeof(noise(0,tfn)) == Tuple{UInt64,UInt64} @test noise(0, tfn) == rand(tf, Tuple{UInt64,UInt64}) end @testset "Threefry4x" begin local tf = Threefry4x() local tfn = ThreefryNoise(tf) @test typeof(noise(0,tfn)) == NTuple{4,UInt64} end end @testset "PhiloxNoise" begin @testset "Philox2x" begin local ph = Philox2x() local phn = PhiloxNoise(ph) @test typeof(noise(0, phn)) == NTuple{2,UInt64} @test noise(0, phn) == rand(ph, NTuple{2,UInt64}) end @testset "Philox4x" begin local ph = Philox4x() local phn = PhiloxNoise(ph) @test typeof(noise(0, phn)) == NTuple{4,UInt64} @test noise(0, phn) == rand(ph, NTuple{4,UInt64}) end end if Random123.R123_USE_AESNI @testset "AESNINoise" begin @testset "AESNI1x" begin local aesni = AESNI1x() local an = AESNINoise(aesni) @test typeof(noise(0,an)) == UInt128 @test noise(1,an) == rand(aesni, UInt128) end end @testset "ARSNoise" begin @testset "ARS1x" begin local ars = ARS1x() local arsn = ARSNoise(ars) @test typeof(noise(0, arsn)) == Tuple{UInt128} @test noise(1, arsn) == rand(ars, Tuple{UInt128}) end @testset "ARS4x" begin local ars = ARS4x() local arsn = ARSNoise(ars) x = UInt32.((0,1,2,3)) @test typeof(noise(x, arsn)) == NTuple{4,UInt32} # ??? @test noise(0, arsn) == rand(ars, NTuple{4,UInt32}) end end end end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
389
using RandomNoise using Random123 using Random using Distributions using Test using Aqua @testset "RandomNoise.jl" begin include("pairing_functions.jl") include("noise.jl") include("random123.jl") include("convert.jl") include("noise_rng.jl") include("noise_maps.jl") include("transforms.jl") include("distributions.jl") Aqua.test_all(RandomNoise) end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
code
252
using RandomNoise: noise_getindex @testset "Transforms" begin sqn = SquirrelNoise5() @test typeof(noise_getindex(sqn, identity, 1, UInt64)) == UInt64 nu = NoiseUniform{Float32}() @test typeof(noise_getindex(sqn, nu, 1)) == Float32 end
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
docs
7376
# RandomNoise.jl [![Build Status](https://github.com/csimal/RandomNoise.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/csimal/RandomNoise.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/csimal/RandomNoise.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/csimal/RandomNoise.jl) [![Aqua QA](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl) This package provides a minimalist interface for using noise functions as an alternative to pseudorandom number generators. Noise functions, also known as Counter-Based RNGs are another approach to traditional PRNGs, which have several advantages for parallel computation and procedural generation. While this package allows using noise functions as sequential RNGs, it is mostly focused on using them as streams of random values that can be indexed in any order at constant cost and memory overhead. ## Using noise functions RandomNoise.jl defines an `AbstractNoise` type for all noise functions. All implementations of `AbstractNoise` must implement a single method `noise(n,rng)` that returns the `n`-th term of the sequence generated by the noise function. ```julia-repl julia> sqn = SquirrelNoise5() SquirrelNoise5(0x00000000) julia> noise(1, sqn) 0xc895cb1d ``` Additionally, most noise functions can be provided with a seed. Unlike PRNGs, this generates a completely different sequence, rather than jumping at a different point in the same sequence. ```julia-repl julia> sqn = SquirrelNoise5(42) SquirrelNoise5(0x0000002a) julia> noise(1, sqn) 0xd6c56929 ``` ## Noise functions implemented in this package RandomNoise.jl currently provides three noise functions * `SquirrelNoise5` a 32-bit noise function, originally by [Squirrel Eiserloh](https://pastebin.com/dVZcMJJQ) * `SquirrelNoise5x2` a 64-bit noise function, consisting of two stacked `SquirrelNoise5` * `Murmur3Noise` a 32-bit noise function based on the Murmur3 hash function In addition, support for [Random123.jl](https://github.com/JuliaRandom/Random123.jl)'s CBRNGs is provided via immutable wrapper types. Both RandomNoise and Random123 need to be loaded to use them. ```julia using RandomNoise using Random123 rng = Threefry2x() tfn = ThreefryNoise(rng) noise(0, tfn) ``` The noise functions implemented in this package are more lightweight, but all fail some tests on BigCrush (see Benchmarks below). Use the ones from Random123 if you want some battle-tested generators. ## Noise Maps Being able to generate random integers on demand is all well and good, but most of the time we'd like to use other types of random values, floating point numbers, for example. For this purpose, we provide a special type called `NoiseMap` that wraps around a noise function and a transform that maps the output of the noise function to some desired values. ```julia-repl julia> nm = NoiseMap(SquirrelNoise5(), sin) NoiseMap{Float64, 1, SquirrelNoise5, typeof(sin)}(SquirrelNoise5(0x00000000), sin) ``` The resulting object can called just like any function ```julia-repl julia> nm(1) 0.013299689581968843 julia> nm.(1:5) 5-element Vector{Float64}: 0.013299689581968843 0.9728924552038383 -0.9468531800274045 -0.5680157365140597 -0.03113989875496316 ``` It can also be indexed like an array ```julia-repl julia> nm[1] 0.013299689581968843 ``` By default, noise maps are "one-dimensional", but can be defined for arbitrary dimensions ```julia-repl julia> nm2 = NoiseMap(SquirrelNoise5(), sin, 2) NoiseMap{Float64, 2, SquirrelNoise5, typeof(sin)}(SquirrelNoise5(0x00000000), sin) julia> nm2(1,1) 0.013299689581968843 ``` Beside a function, the transform can also be an instance of `NoiseUniform`, a special type to generate floating point numbers uniformly distributed in the interval `[0,1)`. ```julia-repl julia> nm3 = NoiseMap(SquirrelNoise5(), NoiseUniform{Float64}()) NoiseMap{Float64, 1, SquirrelNoise5, NoiseUniform{Float64}}(SquirrelNoise5(0x00000000), NoiseUniform{Float64}()) ``` Finally, when passing a `UnivariateDistribution` from [Distributions.jl](https://juliastats.org/Distributions.jl/stable/), the output values are samples from that distribution ```julia-repl julia> nm4 = NoiseMap(SquirrelNoise5(), Normal(0,1)) NoiseMap{Float64, 1, SquirrelNoise5, Normal{Float64}}(SquirrelNoise5(0x00000000), Normal{Float64}(μ=0.0, σ=1.0)) julia> nm4.(1:5) 5-element Vector{Float64}: 0.7841899388190731 0.5263725651428768 0.14096081624298265 0.6549392209760272 0.18955444371040095 ``` ## Using noise functions in `rand()` Any noise function can be used as a sequential PRNG simply by creating a counter and incrementing it each time a new number is generated. Examples of such *Counter Based RNGs* (CBRNGs) can be found in the [Random123.jl](https://github.com/JuliaRandom/Random123.jl) package. The noise functions defined in this package can be made into CBRNGs by passing them to a `NoiseRNG` object. ```julia-repl julia> rng = NoiseRNG(SquirrelNoise5()) NoiseRNG{UInt32, SquirrelNoise5}(SquirrelNoise5(0x00000000), 0x00000000) julia> rand(rng) 0.08778560161590576 ``` Note: Since Random123.jl already defines `rand` for it's CBRNGs, we do not support passing them to `NoiseRNG`. --- ## Noise functions vs PRNGs This [GDC 2017 talk](https://www.youtube.com/watch?v=LWFzPP8ZbdU) by Squirrel Eiserloh is an excellent introduction to noise functions and their practical applications. Traditional Pseudo Random Number Generators (PRNGs) work by repeatedly applying a map that scrambles the bits of its inputs, starting from a given seed, so that when generating a sequence of pseudorandom numbers, the `n`-th term is the result of applying that map `n` times to the seed. This has several downsides. First, PRNGs need to hold a state that gets mutated every time a new number is generated, making them ill-suited to parallel workflows. Second, the generated numbers can only be computed in order, so if one wants to access a sequence of pseudorandom numbers out of order, the best way is often to just store it in memory. A third downside is that changing the seed of the generator usually just jumps to a different point in the sequence, so when using multiple seeds in parallel, it's possible for two generators to synchronize with each other. Noise Functions/CBRNGs on the other hand, work by applying a bit-scrambling map once. That is, the `n`-th number in the sequence is computed by `noise(n)`. These solve a lot of the problems with traditional PRNGs. They have no mutable state, and the sequence of numbers can be accessed out of order and at constant cost, making them ideal for parallel workflows. Furthermore, because the sequence of numbers can be accessed out of order, this removes the need to store them in memory for performance. Lastly, changing the seed of a noise function generates a completely different sequence, which means that we don't run into the problem of different generators catching up with each other. ## Benchmarks The `SquirrelNoise5`, `SquirrelNoise5x2` and `Murmur3Noise` were tested with the BigCrush benchmark from [RNGTest](https://github.com/JuliaRandom/RNGTest.jl). Both variants of SquirrelNoise5 fail 8 tests (Gap and MaxOft), while Murmur3Noise fails 10 (BirthdaySpacings, Gap, MaxOft and SumCollector). See `benchmarks/results` for more details.
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.1.2
f395d4f8437d769e0f2032a8770f9159b6ee8471
docs
174
```@meta CurrentModule = NoiseRNG ``` # NoiseRNG Documentation for [NoiseRNG](https://github.com/csimal/NoiseRNG.jl). ```@index ``` ```@autodocs Modules = [NoiseRNG] ```
RandomNoise
https://github.com/csimal/RandomNoise.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
1330
using CGcoefficient using BenchmarkTools function calculate_lsjj(test_range::AbstractArray) sum = 0.0 for l1 in test_range for l2 in test_range for (dj1, dj2) in [(2l1-1, 2l2-1), (2l1-1, 2l2+1), (2l1+1, 2l2-1), (2l1+1, 2l2+1)] for L in abs(l1-l2):(l1+l2) for (S, J) in [(0, L), (1, L-1), (1, L), (1, L+1)] sum += flsjj(l1, l2, dj1, dj2, L, S, J) end end end end end return sum end function calculate_norm9j(test_range::AbstractArray) sum = 0.0 for l1 in test_range for l2 in test_range for (dj1, dj2) in [(2l1-1, 2l2-1), (2l1-1, 2l2+1), (2l1+1, 2l2-1), (2l1+1, 2l2+1)] for L in abs(l1-l2):(l1+l2) for (S, J) in [(0, L), (1, L-1), (1, L), (1, L+1)] sum += fnorm9j(2l1, 1, dj1, 2l2, 1, dj2, 2L, 2S, 2J) end end end end end return sum end test_range = 0:10 t1 = @belapsed calculate_lsjj(test_range) t2 = @belapsed calculate_norm9j(test_range) println("diff = ", calculate_lsjj(test_range) - calculate_norm9j(test_range)) println("lsjj time = $(t1)s") println("norm9j time = $(t2)s")
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
3143
push!(LOAD_PATH, "../src/") using CGcoefficient using BenchmarkTools using Test # wapper of gsl 3nj functions function gsl3j(dj1::Int, dj2::Int, dj3::Int, dm1::Int, dm2::Int, dm3::Int) ccall( (:gsl_sf_coupling_3j, "libgsl"), Cdouble, (Cint, Cint, Cint, Cint, Cint, Cint), dj1, dj2, dj3, dm1, dm2, dm3 ) end function gsl6j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int) ccall( (:gsl_sf_coupling_6j, "libgsl"), Cdouble, (Cint, Cint, Cint, Cint, Cint, Cint), dj1, dj2, dj3, dj4, dj5, dj6 ) end function gsl9j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int, dj7::Int, dj8::Int, dj9::Int) ccall( (:gsl_sf_coupling_9j, "libgsl"), Cdouble, (Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint), dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9 ) end function calculate_3j(func::Function, test_range::AbstractArray) if func == f3j wigner_init_float(cld(maximum(test_range), 2), "Jmax", 3) end sum = 0.0 for dj1 in test_range for dj2 in test_range for dj3 in test_range for dm1 in -dj1:2:dj1 for dm2 in -dj2:2:dj2 dm3 = -dm1-dm2 sum += func(dj1, dj2, dj3, dm1, dm2, dm3) end end end end end return sum end function calculate_6j(func::Function, test_range::AbstractArray) if func == f6j wigner_init_float(cld(maximum(test_range), 2), "Jmax", 6) end sum = 0.0 for j1 in test_range for j2 in test_range for j3 in test_range for j4 in test_range for j5 in test_range for j6 in test_range sum += func(j1, j2, j3, j4, j5, j6) end end end end end end return sum end function calculate_9j(func::Function, test_range::AbstractArray) if func == f9j wigner_init_float(cld(maximum(test_range), 2), "Jmax", 9) end sum = 0.0 for j1 in test_range for j2 in test_range for j3 in test_range for j4 in test_range for j5 in test_range for j6 in test_range for j7 in test_range for j8 in test_range for j9 in test_range sum += func(j1,j2,j3,j4,j5,j6,j7,j8,j9) end end end end end end end end end return sum end test_range = 40:50 t1 = @belapsed calculate_3j(f3j, test_range) t2 = @belapsed calculate_3j(gsl3j, test_range) println("diff = ", calculate_3j(f3j, test_range) - calculate_3j(gsl3j, test_range)) println("f3j time = $(t1)s") println("gsl3j time = $(t2)s") test_range = 45:60 t1 = @belapsed calculate_6j(f6j, test_range) t2 = @belapsed calculate_6j(gsl6j, test_range) println("diff = ", calculate_6j(f6j, test_range) - calculate_6j(gsl6j, test_range)) println("f6j time = $(t1)s") println("gsl6j time = $(t2)s") test_range = 30:35 t1 = @belapsed calculate_9j(f9j, test_range) t2 = @belapsed calculate_9j(gsl9j, test_range) println("diff = ", calculate_9j(f9j, test_range) - calculate_9j(gsl9j, test_range)) println("f9j time = $(t1)s") println("gsl9j time = $(t2)s")
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
361
using Documenter push!(LOAD_PATH, "../src/") using CGcoefficient makedocs( modules = [CGcoefficient], sitename = "CGcoefficient.jl", clean = false, pages = [ "Home" => "index.md", "Formula" => "formula.md", "API" => "api.md" ] ) deploydocs( repo = "github.com/0382/CGcoefficient.jl.git", target = "build/" )
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
961
module CGcoefficient export CG, CG0, threeJ, sixJ, nineJ, Racah, dCG, d3j, d6j, d9j, dRacah, lsjj, norm9J, Moshinsky, SqrtRational, exact_sqrt, simplify, HalfInt, iphase, is_same_parity, check_jm, check_couple, binomial_data_size, binomial_index, fCG, fCG0, f3j, f6j, f9j, fRacah, fbinomial, unsafe_fbinomial, fMoshinsky, dfunc, flsjj, fCGspin, fnorm9j, wigner_init_float include("SqrtRational.jl") include("util.jl") include("WignerSymbols.jl") include("floatWignerSymbols.jl") function __init__() global _fbinomial_nmax = 67 global _fbinomial_data = Vector{Float64}(undef, binomial_data_size(get_fbinomial_nmax())) for n = 0:get_fbinomial_nmax() for k = 0:div(n, 2) get_fbinomial_data()[binomial_index(n, k)] = binomial(UInt64(n), UInt64(k)) end end nothing end end # module CGcoefficient
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
6953
import Base: +, -, *, /, == using Markdown using Primes """ SqrtRational <: Real Store exact value of a `Rational`'s square root. It is stored in `s√r` format, and we do not simplify it during arithmetics. You can use the `simplify` function to simplify it. """ struct SqrtRational{T} <: Real s::Rational{T} r::Rational{T} SqrtRational{T}(s::Rational{T}, r::Rational{T}) where {T} = begin r < 0 && throw(ArgumentError("invalid SqrtRational $s√$r")) (iszero(s) || iszero(r)) && return new(zero(s), one(r)) new(s, r) end end SqrtRational(s::Rational{T1}, r::Rational{T2}) where {T1,T2} = SqrtRational{promote_type(T1, T2)}(promote(s, r)...) SqrtRational(s::Integer, r::Rational{T}) where {T} = SqrtRational(promote(s, r)...) SqrtRational(s::Rational{T}, r::Integer) where {T} = SqrtRational(promote(s, r)...) SqrtRational(s::Integer, r::Integer) = SqrtRational(promote(Rational(s), r)...) SqrtRational(s::Union{Integer,Rational}) = SqrtRational(s, one(s)) """ exact_sqrt(r::Union{Integer, Rational}) Get exact `√r` using `SqrtRational` type. """ exact_sqrt(r::Union{Integer,Rational}) = SqrtRational(one(r), r) # some basic functions Base.zero(::Type{SqrtRational{T}}) where {T} = SqrtRational(zero(T), one(T)) Base.one(::Type{SqrtRational{T}}) where {T} = SqrtRational(one(T), one(T)) Base.zero(x::SqrtRational) = zero(typeof(x)) Base.one(x::SqrtRational) = one(typeof(x)) Base.sign(x::SqrtRational) = sign(x.s) Base.signbit(x::SqrtRational) = signbit(x.s) Base.inv(x::SqrtRational) = SqrtRational(inv(x.s), inv(x.r)) # override some operators +(x::SqrtRational) = x -(x::SqrtRational) = SqrtRational(-x.s, x.r) *(x::SqrtRational, y::SqrtRational) = SqrtRational(x.s * y.s, x.r * y.r) *(x::SqrtRational, y::Union{Integer,Rational}) = SqrtRational(x.s * y, x.r) *(x::Union{Integer,Rational}, y::SqrtRational) = y * x /(x::SqrtRational, y::SqrtRational) = SqrtRational(x.s / y.s, x.r / y.r) /(x::SqrtRational, y::Union{Integer,Rational}) = SqrtRational(x.s / y, x.r) /(x::Union{Integer,Rational}, y::SqrtRational) = SqrtRational(x / y.s, inv(y.r)) ==(x::SqrtRational, y::SqrtRational) = begin if y.s == 0 return x.s == 0 else isone((x.s / y.s)^2 * (x.r / y.r)) end end ==(x::SqrtRational, y::Union{Integer,Rational}) = (x == SqrtRational(y)) ==(x::Union{Integer,Rational}, y::SqrtRational) = (SqrtRational(x) == y) # Only if `r == 1` in `s√r`, the add operator can work. # We do not simplify `s√r` every time, but in this function, # we need to simplify it first, and then do the `+` operator. +(x::SqrtRational, y::Union{Integer,Rational}) = begin r = x.r t1 = isqrt(numerator(r)) t1 * t1 != numerator(r) && throw(ArgumentError("cannot simplify $(x)")) t2 = isqrt(denominator(r)) t2 * t2 != denominator(r) && throw(ArgumentError("cannot simplify $(x)")) return x.s * (t1 // t2) + y end +(x::Union{Integer,Rational}, y::SqrtRational) = y + x +(x::SqrtRational{T1}, y::SqrtRational{T2}) where {T1,T2} = begin if x == 0 return y else return x * (one(promote_type(T1, T2)) + y / x) end end -(x::SqrtRational, y::Union{Integer,Rational}) = (x + (-y)) -(x::Union{Integer,Rational}, y::SqrtRational) = (x + (-y)) -(x::SqrtRational, y::SqrtRational) = (x + (-y)) # widen Base.widen(x::SqrtRational) = SqrtRational(widen(x.s), widen(x.r)) # convert """ float(x::SqrtRational)::Float64 Although we use `BigInt` in calculation, we do not convert it to `BigFloat`. Because this package is designed for numeric calculation, `BigFloat` is unnecessary. """ Base.float(x::SqrtRational) = Float64(x.s) * sqrt(Float64(x.r)) # show Base.show(io::IO, ::MIME"text/plain", x::SqrtRational) = begin if isone(x.r) if denominator(x.s) == 1 print(io, numerator(x.s)) else print(io, x.s) end return elseif isone(x.s) if denominator(x.r) == 1 print(io, "√$(numerator(x.r))") else print(io, "√($(x.r))") end return elseif isone(-x.s) if denominator(x.r) == 1 print(io, "-√$(numerator(x.r))") else print(io, "-√($(x.r))") end return end to_show::String = "" if denominator(x.s) == 1 to_show = string(numerator(x.s)) else to_show = "$(x.s)" end if denominator(x.r) == 1 to_show *= "√$(numerator(x.r))" else to_show *= "√($(x.r))" end print(io, to_show) end Base.show(io::IO, x::SqrtRational) = show(io::IO, "text/plain", x) Base.show(io::IO, ::MIME"text/markdown", x::SqrtRational) = begin if isone(x.r) if denominator(x.s) == 1 show(io, "text/markdown", Markdown.parse("``$(numerator(x.s))``")) else show(io, "text/markdown", Markdown.parse("``\\frac{$(numerator(x.s))}{$(denominator(x.s))}``")) end return elseif isone(x.s) if denominator(x.r) == 1 show(io, "text/markdown", Markdown.parse("``\\sqrt{$(numerator(x.r))}``")) else show(io, "text/markdown", Markdown.parse("``\\sqrt{\\frac{$(numerator(x.r))}{$(denominator(x.r))}}``")) end return elseif isone(-x.s) if denominator(x.r) == 1 show(io, "text/markdown", Markdown.parse("``-\\sqrt{$(numerator(x.r))}``")) else show(io, "text/markdown", Markdown.parse("``-\\sqrt{\\frac{$(numerator(x.r))}{$(denominator(x.r))}}``")) end return end to_show::String = "" if denominator(x.s) == 1 to_show = string(numerator(x.s)) else to_show = "\\frac{$(numerator(x.s))}{$(denominator(x.s))}" end if denominator(x.r) == 1 to_show *= "\\sqrt{$(numerator(x.r))}" else to_show *= "\\sqrt{\\frac{$(numerator(x.r))}{$(denominator(x.r))}}" end show(io, "text/markdown", Markdown.parse("``$to_show``")) end """ simplify(n::Integer) Simplify a integer `n = x * t^2` to `(x, t)` """ function simplify(n::Integer) s = sign(n) n = s * n x = one(n) t = one(n) for (f, i) in factor(n) ti, xi = divrem(i, 2) xi == 1 && (x = x * f) ti != 0 && (t = t * f^ti) end return s * x, t end """ simplify(x::SqrtRational) Simplify a SqrtRational. """ function simplify(x::SqrtRational) nx, nt = simplify(numerator(x.r)) dx, dt = simplify(denominator(x.r)) nt *= numerator(x.s) dt *= denominator(x.s) a0 = gcd(nt, dt) nt = div(nt, a0) dt = div(dt, a0) a1 = gcd(nx, dt) a2 = gcd(dx, nt) dt = div(dt, a1) nt = div(nt, a2) dx = div(dx, a2) * a1 nx = div(nx, a1) * a2 return SqrtRational(nt // dt, nx // dx) end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
18538
# This file contains the core functions of WignerSymbols and CG-coefficient. """ HalfInt = Union{Integer, Rational} Angular momentum quantum numbers may be half integers and integers. With `HalfInt` type, you can use both `2` and `3//2` as parameters. But the parameter like `5//3`, who's denominator is not `2` while gives out error. """ const HalfInt = Union{Integer,Rational} # basic CG coefficient calculation function function _dCG(dj1::BigInt, dj2::BigInt, dj3::BigInt, dm1::BigInt, dm2::BigInt, dm3::BigInt) check_jm(dj1, dm1) || return zero(SqrtRational) check_jm(dj2, dm2) || return zero(SqrtRational) check_jm(dj3, dm3) || return zero(SqrtRational) check_couple(dj1, dj2, dj3) || return zero(SqrtRational) dm1 + dm2 == dm3 || return zero(SqrtRational) J::BigInt = div(dj1 + dj2 + dj3, 2) Jm1::BigInt = J - dj1 Jm2::BigInt = J - dj2 Jm3::BigInt = J - dj3 j1mm1::BigInt = div(dj1 - dm1, 2) j2mm2::BigInt = div(dj2 - dm2, 2) j3mm3::BigInt = div(dj3 - dm3, 2) j2pm2::BigInt = div(dj2 + dm2, 2) # value in sqrt A = (binomial(dj1, Jm2) * binomial(dj2, Jm3)) // ( binomial(J + 1, Jm3) * binomial(dj1, j1mm1) * binomial(dj2, j2mm2) * binomial(dj3, j3mm3) ) B::BigInt = zero(BigInt) low::BigInt = max(zero(BigInt), j1mm1 - Jm2, j2pm2 - Jm1) high::BigInt = min(Jm3, j1mm1, j2pm2) for z in low:high B = -B + binomial(Jm3, z) * binomial(Jm2, j1mm1 - z) * binomial(Jm1, j2pm2 - z) end return SqrtRational(iphase(high) * B, A) end # spaecial case: m1 == m2 == m3 == 0 function _CG0(j1::BigInt, j2::BigInt, j3::BigInt) check_couple(2j1, 2j2, 2j3) || return zero(SqrtRational) J = j1 + j2 + j3 isodd(J) && return zero(SqrtRational) g = div(J, 2) return SqrtRational(iphase(g - j3) * binomial(g, j3) * binomial(j3, g - j1), big(1) // (binomial(J + 1, 2j3 + 1) * binomial(2j3, J - 2j1))) end # use CG coefficient to calculate 3j-symbol function _d3j(dj1::BigInt, dj2::BigInt, dj3::BigInt, dm1::BigInt, dm2::BigInt, dm3::BigInt) iphase(dj1 + div(dj3 + dm3, 2)) * exact_sqrt(1 // (dj3 + 1)) * _dCG(dj1, dj2, dj3, -dm1, -dm2, dm3) end # basic 6j-symbol calculation funciton function _d6j(dj1::BigInt, dj2::BigInt, dj3::BigInt, dj4::BigInt, dj5::BigInt, dj6::BigInt) check_couple(dj1, dj2, dj3) || return zero(SqrtRational) check_couple(dj1, dj5, dj6) || return zero(SqrtRational) check_couple(dj4, dj2, dj6) || return zero(SqrtRational) check_couple(dj4, dj5, dj3) || return zero(SqrtRational) j123::BigInt = div(dj1 + dj2 + dj3, 2) j156::BigInt = div(dj1 + dj5 + dj6, 2) j426::BigInt = div(dj4 + dj2 + dj6, 2) j453::BigInt = div(dj4 + dj5 + dj3, 2) jpm123::BigInt = div(dj1 + dj2 - dj3, 2) jpm132::BigInt = div(dj1 + dj3 - dj2, 2) jpm231::BigInt = div(dj2 + dj3 - dj1, 2) jpm156::BigInt = div(dj1 + dj5 - dj6, 2) jpm426::BigInt = div(dj4 + dj2 - dj6, 2) jpm453::BigInt = div(dj4 + dj5 - dj3, 2) # value in sqrt A = (binomial(j123 + 1, dj1 + 1) * binomial(dj1, jpm123)) // ( binomial(j156 + 1, dj1 + 1) * binomial(dj1, jpm156) * binomial(j453 + 1, dj4 + 1) * binomial(dj4, jpm453) * binomial(j426 + 1, dj4 + 1) * binomial(dj4, jpm426) ) B::BigInt = zero(BigInt) low::BigInt = max(j123, j453, j426, j156) high::BigInt = min(jpm123 + j453, jpm132 + j426, jpm231 + j156) for x = low:high B = -B + binomial(x + 1, j123 + 1) * binomial(jpm123, x - j453) * binomial(jpm132, x - j426) * binomial(jpm231, x - j156) end return SqrtRational(iphase(high) * B // (dj4 + 1), A) end # use 6j-symbol to calculate Racah coefficient function _dRacah(dj1::BigInt, dj2::BigInt, dj3::BigInt, dj4::BigInt, dj5::BigInt, dj6::BigInt) iphase(div(dj1 + dj2 + dj3 + dj4, 2)) * _d6j(dj1, dj2, dj5, dj4, dj3, dj6) end # basic 9j-symbol calculation funciton function _d9j(dj1::BigInt, dj2::BigInt, dj3::BigInt, dj4::BigInt, dj5::BigInt, dj6::BigInt, dj7::BigInt, dj8::BigInt, dj9::BigInt) check_couple(dj1, dj2, dj3) || return zero(SqrtRational) check_couple(dj4, dj5, dj6) || return zero(SqrtRational) check_couple(dj7, dj8, dj9) || return zero(SqrtRational) check_couple(dj1, dj4, dj7) || return zero(SqrtRational) check_couple(dj2, dj5, dj8) || return zero(SqrtRational) check_couple(dj3, dj6, dj9) || return zero(SqrtRational) j123::BigInt = div(dj1 + dj2 + dj3, 2) j456::BigInt = div(dj4 + dj5 + dj6, 2) j789::BigInt = div(dj7 + dj8 + dj9, 2) j147::BigInt = div(dj1 + dj4 + dj7, 2) j258::BigInt = div(dj2 + dj5 + dj8, 2) j369::BigInt = div(dj3 + dj6 + dj9, 2) pm123::BigInt = div(dj1 + dj2 - dj3, 2) pm132::BigInt = div(dj1 + dj3 - dj2, 2) pm231::BigInt = div(dj2 + dj3 - dj1, 2) pm456::BigInt = div(dj4 + dj5 - dj6, 2) pm465::BigInt = div(dj4 + dj6 - dj5, 2) pm564::BigInt = div(dj5 + dj6 - dj4, 2) pm789::BigInt = div(dj7 + dj8 - dj9, 2) pm798::BigInt = div(dj7 + dj9 - dj8, 2) pm897::BigInt = div(dj8 + dj9 - dj7, 2) # value in sqrt P0_nu::BigInt = binomial(j123 + 1, dj1 + 1) * binomial(dj1, pm123) * binomial(j456 + 1, dj5 + 1) * binomial(dj5, pm456) * binomial(j789 + 1, dj9 + 1) * binomial(dj9, pm798) P0_de::BigInt = binomial(j147 + 1, dj1 + 1) * binomial(dj1, div(dj1 + dj4 - dj7, 2)) * binomial(j258 + 1, dj5 + 1) * binomial(dj5, div(dj2 + dj5 - dj8, 2)) * binomial(j369 + 1, dj9 + 1) * binomial(dj9, div(dj3 + dj9 - dj6, 2)) P0 = P0_nu // P0_de dtl::BigInt = max(abs(dj2 - dj6), abs(dj4 - dj8), abs(dj1 - dj9)) dth::BigInt = min(dj2 + dj6, dj4 + dj8, dj1 + dj9) PABC::Rational{BigInt} = zero(Rational{BigInt}) for dt::BigInt = dtl:2:dth j19t::BigInt = div(dj1 + dj9 + dt, 2) j26t::BigInt = div(dj2 + dj6 + dt, 2) j48t::BigInt = div(dj4 + dj8 + dt, 2) Pt_de = binomial(j19t + 1, dt + 1) * binomial(dt, div(dj1 + dt - dj9, 2)) * binomial(j26t + 1, dt + 1) * binomial(dt, div(dj2 + dt - dj6, 2)) * binomial(j48t + 1, dt + 1) * binomial(dt, div(dj4 + dt - dj8, 2)) Pt_de *= (dt + 1)^2 xl::BigInt = max(j123, j369, j26t, j19t) xh::BigInt = min(pm123 + j369, pm132 + j26t, pm231 + j19t) At::BigInt = zero(BigInt) for x = xl:xh At = -At + binomial(x + 1, j123 + 1) * binomial(pm123, x - j369) * binomial(pm132, x - j26t) * binomial(pm231, x - j19t) end yl::BigInt = max(j456, j26t, j258, j48t) yh::BigInt = min(pm456 + j26t, pm465 + j258, pm564 + j48t) Bt::BigInt = zero(BigInt) for y = yl:yh Bt = -Bt + binomial(y + 1, j456 + 1) * binomial(pm456, y - j26t) * binomial(pm465, y - j258) * binomial(pm564, y - j48t) end zl::BigInt = max(j789, j19t, j48t, j147) zh::BigInt = min(pm789 + j19t, pm798 + j48t, pm897 + j147) Ct::BigInt = zero(BigInt) for z = zl:zh Ct = -Ct + binomial(z + 1, j789 + 1) * binomial(pm789, z - j19t) * binomial(pm798, z - j48t) * binomial(pm897, z - j147) end PABC += (iphase(xh + yh + zh) * At * Bt * Ct) // Pt_de end return SqrtRational(iphase(dth) * PABC, P0) end function _lsjj_helper(l1::BigInt, l2::BigInt, dj1::BigInt, dj2::BigInt, J::BigInt) iphase(div(dj2 + 1, 2) + l1 + J) * _d6j(2l1, BigInt(1), dj1, dj2, 2J, 2l2) end # S = 0 function _lsjj_S0(l1::BigInt, l2::BigInt, dj1::BigInt, dj2::BigInt, J::BigInt) exact_sqrt((dj1 + 1) * (dj2 + 1) // 2) * _lsjj_helper(l1, l2, dj1, dj2, J) end # S = 1, J = L - 1 function _lsjj_S1_m1(l1::BigInt, l2::BigInt, dj1::BigInt, dj2::BigInt, J::BigInt) L = J + 1 f0 = ((dj1 + 1) * (dj2 + 1)) // (2L * (2L - 1)) mj = div(dj1 - dj2, 2) pj = div(dj1 + dj2, 2) + 1 fL = (L + mj) * (L - mj) * (L + pj) * (pj - L) ml = l1 - l2 pl = l1 + l2 + 1 fJ = (L + ml) * (L - ml) * (L + pl) * (pl - L) exact_sqrt(fJ * f0) * _lsjj_helper(l1, l2, dj1, dj2, J) - exact_sqrt(fL * f0) * _lsjj_helper(l1, l2, dj1, dj2, L) end # S = 1, J = L function _lsjj_S1_0(l1::BigInt, l2::BigInt, dj1::BigInt, dj2::BigInt, J::BigInt) factor = div(dj1 - dj2, 2) * div(dj1 + dj2 + 2, 2) - (l1 - l2) * (l1 + l2 + 1) SqrtRational(factor, (dj1 + 1) * (dj2 + 1) // (2J * (J + 1))) * _lsjj_helper(l1, l2, dj1, dj2, J) end # S = 1, J = L + 1 function _lsjj_S1_p1(l1::BigInt, l2::BigInt, dj1::BigInt, dj2::BigInt, J::BigInt) f0 = ((dj1 + 1) * (dj2 + 1)) // (2J * (2J + 1)) mj = div(dj1 - dj2, 2) pj = div(dj1 + dj2, 2) + 1 fL = (J + mj) * (J - mj) * (J + pj) * (pj - J) ml = l1 - l2 pl = l1 + l2 + 1 fJ = (J + ml) * (J - ml) * (J + pl) * (pl - J) exact_sqrt(fL * f0) * _lsjj_helper(l1, l2, dj1, dj2, J - 1) - exact_sqrt(fJ * f0) * _lsjj_helper(l1, l2, dj1, dj2, J) end function _lsjj(l1::BigInt, l2::BigInt, dj1::BigInt, dj2::BigInt, L::BigInt, S::BigInt, J::BigInt) if abs(dj1 - 2l1) != 1 || abs(dj2 - 2l2) != 1 return zero(SqrtRational) end check_couple(2l1, 2l2, 2L) || return zero(SqrtRational) check_couple(dj1, dj2, 2J) || return zero(SqrtRational) check_couple(2L, 2S, 2J) || return zero(SqrtRational) S == 0 && return _lsjj_S0(l1, l2, dj1, dj2, J) if S == 1 J == L - 1 && return _lsjj_S1_m1(l1, l2, dj1, dj2, J) J == L && return _lsjj_S1_0(l1, l2, dj1, dj2, J) J == L + 1 && return _lsjj_S1_p1(l1, l2, dj1, dj2, J) end return zero(SqrtRational) end function _Moshinsky(N::BigInt, L::BigInt, n::BigInt, l::BigInt, n1::BigInt, l1::BigInt, n2::BigInt, l2::BigInt, Λ::BigInt) f1 = 2 * n1 + l1 f2 = 2 * n2 + l2 F = 2 * N + L f = 2 * n + l f1 + f2 == F + f || return zero(SqrtRational) χ = f1 + f2 nl1 = n1 + l1 nl2 = n2 + l2 NL = N + L nl = n + l r1 = binomial(2nl1 + 1, nl1) // (binomial(f1 + 2, n1) * (nl1 + 2)) r2 = binomial(2nl2 + 1, nl2) // (binomial(f2 + 2, n2) * (nl2 + 2)) R = binomial(2NL + 1, NL) // (binomial(F + 2, N) * (NL + 2)) r = binomial(2nl + 1, nl) // (binomial(f + 2, n) * (nl + 2)) pre_sum = exact_sqrt(r1 * r2 * R * r // big(2)^χ) half_lsum = div(l1 + l2 + L + l, 2) sum = zero(SqrtRational) for fa = 0:min(f1, F) fb = f1 - fa fc = F - fa fd = f2 - fc fd >= 0 || continue t = exact_sqrt(binomial(f1 + 2, fa + 1) * binomial(f2 + 2, fc + 1) * binomial(F + 2, fa + 1) * binomial(f + 2, fb + 1)) for la = (fa&0x01):2:fa na = div(fa - la, 2) nla = na + la ta = ((2 * la + 1) * binomial(fa + 1, na)) // binomial(2nla + 1, nla) for lb = abs(l1 - la):2:min(la + l1, fb) nb = div(fb - lb, 2) nlb = nb + lb tb = ((2 * lb + 1) * binomial(fb + 1, nb)) // binomial(2nlb + 1, nlb) g1 = div(la + lb + l1, 2) pCG_ab = SqrtRational(binomial(g1, l1) * binomial(l1, g1 - la), big(1) // (binomial(2g1 + 1, 2(g1 - l1)) * binomial(2l1, 2(g1 - la)))) for lc = abs(L - la):2:min(la + L, fc) nc = div(fc - lc, 2) nlc = nc + lc tc = ((2 * lc + 1) * binomial(fc + 1, nc)) // binomial(2nlc + 1, nlc) G = div(la + lc + L, 2) pCG_ac = SqrtRational(binomial(G, L) * binomial(L, G - la), big(1) // (binomial(2G + 1, 2(G - L)) * binomial(2L, 2(G - la)))) ld_min = max(abs(l2 - lc), abs(l - lb)) ld_max = min(fd, lb + l, lc + l2) for ld = ld_min:2:ld_max nd = div(fd - ld, 2) nld = nd + ld td = ((2 * ld + 1) * binomial(fd + 1, nd)) // binomial(2nld + 1, nld) g2 = div(lc + ld + l2, 2) pCG_cd = SqrtRational(binomial(g2, l2) * binomial(l2, g2 - lc), big(1) // (binomial(2g2 + 1, 2(g2 - l2)) * binomial(2l2, 2(g2 - lc)))) g = div(lb + ld + l, 2) pCG_bd = SqrtRational(binomial(g, l) * binomial(l, g - lb), big(1) // (binomial(2g + 1, 2(g - l)) * binomial(2l, 2(g - lb)))) l_diff = la + lb + lc + ld - half_lsum phase = l_diff >= 0 ? iphase(ld) * 2^l_diff : iphase(ld) // 2^(-l_diff) ninej = d9j(2 * la, 2 * lb, 2 * l1, 2 * lc, 2 * ld, 2 * l2, 2 * L, 2 * l, 2 * Λ) sum = sum + phase * t * ta * tb * tc * td * pCG_ab * pCG_ac * pCG_bd * pCG_cd * ninej end end end end end return pre_sum * sum end """ dCG(dj1::Integer, dj2::Integer, dj3::Integer, dm1::Integer, dm2::Integer, dm3::Integer) CG coefficient function with double angular monentum number parameters, so that the parameters can be integer. You can calculate `dCG(1, 1, 2, 1, 1, 2)` to calculate the real `CG(1//2, 1//2, 1, 1/2, 1//2, 1)` """ @inline dCG(dj1::Integer, dj2::Integer, dj3::Integer, dm1::Integer, dm2::Integer, dm3::Integer) = _dCG(BigInt.((dj1, dj2, dj3, dm1, dm2, dm3))...) """ d3j(dj1::Integer, dj2::Integer, dj3::Integer, dm1::Integer, dm2::Integer, dm3::Integer) 3j-symbol function with double angular monentum number parameters, so that the parameters can be integer. """ @inline d3j(dj1::Integer, dj2::Integer, dj3::Integer, dm1::Integer, dm2::Integer, dm3::Integer) = _d3j(BigInt.((dj1, dj2, dj3, dm1, dm2, dm3))...) """ d6j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer) 6j-symbol function with double angular monentum number parameters, so that the parameters can be integer. """ @inline d6j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer) = _d6j(BigInt.((dj1, dj2, dj3, dj4, dj5, dj6))...) """ dRacah(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer) Racah coefficient function with double angular momentum parameters, so that the parameters can be integer. """ @inline dRacah(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer) = _dRacah(BigInt.((dj1, dj2, dj3, dj4, dj5, dj6))...) """ d9j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer, dj7::Integer, dj8::Integer, dj9::Integer) 9j-symbol function with double angular monentum number parameters, so that the parameters can be integer. """ @inline d9j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer, dj7::Integer, dj8::Integer, dj9::Integer) = _d9j(BigInt.((dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9))...) @doc raw""" CG(j1::HalfInt, j2::HalfInt, j3::HalfInt, m1::HalfInt, m2::HalfInt, m3::HalfInt) CG coefficient ``\langle j_1m_1 j_2m_2 | j_3m_3 \rangle`` """ @inline CG(j1::HalfInt, j2::HalfInt, j3::HalfInt, m1::HalfInt, m2::HalfInt, m3::HalfInt) = simplify(_dCG(BigInt.((2j1, 2j2, 2j3, 2m1, 2m2, 2m3))...)) @doc raw""" CG0(j1::Integer, j2::Integer, j3::Integer) CG coefficient special case: ``\langle j_1 0 j_2 0 | j_3 0 \rangle``. """ @inline CG0(j1::Integer, j2::Integer, j3::Integer) = simplify(_CG0(big(j1), big(j2), big(j3))) @doc raw""" threeJ(j1::HalfInt, j2::HalfInt, j3::HalfInt, m1::HalfInt, m2::HalfInt, m3::HalfInt) Wigner 3j-symbol ```math \begin{pmatrix} j_1 & j_2 & j_3 \\ m_1 & m_2 & m_3 \end{pmatrix} ``` """ @inline threeJ(j1::HalfInt, j2::HalfInt, j3::HalfInt, m1::HalfInt, m2::HalfInt, m3::HalfInt) = simplify(_d3j(BigInt.((2j1, 2j2, 2j3, 2m1, 2m2, 2m3))...)) @doc raw""" sixJ(j1::HalfInt, j2::HalfInt, j3::HalfInt, j4::HalfInt, j5::HalfInt, j6::HalfInt) Wigner 6j-symbol ```math \begin{Bmatrix} j_1 & j_2 & j_3 \\ j_4 & j_5 & j_6 \end{Bmatrix} ``` """ @inline sixJ(j1::HalfInt, j2::HalfInt, j3::HalfInt, j4::HalfInt, j5::HalfInt, j6::HalfInt) = simplify(_d6j(BigInt.((2j1, 2j2, 2j3, 2j4, 2j5, 2j6))...)) @doc raw""" Racah(j1::HalfInt, j2::HalfInt, j3::HalfInt, j4::HalfInt, j5::HalfInt, j6::HalfInt) Racah coefficient ```math W(j_1j_2j_3j_4, j_5j_6) = (-1)^{j_1+j_2+j_3+j_4} \begin{Bmatrix} j_1 & j_2 & j_5 \\ j_4 & j_3 & j_6 \end{Bmatrix} ``` """ @inline Racah(j1::HalfInt, j2::HalfInt, j3::HalfInt, j4::HalfInt, j5::HalfInt, j6::HalfInt) = simplify(_dRacah(BigInt.((2j1, 2j2, 2j3, 2j4, 2j5, 2j6))...)) @doc raw""" nineJ(j1::HalfInt, j2::HalfInt, j3::HalfInt, j4::HalfInt, j5::HalfInt, j6::HalfInt, j7::HalfInt, j8::HalfInt, j9::HalfInt) Wigner 9j-symbol ```math \begin{Bmatrix} j_1 & j_2 & j_3 \\ j_4 & j_5 & j_6 \\ j_7 & j_8 & j_9 \end{Bmatrix} ``` """ @inline nineJ(j1::HalfInt, j2::HalfInt, j3::HalfInt, j4::HalfInt, j5::HalfInt, j6::HalfInt, j7::HalfInt, j8::HalfInt, j9::HalfInt) = simplify(_d9j(BigInt.((2j1, 2j2, 2j3, 2j4, 2j5, 2j6, 2j7, 2j8, 2j9))...)) @doc raw""" norm9J(j1::HalfInt, j2::HalfInt, j3::HalfInt, j4::HalfInt, j5::HalfInt, j6::HalfInt, j7::HalfInt, j8::HalfInt, j9::HalfInt) normalized Wigner 9j-symbol ```math \begin{bmatrix} j_1 & j_2 & j_3 \\ j_4 & j_5 & j_6 \\ j_7 & j_8 & j_9 \end{bmatrix} = \sqrt{(2j_3+1)(2j_6+1)(2j_7+1)(2j_8+1)} \begin{Bmatrix} j_1 & j_2 & j_3 \\ j_4 & j_5 & j_6 \\ j_7 & j_8 & j_9 \end{Bmatrix} ``` """ @inline norm9J(j1::HalfInt, j2::HalfInt, j3::HalfInt, j4::HalfInt, j5::HalfInt, j6::HalfInt, j7::HalfInt, j8::HalfInt, j9::HalfInt) = simplify(exact_sqrt((2j3 + 1) * (2j6 + 1) * (2j7 + 1) * (2j8 + 1)) * _d9j(BigInt.((2j1, 2j2, 2j3, 2j4, 2j5, 2j6, 2j7, 2j8, 2j9))...)) @doc raw""" lsjj(l1::Integer, l2::Integer, j1::HalfInt, j2::HalfInt, L::Integer, S::Integer, J::Integer) LS-coupling to jj-coupling transformation coefficient ```math |l_1 l_2 j_1 j_2; J\rangle = \sum_{LS} \langle l_1 l_2 LSJ | l_1 l_2 j_1 j_2; J \rangle |l_1 l_2 LSJ \rangle ``` """ @inline lsjj(l1::Integer, l2::Integer, j1::HalfInt, j2::HalfInt, L::Integer, S::Integer, J::Integer) = simplify(_lsjj(BigInt.((l1, l2, 2j1, 2j2, L, S, J))...)) @doc raw""" Moshinsky(N::Integer, L::Integer, n::Integer, l::Integer, n1::Integer, l1::Integer, n2::Integer, l2::Integer, Λ::Integer) Moshinsky bracket,Ref: Buck et al. Nuc. Phys. A 600 (1996) 387-402. Since this function is designed for demonstration the exact result, It only calculate the case of ``\tan(\beta) = 1``. """ @inline Moshinsky(N::Integer, L::Integer, n::Integer, l::Integer, n1::Integer, l1::Integer, n2::Integer, l2::Integer, Λ::Integer) = simplify(_Moshinsky(BigInt.((N, L, n, l, n1, l1, n2, l2, Λ))...))
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
20424
_fbinomial_data = Float64[] _fbinomial_nmax = Int(0) @inline get_fbinomial_data()::Vector{Float64} = _fbinomial_data::Vector{Float64} @inline get_fbinomial_nmax()::Int = _fbinomial_nmax::Int """ fbinomial(n::Integer, k::Integer) `binomial` with Float64 return value. """ @inline function fbinomial(n::Integer, k::Integer)::Float64 if n < 0 || n > get_fbinomial_nmax() || k < 0 || k > n return 0.0 end k = min(k, n - k) return @inbounds get_fbinomial_data()[binomial_index(n, k)] end """ function unsafe_fbinomial(n::Int, k::Int) Same as fbinomial, but without bounds check. Thus for `n < 0` or `n > _nmax` or `k < 0` or `k > n`, the result is undefined. In Wigner symbol calculation, the mathematics guarantee that `unsafe_fbinomial(n, k)` is always safe. """ @inline function unsafe_fbinomial(n::Int, k::Int)::Float64 k = min(k, n - k) return @inbounds get_fbinomial_data()[binomial_index(n, k)] end function _extent_fbinomial_data(n::Int) if n > get_fbinomial_nmax() old_data = copy(get_fbinomial_data()) resize!(get_fbinomial_data(), binomial_data_size(n)) copyto!(get_fbinomial_data(), old_data) for m = get_fbinomial_nmax()+1:n for k = 0:div(m, 2) get_fbinomial_data()[binomial_index(m, k)] = binomial(BigInt(m), BigInt(k)) end global _fbinomial_nmax = get_fbinomial_nmax() + 1 end global _fbinomial_nmax = n end nothing end """ wigner_init_float(n::Integer, mode::AbstractString, rank::Integer) This function reserves memory for fbinomial(n, k). In this code, the `fbinomial` function is only valid in the stored range. If you call a `fbinomial` function out of the range, it just gives you `0`. The `__init__()` function stores to `nmax = 67`. The parameters means | | Calculate range | CG & 3j | 6j & Racah | 9j | | :-----------------------------------: | :-------------------: | :---------: | :---------: | :---------: | | meaning of `type` | `type`\\\\`rank` | 3 | 6 | 9 | | max angular momentum | `"Jmax"` | `3*Jmax+1` | `4*Jmax+1` | `5*Jmax+1` | | max two-body coupled angular momentum | `"2bjmax"` | `2*jmax+1` | `3*jmax+1` | `4*jmax+1` | | max binomial | `"nmax"` | `nmax` | `namx` | `nmax` | The `"2bjmax"` mode means your calculation only consider two-body coupling, and no three-body coupling. This mode assumes that in all these coefficients, at least one of the angular momentun is just a single particle angular momentum. With this assumption, `"2bjmax"` mode will use less memory than `"Jmax"` mode. `"Jmax"` means the global maximum angular momentum, for every parameters. It is always safe with out any assumption. The `"nmax"` mode directly set `nmax`, and the `rank` parameter is ignored. `rank = 6` means you only need to calculate CG and/or 6j symbols, you don't need to calculate 9j symbol. For example ```julia wigner_init_float(21, "Jmax", 6) ``` means you calculate CG and 6j symbols, and donot calculate 9j symbol. The maximum angular momentum in your system is 21. You do not need to rememmber those values in the table. You just need to find the maximum angular momentum in you canculation, then call the function. The wigner_init_float function is **not** thread safe, so you should call it before you start your calculation. """ function wigner_init_float(n::Integer, mode::AbstractString, rank::Integer) if mode == "Jmax" rank == 3 && _extent_fbinomial_data(3 * n + 1) rank == 6 && _extent_fbinomial_data(4 * n + 1) rank == 9 && _extent_fbinomial_data(5 * n + 1) if rank != 3 && rank != 6 && rank != 9 throw(ArgumentError("invalid rank $rank")) end elseif mode == "2bjmax" rank == 3 && _extent_fbinomial_data(2 * n + 1) rank == 6 && _extent_fbinomial_data(3 * n + 1) rank == 9 && _extent_fbinomial_data(4 * n + 1) if rank != 3 && rank != 6 && rank != 9 throw(ArgumentError("invalid rank $rank")) end elseif mode == "nmax" _extent_fbinomial_data(n) else throw(ArgumentError("invalid mode $mode")) end nothing end # basic CG coefficient calculation function with Float64 return value # unlike the SqrtRational version, this function gives out zero when the parameters are not valid function _fCG(dj1::Int, dj2::Int, dj3::Int, dm1::Int, dm2::Int, dm3::Int) check_jm(dj1, dm1) && check_jm(dj2, dm2) && check_jm(dj3, dm3) || return zero(Float64) check_couple(dj1, dj2, dj3) || return zero(Float64) dm1 + dm2 == dm3 || return zero(Float64) J::Int = div(dj1 + dj2 + dj3, 2) Jm1::Int = J - dj1 Jm2::Int = J - dj2 Jm3::Int = J - dj3 j1mm1::Int = div(dj1 - dm1, 2) j2mm2::Int = div(dj2 - dm2, 2) j3mm3::Int = div(dj3 - dm3, 2) j2pm2::Int = div(dj2 + dm2, 2) A = sqrt(unsafe_fbinomial(dj1, Jm2) * unsafe_fbinomial(dj2, Jm3) / ( unsafe_fbinomial(J + 1, Jm3) * unsafe_fbinomial(dj1, j1mm1) * unsafe_fbinomial(dj2, j2mm2) * unsafe_fbinomial(dj3, j3mm3) )) B = zero(Float64) low::Int = max(zero(Int), j1mm1 - Jm2, j2pm2 - Jm1) high::Int = min(Jm3, j1mm1, j2pm2) for z in low:high B = -B + unsafe_fbinomial(Jm3, z) * unsafe_fbinomial(Jm2, j1mm1 - z) * unsafe_fbinomial(Jm1, j2pm2 - z) end return iphase(high) * A * B end function _fCG0(j1::Int, j2::Int, j3::Int) check_couple(2j1, 2j2, 2j3) || return zero(Float64) J = j1 + j2 + j3 isodd(J) && return zero(Float64) g = div(J, 2) return iphase(g - j3) * unsafe_fbinomial(g, j3) * unsafe_fbinomial(j3, g - j1) / sqrt(unsafe_fbinomial(J + 1, 2j3 + 1) * unsafe_fbinomial(2j3, J - 2j1)) end function _f6j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int) check_couple(dj1, dj2, dj3) && check_couple(dj1, dj5, dj6) & check_couple(dj4, dj2, dj6) && check_couple(dj4, dj5, dj3) || return zero(Float64) j123::Int = div(dj1 + dj2 + dj3, 2) j156::Int = div(dj1 + dj5 + dj6, 2) j426::Int = div(dj4 + dj2 + dj6, 2) j453::Int = div(dj4 + dj5 + dj3, 2) jpm123::Int = div(dj1 + dj2 - dj3, 2) jpm132::Int = div(dj1 + dj3 - dj2, 2) jpm231::Int = div(dj2 + dj3 - dj1, 2) jpm156::Int = div(dj1 + dj5 - dj6, 2) jpm426::Int = div(dj4 + dj2 - dj6, 2) jpm453::Int = div(dj4 + dj5 - dj3, 2) A = sqrt(unsafe_fbinomial(j123 + 1, dj1 + 1) * unsafe_fbinomial(dj1, jpm123) / ( unsafe_fbinomial(j156 + 1, dj1 + 1) * unsafe_fbinomial(dj1, jpm156) * unsafe_fbinomial(j453 + 1, dj4 + 1) * unsafe_fbinomial(dj4, jpm453) * unsafe_fbinomial(j426 + 1, dj4 + 1) * unsafe_fbinomial(dj4, jpm426) )) B = zero(Float64) low::Int = max(j123, j453, j426, j156) high::Int = min(jpm123 + j453, jpm132 + j426, jpm231 + j156) for x = low:high B = -B + unsafe_fbinomial(x + 1, j123 + 1) * unsafe_fbinomial(jpm123, x - j453) * unsafe_fbinomial(jpm132, x - j426) * unsafe_fbinomial(jpm231, x - j156) end return iphase(high) * A * B / (dj4 + 1) end function _f9j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int, dj7::Int, dj8::Int, dj9::Int) check_couple(dj1, dj2, dj3) && check_couple(dj4, dj5, dj6) && check_couple(dj7, dj8, dj9) || return zero(Float64) check_couple(dj1, dj4, dj7) && check_couple(dj2, dj5, dj8) && check_couple(dj3, dj6, dj9) || return zero(Float64) j123::Int = div(dj1 + dj2 + dj3, 2) j456::Int = div(dj4 + dj5 + dj6, 2) j789::Int = div(dj7 + dj8 + dj9, 2) j147::Int = div(dj1 + dj4 + dj7, 2) j258::Int = div(dj2 + dj5 + dj8, 2) j369::Int = div(dj3 + dj6 + dj9, 2) pm123::Int = div(dj1 + dj2 - dj3, 2) pm132::Int = div(dj1 + dj3 - dj2, 2) pm231::Int = div(dj2 + dj3 - dj1, 2) pm456::Int = div(dj4 + dj5 - dj6, 2) pm465::Int = div(dj4 + dj6 - dj5, 2) pm564::Int = div(dj5 + dj6 - dj4, 2) pm789::Int = div(dj7 + dj8 - dj9, 2) pm798::Int = div(dj7 + dj9 - dj8, 2) pm897::Int = div(dj8 + dj9 - dj7, 2) # value in sqrt P0_nu = unsafe_fbinomial(j123 + 1, dj1 + 1) * unsafe_fbinomial(dj1, pm123) * unsafe_fbinomial(j456 + 1, dj5 + 1) * unsafe_fbinomial(dj5, pm456) * unsafe_fbinomial(j789 + 1, dj9 + 1) * unsafe_fbinomial(dj9, pm798) P0_de = unsafe_fbinomial(j147 + 1, dj1 + 1) * unsafe_fbinomial(dj1, div(dj1 + dj4 - dj7, 2)) * unsafe_fbinomial(j258 + 1, dj5 + 1) * unsafe_fbinomial(dj5, div(dj2 + dj5 - dj8, 2)) * unsafe_fbinomial(j369 + 1, dj9 + 1) * unsafe_fbinomial(dj9, div(dj3 + dj9 - dj6, 2)) P0 = P0_nu / P0_de dtl::Int = max(abs(dj2 - dj6), abs(dj4 - dj8), abs(dj1 - dj9)) dth::Int = min(dj2 + dj6, dj4 + dj8, dj1 + dj9) PABC = zero(Float64) for dt::Int = dtl:2:dth j19t::Int = div(dj1 + dj9 + dt, 2) j26t::Int = div(dj2 + dj6 + dt, 2) j48t::Int = div(dj4 + dj8 + dt, 2) Pt_de = unsafe_fbinomial(j19t + 1, dt + 1) * unsafe_fbinomial(dt, div(dj1 + dt - dj9, 2)) * unsafe_fbinomial(j26t + 1, dt + 1) * unsafe_fbinomial(dt, div(dj2 + dt - dj6, 2)) * unsafe_fbinomial(j48t + 1, dt + 1) * unsafe_fbinomial(dt, div(dj4 + dt - dj8, 2)) Pt_de *= (dt + 1)^2 xl::Int = max(j123, j369, j26t, j19t) xh::Int = min(pm123 + j369, pm132 + j26t, pm231 + j19t) At = zero(Float64) for x = xl:xh At = -At + unsafe_fbinomial(x + 1, j123 + 1) * unsafe_fbinomial(pm123, x - j369) * unsafe_fbinomial(pm132, x - j26t) * unsafe_fbinomial(pm231, x - j19t) end yl::Int = max(j456, j26t, j258, j48t) yh::Int = min(pm456 + j26t, pm465 + j258, pm564 + j48t) Bt = zero(Float64) for y = yl:yh Bt = -Bt + unsafe_fbinomial(y + 1, j456 + 1) * unsafe_fbinomial(pm456, y - j26t) * unsafe_fbinomial(pm465, y - j258) * unsafe_fbinomial(pm564, y - j48t) end zl::Int = max(j789, j19t, j48t, j147) zh::Int = min(pm789 + j19t, pm798 + j48t, pm897 + j147) Ct = zero(Float64) for z = zl:zh Ct = -Ct + unsafe_fbinomial(z + 1, j789 + 1) * unsafe_fbinomial(pm789, z - j19t) * unsafe_fbinomial(pm798, z - j48t) * unsafe_fbinomial(pm897, z - j147) end PABC += (iphase(xh + yh + zh) * At * Bt * Ct) / Pt_de end return iphase(dth) * sqrt(P0) * PABC end function _fMoshinsky(N::Int, L::Int, n::Int, l::Int, n1::Int, l1::Int, n2::Int, l2::Int, Λ::Int, tanβ::Float64) f1 = 2 * n1 + l1 f2 = 2 * n2 + l2 F = 2 * N + L f = 2 * n + l f1 + f2 == F + f || return zero(Float64) secβ = √(1 + tanβ * tanβ) cosβ = 1 / secβ sinβ = tanβ / secβ nl1 = n1 + l1 nl2 = n2 + l2 NL = N + L nl = n + l r1 = unsafe_fbinomial(2nl1 + 1, nl1) / (unsafe_fbinomial(f1 + 2, n1) * ((nl1 + 2) << l1)) r2 = unsafe_fbinomial(2nl2 + 1, nl2) / (unsafe_fbinomial(f2 + 2, n2) * ((nl2 + 2) << l2)) R = unsafe_fbinomial(2NL + 1, NL) / (unsafe_fbinomial(F + 2, N) * ((NL + 2) << L)) r = unsafe_fbinomial(2nl + 1, nl) / (unsafe_fbinomial(f + 2, n) * ((nl + 2) << l)) pre_sum = √(r1 * r2 * R * r) sum = zero(Float64) for fa = 0:min(f1, F) fb = f1 - fa fc = F - fa fd = f2 - fc fd >= 0 || continue t = sinβ^(fa + fd) * cosβ^(fb + fc) t = t * √(unsafe_fbinomial(f1 + 2, fa + 1) * unsafe_fbinomial(f2 + 2, fc + 1) * unsafe_fbinomial(F + 2, fa + 1) * unsafe_fbinomial(f + 2, fb + 1)) for la = (fa&0x01):2:fa na = div(fa - la, 2) nla = na + la ta = (((2 * la + 1) << la) * unsafe_fbinomial(fa + 1, na)) / unsafe_fbinomial(2nla + 1, nla) for lb = abs(l1 - la):2:min(la + l1, fb) nb = div(fb - lb, 2) nlb = nb + lb tb = (((2 * lb + 1) << lb) * unsafe_fbinomial(fb + 1, nb)) / unsafe_fbinomial(2nlb + 1, nlb) g1 = div(la + lb + l1, 2) CGab = unsafe_fbinomial(g1, l1) * unsafe_fbinomial(l1, g1 - la) / √(unsafe_fbinomial(2g1 + 1, 2(g1 - l1)) * unsafe_fbinomial(2l1, 2(g1 - la))) for lc = abs(L - la):2:min(la + L, fc) nc = div(fc - lc, 2) nlc = nc + lc tc = (((2 * lc + 1) << lc) * unsafe_fbinomial(fc + 1, nc)) / unsafe_fbinomial(2nlc + 1, nlc) G = div(la + lc + L, 2) CGac = unsafe_fbinomial(G, L) * unsafe_fbinomial(L, G - la) / √(unsafe_fbinomial(2G + 1, 2(G - L)) * unsafe_fbinomial(2L, 2(G - la))) ld_min = max(abs(l2 - lc), abs(l - lb)) ld_max = min(fd, lb + l, lc + l2) for ld = ld_min:2:ld_max nd = div(fd - ld, 2) nld = nd + ld td = (((2 * ld + 1) << ld) * unsafe_fbinomial(fd + 1, nd)) / unsafe_fbinomial(2nld + 1, nld) g2 = div(lc + ld + l2, 2) CGcd = unsafe_fbinomial(g2, l2) * unsafe_fbinomial(l2, g2 - lc) / √(unsafe_fbinomial(2g2 + 1, 2(g2 - l2)) * unsafe_fbinomial(2l2, 2(g2 - lc))) g = div(lb + ld + l, 2) CGbd = unsafe_fbinomial(g, l) * unsafe_fbinomial(l, g - lb) / √(unsafe_fbinomial(2g + 1, 2(g - l)) * unsafe_fbinomial(2l, 2(g - lb))) phase = iphase(ld) ninej = f9j(2 * la, 2 * lb, 2 * l1, 2 * lc, 2 * ld, 2 * l2, 2 * L, 2 * l, 2 * Λ) sum = sum + phase * t * ta * tb * tc * td * CGab * CGac * CGbd * CGcd * ninej end end end end end return pre_sum * sum end function _dfunc(dj::Int, dm1::Int, dm2::Int, β::Float64) check_jm(dj, dm1) && check_jm(dj, dm2) || return zero(Float64) jm1 = div(dj - dm1, 2) jp1 = div(dj + dm1, 2) jm2 = div(dj - dm2, 2) mm = div(dm1 + dm2, 2) s, c = sincos(β) kmin = max(0, -mm) kmax = min(jm1, jm2) sum = 0.0 for k = kmin:kmax sum = -sum + unsafe_fbinomial(jm1, k) * unsafe_fbinomial(jp1, mm + k) * c^(mm + 2k) * s^(jm1 + jm2 - 2k) end sum = iphase(jm2 + kmax) * sum sum = sum * √(unsafe_fbinomial(dj, jm1) / unsafe_fbinomial(dj, jm2)) return sum end function _flsjj_helper(l1::Int, l2::Int, dj1::Int, dj2::Int, J::Int) iphase(div(dj2 + 1, 2) + l1 + J) * _f6j(2l1, 1, dj1, dj2, 2J, 2l2) end # S = 0 function _flsjj_S0(l1::Int, l2::Int, dj1::Int, dj2::Int, J::Int) sqrt((dj1 + 1) * (dj2 + 1) / 2) * _flsjj_helper(l1, l2, dj1, dj2, J) end # S = 1, J = L - 1 function _flsjj_S1_m1(l1::Int, l2::Int, dj1::Int, dj2::Int, J::Int) L = J + 1 f0 = ((dj1 + 1) * (dj2 + 1)) / (2L * (2L - 1)) mj = div(dj1 - dj2, 2) pj = div(dj1 + dj2, 2) + 1 fL = (L + mj) * (L - mj) * (L + pj) * (pj - L) ml = l1 - l2 pl = l1 + l2 + 1 fJ = (L + ml) * (L - ml) * (L + pl) * (pl - L) sqrt(fJ * f0) * _flsjj_helper(l1, l2, dj1, dj2, J) - sqrt(fL * f0) * _flsjj_helper(l1, l2, dj1, dj2, L) end # S = 1, J = L function _flsjj_S1_0(l1::Int, l2::Int, dj1::Int, dj2::Int, J::Int) factor = div(dj1 - dj2, 2) * div(dj1 + dj2 + 2, 2) - (l1 - l2) * (l1 + l2 + 1) factor * sqrt((dj1 + 1) * (dj2 + 1) / (2J * (J + 1))) * _flsjj_helper(l1, l2, dj1, dj2, J) end # S = 1, J = L + 1 function _flsjj_S1_p1(l1::Int, l2::Int, dj1::Int, dj2::Int, J::Int) f0 = ((dj1 + 1) * (dj2 + 1)) / (2J * (2J + 1)) mj = div(dj1 - dj2, 2) pj = div(dj1 + dj2, 2) + 1 fL = (J + mj) * (J - mj) * (J + pj) * (pj - J) ml = l1 - l2 pl = l1 + l2 + 1 fJ = (J + ml) * (J - ml) * (J + pl) * (pl - J) sqrt(fL * f0) * _flsjj_helper(l1, l2, dj1, dj2, J - 1) - sqrt(fJ * f0) * _flsjj_helper(l1, l2, dj1, dj2, J) end function _flsjj(l1::Int, l2::Int, dj1::Int, dj2::Int, L::Int, S::Int, J::Int) if abs(dj1 - 2l1) != 1 || abs(dj2 - 2l2) != 1 return zero(Float64) end check_couple(dj1, dj2, 2J) || return zero(Float64) check_couple(2l1, 2l2, 2L) || return zero(Float64) check_couple(2L, 2S, 2J) || return zero(Float64) S == 0 && return _flsjj_S0(l1, l2, dj1, dj2, J) if S == 1 J == L - 1 && return _flsjj_S1_m1(l1, l2, dj1, dj2, J) J == L && return _flsjj_S1_0(l1, l2, dj1, dj2, J) J == L + 1 && return _flsjj_S1_p1(l1, l2, dj1, dj2, J) end return zero(Float64) end """ fCG(dj1::Integer, dj2::Integer, dj3::Integer, dm1::Integer, dm2::Integer, dm3::Integer) float64 and fast CG coefficient. """ @inline function fCG(dj1::Integer, dj2::Integer, dj3::Integer, dm1::Integer, dm2::Integer, dm3::Integer) return _fCG(Int.((dj1, dj2, dj3, dm1, dm2, dm3))...) end """ fCG0(dj1::Integer, dj2::Integer, dj3::Integer) float64 and fast CG coefficient for `m1 == m2 == m3 == 0`. """ @inline function fCG0(dj1::Integer, dj2::Integer, dj3::Integer) return _fCG0(Int.((dj1, dj2, dj3))...) end """ fCGspin(ds1::Integer, ds2::Integer, S::Integer) float64 and fast CG coefficient for two spin-1/2 coupling. """ @inline function fCGspin(ds1::Integer, ds2::Integer, S::Integer) unsigned(S) > 1 && return zero(Float64) (abs(ds1) != 1 || abs(ds2) != 1) && return zero(Float64) if iszero(S) return ds1 == ds2 ? 0.0 : copysign(1 / √2, ds1) else # S = 1 return ds1 == ds2 ? 1.0 : 1 / √2 end end """ f3j(dj1::Integer, dj2::Integer, dj3::Integer, dm1::Integer, dm2::Integer, dm3::Integer) float64 and fast Wigner 3j symbol. """ @inline function f3j(dj1::Integer, dj2::Integer, dj3::Integer, dm1::Integer, dm2::Integer, dm3::Integer) return iphase(dj1 + div(dj3 + dm3, 2)) * fCG(dj1, dj2, dj3, -dm1, -dm2, dm3) / sqrt(dj3 + 1) end """ f6j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer) float64 and fast Wigner 6j symbol. """ @inline function f6j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer) return _f6j(Int.((dj1, dj2, dj3, dj4, dj5, dj6))...) end """ Racah(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer) float64 and fast Racah coefficient. """ @inline function fRacah(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer) return iphase(div(dj1 + dj2 + dj3 + dj4, 2)) * f6j(dj1, dj2, dj5, dj4, dj3, dj6) end """ f9j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer, dj7::Integer, dj8::Integer, dj9::Integer) float64 and fast Wigner 9j symbol. """ @inline function f9j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer, dj7::Integer, dj8::Integer, dj9::Integer) return _f9j(Int.((dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9))...) end """ fnorm9j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer, dj7::Integer, dj8::Integer, dj9::Integer) float64 and fast normalized Wigner 9j symbol. """ @inline function fnorm9j(dj1::Integer, dj2::Integer, dj3::Integer, dj4::Integer, dj5::Integer, dj6::Integer, dj7::Integer, dj8::Integer, dj9::Integer) return sqrt((dj3 + 1.0) * (dj6 + 1.0) * (dj7 + 1.0) * (dj8 + 1.0)) * f9j(dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9) end """ lsjj(l1::Integer, l2::Integer, dj1::Integer, dj2::Integer, L::Integer, S::Integer, J::Integer) float64 and fast lsjj coefficient. """ @inline function flsjj(l1::Integer, l2::Integer, dj1::Integer, dj2::Integer, L::Integer, S::Integer, J::Integer) return _flsjj(Int.((l1, l2, dj1, dj2, L, S, J))...) end """ fMoshinsky(N::Integer, L::Integer, n::Integer, l::Integer, n1::Integer, l1::Integer, n2::Integer, l2::Integer, tanβ::Float64 = 1.0) float64 and fast Moshinsky bracket. """ @inline function fMoshinsky(N::Integer, L::Integer, n::Integer, l::Integer, n1::Integer, l1::Integer, n2::Integer, l2::Integer, Λ::Integer, tanβ::Float64=1.0) return _fMoshinsky(Int.((N, L, n, l, n1, l1, n2, l2, Λ))..., tanβ) end """ dfunc(dj::Integer, dm1::Integer, dm2::Integer, β::Float64) Wigner d-function. """ @inline function dfunc(dj::Integer, dm1::Integer, dm2::Integer, β::Float64) return _dfunc(Int.((dj, dm1, dm2))..., β) end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
1528
# this file contains some useful functions """ iphase(n::Integer) ``(-1)^n`` """ @inline iphase(n::T) where {T <: Integer} = iseven(n) ? one(T) : -one(T) """ is_same_parity(x::T, y::T) where {T <: Integer} judge if two integers are same odd or same even """ @inline is_same_parity(x::T, y::T) where {T <: Integer} = iseven(x ⊻ y) """ check_jm(dj::T, dm::T) where {T <: Integer} check if the m-quantum number if one of the components of the j-quantum number, in other words, `m` and `j` has the same parity, and `abs(m) < j` """ @inline check_jm(dj::T, dm::T) where {T <: Integer} = is_same_parity(dj, dm) & (abs(dm) <= dj) """ check_couple(dj1::T, dj2::T, dj3::T) where {T <: Integer} check if three angular monentum number `j1, j2, j3` can couple """ @inline check_couple(dj1::T, dj2::T, dj3::T) where {T <: Integer} = begin (dj1 >= 0) & (dj2 >= 0) & is_same_parity(dj1 + dj2, dj3) & (abs(dj1 - dj2) <= dj3 <= dj1 + dj2) end @doc raw""" binomial_data_size(n::Int)::Int Store (half) binomial data in the order of ```text # n - data 0 1 1 1 2 1 2 3 1 3 4 1 4 6 5 1 5 10 6 1 6 15 20 ``` Return the total number of the stored data. """ @inline function binomial_data_size(n::Int)::Int x = div(n, 2) + 1 return x * (x + isodd(n)) end @doc raw""" binomial_index(n::Int, k::Int)::Int Return the index of the binomial coefficient in the table. """ @inline function binomial_index(n::Int, k::Int)::Int x = div(n, 2) + 1 return x * (x - iseven(n)) + k + 1 end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
1886
using Test using CGcoefficient include("test_sqrtrational.jl") include("test_special.jl") include("test_orthonormality.jl") include("test_with_gsl.jl") include("test_float_gsl.jl") include("test_Moshinsky.jl") @testset "test SqrtRational" begin test_sqrtrational() end @testset "test SqrtRational show" begin test_show() end @testset "test simplify" begin test_simplify() end @testset "special condition: CG" begin test_special_CG(1//2:1//2:10) end @testset "special condition: CG0" begin test_CG0(1:10) end @testset "special condition: CGspin" begin test_CGspin() end @testset "special condition: 6j" begin test_special_6j(1//2:1//2:5) end @testset "special condition: Racah" begin test_special_Racah(1//2:1//2:5) end @testset "special condition: 9j" begin test_special_9j(1//2:1//2:3) end @testset "special condition: lsjj" begin test_lsjj(0:5) end @testset "special condition: flsjj" begin test_flsjj(0:5) end @testset "test orthonormality: dCG" begin test_orthonormality_dCG(0:8) end @testset "test summation: d3j" begin test_summation_d3j(0:40) end @testset "test orthonormality: d6j" begin test_orthonormality_d6j(0:6) end @testset "test orthonormality: d9j" begin test_orthonormality_d9j(0:4) end @testset "test Moshinsky" begin test_Moshinsky() end try gsl3j(1, 1, 1, 0, 0, 0) catch err if isa(err, ErrorException) println(err.msg) println("If you want to run test with libgsl, please download gsl library and rerun the test.") exit() end error(err) end @testset "test with gsl: 3j" begin test_3j_with_gsl(1:5) end @testset "test with gsl: 6j" begin test_6j_with_gsl(1:5) end @testset "test with gsl: 9j" begin test_9j_with_gsl(1:5) end @testset "float version: f3j" begin test_f3j_with_gsl(50:55) end @testset "float version: f6j" begin test_f6j_with_gsl(50:55) end @testset "float version: f9j" begin test_f9j_with_gsl(50:52) end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
904
# this file test the Moshinsky coefficients # the data comes from: Buck et al. Nuc. Phys. A 600 (1996) 387-402 const Moshinsky_test_set = [ 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 1 0 0 0 1 1 0 2 0 0 0 0 0 2 2 0 1 0 1 0 0 0 2 2 0 0 0 2 0 0 0 2 2 1 0 0 0 0 1 0 1 0 0 1 0 1 0 1 0 1 0 0 0 1 0 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 2 0 0 0 1 0 1 2 0 1 0 1 0 1 0 1 2 0 0 0 2 0 1 0 1 2] const inv_sqrt2 = exact_sqrt(1//2) const Moshinsky_test_set_result = [ 1, inv_sqrt2, -inv_sqrt2, 1//2, -inv_sqrt2, 1//2, inv_sqrt2, 0, -inv_sqrt2, -1, inv_sqrt2, 0, -inv_sqrt2 ] function test_Moshinsky() for i = eachindex(Moshinsky_test_set_result) @test Moshinsky(Moshinsky_test_set[i, :]...) == Moshinsky_test_set_result[i] @test fMoshinsky(Moshinsky_test_set[i, :]...) ≈ float(Moshinsky_test_set_result[i]) end end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
3029
# this file test the validity by comparing with the widely used `libgsl` # wapper of gsl 3nj functions function gsl3j(dj1::Int, dj2::Int, dj3::Int, dm1::Int, dm2::Int, dm3::Int) ccall( (:gsl_sf_coupling_3j, "libgsl"), Cdouble, (Cint, Cint, Cint, Cint, Cint, Cint), dj1, dj2, dj3, dm1, dm2, dm3 ) end function gsl6j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int) ccall( (:gsl_sf_coupling_6j, "libgsl"), Cdouble, (Cint, Cint, Cint, Cint, Cint, Cint), dj1, dj2, dj3, dj4, dj5, dj6 ) end function gsl9j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int, dj7::Int, dj8::Int, dj9::Int) ccall( (:gsl_sf_coupling_9j, "libgsl"), Cdouble, (Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint), dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9 ) end function check_6j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int) check_couple(dj1, dj2, dj3) & check_couple(dj1, dj5, dj6) & check_couple(dj4, dj2, dj6) & check_couple(dj4, dj5, dj3) end function check_9j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int, dj7::Int, dj8::Int, dj9::Int) check_couple(dj1, dj2, dj3) & check_couple(dj4, dj5, dj6) & check_couple(dj7, dj8, dj9) & check_couple(dj1, dj4, dj7) & check_couple(dj2, dj5, dj8) & check_couple(dj3, dj6, dj9) end function test_f3j_with_gsl(test_range::AbstractArray) wigner_init_float(cld(maximum(test_range), 2), "Jmax", 3) for dj1 in test_range for dj2 in test_range for dj3 in test_range for dm1 in -dj1:2:dj1 for dm2 in -dj2:2:dj2 dm3 = -dm1-dm2 if check_couple(dj1, dj2, dj3) & check_jm(dj3, dm3) gsl = gsl3j(dj1, dj2, dj3, dm1, dm2, dm3) my = f3j(dj1, dj2, dj3, dm1, dm2, dm3) @test isapprox(my, gsl; atol=1e-10) end end end end end end end function test_f6j_with_gsl(test_range::AbstractArray) wigner_init_float(cld(maximum(test_range), 2), "Jmax", 6) for j1 in test_range for j2 in test_range for j3 in test_range for j4 in test_range for j5 in test_range for j6 in test_range if check_6j(j1, j2, j3, j4, j5, j6) gsl = gsl6j(j1, j2, j3, j4, j5, j6) my = f6j(j1,j2,j3,j4,j5,j6) @test isapprox(my, gsl; atol=1e-10) end end end end end end end end function test_f9j_with_gsl(test_range::AbstractArray) wigner_init_float(cld(maximum(test_range), 2), "Jmax", 9) for j1 in test_range for j2 in test_range for j3 in test_range for j4 in test_range for j5 in test_range for j6 in test_range for j7 in test_range for j8 in test_range for j9 in test_range if check_9j(j1,j2,j3,j4,j5,j6,j7,j8,j9) gsl = gsl9j(j1,j2,j3,j4,j5,j6,j7,j8,j9) my = f9j(j1,j2,j3,j4,j5,j6,j7,j8,j9) @test isapprox(my, gsl; atol=1e-10) end end end end end end end end end end end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
4070
# this file test the orthonormality of Wigner symbols # All formulat are refered in # [1] D. A. Varshalovich, A. N. Moskalev and V. K. Khersonskii, Quantum Theory of Angular Momentum, (World Scientific, 1988). # Ref[1], P236, Sec 8.1, Formula (8) function test_orthonormality_dCG(test_range::AbstractArray) # Formula (8) first part for dj1 in test_range for dj2 in test_range for dj3 in test_range for dj4 in test_range if check_couple(dj1, dj2, dj3) && check_couple(dj1, dj2, dj4) for dm3 = -min(dj3,dj4):2:min(dj3,dj4) sum = zero(SqrtRational) for dm1 = -dj1:2:dj1 dm2 = dm3 - dm1 if check_jm(dj2, dm2) sum += dCG(dj1,dj2,dj3,dm1,dm2,dm3) * dCG(dj1,dj2,dj4,dm1,dm2,dm3) end end @test sum == Int(dj3==dj4) end end end end end end # Formula (8) second part for dj1 in test_range for dj2 in test_range for dm1 = -dj1:2:dj1 for dm2 = -dj2:2:dj2 for dm3 = -dj1:2:dj1 dm = dm1 + dm2 dm4 = dm - dm3 sum = zero(SqrtRational) for dj3 = abs(dj1-dj2):2:(dj1+dj2) if check_jm(dj2, dm4) && check_jm(dj3, dm) sum += dCG(dj1,dj2,dj3,dm1,dm2,dm) * dCG(dj1,dj2,dj3,dm3,dm4,dm) end end @test sum == Int(dm1 == dm3) end end end end end end # Ref[1], P453, Sec 12.1, Formula (2) function test_summation_d3j(test_range::AbstractArray) for dj1 = test_range for dj3 = 0:maximum(test_range) check_couple(dj1, dj1, dj3) || continue sum = zero(SqrtRational) for dm1 = -dj1:2:dj1 sum += iphase(div(dj1-dm1, 2)) * d3j(dj1,dj1,dj3,dm1,-dm1,0) end @test sum == exact_sqrt(dj1+1) * Int(dj3==0) end end end # Ref[1], P291, Sec 9.1, Formula(9) function test_orthonormality_d6j(test_range::AbstractArray) for dj1 in test_range for dj2 in test_range for dj4 in test_range for dj5 in test_range for dj6 in test_range for dj7 in test_range is_same_parity(dj6, dj7) || continue check_couple(dj1, dj5, dj6) || continue check_couple(dj1, dj5, dj7) || continue check_couple(dj4, dj2, dj6) || continue check_couple(dj4, dj2, dj7) || continue is_same_parity(dj1 + dj2, dj4 + dj5) || continue sum = zero(SqrtRational) djmin = max(abs(dj1-dj2), abs(dj4-dj5)) djmax = min(dj1+dj2, dj4+dj5) for dj3 = djmin:2:djmax sum += (dj3+1) * (dj6+1) * ( d6j(dj1,dj2,dj3,dj4,dj5,dj6) * d6j(dj1,dj2,dj3,dj4,dj5,dj7) ) end @test sum == Int(dj6==dj7) end end end end end end end # Ref[1], P335, Sec 10.1, Formula (9) function test_orthonormality_d9j(test_range::AbstractArray) for a in test_range for b in test_range for c in test_range for d in test_range for e in test_range for f in test_range for cx in test_range for fx in test_range for j in test_range is_same_parity(c, cx) || continue is_same_parity(f, fx) || continue check_couple(a, b, c) || continue check_couple(a, b, cx) || continue check_couple(d, e, f) || continue check_couple(d, e, fx) || continue check_couple(c, f, j) || continue check_couple(cx, fx, j) || continue sum = zero(SqrtRational) for g in abs(a-d):2:(a+d) for h in abs(b-e):2:(b+e) if check_couple(g, h, j) sum += (g+1)*(h+1)*( d9j(a,b,c,d,e,f,g,h,j) * d9j(a,b,cx,d,e,fx,g,h,j) ) end end end if (c==cx) && (f==fx) @test sum == 1//((c+1)*(f+1)) else @test sum == 0 end end end end end end end end end end end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
4143
# this file test the some special case if Wigner symbols # especially the when one of arguement is equal to zero # All formulat are refered in # [1] D. A. Varshalovich, A. N. Moskalev and V. K. Khersonskii, Quantum Theory of Angular Momentum, (World Scientific, 1988). # test special condition for CG coefficients # Ref[1], P248, Sec 8.5, Formula(1) function test_special_CG(test_range::AbstractArray) for j = test_range for m = -j:1:j cg = CG(j, j, 0, m, -m, 0) mycg = iphase(Int(j - m)) / exact_sqrt(2j + 1) @test cg == mycg end end end function test_CG0(test_range::AbstractArray) for j1 = test_range, j2 = test_range, j3 = test_range if check_couple(Int(2j1), Int(2j2), Int(2j3)) cg0 = CG0(j1, j2, j3) tj = threeJ(j1, j2, j3, 0, 0, 0) * iphase(2j1 + j3) * exact_sqrt(2j3 + 1) @test cg0 == tj end end end function test_CGspin() @test fCGspin(1, 1, 1) ≈ fCG(1, 1, 2, 1, 1, 2) ≈ 1.0 @test fCGspin(1, 1, 0) ≈ fCG(1, 1, 0, 1, 1, 2) ≈ 0.0 @test fCGspin(1, -1, 1) ≈ fCG(1, 1, 2, 1, -1, 0) ≈ 1/√2 @test fCGspin(1, -1, 0) ≈ fCG(1, 1, 0, 1, -1, 0) ≈ 1/√2 @test fCGspin(-1, 1, 1) ≈ fCG(1, 1, 2, -1, 1, 0) ≈ 1/√2 @test fCGspin(-1, 1, 0) ≈ fCG(1, 1, 0, -1, 1, 0) ≈ -1/√2 @test fCGspin(-1, -1, 1) ≈ fCG(1, 1, 2, -1, -1, -2) ≈ 1.0 @test fCGspin(-1, -1, 0) ≈ fCG(1, 1, 0, -1, -1, -2) ≈ 0.0 end # test special condition for 6j symbols # Ref[1], P299, Sec 9.5, Formula (1) function test_special_6j(test_range::AbstractArray) for j1 in test_range, j2 in test_range, j3 in test_range if check_couple(Int(2j1), Int(2j2), Int(2j3)) sj = sixJ(j1, j2, j3, j2, j1, 0) mysj = iphase(Int(j1 + j2 + j3)) / exact_sqrt((2j1 + 1) * (2j2 + 1)) @test sj == mysj end end end # test special condition for Racah coefficients # Ref[1], P300, Sec 9.5, Formula (2) function test_special_Racah(test_range::AbstractArray) for j1 in test_range, j2 in test_range, j3 in test_range if check_couple(Int(2j1), Int(2j2), Int(2j3)) rc = Racah(0, j1, j2, j3, j1, j2) myrc = 1 / exact_sqrt((2j1 + 1) * (2j2 + 1)) @test rc == myrc end end end function check_6j(j1::HalfInt, j2::HalfInt, j3::HalfInt, j4::HalfInt, j5::HalfInt, j6::HalfInt) dj1, dj2, dj3, dj4, dj5, dj6 = Int64.((2j1, 2j2, 2j3, 2j4, 2j5, 2j6)) check_couple(dj1, dj2, dj3) & check_couple(dj1, dj5, dj6) & check_couple(dj4, dj2, dj6) & check_couple(dj4, dj5, dj3) end # test special condition for 9j symbols # Ref[1], P357, Sec 10.9, Formula (1) function test_special_9j(test_range::AbstractArray) for j1 in test_range, j2 in test_range, j3 in test_range, j4 in test_range, j5 in test_range, j7 in test_range if check_6j(j1, j2, j3, j5, j4, j7) nj = nineJ(j1, j2, j3, j4, j5, j3, j7, j7, 0) snj = iphase(Int(j2 + j3 + j4 + j7)) / exact_sqrt((2j3 + 1) * (2j7 + 1)) snj *= sixJ(j1, j2, j3, j5, j4, j7) @test nj == snj end end end function test_lsjj(test_range::AbstractArray) for l1 in test_range for l2 in test_range for L in abs(l1-l2):(l1+l2) for (j1, j2) in [(l1+1//2, l2+1//2), (l1+1//2, l2-1//2), (l1-1//2, l2+1//2), (l1-1//2, l2-1//2)] for (S, J) in [(0, L), (1, L-1), (1, L), (1, L+1)] @test lsjj(l1, l2, j1, j2, L, S, J) == norm9J(l1, 1//2, j1, l2, 1//2, j2, L, S, J) end end end end end end function test_flsjj(test_range::AbstractArray) for l1 in test_range for l2 in test_range for L in abs(l1-l2):(l1+l2) for (dj1, dj2) in [(2l1+1, 2l2+1), (2l1+1, 2l2-1), (2l1-1, 2l2+1), (2l1-1, 2l2-1)] for (S, J) in [(0, L), (1, L-1), (1, L), (1, L+1)] @test flsjj(l1, l2, dj1, dj2, L, S, J) ≈ fnorm9j(2l1, 1, dj1, 2l2, 1, dj2, 2L, 2S, 2J) end end end end end end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
2485
# this file test the behavior of `SqrtRational` function test_sqrtrational() x = 3//5 * exact_sqrt(2//3) @test zero(x) == 0 @test 0*x == 0 @test (0*x).r == 1 @test (0*x) == zero(x) @test 1 == one(x) @test x*inv(x) == one(x) @test inv(x) == one(x)/x @test sign(+x) == 1 @test sign(-x) == -1 @test sign(0*x) == 0 @test signbit(+x) == false @test signbit(-x) == true @test signbit(0*x) == false end function test_show() x = exact_sqrt(3) y = exact_sqrt(3//5) @test string(zero(x)) == "0" @test string(one(x)) == "1" @test string(2//3*one(x)) == "2//3" @test string(x) == "√3" @test string(-x) == "-√3" @test string(-y) == "-√(3//5)" @test string(y) == "√(3//5)" @test string(3*x) == "3√3" @test string(2//3*y) == "2//3√(3//5)" io = IOBuffer() show(io, "text/markdown", zero(x)) @test String(take!(io)) == raw"$0$" * "\n" show(io, "text/markdown", one(x)) @test String(take!(io)) == raw"$1$" * "\n" show(io, "text/markdown", 2//3*one(x)) @test String(take!(io)) == raw"$\frac{2}{3}$" * "\n" show(io, "text/markdown", x) @test String(take!(io)) == raw"$\sqrt{3}$" * "\n" show(io, "text/markdown", y) @test String(take!(io)) == raw"$\sqrt{\frac{3}{5}}$" * "\n" show(io, "text/markdown", -x) @test String(take!(io)) == raw"$-\sqrt{3}$" * "\n" show(io, "text/markdown", -y) @test String(take!(io)) == raw"$-\sqrt{\frac{3}{5}}$" * "\n" show(io, "text/markdown", 3*x) @test String(take!(io)) == raw"$3\sqrt{3}$" * "\n" show(io, "text/markdown", 2//3*y) @test String(take!(io)) == raw"$\frac{2}{3}\sqrt{\frac{3}{5}}$" * "\n" end function test_simplify() @test simplify(2^7 * 3^3) == (2 * 3, 2^3 * 3) @test simplify(exact_sqrt(3//4)) == exact_sqrt(3) / 2 test_simplify_with_6j() end function test_simplify_with_6j() test_range = 2:1//2:4 for j1 in test_range for j2 in test_range for j3 in test_range for j4 in test_range for j5 in test_range for j6 in test_range dj1, dj2, dj3, dj4, dj5, dj6 = Int.((2j1, 2j2, 2j3, 2j4, 2j5, 2j6)) if check_couple(dj1, dj2, dj3) & check_couple(dj1, dj5, dj6) & check_couple(dj4, dj2, dj6) & check_couple(dj4, dj5, dj3) x = sixJ(j1,j2,j3,j4,j5,j6) @test simplify(x) == x end end end end end end end end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
code
3089
# this file test the validity by comparing with the widely used `libgsl` # wapper of gsl 3nj functions function gsl3j(dj1::Int, dj2::Int, dj3::Int, dm1::Int, dm2::Int, dm3::Int) ccall( (:gsl_sf_coupling_3j, "libgsl"), Cdouble, (Cint, Cint, Cint, Cint, Cint, Cint), dj1, dj2, dj3, dm1, dm2, dm3 ) end function gsl6j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int) ccall( (:gsl_sf_coupling_6j, "libgsl"), Cdouble, (Cint, Cint, Cint, Cint, Cint, Cint), dj1, dj2, dj3, dj4, dj5, dj6 ) end function gsl9j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int, dj7::Int, dj8::Int, dj9::Int) ccall( (:gsl_sf_coupling_9j, "libgsl"), Cdouble, (Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint), dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9 ) end function check_6j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int) check_couple(dj1, dj2, dj3) & check_couple(dj1, dj5, dj6) & check_couple(dj4, dj2, dj6) & check_couple(dj4, dj5, dj3) end function check_9j(dj1::Int, dj2::Int, dj3::Int, dj4::Int, dj5::Int, dj6::Int, dj7::Int, dj8::Int, dj9::Int) check_couple(dj1, dj2, dj3) & check_couple(dj4, dj5, dj6) & check_couple(dj7, dj8, dj9) & check_couple(dj1, dj4, dj7) & check_couple(dj2, dj5, dj8) & check_couple(dj3, dj6, dj9) end # Because the gsl compute wigner 3nj symbols using float point number, # sometimes my code give out zero, but gsl give out a very small number. # In this condition, `≈` operator will give false result. function test_3j_with_gsl(test_range::AbstractArray) for dj1 in test_range for dj2 in test_range for dj3 in test_range for dm1 in -dj1:2:dj1 for dm2 in -dj2:2:dj2 dm3 = -dm1-dm2 if check_couple(dj1, dj2, dj3) & check_jm(dj3, dm3) gsl = gsl3j(dj1, dj2, dj3, dm1, dm2, dm3) my = float(d3j(dj1, dj2, dj3, dm1, dm2, dm3)) @test (my == 0 && gsl < 1e-10) || (gsl ≈ my) end end end end end end end function test_6j_with_gsl(test_range::AbstractArray) for j1 in test_range for j2 in test_range for j3 in test_range for j4 in test_range for j5 in test_range for j6 in test_range if check_6j(j1, j2, j3, j4, j5, j6) gsl = gsl6j(j1, j2, j3, j4, j5, j6) my = float(d6j(j1,j2,j3,j4,j5,j6)) @test (my == 0 && gsl < 1e-10) || (gsl ≈ my) end end end end end end end end function test_9j_with_gsl(test_range::AbstractArray) for j1 in test_range for j2 in test_range for j3 in test_range for j4 in test_range for j5 in test_range for j6 in test_range for j7 in test_range for j8 in test_range for j9 in test_range if check_9j(j1,j2,j3,j4,j5,j6,j7,j8,j9) gsl = gsl9j(j1,j2,j3,j4,j5,j6,j7,j8,j9) my = float(d9j(j1,j2,j3,j4,j5,j6,j7,j8,j9)) @test (my == 0 && gsl < 1e-10) | (gsl ≈ my) end end end end end end end end end end end
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
docs
4358
# CGcoefficient.jl [![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE) [![CI](https://github.com/0382/CGcoefficient.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/0382/CGcoefficient.jl/actions/workflows/CI.yml) [![codecov.io](http://codecov.io/github/0382/CGcoefficient.jl/coverage.svg?branch=master)](http://codecov.io/github/0382/CGcoefficient.jl?branch=master) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://0382.github.io/CGcoefficient.jl/dev) [[中文](README_zh.md)] A package to calculate CG-coefficient, Racah coefficient, Wigner 3j, 6j, 9j symbols and Moshinsky brakets. One can get the exact result with `SqrtRational` type, which use `BigInt` to avoid overflow. And we also offer float version for numeric calculation, which is about twice faster than [GNU Scientific Library](https://www.gnu.org/software/gsl/). I also rewrite the float version with c++ for numeric calculation: [WignerSymbol](https://github.com/0382/WignerSymbol). For more details and the calculation formula, please see the document [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://0382.github.io/CGcoefficient.jl/dev). ### Install Just start a Julia REPL, and install it ```julia-repl julia> ] pkg> add CGcoefficient ``` ### Example ```julia-repl julia> CG(1,2,3,1,1,2) √(2//3) julia> nineJ(1,2,3,4,5,6,3,6,9) 1//1274√(3//5) julia> f6j(6,6,6,6,6,6) -0.07142857142857142 ``` For more examples please see the document. ### API This package contains two types of functions: 1. The exact functions return `SqrtRational`, which are designed for demonstration. They use `BigInt` in the internal calculation, and do not cache the binomial table, so they are not efficient. 2. The floating-point functions return `Float64`, which are designed for numeric calculation. They use `Int, Float64` in the internal calculation, and you should pre-call `wigner_init_float` to calculate and cache the binomial table for later calculation. They may give inaccurate result for vary large angular momentum, due to floating-point arithmetic. They are trustworthy for angular momentum number `Jmax <= 60`. #### Exact functions - `CG(j1, j2, j3, m1, m2, m3)`, CG-coefficient, arguments are `HalfInt`s, aka `Integer` or `Rational` like `3//2`. - `CG0(j1, j2, j3)`, CG-coefficient for `m1 = m2 = m3 = 0`, only integer angular momentum number is meaningful. - `threeJ(j1, j2, j3, m1, m2, m3)`, Wigner 3j-symbol, `HalfInt` arguments. - `sixJ(j1, j2, j3, j4, j5, j6)`, Wigner 6j-symbol, `HalfInt` arguments. - `Racah(j1, j2, j3, j4, j5, j6)`, Racah coefficient, `HalfInt` arguments. - `nineJ(j1, j2, j3, j4, j5, j6, j7, j8, j9)`, Wigner 9j-symbol, `HalfInt` arguments. - `norm9J(j2, j3, j4, j5, j5, j6, j7, j8, j9)`, normalized 9j-symbol, `HalfInt` arguments. - `lsjj(l1, l2, j1, j2, L, S, J)`, LS-coupling to jj-coupling transform coefficient. It actually equals to a normalized 9j-symbol, but easy to use and faster. `j1, j2` can be `HalfInt`. - `Moshinsky(N, L, n, l, n1, l1, n2, l2, Λ)`, Moshinsky brakets, `Integer` arguments. #### Float functions For faster numeric calculation, if the angular momentum number can be half-integer, the argument of the functions is actually double of the number. So that all arguments are integers. The doubled arguments are named starts with `d`. - `fCG(dj1, dj2, dj3, dm1, dm2, dm3)`, CG-coefficient. - `fCG0(j1, j2, j3)`, CG-coefficient for `m1 = m2 = m3 = 0`. - `fCGspin(ds1, ds2, S)`, quicker CG-coefficient for two spin-1/2 coupling. - `f3j(dj1, dj2, dj3, dm1, dm2, dm3)`, Wigner 3j-symbol. - `f6j(dj1, dj2, dj3, dj4, dj5, dj6)`, Wigner 6j-symbol. - `fRacah(dj1, dj2, dj3, dj4, dj5, dj6)`, Racah coefficient. - `f9j(dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9)`, Wigner 9j-symbol. - `fnorm9j(dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9)`, normalized 9j-symbol. - `flsjj(l1, l2, dj1, dj2, L, S, J)`, LS-coupling to jj-coupling transform coefficient. - `fMoshinsky(N, L, n, l, n1, l1, n2, l2, Λ)`, Moshinsky brakets. - `dfunc(dj, dm1, dm2, β)`, Wigner d-function. ### Reference - [https://github.com/ManyBodyPhysics/CENS](https://github.com/ManyBodyPhysics/CENS) - D. A. Varshalovich, A. N. Moskalev and V. K. Khersonskii, *Quantum Theory of Angular Momentum*, (World Scientific, 1988).
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
docs
3014
# CGcoefficient.jl [![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE) [![CI](https://github.com/0382/CGcoefficient.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/0382/CGcoefficient.jl/actions/workflows/CI.yml) [![codecov.io](http://codecov.io/github/0382/CGcoefficient.jl/coverage.svg?branch=master)](http://codecov.io/github/0382/CGcoefficient.jl?branch=master) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://0382.github.io/CGcoefficient.jl/dev) [[English](README.md)] 计算CG系数,Racah系数,Wigner 3j, 6j, 9j系数,Moshinsky系数等。 你可以使用定义的`SqrtRational`类型以保存准确结果,它内部使用`BigInt`计算以避免溢出。同时我们也提供浮点数运算的快速版本,比[GNU Scientific Library](https://www.gnu.org/software/gsl/)快一倍。 我也用c++重写了浮点数版本,用于数值计算:[WignerSymbol](https://github.com/0382/WignerSymbol). 关于更多更多细节以及计算公式,请看文档[![](https://img.shields.io/badge/docs-dev-blue.svg)](https://0382.github.io/CGcoefficient.jl/dev)。 ### 安装 使用julia REPL安装即可 ```julia-repl julia> ] pkg> add CGcoefficient ``` ### 示例 ```julia-repl julia> CG(1,2,3,1,1,2) √(2//3) julia> nineJ(1,2,3,4,5,6,3,6,9) 1//1274√(3//5) julia> f6j(6,6,6,6,6,6) -0.07142857142857142 ``` 更多示例请看文档。 ### 函数列表 这个包提供两类函数。 1. 精确函数。返回`SqrtRational`;这类函数主要是为了演示,内部使用`BigInt`进行计算,不需要缓存,计算速度相对较慢。 2. 浮点数函数。返回双精度浮点数;这类函数主要是为了数值计算,内部使用`Float64`进行计算。在使用之前,你需要先调用`wigner_init_float`来预想计算二项式系数表并缓存这个表,用于后面的计算。当角动量量子数非常大的时候,它们可能会由于浮点数计算产生一些误差,但对于角动量量子数`Jmax <= 60`,计算都是可信的。 #### 精确函数 - `CG(j1, j2, j3, m1, m2, m3)`, CG系数,参数是所谓`HalfInt`,也就是整数或者`3//2`这样分数类型。 - `CG0(j1, j2, j3)`, CG系数特殊情况`m1 = m2 = m3 = 0`,此时当然角动量是整数才有意义。 - `threeJ(j1, j2, j3, m1, m2, m3)`, Wigner 3j系数,参数均为`HalfInt`。 - `sixJ(j1, j2, j3, j4, j5, j6)`, Wigner 6j系数,参数均为`HalfInt`。 - `Racah(j1, j2, j3, j4, j5, j6)`, Racah系数,参数均为`HalfInt`。 - `nineJ(j1, j2, j3, j4, j5, j6, j7, j8, j9)`, Wigner 9j系数,参数均为`HalfInt`。 - `norm9J(j2, j3, j4, j5, j5, j6, j7, j8, j9)`, normalized 9j系数,参数均为`HalfInt`。 - `lsjj(l1, l2, j1, j2, L, S, J)`, LS耦合到jj耦合的转换系数,它实际上等于一个normalized 9j系数,但更易于使用且更快。`j1, j2`是`HalfInt`,其余必须是整数。 - `Moshinsky(N, L, n, l, n1, l1, n2, l2, Λ)`, Moshinsky括号,参数均为`HalfInt`。 #### 浮点数函数 对于数值计算而言,为了效率我们避免使用分数类型,如果某个参数可能是半整数,函数的则使用两倍的角动量量子数作为参数,以此避免半整数。在形参命名中,如果某个参数接受两倍的角动量,那么会有一个`d`前缀。 - `fCG(dj1, dj2, dj3, dm1, dm2, dm3)`, CG系数 - `fCG0(j1, j2, j3)`, CG系数特殊情况`m1 = m2 = m3 = 0`。 - `fCGspin(ds1, ds2, S)`, 快速计算1/2自旋的CG系数。 - `f3j(dj1, dj2, dj3, dm1, dm2, dm3)`, Wigner 3j系数。 - `f6j(dj1, dj2, dj3, dj4, dj5, dj6)`, Wigner 6j系数。 - `fRacah(dj1, dj2, dj3, dj4, dj5, dj6)`, Racah系数。 - `f9j(dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9)`, Wigner 9j系数。 - `fnorm9j(dj1, dj2, dj3, dj4, dj5, dj6, dj7, dj8, dj9)`, normalized 9j系数。 - `flsjj(l1, l2, dj1, dj2, L, S, J)`, LS耦合到jj耦合的转换系数。 - `fMoshinsky(N, L, n, l, n1, l1, n2, l2, Λ)`, oshinsky括号 - `dfunc(dj, dm1, dm2, β)`, Wigner d 函数。 ### 参考资料 - [https://github.com/ManyBodyPhysics/CENS](https://github.com/ManyBodyPhysics/CENS) - D. A. Varshalovich, A. N. Moskalev and V. K. Khersonskii, *Quantum Theory of Angular Momentum*, (World Scientific, 1988).
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
docs
1696
# API ## Types ```@docs HalfInt SqrtRational ``` ## Exact functions The default functions give out exact result in the format of `SqrtRational`. The results are simplified to give out shotest possible result. Their arguments are `HalfInt` (aka Integer or Rational with denomiator 2). ```@docs CG CG0 threeJ sixJ nineJ norm9J lsjj Racah Moshinsky ``` People often use double of angular momentum quantum number as parameters, so we can use integer as parameters. This package also offers such functions, where the `d` letter means *double*. These functions also give out exact `SqrtRational` results, but are not simplified. Because the `simplify` function is quite slow, if you want to do some calculation for the result, we suggest to use `d`-precedent functions first and `simplify` after call calculations. ```@docs dCG d3j d6j d9j dRacah ``` ## float version functions Float version functions is always used for numeric calculation. They are designed for fast calculation. You should call `wigner_init_float` to reserve the inner **binomial table**. They only resive `Integer` arguments, thus `fCG, f3j, f6j, fRacha, f9j` only resive arguements which are double of the exact quantum number. The rest functions do not need to do so. The difference is labeled with the arguement name: `dj` means of double of the quantum number, while `j` means the exact quantum number. ```@docs fbinomial unsafe_fbinomial fCG fCG0 fCGspin f3j f6j fRacah f9j fnorm9j flsjj fMoshinsky dfunc wigner_init_float ``` ## Some useful function ```@docs iphase is_same_parity check_jm check_couple binomial_data_size binomial_index exact_sqrt float(::SqrtRational) simplify(::Integer) simplify(::SqrtRational) ```
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
docs
9627
# Formula ## CG coefficient Ref [^1], P240, Section 8.2.4, Formula (20). ```math C_{j_1m_1j_2m_2}^{j_3m_3} = \delta_{m_3, m_1+m_2} \left[ \dfrac{\begin{pmatrix}2j_1 \\ J-2j_2\end{pmatrix}\begin{pmatrix}2j_2\\J-2j_3\end{pmatrix}}{\begin{pmatrix}J+1\\J-2j_3\end{pmatrix}\begin{pmatrix}2j_1\\j_1-m_1\end{pmatrix}\begin{pmatrix}2j_2 \\ j_2 - m_2\end{pmatrix}\begin{pmatrix}2j_3 \\ j_3-m_3\end{pmatrix}} \right]^{1/2} \\ \times \sum_{z} (-1)^{z}\begin{pmatrix}J-2j_3 \\ z\end{pmatrix}\begin{pmatrix}J-2j_2 \\ j_1-m_1-z\end{pmatrix}\begin{pmatrix}J-2j_1 \\ j_2 + m_2 - z\end{pmatrix} ``` where, $J = j_1+j_2+j_3$. It is already combination of binomials. ## 3j symbol Ref [^1], P236, Section 8.1.2, Formula (11). ```math \begin{pmatrix}j_1 & j_2 & j_3 \\ m_1 & m_2 & m_3\end{pmatrix} = (-1)^{j_3+m_3+2j_1}\dfrac{1}{\sqrt{2j_3+1}}C_{j_1-m_1j_2-m_2}^{j_3m_3} ``` This package use the CG coefficient above to calculate 3j symbol. ## 6j symbol Ref [^1], P293, Section 9.2.1, Formula (1). ```math \begin{Bmatrix}j_1 & j_2 & j_3 \\ j_4 & j_5 & j_6\end{Bmatrix} = \Delta(j_1j_2j_3)\Delta(j_4j_5j_3)\Delta(j_1j_5j_6)\Delta(j_4j_2j_6) \\ \times \sum\limits_x\dfrac{(-1)^x(x+1)!}{(x-j_{123})!(x-j_{453})!(x-j_{156})!(x-j_{426})!(j_{1245}-x)!(j_{1346}-x)!(j_{2356}-x)!} ``` Here, I use $j_{123} \equiv j_1+j_2+j_3$ for simplicity. The symbol $\Delta(abc)$ is defined as ```math \Delta(abc) = \left[\dfrac{(a+b-c)!(a-b+c)!(-a+b+c)!}{(a+b+c+1)!}\right]^{\frac{1}{2}}. ``` We can find that ```math \begin{pmatrix}j_1+j_2-j_3 \\ x - j_{453}\end{pmatrix} = \dfrac{(j_1+j_2-j_3)!}{(x-j_{453})!(j_{1245}-x)!} \\ \begin{pmatrix}j_1-j_2+j_3 \\ x - j_{426}\end{pmatrix} = \dfrac{(j_1-j_2+j_3)!}{(x-j_{426})!(j_{1346}-x)!} \\ \begin{pmatrix}j_2+j_3-j_1 \\ x - j_{156}\end{pmatrix} = \dfrac{(j_2+j_3-j_1)!}{(x-j_{156})!(j_{2356}-x)!} \\ \begin{pmatrix}x+1 \\ j_{123}+1\end{pmatrix} = \dfrac{(x+1)!}{(x-j_{123})(j_{123}+1)!}. ``` So, we have ```math \begin{Bmatrix}j_1 & j_2 & j_3 \\ j_4 & j_5 & j_6\end{Bmatrix} = \dfrac{\Delta(j_4j_5j_3)\Delta(j_1j_5j_6)\Delta(j_4j_2j_6)}{\Delta(j_1j_2j_3)} \\ \times \sum\limits_x (-1)^x \begin{pmatrix}x+1 \\ j_{123}+1\end{pmatrix} \begin{pmatrix}j_1+j_2-j_3 \\ x - j_{453}\end{pmatrix} \begin{pmatrix}j_1-j_2+j_3 \\ x - j_{426}\end{pmatrix} \begin{pmatrix}j_2+j_3-j_1 \\ x - j_{156}\end{pmatrix}. ``` Rewrite $\Delta(abc)$ with binomials, ```math \Delta(abc) = \left[\dfrac{1}{\begin{pmatrix}a+b+c+1 \\ 2a + 1\end{pmatrix} \begin{pmatrix}2a \\ a + b - c\end{pmatrix}(2a+1)}\right]^{\frac{1}{2}}. ``` So ```math \dfrac{\Delta(j_4j_5j_3)\Delta(j_1j_5j_6)\Delta(j_4j_2j_6)}{\Delta(j_1j_2j_3)} \\ = \dfrac{1}{2j_4+1} \left[\dfrac{\begin{pmatrix}j_{123}+1 \\ 2j_1+1\end{pmatrix}\begin{pmatrix}2j_1 \\ j_1 + j_2 - j_3\end{pmatrix}}{\begin{pmatrix}j_{156}+1 \\ 2j_1+1\end{pmatrix}\begin{pmatrix}2j_1 \\ j_1+j_5-j_6\end{pmatrix}\begin{pmatrix}j_{453}+1\\2j_4+1\end{pmatrix}\begin{pmatrix}2j_4\\j_4+j_5-j_3\end{pmatrix}\begin{pmatrix}j_{426}+1 \\ 2j_4+1\end{pmatrix}\begin{pmatrix}2j_4 \\ j_4+j_2-j_6\end{pmatrix}}\right]^{\frac{1}{2}} ``` ## Racha coefficient Ref [^1], P291, Section 9.1.2, Formula (11) ```math W(j_1j_2j_3j_4, j_5j_6) = (-1)^{j_1+j_2+j_3+j_4} \begin{Bmatrix} j_1 & j_2 & j_5 \\ j_4 & j_3 & j_6 \end{Bmatrix} ``` This package uses the 6j symbol above to calculate Racha coefficient. ## 9j symbol Ref [^1], P340, Section 10.2.4, Formula (20) ```math \begin{Bmatrix}j_1 & j_2 & j_3 \\ j_4 & j_5 & j_6 \\ j_7 & j_8 & j_9\end{Bmatrix} = \sum\limits_{t}(-1)^{2t}(2t+1)\begin{Bmatrix}j_1 & j_2 & j_3 \\ j_6 & j_9 & t\end{Bmatrix} \begin{Bmatrix}j_4 & j_5 & j_6 \\ j_2 & t & j_8\end{Bmatrix} \begin{Bmatrix}j_7 & j_8 & j_9 \\ t & j_1 & j_4\end{Bmatrix} ``` Use the 6j symbol result above, we get ```math \dfrac{\Delta(j_1j_9t)\Delta(j_6j_9j_3)\Delta(j_6j_2t)}{\Delta(j_1j_2j_3)} \dfrac{\Delta(j_4tj_8)\Delta(j_2tj_6)\Delta(j_2j_5j_8)}{\Delta(j_4j_5j_6)} \dfrac{\Delta(j_7j_1j_4)\Delta(tj_1j_9)\Delta(tj_8j_4)}{\Delta(j_7j_8j_9)} \\ = \dfrac{\Delta(j_3j_6j_9)\Delta(j_2j_5j_8)\Delta(j_1j_4j_7)}{\Delta(j_1j_2j_3)\Delta(j_4j_5j_6)\Delta(j_7j_8j_9)} \Delta^2(j_1j_9t)\Delta^2(j_2j_6t)\Delta^2(j_4j_8t). ``` Define ```math P_0 \equiv \dfrac{\Delta(j_3j_6j_9)\Delta(j_2j_5j_8)\Delta(j_1j_4j_7)}{\Delta(j_1j_2j_3)\Delta(j_4j_5j_6)\Delta(j_7j_8j_9)} \\ = \left[\dfrac{\begin{pmatrix}j_{123} + 1 \\ 2j_1+1\end{pmatrix}\begin{pmatrix}2j_1\\j_1+j_2-j_3\end{pmatrix}\begin{pmatrix}j_{456}+1\\2j_5+1\end{pmatrix}\begin{pmatrix}2j_5 \\ j_4+j_5-j_6\end{pmatrix}\begin{pmatrix}j_{789}+1 \\ 2j_9+1\end{pmatrix}\begin{pmatrix}2j_9 \\ j_7 + j_9 - j_8\end{pmatrix}}{\begin{pmatrix}j_{147} + 1\\ 2j_1 + 1\end{pmatrix}\begin{pmatrix}2j_1 \\ j_1+j_4-j_7\end{pmatrix}\begin{pmatrix}j_{258}+1 \\ 2j_5+1\end{pmatrix}\begin{pmatrix}2j_5 \\ j_2+j_5 - j_8\end{pmatrix}\begin{pmatrix}j_{369}+1 \\ 2j_9+1\end{pmatrix}\begin{pmatrix}2j_9 \\ j_3+j_9 - j_6\end{pmatrix}}\right]^{1/2}. ``` and then define ```math P(t) \equiv (-1)^{2t}(2t+1)\Delta^2(j_1j_9t)\Delta^2(j_2j_6t)\Delta^2(j_4j_8t) = \dfrac{(-1)^{2t}}{(2t+1)^2} \times \\ \dfrac{1}{\begin{pmatrix}j_1+j_9+t+1 \\ 2t+1\end{pmatrix}\begin{pmatrix}2t \\ j_1+t-j_9\end{pmatrix}\begin{pmatrix}j_2+j_6+t+1 \\ 2t+1\end{pmatrix}\begin{pmatrix}2t \\ j_2+t-j_6\end{pmatrix}\begin{pmatrix}j_4+j_8+t \\ 2t+1\end{pmatrix}\begin{pmatrix}2t \\ j_4+t-j_8\end{pmatrix}}. ``` ```math A(t,x) \equiv (-1)^x\begin{pmatrix}x+1 \\ j_{123} + 1\end{pmatrix}\begin{pmatrix}j_1+j_2-j_3 \\ x - (j_6+j_9+j_3)\end{pmatrix} \begin{pmatrix}j_1+j_3-j_2 \\ x - (j_6+j_2+t)\end{pmatrix}\begin{pmatrix}j_2+j_3-j_1 \\ x - (j_1 + j_9 + t)\end{pmatrix}. ``` ```math B(t,y) \equiv (-1)^y\begin{pmatrix}y+1 \\ j_{456} + 1\end{pmatrix}\begin{pmatrix}j_4+j_5-j_6 \\ y - (j_2+t+j_6)\end{pmatrix}\begin{pmatrix}j_4+j_6-j_5 \\ y - (j_2+j_5+j_8)\end{pmatrix}\begin{pmatrix}j_5+j_6-j_4 \\ y - (j_4+t+j_8)\end{pmatrix}. ``` ```math C(t,z) \equiv (-1)^z \begin{pmatrix}z+1 \\ j_{789} + 1\end{pmatrix}\begin{pmatrix}j_7+j_8-j_9 \\ z - (t+j_1+j_9)\end{pmatrix}\begin{pmatrix}j_7+j_9-j_8 \\ z - (t+j_8+j_4)\end{pmatrix}\begin{pmatrix}j_8+j_9- j_7 \\ z - (j_7 + j_1 + j_4)\end{pmatrix}. ``` At last, we get ```math \begin{Bmatrix}j_1 & j_2 & j_3 \\ j_4 & j_5 & j_6 \\ j_7 & j_8 & j_9\end{Bmatrix} = P_0\sum_t P(t) \left(\sum_x A(t,x)\right) \left(\sum_y B(t,y)\right) \left(\sum_z C(t,z)\right) ``` It deserves to be mentioned that, although the formula has 4 $\sum$s, the $\sum$ of $x,y,z$ are decoupled. So we can do the three `for loop`s respectively, which means the depth of `for loop` is not 4 but 2. ## Estimate the capacity Assume we are doing a calculation for a system, we will not calculate the Winger Symbols with very large angular momentum, because usually we will take some trunction. If in such truncated system, the max angular momentum is $J_{max}$, now we can estimate how many binomial coefficients we need to store to compute those Wigner Symbols. ### With maximum $J_{max}$ #### CG & 3j According to the formula, the max possible binomial is $\begin{pmatrix} J+1 \\ J-2j_3\end{pmatrix}$, where $J = j_1+j_2+j_3$. So we need at least store binomials to $\begin{pmatrix} n_{min} \\ k\end{pmatrix}$ where ```math n_{min} \geq 3J_{max}+1 ``` #### 6j & Racha For binomials in `sqrt`,the maximum possible $n = 3J_{max}+1$, and for those in the summation, we have to calculate the boundary of $x + 1$. According to the formula ```math x \leq \min\{j_1+j_2+j_4+j_5, j_1+j_3+j_4+j_6, j_2+j_3+j_5+j_6\} \leq 4J_{max} ``` So we have to at least store to ```math n_{min} \geq 4J_{max} + 1 ``` #### 9j Similarly, according to $P_0$, we need $3J_{max}+1$. According to $P(t)$, ```math t \leq \min\{j_2 + j_6, j_4 + j_8, j_1 + j_9\} \leq 2J_{max} ``` so we need $j_1 + j_9 + t + 1 \leq 4J_{max} + 1$. According to $A(t, x),\; B(t, y),\; C(t, z)$, ```math x \leq \min\{j_1+j_2+j_6+j_9, j_1+j_3+j_6+t, j_2+j_3+j_9+t\} \leq 5J_{max} ``` so we need to at least store to ```math n_{min} \geq 5J_{max} + 1 ``` ### With maximum single particle $j_{max}$ Considering a quantum many body calculation, we can get a more optimistic estimation of the calculation capacity. In a quantum many body calculation, we often truncate single particle orbits, and in this condition we assume that we only need to consider two-body coupled angular momentum. The maximum angular momentum of the single particle orbits defined as $j_{max}$. If for each function, there are at least one of the parameters is single particle angular momentum, then we can get the following estimation. #### CG & 3j In this condition, the $j_1, j_2, j_3$ contains two single particle angular momentum, and the rest one is a coupled two body angular momentum. So ```math n_{min} \geq 4j_{max} + 1 ``` #### 6j & Racha Similarly ```math x \leq \min\{j_1+j_2+j_4+j_5, j_1+j_3+j_4+j_6, j_2+j_3+j_5+j_6\} ``` These summations of four angular momentum can be split into two kinds, all single particle angular momentum, and two single particle with two two body angular momentum. Consider the worst condition ```math n_{min} \geq 6j_{max} + 1 ``` ### 9j We assume the 9j symbol contains at least one single particle angular momentum, then according to the coupling rules, the 9j symbol can be split into kinds ```math \begin{Bmatrix} 1 & 1 & 2 \\ 1 & 1 & 2 \\ 2 & 2 & 2 \end{Bmatrix} \quad \begin{Bmatrix} 1 & 1 & 2 \\ 1 & 2 & 1 \\ 2 & 1 & 1 \end{Bmatrix} ``` where $1$ represents single particle and $2$ for two body angular momentum. In both cases, we can deduce that ```math n_{min} \geq 8j_{max} + 1 ``` ---- Reference [^1]: A. N. Moskalev D. A. Varshalovich and V. K. Khersonskii, *Quantum theory of angular momentum*.
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
0.2.9
32f96d9a33411b31cb42e2a11538117fa9bb6bdc
docs
2724
# Home A package to calculate CG-coefficient, Racha coefficient, and Wigner 3j, 6j, 9j symbols. We offer three version API for all these coeddicients. - **normal version**: `CG, threeJ, SixJ, Racah, nineJ`. Their parameters can be `Integer` or `Rational` (half integer), and their result is simplified by default. - **double parameters version**: `dCG, d3j, d6j, dRacah d9j`. Their parameters means double of the real angular momentum, so can only be `Integer`. The result is not simplified. We will explain what is `simplify` later. - **float version**: `fCG, f3j, f6j, fRacah, f9j`. Their parameters is same as double parameter version. They use `Float64` for calculation, so they are not exact but are fast for numeric calculation. Because these function use stored `binomial` result for speed up calculation, you should reserve space before calculate large angular momentum coefficients. See `wigner_init_float` function for details. ## Install Just install with Julia REPL and enjoy it. ```julia-repl pkg> add CGcoefficient ``` ## Usage ```@setup example push!(LOAD_PATH, "../../src/") # hide ``` ```@example example using CGcoefficient sixJ(1,2,3,4,5,6) ``` In a markdown enviroment, such as jupyter notebook, it will give you a latex output. ```@example example d6j(2,4,6,8,10,12) ``` The `d` version functions do not simplify the result for the seek of speed, because `simplify` needs prime factorization which is slow. You can simplify the result explicitly, ```@example example simplify(d6j(2,4,6,8,10,12)) ``` You can also do some arithmetics with the result, thus do arithmetics using the `SqrtRational` type. The result is also not simplified ```@example example x = sixJ(1,2,3,4,5,6) * exact_sqrt(1//7) * exact_sqrt(1//13) * iphase(2+3+5+6) simplify(x) ``` In a console enviroment it will give out a text output. ```@repl example nineJ(1,2,3,5,4,3,6,6,0) ``` You can also use `print` function to force print a text output. ```@example example print(Racah(1,2,3,2,1,2)) ``` ## About This package is inspired by Ref [^1]. See [CENS-MBPT](https://github.com/ManyBodyPhysics/CENS/blob/master/MBPT/VEffective/bhf-modules.f90) for details. The idea is to simplify 3nj Symbols to sum combinations of binomial coefficients. We can calculate binomial coefficients by Pascal's Triangle, and store them first. Then we calculate 3nj Symbols using the stored binomial coefficients. In this package, we just use the builtin `binomial` function for exact calculation. Only the float version uses stored `binomial`s. ## Index - [Formula](formula.md) - [API](api.md) [^1]: T. Engeland and M. Hjorth-Jensen, the Oslo-FCI code. [https://github.com/ManyBodyPhysics/CENS](https://github.com/ManyBodyPhysics/CENS).
CGcoefficient
https://github.com/0382/CGcoefficient.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
394
module Consensus using StochasticDiffEq using Suppressor import Distributions.Uniform import Statistics.mean include("benchmarkFunctions.jl") include("checkAllocations.jl") include("defaults.jl") include("method.jl") include("minimise.jl") export minimise, maximise, minimize, maximize export AckleyFunction, Parabola, RastriginFunction export @isAllocationFree, @isCalledFromFunction end
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
1314
function Parabola(x::AbstractVector{<:Real}, B::Real=0, C::Real=0) D = length(x) res = 0.0 for d = 1:D res += (x[d] - B)^2 end return res / 2 + C end function AckleyFunction(x::AbstractVector{<:Real}, B::Real=0, C::Real=0) first = AckleyFirstTerm(x, B) second = AckleySecondTerm(x, B) return 20 * (1 - exp(first)) - exp(second) + ℯ + C end function AckleyFirstTerm(x::AbstractVector{Float64}, B::Real) D = length(x) C = -0.2 / sqrt(D) res = 0.0 for d = 1:D res += (x[d] - B)^2 end return C * sqrt(res) end function AckleySecondTerm(x::AbstractVector{Float64}, B::Real) D = length(x) res = 0.0 for d = 1:D arg = 2π * (x[d] - B) if !isinf(arg) res += cos(arg) end end return res / D end function RastriginFunction(x::AbstractVector{<:Real}, B::Real=0, C::Real=0) first = RastriginFirstTerm(x, B) second = RastriginSecondTerm(x, B) return 10 * (1 - first) + second + C end function RastriginFirstTerm(x::AbstractVector{Float64}, B::Real) D = length(x) res = 0.0 for d = 1:D arg = 2π * (x[d] - B) if !isinf(arg) res += cos(arg) end end return res / D end function RastriginSecondTerm(x::AbstractVector{Float64}, B::Real) D = length(x) res = 0.0 for d = 1:D res += (x[d] - B)^2 end return res / D end
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
394
macro isCalledFromFunction() expr = esc(:( try currentFunctionName = nameof(var"#self#") true catch false end )) return expr end macro isAllocationFree(expr...) return esc( quote !@isCalledFromFunction() && @warn "@isAllocationFree could be imprecise if evaluated outside a function" (@allocated $(expr...)) === 0 end, ) end
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
171
const DEFAULT_OPTIONS = (;# M=100, N=50, R=1, T=100, α=50, Δt=0.1, λ=1, σ=1, ε=0.1, integrator=EM(), returnSamples=false, returnSolutions=false );
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
1039
Hε(x::Real, ε::Real) = (1 + tanh(x / ε)) / 2; ωfα(α, f, x) = exp(-α * f(x)); function meanValue!(X, cache) D = cache.D f = cache.f N = cache.N vf = cache.vf α = cache.α ∑ω = 0.0 for d = 1:D vf[d] = 0.0 end for i = 1:N xi = view(X, :, i) ωi = ωfα(α, f, xi) ∑ω += ωi for d = 1:D vf[d] += ωi * xi[d] end end for d = 1:D vf[d] /= ∑ω end return nothing end function dt!(Ẋ, X, cache, t) meanValue!(X, cache) D = cache.D f = cache.f N = cache.N vf = cache.vf ε = cache.ε λ = cache.λ fvf = f(vf) for i = 1:N xi = view(X, :, i) fi = f(xi) C = λ * Hε(fi - fvf, ε) for d = 1:D Ẋ[d, i] = C * (vf[d] - xi[d]) end end return nothing end function dW!(Ẋ, X, cache, t) D = cache.D N = cache.N sqrt2σ = cache.sqrt2σ vf = cache.vf for i = 1:N xi = view(X, :, i) C = 0.0 for d = 1:D C += (xi[d] - vf[d])^2 end C = sqrt2σ * sqrt(C) for d = 1:D Ẋ[d, i] = C end end return nothing end
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
2105
function minimise(f::Function, x::AbstractVector{<:Real}; args...) options = getOptions(; args...) optimisers, _ = minimiseWithParsedOptions(f, x, options) optimiser = mean(optimisers) if options.returnSamples return optimiser, optimisers else return optimiser end end function getOptions(; args...) options = merge(DEFAULT_OPTIONS, args) @assert options.ε > 0 return options end function minimiseWithParsedOptions( f::Function, x::AbstractVector{<:Real}, options::NamedTuple, ) cache = getCache(f, x, options) X0 = getInitialState(x, cache) T = Float64(cache.T) time = (0.0, T) function remakeProblem(prob, i, repeat) cache = getCache(f, x, options) X0 = getInitialState(x, cache) return remake(prob, u0=X0, p=cache) end problem = SDEProblem(dt!, dW!, X0, time, cache) ensembleProblem = EnsembleProblem( problem, prob_func=remakeProblem ) solutions = nothing @suppress_err begin solutions = solve(ensembleProblem, cache.integrator, EnsembleThreads(), dt=cache.Δt, saveat=T, trajectories=cache.M ) end optimisers = map(getOptimiser, solutions) return optimisers, solutions end function getOptimiser(solution) X = solution[end] cache = solution.prob.p meanValue!(X, cache) return cache.vf end function getCache(f::Function, x::AbstractVector{<:Real}, options::NamedTuple) D = length(x) sqrt2σ = sqrt(2) * options.σ vf = zeros(D) newFields = (; D, f, vf, sqrt2σ) cache = merge(options, newFields) return cache end function getInitialState(x::AbstractVector{<:Real}, cache::NamedTuple) D, N, R = cache.D, cache.N, cache.R X0 = zeros(D, N) for n = 1:N, d = 1:D X0[d, n] = rand(Uniform(x[d] - R, x[d] + R)) end return X0 end function minimise(f::Function, x::Real; args...) g(x) = f(x[1]) return minimise(g::Function, [x]; args...) end function maximise(f::Function, x; args...) g(x) = -f(x) return minimise(g::Function, x; args...) end minimize(f::Function, x; args...) = minimise(f, x; args...); maximize(f::Function, x; args...) = maximise(f, x; args...);
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
1644
using Consensus using Test const N = 20; function tests() @testset "Ackley Function" begin @testset "allocations" begin x = rand(N) B = rand() C = rand() @test @isAllocationFree Consensus.AckleyFirstTerm(x, B) @test @isAllocationFree Consensus.AckleySecondTerm(x, B) @test @isAllocationFree AckleyFunction(x, B, C) end @testset "values" begin B = rand() C = rand() x = ones(N) * B @test AckleyFunction(x, 0, C) >= C @test AckleyFunction(x, B, C) ≈ C @test AckleyFunction(x * 0, 0, C) ≈ C @test AckleyFunction(x * 0) ≈ 0 end end @testset "Rastrigin Function" begin @testset "allocations" begin x = rand(N) B = rand() C = rand() @test @isAllocationFree Consensus.RastriginFirstTerm(x, B) @test @isAllocationFree Consensus.RastriginSecondTerm(x, B) @test @isAllocationFree RastriginFunction(x, B, C) end @testset "values" begin B = rand() C = rand() x = ones(N) * B @test RastriginFunction(x, 0, C) >= C @test RastriginFunction(x, B, C) ≈ C @test RastriginFunction(x * 0, 0, C) ≈ C @test RastriginFunction(x * 0) ≈ 0 end end @testset "Parabola" begin @testset "allocations" begin x = rand(N) B = rand() C = rand() @test @isAllocationFree Parabola(x, B, C) end @testset "values" begin B = rand() C = rand() x = ones(N) * B @test Parabola(x, 0, C) >= C @test Parabola(x, B, C) ≈ C @test Parabola(x * 0, 0, C) ≈ C @test Parabola(x * 0) ≈ 0 end end end tests()
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
154
using Consensus using Test using JuliaFormatter function tests() @test format(".", remove_extra_newlines = true, indent = 2, margin = 80) end tests()
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
911
using Consensus using Test const N = 20; function tests() @testset "meanValue!" begin f = AckleyFunction x = rand(N) options = Consensus.getOptions() cache = Consensus.getCache(f, x, options) X = Consensus.getInitialState(x, cache) @test @isAllocationFree Consensus.meanValue!(X, cache) end @testset "dt!" begin f = AckleyFunction x = rand(N) options = Consensus.getOptions() cache = Consensus.getCache(f, x, options) X = Consensus.getInitialState(x, cache) Ẋ = zero(X) t = rand() @test @isAllocationFree Consensus.dt!(Ẋ, X, cache, t) end @testset "dW!" begin f = AckleyFunction x = rand(N) options = Consensus.getOptions() cache = Consensus.getCache(f, x, options) X = Consensus.getInitialState(x, cache) Ẋ = zero(X) t = rand() @test @isAllocationFree Consensus.dW!(Ẋ, X, cache, t) end end tests()
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
1136
using Consensus using Test import Distributions.Uniform import LinearAlgebra.norm NegParabola(x) = -Parabola(x); for method in (:minimise, :maximise, :minimize, :maximize) @eval begin function $(Symbol(method, :Test))(f, N) x = rand(Uniform(-3, 3), N) z = $method(f, x) @test norm(z) < norm(x) end end end function dimTest(N) @testset "Parabola" begin minimiseTest(Parabola, N) end @testset "Ackley" begin minimiseTest(AckleyFunction, N) end @testset "Rastrigin" begin minimiseTest(RastriginFunction, N) end end function tests() @testset "minimise" begin @testset "1D" begin dimTest(1) end @testset "5D" begin dimTest(5) end @testset "20D" begin dimTest(5) end @testset "shifted" begin f(x) = Parabola(x, 1, 2) x = [0] z = minimise(f, x) @test norm(z .- 1) < norm(x .- 1) end end @testset "minimize" begin minimizeTest(Parabola, 1) end @testset "maximise" begin maximiseTest(NegParabola, 1) end @testset "maximize" begin maximizeTest(NegParabola, 1) end end tests()
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
code
271
using SafeTestsets @safetestset "benchmarkFunctions" begin include("benchmarkFunctions.jl") end @safetestset "method" begin include("method.jl") end @safetestset "minimise" begin include("minimise.jl") end @safetestset "format" begin include("format.jl") end
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
1.0.0
7919259feeca03474453dc0b95d5b72da6fbaf65
docs
4493
# Consensus.jl [![CI](https://github.com/rafaelbailo/Consensus.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/rafaelbailo/Consensus.jl/actions/workflows/CI.yml) **Consensus.jl** is a lightweight, gradient-free, stochastic optimisation package for Julia. It uses _Consensus-Based Optimisation_ (CBO), a flavour of _Particle Swarm Optimisation_ (PSO) first introduced by [R. Pinnau, C. Totzeck, O. Tse, and S. Martin (2017)][1]. This is a method of global optimisation particularly suited for rough functions, where gradient descent would fail. It is also useful for optimisation in higher dimensions. This package was created and is developed by [Dr Rafael Bailo](https://rafaelbailo.com/). ## Usage The basic command of the library is `minimise(f, x0)`, where `f` is the function you want to minimise, and `x0` is an initial guess. It returns an approximation of the point `x` that minimises `f`. You have two options to define the objective function: - `x` is of type `Real`, and `f` is defined as `f(x::Real) = ...`. - `x` is of type `AbstractVector{<:Real}`, and `f` is defined as `f(x::AbstractVector{<:Real}) = ...`. ### A trivial example We can demonstrate the functionality of the library by minimising the function $f(x)=x^2$. If you suspect the minimiser is near $x=1$, you can simply run ```jl using Consensus f(x) = x^2; x0 = 1; x = minimise(f, x0) ``` to obtain ```jl julia> x 1-element Vector{Float64}: 0.08057420724239409 ``` Your `x` may vary, since the method is stochastic. The answer should be close, but not exactly equal, to zero. Behind the scenes, **Consensus.jl** is running the algorithm using `N = 50` particles per realisation. It runs the `M = 100` realisations, and returns the averaged result. If you want to parallelise these runs, simply start julia with multiple threads, e.g.: ```sh $ julia --threads 4 ``` **Consensus.jl** will then automatically parallelise the optimisation. This is thanks to the functionality of [StochasticDiffEq.jl](https://github.com/SciML/StochasticDiffEq.jl), which is used under the hood to implement the algorithm. ### Advanced options There are several parameters that can be customised. The most important are: - `N`: the number of particles per realisation. - `M`: the number of realisations, whose results are averaged in the end. - `T`: the run time of each realisation. The longer this is, the better the results, but the longer you have to wait for them. - `Δt`: the discretisation step of the realisations. Smaller is more accurate, but slower. If the optimisation fails (returns `Inf` or `NaN`), making this smaller is likely to help. - `R`: the radius of the initial sampling area, which is centred around your intiial guess `x0`. - `α`: the exponential weight. The higher this is, the better the results, but you might need to decrease `Δt` if `α` is too large. We can run the previous example with custom parameters by calling ```jl julia> x2 = minimise(f, x0, N = 30, M = 100, T = 10, Δt = 0.5, R = 2, α = 500) 1-element Vector{Float64}: 0.0017988128895332278 ``` For the other parameters, please refer to the paper of [R. Pinnau, C. Totzeck, O. Tse, and S. Martin (2017)][1]. You can see the default values of the parameters by evaluating `Consensus.DEFAULT_OPTIONS`. ### Non-trivial examples Since CBO is not a gradient method, it will perform well on rough functions. **Consensus.jl** implements two well-known test cases in any number of dimensions: - The [Ackley function](https://en.wikipedia.org/wiki/Ackley_function). - The [Rastrigin function](https://en.wikipedia.org/wiki/Rastrigin_function). We can minimise the Ackley function in two dimensions, starting near the point $x=(1,1)$, by running ```jl julia> x3 = minimise(AckleyFunction, [1, 1]) 2-element Vector{Float64}: 0.0024744433653736513 0.030533227060295706 ``` We can also minimise the Rastrigin function in five dimensions, starting at a random point, with more realisations, and with a larger radius, by running ```jl julia> x4 = minimise(RastriginFunction, rand(5), M = 200, R = 5) 5-element Vector{Float64}: -0.11973689657393186 0.07882427348951951 0.18515501300052115 -0.06532360247574359 -0.13132340855939928 ``` ### Auxiliary commands There is a `maximise(f, x0)` method, which simply minimises the function `g(x) = -f(x)`. Also, if you're that way inclined, you can call `minimize(f, x0)` and `maximize(f, x0)`, in the American spelling. [1]: http://dx.doi.org/10.1142/S0218202517400061
Consensus
https://github.com/rafaelbailo/Consensus.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
1292
using Documenter, RigidBodyTools ENV["GKSwstype"] = "nul" # removes GKS warnings during plotting makedocs( sitename = "RigidBodyTools.jl", doctest = true, clean = true, pages = [ "Home" => "index.md", "Bodies and Transforms" => ["manual/shapes.md", "manual/transforms.md", "manual/bodylists.md"], "Motions" => ["manual/dofmotions.md", "manual/joints.md", "manual/exogenous.md", "manual/deformation.md", "manual/surfacevelocities.md"] #"Internals" => [ "internals/properties.md"] ], #format = Documenter.HTML(assets = ["assets/custom.css"]) format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true", mathengine = MathJax(Dict( :TeX => Dict( :equationNumbers => Dict(:autoNumber => "AMS"), :Macros => Dict() ) )) ), #assets = ["assets/custom.css"], #strict = true ) #if "DOCUMENTER_KEY" in keys(ENV) deploydocs( repo = "github.com/JuliaIBPM/RigidBodyTools.jl.git", target = "build", deps = nothing, make = nothing #versions = "v^" ) #end
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
3553
module RigidBodyTools using StaticArrays using LinearAlgebra using UnPack import Base: *, +, -, inv, transpose, vec import Base: @propagate_inbounds,getindex, setindex!,iterate,size,length,push!, collect,view,findall import LinearAlgebra: dot export Body, NullBody export RigidBodyMotion, AbstractKinematics, d_dt, motion_velocity, motion_state, surface_velocity!, surface_velocity, update_body!, transform_body!, AbstractDeformationMotion, ConstantDeformationMotion, DeformationMotion, NullDeformationMotion,maxvelocity, zero_body, update_exogenous!, zero_exogenous, body_velocities, velocity_in_body_coordinates_2d, rebase_from_inertial_to_reference export parent_body_of_joint, child_body_of_joint, parent_joint_of_body, child_joints_of_body, position_vector,velocity_vector,deformation_vector, exogenous_position_vector, exogenous_velocity_vector, unconstrained_position_vector, unconstrained_velocity_vector export AbstractDOFKinematics, AbstractPrescribedDOFKinematics, DOFKinematicData, SmoothRampDOF, SmoothVelocityRampDOF, OscillatoryDOF, ConstantVelocityDOF, CustomDOF, ExogenousDOF, ConstantPositionDOF, UnconstrainedDOF, Kinematics, dof_position, dof_velocity, dof_acceleration, ismoving, is_system_in_relative_motion export RigidTransform, rotation_about_x, rotation_about_y, rotation_about_z, rotation_from_quaternion, quaternion, rotation_about_axis, rotation_identity, MotionTransform, ForceTransform, AbstractTransformOperator, rotation_transform, translation_transform, motion_transform_from_A_to_B, force_transform_from_A_to_B, cross_matrix, cross_vector, translation, rotation, motion_subspace, joint_velocity export PluckerForce, PluckerMotion, motion_rhs!, zero_joint, zero_motion_state, init_motion_state, angular_only, linear_only export Joint, joint_transform, parent_to_child_transform, LinkedSystem, position_dimension, exogenous_dimension, constrained_dimension, unconstrained_dimension, position_and_vel_dimension, body_transforms, number_of_dofs export RevoluteJoint, PrismaticJoint, CylindricalJoint, SphericalJoint, FreeJoint, FreeJoint2d, FixedJoint const NDIM = 2 const CHUNK = 3*(NDIM-1) abstract type BodyClosureType end abstract type OpenBody <: BodyClosureType end abstract type ClosedBody <: BodyClosureType end abstract type PointShiftType end abstract type Unshifted <: PointShiftType end abstract type Shifted <: PointShiftType end abstract type Body{N,C<:BodyClosureType} end abstract type AbstractMotion end abstract type AbstractDeformationMotion <: AbstractMotion end struct NullBody <: Body{0,ClosedBody} cent :: Tuple{Float64,Float64} α :: Float64 x̃ :: Vector{Float64} ỹ :: Vector{Float64} x :: Vector{Float64} y :: Vector{Float64} x̃end :: Vector{Float64} ỹend :: Vector{Float64} xend :: Vector{Float64} yend :: Vector{Float64} end NullBody() = NullBody((0.0,0.0),0.0,Float64[],Float64[],Float64[],Float64[],Float64[],Float64[],Float64[],Float64[]) numpts(::Body{N}) where {N} = N numpts(::Nothing) = 0 include("kinematics.jl") include("rigidtransform.jl") include("joints.jl") include("lists.jl") include("rigidbodymotions.jl") include("directmotions.jl") include("tools.jl") include("assignvelocity.jl") include("shapes.jl") include("plot_recipes.jl") end
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
512
""" surface_velocity(body::Body,motion::AbstractMotion,t::Real[;inertial=true]) Return the components of rigid body velocity (in inertial coordinate system) at surface positions described by inertial coordinates in body `body` at time `t`, based on supplied motions in `motion` for the body. If `inertial=false`, then velocities are computed and body positions are assumed to be in comoving coordinates. """ surface_velocity(b::Body,a...;kwargs...) = surface_velocity!(zero(b.x),zero(b.y),b,a...;kwargs...)
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
9325
#= NOTE: The combined rigid/deforming motion needs to be updated, so that deforming motion is added to an underlying linked system. To create a subtype of AbstractDeformationMotion, one must extend `deformation_velocity(body,m,t)`, to supply the surface values of the motion in-place in vectors `u` and `v`. These are interpreted as an update of the body-fixed coordinates, `b.x̃end` and `b.ỹend`, in the body's coordinate system. =# """ NullDeformationMotion(u::Vector{Float64},v::Vector{Float64}) Create a null instance of directly-specified deformation, used for rigid bodies. """ struct NullDeformationMotion <: AbstractDeformationMotion end deformation_velocity(b::Body,m::NullDeformationMotion,t::Real) = Float64[] zero_motion_state(b::Body,m::NullDeformationMotion) = Float64[] motion_state(b::Body,m::NullDeformationMotion) = Float64[] ismoving(m::AbstractDeformationMotion) = true ismoving(m::NullDeformationMotion) = false function update_body!(b::Body,x::AbstractVector,m::NullDeformationMotion) end """ ConstantDeformationMotion(u::Vector{Float64},v::Vector{Float64}) Create an instance of basic directly-specified (constant) velocity, to be associated with a body whose length is the same as `u` and `v`. """ struct ConstantDeformationMotion{VT} <: AbstractDeformationMotion u :: VT v :: VT end function deformation_velocity(b::Body,m::ConstantDeformationMotion,t::Real) return vcat(m.u,m.v) end struct DeformationMotion{UT,VT} <: AbstractDeformationMotion ufcn :: UT vfcn :: VT end """ DeformationMotion(u::Function,v::Function) Create an instance of directly-specified velocity whose components are specified with functions. These functions `u` and `v` must each be of the form `f(x̃,ỹ,t)`, where `x̃` and `ỹ` are coordinates of a point in the body coordinate system and `t` is time, and they must return the corresponding velocity component in the body coordinate system. """ DeformationMotion(::Function,::Function) """ deformation_velocity(b::Body,m::DeformationMotion,t::Real) Return the velocity components (as a vector) of a `DeformationMotion` at the given time `t`. These specify the velocities (in body cooordinates) of the surface segments endpoints. """ function deformation_velocity(b::Body,m::DeformationMotion,t::Real) return vcat(m.ufcn.(b.x̃end,b.ỹend,t), m.vfcn.(b.x̃end,b.ỹend,t)) end """ motion_state(b::Body,m::AbstractDeformationMotion) Return the current state vector of body `b` associated with direct motion `m`. It returns the concatenated coordinates of the body surface (in the body-fixed coordinate system). """ function motion_state(b::Body,m::AbstractDeformationMotion) return vcat(b.x̃end,b.ỹend) end function zero_motion_state(b::Body,m::AbstractDeformationMotion) return vcat(zero(b.x̃end),zero(b.ỹend)) end # This computes deformation velocities relative to the body, in the body coordinates function _surface_velocity!(u::AbstractVector{Float64},v::AbstractVector{Float64}, b::Body{N,C},m::AbstractDeformationMotion,t::Real) where {N,C} vel = deformation_velocity(b,m,t) lenx = length(vel) # interpolate to the midpoints if lenx > 0 umid, vmid = _midpoints(vel[1:lenx÷2],vel[lenx÷2+1:lenx],C) u .= umid v .= vmid end # Rotate to the inertial coordinate system #T = RigidTransform(b.cent,b.α) #for i in eachindex(u) # Utmp = T.R'*[u[i],v[i],0.0] # u[i], v[i] = Utmp[1:2] #end return u, v end function _update_body!(b::Body{N,C},x::AbstractVector,m::AbstractDeformationMotion) where {N,C} #length(x) == length(motion_state(b,m)) || error("wrong length for motion state vector") lenx = length(x) if lenx > 0 b.x̃end .= x[1:lenx÷2] b.ỹend .= x[lenx÷2+1:lenx] end #= b.x̃, b.ỹ = _midpoints(b.x̃end,b.ỹend,C) # use the existing rigid transform of the body to update the # inertial coordinates of the surface T = RigidTransform(b.cent,b.α) T(b) =# return b end #= AbstractRigidAndDeformingMotion describes motions that superpose the rigid-body motion with surface deformation. For this type of motion, the velocity is described by the usual rigid-body components (reference point velocity, angular velocity), plus vectors ũ and ṽ, describing the surface endpoint velocity *in the body coordinate system*. The motion state consists of the centroid, the angle, and the positions x̃end and ỹend of the surface endpoints in the body coordinate system. To create a motion of this type, we still need to supply an extension of deformation_velocity(b,m,t). However, this needs to supply only the deforming part of the velocity, and in the body's own coordinate system. =# #= """ RigidAndDeformingMotion(rig::RigidBodyMotion,def::AbstractDeformationMotion) Create an instance of basic superposition of a rigid-body motion and directly-specified deformation velocity in body coordinates. """ struct RigidAndDeformingMotion{RT,DT} <: AbstractMotion rigidmotion :: RT defmotion :: DT end """ RigidAndDeformingMotion(kin::AbstractKinematics,def::AbstractDeformationMotion) Create an instance of basic superposition of a rigid-body motion with kinematics `kin`, and directly-specified deformation velocity in body coordinates. """ RigidAndDeformingMotion(kin::AbstractKinematics,def::AbstractDeformationMotion) = RigidAndDeformingMotion(RigidBodyMotion(kin),def) """ RigidAndDeformingMotion(kin::AbstractKinematics,ũ::Vector{Float64},ṽ::Vector{Float64}) Create an instance of basic superposition of a rigid-body motion and directly-specified (constant) deformation velocity in body coordinates, to be associated with a body whose length is the same as `ũ` and `ṽ`. """ RigidAndDeformingMotion(kin::AbstractKinematics, ũ, ṽ) = RigidAndDeformingMotion(RigidBodyMotion(kin), BasicDirectMotion(ũ,ṽ)) """ RigidAndDeformingMotion(ċ,α̇,ũ::Vector{Float64},ṽ::Vector{Float64}) Specify constant translational `ċ` and angular `α̇` velocity and directly-specified (constant) deformation velocity in body coordinates, to be associated with a body whose length is the same as `ũ` and `ṽ`. """ RigidAndDeformingMotion(ċ, α̇, ũ, ṽ) = RigidAndDeformingMotion(RigidBodyMotion(ċ, α̇), BasicDirectMotion(ũ,ṽ)) """ surface_velocity!(u::AbstractVector{Float64},v::AbstractVector{Float64}, b::Body,motion::RigidAndDeformingMotion,t::Real) Assign the components of velocity `u` and `v` (in inertial coordinate system) at surface positions described by points in body `b` (also in inertial coordinate system) at time `t`, based on supplied motion `motion` for the body. This function calls the supplied function for the deformation part in `motion.defmotion`. """ function surface_velocity!(u::AbstractVector{Float64},v::AbstractVector{Float64}, b::Body,m::RigidAndDeformingMotion,t::Real) surface_velocity!(u, v, b, m.defmotion, t) # Add the rigid part urig, vrig = similar(u), similar(v) surface_velocity!(urig,vrig,b,m.rigidmotion,t) u .+= urig v .+= vrig return u, v end =# #= """ deformation_velocity(b::Body,m::RigidAndDeformingMotion,t::Real) Return the velocity components (as a vector) of a `RigidAndDeformingMotion` at the given time `t`. """ @inline deformation_velocity(b::Body,m::RigidAndDeformingMotion,t::Real) = vcat(deformation_velocity(b,m.rigidmotion,t),deformation_velocity(b,m.defmotion,t)) """ motion_state(b::Body,m::RigidAndDeformingMotion) Return the current state vector of body `b` associated with rigid+direct motion `m`. It returns the concatenated coordinates of the rigid-body mode and the body surface (in the body coordinate system). """ @inline motion_state(b::Body,m::RigidAndDeformingMotion) = vcat(motion_state(b,m.rigidmotion),motion_state(b,m.defmotion)) """ update_body!(b::Body,x::AbstractVector,m::RigidAndDeformingMotion) Update body `b` with the motion state vector `x`. The part of the motion state associated with surface deformation is interpreted as expressed in body coordinates. The information in `m` is used for parsing only. """ function update_body!(b::Body{N,C},x::AbstractVector,m::RigidAndDeformingMotion) where {N,C} length(x) == length(motion_state(b,m)) || error("wrong length for motion state vector") lenrigx = length(motion_state(b,m.rigidmotion)) lendefx = length(x) - lenrigx b.x̃end .= x[lenrigx+1:lenrigx+lendefx÷2] b.ỹend .= x[lenrigx+lendefx÷2+1:length(x)] b.x̃, b.ỹ = _midpoints(b.x̃end,b.ỹend,C) update_body!(b,x[1:lenrigx],m.rigidmotion) return b end =# #= """ surface_velocity(b::Body,motion::AbstractDeformationMotion,t::Real) Return the components of velocities (in inertial components) at surface positions described by points in body `b` (also in inertial coordinate system) at time `t`, based on supplied motion `motion` for the body. """ surface_velocity(b::Body,m::AbstractDeformationMotion,t::Real) = surface_velocity!(similar(b.x),similar(b.y),b,m,t) =#
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
15170
### JOINTS ### #= Note that all 3-d joints with Revolute, Prismatic, Helical, Cylindrical joints all need the joint to be along its z axis, so this dictates how the parent-to-joint and child-to-joint transforms are to be created. =# abstract type AbstractJointType end # Joint structure struct Joint{ND,JT} "Parent body ID (0 for inertial)" parent_id :: Int "Child body ID" child_id :: Int "Constrained DOFs with prescribed behaviors" cdofs :: Vector{Int} "Constrained DOFs with exogenously-specified behaviors" edofs :: Vector{Int} "Unconstrained DOFS" udofs :: Vector{Int} "Kinematics for prescribed DOFs" kins :: Vector{AbstractPrescribedDOFKinematics} #"Initial values for DOFs" #xinit_dofs :: Vector{Float64} "Joint parameters" params :: Dict "Buffer for holding joint dof velocity" vbuf :: Vector{Float64} "Transform matrix from parent to joint" Xp_to_j :: MotionTransform "Transform matrix from child to joint" Xch_to_j :: MotionTransform end """ Joint(jtype::AbstractJointType,parent_id,Xp_to_j::MotionTransform,child_id,Xch_to_j::MotionTransform, dofs::Vector{AbstractDOFKinematics};[params=Dict()]) Construct a joint of type `jtype`, connecting parent body of id `parent_id` to child body of id `child_id`. The placement of the joint on the bodies is given by `Xp_to_j` and `Xch_to_j`, the transforms from the parent and child coordinate systems to the joint system, respectively. Each of the degrees of freedom for the joint is specified with `dofs`, a vector of `AbstractDOFKinematics`. Any parameters required by the joint can be passed along in the optional `params` dictionary. """ function Joint(::Type{JT},parent_id::Int,Xp_to_j::MotionTransform{ND},child_id::Int,Xch_to_j::MotionTransform{ND},dofs::Vector{T}; params = Dict()) where {JT<:AbstractJointType,ND,T<:AbstractDOFKinematics} @assert length(dofs)==number_of_dofs(JT) "input dofs must have correct length" dof_lists = Dict("constrained" => Int[], "exogenous" => Int[], "unconstrained" => Int[]) kins = AbstractDOFKinematics[] for (i,dof) in enumerate(dofs) _classify_joint!(dof_lists,kins,i,dof) end vbuf = zeros(Float64,number_of_dofs(JT)) Joint{ND,JT}(parent_id,child_id,dof_lists["constrained"],dof_lists["exogenous"],dof_lists["unconstrained"], kins,params,vbuf,Xp_to_j,Xch_to_j) end function Base.show(io::IO, joint::Joint{ND,JT}) where {ND,JT} println(io, "Joint of dimension $ND and type $JT") println(io, " Constrained dofs = $(joint.cdofs)") println(io, " Exogenous dofs = $(joint.edofs)") println(io, " Unconstrained dofs = $(joint.udofs)") end physical_dimension(j::Joint{ND}) where {ND} = ND function physical_dimension(jvec::Vector{<:Joint{ND}}) where {ND} #@assert allequal(physical_dimension.(jvec)) "Not all joints are same physical dimension" return physical_dimension(first(jvec)) end position_dimension(j::Joint{ND,JT}) where {ND,JT} = position_dimension(JT) number_of_dofs(j::Joint{ND,JT}) where {ND,JT} = number_of_dofs(JT) function ismoving(joint::Joint) @unpack edofs, udofs, kins = joint any(map(dof -> ismoving(dof),kins)) || !isempty(edofs) || !isempty(udofs) end """ motion_subspace(j::Joint) Return the `6 x ndof` (3d) or `3 x ndof` (2d) matrix providing the mapping from joint dof velocities to the full Plucker velocity vector of the joint. This matrix represents the subspace of free motion in the full space. It is orthogonal to the constrained subspace. """ motion_subspace(j::Joint{ND,JT},q::AbstractVector) where {ND,JT} = motion_subspace(JT,j.params,Val(ND),q) constrained_dimension(j::Joint) = length(j.cdofs) exogenous_dimension(j::Joint) = length(j.edofs) unconstrained_dimension(j::Joint) = length(j.udofs) position_and_vel_dimension(j::Joint) = position_dimension(j) + exogenous_dimension(j) + unconstrained_dimension(j) function check_q_dimension(q,C::Type{T}) where T<:AbstractJointType @assert length(q) == position_dimension(C) "Incorrect length of q" end """ joint_transform(q::AbstractVector,joint::Joint) Use the joint dof entries in `q` to create a joint transform operator. The number of entries in `q` must be apprpriate for the type of joint `joint`. """ function joint_transform(q::AbstractVector,joint::Joint{ND,JT}) where {ND,JT<:AbstractJointType} @unpack params = joint check_q_dimension(q,JT) joint_transform(q,JT,params,Val(ND)) end """ parent_to_child_transform(q::AbstractVector,joint::Joint) Use the joint dof entries in `q` to create a transform operator from the parent of joint `joint` to the child of joint `joint`. The number of entries in `q` must be apprpriate for the type of joint `joint`. """ function parent_to_child_transform(q::AbstractVector,joint::Joint) @unpack Xp_to_j, Xch_to_j = joint Xj = joint_transform(q,joint) Xp_to_ch = inv(Xch_to_j)*Xj*Xp_to_j end function _classify_joint!(dof_lists,kins,index,kin::AbstractDOFKinematics) push!(dof_lists["constrained"],index) push!(kins,kin) nothing end _classify_joint!(dof_lists,kins,index,::ExogenousDOF) = (push!(dof_lists["exogenous"],index); nothing) _classify_joint!(dof_lists,kins,index,::UnconstrainedDOF) = (push!(dof_lists["unconstrained"],index); nothing) ### Joint evolution equations ### """ zero_joint(joint::Joint[;dimfcn=position_and_vel_dimension]) Create a vector of zeros for different aspects of the joint state, based on the argument `dimfcn`. By default, it uses `position_and_vel_dimension` and creates a zero vector sized according to the the position of the joint and the parts of the joint velocity that must be advanced (from acceleration). Alternatively, one can use `position_dimension`, `constrained_dimension`, `unconstrained_dimension`, or `exogenous_dimension`. """ function zero_joint(joint::Joint{ND,JT};dimfcn=position_and_vel_dimension) where {ND,JT} return zeros(Float64,dimfcn(joint)) end """ init_joint(joint::Joint[;tinit=0.0]) Create an initial state vector for a joint. It initializes the joint's constrained degrees of freedom with their kinematics, evaluated at time `tinit` (equal to zero, by default). Other degrees of freedom (exogenous, unconstrained) are initialized to zero, so they can be set manually. """ function init_joint(joint::Joint{ND,JT};tinit = 0.0) where {ND,JT} @unpack kins, cdofs = joint x = zero_joint(joint) q = view(x,1:position_dimension(joint)) for (i,jdof) in enumerate(cdofs) kd = kins[i](tinit) q[jdof] = dof_position(kd) end return x end function joint_rhs!(dxdt::AbstractVector,x::AbstractVector,t::Real,a_edof::AbstractVector,a_udof::AbstractVector,joint::Joint{ND,JT}) where {ND,JT} @unpack kins, cdofs, edofs, udofs, vbuf = joint # Evaluate the velocity of the dofs and place the result in joint.vbuf _joint_velocity!(x,t,joint) # x holds both q and the parts of qdot that must be advanced q = view(x,1:position_dimension(joint)) qdot = view(dxdt,1:position_dimension(joint)) aeu = view(dxdt,position_dimension(joint)+1:position_and_vel_dimension(joint)) # parse the exogenous accelerations into their entries for (i,jdof) in enumerate(edofs) aeu[i] = a_edof[i] end # parse the unconstrained accelerations into their entries for (i,jdof) in enumerate(udofs) aeu[exogenous_dimension(joint)+i] = a_udof[i] end joint_dqdt!(qdot,q,vbuf,JT) end """ joint_velocity(x::AbstractVector,t,joint::Joint) -> PluckerMotion Given a joint `joint`'s full state vector `x`, compute the joint Plucker velocity at time `t`. """ function joint_velocity(x::AbstractVector,t::Real,joint::Joint) @unpack vbuf = joint _joint_velocity!(x,t,joint) q = view(x,1:position_dimension(joint)) return PluckerMotion(motion_subspace(joint,q)*vbuf) end function _joint_velocity!(x::AbstractVector,t::Real,joint::Joint) @unpack kins, cdofs, edofs, udofs, vbuf = joint veu = view(x,position_dimension(joint)+1:position_and_vel_dimension(joint)) vbuf .= 0.0 # evaluate the prescribed kinematics at the current time for (i,jdof) in enumerate(cdofs) kd = kins[i](t) vbuf[jdof] = dof_velocity(kd) end # parse the exogenous velocities into their entries for (i,jdof) in enumerate(edofs) vbuf[jdof] = veu[i] end # parse the unconstrained velocities into their entries for (i,jdof) in enumerate(udofs) vbuf[jdof] = veu[exogenous_dimension(joint)+i] end end function _joint_dqdt_standard!(dqdt,q,v) dqdt .= v end function _joint_dqdt_quaternion!(dqdt,q,w) dqdt[1] = -q[2]*w[1] - q[3]*w[2] - q[4]*w[3] dqdt[2] = q[1]*w[1] - q[4]*w[2] + q[3]*w[3] dqdt[3] = q[4]*w[1] + q[1]*w[2] - q[2]*w[3] dqdt[4] = -q[3]*w[1] + q[2]*w[2] + q[1]*w[3] dqdt .*= 0.5 return dqdt end #### Joint types #### ## Default joint velocity calculation function joint_dqdt!(dqdt,q,v::Vector,::Type{T}) where T<:AbstractJointType _joint_dqdt_standard!(dqdt,q,v) nothing end function motion_subspace(JT::Type{<:AbstractJointType},p::Dict,::Val{2},q) S3 = motion_subspace(JT,p,Val(3),q) m, n = size(S3) SMatrix{3,n}(S3[3:5,:]) end ## Revolute joint ## """ RevoluteJoint <: AbstractJointType A 2d or 3d joint with one rotational (about z axis) degree of freedom. """ abstract type RevoluteJoint <: AbstractJointType end number_of_dofs(::Type{RevoluteJoint}) = 1 position_dimension(::Type{RevoluteJoint}) = 1 function joint_transform(q::AbstractVector,::Type{RevoluteJoint},p::Dict,::Val{ND}) where {ND} R = rotation_about_z(-q[1]) x = SVector{3}([0.0,0.0,0.0]) return MotionTransform{ND}(x,R) end motion_subspace(::Type{RevoluteJoint},p::Dict,::Val{3},q) = SMatrix{6,1,Float64}([0 0 1 0 0 0]') ## Prismatic joint ## """ PrismaticJoint <: AbstractJointType A 3d joint with one translational (along z axis) degree of freedom. """ abstract type PrismaticJoint <: AbstractJointType end number_of_dofs(::Type{PrismaticJoint}) = 1 position_dimension(::Type{PrismaticJoint}) = 1 function joint_transform(q::AbstractVector,::Type{PrismaticJoint},p::Dict,::Val{3}) R = rotation_identity() x = SVector{3}([0.0,0.0,q[1]]) return MotionTransform{3}(x,R) end motion_subspace(::Type{PrismaticJoint},p::Dict,::Val{3},q) = SMatrix{6,1,Float64}([0 0 0 0 0 1]') ## Helical joint ## """ HelicalJoint <: AbstractJointType A 3d joint with one rotational (angle about z axis) degree of freedom, and coupled translational motion along the z axis based on pitch. """ abstract type HelicalJoint <: AbstractJointType end number_of_dofs(::Type{HelicalJoint}) = 1 position_dimension(::Type{HelicalJoint}) = 1 function joint_transform(q::AbstractVector,C::Type{HelicalJoint},p::Dict,::Val{3}) R = rotation_about_z(-q[1]) x = SVector{3}([0.0,0.0,p["pitch"]*q[1]]) return MotionTransform{3}(x,R) end motion_subspace(::Type{HelicalJoint},p::Dict,::Val{3},q) = SMatrix{6,1,Float64}([0 0 1 0 0 p["pitch"]]') ## Cylindrical joint ## """ CylindricalJoint <: AbstractJointType A 3d joint with one rotational (angle about z axis) and one translational (z axis) degrees of freedom. """ abstract type CylindricalJoint <: AbstractJointType end number_of_dofs(::Type{CylindricalJoint}) = 2 position_dimension(::Type{CylindricalJoint}) = 2 function joint_transform(q::AbstractVector,::Type{CylindricalJoint},p::Dict,::Val{3}) R = rotation_about_z(-q[1]) x = SVector{3}([0.0,0.0,q[2]]) return MotionTransform{3}(x,R) end motion_subspace(::Type{CylindricalJoint},p::Dict,::Val{3},q) = SMatrix{6,2,Float64}([0 0 1 0 0 0; 0 0 0 0 0 1]') ## Spherical joint ## """ SphericalJoint <: AbstractJointType A 3d joint with three rotational degrees of freedom. It uses a quaternion to define its orientation, so it has four position coordinates. """ abstract type SphericalJoint <: AbstractJointType end number_of_dofs(::Type{SphericalJoint}) = 3 position_dimension(::Type{SphericalJoint}) = 4 function joint_transform(q::AbstractVector,::Type{SphericalJoint},p::Dict,::Val{3}) R = rotation_from_quaternion(quaternion(q)) x = SVector{3}([0.0,0.0,0.0]) return MotionTransform{3}(x,R) end motion_subspace(::Type{SphericalJoint},p::Dict,::Val{3},q) = SMatrix{6,3,Float64}([1 0 0 0 0 0; 0 1 0 0 0 0; 0 0 1 0 0 0]') function joint_dqdt!(dqdt,q,v,::Type{SphericalJoint}) _joint_dqdt_quaternion!(dqdt,q,v) nothing end ## Free joint (3d) ## """ FreeJoint <: AbstractJointType A 3d joint with all six degrees of freedom. It uses a quaternion to define its orientation, so it has seven position coordinates. """ abstract type FreeJoint <: AbstractJointType end number_of_dofs(::Type{FreeJoint}) = 6 position_dimension(::Type{FreeJoint}) = 7 function joint_transform(q::AbstractVector,::Type{FreeJoint},p::Dict,::Val{3}) R = rotation_from_quaternion(quaternion(q[1:4])) x = SVector{3}(q[5:7]) return MotionTransform{3}(R'*x,R) end motion_subspace(::Type{FreeJoint},p::Dict,::Val{3},q) = SMatrix{6,6,Float64}(I) function joint_dqdt!(dqdt,q,v,::Type{FreeJoint}) qrdot, qtdot = view(dqdt,1:4), view(dqdt,5:7) qr, qt = view(q,1:4), view(q,5:7) vr, vt = view(v,1:3), view(v,4:6) _joint_dqdt_quaternion!(qrdot,qr,vr) _joint_dqdt_standard!(qtdot,qt,vt) nothing end ## Free joint (2d) ## """ FreeJoint2d <: AbstractJointType A 2d joint with three degrees of freedom (angle, x, y). """ abstract type FreeJoint2d <: AbstractJointType end number_of_dofs(::Type{FreeJoint2d}) = 3 position_dimension(::Type{FreeJoint2d}) = 3 function joint_transform(q::AbstractVector,::Type{FreeJoint2d},p::Dict,::Val{2}) R = rotation_about_z(-q[1]) x = SVector{3}(q[2],q[3],0.0) return MotionTransform{2}(x,R) end function motion_subspace(JT::Type{FreeJoint2d},p::Dict,::Val{2},q) R = rotation_transform(joint_transform(q,JT,p,Val(2))) R*SMatrix{3,3,Float64}(I) end ## Fixed joint ## abstract type FixedJoint <: AbstractJointType end """ Joint(X::MotionTransform,bid::Int) Construct a joint that simply places the body with ID `bid` rigidly in the configuration given by `X`. """ Joint(Xp_to_j::MotionTransform{ND},child_id::Int) where {ND} = Joint(FixedJoint,0,Xp_to_j,child_id,MotionTransform{ND}()) """ Joint(X::MotionTransform) For a problem with a single body, construct a joint that simply places the body rigidly in the configuration given by `X`. """ Joint(Xp_to_j::MotionTransform{ND}) where {ND} = Joint(FixedJoint,0,Xp_to_j,1,MotionTransform{ND}()) function Joint(::Type{FixedJoint},parent_id::Int,Xp_to_j::MotionTransform{2},child_id::Int,Xch_to_j::MotionTransform{2}) dofs = [ConstantVelocityDOF(0.0) for i = 1:3] Joint(FreeJoint2d,parent_id,Xp_to_j,child_id,Xch_to_j,dofs) end function Joint(::Type{FixedJoint},parent_id::Int,Xp_to_j::MotionTransform{3},child_id::Int,Xch_to_j::MotionTransform{3}) dofs = [ConstantVelocityDOF(0.0) for i = 1:6] Joint(FreeJoint,parent_id,Xp_to_j,child_id,Xch_to_j,dofs) end
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
19034
#= Kinematics Any set of kinematics added here must be accompanied by a function (kin::AbstractKinematics)(t) that returns kinematic data of type `KinematicData` holding t, c, ċ, c̈, α, α̇, α̈: the evaluation time, the reference point position, velocity, acceleration (all complex), and angle, angular velocity, and angular acceleration =# using DocStringExtensions import ForwardDiff import Base: +, *, -, >>, <<, show using SpaceTimeFields import SpaceTimeFields: Abstract1DProfile, >>, ConstantProfile, d_dt, FunctionProfile ## Individual DOF kinematics ## abstract type AbstractDOFKinematics end abstract type AbstractPrescribedDOFKinematics <: AbstractDOFKinematics end struct DOFKinematicData t :: Float64 x :: Float64 ẋ :: Float64 ẍ :: Float64 end (k::AbstractPrescribedDOFKinematics)(t) = DOFKinematicData(t,k.x(t),k.ẋ(t),k.ẍ(t)) """ dof_position(kd::DOFKinematicData) -> Float64 Returns the position of the given kinematic data of the degree of freedom """ dof_position(kd::DOFKinematicData) = kd.x """ dof_velocity(kd::DOFKinematicData) -> Float64 Returns the velocity of the given kinematic data of the degree of freedom """ dof_velocity(kd::DOFKinematicData) = kd.ẋ """ dof_acceleration(kd::DOFKinematicData) -> Float64 Returns the acceleration of the given kinematic data of the degree of freedom """ dof_acceleration(kd::DOFKinematicData) = kd.ẍ function ismoving(dof::AbstractPrescribedDOFKinematics) !((dof isa ConstantVelocityDOF && dof.ẋ0 == 0.0)||(dof isa ConstantPositionDOF)) end ### Types of dof kinematics ### """ ConstantPositionDOF(x0::Float64) <: AbstractPrescribedDOFKinematics Set kinematics with constant position `x0`. """ struct ConstantPositionDOF <: AbstractPrescribedDOFKinematics x0 :: Float64 x :: Abstract1DProfile ẋ :: Abstract1DProfile ẍ :: Abstract1DProfile end function ConstantPositionDOF(x0) x = ConstantProfile(x0) ẋ = d_dt(x) ẍ = d_dt(ẋ) ConstantPositionDOF(x0,x,ẋ,ẍ) end function show(io::IO, p::ConstantPositionDOF) print(io, "Constant position kinematics (position = $(p.x0))") end """ ConstantVelocityDOF(ẋ0::Float64) <: AbstractPrescribedDOFKinematics Set kinematics with constant velocity `ẋ0`. """ struct ConstantVelocityDOF <: AbstractPrescribedDOFKinematics ẋ0 :: Float64 x :: Abstract1DProfile ẋ :: Abstract1DProfile ẍ :: Abstract1DProfile end function ConstantVelocityDOF(ẋ0) f(t) = ẋ0*t x = FunctionProfile(f) ẋ = d_dt(x) ẍ = d_dt(ẋ) ConstantVelocityDOF(ẋ0,x,ẋ,ẍ) end function show(io::IO, p::ConstantVelocityDOF) print(io, "Constant velocity kinematics (velocity = $(p.ẋ0))") end """ SmoothRampDOF(ẋ0,Δx,t0[;ramp=EldredgeRamp(11.0)]) <: AbstractPrescribedDOFKinematics Kinematics describing a smooth ramp change in position `Δx` starting at time `t0` with nominal rate `ẋ0`. Note that the sign of `ẋ0` should be the same as the sign of `Δx`, and will be automatically changed if they differ. The optional ramp argument is assumed to be given by the smooth ramp `EldredgeRamp` with a smoothness factor of 11 (larger values lead to sharper transitions on/off the ramp), but this can be replaced by another Eldredge ramp with a different value or a `ColoniusRamp`. """ struct SmoothRampDOF <: AbstractPrescribedDOFKinematics ẋ0 :: Float64 Δx :: Float64 t0 :: Float64 ramp :: Abstract1DProfile x :: Abstract1DProfile ẋ :: Abstract1DProfile ẍ :: Abstract1DProfile end function SmoothRampDOF(ẋ0,Δx,t0; ramp = EldredgeRamp(11.0)) ẋ0_sign = sign(Δx)*abs(ẋ0) Δt = abs(Δx/ẋ0_sign) x = ẋ0_sign*((ramp >> t0) - (ramp >> (t0 + Δt))) ẋ = d_dt(x) ẍ = d_dt(ẋ) SmoothRampDOF(ẋ0_sign,Δx,t0,ramp,x,ẋ,ẍ) end function show(io::IO, p::SmoothRampDOF) print(io, "Smooth position ramp kinematics (nominal rate = $(p.ẋ0), amplitude = $(p.Δx), nominal time = $(p.t0)), smoothing=$(p.ramp)") end """ SmoothVelocityRampDOF(ẍ0,ẋ1,ẋ2,t0[;ramp=EldredgeRamp(11.0)]) <: AbstractPrescribedDOFKinematics Kinematics describing a smooth ramp change in velocity from `ẋ1` to `ẋ2` starting at time `t0` with nominal acceleration `ẍ0`. Note that the sign of `ẍ0` should be the same as the sign of `ẋ2-ẋ1`, and will be automatically changed if they differ. The optional ramp argument is assumed to be given by the smooth ramp `EldredgeRamp` with a smoothness factor of 11 (larger values lead to sharper transitions on/off the ramp), but this can be replaced by another Eldredge ramp with a different value. """ struct SmoothVelocityRampDOF <: AbstractPrescribedDOFKinematics ẍ0 :: Float64 ẋ1 :: Float64 ẋ2 :: Float64 t0 :: Float64 ramp :: Abstract1DProfile x :: Abstract1DProfile ẋ :: Abstract1DProfile ẍ :: Abstract1DProfile end function SmoothVelocityRampDOF(ẍ0,ẋ1,ẋ2,t0; ramp::EldredgeRamp = EldredgeRamp(11.0)) Δẋ = ẋ2 - ẋ1 ẍ0_sign = sign(Δẋ)*abs(ẍ0) Δt = Δẋ/ẍ0_sign ri = _ramp_int(ramp) x = FunctionProfile(t -> ẋ1*t) + ẍ0_sign*((ri >> t0) - (ri >> (t0 + Δt))) ẋ = d_dt(x) ẍ = d_dt(ẋ) SmoothVelocityRampDOF(ẍ0_sign,ẋ1,ẋ2,t0,ramp,x,ẋ,ẍ) end _ramp_int(ramp::EldredgeRamp) = EldredgeRampIntegral(ramp.aₛ) function show(io::IO, p::SmoothVelocityRampDOF) print(io, "Smooth velocity ramp kinematics (nominal rate = $(p.ẍ0), initial velocity = $(p.ẋ1), final velocity = $(p.ẋ2), nominal time = $(p.t0)), smoothing = $(p.ramp)") end """ OscillatoryDOF(amp,angfreq,phase,ẋ0) <: AbstractPrescribedDOFKinematics Set sinusoidal kinematics with amplitude `amp`, angular frequency `angfreq`, phase `phase`, and mean velocity `ẋ0`. The function it provides is `x(t) = ẋ0*t + amp*sin(angfreq*t+phase)`. """ struct OscillatoryDOF <: AbstractPrescribedDOFKinematics "Amplitude" A :: Float64 "Angular frequency" Ω :: Float64 "Phase" ϕ :: Float64 "Mean velocity" ẋ0 :: Float64 x :: Abstract1DProfile ẋ :: Abstract1DProfile ẍ :: Abstract1DProfile end function OscillatoryDOF(A,Ω,ϕ,ẋ0) f(t) = ẋ0*t x = FunctionProfile(f) + A*(Sinusoid(Ω) >> (ϕ/Ω)) ẋ = d_dt(x) ẍ = d_dt(ẋ) OscillatoryDOF(A,Ω,ϕ,ẋ0,x,ẋ,ẍ) end function show(io::IO, p::OscillatoryDOF) print(io, "Oscillatory kinematics (amplitude = $(p.A), ang freq = $(p.Ω), phase = $(p.ϕ), mean velocity = $(p.ẋ0))") end """ CustomDOF(f::Function) <: AbstractPrescribedDOFKinematics Set custom kinematics for a degree of freedom with a function `f` that specifies its value at any given time. """ struct CustomDOF <: AbstractPrescribedDOFKinematics f :: Function x :: Abstract1DProfile ẋ :: Abstract1DProfile ẍ :: Abstract1DProfile end function CustomDOF(f::Function) x = FunctionProfile(f) ẋ = d_dt(x) ẍ = d_dt(ẋ) CustomDOF(f,x,ẋ,ẍ) end function show(io::IO, p::CustomDOF) print(io, "Custom kinematics") end """ ExogenousDOF() <: AbstractDOFKinematics Sets a DOF as constrained, but with its behavior set by an exogenous process at every instant. For such a DOF, one must provide a vector `[x,ẋ,ẍ]`. """ struct ExogenousDOF <: AbstractDOFKinematics end function show(io::IO, p::ExogenousDOF) print(io, "Exogeneously-specified DOF") end """ UnconstrainedDOF([f::Function]) <: AbstractDOFKinematics Sets a DOF as unconstrained, so that its behavior is either completely free or determined by a given force response (e.g., spring and/or damper). This force response is set by the optional input function `f`. The signature of `f` must be `f(x,xdot,t)`, where `x` and `xdot` are the position of the dof and its derivative, respectively, and `t` is the current time. It must return a single scalar, serving as a force or torque for that DOF. """ struct UnconstrainedDOF <: AbstractDOFKinematics f :: Function end UnconstrainedDOF() = UnconstrainedDOF((x,xdot,t) -> zero(x)) function show(io::IO, p::UnconstrainedDOF) print(io, "Unconstrained DOF") end ##### #= """ An abstract type for types that takes in time and returns `KinematicData(t,c, ċ, c̈, α, α̇, α̈)`. It is important to note that `c` and `α` only provide the values relative to their respective initial values at `t=0`. """ abstract type AbstractKinematics end struct KinematicData t :: Float64 c :: ComplexF64 ċ :: ComplexF64 c̈ :: ComplexF64 α :: Float64 α̇ :: Float64 α̈ :: Float64 end # APIs """ complex_translational_position(k::KinematicData;[inertial=true]) -> ComplexF64 Return the complex translational position (relative to the initial position) of kinematic data `k`, expressed in inertial coordinates (if `inertial=true`, the default) or in comoving coordinates if `inertial=false`. """ complex_translational_position(k::KinematicData;inertial::Bool=true) = _complex_translation_position(k,Val(inertial)) _complex_translation_position(k,::Val{true}) = k.c _complex_translation_position(k,::Val{false}) = k.c*exp(-im*k.α) """ complex_translational_velocity(k::KinematicData;[inertial=true]) -> ComplexF64 Return the complex translational velocity of kinematic data `k`, relative to inertial reference frame, expressed in inertial coordinates (if `inertial=true`, the default) or in comoving coordinates if `inertial=false`. """ complex_translational_velocity(k::KinematicData;inertial::Bool=true) = _complex_translation_velocity(k,Val(inertial)) _complex_translation_velocity(k,::Val{true}) = k.ċ _complex_translation_velocity(k,::Val{false}) = k.ċ*exp(-im*k.α) """ complex_translational_acceleration(k::KinematicData;[inertial=true]) -> ComplexF64 Return the complex translational acceleration of kinematic data `k`, relative to inertial reference frame, expressed in inertial coordinates (if `inertial=true`, the default) or in comoving coordinates if `inertial=false`. """ complex_translational_acceleration(k::KinematicData;inertial::Bool=true) = _complex_translation_acceleration(k,Val(inertial)) _complex_translation_acceleration(k,::Val{true}) = k.c̈ _complex_translation_acceleration(k,::Val{false}) = k.c̈*exp(-im*k.α) """ angular_position(k::KinematicData) -> Float64 Return the angular orientation of kinematic data `k`, relative to inital value, in the inertial reference frame. """ angular_position(k::KinematicData) = k.α """ angular_velocity(k::KinematicData) -> Float64 Return the angular velocity of kinematic data `k`, relative to inertial reference frame. """ angular_velocity(k::KinematicData) = k.α̇ """ angular_acceleration(k::KinematicData) -> Float64 Return the angular acceleration of kinematic data `k`, relative to inertial reference frame. """ angular_acceleration(k::KinematicData) = k.α̈ """ translational_position(k::KinematicData;[inertial=true]) -> Tuple Return the translational position of kinematic data `k` (relative to the initial position), expressed as a Tuple in inertial coordinates (if `inertial=true`, the default) or in comoving coordinates if `inertial=false`. """ translational_position(k::KinematicData;kwargs...) = reim(complex_translational_position(k;kwargs...)) """ translational_velocity(k::KinematicData;[inertial=true]) -> Tuple Return the translational velocity of kinematic data `k`, relative to inertial reference frame, expressed as a Tuple in inertial coordinates (if `inertial=true`, the default) or in comoving coordinates if `inertial=false`. """ translational_velocity(k::KinematicData;kwargs...) = reim(complex_translational_velocity(k;kwargs...)) """ translational_acceleration(k::KinematicData;[inertial=true]) -> Tuple Return the translational acceleration of kinematic data `k`, relative to inertial reference frame, expressed as a Tuple in inertial coordinates (if `inertial=true`, the default) or in comoving coordinates if `inertial=false`. """ translational_acceleration(k::KinematicData;kwargs...) = reim(complex_translational_acceleration(k;kwargs...)) #### """ Kinematics(apk::AbstractDOFKinematics,xpk::AbstractDOFKinematics,ykp::AbstractDOFKinematics[;pivot=(0.0,0.0)]) Set the full 2-d kinematics of a rigid body, specifying the kinematics of the the angle ``\\alpha`` (with `apk`) and ``x`` and ``y`` coordinates of the pivot point with `xpk` and `ypk`, respectively. The pivot point is specified (in body-fixed coordinates) with the optional argument `pivot`. """ struct Kinematics{AK<:AbstractDOFKinematics,XK<:AbstractDOFKinematics,YK<:AbstractDOFKinematics} <: AbstractKinematics x̃p :: Float64 ỹp :: Float64 apk :: AK xpk :: XK ypk :: YK Kinematics(x̃p::Real,ỹp::Real,apk,xpk,ypk) = new{typeof(apk),typeof(xpk),typeof(ypk)}(convert(Float64,x̃p),convert(Float64,ỹp),apk,xpk,ypk) end Kinematics(apk::AbstractDOFKinematics,xpk::AbstractDOFKinematics,ypk::AbstractDOFKinematics;pivot=(0.0,0.0)) = Kinematics(pivot...,apk,xpk,ypk) function (kin::Kinematics)(t) z̃p = kin.x̃p + im*kin.ỹp apkd = kin.apk(t) xpkd = kin.xpk(t) ypkd = kin.ypk(t) zp = dof_position(xpkd) + im*dof_position(ypkd) żp = dof_velocity(xpkd) + im*dof_velocity(ypkd) z̈p = dof_acceleration(xpkd) + im*dof_acceleration(ypkd) α = dof_position(apkd) α̇ = dof_velocity(apkd) α̈ = dof_acceleration(apkd) dzp = z̃p*exp(im*α) c = zp - dzp ċ = żp - im*α̇*dzp c̈ = z̈p - (im*α̈ - α̇^2)*dzp KinematicData(t,c,ċ,c̈,α,α̇,α̈) end """ Constant(Up,Ω;[pivot = (0.0,0.0)]) Set constant translational Up and angular velocity Ω with respect to a specified point P. This point is established by its initial position `pivot` (note that the initial angle is assumed to be zero). By default, this initial position is (0,0). `Up` and `pivot` can be specified by either Tuple or by complex value. """ Constant(żp::Complex, α̇;pivot=complex(0.0)) = Kinematics(ConstantVelocityDOF(α̇), ConstantVelocityDOF(real(żp)), ConstantVelocityDOF(imag(żp)); pivot=reim(pivot)) Constant(żp::Tuple,α̇;pivot=(0.0,0.0)) = Constant(complex(żp...),α̇;pivot=complex(pivot...)) """ Pitchup(U₀,a,K,α₀,t₀,Δα,ramp=EldredgeRamp(11.0)) <: AbstractKinematics Kinematics describing a pitch-ramp motion (horizontal translation with rotation) starting at time ``t_0`` about an axis at `a` (expressed relative to the centroid, in the ``\\tilde{x}`` direction in the body-fixed coordinate system), with translational velocity `U₀` in the inertial ``x`` direction, initial angle ``\\alpha_0``, dimensionless angular velocity ``K = \\dot{\\alpha}_0c/2U_0``, and angular change ``\\Delta\\alpha``. The optional ramp argument is assumed to be given by the smooth ramp `EldredgeRamp` with a smoothness factor of 11 (larger values lead to sharper transitions on/off the ramp), but this can be replaced by another Eldredge ramp with a different value or a `ColoniusRamp`. """ Pitchup(U₀,a,K,α₀,t₀,Δα;ramp=EldredgeRamp(11.0)) = Kinematics(SmoothRampDOF(α₀,2K,Δα,t₀;ramp=ramp), ConstantVelocityDOF(U₀), ConstantPositionDOF(0.0); pivot=(a,0.0)) """ Oscillation(Ux,Uy,α̇₀,ax,ay,Ω,Ax,Ay,ϕx,ϕy,α₀,Δα,ϕα) <: AbstractKinematics Set 2-d oscillatory kinematics. This general constructor sets up motion of a rotational axis, located at `ax`, `ay` (expressed relative to the body centroid, in a body-fixed coordinate system). The rotational axis motion is described by `` x(t) = U_x t + A_x\\sin(\\Omega t - \\phi_x), \\quad y(t) = U_y t + A_y\\sin(\\Omega t - \\phi_y), \\quad \\alpha(t) = \\alpha_0 + \\dot{\\alpha}_0 t + \\Delta\\alpha \\sin(\\Omega t - \\phi_{\\alpha}) `` """ Oscillation(Ux,Uy,α̇₀,ax,ay,Ω,Ax,Ay,ϕx,ϕy,α₀,Δα,ϕα) = Kinematics(OscillatoryDOF(Δα,Ω,ϕα,α₀,α̇₀), OscillatoryDOF(Ax,Ω,ϕx,0.0,Ux), OscillatoryDOF(Ay,Ω,ϕy,0.0,Uy); pivot=(ax,ay)) """ PitchHeave(U₀,a,Ω,α₀,Δα,ϕp,A,ϕh) Create oscillatory pitching and heaving kinematics of a pitch axis at location ``a`` (expressed relative to the centroid in the ``\\tilde{x}`` direction of the body-fixed coordinate system), of the form (in inertial coordinates) `` x(t) = U_0 t, \\quad y(t) = A\\sin(\\Omega t - \\phi_h), \\quad \\alpha(t) = \\alpha_0 + \\Delta\\alpha \\sin(\\Omega t - \\phi_p) `` """ PitchHeave(U₀, a, Ω, α₀, Δα, ϕp, A, ϕh) = Oscillation(U₀, 0.0, 0.0, a, 0.0, Ω, 0.0, A, 0.0, ϕh, α₀, Δα, ϕp) """ OscillationXY(Ux,Uy,Ω,Ax,ϕx,Ay,ϕy) Set oscillatory kinematics in the ``x`` and ``y`` directions, of the form `` x(t) = U_x t + A_x \\sin(\\Omega t - \\phi_x), \\quad y(t) = U_y t + A_y \\sin(\\Omega t - \\phi_y) `` """ OscillationXY(Ux,Uy,Ω,Ax,ϕx,Ay,ϕy) = Oscillation(Ux, Uy, 0, 0, 0, Ω, Ax, Ay, ϕx, ϕy, 0, 0, 0) """ OscillationX(Ux,Ω,Ax,ϕx) Set oscillatory kinematics in the ``x`` direction, of the form `` x(t) = U_x t + A_x \\sin(\\Omega t - \\phi_x), `` """ OscillationX(Ux,Ω,Ax,ϕx) = Oscillation(Ux, 0, 0, 0, 0, Ω, Ax, 0, ϕx, 0, 0, 0, 0) """ OscillationY(Uy,Ω,Ay,ϕy) Set oscillatory kinematics in the ``y`` direction, of the form `` y(t) = U_y t + A_y \\sin(\\Omega t - \\phi_y) `` """ OscillationY(Uy,Ω,Ay,ϕy) = Oscillation(0, Uy, 0, 0, 0, Ω, 0, Ay, 0, ϕy, 0, 0, 0) """ RotationalOscillation(ax,ay,Ω,α₀,α̇₀,Δα,ϕα) Set oscillatory rotational kinematics about an axis located at `ax`, `ay` (expressed relative to the body centroid, in a body-fixed coordinate system), of the form `` \\alpha(t) = \\alpha_0 + \\dot{\\alpha}_0 t + \\Delta\\alpha \\sin(\\Omega t - \\phi_{\\alpha}) `` """ RotationalOscillation(ax,ay,Ω,α₀,α̇₀,Δα,ϕα) = Oscillation(0, 0, α̇₀, ax, ay, Ω, 0, 0, 0, 0, α₀, Δα, ϕα) """ RotationalOscillation(Ω,Δα,ϕα) Set oscillatory rotational kinematics about the centroid of the form `` \\alpha(t) = \\Delta\\alpha \\sin(\\Omega t - \\phi_{\\alpha}) `` """ RotationalOscillation(Ω,Δα,ϕα) = RotationalOscillation(0,0,Ω,0,0,Δα,ϕα) =# #### #### abstract type Switch end abstract type SwitchOn <: Switch end abstract type SwitchOff <: Switch end """ SwitchedKinematics <: AbstractDOFKinematics Modulates a given set of kinematics between simple on/off states. The velocity specified by the given kinematics is toggled on/off. # Fields $(FIELDS) """ struct SwitchedKinematics{S <: Switch} <: AbstractDOFKinematics "time at which the kinematics should be turned on" t_on :: Float64 "time at which the kinematics should be turned off" t_off :: Float64 "kinematics to be followed in the on state" kin :: AbstractDOFKinematics off :: AbstractDOFKinematics SwitchedKinematics(t_on,t_off,kin) = t_on > t_off ? new{SwitchOn}(t_on,t_off,kin,ConstantVelocityDOF(0.0)) : new{SwitchOff}(t_on,t_off,kin,ConstantVelocityDOF(0.0)) end # note that these do not introduce impulsive changes into the derivatives (p::SwitchedKinematics{SwitchOn})(t) = t <= p.t_on ? p.off(t) : p.kin(t-p.t_on) (p::SwitchedKinematics{SwitchOff})(t) = t <= p.t_off ? p.kin(t-p.t_on) : p.off(t)
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
8370
export BodyList, RigidTransformList, MotionTransformList, PluckerMotionList, getrange abstract type SetOfBodies end const LISTS = [:BodyList, :Body], [:RigidTransformList, :RigidTransform], [:MotionTransformList, :MotionTransform], [:PluckerMotionList, :PluckerMotion] """ BodyList([b1,b2,...]) Create a list of bodies """ BodyList """ RigidTransformList([t1,t2,...]) Create a list of rigid transforms """ RigidTransformList """ MotionTransformList([t1,t2,...]) Create a list of motion transforms """ MotionTransformList for (listtype,listelement) in LISTS @eval struct $listtype <: SetOfBodies list :: Vector{$listelement} end @eval Base.eltype(f::$listtype) = Base.eltype(f.list) @eval $listtype() = $listtype($listelement[]) @eval @propagate_inbounds getindex(A::$listtype, i::Int) = A.list[i] @eval @propagate_inbounds setindex!(A::$listtype, v::$listelement, i::Int) = A.list[i] = v @eval @propagate_inbounds getindex(A::$listtype, I...) = A.list[I...] @eval @propagate_inbounds setindex!(A::$listtype, v, I...) = A.list[I...] = v @eval iterate(A::$listtype) = iterate(A.list) @eval iterate(A::$listtype,I) = iterate(A.list,I) @eval size(A::$listtype) = size(A.list) @eval length(A::$listtype) = length(A.list) @eval findall(f::Function,A::$listtype) = findall(f,A.list) @eval push!(bl::$listtype,b::$listelement) = push!(bl.list,b) end numpts(bl::BodyList) = mapreduce(numpts,+,bl;init=0) zero_body(b::Union{Body,BodyList}) = zeros(Float64,numpts(b)) """ collect(bl::bodylist[,endpoints=false][,ref=false]) -> Vector{Float64}, Vector{Float64} Collect the inertial-space coordinates of all of the Lagrange points comprising the bodies in body list `bl` and return each assembled set of coordinates as a vector. By default, `endpoints=false` and `ref=false`, which means this collects the midpoints of segments in the inertial coordinates. If `endpoints=true` it collects segment endpoints instead. If `ref=true` it collects the coordinates in the body coordinate system. """ collect(bl::BodyList;endpoints=false,ref=false) = _collect(bl,Val(endpoints),Val(ref)) collect(body::Body;kwargs...) = collect(BodyList([body]);kwargs...) function _collect(bl,::Val{false},::Val{false}) xtmp = Float64[] ytmp = Float64[] for b in bl append!(xtmp,b.x) append!(ytmp,b.y) end return xtmp,ytmp end function _collect(bl::BodyList,::Val{true},::Val{false}) xtmp = Float64[] ytmp = Float64[] for b in bl append!(xtmp,b.xend) append!(ytmp,b.yend) end return xtmp,ytmp end function _collect(bl,::Val{false},::Val{true}) xtmp = Float64[] ytmp = Float64[] for b in bl append!(xtmp,b.x̃) append!(ytmp,b.ỹ) end return xtmp,ytmp end function _collect(bl::BodyList,::Val{true},::Val{true}) xtmp = Float64[] ytmp = Float64[] for b in bl append!(xtmp,b.x̃end) append!(ytmp,b.ỹend) end return xtmp,ytmp end """ getrange(bl::BodyList,bid::Int) -> Range Return the subrange of indices in the global set of surface point data corresponding to body `bid` in a BodyList `bl`. """ function getrange(bl::BodyList,i::Int) i <= length(bl) || error("Unavailable body") first = 1 j = 1 while j < i first += numpts(bl[j]) j += 1 end last = first+numpts(bl[i])-1 return first:last end """ global_to_local_index(i::Int,bl::BodyList) -> (Int, Int) Return the ID `bid` of the body in body list `bl` on which global index `i` sits, as well as the local index of `iloc` on that body and return as `(bid,iloc)` """ function global_to_local_index(i::Int,bl::BodyList) bid = 1 ir = getrange(bl,bid) while !(in(i,ir)) && bid <= length(bl) bid += 1 ir = getrange(bl,bid) end return bid, i-first(ir)+1 end #= """ getrange(bl::BodyList,ml::MotionList,i::Int) -> Range Return the subrange of indices in the global vector of motion state data corresponding to body `i` in a BodyList `bl` with corresponding motion list `ml`. """ function getrange(bl::BodyList,ml::MotionList,i::Int) i <= length(bl) || error("Unavailable body") first = 1 j = 1 while j < i first += length(motion_state(bl[j],ml[j])) j += 1 end last = first+length(motion_state(bl[i],ml[i]))-1 return first:last end =# """ view(f::AbstractVector,bl::BodyList,bid::Int) -> SubArray Provide a view of the range of values in vector `f` corresponding to the Lagrange points of the body with index `bid` in a BodyList `bl`. """ function Base.view(f::AbstractVector,bl::BodyList,bid::Int) length(f) == numpts(bl) || error("Inconsistent size of data for viewing") return view(f,getrange(bl,bid)) end """ sum(f::AbstractVector,bl::BodyList,i::Int) -> Real Compute a sum of the elements of vector `f` corresponding to body `i` in body list `bl`. """ Base.sum(f::AbstractVector,bl::BodyList,i::Int) = sum(view(f,bl,i)) """ (tl::MotionTransformList)(bl::BodyList) -> BodyList Carry out transformations of each body in `bl` with the corresponding transformation in `tl`, creating a new body list. """ @inline function (tl::MotionTransformList)(bl::BodyList) bl_transform = deepcopy(bl) update_body!(bl_transform,tl) end """ update_body!(bl::BodyList,tl::MotionTransformList) -> BodyList Carry out in-place transformations of each body in `bl` with the corresponding transformation in `tl`. """ @inline function update_body!(bl::BodyList,tl::MotionTransformList) length(tl) == length(bl) || error("Inconsistent lengths of lists") map((T,b) -> update_body!(b,T),tl,bl) end """ transform_body!(bl::BodyList,tl::MotionTransformList) -> BodyList Carry out in-place transformations of body coordinate systems for each body in `bl` with the corresponding transformation in `tl`. """ @inline function transform_body!(bl::BodyList,tl::MotionTransformList) length(tl) == length(bl) || error("Inconsistent lengths of lists") map((T,b) -> transform_body!(b,T),tl,bl) end """ motion_transform_from_A_to_B(tl::MotionTransformList,bodyidA::Int,bodyidB::Int) -> MotionTransform Returns a motion transform mapping from the coordinate system of body `bodyidA` to body `bodyidB`. Either of these bodies might be 0. """ motion_transform_from_A_to_B(Xl::MotionTransformList,bodyA::Int,bodyB::Int) = _motion_transform_from_A_to_B(Xl,_dimensionality(Xl),Val(bodyA),Val(bodyB)) """ force_transform_from_A_to_B(tl::MotionTransformList,bodyidA::Int,bodyidB::Int) -> ForceTransform Returns a force transform mapping from the coordinate system of body `bodyidA` to body `bodyidB`. Either of these bodies might be 0. """ force_transform_from_A_to_B(Xl::MotionTransformList,bodyA::Int,bodyB::Int) = transpose(motion_transform_from_A_to_B(Xl,bodyB,bodyA)) _motion_transform_from_A_to_B(Xl,ND,::Val{bodyA},::Val{bodyB}) where {bodyA,bodyB} = Xl[bodyB]*inv(Xl[bodyA]) _motion_transform_from_A_to_B(Xl,ND,::Val{0},::Val{bodyB}) where {bodyB} = Xl[bodyB] _motion_transform_from_A_to_B(Xl,ND,::Val{bodyA},::Val{0}) where {bodyA} = inv(Xl[bodyA]) _motion_transform_from_A_to_B(Xl,ND,::Val{bodyA},::Val{bodyA}) where {bodyA} = MotionTransform{ND}() _motion_transform_from_A_to_B(Xl,ND,::Val{0},::Val{0}) = MotionTransform{ND}() _dimensionality(tl::MotionTransformList) = _dimensionality(first(tl)) _dimensionality(t::MotionTransform{ND}) where {ND} = ND """ vec(tl::RigidTransformList) -> Vector{Float64} Returns a concatenation of length-3 vectors of the form [x,y,α] corresponding to the translation and rotation specified by the given by the list of transforms `tl`. """ vec(tl::RigidTransformList) = mapreduce(vec,vcat,tl) """ RigidTransformList(x::Vector) Parses vector `x`, containing rigid-body configuration data ordered as x, y, α for each body, into a `RigidTransformList`. """ function RigidTransformList(x::Vector{T}) where T <: Real nb, md = _length_and_mod(x) md == 0 || error("Invalid length of vector") first = 0 tl = RigidTransformList() for i in 1:nb push!(tl,RigidTransform(view(x,first+1:first+CHUNK))) first += CHUNK end return tl end _length_and_mod(x::Vector{T}) where T <: Real = (n = length(x); return n ÷ CHUNK, n % CHUNK)
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
2330
using RecipesBase using ColorTypes using LaTeXStrings import PlotUtils: cgrad #using Compat #using Compat: range const mygreen = RGBA{Float64}(151/255,180/255,118/255,1) const mygreen2 = RGBA{Float64}(113/255,161/255,103/255,1) const myblue = RGBA{Float64}(74/255,144/255,226/255,1) @recipe function plot(b::Body{N,CS}) where {N,CS} x = RigidBodyTools._extend_array(b.x,CS) y = RigidBodyTools._extend_array(b.y,CS) #x = [b.x; b.x[1]] #y = [b.y; b.y[1]] linecolor --> mygreen if CS == ClosedBody fillrange --> 0 fillcolor --> mygreen else fill := :false end aspect_ratio := 1 legend := :none grid := false x := x y := y () end @recipe function plot(b::NullBody) end @recipe function f(m::RigidBodyMotion;tmax=10) t = 0.0:0.01:tmax cx = map(ti -> translational_position(m(ti))[1],t) cy = map(ti -> translational_position(m(ti))[2],t) α = map(ti -> angular_position(m(ti)),t) ux = map(ti -> translational_velocity(m(ti))[1],t) uy = map(ti -> translational_velocity(m(ti))[2],t) adot = map(ti -> angular_velocity(m(ti)),t) xlims --> (0,tmax) layout := (2,3) grid --> :none linewidth --> 1 legend --> :none framestyle --> :frame xguide --> L"t" xlim = min(minimum(cx),minimum(cy)),max(maximum(cx),maximum(cy)) alim = extrema(α) ulim = min(minimum(ux),minimum(uy)),max(maximum(ux),maximum(uy)) adlim = extrema(adot) @series begin subplot := 1 ylims --> xlim yguide --> L"x" t, cx end @series begin subplot := 2 ylims --> xlim yguide --> L"y" t, cy end @series begin subplot := 3 ylims --> alim yguide --> L"\alpha" t, α end @series begin subplot := 4 ylims --> ulim yguide --> L"u" t, ux end @series begin subplot := 5 ylims --> ulim yguide --> L"v" t, uy end @series begin subplot := 6 ylims --> adlim yguide --> L"\dot{\alpha}" t, adot end end function RecipesBase.RecipesBase.apply_recipe(plotattributes::Dict{Symbol, Any}, bl::BodyList) series_list = RecipesBase.RecipeData[] for b in bl append!(series_list, RecipesBase.RecipesBase.apply_recipe(copy(plotattributes), b) ) end series_list end
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
27788
# Linked systems # function _default_exogenous_function!(a_edof,u,p,t) end function _default_unconstrained_function!(a_udof,u,p,t) end """ RigidBodyMotion Type containing the connectivities and motions of rigid bodies, linked to the inertial system and possibly to each other, via joints. The basic constructor is `RigidBodyMotion(joints::Vector{Joint},nbody::Int)`, in which `joints` contains a vector of joints of [`Joint`](@ref) type, each specifying the connection between a parent and a child body. (The parent may be the inertial coordinate system.) """ struct RigidBodyMotion{ND} <: AbstractMotion "Number of distinct linked systems" nls :: Int "Number of bodies" nbody :: Int "List of linked bodies, starting with the one connected to inertial system" lslists :: Vector{Vector{Int}} "Vector of joint specifications and motions" joints :: Vector{Joint} "Vector of prescribed deformations of bodies" deformations :: Vector{AbstractDeformationMotion} "Vector specifying the parent body of a body (0 = inertial system)" parent_body :: Vector{Int} "Vector specifying the parent joint of a body" parent_joint :: Vector{Int} "Vector of vectors, specifying the list of child bodies of a body (empty if no children)" child_bodies :: Vector{Vector{Int}} "Vector of vectors, specifying the list of child joints of a body (empty if no children)" child_joints :: Vector{Vector{Int}} "Set of indices providing the joint position coordinates in the global state vector" position_indices :: Vector{Int} "Set of indices providing the joint velocity coordinates in the global state vector" vel_indices :: Vector{Int} "Sets of indices providing the body point coordinates in the global state vector" deformation_indices :: Vector{Vector{Int}} "Function to specify exogenous behavior, must be mutating and have signature (a,u,p,t)" exogenous_function! :: Function "Buffers for exogenous and unconstrained behavior" a_edof_buffer :: Vector{Float64} "Buffers for exogenous and unconstrained behavior" a_udof_buffer :: Vector{Float64} end function RigidBodyMotion(joints::Vector{<:Joint},bodies::BodyList,deformations::Vector{<:AbstractDeformationMotion}; exogenous::Function = _default_exogenous_function!) nbody = length(bodies) parent_body = zeros(Int,nbody) parent_joint = zeros(Int,nbody) child_bodies = [Int[] for i in 1:nbody] child_joints = [Int[] for i in 1:nbody] lscnt = 0 lsroots = Int[] for bodyid in 1:nbody parent_joint[bodyid] = pjid = _parent_joint_of_body(bodyid,joints) parent_body[bodyid] = pbid = joints[pjid].parent_id if pbid == 0 lscnt += 1 push!(lsroots,bodyid) end child_joints[bodyid] = cjids = _child_joints_of_body(bodyid,joints) child_bodies[bodyid] = [joints[cjid].child_id for cjid in cjids] end @assert lscnt > 0 "There is no body connected to the inertial system" lslists = [Int[] for lsid in 1:lscnt] for (lsid,lsroot) in enumerate(lsroots) lslist = lslists[lsid] _list_of_linked_bodies!(lslist,lsroot,child_bodies) end total_members = mapreduce(x -> length(x),+,lslists) @assert total_members == nbody "Not all bodies have been added as members of linked lists" position_indices = mapreduce(jid -> _getrange(joints,position_and_vel_dimension,jid)[1:position_dimension(joints[jid])], vcat,eachindex(joints)) vel_indices = mapreduce(jid -> _getrange(joints,position_and_vel_dimension,jid)[position_dimension(joints[jid])+1:position_and_vel_dimension(joints[jid])], vcat,eachindex(joints)) index_i = length(position_indices) + length(vel_indices) deformation_indices = Vector{Int}[] for (b,m) in zip(bodies,deformations) def_length = length(motion_state(b,m)) push!(deformation_indices,collect(index_i+1:index_i+def_length)) index_i += def_length end a_edof_buffer = _zero_joint(joints,exogenous_dimension) a_udof_buffer = _zero_joint(joints,unconstrained_dimension) RigidBodyMotion{physical_dimension(joints)}(lscnt,nbody,lslists,joints,deformations,parent_body,parent_joint, child_bodies,child_joints,position_indices,vel_indices,deformation_indices, exogenous,a_edof_buffer,a_udof_buffer) end RigidBodyMotion(joints::Vector{<:Joint},bodies::BodyList;kwargs...) = RigidBodyMotion(joints,bodies,[NullDeformationMotion() for bi in 1:length(bodies)];kwargs...) RigidBodyMotion(joint::Joint,body::Body,def::AbstractDeformationMotion;kwargs...) = RigidBodyMotion([joint],BodyList([body]),[def];kwargs...) RigidBodyMotion(joint::Joint,body::Body;kwargs...) = RigidBodyMotion([joint],BodyList([body]);kwargs...) function Base.show(io::IO, ls::RigidBodyMotion) println(io, "$(ls.nls) linked system(s) of bodies") println(io, " $(ls.nbody) bodies") println(io, " $(length(ls.joints)) joints") end """ ismoving(m::RigidBodyMotion) Checks if any joint in `m` is in motion """ function ismoving(m::RigidBodyMotion) @unpack joints, deformations = m any(map(joint -> ismoving(joint),joints)) || any(map(def -> ismoving(def),deformations)) end """ is_system_in_relative_motion(lsid::Int,ls::RigidBodyMotion) -> Bool Returns `true` if the linked system with ID `lsid` is in relative motion, i.e., if one or more of the joints (not connected to the inertial system) returns `true` for the function `ismoving(joint)`. """ function is_system_in_relative_motion(lsid::Int,m::RigidBodyMotion) @unpack lslists = m bodyid = first_body(lsid,m) ismove = false return _ismoving_tree(ismove,bodyid,m) end function _ismoving_tree(ismove::Bool,bodyid::Int,m::RigidBodyMotion) @unpack joints, deformations = m ismove |= ismoving(deformations[bodyid]) for jid in child_joints_of_body(bodyid,m) ismove |= ismoving(joints[jid]) bodyid = child_body_of_joint(jid,m) ismove = _ismoving_tree(ismove,bodyid,m) end return ismove end function _list_of_linked_bodies!(lslist,bodyid,child_bodies) push!(lslist,bodyid) for childid in child_bodies[bodyid] _list_of_linked_bodies!(lslist,childid,child_bodies) end nothing end function _check_for_only_one_body(ls::RigidBodyMotion) @assert ls.nbody == 1 "Linked system must only contain one body" end """ parent_joint_of_body(bodyid,ls::RigidBodyMotion) Return the index of the parent joint of body `bodyid` in system `ls`. """ parent_joint_of_body(bodyid::Int,ls::RigidBodyMotion) = _parent_joint_of_body(bodyid,ls.joints) """ child_joints_of_body(bodyid,ls::RigidBodyMotion) Return the indices (if any) of the child joints of body `bodyid` in system `ls`. This function also accepts `bodyid = 0`, and returns the indices of joints that connect bodies to the inertial coordinate system. """ child_joints_of_body(bodyid::Int,ls::RigidBodyMotion) = _child_joints_of_body(bodyid,ls.joints) """ parent_body_of_joint(jid,ls::RigidBodyMotion) Return the index of the parent body of joint `jid` in system `ls`. """ parent_body_of_joint(jid::Int,ls::RigidBodyMotion) = ls.joints[jid].parent_id """ child_body_of_joint(jid,ls::RigidBodyMotion) Return the index of the child body of joint `jid` in system `ls`. """ child_body_of_joint(jid::Int,ls::RigidBodyMotion) = ls.joints[jid].child_id # If this is empty, then there should be an error, since all bodies # need a parent joint. If it has more than one result, also an error, # since a body can only have one parent joint function _parent_joint_of_body(bodyid,joints::Vector{<:Joint}) idx = findall(x -> x.child_id == bodyid, joints) @assert length(idx) > 0 "Body "*string(bodyid)*" has no parent joint" @assert length(idx) == 1 "Body "*string(bodyid)*" has too many parent joints" return first(idx) end function _child_joints_of_body(bodyid,joints::Vector{<:Joint}) idx = findall(x -> x.parent_id == bodyid, joints) return idx end number_of_linked_systems(ls::RigidBodyMotion) = ls.nls """ first_body(lsid::Int,ls::RigidBodyMotion) Return the index of the first body in linked system `lsid` in the overall set of linked systems `ls`. This body's parent is the inertial coordinate system. """ function first_body(lsid::Int,ls::RigidBodyMotion) @unpack lslists, parent_joint = ls first(lslists[lsid]) end """ first_joint(lsid::Int,ls::RigidBodyMotion) Return the index of the first joint in linked system `lsid` in the overall set of linked systems `ls`. This joint's parent is the inertial coordinate system. """ function first_joint(lsid::Int,ls::RigidBodyMotion) @unpack lslists, parent_joint = ls parent_joint[first_body(lsid,ls)] end for f in [:number_of_dofs,:position_dimension,:position_and_vel_dimension,:constrained_dimension, :exogenous_dimension,:unconstrained_dimension] @eval $f(ls::RigidBodyMotion) = mapreduce(x -> $f(x),+,ls.joints) end """ getrange(ls::RigidBodyMotion,dimfcn::Function,jid::Int) -> Range Return the subrange of indices in the global state vector for the state corresponding to joint `jid` in linked system `ls`. """ function getrange(ls::RigidBodyMotion,dimfcn::Function,jid::Int) @unpack joints = ls _getrange(joints,dimfcn,jid) end function _getrange(joints::Vector{<:Joint},dimfcn::Function,jid::Int) 0 < jid <= length(joints) || error("Unavailable joint") first = 1 j = 1 while j < jid first += dimfcn(joints[j]) j += 1 end last = first+dimfcn(joints[jid])-1 return first:last end """ view(q::AbstractVector,ls::RigidBodyMotion,jid::Int[;dimfcn=position_dimension]) -> SubArray Provide a view of the range of values in vector `q` corresponding to the position of the joint with index `jid` in a RigidBodyMotion `ls`. The optional argument `dimfcn` can be set to `position_dimension`, `constrained_dimension`, `unconstrained_dimension`, or `exogenous_dimension`. """ function Base.view(q::AbstractVector,ls::RigidBodyMotion,jid::Int;dimfcn::Function=position_dimension) return view(q,getrange(ls,dimfcn,jid)) end """ body_transforms(x::AbstractVector,ls::RigidBodyMotion) -> MotionTransformList Parse the overall state vector `x` into the individual joints and construct the inertial system-to-body transforms for every body. Return these transforms in a `MotionTransformList`. """ function body_transforms(x::AbstractVector,ls::RigidBodyMotion{ND}) where {ND} q = position_vector(x,ls) X = MotionTransform{ND}() ml = [deepcopy(X) for jb in 1:ls.nbody] for lsid in 1:number_of_linked_systems(ls) jid = first_joint(lsid,ls) _joint_descendants_transform!(ml,X,jid,q,ls) end return MotionTransformList(ml) end function _joint_descendants_transform!(ml,Xp::MotionTransform,jid::Int,q::AbstractVector,ls::RigidBodyMotion) @unpack joints, child_joints = ls joint = joints[jid] Xch = parent_to_child_transform(view(q,ls,jid),joint)*Xp bid = joint.child_id ml[bid] = deepcopy(Xch) for jcid in child_joints[bid] _joint_descendants_transform!(ml,Xch,jcid,q,ls) end nothing end """ body_velocities(x::AbstractVector,t::Real,ls::RigidBodyMotion) -> PluckerMotionList Compute the velocities of bodies for the rigid body system `ls`, expressing each in its own coordinate system. To carry this out, the function evaluates velocities of dofs with prescribed kinematics at time `t` and and obtains the remaining free dofs (exogenous and unconstrained) from the state vector `x`. """ function body_velocities(x::AbstractVector,t::Real,ls::RigidBodyMotion{ND}) where {ND} v0 = PluckerMotion{2}() vl = [v0 for jb in 1:ls.nbody] for lsid in 1:number_of_linked_systems(ls) jid = first_joint(lsid,ls) _child_velocity_from_parent!(vl,v0,jid,x,t,ls) end return PluckerMotionList(vl) end function _child_velocity_from_parent!(vl,vp::AbstractPluckerMotionVector,jid::Int,x::AbstractVector,t::Real,ls::RigidBodyMotion) @unpack joints, child_joints = ls joint = joints[jid] xJ = view(x,ls,jid;dimfcn=position_and_vel_dimension) q = position_vector(x,ls) vJ = joint_velocity(xJ,t,joint) qJ = view(q,ls,jid) Xp_to_ch = parent_to_child_transform(qJ,joint) #xJ_to_ch = Xp_to_ch*inv(joint.Xp_to_j) xJ_to_ch = inv(joint.Xch_to_j) vch = _child_velocity_from_parent(Xp_to_ch,vp,xJ_to_ch,vJ) bid = joint.child_id vl[bid] = deepcopy(vch) for jcid in child_joints[bid] _child_velocity_from_parent!(vl,vch,jcid,x,t,ls) end nothing end function _child_velocity_from_parent(Xp_to_ch::MotionTransform,vp::AbstractPluckerMotionVector,XJ_to_ch::MotionTransform,vJ::AbstractPluckerMotionVector) vch = Xp_to_ch*vp + XJ_to_ch*vJ end """ zero_joint(ls::RigidBodyMotion[;dimfcn=position_and_vel_dimension]) Create a vector of zeros for some aspect of the state of the linked system(s) `ls`, based on the argument `dimfcn`. By default, it uses `position_and_vel_dimension` and creates a zero vector sized according to the state of the joint. Alternatively, one can use `position_dimension`, `constrained_dimension`, `unconstrained_dimension`, or `exogenous_dimension`. """ zero_joint(ls::RigidBodyMotion;dimfcn=position_and_vel_dimension) = _zero_joint(ls.joints,dimfcn) _zero_joint(joints::Vector{<:Joint},dimfcn) = mapreduce(joint -> zero_joint(joint;dimfcn=dimfcn),vcat,joints) """ zero_motion_state(bl::BodyList,ls::RigidBodyMotion) Create a vector of zeros for the state of the linked system(s) `ls`. """ function zero_motion_state(bl::BodyList,ls::RigidBodyMotion) @unpack deformations = ls x = zero_joint(ls) for (b,m) in zip(bl,deformations) xi = zero_motion_state(b,m) append!(x,xi) end return x end function zero_motion_state(b::Body,ls::RigidBodyMotion) _check_for_only_one_body(ls) zero_motion_state(BodyList([b]),ls) end """ init_motion_state(bl::BodyList,ls::RigidBodyMotion[;tinit = 0.0]) Initialize the global linked system state vector, using the prescribed motions for constrained degrees of freedom to initialize the position components (evaluated at `tinit`, which by default is 0). The other degrees of freedom are initialized to zero, and can be set manually. """ function init_motion_state(bl::BodyList,ls::RigidBodyMotion;kwargs...) @unpack deformations = ls x = mapreduce(joint -> init_joint(joint;kwargs...),vcat,ls.joints) for (b,m) in zip(bl,deformations) xi = motion_state(b,m) append!(x,xi) end return x end function init_motion_state(b::Body,ls::RigidBodyMotion;kwargs...) _check_for_only_one_body(ls) init_motion_state(BodyList([b]),ls;kwargs...) end """ position_vector(x::AbstractVector,ls::RigidBodyMotion) Returns a view of the global state vector for a linked system containing only the position. """ function position_vector(x::AbstractVector,ls::RigidBodyMotion) @unpack position_indices = ls return view(x,position_indices) end """ position_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) Returns a view of the global state vector for a linked system containing only the position of joint `jid`. """ function position_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) @unpack position_indices = ls q = view(x,position_indices) return view(q,ls,jid) end """ exogenous_position_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) Returns a view of the exogenous dof position(s), if any, of joint `jid` in the global state vector `x`. """ function exogenous_position_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) @unpack joints = ls qj = position_vector(x,ls,jid) return view(qj,joints[jid].edofs) end """ unconstrained_position_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) Returns a view of the unconstrained dof position(s), if any, of joint `jid` in the global state vector `x`. """ function unconstrained_position_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) @unpack joints = ls qj = position_vector(x,ls,jid) return view(qj,joints[jid].udofs) end """ velocity_vector(x::AbstractVector,ls::RigidBodyMotion) Returns a view of the global state vector for a linked system containing only the velocity. """ function velocity_vector(x::AbstractVector,ls::RigidBodyMotion) @unpack vel_indices = ls return view(x,vel_indices) end """ velocity_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) Returns a view of the global state vector for a linked system containing only the velocity of joint `jid`. """ function velocity_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) @unpack joints = ls ir = _getrange(joints,position_and_vel_dimension,jid)[position_dimension(joints[jid])+1:position_and_vel_dimension(joints[jid])] return view(x,ir) end """ exogenous_velocity_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) Returns a view of the exogenous dof position(s), if any, of joint `jid` in the global state vector `x`. """ function exogenous_velocity_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) @unpack joints = ls qdotj = velocity_vector(x,ls,jid) return view(qdotj,1:exogenous_dimension(joints[jid])) end """ unconstrained_velocity_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) Returns a view of the unconstrained dof position(s), if any, of joint `jid` in the global state vector `x`. """ function unconstrained_velocity_vector(x::AbstractVector,ls::RigidBodyMotion,jid::Int) @unpack joints = ls qdotj = velocity_vector(x,ls,jid) j = joints[jid] return view(qdotj,exogenous_dimension(j)+1:exogenous_dimension(j)+unconstrained_dimension(j)) end """ deformation_vector(x::AbstractVector,ls::RigidBodyMotion,bid::Int) Returns a view of the global state vector for a linked system containing only the body surface positions of the body with id `bid`. """ function deformation_vector(x::AbstractVector,ls::RigidBodyMotion,bid::Int) @unpack deformation_indices = ls return view(x,deformation_indices[bid]) end ### motion_rhs! APIs ### """ motion_rhs!(dxdt::AbstractVector,x::AbstractVector,p::Tuple{RigidBodyMotion,BodyList},t::Real) Sets the right-hand side vector `dxdt` (mutating) for linked system `ls` of bodies `bl`, using the current state vector `x`, the current time `t`. """ function motion_rhs!(dxdt::AbstractVector,x::AbstractVector,p::Tuple{RigidBodyMotion,Union{Body,BodyList}},t::Real) ls, bl = p @unpack a_edof_buffer, a_udof_buffer, exogenous_function! = ls fill!(a_udof_buffer,0.0) exogenous_function!(a_edof_buffer,x,ls,t) motion_rhs!(dxdt,x,t,a_edof_buffer,a_udof_buffer,ls,bl) end function motion_rhs!(dxdt::AbstractVector,x::AbstractVector,t::Real,a_edof::AbstractVector,a_udof::AbstractVector,ls::RigidBodyMotion,bl::BodyList) @unpack joints, deformations = ls for (jid,joint) in enumerate(joints) dxdt_j = view(dxdt,ls,jid;dimfcn=position_and_vel_dimension) x_j = view(x,ls,jid;dimfcn=position_and_vel_dimension) a_edof_j = view(a_edof,ls,jid;dimfcn=exogenous_dimension) a_udof_j = view(a_udof,ls,jid;dimfcn=unconstrained_dimension) joint_rhs!(dxdt_j,x_j,t,a_edof_j,a_udof_j,joint) end for (bid,b) in enumerate(bl) dxdt_b = deformation_vector(dxdt,ls,bid) dxdt_b .= deformation_velocity(b,deformations[bid],t) end nothing end function motion_rhs!(dxdt::AbstractVector,x::AbstractVector,t::Real,a_edof::AbstractVector,a_udof::AbstractVector,ls::RigidBodyMotion,b::Body) _check_for_only_one_body(ls) motion_rhs!(dxdt,x,t,a_edof,a_udof,ls,BodyList([b])) end ### updating exogenous variables ### """ zero_exogenous(ls::RigidBodyMotion) Generate a zero vector of exogenous acclerations for system `ls` """ zero_exogenous(ls::RigidBodyMotion) = zero(ls.a_edof_buffer) """ update_exogenous!(ls::RigidBodyMotion,a_edof::AbstractVector) Mutates the exogenous buffer of `ls` with the supplied vector of exogenous accelerations `a_edof`. This function is useful for supplying time-varying exogenous values to the integrator from an outer loop. """ function update_exogenous!(ls::RigidBodyMotion,a_edof::AbstractVector) @assert length(ls.a_edof_buffer) == length(a_edof) "Incorrect length of exogenous vector" ls.a_edof_buffer .= a_edof nothing end """ rebase_from_inertial_to_reference(Xi_to_A::MotionTransform,x::AbstractVector,m::RigidBodyMotion,reference_body::Int) If `Xi_to_A` represents a motion transform from the inertial coordinates to some other coordinates A, such as that of a body, then this function returns a motion transform from the reference body coordinates to coordinates A. It uses the current joint state vector `x` to construct the transform list of the system `m`. """ function rebase_from_inertial_to_reference(Xi_to_A::MotionTransform{ND},x::AbstractVector,m::RigidBodyMotion,reference_body::Int) where {ND} Xl = body_transforms(x,m) Xi_to_ref = _reference_transform(Xl,ND,Val(reference_body)) Xref_to_A = Xi_to_A*inv(Xi_to_ref) return Xref_to_A end ### Surface velocity API ### """ surface_velocity!(u::AbstractVector,v::AbstractVector,bl::BodyList,x::AbstractVector,m::RigidBodyMotion,t::Real[;axes=0,frame=axes,motion_part=:full]) Calculate the surface velocity components `u` and `v` for the points on bodies `bl`. The function evaluates prescribed kinematics at time `t` and extracts non-prescribed (exogenous and unconstrained) velocities from state vector `x`. There are three keyword arguments that can change the behavior of this function: `axes` determines whether the components returned are expressed in the inertial coordinate system (0, the default) or another body's coordinates (the body ID); `frame` specifies that the motion should be measured relative to another reference body's velocity (by default, 0); and `motion_part` determines whether the entire reference body velocity is used (`:full`, the default), only the angular part (`:angular`), or only the linear part (`:linear`). """ function surface_velocity!(u::AbstractVector,v::AbstractVector,bl::BodyList,x::AbstractVector,m::RigidBodyMotion{ND},t::Real; axes=0,frame=0,motion_part=:full) where {ND} @unpack deformations = m Xl = body_transforms(x,m) vl = body_velocities(x,t,m) Xref = _reference_transform(Xl,ND,Val(axes)) Xframe = _reference_transform(Xl,ND,Val(frame)) vref_0 = inv(Xframe)*_reference_velocity(vl,ND,motion_part,Val(frame)) for (bid,b) in enumerate(bl) ub = view(u,bl,bid) vb = view(v,bl,bid) R = _rotation_transform(Xl[bid],Xref,Val(bid==axes)) vrel = vl[bid] - Xl[bid]*vref_0 # relative velocity _surface_velocity!(ub,vb,b,vrel,deformations[bid],R,t) end end function surface_velocity!(u::AbstractVector,v::AbstractVector,b::Body,x::AbstractVector,m::RigidBodyMotion,t::Real;kwargs...) _check_for_only_one_body(m) surface_velocity!(u,v,BodyList([b]),x,m,t;kwargs...) end _reference_transform(ml,ND,::Val{0}) = MotionTransform{ND}() _reference_transform(ml,ND,::Val{N}) where N = ml[N] _reference_velocity(vl,ND,motion_part,::Val{0}) = PluckerMotion{ND}() _reference_velocity(vl,ND,motion_part,::Val{N}) where N = _body_velocity(vl[N],Val(motion_part)) _rotation_transform(X::MotionTransform,Xref::MotionTransform,::Val{false}) = rotation_transform(Xref*inv(X)) _rotation_transform(X::MotionTransform{ND},Xref::MotionTransform,::Val{true}) where {ND} = MotionTransform{ND}() _body_velocity(v::PluckerMotion,::Val{:full}) = v _body_velocity(v::PluckerMotion,::Val{:angular}) = angular_only(v) _body_velocity(v::PluckerMotion,::Val{:linear}) = linear_only(v) """ velocity_in_body_coordinates_2d(x,y,v::AbstractPluckerMotionVector) Evaluate the rigid-body velocity `v` at position ``(x,y)``, in the same coordinate system as `v` itself. """ function velocity_in_body_coordinates_2d(x̃,ỹ,vb::AbstractPluckerMotionVector{2}) Xb_to_p = MotionTransform(x̃,ỹ,0.0) Xb_to_p*vb end function velocity_in_inertial_coordinates_2d(x̃,ỹ,vb::AbstractPluckerMotionVector{2},Xb_to_0::MotionTransform{2}) rotation_transform(Xb_to_0)*velocity_in_body_coordinates_2d(x̃,ỹ,vb) end function velocity_in_body_coordinates_2d!(u::AbstractVector,v::AbstractVector,b::Body,vb::AbstractPluckerMotionVector{2}) for i in 1:numpts(b) vp = velocity_in_body_coordinates_2d(b.x̃[i],b.ỹ[i],vb) u[i], v[i] = vp.linear end end function _surface_velocity!(u::AbstractVector,v::AbstractVector,b::Body,vb::AbstractPluckerMotionVector{2},deformation::AbstractDeformationMotion,Rb_to_0::MotionTransform{2},t) u .= 0.0 v .= 0.0 _surface_velocity!(u,v,b,deformation,t) for i in 1:numpts(b) vp = velocity_in_body_coordinates_2d(b.x̃[i],b.ỹ[i],vb) vp += PluckerMotion{2}(linear=[u[i],v[i]]) # add the deformation to the rigid-body plucker vector vp = Rb_to_0*vp # rotate to the inertial system u[i], v[i] = vp.linear end end ### update_body! API ### """ update_body!(bl::Union{Body,BodyList},x::AbstractVector,m::RigidBodyMotion) Update body/bodies in `bl` with the rigid-body motion `m` and state vector `x`. """ function update_body!(bl::BodyList,x::AbstractVector,m::RigidBodyMotion) @unpack deformations = m for (bid,b) in enumerate(bl) _update_body!(b,deformation_vector(x,m,bid),deformations[bid]) end ml = body_transforms(x,m) update_body!(bl,ml) return bl end function update_body!(b::Body,x::AbstractVector,m::RigidBodyMotion) _check_for_only_one_body(m) @unpack deformations = m _update_body!(b,deformation_vector(x,m,1),deformations[1]) T = body_transforms(x,m)[1] update_body!(b,T) return b end """ update_body!(bl::Union{Body,BodyList},x::AbstractVector,m::RigidBodyMotion) Transform body/bodies in `bl` with the rigid-body motion `m` and state vector `x`. """ function transform_body!(bl::BodyList,x::AbstractVector,m::RigidBodyMotion) @unpack deformations = m for (bid,b) in enumerate(bl) _update_body!(b,deformation_vector(x,m,bid),deformations[bid]) end ml = body_transforms(x,m) transform_body!(bl,ml) return bl end function transform_body!(b::Body,x::AbstractVector,m::RigidBodyMotion) _check_for_only_one_body(m) @unpack deformations = m _update_body!(b,deformation_vector(x,m,1),deformations[1]) T = body_transforms(x,m)[1] transform_body!(b,T) return b end """ maxvelocity(b::Union{Body,BodyList},x::AbstractVector,m::RigidBodyMotion[,tmax=10,dt=0.05]) Search through the given motion state vector `x` and motion `m` applied to body `b` and return `(umax,i,t,bid)`, the maximum velocity magnitude, the global index of the body point where it occurs, the time at which it occurs, and the body on which it occurs. """ function maxvelocity(bl::BodyList,x::AbstractVector,m::RigidBodyMotion;tf=10.0,dt=0.05) u, v = zeros(numpts(bl)), zeros(numpts(bl)) i = 1 bid = 1 umax = 0.0 tmax = 0.0 for t in 0.0:dt:tf surface_velocity!(u,v,bl,x,m,t) umag = sqrt.(u.^2+v.^2) umax_t, i_t = findmax(umag) bid_t, iloc_t = global_to_local_index(i_t,bl) if umax_t > umax umax, i, tmax, bid = umax_t, i_t, t, bid_t end end return umax, i, tmax, bid end maxvelocity(b::Body,x::AbstractVector,m::RigidBodyMotion;kwargs...) = maxvelocity(BodyList([b]),x,m;kwargs...)
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
24970
# Rigid-body transformation routines # Things to do here: # - Combine RigidTransform with MotionTransform # - probably should distinguish in-place and non-in-place versions const O3VECTOR = SVector{3}(zeros(Float64,3)) const I3 = SMatrix{3,3}(I) const O3 = SMatrix{3,3}(zeros(Float64,9)) const I6 = SMatrix{6,6}(I) const PLUCKER2DANG = 1:1 const PLUCKER2DLIN = 2:3 const PLUCKER3DANG = 1:3 const PLUCKER3DLIN = 4:6 plucker_dimension(::Val{2}) = 3 plucker_dimension(::Val{3}) = 6 ### Plucker vectors ### abstract type AbstractPluckerVector{ND} end abstract type AbstractPluckerMotionVector{ND} <: AbstractPluckerVector{ND} end abstract type AbstractPluckerForceVector{ND} <: AbstractPluckerVector{ND} end """ PluckerMotion(data::AbstractVector) Creates an instance of a Plucker motion vector, ``v = \\begin{bmatrix} \\Omega \\\\ U \\end{bmatrix}`` using the vector in `data`. If `data` is of length 6, then it creates a 3d motion vector, and the first 3 entries are assumed to comprise the rotational component `\\Omega` and the last 3 entries the translational component `U`. If `data` is of length 3, then it creates a 2d motion vector, assuming that the first entry in `data` represents the rotational component and the second and third entries the x and y translational components. """ PluckerMotion """ PluckerForce(data::AbstractVector) Creates an instance of a Plucker force vector, ``f = \\begin{bmatrix} M \\\\ F \\end{bmatrix}`` using the vector in `data`. If `data` is of length 6, then it creates a 3d force vector, and the first 3 entries are assumed to comprise the moment component `M` and the last 3 entries the force component `F`. If `data` is of length 3, then it creates a 2d force vector, assuming that the first entry in `data` represents the moment component and the second and third entries the x and y force components. """ PluckerForce for typename in [:PluckerMotion,:PluckerForce] abstype = Symbol("Abstract",typename,"Vector") @eval struct $typename{ND} <: $abstype{ND} data :: SVector angular :: SubArray linear :: SubArray $typename{2}(v::SVector) = new{2}(v,view(v,PLUCKER2DANG),view(v,PLUCKER2DLIN)) $typename{3}(v::SVector) = new{3}(v,view(v,PLUCKER3DANG),view(v,PLUCKER3DLIN)) end fname_underscore = Symbol("_",lowercase(string(typename))) @eval function $typename{ND}() where {ND} pd = plucker_dimension(Val(ND)) $typename{ND}(SVector{pd}(zeros(Float64,pd))) end @eval $typename(v::SVector{3}) = $typename{2}(v) @eval $typename{2}(;angular::Real = zero(Float64),linear::AbstractVector = zeros(Float64,2)) = $typename(angular,linear) @eval $typename{3}(;angular::AbstractVector = zeros(Float64,3),linear::AbstractVector = zeros(Float64,3)) = $typename(angular,linear) @eval $typename(Ω::Real,U::AbstractVector) = $typename([Ω,U...]) @eval $typename(Ω::AbstractVector,U::AbstractVector) = $typename([Ω...,U...]) @eval $typename(v::SVector{6}) = $typename{3}(v) @eval $typename(v::AbstractVector) = $fname_underscore(v,Val(length(v))) # We might not want to have strictly Float64 elements, so might rethink this @eval $fname_underscore(v,::Val{3}) = $typename(SVector{3}(convert(Vector{Float64},v))) @eval $fname_underscore(v,::Val{6}) = $typename(SVector{6}(convert(Vector{Float64},v))) @eval (+)(a::$typename{ND},b::$typename{ND}) where {ND} = $typename{ND}(a.data+b.data) @eval (-)(a::$typename{ND},b::$typename{ND}) where {ND} = $typename{ND}(a.data-b.data) @eval (-)(a::$typename{ND}) where {ND} = $typename{ND}(-a.data) @eval @propagate_inbounds getindex(A::$typename, i::Int) = A.data[i] @eval @propagate_inbounds getindex(A::$typename, I...) = A.data[I...] @eval iterate(A::$typename) = iterate(A.data) @eval iterate(A::$typename,I) = iterate(A.data,I) @eval size(A::$typename) = size(A.data) @eval length(A::$typename) = length(A.data) @eval _get_angular_part(v::$typename) = v.angular @eval _get_linear_part(v::$typename) = v.linear end function show(io::IO, p::PluckerMotion{3}) print(io, "3d Plucker motion vector, Ω = $(p.angular), v = $(p.linear)") end function show(io::IO, p::PluckerMotion{2}) print(io, "2d Plucker motion vector, Ω = $(p.angular[1]), U = $(p.linear)") end function show(io::IO, p::PluckerForce{3}) print(io, "3d Plucker force vector, M = $(p.angular), F = $(p.linear)") end function show(io::IO, p::PluckerForce{2}) print(io, "2d Plucker force vector, M = $(p.angular[1]), F = $(p.linear)") end for motname in [:Motion,:Force] typename = Symbol("Plucker",motname) transname = Symbol(motname,"Transform") abstype = Symbol("Abstract",typename,"Vector") for partname in [:Angular,:Linear] newtype = Symbol(typename,partname) fname = Symbol(lowercase(string(partname)),"_only") getpartfunc = Symbol("_get_",lowercase(string(partname)),"_part") @eval export $newtype, $fname @eval struct $newtype{ND} <: $abstype{ND} plucker :: $abstype{ND} $newtype(v::$typename{ND}) where {ND} = new{ND}(v) end @eval (+)(a::$newtype{ND},b::$newtype{ND}) where {ND} = $newtype{ND}(a.plucker+b.plucker) @eval (-)(a::$newtype{ND},b::$newtype{ND}) where {ND} = $newtype{ND}(a.plucker-b.plucker) @eval (-)(a::$newtype{ND}) where {ND} = $newtype{ND}(-a.plucker) @eval $fname(v::$typename) = $newtype(v::$typename) @eval $getpartfunc(v::$newtype) = $getpartfunc(v.plucker) end end """ angular_only(v::AbstractPluckerVector) Returns a Plucker vector with only the angular part of the motion or force vector `v` available for subsequent operations. Note that no copy of the original data in `v` is made. Rather, this simply provides a lazy reference to the angular data in `v`. """ angular_only """ linear_only(v::AbstractPluckerVector) Returns a Plucker vector with only the linear part of the motion or force vector `v` available for subsequent operations. Note that no copy of the original data in `v` is made. Rather, this simply provides a lazy reference to the linear data in `v`. """ linear_only """ dot(f::AbstractPluckerForceVector,v::AbstractPluckerMotionVector) -> Real Calculate the scalar product between force `f` and motion `v`. The commutation of this is also possible, `dot(v,f)`. """ dot(::AbstractPluckerForceVector,::AbstractPluckerMotionVector) dot(f::PluckerForce{ND},v::PluckerMotion{ND}) where {ND} = dot(f.data,v.data) dot(v::PluckerMotion{ND},f::PluckerForce{ND}) where {ND} = dot(f,v) dot(f::PluckerForceAngular{ND},v::AbstractPluckerMotionVector{ND}) where {ND} = dot(_get_angular_part(f),_get_angular_part(v)) dot(f::PluckerForceLinear{ND},v::AbstractPluckerMotionVector{ND}) where {ND} = dot(_get_linear_part(f),_get_linear_part(v)) dot(f::AbstractPluckerForceVector{ND},v::PluckerMotionAngular{ND}) where {ND} = dot(_get_angular_part(f),_get_angular_part(v)) dot(f::AbstractPluckerForceVector{ND},v::PluckerMotionLinear{ND}) where {ND} = dot(_get_linear_part(f),_get_linear_part(v)) dot(v::PluckerMotionAngular{ND},f::AbstractPluckerForceVector{ND}) where {ND} = dot(_get_angular_part(f),_get_angular_part(v)) dot(v::PluckerMotionLinear{ND},f::AbstractPluckerForceVector{ND}) where {ND} = dot(_get_linear_part(f),_get_linear_part(v)) dot(v::AbstractPluckerMotionVector{ND},f::PluckerForceAngular{ND}) where {ND} = dot(_get_angular_part(f),_get_angular_part(v)) dot(v::AbstractPluckerMotionVector{ND},f::PluckerForceLinear{ND}) where {ND} = dot(_get_linear_part(f),_get_linear_part(v)) ### Plucker transform matrices ### abstract type AbstractTransformOperator{ND} end struct MotionTransform{ND} <: AbstractTransformOperator{ND} x :: SVector R :: SMatrix matrix :: SMatrix end struct ForceTransform{ND} <: AbstractTransformOperator{ND} x :: SVector R :: SMatrix matrix :: SMatrix end const RigidTransform = MotionTransform{ND} where {ND} function show(io::IO, p::MotionTransform{3}) print(io, "3d motion transform, x = $(p.x), R = $(p.R)") end function show(io::IO, p::ForceTransform{3}) print(io, "3d force transform, x = $(p.x), R = $(p.R)") end function show(io::IO, p::MotionTransform{2}) print(io, "2d motion transform, x = $(p.x[1:2]), R = $(p.R[1:2,1:2])") end function show(io::IO, p::ForceTransform{2}) print(io, "2d force transform, x = $(p.x[1:2]), R = $(p.R[1:2,1:2])") end translation(T::AbstractTransformOperator{3}) = T.x rotation(T::AbstractTransformOperator{3}) = T.R translation(T::AbstractTransformOperator{2}) = SVector{2}(T.x[1:2]) rotation(T::AbstractTransformOperator{2}) = SMatrix{2,2}(T.R[1:2,1:2]) (*)(T::AbstractTransformOperator,v) = T.matrix*v (*)(v,T::AbstractTransformOperator) = v*T.matrix (*)(T::MotionTransform,v::PluckerMotion) = PluckerMotion(T*v.data) (*)(T::ForceTransform,v::PluckerForce) = PluckerForce(T*v.data) for motname in [:Motion,:Force] typename = Symbol("Plucker",motname) transname = Symbol(motname,"Transform") #abstype = Symbol("Abstract",typename,"Vector") newangulartype = Symbol(typename,"Angular") newlineartype = Symbol(typename,"Linear") @eval (*)(T::$transname,v::$newangulartype{2}) = $typename(view(T.matrix,1:3,PLUCKER2DANG)*_get_angular_part(v)) @eval (*)(T::$transname,v::$newangulartype{3}) = $typename(view(T.matrix,1:6,PLUCKER3DANG)*_get_angular_part(v)) @eval (*)(T::$transname,v::$newlineartype{2}) = $typename(view(T.matrix,1:3,PLUCKER2DLIN)*_get_linear_part(v)) @eval (*)(T::$transname,v::$newlineartype{3}) = $typename(view(T.matrix,1:6,PLUCKER3DLIN)*_get_linear_part(v)) end """ transpose(X::MotionTransform) -> ForceTransform transpose(X::ForceTransform) -> MotionTransform For a motion transform `X` mapping from system A to B, returns the force transform mapping from B to A. Alternatively, if `X` is a force transform, it returns the motion transform. """ function transpose(T::MotionTransform{ND}) where {ND} x = cross_vector(T.R*cross_matrix(-T.x)*T.R') ForceTransform{ND}(x,transpose(T.R),transpose(T.matrix)) end function transpose(T::ForceTransform{ND}) where {ND} x = cross_vector(T.R*cross_matrix(-T.x)*T.R') MotionTransform{ND}(x,transpose(T.R),transpose(T.matrix)) end """ inv(X::AbstractTransformOperator) -> AbstractTransformOperator Return the inverse of the motion or force transform `X`. """ inv(T::MotionTransform{ND}) where {ND} = transpose(ForceTransform{ND}(T.x,T.R)) inv(T::ForceTransform{ND}) where {ND} = transpose(MotionTransform{ND}(T.x,T.R)) # Should be able to do the following in a lazy way, by wrapping the original transform # rather than making a whole new transform. """ rotation_transform(T::AbstractTransformOperator) -> AbstractTransformOperator Returns a transform operator consisting of only the rotational part of `T`. """ rotation_transform(T::MotionTransform{ND}) where {ND} = MotionTransform{ND}(O3VECTOR,T.R) rotation_transform(T::ForceTransform{ND}) where {ND} = ForceTransform{ND}(O3VECTOR,T.R) """ translation_transform(T::AbstractTransformOperator) -> AbstractTransformOperator Returns a transform operator consisting of only the translational part of `T`. """ translation_transform(T::MotionTransform{ND}) where {ND} = MotionTransform{ND}(T.x,I3) translation_transform(T::ForceTransform{ND}) where {ND} = ForceTransform{ND}(T.x,I3) vec(T::AbstractTransformOperator{2}) = [T.x[1],T.x[2],_get_angle_of_2d_transform(T)] function _get_angle_of_2d_transform(T::AbstractTransformOperator{2}) eith = T.R[1,1] + im*T.R[1,2] return real(-im*log(eith)) end ### MotionTransform acting on position coordinate data ### function (T::MotionTransform{2})(x̃::Real,ỹ::Real) Xr = T.R'*[x̃,ỹ,0.0] return T.x[1] + Xr[1], T.x[2] + Xr[2] end function (T::MotionTransform{2})(x̃::AbstractVector{S},ỹ::AbstractVector{S}) where {S<:Real} x = deepcopy(x̃) y = deepcopy(ỹ) for i = 1:length(x̃) x[i],y[i] = T(x̃[i],ỹ[i]) end return x, y end """ (T::MotionTransform)(b::Body) -> Body Transforms a body `b` using the given `MotionTransform`, creating a copy of this body with the new configuration. In using this transform `T` (which defines a transform from system A to system B), A is interpreted as an inertial coordinate system and B as the body system. Thus, the position vector in `T` is interpreted as the relative position of the body in inertial coordinates and the inverse of the rotation operator is applied to transform body-fixed coordinates to the inertial frame. """ function (T::MotionTransform{2})(b::Body) b_transform = deepcopy(b) update_body!(b_transform,T) end """ update_body!(b::Body,T::MotionTransform) Transforms a body (in-place) using the given `MotionTransform`. In using this transform `T` (which defines a transform from system A to system B), A is interpreted as an inertial coordinate system and B as the body system. Thus, the position vector in `T` is interpreted as the relative position of the body in inertial coordinates and the inverse of the rotation operator is applied to transform body-fixed coordinates to the inertial frame. """ function update_body!(b::Body{N,C},T::MotionTransform{2}) where {N,C} b.xend, b.yend = T(b.x̃end,b.ỹend) b.x, b.y = _midpoints(b.xend,b.yend,C) b.α = _get_angle_of_2d_transform(T) b.cent = (T.x[1], T.x[2]) return b end function update_body!(b::NullBody,T::MotionTransform{2}) return b end """ transform_body!(b::Body,T::MotionTransform) Transforms a body's own coordinate system (in-place) using the given `MotionTransform`. This function differs from [`update_body!`](@ref) because it changes the coordinates of the body in its own coordinate system, whereas the latter function only changes the inertial coordinates of the body. `T` is interpreted as a transform from the new system to the old system. """ function transform_body!(b::Body{N,C},T::MotionTransform{2}) where {N,C} b.xend, b.yend = T(b.x̃end,b.ỹend) b.x̃end .= b.xend b.ỹend .= b.yend b.x, b.y = _midpoints(b.xend,b.yend,C) b.x̃ .= b.x b.ỹ .= b.y b.α = _get_angle_of_2d_transform(T) b.cent = (T.x[1], T.x[2]) return b end ### function _motion_transform_matrix(xA_to_B::SVector{3},RA_to_B::SMatrix{3,3}) xM = cross_matrix(xA_to_B) Mtrans = SMatrix{6,6}([I3 O3; -xM I3]) Mrot = SMatrix{6,6}([RA_to_B O3; O3 RA_to_B]) return Mrot*Mtrans end function _force_transform_matrix(xA_to_B::SVector{3},RA_to_B::SMatrix{3,3}) xM = cross_matrix(xA_to_B) Mtrans = SMatrix{6,6}([I3 -xM; O3 I3]) Mrot = SMatrix{6,6}([RA_to_B O3; O3 RA_to_B]) return Mrot*Mtrans end function _motion_transform_matrix(xA_to_B::SVector{3}) xM = cross_matrix(xA_to_B) Mtrans = SMatrix{6,6}([I3 O3; -xM I3]) return Mtrans end function _force_transform_matrix(xA_to_B::SVector{3}) xM = cross_matrix(xA_to_B) Mtrans = SMatrix{6,6}([I3 -xM; O3 I3]) return Mtrans end function _motion_transform_matrix(RA_to_B::SMatrix{3,3}) Mrot = SMatrix{6,6}([RA_to_B O3; O3 RA_to_B]) return Mrot end function _force_transform_matrix(RA_to_B::SMatrix{3,3}) Mrot = SMatrix{6,6}([RA_to_B O3; O3 RA_to_B]) return Mrot end for f in [:motion, :force] fname_underscore = Symbol("_",f,"_transform_matrix") fname2d_underscore = Symbol(fname_underscore,"_2d") typename = Symbol(uppercasefirst(string(f)),"Transform") @eval $typename{3}(x_3d::SVector{3},R_3d::SMatrix{3,3}) = $typename(x_3d,R_3d) @eval $typename{2}(x_3d::SVector{3},R_3d::SMatrix{3,3}) = $typename(SVector{2}(view(x_3d,1:2)),R_3d) @eval $typename{ND}() where {ND} = $typename{ND}(O3VECTOR,rotation_identity()) @eval function $typename(x_3d::SVector{3},R_3d::SMatrix{3,3}) M = $fname_underscore(x_3d,R_3d) return $typename{3}(x_3d,R_3d,M) end @eval function $typename(x_2d::SVector{2},R_3d::SMatrix{3,3}) x_3d = SVector{3}([x_2d... 0.0]) M = $fname2d_underscore(x_3d,R_3d) return $typename{2}(x_3d,R_3d,M) end @eval function $typename(x_2d::SVector{2}) x_3d = SVector{3}([x_2d... 0.0]) M = $fname2d_underscore(x_3d) return $typename{2}(x_3d,I3,M) end @eval function $typename(x_2d::SVector{2},R_2d::SMatrix{2,2}) R_3d = SMatrix{3,3}([R_2d zeros(Float64,2,1); zeros(Float64,1,2) 1.0]) $typename(x_2d,R_3d) end @eval function $typename(x::AbstractVector,R::AbstractMatrix) lenx = length(x) nx, ny = size(R) @assert (lenx == 2 || lenx == 3) "x has inconsistent length" @assert (nx == ny == 3 || nx == ny == 2) "Rotation matrix has inconsistent dimensions" $typename(SVector{lenx}(x),SMatrix{nx,ny}(R)) end @eval $typename(x::SVector{2},Θ::Real) = $typename(x,rotation_about_z(-Θ)) @eval $typename(x::Vector,θ::Real) = $typename(SVector{2}(x),θ) @eval $typename(x::Tuple,θ::Real) = $typename(SVector{2}(x...),θ) @eval $typename(x::Real,y::Real,θ::Real) = $typename(SVector{2}([x,y]),θ) @eval $typename(c::Complex{T},θ::Real) where T<:Real = $typename((real(c),imag(c)),θ) @eval $typename(v::AbstractVector) = $typename(v...) @eval $typename(T::RigidTransform) = $typename(vec(T)) @eval function $fname2d_underscore(x_3d::SVector{3},R_3d::SMatrix{3,3}) M_3d = $fname_underscore(x_3d,R_3d) return SMatrix{3,3}(view(M_3d,3:5,3:5)) end @eval function $fname2d_underscore(x_3d::SVector{3}) M_3d = $fname_underscore(x_3d) return SMatrix{3,3}(view(M_3d,3:5,3:5)) end @eval function $fname2d_underscore(R_3d::SMatrix{3,3}) M_3d = $fname_underscore(R_3d) return SMatrix{3,3}(view(M_3d,3:5,3:5)) end @eval function (*)(T1::$typename{ND},T2::$typename{ND}) where {ND} x12 = cross_vector(T2.R'*cross_matrix(T1.x)*T2.R + cross_matrix(T2.x)) R12 = T1.R*T2.R $typename{ND}(x12,R12,T1.matrix*T2.matrix) end end """ MotionTransform(xA_to_B::SVector,RA_to_B::SMatrix) -> MotionTransform Computes the Plucker transform matrix for motion vectors, transforming from system A to system B. The input `xA_to_B` is the Euclidean vector from the origin of A to the origin of B, expressed in A coordinates, and `RA_to_B` is the rotation matrix transforming coordinates in system A to those in system B. The resulting matrix has the form ``{}^B T^{(m)}_A = \\begin{bmatrix} R & 0 \\\\ 0 & R \\end{bmatrix} \\begin{bmatrix} 1 & 0 \\\\ -x^\\times & 1 \\end{bmatrix}`` One can also provide `xA_to_B` as a standard vector and `RA_to_B` as a standard 3 x 3 matrix. If `xA_to_B` has length 3, then a three-dimensional transform (a 6 x 6 Plucker transform) is created. If `xA_to_B` has length 2, then a two-dimensional transform (3 x 3 Plucker transform) is returned. """ MotionTransform(::SVector{3},::SMatrix) """ MotionTransform(xA_to_B,θ::Real) -> MotionTransform Computes the 3 x 3 2D Plucker transform matrix for motion vectors, transforming from system A to system B. The input `xA_to_B` is the 2-d Euclidean vector from the origin of A to the origin of B, expressed in A coordinates, and `θ` is the angle of system B relative to system A. `xA_to_B` can be in the form of a static vector, a vector, or a tuple. """ MotionTransform(::AbstractVector,::Real) """ MotionTransform(T::RigidTransform) -> MotionTransform Computes the 3 x 3 2D Plucker transform matrix for motion vectors, transforming from system A to system B, from the rigid transform `T`. """ MotionTransform(::RigidTransform) """ ForceTransform(xA_to_B::SVector,RA_to_B::SMatrix) -> ForceTransform Computes the 6 x 6 Plucker transform matrix for force vectors, transforming from system A to system B. The input `xA_to_B` is the Euclidean vector from the origin of A to the origin of B, expressed in A coordinates, and `RA_to_B` is the rotation matrix transforming coordinates in system A to those in system B. The resulting matrix has the form ``{}^B T^{(f)}_A = \\begin{bmatrix} R & 0 \\\\ 0 & R \\end{bmatrix} \\begin{bmatrix} 1 & -x^\\times \\\\ 0 & 1 \\end{bmatrix}`` """ ForceTransform(::SVector{3},::SMatrix) """ ForceTransform(xA_to_B,θ::Real) -> ForceTransform Computes the 3 x 3 2D Plucker transform matrix for force vectors, transforming from system A to system B. The input `xA_to_B` is the 2-d Euclidean vector from the origin of A to the origin of B, expressed in A coordinates, and `θ` is the angle of system B relative to system A. `xA_to_B` can be in the form of a static vector, a vector, or a tuple. """ ForceTransform(::AbstractVector,::Real) """ ForceTransform(T::RigidTransform) -> ForceTransform Computes the 3 x 3 2D Plucker transform matrix for force vectors, transforming from system A to system B, from the rigid transform `T`. """ ForceTransform(::RigidTransform) ### Rotation matrices ### rotation_identity() = I3 """ rotation_about_z(θ::Real) -> SMatrix{3,3} Constructs the rotation matrix corresponding to rotation about the z axis by angle θ. The matrix transforms the coordinates of a vector in system A to coordinates in system B, where Θ is the angle of A with respect to B. (Flip the sign of the input Θ if you want it to correspond to B's angle relative to A.) """ function rotation_about_z(θ::Real) cth, sth = cos(θ), sin(θ) R = @SMatrix[cth -sth 0.0; sth cth 0.0; 0.0 0.0 1.0] return R end """ rotation_about_y(θ::Real) -> SMatrix{3,3} Constructs the rotation matrix corresponding to rotation about the y axis by angle θ. The matrix transforms the coordinates of a vector in system A to coordinates in system B, where Θ is the angle of A with respect to B. (Flip the sign of the input Θ if you want it to correspond to B's angle relative to A.) """ function rotation_about_y(θ::Real) cth, sth = cos(θ), sin(θ) R = @SMatrix[cth 0.0 sth; 0.0 1.0 0.0; -sth 0.0 cth] return R end """ rotation_about_x(θ::Real) -> SMatrix{3,3} Constructs the rotation matrix corresponding to rotation about the x axis by angle θ. The matrix transforms the coordinates of a vector in system A to coordinates in system B, where Θ is the angle of A with respect to B. (Flip the sign of the input Θ if you want it to correspond to B's angle relative to A.) """ function rotation_about_x(θ::Real) cth, sth = cos(θ), sin(θ) R = @SMatrix[1.0 0.0 0.0; 0.0 cth -sth; 0.0 sth cth] return R end """ rotation_about_axis(θ::Real,v::Vector) -> SMatrix{3,3} Constructs the rotation matrix corresponding to rotation about the axis `v` by angle θ. The matrix transforms the coordinates of a vector in system A to coordinates in system B, where Θ is the angle of A with respect to B. (Flip the sign of the input Θ if you want it to correspond to B's angle relative to A.) """ rotation_about_axis(ϴ::Real,v::SVector{3}) = rotation_from_quaternion(quaternion(ϴ,v)) rotation_about_axis(Θ::Real,v::Vector) = rotation_about_axis(Θ,SVector{3}(v)) """ rotation_from_quaternion(q::SVector{4}) -> SMatrix{3,3} Constructs a rotation matrix from a given quaternion `q` (a 4-dimensional vector). The matrix transforms the coordinates of a vector in system A to coordinates in system B, where A is rotated with respect to B by θ. """ function rotation_from_quaternion(q::SVector{4}) w, x, y, z = q R = @SMatrix[1-2y^2-2z^2 2*x*y-2*z*w 2*x*z+2*y*w; 2*x*y+2*z*w 1-2x^2-2z^2 2*y*z-2*x*w; 2*x*z-2*y*w 2*y*z+2*x*w 1-2x^2-2y^2] return R end rotation_from_quaternion(q::Vector) = rotation_from_quaternion(SVector{4}(q)) """ quaternion(θ::Real,v::SVector{3}) -> SVector{4} Form the quaternion ``q = w + x\\hat{i} + y\\hat{j} + z\\hat{k}`` from the given rotation angle `θ` and rotation axis `v`. Note that `v` need not be a unit vector. """ function quaternion(θ::Real,v::SVector{3}) vnorm = v/norm(v) q = SVector{4}([cos(θ/2),sin(θ/2)*vnorm...]) end quaternion(θ::Real,v::Vector) = quaternion(θ,SVector{3}(v)) quaternion(q::AbstractVector) = quaternion(q[1],SVector{3}(q[2:4])) """ cross_matrix(v::SVector) -> SMatrix Takes a vector `v` and forms the corresponding cross-product matrix `M`, so that ``v \\times w`` is equivalent to ``M\\cdot w``. """ function cross_matrix(v::SVector{3}) M = @SMatrix [0.0 -v[3] v[2]; v[3] 0.0 -v[1]; -v[2] v[1] 0.0] return M end cross_matrix(v::Vector) = cross_matrix(SVector{3}(v)) """ cross_vector(M::SMatrix) -> SVector Takes a matrix `M` and forms the corresponding axial vector `v` from the matrix's anti-symmetric part (``M_a = (M-M^{T})/2``), so that ``v \\times w`` is equivalent to ``M_a\\cdot w``. """ function cross_vector(M::SMatrix{3,3}) Ma = 0.5*(M - transpose(M)) return @SVector [Ma[3,2],Ma[1,3],Ma[2,1]] end cross_vector(M::Matrix) = cross_vector(SMatrix{3,3}(M))
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
20000
using Dierckx using Statistics: mean using Elliptic using Roots using LinearAlgebra #= Approach: - every body shape must contain xend, yend, x̃end, ỹend, x, y, x̃, ỹ - x̃end, ỹend, x̃, ỹ, are the untransformed coordinates and remain invariant in rigid transforms, but are modified in deforming motions - end points of segments are moved (dx̃end/dt) transformed (x̃end -> xend). - For polygons, the endpoints coincide with vertices. - the Lagrange points (x, y) are the midpoints of segments, and are to be computed from (xend, yend) using midpoint after every transform. - may not need the x̃, ỹ coordinates. =# export BasicBody,Ellipse,Circle,Rectangle,Square,Plate,ThickPlate,SplinedBody,NACA4,Polygon,NullBody """ BasicBody(x,y[,closuretype=ClosedBody]) <: Body Construct a body by simply passing in the `x` and `y` coordinate vectors. The last point will be automatically connected to the first point. The coordinate vectors are assumed to be expressed in the body-fixed coordinate system. The optional `closuretype` specifies whether the body is closed (`ClosedBody`) or open (`OpenBody`). If closed, then the first and last points are assumed joined in operations that require neighbor points. """ mutable struct BasicBody{N,C<:BodyClosureType} <: Body{N,C} cent :: Tuple{Float64,Float64} α :: Float64 x̃ :: Vector{Float64} ỹ :: Vector{Float64} x :: Vector{Float64} y :: Vector{Float64} x̃end :: Vector{Float64} ỹend :: Vector{Float64} xend :: Vector{Float64} yend :: Vector{Float64} end function BasicBody(xend::Vector{T},yend::Vector{T};closuretype::Type{<:BodyClosureType}=ClosedBody) where {T <: Real} @assert length(xend) == length(yend) x, y = _midpoints(xend,yend,closuretype) BasicBody{length(x),closuretype}((0.0,0.0),0.0,x,y,x,y,xend,yend,xend,yend) end function Base.show(io::IO, body::BasicBody{N,C}) where {N,C} println(io, "Basic pointwise-specified body with $N points") println(io, " Current position: ($(body.cent[1]),$(body.cent[2]))") println(io, " Current angle (rad): $(body.α)") end #### Ellipses and circles #### """ Ellipse(a,b,n[,endpointson=false],[shifted=false]) <: Body Construct an elliptical body with semi-major axis `a` and semi-minor axis `b`, with `n` points distributed on the body perimeter. Can also call this with `Ellipse(a,b,ds)` where `ds` is the desired spacing between points. If `endpointson=true`, then the endpoints will be placed on the surface and the midpoints will lie inside the nominal ellipse. By default, the midpoints lie on the ellipse. If `shifted=true`, then the first endpoint lies on an axis of symmetry. By default the first midpoint lies on the axis symmetry. """ mutable struct Ellipse{N} <: Body{N,ClosedBody} a :: Float64 b :: Float64 cent :: Tuple{Float64,Float64} α :: Float64 x̃ :: Vector{Float64} ỹ :: Vector{Float64} x :: Vector{Float64} y :: Vector{Float64} x̃end :: Vector{Float64} ỹend :: Vector{Float64} xend :: Vector{Float64} yend :: Vector{Float64} end #= endpointson=false ensures that the midpoints lie on the surface of the ellipse (and the endpoints are outside) =# function Ellipse(a::Real,b::Real,N::Int;endpointson=false,shifted=false) #N = 4*round(Int,N_given/4) # ensure that N is divisible by 4 shiftedtype = shifted ? Shifted : Unshifted Nqrtr = div(N,4) + 1 maj, min = a > b ? (a, b) : (b, a) m = 1 - min^2/maj^2 smax = maj*Elliptic.E(m) Δs = smax/(Nqrtr-1) ϴ, _ = _get_ellipse_thetas(Δs,smax,maj,m,shiftedtype) _x, _y = min*cos.(ϴ), maj*sin.(ϴ) x, y = a > b ? (reverse(_y),reverse(_x)) : (_x,_y) adj = _last_segment_decrement(shiftedtype) xt = vcat(x,-reverse(x[1:end-adj]),-x[1+adj:end], reverse(x[1+adj:end-adj])) yt = vcat(y, reverse(y[1:end-adj]),-y[1+adj:end],-reverse(y[1+adj:end-adj])) # if this is endpointson = false, then xt, yt are the desired midpoints # otherwise, these are the endpoints if endpointson xend, yend = copy(xt), copy(yt) x, y = _midpoints(xt,yt,ClosedBody) else x, y = copy(xt), copy(yt) midinv = midpoint_inverse(length(x)) xend = midinv*x yend = midinv*y end Ellipse{length(x)}(a,b,(0.0,0.0),0.0,x,y,x,y,xend,yend,xend,yend) end function _get_ellipse_thetas(Δs,smax,maj,m,shiftedtype) slast = _start_s(Δs,shiftedtype) θlast = 0.0 s = maj*Elliptic.E(θlast,m) θ = _init_Θ(shiftedtype) ds = [] while s < _max_s(smax,Δs,shiftedtype) θi = find_zero(x -> maj*Elliptic.E(x,m) - slast - Δs,θlast,atol=1e-12) s = maj*Elliptic.E(θi,m) push!(ds,s-slast) push!(θ,θi) θlast = θi slast = s end θ, ds end _start_s(Δs,::Type{Shifted}) = -0.5*Δs _start_s(Δs,::Type{Unshifted}) = 0.0 _init_Θ(::Type{Shifted}) = Float64[] _init_Θ(::Type{Unshifted}) = Float64[0.0] _max_s(smax,Δs,::Type{Shifted}) = smax-Δs _max_s(smax,Δs,::Type{Unshifted}) = smax _last_segment_decrement(::Type{Shifted}) = 0 _last_segment_decrement(::Type{Unshifted}) = 1 midpoint_inverse(N) = _midpoint_inverse(N,Val(mod(N,2)==0)) function _midpoint_inverse(n::Int,::Val{true}) # even N #mod(n,2) == 0 || error("midpoint inverse only verified for even n") d = 1/n u = Matrix(undef,1,n) num = 1.0-d sgn = 1.0 u[1] = u[n] = sgn*num for i in 2:n÷2 num -= 2d sgn *= -1.0 u[i] = u[n-i+1] = sgn*num end A = Matrix(undef,n,n) A[1,:] = u for i in 2:n u .= circshift(u,(0,1)) A[i,:] = u end return A end function _midpoint_inverse(n::Int,::Val{false}) # odd N #mod(n,2) == 0 || error("midpoint inverse only verified for even n") u = Matrix(undef,1,n) sgn = 1.0 u[1] = sgn for i in 2:n sgn *= -1.0 u[i] = sgn end A = copy(u) for i in 2:n u .= circshift(u,(0,1)) A = vcat(A,u) end return A end """ Circle(a,n) <: Body Construct a circular body with radius `a` and with `n` points distributed on the body perimeter. """ Circle(::Real,::Int) """ Circle(a,targetsize::Float64) <: Body Construct a circular body with radius `a` with spacing between points set approximately to `targetsize`. """ Circle(::Real,::Real) Circle(a::Real,arg;kwargs...) = Ellipse(a,a,arg;kwargs...) function Base.show(io::IO, body::Ellipse{N}) where {N} if body.a == body.b println(io, "Circular body with $N points and radius $(body.a)") else println(io, "Elliptical body with $N points and semi-axes ($(body.a),$(body.b))") end println(io, " Current position: ($(body.cent[1]),$(body.cent[2]))") println(io, " Current angle (rad): $(body.α)") end #### Rectangles and squares #### """ Rectangle(a,b,n) <: Body Construct a rectangular body with x̃ side half-length `a` and ỹ side half-length `b`, with approximately `n` points distributed along the perimeter. The centroid of the rectangle is placed at the origin (so that the lower left corner is at (-a,-b)). Points are not placed at the corners, but rather, are shifted by half a segment. This ensures that all normals are perpendicular to the sides. """ Rectangle(a::Real,b::Real,arg;kwargs...) = Polygon([-a,a,a,-a],[-b,-b,b,b],arg;kwargs...) """ Rectangle(a,b,ds) <: Body Construct a rectangular body with x̃ side half-length `a` and ỹ side half-length `b`, with approximate spacing `ds` between points. """ Rectangle(::Real,::Real,::Real) """ Square(a,n) <: Body Construct a square body with side half-length `a` and with approximately `n` points distributed along the perimeter. """ Square(a::Real,arg;kwargs...) = Rectangle(a,a,arg;kwargs...) """ Square(a,ds) <: Body Construct a square body with side half-length `a`, with approximate spacing `ds` between points. """ Square(::Real,::Real) #### Plates #### """ Plate(a,n) <: Body Construct a flat plate of zero thickness with length `a`, divided into `n` equal segments. """ Plate(len::Real,arg) = Polygon([-0.5*len,0.5*len],[0.0,0.0],arg,closuretype=OpenBody) """ Plate(a,ds) <: Body Construct a flat plate of zero thickness with length `a`, with approximate spacing `ds` between points. """ Plate(::Real,::Real) #### Polygons #### """ Polygon(x::Vector,y::Vector,n[,closuretype=ClosedBody]) Create a polygon shape with vertices `x` and `y`, with approximately `n` points distributed along the perimeter. """ mutable struct Polygon{N,NV,C<:BodyClosureType} <: Body{N,C} cent :: Tuple{Float64,Float64} α :: Float64 x̃ :: Vector{Float64} ỹ :: Vector{Float64} x :: Vector{Float64} y :: Vector{Float64} x̃end :: Vector{Float64} ỹend :: Vector{Float64} xend :: Vector{Float64} yend :: Vector{Float64} side :: Vector{UnitRange{Int64}} end """ Polygon(x::Vector,y::Vector,ds::Float64[,closuretype=ClosedBody]) Create a polygon shape with vertices `x` and `y`, with approximate spacing `ds` between points. """ Polygon(::AbstractVector,::AbstractVector,::Real) function Polygon(xv::AbstractVector{T},yv::AbstractVector{T},a::Float64;closuretype=ClosedBody) where {T<:Real} xend, yend, x, y, side = _polygon(xv,yv,a,closuretype) Polygon{length(x),length(xv),closuretype}((0.0,0.0),0.0,x,y,x,y,xend,yend,xend,yend,side) end @inline Polygon(xv,yv,n::Int;closuretype=ClosedBody) = Polygon(xv,yv,polygon_perimeter(xv,yv,closuretype)/n,closuretype=closuretype) function polygon_perimeter(xv,yv,closuretype) xvcirc = _extend_array(xv,closuretype) yvcirc = _extend_array(yv,closuretype) len = 0.0 for i in 1:length(xvcirc)-1 len += sqrt((xvcirc[i+1]-xvcirc[i])^2+(yvcirc[i+1]-yvcirc[i])^2) end return len end function Base.show(io::IO, body::Polygon{N,NV,CS}) where {N,NV,CS} cb = CS == ClosedBody ? "Closed " : "Open " println(io, cb*"polygon with $NV vertices and $N points") println(io, " Current position: ($(body.cent[1]),$(body.cent[2]))") println(io, " Current angle (rad): $(body.α)") end function _polygon(xv::AbstractVector{T},yv::AbstractVector{T},ds::Float64,closuretype) where {T<:Real} xvcirc = _extend_array(xv,closuretype) yvcirc = _extend_array(yv,closuretype) xend, yend, side = Float64[], Float64[], UnitRange{Int64}[] totlen = 0 for i in 1:length(xvcirc)-2 xi, yi = _line_points(xvcirc[i],yvcirc[i],xvcirc[i+1],yvcirc[i+1],ds) len = length(xi)-1 append!(xend,xi[1:len]) append!(yend,yi[1:len]) push!(side,totlen+1:totlen+len) totlen += len end xi, yi = _line_points(xvcirc[end-1],yvcirc[end-1],xvcirc[end],yvcirc[end],ds) len = length(xi)-_last_segment_decrement(closuretype) append!(xend,xi[1:len]) append!(yend,yi[1:len]) push!(side,totlen+1:totlen+len) x, y = _midpoints(xend,yend,closuretype) return xend, yend, x, y, side end _extend_array(x,::Type{ClosedBody}) = [x;x[1]] _extend_array(x,::Type{OpenBody}) = x _last_segment_decrement(::Type{ClosedBody}) = 1 _last_segment_decrement(::Type{OpenBody}) = 0 function _line_points(x1,y1,x2,y2,n::Int) dx, dy = x2-x1, y2-y1 len = sqrt(dx^2+dy^2) Δs = len/(n-1) x = zeros(n) y = zeros(n) range = (0:n-1)/(n-1) @. x = x1 + dx*range @. y = y1 + dy*range return x, y end function _line_points(x1,y1,x2,y2,ds::Float64) dx, dy = x2-x1, y2-y1 len = sqrt(dx^2+dy^2) return _line_points(x1,y1,x2,y2,round(Int,len/ds)+1) end #### Splined body #### """ SplinedBody(X,Δx[,closuretype=ClosedBody]) -> BasicBody Using control points in `X` (assumed to be N x 2, where N is the number of points), create a set of points that are uniformly spaced (with spacing `Δx`) on a curve that passes through the control points. A cubic parametric spline algorithm is used. If the optional parameter `closuretype` is set to `OpenBody`, then the end points are not joined together. """ function SplinedBody(Xpts_raw::Array{Float64,2},Δx::Float64;closuretype::Type{<:BodyClosureType}=ClosedBody) x, y = _splined_body(Xpts_raw,Δx,closuretype) return BasicBody(x,y,closuretype=closuretype) end """ SplinedBody(x,y,Δx[,closuretype=ClosedBody]) -> BasicBody Using control points in `x` and `y`, create a set of points that are uniformly spaced (with spacing `Δx`) on a curve that passes through the control points. A cubic parametric spline algorithm is used. If the optional parameter `closuretype` is set to `OpenBody`, then the end points are not joined together. """ SplinedBody(x::AbstractVector{Float64},y::AbstractVector{Float64},Δx::Float64;kwargs...) = SplinedBody(hcat(x,y),Δx;kwargs...) function _splined_body(Xpts_raw::Array{Float64,2},Δx::Float64,closuretype::Type{<:BodyClosureType}) # Assume Xpts are in the form N x 2 Xpts = copy(Xpts_raw) if Xpts[1,:] != Xpts[end,:] Xpts = vcat(Xpts,Xpts[1,:]') end spl = (closuretype == ClosedBody) ? ParametricSpline(Xpts',periodic=true) : ParametricSpline(Xpts') tfine = range(0,1,length=1001) dX = derivative(spl,tfine) np = ceil(Int,sqrt(sum(dX.^2)*(tfine[2]-tfine[1]))/Δx) tsamp = range(0,1,length=np) x = [X[1] for X in spl.(tsamp[1:end-1])] y = [X[2] for X in spl.(tsamp[1:end-1])] return x, y end """ ThickPlate(length,thick,n,[λ=1.0]) <: Body Construct a flat plate with length `length` and thickness `thick`, with `n` points distributed along one side. The optional parameter `λ` distributes the points differently. Values between `0.0` and `1.0` are accepted. Alternatively, the shape can be specified with a target point spacing in place of `n`. """ mutable struct ThickPlate{N} <: Body{N,ClosedBody} len :: Float64 thick :: Float64 cent :: Tuple{Float64,Float64} α :: Float64 x̃ :: Vector{Float64} ỹ :: Vector{Float64} x :: Vector{Float64} y :: Vector{Float64} x̃end :: Vector{Float64} ỹend :: Vector{Float64} xend :: Vector{Float64} yend :: Vector{Float64} end function ThickPlate(len::Real,thick::Real,N::Int;λ::Float64=1.0) # input N is the number of panels on one side only # set up points on flat sides Δϕ = π/N Jϕa = [sqrt(sin(ϕ)^2+λ^2*cos(ϕ)^2) for ϕ in range(π-Δϕ/2,stop=Δϕ/2,length=N)] Jϕ = len*Jϕa/Δϕ/sum(Jϕa) xtopface = -0.5*len .+ Δϕ*cumsum([0.0; Jϕ]) xtop = 0.5*(xtopface[1:N] + xtopface[2:N+1]) Δsₑ = Δϕ*Jϕ[1] Nₑ = 2*floor(Int,0.25*π*thick/Δsₑ) xedgeface = [0.5*len + 0.5*thick*cos(ϕ) for ϕ in range(π/2,stop=-π/2,length=Nₑ+1)] yedgeface = [ 0.5*thick*sin(ϕ) for ϕ in range(π/2,stop=-π/2,length=Nₑ+1)] xedge = 0.5*(xedgeface[1:Nₑ]+xedgeface[2:Nₑ+1]) yedge = 0.5*(yedgeface[1:Nₑ]+yedgeface[2:Nₑ+1]) x̃end = Float64[] ỹend = Float64[] for xi in xtop push!(x̃end,xi) push!(ỹend,0.5*thick) end for i = 1:Nₑ push!(x̃end,xedge[i]) push!(ỹend,yedge[i]) end for xi in reverse(xtop,dims=1) push!(x̃end,xi) push!(ỹend,-0.5*thick) end for i = Nₑ:-1:1 push!(x̃end,-xedge[i]) push!(ỹend,yedge[i]) end x̃end .= reverse(x̃end) ỹend .= reverse(ỹend) x̃, ỹ = _midpoints(x̃end,ỹend,ClosedBody) ThickPlate{length(x̃)}(len,thick,(0.0,0.0),0.0,x̃,ỹ,x̃,ỹ,x̃end,ỹend,x̃end,ỹend) end function Base.show(io::IO, body::ThickPlate{N}) where {N} println(io, "Thick plate with $N points and length $(body.len) and thickness $(body.thick)") println(io, " Current position: ($(body.cent[1]),$(body.cent[2]))") println(io, " Current angle (rad): $(body.α)") end #### NACA 4-digit airfoil #### """ NACA4(cam,pos,thick,ds::Float64,[len=1.0]) <: Body{N} Generates points in the shape of a NACA 4-digit airfoil. The relative camber is specified by `cam`, the position of maximum camber (as fraction of chord) by `pos`, and the relative thickness by `thick`. The parameter `ds` specifies the distance between points. The optional parameter `len` specifies the chord length, which defaults to 1.0. # Example ```jldoctest julia> b = NACA4(0.0,0.0,0.12,0.02); ``` """ mutable struct NACA4{N} <: Body{N,ClosedBody} len :: Float64 camber :: Float64 pos :: Float64 thick :: Float64 cent :: Tuple{Float64,Float64} α :: Float64 x̃ :: Vector{Float64} ỹ :: Vector{Float64} x :: Vector{Float64} y :: Vector{Float64} x̃end :: Vector{Float64} ỹend :: Vector{Float64} xend :: Vector{Float64} yend :: Vector{Float64} end NACA4(cam::Float64,pos::Float64,t::Float64,ds::Float64;len=1.0) = _naca4(cam,pos,t,ds,len) function NACA4(cam::Float64,pos::Float64,t::Float64,n::Int;len=1.0) # Determine the perimeter of the shape ds_refined = 0.005 perim = arclength(_naca4(cam,pos,t,ds_refined,len)) return NACA4(cam,pos,t,perim/n;len=len) end """ NACA4(n4::Int,ds::Float64,[len=1.0]) <: Body{N} Generates points in the shape of a NACA 4-digit airfoil, specified by `n4`, with distance between points specified by `ds`. The optional parameter `len` specifies the chord length, which defaults to 1.0. # Example ```jldoctest julia> b = NACA4(0012,0.02); ``` """ function NACA4(num4::Int,a...;kwargs...) num4_str = string(num4,pad=4) cam = parse(Int,num4_str[1])/100 pos = parse(Int,num4_str[2])/10 t = parse(Int,num4_str[3:4])/100 NACA4(cam,pos,t,a...;kwargs...) end function _naca4(cam,pos,t,ds,len) # Here, cam is the fractional camber, pos is the fractional chordwise position # of max camber, and t is the fractional thickness. np = 200 npan = 2*np-2 # Trailing edge bunching an = 1.5 anp = an+1 x = zeros(np) θ = zeros(size(x)) yc = zeros(size(x)) for j = 1:np frac = Float64((j-1)/(np-1)) x[j] = 1 - anp*frac*(1-frac)^an-(1-frac)^anp; if x[j] < pos yc[j] = cam/pos^2*(2*pos*x[j]-x[j]^2) if pos > 0 θ[j] = atan(2*cam/pos*(1-x[j]/pos)) end else yc[j] = cam/(1-pos)^2*((1-2*pos)+2*pos*x[j]-x[j]^2) if pos > 0 θ[j] = atan(2*cam*pos/(1-pos)^2*(1-x[j]/pos)) end end end xu = zeros(size(x)) yu = xu xl = xu yl = yu yt = t/0.20*(0.29690*sqrt.(x)-0.12600*x-0.35160*x.^2+0.28430*x.^3-0.10150*x.^4) xu = x-yt.*sin.(θ) yu = yc+yt.*cos.(θ) xl = x+yt.*sin.(θ) yl = yc-yt.*cos.(θ) rt = 1.1019*t^2; θ0 = 0 if pos > 0 θ0 = atan(2*cam/pos) end # Center of leading edge radius xrc = rt*cos(θ0) yrc = rt*sin(θ0) θle = collect(0:π/50:2π) xlec = xrc .+ rt*cos.(θle) ylec = yrc .+ rt*sin.(θle) # Assemble data coords = [xu yu xl yl x yc] cole = [xlec ylec] # Close the trailing edge xpanold = [0.5*(xl[np]+xu[np]); reverse(xl[2:np-1],dims=1); xu[1:np-1]] ypanold = [0.5*(yl[np]+yu[np]); reverse(yl[2:np-1],dims=1); yu[1:np-1]] xpan = zeros(npan) ypan = zeros(npan) for ipan = 1:npan if ipan < npan xpan1 = xpanold[ipan] ypan1 = ypanold[ipan] xpan2 = xpanold[ipan+1] ypan2 = ypanold[ipan+1] else xpan1 = xpanold[npan] ypan1 = ypanold[npan] xpan2 = xpanold[1] ypan2 = ypanold[1] end xpan[ipan] = 0.5*(xpan1+xpan2) ypan[ipan] = 0.5*(ypan1+ypan2) end w = ComplexF64[1;reverse(xpan,dims=1)+im*reverse(ypan,dims=1)]*len w .-= mean(w) x̃end = real.(w) ỹend = imag.(w) x̃end, ỹend = _splined_body(hcat(x̃end,ỹend),ds,OpenBody) x̃, ỹ = _midpoints(x̃end,ỹend,ClosedBody) NACA4{length(x̃)}(len,cam,pos,t,(0.0,0.0),0.0,x̃,ỹ,x̃,ỹ,x̃end,ỹend,x̃end,ỹend) end function Base.show(io::IO, body::NACA4{N}) where {N} println(io, "NACA 4-digit airfoil with $N points and length $(body.len) and thickness $(body.thick)") println(io, " Current position: ($(body.cent[1]),$(body.cent[2]))") println(io, " Current angle (rad): $(body.α)") end #### function _adjustnumber(targetsize::Real,shapefcn::Type{T},params...;kwargs...) where {T <: Body} ntrial = 501 return floor(Int,ntrial*mean(dlength(shapefcn(params...,ntrial;kwargs...)))/targetsize) end for shape in (:Ellipse,:ThickPlate) @eval RigidBodyTools.$shape(params...;kwargs...) = $shape(Base.front(params)..., _adjustnumber(Base.last(params),$shape,Base.front(params)...;kwargs...);kwargs...) end
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
8622
### Tools ### import Base:diff, length export midpoints,dlength,normal,dlengthmid,centraldiff,normalmid,numpts, arccoord,arccoordmid,arclength # Evaluate some geometric details of a body """ length(body::Body) Return the number of points on the body perimeter """ length(::Body{N}) where {N} = N @deprecate length numpts for f in [:diff,:midpoints,:centraldiff] _f = Symbol("_"*string(f)) @eval $f(b::Body;axes=:inertial) = $_f(b,Val(axes)) @eval $_f(b::Body{N,C},::Val{:inertial}) where {N,C<:BodyClosureType} = $_f(b.xend,b.yend,C) @eval $_f(b::Body{N,C},::Val{:body}) where {N,C<:BodyClosureType} = $_f(b.x̃end,b.ỹend,C) @eval function $f(bl::BodyList;kwargs...) xl = Float64[] yl = Float64[] for b in bl xb, yb = $f(b;kwargs...) append!(xl,xb) append!(yl,yb) end return xl, yl end end """ diff(body::Body[;axes=:inertial]) -> Tuple{Vector{Float64},Vector{Float64}} Compute the x and y differences of the faces on the perimeter of body `body`, whose ends are at the current `x` and `y` coordinates (in inertial space) of the body (if `axes=:inertial`), or at the reference `x̃` and `ỹ` coordinates (body-fixed space) if `axes=:body`. Face 1 corresponds to the face between points 1 and 2, for example. If `body` is a `BodyList`, then it computes the differences separately on each constituent body. """ diff(::Body) """ diff(bl::BodyList[;axes=:inertial]) -> Tuple{Vector{Float64},Vector{Float64}} Compute the `diff` on each constituent body in `bl`. """ diff(::BodyList) function _diff(x::Vector{Float64},y::Vector{Float64},::Type{ClosedBody}) N = length(x) @assert N == length(y) dxtmp = circshift(x,-1) .- x dytmp = circshift(y,-1) .- y return dxtmp, dytmp end function _diff_ccw(x::Vector{Float64},y::Vector{Float64},::Type{ClosedBody}) N = length(x) @assert N == length(y) dxtmp = x .- circshift(x,1) dytmp = y .- circshift(y,1) return dxtmp, dytmp end function _diff(x::Vector{Float64},y::Vector{Float64},::Type{OpenBody}) @assert length(x) == length(y) return diff(x), diff(y) end """ midpoints(body::Body[;axes=:inertial]) -> Tuple{Vector{Float64},Vector{Float64}} Compute the x and y midpoints of the faces on the perimeter of body `body`, whose ends are at the current `x` and `y` coordinates (in inertial space) of the body (if `axes=:inertial`), or at the reference `x̃` and `ỹ` coordinates (body-fixed space) if `axes=:body`. Face 1 corresponds to the face between points 1 and 2, for example. If `body` is a `BodyList`, then it computes the differences separately on each constituent body. """ midpoints(::Body) """ midpoints(bl::BodyList[;axes=:inertial]) -> Tuple{Vector{Float64},Vector{Float64}} Compute the `midpoints` on each constituent body in `bl`. """ midpoints(::BodyList) function _midpoints(x::Vector{Float64},y::Vector{Float64},::Type{ClosedBody}) N = length(x) @assert N == length(y) xc = 0.5*(x .+ circshift(x,-1)) yc = 0.5*(y .+ circshift(y,-1)) return xc, yc end function _midpoints_ccw(x::Vector{Float64},y::Vector{Float64},::Type{ClosedBody}) N = length(x) @assert N == length(y) xc = 0.5*(x .+ circshift(x,1)) yc = 0.5*(y .+ circshift(y,1)) return xc, yc end function _midpoints(x::Vector{Float64},y::Vector{Float64},::Type{OpenBody}) @assert length(x) == length(y) xc = 0.5*(x[1:end-1]+x[2:end]) yc = 0.5*(y[1:end-1]+y[2:end]) return xc, yc end """ centraldiff(body::Body[;axes=:inertial]) -> Tuple{Vector{Float64},Vector{Float64}} Compute the circular central differences of coordinates on body `body` (or on each body in list `body`). If `axes=:body`, uses the reference coordinates in body-fixed space. """ centraldiff(::Body) """ centraldiff(bl::BodyList[;axes=:inertial]) -> Tuple{Vector{Float64},Vector{Float64}} Compute the `centraldiff` on each constituent body in `bl`. If `axes=:body`, uses the reference coordinates in body-fixed space. """ centraldiff(::BodyList) _centraldiff(x,y,C) = _diff(x,y,C) #= function _centraldiff(xend::Vector{Float64},yend::Vector{Float64},::Type{ClosedBody}) xc, yc = _midpoints(x,y,ClosedBody) xc .= circshift(xc,1) yc .= circshift(yc,1) return _diff(xend,yend,ClosedBody) end function _centraldiff(xend::Vector{Float64},yend::Vector{Float64},::Type{OpenBody}) xc, yc = _midpoints(x,y,OpenBody) dxc, dyc = _diff(xc,yc,OpenBody) return [xc[1]-x[1];dxc;x[end]-xc[end]], [yc[1]-y[1];dyc;y[end]-yc[end]] end =# """ dlength(body::Body/BodyList[;axes=:inertial]) -> Vector{Float64} Compute the lengths of the faces on the perimeter of body `body`, whose ends are at the current `xend` and `yend` coordinates (in inertial space) of the body. Face 1 corresponds to the face between endpoints 1 and 2, for example. If `axes=:body`, uses the reference coordinates in body-fixed space. """ function dlength(b::Union{Body,BodyList};kwargs...) dx, dy = diff(b;kwargs...) return sqrt.(dx.^2+dy.^2) end """ dlengthmid(body::Body/BodyList[;axes=:inertial]) -> Vector{Float64} Same as [`dlength`](@ref). """ dlengthmid(b::Union{Body,BodyList};kwargs...) = dlength(b;kwargs...) #= function dlengthmid(b::Union{Body,BodyList}) dx, dy = centraldiff(b) return sqrt.(dx.^2+dy.^2) end =# """ normal(body::Body/BodyList[;axes=:inertial]) -> Tuple{Vector{Float64},Vector{Float64}} Compute the current normals in inertial components (if `axes=:inertial`) or body- fixed components (if `axes=:body`) of the faces on the perimeter of body `body`, whose ends are at the current `xend` and `yend` coordinates (in inertial space) of the body. Face 1 corresponds to the face between points 1 and 2, for example. For an `OpenBody`, this provides a vector that is one element shorter than the number of points. """ function normal(b::Union{Body,BodyList};kwargs...) dx, dy = diff(b;kwargs...) ds = dlength(b) return dy./ds, -dx./ds end """ normalmid(body::Body/BodyList[;axes=:inertial]) -> Tuple{Vector{Float64},Vector{Float64}} Compute the current normals in inertial components (if `axes=:inertial`) or body- fixed components (if `axes=:body`) of the faces formed between endpoints on the perimeter of body `body` (or each body in list `body`). """ normalmid(b::Union{Body,BodyList};kwargs...) = normal(b;kwargs...) #= function normalmid(b::Union{Body,BodyList};kwargs...) dx, dy = centraldiff(b;kwargs...) ds = dlengthmid(b) return dy./ds, -dx./ds end =# """ arccoordmid(body::Body/BodyList[;axes=:inertial]) -> Vector{Float64} Returns a vector containing the arclength coordinate along the surface of `body`, evaluated at the midpoints between the ends of faces. So, e.g., the first coordinate would be half of the length of face 1, the second would be half of face 2 plus all of face 1, etc. Use inertial components (if `axes=:inertial`) or body- fixed components (if `axes=:body`). If this is a body list, restart the origin of the coordinates on each body in the list. """ function arccoordmid(b::Body;kwargs...) ds = dlength(b;kwargs...) s = 0.5*ds pop!(pushfirst!(ds,0.0)) s .+= accumulate(+,ds) return s end """ arccoord(body::Body/BodyList[;axes=:inertial]) -> Vector{Float64} Returns a vector containing the arclength coordinate along the surface of `body`, evaluated at the second endpoint of each face. So, e.g., the first coordinate would be the length of face 1, the second the length of face 2, and the last would be total length of all of the faces. Use inertial components (if `axes=:inertial`) or body-fixed components (if `axes=:body`). If this is a body list, restart the origin of the coordinates on each body in the list. """ function arccoord(b::Body;kwargs...) ds = dlength(b;kwargs...) s = accumulate(+,ds) return s end for f in [:arccoord,:arccoordmid] @eval function $f(bl::BodyList;kwargs...) sl = Float64[] for b in bl sb = $f(b;kwargs...) append!(sl,sb) end return sl end end """ arclength(body::Body[;axes=:inertial]) Compute the total arclength of `body`, from the sum of the lengths of the faces. If `axes=:body`, use the body-fixed coordinates. """ arclength(b::Body;kwargs...) = sum(dlength(b;kwargs...)) """ arclength(bl::BodyList[;axes=:inertial]) -> Vector{Float64} Compute the total arclength of each body in `bl` and assemble the results into a vector. If `axes=:body`, use the body-fixed coordinates. """ function arclength(bl::BodyList;kwargs...) [arclength(b;kwargs...) for b in bl] end
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
4406
using Statistics const MYEPS = 20*eps() @testset "Bodies" begin bn = nothing @test numpts(bn) == 0 p = Plate(1,100) dx, dy = diff(p) @test maximum(dx) ≈ minimum(dx) ≈ 0.01 @test maximum(dy) ≈ minimum(dy) ≈ 0.0 @test sum(dlength(p)) ≈ sum(dlengthmid(p)) c = Rectangle(1,2,400) dx, dy = diff(c) @test length(dx) == 400 @test sum(dlength(c)) ≈ 12.0 s = arccoord(c) @test s[end] ≈ 12.0 ≈ arclength(c) smid = arccoordmid(c) @test smid[1] > 0.0 && smid[end] < s[end] c = Square(1,0.01) @test isapprox(mean(dlength(c)),0.01,atol=1e-4) c = Ellipse(1,2,0.01) @test isapprox(mean(dlength(c)),0.01,atol=1e-4) c = Ellipse(1,2,100) nx, ny = normalmid(c) #@test nx[1] == ny[26] == -nx[51] == -ny[76] == 1.0 @test abs(sum(nx)) < 1000.0*eps(1.0) @test abs(sum(ny)) < 1000.0*eps(1.0) T = MotionTransform((1.0,-1.0),π/4) update_body!(c,T) nx2, ny2 = normalmid(c,axes=:body) @test sum(abs.(nx .- nx2)) < 1000.0*eps(1.0) @test sum(abs.(ny .- ny2)) < 1000.0*eps(1.0) end @testset "Null body" begin b1 = NullBody() @test numpts(b1) == 0 end @testset "Rectangle" begin b = Rectangle(0.5,1.0,60) nx0, ny0 = normalmid(b) @test all(isapprox.(nx0[1:10],0.0,atol=MYEPS)) && all(isapprox.(nx0[11:30],1.0,atol=MYEPS)) && all(isapprox.(nx0[31:40],0.0,atol=MYEPS)) && all(isapprox.(nx0[41:60],-1.0,atol=MYEPS)) @test all(isapprox.(ny0[1:10],-1.0,atol=MYEPS)) && all(isapprox.(ny0[11:30],0.0,atol=MYEPS)) && all(isapprox.(ny0[31:40],1.0,atol=MYEPS)) && all(isapprox.(ny0[41:60],0.0,atol=MYEPS)) ds = dlengthmid(b) @test all(ds .≈ 0.1) T = MotionTransform((1.0,-1.0),π/2) update_body!(b,T) T2 = MotionTransform((1,-1),π/2) update_body!(b,T2) nx, ny = normalmid(b) @test all(isapprox.(nx[1:10],1.0,atol=MYEPS)) && all(isapprox.(nx[11:30],0.0,atol=MYEPS)) && all(isapprox.(nx[31:40],-1.0,atol=MYEPS)) && all(isapprox.(nx[41:60],0.0,atol=MYEPS)) @test all(isapprox.(ny[1:10],0.0,atol=MYEPS)) && all(isapprox.(ny[11:30],1.0,atol=MYEPS)) && all(isapprox.(ny[31:40],0.0,atol=MYEPS)) && all(isapprox.(ny[41:60],-1.0,atol=MYEPS)) ds = dlengthmid(b) @test all(ds .≈ 0.1) T = MotionTransform((1.2,-1.5),π/4) update_body!(b,T) nx2, ny2 = normalmid(b,axes=:body) @test sum(abs.(nx0 .- nx2)) < 1000.0*eps(1.0) @test sum(abs.(ny0 .- ny2)) < 1000.0*eps(1.0) end @testset "Polygons" begin b = Polygon([1.0,1.0,0.0,0.0],[0.0,0.5,0.5,0.0],0.02) nx0, ny0 = normalmid(b) @test b.side[1] == 1:25 && b.side[2] == 26:75 && b.side[3] == 76:100 && b.side[4] == 101:150 @test all(isapprox.(nx0[b.side[1]],1.0,atol=MYEPS)) && all(isapprox.(nx0[b.side[2]],0.0,atol=MYEPS)) && all(isapprox.(nx0[b.side[3]],-1.0,atol=MYEPS)) && all(isapprox.(nx0[b.side[4]],0.0,atol=MYEPS)) @test all(isapprox.(ny0[b.side[1]],0.0,atol=MYEPS)) && all(isapprox.(ny0[b.side[2]],1.0,atol=MYEPS)) && all(isapprox.(ny0[b.side[3]],0.0,atol=MYEPS)) && all(isapprox.(ny0[b.side[4]],-1.0,atol=MYEPS)) ds = dlengthmid(b) @test all(ds .≈ 0.02) end @testset "Lists" begin bl = BodyList() @test numpts(bl) == 0 n1 = 101 n2 = 201 p = Plate(1,n1) c = Rectangle(1,2,n2) bl = BodyList([p,c]) @test length(bl) == 2 @test eltype(bl) == Body sl = arccoord(bl) @test sl[1:numpts(p)] == arccoord(p) @test sl[numpts(p)+1:numpts(bl)] == arccoord(c) t1 = MotionTransform((0.0,0.0),0.0) t2 = MotionTransform((1.0,0.0),π/2) tl = MotionTransformList([t1,t2]) push!(tl,t1) @test length(tl) == 3 @test eltype(tl) == MotionTransform v = rand(numpts(bl)) @test numpts(bl) == numpts(p)+numpts(c) @test v[1:numpts(p)] == view(v,bl,1) @test v[(numpts(p)+1):(numpts(p)+numpts(c))] == view(v,bl,2) tl = MotionTransformList([t1,t2]) update_body!(bl,tl) @test [bl[1].cent...] == translation(tl[1]) @test [bl[2].cent...] == translation(tl[2]) @test bl[1].α == RigidBodyTools._get_angle_of_2d_transform(tl[1]) @test bl[2].α == RigidBodyTools._get_angle_of_2d_transform(tl[2]) b1 = Rectangle(0.5,1.0,60) b2 = Rectangle(0.5,1.0,60) bl = BodyList() push!(bl,b1) push!(bl,b2) nx, ny = normalmid(bl) nxb1, nyb1 = normalmid(b1) nxb2, nyb2 = normalmid(b2) @test nx[1:60] == nxb1 && ny[1:60] == nyb1 && nx[61:120] == nxb2 && ny[61:120] == nyb2 end
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
2102
using RigidBodyTools using Literate using Test ENV["GKSwstype"] = "nul" # removes GKS warnings during plotting const GROUP = get(ENV, "GROUP", "All") macro mysafetestset(args...) name, expr = args quote ex = quote name_str = $$(QuoteNode(name)) expr_str = $$(QuoteNode(expr)) mod = gensym(name_str) ex2 = quote @eval module $mod using Test @testset $name_str $expr_str end nothing end eval(ex2) end eval(ex) end end notebookdir = "../examples" docdir = "../docs/src/manual" litdir = "./literate" for (root, dirs, files) in walkdir(litdir) if splitpath(root)[end] == "assets" for file in files cp(joinpath(root, file),joinpath(notebookdir,file),force=true) cp(joinpath(root, file),joinpath(docdir,file),force=true) cp(joinpath(root, file),joinpath(".",file),force=true) end end end if GROUP == "Transforms" include("transforms.jl") end if GROUP == "Bodies" include("bodies.jl") end if GROUP == "All" || GROUP == "Auxiliary" include("transforms.jl") include("bodies.jl") end if GROUP == "All" || GROUP == "Literate" for (root, dirs, files) in walkdir(litdir) for file in files global file_str = "$file" global body = :(begin include(joinpath($root,$file)) end) endswith(file,".jl") && @mysafetestset file_str body #endswith(file,".jl") && @testset "$file" begin include(joinpath(root,file)) end end end end if GROUP == "Notebooks" for (root, dirs, files) in walkdir(litdir) for file in files #endswith(file,".jl") && startswith(file,"surface") && Literate.notebook(joinpath(root, file),notebookdir) endswith(file,".jl") && Literate.notebook(joinpath(root, file),notebookdir) end end end if GROUP == "Documentation" for (root, dirs, files) in walkdir(litdir) for file in files endswith(file,".jl") && Literate.markdown(joinpath(root, file),docdir) end end end
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
7298
using LinearAlgebra @testset "Rotations" begin θ = rand() r = [0,0,1] R1 = rotation_about_z(θ) R2 = rotation_about_axis(θ,r) @test R1 ≈ R2 r = [0,1,0] R1 = rotation_about_y(θ) R2 = rotation_about_axis(θ,r) @test R1 ≈ R2 r = [1,0,0] R1 = rotation_about_x(θ) R2 = rotation_about_axis(θ,r) @test R1 ≈ R2 end @testset "Transforms" begin x = rand(3) @test cross_vector(cross_matrix(x)) ≈ x r = rand(2) Θ = 0.0 TM = MotionTransform(r,Θ) vA = rand(3) vB = TM*vA # Should give velocity based at origin of B @test vB ≈ vA .+ [0.0,-vA[1]*r[2],vA[1]*r[1]] TF = ForceTransform(r,Θ) fA = rand(3) fB = TF*fA # Should give moment about origin of B @test fB ≈ fA .- [r[1]*fA[3]-r[2]*fA[2],0.0,0.0] x2 = rand(2) Θ = rand() R2 = [cos(-Θ) -sin(-Θ); sin(-Θ) cos(-Θ)] TM2_1 = MotionTransform(x2,R2) TM2_2 = MotionTransform(x2,Θ) @test TM2_1 isa MotionTransform{2} @test TM2_1.matrix ≈ TM2_2.matrix TM3_1 = MotionTransform(rand(3),rotation_about_axis(rand(),rand(3))) TM3_2 = MotionTransform(rand(3),rotation_about_axis(rand(),rand(3))) @test TM3_1 isa MotionTransform{3} TM3_12 = TM3_1*TM3_2 @test TM3_12 isa MotionTransform @test MotionTransform(TM3_12.x,TM3_12.R).matrix ≈ TM3_12.matrix TM3_t = transpose(TM3_1) @test ForceTransform(TM3_t.x,TM3_t.R).matrix ≈ TM3_t.matrix TM2_1 = MotionTransform(rand(2),rotation_about_z(rand())) TM2_2 = MotionTransform(rand(2),rotation_about_z(rand())) @test TM2_1 isa MotionTransform{2} TM2_12 = TM2_1*TM2_2 @test TM2_12 isa MotionTransform @test MotionTransform{2}(TM2_12.x,TM2_12.R).matrix ≈ TM2_12.matrix TM2_t = transpose(TM2_1) @test ForceTransform{2}(TM2_t.x,TM2_t.R).matrix ≈ TM2_t.matrix TMinv = inv(TM) TMiTM = TMinv*TM @test isapprox(TMiTM.x,zeros(3),atol=1e-15) @test isapprox(TMiTM.R,I,atol=1e-15) @test isapprox(TMiTM.matrix,I,atol=1e-15) TMiTM = TM*TMinv @test isapprox(TMiTM.x,zeros(3),atol=1e-15) @test isapprox(TMiTM.R,I,atol=1e-15) @test isapprox(TMiTM.matrix,I,atol=1e-15) x = (rand(),rand()) θ = rand() TM = MotionTransform(x,θ) TR = RigidTransform(x,θ) x̃ = (rand(),rand()) @test TM(x̃...) == TR(x̃...) end @testset "Plucker vectors" begin vA = PluckerMotion(rand(3)) vAr = angular_only(vA) @test RigidBodyTools._get_angular_part(vA) === RigidBodyTools._get_angular_part(vAr) vAl = linear_only(vA) @test RigidBodyTools._get_linear_part(vA) === RigidBodyTools._get_linear_part(vAl) vA = PluckerMotion(rand(6)) vAr = angular_only(vA) @test RigidBodyTools._get_angular_part(vA) === RigidBodyTools._get_angular_part(vAr) vAl = linear_only(vA) @test RigidBodyTools._get_linear_part(vA) === RigidBodyTools._get_linear_part(vAl) x = (rand(),rand()) θ = rand() TM = MotionTransform(x,θ) vA = PluckerMotion(rand(3)) TM*vA vA = PluckerForce(rand(3)) vAr = angular_only(vA) @test RigidBodyTools._get_angular_part(vA) === RigidBodyTools._get_angular_part(vAr) vAl = linear_only(vA) @test RigidBodyTools._get_linear_part(vA) === RigidBodyTools._get_linear_part(vAl) vA = PluckerForce(rand(6)) vAr = angular_only(vA) @test RigidBodyTools._get_angular_part(vA) === RigidBodyTools._get_angular_part(vAr) vAl = linear_only(vA) @test RigidBodyTools._get_linear_part(vA) === RigidBodyTools._get_linear_part(vAl) x = (rand(),rand()) θ = rand() TM = ForceTransform(x,θ) vA = PluckerForce(rand(3)) TM*vA TM*angular_only(vA) TM*linear_only(vA) TM = MotionTransform(x,θ) vA = PluckerMotion{2}(angular=1) vB = PluckerMotion([1,2,3]) @test TM*angular_only(vA) == TM*angular_only(vB) vA = PluckerMotion{2}(linear=[2,3]) @test TM*linear_only(vA) == TM*linear_only(vB) TM = MotionTransform(rand(3),rotation_about_axis(rand(),rand(3))) vA = PluckerMotion{3}(angular=[1,2,3]) vB = PluckerMotion([1,2,3,4,5,6]) @test TM*angular_only(vA) == TM*angular_only(vB) vA = PluckerMotion{3}(linear=[4,5,6]) @test TM*linear_only(vA) == TM*linear_only(vB) vA = PluckerMotion(rand(3)) fA = PluckerForce(rand(3)) @test dot(angular_only(fA),vA) == dot(fA,angular_only(vA)) == dot(angular_only(vA),fA) == dot(vA,angular_only(fA)) @test dot(linear_only(fA),vA) == dot(fA,linear_only(vA)) == dot(linear_only(vA),fA) == dot(vA,linear_only(fA)) vA = PluckerMotion(rand(6)) fA = PluckerForce(rand(6)) @test dot(angular_only(fA),vA) == dot(fA,angular_only(vA)) == dot(angular_only(vA),fA) == dot(vA,angular_only(fA)) @test dot(linear_only(fA),vA) == dot(fA,linear_only(vA)) == dot(linear_only(vA),fA) == dot(vA,linear_only(fA)) end @testset "Linked systems" begin Xp_to_j1 = MotionTransform(0.0,0.0,0.0) Xch_to_j1 = MotionTransform(-0.5,0.0,0.0) Xp_to_j2 = MotionTransform(1.02,0.0,0.0) Xch_to_j2 = MotionTransform(-1.02,0.0,0.0) Xp_to_j3 = MotionTransform(-5.0,0.0,0.0) Xch_to_j3 = MotionTransform(-0.5,0.0,0.0) dofs1 = [OscillatoryDOF(π/4,2π,0.0,0.0),ConstantPositionDOF(0.0),OscillatoryDOF(1.0,2π,-π/2,0.0)] #dofs11 = [OscillatoryDOF(π/4,2π,0.0,0.0),UnconstrainedDOF(),ExogenousDOF()] #dofs12 = [OscillatoryDOF(π/4,2π,π/3,0.0),ConstantPositionDOF(0.0),ExogenousDOF()] dofs2 = [OscillatoryDOF(π/4,2π,π/4,0.0)] dofs3 = [OscillatoryDOF(π/4,2π,π/2,0.0)] dofs4 = [ConstantVelocityDOF(0)] joint1 = Joint(FreeJoint2d,0,Xp_to_j1,1,Xch_to_j1,dofs1) joint2 = Joint(RevoluteJoint,1,Xp_to_j2,2,Xch_to_j2,dofs2) joint3 = Joint(RevoluteJoint,2,Xp_to_j2,3,Xch_to_j2,dofs3) joint4 = Joint(RevoluteJoint,2,Xp_to_j2,4,Xch_to_j2,dofs4) joint5 = Joint(FreeJoint2d,0,Xp_to_j3,5,Xch_to_j3,dofs1) joint6 = Joint(RevoluteJoint,5,Xp_to_j2,6,Xch_to_j2,dofs4) @test ismoving(joint3) @test !ismoving(joint4) joints = [joint2,joint6,joint3,joint4,joint5,joint1] body1 = Ellipse(1.0,0.2,200) body2 = deepcopy(body1) body3 = deepcopy(body1) body4 = deepcopy(body1) body5 = deepcopy(body1) body6 = deepcopy(body1) bl = BodyList([body1,body2,body3,body4,body5,body6]) ls = RigidBodyMotion(joints,bl) lsid = 1 # this system should be internally in motion @test is_system_in_relative_motion(lsid,ls) lsid = 2 # this system should be internally fixed @test !is_system_in_relative_motion(lsid,ls) ufcn(x,y,t) = 0.25*2π*x*y*cos(2π*t) vfcn(x,y,t) = 0.25*2π*(x^2-y^2)*cos(2π*t) def = DeformationMotion(ufcn,vfcn) X = MotionTransform([0,0],0) joint = Joint(X) ls = RigidBodyMotion(joint,body1,def) @test ismoving(ls) defs = AbstractDeformationMotion[NullDeformationMotion(), NullDeformationMotion(), NullDeformationMotion(), NullDeformationMotion(), def, NullDeformationMotion()] ls = RigidBodyMotion(joints,bl,defs) lsid = 2 # now this system is no longer internally fixed, because body 5 deforms @test is_system_in_relative_motion(lsid,ls) x = init_motion_state(bl,ls) Xl = body_transforms(x,ls) X1_to_2 = rebase_from_inertial_to_reference(Xl[2],x,ls,1) X0_to_2 = X1_to_2*Xl[1] @test X0_to_2.x ≈ Xl[2].x && X0_to_2.R ≈ Xl[2].R X1_to_4 = rebase_from_inertial_to_reference(Xl[4],x,ls,1) X0_to_4 = X1_to_4*Xl[1] @test X0_to_4.x ≈ Xl[4].x && X0_to_4.R ≈ Xl[4].R end
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
2053
# # Lists of bodies and their transforms #md # ```@meta #md # CurrentModule = RigidBodyTools #md # ``` #= We might want to have several distinct bodies. Here, we discuss how to combine bodies into lists, and similarly, their transforms. =# using RigidBodyTools using Plots #= ## Body list Suppose we have two bodies and we wish to combine them into a single list. The advantage of doing so is that many of the operations we have presented previously also extend to lists. We use `BodyList` to combine them. =# b1 = Circle(1.0,0.02) b2 = Rectangle(1.0,2.0,0.02) bl = BodyList([b1,b2]) #= Another way to do this is to push each one onto the list: =# bl = BodyList() push!(bl,b1) push!(bl,b2) #= We can transform the list by creating a list of transforms with a `MotionTransformList` =# X1 = MotionTransform([2.0,3.0],0.0) X2 = MotionTransform([-2.0,-0.5],π/4) tl = MotionTransformList([X1,X2]) #= The transform list can be applied to the whole body list simply with =# tl(bl) #= which creates a copy of the body list and transforms that, or =# update_body!(bl,tl) #= which updates each body in `bl` in place. =# #= Let's see our effect =# plot(bl) #= It is important to note that the list points to the original bodies, so that any change made to the list is reflected in the original bodies, e.g. =# plot(b2) #= ## Utilities on lists There are some specific utilities that are helpful for lists. For example, to collect all of the x, y points (the segment midpoints) in the list into two vectors, use =# x, y = collect(bl) #= In a vector comprising data on these concatenated surface points, we can use `view` to look at just one body's part and change it: =# f = zero(x) f1 = view(f,bl,1) f1 .= 1.0; plot(f) #= Also, we can sum up the values for one of the bodies: =# sum(f,bl,2) #md # ## Body and transform list functions #md # ```@docs #md # BodyList #md # getrange #md # Base.collect(::BodyList) #md # Base.sum(::AbstractVector,::BodyList,::Int) #md # Base.view(::AbstractVector,::BodyList,::Int) #md # MotionTransformList #md # ```
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
4775
# # Deforming bodies #md # ```@meta #md # CurrentModule = RigidBodyTools #md # ``` #= Thus far we have only shown rigid body motion. However, we can also prescribe surface deformation as an additional component of a body's motion. =# using RigidBodyTools using Plots #= Before we get started, let's define the same macro that we used earlier in order to visualize our system's motion =# macro animate_motion(b,m,dt,tmax,xlim,ylim) return esc(quote bc = deepcopy($b) t0, x0 = 0.0, init_motion_state(bc,$m) dxdt = zero(x0) x = copy(x0) @gif for t in t0:$dt:t0+$tmax motion_rhs!(dxdt,x,($m,bc),t) global x += dxdt*$dt update_body!(bc,x,$m) plot(bc,xlims=$xlim,ylims=$ylim) end every 5 end) end #= For deforming bodies, we specify the velocity of the surface directly. This deformation velocity is expressed in the coordinate system attached to the body, rather than the inertial coordinate system. This enables the motion to be easily superposed with the rigid-body motion described earlier. It is also important to note that the motion is applied **to the endpoints** of the surface segments. The midpoints are then constructed from the updated endpoints. =# #= ## Example: Basic deformation Let's see an example. We will create an oscillatory deformation of a circle. We create the motion by creating functions for each component of velocity. =# Ω = 2π ufcn(x,y,t) = 0.25*x*y*Ω*cos(Ω*t) vfcn(x,y,t) = 0.25*(x^2-y^2)*Ω*cos(Ω*t) def = DeformationMotion(ufcn,vfcn) #= We will create a simple fixed revolute joint that anchors the body's center to the inertial system. (Note that we don't need to create a body list here, since we are only working with one body and one joint.) =# Xp_to_jp = MotionTransform(0.0,0.0,0.0) Xc_to_jc = MotionTransform(0.0,0.0,0.0) dofs = [ConstantVelocityDOF(0.0)] joint = Joint(RevoluteJoint,0,Xp_to_jp,1,Xc_to_jc,dofs) body = Circle(1.0,0.02) #= To construct the system, we supply the joint and body, as before, as well as the deformation. =# ls = RigidBodyMotion(joint,body,def) #= Let's animate this motion =# @animate_motion body ls 0.01 4 (-2,2) (-2,2) #= The body remains fixed, but the surface deforms! =# #= ## Example: Expanding motion Now a circle undergoing an expansion. For this, we set constant velocity components equal to constants, the coordinates of the surface segment endpoints =# body = Circle(1.0,0.02) u = copy(body.x̃end) v = copy(body.ỹend) def = ConstantDeformationMotion(u,v) ls = RigidBodyMotion(joint,body,def) @animate_motion body ls 0.01 2 (-5,5) (-5,5) #= ## Example: Combining rigid motion and deforming motion. Now, let's combine an oscillatory rigid-body rotation with oscillatory deformation, this time applied to a square. =# Xp_to_jp = MotionTransform(0.0,0.0,0.0) Xc_to_jc = MotionTransform(0.0,0.0,0.0) Ω = 1.0 dofs = [OscillatoryDOF(π/4,Ω,0.0,0.0)] joint = Joint(RevoluteJoint,0,Xp_to_jp,1,Xc_to_jc,dofs) body = Square(1.0,0.02) ufcn(x,y,t) = 0.25*(x^2+y^2)*y*Ω*cos(Ω*t) vfcn(x,y,t) = -0.25*(x^2+y^2)*x*Ω*cos(Ω*t) def = DeformationMotion(ufcn,vfcn) ls = RigidBodyMotion(joint,body,def) @animate_motion body ls π/100 4π (-2,2) (-2,2) #= ## Example: Defining new deformations We can also define new types of deformation that are more specialized. We need only define a subtype of `AbstractDeformationMotion` and extend the function `deformation_velocity` to work with it. The signature of this function is `deformation_velocity(body,deformation,time)`. For example, let's define a motion on a rectangular shape that will deform only the top side in the normal direction, but leave the rest of the surface stationary. We will use the `side` field of the `Polygon` shape type to access the top, and set its vertical velocity. =# struct TopMotion{UT} <: AbstractDeformationMotion vtop :: UT end function RigidBodyTools.deformation_velocity(body::Polygon,def::TopMotion,t::Real) u, v = zero(body.x̃end), zero(body.ỹend) top = body.side[3] v[top] .= def.vtop.(body.x̃end[top],body.ỹend[top],t) return vcat(u,v) end #= Now apply it =# Xp_to_jp = MotionTransform(0.0,0.0,0.0) Xc_to_jc = MotionTransform(0.0,0.0,0.0) dofs = [ConstantVelocityDOF(0.0)] joint = Joint(RevoluteJoint,0,Xp_to_jp,1,Xc_to_jc,dofs) body = Rectangle(1.0,2.0,0.02) vfcn(x,y,t) = 0.2*(1-x^2)*cos(t) def = TopMotion(vfcn) ls = RigidBodyMotion(joint,body,def) #= Let's try it out =# @animate_motion body ls π/100 4π (-1.5,1.5) (-2.5,2.5) #= As desired, the top surface deforms vertically, but the rest of the surface is stationary. =# #md # ## Deformation functions #md # ```@docs #md # DeformationMotion #md # ConstantDeformationMotion #md # ```
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
4275
# # Behaviors of degrees of freedom #md # ```@meta #md # CurrentModule = RigidBodyTools #md # ``` #= To define the motion of a joint requires that we define the behavior of each of the joint's degrees of freedom. There are three different types of behavior of a degree of freedom: (1) Its motion is prescribed with a given function of time, in which case we say that the degree of freedom is *constrained* (2) Its motion is specified directly, but determined by a process that lies outside of the body system, in which case we say the degree of freedom is *exogenous*. (3) Its motion is determined indirectly by some sort of force model for its behavior, such as a spring or damper, in which case we say the degree of freedom is *unconstrained*. Here, we will discuss how to set a degree of freedom with one of these behaviors, and how to set the prescribed motion, if desired. =# using RigidBodyTools using Plots #= ## Constrained behavior (i.e., prescribed motion) When a degree of freedom is constrained, then its behavior over time is set by some time-varying function. There are a number of different types of predefined time-varying behaviors. =# #= ### Constant velocity To specify constant velocity with some velocity, e.g. $U=1$, set =# U = 1.0 k = ConstantVelocityDOF(U) #= For any prescribed motion, we can evaluate it at any specified time. It returns data of type `DOFKinematicData`. =# t = 1.0 kt = k(t) #= The kinematic data can be parsed with `dof_position`, `dof_velocity`, and `dof_acceleration`: =# dof_position(kt) #- dof_velocity(kt) #- dof_acceleration(kt) #= Let's plot the position over time =# t = range(0,3,length=301) plot(t,dof_position.(k.(t)),xlims=(0,Inf),ylims=(0,Inf)) #= ### Oscillatory motion We can set the position to be a sinusoidal function. For this, we set the amplitude, the angular frequency, the phase, and the mean velocity (typically zero). =# A = 1.0 ## amplitude Ω = 2π ## angular frequency ϕ = π/2 ## phase vel = 0 ## mean velocity k = OscillatoryDOF(A,Ω,ϕ,vel) #= Plot the position, velocity, and acceleration =# plot(t,dof_position.(k.(t)),xlims=(0,Inf),label="x") plot!(t,dof_velocity.(k.(t)),label="ẋ") plot!(t,dof_acceleration.(k.(t)),label="ẍ") #= ### Smooth ramp motion To ramp the position from one value to another, we use the `SmoothRampDOF`. For this, we need to specify the nominal velocity of the ramp, the change in position, and the time at which the ramp starts. There is an optional argument `ramp` to control the ramp's smoothness. It defaults to `EldredgeRamp(11.0)`, an Eldredge-type ramp with smoothness factor 11. =# vel = 1.0 ## nominal ramp velocity Δx = 1.0 ## change in position t0 = 1.0 ## time of ramp start k = SmoothRampDOF(vel,Δx,t0) #= Plot the position =# plot(t,dof_position.(k.(t)),xlims=(0,Inf),label="x") #= We can also ramp up the velocity from one value to another, using `SmoothVelocityRampDOF`. For example, =# u1 = 1.0 ## initial velocity u2 = 2.0 ## final velocity acc = 1.0 ## nominal acceleration of the ramp t0 = 1.0 ## time of ramp start k = SmoothVelocityRampDOF(acc,u1,u2,t0) #= Plot the velocity =# plot(t,dof_velocity.(k.(t)),xlims=(0,Inf),label="u") #= and the position =# plot(t,dof_position.(k.(t)),xlims=(0,Inf),label="x") #= ### User-defined motion The user can specify the time-varying position by supplying a function of time and using `CustomDOF`. It automatically differentiates this function to get velocity and acceleration. For example, a quadratic behavior =# f(t) = 1.0*t + 2.0*t^2 k = CustomDOF(f) #= Plot the position =# plot(t,dof_position.(k.(t)),xlims=(0,Inf),label="x") #= and the velocity =# plot(t,dof_velocity.(k.(t)),xlims=(0,Inf),label="ẋ") #= and the acceleration =# plot(t,dof_acceleration.(k.(t)),xlims=(0,Inf),label="ẍ") #= ## Exogenous and unconstrained behaviors If the degree of freedom is to be *exogenous* or *unconstrained*, then it can be designated as such, e.g, =# k = ExogenousDOF() #= or =# k = UnconstrainedDOF() #md # ## Degree of freedom functions #md # ```@docs #md # ConstantVelocityDOF #md # OscillatoryDOF #md # SmoothRampDOF #md # SmoothVelocityRampDOF #md # CustomDOF #md # ExogenousDOF #md # UnconstrainedDOF #md # dof_position #md # dof_velocity #md # dof_acceleration #md # ```
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
3838
# # Exogenous degrees of freedom #md # ```@meta #md # CurrentModule = RigidBodyTools #md # ``` #= As we mentioned in previous pages, some degrees of freedom can be designated as *exogenous*, meaning that their behavior is determined by some external process that we do not model explicitly. In practice, that means that the acceleration of such a degree of freedom must by explicitly provided at every time step while the state vector is being advanced. =# using RigidBodyTools using Plots #= As usual, we will demonstrate this via an example. In the example, a single flat plate will be commanded to pitch upward by 45 degrees about its leading edge. It will move steadily in the +x direction. However, its y acceleration will vary randomly via some exogenous process. =# Xp_to_jp = MotionTransform(0.0,0.0,0.0) Xc_to_jc = MotionTransform(0.5,0.0,0.0) dofs = [SmoothRampDOF(0.4,π/4,0.5),ConstantVelocityDOF(1.0),ExogenousDOF()] joint = Joint(FreeJoint2d,0,Xp_to_jp,1,Xc_to_jc,dofs) body = ThickPlate(1.0,0.05,0.02) #= We need to provide a means of passing along the time-varying information about the exogenous acclerations to the time integrator. There are two ways we can do this. =# #= #### Method 1: A function for exogenous acclerations. We can provide a function that will specify the exogenous y acceleration. Here, we will create a function that sets it to a random value chosen from a normal distribution. Note that the function must be mutating and have a signature `(a,x,p,t)`, where `a` is the exogenous acceleration vector. The arguments `x` and `p` are a state and a parameter, which can be flexibly defined. Here, the *state* is the rigid-body system state and the *parameter* is the `RigidBodyMotion` structure. The last argument `t` is time. In this example, we don't need any of those arguments. =# function my_exogenous_function!(a,x,ls,t) a .= randn(length(a)) end #= We pass that along via the `exogenous` keyword argument. =# ls = RigidBodyMotion(joint,body;exogenous=my_exogenous_function!) #= #### Method 2: Setting the exogenous accelerations explicitly in the loop Another approach we can take is to set the exogenous acceleration(s) explicitly in the loop, using the `update_exogenous!` function. This function saves the vector of accelerations in a buffer in the `RigidBodyMotion` structure so that it is available to the time integrator. We will demonstrate that approach here. =# ls = RigidBodyMotion(joint,body) #= Let's initialize the state vector and its rate of change =# bc = deepcopy(body) dt, tmax = 0.01, 3.0 t0, x0 = 0.0, init_motion_state(bc,ls) dxdt = zero(x0) x = copy(x0) #= Note that the state vector has four elements. The first two are associated with the prescribed motions for rotation and x translation. The third is the y position, the exogenous degree of freedom. And the fourth is the y velocity. Why the y velocity? Because the exogenous behavior is specified via its acceleration. Let's advance the system and animate it. We include a horizontal line along the hinge axis to show the effect of the exogenous motion. =# xhist = [] a_edof = zero_exogenous(ls) @gif for t in t0:dt:t0+tmax a_edof .= randn(length(a_edof)) update_exogenous!(ls,a_edof) motion_rhs!(dxdt,x,(ls,bc),t) global x += dxdt*dt update_body!(bc,x,ls) push!(xhist,copy(x)) plot(bc,xlims=(-1,5),ylims=(-1.5,1.5)) hline!([0.0]) end every 5 #= Let's plot the exogenous state and its velocity =# plot(t0:dt:t0+tmax,map(x -> exogenous_position_vector(x,ls,1)[1],xhist),label="y position",xlabel="t") plot!(t0:dt:t0+tmax,map(x -> exogenous_velocity_vector(x,ls,1)[1],xhist),label="y velocity") #= The variation in velocity is quite noisy (and constitutes a random walk). In contrast, the change in position is relatively smooth, since it represents an integral of this velocity. =#
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
11534
# # Joints and body-joint systems #md # ```@meta #md # CurrentModule = RigidBodyTools #md # ``` #= For systems consisting of one or more rigid bodies, *joints* are used to specify the degrees of freedom permitted for the body. Even for a single rigid body, the body is assumed to be connected by a joint with the inertial coordinate system. In three dimensions, there are several different classes of joint: - `RevoluteJoint`, which rotates about an axis and has only one degree of freedom - `PrismaticJoint`, which slides along one axis and has only one degree of freedom - `HelicalJoint`, which rotates about and slides along one axis (two degrees of freedom) - `SphericalJoint`, which rotates freely about one point (three degrees of freedom) - `FreeJoint`, which can move in any manner (six degrees of freedom) However, in two spatial dimensions, there are only two - `RevoluteJoint` (one degree of freedom: rotation) - `FreeJoint2d` (three degrees of freedom: rotation, two translation) =# using RigidBodyTools using Plots #= A joint serves as a connection between two bodies; one of the bodies is the *parent* and the other is the *child*. It is also common for a body to be connected to the inertial coordinate system, in which case the inertial system is the parent and the body is the child. The user must specify the id of the parent body and the child body. The id of the inertial system is 0. Before we discuss how a joint is specified, it is important to understand that a joint is basically just an intermediate `MotionTransform` from the parent body's system to the child body's system. That is, to construct the transform from body P to body C, we would compose it as follows $${}^C X_{P} = {}^{C}X_{J(C)} {}^{J(C)}X_{J(P)} {}^{J(P)}X_{P}$$ The transform in the middle is the joint transform and is the only one of these that can vary in time. It maps from one coordinate system attached (rididly) to the parent body to another coordinate system attached (rigidly) to the child body. The degrees of freedom of the joint constrain the behavior of this joint transform. Below, we show how joints are constructed and used. =# #= ## Joint construction generalities The user must specify where the joint is located on each body, relative to the origin of the body's coordinate system, and what orientation the joint takes with respect to the body's coordinate system. These are specified with `MotionTransform`s, transforming from each body's coordinate system to the joint's coordinate system on that body. This transform is invariant -- it never changes. Also, the user must specify the behavior of each of the degrees of freedom of a joint, using the tools we discussed in the previous page. The basic signature is `Joint(joint_type,parent_body_id,Xp_to_jp,child_body_id,Xc_to_jc,doflist)` However, there is a specialized signature if you simply wish to place a body in some stationary configuration `X`: `Joint(X,body_id)` and if there is only one body and it is stationary, then `Joint(X)` will do. =# #= ## Example Let's see a 2d example. Suppose we have two bodies, 1 and 2. Body 1 is to be connected to the inertial coordinate system, and prescribed with motion that causes it to oscillate rotationally (*pitch*) about a point located at $(-1,0)$ and in the body's coordinate system, and this pitch axis can oscillate up and down (*heave*). Body 2 is to be connected by a hinge to body 1, and this hinge's angle will also oscillate. We will set the hinge to be located at $(1.02,0)$ on body 1 and $(-1.02,0)$ on body 2. =# #= ### Joint from inertial system to body 1 First, let's construct the joint from the inertial system to body 1. This should be a `FreeJoint2d`, since motion is prescribed in two of the three degrees of freedom (as well as the third one, with zero velocity). We can assume that the joint is attached to the origin of the parent (the inertial system). On the child (body 1), the joint is to be at `[-1,0]`. =# pid = 0 Xp_to_jp = MotionTransform([0,0],0) cid = 1 Xc_to_jc = MotionTransform([-1,0],0) #= For the rotational and the y degrees of freedom, we need oscillatory motion. For the rotational motion, let's set the amplitude to $\pi/4$ and the angular frequency to $\Omega = 2\pi$, but set the phase and mean velocity both to zero. =# Ar = π/4 Ω = 2π ϕr = 0.0 vel = 0.0 kr = OscillatoryDOF(Ar,Ω,ϕr,vel) #= For the plunging, we will set an amplitude of 1 and a phase lag of $\pi/2$, but keep the same frequency as the pitching. =# Ay = 1 ϕy = -π/2 ky = OscillatoryDOF(Ay,Ω,ϕy,vel) #= The x degree of freedom is simply constant velocity, set to 0, to ensure it does not move in the $x$ direction. =# kx = ConstantVelocityDOF(0) #- #= We put these together into a vector, to pass along to the joint constructor. The ordering of these in the vector is important. It must be [rotational, x, y]. =# dofs = [kr,kx,ky]; #= Now set the joint =# joint1 = Joint(FreeJoint2d,pid,Xp_to_jp,cid,Xc_to_jc,dofs) #= Note that this joint has three constrained degrees of freedom, no exogenous degrees of freedom, and no unconstrained degrees of freedom. In a later example, we will change this. =# #= ### Joint from body 1 to body 2 This joint is a `RevoluteJoint`. First set the joint locations on each body. =# pid = 1 Xp_to_jp = MotionTransform([1.02,0],0) cid = 2 Xc_to_jc = MotionTransform([-1.02,0],0) #= Now set its single degree of freedom (rotation) to have oscillatory kinematics. We will set its amplitude the same as before, but give it a phase lag =# Ar = π/4 Ω = 2π ϕr = -π/4 kr = OscillatoryDOF(Ar,Ω,ϕr,vel) #= Put it in a one-element vector. =# dofs = [kr]; #= and construct the joint =# joint2 = Joint(RevoluteJoint,pid,Xp_to_jp,cid,Xc_to_jc,dofs) #= Group the two joints together into a vector. It doesn't matter what order this vector is in, since the connectivity will be figured out any way it is ordered, but it numbers the joints by the order they are provided here. =# joints = [joint1,joint2]; #= ## Assembling the joints and bodies The joints and bodies comprise an overall `RigidBodyMotion` system. When this system is constructed, all of the connectivities are determined (or missing connectivities are revealed). The construction requires that we have set up the bodies themselves, so let's do that first. We will make both body 1 and body 2 an ellipse of aspect ratio 5. Note that ordering of bodies matters here, because the first in the list is interpreted as body 1, etc. =# b1 = Ellipse(1.0,0.2,0.02) b2 = Ellipse(1.0,0.2,0.02) bodies = BodyList([b1,b2]) #= Now we can construct the system =# ls = RigidBodyMotion(joints,bodies) #= Before we proceed, it is useful to demonstrate some of the tools we have to probe the connectivity of the system. For example, to find the parent joint of body 1, we use =# parent_joint_of_body(1,ls) #= This returns 1, since we have connected body 1 to joint 1. How about the child joint of body 1? We expect it to be 2. Since there might be more than one child, this returns a vector: =# child_joints_of_body(1,ls) #= We can also check the body connectivity of joints. This can be very useful for more complicated systems in which the joint numbering is less clear. The parent body of joint 1 =# parent_body_of_joint(1,ls) #= This returns 0 since we have connected joint 1 to the inertial system. The child body of joint 2: =# child_body_of_joint(2,ls) #= ## The system state vector A key concept in advancing, plotting, and doing further analysis of this system of joints and bodies is the *state vector*, $x$. This state vector has entries for the position of every degree of freedom of all of the joints. It also may have further entries for other quantities that need to be advanced, but for this example, there are no other entries. There are two functions that are useful for constructing the state vector. The first is `zero_motion_state`, which simply creates a vector of zeros of the correct size. =# zero_motion_state(bodies,ls) #= The second is `init_motion_state`, which fills in initial position values for any degrees of freedom that have been prescribed. =# x = init_motion_state(bodies,ls) #= Note that neither of these functions has any mutating effect on the arguments (`bodies` and `ls`). Also, it is always possible for the user to modify the entries in the state vector after this function is called. In general, it would be difficult to determine which entry is which in this state vector, so we can use a special function for this. For example, to get access to just the part of the state vector for the positions of joint 1, =# jid = 1 x1 = position_vector(x,ls,jid) #= This is a view on the overall state vector. This, if you decide to change an entry of `x1`, this, in turn, would change the correct entry in `x`. =# #= We can use the system state vector to put the bodies in their proper places, using the joint positions in `x`. =# update_body!(bodies,x,ls) #= Let's plot this just to check =# plot(bodies,xlims=(-4,4),ylims=(-4,4)) #= ## Advancing the state vector Once the initial state vector is constructed, then the system can be advanced in time. In this example, there are no exogenous or unconstrained degrees of freedom that require extra input, so the system is *closed* as it is. To advance the system, we need to solve the system of equations $$\frac{\mathrm{d}x}{\mathrm{d}t} = f(x,t)$$ The function $f(x,t)$ describing the rate of change of $x$ is given by the function `motion_rhs!`. This function mutates its first argument, the rate-of-change vector `dxdt`, which can then be used to update the state. The system and bodies are passed in as a tuple, followed by time. Using a simple forward Euler method, the state vector can be advanced as follows =# t0, x0 = 0.0, init_motion_state(bodies,ls) dxdt = zero(x0) x = copy(x0) dt, tmax = 0.01, 4.0 for t in t0:dt:t0+tmax motion_rhs!(dxdt,x,(ls,bodies),t) global x += dxdt*dt end #= Now that we know how to advance the state vector, let's create a macro that can be used to make a movie of the evolving system. =# macro animate_motion(b,m,dt,tmax,xlim,ylim) return esc(quote bc = deepcopy($b) t0, x0 = 0.0, init_motion_state(bc,$m) dxdt = zero(x0) x = copy(x0) @gif for t in t0:$dt:t0+$tmax motion_rhs!(dxdt,x,($m,bc),t) global x += dxdt*$dt update_body!(bc,x,$m) plot(bc,xlims=$xlim,ylims=$ylim) end every 5 end) end #= Let's use it here =# @animate_motion bodies ls 0.01 4 (-4,4) (-4,4) #md # ## Joint functions #md # ```@docs #md # Joint #md # zero_joint #md # init_joint #md # ``` #md # ## System and state functions #md # ```@docs #md # RigidBodyMotion #md # zero_motion_state #md # init_motion_state #md # Base.view(::AbstractVector,::RigidBodyMotion,::Int) #md # position_vector #md # velocity_vector #md # deformation_vector #md # exogenous_position_vector #md # exogenous_velocity_vector #md # unconstrained_position_vector #md # unconstrained_velocity_vector #md # body_transforms #md # motion_transform_from_A_to_B #md # force_transform_from_A_to_B #md # body_velocities #md # motion_rhs! #md # zero_exogenous #md # update_exogenous! #md # maxvelocity #md # ismoving(::RigidBodyMotion) #md # is_system_in_relative_motion #md # rebase_from_inertial_to_reference #md # ``` #md # ## Joint types #md # ```@docs #md # RevoluteJoint #md # PrismaticJoint #md # HelicalJoint #md # SphericalJoint #md # FreeJoint #md # FreeJoint2d #md # ```
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
4842
# # Creating bodies #md # ```@meta #md # CurrentModule = RigidBodyTools #md # ``` #= The most basic functions of this package create an object of type `Body`. There are a variety of such functions, a few of which we will demonstrate here. Generally speaking, we are interesting in creating the object and placing it in a certain position and orientation. We do this in two steps: we create the basic shape, centered at the origin with a default orientation, and then we transform the shape to a desired location and orientation. We will discuss the shapes in this notebook, and the transforms in the following notebook. It is useful to stress that each body stores two types of points internally: the *endpoints* of the segments that comprise the body surface, and the *midpoints* of these segments. The midpoints are intended for use in downstream calculations, e.g. as forcing points in the calculations on immersed layers. The midpoints are simply the geometric averages of the endpoints, so endpoints are the ones that are transformed first, and midpoints are updated next. =# using RigidBodyTools using Plots #= ## Creating a shape Let's first create a shape. For any shape, we have to make a choice of the geometric dimensions (e.g, radius of the circle, side lengths of a rectangle), as well as the points that we use to discretely represent the surface. For this latter choice, there are two constructor types: we can specify the number of points (as an integer), or we can specify the nominal spacing between points (as a floating-point number). The second approach is usually preferable when we use these tools for constructing immersed bodies. It is important to stress that the algorithms for placing points attempt to make the spacing as uniform as possible. Let's create the most basic shape, a circle of radius 1. We will discretize it with 100 points first: =# b = Circle(1.0,100) #= Now we will create the same body with a spacing of 0.02 =# b = Circle(1.0,0.02) #= This choice led to 312 points along the circumference. Quick math will tell you that the point spacing is probably not exactly 0.02. In fact, you can find out the actual spacing with `dlengthmid`. This function calculates the spacing associated with each point. (It does so by first calculating the spacing between midpoints between each point and its two adjacent points.) =# dlengthmid(b) #= It is just a bit larger than 0.02. A few other useful functions on the shape. To simply know the number of points, =# length(b) #= To find the outward normal vectors (based on the perpendicular to the line joining the adjacent midpoints): =# nx, ny = normalmid(b) #= We can also plot the shape =# plot(b) #= Sometimes we don't want to fill in the shape (and maybe change the line color). In that case, we can use =# plot(b,fill=:false,linecolor=:black) #= ## Other shapes Let's see some other shapes in action, like a square and an ellipse =# b1, b2 = Square(1.0,0.02), Ellipse(0.6,0.1,0.02) plot(plot(b1), plot(b2)) #= A NACA 4412 airfoil, with chord length 1, and 0.02 spacing between points. =# b = NACA4(0.04,0.4,0.12,0.02) plot(b) #= A flat plate with no thickness =# b = Plate(1.0,0.02) plot(b) #= and a flat plate with a 5 percent thickness (and rounded ends) =# b = ThickPlate(1.0,0.05,0.01) plot(b) #= There are also some generic tools for creating shapes. A `BasicBody` simply consists of points that describe the vertices. The interface for this is very simple. =# x = [1.0, 1.2, 0.7, 0.6, 0.2, -0.1, 0.1, 0.4] y = [0.1, 0.5, 0.8, 1.2, 0.8, 0.6, 0.2, 0.3] b = BasicBody(x,y) #- plot(b) scatter!(b,markersize=3,markercolor=:black) #= However, this function does not insert any points along the sides between vertices. We have to do the work of specifying these points in the original call. For this reason, there are a few functions that are more directly useful. For example, we can create a polygon from these vertices, with a specified spacing between points distributed along the polygon sides =# b = Polygon(x,y,0.02) #- plot(b) scatter!(b,markersize=3,markercolor=:black) #= Alternatively, we can interpret those original points as control points for splines, with a spacing between points along the splines provided: =# b = SplinedBody(x,y,0.02) #- plot(b) scatter!(b,markersize=3,markercolor=:black) #md # ## Body functions #md # ```@docs #md # BasicBody #md # Polygon #md # Circle #md # Ellipse #md # NACA4 #md # Plate #md # Rectangle #md # SplinedBody #md # Square #md # ``` #md # ## Shape utilities #md # ```@docs #md # centraldiff #md # Base.diff(::Body) #md # Base.diff(::BodyList) #md # dlength #md # dlengthmid #md # Base.length(::Body) #md # midpoints(::Body) #md # midpoints(::BodyList) #md # normal #md # normalmid #md # arccoord #md # arccoordmid #md # arclength(::Body) #md # arclength(::BodyList) #md # ```
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git
[ "MIT" ]
0.5.8
00e976b2114783858a92e581e4895769d319ab83
code
4454
# # Evaluating velocities on body surfaces #md # ```@meta #md # CurrentModule = RigidBodyTools #md # ``` #= For use in mechanics problems, it is important to be able to output the velocity of the points on the surfaces of bodies at a given system state and time. We use the function `surface_velocity!` for this. Here, we will demonstrate its use, and particularly, its various options. We will use a simple problem, consisting of two flat plates connected by a `RevoluteJoint`, and one of the plates connected to the inertial system by a `FreeJoint2d`, oscillating in y coordinate only. =# using RigidBodyTools using Plots #= ## Set up the bodies, joints, and motion =# body1 = Plate(1.0,200) body2 = deepcopy(body1) bodies = BodyList([body1,body2]) #= Joint 1, connecting body 1 to inertial system =# Xp_to_j1 = MotionTransform(0.0,0.0,0.0) Xch_to_j1 = MotionTransform(-0.5,0.0,0.0) dofs1 = [ConstantVelocityDOF(0),ConstantVelocityDOF(0),OscillatoryDOF(1.0,2π,0,0.0)] joint1 = Joint(FreeJoint2d,0,Xp_to_j1,1,Xch_to_j1,dofs1) #= Joint 2, connecting body 2 to body 1 =# Xp_to_j2 = MotionTransform(0.5,0.0,0.0) Xch_to_j2 = MotionTransform(-0.5,0.0,0.0) dofs2 = [OscillatoryDOF(π/4,2π,-π/4,0.0)] joint2 = Joint(RevoluteJoint,1,Xp_to_j2,2,Xch_to_j2,dofs2) #= Assemble, and get the initial joint state vector at t = 0 =# joints = [joint1,joint2] ls = RigidBodyMotion(joints,bodies) t = 0 x = init_motion_state(bodies,ls;tinit=t) #= Let's plot the bodies, just to visualize their current configuration. =# update_body!(bodies,x,ls) plot(bodies,xlim=(-1,3),ylim=(-2,2)) #= Because of the phase difference, joint 2 is bent at an angle initially. =# #= ## Evaluate velocity on body points First, initialize vectors for the `u` and `v` components in this 2d example, using the `zero_body` function. =# u, v = zero_body(bodies), zero_body(bodies) #= Now evaluate the velocities at time 0 =# surface_velocity!(u,v,bodies,x,ls,t) #= We can plot these on each body using the `view` function for `BodyList`. For example, the vectors of u and v velocities on body 1 are =# bodyid = 1 s = arccoord(bodies[bodyid]) plot(s,view(u,bodies,bodyid),ylim=(-20,20),label="u1") plot!(s,view(v,bodies,bodyid),label="v1") #= This shows a pure vertical translation. On body 2, we see a mixture of the translation of body 1, plus the rotation of joint 2, which is reflected in the linear variation. Since the plate is at an angle, some of this rotation shows up as a negative u component. =# bodyid = 2 s = arccoord(bodies[bodyid]) plot(s,view(u,bodies,bodyid),ylim=(-20,20),label="u2") plot!(s,view(v,bodies,bodyid),label="v2") #= We can compute these velocities in different components, using the optional `axes` argument. For example, let's see the velocities on body 2 in its own coordinate system =# surface_velocity!(u,v,bodies,x,ls,t;axes=2) bodyid = 2 s = arccoord(bodies[bodyid]) plot(s,view(u,bodies,bodyid),ylim=(-20,20),label="u2") plot!(s,view(v,bodies,bodyid),label="v2") #= Now only the v component (the component perpendicular to the plate) depicts the rotation, and the u component has only a portion of the translational motion from joint 1. We can also compute the velocity relative to a body reference frame, using the optional `frame` argument. Let's compute the velocities relative to the velocity of body 1 (and in body 1 coordinates) and plot them. =# surface_velocity!(u,v,bodies,x,ls,t;axes=1,frame=1) bodyid = 1 s = arccoord(bodies[bodyid]) plot(s,view(u,bodies,bodyid),ylim=(-20,20),label="u1") plot!(s,view(v,bodies,bodyid),label="v1") #= Body 1 has no velocity in this reference frame. And body 2 has only a pure rotation... =# bodyid = 2 s = arccoord(bodies[bodyid]) plot(s,view(u,bodies,bodyid),ylim=(-20,20),label="u2") plot!(s,view(v,bodies,bodyid),label="v2") #= We do not have to remove all of the motion of the reference body when we compute velocity in a moving reference frame. We can use the `motion_part` keyword argument to remove only, e.g., `:angular` or `:linear` part (instead of `:full`, the default). For example, if we remove the angular part of body 2's motion, we are left with only the translation from joint 1 =# surface_velocity!(u,v,bodies,x,ls,t;axes=2,frame=2,motion_part=:angular) bodyid = 2 s = arccoord(bodies[bodyid]) plot(s,view(u,bodies,bodyid),ylim=(-20,20),label="u2") plot!(s,view(v,bodies,bodyid),label="v2") #md # ## Surface velocity functions #md # ```@docs #md # surface_velocity! #md # ```
RigidBodyTools
https://github.com/JuliaIBPM/RigidBodyTools.jl.git