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.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
546
using Dates: Dates println("Running tests starting at ", Dates.format(Dates.now(), "HH:MM:SS"), ".") using Pkg cd((@__DIR__) * "/..") Pkg.activate(".") try Δt = @elapsed Pkg.test("PostNewtonian"; coverage=true, test_args=ARGS) println("Running tests took $Δt seconds.") catch e println("Tests failed; proceeding to coverage") end Pkg.activate() # Activate Julia's base (home) directory using Coverage cd((@__DIR__) * "/..") coverage = Coverage.process_folder() Coverage.writefile("lcov.info", coverage) Coverage.clean_folder(".")
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
4416
module PostNewtonian # Always explicitly address functions similar to functions defined in this package, # which come from these packages: using MacroTools: MacroTools using FastDifferentiation: FastDifferentiation using RuntimeGeneratedFunctions: RuntimeGeneratedFunctions # Otherwise, we just explicitly import specific functions: using DataInterpolations: CubicSpline using InteractiveUtils: methodswith using LinearAlgebra: mul! using OrdinaryDiffEq: Vern9, #AutoVern9, Rodas5P, ODEFunction, ODEProblem, solve, remake, terminate!, CallbackSet, DiscreteCallback, VectorContinuousCallback using Quaternionic: QuatVec, Rotor, abs2vec, components, normalize, (⋅), (×) using Random: AbstractRNG, default_rng using RecursiveArrayTools: DiffEqArray using SciMLBase: ODESolution, parameterless_type, FullSpecialize, AbstractDiffEqInterpolation, build_solution, get_du using SciMLBase.ReturnCode: ReturnCode using SphericalFunctions: D!, Diterator, Dprep, Yiterator using StaticArrays: SVector, MVector using SymbolicIndexingInterface: SymbolCache using TestItems: @testitem # See the "Code structure" section of the documentation for a description of the simple # hierarchy into which this code is organized. The different levels of that hierarchy are # reflected cleanly in the files `include`d below. # It's more common in PN to use `ln` — which I also prefer, as `log` seems ambiguous. const ln = log include("utilities.jl") export termination_forwards, termination_backwards, dtmin_terminator, decreasing_v_terminator, nonfinite_terminator using .MathConstants include("pn_systems.jl") export PNSystem, pn_order, BBH, BHBH, BHNS, NSNS, BNS, FDPNSystem, fd_pnsystem include("pn_expansion.jl") export PNExpansion, PNTerm, PNExpansionParameter include("fundamental_variables.jl") using .FundamentalVariables #export M₁, M₂, χ⃗₁, χ⃗₂, R, v, Φ, Λ₁, Λ₂ # Avoid clashes: don't export include("derived_variables.jl") using .DerivedVariables export total_mass, # M, # Avoid clashes: don't export nicer names for important variables reduced_mass, # μ, reduced_mass_ratio, # ν, mass_difference_ratio, # δ, mass_ratio, # q, chirp_mass, # ℳ, # X1, X₁, # X2, X₂, n_hat, n̂, lambda_hat, λ̂, ell_hat, ℓ̂, Omega, Ω, S⃗₁, S⃗₂, S⃗, Σ⃗, χ⃗, χ⃗ₛ, χ⃗ₐ, chi_perp, χₚₑᵣₚ, chi_eff, χₑ, chi_p, χₚ, S⃗₀⁺, S⃗₀⁻, S₀⁺ₙ, S₀⁻ₙ, S₀⁺λ, S₀⁻λ, S₀⁺ₗ, S₀⁻ₗ, χ₁², χ₂², χ₁, χ₂, χ₁₂, χ₁ₗ, χ₂ₗ, χₛₗ, χₐₗ, Sₙ, Σₙ, Sλ, Σλ, Sₗ, Σₗ, sₗ, σₗ, S₁ₙ, S₁λ, S₁ₗ, S₂ₙ, S₂λ, S₂ₗ, rₕ₁, rₕ₂, Ωₕ₁, Ωₕ₂, sin²θ₁, sin²θ₂, ϕ̇̂₁, ϕ̇̂₂, Î₀₁, Î₀₂, κ₁, κ₂, κ₊, κ₋, λ₁, λ₂, λ₊, λ₋ include("pn_expressions.jl") export gw_energy_flux, 𝓕, tidal_heating, binding_energy, 𝓔, binding_energy_deriv, 𝓔′, Omega_p, Ω⃗ₚ, Omega_chi1, Ω⃗ᵪ₁, Omega_chi2, Ω⃗ᵪ₂, #𝛡, aₗ, Ω⃗ᵪ # Too obscure to bother with γₚₙ, inverse_separation, γₚₙ′, inverse_separation_deriv, γₚₙ⁻¹, inverse_separation_inverse, separation, # r, separation_deriv, # r′, separation_dot, # ṙ, separation_inverse, # r⁻¹, mode_weights!, h! include("dynamics.jl") export up_down_instability, estimated_time_to_merger, fISCO, ΩISCO, uniform_in_phase, orbital_evolution include("waveforms.jl") export coorbital_waveform, inertial_waveform, coorbital_waveform_computation_storage, inertial_waveform_computation_storage, coorbital_waveform!, inertial_waveform! include("compatibility_layers.jl") export GWFrames include("assorted_binaries/examples.jl") export superkick, hangup_kick include("assorted_binaries/random.jl") # Base.rand is the only function in that file, hence no need for exports include("precompilation.jl") include("predefinitions_Symbolics.jl") if !isdefined(Base, :get_extension) using Requires end @static if !isdefined(Base, :get_extension) # COV_EXCL_START function __init__() @require Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" include( "../ext/PostNewtonianSymbolicsExt.jl" ) end # COV_EXCL_STOP end end # module PostNewtonian
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
44
include("compatibility_layers/gwframes.jl")
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
1128
module DerivedVariables using ..PostNewtonian: VecOrPNSystem using ..PostNewtonian.FundamentalVariables using Quaternionic: 𝐢, 𝐣, 𝐤, QuatVec, (⋅), (×), abs2vec, absvec include("derived_variables/mass_combinations.jl") export total_mass, M, reduced_mass, μ, reduced_mass_ratio, ν, mass_difference_ratio, δ, mass_ratio, q, chirp_mass, ℳ, X1, X₁, X2, X₂ include("derived_variables/orbital_elements.jl") export n_hat, n̂, lambda_hat, λ̂, ell_hat, ℓ̂, Omega, Ω, lnv include("derived_variables/spin_combinations.jl") export S⃗₁, S⃗₂, S⃗, Σ⃗, χ⃗, χ⃗ₛ, χ⃗ₐ, chi_perp, χₚₑᵣₚ, χₑ, chi_eff, χₚ, chi_p, S⃗₀⁺, S⃗₀⁻, S₀⁺ₙ, S₀⁻ₙ, S₀⁺λ, S₀⁻λ, S₀⁺ₗ, S₀⁻ₗ, χ₁², χ₂², χ₁, χ₂, χ₁₂, χ₁ₗ, χ₂ₗ, χₛₗ, χₐₗ, Sₙ, Σₙ, Sλ, Σλ, Sₗ, Σₗ, sₗ, σₗ, S₁ₙ, S₁λ, S₁ₗ, S₂ₙ, S₂λ, S₂ₗ include("derived_variables/horizons.jl") export rₕ₁, rₕ₂, Ωₕ₁, Ωₕ₂, sin²θ₁, sin²θ₂, ϕ̇̂₁, ϕ̇̂₂, Î₀₁, Î₀₂, κ₁, κ₂, κ₊, κ₋, λ₁, λ₂, λ₊, λ₋ end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
124
include("dynamics/up_down_instability.jl") include("dynamics/right_hand_sides.jl") include("dynamics/orbital_evolution.jl")
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
5276
module FundamentalVariables using ..PostNewtonian using ..PostNewtonian: PNSystem, BHNS, NSNS, FDPNSystem using ..PostNewtonian: M₁index, M₂index, χ⃗₁indices, χ⃗₂indices, Rindices, vindex, Φindex using Quaternionic: Quaternionic, QuatVec, Rotor export M₁, M₂, χ⃗₁, χ⃗₂, R, v, Φ, Λ₁, Λ₂, M1, M2, chi1, chi2, Phi, Lambda1, Lambda2 ## NOTE: ## This indices used below are intimately bound to choices made in the definitions of ## the various `PNSystem`s. Any changes there must be mirrored here, and vice versa. """ M₁(pnsystem) M1(pnsystem) Mass of object 1 in this system. """ M₁(s::PNSystem) = M₁(s.state) M₁(state::AbstractVector) = @inbounds state[M₁index] const M1 = M₁ """ M₂(pnsystem) M2(pnsystem) Mass of object 2 in this system. """ M₂(s::PNSystem) = M₂(s.state) M₂(state::AbstractVector) = @inbounds state[M₂index] const M2 = M₂ """ χ⃗₁(pnsystem) chi1(pnsystem) Dimensionless spin vector of object 1 in this system, as a `QuatVec`. """ χ⃗₁(s::PNSystem) = χ⃗₁(s.state) χ⃗₁(state::AbstractVector) = @inbounds QuatVec(view(state, χ⃗₁indices)...) const chi1 = χ⃗₁ """ χ⃗₂(pnsystem) chi2(pnsystem) Dimensionless spin vector of object 2 in this system, as a `QuatVec`. """ χ⃗₂(s::PNSystem) = χ⃗₂(s.state) χ⃗₂(state::AbstractVector) = @inbounds QuatVec(view(state, χ⃗₂indices)...) const chi2 = χ⃗₂ """ R(pnsystem) Orientation of the binary, as a `Rotor`. At any instant, the binary is represented by the right-handed triad ``(n̂, λ̂, ℓ̂)``, where [``n̂``](@ref PostNewtonian.n̂) is the unit vector pointing from object 2 to object 1, and the instantaneous velocities of the binary's elements are in the ``n̂``-``λ̂`` plane. This `Rotor` will rotate the ``x̂`` vector to be along ``n̂``, the ``ŷ`` vector to be along ``λ̂``, and the ``ẑ`` vector to be along ``ℓ̂``. Note that the angular velocity associated to `R` is given by ``Ω⃗ = 2 Ṙ R̄ = Ω ℓ̂ + ϖ n̂``. (Any component of ``Ω⃗`` along ``λ̂`` would violate the condition that the velocities be in the ``n̂``-``λ̂`` plane.) Here, the scalar quantity ``Ω`` is the orbital angular frequency, and ``ϖ`` is the precession angular frequency. See also [`n̂`](@ref PostNewtonian.n̂), [`λ̂`](@ref PostNewtonian.λ̂), [`ℓ̂`](@ref PostNewtonian.ℓ̂), [`Ω`](@ref PostNewtonian.Ω), and [`𝛡`](@ref PostNewtonian.𝛡)``=ϖ n̂``. """ R(s::PNSystem) = R(s.state) R(state::AbstractVector) = @inbounds Rotor(view(state, Rindices)...) @doc raw""" v(pnsystem) v(;Ω, M=1) Post-Newtonian velocity parameter. This is related to the orbital angular frequency ``\Omega`` as ```math v \colonequals (M\,\Omega)^{1/3}, ``` where ``M`` is the total mass of the binary. Note that if you want to pass the value ``Ω`` (rather than a `PNSystem`), you must pass it as a keyword argument — as in `v(Ω=0.1)`. See also [`Ω`](@ref). """ v(s::PNSystem) = v(s.state) v(state::AbstractVector) = @inbounds state[vindex] v(; Ω, M=1) = ∛(M * Ω) """ Φ(pnsystem) Phi(pnsystem) Integrated orbital phase of the system. It is computed as the integral of [`Ω`](@ref). """ Φ(s::PNSystem) = Φ(s.state) Φ(state::AbstractVector) = @inbounds state[Φindex] const Phi = Φ @doc raw""" Λ₁(pnsystem) Lambda1(pnsystem) Quadrupolar tidal-coupling parameter of object 1 in this system. We imagine object 1 begin placed in an (adiabatic) external field with Newtonian potential ``\phi``, resulting in a tidal field measured by ``\partial_i \partial_j \phi`` evaluated at the center of mass of the object. This induces a quadrupole moment ``Q_{ij}`` in object 1, which can be related to the tidal field as ```math Q_{ij} = -\frac{G^4}{c^{10}} \Lambda_1 M_1^5 \partial_i \partial_j \phi, ``` where ``M_1`` is the mass of object 1. This tidal-coupling parameter ``\Lambda_1`` can be related to the Love number ``k_2`` (where the subscript 2 refers to the fact that this is for the ``\ell=2`` quadrupole, rather than object 2) as ```math \Lambda_1 = \frac{2}{3} \frac{c^{10}}{G^5} \frac{R_1^5}{M_1^5} k_2, ``` where ``R_1`` is the radius of object 1. Note that ``\Lambda_1`` is dimensionless. For black holes, it is precisely zero; for neutron stars it may range up to 1; more exotic objects may have significantly larger values. Note that — as of this writing — only `NSNS` systems can have a nonzero value for this quantity. All other types return `0`, which Julia can use to eliminate code that would then be 0. Thus, it is safe and efficient to use this quantity in any PN expression that specializes on the type of `pnsystem`. """ Λ₁(pn::PNSystem) = zero(eltype(pn)) Λ₁(pn::NSNS) = pn.Λ₁ Λ₁(pn::FDPNSystem) = pn.Λ₁ const Lambda1 = Λ₁ @doc raw""" Λ₂(pnsystem) Lambda2(pnsystem) Quadrupolar tidal coupling parameter of object 2 in this system. See [`Λ₁`](@ref) for details about the definition, swapping "object 1" with "object 2". Note that — as of this writing — only `BHNS` and `NSNS` systems can have a nonzero value for this quantity. All other types return `0`, which Julia can use to eliminate code that would then be 0. Thus, it is safe and efficient to use this quantity in any PN expression that specializes on the type of `pnsystem`. """ Λ₂(pn::PNSystem) = zero(eltype(pn)) Λ₂(pn::BHNS) = pn.Λ₂ Λ₂(pn::NSNS) = pn.Λ₂ Λ₂(pn::FDPNSystem) = pn.Λ₂ const Lambda2 = Λ₂ end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
14202
# This a utility that allow us to interoperate with FastDifferentiation.Node and other # Number types. function _efficient_vector(::Val{N}, ::Val{T}) where {N,T} if isbitstype(T) MVector{N,T}(undef) else Vector{T}(undef, N) end end @doc raw""" PNExpansion{N,T,NMax} This object can be multiplied by a scalar or another `PNExpansion` object, and contains a tuple of coefficients. The coefficients are stored in the order of the expansion, with the zeroth-order coefficient first. Multiplication by a scalar just multiplies each of the elements. Multiplication by another `PNExpansion` object is done by convolving the two tuples of coefficients. Blanchet (2014) defines the post-Newtonian expansion parameter as follows: > This parameter represents essentially a slow motion estimate ``ϵ ∼ 𝑣/𝑐``, where ``𝑣`` > denotes a typical internal velocity. By a slight abuse of notation, following > Chandrasekhar et al. [...], we shall henceforth write formally ``ϵ ≡ 1/𝑐``, even though > ``ϵ`` is dimensionless whereas ``𝑐`` has the dimension of a velocity. Thus, ``1/𝑐 ≪ 1`` > in the case of post-Newtonian sources. The small post-Newtonian remainders will be denoted > ``𝒪(1/𝑐^𝑛)``. Furthermore, [...] we shall refer to a small post-Newtonian term with > formal order ``𝒪(1/𝑐^𝑛)`` relative to the Newtonian acceleration in the equations of > motion, as ``\frac{𝑛}{2}\text{PN}``. Therefore, we consider the coefficients of the `PNExpansion` to be a polynomial in ``1/𝑐``. Here, the type parameter `N` corresponds to the number of elements actually present in the tuple of coefficients, and `T` is the type of the coefficients. The `NMax` parameter is the maximum number of elements, related to the usual PN order by ```math \text{pn_order} = \frac{\texttt{NMax}-1} {2}. ``` The `N` parameter is not related to the PN order; it is just used by Julia to know how many elements are currently in the coefficients, but is required to be 1 ≤ N ≤ NMax. """ struct PNExpansion{N,T,NMax} coeffs::NTuple{N,T} function PNExpansion{N,T,NMax}(coeffs) where {N,T,NMax} if N < 1 throw(ArgumentError("`N=$N` must be >0.")) end if N > NMax throw(ArgumentError("`N=$N` must be <`NMax=$NMax`.")) end return new{N,T,NMax}(coeffs) end function PNExpansion(coeffs::NTuple{N,T}, NMax) where {N,T} if N < 1 throw(ArgumentError("`N=$N` must be >0.")) end if N > NMax throw(ArgumentError("`N=$N` must be <`NMax=$NMax`.")) end return new{N,T,NMax}(coeffs) end end pn_order(::PNExpansion{N,T,NMax}) where {N,T,NMax} = (NMax - 1)//2 Base.getindex(pn::PNExpansion, i::Int) = pn.coeffs[i] Base.length(pn::PNExpansion) = length(pn.coeffs) Base.eltype(pn::PNExpansion) = eltype(pn.coeffs) function Base.sum(pn_expansion::PNExpansion{N,T,NMax}) where {N,T,NMax} return sum(pn_expansion[i] for i ∈ 1:N, init ∈ zero(T)) end function Base.:+(pn::PNExpansion{N,T1,NMax}, x::T2) where {N,T1,NMax,T2<:Number} T3 = promote_type(T1, T2) return PNExpansion(ntuple(i -> i == 1 ? pn[1] + x : T3(pn[i]), Val(N)), NMax) end Base.:+(x::T, pn::PNExpansion) where {T<:Number} = pn + x function Base.:-(pn::PNExpansion{N,T,NMax}) where {N,T,NMax} return PNExpansion{N,T,NMax}((-).(pn.coeffs)) end function Base.:*(pn::PNExpansion{N,T1,NMax}, x::T2) where {N,T1,NMax,T2<:Number} T3 = promote_type(T1, T2) return PNExpansion{N,T3,NMax}(@. T3(pn.coeffs * x)) end Base.:*(x::T, pn::PNExpansion) where {T<:Number} = pn * x function Base.:+( pn1::PNExpansion{N1,T1,NMax1}, pn2::PNExpansion{N2,T2,NMax2} ) where {N1,N2,T1,T2,NMax1,NMax2} throw( ArgumentError( "`PNExpansion` addition is only defined for objects of the same PN order." * "\nGot NMax1=$(NMax1) and NMax2=$(NMax2).", ), ) end function Base.:+( pn1::PNExpansion{N1,T1,NMax}, pn2::PNExpansion{N2,T2,NMax} ) where {N1,N2,T1,T2,NMax} if N1 > N2 return pn2 + pn1 else PNExpansion(ntuple(i -> sum_term(i, pn1, pn2), Val(N2)), NMax) end end function sum_term( i, pn1::PNExpansion{N1,T1,NMax}, pn2::PNExpansion{N2,T2,NMax} ) where {N1,N2,T1,T2,NMax} T3 = promote_type(T1, T2) if i ≤ N1 return T3(pn1.coeffs[i] + pn2.coeffs[i]) else return T3(pn2.coeffs[i]) end end function Base.:*( pn1::PNExpansion{N1,T1,NMax1}, pn2::PNExpansion{N2,T2,NMax2} ) where {N1,N2,T1,T2,NMax1,NMax2} throw( ArgumentError( "`PNExpansion` multiplication is only defined for objects of the same PN order." * "\nGot NMax1=$(NMax1) and NMax2=$(NMax2).", ), ) end function Base.:*( pn1::PNExpansion{N1,T1,NMax}, pn2::PNExpansion{N2,T2,NMax} ) where {N1,N2,T1,T2,NMax} if N1 > N2 return pn2 * pn1 else N3 = min(N1 + N2 - 1, NMax) PNExpansion(ntuple(i -> product_term(i, pn1, pn2), Val(N3)), NMax) end end function product_term( i, pn1::PNExpansion{N1,T1,NMax}, pn2::PNExpansion{N2,T2,NMax} ) where {N1,N2,T1,T2,NMax} T3 = promote_type(T1, T2) return sum( pn1.coeffs[j] * pn2.coeffs[i - j + 1] for j ∈ max(1, i - N2 + 1):min(i, N1), init ∈ zero(T3) ) end Base.:/(p::PNExpansion, x::Number) = p * (1 / x) function FastDifferentiation.derivative( pn_expansion::PNExpansion{N,T,NMax}, fd_node::FastDifferentiation.Node ) where {N,T,NMax} return PNExpansion( ntuple(i -> FastDifferentiation.derivative(pn_expansion[i], fd_node), Val(N)), NMax ) end Base.Tuple(pn::PNExpansion) = pn.coeffs SVector(pn::PNExpansion) = SVector(pn.coeffs) """ PNTerm{T,PNOrder,c⁻¹Exponent} This object represents a single term in a PNExpansion. It has a single field: `coeff`, which is the coefficient of the term. The type parameter `T` is the type of the coefficient. The type parameter `PNOrder` is a half-integer (just as in [`PNSystem`](@ref)s) representing the PN order of the expansion. And the type parameter `c⁻¹Exponent` is an integer representing the exponent of the PN expansion parameter ``1/c``. `PNTerm`s can be multiplied and divided by scalars and exponentiated by integers, to produce another `PNTerm`. They can also be added to other `PNTerm`s to produce a `PNExpansion`. A simple way to define a `PNTerm` or a `PNExpansion` is to define the PN expansion parameter ```julia c = PNExpansionParameter(pnsystem) ``` and use that naturally in formulas, as in ```julia e = 1 + (v/c)^2 * (-ν/12 - 3//4) + (v/c)^4 * (-ν^2/24 + 19ν/8 - 27//8) ``` Any exponent higher than the desired `PNOrder` will be automatically set to zero. Useful facts: - `v` has order `1/c` - `x` has order `1/c^2` - `γ` has order `1/c^2` - `1/r` has order `1/c^2` """ struct PNTerm{T,PNOrder,c⁻¹Exponent} coeff::T function PNTerm{T,PNOrder,c⁻¹Exponent}(coeff) where {T,PNOrder,c⁻¹Exponent} if c⁻¹Exponent > 2PNOrder coeff = zero(coeff) end return new{T,PNOrder,c⁻¹Exponent}(coeff) end function PNTerm{T,PNOrder}(c⁻¹exp::Int, coeff) where {T,PNOrder} if c⁻¹exp > 2PNOrder coeff = zero(coeff) end return new{T,PNOrder,c⁻¹exp}(coeff) end end Base.length(pn::PNTerm) = 1 Base.eltype(pn::PNTerm{T}) where {T} = T c⁻¹exp(pn::PNTerm{T,PNOrder,c⁻¹Exponent}) where {T,PNOrder,c⁻¹Exponent} = c⁻¹Exponent function Base.sum(pn::PNTerm) return pn.coeff end function Base.:+(pn::PNTerm) return pn end function Base.inv(term::PNTerm{T,PNOrder,c⁻¹Exponent}) where {T,PNOrder,c⁻¹Exponent} return PNTerm{T,PNOrder}(-c⁻¹exp(term), inv(term.coeff)) end function Base.:^(term::PNTerm{T,PNOrder,c⁻¹Exponent}, n::Int) where {T,PNOrder,c⁻¹Exponent} coeff = term.coeff^n return PNTerm{typeof(coeff),PNOrder}(c⁻¹exp(term) * n, coeff) end function Base.:*( x::Number, term::PNTerm{T,PNOrder,c⁻¹Exponent} ) where {T,PNOrder,c⁻¹Exponent} coeff = x * term.coeff return PNTerm{typeof(coeff),PNOrder,c⁻¹Exponent}(coeff) end Base.:*(term::PNTerm, x::Number) = x * term function Base.:/( term::PNTerm{T,PNOrder,c⁻¹Exponent}, x::Number ) where {T,PNOrder,c⁻¹Exponent} coeff = term.coeff / x return PNTerm{typeof(coeff),PNOrder,c⁻¹Exponent}(coeff) end function Base.:/( x::Number, term::PNTerm{T,PNOrder,c⁻¹Exponent} ) where {T,PNOrder,c⁻¹Exponent} coeff = x / term.coeff return PNTerm{typeof(coeff),PNOrder}(-c⁻¹exp(term), coeff) end function Base.:+( x::T1, term::PNTerm{T2,PNOrder,c⁻¹Exponent} ) where {T1<:Number,T2,PNOrder,c⁻¹Exponent} if c⁻¹exp(term) < 0 throw( ArgumentError( "Cannot add a `PNTerm` with a negative exponent: " * "c⁻¹exp(term)=$(c⁻¹exp(term))." * "\nResult will be a `PNExpansion`, which cannot store positive exponents.", ), ) end T = promote_type(T1, T2) N₀ = c⁻¹exp(term) + 1 NMax = Int(2PNOrder + 1) N = min(N₀, NMax) coeffs = _efficient_vector(Val(N), Val(T)) coeffs .= zero(T) @inbounds coeffs[1] = x @inbounds if N₀ ≤ NMax coeffs[N₀] += term.coeff end return PNExpansion{N,T,NMax}(Tuple(coeffs)) end Base.:+(term::PNTerm, x::Number) = x + term function Base.:-(term::PNTerm{T,PNOrder,c⁻¹Exponent}) where {T,PNOrder,c⁻¹Exponent} return PNTerm{T,PNOrder,c⁻¹Exponent}(-term.coeff) end function Base.:*( term1::PNTerm{T1,PNOrder,c⁻¹E1}, term2::PNTerm{T2,PNOrder,c⁻¹E2} ) where {T1,T2,PNOrder,c⁻¹E1,c⁻¹E2} c⁻¹Exponent = c⁻¹exp(term1) + c⁻¹exp(term2) coeff = term1.coeff * term2.coeff return PNTerm{typeof(coeff),PNOrder,c⁻¹Exponent}(coeff) end function Base.:/( term1::PNTerm{T1,PNOrder,c⁻¹E1}, term2::PNTerm{T2,PNOrder,c⁻¹E2} ) where {T1,T2,PNOrder,c⁻¹E1,c⁻¹E2} c⁻¹Exponent = c⁻¹E1 - c⁻¹E2 coeff = term1.coeff / term2.coeff return PNTerm{typeof(coeff),PNOrder,c⁻¹Exponent}(coeff) end function Base.:+( term1::PNTerm{T1,PNOrder,c⁻¹E1}, term2::PNTerm{T2,PNOrder,c⁻¹E2} ) where {T1,T2,PNOrder,c⁻¹E1,c⁻¹E2} if c⁻¹exp(term1) < 0 throw( ArgumentError( "Cannot add a `PNTerm` with a negative exponent: " * "c⁻¹exp(term1)=$(c⁻¹exp(term1))." * "\nResult will be a `PNExpansion`, which cannot store positive exponents.", ), ) end if c⁻¹exp(term2) < 0 throw( ArgumentError( "Cannot add a `PNTerm` with a negative exponent: " * "c⁻¹exp(term2)=$(c⁻¹exp(term2))." * "\nResult will be a `PNExpansion`, which cannot store positive exponents.", ), ) end T = promote_type(T1, T2) N1₀ = c⁻¹exp(term1) + 1 N2₀ = c⁻¹exp(term2) + 1 NMax = Int(2PNOrder + 1) N = min(max(N1₀, N2₀), NMax) coeffs = _efficient_vector(Val(N), Val(T)) coeffs .= zero(T) @inbounds if N1₀ ≤ N coeffs[N1₀] += term1.coeff end @inbounds if N2₀ ≤ N coeffs[N2₀] += term2.coeff end return PNExpansion{N,T,NMax}(Tuple(coeffs)) end Base.:-(term1::PNTerm, term2::PNTerm) = term1 + (-term2) function Base.:+( term::PNTerm{T1,PNOrder,c⁻¹E1}, expansion::PNExpansion{N2,T2,NMax2} ) where {T1,PNOrder,c⁻¹E1,N2,T2,NMax2} if c⁻¹exp(term) < 0 throw( ArgumentError( "Cannot add a `PNTerm` with a negative exponent: " * "c⁻¹exp(term)=$(c⁻¹exp(term))." * "\nResult will be a `PNExpansion`, which cannot store positive exponents.", ), ) end N1 = c⁻¹exp(term) + 1 NMax1 = Int(2PNOrder + 1) NMax = min(NMax1, NMax2) N = min(max(N1, N2), NMax) T = promote_type(T1, T2) coeffs = _efficient_vector(Val(N), Val(T)) coeffs .= zero(T) @inbounds if N1 ≤ N coeffs[N1] += term.coeff end @inbounds for i ∈ 1:N if i ≤ N2 coeffs[i] += expansion[i] end end return PNExpansion{N,T,NMax}(Tuple(coeffs)) end Base.:+(expansion::PNExpansion, term::PNTerm) = term + expansion Base.:-(term::PNTerm, x::Number) = term + (-x) Base.:-(x::Number, term::PNTerm) = x + (-term) Base.:-(term::PNTerm, expansion::PNExpansion) = term + (-expansion) Base.:-(expansion::PNExpansion, term::PNTerm) = expansion + (-term) Base.:-(x::Number, expansion::PNExpansion) = x + (-expansion) Base.:-(expansion::PNExpansion, x::Number) = expansion + (-x) function Base.:*( expansion::PNExpansion{N1,T1,NMax1}, term::PNTerm{T2,PNOrder,c⁻¹E2} ) where {N1,T1,NMax1,T2,PNOrder,c⁻¹E2} ΔN = c⁻¹exp(term) # Note that ΔN may be negative! NMax2 = Int(2PNOrder + 1) NMax = min(NMax1, NMax2) N = min(max(N1, N1 + ΔN), NMax) # Check that no terms from expansion will be lost to negative PN orders @inbounds for i ∈ 1:min(max(0, -ΔN), N1) if !iszero(expansion[i]) throw( ArgumentError( "Cannot multiply `PNExpansion` by `PNTerm` with negative exponent: " * "c⁻¹exp(term)=$(c⁻¹exp(term))." * "\nResult will be a `PNExpansion`, which cannot store positive exponents.", ), ) end end T = promote_type(T1, T2) coeffs = _efficient_vector(Val(N), Val(T)) coeffs .= zero(T) @inbounds for i ∈ max(1, 1 - ΔN):min(N1, N - ΔN) coeffs[i + ΔN] = expansion[i] * term.coeff end return PNExpansion{N,T,NMax}(Tuple(coeffs)) end Base.:*(term::PNTerm, expansion::PNExpansion) = expansion * term # (a, b, c, d, e, f, g) * (c⁻¹^2) = (0, 0, a, b, c, d, e) Base.:/(expansion::PNExpansion, term::PNTerm) = expansion * inv(term) """ PNExpansionParameter(pnsystem) Create a [`PNTerm`](@ref) object representing the post-Newtonian expansion parameter ``c``. This can be used to automatically create more complicated `PNTerm`s, which combine to form a [`PNExpansion`](@ref). This is a simple but effective way to write PN formulas while automatically tracking the PN order of each term. """ function PNExpansionParameter(::PNSystem{ST,PNOrder}) where {ST,PNOrder} return PNTerm{eltype(ST),PNOrder}(-1, one(eltype(ST))) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
274
include("utilities/macros.jl") include("pn_expressions/flux.jl") include("pn_expressions/tidal_heating.jl") include("pn_expressions/binding_energy.jl") include("pn_expressions/separation.jl") include("pn_expressions/precession.jl") include("pn_expressions/mode_weights.jl")
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
10221
""" PNSystem{T, PNOrder} Base type for all PN systems, such as `BBH`, `BHNS`, and `NSNS`. These objects encode all essential properties of the binary, including its current state. As such, they can be used as inputs to the various [fundamental](@ref Fundamental-variables) and [derived variables](@ref Derived-variables), as well as [PN expressions](@ref) and [dynamics](@ref Dynamics) functions. All subtypes should contain a `state` vector holding all of the fundamental variables for the given type of system. The parameter `T` is the type of the `state` vector — for example, `Vector{Float64}`. `PNOrder` is a `Rational` giving the order to which PN expansions should be carried. """ abstract type PNSystem{ST,PNOrder} end const VecOrPNSystem = Union{AbstractVector,PNSystem} const pnsystem_symbols = ( :M₁, :M₂, :χ⃗₁ˣ, :χ⃗₁ʸ, :χ⃗₁ᶻ, :χ⃗₂ˣ, :χ⃗₂ʸ, :χ⃗₂ᶻ, :Rʷ, :Rˣ, :Rʸ, :Rᶻ, :v, :Φ ) for (i, s) ∈ enumerate(pnsystem_symbols) sindex = Symbol("$(s)index") @eval const $sindex = $i end const χ⃗₁indices = χ⃗₁ˣindex:χ⃗₁ᶻindex const χ⃗₂indices = χ⃗₂ˣindex:χ⃗₂ᶻindex const Rindices = Rʷindex:Rᶻindex Base.eltype(::PNSystem{ST}) where {ST} = eltype(ST) pn_order(::PNSystem{ST,PNOrder}) where {ST,PNOrder} = PNOrder order_index(pn::PNSystem) = 1 + Int(2pn_order(pn)) """ causes_domain_error!(u̇, p) Ensure that these parameters correspond to a physically valid set of PN parameters. If the parameters are not valid, this function should modify `u̇` to indicate that the current step is invalid. This is done by filling `u̇` with `NaN`s, which will be detected by the ODE solver and cause it to try a different (smaller) step size. Currently, the only check that is done is to test that these parameters result in a PN parameter v>0. In the future, this function may be expanded to include other checks. """ function causes_domain_error!(u̇, p::PNSystem{VT}) where {VT} if p.state[vindex] ≤ 0 # If this is expanded, document the change in the docstring. u̇ .= convert(eltype(VT), NaN) true else false end end function prepare_system(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, Φ=0, PNOrder=typemax(Int)) state = [M₁; M₂; vec(QuatVec(χ⃗₁)); vec(QuatVec(χ⃗₂)); components(Rotor(R)); v; Φ] ST = typeof(state) PNOrder = prepare_pn_order(PNOrder) return (ST, PNOrder, state) end function prepare_pn_order(PNOrder) if PNOrder != typemax(Int) round(Int, 2PNOrder)//2 else (typemax(Int) - 2)//2 end end """ BBH{T, PNOrder} The [`PNSystem`](@ref) subtype describing a binary black hole system. The `state` vector here holds the fundamental variables `M₁`, `M₂`, `χ⃗₁`, `χ⃗₂`, `R`, `v`, with the spins unpacked into three components each, and `R` unpacked into four — for a total of 13 elements. Optionally, `Φ` may also be tracked as the 14th element of the `state` vector. This is just the integral of the orbital angular frequency `Ω`, and holds little interest for general systems beyond a convenient description of how "far" the system has evolved. """ struct BBH{T,PNOrder} <: PNSystem{T,PNOrder} state::T BBH{T,PNOrder}(state) where {T,PNOrder} = new{T,PNOrder}(state) function BBH(; M₁, M₂, χ⃗₁, χ⃗₂, v, R=Rotor(1), Φ=0, PNOrder=typemax(Int), kwargs...) (T, PNOrder, state) = prepare_system(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, Φ, PNOrder) return new{T,PNOrder}(state) end function BBH(state; Λ₁=0, Λ₂=0, PNOrder=typemax(Int)) @assert length(state) == 14 @assert Λ₁ == 0 @assert Λ₂ == 0 return new{typeof(state),prepare_pn_order(PNOrder)}(state) end end const BHBH = BBH """ BHNS{T, PNOrder} The [`PNSystem`](@ref) subtype describing a black-hole—neutron-star binary system. The `state` vector is the same as for a [`BBH`](@ref). There is an additional field `Λ₂` holding the (constant) tidal-coupling parameter of the neutron star. Note that the neutron star is *always* object 2 — meaning that `M₂`, `χ⃗₂`, and `Λ₂` always refer to it; `M₁` and `χ⃗₁` always refer to the black hole. See also [`NSNS`](@ref). """ struct BHNS{ST,PNOrder,ET} <: PNSystem{ST,PNOrder} state::ST Λ₂::ET BHNS{T,PNOrder,ET}(state) where {T,PNOrder,ET} = new{T,PNOrder,ET}(state) BHNS{T,PNOrder}(state) where {T,PNOrder} = new{T,PNOrder,eltype(T)}(state) function BHNS(; M₁, M₂, χ⃗₁, χ⃗₂, v, R=Rotor(1), Λ₂, Φ=0, PNOrder=typemax(Int), kwargs... ) ST, PNOrder, state = prepare_system(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, Φ, PNOrder) ET = eltype(ST) return new{ST,PNOrder,ET}(state, convert(ET, Λ₂)) end function BHNS(state; Λ₂, Λ₁=0, PNOrder=typemax(Int)) @assert length(state) == 14 ST, PNOrder = typeof(state), prepare_pn_order(PNOrder) ET = eltype(ST) return new{ST,PNOrder,ET}(state, convert(ET, Λ₂)) end end """ NSNS{T, PNOrder} The [`PNSystem`](@ref) subtype describing a neutron-star—neutron-star binary system. The `state` vector is the same as for a [`BBH`](@ref). There are two additional fields `Λ₁` and `Λ₂` holding the (constant) tidal-coupling parameters of the neutron stars. See also [`BHNS`](@ref). """ struct NSNS{ST,PNOrder,ET} <: PNSystem{ST,PNOrder} state::ST Λ₁::ET Λ₂::ET NSNS{T,PNOrder,ET}(state) where {T,PNOrder,ET} = new{T,PNOrder,ET}(state) NSNS{T,PNOrder}(state) where {T,PNOrder} = new{T,PNOrder,eltype(T)}(state) function NSNS(; M₁, M₂, χ⃗₁, χ⃗₂, v, R=Rotor(1), Λ₁, Λ₂, Φ=0, PNOrder=typemax(Int), kwargs... ) ST, PNOrder, state = prepare_system(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, Φ, PNOrder) ET = eltype(ST) return new{ST,PNOrder,ET}(state, convert(ET, Λ₁), convert(ET, Λ₂)) end function NSNS(state; Λ₁, Λ₂, PNOrder=typemax(Int)) @assert length(state) == 14 ST, PNOrder = typeof(state), prepare_pn_order(PNOrder) ET = eltype(state) return new{ST,PNOrder,ET}(state, convert(ET, Λ₁), convert(ET, Λ₂)) end end const BNS = NSNS """ FDPNSystem{FT, PNOrder}(state, Λ₁, Λ₂) A `PNSystem` that contains information as variables from [`FastDifferentiation.jl`](https://docs.juliahub.com/General/FastDifferentiation/stable/). See also [`fd_pnsystem`](@ref) for a particular instance of this type. Note that this type also involves the type `FT`, which will be the float type of actual numbers that eventually get fed into (and will be passed out from) functions that use this system. The correct type of `FDPNSystem` is used in calculating `𝓔′`. """ struct FDPNSystem{FT,PNOrder} <: PNSystem{Vector{FastDifferentiation.Node},PNOrder} state::Vector{FastDifferentiation.Node} Λ₁::FastDifferentiation.Node Λ₂::FastDifferentiation.Node function FDPNSystem(FT, PNOrder=typemax(Int)) FastDifferentiation.@variables M₁ M₂ χ⃗₁ˣ χ⃗₁ʸ χ⃗₁ᶻ χ⃗₂ˣ χ⃗₂ʸ χ⃗₂ᶻ Rʷ Rˣ Rʸ Rᶻ v Φ Λ₁ Λ₂ return new{FT,prepare_pn_order(PNOrder)}( [M₁, M₂, χ⃗₁ˣ, χ⃗₁ʸ, χ⃗₁ᶻ, χ⃗₂ˣ, χ⃗₂ʸ, χ⃗₂ᶻ, Rʷ, Rˣ, Rʸ, Rᶻ, v, Φ], Λ₁, Λ₂ ) end end Base.eltype(::FDPNSystem{FT}) where {FT} = FT """ fd_pnsystem A symbolic `PNSystem` that contains symbolic information for all types of `PNSystem`s. In particular, note that this object has (essentially) infinite `PNOrder`, has nonzero values for quantities like `Λ₁` and `Λ₂`, and assumes that the eventual output will be in `Float64`. If you want different choices, you may need to call [`FDPNSystem`](@ref) yourself, or even construct a different specialized subtype of `PNSystem` (it's not hard). # Examples ```jldoctest julia> using PostNewtonian: M₁, M₂, χ⃗₁, χ⃗₂, FDPNSystem julia> fd_pnsystem = FDPNSystem(Float64) FDPNSystem{Float64, 9223372036854775805//2}(FastDifferentiation.Node[M₁, M₂, χ⃗₁ˣ, χ⃗₁ʸ, χ⃗₁ᶻ, χ⃗₂ˣ, χ⃗₂ʸ, χ⃗₂ᶻ, Rʷ, Rˣ, Rʸ, Rᶻ, v, Φ], Λ₁, Λ₂) julia> M₁(fd_pnsystem), M₂(fd_pnsystem) (M₁, M₂) julia> χ⃗₁(fd_pnsystem) + χ⃗₁ˣ𝐢 + χ⃗₁ʸ𝐣 + χ⃗₁ᶻ𝐤 julia> χ⃗₂(fd_pnsystem) + χ⃗₂ˣ𝐢 + χ⃗₂ʸ𝐣 + χ⃗₂ᶻ𝐤 ``` """ const fd_pnsystem = FDPNSystem(Float64) function SVector(pnsystem::PNSystem) return SVector{16,eltype(pnsystem)}( pnsystem.state[1], pnsystem.state[2], pnsystem.state[3], pnsystem.state[4], pnsystem.state[5], pnsystem.state[6], pnsystem.state[7], pnsystem.state[8], pnsystem.state[9], pnsystem.state[10], pnsystem.state[11], pnsystem.state[12], pnsystem.state[13], pnsystem.state[14], Λ₁(pnsystem), Λ₂(pnsystem), ) end function SVector(pnsystem::FDPNSystem) return SVector{16,FastDifferentiation.Node}( pnsystem.state[1], pnsystem.state[2], pnsystem.state[3], pnsystem.state[4], pnsystem.state[5], pnsystem.state[6], pnsystem.state[7], pnsystem.state[8], pnsystem.state[9], pnsystem.state[10], pnsystem.state[11], pnsystem.state[12], pnsystem.state[13], pnsystem.state[14], Λ₁(pnsystem), Λ₂(pnsystem), ) end @testitem "PNSystem constructors" begin using Quaternionic pnA = BBH(; M₁=1.0f0, M₂=2.0f0, χ⃗₁=Float32[3.0, 4.0, 5.0], χ⃗₂=Float32[6.0, 7.0, 8.0], v=0.23f0 ) @test pnA.state == Float32[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; 1.0; 0.0; 0.0; 0.0; 0.23; 0.0] pnB = BBH(; M₁=1.0f0, M₂=2.0f0, χ⃗₁=Float32[3.0, 4.0, 5.0], χ⃗₂=Float32[6.0, 7.0, 8.0], v=0.23f0, Φ=9.0f0, ) @test pnB.state == Float32[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; 1.0; 0.0; 0.0; 0.0; 0.23; 9.0] R = randn(RotorF32) pn1 = BBH(; M₁=1.0f0, M₂=2.0f0, χ⃗₁=Float32[3.0, 4.0, 5.0], χ⃗₂=Float32[6.0, 7.0, 8.0], R=R, v=0.23f0, ) @test pn1.state ≈ [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; components(R)...; 0.23; 0.0] pn2 = BBH(; M₁=1.0f0, M₂=2.0f0, χ⃗₁=Float32[3.0, 4.0, 5.0], χ⃗₂=Float32[6.0, 7.0, 8.0], R=R, v=0.23f0, Φ=9.0f0, ) @test pn2.state ≈ [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; components(R)...; 0.23; 9.0] pn1.state[end] = 9.0f0 @test pn1.state == pn2.state end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
1142
let using Logging: Logging Logging.with_logger(Logging.SimpleLogger(Logging.Error)) do # Adapted from "Quick start" example M₁ = 0.4 M₂ = 0.6 χ⃗₁ = [0.0, 0.01, 0.1] χ⃗₂ = [0.01, 0.0, 0.1] Ωᵢ = 0.15 Ω₁ = 99Ωᵢ / 100 Ωₑ = 0.20 inspiral = orbital_evolution(M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; Ω₁, Ωₑ) uniform_in_phase(inspiral, 128) t′ = (inspiral.t[end] - 1.0):0.1:inspiral.t[end] inspiral = inspiral(t′) h = inertial_waveform(inspiral) # Exercise a couple explicit PN orders for PNOrder ∈ [4//1, typemax(Int)] coorbital_waveform( orbital_evolution(M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; Ω₁, Ωₑ, PNOrder); PNOrder ) end # People may use the GWFrames interface; it *should* be covered above, # but just to be sure... Approximant = "TaylorT1" delta = (M₁ - M₂) / (M₁ + M₂) chi1_i = χ⃗₁ chi2_i = χ⃗₂ Omega_orb_i = Ωᵢ Omega_orb_0 = Ω₁ GWFrames.PNWaveform(Approximant, delta, chi1_i, chi2_i, Omega_orb_i; Omega_orb_0) end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
1660
# Pre-define a few functions / structs that the Symbolics extension can extend """ hold(x) Delay evaluation of the argument in `Symbolics` expressions. This is just a helper function that acts trivially — like the `identity` function — but also gets registered with `Symbolics` to avoid evaluation of the argument. For example, we can preserve expressions like `π^2`, which Julia would normally convert directly to a `Float64`. Note that you probably don't want to use this function directly; this will probably be done for you by [`@pn_expression`](@ref PostNewtonian.@pn_expression) or similar. If you *do* want to use this directly, you probably want another layer of indirection to construct something like `Symbolics.Num(SymbolicUtils.Term(hold, [x]))` so that you can use the result in a symbolic expression. """ function hold end """ unhold(expr) Remove occurrences of [`hold`](@ref) from an `Expr`. """ function unhold end """ SymbolicPNSystem{ST, PNOrder, ET}(state, Λ₁, Λ₂) A `PNSystem` that contains information as variables from [`Symbolics.jl`](https://symbolics.juliasymbolics.org/). # Examples ```jldoctest julia> using Symbolics julia> using PostNewtonian: M₁, M₂, χ⃗₁, χ⃗₂, SymbolicPNSystem julia> symbolic_pnsystem = SymbolicPNSystem() SymbolicPNSystem{Vector{Num}, 9223372036854775805//2, Num}(Num[M₁, M₂, χ⃗₁ˣ, χ⃗₁ʸ, χ⃗₁ᶻ, χ⃗₂ˣ, χ⃗₂ʸ, χ⃗₂ᶻ, Rʷ, Rˣ, Rʸ, Rᶻ, v, Φ], Λ₁, Λ₂) julia> M₁(symbolic_pnsystem), M₂(symbolic_pnsystem) (M₁, M₂) julia> χ⃗₁(symbolic_pnsystem) χ⃗₁ julia> χ⃗₂(symbolic_pnsystem) χ⃗₂ ``` """ struct SymbolicPNSystem{ST,PNOrder,ET} <: PNSystem{ST,PNOrder} state::ST Λ₁::ET Λ₂::ET end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
404
include("utilities/mathconstants.jl") include("utilities/misc.jl") include("utilities/truncated_series_monoid.jl") include("utilities/truncated_series_inversion.jl") include("utilities/combine_solutions.jl") include("utilities/termination_criteria.jl") # Don't include macros.jl yet; we need to get contents of `FundamentalVariables` and # `DerivedVariables`, so that's included by `pn_expressions.jl`.
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
7973
# Helper functions to get the `pnsystem` from either an ODESolution or the result of # interpolating such a thing _pnsystem(inspiral::ODESolution) = inspiral.prob.p _pnsystem(inspiral::DiffEqArray) = inspiral.p """ coorbital_waveform_computation_storage(inspiral; [ℓₘᵢₙ=2], [ℓₘₐₓ=8], [PNOrder]) coorbital_waveform_computation_storage(inspiral; [ell_min=2], [ell_max=8], [PNOrder]) Construct storage needed to compute waveforms in the co-orbital frame without allocations. This returns the storage for the waveforms themselves and `PNSystem` used as temporary storage. The returned quantity can just be passed as the first argument to [`coorbital_waveform!`](@ref) without being unpacked. The meaning of the arguments is the same as in [`coorbital_waveform`](@ref). """ function coorbital_waveform_computation_storage( inspiral; ell_min=2, ell_max=8, ℓₘᵢₙ=ell_min, ℓₘₐₓ=ell_max, PNOrder=pn_order(_pnsystem(inspiral)), ) @assert 0 ≤ ℓₘᵢₙ ≤ 2 @assert ℓₘᵢₙ ≤ ℓₘₐₓ p = _pnsystem(inspiral) PNSystemType = parameterless_type(p) pnsystem = PNSystemType(copy(inspiral.u[1]); Λ₁=Λ₁(p), Λ₂=Λ₂(p), PNOrder) n_modes = (ℓₘₐₓ + 1)^2 - ℓₘᵢₙ^2 h = Array{Complex{eltype(inspiral)}}(undef, n_modes, length(inspiral)) return h, pnsystem end """ coorbital_waveform!(storage, inspiral; [ℓₘᵢₙ=2], [ℓₘₐₓ=8], [PNOrder]) coorbital_waveform!(storage, inspiral; [ell_min=2], [ell_max=8], [PNOrder]) Evaluate the post-Newtonian waveform mode weights in the co-orbital frame for the given `inspiral` output by [`orbital_evolution`](@ref), using pre-allocated storage. The storage is assumed to be the object returned from [`coorbital_waveform_computation_storage`](@ref). Other arguments are the same as in [`coorbital_waveform`](@ref). """ function coorbital_waveform!( storage, inspiral; ell_min=2, ell_max=8, ℓₘᵢₙ=ell_min, ℓₘₐₓ=ell_max, PNOrder=pn_order(storage[2]), ) h, pnsystem = storage @assert length(pnsystem.state) == length(inspiral.u[1]) @assert length(inspiral) == size(h, 2) @assert (ℓₘₐₓ + 1)^2 - ℓₘᵢₙ^2 == size(h, 1) @inbounds @fastmath for iₜ ∈ eachindex(inspiral) pnsystem.state .= inspiral.u[iₜ] h!(@view(h[:, iₜ]), pnsystem; ℓₘᵢₙ, ℓₘₐₓ) end return h end """ coorbital_waveform(inspiral; [ℓₘᵢₙ=2], [ℓₘₐₓ=8], [PNOrder]) coorbital_waveform(inspiral; [ell_min=2], [ell_max=8], [PNOrder]) Evaluate the post-Newtonian waveform mode weights in the co-orbital frame for the given `inspiral` output by [`orbital_evolution`](@ref). See also [`inertial_waveform`](@ref) for the waveform in the inertial frame. For a detailed description of the format and physical interpretation of the returned quantity, see the ["Waveforms" section of the manual.](https://moble.github.io/PostNewtonian.jl/stable/internals/waveforms.html) The `PNOrder` defaults to the one used to compute `inspiral`, but may be changed by passing the keyword argument. !!! tip If you need this waveform at a different set of times `t′` than is currently present in `inspiral.t`, you should use the built-in interpolation capabilities of `inspiral` *first*, as in `inspiral′ = inspiral(t′)`, rather than interpolating the results of this function. Or, perhaps better yet, you could select the times when calling `orbital_evolution` by using the `saves_per_orbit` or `saveat` keyword argument to that function. These approaches will be more accurate, faster, and require less memory than interpolating the result of this function. If using `saves_per_orbit`, you probably want to set it to *at least* `2ℓₘₐₓ`, or preferably `4ℓₘₐₓ`. The mode weights are given starting at `ℓₘᵢₙ` (which must satisfy `0 ≤ ℓₘᵢₙ ≤ 2`) and extending through `ℓₘₐₓ`. The waveform is returned as a 2-dimensional `Array`, in which the first index varies over the mode index from `(ℓ, m) = (ℓₘᵢₙ, -ℓₘᵢₙ)` to `(ℓ, m) = (ℓₘₐₓ, ℓₘₐₓ)`, with `m` varying most rapidly, and the second index varying over the time steps. In this function, the waveform is returned in the co-orbital frame — which is somewhat like the co-rotating frame. In particular, the modes of non-precessing systems vary slowly, over inspiral timescales; modes of precessing systems still vary on orbital timescales, though even this variation could be factored out. """ function coorbital_waveform( inspiral; ell_min=2, ell_max=8, ℓₘᵢₙ=ell_min, ℓₘₐₓ=ell_max, PNOrder=pn_order(_pnsystem(inspiral)), ) storage = coorbital_waveform_computation_storage(inspiral; ℓₘᵢₙ, ℓₘₐₓ, PNOrder) return coorbital_waveform!(storage, inspiral; ℓₘᵢₙ, ℓₘₐₓ, PNOrder) end """ inertial_waveform_computation_storage(inspiral; [ℓₘᵢₙ=2], [ℓₘₐₓ=8], [PNOrder]) inertial_waveform_computation_storage(inspiral; [ell_min=2], [ell_max=8], [PNOrder]) Construct storage needed to compute waveforms in the inertial frame without allocations. This returns the storage for the waveforms themselves, storage used for computing the Wigner 𝔇 matrices, and for "in-place" multiplication. The returned quantity can just be passed as the first argument to [`inertial_waveform!`](@ref) without being unpacked. The meaning of the arguments is the same as in [`inertial_waveform`](@ref). """ function inertial_waveform_computation_storage( inspiral; ell_min=2, ell_max=8, ℓₘᵢₙ=ell_min, ℓₘₐₓ=ell_max, PNOrder=pn_order(_pnsystem(inspiral)), ) h, pnsystem = coorbital_waveform_computation_storage(inspiral; ℓₘᵢₙ, ℓₘₐₓ, PNOrder) (D, H_rec_coeffs, eⁱᵐᵅ, eⁱᵐᵞ) = Dprep(ℓₘₐₓ, eltype(inspiral)) hᵢ = similar(h[:, 1]) return h, pnsystem, D, H_rec_coeffs, eⁱᵐᵅ, eⁱᵐᵞ, hᵢ end """ inertial_waveform!(storage, inspiral; [ℓₘᵢₙ=2], [ℓₘₐₓ=8], [PNOrder]) inertial_waveform!(storage, inspiral; [ell_min=2], [ell_max=8], [PNOrder]) Evaluate the post-Newtonian waveform mode weights in the inertial frame for the given `inspiral` output by [`orbital_evolution`](@ref), using pre-allocated storage. The storage is assumed to be the object returned from [`inertial_waveform_computation_storage`](@ref). Other arguments are the same as in [`inertial_waveform`](@ref). """ function inertial_waveform!( storage, inspiral; ell_min=2, ell_max=8, ℓₘᵢₙ=ell_min, ℓₘₐₓ=ell_max, PNOrder=pn_order(storage[2]), ) h, pnsystem, D, H_rec_coeffs, eⁱᵐᵅ, eⁱᵐᵞ, hᵢ = storage @assert length(pnsystem.state) == length(inspiral.u[1]) @assert length(inspiral) == size(h, 2) @assert (ℓₘₐₓ + 1)^2 - ℓₘᵢₙ^2 == size(h, 1) @inbounds @fastmath for iₜ ∈ eachindex(inspiral) pnsystem.state .= inspiral.u[iₜ] h!(@view(h[:, iₜ]), pnsystem; ℓₘᵢₙ, ℓₘₐₓ) D!(D, conj(R(pnsystem)), ℓₘₐₓ, H_rec_coeffs, eⁱᵐᵅ, eⁱᵐᵞ) f′ = Yiterator(hᵢ, ℓₘₐₓ, ℓₘᵢₙ, 1) f = Yiterator(h[:, iₜ], ℓₘₐₓ, ℓₘᵢₙ, 1) 𝔇 = Diterator(D, ℓₘₐₓ, ℓₘᵢₙ) for (f′ˡ, fˡ, 𝔇ˡ) ∈ zip(f′, f, 𝔇) mul!(f′ˡ, 𝔇ˡ, fˡ) end h[:, iₜ] .= hᵢ end return h end """ inertial_waveform(inspiral; [ℓₘᵢₙ=2], [ℓₘₐₓ=8], [PNOrder]) inertial_waveform(inspiral; [ell_min=2], [ell_max=8], [PNOrder]) Evaluate the post-Newtonian waveform mode weights in the inertial frame for the given `inspiral` output by [`orbital_evolution`](@ref). The inertial frame is the one in which inertial observers are found, so this waveform is more like one that actual observers would detect. This function transforms the waveform from the co-orbital frame — which is the one in which PN expressions are provided. See [`coorbital_waveform`](@ref) for details about the other arguments and returned quantity. """ function inertial_waveform( inspiral; ell_min=2, ell_max=8, ℓₘᵢₙ=ell_min, ℓₘₐₓ=ell_max, PNOrder=pn_order(_pnsystem(inspiral)), ) storage = inertial_waveform_computation_storage(inspiral; ℓₘᵢₙ, ℓₘₐₓ, PNOrder) return inertial_waveform!(storage, inspiral; ℓₘᵢₙ, ℓₘₐₓ, PNOrder) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
3581
""" superkick(;v=0.2, χ=0.99, PNOrder=typemax(Int)) superkick(;v=0.2, chi=0.99, PNOrder=typemax(Int)) Construct a black-hole binary in "superkick" configuration. This is the scenario first published by [Campanelli et al. (2007)](https://arxiv.org/abs/gr-qc/0701164), which has equal-mass black holes with spins of equal magnitude oriented in opposite directions in the orbital plane. This configuration produces large asymmetrical emission of gravitational-wave linear momentum along the ``+z`` or ``-z`` directions, depending on which part of the orbit the binary is in. Depending on when the system mergers, the remnant may then acquire a huge recoil velocity. (That recoil velocity, of course, depends on details of the merger, which post-Newtonian approximations cannot describe. Therefore, we cannot actually use PN methods to derive any useful information about the remnant.) Note that the name "superkick" appeared in the literature before a class of systems that can achieve even larger recoil velocities: see [`hangup_kick`](@ref) for such systems. # Examples ```julia-repl julia> pnsystem = superkick(v=0.1) BBH{Vector{Float64}, 9223372036854775805//2}([0.5, 0.5, 0.99, 0.0, 0.0, -0.99, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.1, 0.0]) julia> inspiral = orbital_evolution(pnsystem); julia> inspiral[:v, 1] 0.1 julia> absvec(PostNewtonian.χ⃗₁(inspiral[1])) 0.99 ``` """ function superkick(; v=0.2, chi=0.99, χ=chi, PNOrder=typemax(Int)) M₁ = M₂ = 0.5 χ⃗₁ = [χ, 0, 0] χ⃗₂ = [-χ, 0, 0] R = Rotor(1) return BBH(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, PNOrder) end @doc raw""" hangup_kick(;v=0.2, χ=0.99, θ=deg2rad(50.98), ϕ=deg2rad(30.0), PNOrder=typemax(Int)) hangup_kick(;v=0.2, chi=0.99, theta=deg2rad(50.98), phi=deg2rad(30.0), PNOrder=typemax(Int)) Construct a black-hole binary in [hangup-kick](https://arxiv.org/abs/1908.04382) configuration. The spin magnitudes are both equal to `χ`. The direction of ``\vec{\chi}_1`` is given by the spherical coordinates (`θ`, `ϕ`). ``\vec{\chi}_2`` is the same, except that its projection into the orbital plane is opposite to that of ``\vec{\chi}_1``. See also [`superkick`](@ref) for the original systems, which can't actually achieve recoil kicks as large as those achieved by "hangup-kick" systems. The physical mechanism here is similar to the one described in [`superkick`](@ref), with an additional "hangup" due to the fact that the spins have components parallel to the orbital angular velocity. The physical interpretation of that part is that any system with such spin components will not merge as quickly because the remnant black hole must have total dimensionless spin less than 1, so excess angular momentum must be radiated away. This gives the hangup-kick configuration more time to develop a large recoil. # Examples ```julia-repl julia> pnsystem = hangup_kick(v=0.1) BBH{Vector{Float64}, 9223372036854775805//2}([0.5, 0.5, 0.3845784887294712, 0.6661094819774992, 0.6232957115416596, -0.3845784887294712, -0.6661094819774992, 0.6232957115416596, 1.0, 0.0, 0.0, 0.0, 0.1, 0.0]) julia> inspiral = orbital_evolution(pnsystem); julia> inspiral[:v, 1] 0.1 julia> absvec(PostNewtonian.χ⃗₁(inspiral[1])) 0.99 ``` """ function hangup_kick(; v=0.2, chi=0.99, χ=chi, theta=deg2rad(50.98), θ=theta, phi=deg2rad(30.0), ϕ=phi, PNOrder=typemax(Int), ) M₁ = M₂ = 0.5 χ⃗₁ = χ * [sin(ϕ) * sin(θ), cos(ϕ) * sin(θ), cos(θ)] χ⃗₂ = χ * [-sin(ϕ) * sin(θ), -cos(ϕ) * sin(θ), cos(θ)] R = Rotor(1) return BBH(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, PNOrder) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
3367
@doc raw""" rand([rng=default_rng()], pnclass; [v=0.2], [PNOrder=typemax(Int)]) Generate a random PNSystem, specifically of class `pnclass` (one of [`BBH`](@ref), [`BHNS`](@ref), or [`NSNS`](@ref)), with parameters chosen to be consistent with typical LIGO/Virgo/KAGRA searches as of this writing. # Examples ```julia-repl julia> pnsystem = rand(BBH); julia> inspiral = orbital_evolution(pnsystem); ``` # Parameter ranges Choosing the space of parameters from which to randomly select values is nontrivial. The most relevant numbers are of two types from LIGO/Virgo/KAGRA: (1) the range of parameters over which systems are *searched for*, and (2) the range of parameters used as priors in parameter estimation. Appendix B1 of LIGO's [GWTC-1 catalog paper](https://arxiv.org/abs/1811.12907) says that the "spin vectors are assumed to be isotropic on the sphere and uniform in spin magnitude", with two choices of uniform magnitude: ``a_i \leq 0.89`` and ``a_i \leq 0.05``. The dimensionless tidal deformabilities ``\Lambda_i`` of each NS are assumed to be jointly uniform within ``0 \leq \Lambda_i \leq 5000``. The more current [GWTC-3 paper](https://arxiv.org/abs/2111.03606) searches with the following: > The PyCBC-BBH analysis focuses on a region ranging in primary component mass from 5M to > 350M, with mass ratios from 1/3 to 1, and effective spins ranging from ``\chi_\mathrm{eff} > = −0.998`` to ``0.998``. That paper's parameter estimation uses uniform priors over spin magnitudes and redshifted component masses; isotropic spin orientation, sky location and binary orientation; mass-ratio ``q \in [0.05, 1]`` (sometimes extending down to ``q=0.02``). It seems that the actual ranges of the spin magnitudes and masses are restricted based on initial guesses, which may be expanded to ensure that the posteriors lie entirely within the priors. The distance priors are uniform in ``D_\mathrm{L}^2``, with some adjustments due to cosmology. For the purposes of this package, we're not too interested in absolute scales — specifically distance or total mass — so we'll just choose the total mass to be ``1`` at the initial frequency, then sample based on mass ratio and spin magnitudes. Given these, it seems like the current state of the art would be well covered by choosing a random `q` ∈ [0.05, 1], `χᵢ` ∈ [0, 0.998], and `Λᵢ` ∈ [0, 5000], with isotropic choices for orientations. Note that the `Λᵢ` are only used if the input `pnclass` is `BHNS` or `NSNS`. If you would prefer a different range of parameters, the source code for this function is easily modified. """ function Base.rand(pnclass::Type{P}; v::T=0.2, PNOrder=typemax(Int)) where {P<:PNSystem,T} return rand(default_rng(), pnclass; v, PNOrder) end function Base.rand( rng::AbstractRNG, pnclass::Type{P}; v::T=0.2, PNOrder=typemax(Int) ) where {P<:PNSystem,T} qₘᵢₙ = T(big"0.05") # Note that we're using q≤1 here for consistency with LIGO χₘₐₓ = T(big"0.998") Λₘₐₓ = T(big"5000.0") q = rand(rng, T) * (1 - qₘᵢₙ) + qₘᵢₙ M₁ = 1 / (q + 1) M₂ = q / (q + 1) χ⃗₁ = χₘₐₓ * rand(rng, T) * normalize(randn(rng, QuatVec{T})) χ⃗₂ = χₘₐₓ * rand(rng, T) * normalize(randn(rng, QuatVec{T})) R = randn(rng, Rotor{T}) Λ₁ = Λₘₐₓ * rand(rng, T) Λ₂ = Λₘₐₓ * rand(rng, T) return pnclass(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, Λ₁, Λ₂, PNOrder) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
9177
module GWFrames using ..PostNewtonian using Quaternionic: Quaternionic, QuatVec, Rotor """ PNWaveform(Approximant, delta, chi1_i, chi2_i, Omega_orb_i; kwargs...) Compute a PN waveform, with the same call signature as `GWFrames.PNWaveform` This is essentially a compatibility layer for the corresponding function in the original [`GWFrames`](https://github.com/moble/GWFrames/blob/01b39bfe/Code/PNWaveforms.cpp#L83-L88) Python package, with several additional optional arguments: `inertial`, `dt`, `quiet`, `ell_min`, `ell_max`, `Lambda1`, and `Lambda2` (see below). Also, this function accepts optional arguments either as positional arguments (which the original `GWFrames` requires) or as keyword arguments. !!! warning We do *not* expect the result of this function to be identical to the result from the `GWFrames` Python package. In particular, this package uses more general expressions for the tidal-heating terms, fixes an error in the 2PN quadratic-spin terms for the waveform modes, uses more accurate (and efficient) ODE integration, and uses a more accurate method to compute the number of steps per orbit (by default). Also note that there are differences in the order of operations for computing intermediate variables. Cancellation and roundoff error caused by these differences can have surprisingly large effects on the orbital evolution in many cases — particularly for precessing systems. Results from the two packages have been painstakingly analyzed, leading to the conclusion that all differences are caused by such errors or the differences in formulations mentioned above. The Julia interface is more detailed, flexible, and efficient than the simple `GWFrames` interface that this function emulates. In particular, [`orbital_evolution`](@ref) takes essentially all the same arguments that [`DifferentialEquations.solve`](https://diffeq.sciml.ai/dev/basics/common_solver_opts/) takes, and returns a [`solution`](https://diffeq.sciml.ai/dev/basics/solution/) that provides dense output and more details about the ODE solution itself. For example, one reason this function is more efficient than `GWFrames` is that we can use dense output to solve with fewer timesteps, while accurately and efficiently interpolating to the requested timesteps. While `orbital_evolution` solves for the dynamics, [`coorbital_waveform`](@ref) or [`inertial_waveform`](@ref) provides the actual waveform; both are returned by this function. ## Required arguments * `Approximant`: Currently, supported arguments are `"TaylorT1"`, `"TaylorT4"`, and `"TaylorT5"`. * `delta`: Fractional mass difference ``(M₁-M₂)/(M₁+M₂)`` * `chi1_i`: Normalized spin vector ``S⃗₁/M₁²`` * `chi2_i`: Normalized spin vector ``S⃗₂/M₂²`` * `Omega_orb_i`: Orbital angular frequency at initial instant ## Optional arguments As mentioned above, the following may be given *either* as positional arguments in this order (though any number of them may be omitted from the end), or as keyword arguments. * `Omega_orb_0=Omega_orb_i`: Orbital angular frequency at first instant found in data. If this is less than `Omega_orb_i`, the system is integrated backwards in time from the latter value to this value. * `R_frame_i=Rotor(1)`: Initial orientation of the frame. * `MinStepsPerOrbit=32`: Number of time steps in the output data per orbit. Because the waveform modes go as high as ``m=8``, this number should be at least 16 to avoid Nyquist aliasing in those modes. Note that this value may be overridden by `dt` (see below). * `PNWaveformModeOrder=4.0`: Maximum PN order of terms in the waveform formulas. * `PNOrbitalEvolutionOrder=4.0`: Maximum PN order of terms in the orbital-evolution formulas. * `inertial=false`: If `true`, transform waveform to the inertial frame; otherwise, the waveform will be in the co-orbital frame. * `dt=0`: Uniform time step size of the output. If this is not a strictly positive number, `MinStepsPerOrbit` will be used instead. * `quiet=true`: If `false`, show informational messages about the reasons for terminating the ODE integration. In either case, warnings will still be issued if terminating for bad or suspicious reasons. See the documentation of [`orbital_evolution`](@ref) for an example of how to filter warnings also. * `ell_min=2`: The lowest ℓ value in the output waveform. * `ell_max=8`: The highest ℓ value in the output waveform. * `Lambda1=0`: Tidal-coupling parameter of object 1. * `Lambda2=0`: Tidal-coupling parameter of object 2. ## Returned values This function returns a NamedTuple with the following keys: * `t`: The vector of time steps at which the data are evaluated. The time ``t=0`` corresponds to the initial values that are arguments to this function. * `data`: Matrix of complex values of the mode weights. The shape is length(t) x 77. The first dimension enumerates the values at each instant of time. The second dimension enumerates the modes, starting with ``(2,-2)``, then ``(2,-1)``, up to ``(2,2)``, followed by ``(3,-3)``, and so on up to ``(8,8)``. This is the opposite ordering as results from `GWFrames`, but the same as the ordering used by the `sxs` and `scri` packages. However, also note that certain conversions between Julia and Python *may* transpose matrices, because Julia is Fortran-ordered by default, whereas numpy is C-ordered. It is best to check the shape manually to be sure which dimension is which. * `frame`: Matrix of shape length(t) x 4 representing the frame-orientation quaternion as a function of time `t`. * `M1`, `M2`: Vectors of the respective masses as functions of time `t`. Note that only at the time corresponding to `Omega_orb_i` will the total mass be precisely 1. Generally, tidal heating will lead to time-dependent masses. * `chi1`, `chi2`: Matrices of shape length(t) x 3 representing the spins as functions of time `t`. * `v`: PN velocity parameter as a function of time `t`. * `Phi`: Orbital phase as a function of time `t`. Because this is a NamedTuple, the fields can be accessed much like the fields of a `WaveformModes` object in the `scri` or `sxs` Python packages — as in `w.t` and `w.data`, where `w` is the object returned by this function. """ function PNWaveform( Approximant::String, delta, chi1_i, chi2_i, Omega_orb_i, Omega_orb_0, R_frame_i=[1.0], MinStepsPerOrbit=32, PNWaveformModeOrder=4.0, PNOrbitalEvolutionOrder=4.0, inertial=false, dt=0.0, quiet=true, ell_min=2, ell_max=8, Lambda1=0, Lambda2=0, kwargs..., ) # Note that this method's signature is missing the `Omega_orb_0` default # value; if it is not given, Julia selects the other (keyword-based) # method, which does have a default method for it. return PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i; Omega_orb_0, R_frame_i, MinStepsPerOrbit, PNWaveformModeOrder, PNOrbitalEvolutionOrder, inertial, dt, quiet, ell_min, ell_max, Lambda1, Lambda2, kwargs..., ) end function PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i; Omega_orb_0=Omega_orb_i, R_frame_i=[1.0], MinStepsPerOrbit=32, PNWaveformModeOrder=4.0, PNOrbitalEvolutionOrder=4.0, inertial=false, dt=0.0, quiet=true, ell_min=2, ell_max=8, Lambda1=0, Lambda2=0, kwargs..., ) M₁ = (1 + delta) / 2 M₂ = (1 - delta) / 2 χ⃗₁ = QuatVec(chi1_i) χ⃗₂ = QuatVec(chi2_i) Ωᵢ = Omega_orb_i Ω₁ = Omega_orb_0 Rᵢ = Rotor(R_frame_i) saveat = if dt > 0.0 if haskey(kwargs, :saveat) error("GWFrames.PNWaveform received both `dt` and `saveat` arguments") end dt elseif haskey(kwargs, :saveat) kwargs = Dict(kwargs) pop!(kwargs, :saveat) else [] end # Inspiral solution = orbital_evolution( M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; Λ₁=Lambda1, Λ₂=Lambda2, Ω₁=Ω₁, Rᵢ=Rᵢ, approximant=Approximant, PNOrder=PNOrbitalEvolutionOrder, quiet=quiet, saveat, kwargs..., ) if saveat == [] solution = uniform_in_phase(solution, MinStepsPerOrbit) end # Waveform h = if inertial inertial_waveform(solution; ℓₘᵢₙ=ell_min, ℓₘₐₓ=ell_max, PNOrder=PNWaveformModeOrder) else coorbital_waveform(solution; ℓₘᵢₙ=ell_min, ℓₘₐₓ=ell_max, PNOrder=PNWaveformModeOrder) end # Return return ( t=solution.t, data=transpose(h), frame=transpose(stack(solution[[:Rʷ, :Rˣ, :Rʸ, :Rᶻ]])), M1=solution[:M₁], M2=solution[:M₂], chi1=transpose(stack(solution[[:χ⃗₁ˣ, :χ⃗₁ʸ, :χ⃗₁ᶻ]])), chi2=transpose(stack(solution[[:χ⃗₂ˣ, :χ⃗₂ʸ, :χ⃗₂ᶻ]])), v=solution[:v], Phi=solution[:Φ], ) end end # module GWFrames
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
7985
""" rₕ₁(s) Horizon radius of black hole 1. As defined on page 2, line 4, of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020). See the documentation section on ["Horizons"](@ref Horizons) for more details. """ rₕ₁(s::VecOrPNSystem) = M₁(s) * (1 + √(1 - min(χ₁²(s), 1))) """ rₕ₂(s) Horizon radius of black hole 2. As defined on page 2, line 4, of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020). See the documentation section on ["Horizons"](@ref Horizons) for more details. """ rₕ₂(s::VecOrPNSystem) = M₂(s) * (1 + √(1 - min(χ₂²(s), 1))) """ Ωₕ₁(s) Horizon angular velocity of black hole 1. As defined on page 2, line 5, of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020). See the documentation section on ["Horizons"](@ref Horizons) for more details. """ Ωₕ₁(s::VecOrPNSystem) = χ₁(s) / 2rₕ₁(s) """ Ωₕ₂(s) Horizon angular velocity of black hole 2. As defined on page 2, line 5, of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020). See the documentation section on ["Horizons"](@ref Horizons) for more details. """ Ωₕ₂(s::VecOrPNSystem) = χ₂(s) / 2rₕ₂(s) """ sin²θ₁(s) Sine-squared of angle between spin of black hole 1 and vector to black hole 2. Compare to Eq. (18) of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020). See the documentation section on ["Horizons"](@ref Horizons) for more details. """ function sin²θ₁(s::VecOrPNSystem) let χ₁² = χ₁²(s) ifelse(iszero(χ₁²), one(χ₁²), abs2vec(n̂(s) × χ⃗₁(s)) / χ₁²) end end """ sin²θ₂(s) Sine-squared of angle between spin of black hole 2 and vector to black hole 1. Compare to Eq. (18) of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020). See the documentation section on ["Horizons"](@ref Horizons) for more details. """ function sin²θ₂(s::VecOrPNSystem) let χ₂² = χ₂²(s) ifelse(iszero(χ₂²), one(χ₂²), abs2vec(n̂(s) × χ⃗₂(s)) / χ₂²) end end @doc raw""" ϕ̇̂₁(s) Rate of rotation of black hole 2 about the spin of black hole 1, relative to orbital rotation rate. This is the rotation rate ϕ̇ as defined in Eq. (19) of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020), divided by ``v^3 = M\, \Omega``. This division is done to make sure we can track the relative PN order of terms that depend on this. See the documentation section on ["Horizons"](@ref Horizons) for more details. """ function ϕ̇̂₁(s::VecOrPNSystem) let χ₁ = χ₁(s), sin²θ₁ = sin²θ₁(s), M = M(s) ifelse( iszero(χ₁), inv(M), ifelse(iszero(sin²θ₁), zero(χ₁), ℓ̂(s) ⋅ χ⃗₁(s) / (M * χ₁ * sin²θ₁)), ) end end @doc raw""" ϕ̇̂₂(s) Rate of rotation of black hole 1 about the spin of black hole 2, relative to orbital rotation rate. This is the rotation rate ϕ̇ as defined in Eq. (19) of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020), divided by ``v^3 = M\, \Omega``. This division is done to make sure we can track the relative PN order of terms that depend on this. See the documentation section on ["Horizons"](@ref Horizons) for more details. """ function ϕ̇̂₂(s::VecOrPNSystem) let χ₂ = χ₂(s), sin²θ₂ = sin²θ₂(s), M = M(s) ifelse( iszero(χ₂), inv(M), ifelse(iszero(sin²θ₂), zero(χ₂), ℓ̂(s) ⋅ χ⃗₂(s) / (M * χ₂ * sin²θ₂)), ) end end @doc raw""" Î₀₁(s) Horizon moment of inertia of black hole 1. This is the moment divided by ``ν^2 v^{12}``, as given by Eq. (10) of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020). See the documentation section on ["Horizons"](@ref Horizons) for more details. """ function Î₀₁(s::VecOrPNSystem) let χ₁² = χ₁²(s), sin²θ₁ = sin²θ₁(s) (16rₕ₁(s) / 5M(s)^2) * M₁(s)^3 * sin²θ₁ * (1 - 3//4 * χ₁² + 15//4 * χ₁² * sin²θ₁) end end @doc raw""" Î₀₂(s) Horizon moment of inertia of black hole 2. This is the moment divided by ``ν^2 v^{12}``, as given by Eq. (10) of [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020). See the documentation section on ["Horizons"](@ref Horizons) for more details. """ function Î₀₂(s::VecOrPNSystem) let χ₂² = χ₂²(s), sin²θ₂ = sin²θ₂(s) (16rₕ₂(s) / 5M(s)^2) * M₂(s)^3 * sin²θ₂ * (1 - 3//4 * χ₂² + 15//4 * χ₂² * sin²θ₂) end end @doc raw""" κ₁(s) The "quadrupolar polarisability" of object 1 used by [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). Note that Bohé et al. refer to the closely related (and co-authored) [Marsat (2014)](https://arxiv.org/abs/1411.4118), who notes above Eq. (4.7) that this is denoted ``C_{\mathrm{ES}^2}`` in [Levi and Steinhoff (2014)](https://arxiv.org/abs/1410.2601), who in turn notes that "we can set ... the Wilson coefficients ``C_{\mathrm{ES}^2} = C_{\mathrm{BS}^3} = 1`` for the black hole case." However, a very similar constant ``\kappa_A`` is used in Eq. (2.1) of [Buonanno et al. (2012)](https://arxiv.org/abs/1209.6349). They say that ``\kappa_A=1`` for an *isolated* black hole, but can deviate from 1 for a black hole in a binary — though those deviations occur at "much higher" order than those they consider (2PN). See also [`λ₁`](@ref). !!! warn This function will be incorrect for objects other than black holes. It is not clear to me if this is the same quantity as ``C_Q`` used in some papers, such as [Bini and Geralico (2014)](https://arxiv.org/abs/1408.5261), but they point out that for neutron stars, the value varies between 4.3 and 7.4, depending on the equation of state. This quantity may also be related to [`λ₁`](@ref). Pull requests or issues with more information are welcome. """ function κ₁(s::VecOrPNSystem) return one(eltype(s)) end """ κ₂(s) The "quadrupolar polarisability" of object 2 used by [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). See [`κ₁`](@ref) for more details. """ function κ₂(s::VecOrPNSystem) return one(eltype(s)) end """ κ₊(s) Equal to [`κ₁`](@ref)` + `[`κ₂`](@ref); defined below Eq. (3.28) of [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). """ function κ₊(s::VecOrPNSystem) return κ₁(s) + κ₂(s) end """ κ₋(s) Equal to [`κ₁`](@ref)` - `[`κ₂`](@ref); defined below Eq. (3.28) of [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). """ function κ₋(s::VecOrPNSystem) return κ₁(s) - κ₂(s) end @doc raw""" λ₁(s) The "quadrupolar polarisability" of object 1 used by [Marsat (2014)](https://arxiv.org/abs/1411.4118), who notes above Eq. (4.11) that this is denoted ``C_{\mathrm{BS}^2}`` in [Levi and Steinhoff (2014)](https://arxiv.org/abs/1410.2601), who in turn notes that "we can set ... the Wilson coefficients ``C_{\mathrm{ES}^2} = C_{\mathrm{BS}^3} = 1`` for the black hole case." See also [`κ₁`](@ref). !!! warn This function will be incorrect for objects other than black holes. It is not clear to me if this is the same quantity as ``C_Q`` used in some papers, such as [Bini and Geralico (2014)](https://arxiv.org/abs/1408.5261), but they point out that for neutron stars, the value varies between 4.3 and 7.4, depending on the equation of state. This quantity may also be related to [`λ₁`](@ref). Pull requests or issues with more information are welcome. """ function λ₁(s::VecOrPNSystem) return one(eltype(s)) end """ λ₂(s) The "quadrupolar polarisability" of object 2 used by [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). See [`λ₁`](@ref) for more details. """ function λ₂(s::VecOrPNSystem) return one(eltype(s)) end """ λ₊(s) Equal to [`λ₁`](@ref)` + `[`λ₂`](@ref); defined below Eq. (3.28) of [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). """ function λ₊(s::VecOrPNSystem) return λ₁(s) + λ₂(s) end """ λ₋(s) Equal to [`λ₁`](@ref)` - `[`λ₂`](@ref); defined below Eq. (3.28) of [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). """ function λ₋(s::VecOrPNSystem) return λ₁(s) - λ₂(s) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
2493
""" M(pnsystem) M(M₁, M₂) total_mass(pnsystem) total_mass(M1, M2) Compute the total mass ``M₁+M₂``. """ M(M₁, M₂) = M₁ + M₂ M(s::VecOrPNSystem) = M(M₁(s), M₂(s)) const total_mass = M """ μ(pnsystem) μ(M₁, M₂) reduced_mass(pnsystem) reduced_mass(M1, M2) Compute the reduced mass ``(M₁ M₂)/(M₁+M₂)``. """ μ(M₁, M₂) = (M₁ * M₂) / (M₁ + M₂) μ(s::VecOrPNSystem) = μ(M₁(s), M₂(s)) const reduced_mass = μ """ ν(pnsystem) ν(M₁, M₂) reduced_mass_ratio(pnsystem) reduced_mass_ratio(M1, M2) Compute the reduced mass ratio ``(M₁ M₂)/(M₁+M₂)^2``. Note that the denominator is squared, unlike in the reduced mass [`μ`](@ref). """ ν(M₁, M₂) = (M₁ * M₂) / (M₁ + M₂)^2 ν(s::VecOrPNSystem) = ν(M₁(s), M₂(s)) ν(; q) = q / (1 + q)^2 const reduced_mass_ratio = ν """ δ(pnsystem) δ(M₁, M₂) mass_difference_ratio(pnsystem) mass_difference_ratio(M1, M2) Compute mass-difference ratio ``(M₁-M₂)/(M₁+M₂)``. Note that we do not restrict to ``M₁ ≥ M₂`` or vice versa; if you prefer that ``δ`` always be positive (or always negative), you are responsible for ensuring that. """ δ(M₁, M₂) = (M₁ - M₂) / (M₁ + M₂) δ(s::VecOrPNSystem) = δ(M₁(s), M₂(s)) δ(; q) = (q - 1) / (q + 1) const mass_difference_ratio = δ """ q(pnsystem) q(M₁, M₂) mass_ratio(pnsystem) mass_ratio(M1, M2) Compute mass ratio ``M₁/M₂``. Note that we do not restrict to ``M₁ ≥ M₂`` or vice versa; if you prefer that ``q`` always be greater than or equal to 1 (or vice versa), you are responsible for ensuring that. """ q(M₁, M₂) = M₁ / M₂ q(s::VecOrPNSystem) = q(M₁(s), M₂(s)) const mass_ratio = q """ ℳ(pnsystem) ℳ(M₁, M₂) chirp_mass(pnsystem) chirp_mass(M1, M2) Compute the chirp mass ℳ, which determines the leading-order orbital evolution of a binary system due to energy loss by gravitational-wave emission. The chirp mass is defined as ```math \\mathcal{M} = \\frac{(M_1 M_2)^{3/5}} {(M_1 + M_2)^{1/5}}. ``` """ ℳ(M₁, M₂) = ((M₁ * M₂)^3 / (M₁ + M₂))^(1//5) ℳ(s::VecOrPNSystem) = ℳ(M₁(s), M₂(s)) const chirp_mass = ℳ """ X₁(pnsystem) X₁(M₁, M₂) X1(pnsystem) X1(M1, M2) Compute the reduced *individual* mass ``M₁/(M₁+M₂)``. """ X₁(M₁, M₂) = M₁ / (M₁ + M₂) X₁(s::VecOrPNSystem) = X₁(M₁(s), M₂(s)) const X1 = X₁ """ X₂(pnsystem) X₂(M₁, M₂) X2(pnsystem) X2(M1, M2) Compute the reduced *individual* mass ``M₂/(M₁+M₂)``. """ X₂(M₁, M₂) = M₂ / (M₁ + M₂) X₂(s::VecOrPNSystem) = X₂(M₁(s), M₂(s)) const X2 = X₂
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
1480
""" n̂(pnsystem) n̂(R) n_hat(pnsystem) n_hat(R) The unit vector pointing from object 2 to object 1, when the frame is given by the rotor `R`. This is equal to ```math n̂(R) = R x̂ R̄ ``` """ n̂(R) = QuatVec(R(𝐢)) n̂(s::VecOrPNSystem) = n̂(R(s)) const n_hat = n̂ """ λ̂(pnsystem) λ̂(R) lambda_hat(pnsystem) lambda_hat(R) The unit vector pointing in the direction of the instantaneous velocity of object 1, when the frame is given by the rotor `R`. This is equal to ```math λ̂(R) = R ŷ R̄ ``` This also completes the right-handed triple of ``(n̂, λ̂, ℓ̂)``. """ λ̂(R) = QuatVec(R(𝐣)) λ̂(s::VecOrPNSystem) = λ̂(R(s)) const lambda_hat = λ̂ """ ℓ̂(pnsystem) ℓ̂(R) ell_hat(pnsystem) ell_hat(R) The unit vector pointing along the direction of orbital angular velocity, when the frame is given by the rotor `R`. This is equal to ```math ℓ̂(R) = R ẑ R̄ ``` """ ℓ̂(R) = QuatVec(R(𝐤)) ℓ̂(s::VecOrPNSystem) = ℓ̂(R(s)) const ell_hat = ℓ̂ @doc raw""" Ω(pnsystem) Ω(;v, M=1) Omega(pnsystem) Omega(;v, M=1) Orbital angular frequency. The parameter `v` is the PN velocity parameter, and must be passed as a keyword argument — as in `Ω(v=0.1)`. The parameter `M` is the total mass of the binary. They are related *by definition* as ```math \Omega \colonequals \frac{v^3}{M}. ``` See also [`v`](@ref). """ Ω(; v, M=1) = v^3 / M Ω(s::VecOrPNSystem) = Ω(; v=v(s), M=M(s)) const Omega = Ω lnv(s::VecOrPNSystem) = ln(v(s))
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
6766
""" S⃗₁(pnsystem) Dimensionful spin vector of object 1. """ S⃗₁(s::VecOrPNSystem) = χ⃗₁(s) * M₁(s)^2 """ S⃗₂(pnsystem) Dimensionful spin vector of object 2. """ S⃗₂(s::VecOrPNSystem) = χ⃗₂(s) * M₂(s)^2 """ S⃗(pnsystem) S⃗(M₁, M₂, χ⃗₁, χ⃗₂) Total (dimensionful) spin vector ``S⃗₁+S⃗₂``. """ S⃗(M₁, M₂, χ⃗₁, χ⃗₂) = χ⃗₁ * M₁^2 + χ⃗₂ * M₂^2 S⃗(s::VecOrPNSystem) = S⃗(M₁(s), M₂(s), χ⃗₁(s), χ⃗₂(s)) """ Σ⃗(pnsystem) Σ⃗(M₁, M₂, χ⃗₁, χ⃗₂) Differential spin vector ``M(a⃗₂-a⃗₁)``. """ Σ⃗(M₁, M₂, χ⃗₁, χ⃗₂) = (M₁ + M₂) * (χ⃗₂ * M₂ - χ⃗₁ * M₁) Σ⃗(s::VecOrPNSystem) = Σ⃗(M₁(s), M₂(s), χ⃗₁(s), χ⃗₂(s)) """ χ⃗(pnsystem) χ⃗(S⃗, M) Normalized spin vector ``S⃗/M²``. """ χ⃗(S⃗, M) = S⃗ / M^2 χ⃗(s::VecOrPNSystem) = χ⃗(S⃗(s), M(s)) """ χ⃗ₛ(M₁, M₂, χ⃗₁, χ⃗₂) Symmetric spin vector ``(χ⃗₁+χ⃗₂)/2``. """ χ⃗ₛ(χ⃗₁, χ⃗₂) = (χ⃗₁ + χ⃗₂) / 2 χ⃗ₛ(M₁, M₂, χ⃗₁, χ⃗₂) = (χ⃗₁ + χ⃗₂) / 2 χ⃗ₛ(s::VecOrPNSystem) = χ⃗ₛ(M₁(s), M₂(s), χ⃗₁(s), χ⃗₂(s)) """ χ⃗ₐ(M₁, M₂, χ⃗₁, χ⃗₂) Antisymmetric spin vector ``(χ⃗₁-χ⃗₂)/2``. """ χ⃗ₐ(χ⃗₁, χ⃗₂) = (χ⃗₁ - χ⃗₂) / 2 χ⃗ₐ(M₁, M₂, χ⃗₁, χ⃗₂) = (χ⃗₁ - χ⃗₂) / 2 χ⃗ₐ(s::VecOrPNSystem) = χ⃗ₐ(M₁(s), M₂(s), χ⃗₁(s), χ⃗₂(s)) χₚₑᵣₚ(s::VecOrPNSystem) = √(χ₁²(s) - (χ₁ₗ(s))^2 + χ₂²(s) - (χ₂ₗ(s))^2) const chi_perp = χₚₑᵣₚ @doc raw""" χₑ(s) chi_eff(s) Effective spin parameter of the system. Defined as ```math \chi_{\mathrm{eff}} \colonequals \frac{c}{G} \left( \frac{\mathbf{S}_1}{M_1} + \frac{\mathbf{S}_2}{M_2} \right) \cdot \frac{\hat{\mathbf{L}}_{\mathrm{N}}} {M}. ``` """ function χₑ(s::VecOrPNSystem) return (S₁ₗ(s) / M₁(s) + S₂ₗ(s) / M₂(s)) / M(s) end const chi_eff = χₑ @doc raw""" χₚ(s) chi_p(s) Effective precession spin parameter of the system. Note that there are *two different* definitions of this quantity found in the literature. The [original definition](https://arxiv.org/abs/1408.1810) (converted to the convention where ``M_1 \geq M_2``) is ```math \begin{gathered} A_1 = 2 + \frac{3M_2}{2M_1} \\ A_2 = 2 + \frac{3M_1}{2M_2} \\ \chi_{\mathrm{p}} \colonequals \frac{1}{A_1 M_1^2} \mathrm{max}\left(A_1 S_{1\perp}, A_2 S_{2\perp} \right). \end{gathered} ``` In a paper from early in the detection era, the [LIGO collaboration used this definition](https://arxiv.org/abs/1606.01210). However, a [more recent paper](https://arxiv.org/abs/2010.04131) redefines this essentially as ``M_1^2`` times that quantity. Using the convention that ``q = M_2/M_1 \leq 1``, the definition may be more compactly written as ```math \chi_{\mathrm{p}} \colonequals \mathrm{max} \left( \chi_{1\perp}, \chi_{2\perp} q \frac{4q+3}{4+3q} \right). ``` Again, a more recent paper by [LIGO/Virgo/KAGRA](https://arxiv.org/abs/2111.03606) uses this convention. Because it seems to be the trend, this function uses the latter definition. """ function χₚ(s::VecOrPNSystem) χ₁ₚₑᵣₚ = √(χ₁ₙ(s)^2 + χ₁λ(s)^2) χ₂ₚₑᵣₚ = √(χ₂ₙ(s)^2 + χ₂λ(s)^2) let q = 1 / q(s) # This is to convert to LVK's convention if q > 1 q, χ₁ₚₑᵣₚ, χ₂ₚₑᵣₚ = 1 / q, χ₂ₚₑᵣₚ, χ₁ₚₑᵣₚ end max(χ₁ₚₑᵣₚ, χ₂ₚₑᵣₚ * q * (4q + 3) / (4 + 3q)) end # let M₁=M₁(s), M₂=M₂(s) # if M₁ < M₂ # M₁, M₂ = M₂, M₁ # end # B₁ = 2 + 3M₂ / 2M₁ # B₂ = 2 + 3M₁ / 2M₂ # S₁ₚₑᵣₚ = √(S₁ₙ(s)^2 + S₁λ(s)^2) # S₂ₚₑᵣₚ = √(S₂ₙ(s)^2 + S₂λ(s)^2) # max(B₁*S₁ₚₑᵣₚ, B₂*S₂ₚₑᵣₚ) / (B₁*M₁^2) # end end const chi_p = χₚ @doc raw""" S⃗₀⁺(s) S⃗₀⁺(M₁, M₂, κ₁, κ₂, S⃗₁, S⃗₂) Defined in Eq. (3.4) of [Buonanno et al. (2012)](https://arxiv.org/abs/1209.6349): ```math \vec{S}_0^+ = \frac{M}{M_1} \left( \frac{\kappa_1} {\kappa_2} \right)^{1/4} \left( 1 + \sqrt{1 - \kappa_1 \kappa_2} \right)^{1/2} \vec{S}_1 + \frac{M}{M_2} \left( \frac{\kappa_2} {\kappa_1} \right)^{1/4} \left( 1 - \sqrt{1 - \kappa_1 \kappa_2} \right)^{1/2} \vec{S}_2. ``` Note that, currently, ``\kappa_1`` and ``\kappa_2`` are both assumed to be equal to 1, as is the case for black holes. You can define `κ₁` and `κ₂` to have other values for your own `PNSystem` types, and this function will work appropriately. See also [`S⃗₀⁻`](@ref). """ S⃗₀⁺(s::VecOrPNSystem) = S⃗₀⁺(M₁(s), M₂(s), κ₁(s), κ₂(s), S⃗₁(s), S⃗₂(s)) function S⃗₀⁺(M₁, M₂, κ₁, κ₂, S⃗₁, S⃗₂) M = M₁ + M₂ κᵣ = (κ₁ / κ₂)^(1//4) return (M / M₁) * κᵣ * √(1 + √(1 - κ₁ * κ₂)) * S⃗₁ + (M / M₂) / κᵣ * √(1 - √(1 - κ₁ * κ₂)) * S⃗₂ end S₀⁺ₙ(s::VecOrPNSystem) = S⃗₀⁺(M₁(s), M₂(s), κ₁(s), κ₂(s), S₁ₙ(s), S₂ₙ(s)) S₀⁺λ(s::VecOrPNSystem) = S⃗₀⁺(M₁(s), M₂(s), κ₁(s), κ₂(s), S₁λ(s), S₂λ(s)) S₀⁺ₗ(s::VecOrPNSystem) = S⃗₀⁺(M₁(s), M₂(s), κ₁(s), κ₂(s), S₁ₗ(s), S₂ₗ(s)) @doc raw""" S⃗₀⁻(s) S⃗₀⁻(M₁, M₂, κ₁, κ₂, S⃗₁, S⃗₂) Defined below Eq. (3.4) of [Buonanno et al. (2012)](https://arxiv.org/abs/1209.6349): ```math \vec{S}_0^- = \frac{M}{M_1} \left( \frac{\kappa_1} {\kappa_2} \right)^{1/4} \left( 1 - \sqrt{1 - \kappa_1 \kappa_2} \right)^{1/2} \vec{S}_1 + \frac{M}{M_2} \left( \frac{\kappa_2} {\kappa_1} \right)^{1/4} \left( 1 + \sqrt{1 - \kappa_1 \kappa_2} \right)^{1/2} \vec{S}_2. ``` Note that, currently, ``\kappa_1`` and ``\kappa_2`` are both assumed to be equal to 1, as is the case for black holes. You can define `κ₁` and `κ₂` to have other values for your own `PNSystem` types, and this function will work appropriately. See also [`S⃗₀⁺`](@ref). """ S⃗₀⁻(s::VecOrPNSystem) = S⃗₀⁻(M₁(s), M₂(s), κ₁(s), κ₂(s), S⃗₁(s), S⃗₂(s)) S⃗₀⁻(M₁, M₂, κ₁, κ₂, S⃗₁, S⃗₂) = S⃗₀⁺(M₂, M₁, κ₂, κ₁, S⃗₂, S⃗₁) S₀⁻ₙ(s::VecOrPNSystem) = S⃗₀⁻(M₁(s), M₂(s), κ₁(s), κ₂(s), S₁ₙ(s), S₂ₙ(s)) S₀⁻λ(s::VecOrPNSystem) = S⃗₀⁻(M₁(s), M₂(s), κ₁(s), κ₂(s), S₁λ(s), S₂λ(s)) S₀⁻ₗ(s::VecOrPNSystem) = S⃗₀⁻(M₁(s), M₂(s), κ₁(s), κ₂(s), S₁ₗ(s), S₂ₗ(s)) χ₁²(s::VecOrPNSystem) = abs2vec(χ⃗₁(s)) χ₂²(s::VecOrPNSystem) = abs2vec(χ⃗₂(s)) χ₁(s::VecOrPNSystem) = absvec(χ⃗₁(s)) χ₂(s::VecOrPNSystem) = absvec(χ⃗₂(s)) χ₁₂(s::VecOrPNSystem) = χ⃗₁(s) ⋅ χ⃗₂(s) χₛₗ(s::VecOrPNSystem) = χ⃗ₛ(s) ⋅ ℓ̂(s) χₐₗ(s::VecOrPNSystem) = χ⃗ₐ(s) ⋅ ℓ̂(s) χ₁ₙ(s::VecOrPNSystem) = χ⃗₁(s) ⋅ n̂(s) χ₁λ(s::VecOrPNSystem) = χ⃗₁(s) ⋅ λ̂(s) χ₁ₗ(s::VecOrPNSystem) = χ⃗₁(s) ⋅ ℓ̂(s) χ₂ₙ(s::VecOrPNSystem) = χ⃗₂(s) ⋅ n̂(s) χ₂λ(s::VecOrPNSystem) = χ⃗₂(s) ⋅ λ̂(s) χ₂ₗ(s::VecOrPNSystem) = χ⃗₂(s) ⋅ ℓ̂(s) Sₙ(s::VecOrPNSystem) = S⃗(s) ⋅ n̂(s) Σₙ(s::VecOrPNSystem) = Σ⃗(s) ⋅ n̂(s) Sλ(s::VecOrPNSystem) = S⃗(s) ⋅ λ̂(s) Σλ(s::VecOrPNSystem) = Σ⃗(s) ⋅ λ̂(s) Sₗ(s::VecOrPNSystem) = S⃗(s) ⋅ ℓ̂(s) Σₗ(s::VecOrPNSystem) = Σ⃗(s) ⋅ ℓ̂(s) sₗ(s::VecOrPNSystem) = S⃗(s) ⋅ ℓ̂(s) / M(s)^2 σₗ(s::VecOrPNSystem) = Σ⃗(s) ⋅ ℓ̂(s) / M(s)^2 S₁ₙ(s::VecOrPNSystem) = S⃗₁(s) ⋅ n̂(s) S₁λ(s::VecOrPNSystem) = S⃗₁(s) ⋅ λ̂(s) S₁ₗ(s::VecOrPNSystem) = S⃗₁(s) ⋅ ℓ̂(s) S₂ₙ(s::VecOrPNSystem) = S⃗₂(s) ⋅ n̂(s) S₂λ(s::VecOrPNSystem) = S⃗₂(s) ⋅ λ̂(s) S₂ₗ(s::VecOrPNSystem) = S⃗₂(s) ⋅ ℓ̂(s)
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
24294
""" estimated_time_to_merger(M, ν, v) estimated_time_to_merger(pnsystem) Compute the lowest-order PN approximation for the time to merger, starting from PN velocity parameter `v`. This is used internally as a convenient way to estimate how long the inspiral integration should run for; we don't want it to integrate forever if PN has broken down. However, it can be a very poor approximation, especially close to merger, and doubly so if the spins or eccentricity are significant. """ function estimated_time_to_merger(M, ν, v) return 5M / (256ν * v^8) end function estimated_time_to_merger(pnsystem) return estimated_time_to_merger(M(pnsystem), ν(pnsystem), v(pnsystem)) end """ fISCO(q, M) fISCO(pnsystem) Compute the "BKL" approximation for the ISCO (Innermost Stable Circular Orbit) frequency. This is taken from Eq. (5) of [Hanna et al. (2008)](https://arxiv.org/abs/0801.4297). Note that this does not account for the spins of the objects in the binary, so that this returns a very crude estimate of a frequency of interest. """ function fISCO(q, M) let π = oftype(q, π) if q > 1 q = 1 / q end (10 + q * (28 + q * (-26 + q * 8))) / (10π * (6M)^(3//2)) end end function fISCO(pnsystem) return fISCO(q(pnsystem), M(pnsystem)) end """ ΩISCO(q,M) ΩISCO(pnsystem) 2π times [`fISCO`](@ref). """ function ΩISCO(q, M) return 2oftype(q, π) * fISCO(q, M) end function ΩISCO(pnsystem) return 2eltype(pnsystem)(π) * fISCO(pnsystem) end @doc raw""" uniform_in_phase(solution, saves_per_orbit) Interpolate `solution` to uniform steps in phase. By default, the `solution` returned by [`orbital_evolution`](@ref) may be sampled very sparsely — too sparsely to satisfy the Nyquist limit of the waveform. If the waveform extends to ``\ell_{\mathrm{max}}``, there will be modes varying slightly more rapidly than ``\exp\left(\pm i\, \ell_{\mathrm{max}}\, \Phi \right)``, where ``\Phi`` is the orbital phase. If the frequency were constant, this would require at least ``2\ell_{\mathrm{max}}`` samples per orbit. To incorporate a safety factor, ``4\ell_{\mathrm{max}}`` seems to work fairly reliably. See also the `saves_per_orbit` and `saveat` arguments to [`orbital_evolution`](@ref), as well as interpolation-in-time capabilities of the result of that function. """ function uniform_in_phase(solution, saves_per_orbit) let π = eltype(solution)(π) t = solution.t Φ = solution[:Φ] δΦ = 2π / saves_per_orbit Φrange = range(extrema(Φ)...; step=δΦ) t_Φ = CubicSpline(t, Φ)(Φrange) # Ensure that t=0 is interpolated back # to *exactly* t=0 instead of, e.g., -1e-24: t_Φ[1] = t[1] solution(t_Φ) end end function default_termination_criteria_forwards(pnsystem, vₑ, quiet) return CallbackSet( termination_forwards(vₑ, quiet), dtmin_terminator(eltype(pnsystem), quiet), decreasing_v_terminator(quiet), nonfinite_terminator(), ) end function default_termination_criteria_backwards(pnsystem, v₁, quiet) return CallbackSet( termination_backwards(v₁, quiet), dtmin_terminator(eltype(pnsystem), quiet), nonfinite_terminator(), ) end function default_reltol(pnsystem) T = eltype(pnsystem) return eps(T)^(11//16) end function default_abstol(pnsystem) T = eltype(pnsystem) return T[ T[eps(T(M₁(pnsystem) + M₂(pnsystem)))^(11//16) for _ ∈ 1:2] T[eps(T)^(11//16) for _ ∈ 3:length(pnsystem.state)] ] end """ orbital_evolution(pnsystem; kwargs...) orbital_evolution(M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; kwargs...) Integrate the orbital dynamics of an inspiraling non-eccentric compact binary. ## Required arguments The first argument to this function may be a single `PNSystem` that encodes these required arguments (as well as `Rᵢ`, `Λ₁`, and `Λ₂` among the keyword arguments), or the following may be given explicitly: * `M₁`: Initial mass of object 1 * `M₂`: Initial mass of object 2 * `χ⃗₁`: Initial dimensionless spin of object 1, `S⃗₁/M₁²` * `χ⃗₂`: Initial dimensionless spin of object 2, `S⃗₂/M₂²` * `Ωᵢ`: Initial orbital angular frequency (Note that the explicit inputs require `Ωᵢ`, whereas `PNSystem`s require `vᵢ` as input.) These parameters all describe the "initial" conditions. See below for an explanation of the different meanings of "initial" and "first" in this context. Note that the masses change in time as a result of tidal heating — though the changes are quite small throughout most of the inspiral. The spins change direction due to precession, but also change in magnitude due to tidal heating. Therefore, the values passed here are only precisely as given *precisely at* the moment of the initial data corresponding to the frequency `Ωᵢ`. ## Keyword arguments Note that several of these keywords are given as Unicode but can also be given as the ASCII string noted. For example, `Λ₁` may be input as `Lambda1` equivalently; the default values are the same, regardless. * `Λ₁=0` or `Lambda1`: Tidal-coupling parameter of object 1. * `Λ₂=0` or `Lambda2`: Tidal-coupling parameter of object 2. * `Ω₁=Ωᵢ` or `Omega_1`: First angular frequency in output data. This may be less than `Ωᵢ`, in which case we integrate backwards to this point, and combine the backwards and forwards solutions into one seamless output. (See next section.) * `Ωₑ=Ω(v=1,M=M₁+M₂)` or `Omega_e`: Final angular frequency at which to stop ODE integration. Note that integration may stop before the system reaches this frequency, if we detect that PN has broken down irretrievably — for example, if one of the masses is no longer strictly positive, if a spin is super-extremal, or the PN velocity parameter `v` is decreasing, or is no longer in the range `(0,1)`. Warnings will usually only be issued if `v < 0.35`, but if `quiet=true` informational messages will be issued. * `Rᵢ=Rotor(1)` or `R_i`: Initial orientation of binary. * `approximant="TaylorT1"`: Method of evaluating the right-hand side of the evolution equations. Other possibilities are [`"TaylorT4"`](@ref TaylorT4!) and [`"TaylorT5"`](@ref TaylorT5!). See the documentation of [`TaylorT1!`](@ref) for more details. * `PNOrder=typemax(Int)`: Order to which to retain powers of ``v^2`` in PN expansions. The default is to include all available terms in each PN expression. * `check_up_down_instability=true`: Warn if the "up-down instability" (see below) is likely to affect this system. * `time_stepper=Vern9()`: Choice of solver in OrdinaryDiffEq to integrate ODE. * `abstol=eps(T)^(11//16)`: Absolute tolerance of ODE solver, where `T` is the common type to which all the positional arguments are promoted. This is the tolerance on local error estimates, not necessarily the global error. Note that `11//16` is just chosen to suggest that we will have roughly 11 digits of accuracy (locally) for `Float64` computations, and a similar accuracy for other float types *relative to* that type's epsilon. * `reltol=eps(T)^(11//16)`: Relative tolerance of ODE solver. (As above.) * `termination_criteria_forwards=nothing`: Callbacks to use for forwards-in-time evolution. See below for discussion of the default value. * `termination_criteria_backwards=nothing`: Callbacks to use for backwards-in-time evolution. See below for discussion of the default value. * `force_dtmin=true`: If `dt` decreases below the integrator's own minimum, and this is false, the integrator will immediately raise an error, before the termination criteria have the chance to exit gracefully. Note that a true value here is critical if the `dtmin_terminator` callback is to have any effect. * `quiet=true`: If set to `false`, informational messages about successful terminations of the ODE integrations (which occur when the target ``v`` is reached in either direction) will be provided. Warnings will still be issued when terminating for other reasons; if you wish to silence them too, you should do something like ```julia using Logging with_logger(SimpleLogger(Logging.Error)) do <your code goes here> end ``` * `saves_per_orbit=0`: If greater than 0, the output will be interpolated so that there are `saves_per_orbit` time steps in the output for each orbit. Note that this conflicts with the `saveat` option noted below. All remaining keyword arguments are passed to the [`solve` function](https://github.com/SciML/DiffEqBase.jl/blob/8e6173029c630f6908252f3fc28a69c1f0eab456/src/solve.jl#L393) of `DiffEqBase`. See that function's documentation for details, including useful keyword arguments. The most likely important one is * `saveat`: Denotes specific times to save the solution at, during the solving phase — either a time step or a vector of specific times. In particular, if you want the solution to be output at uniform time steps `δt`, you want to pass something like `saveat=δt`; you *don't want* the `solve` keyword `dt`, which is just the initial suggestion for adaptive systems. It is not permitted to pass this option *and* the `saves_per_orbit` option. Also note that `callback` can be used, and is combined with the callbacks generated by the `termination_criteria_*` arguments above. That is, you can use the default ones *and* your own by passing arguments to `callback`. See [the documentation](https://diffeq.sciml.ai/dev/features/callback_functions/) for more details, but note that if you want to make your own callbacks, you will need to add `OrdinaryDiffEq` to your project — or possibly even `DifferentialEquations` for some of the fancier built-in callbacks. ## ODE system The evolved variables, in order, are * `M₁`: Mass of black hole 1 * `M₂`: Mass of black hole 2 * `χ⃗₁ˣ`: ``x`` component of dimensionless spin of black hole 1 * `χ⃗₁ʸ`: ``y`` component... * `χ⃗₁ᶻ`: ``z`` component... * `χ⃗₂ˣ`: ``x`` component of dimensionless spin of black hole 2 * `χ⃗₂ʸ`: ``y`` component... * `χ⃗₂ᶻ`: ``z`` component... * `Rʷ`: Scalar component of frame rotor * `Rˣ`: ``x`` component... * `Rʸ`: ``y`` component... * `Rᶻ`: ``z`` component... * `v`: PN "velocity" parameter related to the total mass ``M`` and orbital angular frequency ``Ω`` by ``v = (M Ω)^{1/3}`` * `Φ`: Orbital phase given by integrating ``Ω`` The masses and spin magnitudes evolve according to [`tidal_heating`](@ref). The spin directions evolve according to [`Ω⃗ᵪ₁`](@ref) and [`Ω⃗ᵪ₂`](@ref). The frame precesses with angular velocity [`Ω⃗ₚ`](@ref), while also rotating with angular frequency `Ω` about the [Newtonian orbital angular velocity direction](@ref ℓ̂). The frame rotor ``R`` is given by integrating the sum of these angular velocities as described in [Boyle (2016)](https://arxiv.org/abs/1604.08139). And finally, the PN parameter ``v`` evolves according to something like ```math \\dot{v} = - \\frac{\\mathcal{F} + \\dot{M}_1 + \\dot{M}_2} {\\mathcal{E}'} ``` where [`𝓕`](@ref) is the flux of gravitational-wave energy out of the system, ``\\dot{M}_1`` and ``\\dot{M}_2`` are due to tidal coupling as computed by [`tidal_heating`](@ref), and [`𝓔′`](@ref) is the derivative of the binding energy with respect to ``v``. For `"TaylorT1"`, the right-hand side of this equation is evaluated as given; for `"TaylorT4"`, the right-hand side is first expanded as a Taylor series in ``v`` and then truncated at some desired order; for `"TaylorT5"`, the *inverse* of the right-hand side is expanded as a Taylor series in ``v``, truncated at some desired order, and then inverted to obtain an expression in terms of ``v``. ## Returned solution The returned quantity is an [`ODESolution`](https://diffeq.sciml.ai/dev/basics/solution/) object, which has various features for extracting and interpolating the data. We'll call this object `sol`. !!! note The solution comes with data at the time points the ODE integrator happened to step to. However, it *also* comes with dense output (unless you manually turn it off when calling `orbital_evolution`). This means that you can interpolate the solution to any other set of time points you want simply by calling it as `sol(t)` for some vector of time points `t`. The quantity returned by that will have all the features described below, much like the original solution. Note that if you only want some of the data, you can provide the optional keyword argument `idxs` to specify which of the elements described below you want to interpolate. For example, if you only want to interpolate the values of `M₁` and `M₂`, you can use `sol(t, idxs=[1,2])`. The field `sol.t` is the set of time points at which the solution is given. To access the `i`th variable at time step `j`, use `sol[i, j]`.[^1] You can also use colons. For example, `sol[:, j]` is a vector of all the data at time step `j`, and `sol[i, :]` is a vector of the `i`th variable at all times. [^1]: Here, the `i`th variable just refers to which number it has in the list of evolved variables in the ODE system, as described under "ODE system". For convenience, you can also access the individual variables with their symbols. For example, `sol[:v]` returns a vector of the PN velocity parameter at each time step. Note the colon in `:v`, which is [Julia's notation for a `Symbol`](https://docs.julialang.org/en/v1/base/base/#Core.Symbol). ## Initial frequency vs. first frequency vs. end frequency Note the distinction between `Ωᵢ` (with subscript `i`) and `Ω₁` (with subscript `1`). The first, `Ωᵢ`, represents the angular frequency of the *initial condition* from which the ODE integrator will begin; the second, `Ω₁`, represents the target angular frequency of the first element of the output data. That is, the ODE integration will run forwards in time from `Ωᵢ` to the merger, and then — if `Ωᵢ>Ω₁` — come back to `Ωᵢ` and run backwards in time to `Ω₁`. The output data will stitch these two together to be one continuous (forwards-in-time) data series. For example, if you are trying to match to a numerical relativity (NR) simulation, you can read the masses and spins off of the NR data when the system is orbiting at angular frequency `Ωᵢ`. Integrating the post-Newtonian (PN) solution forwards in time from this point will allow you to compare the PN and NR waveforms. However, you may want to know what the waveform was at *earlier* times than are present in the NR data. For this, you also have to integrate backwards in time. We parameterize the point to which you integrate backwards with `Ω₁`. In either case, element `1` of the output solution will have frequency `Ω₁` — though by default it is equal to `Ωᵢ`. Similarly, the optional argument `Ωₑ=1` is the frequency of the `end` element of the solution — that is Julia's notation for the last element. Note that this is automatically reduced if necessary so that the corresponding PN parameter ``v`` is no greater than 1, which may be the case whenever the total mass is greater than 1. ## Up-down instability Be aware that the [up-down instability](http://arxiv.org/abs/1506.09116) (where the more massive black hole has spin aligned with the orbital angular velocity, and the less massive has spin anti-aligned) can cause systems with nearly zero precession at the initial time to evolve into a highly precessing system either at earlier or later times. This is a real physical result, rather than a numerical issue. If you want to simulate a truly non-precessing system, you should explicitly set the in-place components of spin to precisely 0. By default, we check for this condition, and will issue a warning if it is likely to be encountered for systems with low initial precession. The function used to compute the unstable region is [`up_down_instability`](@ref). ## Time-stepper algorithms `Tsit5()` is a good default choice for time stepper when using `Float64` with medium-low tolerance. If stiffness seems to be impacting the results, `AutoTsit5(Rosenbrock23())` will automatically switch when stiffness occurs. For tighter tolerances, especially when using `Double64`s, `Vern9()` or `AutoVern9(Rodas5P())` are good choices. For very loose tolerances, as when using `Float32`s, it might be better to use `OwrenZen3()`. ## Termination criteria The termination criteria are vital to efficiency of the integration and correctness of the solution. The default values for forwards- and backwards-in-time evolution, respectively, are ```julia CallbackSet( termination_forwards(v(Ω=Ωₑ, M=M₁+M₂)), dtmin_terminator(T), decreasing_v_terminator(), nonfinite_terminator() ) ``` and ```julia CallbackSet( termination_backwards(v(Ω=Ω₁, M=M₁+M₂)), dtmin_terminator(T), nonfinite_terminator() ) ``` where `T` is the common float type of the input arguments. If any additional termination criteria are needed, they could be added as additional elements of the `CallbackSet`s. See the [callback documentation](https://diffeq.sciml.ai/stable/features/callback_functions/) for details. """ Base.@constprop :aggressive function orbital_evolution( M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; Lambda1=0, Lambda2=0, Omega_1=0, Omega_e=Ω(; v=1, M=M₁ + M₂), R_i=Rotor(true), Λ₁=Lambda1, Λ₂=Lambda2, Ω₁=Omega_1, Ωₑ=Omega_e, Rᵢ=R_i, approximant="TaylorT1", PNOrder=typemax(Int), check_up_down_instability=true, time_stepper=Vern9(), reltol=nothing, abstol=nothing, termination_criteria_forwards=nothing, termination_criteria_backwards=nothing, quiet=true, force_dtmin=true, saves_per_orbit=false, solve_kwargs..., ) # Sanity checks for the inputs RHS! = if approximant == "TaylorT1" TaylorT1RHS! elseif approximant == "TaylorT4" TaylorT4RHS! elseif approximant == "TaylorT5" TaylorT5RHS! else error("Approximant `$approximant` is not currently supported") end if M₁ ≤ 0 || M₂ ≤ 0 error("Unphysical masses: M₁=$M₁, M₂=$M₂.") end χ⃗₁, χ⃗₂ = QuatVec(χ⃗₁), QuatVec(χ⃗₂) if abs2vec(χ⃗₁) > 1 || abs2vec(χ⃗₂) > 1 error( "Unphysical spins: |χ⃗₁|=$(abs2vec(χ⃗₁)), |χ⃗₂|=$(abs2vec(χ⃗₂)).\n" * "These are dimensionless spins, which should be less than 1.\n" * "Perhaps you forgot to divide by M₁² or M₂², respectively.", ) end Rᵢ = Rotor(Rᵢ) vᵢ = v(; Ω=Ωᵢ, M=M₁ + M₂) if vᵢ ≥ 1 error( "The input Ωᵢ=$Ωᵢ is too large; with these masses, it corresponds to\n" * "vᵢ=$vᵢ, which is beyond the reach of post-Newtonian methods.", ) end if !iszero(Λ₁) && iszero(Λ₂) error( "By convention, the NS in a BHNS binary must be the second body,\n" * "meaning that Λ₁ should be zero, and only Λ₂ should be nonzero.\n" * "You may want to swap the masses, spins, and Λ parameters.\n" * "Alternatively, both can be nonzero, resulting in an NSNS binary.", ) end if Ω₁ > Ωᵢ error( "Initial frequency Ωᵢ=$Ωᵢ should be greater than " * "or equal to first frequency Ω₁=$Ω₁.", ) end if Ωᵢ > Ωₑ error( "Initial frequency Ωᵢ=$Ωᵢ should be less than " * "or equal to ending frequency Ωₑ=$Ωₑ.", ) end if saves_per_orbit != false && "saveat" ∈ keys(solve_kwargs) error( "It doesn't make sense to pass the `saves_per_orbit` argument *and* the " * "`saveat` argument; only one may be passed.", ) end v₁ = v(; Ω=Ω₁, M=M₁ + M₂) vₑ = min(v(; Ω=Ωₑ, M=M₁ + M₂), 1) Φ = 0 # Initial conditions for the ODE integration pnsystem = let R = Rᵢ, v = vᵢ if !iszero(Λ₁) && !iszero(Λ₂) NSNS(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, Λ₁, Λ₂, Φ, PNOrder) elseif !iszero(Λ₂) BHNS(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, Λ₂, Φ, PNOrder) else BBH(; M₁, M₂, χ⃗₁, χ⃗₂, R, v, Φ, PNOrder) end end if isnothing(termination_criteria_forwards) termination_criteria_forwards = default_termination_criteria_forwards( pnsystem, vₑ, quiet ) end if isnothing(termination_criteria_backwards) && v₁ < v(pnsystem) termination_criteria_backwards = default_termination_criteria_backwards( pnsystem, v₁, quiet ) end # The choice of 11//16 here is just an easy way to get an idea that for Float64 this # will give us around 11 digits of accuracy, and a similar fraction of the precision for # other types. T = eltype(pnsystem) if isnothing(reltol) reltol = default_reltol(pnsystem) end if isnothing(abstol) abstol = default_abstol(pnsystem) end return orbital_evolution( pnsystem; RHS!, v₁, vₑ, check_up_down_instability, quiet, termination_criteria_forwards, termination_criteria_backwards, time_stepper, reltol, abstol, force_dtmin, saves_per_orbit, solve_kwargs..., ) end Base.@constprop :aggressive function orbital_evolution( pnsystemᵢ; (RHS!)=TaylorT1RHS!, v₁=zero(eltype(pnsystemᵢ)), vₑ=one(eltype(pnsystemᵢ)), check_up_down_instability=true, quiet=true, termination_criteria_forwards=default_termination_criteria_forwards( pnsystemᵢ, vₑ, quiet ), termination_criteria_backwards=default_termination_criteria_backwards( pnsystemᵢ, v₁, quiet ), time_stepper=Vern9(), reltol=default_reltol(pnsystemᵢ), abstol=default_abstol(pnsystemᵢ), force_dtmin=true, saves_per_orbit=zero(eltype(pnsystemᵢ)), solve_kwargs..., ) pnsystem = deepcopy(pnsystemᵢ) if check_up_down_instability up_down_instability_warn(pnsystem, v₁, vₑ) end # Log an error if the initial parameters return a NaN on the right-hand side let uᵢ = copy(pnsystem.state) u̇ = similar(uᵢ) tᵢ = zero(eltype(pnsystem)) RHS!(u̇, uᵢ, pnsystem, tᵢ) if any(isnan, u̇) || any(isnan, uᵢ) # COV_EXCL_START @error "Found a NaN with initial parameters:" value.(uᵢ) value.(u̇) pnsystem error("Found NaN") # COV_EXCL_STOP end end # Note: This estimate for the time span over which to integrate may be very bad, # especially close to merger. An underestimate would lead to an inspiral ending too # soon, but an overestimate can lead to integration continuing very slowly in a regime # where PN has broken down. τ = estimated_time_to_merger(pnsystem) problem_forwards = ODEProblem( RHS!, pnsystem.state, (zero(τ), 4τ), pnsystem; callback=termination_criteria_forwards, ) solution_forwards = solve( problem_forwards, time_stepper; reltol, abstol, force_dtmin, solve_kwargs... ) solution = if v₁ > 0 # Reset state to initial conditions pnsystem.state[:] .= pnsystemᵢ.state # Note: Here again, we don't want to overestimate the time span by too much, but we # also don't want to underestimate and get a shortened waveform. This should be a # better estimate, though, because it's dealing with lower speeds, at which PN # approximation should be more accurate. τ = estimated_time_to_merger(M(pnsystem), ν(pnsystem), v₁) - τ problem_backwards = remake( problem_forwards; tspan=(zero(τ), -4τ), callback=termination_criteria_backwards, ) solution_backwards = solve( problem_backwards, time_stepper; reltol, abstol, force_dtmin, solve_kwargs..., ) combine_solutions(solution_backwards, solution_forwards) else solution_forwards end if saves_per_orbit > 0 solution = uniform_in_phase(solution, saves_per_orbit) end return solution end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
6033
function v̇_numerator(pnsystem; pn_expansion_reducer=Val(sum)) (Ṡ₁, Ṁ₁, Ṡ₂, Ṁ₂) = tidal_heating(pnsystem; pn_expansion_reducer) return -(𝓕(pnsystem; pn_expansion_reducer) + Ṁ₁ + Ṁ₂) end function v̇_denominator(pnsystem; pn_expansion_reducer=Val(sum)) return 𝓔′(pnsystem; pn_expansion_reducer) end function v̇_numerator_coeffs(pnsystem) return v̇_numerator(pnsystem; pn_expansion_reducer=Val(identity)).coeffs end function v̇_denominator_coeffs(pnsystem) return v̇_denominator(pnsystem; pn_expansion_reducer=Val(identity)).coeffs end TaylorT1_v̇(p) = v̇_numerator(p) / v̇_denominator(p) TaylorT4_v̇(p) = truncated_series_ratio(v̇_numerator_coeffs(p), v̇_denominator_coeffs(p)) function TaylorT5_v̇(p) return inv(truncated_series_ratio(v̇_denominator_coeffs(p), v̇_numerator_coeffs(p))) end @pn_expression function TaylorTn!(pnsystem, u̇, TaylorTn_v̇::V̇) where {V̇} # If these parameters result in v≤0, fill u̇ with NaNs so that `solve` will # know that this was a bad step and try again. causes_domain_error!(u̇, pnsystem) && return nothing v̇ = TaylorTn_v̇(pnsystem) Ω⃗ = Ω⃗ₚ(pnsystem) + Ω * ℓ̂ (Ṡ₁, Ṁ₁, Ṡ₂, Ṁ₂) = tidal_heating(pnsystem) χ̂₁ = ifelse(iszero(χ₁), ℓ̂, χ⃗₁ / χ₁) χ̂₂ = ifelse(iszero(χ₂), ℓ̂, χ⃗₂ / χ₂) χ⃗̇₁ = (Ṡ₁ / M₁^2) * χ̂₁ - (2Ṁ₁ / M₁) * χ⃗₁ + Ω⃗ᵪ₁(pnsystem) × χ⃗₁ χ⃗̇₂ = (Ṡ₂ / M₂^2) * χ̂₂ - (2Ṁ₂ / M₂) * χ⃗₂ + Ω⃗ᵪ₂(pnsystem) × χ⃗₂ Ṙ = Ω⃗ * R / 2 u̇[M₁index] = Ṁ₁ u̇[M₂index] = Ṁ₂ u̇[χ⃗₁ˣindex] = χ⃗̇₁.x u̇[χ⃗₁ʸindex] = χ⃗̇₁.y u̇[χ⃗₁ᶻindex] = χ⃗̇₁.z u̇[χ⃗₂ˣindex] = χ⃗̇₂.x u̇[χ⃗₂ʸindex] = χ⃗̇₂.y u̇[χ⃗₂ᶻindex] = χ⃗̇₂.z u̇[Rʷindex] = Ṙ.w u̇[Rˣindex] = Ṙ.x u̇[Rʸindex] = Ṙ.y u̇[Rᶻindex] = Ṙ.z u̇[vindex] = v̇ u̇[Φindex] = Ω return nothing end sys = SymbolCache(collect(pnsystem_symbols), nothing, :t) @doc raw""" TaylorT1!(u̇, pnsystem) Compute the right-hand side for the orbital evolution of a non-eccentric binary in the "TaylorT1" approximant. This approximant is the simplest, in which the time derivative ``\dot{v}`` is given directly by ```math \dot{v} = -\frac{\mathcal{F} + \dot{M}_1 + \dot{M}_2} {\mathcal{E}'}, ``` and the PN expression for each term on the right-hand side is evaluated numerically before insertion directly in this expression. Compare [`TaylorT4!`](@ref) and [`TaylorT5!`](@ref). Here, `u̇` is the time-derivative of the state vector, which is stored in the [`PNSystem`](@ref) object `p`. """ TaylorT1!(u̇, pnsystem) = TaylorTn!(pnsystem, u̇, TaylorT1_v̇) TaylorT1!(u̇, u, p, t) = (p.state .= u; TaylorT1!(u̇, p)) """ TaylorT1RHS! A `SciMLBase.ODEFunction` wrapper for [`TaylorT1!`](@ref), suitable for passing into `OrdinaryDiffEq.solve`. """ const TaylorT1RHS! = ODEFunction{true,FullSpecialize}(TaylorT1!; sys) @doc raw""" TaylorT4!(u̇, pnsystem) Compute the right-hand side for the orbital evolution of a non-eccentric binary in the "TaylorT4" approximant. In this approximant, we compute ``\dot{v}`` by expanding the right-hand side of ```math \dot{v} = -\frac{\mathcal{F} + \dot{M}_1 + \dot{M}_2} {\mathcal{E}'} ``` as a series in ``v``, truncating again at the specified PN order, and only then is the result evaluated. Compare [`TaylorT1!`](@ref) and [`TaylorT5!`](@ref). Here, `u` is the ODE state vector, which should just refer to the `state` vector stored in the [`PNSystem`](@ref) object `p`. The parameter `t` represents the time, and will surely always be unused in this package, but is part of the `DifferentialEquations` API. !!! note "Truncation order vs. `PNOrder` vs. PN order" When expanding the fraction given above as a series in ``v``, the truncation order is not necessarily the value of `PNOrder` given in the input `p`. Instead, it is the highest order of the series that is present in the numerator or denominator — which is what we would normally *call* the PN order of those expansions. The `PNOrder` parameter is the highest order of the series that is *allowed* to be present in those expansions, so that if `PNOrder` is `typemax(Int)`, the series will be expanded to the highest order given in any of the PN expansions, but the expansion of the ratio will not go to infinite order. This is the reason that `TaylorT4` and `TaylorT5` do not approach `TaylorT1` as `PNOrder` approaches `typemax(Int)`. """ TaylorT4!(u̇, pnsystem) = TaylorTn!(pnsystem, u̇, TaylorT4_v̇) TaylorT4!(u̇, u, p, t) = (p.state .= u; TaylorT4!(u̇, p)) """ TaylorT4RHS! A `SciMLBase.ODEFunction` wrapper for [`TaylorT4!`](@ref), suitable for passing into `OrdinaryDiffEq.solve`. """ const TaylorT4RHS! = ODEFunction{true,FullSpecialize}(TaylorT4!; sys) @doc raw""" TaylorT5!(u̇, pnsystem) Compute the right-hand side for the orbital evolution of a non-eccentric binary in the "TaylorT5" approximant. In this approximant, we compute ``\dot{v}`` by expanding the right-hand side of *the multiplicative inverse of* the usual expression ```math \frac{1}{\dot{v}}=\frac{dt}{dv} = -\frac{\mathcal{E}'} {\mathcal{F} + \dot{M}_1 + \dot{M}_2} ``` as a series in ``v``, truncating again at the specified PN order, evaluating the result, and then taking the multiplicative inverse again to find ``\dot{v}``. This approximant was introduced by [Ajith (2011)](https://arxiv.org/abs/1107.1267) [see Eq. (3.5)]. Compare [`TaylorT1!`](@ref) and [`TaylorT4!`](@ref). Here, `u` is the ODE state vector, which should just refer to the `state` vector stored in the [`PNSystem`](@ref) object `p`. The parameter `t` represents the time, and will surely always be unused in this package, but is part of the `DifferentialEquations` API. """ TaylorT5!(u̇, pnsystem) = TaylorTn!(pnsystem, u̇, TaylorT5_v̇) TaylorT5!(u̇, u, p, t) = (p.state .= u; TaylorT5!(u̇, p)) """ TaylorT5RHS! A `SciMLBase.ODEFunction` wrapper for [`TaylorT5!`](@ref), suitable for passing into `OrdinaryDiffEq.solve`. """ const TaylorT5RHS! = ODEFunction{true,FullSpecialize}(TaylorT5!; sys)
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
4097
@doc raw""" up_down_instability(pnsystem) Compute the range of frequencies over which the system is unstable to increasing precession. The returned value is a pair of dimensionless frequencies giving the lower and upper frequencies between which we can expect instability. If there is no instability expected, the returned pair is just ``(1/M, 1/M)`` — where ``M`` is the total mass of the system, and ``1/M`` is the upper limit of physically reasonable frequencies. For compact binaries in which the spins are either aligned or anti-aligned with the orbital angular velocity, we do not expect any precession effects — simply by symmetry. However, if the spin of the higher-mass object is aligned with the orbital angular velocity and the spin of the lower-mass object is anti-aligned, the binary is unstable to precession — meaning that any minuscule misalignment can grow rapidly into significant precession. This was first reported by [Gerosa et al. (2015)](http://arxiv.org/abs/1506.09116), and the range over which the system is unstable is given by Eq. (2) of that reference. We use the lowest-order approximation to convert binary separation to frequency. The result is also "clamped" between ``0`` and ``1/M``, because sometimes the PN approximations involved break down and return values outside of those physically plausible limits. Note that Gerosa et al. use the convention that ``q = M_2/M_1`` — which is opposite to the convention used in [this package](@ref q); which we account for internally in this function. They also assume that ``M_1 \geq M_2``, which we deal with by automatically swapping the relevant quantities. Neither of these requires any adjustment by users of this function. """ @pn_expression function up_down_instability(pnsystem) T = eltype(pnsystem) Ωₘₐₓ = PostNewtonian.Ω(; v=one(T), M=M) # Note that, as mentioned in the docstring, Gerosa et al. use q<1 if M₂ > M₁ # Just swap the relevant variables χ₂ₗ, χ₁ₗ = χ₁ₗ, χ₂ₗ else q = inv(q) end if χ₁ₗ > 0 && χ₂ₗ < 0 # Note that `r₊ ≥ r₋`, but we keep corresponding subscripts, # which means that `Ω₊ ≤ Ω₋`! r₊ = M * (√abs(χ₁ₗ) + √abs(q * χ₂ₗ))^4 / (1 - q)^2 r₋ = M * (√abs(χ₁ₗ) - √abs(q * χ₂ₗ))^4 / (1 - q)^2 Ω₊ = √(M / r₊)^3 Ω₋ = √(M / r₋)^3 (clamp(Ω₊, zero(T), Ωₘₐₓ), clamp(Ω₋, zero(T), Ωₘₐₓ)) else (Ωₘₐₓ, Ωₘₐₓ) end end @doc raw""" function up_down_instability_warn(pnsystem, v₁, vₑ, vₗᵢₘᵢₜ=1//2) If this system is likely to encounter the up-down instability, log a warning with details. This function issues the warning if the system is reasonably non-precessing (``\chi_\perp \leq 10^{-2}``) in its current configuration (as given by `pnsystem`), and the range of frequencies `(v₁, vₑ)` over which it will be integrated is likely to encounter the up-down instability — except that frequencies above `vₗᵢₘᵢₜ` will be ignored, as PN is likely to have broken down anyway. See [`up_down_instability`](@ref) for details of the calculation of the unstable region. """ @pn_expression function up_down_instability_warn(pnsystem, v₁, vₑ, vₗᵢₘᵢₜ=1//2) if χₚₑᵣₚ ≤ 1e-2 && !iszero(χₚₑᵣₚ) (Ω₊, Ω₋) = up_down_instability(pnsystem) v₊, v₋ = PostNewtonian.v(; Ω=Ω₊, M=M), PostNewtonian.v(; Ω=Ω₋, M=M) if v₁ < min(v₋, vₗᵢₘᵢₜ) && min(vₑ, vₗᵢₘᵢₜ) > v₊ @warn ( "\n" * "This system is likely to encounter the up-down instability in the frequency\n" * "range (Ω₊, Ω₋)=$((Ω₊, Ω₋)), which corresponds to\n" * "PN velocity parameters (v₊, v₋)=$((v₊, v₋)).\n" * "This is a true physical instability, not just a numerical issue. Despite the\n" * "fact that the initial conditions contain very small precession, the system will\n" * "likely evolve to have very large precession. See `up_down_instability` docs\n" * "for details." * "\n\nParameters:" ) M₁ M₂ χ⃗₁ χ⃗₂ R v v₁ vₑ end end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
10084
# Variable names refer to as-yet-unknown coefficients from v2 of Bini and Damour (2013b) const a₆ᶜ¹ = 0 const a₆₅ᶜ¹ = 0 const a₇ˡⁿ¹ = 0 const a₇ᶜ¹ = 0 """ 𝓔(pnsystem) binding_energy(pnsystem) Compute the gravitational binding energy of a compact binary. Note that this may not be as useful as its derivative, [`𝓔′`](@ref), which is used as part of the right-hand side for orbital evolutions. The nonspinning orbital binding energy is known through 4pN. The expressions through 3.5pN here come from Eq. (233) of [Blanchet (2014)](https://doi.org/10.12942/lrr-2014-2). The 4pN term from Eq. (5.2d) of [Jaranowski and Schäfer](https://arxiv.org/abs/1303.3225v1) is known exactly, now that the ``ν``-linear piece is given as Eq. (32) of [Bini and Damour (2013a)](https://arxiv.org/abs/1305.4884v1). The remaining terms are not known exactly, but [Bini and Damour (2013b)](https://arxiv.org/abs/1312.2503v2) have derived some terms, though there is incomplete information, which are noted as the constants in this code. The spin-orbit terms in the energy are now complete to 4.0pN (the last term is zero). These terms come from Eq. (4.6) of [Bohé et al. (2012)](https://arxiv.org/abs/1212.5520v2). The spin-squared terms (by which we mean both spin-spin and spin-orbit squared terms) in the energy are known to 3pN order, and given in Eq. (3.33) of [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). The tidal-coupling terms come in to the binding energy at relative 5pN order, and are known to 6pN order. These terms come from Eq. (2.11) of [Vines et al. (2011)](https://prd.aps.org/abstract/PRD/v83/i8/e084051). Note their unusual convention for mass ratios, where ``χ₁ = m₁/m`` in their notation; in particular, ``χ`` is not a spin parameter. Also note that ``λ̂ = λ₂ v^{10}/(m₁+m₂)^5``, and we need to add the coupling terms again with ``1 ↔ 2``. Finally, note the normalization difference, where a different overall factor is used, leading to a sign difference. """ @pn_expression function 𝓔(pnsystem) return -μ * c^2 * (v / c)^2 / 2 * @pn_expansion( # Non-spinning terms; Eq. (233) of Blanchet (2014) 1 + (v / c)^2 * (-ν / 12 - 3//4) + (v / c)^4 * (-ν^2 / 24 + 19ν / 8 - 27//8) + (v / c)^6 * (-35ν^3 / 5184 - 155ν^2 / 96 + (34445//576 - 205π^2 / 96)ν - 675//64) # Eq. (5.2d) of Jaranowski and Schäfer + (v / c)^8 * ( -3969//128 + 77ν^4 / 31104 + 301ν^3 / 1728 + (-498449//3456 + 3157π^2 / 576)ν^2 + (-123671//5760 + 1792ln2 / 15 + 9037π^2 / 1536 + 896γₑ / 15)ν + 2ln(v) * (448ν / 15) ) # Below are the incomplete terms from Eq. (74) of https://arxiv.org/abs/1312.2503v2 + (v / c)^10 * ( -45927//512 + ν^5 / 512 + 55ν^4 / 512 + (-1353π^2 / 256 + 69423//512)ν^3 + (-21337π^2 / 1024 + 3a₆ᶜ¹ - 896ln2 / 5 - 448γₑ / 5 + 893429//2880)ν^2 + ( -228916843//115200 - 9976γₑ / 35 + 729ln3 / 7 - 23672ln2 / 35 + 126779π^2 / 512 )ν + 2ln(v) * (-4988ν / 35 - 656ν^2 / 5) ) + (v / c)^11 * (10ν / 3 * (13696π / 525 + ν * a₆₅ᶜ¹)) + (v / c)^12 * ( -264627//1024 + 2717ν^6 / 6718464 + 5159ν^5 / 248832 + (272855π^2 / 124416 - 20543435//373248)ν^4 + ( 1232γₑ / 27 + 6634243π^2 / 110592 - 11a₆ᶜ¹ / 2 - 71700787//51840 + 2464ln2 / 27 )ν^3 + ( 113176680983//14515200 + 18491π^4 / 2304 + 246004ln2 / 105 + 112772γₑ / 105 + a₆ᶜ¹ * 11//2 + a₇ˡⁿ¹ * 2//3 + a₇ᶜ¹ * 11//3 - 86017789π^2 / 110592 - 2673ln3 / 14 )ν^2 + ( -389727504721//43545600 + 74888ln2 / 243 - 7128ln3 / 7 - 30809603π^4 / 786432 - 3934568γₑ / 8505 + 9118627045π^2 / 5308416 )ν + 2ln(v) * (-1967284ν / 8505 + 24464ν^3 / 135 + (39754//105 + a₇ˡⁿ¹ * 11//3)ν^2) ) # Spin-orbit; Eq. (4.6) of Bohé et al. (2012) + (v / c)^3 * (14sₗ / 3 + 2δ * σₗ) + (v / c)^5 * ((11 - 61ν / 9) * sₗ + (3 - 10ν / 3)δ * σₗ) + (v / c)^7 * ((135//4 - 367ν / 4 + 29ν^2 / 12) * sₗ + (27//4 - 39ν + 5ν^2 / 4)δ * σₗ) # Spin-squared; Eq. (3.33) of Bohé et al. (2015) + (v / c)^4 * ( sₗ^2 * (-κ₊ - 2) + sₗ * σₗ * (-δ * κ₊ - 2δ + κ₋) + σₗ^2 * (δ * κ₋ / 2 - κ₊ / 2 + (κ₊ + 2)ν) ) + (v / c)^6 * ( sₗ^2 * (-5δ * κ₋ / 3 - 25 * κ₊ / 6 + 50//9 + (5κ₊ / 6 + 5//3)ν) + sₗ * σₗ * ( -5 * δ * κ₊ / 2 + 25 * δ / 3 + 5κ₋ / 2 + (5δ * κ₊ / 6 + 5δ / 3 + 35κ₋ / 6)ν ) + σₗ^2 * ( 5δ * κ₋ / 4 - 5κ₊ / 4 + 5 + (5δ * κ₋ / 4 + 5κ₊ / 4 - 10)ν + (-5κ₊ / 6 - 5//3)ν^2 ) ) # Spin-cubed; Eq. (6.17) of Marsat (2014) + (v / c)^7 * ( sₗ^3 * (2κ₊ + 4λ₊ - 20) + sₗ^2 * σₗ * (2δ * κ₊ + 6δ * λ₊ - 32δ + 4κ₋ - 6λ₋) + sₗ * σₗ^2 * (5δ * κ₋ - 6δ * λ₋ - 5κ₊ + 6λ₊ - 12 + (-2κ₊ - 12λ₊ + 68)ν) + σₗ^3 * (-3δ * κ₊ + 2δ * λ₊ + 3κ₋ - 2λ₋ + (-2δ * λ₊ + 12δ - 6κ₋ + 6λ₋)ν) ) # NS tidal coupling; Eq. (2.11) of Vines et al. (2011) with λ̂=v^10*Λ₂*(M₂/M)^5 + (v / c)^10 * (-9Λ₁ * ν * X₁^3 - 9Λ₂ * ν * X₂^3) + (v / c)^12 * ( -11//2 * (3 + 2X₁ + 3X₁^2)Λ₁ * ν * X₁^3 - 11//2 * (3 + 2X₂ + 3X₂^2)Λ₂ * ν * X₂^3 ) ) end const binding_energy = 𝓔 """ 𝓔′(pnsystem) binding_energy_deriv(pnsystem) Compute the derivative with respect to ``v`` of the binding energy of a compact binary. This is computed automatically (via `FastDifferentiation`) from [`𝓔`](@ref); see that function for details of the PN formulas. """ @generated function 𝓔′( pnsystem::PNSystem{ST,PNOrder}; pn_expansion_reducer::Val{PNExpansionReducer}=Val(sum) ) where {ST,PNOrder,PNExpansionReducer} # Create a `PNSystem` with `FastDifferentiation` (henceforth FD) variables, using the # same PNOrder as the input `pnsystem`. fdpnsystem = FDPNSystem(eltype(ST), PNOrder) # FD expects a single vector of variables, so we concatenate the state vector with the # two tidal-coupling parameters vars = FastDifferentiation.Node[fdpnsystem.state; Λ₁(fdpnsystem); Λ₂(fdpnsystem)] # Now we evaluate 𝓔 using the FD variables. This will expand all derived variables in # terms of the fundamental variables, but FD will take care of evaluating those # efficiently via common subexpression elimination (CSE). 𝓔formula = 𝓔(fdpnsystem; pn_expansion_reducer=Val(PNExpansionReducer)) # Now we take the derivative of 𝓔 with respect to v. 𝓔′ = SVector(FastDifferentiation.derivative(𝓔formula, v(fdpnsystem))) # Turn that into an Expr (FD insists on making it a function) in_place = true init_with_zeros = false 𝓔′expr = FastDifferentiation.make_Expr(𝓔′, vars, in_place, init_with_zeros) # Now, we use `MacroTools` to get the body of the function. 𝓔′body = MacroTools.unblock(MacroTools.splitdef(𝓔′expr)[:body]) # # At this point, the function is just a long series of statements inside an `@inbounds` # # block, which we will want later, but first we need to extract them. MacroTools.@capture(𝓔′body, @inbounds begin 𝓔′statements__ end) || throw( ArgumentError( "\nNo @inbounds block found in 𝓔′ expression." * "\nSomething may have changed in FastDifferentiation." * "\nOpen an issue citing this Julia call:" * "\n```julia" * "\nusing PostNewtonian" * "\n𝓔′($pnsystem)" * "\n```", ), ) # The 𝓔′statements are mostly what we want, except that the last line is a return # statement. We want that result, but we don't to return it yet; we want to wrap that # result, so we just get that returned quantity here. MacroTools.@capture(𝓔′statements[end], return 𝓔′return_) || throw( ArgumentError( "\nNo return statement found in 𝓔′ expression." * "\nSomething may have changed in FastDifferentiation." * "\nOpen an issue citing this Julia call:" * "\n```julia" * "\nusing PostNewtonian" * "\n𝓔′($pnsystem)" * "\n```", ), ) 𝓔′statements[end] = 𝓔′return if PNExpansionReducer === identity # When `pn_expansion_reducer=Val(identity)` is passed, we return a PNExpansion NMax = Int(2PNOrder + 1) return quote input_variables = SVector(pnsystem) result = MVector{$(length(𝓔′)),$(eltype(ST))}(undef) result .= 0 @fastmath @inbounds begin $(𝓔′statements...) end return PNExpansion{$(length(𝓔′)),$(eltype(ST)),$NMax}(Tuple(result)) end else # Otherwise, FD produces a 1-tuple, so we just extract the value from that. return quote input_variables = SVector(pnsystem) result = MVector{1,$(eltype(ST))}(undef) result .= 0 @fastmath @inbounds begin $(𝓔′statements...) end return result[1] end end end const binding_energy_deriv = 𝓔′
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
7828
""" 𝓕(pnsystem) gw_energy_flux(pnsystem) Compute the gravitational-wave energy flux to infinity The nonspinning flux terms are complete to 4.5pN order, and are given in Eq. (6.11) of [Blanchet et al. (2023)](https://arxiv.org/abs/2304.11186). The spin-orbit terms in the flux are now known to 4.0pN. These terms come from Eq. (4.9) of [Marsat et al. (2013)](https://arxiv.org/abs/1307.6793v1) The spin-squared terms (by which we mean both spin-spin and spin-orbit squared terms) in the flux are known to 3pN order, and given most conveniently in Eq. (4.14) of [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). Beyond 4.5pN, terms are only known in the extreme-mass-ratio limit. These terms are given in Appendix A of [Fujita (2012)](https://arxiv.org/abs/1211.5535v1). He computed them up to 22pN. That seems like overkill, so we'll just go up to 6pN. For systems with matter, the tidal-heating terms come in at relative 5pN order, and are known partially at 6pN order. These terms come from Eq. (3.6) of [Vines et al. (2011)](https://prd.aps.org/abstract/PRD/v83/i8/e084051). Note their unusual convention for mass ratios, where ``χ₁ = m₁/m`` in their notation; in particular, ``χ`` is not a spin parameter. Also note that ``λ̂ = λ₂ v^{10}/(m₁+m₂)^5``, and we need to add the coupling terms again with ``1 ↔ 2``. Finally, note the normalization difference, where a different overall factor is used, leading to a sign difference. """ @pn_expression function 𝓕(pnsystem) return 32c^5 / 5G * ν^2 * (v / c)^10 * @pn_expansion( # Non-spinning terms; Eq. (314) of Blanchet (2014) 1 + (v / c)^2 * (-1247//336 - 35ν / 12) + (v / c)^3 * (4π) + (v / c)^4 * (-44711//9072 + 9271ν / 504 + 65ν^2 / 18) + (v / c)^5 * ((-8191//672 - 583 * ν / 24)π) + (v / c)^6 * ( 6643739519//69854400 + 16π^2 / 3 - 1712 * (γₑ + 2ln2 + ln(v)) / 105 + (-134543//7776 + 41π^2 / 48)ν - 94403ν^2 / 3024 - 775ν^3 / 324 ) + (v / c)^7 * ((-16285//504 + 214745ν / 1728 + 193385ν^2 / 3024)π) + (v / c)^8 * ( -323105549467//3178375200 + 232597γₑ / 4410 - 1369π^2 / 126 + 39931ln2 / 294 - 47385ln3 / 1568 + 232597ln(v) / 4410 + ( -1452202403629//1466942400 + 41478γₑ / 245 - 267127π^2 / 4608 + 479062ln2 / 2205 + 47385ln3 / 392 + 41478ln(v) / 245 )ν + (1607125//6804 - 3157π^2 / 384)ν^2 + 6875ν^3 / 504 + 5ν^4 / 6 ) + (v / c)^9 * ( ( 265978667519//745113600 - 6848 * (γₑ + 2ln2 + ln(v)) / 105 + (2062241//22176 + 41π^2 / 12)ν - 133112905ν^2 / 290304 - 3719141ν^3 / 38016 )π ) # Spin-orbit terms; Eq. (4.9) of Marsat et al. (2013) + (v / c)^3 * (-4 * sₗ - 5δ / 4 * σₗ) + (v / c)^5 * ((-9//2 + 272ν / 9) * sₗ + (-13//16 + 43ν / 4)δ * σₗ) + (v / c)^6 * ((-16π) * sₗ + (-31π / 6)δ * σₗ) + (v / c)^7 * ( (476645//6804 + 6172ν / 189 - 2810ν^2 / 27) * sₗ + (9535//336 + 1849ν / 126 - 1501ν^2 / 36)δ * σₗ ) + (v / c)^8 * ( (-3485//96 + 13879ν / 72)π * sₗ + (-7163//672 + 130583ν / 2016)π * δ * σₗ ) # Spin-squared terms; Eq. (4.14) of Bohé et al. (2015) + (v / c)^4 * ( sₗ^2 * (2κ₊ + 4) + sₗ * σₗ * (2δ * κ₊ + 4δ - 2κ₋) + σₗ^2 * (-δ * κ₋ + κ₊ + 1//16 + (-2κ₊ - 4)ν) ) + (v / c)^6 * ( sₗ^2 * (41δ * κ₋ / 16 - 271κ₊ / 112 - 5239//504 + (-43κ₊ / 4 - 43//2)ν) + sₗ * σₗ * ( -279δ * κ₊ / 56 - 817δ / 56 + 279κ₋ / 56 + (-43δ * κ₊ / 4 - 43δ / 2 + κ₋ / 2)ν ) + σₗ^2 * ( 279δ * κ₋ / 112 - 279 * κ₊ / 112 - 25//8 + (45δ * κ₋ / 16 + 243κ₊ / 112 + 344//21)ν + (43κ₊ / 4 + 43//2)ν^2 ) ) # Spin-cubed; Eq. (6.19) of Marsat (2014) + (v / c)^7 * ( sₗ^3 * (-16κ₊ / 3 - 4λ₊ + 40//3) + sₗ^2 * σₗ * (-35δ * κ₊ / 6 - 6δ * λ₊ + 73δ / 3 - 3κ₋ / 4 + 6λ₋) + sₗ * σₗ^2 * ( -35δ * κ₋ / 12 + 6δ * λ₋ + 35κ₊ / 12 - 6λ₊ + 32//3 + (22κ₊ / 3 + 12λ₊ - 172//3)ν ) + σₗ^3 * ( 67δ * κ₊ / 24 - 2δ * λ₊ - δ / 8 - 67κ₋ / 24 + 2λ₋ + (δ * κ₊ / 2 + 2δ * λ₊ - 11δ + 61κ₋ / 12 - 6λ₋)ν ) ) # EMRI terms; Appendix A of Fujita (2012), with lower-order terms removed because # they have since been incorporated into non-EMRI terms above + (v / c)^10 * ( -2500861660823683//2831932303200 - 424223π^2 / 6804 - 83217611ln2 / 1122660 + 916628467γₑ / 7858620 + 47385ln3 / 196 + 916628467ln(v) / 7858620 ) + (v / c)^11 * ( -142155π * ln3 / 784 + 8399309750401π / 101708006400 + 177293γₑ * π / 1176 + 8521283π * ln2 / 17640 + 177293π * ln(v) / 1176 ) + (v / c)^12 * ( -271272899815409ln2 / 157329572400 - 54784π^2 * ln2 / 315 - 246137536815857γₑ / 157329572400 - 437114506833ln3 / 789268480 - 256π^4 / 45 - 27392γₑ * π^2 / 315 - 27392ζ3 / 105 - 37744140625ln5 / 260941824 + 1465472γₑ^2 / 11025 + 5861888γₑ * ln2 / 11025 + 5861888ln2^2 / 11025 + 2067586193789233570693//602387400044430000 + 3803225263π^2 / 10478160 + ln(v) * ( -246137536815857//157329572400 - 27392π^2 / 315 + 2930944γₑ / 11025 + 5861888ln2 / 11025 + 1465472ln(v) / 11025 ) ) # NS tidal heating; Eq. (3.6) [(3.7) on arXiv] of Vines et al. (2011) + (v / c)^10 * ((18 - 12X₁)Λ₁ * X₁^4 + (18 - 12X₂)Λ₂ * X₂^4) + (v / c)^12 * ( (-704 - 1803X₁ + 4501X₁^2 - 2170X₁^3)Λ₁ * X₁^4 / 28 + (-704 - 1803X₂ + 4501X₂^2 - 2170X₂^3)Λ₂ * X₂^4 / 28 ) ) end const gw_energy_flux = 𝓕
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
16549
# This function is stolen from SphericalFunctions.jl @inline Yindex(ℓ, m, ℓₘᵢₙ=0) = ℓ*(ℓ + 1) - ℓₘᵢₙ^2 + m + 1 @doc raw""" h!(h, pnsystem; ℓₘᵢₙ=0, ℓₘₐₓ=typemax(Int)) mode_weights!(h, pnsystem; ℓₘᵢₙ=0, ℓₘₐₓ=typemax(Int)) Compute mode weights of gravitational waves emitted by `pn` system, modifying `h` in place. !!! note This is a low-level function; you probably don't want to use this directly. See [`coorbital_waveform`](@ref) or [`inertial_waveform`](@ref) for more user-friendly functions. These modes are computed in the "co-orbital" frame, in which the larger object lies on the positive ``x`` axis, the smaller lies on the negative ``x`` axis, and the instantaneous angular velocity is in the positive ``z`` direction. The modes are stored in `h` in order of increasing ``ℓ`` and increasing ``m``, with ``m`` iterating fastest, all the way up to the highest available mode, ``(8,8)``. Because gravitational waves have spin weight -2, the ``(ℓ,m)=(0,0)``, ``(1,-1)``, ``(1,0)``, and ``(1,1)`` modes are always 0. By default, we assume that these modes are nonetheless included in `h`. If that is not the case, set `ℓₘᵢₙ` to the smallest ``ℓ`` value that should be present in the output data — `ℓₘᵢₙ=2` being the most reasonable alternative. These results come most directly from Eqs. (A5) of [Boyle et al. (2014)](https://arxiv.org/abs/1409.4431), with the exception of errors in the 2PN spin-spin terms, in which cases we must multiply by ``\nu/2`` and make the substitutions $S_1 \mapsto S_0^+$ and $S_2 \mapsto S_0^-$. In turn, those expressions are synthesized from the following: Non-spinning terms are taken from [Blanchet (2014)](https://doi.org/10.12942/lrr-2014-2), except for the highest-pN term in the (2,±2) mode, which are taken from [Blanchet et al. (2023)](https://arxiv.org/abs/2304.11186), and the ``m=0`` modes, which are taken from [Favata (2008)](https://arxiv.org/abs/0812.0069). The 1PN spin-orbit term is from Eq. (3.22d) of [Kidder (1995)](https://link.aps.org/doi/10.1103/PhysRevD.52.821). The 1.5PN spin-orbit term is from Eq. (3.22f) of Kidder (1995) and Eq. (F15b) of [Will and Wiseman (1996)](https://link.aps.org/doi/10.1103/PhysRevD.54.4813). The 2PN spin-orbit term is from Eq. (4.13) of [Buonanno, Faye, Hinderer (2013)](https://link.aps.org/doi/10.1103/PhysRevD.87.044009), while the 2PN spin-spin term is from Eq. (4.15) of that reference. """ @pn_expression 2 function h!(h, pnsystem; ℓₘᵢₙ=0, ℓₘₐₓ=typemax(Int)) h .= false # Set everything to 0 just to be safe h₀ = 2ν * (v/c)^2 * √(16π/5) # ell=2 if ℓₘₐₓ ≥ 2 h[Yindex(2,0,ℓₘᵢₙ)] = h₀ * (-5/(14√6)) * @pn_expansion( # Eq. (4.3a) of Favata (2008) 1 + (v/c)^2 * (-4075//4032 + 67ν/48) + (v/c)^4 * (-151877213//67060224 - 123815ν/44352 + 205ν^2/352) + (v/c)^5 * (-253//336 + 253ν/84)π + (v/c)^6 * ( -4397711103307//532580106240 + (700464542023//13948526592 - 205π^2/96)ν + 69527951ν^2/166053888 + 1321981ν^3/5930496 ) ) h[Yindex(2,1,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^1 * (𝒾 * δ / 3) + (v/c)^3 * (𝒾 * δ * (-17 + 20ν) / 84) + (v/c)^4 * ((δ * (1 + 2𝒾*π + 4ln2)) / 6) + (v/c)^5 * (𝒾 * δ * (-172 + ν * (-2036 + 237ν)) / 1512) + (v/c)^6 * (δ*(-34𝒾*π - 17*(1 + 4ln2) + 2ν * (353 + 6𝒾*π + 12ln2)) / 168) ) h[Yindex(2,2,ℓₘᵢₙ)] = h₀ * @pn_expansion( 1 + (v/c)^2 * ((-107 + 55ν)/42) + (v/c)^3 * (2π) + (v/c)^4 * ((-2173 + ν * (-7483 + 2047ν)) / 1512) + (v/c)^5 * (-24𝒾*ν + ((-107 + 34ν)π) / 21) + (v/c)^6 * ( (27027409//646800) - 856γₑ/105 + (ν*(-834555 + ν*(-729396 + 114635ν))) / 99792 + 41ν * π^2 / 96 + (2π*(214𝒾 + 35π))/105 - 1712ln2/105 - (856//105)*ln(v) ) + (v/c)^7 * ((-2𝒾 * ν * (-501655 + 24396ν) + 15*(-2173 + 2ν*(-2459 + 560ν))π) / 11340) # Eq. (6.17) of Blanchet et al. (2023) + (v/c)^8 * ( - 846557506853//12713500800 + 45796γₑ/2205 - 22898𝒾*π/2205 - 107π^2/63 + 45796(2ln2+ln(v))/2205 + (-336005827477//4237833600 + 15284γₑ/441 - 219314𝒾*π/2205 - 9755*π^2/32256 + 15284(2ln2+ln(v))/441)ν + (256450291//7413120 - 1025*π^2/1008)ν^2 - 81579187ν^3/15567552 + 26251249ν^4/31135104 ) ) end # ell=3 if ℓₘₐₓ ≥ 3 h[Yindex(3,0,ℓₘᵢₙ)] = h₀ * @pn_expansion((v/c)^5 * (-2𝒾 * √(6//7) * ν / 5)) h[Yindex(3,1,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^1 * (𝒾 * δ / 12√14) + (v/c)^3 * (-𝒾 * δ * (4 + ν) / 18√14) + (v/c)^4 * (δ * (7 + 5𝒾*π + 10ln2) / 60√14) + (v/c)^5 * (-𝒾 * δ * (-607 + ν*(272 + 247ν)) / 2376√14) + (v/c)^6 * ( δ * (-5𝒾 * (16 + 7ν)π + 2*(-56 + ν - 5*(16 + 7ν)*ln2)) / 360√14 ) + (v/c)^7 * ( 𝒾 * δ / 12√14 * ( (10753397//1513512) - 2ln2*((212//105) + ln2) - (26//21)*γₑ + (π^2/6) - 2𝒾*π*((41//105) + ln2) + (ν/8)*(-(1738843//19305) + (41//8)*π^2) + (327059//30888)*ν^2 - (17525//15444)*ν^3 + ln(v) * (-26//21) ) ) ) h[Yindex(3,2,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^2 * (√(5//7) * (1 - 3ν) / 3) + (v/c)^4 * ((-193 + (145 - 73ν)*5ν) / 54√35) + (v/c)^5 * ((-15𝒾 + 66𝒾*ν + 10π - 30π*ν) / 3√35) + (v/c)^6 * ((-1451 + (-17387 + 3*(33342 - 5341ν)ν)ν) / 2376√35) ) h[Yindex(3,3,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^1 * (-3𝒾 * √(15//224) * δ) + (v/c)^3 * (-3𝒾 * √(15//56) * δ * (-2 + ν)) + (v/c)^4 * (√(243//70) * δ * (-7 - 5𝒾*π + 10ln³╱₂) / 4) + (v/c)^5 * (-𝒾 * √(3//542080) * δ * (369 + (-3676 + 887ν)ν)) + (v/c)^6 * (δ * (-3645𝒾 * (-8 + 3ν)π + (40824 - 96206ν + 7290*(-8 + 3ν)ln³╱₂)) / 216√210) + (v/c)^7 * ( ((-3𝒾)/4) * √(15//14) * δ * ( (19388147//280280) + (492//35)ln³╱₂ - 18*ln³╱₂^2 - (78//7)γₑ + (3//2)π^2 + 6𝒾 * π * (-41//35 + 3ln³╱₂) + (-7055//3432 + 41//64 * π^2)ν - (318841//17160)ν^2 + (8237//2860)ν^3 + ln(v) * (-(39//7) * 4ln2) ) ) ) end # ell=4 if ℓₘₐₓ ≥ 4 h[Yindex(4,0,ℓₘᵢₙ)] = h₀ * (-1 / 504√2) * @pn_expansion( # Eq. (4.3b) of Favata (2008) 1 + (v/c)^2 * (-180101//29568 + 27227ν/1056) + (v/c)^4 * (2201411267//158505984 - 34829479ν/432432 + 844951ν^2/27456) + (v/c)^5 * (-13565//1232 + 13565ν/308)π + (v/c)^6 * ( 15240463356751//781117489152 + (-1029744557245//27897053184 - 205π^2/96)ν - 4174614175ν^2/36900864 + 221405645ν^3/11860992 ) ) h[Yindex(4,1,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^3 * (𝒾 * δ * (1 - 2ν) / 84√10) + (v/c)^5 * (-𝒾 * δ * (404 + (-1011 + 332ν)ν) / 11088√10) + (v/c)^6 * (δ * (64 - 1661ν - 30𝒾*(-1 + 2ν)π + 60*(1 - 2ν)ln2) / 2520√10) ) h[Yindex(4,2,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^2 * (√5 * (1 - 3ν) / 63) + (v/c)^4 * ((-1311 + 5*(805 - 57ν)ν) / 4158√5) + (v/c)^5 * ((-21𝒾 + ν*(84𝒾 - 30π) + 10π) / 63√5) + (v/c)^6 * ((9342351 + 7ν*(-5460759 + 115ν*(34822 + 3363ν))) / 22702680√5) ) h[Yindex(4,3,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^3 * (9𝒾 * δ * (-1 + 2ν) / 4√70) + (v/c)^5 * (3𝒾 * δ * (468 + (-1267 + 524ν)ν) / 176√70) + (v/c)^6 * (δ * (-5184 + 16301ν + 2430𝒾*(-1 + 2ν)π + 4860*(1 - 2ν)ln³╱₂) / 360√70) ) h[Yindex(4,4,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^2 * (8 * √(5//7) * (-1 + 3ν) / 9) + (v/c)^4 * (4 * (1779 + 5ν*(-1273 + 525ν)) / 297√35) + (v/c)^5 * ((160*(-1 + 3ν)π + 𝒾*(336 - 1193ν + 320*(-1 + 3ν)ln2)) / 9√35) + (v/c)^6 * ((-9618039 + 7ν*(9793071 + 5ν*(-3231338 + 678291ν))) / 405405√35) ) end # ell=5 if ℓₘₐₓ ≥ 5 h[Yindex(5,1,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^3 * (𝒾 * δ * (1 - 2ν) / 288√385) + (v/c)^5 * (-𝒾 * δ * (179 + 4*(-88 + ν)ν) / 11232√385) + (v/c)^6 * (δ * (181 - 70𝒾*(-1 + 2ν)π + 140ln2 - 28ν*(313 + 10ln2)) / 20160√385) ) h[Yindex(5,2,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^4 * ((2 + 10*(-1 + ν)ν) / 27√55) + (v/c)^6 * ((-3911 + 7ν*(3079 + 35ν*(-118 + 33ν))) / 12285√55) ) h[Yindex(5,3,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^3 * (9𝒾 * √(3//110) * δ * (-1 + 2ν) / 32) + (v/c)^5 * (3𝒾 * √(3//110) * δ * (207 + 8ν*(-58 + 11ν)) / 416) + (v/c)^6 * (δ * (-395847 + 1171828ν + 153090𝒾*(-1 + 2ν)π - 306180*(-1 + 2ν)*ln³╱₂) / 60480√330) ) h[Yindex(5,4,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^4 * ((-32 - 160*(-1 + ν)ν) / 9√165) + (v/c)^6 * (16*(4451 - 7ν*(3619 + 5ν*(-1042 + 339ν))) / 4095√165) ) h[Yindex(5,5,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^3 * (-625𝒾 * δ * (-1 + 2ν) / 96√66) + (v/c)^5 * (-625𝒾 * δ * (263 + 16ν*(-43 + 16ν)) / 3744√66) + (v/c)^6 * (δ * (565625 - 1481676ν - 218750𝒾*(-1 + 2ν)π + 437500*(-1 + 2ν)ln⁵╱₂) / 6720√66) ) end # ell=6 if ℓₘₐₓ ≥ 6 h[Yindex(6,0,ℓₘᵢₙ)] = h₀ * (4195/(1419264√273)) * @pn_expansion( # Eq. (4.3c) of Favata (2008) + (v/c)^2 * (1 - 3612ν/839) + (v/c)^4 * (-45661561//6342840 + 101414ν/2517 - 48118ν^2/839) + (v/c)^5 * (1248//839 - 4992ν/839)π + (v/c)^6 * ( 3012132889099//144921208320 - 27653500031ν/191694720 + 1317967427ν^2/4107744 - 24793657ν^3/342312 ) ) h[Yindex(6,1,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^5 * (𝒾 * δ * (-1 + ν) * (-1 + 3 * ν) / 8316√26) ) h[Yindex(6,2,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^4 * ((2 + (-1 + ν) * 10ν) / 297√65) + (v/c)^6 * ((-81 + (59 + (-64 + 7ν)ν) * 7ν) / 2079√65) ) h[Yindex(6,3,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^5 * (-81𝒾 * δ * (-1 + ν) * (-1 + 3ν) / 616√65) ) h[Yindex(6,4,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^4 * (-128 * √(2//39) * (1 + 5 * (-1 + ν)ν) / 495) + (v/c)^6 * (-64 * √(2//39) * (-93 + 7 * (71 + (-88 + 19ν)ν)ν) / 3465) ) h[Yindex(6,5,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^5 * (3125𝒾 * δ * (-1 + ν) * (-1 + 3ν) / 504√429) ) h[Yindex(6,6,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^4 * (54 * (1 + 5 * (-1 + ν)ν) / 5√143) + (v/c)^6 * (27 * (-113 + 7 * (91 + (-128 + 39ν)ν)ν) / 35√143) ) end # ell=7 if ℓₘₐₓ ≥ 7 h[Yindex(7,1,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^5 * (𝒾 * δ * (-1 + ν) * (-1 + 3ν) / 864864√2) ) h[Yindex(7,2,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^6 * ((1 - (-1 + ν)^2 * 7ν) / 3003√3) ) h[Yindex(7,3,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^5 * (-243𝒾 * √(3//2) * δ * (-1 + ν) * (-1 + 3ν) / 160160) ) h[Yindex(7,4,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^6 * (128√(2//33) * (-1 + (-1 + ν)^2 * 7ν) / 1365) ) h[Yindex(7,5,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^5 * (15625𝒾 * δ * (-1 + ν) * (-1 + 3ν) / 26208√66) ) h[Yindex(7,6,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^6 * (-81√(3//143) * (-1 + (-1 + ν)^2 * 7ν) / 35) ) h[Yindex(7,7,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^5 * (-16807𝒾 * √(7//858) * δ * (-1 + ν) * (-1 + 3ν) / 1440) ) end # ell=8 if ℓₘₐₓ ≥ 8 h[Yindex(8,0,ℓₘᵢₙ)] = h₀ * (-75601/(213497856√119)) * @pn_expansion( # Eq. (4.3d) of Favata (2008) + (v/c)^4 * (1 - 452070ν/75601 + 733320ν^2/75601) + (v/c)^6 * ( - 265361599//33869248 + 18177898147ν/321757856 - 722521125ν^2/5745676 + 261283995ν^3/2872838 ) ) h[Yindex(8,2,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^6 * (-(-1 + (-1 + ν)^2 * 7ν) / 9009√85) ) h[Yindex(8,4,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^6 * ((128√(2//187) * (-1 + (-1 + ν)^2 * 7ν)) / 4095) ) h[Yindex(8,6,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^6 * ((-243√(3//17017) * (-1 + (-1 + ν)^2 * 7ν)) / 35) ) h[Yindex(8,8,ℓₘᵢₙ)] = h₀ * @pn_expansion( (v/c)^6 * ((16384√(2//85085) * (-1 + (-1 + ν)^2 * 7ν)) / 63) ) end # Symmetric spin terms if ℓₘₐₓ ≥ 2 h[Yindex(2,0,ℓₘᵢₙ)] += h₀ * @pn_expansion( (v/c)^4 * ((S₀⁺ₙ * S₀⁻ₙ - S₀⁺λ * S₀⁻λ) / (√6 * M^4)) ) h[Yindex(2,1,ℓₘᵢₙ)] += h₀ * @pn_expansion( (v/c)^2 * (𝒾 * Σₗ / 2M^2) + (v/c)^4 * (𝒾 * (-86*Sₗ*δ + Σₗ*(139ν - 79)) / 42M^2) ) h[Yindex(2,2,ℓₘᵢₙ)] += h₀ * @pn_expansion( (v/c)^3 * (-(6Sₗ + 2Σₗ*δ) / 3M^2) + (v/c)^4 * ( (12S₀⁺ₗ*S₀⁻ₗ + 10S₀⁺λ*S₀⁻λ - 22S₀⁺ₙ*S₀⁻ₙ - 15𝒾 * (S₀⁺ₙ*S₀⁻λ + S₀⁺λ*S₀⁻ₙ)) / 12M^4 ) ) end if ℓₘₐₓ ≥ 3 h[Yindex(3,1,ℓₘᵢₙ)] += h₀ * @pn_expansion( (v/c)^4 * (√14𝒾 * (Sₗ*δ - 5Σₗ*(3ν - 1)) / 336M^2) ) h[Yindex(3,2,ℓₘᵢₙ)] += h₀ * @pn_expansion( (v/c)^3 * (2√35 * (Sₗ + Σₗ*δ) / 21M^2) ) h[Yindex(3,3,ℓₘᵢₙ)] += h₀ * @pn_expansion( (v/c)^4 * (3√210𝒾 * (7Sₗ*δ - 3Σₗ*(3ν - 1)) / 112M^2) ) end if ℓₘₐₓ ≥ 4 h[Yindex(4,1,ℓₘᵢₙ)] += h₀ * @pn_expansion( (v/c)^4 * (√10𝒾 * (Sₗ*δ - 3Σₗ*ν + Σₗ) / 336M^2) ) h[Yindex(4,3,ℓₘᵢₙ)] += h₀ * @pn_expansion( (v/c)^4 * (9√70𝒾 * (-Sₗ*δ + 3Σₗ*ν - Σₗ) / 112M^2) ) end # Symmetrize everything for ℓ in 2:ℓₘₐₓ for m in 1:ℓ h[Yindex(ℓ,-m,ℓₘᵢₙ)] = ifelse(isodd(ℓ), -1, 1) * conj(h[Yindex(ℓ,m,ℓₘᵢₙ)]) end end # Anti-symmetric spin terms if ℓₘₐₓ ≥ 2 h̃₂₀ = h₀ * @pn_expansion( (v/c)^2 * (√6𝒾 * Σₙ / 6M^2) + (v/c)^4 * (√6𝒾 * (255Sₙ*δ - Σₙ*(506ν - 45)) / 126M^2) ) h[Yindex(2,0,ℓₘᵢₙ)] += h̃₂₀ h̃₂₁ = h₀ * @pn_expansion( (v/c)^3 * ((4𝒾*Sλ + 25*Sₙ + 4𝒾*Σλ*δ + 13*Σₙ*δ) / 6M^2) + (v/c)^4 * -3 * (S₀⁺ₙ*S₀⁻ₗ + S₀⁺ₗ*S₀⁻ₙ) / (4M^4) ) h[Yindex(2,1,ℓₘᵢₙ)] += h̃₂₁ h[Yindex(2,-1,ℓₘᵢₙ)] += -conj(h̃₂₁) h̃₂₂ = h₀ * @pn_expansion( (v/c)^2 * (-(Σλ + 𝒾*Σₙ) / 2M^2) + (v/c)^4 * ((19*Sλ*δ + 182𝒾*Sₙ*δ - 43*Σλ*ν + 5*Σλ - 280𝒾*Σₙ*ν + 98𝒾*Σₙ) / 84M^2) ) h[Yindex(2,2,ℓₘᵢₙ)] += h̃₂₂ h[Yindex(2,-2,ℓₘᵢₙ)] += -conj(h̃₂₂) end if ℓₘₐₓ ≥ 3 h̃₃₀ = h₀ * @pn_expansion( (v/c)^4 * (√42 * (-17Sλ*δ + Σλ*(35ν - 9)) / 168M^2) ) h[Yindex(3,0,ℓₘᵢₙ)] += h̃₃₀ h̃₃₁ = h₀ * @pn_expansion( (v/c)^3 * (√14 * (𝒾*Sλ + Sₙ + δ*(𝒾*Σλ + Σₙ)) / 21M^2) ) h[Yindex(3,1,ℓₘᵢₙ)] += h̃₃₁ h[Yindex(3,-1,ℓₘᵢₙ)] += conj(h̃₃₁) h̃₃₂ = h₀ * @pn_expansion( (v/c)^4 * (√35 * (-Σλ*(83ν - 17) + 4𝒾*Σₙ*(55ν - 13) + 25δ * (Sλ - 4𝒾*Sₙ)) / 168M^2) ) h[Yindex(3,2,ℓₘᵢₙ)] += h̃₃₂ h[Yindex(3,-2,ℓₘᵢₙ)] += conj(h̃₃₂) h̃₃₃ = h₀ * @pn_expansion( (v/c)^3 * (√210𝒾 * (Sλ + 𝒾*Sₙ + δ*(Σλ + 𝒾*Σₙ)) / 21M^2) ) h[Yindex(3,3,ℓₘᵢₙ)] += h̃₃₃ h[Yindex(3,-3,ℓₘᵢₙ)] += conj(h̃₃₃) end if ℓₘₐₓ ≥ 4 h̃₄₀ = h₀ * @pn_expansion( (v/c)^4 * (√2𝒾 * (Sₙ*δ - 3Σₙ*ν + Σₙ) / 168M^2) ) h[Yindex(4,0,ℓₘᵢₙ)] += h̃₄₀ h̃₄₂ = h₀ * @pn_expansion( (v/c)^4 * (√5 * (-13Σλ*(3ν - 1) + 14𝒾*Σₙ*(3ν - 1) + δ*(13Sλ - 14𝒾*Sₙ)) / 168M^2) ) h[Yindex(4,2,ℓₘᵢₙ)] += h̃₄₂ h[Yindex(4,-2,ℓₘᵢₙ)] += -conj(h̃₄₂) h̃₄₄ = h₀ * @pn_expansion( (v/c)^4 * (9√35 * (-3Σλ*ν + Σλ - 𝒾*Σₙ*(3ν - 1) + δ*(Sλ + 𝒾*Sₙ)) / 56M^2) ) h[Yindex(4,4,ℓₘᵢₙ)] += h̃₄₄ h[Yindex(4,-4,ℓₘᵢₙ)] += -conj(h̃₄₄) end h end const mode_weights! = h!
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
5049
""" Ω⃗ₚ(pnsystem) Compute the angular velocity of orbital precession. This is the angular velocity *of* the orbital angular velocity direction unit vector ``ℓ̂``; the time derivative of that *unit* vector is ``Ω⃗ₚ × ℓ̂``. At the moment, this is computed solely by expressions from [Bohé et al. (2013)](https://arxiv.org/abs/1212.5520). See [`𝛡`](@ref) for details. See also [`R`](@ref PostNewtonian.R). """ Ω⃗ₚ(pnsystem) = 𝛡(pnsystem) const Omega_p = Ω⃗ₚ """ 𝛡(pnsystem) Compute the angular velocity of orbital precession according to Bohé et al. As [Bohé et al. (2013)](https://arxiv.org/abs/1212.5520) explain above their Eq. (4.1), the orbital precession is given by the time derivative of the orbital axis: 𝓵̇ = 𝛡 × 𝓵, where the angular velocity is along the separation vector 𝓷, so that 𝛡 = ϖ 𝓷. And in turn, they define aₗ ≔ r ω ϖ, where r is the separation and ω is the orbital angular frequency. Then, they define the PN parameter γₚₙ≔M/r and we have Mω = v³ so that ϖ = γₚₙ aₗ / v³. The parameters γₚₙ and aₗ are given by Eqs. (4.3) and (4.4), and given here by the functions [`γₚₙ`](@ref) and [`aₗ`](@ref). The spin-squared terms (by which we mean both spin-spin and spin-orbit squared terms) in the energy are known to 3pN order, and given in [Eq. (3.32) of Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). See also [`R`](@ref PostNewtonian.R). """ @pn_expression function 𝛡(pnsystem) return (γₚₙ(pnsystem) * aₗ(pnsystem) / (v / c)^3) * n̂ end """ aₗ(pnsystem) Eq. (4.4) of [Bohé et al. (2013)](https://arxiv.org/abs/1212.5520). This term contributes to [`𝛡`](@ref). """ @pn_expression function aₗ(pnsystem) return (v / c)^7 / M^3 * @pn_expansion( (7Sₙ + 3δ * Σₙ) + (v / c)^2 * ((-10 - 29ν / 3) * Sₙ + δ * (-6 - 9ν / 2) * Σₙ) + (v / c)^4 * ((3//2 + 59ν / 4 + 52ν^2 / 9) * Sₙ + δ * (3//2 + 73ν / 8 + 17ν^2 / 6) * Σₙ) ) end """ Ω⃗ᵪ₁(pnsystem) Compute the angular velocity of precession of χ⃗₁ In the approximation that the spin *magnitude* is constant, the time derivative of ``χ⃗₁`` is due to its rotation alone, and is given by ``Ω⃗ᵪ₁ × χ⃗₁``. Note that this function simply calls [`Ω⃗ᵪ`](@ref) with the appropriate parameters. """ @pn_expression function Ω⃗ᵪ₁(pnsystem) # Note that `PNExpansionReducer` appears magically via the `@pn_expression` macro, along # with other magic variables, as usual. return QuatVec(Ω⃗ᵪ(M₁, M₂, χ⃗₁, χ⃗₂, v, R, pnsystem, PNExpansionReducer)) end const Omega_chi1 = Ω⃗ᵪ₁ """ Ω⃗ᵪ₂(pnsystem) Compute the angular velocity of precession of χ⃗₂ In the approximation that the spin *magnitude* is constant, the time derivative of ``χ⃗₂`` is due to its rotation alone, and is given by ``Ω⃗ᵪ₂ × χ⃗₂``. Note that this function simply calls [`Ω⃗ᵪ`](@ref) with the appropriate parameters. """ @pn_expression function Ω⃗ᵪ₂(pnsystem) # Note that `PNExpansionReducer` appears magically via the `@pn_expression` macro, along # with other magic variables, as usual. return QuatVec(Ω⃗ᵪ(M₂, M₁, χ⃗₂, χ⃗₁, v, R, pnsystem, PNExpansionReducer)) end const Omega_chi2 = Ω⃗ᵪ₂ """ Ω⃗ᵪ(Mⱼ, Mₖ, χ⃗ⱼ, χ⃗ₖ, R) Compute the angular velocity of precession of spin vector `χ⃗ⱼ`. In the approximation that the spin *magnitude* is constant, the time derivative of ``χ⃗ⱼ`` is due to its rotation alone, and is given by ``Ω⃗ᵪ × χ⃗ⱼ``. Note that this function is called by [`Ω⃗ᵪ₁`](@ref) and [`Ω⃗ᵪ₂`](@ref) with the appropriate parameters; you probably want to use those instead of this one. The spin-spin term is given by Eq. (2.4) of [Kidder (1995)](http://link.aps.org/doi/10.1103/PhysRevD.52.821); the spin-orbit terms by Eq. (4.5) of [Bohé et al. (2013)](http://arxiv.org/abs/1212.5520v2); and the quadrupole-monopole term by Eq. (2.7) [Racine (2008)](http://link.aps.org/doi/10.1103/PhysRevD.78.044021). """ function Ω⃗ᵪ(Mⱼ, Mₖ, χ⃗ⱼ, χ⃗ₖ, v, R, pnsystem, PNExpansionReducer) # Note that we don't use the `@pn_expression` macro here, because we're swapping # the order of certain arguments above, so we do it manually here, and don't just # call things like `δ(pnsystem)` because that would fail to swap. let M = M(Mⱼ, Mₖ), ν = ν(Mⱼ, Mₖ), δ = δ(Mⱼ, Mₖ), n̂ = n̂(R), ℓ̂ = ℓ̂(R), c = one(eltype(pnsystem)) χⱼₙ = χ⃗ⱼ ⋅ n̂ χₖₙ = χ⃗ₖ ⋅ n̂ (v / c)^5 / M * @pn_expansion pnsystem ( # Spin-spin term from Eq. (2.4) of Kidder v / c * (Mₖ^2 / M^2) * (-χ⃗ₖ + 3χₖₙ * n̂) # Spin-orbit terms from Eq. (4.5) of Bohé et al. + ( (3//4 + ν / 2 - 3δ / 4) + (v / c)^2 * (9//16 + 5ν / 4 - ν^2 / 24 + δ * (-9//16 + 5ν / 8)) + (v / c)^4 * ( 27//32 + 3ν / 16 - 105ν^2 / 32 - ν^3 / 48 + δ * (-27//32 + 39ν / 8 - 5ν^2 / 32) ) ) * ℓ̂ # Quadrupole-monopole term from Eq. (2.7) of Racine + v / c * (3ν * χⱼₙ * n̂) ) end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
12954
@doc raw""" γₚₙ(pnsystem) inverse_separation(pnsystem) Compute the post-Newtonian parameter ```math \gamma_{\mathrm{PN}} \equiv \frac{G\, M}{r\, c^2}, ``` where ``r`` is the magnitude of the orbital separation. This quantity has PN order 1, and is given by Eq. (4.3) of [Bohé et al. (2013)](https://arxiv.org/abs/1212.5520) and Eq. (3.32) of [Bohé et al. (2015)](https://arxiv.org/abs/1501.01529). Note that there is a 3PN gauge term of ``-22ν\ln(r/r₀')/3`` that is simply ignored here, as it should cancel out of any physical quantity. """ @pn_expression function γₚₙ(pnsystem) return (v / c)^2 * @pn_expansion( # Non-spinning terms; Eq. (4.3) of Bohé et al. (2013) 1 + (v / c)^2 * (1 - ν / 3) + (v / c)^4 * (1 - 65ν / 12) + (v / c)^6 * (1 + (-2203//2520 - 41π^2 / 192)ν + 229ν^2 / 36 + ν^3 / 81) # Spin-orbit terms; Eq. (4.3) of Bohé et al. (2013) + (v / c)^3 * (5//3 * sₗ + δ * σₗ) + (v / c)^5 * ((10//3 + 8ν / 9) * sₗ + 2δ * σₗ) + (v / c)^7 * ((5 - 127ν / 12 - 6ν^2) * sₗ + δ * (3 - 61ν / 6 - 8ν^2 / 3) * σₗ) # Spin-squared terms; Eq. (3.32) of Bohé et al. (2015) + (v / c)^4 * ( sₗ^2 * (-κ₊ / 2 - 1) + sₗ * σₗ * (-δ * κ₊ / 2 - δ + κ₋ / 2) + σₗ^2 * (δ * κ₋ / 4 - κ₊ / 4 + (κ₊ / 2 + 1)ν) ) + (v / c)^6 * ( sₗ^2 * (-11δ * κ₋ / 12 - 11κ₊ / 12 + 14//9 + (-κ₊ / 6 - 1//3)ν) + sₗ * σₗ * (5δ / 3 + (-δ * κ₊ / 6 - δ / 3 + 23κ₋ / 6)ν) + σₗ^2 * (1 + (δ * κ₋ - κ₊ - 2)ν + (κ₊ / 6 + 1//3)ν^2) ) ) end const inverse_separation = γₚₙ @doc raw""" γₚₙ′(pnsystem) inverse_separation_deriv(pnsystem) Compute the derivative of [`γₚₙ`](@ref) with respect to `v`. """ @generated function γₚₙ′( pnsystem::PNSystem{ST,PNOrder}; pn_expansion_reducer::Val{PNExpansionReducer}=Val(sum) ) where {ST,PNOrder,PNExpansionReducer} # Create a `PNSystem` with `FastDifferentiation` (henceforth FD) variables, using the # same PNOrder as the input `pnsystem`. fdpnsystem = FDPNSystem(eltype(ST), PNOrder) # FD expects a single vector of variables, so we concatenate the state vector with the # two tidal-coupling parameters vars = FastDifferentiation.Node[fdpnsystem.state; Λ₁(fdpnsystem); Λ₂(fdpnsystem)] # Now we evaluate γₚₙ using the FD variables. This will expand all derived variables in # terms of the fundamental variables, but FD will take care of evaluating those # efficiently via common subexpression elimination (CSE). γₚₙformula = γₚₙ(fdpnsystem; pn_expansion_reducer=Val(PNExpansionReducer)) # Now we take the derivative of γₚₙ with respect to v. γₚₙ′ = SVector(FastDifferentiation.derivative(γₚₙformula, v(fdpnsystem))) # Turn that into an Expr (FD insists on making it a function) in_place = true init_with_zeros = false γₚₙ′expr = FastDifferentiation.make_Expr(γₚₙ′, vars, in_place, init_with_zeros) # Now, we use `MacroTools` to get the body of the function. γₚₙ′body = MacroTools.unblock(MacroTools.splitdef(γₚₙ′expr)[:body]) # # At this point, the function is just a long series of statements inside an `@inbounds` # # block, which we will want later, but first we need to extract them. MacroTools.@capture(γₚₙ′body, @inbounds begin γₚₙ′statements__ end) || throw( ArgumentError( "\nNo @inbounds block found in γₚₙ′ expression." * "\nSomething may have changed in FastDifferentiation." * "\nOpen an issue citing this Julia call:" * "\n```julia" * "\nusing PostNewtonian" * "\nγₚₙ′($pnsystem)" * "\n```", ), ) # The γₚₙ′statements are mostly what we want, except that the last line is a return # statement. We want that result, but we don't to return it yet; we want to wrap that # result, so we just get that returned quantity here. MacroTools.@capture(γₚₙ′statements[end], return γₚₙ′return_) || throw( ArgumentError( "\nNo return statement found in γₚₙ′ expression." * "\nSomething may have changed in FastDifferentiation." * "\nOpen an issue citing this Julia call:" * "\n```julia" * "\nusing PostNewtonian" * "\nγₚₙ′($pnsystem)" * "\n```", ), ) γₚₙ′statements[end] = γₚₙ′return if PNExpansionReducer === identity # When `pn_expansion_reducer=Val(identity)` is passed, we return a PNExpansion NMax = Int(2PNOrder + 1) return quote input_variables = SVector(pnsystem) result = MVector{$(length(γₚₙ′)),$(eltype(ST))}(undef) result .= 0 @fastmath @inbounds begin $(γₚₙ′statements...) end return PNExpansion{$(length(γₚₙ′)),$(eltype(ST)),$NMax}(Tuple(result)) end else # Otherwise, FD produces a 1-tuple, so we just extract the value from that. return quote input_variables = SVector(pnsystem) result = MVector{1,$(eltype(ST))}(undef) result .= 0 @fastmath @inbounds begin $(γₚₙ′statements...) end return result[1] end end end const inverse_separation_deriv = γₚₙ′ """ r(pnsystem) separation(pnsystem) Compute the separation between the two black holes. This is essentially the inverse of [`γₚₙ`](@ref), with some factors of `G` and `M` thrown in. Note that there should be a factor of `1/c^2` in this expression; we reserve it to use explicitly in PN expansions. That is, for every factor of `1/r`, we explicitly include a factor of `1/c^2` in the expansion. """ @pn_expression function r(pnsystem) let γₚₙ = γₚₙ(pnsystem) return G * M / (γₚₙ * c^2) end end const separation = r """ r′(pnsystem) separation_deriv(pnsystem) Compute the derivative of the separation between the two black holes with respect to `v`. """ @pn_expression function r′(pnsystem) let γₚₙ = γₚₙ(pnsystem) -γₚₙ′ * G * M / (γₚₙ^2 * c^2) end end const separation_deriv = r′ @pn_expression function ṙ(pnsystem) let γₚₙ = γₚₙ(pnsystem), γₚₙ′ = γₚₙ′(pnsystem), 𝓕 = 𝓕(pnsystem), 𝓔′ = 𝓔′(pnsystem) 𝓕 * γₚₙ′ * G * M / (γₚₙ^2 * c^2 * 𝓔′) end end const separation_dot = ṙ """ γₚₙ⁻¹(γ, pnsystem) inverse_separation_inverse(γ, pnsystem) Return `v` such that `γₚₙ(pnsystem) = γ` when `pnsystem` is evaluated at `v`. Note that the value of `v` in the input `pnsystem` is ignored; you may use any value. It may also be convenient to know that you can set the value of `v` in `pnsystem` to the returned value using `PostNewtonian.vindex` as in ```julia pnsystem.state[PostNewtonian.vindex] = γₚₙ⁻¹(γ, pnsystem) ``` See also [`r⁻¹`](@ref). """ function γₚₙ⁻¹(γ, pnsystem) if 2γ ≥ 1 @info "Error with" pnsystem throw(ArgumentError("γ=$γ ≥ 1/2 describes a binary that has already merged")) elseif γ ≤ 0 @info "Error with" pnsystem throw(ArgumentError("γ=$γ ≤ 0 is unphysical")) end # We evaluate at v=1 just to get all the terms out separately, without actually multiplying # by the powers of v. pn = deepcopy(pnsystem) pn.state[vindex] = one(eltype(pn)) # Now we can get the actual terms. Note that there is a pre-factor of (v/c)^2. γₚₙ_expansion = γₚₙ(pn; pn_expansion_reducer=Val(identity)) # Include the pre-factor of (v/c)^2, then compute coefficients of the first and second # derivatives with respect to v. coeffs = (0.0, 0.0, γₚₙ_expansion.coeffs...) coeffs′ = Tuple(i * c for (i, c) ∈ enumerate(coeffs[2:end])) coeffs′′ = Tuple(i * c for (i, c) ∈ enumerate(coeffs′[2:end])) # Defining the cost function as Ξ(v) = (evalpoly(v, coeffs) - γ)^2, the Newton step is # -Ξ′(v) / Ξ′′(v), which is easy to compute from the coefficients: function newton_step(v) return -( (evalpoly(v, coeffs) - γ) * evalpoly(v, coeffs′) / ((evalpoly(v, coeffs) - γ) * evalpoly(v, coeffs′′) + (evalpoly(v, coeffs′))^2) ) end # Now we just do a few Newton steps to get the value of v. vᵢ = let ν = ν(pnsystem) try √((3 - √(-12ν * γ + 36γ + 9)) / (2ν - 6)) catch return zero(γ) # @info γ pnsystem # rethrow end end for i ∈ 1:10 # Limit the possible number of steps, just in case δvᵢ = newton_step(vᵢ) vᵢ += δvᵢ if abs(δvᵢ) < 10eps(vᵢ) break end end return vᵢ end const inverse_separation_inverse = γₚₙ⁻¹ """ r⁻¹(r, pnsystem) separation_inverse(r, pnsystem) Return `v` such that `r = r(v)` when `pnsystem` is evaluated at `v`. Note that the value of `v` in the input `pnsystem` is ignored; you may use any value. It may also be convenient to know that you can set the value of `v` in `pnsystem` to the returned value using `PostNewtonian.vindex` as in ```julia pnsystem.state[PostNewtonian.vindex] = r⁻¹(r, pnsystem) ``` See also [`γₚₙ⁻¹`](@ref). """ function r⁻¹(r, pnsystem) let c = 1, G = 1, M = M(pnsystem) γ = G * M / (r * c^2) v = γₚₙ⁻¹(γ, pnsystem) end end const separation_inverse = r⁻¹ """ This module contains a few expressions from [Kidder (1995)](https://arxiv.org/abs/gr-qc/9506022). This is mostly here for testing, because these expressions are not directly used in this package: they are somewhat outdated and describe quantities that are not actually used in this formulation. However, they were used in the SpEC code as an initial guess for eccentricity reduction, so we want to make sure that results from this package are consistent with those from SpEC. """ module Kidder1995 using PostNewtonian: @pn_expansion, @pn_expression, M, M₁, M₂, ν, δ, χ₁ₗ, χ₂ₗ, χ₁₂, Ω, type_converter, PNExpansionParameter """ r(pnsystem) Eq. (4.13). """ @pn_expression function r(pnsystem) let m = M, m₁ = M₁, m₂ = M₂, η = ν, δm = δ * M, χ₁L̂ₙŝ₁ = χ₁ₗ, χ₂L̂ₙŝ₂ = χ₂ₗ, ω = Ω m * (m * ω)^(-2//3) * @pn_expansion( 1 - 1//3 * (3 - η) * (m * ω)^(2//3) / c^2 - ( 1//3 * ((χ₁L̂ₙŝ₁ * (2 * m₁^2 / m^2 + 3η)) + (χ₂L̂ₙŝ₂ * (2 * m₂^2 / m^2 + 3η))) ) * (m * ω) / c^3 + (η * (19//4 + η / 9) - 1//2 * η * (χ₁₂ - 3χ₁L̂ₙŝ₁ * χ₂L̂ₙŝ₂)) * (m * ω)^(4//3) / c^4 ) end end const separation = r """ ṙ(pnsystem) Eq. (4.12), computed as ṙ = (dE/dt) / (dE/dr), re-expanded and truncated. """ @pn_expression function ṙ(pnsystem) let r = r(pnsystem) let m = M, m₁ = M₁, m₂ = M₂, η = ν, δm = δ * M, χ₁L̂ₙŝ₁ = χ₁ₗ, χ₂L̂ₙŝ₂ = χ₂ₗ -64//5 * η * (m / r)^3 * @pn_expansion( 1 - 1//336 * (1751 + 588η) * (m / r) / c^2 - ( 7//12 * ( (χ₁L̂ₙŝ₁ * (19 * m₁^2 / m^2 + 15η)) + (χ₂L̂ₙŝ₂ * (19 * m₂^2 / m^2 + 15η)) ) - 4π ) * (m / r)^(3//2) / c^3 - 5//48 * η * (59χ₁₂ - 173χ₁L̂ₙŝ₁ * χ₂L̂ₙŝ₂) * (m / r)^2 / c^4 ) end end end end # module Kidder1995 @testitem "separation" begin using Random using PostNewtonian: @pn_expansion, @pn_expression, ṙ, Kidder1995 rng = Random.Xoshiro(1234) for pnsystem ∈ (rand(rng, BBH) for _ ∈ 1:1_000) # We know that Larry's expression is outdated. It may get more so as we include # newer PN terms, so this tolerance may need to be adjusted. This is more of a # sanity check. @test Kidder1995.ṙ(pnsystem) ≈ ṙ(pnsystem) rtol = 0.03 end end @testitem "separation_inverse" begin using Random using PostNewtonian: PostNewtonian, γₚₙ, γₚₙ⁻¹, M₁index, M₂index, v, r, r⁻¹ rng = Random.Xoshiro(1234) for _ ∈ 1:100_000 # First, create a random system. Make it NSNS to ensure that as many code paths as # possible are tested. Ensure that v≤1/2 to avoid cases where the system has # already merged. pnsystem = rand(rng, NSNS; v=rand(rng) / 2) # Test γ vᵧ = γₚₙ⁻¹(γₚₙ(pnsystem), pnsystem) @test abs(1 - vᵧ / v(pnsystem)) < 3eps(typeof(vᵧ)) # Now perturb the masses just enough to ensure that the total mass is significantly # different from 1, but not so different as to mess with the tolerance. pnsystem.state[M₁index] *= 1.03 pnsystem.state[M₂index] *= 1.09 # And re-test with `r` instead of `γ`. vᵣ = r⁻¹(r(pnsystem), pnsystem) @test abs(1 - vᵣ / v(pnsystem)) < 3eps(typeof(vᵣ)) end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
2507
@doc raw""" tidal_heating(pnsystem) Compute the rate of energy and angular-momentum absorption into each black hole in a binary. The returned quantity is a tuple `(Ṡ₁, Ṁ₁, Ṡ₂, Ṁ₂)`, representing the corresponding rates of change of spin (magnitude) and mass on black hole 1 and black hole 2. These apply to general — possibly precessing — non-eccentric binaries. This collection of terms comes from [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020). It probably wouldn't be too hard to extend Alvi's analysis to eccentric systems. Note that the validity of the result depends not only on the PN parameter ``v``, but also on the angles of the spins relative to the separation vector ``n̂``: the smaller the angle, the lower the ``v`` at which the approximations should be expected to break down. See also - [Tagoshi and Sasaki (1994)](http://arxiv.org/abs/gr-qc/9405062) - [Poisson and Sasaki (1995)](https://arxiv.org/abs/gr-qc/9412027) - [Tagoshi et al. (1997)](https://arxiv.org/abs/gr-qc/9711072) - [Porto (2007)](https://arxiv.org/abs/0710.5150) - [Chatziioannou et al. (2012)](https://arxiv.org/abs/1211.1686) See the documentation section on ["Horizons"](@ref Horizons) for details about the computation of horizon quantities used in this function. """ @pn_expression function tidal_heating(pnsystem) # References to pages and equation numbers are from Alvi (2001) # Un-normalize these quantities (they could now be defined this way...) ϕ̇₁ = (v / c)^3 * ϕ̇̂₁ ϕ̇₂ = (v / c)^3 * ϕ̇̂₂ I₀₁ = ν^2 * (v / c)^12 * Î₀₁ I₀₂ = ν^2 * (v / c)^12 * Î₀₂ # Eq. (21) # Note that the Ṁ₁ and Ṁ₂ terms start at 2.5pN order relative to the flux (because # ϕ̇ᵢ * I₀ᵢ is at absolute 7.5pN order, while flux starts at absolute 5pN order). That's # why they're divided by c^5 inside the `@pn_expansion`. Ṡ₁ = I₀₁ * @pn_expansion (ϕ̇₁ / c^3 - Ωₕ₁) Ṁ₁ = ϕ̇₁ * I₀₁ * c^5 * @pn_expansion (ϕ̇₁ / c^3 - Ωₕ₁) / c^5 # = ϕ̇₁ * Ṡ₁ Ṡ₂ = I₀₂ * @pn_expansion (ϕ̇₂ / c^3 - Ωₕ₂) Ṁ₂ = ϕ̇₂ * I₀₂ * c^5 * @pn_expansion (ϕ̇₂ / c^3 - Ωₕ₂) / c^5 # = ϕ̇₂ * Ṡ₂ # # Eq. (21) # Ṡ₁ = ν^2 * Î₀₁ * v^12 * @pn_expansion (v^3 * ϕ̇̂₁ - Ωₕ₁) # Ṁ₁ = ν^2 * Î₀₁ * v^12 * v^3 * ϕ̇̂₁ * @pn_expansion 5 (v^3 * ϕ̇̂₁ - Ωₕ₁) # ϕ̇₁ * Ṡ₁ # Ṡ₂ = ν^2 * Î₀₂ * v^12 * @pn_expansion (v^3 * ϕ̇̂₂ - Ωₕ₂) # Ṁ₂ = ν^2 * Î₀₂ * v^12 * v^3 * ϕ̇̂₂ * @pn_expansion 5 (v^3 * ϕ̇̂₂ - Ωₕ₂) # ϕ̇₂ * Ṡ₂ return (Ṡ₁, Ṁ₁, Ṡ₂, Ṁ₂) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
3390
# This should be an internal class that just allows us to combine ODE solution objects struct CombinedInterpolationData <: AbstractDiffEqInterpolation sol₋::Any sol₊::Any tᵢ::Any end function (interp::CombinedInterpolationData)( tvals::AbstractFloat, idxs, deriv, p, continuity::Symbol=:left ) if tvals ≥ interp.tᵢ interp.sol₊.interp(tvals, idxs, deriv, p, continuity) else interp.sol₊.interp(tvals, idxs, deriv, p, continuity) end end function (interp::CombinedInterpolationData)( val, tvals::AbstractFloat, idxs, deriv, p, continuity::Symbol=:left ) if tvals ≥ interp.tᵢ interp.sol₊.interp(val, tvals, idxs, deriv, p, continuity) else interp.sol₊.interp(val, tvals, idxs, deriv, p, continuity) end end function (interp::CombinedInterpolationData)( tvals, idxs, deriv, p, continuity::Symbol=:left ) val = if idxs isa Integer Vector{eltype(interp.sol₊)}(undef, length(tvals)) elseif isnothing(idxs) [Vector{eltype(interp.sol₊)}(undef, size(interp.sol₊, 1)) for _ ∈ eachindex(tvals)] else [Vector{eltype(interp.sol₊)}(undef, length(idxs)) for _ ∈ eachindex(tvals)] end return interp(val, tvals, idxs, deriv, p, continuity) end function (interp::CombinedInterpolationData)( val, tvals, idxs, deriv, p, continuity::Symbol=:left ) i₊ = tvals .≥ interp.tᵢ i₋ = tvals .< interp.tᵢ if idxs isa Integer for i ∈ eachindex(tvals) if tvals[i] ≥ interp.tᵢ val[i] = interp.sol₊.interp(tvals[i], idxs, deriv, p, continuity) else val[i] = interp.sol₋.interp(tvals[i], idxs, deriv, p, continuity) end end else for i ∈ eachindex(tvals) if tvals[i] ≥ interp.tᵢ val[i] .= interp.sol₊.interp(tvals[i], idxs, deriv, p, continuity) else val[i] .= interp.sol₋.interp(tvals[i], idxs, deriv, p, continuity) end end end p = interp.sol₊.prob.p variables = interp.sol₊.prob.f.sys.variables parameters = interp.sol₊.prob.f.sys.parameters independent_variables = interp.sol₊.prob.f.sys.independent_variables return DiffEqArray(val, tvals, p; variables, parameters, independent_variables) end """ combine_solutions(sol₋, sol₊) Combine ODESolutions This function is internal to this package. It is not entirely general, but allows us to combine the backwards- and forwards-in-time solutions of the PN orbital-evolution ODE equations into a single `ODESolution` object that should behave just as if it were the result of `solve`. In particular, indexing, interpolation, and iterations should behave exactly as [described in the `DifferentialEquations` docs](https://diffeq.sciml.ai/stable/basics/solution/). """ function combine_solutions(sol₋, sol₊) alg = sol₊.alg t = [reverse(sol₋.t[2:end]); sol₊.t] u = [reverse(sol₋.u[2:end]); sol₊.u] retcode = sol₊.retcode # Could be something more clever; maybe the worse retcode? problem = ODEProblem(sol₊.prob.f, u[1], (t[1], t[end]), sol₊.prob.p) if sol₊.dense interp = CombinedInterpolationData(sol₋, sol₊, sol₊.t[1]) build_solution(problem, alg, t, u; dense=true, retcode=retcode, interp=interp) else build_solution(problem, alg, t, u; dense=false, retcode=retcode) end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
7148
""" type_converter(pnsystem, x) Convert `x` to a type appropriate for the float type of `pnsystem`. This is sort of an expansion of the `convert` function, but with nicer syntax for types from this package, including the ability to do really weird things for `SymbolicPNSystem`. It's needed to ensure that the types of variables and constants are correct when we use them in expressions, rather than just assuming everything is a `Float64`. """ function type_converter(pnsystem, x) return convert(eltype(pnsystem), x) end function type_converter(::FDPNSystem{FT}, x) where {FT} return convert(FT, x) end function type_converter(::FDPNSystem, x::FastDifferentiation.Node) return x end fundamental_variables = methodswith(PNSystem, FundamentalVariables) fundamental_quaternionic_variables = [ m for m ∈ methodswith(AbstractVector, FundamentalVariables) if m.name ∈ [:χ⃗₁, :χ⃗₂, :R] ] derived_variables = methodswith(VecOrPNSystem, DerivedVariables) pnvariables = map(v -> v.name, [fundamental_variables; derived_variables]) irrationals = unique( [ find_symbols_of_type(Base.MathConstants, Irrational) find_symbols_of_type(MathConstants, Irrational) ], ) # This should include all the unary functions that we want to use in any PN expression. unary_funcs = [:√, :sqrt, :log, :ln, :sin, :cos] function pn_expression(pnsystem::Symbol, body) # Look for variables in `body` that we need to treat specially, and write exprs to do # so. These three are described as bullet points in the docstring of `@pn_expression`. pnvariables_exprs = [ :($v = $v($pnsystem)) for v ∈ filter(v -> MacroTools.inexpr(body, v), pnvariables) ] irrationals_exprs = [ :($v = type_converter($pnsystem, $v)) for v ∈ filter(v -> MacroTools.inexpr(body, v), irrationals) ] unary_funcs_exprs = [ :($v = (x -> $v(type_converter($pnsystem, x)))) for v ∈ filter(v -> MacroTools.inexpr(body, v), unary_funcs) ] exprs = [ pnvariables_exprs irrationals_exprs unary_funcs_exprs ] # Next, add pnsystem as the argument to each @pn_expansion call new_body = MacroTools.unblock( macroexpand( @__MODULE__, MacroTools.postwalk(body) do x if MacroTools.isexpr(x, :macrocall) && x.args[1] == Symbol("@pn_expansion") && !isa(x.args[end - 1], Symbol) x′ = deepcopy(x) insert!(x′.args, length(x′.args), pnsystem) x′ else x end end; recursive=true, ), ) # Finally, just wrap `new_body` in a `let` block, where we include exprs created above. # Also include the definitions `c=G=1` (to be overwritten inside any `@pn_expansion`). return full_body = MacroTools.unblock( quote c = one(eltype($pnsystem)) G = one(eltype($pnsystem)) @fastmath let $(exprs...) $(new_body) end end, ) end function pn_expression(arg_index::Integer, func) splitfunc = MacroTools.splitdef(func) pnsystem = MacroTools.namify(splitfunc[:args][arg_index]) splitfunc[:kwargs] = [ splitfunc[:kwargs] :($(Expr(:kw, :(pn_expansion_reducer::Val{PNExpansionReducer}), :(Val(sum))))) ] splitfunc[:whereparams] = (splitfunc[:whereparams]..., :PNExpansionReducer) splitfunc[:body] = pn_expression(pnsystem, splitfunc[:body]) return MacroTools.combinedef(splitfunc) end """ @pn_expression [arg_index=1] func This macro takes the function `func`, looks for various symbols inside that function, and if present defines them appropriately inside that function. The first argument to this macro is `arg_index`, which just tells us which argument to the function `func` is a `PNSystem`. For example, the variables defined in [`PostNewtonian.FundamentalVariables`](@ref "Fundamental variables") all take a single argument of `pnsystem`, which is used to compute the values for those variables; this macro just needs to know where to find `pnsystem`. Once it has this information, there are five types of transformations it will make: 1. Adds a keyword argument `pn_expansion_reducer::Val{PNExpansionReducer}=Val(sum)` to the function signature. This is used to determine how to reduce the PN expansion terms. The default is `Val(sum)`, which will just return a single number, but `Val(identity)` can be used to return the expansion. This should be used inside the function as `PNExpansionReducer`, and will be automatically used inside any `@pn_expansion`. 2. For every [fundamental](@ref "Fundamental variables") or [derived](@ref "Derived variables") variable, the name of that variable used in the body of `func` will be replaced by its value when called with `pnsystem`. For example, you can simply use the symbols `M₁` or `μ` in your code, rather than calling them as [`M₁(pnsystem)`](@ref M₁) or [`μ(pnsystem)`](@ref μ) every time they appear. 3. Every `Irrational` defined in `Base.MathConstants` or `PostNewtonian.MathConstants` will be transformed to the `eltype` of `pnsystem`. This lets you naturally use such constants in expressions like `2π/3` without automatically converting to `Float64`. 4. Each of a short list of functions given by `unary_funcs` in `utilities/macros.jl` will first convert their arguments to the `eltype` of `pnsystem`. In particular, you can use expressions like `√10` or `ln(2)` without the result being converted to a `Float64`. 5. Insert the `pnsystem` argument as the first argument to each occurrence of `@pn_expansion` that needs it. To be more explicit, the first three are achieved by defining the relevant quantities in a `let` block placed around the body of `func`, so that the values may be used efficiently without recomputation. If you need to use one of the fundamental- or derived-variable functions as arguments of values other than those encapsulated in `pnsystem`, you'll need to address them explicitly with the module name — as in `PostNewtonian.v(;Ω, M)`. """ macro pn_expression(func) return esc(pn_expression(1, func)) end macro pn_expression(arg_index, func) return esc(pn_expression(arg_index, func)) end """ @pn_expansion [pnsystem] expansion Gather terms in `expansion` by the powers of ``1/c`` involved, zeroing out any terms with powers of ``1/c`` higher than the `pnsystem`'s `PNOrder` parameter, and combine the terms using the `PNExpansionReducer` specified in argument of the function that includes this macro call. This expansion is achieved by setting — inside a `let` block created by this macro — Note that the `pnsystem` argument can be inserted automatically by [`@pn_expression`](@ref). """ macro pn_expansion(pnsystem, expr) return esc(pn_expansion(pnsystem, expr)) end function pn_expansion(pnsystem, expr) quote let c = PNExpansionParameter($pnsystem) PNExpansionReducer($expr) end end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
3851
module MathConstants export log2, ln2, log3, ln3, log5, ln5, log3halves, log³╱₂, ln³╱₂, log5halves, log⁵╱₂, ln⁵╱₂, apery, ζ3, γₑ, 𝒾 Base.@irrational ln2 0.6931471805599453 log2 Base.@irrational γₑ 0.57721566490153286061 euler Base.@irrational ln3 1.0986122886681097 big"1.098612288668109691395245236922525704647490557822749451734694333637494293218608966873615754813732088787970029" Base.@irrational ln5 1.6094379124341003 big"1.60943791243410037460075933322618763952560135426851772191264789147417898770765776463013387809317961" Base.@irrational ln³╱₂ 0.4054651081081644 big"0.40546510810816438197801311546434913657199042346249419761401432414410067124891425126775242781731340" Base.@irrational ln⁵╱₂ 0.9162907318741551 big"0.91629073187415506518352721176801107145010121990826246779196788198078536573796304902427055109676092" Base.@irrational ζ3 1.2020569031595942 big"1.20205690315959428539973816151144999076498629234049888179227155534183820578631309018645587360933525814619915" const 𝒾 = im # When defining @irrationals, if the third argument is a symbol, it is expected to name an # existing constant compiled into MPFR, with prefix `mpfr_const_`, which is a very limited # set. All MPFR constants except `log2` already exist in `Base.MathConstants`. Otherwise, # that third argument should be a literal BigFloat; it cannot be a variable name. @doc raw""" γₑ [Euler's constant](https://en.wikipedia.org/wiki/Euler%27s_constant) (also known as the Euler–Mascheroni constant) is defined as the limit as ``n \to \infty`` of the difference between the ``n``th partial sum of the harmonic series and ``\log(n)``. This is OEIS sequence [A001620](https://oeis.org/A001620). ```julia-repl julia> PostNewtonian.γₑ γₑ = 0.5772156649015... julia> n=10_000_000; sum(1 ./ (1:n))-log(n) 0.5772157149015307 ``` """ γₑ """ ζ3 apery [Apéry's constant](https://en.wikipedia.org/wiki/Ap%C3%A9ry%27s_constant) is defined as ``ζ(3)``, where ``ζ`` is the Riemann zeta function. This is OEIS sequence [A002117](https://oeis.org/A002117). ```julia-repl julia> PostNewtonian.apery ζ3 = 1.2020569031595... julia> PostNewtonian.ζ3 ζ3 = 1.2020569031595... julia> sum((1:10_000_000).^-3) 1.2020569031595896 ``` """ ζ3 const apery = ζ3 """ ln2 log2 The natural logarithm of 2. This is OEIS sequence [A002162](https://oeis.org/A002162). ```julia-repl julia> PostNewtonian.ln2 ln2 = 0.6931471805599... julia> exp(PostNewtonian.ln2) 2.0 julia> exp(big(PostNewtonian.ln2)) 2.0 ``` """ ln2 const log2 = ln2 """ ln3 log3 The natural logarithm of 3. This is OEIS sequence [A002391](https://oeis.org/A002391). ```julia-repl julia> PostNewtonian.ln3 ln3 = 1.0986122886681... julia> exp(PostNewtonian.ln3) 3.0000000000000004 julia> exp(big(PostNewtonian.ln3)) 3.0 ``` """ ln3 const log3 = ln3 """ ln5 log5 The natural logarithm of 5. This is OEIS sequence [A016628](https://oeis.org/A016628). ```julia-repl julia> PostNewtonian.ln5 ln5 = 1.6094379124341... julia> exp(PostNewtonian.ln5) 4.999999999999999 julia> exp(big(PostNewtonian.ln5)) 5.0 ``` """ ln5 const log5 = ln5 """ ln³╱₂ log³╱₂ log3halves The natural logarithm of 3//2. This is OEIS sequence [A016578](https://oeis.org/A016578). ```julia-repl julia> PostNewtonian.ln³╱₂ ln³╱₂ = 0.4054651081081... julia> exp(PostNewtonian.ln³╱₂) 1.5 julia> exp(big(PostNewtonian.ln³╱₂)) 1.5 ``` """ ln³╱₂ const log³╱₂ = ln³╱₂ const log3halves = ln³╱₂ """ ln⁵╱₂ log⁵╱₂ log5halves The natural logarithm of 5//2. This is OEIS sequence [A016579](https://oeis.org/A016579). ```julia-repl julia> PostNewtonian.ln⁵╱₂ ln⁵╱₂ = 0.9162907318741... julia> exp(PostNewtonian.ln⁵╱₂) 2.5 julia> exp(big(PostNewtonian.ln⁵╱₂)) 2.5 ``` """ ln⁵╱₂ const log⁵╱₂ = ln⁵╱₂ const log5halves = ln⁵╱₂ end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
2060
""" value(x) Return `x` or the value wrapped by the `Dual` number `x` """ value(x) = hasproperty(x, :value) ? getproperty(x, :value) : x """ find_symbols_of_type(mod, T) Given a module `mod` (not just its name, but the actual imported module), find all objects inside that module that are instances of the given type `T`. The returned quantity is a vector of `Symbol`s. """ function find_symbols_of_type(mod, T) return filter(n -> getproperty(mod, n) isa T, names(mod)) end """ iscall(x, symbols) Return `true` if the `Expr` `x` is a call to any element of `symbols`. """ iscall(x, symbols) = MacroTools.isexpr(x, :call) && x.args[1] ∈ symbols """ isadd(x) Return `true` if the `Expr` `x` is a call to `(+)` or `:+`. """ isadd(x) = iscall(x, ((+), :+)) """ ismul(x) Return `true` if the `Expr` `x` is a call to `(*)` or `:*`. """ ismul(x) = iscall(x, ((*), :*)) """ flatten_binary!(expr, symbols) Flatten nested binary operations — that is, apply associativity repeatedly. """ function flatten_binary!(expr, symbols) while iscall(expr, symbols) && any(x -> iscall(x, symbols), expr.args[2:end]) args = expr.args[2:end] i₊ = findfirst(x -> iscall(x, symbols), args) args′ = [first(symbols); args[1:(i₊ - 1)]; args[i₊].args[2:end]; args[(i₊ + 1):end]] expr.args[:] = args′[1:length(expr.args)] append!(expr.args, args′[(1 + length(expr.args)):end]) end return expr end flatten_add!(expr) = flatten_binary!(expr, ((+), :+)) flatten_mul!(expr) = flatten_binary!(expr, ((*), :*)) """ apply_to_first_add!(expr, func) Apply `func` to the first sub-expression found in a "prewalk"-traversal of `expr` that satisfies [`isadd`](@ref). If `func` acts in place, so does this function. In either case, the expression should be returned. """ function apply_to_first_add!(expr, func) found_add = false MacroTools.prewalk(expr) do x if !found_add && isadd(x) found_add = true func(x) else x end end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
7739
""" termination_forwards(vₑ, [quiet]) Construct termination criteria of solving PN evolution forwards in time These criteria include checking that the masses are positive and the dimensionless spins are less than 1, as well as ensuring that the evolution will terminate at `vₑ`. The optional `quiet` argument will silence informational messages about reaching the target value of `vₑ` if set to `true`, but warnings will still be issued when terminating for other reasons. """ function termination_forwards(vₑ, quiet=false) # Triggers the `continuous_terminator!` whenever one of these conditions crosses 0. # More precisely, the integrator performs a root find to finish precisely # when one of these conditions crosses 0. function conditions(out, state, t, integrator) out[1] = state[M₁index] # Terminate if M₁ ≤ 0 out[2] = state[M₂index] # Terminate if M₂ ≤ 0 out[3] = 1 - sum(x -> x^2, @view state[χ⃗₁indices]) # Terminate if χ₁ > 1 out[4] = 1 - sum(x -> x^2, @view state[χ⃗₂indices]) # Terminate if χ₂ > 1 return out[5] = vₑ - state[vindex] # Terminate at v = vₑ end function terminator!(integrator, event_index) if event_index == 1 @warn "Terminating forwards evolution because M₁ has become non-positive. This is unusual." elseif event_index == 2 @warn "Terminating forwards evolution because M₂ has become non-positive. This is unusual." elseif event_index == 3 @warn "Terminating forwards evolution because χ₁>1. Suggests early breakdown of PN." elseif event_index == 4 @warn "Terminating forwards evolution because χ₂>1. Suggests early breakdown of PN." elseif event_index == 5 quiet || @info ( "Terminating forwards evolution because the PN parameter 𝑣 " * "has reached 𝑣ₑ=$(value(vₑ)). This is ideal." ) end return terminate!(integrator) end return VectorContinuousCallback( conditions, terminator!, 5; # We have 5 criteria above save_positions=(false, false), # Only save before the termination, not after ) end """ termination_backwards(v₁, [quiet]) Construct termination criteria of solving PN evolution backwards in time These criteria include checking that the masses are positive and the dimensionless spins are less than 1, as well as ensuring that the evolution will terminate at `v₁`. The optional `quiet` argument will silence informational messages about reaching the target value of `v₁` if set to `true`, but warnings will still be issued when terminating for other reasons. """ function termination_backwards(v₁, quiet=false) function terminators_backwards(out, state, t, integrator) out[1] = state[M₁index] # Terminate if M₁≤0 out[2] = state[M₂index] # Terminate if M₂≤0 out[3] = 1 - sum(x -> x^2, @view state[χ⃗₁indices]) # Terminate if χ₁>1 out[4] = 1 - sum(x -> x^2, @view state[χ⃗₂indices]) # Terminate if χ₂>1 return out[5] = v₁ - state[vindex] # Terminate at v = v₁ end function terminator_backwards!(integrator, event_index) if event_index == 1 @warn "Terminating backwards evolution because M₁ has become non-positive. Suggests problem with PN." elseif event_index == 2 @warn "Terminating backwards evolution because M₂ has become non-positive. Suggests problem with PN." elseif event_index == 3 @warn "Terminating backwards evolution because χ₁>1. Suggests problem with PN." elseif event_index == 4 @warn "Terminating backwards evolution because χ₂>1. Suggests problem with PN." elseif event_index == 5 quiet || @info ( "Terminating backwards evolution because the PN parameter 𝑣 " * "has reached 𝑣₁=$(value(v₁)). This is ideal." ) end return terminate!(integrator) end return VectorContinuousCallback( terminators_backwards, terminator_backwards!, 5; # We have 5 criteria above save_positions=(false, false), # Only save before the termination, not after ) end """ dtmin_terminator(T, [quiet]) Construct termination criterion to terminate when `dt` drops below `√eps(T)`. Pass `force_dtmin=true` to `solve` when using this callback. Otherwise, the time-step size may decrease too much *within* a single time step, so that the integrator itself will quit before reaching this callback, leading to a less graceful exit. If this terminator is triggered while `v` is less than 0.35, a warning will always be issued; otherwise an `info` message will be issued only if the `quiet` flag is set to `false`. """ function dtmin_terminator(T, quiet=false) sqrtϵ::T = √eps(T) # Tricks for faster closures discrete_condition = let sqrtϵ = sqrtϵ (state, t, integrator) -> abs(integrator.dt) < sqrtϵ end function discrete_terminator!(integrator) v = integrator.u[vindex] message = ( "Terminating evolution because the time-step size has become very small:\n" * "|dt=$(integrator.dt)| < √ϵ=$(sqrtϵ)\n" * "This is only unexpected for 𝑣 ≲ 0.35; the current value is 𝑣=$v." ) if v < 7//20 @warn message elseif !quiet @info message end return terminate!(integrator) end return DiscreteCallback( discrete_condition, discrete_terminator!; save_positions=(false, false) ) end """ decreasing_v_terminator([quiet]) Construct termination criterion to stop integration when `v` is decreasing. Note that some systems may truly have decreasing `v` as physical solutions — including eccentric systems and possibly precessing systems. You may prefer to implement another solution, like detecting when `v` decreases below some threshold, or detecting when `v` is decreasing too quickly. See this function's source code for a simple If this terminator is triggered while `v` is less than 0.35, a warning will always be issued; otherwise an `info` message will be issued only if the `quiet` flag is set to `false`. """ function decreasing_v_terminator(quiet=false) function discrete_condition(state, t, integrator) return get_du(integrator)[vindex] < 0 # This translates to v̇<0 end function discrete_terminator!(integrator) v = integrator.u[vindex] ∂ₜv = get_du(integrator)[vindex] message = ( "Terminating forwards evolution because 𝑣 is decreasing:\n" * "This is only unusual if 𝑣 ≲ 0.35; the current value is 𝑣=$v\n" * "∂ₜ𝑣=$∂ₜv." ) if v < 7//20 @warn message elseif !quiet @info message end return terminate!(integrator) end return DiscreteCallback( discrete_condition, discrete_terminator!; save_positions=(false, false) ) end """ nonfinite_terminator() Construct termination criterion to stop integration when any NaN or Inf is found in the data after an integration step. If this terminator is triggered, a warning will always be issued. """ function nonfinite_terminator() function discrete_condition(state, t, integrator) return !(all(isfinite, state) && isfinite(t) && isfinite(integrator.dt)) end function discrete_terminator!(integrator) @warn "Terminating forwards evolution because a non-finite number was found" return terminate!(integrator) end return DiscreteCallback( discrete_condition, discrete_terminator!; save_positions=(false, false) ) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
16044
@doc raw""" x╱f_mod_xⁿ⁻¹(a) Compute the truncated power series expansion of ``x/f`` mod ``x^{n-1}``, where ``f`` is the power series expansion of a function ``f(x)`` ```math f(x) = a[1] x + a[2] x^2 + a[3] x^3 + \ldots + a[n-1] x^{n-1}. ``` Note, in particular that there is no constant term. The result is a power series expansion ```math h(x) = h[1] + h[2] x + h[3] x^2 + \ldots + h[n-1] x^{n-2}, ``` which notably *does* have a constant term. This function is essentially a helper function for the [`lagrange_inversion`](@ref) function. """ function x╱f_mod_xⁿ⁻¹(a::NTuple{N,T}) where {N,T} b = zeros(MVector{N,typeof(inv(a[1]))}) b[1] = inv(a[1]) for i ∈ 2:N b[i] = -b[1] * sum((a[j] * b[i - j + 1] for j ∈ 2:i); init=zero(eltype(b))) end return Tuple(b) end @testitem "x╱f_mod_xⁿ⁻¹" begin using PostNewtonian: x╱f_mod_xⁿ⁻¹ # We'll compare to exact values computed by SymPy for a few small values of `n`. test_x╱f_mod_xⁿ⁻¹(a::NTuple{1}) = (1 / a[1],) test_x╱f_mod_xⁿ⁻¹(a::NTuple{2}) = (1 / a[1], -a[2] / a[1]^2) test_x╱f_mod_xⁿ⁻¹(a::NTuple{3}) = (1 / a[1], -a[2] / a[1]^2, (-a[1] * a[3] + a[2]^2) / a[1]^3) test_x╱f_mod_xⁿ⁻¹(a::NTuple{4}) = ( 1 / a[1], -a[2] / a[1]^2, (-a[1] * a[3] + a[2]^2) / a[1]^3, (-a[1]^2 * a[4] + 2 * a[1] * a[2] * a[3] - a[2]^3) / a[1]^4, ) test_x╱f_mod_xⁿ⁻¹(a::NTuple{5}) = ( 1 / a[1], -a[2] / a[1]^2, (-a[1] * a[3] + a[2]^2) / a[1]^3, (-a[1]^2 * a[4] + 2 * a[1] * a[2] * a[3] - a[2]^3) / a[1]^4, ( -a[1]^3 * a[5] + 2 * a[1]^2 * a[2] * a[4] + a[1]^2 * a[3]^2 - 3 * a[1] * a[2]^2 * a[3] + a[2]^4 ) / a[1]^5, ) test_x╱f_mod_xⁿ⁻¹(a::NTuple{6}) = ( 1 / a[1], -a[2] / a[1]^2, (-a[1] * a[3] + a[2]^2) / a[1]^3, (-a[1]^2 * a[4] + 2 * a[1] * a[2] * a[3] - a[2]^3) / a[1]^4, ( -a[1]^3 * a[5] + 2 * a[1]^2 * a[2] * a[4] + a[1]^2 * a[3]^2 - 3 * a[1] * a[2]^2 * a[3] + a[2]^4 ) / a[1]^5, ( -a[1]^4 * a[6] + 2 * a[1]^3 * a[2] * a[5] + 2 * a[1]^3 * a[3] * a[4] - 3 * a[1]^2 * a[2]^2 * a[4] - 3 * a[1]^2 * a[2] * a[3]^2 + 4 * a[1] * a[2]^3 * a[3] - a[2]^5 ) / a[1]^6, ) test_x╱f_mod_xⁿ⁻¹(a::NTuple{7}) = ( 1 / a[1], -a[2] / a[1]^2, (-a[1] * a[3] + a[2]^2) / a[1]^3, (-a[1]^2 * a[4] + 2 * a[1] * a[2] * a[3] - a[2]^3) / a[1]^4, ( -a[1]^3 * a[5] + 2 * a[1]^2 * a[2] * a[4] + a[1]^2 * a[3]^2 - 3 * a[1] * a[2]^2 * a[3] + a[2]^4 ) / a[1]^5, ( -a[1]^4 * a[6] + 2 * a[1]^3 * a[2] * a[5] + 2 * a[1]^3 * a[3] * a[4] - 3 * a[1]^2 * a[2]^2 * a[4] - 3 * a[1]^2 * a[2] * a[3]^2 + 4 * a[1] * a[2]^3 * a[3] - a[2]^5 ) / a[1]^6, ( -a[1]^5 * a[7] + 2 * a[1]^4 * a[2] * a[6] + 2 * a[1]^4 * a[3] * a[5] + a[1]^4 * a[4]^2 - 3 * a[1]^3 * a[2]^2 * a[5] - 6 * a[1]^3 * a[2] * a[3] * a[4] - a[1]^3 * a[3]^3 + 4 * a[1]^2 * a[2]^3 * a[4] + 6 * a[1]^2 * a[2]^2 * a[3]^2 - 5 * a[1] * a[2]^4 * a[3] + a[2]^6 ) / a[1]^7, ) for N ∈ 1:7 a = (3, 7, 11, 17, 29, 37, 53)[1:N] @test all(test_x╱f_mod_xⁿ⁻¹(a) .≈ x╱f_mod_xⁿ⁻¹(a)) end end @doc raw""" hⁱ✖h_mod_xⁿ⁻¹(h, i) Compute the truncated power series expansion of ``h^i`` mod ``x^{n-1}``, where ``h`` is the power series expansion of a function ``h(x)`` ```math h(x) = h[1] + h[2] x + h[3] x^2 + \ldots + h[n-1] x^{n-2}. ``` The result is a power series expansion ```math h^i(x) = h^i[1] + h^i[2] x + h^i[3] x^2 + \ldots + h^i[n-1] x^{n-2}. ``` This function is essentially a helper function for the [`lagrange_inversion`](@ref) function. """ function hⁱ✖h_mod_xⁿ⁻¹(hⁱ::NTuple{N,T}, h::NTuple{N,T}) where {N,T} hⁱ⁺¹ = zeros(MVector{N,T}) for i ∈ 1:N hⁱ⁺¹[i] = sum((hⁱ[j] * h[i - j + 1] for j ∈ 1:i)) end return Tuple(hⁱ⁺¹) end @testitem "hⁱ✖h_mod_xⁿ⁻¹" begin using PostNewtonian: hⁱ✖h_mod_xⁿ⁻¹ # We'll compare to exact values computed by SymPy for a few small values of `n` and `i` test_hⁱ_mod_xⁿ⁻¹(h::NTuple{1}, ::Val{1}) = (h[0 + 1],) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{1}, ::Val{2}) = (h[0 + 1]^2,) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{2}, ::Val{1}) = (h[0 + 1], h[1 + 1]) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{2}, ::Val{2}) = (h[0 + 1]^2, 2 * h[0 + 1] * h[1 + 1]) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{2}, ::Val{3}) = (h[0 + 1]^3, 3 * h[0 + 1]^2 * h[1 + 1]) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{3}, ::Val{1}) = (h[0 + 1], h[1 + 1], h[2 + 1]) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{3}, ::Val{2}) = (h[0 + 1]^2, 2 * h[0 + 1] * h[1 + 1], 2 * h[0 + 1] * h[2 + 1] + h[1 + 1]^2) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{3}, ::Val{3}) = ( h[0 + 1]^3, 3 * h[0 + 1]^2 * h[1 + 1], 3 * h[0 + 1]^2 * h[2 + 1] + 3 * h[0 + 1] * h[1 + 1]^2, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{3}, ::Val{4}) = ( h[0 + 1]^4, 4 * h[0 + 1]^3 * h[1 + 1], 4 * h[0 + 1]^3 * h[2 + 1] + 6 * h[0 + 1]^2 * h[1 + 1]^2, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{4}, ::Val{1}) = (h[0 + 1], h[1 + 1], h[2 + 1], h[3 + 1]) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{4}, ::Val{2}) = ( h[0 + 1]^2, 2 * h[0 + 1] * h[1 + 1], 2 * h[0 + 1] * h[2 + 1] + h[1 + 1]^2, 2 * h[0 + 1] * h[3 + 1] + 2 * h[1 + 1] * h[2 + 1], ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{4}, ::Val{3}) = ( h[0 + 1]^3, 3 * h[0 + 1]^2 * h[1 + 1], 3 * h[0 + 1]^2 * h[2 + 1] + 3 * h[0 + 1] * h[1 + 1]^2, 3 * h[0 + 1]^2 * h[3 + 1] + 6 * h[0 + 1] * h[1 + 1] * h[2 + 1] + h[1 + 1]^3, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{4}, ::Val{4}) = ( h[0 + 1]^4, 4 * h[0 + 1]^3 * h[1 + 1], 4 * h[0 + 1]^3 * h[2 + 1] + 6 * h[0 + 1]^2 * h[1 + 1]^2, 4 * h[0 + 1]^3 * h[3 + 1] + 12 * h[0 + 1]^2 * h[1 + 1] * h[2 + 1] + 4 * h[0 + 1] * h[1 + 1]^3, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{4}, ::Val{5}) = ( h[0 + 1]^5, 5 * h[0 + 1]^4 * h[1 + 1], 5 * h[0 + 1]^4 * h[2 + 1] + 10 * h[0 + 1]^3 * h[1 + 1]^2, 5 * h[0 + 1]^4 * h[3 + 1] + 20 * h[0 + 1]^3 * h[1 + 1] * h[2 + 1] + 10 * h[0 + 1]^2 * h[1 + 1]^3, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{5}, ::Val{1}) = (h[0 + 1], h[1 + 1], h[2 + 1], h[3 + 1], h[4 + 1]) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{5}, ::Val{2}) = ( h[0 + 1]^2, 2 * h[0 + 1] * h[1 + 1], 2 * h[0 + 1] * h[2 + 1] + h[1 + 1]^2, 2 * h[0 + 1] * h[3 + 1] + 2 * h[1 + 1] * h[2 + 1], 2 * h[0 + 1] * h[4 + 1] + 2 * h[1 + 1] * h[3 + 1] + h[2 + 1]^2, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{5}, ::Val{3}) = ( h[0 + 1]^3, 3 * h[0 + 1]^2 * h[1 + 1], 3 * h[0 + 1]^2 * h[2 + 1] + 3 * h[0 + 1] * h[1 + 1]^2, 3 * h[0 + 1]^2 * h[3 + 1] + 6 * h[0 + 1] * h[1 + 1] * h[2 + 1] + h[1 + 1]^3, 3 * h[0 + 1]^2 * h[4 + 1] + 6 * h[0 + 1] * h[1 + 1] * h[3 + 1] + 3 * h[0 + 1] * h[2 + 1]^2 + 3 * h[1 + 1]^2 * h[2 + 1], ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{5}, ::Val{4}) = ( h[0 + 1]^4, 4 * h[0 + 1]^3 * h[1 + 1], 4 * h[0 + 1]^3 * h[2 + 1] + 6 * h[0 + 1]^2 * h[1 + 1]^2, 4 * h[0 + 1]^3 * h[3 + 1] + 12 * h[0 + 1]^2 * h[1 + 1] * h[2 + 1] + 4 * h[0 + 1] * h[1 + 1]^3, 4 * h[0 + 1]^3 * h[4 + 1] + 12 * h[0 + 1]^2 * h[1 + 1] * h[3 + 1] + 6 * h[0 + 1]^2 * h[2 + 1]^2 + 12 * h[0 + 1] * h[1 + 1]^2 * h[2 + 1] + h[1 + 1]^4, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{5}, ::Val{5}) = ( h[0 + 1]^5, 5 * h[0 + 1]^4 * h[1 + 1], 5 * h[0 + 1]^4 * h[2 + 1] + 10 * h[0 + 1]^3 * h[1 + 1]^2, 5 * h[0 + 1]^4 * h[3 + 1] + 20 * h[0 + 1]^3 * h[1 + 1] * h[2 + 1] + 10 * h[0 + 1]^2 * h[1 + 1]^3, 5 * h[0 + 1]^4 * h[4 + 1] + 20 * h[0 + 1]^3 * h[1 + 1] * h[3 + 1] + 10 * h[0 + 1]^3 * h[2 + 1]^2 + 30 * h[0 + 1]^2 * h[1 + 1]^2 * h[2 + 1] + 5 * h[0 + 1] * h[1 + 1]^4, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{5}, ::Val{6}) = ( h[0 + 1]^6, 6 * h[0 + 1]^5 * h[1 + 1], 6 * h[0 + 1]^5 * h[2 + 1] + 15 * h[0 + 1]^4 * h[1 + 1]^2, 6 * h[0 + 1]^5 * h[3 + 1] + 30 * h[0 + 1]^4 * h[1 + 1] * h[2 + 1] + 20 * h[0 + 1]^3 * h[1 + 1]^3, 6 * h[0 + 1]^5 * h[4 + 1] + 30 * h[0 + 1]^4 * h[1 + 1] * h[3 + 1] + 15 * h[0 + 1]^4 * h[2 + 1]^2 + 60 * h[0 + 1]^3 * h[1 + 1]^2 * h[2 + 1] + 15 * h[0 + 1]^2 * h[1 + 1]^4, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{6}, ::Val{1}) = (h[0 + 1], h[1 + 1], h[2 + 1], h[3 + 1], h[4 + 1], h[5 + 1]) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{6}, ::Val{2}) = ( h[0 + 1]^2, 2 * h[0 + 1] * h[1 + 1], 2 * h[0 + 1] * h[2 + 1] + h[1 + 1]^2, 2 * h[0 + 1] * h[3 + 1] + 2 * h[1 + 1] * h[2 + 1], 2 * h[0 + 1] * h[4 + 1] + 2 * h[1 + 1] * h[3 + 1] + h[2 + 1]^2, 2 * h[0 + 1] * h[5 + 1] + 2 * h[1 + 1] * h[4 + 1] + 2 * h[2 + 1] * h[3 + 1], ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{6}, ::Val{3}) = ( h[0 + 1]^3, 3 * h[0 + 1]^2 * h[1 + 1], 3 * h[0 + 1]^2 * h[2 + 1] + 3 * h[0 + 1] * h[1 + 1]^2, 3 * h[0 + 1]^2 * h[3 + 1] + 6 * h[0 + 1] * h[1 + 1] * h[2 + 1] + h[1 + 1]^3, 3 * h[0 + 1]^2 * h[4 + 1] + 6 * h[0 + 1] * h[1 + 1] * h[3 + 1] + 3 * h[0 + 1] * h[2 + 1]^2 + 3 * h[1 + 1]^2 * h[2 + 1], 3 * h[0 + 1]^2 * h[5 + 1] + 6 * h[0 + 1] * h[1 + 1] * h[4 + 1] + 6 * h[0 + 1] * h[2 + 1] * h[3 + 1] + 3 * h[1 + 1]^2 * h[3 + 1] + 3 * h[1 + 1] * h[2 + 1]^2, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{6}, ::Val{4}) = ( h[0 + 1]^4, 4 * h[0 + 1]^3 * h[1 + 1], 4 * h[0 + 1]^3 * h[2 + 1] + 6 * h[0 + 1]^2 * h[1 + 1]^2, 4 * h[0 + 1]^3 * h[3 + 1] + 12 * h[0 + 1]^2 * h[1 + 1] * h[2 + 1] + 4 * h[0 + 1] * h[1 + 1]^3, 4 * h[0 + 1]^3 * h[4 + 1] + 12 * h[0 + 1]^2 * h[1 + 1] * h[3 + 1] + 6 * h[0 + 1]^2 * h[2 + 1]^2 + 12 * h[0 + 1] * h[1 + 1]^2 * h[2 + 1] + h[1 + 1]^4, 4 * h[0 + 1]^3 * h[5 + 1] + 12 * h[0 + 1]^2 * h[1 + 1] * h[4 + 1] + 12 * h[0 + 1]^2 * h[2 + 1] * h[3 + 1] + 12 * h[0 + 1] * h[1 + 1]^2 * h[3 + 1] + 12 * h[0 + 1] * h[1 + 1] * h[2 + 1]^2 + 4 * h[1 + 1]^3 * h[2 + 1], ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{6}, ::Val{5}) = ( h[0 + 1]^5, 5 * h[0 + 1]^4 * h[1 + 1], 5 * h[0 + 1]^4 * h[2 + 1] + 10 * h[0 + 1]^3 * h[1 + 1]^2, 5 * h[0 + 1]^4 * h[3 + 1] + 20 * h[0 + 1]^3 * h[1 + 1] * h[2 + 1] + 10 * h[0 + 1]^2 * h[1 + 1]^3, 5 * h[0 + 1]^4 * h[4 + 1] + 20 * h[0 + 1]^3 * h[1 + 1] * h[3 + 1] + 10 * h[0 + 1]^3 * h[2 + 1]^2 + 30 * h[0 + 1]^2 * h[1 + 1]^2 * h[2 + 1] + 5 * h[0 + 1] * h[1 + 1]^4, 5 * h[0 + 1]^4 * h[5 + 1] + 20 * h[0 + 1]^3 * h[1 + 1] * h[4 + 1] + 20 * h[0 + 1]^3 * h[2 + 1] * h[3 + 1] + 30 * h[0 + 1]^2 * h[1 + 1]^2 * h[3 + 1] + 30 * h[0 + 1]^2 * h[1 + 1] * h[2 + 1]^2 + 20 * h[0 + 1] * h[1 + 1]^3 * h[2 + 1] + h[1 + 1]^5, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{6}, ::Val{6}) = ( h[0 + 1]^6, 6 * h[0 + 1]^5 * h[1 + 1], 6 * h[0 + 1]^5 * h[2 + 1] + 15 * h[0 + 1]^4 * h[1 + 1]^2, 6 * h[0 + 1]^5 * h[3 + 1] + 30 * h[0 + 1]^4 * h[1 + 1] * h[2 + 1] + 20 * h[0 + 1]^3 * h[1 + 1]^3, 6 * h[0 + 1]^5 * h[4 + 1] + 30 * h[0 + 1]^4 * h[1 + 1] * h[3 + 1] + 15 * h[0 + 1]^4 * h[2 + 1]^2 + 60 * h[0 + 1]^3 * h[1 + 1]^2 * h[2 + 1] + 15 * h[0 + 1]^2 * h[1 + 1]^4, 6 * h[0 + 1]^5 * h[5 + 1] + 30 * h[0 + 1]^4 * h[1 + 1] * h[4 + 1] + 30 * h[0 + 1]^4 * h[2 + 1] * h[3 + 1] + 60 * h[0 + 1]^3 * h[1 + 1]^2 * h[3 + 1] + 60 * h[0 + 1]^3 * h[1 + 1] * h[2 + 1]^2 + 60 * h[0 + 1]^2 * h[1 + 1]^3 * h[2 + 1] + 6 * h[0 + 1] * h[1 + 1]^5, ) test_hⁱ_mod_xⁿ⁻¹(h::NTuple{6}, ::Val{7}) = ( h[0 + 1]^7, 7 * h[0 + 1]^6 * h[1 + 1], 7 * h[0 + 1]^6 * h[2 + 1] + 21 * h[0 + 1]^5 * h[1 + 1]^2, 7 * h[0 + 1]^6 * h[3 + 1] + 42 * h[0 + 1]^5 * h[1 + 1] * h[2 + 1] + 35 * h[0 + 1]^4 * h[1 + 1]^3, 7 * h[0 + 1]^6 * h[4 + 1] + 42 * h[0 + 1]^5 * h[1 + 1] * h[3 + 1] + 21 * h[0 + 1]^5 * h[2 + 1]^2 + 105 * h[0 + 1]^4 * h[1 + 1]^2 * h[2 + 1] + 35 * h[0 + 1]^3 * h[1 + 1]^4, 7 * h[0 + 1]^6 * h[5 + 1] + 42 * h[0 + 1]^5 * h[1 + 1] * h[4 + 1] + 42 * h[0 + 1]^5 * h[2 + 1] * h[3 + 1] + 105 * h[0 + 1]^4 * h[1 + 1]^2 * h[3 + 1] + 105 * h[0 + 1]^4 * h[1 + 1] * h[2 + 1]^2 + 140 * h[0 + 1]^3 * h[1 + 1]^3 * h[2 + 1] + 21 * h[0 + 1]^2 * h[1 + 1]^5, ) for N ∈ 1:6 h = (3, 7, 11, 17, 29, 37)[1:N] hⁱ⁻¹ = (1, 0, 0, 0, 0, 0)[1:N] for i ∈ 1:(N + 1) hⁱ = hⁱ✖h_mod_xⁿ⁻¹(hⁱ⁻¹, h) @test all(hⁱ .≈ test_hⁱ_mod_xⁿ⁻¹(h, Val(i))) hⁱ⁻¹ = hⁱ end end end @doc raw""" lagrange_inversion(a) Compute the *compositional* inverse (a.k.a. reversion) of the power series expansion ```math f(x) = a[1]*x + a[2]*x^2 + \ldots + a[n-1]*x^{n-1} ``` about 0, where `a` is an NTuple. Note, in particular, that there is no constant term. The result is a similar NTuple `b` allowing us to write ```math f^{-1}(y) = b[1]*y + b[2]*y^2 + \ldots + b[n-1]*y^{n-1}, ``` such that ``f^{-1}(f(x)) = f(f^{-1}(y)) = x`` mod ``x^n``. See [`truncated_series_inverse`](@ref) for the *multiplicative* inverse. When the constant coefficient ``a_0`` is nonzero, the result must be expanded about a different point, which is done by evaluating the output as ``f^{-1}(y-a_0)``. Similarly, if the original expansion is about a point ``x_0 ≠ 0``, the result must be shifted by adding ``x_0`` to the output. [Johansson (2015)](https://doi.org/10.1090/S0025-5718-2014-02857-3) summarizes this basic form of the algorithm nicely: > Our setting is the ring of truncated power series ``R[[x]]/\langle x^n \rangle`` over a > commutative coefficient ring ``R`` in which the integers ``1,...,n−1`` are cancellable > (i.e., nonzero and not zero divisors). [...] If ``f(x) = x/h(x)`` where ``h(0)`` is a > unit, then the compositional inverse or reversion ``f^{-1}(x)`` satisfying ``f(f^{-1}(x)) > = f^{-1}(f(x)) = x`` exists and its coefficients are given by > ```math > [x^k] f^{-1}(x) = \frac{1}{k} [x^{k-1}] h(x)^k. > ``` Note that Johansson also presents a pair of asymptotically faster algorithms for computing the compositional inverse. Because of the low orders of the power series expansions we typically work with, it is not clear if the improved scaling of those algorithms would actually be beneficial in practice, so we stick with the basic algorithm here — though they would not be too difficult to implement if needed. """ function lagrange_inversion(a::NTuple{N,T}) where {N,T} h = x╱f_mod_xⁿ⁻¹(a) f⁻¹ = zeros(MVector{N,typeof(h[end] / 2)}) hⁱ = h # Create storage for the loop for i ∈ eachindex(f⁻¹) f⁻¹[i] = hⁱ[i] / i # Note that hⁱ[i] is the coefficient of x^(i-1) in hⁱ(x) hⁱ = hⁱ✖h_mod_xⁿ⁻¹(hⁱ, h) # We set hⁱ to hⁱ⁺¹ for the next iteration end return Tuple(f⁻¹) end @testitem "lagrange_inversion" begin using PostNewtonian: lagrange_inversion using Random rng = Random.Xoshiro(123) for N ∈ 2:16 n = N + 1 a = Tuple(randn(rng, N)) b = lagrange_inversion(a) for x ∈ (1e-12, 1e-10, 1e-8, 1e-7, 1e-6, 1e-5, 8e-4, 4e-4, 2e-4, 1e-4) f = evalpoly(x, (zero(eltype(a)), a...)) g = evalpoly(f, (zero(eltype(b)), b...)) δ = abs(x - g) ϵ = max(n * eps(eltype(a)), 4n * x^n) # println() # @show n N x g x^n δ ϵ @test δ < ϵ end # println() end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
6656
@doc raw""" truncated_series_inverse(a) truncated_series_inverse!(b, a) Given the coefficients `a` of a series, find the coefficients `b` of the *multiplicative* inverse of that series, up to the order of the original series. That is, if ```math A \colonequals \sum_{i=0}^n a_{i-1} v^i, ``` then we return the coefficients `b` of the series ```math B \colonequals \sum_{i=0}^n b_{i-1} v^i ``` such that ```math A\, B = 1 + \mathcal{O}(v^{n+1}). ``` See [`lagrange_inversion`](@ref) for the *compositional* inverse (a.k.a. reversion), which returns the coefficients of ``f^{-1}`` such that ``f^{-1}(f(v)) = v + \mathcal{O}(v^{n+1})``. Note that this function returns the *coefficients* of the inverse, rather than its value. This is relevant for use in [`truncated_series_product`](@ref) and [`truncated_series_ratio`](@ref) — the latter of which just combines the former with this function. For example, suppose the input coefficients represent the series ```math A \colonequals \sum_{i=0}^n a_{i-1} v^i. ``` (Remember that Julia's indexing is 1-based, so we subtract 1 to get the index of the coefficient of ``v^i``.) Then we return the coefficients `b` of the series ```math B \colonequals \sum_{i=0}^n b_{i-1} v^i ``` such that ```math A\, B = 1 + \mathcal{O}(v^{n+1}). ``` !!! note This function requires that `a[1]` be nonzero. If you have a series that starts at a higher term — say, ``v^n`` for ``n>0`` — you should factor out the ``v^n``, and multiply the series resulting from this function by ``v^{-n}``. ## Explanation The inverse coefficients can be computed fairly easily by induction. Start by defining ```math b_0 = 1/a_0. ``` Now, assuming that we've computed all coefficients up to and including ``b_{i}``, we can compute ``b_{i+1}`` from the condition that the term proportional to ``v^{i+1}`` in the product of the series and its inverse must be zero. This gives ```math b_{i+1} = -b_0\sum_{j=1}^{i} a_j b_{i-j}. ``` """ function truncated_series_inverse(a::AbstractVector) b = similar(a) return truncated_series_inverse!(b, a) end function truncated_series_inverse(a::NTuple{N,T}) where {N,T} b = MVector{N,T}(undef) truncated_series_inverse!(b, SVector{N,T}(a)) return Tuple(b) end function truncated_series_inverse!(b, a) @assert length(b) == length(a) n = length(a) @inbounds @fastmath if n > 0 b[0 + 1] = inv(a[0 + 1]) end @inbounds @fastmath for i ∈ 0:(n - 2) b[i + 1 + 1] = -b[0 + 1] * sum((a[j + 1] * b[i + 1 - j + 1] for j ∈ 1:(i + 1)); init=zero(eltype(a))) end return b end @doc raw""" truncated_series_product(a, b, v) Evaluate the truncated product of the series `a` and `b`, which are expanded in powers of `v`. Note that this function returns the *value* of the summation, rather than its coefficients. Here we define the series in terms of the coefficients `a` and `b` as ```math A \colonequals \sum_{i=0}^n a_{i-1} v^i \qquad B \colonequals \sum_{i=0}^n b_{i-1} v^i, ``` and return the *value* of the product ``A\, B`` truncated at ``v^n``. Internally, the sums are performed using `evalpoly`. See also [`truncated_series_ratio`](@ref). """ function truncated_series_product(a, b, v) @assert length(a) == length(b) N = length(a) - 1 if N < 0 return zero(v) end ex = b[N + 1] * a[1] for n ∈ (N - 1):-1:0 ex = muladd(v, ex, b[n + 1] * evalpoly(v, @view a[1:((N - n) + 1)])) end return ex end function truncated_series_product(a::NTuple{N,T}, b, v) where {N,T} @assert length(a) == length(b) if N < 1 return zero(v) end ex = b[N] * a[1] for n ∈ (N - 2):-1:0 ex = muladd(v, ex, b[n + 1] * evalpoly(v, a[1:((N - n - 1) + 1)])) end return ex end @doc raw""" truncated_series_ratio(a, b, v) Evaluate the truncated ratio of the series `a` and `b`, which are expanded in powers of `v`. Note that this function returns the *value* of the summation, rather than its coefficients. Here we define the series in terms of the coefficients `a` and `b` as ```math A \colonequals \sum_{i=0}^n a_{i-1} v^i \qquad B \colonequals \sum_{i=0}^n b_{i-1} v^i, ``` and return the *value* of the ratio ``A / B`` truncated at ``v^n``. This function simply combines [`truncated_series_product`](@ref) and [`truncated_series_inverse`](@ref). """ function truncated_series_ratio(a, b, v) return truncated_series_product(a, truncated_series_inverse(b), v) end @doc raw""" truncated_series_ratio(a, b) Evaluate the truncated ratio of the series `a` and `b`, evaluated at expansion value 1. This is relevant when the expansion is not in the dynamic variable `v`, for example, but in powers of ``1/c`` as in post-Newtonian expansions. (That is, when the `v` dependence is already include in the input coefficients.) """ function truncated_series_ratio(a::NTuple{N1,T1}, b::NTuple{N2,T2}) where {N1,N2,T1,T2} N = max(N1, N2) T = promote_type(T1, T2) if N2 == 0 throw(DomainError("truncated_series_ratio(a,b): b must have at least one term")) elseif N1 == 0 return zero(T) end b⁻¹ = MVector{N,T}(undef) @inbounds @fastmath begin b⁻¹[0 + 1] = inv(b[0 + 1]) for i ∈ 0:(N2 - 2) b⁻¹[i + 1 + 1] = -b⁻¹[0 + 1] * sum((b[j + 1] * b⁻¹[i + 1 - j + 1] for j ∈ 1:(i + 1)); init=zero(T)) end for i ∈ (N2 - 1):(N - 2) b⁻¹[i + 1 + 1] = -b⁻¹[0 + 1] * sum((b[j + 1] * b⁻¹[i + 1 - j + 1] for j ∈ 1:(N2 - 1)); init=zero(T)) end a╱b = zero(T) for i1 ∈ 1:N1 a╱b += a[i1] * sum((b⁻¹[i2] for i2 ∈ 1:(N - i1 + 1)); init=zero(T)) end a╱b end end @testitem "truncated_series_ratio(a,b)" begin using Random using DoubleFloats import PostNewtonian: truncated_series_inverse, truncated_series_ratio Random.seed!(123) for T ∈ [Float32, Float64, Double64] for N ∈ 1:20 A = rand(T, N) A[1] = one(T) + rand(T) / 100 a = Tuple(A) x = rand(T) ϵ = sum(a) * N * eps(T) for N1 ∈ 1:N expected = sum(truncated_series_inverse(a)) unit = zeros(T, N1) unit[1] = one(T) @test truncated_series_ratio(Tuple(unit), a) ≈ expected rtol = ϵ end @test truncated_series_ratio(a, a) ≈ 1 rtol = ϵ @test truncated_series_ratio(a, x .* a) ≈ 1 / x rtol = ϵ @test truncated_series_ratio(x .* a, a) ≈ x rtol = ϵ end end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
1412
@testitem "Aqua quality assurance tests" begin using Aqua: Aqua Aqua.test_all( PostNewtonian; ambiguities=false, unbound_args=(broken=true,), #persistent_tasks=(broken=true,), ) end @testitem "ExplicitImports tests" begin using ExplicitImports: ExplicitImports @test ExplicitImports.check_no_implicit_imports(PostNewtonian) === nothing @test ExplicitImports.check_all_explicit_imports_via_owners(PostNewtonian) === nothing @test_broken ExplicitImports.check_all_explicit_imports_are_public(PostNewtonian) === nothing @test ExplicitImports.check_no_stale_explicit_imports( PostNewtonian; ignore=( :M, :R, :X₁, :X₂, :q, :δ, :μ, :ν, :χ⃗₁, :χ⃗₂, :ℳ, :ln, :ln2, :ln3, :ln5, :order_index, :γₑ, :ζ3, :PNExpansionParameter, :type_converter, ), ) === nothing @test ExplicitImports.check_all_qualified_accesses_via_owners(PostNewtonian) === nothing @test_broken ExplicitImports.check_all_qualified_accesses_are_public(PostNewtonian) === nothing @test ExplicitImports.check_no_self_qualified_accesses( PostNewtonian; ignore=(:Ω, :v) ) === nothing end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
1624
#= # The most stringent test of the macros comes in `𝓔′`, because we have a typical PN expression in `𝓔` (which is already a reasonable test of the macros), then we evaluate it symbolically, differentiate that symbolically, convert it back to a piece of code, apply `@pn_expansion`, and then wrap it up in a function to which we apply `@pn_expression` again. So this test does all that a little more manually and compares the results at each order. # =# @testitem "binding_energy" begin using DoubleFloats: Double64 using Random: Xoshiro include("binding_energy_reference.jl") rng = Xoshiro(1234) for PNOrder ∈ (0//2):(1//2):(13//2) for T ∈ [Float32, Float64, Double64] v = T(1//10) for _ ∈ 1:100 numpn = rand(rng, NSNS; v, PNOrder) ϵ = 2eps(PostNewtonian.μ(numpn) * v^2) @test 𝓔(numpn) ≈ be(numpn, false) atol = ϵ rtol = 3eps(T) @test 𝓔′(numpn) ≈ be(numpn, true) atol = ϵ rtol = 3eps(T) end end end end @testitem "binding_energy_symbolics" begin using Symbolics using DoubleFloats: Double64 using Random: Xoshiro include("binding_energy_reference.jl") rng = Xoshiro(1234) for PNOrder ∈ [(0//2):(1//2):(13//2); 1_000//2] for T ∈ [Float32, Float64, Double64] v = T(1//10) for _ ∈ 1:100 numpn = rand(rng, NSNS; v, PNOrder) ϵ = 2eps(PostNewtonian.μ(numpn) * v^2) @test 𝓔′(numpn, Val(:Symbolics)) ≈ 𝓔′(numpn) atol = ϵ rtol = 3eps(T) end end end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
5828
""" This file creates a very explicit binding energy function for a Post-Newtonian system. It largely duplicates the contents of the package's actual `binding_energy ≡ 𝓔` function, but in a way that doesn't rely on macro fanciness or the PNTerm trickery. This is useful for testing the package's actual `binding_energy` function, as well as the validity of the macro and PNTerm stuff. Once the interface is finished, this could be done more elegantly with `@testsetup` from the `TestItems` package. """ using PostNewtonian: a₆ᶜ¹, a₆₅ᶜ¹, a₇ˡⁿ¹, a₇ᶜ¹ function be(pnsystem, deriv) let M₁ = PostNewtonian.M₁(pnsystem), M₂ = PostNewtonian.M₂(pnsystem), v = PostNewtonian.v(pnsystem), Λ₁ = PostNewtonian.Λ₁(pnsystem), Λ₂ = PostNewtonian.Λ₂(pnsystem), X₁ = PostNewtonian.X₁(pnsystem), X₂ = PostNewtonian.X₂(pnsystem), M = PostNewtonian.M(pnsystem), sₗ = PostNewtonian.sₗ(pnsystem), δ = PostNewtonian.δ(pnsystem), μ = PostNewtonian.μ(pnsystem), ν = PostNewtonian.ν(pnsystem), σₗ = PostNewtonian.σₗ(pnsystem), χ₁² = PostNewtonian.χ₁²(pnsystem), χ₁₂ = PostNewtonian.χ₁₂(pnsystem), χ₂² = PostNewtonian.χ₂²(pnsystem), χₐₗ = PostNewtonian.χₐₗ(pnsystem), χₛₗ = PostNewtonian.χₛₗ(pnsystem), κ₊ = PostNewtonian.κ₊(pnsystem), κ₋ = PostNewtonian.κ₋(pnsystem), λ₊ = PostNewtonian.λ₊(pnsystem), λ₋ = PostNewtonian.λ₋(pnsystem), π = PostNewtonian.type_converter(pnsystem, π), ln2 = PostNewtonian.type_converter(pnsystem, PostNewtonian.ln2), ln3 = PostNewtonian.type_converter(pnsystem, PostNewtonian.ln3), γₑ = PostNewtonian.type_converter(pnsystem, PostNewtonian.γₑ), ln = (x -> log(PostNewtonian.type_converter(pnsystem, x))), pn_order = PostNewtonian.pn_order(pnsystem) e = Dict() eˡⁿ = Dict() c = -1//2 * μ # NOTE: Included v^2 factor inside sum for easier differentiation e[0] = 1 e[2] = (-ν / 12 - 3//4) e[4] = (-ν^2 / 24 + 19ν / 8 - 27//8) e[6] = (-35ν^3 / 5184 - 155ν^2 / 96 + (34445//576 - 205π^2 / 96)ν - 675//64) e[8] = ( -3969//128 + 77ν^4 / 31104 + 301ν^3 / 1728 + (-498449//3456 + 3157π^2 / 576)ν^2 + (-123671//5760 + 1792ln2 / 15 + 9037π^2 / 1536 + 896γₑ / 15)ν ) eˡⁿ[8] = (448ν / 15) # Below are the incomplete terms from Eq. (74) of https://arxiv.org/abs/1312.2503v2 e[10] = ( -45927//512 + ν^5 / 512 + 55ν^4 / 512 + (-1353π^2 / 256 + 69423//512)ν^3 + (-21337π^2 / 1024 + 3a₆ᶜ¹ - 896ln2 / 5 - 448γₑ / 5 + 893429//2880)ν^2 + ( -228916843//115200 - 9976γₑ / 35 + 729ln3 / 7 - 23672ln2 / 35 + 126779π^2 / 512 )ν ) eˡⁿ[10] = (-4988ν / 35 - 656ν^2 / 5) e[11] = (10ν / 3 * (13696π / 525 + ν * a₆₅ᶜ¹)) e[12] = ( -264627//1024 + 2717ν^6 / 6718464 + 5159ν^5 / 248832 + (272855π^2 / 124416 - 20543435//373248)ν^4 + ( 1232γₑ / 27 + 6634243π^2 / 110592 - 11a₆ᶜ¹ / 2 - 71700787//51840 + 2464ln2 / 27 )ν^3 + ( 113176680983//14515200 + 18491π^4 / 2304 + 246004ln2 / 105 + 112772γₑ / 105 + a₆ᶜ¹ * 11//2 + a₇ˡⁿ¹ * 2//3 + a₇ᶜ¹ * 11//3 - 86017789π^2 / 110592 - 2673ln3 / 14 )ν^2 + ( -389727504721//43545600 + 74888ln2 / 243 - 7128ln3 / 7 - 30809603π^4 / 786432 - 3934568γₑ / 8505 + 9118627045π^2 / 5308416 )ν ) eˡⁿ[12] = (-1967284ν / 8505 + 24464ν^3 / 135 + (39754//105 + a₇ˡⁿ¹ * 11//3)ν^2) # Spin-orbit e[3] = (14sₗ / 3 + 2δ * σₗ) e[5] = ((11 - 61ν / 9) * sₗ + δ * (3 - 10ν / 3) * σₗ) e[7] = ((135//4 - 367ν / 4 + 29ν^2 / 12) * sₗ + δ * (27//4 - 39ν + 5ν^2 / 4) * σₗ) # Spin-squared e[4] += ( sₗ^2 * (-κ₊ - 2) + sₗ * σₗ * (-δ * κ₊ - 2δ + κ₋) + σₗ^2 * (δ * κ₋ / 2 - κ₊ / 2 + (κ₊ + 2)ν) ) e[6] += ( sₗ^2 * (-5δ * κ₋ / 3 - 25 * κ₊ / 6 + 50//9 + (5κ₊ / 6 + 5//3)ν) + sₗ * σₗ * (-5 * δ * κ₊ / 2 + 25 * δ / 3 + 5κ₋ / 2 + (5δ * κ₊ / 6 + 5δ / 3 + 35κ₋ / 6)ν) + σₗ^2 * ( 5δ * κ₋ / 4 - 5κ₊ / 4 + 5 + (5δ * κ₋ / 4 + 5κ₊ / 4 - 10)ν + (-5κ₊ / 6 - 5//3)ν^2 ) ) # Spin-cubed e[7] += ( sₗ^3 * (2κ₊ + 4λ₊ - 20) + sₗ^2 * σₗ * (2δ * κ₊ + 6δ * λ₊ - 32δ + 4κ₋ - 6λ₋) + sₗ * σₗ^2 * (5δ * κ₋ - 6δ * λ₋ - 5κ₊ + 6λ₊ - 12 + (-2κ₊ - 12λ₊ + 68)ν) + σₗ^3 * (-3δ * κ₊ + 2δ * λ₊ + 3κ₋ - 2λ₋ + (-2δ * λ₊ + 12δ - 6κ₋ + 6λ₋)ν) ) # NS tidal coupling e[10] += -9 * (Λ₁ * X₁^3 + Λ₂ * X₂^3)ν e[12] += -11//2 * ((3 + 2X₁ + 3X₁^2)Λ₁ * X₁^3 + (3 + 2X₂ + 3X₂^2)Λ₂ * X₂^3)ν if deriv c * v * ( sum(v^(k) * coeff * (k + 2) for (k, coeff) ∈ e if k ≤ 2pn_order; init=0) + sum( v^(k) * coeff * 2 * ((k + 2) * log(v) + 1) for (k, coeff) ∈ eˡⁿ if k ≤ 2pn_order; init=0, ) ) else c * v^2 * ( sum(v^(k) * coeff for (k, coeff) ∈ e if k ≤ 2pn_order; init=0) + sum(v^(k) * coeff * 2log(v) for (k, coeff) ∈ eˡⁿ if k ≤ 2pn_order; init=0) ) end end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
4210
@testitem "GWFrames" begin using Random using Logging using Quaternionic Random.seed!(1234) T = Float64 M₁ = T(5//8) M₂ = T(3//8) χ⃗₁ = normalize(randn(QuatVec{T})) * rand(T(0):T(1//1_000_000):T(1)) χ⃗₂ = normalize(randn(QuatVec{T})) * rand(T(0):T(1//1_000_000):T(1)) Ωᵢ = T(1//64) Ω₁ = Ωᵢ / 2 Ωₑ = 1 Rᵢ = exp(normalize(randn(QuatVec{T})) * rand(T(0):T(1//1_000_000):T(1//1_000))) Mₜₒₜ = M₁ + M₂ q = M₁ / M₂ vᵢ = PostNewtonian.v(; Ω=Ωᵢ, M=M₁ + M₂) v₁ = PostNewtonian.v(; Ω=Ω₁, M=M₁ + M₂) vₑ = min(PostNewtonian.v(; Ω=Ωₑ, M=M₁ + M₂), 1) uᵢ = [M₁; M₂; vec(χ⃗₁); vec(χ⃗₂); components(Rᵢ); vᵢ] Approximant = "TaylorT1" delta = PostNewtonian.δ(M₁, M₂) chi1_i = vec(χ⃗₁) chi2_i = vec(χ⃗₂) Omega_orb_i = Ωᵢ Omega_orb_0 = Ω₁ # Just make sure we don't get any errors with various signatures GWFrames.PNWaveform(Approximant, delta, chi1_i, chi2_i, Omega_orb_i) GWFrames.PNWaveform(Approximant, delta, chi1_i, chi2_i, Omega_orb_i, Omega_orb_0) GWFrames.PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i, Omega_orb_0, [components(Rᵢ)...] ) GWFrames.PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i, Omega_orb_0, [components(Rᵢ)...], 37, ) # Test to ensure we don't get info with default value of `quiet`, and we *do* when `quiet=false` PNOrder = 1.5 R_frame_i = [1.0] MinStepsPerOrbit = 32 PNWaveformModeOrder = 4.0 PNOrbitalEvolutionOrder = PNOrder @test_logs min_level = Logging.Info GWFrames.PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i, Omega_orb_0, R_frame_i, MinStepsPerOrbit, PNWaveformModeOrder, PNOrbitalEvolutionOrder, ) @test_logs min_level = Logging.Info GWFrames.PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i; Omega_orb_0, PNOrbitalEvolutionOrder, ) @test_logs min_level = Logging.Info GWFrames.PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i; Omega_orb_0, PNOrbitalEvolutionOrder, quiet=true, ) @test_logs (:info, r"Terminating forwards") (:info, r"Terminating backwards") GWFrames.PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i; Omega_orb_0, PNOrbitalEvolutionOrder, quiet=false, Omega_e=0.729, # This system fails by dt with v≈0.972, so just don't go that high ) # Make sure that `MinStepsPerOrbit` gives us what we want @testset verbose = true "MinStepsPerOrbit" begin for MinStepsPerOrbit ∈ [17, 31, 32, 33, 64] w = GWFrames.PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i; Omega_orb_0, MinStepsPerOrbit, ) for Φᵢ ∈ w.Phi[begin:(end - MinStepsPerOrbit)] NSteps = sum(@. Φᵢ ≤ w.Phi ≤ Φᵢ + 2π * (1 - 1 / 100MinStepsPerOrbit)) @test NSteps == MinStepsPerOrbit end end end # Make sure the `dt` gives us what we want @testset verbose = true "Uniform time steps" begin for dt ∈ T[1, 1//3, 1//10] w = GWFrames.PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i; Omega_orb_0, dt ) difft = diff(w.t) @test dt - minimum(difft) < length(w.t) * 10eps(dt) @test maximum(difft) - dt < length(w.t) * 10eps(dt) end end # Test initial conditions w = GWFrames.PNWaveform( Approximant, delta, chi1_i, chi2_i, Omega_orb_i; Omega_orb_0, dt=one(T) ) iᵢ = argmin(abs.(w.t)) @test w.M1[iᵢ] == M₁ # Because 0.625 happens to be exact in Float64 @test w.M2[iᵢ] == M₂ # Because 0.375 happens to be exact in Float64 @test w.chi1[iᵢ, :] == vec(χ⃗₁) @test w.chi2[iᵢ, :] == vec(χ⃗₂) @test w.frame[iᵢ, :] == components(Rotor(1)) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
769
@testitem "macros" begin using Quaternionic using Symbolics @eval PostNewtonian PostNewtonian.@pn_expression function macro_test(pnstate) return v * π√10 end for T ∈ [Float32, Float64, BigFloat] M₁, M₂, χ⃗₁, χ⃗₂, R, v = T(1), T(1), QuatVec(T(0)), QuatVec(T(0)), Rotor(T(1)), T(1//17) pnstate = BBH(; M₁, M₂, χ⃗₁, χ⃗₂, R, v) @test PostNewtonian.macro_test(pnstate) == v * (T(π) * √T(10)) end symbolic_pnsystem = PostNewtonian.SymbolicPNSystem() @test isequal( PostNewtonian.macro_test(symbolic_pnsystem), PostNewtonian.v(symbolic_pnsystem) * Num(SymbolicUtils.Term(PostNewtonian.hold, [π])) * √Num(SymbolicUtils.Term(PostNewtonian.hold, [10])), ) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
3617
@testitem "Orbital evolution" begin using Random using Logging using Quaternionic import OrdinaryDiffEq: ReturnCode Random.seed!(1234) T = Float64 M₁ = T(5//8) M₂ = T(3//8) χ⃗₁ = normalize(randn(QuatVec{T})) * rand(T(0):T(1//1_000_000):T(1)) χ⃗₂ = normalize(randn(QuatVec{T})) * rand(T(0):T(1//1_000_000):T(1)) Ωᵢ = T(1//64) Ω₁ = Ωᵢ / 2 Ωₑ = 1 Rᵢ = exp(normalize(randn(QuatVec{T})) * rand(T(0):T(1//1_000_000):T(1//1_000))) Mₜₒₜ = M₁ + M₂ q = M₁ / M₂ vᵢ = PostNewtonian.v(; Ω=Ωᵢ, M=M₁ + M₂) v₁ = PostNewtonian.v(; Ω=Ω₁, M=M₁ + M₂) vₑ = min(PostNewtonian.v(; Ω=Ωₑ, M=M₁ + M₂), 1) uᵢ = [M₁; M₂; vec(χ⃗₁); vec(χ⃗₂); components(Rᵢ); vᵢ; zero(T)] forwards_termination = ( "Terminating forwards evolution because the PN parameter 𝑣 " * "has reached 𝑣ₑ=$(vₑ). This is ideal." ) backwards_termination = ( "Terminating backwards evolution because the PN parameter 𝑣 " * "has reached 𝑣₁=$(v₁). This is ideal." ) # Check that the input pnsystem doesn't change during evolution pnsystem₁ = BBH(; M₁, M₂, χ⃗₁, χ⃗₂, R=Rᵢ, v=vᵢ) pnsystem₂ = deepcopy(pnsystem₁) inspiral = orbital_evolution(pnsystem₂) @test pnsystem₁.state == inspiral.u[1] @test pnsystem₁.state == pnsystem₂.state # Check for termination info sol1 = @test_logs (:info, forwards_termination) orbital_evolution( M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ, Rᵢ=Rᵢ, quiet=false ) sol2 = @test_logs (:info, forwards_termination) (:info, backwards_termination) orbital_evolution( M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ, Ω₁=Ωᵢ / 2, Rᵢ=Rᵢ, quiet=false ) # Check endpoint values @test sol1.retcode == ReturnCode.Terminated @test sol1[:v, 1] == vᵢ @test sol1[:, 1] ≈ uᵢ @test sol1[:v, end] ≈ vₑ @test sol2.retcode == ReturnCode.Terminated @test sol2[:v, 1] ≈ v₁ iᵢ = argmin(abs.(sol2.t .- 0.0)) # Assuming uᵢ corresponds to t==0.0 @test sol2[:, iᵢ] ≈ uᵢ @test sol2[:v, end] ≈ vₑ # Check various forms of interpolation with the forwards/backwards solution t = LinRange(sol1.t[1], sol1.t[2], 11) @test sol1(t[3]; idxs=(:v)) == sol2(t[3]; idxs=(:v)) @test sol1(t; idxs=(:v)) == sol2(t; idxs=(:v)) @test sol1(t[3]; idxs=7:13) == sol2(t[3]; idxs=7:13) @test sol1(t; idxs=7:13) == sol2(t; idxs=7:13) # Check that we can integrate orbital phase just as well sol3 = @test_logs min_level = Logging.Info orbital_evolution( M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ, Ω₁=Ωᵢ / 2, Rᵢ=Rᵢ, quiet=true ) t₁, tₑ = extrema(sol3.t) t = sol2.t[t₁ .< sol2.t .< tₑ] @test sol2(t) ≈ sol3(t; idxs=1:length(sol3.u[1])) @test sol3(0.0; idxs=(:Φ)) ≈ 0.0 # Initial phase should be ≈0 @test minimum(diff(sol3[:Φ])) > 0 # Ensure that the phase is strictly increasing # Ensure that non-precessing systems don't precess Rᵢ = Rotor(one(T)) sol_np = orbital_evolution( M₁, M₂, QuatVec(0, 0, χ⃗₁.z), QuatVec(0, 0, χ⃗₂.z), Ωᵢ; Ω₁, Rᵢ, quiet=true ) for c ∈ [:χ⃗₁ˣ, :χ⃗₁ʸ, :χ⃗₂ˣ, :χ⃗₂ʸ, :Rˣ, :Rʸ] @test all(sol_np[c] .== 0) end # Test that non-precessing rotors evolve like orbital phase sincosΦ = cat(map(Φ -> [sincos(Φ / 2)...], sol_np[:Φ])...; dims=2) Rwz = sol_np[[PostNewtonian.Rᶻindex, PostNewtonian.Rʷindex], :] @test sincosΦ ≈ Rwz atol = √eps(T) rtol = √eps(T) # Just check that a few nice/random cases can be integrated orbital_evolution(superkick()) orbital_evolution(hangup_kick()) orbital_evolution(rand(BBH)) orbital_evolution(rand(BHNS)) orbital_evolution(rand(NSNS)) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
5080
@testitem "PNTerm algebra" begin using DoubleFloats using PostNewtonian: PNExpansion for T ∈ [Float64, Float16, Double64] pn = rand(BBH; v=T(1) / 5, PNOrder=9//2) c = PNExpansionParameter(pn) z = zero(T) x = T(6) / 5 y = T(17) / 5 w = T(28) / 5 v = T(27) / 13 # Test behavior of `c` as the basic PNTerm for (term, c⁻¹exponent, coeff) ∈ ( (c, -1, 1), (c^2, -2, 1), (x * c^2, -2, x), (c^2 * x, -2, x), (c^2 / x, -2, 1 / x), ((x * c)^2, -2, x^2), ((x * c^2) / c^4, 2, x), ((x * c^2) / c^-4, -6, x), ((x / c^2) / c^4, 6, x), ((x / c^2) * (y / c^4), 6, x * y), ) @test PostNewtonian.c⁻¹exp(term) == c⁻¹exponent @test term.coeff == coeff @test term.coeff isa eltype(pn) @test length(term) == 1 @test eltype(term) === T end # Test PNExpressions @test_throws ArgumentError PNExpansion((), 0) for (expr, expected) ∈ ( (w - (x - y / c), (w - x, y)), (w - (x / c - y), (w + y, -x)), (x - y / c, (x, -y)), (x / c - y, (-y, x)), (x / c^6 + y / c, (z, y, z, z, z, z, x)), (x / c^6 + y / c + w / c^10, (z, y, z, z, z, z, x, z, z, z)), (x / c^6 - y / c, (z, -y, z, z, z, z, x)), (x / c^6 - y / c - w, (-w, -y, z, z, z, z, x)), (x / c^6 - y / c - w / c^10, (z, -y, z, z, z, z, x, z, z, z)), (x / c^6 - (y / c - w), (w, -y, z, z, z, z, x)), (x / c^6 - (y / c - w / c^10), (z, -y, z, z, z, z, x, z, z, z)), (-(x / c^6) - y / c, (z, -y, z, z, z, z, -x)), (-(x / c^6) - y / c - w, (-w, -y, z, z, z, z, -x)), (-(x / c^6) - y / c - w / c^10, (z, -y, z, z, z, z, -x, z, z, z)), ((x * c^2) / c^4 + y / c, (z, y, x)), ((x * c^2) / c^4 + y / c + w, (w, y, x)), ((x * c^2) / c^9 + y / c + w, (w, y, z, z, z, z, z, x)), (w + (x * c^2) / c^4 + y / c, (w, y, x)), (w + (x * c^2) / c^9 + y / c, (w, y, z, z, z, z, z, x)), (w + ((x * c^2) / c^4 + y / c), (w, y, x)), (w + ((x * c^2) / c^9 + y / c), (w, y, z, z, z, z, z, x)), (((x * c^2) / c^4 + y / c + w) / c^3, (z, z, z, w, y, x)), (((x * c^2) / c^4 + y / c + w) / c^5, (z, z, z, z, z, w, y, x)), (((x * c^2) / c^7 + y / c + w) / c^5, (z, z, z, z, z, w, y, z, z, z)), (v * (((x * c^2) / c^4 + y / c + w) / c^3), v .* (z, z, z, w, y, x)), ((((x * c^2) / c^4 + y / c + w) / c^3) * v, v .* (z, z, z, w, y, x)), ((((x * c^2) / c^4 + y / c + w) / c^3) / v, (z, z, z, w, y, x) .* (1 / v)), ) @test expr.coeffs == expected @test pn_order(expr) == pn_order(pn) @test sum(expr) == sum(expected) @test eltype(expr) === T end # Can't make a PNExpression with positive exponents @test_throws ArgumentError x * c + y @test_throws ArgumentError x * c + y / c @test_throws ArgumentError x * c^2 + y @test_throws ArgumentError x * c^2 + y / c @test_throws ArgumentError y + x * c @test_throws ArgumentError y / c + x * c @test_throws ArgumentError y + x * c^2 @test_throws ArgumentError y / c + x * c^2 @test_throws ArgumentError x * c^2 + (y / c + z / c^2) end end @testitem "PNExpansion algebra" begin using Symbolics using PostNewtonian: PNExpansion for N1 ∈ 1:9 for N2 ∈ 1:9 for NMax ∈ max(N1, N2):(N1 + N2 + 3) @variables c⁻¹ x[1:N1] y[1:N2] z poly(e::PNExpansion) = sum(e[i] * c⁻¹^(i - 1) for i ∈ 1:length(e)) eˣ = PNExpansion(tuple(x...), NMax) eʸ = PNExpansion(tuple(y...), NMax) # Test sums polysum = simplify(poly(eˣ + eʸ); expand=true) sumpoly = simplify(poly(eˣ) + poly(eʸ); expand=true) Δ = simplify(polysum - sumpoly; expand=true) @test iszero(Δ) @test_throws ArgumentError eˣ + PNExpansion(tuple(z, x...), NMax + 1) @test_throws ArgumentError PNExpansion(tuple(z, x...), NMax + 1) + eˣ # Test products polyprod = simplify(poly(eˣ * eʸ); expand=true) prodpoly = simplify( substitute( simplify(poly(eˣ) * poly(eʸ); expand=true), Dict([c⁻¹^n => 0 for n ∈ NMax:(2NMax + 3)]), ); expand=true, ) Δ = simplify(polyprod - prodpoly; expand=true) @test iszero(Δ) @test_throws ArgumentError eˣ * PNExpansion(tuple(z, x...), NMax + 1) @test_throws ArgumentError PNExpansion(tuple(z, x...), NMax + 1) * eˣ end end end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
5444
@testitem "Reference tests" begin using Quaternionic using PostNewtonian using ReferenceTests using HDF5 using FileIO using Random function approx(reference, actual; atol=1e-8, rtol=1e-8) return_value = true for (k, v1) ∈ reference if haskey(actual, k) v2 = actual[k] if size(v1) ≠ size(v2) || !isapprox(v1, v2; atol=atol, rtol=rtol) @warn """ Mismatch for key "$k": $(k)_reference = $v1 ≉ $(k)_actual = $v2 """ return_value = false end else @warn """Key "$k" found in "reference" file but not in "actual".""" return_value = false end end for (k, v2) ∈ actual if !haskey(reference, k) @warn """Key "$k" found in "actual" file but not in "reference".""" return_value = false end end return return_value end function compare_v̇(file_name, args...; kwargs...) file_name = joinpath("reference_values", file_name) rng = Random.Xoshiro(1234) pnsystems = [rand(rng, BBH) for _ ∈ 1:1_000] # TaylorT1 is just the ratio of v̇_numerator to v̇_denominator, but we'll store # those separately in case it helps with debugging, so we won't store TaylorT1 # itself. We will store TaylorT4 and TaylorT5, though. @test_reference file_name Dict( "2PNOrder" => (@. Int(2pn_order(pnsystems))), "state" => reduce(hcat, getproperty.(pnsystems, :state)), "v̇_numerator" => PostNewtonian.v̇_numerator.(pnsystems), "v̇_denominator" => PostNewtonian.v̇_denominator.(pnsystems), "TaylorT4" => PostNewtonian.TaylorT4_v̇.(pnsystems), "TaylorT5" => PostNewtonian.TaylorT5_v̇.(pnsystems), ) by = (r, a) -> approx(r, a; atol=0, rtol=1e-15) end compare_v̇("vdot.h5") # These tests rely too heavily on ODE integration being consistent, which seems to be # highly architecture-dependent, so we disable them on CI. if get(ENV, "CI", "false") == "false" @info "We appear not to be on CI; running reference tests involving ODE integration." function compare_inspiral(file_name, args...; kwargs...) file_name = joinpath("reference_values", file_name) inspiral = orbital_evolution(args...; kwargs...) pnsystem = try inspiral.prob.p catch inspiral.p end @test_reference file_name Dict( "2PNOrder" => Int(2pn_order(pnsystem)), "state" => pnsystem.state, "t" => inspiral.t, "u" => reduce(hcat, inspiral.u), ) by = approx end M₁ = 0.8 M₂ = 0.2 χ⃗₁ = QuatVec(0.1, 0.2, 0.3) χ⃗₂ = QuatVec(0.6, 0.4, 0.1) Ωᵢ = PostNewtonian.Ω(; v=0.3, M=M₁ + M₂) Ωₑ = PostNewtonian.Ω(; v=0.4, M=M₁ + M₂) inspiral = orbital_evolution(M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; Ωₑ) compare_inspiral("inspiral1.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ) compare_inspiral("inspiral2.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; Ω₁=Ωᵢ / 2) compare_inspiral("inspiral3.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; saveat=3.7) compare_inspiral( "inspiral4.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; saveat=inspiral.t[3:7:(end - 9)] ) compare_inspiral("inspiral5.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; Ωₑ) compare_inspiral("inspiral6.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; saves_per_orbit=3) compare_inspiral("inspiral7.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; PNOrder=1//2) compare_inspiral("inspiral8.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; PNOrder=3//2) compare_inspiral("inspiral9.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; PNOrder=5//2) compare_inspiral("inspiral10.h5", M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ; PNOrder=7//2) function compare_waveforms( file_name, inspiral, f; ℓₘᵢₙ=2, ℓₘₐₓ=8, PNOrder=typemax(Int) ) file_name = joinpath("reference_values", file_name) h = f(inspiral; ℓₘᵢₙ, ℓₘₐₓ, PNOrder) @test_reference file_name Dict("h" => h) by = approx end compare_waveforms("waveform1.h5", inspiral, coorbital_waveform) compare_waveforms("waveform2.h5", inspiral, coorbital_waveform; ℓₘᵢₙ=1, ℓₘₐₓ=4) compare_waveforms("waveform3.h5", inspiral, coorbital_waveform; PNOrder=1//2) compare_waveforms("waveform4.h5", inspiral, coorbital_waveform; PNOrder=3//2) compare_waveforms("waveform5.h5", inspiral, coorbital_waveform; PNOrder=5//2) compare_waveforms("waveform6.h5", inspiral, coorbital_waveform; PNOrder=7//2) compare_waveforms("waveform7.h5", inspiral, inertial_waveform) compare_waveforms("waveform8.h5", inspiral, inertial_waveform; ℓₘᵢₙ=1, ℓₘₐₓ=4) compare_waveforms("waveform9.h5", inspiral, inertial_waveform; PNOrder=1//2) compare_waveforms("waveform10.h5", inspiral, inertial_waveform; PNOrder=3//2) compare_waveforms("waveform11.h5", inspiral, inertial_waveform; PNOrder=5//2) compare_waveforms("waveform12.h5", inspiral, inertial_waveform; PNOrder=7//2) else @info "We appear to be on CI; skipping reference tests involving ODE integration." end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
769
""" OLD DIRECTIONS: Run this script (from this directory) as time julia --code-coverage=tracefile-%p.info --code-coverage=user --project=. ./runtests.jl Then, if you have `lcov` installed, you should also have `genhtml`, and you can run this genhtml tracefile-<your_PID>.info --output-directory coverage/ && open coverage/index.html to view the coverage locally as HTML. I find that this sometimes requires removing files that aren't really there from the .info file. It's a well-hidden fact that you can turn coverage on and off by adding certain comments around the code you don't want to measure: # COV_EXCL_START untested_code_that_wont_show_up_in_coverage() # COV_EXCL_STOP """ using TestItemRunner @run_package_tests verbose = true
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
1402
@testitem "truncated series monoid" begin using Symbolics using PostNewtonian: truncated_series_inverse, truncated_series_product, truncated_series_ratio @variables a[1:10] b[1:10] v @testset "$N" for N ∈ 0:6 cₐ = collect(a[1:(N + 1)]) cᵦ = collect(b[1:(N + 1)]) A = sum(c * v^(i - 1) for (i, c) ∈ enumerate(cₐ)) A⁻¹ = sum(c * v^(i - 1) for (i, c) ∈ enumerate(truncated_series_inverse(cₐ))) B = sum(c * v^(i - 1) for (i, c) ∈ enumerate(cᵦ)) function truncate_orders(expr) return substitute(expr, Dict(v^n => 0 for n ∈ (N + 1):(2length(a)))) end # Note that we have to engage in some chicanery with a[1] because Symbolics doesn't # deal well with fractions, and converts to Float64 too readily. full_product = simplify(a[1]^(N + 1) * A * A⁻¹; expand=true) truncated_product = simplify( truncate_orders(full_product) / a[1]^(N + 1); expand=true ) @test iszero(truncated_product - 1) full_product = simplify(A * B; expand=true) truncated_product = simplify(truncate_orders(full_product); expand=true) full_product = truncated_series_product(cₐ, cᵦ, v) @test iszero(simplify(truncated_product - full_product; expand=true)) @test iszero(simplify(truncated_series_ratio(cᵦ, cᵦ, v) - 1; expand=true)) end end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
code
1825
@testitem "Up-down instability" begin using Logging using Quaternionic # These parameters are taken more-or-less exactly from 064_CCE, # which is subject to this instability M₁ = 0.561844712025 M₂ = 0.43822158103 χ⃗₁ = QuatVec(-6.25908582173e-09, -2.21655853316e-08, 0.723734029888) χ⃗₂ = QuatVec(3.39881185355e-08, 5.92671870568e-08, -0.799746224993) R = Rotor(1.0) Ωᵢ = 2e-3 v = PostNewtonian.v(; Ω=Ωᵢ, M=M₁ + M₂) state = [M₁, M₂, vec(χ⃗₁)..., vec(χ⃗₂)..., components(R)..., v] Ω₊, Ω₋ = up_down_instability(state) # Test this general property, which should be true of *every* value returned for *any* # inputs to this function: @test 0 ≤ Ω₊ ≤ Ω₋ ≤ PostNewtonian.Ω(; v=1, M=M₁ + M₂) # Now, for the specific set of parameters given above, we should have @test Ω₊ ≈ 5.46e-4 rtol = 1e-2 @test Ω₋ ≈ PostNewtonian.Ω(; v=1, M=M₁ + M₂) ## Check on the test in `orbital_evolution` to make sure it works as expected # Ensure that even with `quiet=true`, we still get a warning for an unstable configuration udi_warning = r"\nThis system is likely to encounter the up-down instability in the" @test_logs (:warn, udi_warning) orbital_evolution( M₁, M₂, χ⃗₁, χ⃗₂, Ω(; v=v), quiet=true ) # Ensure that incorrect mass ordering gets handled properly @test_logs (:warn, udi_warning) orbital_evolution( M₂, M₁, χ⃗₂, χ⃗₁, Ω(; v=v), quiet=true ) # Test that it doesn't warn if χ⃗₁ is downward or χ⃗₂ is upward @test_logs min_level = Logging.Info orbital_evolution( M₁, M₂, QuatVec(χ⃗₁.x, χ⃗₁.y, -χ⃗₁.z / 2), χ⃗₂, Ω(; v=v), Ωₑ=2Ω(; v=v), quiet=true ) @test_logs min_level = Logging.Info orbital_evolution( M₁, M₂, χ⃗₁, QuatVec(χ⃗₂.x, χ⃗₂.y, -χ⃗₂.z), Ω(; v=v), quiet=true ) end
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
2124
# PostNewtonian [![Stable Documentation](https://img.shields.io/badge/docs-stable-blue.svg)](https://moble.github.io/PostNewtonian.jl/stable) [![In-development documentation](https://img.shields.io/badge/docs-dev-blue.svg)](https://moble.github.io/PostNewtonian.jl/dev) [![Coverage](https://codecov.io/gh/moble/PostNewtonian.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/moble/PostNewtonian.jl) [![Test workflow status](https://github.com/moble/PostNewtonian.jl/actions/workflows/Test.yml/badge.svg?branch=main)](https://github.com/moble/PostNewtonian.jl/actions/workflows/Test.yml?query=branch%3Amain) [![Docs workflow status](https://github.com/moble/PostNewtonian.jl/actions/workflows/Docs.yml/badge.svg?branch=main)](https://github.com/moble/PostNewtonian.jl/actions/workflows/Docs.yml?query=branch%3Amain) [![Lint workflow status](https://github.com/moble/PostNewtonian.jl/actions/workflows/Lint.yml/badge.svg?branch=main)](https://github.com/moble/PostNewtonian.jl/actions/workflows/Lint.yml?query=branch%3Amain) [![Aqua QA](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) [![ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://img.shields.io/badge/ColPrac-Contributor's%20Guide-blueviolet)](https://github.com/SciML/ColPrac) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.6847321.svg)](https://doi.org/10.5281/zenodo.6847321) This package computes orbital dynamics of and waveforms from binary black-hole systems, in the post-Newtonian approximation. See [the documentation](https://moble.github.io/PostNewtonian.jl/dev) for details. ## How to Cite If you use PostNewtonian.jl in your work, please cite using the reference given in [CITATION.cff](https://github.com/moble/PostNewtonian.jl/blob/main/CITATION.cff). A bibtex-formatted entry is available by clicking on "Cite this repository" at the top of [this repo's GitHub page](https://github.com/moble/PostNewtonian.jl).
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
955
<!-- Thanks for making a pull request to PostNewtonian.jl. We have added this PR template to help you help us. Make sure to read the contributing guidelines. See the comments below, fill the required fields, and check the items. --> ## Related issues <!-- We normally work with the following workflow (i) create issue; (ii) discussion if necessary; (iii) create PR. So, at least one of the following should be true:--> <!-- Option 1, this closes an existing issue. Fill the number below--> Closes # <!-- Option 2, this is a small fix that arguably won't need an issue. Uncomment below --> <!-- There is no related issue. --> ## Checklist <!-- mark true if NA --> <!-- leave PR as draft until all is checked --> - [ ] I am following the [contributing guidelines](https://github.com/moble/PostNewtonian.jl/blob/main/docs/src/contributing.md) - [ ] Tests are passing - [ ] Lint workflow is passing - [ ] Docs were updated and workflow is passing
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
4863
# Adding new PN terms or expressions !!! danger "Cite your sources!" Remember that it is *absolutely crucial* to record the source of any expressions in the relevant docstrings, including a link to the relevant paper. If the terms or expressions in a given function come from more than one source, use comments inside the code itself to clarify exactly which parts come from which source. The first step in actually adding new information is to decide where it fits in the hierarchy described in the ["Code structure" page](@ref Structure-of-this-package's-code). Most likely, you will want to add new terms to existing PN expressions, and possibly simple functions in [`PostNewtonian.DerivedVariables`](@ref "Derived variables"). Existing code should be a good guide on how to do this. However, it may appear as if some magic is happening in the various PN expressions, whereby variables like `M₁`, `χ⃗₂`, `ν`, `Λ`, etc., can be used without being defined. These are automatically computed by way of the [`@pn_expression`](@ref PostNewtonian.@pn_expression) macro. Also note that to correctly truncate a PN expansion at the desired order, the [`@pn_expansion`](@ref PostNewtonian.@pn_expansion) macro must be used. To make it easier to compare code to original sources, we also want to keep the code looking as similar as possible to equations as given in those sources, so try to keep variable names the same, and order things in the same ways as in the sources. (Don't worry about rewriting expressions to optimize evaluation; Julia will probably do a better job automatically anyway.) There are, however, a few important exceptions to this rule: 1. If you need any new variables to be computed from the ["fundamental variables"](@ref Fundamental-variables), you should define them in the [`PostNewtonian.DerivedVariables`](@ref Derived-variables) module. This will ensure that they can be automatically computed using the [`@pn_expression`](@ref PostNewtonian.@pn_expression). 2. It is crucial to explicitly include factors of ``1/c`` to the appropriate power *relative to the 0-pN order term* inside the `@pn_expansion` macro. For example, the first couple terms in the binding energy expansion look like ```julia 32/5G * ν^2 * v^10 / c^5 * @pn_expansion(1 + (v/c)^2 * (-1247//336 - 35ν/12)) ``` The `1/c^5` factor at the beginning is useful to remind us of the *absolute* order of this expression, but the `1/c^2` factor inside the `@pn_expansion` macro is crucial to ensure that the expression can be correctly truncated at the desired order. Thus, if you want to add a new 6-pN term to the binding energy, you could either manually code it inside the `@pn_expansion` expression, including its `1/c^12` factor, or you could create a separate function that should look like this: ```julia @pn_expression function binding_energy_6pn(pnsystem::PNSystem) 32/5G * ν^2 * v^12 / c^5 * @pn_expansion((v/c)^12 * 17//4) end ``` Note that we have kept the `1/c^5` factor out front, and the `1/c^12` factor inside the `@pn_expansion` macro. This tells the compiler that this is a 6-pN term, so if the user requests a lower pN order, the term should be ignored. 3. It should be possible to evaluate PN expressions using different precisions. To ensure this, enter fractions as `Irrational`s — e.g., `9//5` instead of `9/5`. The latter would be immediately converted to the inexact 64-bit float value `1.8`, which would poison other values. Note that if you are multiplying by something else that already has general float type, as in `9π/5`, you don't need to use `Irrational`; in this case, `9π` is evaluated first and achieves full precision, and is then divided by the exact integer 5, so that it retains full precision. Note that a helpful regex to search for this case is `(?<!(ζ|n|\^))[0-9]+/[0-9]`, which has relatively few false positives in this repo. 4. A slight caveat to the above is that an expression like `3λ/2` could *still* be converted to `Float64` if `λ` is defined at compile time to be `0`. For type-stability reasons, Julia will always treat `0/2` just like it would treat `7/2`, which is converted to `Float64`. Thus, it is probably safest to write expressions like `3//2 * λ`. 5. If you happen to use any other math functions, similarly ensure that their arguments are converted appropriately to retain precision. For unary functions, this can be done automatically by including the function name in the `unary_funcs` list used by [`@pn_expression`](@ref PostNewtonian.@pn_expression).
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
1338
# [Contributing guidelines](@id contributing) First of all, thanks for the interest! We welcome all kinds of contribution, including, but not limited to code, documentation, examples, configuration, issue creating, etc. Please be polite and respectful, and recognize that time spent on this project or helping you specifically is always voluntary. ## Bug reports and discussions If you think you found a bug, feel free to open an [issue](https://github.com/moble/PostNewtonian.jl/issues). Focused suggestions and requests can also be opened as issues. Before opening a pull request, start an issue or a discussion on the topic, please. Note that there is a dedicated page for advice on [adding new PN terms or expressions](adding_terms.md). ## Working on an issue If you found an issue that interests you, comment on that issue what your plans are. If the solution to the issue is clear, you can immediately create a pull request (see below). Otherwise, say what your proposed solution is and wait for a discussion around it. !!! tip Feel free to ping us after a few days if there are no responses. If your solution involves code (or something that requires running the package locally), check the [developer documentation](developer.md). Otherwise, you can use the GitHub interface directly to create your pull request.
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
5575
# [Developer documentation](@id dev_docs) !!! note "Contributing guidelines" If you haven't, please read the [Contributing guidelines](contributing.md) first. If you want to make contributions to this package that involves code, then this guide is for you. ## First time clone !!! tip "If you have writing rights" If you have writing rights, you don't have to fork. Instead, simply clone and skip ahead. Whenever **upstream** is mentioned, use **origin** instead. If this is the first time you work with this repository, follow the instructions below to clone the repository. 1. Fork this repo 2. Clone your repo (this will create a `git remote` called `origin`) 3. Add this repo as a remote: ```bash git remote add upstream https://github.com/moble/PostNewtonian.jl ``` This will ensure that you have two remotes in your git: `origin` and `upstream`. You will create branches and push to `origin`, and you will fetch and update your local `main` branch from `upstream`. ## Linting and formatting Install a plugin on your editor to use [EditorConfig](https://editorconfig.org). This will ensure that your editor is configured with important formatting settings. We use [https://pre-commit.com](https://pre-commit.com) to run the linters and formatters. In particular, the Julia code is formatted using [JuliaFormatter.jl](https://github.com/domluna/JuliaFormatter.jl), so please install it globally first: ```julia-repl julia> # Press ] pkg> activate pkg> add JuliaFormatter ``` To install `pre-commit`, use your standard python method — for example: ```bash python -m pip install pre-commit ``` With `pre-commit` installed, activate it as a pre-commit hook by running this command in the repository folder: ```bash pre-commit install ``` To run the linting and formatting manually, enter the command below: ```bash pre-commit run -a ``` **Now, you can only commit if all the pre-commit tests pass**. ## Testing As with most Julia packages, you can just open Julia in the repository folder, activate the environment, and run `test`: ```julia-repl julia> # press ] pkg> activate . pkg> test ``` ## Working on a new issue We try to keep a linear history in this repo, so it is important to keep your branches up-to-date. 1. Fetch from the remote and fast-forward your local main ```bash git fetch upstream git switch main git merge --ff-only upstream/main ``` 2. Branch from `main` to address the issue (see below for naming) ```bash git switch -c 42-add-answer-universe ``` 3. Push the new local branch to your personal remote repository ```bash git push -u origin 42-add-answer-universe ``` 4. Create a pull request to merge your remote branch into the org main. ### Branch naming - If there is an associated issue, add the issue number. - If there is no associated issue, **and the changes are small**, add a prefix such as "typo", "hotfix", "small-refactor", according to the type of update. - If the changes are not small and there is no associated issue, then create the issue first, so we can properly discuss the changes. - Use dash separated imperative wording related to the issue (e.g., `14-add-tests`, `15-fix-model`, `16-remove-obsolete-files`). ### Commit message - Use imperative or present tense, for instance: *Add feature* or *Fix bug*. - Have informative titles. - When necessary, add a body with details. - If there are breaking changes, add the information to the commit message. ### Before creating a pull request !!! tip "Atomic git commits" Try to create "atomic git commits" (recommended reading: [The Utopic Git History](https://blog.esciencecenter.nl/the-utopic-git-history-d44b81c09593)). - Make sure the tests pass. - Make sure the pre-commit tests pass. - Fetch any `main` updates from upstream and rebase your branch, if necessary: ```bash git fetch upstream git rebase upstream/main BRANCH_NAME ``` - Then you can open a pull request and work with the reviewer to address any issues. ## Building and viewing the documentation locally Following the latest suggestions, we recommend using `LiveServer` to build the documentation. Here is how you do it: 1. Run `julia --project=docs` to open Julia in the environment of the docs. 1. If this is the first time building the docs 1. Press `]` to enter `pkg` mode 1. Run `pkg> dev .` to use the development version of your package 1. Press backspace to leave `pkg` mode 1. Run `julia> using LiveServer` 1. Run `julia> servedocs()` ## Making a new release To create a new release, once the code is merged into `main`, just go to [the `register` action](https://github.com/moble/PostNewtonian.jl/actions/workflows/register.yml), click the gray "Run workflow" button, enter the version component you want to bump, and click the green "Run workflow" button. After that, you only need to wait and verify: - Wait for the bot to comment (should take < 1m) with a link to a RP to the registry - Follow the link and wait for a comment on the auto-merge - The comment should said all is well and auto-merge should occur shortly - After the merge happens, TagBot will trigger and create a new GitHub tag. Check on <https://github.com/moble/PostNewtonian.jl/releases> - After the release is create, a "docs" GitHub action will start for the tag. - After it passes, a deploy action will run. - After that runs, the [stable docs](https://moble.github.io/PostNewtonian.jl/stable) should be updated. Check them and look for the version number.
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
3706
```@meta CurrentModule = PostNewtonian ``` # PostNewtonian This package computes orbital dynamics of and waveforms from binary black-hole systems, in the [post-Newtonian approximation](https://en.wikipedia.org/wiki/Post-Newtonian_expansion). Currently, general precessing quasispherical systems are supported, but support for eccentric systems is still upcoming. ## Installation If you intend to use this package via Python, see [this page](@ref Using-this-package-from-Python) for installation instructions. It is recommended to use this package with Julia version 1.9 or greater, because of that version's improved pre-compilation caching. If you find it very slow the first time you use functions from this package in a new Julia session, that is most likely because Julia has to compile a lot of code. Version 1.9 does a better job of caching that compiled code, which speeds up your first-time usage. If you haven't installed Julia yet, you probably want to use [`juliaup`](https://github.com/JuliaLang/juliaup#readme) to do so. You'll probably also want to use a Julia ["project environment"](https://pkgdocs.julialang.org/v1/environments/) specifically for using this package. An easy way to do this is to create a directory, `cd` into that directory, and then run julia as ```bash julia --project=. ``` Then, installation of this package involves the usual commands: ```julia using Pkg Pkg.add("PostNewtonian") ``` ## Quick start An example with slightly more explanation is given under ["High-level interface"](@ref High-level-interface), and of course the rest of this documentation goes into far more detail. Here we see a simple example to start things off. !!! tip You don't have to use [cool Unicode names](https://docs.julialang.org/en/v1/manual/unicode-input/) for your variables if you don't want to. For example, `chi1` works just as well as `χ⃗₁`. Similarly, many functions in this package have Unicode names or take optional Unicode keyword arguments. But every such name or argument will also have an ASCII equivalent; see the documentation of those functions for the appropriate substitutions. ```@example 1 using PostNewtonian # Initial values of the masses, spins, and orbital angular frequency M₁ = 0.4 M₂ = 0.6 χ⃗₁ = [0.0, 0.5, 0.8] χ⃗₂ = [0.8, 0.0, 0.5] Ωᵢ = 0.01 # Integrate the orbital dynamics inspiral = orbital_evolution(M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ) # Interpolate for nicer plotting t′ = inspiral.t[end]-6_000 : 0.5 : inspiral.t[end] inspiral = inspiral(t′) # Compute the waveform in the inertial frame h = inertial_waveform(inspiral) nothing # hide ``` We can plot the result like this: ```@example 1 using Plots # Requires also installing `Plots` in your project plotlyjs() # hide default(size=(800,480), linewidth=2, leg=:top, legendfontsize=11) # hide default(extra_plot_kwargs = KW(:include_mathjax => "cdn")) # hide plot(inspiral.t, real.(h[1, :]), label=raw"$\Re\left\{h_{2,-2}\right\}$") plot!(inspiral.t, imag.(h[1, :]), label=raw"$\Im\left\{h_{2,-2}\right\}$") plot!(inspiral.t, abs.(h[1, :]), label=raw"$\left|h_{2,-2}\right|$", linewidth=3) plot!(inspiral.t, abs.(h[5, :]), label=raw"$\left|h_{2,2}\right|$") plot!(xlabel=raw"$\text{Time }(M)$", ylabel="Mode weights", ylim=(-0.45,0.45)) savefig("quickstart_waveform.html"); nothing # hide ``` ```@raw html <iframe src="quickstart_waveform.html" style="height:500px;width:100%;"></iframe> ``` We see various features to be expected of a precessing system like this, including slow modulations of the modes on the precession timescale, as well as faster oscillations in the amplitudes and asymmetry between the ``m=\pm 2`` modes on the orbital timescale.
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
993
# Assorted binaries For convenience, an assortment of constructors is provided for relevant classes of physical scenarios, as well as the ability to construct [random](@ref rand) systems across a broad range of reasonable physical parameters. In each case, the returned object is a `PNSystem`, which can be used as input to most functions in this package — most notably the `orbital_evolution` function. For example, to integrate the inspiral of a binary black-hole system in ["superkick"](@ref superkick) configuration, we could write ```julia inspiral = orbital_evolution(superkick()) ``` This implicitly provides the `M₁`, `M₂`, `χ⃗₁`, `χ⃗₂`, `Ωᵢ`, `Rᵢ`, and `PNOrder` arguments (along with `Λ₁` and/or `Λ₂` for `BHNS` or `NSNS` systems) to [`orbital_evolution`](@ref); other keyword arguments to that function can be provided after `superkick()`. ```@autodocs Modules = [PostNewtonian] Pages = ["assorted_binaries/examples.jl"] ``` ```@docs rand(pnclass::PNSystem; v, PNOrder) ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
1291
# Automatic differentiation While symbolic differentiation can be useful in many important scenarios, it is not very helpful for providing derivatives of general evolved waveforms, because waveforms require integration of ODEs. However, Julia is quite capable of automatically differentiating even through an ODE integration — both gradients and Hessians — with respect to any or all of the initial conditions. There are many automatic differentiation packages in Julia. Zygote will most likely be the best in the not-too-distant future, but at the time of writing, the simplest approach is to use [`ForwardDiff.jl`](https://github.com/JuliaDiff/ForwardDiff.jl). A simple wrapper function that takes only the arguments to be differentiated may be needed. The returned quantity will be a vector of waveforms corresponding to the derivative in the waveform at each instant with respect to the desired parameters. More broadly, it can also be helpful to differentiate a *function* of a waveform. For example, if we are trying to minimize the difference between a waveform and a PN waveform, we may have a cost function that takes (some or all of) the PN parameters integrates the ``L^2`` norm of the difference between them. This cost function should be easily differentiable as well.
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
2749
# GWFrames compatibility layer [`GWFrames`](https://github.com/moble/GWFrames) is an old python package that was too hard to upgrade to python 3, and therefore became impossible to maintain. Many of its capabilities have been superseded by the [`scri`](https://github.com/moble/scri) and [`sxs`](https://github.com/sxs-collaboration/sxs/) packages, but not the post-Newtonian capabilities. This package now supersedes the latter. For convenience, the `PostNewtonian.GWFrames` submodule provides a simple function to mimic the arguments used with the original `GWFrames` package to obtain a PN waveform (with a couple extra arguments). We won't bother to provide a return type that can fully mimic the object returned by the original `GWFrames` package, though it should be similar to the ones used by `scri` and `sxs`. This interface can be used directly from Julia, but is more likely to be wanted by python users. To borrow from the example in [the standard python interface documentation](@ref Testing-the-installation): ```julia # Any python imports you need go here import numpy as np import matplotlib.pyplot as plt # Start the Julia session from sxs.julia import GWFrames # Declare the essential parameters delta = 0.0 chi1 = [0.1, 0.2, 0.3] chi2 = [-0.2, 0.1, -0.3] Omega_i = 0.01 # Call into Julia to run some function w = GWFrames.PNWaveform("TaylorT1", delta, chi1, chi2, Omega_i) # Plot the magnitudes of all the modes as functions of time plt.semilogy(w.t, np.abs(w.data)) ``` This should produce precisely the same plot as the python example, but using the `GWFrames` interface. Note that the parameters given here are required, but optional parameters are the same as in the original `GWFrames` interface — which are listed in full in the docstring below. When called directly from Julia, the result will just be a `NamedTuple` with fields described in the docstring below. When called from python as shown above, the resulting `w` will be an [`sxs.WaveformModes` object](https://sxs.readthedocs.io/en/stable/api/waveforms/#waveformmodes-class), with all the usual methods and properties, as well as several fields relevant to post-Newtonian waveforms: - `M1` (array): The primary mass as a function of time. - `M2` (array): The secondary mass as a function of time. - `chi1` (array): The primary spin as a function of time. - `chi2` (array): The secondary spin as a function of time. - `frame` (array): The quaternionic frame as a function of time. - `v` (array): The orbital velocity as a function of time. - `orbital_phase` (array): The orbital phase as a function of time. ```@autodocs Modules = [PostNewtonian.GWFrames] Pages = ["gwframes.jl"] Order = [:module, :type, :constant, :function, :macro] ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
6241
# High-level interface The typical workflow for users of this package will involve two or three steps: 1. Integrate the orbital dynamics of a black-hole binary using the [`orbital_evolution`](@ref) function. 2. (Optional) If not specified in step 1, choose the time steps on which you want the waveform. 3. Compute the waveform as a function of the orbital dynamics using the [`inertial_waveform`](@ref) (or [`coorbital_waveform`](@ref)) function. Here, we'll work through an example, and provide some more details. ## 1. Integrate orbital dynamics First, we have to specify the initial masses, spins, and orbital angular frequency. Let's arbitrarily choose something close to a [hangup-kick](@ref hangup_kick) configuration. ```@example 1 using PostNewtonian # Initial values of the masses, spins, and orbital angular frequency M₁ = 0.6 M₂ = 0.4 χ⃗₁ = [0.7, 0.1, 0.7] χ⃗₂ = [-0.7, 0.1, 0.7] Ωᵢ = 0.01 inspiral = orbital_evolution(M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ) nothing; # hide ``` There are also numerous optional keyword arguments to `orbital_evolution`, controlling things like the range of frequencies over which to integrate (including possibly both forwards *and* backwards from the initial values), accuracy of the ODE integration, the PN order at which to compute the evolution equations, and so on. See that function's [documentation](@ref orbital_evolution) for details. The returned object named `inspiral` here is an [`ODESolution`](https://docs.sciml.ai/DiffEqDocs/stable/basics/solution/) with many features, like high-order interpolation (using dense output from the ODE integrator). The time steps at which the solution was saved are available as `inspiral.t`, and the evolved variables are available as `inspiral.u`, or by their names as in `inspiral[:v]` or `inspiral[:Φ]`. For example, we can plot the components of the spin of object 1 like this: ```@example 1 using Plots # Requires also installing `Plots` in your project plotlyjs() # hide default(size=(800,480), linewidth=2, leg=:top) # hide plot(inspiral.t, inspiral[:χ⃗₁ˣ], label=raw"$\vec{\chi}_1^x$") plot!(inspiral.t, inspiral[:χ⃗₁ʸ], label=raw"$\vec{\chi}_1^y$") plot!(inspiral.t, inspiral[:χ⃗₁ᶻ], label=raw"$\vec{\chi}_1^z$") plot!(xlabel="Time (𝑀)", ylabel="Dimensionless spin components") savefig("inspiral_spins.html"); nothing # hide ``` ```@raw html <!-- NOTE: ../ in src works on github, but not locally --> <iframe src="../inspiral_spins.html" style="height:500px;width:100%;"></iframe> ``` As expected, we see *significant* precession of the spin on long time scales, as well as smaller nutations on orbital time scales visible mostly at later times. The evolved variables, in order, are ```@example 1 join(stdout, PostNewtonian.pnsystem_symbols, ", ") # hide ``` They can be accessed by their symbols, like the spins above, or by their number in this list. To access the `i`th variable at time step `j`, use `sol[i, j]`. You can also use colons: `sol[i, :]` is a vector of the `i`th variable at all times, and `sol[:, j]` is a vector of all the data at time step `j`. For example, `inspiral[:χ⃗₁ˣ]` could also be written as `inspiral[3, :]`. By default, the output of `orbital_evolution` is just the time steps to which the adaptive ODE integrator happened to step. If you know that you want the solution on a set of uniform time steps separated by `dt` — such as when you need to FFT the waveform — you can pass the option `saveat=dt`. Or, if you somehow know the specific set of times `t` at which you want the solution, you can pass `saveat=t`. Finally, if you want the solution — say — 32 times per orbit, you can pass the option `saves_per_orbit=32`, which calls [`uniform_in_phase`](@ref) as needed. ## [2. (Optional) Choose time steps](@id sec_optional_choose_time_steps) If you did not pass the `saveat` or `saves_per_orbit` arguments to `orbital_evolution` (as described in the previous paragraph), the output will usually be on a fairly coarse set of times — possibly many times the orbital period for non-precessing systems. However, in this case the solution will come with "dense output", which lets us quickly and accurately interpolate the solution to a new set of times. This is important if you want the waveform to be sampled at the "local" [Nyquist rate](https://en.wikipedia.org/wiki/Nyquist_rate); anything less and the waveform will be distorted by [aliasing](https://en.wikipedia.org/wiki/Aliasing). For instance, suppose we want to plot the results every ``0.5M`` for the last ``5,000M`` of the data. We could define the new set of times as ```@example 1 t′ = inspiral.t[end]-5_000 : 0.5 : inspiral.t[end] nothing; # hide ``` and then interpolate to this new set of times as ```@example 1 inspiral = inspiral(t′) nothing # hide ``` We couldn't have achieved quite the same effect with the `saveat` argument mentioned above because in this case, we wanted to know the point at which we were ``5,000M`` before the end of the inspiral. In general, if you need the results of `orbital_evolution` before you can decide what you want `t′` to be, this is the approach you'll have to take. ## 3. Compute the waveform Usually, we will also want the actual waveform from this system. We can just call [`inertial_waveform`](@ref) (or [`coorbital_waveform`](@ref) for the waveform in a rotating frame in which the binary is stationary). ```@example 1 h = inertial_waveform(inspiral) nothing; # hide ``` Again, we can plot the result: ```@example 1 plot(inspiral.t, real.(h[1, :]), label=raw"$\Re\left\{h_{2,-2}\right\}$") plot!(inspiral.t, imag.(h[1, :]), label=raw"$\Im\left\{h_{2,-2}\right\}$") plot!(inspiral.t, abs.(h[1, :]), label=raw"$\left|h_{2,-2}\right|$", linewidth=3) plot!(xlabel="Time (𝑀)", ylabel="Mode weights", ylim=(-0.5,0.5)) savefig("waveform.html"); nothing # hide ``` ```@raw html <!-- NOTE: ../ in src works on github, but not locally --> <iframe src="../waveform.html" style="height:500px;width:100%;"></iframe> ``` We see oscillations in the *amplitude* of the ``h_{2,-2}`` mode on the orbital timescale, which is to be expected in a hangup-kick scenario as the system alternates between beaming power preferentially along the ``+z`` and ``-z`` directions.
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
8448
# Using this package from Python While not quite as natural as calling Python code from Julia, it is very easy to call Julia code from Python. The process is essentially the same as using any other Python package, other than installing Julia itself and any dependencies *within* Julia that you may need (both of which are much easier than similar tasks in Python). !!! warning "Be careful of using unicode in Python!" Every effort is made to ensure that *users* of this package can always use plain ASCII — even though this package uses Unicode *internally* and in many of the examples found in this documentation. For example, if keyword arguments are accepted as Unicode, ASCII equivalents are usually also accepted. Some function *names* are similarly in Unicode, but have ASCII equivalents. See the various functions' documentation for acceptable replacements. It can be dangerous to use Unicode in Python in particular. Python only accepts a small subset of Unicode — so that `M₁` for example is not valid input. And what it does accept is automatically ["NFKC normalized"](https://en.wikipedia.org/wiki/Unicode_equivalence#Normal_forms). For example, variable names `Mₐ`, `Ma`, and `Mᵃ` are all treated identically by Python. To illustrate this, consider the following python code: ```python >>> Mₐ = 1 >>> Mᵃ = 2 >>> Ma = 3 >>> print((Mₐ, Mᵃ, Ma)) (3, 3, 3) ``` We might have expected three different values `(1, 2, 3)` in the output, but Python never even sees the variable names as different strings; it interprets these expressions as setting, resetting, and resetting again the value of `Ma`. If you find an example where ASCII substitutions are not possible, please file a [bug report](https://github.com/moble/PostNewtonian.jl/issues/new). ## Installation ### 0. Optionally pre-install Julia If you'll want to use Julia from outside of Python, install Julia first with [the `juliaup` installer](https://github.com/JuliaLang/juliaup?tab=readme-ov-file#juliaup---julia-version-manager). ### 1. Install the `sxs` python package While not *strictly necessary*, the `sxs` python package is very useful for providing a general interface to waveforms, and will automatically install the PostNewtonian package and its dependencies (and even Julia, if necessary). If you use `conda`, just run something like[^1] ```bash conda install -c conda-forge sxs numba::numba numba::llvmlite ``` If you prefer `pip`, use ```bash python -m pip install sxs ``` !!! danger "Avoid segfaults on macOS" If using conda/mamba on macOS, you *must* install the correct versions of `numba` and `llvmlite`, or [you will get segfaults.](https://github.com/numba/numba/issues/7857#issuecomment-1082246028) Specifically, you *must* include the `numba::` prefix to select the correct anaconda channel, as shown in the command given above. A more permanent solution is to run the following commands: ``` conda config --set channel_priority strict conda config --add channels conda-forge --prepend channels numba ``` This will automatically choose the correct versions of numba and llvmlite for your system, without the need to explicitly use the `numba::` prefix ever again. ### 2. Install Julia and `PostNewtonian.jl` The following line will take a few minutes to install Julia (if necessary), then download and compile all the necessary Julia packages. ```bash python -c 'from sxs import julia' ``` ## Testing the installation !!! danger "Import this package first" When using this package from Python with any other non-standard libraries — like `scri` or `lal` — you should always import `sxs.julia` or one of its components *first* in your Python session. This is because those packages may use the same compiled libraries as this package, in the form of shared objects, like `libfftw3`. But because Python packaging is so desperately bad, the libraries that come with Python packages are often quite old and will interfere with the operation of this package. Loading this package first ensures that newer versions of the libraries are loaded, which will typically be backwards compatible. Start up a python session and run something like this: ```python # Any python imports you need go here import numpy as np import matplotlib.pyplot as plt # Start the Julia session from sxs.julia import PNWaveform # Declare the essential parameters M1 = 0.5 M2 = 0.5 chi1 = [0.1, 0.2, 0.3] chi2 = [-0.2, 0.1, -0.3] Omega_i = 0.01 # Call `sxs` wrapper for Julia functions w = PNWaveform(M1, M2, chi1, chi2, Omega_i) # Plot the magnitudes of all the modes as functions of time plt.semilogy(w.t, np.abs(w.data)) ``` The [`sxs.julia.PNWaveform` function](https://github.com/sxs-collaboration/sxs/blob/e6aa63695fdb1a2f97cfb54e04dbbd5453142cd3/sxs/julia/__init__.py#L17-L86) is a simple wrapper that calls [`orbital_evolution`](@ref) and [`inertial_waveform`](@ref), then wraps the result in an [`sxs.WaveformModes` object](https://sxs.readthedocs.io/en/stable/api/waveforms/#waveformmodes-class), with all the usual methods and properties, as well as several additional fields relevant to post-Newtonian waveforms: - `M1` (array): The primary mass as a function of time. - `M2` (array): The secondary mass as a function of time. - `chi1` (array): The primary spin as a function of time. - `chi2` (array): The secondary spin as a function of time. - `frame` (array): The quaternionic frame as a function of time. - `v` (array): The orbital velocity as a function of time. - `orbital_phase` (array): The orbital phase as a function of time. The input arguments for [`sxs.julia.PNWaveform`](https://github.com/sxs-collaboration/sxs/blob/e6aa63695fdb1a2f97cfb54e04dbbd5453142cd3/sxs/julia/__init__.py#L17-L86) are mostly the same as for [`orbital_evolution`](@ref), except that the keyword argument `inertial` will switch whether the returned waveform will be in the inertial frame (the default of `True`) or the coorbital frame (`False`), and the keyword arguments `ell_min`, `ell_max`, and `waveform_pn_order` will be intercepted and passed to [`inertial_waveform`](@ref) or [`coorbital_waveform`](@ref) correspondingly. ## Full Julia interface from Python In general, you can now call any function from the Julia `PostNewtonian` package by running ```python from sxs.julia import PostNewtonian ``` and then calling the function just as you would if you had run `import PostNewtonian` in Julia. That is, any of the functions given in the rest of this documentation should be available in Python, just as they would be in Julia. (Again, note that all function names and arguments should have ASCII equivalents to use from Python.) You can also evaluate *arbitrary Julia code* by prefixing `PostNewtonian.` to the command, or as a fallback write Julia code as a string and pass it to `PostNewtonian.seval("<Julia code goes here>")`. Simple examples include ```python >>> PostNewtonian.println("Hello from Julia!") Hello from Julia! >>> x = PostNewtonian.seval("1+2") >>> x 3 ``` See the [documentation for `juliacall` here](https://github.com/cjdoris/PythonCall.jl#readme) for more details. Whenever they correspond naturally to built-in Python types — like `int`, `float`, `str`, etc. — the returned objects will be converted to such Python objects. Otherwise, the returned objects will be wrappers around Julia `Vector`s, `Matrix`es, or more generally shaped `Array`s. Usually, you will be able to pass these objects directly to Python functions. If you really need a `numpy` array, you can use the `to_numpy()` method that the wrappers will support. Of course, it is *much* simpler to call Python code from Julia, so if you find yourself using a lot of Julia code, you may want to consider flipping your approach. [^1]: As general advice, you should run `conda install -y mamba -n base -c conda-forge`, and then just use the command `mamba` wherever you would have used `conda`; `mamba` is a complete drop-in replacement, but is much faster because it's written in C instead of python. For example, `mamba create -n julia_pn python numpy matplotlib` will typically run faster than the command given here. This becomes a huge advantage when the env has lots of dependencies.
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
2731
# Symbolic manipulations It can be useful to evaluate the post-Newtonian expressions with symbolic arguments. To do so, we just need to create a `PNSystem` containing a `state` vector of symbols. All of the variables defined in [`PostNewtonian.FundamentalVariables`](@ref "Fundamental variables") and [`PostNewtonian.DerivedVariables`](@ref "Derived variables") have methods defined automatically to generate symbols instead of values when called with a symbolic `PNSystem`. In turn, any function modified by the [`@pn_expression`](@ref PostNewtonian.@pn_expression) macro should also be able to return a symbolic result, including all functions described in the "[PN expressions](@ref)" section. For convenience, an extension to this package also provides [`SymbolicPNSystem`](@ref PostNewtonian.SymbolicPNSystem), which produces a `PNSystem` with all the fundamental variables stored as [`Symbolics.jl`](https://symbolics.juliasymbolics.org/) variables — as long as the `Symbolics` package is also loaded. We can extract the symbols as usual: ```julia julia> using PostNewtonian, Symbolics julia> symbolic_pnsystem = PostNewtonian.SymbolicPNSystem() PostNewtonian.SymbolicPNSystem{Vector{Num}, 9223372036854775805//2, Num}(Num[M₁, M₂, χ⃗₁ˣ, χ⃗₁ʸ, χ⃗₁ᶻ, χ⃗₂ˣ, χ⃗₂ʸ, χ⃗₂ᶻ, Rʷ, Rˣ, Rʸ, Rᶻ, v, Φ], Λ₁, Λ₂) julia> v = PostNewtonian.v(symbolic_pnsystem) v ``` More generally, we can obtain a symbolic expression for the [binding energy](@ref PostNewtonian.𝓔) as ```julia julia> 𝓔(symbolic_pnsystem) (-1//2)*(1 + (v^2)*(-(3//4) - (1//12)*ν) + (v^3)*((14//3)*sₗ + 2δ*σₗ) + [...] ``` In fact, this is how the [derivative-of-binding-energy function `𝓔′`](@ref PostNewtonian.𝓔′) used to be constructed, essentially as ```julia julia> ∂ᵥ = Differential(v); julia> expand_derivatives(∂ᵥ(𝓔(symbolic_pnsystem))) -(1 + (v^2)*(-(3//4) - (1//12)*ν) + (v^3)*((14//3)*sₗ + 2δ*σₗ) + [...] ``` Note that special care is taken to preserve the types of `Irrational`s and the arguments of certain functions like `sqrt` and `log`. Ordinarily, Julia will evaluate these as `Float64`s; to ensure that they remain symbolic, we have to wrap them in a function that `Symbolics.jl` will know not to bother expanding: [`PostNewtonian.hold`](@ref). While manipulating these expressions symbolically, you'll probably want to leave those `hold` calls as they are. If you convert the expressions to code, Julia will compile them away easily, so you don't need to do anything more. However, you *can* remove them using [`PostNewtonian.unhold`](@ref) if the code is in [`Expr`](https://docs.julialang.org/en/v1/manual/metaprogramming/#Program-representation) form. ```@docs PostNewtonian.hold PostNewtonian.unhold PostNewtonian.SymbolicPNSystem ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
9731
# A note about units !!! note "TL;DR:" This package uses geometric units with ``G=c=1``. Units are essentially determined by the values you input. Masses and frequencies in particular must have inverse units. For example, if frequency is measured in Hertz, mass should be measured in seconds. The common relativist's convention of measuring in units of "total mass" (whatever that means to you) is also perfectly fine. Output time is in units of the total mass; to get the time in seconds, multiply by the total mass as measured in seconds. Waveforms are output as the asymptotic quantity ``rh/M``; to get an observable strain, multiply by the total mass and divide by the distance to the source. You may want to skip to [Example 2](@ref Units-example-2) for a complete example using astrophysical units. The units of measurement used in this package are implicitly established by the input. Specifically, the arguments `M₁`, `M₂`, and `Ωᵢ` in the call ```julia inspiral = orbital_evolution(M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ) ``` are inherently dimensionful, and the units are effectively determined by the values entered. For example, if we enter `0.4` as `M₁`, we have established the units as — quite simply — those units in which `M₁` has the value `0.4`. The only real requirement on the units of the input arguments is that they must be consistent. In particular, the quantity `(M₁+M₂)*Ωᵢ` should be dimensionless. It must also be noted that this package uses geometric units where ``G=c=1``; in fact, ``G`` and ``c`` never appear in the code at all. This means that you must input values in geometric units, and interpret the output as being in geometric units. This does not completely constrain the units, however. There is still a freedom to scale the units however you wish. For example, it is most common to describe all quantities in units of some mass ``M`` — such as the sum of the input masses `M₁+M₂` or the Solar mass ``M_\odot``. The input arguments would then *all* be given in units of that mass, or more likely some product of that mass with ``G`` and ``c``. The complete set of (required or optional) dimensionful arguments to `orbital_evolution` is ```julia M₁, M₂, Ωᵢ, Λ₁, Λ₂, Ω₁, Ωₑ, abstol, saveat ``` If we scale the values by some `σ`, then to maintain the same physical meaning we should transform all the arguments as ```julia M₁ ↦ M₁ * σ M₂ ↦ M₂ * σ Ωᵢ ↦ Ωᵢ / σ Λ₁ ↦ Λ₁ Λ₂ ↦ Λ₂ Ω₁ ↦ Ω₁ / σ Ωₑ ↦ Ωₑ / σ abstol ↦ [abstol[1:2] * σ; abstol[3:end]] saveat ↦ saveat * σ ``` Note that the scaling happens automatically for default values of the parameters; you would only need to rescale them if you were actually setting them. When the scaled arguments are provided to `orbital_evolution`, the resulting `inspiral` is affected as ```julia inspiral.t ↦ inspiral.t * σ inspiral[:M₁] ↦ inspiral[:M₁] * σ inspiral[:M₂] ↦ inspiral[:M₂] * σ ``` All other evolved variables are dimensionless, and so are unaffected by the scaling. In particular, if the initial conditions are entered with values of `M₁` and `M₂` in their desired final units, no change needs to be made. On the other hand, if the values are entered so that `M₁+M₂=1`, we can rescale any BBH system to any desired total mass `Mₜₒₜ` using ```julia inspiral.t ↦ inspiral.t * Mₜₒₜ * G / c^3 ``` Furthermore, if `M₁` and `M₂` represent the *source-frame* mass, and we need to apply a cosmological redshift `z`, we simply apply ```julia inspiral.t ↦ inspiral.t * (1+z) ``` The waveform ``H`` returned by either [`coorbital_waveform`](@ref) or [`inertial_waveform`](@ref) is the rescaled asymptotic limit of the strain. The observable strain is ```math h \approx H\, \frac{M}{r}\, \frac{G}{c^2} \qquad \mathrm{or} \qquad h \approx H\, \frac{M_z}{d_\mathrm{L}}\, \frac{G}{c^2}. ``` (The equality is only approximate because we assume that terms in ``1/r^2`` can be ignored, which is almost certainly true of any detection in the foreseeable future.) Here, ``r`` is the radius of the observer in asymptotically Minkowski coordinates centered on the source and ``M`` is the total mass of the binary; alternatively, ``M_z=M(1+z)`` is the redshifted mass and ``d_\mathrm{L}`` is the luminosity distance between the source and observer. For more complete description, see [here](@ref Computing-the-waveform). ## Example 1: Scale dependence It's important to check that the claims above are actually true. Here, we put them to the test with a very large scale factor. ```@example units1 using PostNewtonian, Plots # hide plotlyjs() # hide default(size=(800,480), linewidth=3, leg=:top, legendfontsize=11) # hide σ = 10.0^10 # Scale factor M₁ = 0.4 M₂ = 0.6 χ⃗₁ = [0.0, 0.5, 0.8] χ⃗₂ = [0.8, 0.0, 0.5] Ωᵢ = 0.01 Ω₁ = 3Ωᵢ/4 Ωₑ = 0.9 dt = 5.0 inspiral1 = orbital_evolution(M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ, Ω₁=Ω₁, Ωₑ=Ωₑ, saveat=dt) inspiral2 = orbital_evolution(M₁*σ, M₂*σ, χ⃗₁, χ⃗₂, Ωᵢ/σ, Ω₁=Ω₁/σ, Ωₑ=Ωₑ/σ, saveat=dt*σ) plot(inspiral1.t, inspiral1[:v], label="Original") plot!(inspiral2.t/σ, inspiral2[:v], label="Scaled", linewidth=4, ls=:dot) plot!(xlabel="Time", ylabel="PN parameter 𝑣") savefig("units1.html"); nothing # hide # Check that the evolved `v` parameters are nearly equal (when interpolating # the second to *exactly* the same times as the first) inspiral1[:v] ≈ inspiral2(inspiral1.t*σ, idxs=:v) ``` ```@raw html <!-- NOTE: ../ in src works on github, but not locally --> <iframe src="../units1.html" style="height:500px;width:100%;"></iframe> ``` The fact that these curves are on top of each other, and the final expression returned `true` shows that this system does indeed depend on scale as suggested above. ## [Example 2: Astrophysical units](@id Units-example-2) Suppose we want to construct a system consistent with [GW150914](https://arxiv.org/abs/1606.01210), having source-frame masses ``35.6\,M_\odot`` and ``30.0\,M_\odot``, as it would be observed from a distance of ``440\,\mathrm{Mpc}`` with an initial frequency in the dominant ``(\ell,m)=(2,\pm 2)`` modes of ``f_i \approx 20\,\mathrm{Hz}``. Because the masses and frequencies must be in inverse units, we arbitrarily choose to measure frequencies in their natural unit of Hertz, and therefore masses are measured in seconds — multiplying the masses by ``G/c^3`` for geometric units. The distance to the source ``d_\mathrm{L}`` will also be converted to seconds by dividing by ``c``, so that we can simply multiply the waveform by ``M_z/d_\mathrm{L}`` to get the observed strain. The frequency ``f_i`` is the observed initial frequency of the ``(2,2)`` mode. We will need the corresponding angular orbital frequency in the frame. Recall that, by definition of redshift ``z``, we have ```math \frac{f_{\mathrm{source}}} {f_{\mathrm{observer}}} = 1+z \qquad \text{and} \qquad \frac{\Delta t_{\mathrm{observer}}}{\Delta t_{\mathrm{source}}} = 1+z. ``` Thus, the initial *source-frame orbital angular frequency* ``\Omega_i`` is related to the *observer-frame $(2,2)$ temporal frequency* ``f_i`` by[^1] ```math %\Omega_i = 2\pi f_{\mathrm{source}}^{(2,2)} / 2 \qquad f_i = f_{\mathrm{observer}}^{(2,2)} %\qquad %\frac{f_{\mathrm{source}}^{(2,2)}} {f_{\mathrm{observer}}^{(2,2)}} = %\frac{\Omega_i/\pi} {f_i} = 1+z %\qquad \Omega_i = \pi\, f_i\, (1+z). ``` [^1]: Here, we have approximated the frequency of the ``(\ell,m)=(2,\pm 2)`` modes as being twice the orbital frequency. In the post-Newtonian approximation, waveform mode ``H_{\ell,m}`` is frequently written as ``A_{\ell,m}\, \exp[-i\, m\, \Phi]``, where ``\Phi`` is the orbital phase that varies in time with ``d\Phi/dt = \Omega``. Just looking at the exponential, we might expect the frequency of ``H_{\ell,m}`` to be ``m\, \Omega``. However, the "amplitude" term ``A_{\ell,m}`` is not an amplitude in the usual sense; it is actually complex, with a slowly varying phase. This means that the frequency of ``H_{\ell,m}`` is not precisely ``m\, \Omega`` — though this is a reasonable approximation for systems with reasonably low frequency. ```@example units2 using Quaternionic using SphericalFunctions using PostNewtonian using Plots plotlyjs() # hide default(size=(800,480), linewidth=3, leg=:top, legendfontsize=11) # hide # Useful astronomical constants c = float(299_792_458) # meters/second GMₛᵤₙ = 1.32712440041e20 # meters³/second² au = float(149_597_870_700) # meters pc = 1au / (π / 648_000) # meters Mpc = 1_000_000pc # meters # Approximate maximum a posteriori spins (via SXS:BBH:0308) χ⃗₁ = [0.0, 0.0, 0.3224] χ⃗₂ = [0.2663, 0.2134, -0.5761] # Parameters of this system (arXiv:1606.01210) M₁ = 35.6GMₛᵤₙ / c^3 # seconds M₂ = 30.0GMₛᵤₙ / c^3 # seconds dL = 440Mpc / c # seconds z = 0.094 fᵢ = 20 # Hertz Δtₒ = 1/2048 # seconds # Conversions Mz = (M₁+M₂) * (1+z) # seconds Ωᵢ = π * fᵢ * (1+z) # Hertz Δtₛ = Δtₒ / (1+z) # seconds # Evaluate waveform and convert to observer's frame and units inspiral = orbital_evolution(M₁, M₂, χ⃗₁, χ⃗₂, Ωᵢ, saveat=Δtₛ) tₒ = (1+z) * inspiral.t Hₗₘ = inertial_waveform(inspiral) hₗₘ = Hₗₘ * Mz / dL # Evaluate waveform at a point; see Scri.jl for simpler methods R = Quaternionic.from_spherical_coordinates(2.856, 0.0) ₋₂Yₗₘ = SphericalFunctions.ₛ𝐘(-2, 8, Float64, [R])[1, :] h = (₋₂Yₗₘ' * hₗₘ)[1,:] # Plot the results plot(tₒ, real.(h), label="ℎ₊") plot!(tₒ, -imag.(h), label="ℎₓ") plot!(xlabel="Time (seconds)", ylabel="Strain (dimensionless)", ylim=(-1.5e-21,1.5e-21)) plot!(title="Observer-frame waveform", legend=(0.205, 0.9)) savefig("units2.html"); nothing # hide ``` ```@raw html <!-- NOTE: ../ in src works on github, but not locally --> <iframe src="../units2.html" style="height:500px;width:100%;"></iframe> ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
4824
# Structure of this package's code There is a fairly simple hierarchy to the code. Beyond some basic utilities, which are related to how we write the code, rather than post-Newtonian calculations *per se*, we have the following: 1. **System and state** Objects of type `PNSystem` represent the PN system itself and some information about it, including: - The `Binary` type — `BBH`, `BHNS`, or `NSNS` - The float type `T` — `Float64`, etc. - The PN expansion order `PNOrder` — a `Rational` - The current `state` of the system, including the fundamental variables The first of these is represented as the type itself, the last is stored as a vector inside the object, and the rest are represented as type parameters. Note that basically everything below will be written as a function of such an object, which we will denote `pnsystem`. 2. **Fundamental variables** This consists of the basic variables describing the instantaneous state of the system, including `M₁`, `M₂`, `χ⃗₁`, `χ⃗₂`, `R`, `v`. For systems with matter, this may also include tidal deformability for each star, `Λ₁` and `Λ₂`. These are encapsulated within a `PNSystem`, but it's important to note that these should all be accessed through functions like `M₁(pnsystem)` rather than directly like `pnsystem.M₁`. This allows Julia's type system to get involved, enabling important optimizations. Also, these variables can be automatically computed in functions that need them with the `@pn_expression` macro. For example, you can directly use the symbols `M₁`, `M₂`, etc., in a function that is wrapped in that macro, without any qualifiers to specify where those variables are coming from, and the macro will automatically and efficiently evaluate them for you because they are defined in the `PostNewtonian.FundamentalVariables` module. 3. **Derived variables** These are variables that are frequently used in PN expressions that can be computed from the fundamental variables, and are *defined* in terms of them. For example, the total mass `M ≔ M₁+M₂`, the antisymmetric spin vector `χ⃗ₐ ≔ (χ⃗₁-χ⃗₂)/2`, or the orbital separation vector `n̂ ≔ R x̂ R̄`. While none of these are strictly necessary, it is helpful to be able to write the same variables used in articles providing the PN expressions in the code itself. Because they are defined solely in terms of fundamental variables, which can be computed from an `PNSystem` alone, these are all written as functions of such an object — such as `M(pnsystem)`, `χ⃗ₐ(pnsystem)`, and `n̂(pnsystem)`. Again, these quantities will be automatically computed for you in any function wrapped in the `@pn_expression` macro because they are defined in the `PostNewtonian.DerivedVariables` module. 4. **PN expressions** Unlike derived variables, these are not necessarily defined in terms of only the fundamental variables, but they can be calculated in terms of both fundamental and derived variables. These are generally the result of post-Newtonian expansions — the most important examples being the flux [`𝓕`](@ref), binding energy [`𝓔`](@ref), and the waveform mode weights [`h!`](@ref) themselves. 5. **PN expansions** These are the specific parts of a "PN expression" that are expanded in powers of ``1/c``. For example, the flux `𝓕` and binding energy `𝓔` are expanded in powers of ``v/c``. When such PN expansions are defined using the [`@pn_expression`](@ref PostNewtonian.@pn_expression) macro, any occurrence of `c` is turned into an object that captures the exponent of `c` in that expression. The expansion is automatically truncated at the appropriate order, and then `c` is finally set to `1` so that the result can be computed as usual. See [`PNTerm`](@ref PostNewtonian.PNTerm) and [`PNExpansion`](@ref PostNewtonian.PNExpansion) for more details. 6. **Dynamics** This is where the ODE integration actually occurs, to evolve the orbital dynamics of the system. 7. **Evaluation** Finally, we construct the waveforms themselves. This level contains the main interface that will usually be used from Julia code, and should be restricted to fairly high-level functions like `PNWaveform(M₁, M₂, ...)`, while still handling the full range of options that will be present in "Dynamics", for example. 8. **Compatibility layers** This is an optional level of abstraction that allows us to wrap the evaluation layer in functions that are designed to look and act more like other packages' functions. As of this writing, the only such layer is for [`GWFrames`](https://github.com/moble/GWFrames) compatibility, but similar wrappers could certainly be added.
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
6067
# Derived variables ## Orbital elements ```@docs n̂ λ̂ ℓ̂ Ω ``` ## Mass combinations ```@docs PostNewtonian.M PostNewtonian.μ PostNewtonian.ν PostNewtonian.δ PostNewtonian.q PostNewtonian.ℳ PostNewtonian.X₁ PostNewtonian.X₂ ``` ## Spin combinations ```@docs S⃗₁ S⃗₂ S⃗ Σ⃗ χ⃗ χ⃗ₛ χ⃗ₐ χₑ χₚ PostNewtonian.S⃗₀⁺ PostNewtonian.S⃗₀⁻ ``` Additionally, there are numerous convenience functions to give certain components of the spins. They take a single `pnsystem` argument and are not exported. Given the definitions above, they are all fairly self explanatory — such as `χ₁²`, which gives `χ⃗₁ ⋅ χ⃗₁`; or `χ₁₂ = χ⃗₁ ⋅ χ⃗₂`; or `Sₙ = S⃗ ⋅ n̂`. Like all the other fundamental and derived variables, these can be used directly in PN expressions modified by the [`@pn_expression`](@ref PostNewtonian.@pn_expression) macro. ## Horizons We can also compute some variables defined by [Alvi (2001)](http://link.aps.org/doi/10.1103/PhysRevD.64.104020) related to the horizons. The hardest parts to compute here involve the relative angles between the spins and the black-hole separation vectors. Alvi constructs a spherical coordinate system centered on each black hole where the ``z`` axis is given by the direction of the spin, and ``\theta`` and ``\phi`` represent the direction to the other black hole. While he makes a (somewhat ambiguous) choice about the origin of the ``\phi`` coordinate, only ``\dot{\phi}`` comes into the equations, so we don't really care about that origin. Note that Alvi uses ``\mathbf{n}`` to represent the "normal to the orbital plane", whereas we — and most of the rest of the post-Newtonian literature — use [``\hat{\ell}``](@ref PostNewtonian.ℓ̂) for this vector and [``\hat{n}``](@ref PostNewtonian.n̂) to represent the separation vector pointing *from* object 2 *to* object 1. For convenience, we define ```math \hat{n}_i = \begin{cases} -\hat{n} & \text{i=1}, \\ \hphantom{-}\hat{n} & \text{i=2}. \end{cases} ``` Alvi's construction is also somewhat adiabatic, so we treat the spins and orbital plane as constant in the calculation of the instantaneous tidal heating — though they evolve slowly over time — and the angles ``\theta`` and ``\phi`` as evolving rapidly. In our formulation, then, the goal is to find the angle ``\theta_i(t)`` between ``\vec{\chi}_i`` and ``\hat{n}_i``, and the rotation rate ``\dot{\phi}_i(t)`` of ``\hat{n}_i`` about the ``\vec{\chi}_i`` axis. Computing the angle between vectors is a somewhat infamously tricky problem. There are various [claims](https://people.eecs.berkeley.edu/~wkahan/Triangle.pdf) floating around about the best ways to compute quantities involving areas and angles of triangles. While these claims are [surely true for areas](https://inria.hal.science/hal-00790071), I am more skeptical of the relevance for angles. I find it best to realize that you probably don't need the angle *per se*, but trigonometric functions of the angle — like ``\sin^2 \theta_i``, which is what we actually need in this case. In particular, I believe the best results come from computing ```math \sin^2\theta_i = \frac{ \left|\hat{n}_i \times \vec{\chi}_i\right|^2 }{ \left| \vec{\chi}_i\right|^2 }. ``` If the denominator is zero, we set ``\sin^2\theta_i = 1`` from physical considerations. Now consider the quantity ``\hat{n}_i \times \vec{\chi}_i``. We next aim to calculate the rotation rate ``\dot{\phi}_i`` of this vector about ``\vec{\chi}_i``. We begin by directly calculating ```math \partial_t \left(\hat{n}_i \times \vec{\chi}_i\right) = \left(\partial_t \hat{n}_i\right) \times \vec{\chi}_i = \left(\Omega\, \hat{\ell} \times \hat{n}_i\right) \times \vec{\chi}_i = \mp \Omega\, \hat{\lambda} \times \vec{\chi}_i, ``` where the negative sign is chosen for ``i=1`` and positive for ``i=2``. Now, from more fundamental considerations, we can understand the components of this change. Since we assume that ``\vec{\chi}_i`` is constant at each instant for the purposes of calculation here, the only way for ``\hat{n}_i \times \vec{\chi}_i`` to change is either because ``\hat{n}_i`` rotates about ``\vec{\chi}_i``, or because the angle ``\theta_i`` is changing. We can express this as ```math \partial_t \left(\hat{n}_i \times \vec{\chi}_i\right) = \left( \dot{\phi}\, \hat{\chi}_i \right) \times \left(\hat{n}_i \times \vec{\chi}_i\right) + \dot{\theta_i}\, \cot \theta_i\, \left(\hat{n}_i \times \vec{\chi}_i\right). ``` Since these two components are orthogonal, we can obtain ``\dot{\phi}`` directly by taking the component of this quantity along ``\hat{\chi}_i \times \left(\hat{n}_i \times \vec{\chi}_i\right)``: ```math \dot{\phi}_i = \frac{ \left( \Omega\, \hat{\lambda} \times \vec{\chi}_i \right) \cdot \left( \vphantom{\hat{\lambda}} \hat{\chi}_i \times \left(\hat{n} \times \vec{\chi}_i\right) \right) }{ \left| \hat{\chi}_i \times \left(\hat{n} \times \vec{\chi}_i\right) \right|^2 } = \Omega\, \frac{\hat{\ell} \cdot \hat{\chi}_i}{\sin^2 \theta_i}. ``` Here again, we may run into numerical trouble if ``\left| \vec{\chi}_1 \right| \approx 0``, in which case we again use physical arguments to take ``\dot{\phi}_i = \Omega``. We might also expect to run into trouble if ``\sin^2 \theta_i \approx 0``, which corresponds to a polar orbit, in which case Alvi's approximations break down. This turns out to not be a problem *numerically*, because of the cancellation with the numerator, except when ``\sin^2 \theta_i = 0`` exactly. In this case, we choose ``\dot{\phi}_i = 0``. Note that the sign of ``\hat{n}_i`` has dropped out of the calculations of both ``\sin^2\theta_i`` and ``\dot{\phi}_i``, cancelling with the signs that had appeared next to ``\Omega``. ```@docs PostNewtonian.rₕ₁ PostNewtonian.rₕ₂ PostNewtonian.Ωₕ₁ PostNewtonian.Ωₕ₂ PostNewtonian.sin²θ₁ PostNewtonian.sin²θ₂ PostNewtonian.ϕ̇̂₁ PostNewtonian.ϕ̇̂₂ PostNewtonian.Î₀₁ PostNewtonian.Î₀₂ PostNewtonian.κ₁ PostNewtonian.κ₂ PostNewtonian.κ₊ PostNewtonian.κ₋ PostNewtonian.λ₁ PostNewtonian.λ₂ PostNewtonian.λ₊ PostNewtonian.λ₋ ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
3210
# Dynamics ## Integrating orbital evolution ```@docs orbital_evolution uniform_in_phase estimated_time_to_merger fISCO ΩISCO ``` ## Detecting the up-down instability ```@autodocs Modules = [PostNewtonian] Pages = ["dynamics/up_down_instability.jl"] Order = [:module, :type, :constant, :function, :macro] ``` ## Approximants These compute the right-hand sides for the ODE integration of PN orbital evolutions. They only differ in how they compute the time dependence of the fundamental PN variable ``v``. Fundamentally, we have ```math \frac{dv}{dt} = -\frac{\mathcal{F} + \dot{M}_1 + \dot{M}_2} {\mathcal{E}'} ``` as the essential expression. The various approximants differ simply in how they expand this expression. Details are explained in the following docstrings, but in principle the differences should be at the next-highest PN order beyond the orders to which the factors are calculated. Note that `TaylorT2` and `TaylorT3` can also be [found in the literature](https://arxiv.org/abs/0710.0158), and are used to derive analytical expressions for the orbital evolution.[^2] Unfortunately, this can only be accomplished for non-precessing systems, so we don't bother to implement them in this package. [^2]: The second `T` in the `TaylorTn` names refers to the fact that these calculations provide the dynamics in the *time* domain. In a manner following `TaylorT2`, it is also possible to use the stationary-phase approximation to derive the dynamics in the *frequency* domain, thus resulting in [the `TaylorF2` approximant](https://arxiv.org/abs/0901.1628). Finally, it should be noted that approximants named `TaylorK1`, `TaylorK2`, and `TaylorEt` [have also been introduced](https://arxiv.org/abs/0712.3236). None of these other approximants have been implemented in this package. ```@autodocs Modules = [PostNewtonian] Pages = ["dynamics/right_hand_sides.jl"] Order = [:module, :type, :constant, :function, :macro] ``` !!! note "Truncation order vs. `PNOrder` vs. PN order" When expanding the fraction given above as a series in ``v``, the truncation order is not necessarily the value of `PNOrder` given in the input `p`. Instead, it is the highest order of the series that is present in the numerator or denominator — which is what we would normally *call* the PN order of those expansions. The `PNOrder` parameter is the highest order of the series that is *allowed* to be present in those expansions, so that if `PNOrder` is effectively infinite, the series will be expanded to the highest order given in any of the PN expansions, but the expansion of the ratio will not go to infinite order. This is the reason that `TaylorT4` and `TaylorT5` *do not* approach `TaylorT1` as `PNOrder` approaches `typemax(Int)`. This design decision was made to ensure feasibility of the calculations. Note that, internally, the `TaylorT*` functions call `causes_domain_error!`. This is a fairly simplistic detection of when evolved parameters will lead to bad values. It may be desirable to extend this detection to be more sophisticated. ```@docs PostNewtonian.causes_domain_error! ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
541
```@meta CurrentModule = PostNewtonian.FundamentalVariables ``` # Fundamental variables These constitute the basic quantities needed to fully describe a PN binary system at any instant. All other variables — and ultimately all PN expressions — may be expressed as functions of these. In the docstrings below, `pnsystem` is an object of any type that subtypes `PNSystem`. ```@docs PostNewtonian.M₁ PostNewtonian.M₂ PostNewtonian.χ⃗₁ PostNewtonian.χ⃗₂ PostNewtonian.R PostNewtonian.v PostNewtonian.Φ PostNewtonian.Λ₁ PostNewtonian.Λ₂ ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
1267
# PN expressions These are collected from numerous sources in the literature. The docstrings below provide the relevant citations. ## Binding energy ```@autodocs Modules = [PostNewtonian] Pages = ["pn_expressions/binding_energy.jl"] Order = [:module, :type, :constant, :function, :macro] ``` ## Flux ```@autodocs Modules = [PostNewtonian] Pages = ["pn_expressions/flux.jl"] Order = [:module, :type, :constant, :function, :macro] ``` ## Tidal heating ```@autodocs Modules = [PostNewtonian] Pages = ["pn_expressions/tidal_heating.jl"] Order = [:module, :type, :constant, :function, :macro] ``` ## Separation ```@autodocs Modules = [PostNewtonian] Pages = ["pn_expressions/separation.jl"] Order = [:module, :type, :constant, :function, :macro] ``` ### Kidder (1995) ```@autodocs Modules = [PostNewtonian.Kidder1995] Pages = ["pn_expressions/separation.jl"] Order = [:module, :type, :constant, :function, :macro] ``` ## Precession ```@autodocs Modules = [PostNewtonian] Pages = ["pn_expressions/precession.jl"] Order = [:module, :type, :constant, :function, :macro] ``` ## Mode weights ```@autodocs Modules = [PostNewtonian] Pages = ["pn_expressions/mode_weights.jl"] Order = [:module, :type, :constant, :function, :macro] ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
73
# PN systems ```@docs PNSystem BBH BHNS NSNS FDPNSystem fd_pnsystem ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
5912
# Utilities ## PN terms and PN expansions The basic building blocks of post-Newtonian theory are the terms and expansions. These are used to build up the various expressions that describe the dynamics of the system. The terms are the individual parts of the expansions, while the expansions are the full expressions that are expanded in powers of ``1/c``. ```@docs PostNewtonian.PNTerm PostNewtonian.PNExpansionParameter PostNewtonian.PNExpansion ``` ## Macros Some of the most useful features of this package are the macros allowing us to write PN expressions in fairly natural form, without worrying about calculating all the variables needed for each expression, or manually accounting for the various PN orders to which we may need to truncate PN expansions. To achieve this, we rely primarily on two macros. ```@autodocs Modules = [PostNewtonian] Pages = ["utilities/macros.jl"] Order = [:macro, :module, :type, :constant, :function] ``` ## Termination criteria Hopefully, it should not be necessary to directly use these termination criteria. They are used by default in the [`orbital_evolution`](@ref) function. But certain particularly extreme physical parameters may lead ODEs that are difficult to integrate — especially if new PN systems or terms are introduced. These, or similar functions may be helpful examples of ["callbacks"](https://docs.sciml.ai/DiffEqDocs/stable/features/callback_functions/) that can be passed to the ODE integrator. Note that several of these will issue warnings if the evolution has to be terminated for particularly bad or suspicious reasons, even if the `quiet` flag is set to `true`. See the documentation of the `quiet` argument to the [`orbital_evolution`](@ref) function for an example of how to use `Logging` to quiet even the warnings. ```@autodocs Modules = [PostNewtonian] Pages = ["utilities/termination_criteria.jl"] Order = [:module, :type, :constant, :function, :macro] ``` ## Manipulating ODE solutions ```@autodocs Modules = [PostNewtonian] Pages = ["utilities/combine_solutions.jl"] Order = [:module, :type, :constant, :function, :macro] ``` ### Irrational constants These quantities are constants that appear in PN expressions, so they are not exported, but can be used by importing them explicitly or by using the fully qualified names. They are defined here as `Irrational`s. This means that Julia *can* convert them to float types as necessary. Unfortunately, by default Julia converts to `Float64`. For example, `BigFloat(2ζ3)` will be a `BigFloat`, but will only have the precision of a `Float64`, because `2ζ3` is converted first. To get full precision, you'll need to do things like `2BigFloat(ζ3)`. One approach to avoiding this is to explicitly redefine these constants as floats of the desired precision, using `let` to essentially overwrite the name: ```julia function foo(x) let ζ3=oftype(x, ζ3) 2ζ3 + x end end ``` Inside the `let` block, `ζ3` is no longer an `Irrational`; it has been converted to whatever number type `x` is. Thus, when multiplying by 2, it is not converted to a `Float64`; its precision matches that of `x`. This can be quite awkward, so the macro [`PostNewtonian.@pn_expression`](@ref) is provided to (among other things) automatically search for all `Irrational`s and replace them with the appropriate float values. ```@docs PostNewtonian.γₑ PostNewtonian.ζ3 PostNewtonian.ln2 PostNewtonian.ln3 PostNewtonian.ln5 PostNewtonian.ln³╱₂ PostNewtonian.ln⁵╱₂ ``` ## Truncated series We also have some utilities for dealing with series — or more precisely summations, since we only handle finitely many terms. In particular, we need *truncated* multiplication (and some times division) of truncated series. This multiplication is associative and there is a multiplicative identity element — though not always a multiplicative inverse — which means that this structure naturally forms a [monoid](https://en.wikipedia.org/wiki/Monoid). (In fact, it also forms more general structures, like a commutative algebra; all we need is the monoidal structure.) Here, we are assuming that there is a fixed order at which the series are truncated, and that truncated multiplication preserves that order. That is, if ``A`` and ``B`` are summations in terms up to ``v^N`` for some integer ``N``, we want their product and ratio (if it exists) to also be a summation in terms up to ``v^N``. Note that we are not referring to these summations as "polynomials" in ``v``, because the coefficients will sometimes involve ``\ln(v)`` — which is not technically permitted for polynomials. In particular, the presence of logarithms is irrelevant to our meaning of the "order" of the truncated series. This is standard practice in post-Newtonian theory.[^1] [^1]: Different texts in post-Newtonian theory treat these logarithmic terms with varying levels of rigor. The preferred method is [Hadamard regularization](https://en.wikipedia.org/wiki/Hadamard_regularization) (often referred to in the literature as the *partie finie*). A good summary is found in Section 6 of [Blanchet's Living Review](https://link.springer.com/article/10.12942/lrr-2014-2). Another potential approach could be taken following [this paper](https://doi.org/10.1016/0001-8708(89)90079-0). But for our purposes, it will suffice to take the simplistic approach of treating logarithmic terms as if they were any other constant. The following functions implement this behavior: ```@docs PostNewtonian.truncated_series_inverse PostNewtonian.truncated_series_product PostNewtonian.truncated_series_ratio PostNewtonian.lagrange_inversion PostNewtonian.x╱f_mod_xⁿ⁻¹ PostNewtonian.hⁱ✖h_mod_xⁿ⁻¹ ``` ## Miscellaneous ```@autodocs Modules = [PostNewtonian] Pages = ["utilities/misc.jl"] Order = [:module, :type, :constant, :function, :macro] ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.10.2
592e97807d90904fd94a681a4bd1976edc41c0df
docs
3912
# Computing the waveform Once you have [computed the orbital evolution](@ref orbital_evolution), and [selected the time steps](@ref sec_optional_choose_time_steps) on which you want to evaluate the waveform, you can do so with one of the functions documented below. ## Precise definition of waveforms The waveform returned by these functions is essentially the complex strain ``h \colonequals h_+ - i\,h_\times``. However, this quantity decays as ``1/r``, where ``r`` is the radius at which the strain is measured. Therefore, as is conventional, the returned quantity is actually ```math H \colonequals \lim_{r\to\infty} h\, \frac{r}{M}\, \frac{c^2}{G}, ``` where ``M`` is the total mass of the two objects in the binary. Note that both ``h`` and ``H`` are dimensionless, but only ``H`` is scale invariant. Binaries are usually modeled in relativity as being isolated systems in otherwise empty asymptotically flat spacetimes — or even more specifically, in asymptotically Minkowski spacetimes. In this case, ``r`` is just the asymptotic areal radius. The equivalent expression in an FLRW spacetime requires a simple reinterpretation of ``M`` as the redshifted mass ``M_z \colonequals M(1+z)`` and ``r`` as the luminosity distance ``d_L.``[^1] Thus, to obtain the strain as it would be measured (in the asymptotic approximation) by an actual observer in an asymptotically flat universe or in our universe, we just need to invert the previous equation: ```math h \approx H\, \frac{M}{r}\, \frac{G}{c^2} \qquad \mathrm{or} \qquad h \approx H\, \frac{M_z}{d_L}\, \frac{G}{c^2}. ``` [^1]: Note that we use "luminosity distance" as it is [understood in contemporary cosmology](https://arxiv.org/abs/astro-ph/9905116), which is unfortunately different from its meaning in older cosmology literature, and even some of the gravitational-wave astronomy literature from before 2015 or so. Furthermore, ``H`` is a function of coordinates ``(t, \theta, \phi)``. The dependence on ``t`` will be discretely sampled at the times ``t_i`` that are present in the `inspiral` arguments to the functions below. To handle the angular dependence, we provide the waveform decomposed as mode weights in a spin-weighted spherical-harmonic decomposition, so that the actual quantity returned will be ```math H_{\ell,m}(t_i) \colonequals \int H(t, \theta, \phi)\, {}_{-2}\bar{Y}_{\ell,m}(\theta, \phi)\, \sin\theta\, d\theta\, d\phi. ``` The output array is a two-dimensional complex array. The first dimension varies over ``(\ell,m)`` values, with ``m`` varying most rapidly — as in ```julia [(ℓ,m) for ℓ ∈ ℓₘᵢₙ:ℓₘₐₓ for m ∈ -ℓ:ℓ] ``` The second dimension of the array indexes the time. See [Example 2 on the "Units" page](@ref Units-example-2) for a complete example of converting this package's output to standard units in our universe. ## Evaluation of waveforms ```@docs coorbital_waveform inertial_waveform ``` ## In-place evaluation of waveforms This is likely to be an uncommon scenario, but if you happen to need to evaluate the waveform repeatedly on the same set (or at least same number) of time steps and same range of ``\ell`` values, then you can pre-allocate the storage needed in this process, and re-use that storage. To do so, pre-allocate using either [`coorbital_waveform_computation_storage`](@ref) or [`inertial_waveform_computation_storage`](@ref), and then pass the result as the first argument to either [`coorbital_waveform!`](@ref) or [`inertial_waveform!`](@ref). !!! note The `h` array returned by either `coorbital_waveform!` or `inertial_waveform!` is part of the pre-allocated storage. You need to use its values *before* you call either of those functions again, or those values will just be overwritten. ```@docs coorbital_waveform_computation_storage inertial_waveform_computation_storage coorbital_waveform! inertial_waveform! ```
PostNewtonian
https://github.com/moble/PostNewtonian.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
1310
module Flamenco import Sockets include("Server.jl") include("Writer.jl") """ close_server() Stop Flamenco server """ function close_server() Server.close() end """ start_server( f::Function, host::Union{Sockets.IPAddr, String}=Sockets.localhost, port::Int64=8000 ) :: Server.Request Start Flamenco server on specified host/port `f` is function that parsed `request` is forwarded to """ function start_server( f::Function, host::Union{Sockets.IPAddr, String}=Sockets.localhost, port::Int64=8000 ) :: Server.Request request::Server.Request = Server.Request("", "", Dict(), "") try request = Server.start(f, host, port) catch e if e isa InterruptException @warn "Server interrupted" else rethrow(e) end end return request end """ write_response(status_code::Int16, headers::Dict{String, String}; body::String) :: String Return HTTP response String """ function write_response(status_code::Int16, headers::Dict{String, String}; body::String) :: String response::String = "" if length(body) > 0 response = Writer.write(status_code, headers; body=body) else response = Writer.write(status_code, headers) end return response end end
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
3843
module Server import BufferedStreams import Sockets import ThreadPools include("parsers/Http1_1.jl") include("Utils.jl") include("Writer.jl") struct Error code::Int16 message::String end struct Request target::String method::String headers::Dict{String, String} body::String end SERVER = nothing """ _handle_connection(buffered_stream::BufferedStreams.BufferedInputStream) :: Tuple{Error, Request} Forward BufferedInputStream to Http1.1 parser If error occurs, return Error struct and empty Request struct """ function _handle_connection(buffered_stream::BufferedStreams.BufferedInputStream) :: Tuple{Error, Request} body::String = "" error::Error = Error(0, "") headers::Dict{String, String} = Dict() method::String = "" target::String = "" request::Request = Request(target, method, headers, body) try target, method, headers, body = ParserHttp1_1.parse_request(buffered_stream) request = Request(target, method, headers, body) catch e if method!="" && e isa EOFError request = Request(target, method, headers, body) elseif contains(string(typeof(e)), "TimeoutError") error = Error(408, "Request Timeout") elseif contains(string(typeof(e)), "InternalError") error = Error(500, sprint(showerror, e)) else error = Error(401, "Bad Request") end end return error, request end """ close() Stop listening on Socket """ function close() Sockets.close(SERVER) end """ start(f::Function, host::Union{Sockets.IPAddr, String}, port::Integer) :: Request Listen to incoming requests on separate threads Write response (execute corresponding Julia function) to Socket, before closing it """ function start(f::Function, host::Union{Sockets.IPAddr, String}, port::Integer) :: Request error::Error = Error(0, "") request::Request = Request("", "", Dict(), "") response::String = "" global SERVER SERVER = Sockets.listen(parse(Sockets.IPAddr, host), port) # TODO increase backlog=511 while isopen(SERVER) ThreadPools.@bthreads for x in 1:1 socket = Sockets.accept(SERVER) bytes::Vector{UInt8} = readavailable(socket) # TODO: Find better way for PUT/POST requests with blank line before body content # As simply `bytesavailable` will return 0 if ( bytes[1:4] == UInt8[0x50, 0x4f, 0x53, 0x54] || bytes[1:3] == UInt8[0x50, 0x55, 0x54] ) if ( bytes[length(bytes)-3:length(bytes)] == UInt8[0x0d, 0x0a, 0x0d, 0x0a] ) bytes = append!(bytes, readavailable(socket)) end end buffered_stream = BufferedStreams.BufferedInputStream(bytes) try error, request = _handle_connection(buffered_stream) if error.message != "" response = Writer.write(error.code, request.headers; body=error.message) else response = f(request) end catch e error = Error(500, sprint(showerror, e)) @error "Error handling request" exception=(e, stacktrace(catch_backtrace())) if e isa Base.IOError && e.code == -54 @warn "Connection reset by peer (ECONNRESET)" else @error exception=(e, stacktrace(catch_backtrace())) end finally if isopen(socket) write(socket, response) BufferedStreams.close(buffered_stream) Sockets.close(socket) else println("stream closed ...") end end end end return request end end
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
297
module Utils """ has_header(headers::Dict{String, String}, key::String, value::String) :: Bool Check whether corresponding (key, value) pair exists in Header """ function has_header(headers::Dict{String, String}, key::String, value::String) :: Bool return headers[key] == value end end
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
1463
module Writer import Dates include("./status_codes.jl") """ write(status_code::Int16, headers::Dict{String, String}; body::String="") :: String Return HTTP response string - Status line - Headers - Empty line - Body (optional) """ function write(status_code::Int16, headers::Dict{String, String}; body::String="") :: String status_code_string::String = string(status_code) * " " * status_codes[status_code] response::String = "HTTP/1.1 " * status_code_string * "\n" if !haskey(headers, "Date") timestamp::Dates.DateTime = Dates.now(Dates.UTC) dayname::String = Dates.dayabbr(timestamp) day::Int64 = Dates.day(timestamp) monthname::String = Dates.monthabbr(timestamp) year::Int64 = Dates.year(timestamp) hour::Int64 = Dates.hour(timestamp) minute::Int64 = Dates.minute(timestamp) second::Int64 = Dates.second(timestamp) date_string::String = "$dayname, $day $monthname $year $hour:$minute:$second UTC" response *= "Date: " * date_string * "\n" end if !haskey(headers, "Content-Length") response *= "Content-Length: " * string(length(body)) * "\n" end for (key, val) in headers response *= "$key: $val\n" end # TODO: Only if Http 1.1 # if Utils.has_header(headers, "Connection", "close") response *= "Connection: Closed" if body != "" response *= "\n\n" * body end return response end end
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
163
""" InternalError() Internal error """ struct InternalError <: Exception end """ TimeoutError() Parsing timeout error """ struct TimeoutError <: Exception end
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
2022
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#successful_responses const status_codes = Dict( 100 => "Continue", 101 => "Switching Protocols", 102 => "Processing", 103 => "Early Hints", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 208 => "Already Reported", 226 => "IM Used", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Payload Too Large", 414 => "URI Too Long", 415 => "Unsupported Media Type", 416 => "Range Not Satisfiable", 417 => "Expectation Failed", 418 => "I'm a teapot", 421 => "Misdirected Request", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 425 => "Too Early", 426 => "Upgrade Required", 428 => "Precondition Required", 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 451 => "Unavailable For Legal Reasons", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Time-out", 505 => "HTTP Version Not Supported", 506 => "Variant Also Negotiates", 507 => "Insufficient Storage", 508 => "Loop Detected", 509 => "Bandwidth Limit Exceeded", 510 => "Not Extended", 511 => "Network Authentication Required" )
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
12509
module ParserHttp1_1 import BufferedStreams import Dates include("../errors.jl") ASCII_CODE_COLON = 58 ASCII_CODE_CR = 13 # Carriage Return ASCII_CODE_HT = 9 # Horizontal tab ASCII_CODE_LF = 10 # Line Feed ASCII_CODE_SPACE = 32 ASCII_PRINTABLE_RANGE_LOWER = 32 ASCII_PRINTABLE_RANGE_UPPER = 127 FAILED = false # Whether parsing failed #= Private functions =# """ _check_next_char_as_expected(stream::BufferedStreams.BufferedInputStream, ch::Int64) :: Bool Check if next char in stream matches expectation """ function _check_next_char_as_expected(stream::BufferedStreams.BufferedInputStream, ch::Int64) :: Bool is_expected_stream_next_char::Bool = false if BufferedStreams.read(stream, 1)[1] == ch is_expected_stream_next_char = true else global FAILED FAILED = true end return is_expected_stream_next_char end """ _found_crlf(stream::BufferedStreams.BufferedInputStream) :: Bool Find CRLF (line termination) """ function _found_crlf(stream::BufferedStreams.BufferedInputStream) :: Bool ch::UInt8 = BufferedStreams.read(stream, 1)[1] found_crlf::Bool = false while (!found_crlf) if ch == ASCII_CODE_CR if _check_next_char_as_expected(stream, ASCII_CODE_LF) found_crlf = true end else global FAILED FAILED = true end end return found_crlf end """ _is_eof(stream::BufferedStreams.BufferedInputStream) :: Bool Check if parsing reached end of stream """ function _is_eof(stream::BufferedStreams.BufferedInputStream) :: Bool is_eof::Bool = false if stream.available == 0 global FAILED FAILED = true end return is_eof end """ _is_http_1_1(stream::BufferedStreams.BufferedInputStream) :: Bool Ensure is HTTP 1.1 """ function _is_http_1_1(stream::BufferedStreams.BufferedInputStream) :: Bool final_check::Bool = false if (stream.position + 8 > stream.available) global FAILED FAILED =true else check::Bool = true while (check) check = _check_next_char_as_expected(stream, 72) # H check = _check_next_char_as_expected(stream, 84) # T check = _check_next_char_as_expected(stream, 84) # T check = _check_next_char_as_expected(stream, 80) # P check = _check_next_char_as_expected(stream, 47) # / check = _check_next_char_as_expected(stream, 49) # 1 check = _check_next_char_as_expected(stream, 46) # . check = _check_next_char_as_expected(stream, 49) # 1 final_check = true check = false end end return final_check end """ _is_printable_ascii(ch::UInt8) :: Bool Check if char is printable ASCII value """ _is_printable_ascii(ch::UInt8) :: Bool = ASCII_PRINTABLE_RANGE_LOWER <= ch <= ASCII_PRINTABLE_RANGE_UPPER """ _parse_body(stream::BufferedStreams.BufferedInputStream, method::String) :: String Return Body as String, for PUT & POST requests """ function _parse_body(stream::BufferedStreams.BufferedInputStream, method::String) :: String buffer::String = "" function _read_body() buffer = String(UInt8.(BufferedStreams.read(stream))) end if (method == "PUT" || method == "POST") # Skip first empty line (some clients add CRLF before POST content) if (BufferedStreams.peek(stream) == ASCII_CODE_CR) BufferedStreams.read(stream, 1) if _check_next_char_as_expected(stream, ASCII_CODE_LF) _read_body() else global FAILED FAILED = -2 end else _read_body() end end return buffer end """ _parse_headers(stream::BufferedStreams.BufferedInputStream) :: Dict{String, String} Return Header as Dict As counter-measure againt Slowloris attack, if parsing takes longer than 4 seconds => return 408 status """ function _parse_headers(stream::BufferedStreams.BufferedInputStream) :: Dict{String, String} finished::Bool = false headers::Dict{String, String} = Dict() timeout::Bool = true function _check_end_of_header() if (BufferedStreams.read(stream, 1)[1] == ASCII_CODE_CR) if (BufferedStreams.read(stream, 1)[1] == ASCII_CODE_LF) if (BufferedStreams.read(stream, 1)[1] == ASCII_CODE_CR) if (BufferedStreams.read(stream, 1)[1] == ASCII_CODE_LF) finished = true else global FAILED FAILED = true end else BufferedStreams.seek(stream, stream.position-2) end else global FAILED FAILED = true end else global FAILED FAILED = true end end function _header_append(header_name::String, header_value::String) if (length(header_name)==0 || length(header_value)==0) global FAILED FAILED = true else headers[header_name] = header_value end end # Parse each header line # If longer than 4 seconds -> return 408 status start::Int64 = Int(floor(Dates.datetime2unix(Dates.now()))) while( !finished && Int(floor(Dates.datetime2unix(Dates.now()))) - start < 4 ) while (!_is_eof(stream) && !FAILED && !finished) fill_header_name::Bool = true header_name::String = "" header_value::String = "" next_ch::UInt8 = BufferedStreams.peek(stream) while (!FAILED && next_ch!=ASCII_CODE_CR && _is_printable_ascii(next_ch)) # Parsing name part (LHS of colon), but do not discard SP before colon if (next_ch == ASCII_CODE_COLON) BufferedStreams.read(stream, 1) if (BufferedStreams.peek(stream)==ASCII_CODE_SPACE || BufferedStreams.peek(stream)==ASCII_CODE_HT) fill_header_name = false BufferedStreams.read(stream, 1) else BufferedStreams.seek(stream, stream.position-1) if (BufferedStreams.peek(stream) in [33:1:57;] || BufferedStreams.peek(stream) in [59:1:126;]) # ! till 9, &lt; till ~ if fill_header_name header_name *= String(UInt8.(BufferedStreams.read(stream, 1))) else header_value *= String(UInt8.(BufferedStreams.read(stream, 1))) end end end elseif (next_ch==ASCII_CODE_SPACE || next_ch==ASCII_CODE_HT) BufferedStreams.read(stream, 1) if (BufferedStreams.peek(stream)==ASCII_CODE_COLON) fill_header_name = false BufferedStreams.read(stream, 1) end elseif (next_ch in [33:1:57;] || next_ch in [59:1:126;]) # ! till 9, &lt; till ~ if fill_header_name header_name *= String(UInt8.(BufferedStreams.read(stream, 1))) else header_value *= String(UInt8.(BufferedStreams.read(stream, 1))) end else global FAILED FAILED = true end next_ch = BufferedStreams.peek(stream) end _check_end_of_header() _header_append(header_name, header_value) end timeout = false end if timeout throw(TimeoutError()) end return headers end """ _parse_method(stream::BufferedStreams.BufferedInputStream) :: String Return HTTP method as String, among [DELETE, GET, OPTIONS, POST, PUT] """ function _parse_method(stream::BufferedStreams.BufferedInputStream) :: String ch::UInt8 = BufferedStreams.read(stream, 1)[1] check::Bool = true method::String = "" while (check) if (ch == 68) # D check = _check_next_char_as_expected(stream, 69) # E check = _check_next_char_as_expected(stream, 76) # L check = _check_next_char_as_expected(stream, 69) # E check = _check_next_char_as_expected(stream, 84) # T check = _check_next_char_as_expected(stream, 69) # E method = "DELETE" check = false elseif (ch == 71) # G check = _check_next_char_as_expected(stream, 69) # E check = _check_next_char_as_expected(stream, 84) # T method = "GET" check = false elseif (ch == 79) # O check = _check_next_char_as_expected(stream, 80) # P check = _check_next_char_as_expected(stream, 84) # T check = _check_next_char_as_expected(stream, 73) # I check = _check_next_char_as_expected(stream, 79) # O check = _check_next_char_as_expected(stream, 78) # N check = _check_next_char_as_expected(stream, 83) # S method = "OPTIONS" check = false elseif (ch == 80) # P ch = BufferedStreams.read(stream, 1)[1] if (ch == 79) # O check = _check_next_char_as_expected(stream, 83) # S check = _check_next_char_as_expected(stream, 84) # T method = "POST" check = false elseif (ch == 85) # U check = _check_next_char_as_expected(stream, 84) # T method = "PUT" check = false else check = false end else check = false end end if method == "" global FAILED FAILED = true end return method end """ _parse_request_line(stream::BufferedStreams.BufferedInputStream) :: Tuple{String, String} Return Method & Target from Request line """ function _parse_request_line(stream::BufferedStreams.BufferedInputStream) :: Tuple{String, String} method::String = "" target::String = "" while (!FAILED) method = _parse_method(stream) _check_next_char_as_expected(stream, ASCII_CODE_SPACE) target = _parse_target(stream) _check_next_char_as_expected(stream, ASCII_CODE_SPACE) if (length(method)==0 || length(target)==0) global FAILED FAILED = true end if !_is_http_1_1(stream) global FAILED FAILED = true end if !_found_crlf(stream) global FAILED FAILED = true end break end return method, target end """ _parse_target(stream::BufferedStreams.BufferedInputStream) :: String Return Target as String """ function _parse_target(stream::BufferedStreams.BufferedInputStream) :: String ch::UInt8 = BufferedStreams.peek(stream) target::String = "" while (ch != ASCII_CODE_SPACE) target *= String(UInt8.(BufferedStreams.read(stream, 1))) ch = BufferedStreams.peek(stream) end return target end #= Public functions =# """ parse_request(stream::BufferedStreams.BufferedInputStream) :: Tuple {String, String, Dict{String, String}, String} Parse HTTP request (Target, Method, Headers, Body) Only parse Header once, as counter-measure againt Slowloris attack """ function parse_request(stream::BufferedStreams.BufferedInputStream) :: Tuple{String, String, Dict{String, String}, String} body::String = "" header_parsed::Bool = false headers::Dict{String, String} = Dict() method::String = "" target::String = "" global FAILED FAILED = false while (!FAILED) # Only parse Header once (counter-measure againt Slowloris attack) if stream.position > 1 && !header_parsed method, target = _parse_request_line(stream) headers = _parse_headers(stream) header_parsed = true else method, target = _parse_request_line(stream) headers = _parse_headers(stream) end body = _parse_body(stream, method) break end if FAILED throw(InternalError()) end return target, method, headers, body end end
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
305
include("utils/main.jl") server_start() make_and_test_request_delete(["a" => "b"]) make_and_test_request_get(["a" => "b"]) make_and_test_request_options(["a" => "b"]) make_and_test_request_put(["a" => "b"], Dict("a" => 1), 7) make_and_test_request_post(["a" => "b"], Dict("b" => 2), 7) server_close()
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
255
import Sockets include("utils/main.jl") server_start() @testset "404" begin try HTTP.request("GET", "http://127.0.0.1:8000/a", []; retry=false) catch e @test e isa HTTP.ExceptionRequest.StatusError end end server_close()
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
425
include("utils/main.jl") server_start() @testset "Space before Header colon" begin r = HTTP.request("GET", "http://127.0.0.1:8000/", ["a " => "b"]) parse_and_test_request(r, 200, ["a" => "b"], 230, false, true) end @testset "Space after Header colon" begin r = HTTP.request("GET", "http://127.0.0.1:8000/", ["a" => " b"]) parse_and_test_request(r, 200, ["a" => "b"], 230, false, true) end server_close()
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
251
#!/usr/bin/env julia using Test, SafeTestsets @time begin @time @safetestset "CRUD" begin include("crud_test.jl") end @time @safetestset "Header" begin include("header_test.jl") end @time @safetestset "Error" begin include("error_test.jl") end end
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
3913
import Flamenco import HTTP import JSON include("./request.jl") function make_and_test_request_delete(headers::Vector{Pair{String,String}}) :: Nothing r = HTTP.request("DELETE", "http://127.0.0.1:8000/", headers) parse_and_test_request(r, 200, headers, 15, true, false, Dict("Success" => 200)) end function make_and_test_request_get(headers::Vector{Pair{String,String}}) :: Nothing r = HTTP.request("GET", "http://127.0.0.1:8000/", headers) parse_and_test_request(r, 200, headers, 230, false, true) end function make_and_test_request_options(headers::Vector{Pair{String,String}}) :: Nothing r = HTTP.request("OPTIONS", "http://127.0.0.1:8000/", headers) parse_and_test_request(r, 200, headers, 2, true, false, Dict()) compare_http_header(r.headers, "Allow", "POST") compare_http_header(r.headers, "Access-Control-Allow-Methods", "POST") compare_http_header(r.headers, "Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type") end function make_and_test_request_put(headers::Vector{Pair{String,String}}, payload::Dict, content_length::Int64) :: Nothing r = HTTP.request("PUT", "http://127.0.0.1:8000/", headers, JSON.json(payload)) parse_and_test_request(r, 200, headers, content_length, true, false, payload) end function make_and_test_request_post(headers::Vector{Pair{String,String}}, payload::Dict, content_length::Int64) :: Nothing r = HTTP.request("POST", "http://127.0.0.1:8000/", headers, JSON.json(payload)) parse_and_test_request(r, 200, headers, content_length, true, false, payload) end ############# function routes(; request_headers::Dict{String, String}, request_method::String, request_path::String, request_payload::String) :: String body::String = "a" headers::Dict{String, String} = Dict() status_code::Int16 = 404 if (request_path=="/") status_code = 200 delete!(request_headers, "Content-Length") delete!(request_headers, "Date") if (request_method=="DELETE") headers = merge( request_headers, Dict("Content-Type" => "application/json") ) body = JSON.json(Dict( "Success" => 200 )) elseif (request_method=="GET") headers = merge( request_headers, Dict("Content-Type" => "text/html; charset=UTF-8") ) body = """<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Flamenco</title> </head> <body> <div>Content ...</div> </body> </html> """ elseif (request_method=="OPTIONS") headers = merge( request_headers, Dict( "Allow" => "POST", "Access-Control-Allow-Methods" => "POST", "Access-Control-Allow-Headers" => "X-PINGOTHER, Content-Type", "Content-Type" => "application/json" ) ) body = JSON.json(Dict()) elseif (request_method=="PUT" || request_method=="POST") headers = merge( request_headers, Dict( "Content-Type" => "application/json" ) ) body = request_payload end end return Flamenco.write_response(status_code, headers; body=body) end function server_close() :: Nothing Flamenco.close_server() end function server_start() @async Flamenco.start_server("127.0.0.1", 8000) do request::Flamenco.Server.Request routes(; request_headers=request.headers, request_method=request.method, request_path=request.target, request_payload=request.body) end end
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
code
1685
import Dates import HTTP import JSON function compare_http_date_header(header_value::String, timestamp_request_completed::Dates.DateTime) :: Nothing header_value_timestamp::Dates.DateTime = Dates.DateTime(split(header_value, " UTC")[1], "e, d u Y H:M:S") @test header_value_timestamp <= timestamp_request_completed nothing end function compare_http_header(headers::Array, key::String, value::String) :: Nothing @test header_get_value(headers::Array, key::String)==value nothing end function header_get_value(headers::Array, key::String) :: String for item in headers if item[1]==key return item[2] end end end function parse_and_test_request(r::HTTP.Messages.Response, status::Int64, headers::Vector{Pair{String,String}}, content_length::Int64, is_json::Bool, is_get::Bool, body::Union{Dict, String}="") timestamp_request_completed::Dates.DateTime = Dates.now(Dates.UTC) @test r.status==status for (key, value) in headers compare_http_header(r.headers, key, value) end compare_http_date_header(header_get_value(r.headers, "Date"), timestamp_request_completed) # TODO: fix Windows HTML file longer due to line final char if !Sys.iswindows() compare_http_header(r.headers, "Content-Length", string(content_length)) end if is_json header_get_value(r.headers, "Content-Type") == "application/json" @test JSON.json(body) == String(r.body) elseif is_get header_get_value(r.headers, "Content-Type") == "text/html; charset=UTF-8" @test occursin("Content ...", String(r.body)) else length(r.body) == 0 end nothing end
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
0.1.2
ed69b0365eac56ac3e652c5fb865d0a54b18db36
docs
1713
# Flamenco | **Build Status** | |:------------------------------------------------------:| | [![Build Status](https://travis-ci.com/DanceJL/Flamenco.jl.svg?branch=master)](https://travis-ci.com/DanceJL/Flamenco.jl) [![codecov](https://codecov.io/gh/DanceJL/Flamenco.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/DanceJL/Flamenco.jl)| ## 1 - Introduction Simple and fast HTTP parser for CRUD API backend Julia web frameworks. Takes advantage of Julia multi-threading via [ThreadPools](https://github.com/tro3/ThreadPools.jl) and parses requests as buffer via [BufferedStreams](https://github.com/BioJulia/BufferedStreams.jl/). Architecture inspired from [PicoHTTPParser](https://github.com/h2o/picohttpparser). ## 2 - Setup Simply wrap your routing function inside `start_server`: ```julia Flamenco.start_server("127.0.0.1", 8000) do request::Flamenco.Server.Request routes(; request_headers=request.headers, request_method=request.method, request_path=request.target, request_payload=request.body) end ``` Your routing function must accept the 4 arguments: - request.headers ::Dict{String, String} - request.method ::String - request.target ::String - request.body ::String `Content-Type` Header must be set inside your routing function as well. If `Content-Length` and `Date` Headers are not set, Flamenco will automatically set these in the HTTP response. If you would prefer this routing logic to be automatically taken care of, see [DanceJL](https://github.com/DanceJL/Dance.jl) as an example.. # 3 - Supported HTTP Standards Currently only HTTP 1.1 is supported. Also the incoming request must be one of: DELETE, GET, OPTIONS, POST or PUT.
Flamenco
https://github.com/DanceJL/Flamenco.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
code
867
push!(LOAD_PATH, "../src/Retriever.jl") include("../src/Retriever.jl") using Documenter, DocumenterTools makedocs( modules = [Retriever], clean = false, format = Documenter.HTML( # Use clean URLs, unless built as a "local" build # Or set prettyurls = false prettyurls = !("local" in ARGS), ), build = "build", sitename = "Retriever.jl", authors = "Ethan White", linkcheck = !("skiplinks" in ARGS), pages = [ "Home" => "intro.md", "Installation Guide" => "tutorial.md", "Developer's Guide" => "developer.md", "Source" => "index.md", "Command Documentation" => "lib/public.md", "Code of Conduct" => "CODE_OF_CONDUCT.md", ], ) deploydocs( repo = "github.com/weecology/Retriever.jl.git", target = "build", deps = nothing, make = nothing, )
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
code
9173
module Retriever using PyCall export check_for_updates, commit, commit_log, create_rdataset export data_retriever_version, dataset_names export display_all_rdataset_names, download export get_dataset_names_upstream, get_rdataset_names export get_script_citation, get_script_upstream export install_csv, install_json, install_msaccess, install_mysql export install_postgres, install_sqlite, install_xml export reload_scripts, reset_retriever export update_rdataset_catalog, update_rdataset_contents export update_rdataset_script # Create retriever as rt while properly handling precompilation # See: https://github.com/JuliaPy/PyCall.jl#using-pycall-from-julia-modules const rt = PyNULL() function __init__() copy!(rt, pyimport_conda("retriever", "retriever", "conda-forge")) end """ ```julia check_for_updates() ``` Check Retriever scripts for updates. """ function check_for_updates() rt.check_for_updates() end """ ```julia commit(dataset, commit_message::String="", path::String="", quiet::Bool=false) ``` Commit Retriever dataset. """ function commit( dataset, commit_message::String = "", path::String = "", quiet::Bool = false, ) rt.commit(dataset, commit_message, path, quiet) println("Successfully committed.") end """ ```julia commit_log(dataset) ``` Get the commit log for a dataset. """ function commit_log(dataset) rt.commit_log(dataset) end """ ```julia create_rdataset(engine, package::String, dataset_name::String, script_path::Union{String, Nothing}=nothing) ``` Download files for RDatasets to the raw data directory """ function create_rdataset( engine, package::String, dataset_name::String, script_path::Union{String,Nothing} = nothing, ) rt.create_rdataset(engine, package, dataset_name, script_path) end """ ```julia data_retriever_version() ``` Get Data Retriever version. """ function data_retriever_version() rt.__version__ end """ ```julia dataset_names() ``` Return list of all available dataset names. """ function dataset_names() rt.dataset_names() end """ ```julia display_all_rdataset_names(package_name::Array{String,1}=String[]) ``` Displays the list of rdataset names present in the package(s) provided """ function display_all_rdataset_names(package_name::Array{String,1} = String[]) rt.display_all_rdataset_names(package_name) end """ ```julia download(dataset; path::String="./", quiet::Bool=false, subdir::String="", debug::Bool=false, use_cache::Bool=false) ``` Download scripts for retriever. """ function download( dataset; path::String = "./", quiet::Bool = false, subdir::String = "", debug::Bool = false, use_cache::Bool = false, ) rt.download(dataset, path, quiet, subdir, debug, use_cache) end """ ```julia get_dataset_names_upstream(keywords::Array{String,1}=String[], licenses::Array{String,1}=String[], repo::String="") ``` Get dataset names upstream scripts. """ function get_dataset_names_upstream( keywords::Array{String,1} = String[], licenses::Array{String,1} = String[], repo::String = "", ) rt.get_dataset_names_upstream(keywords, licenses, repo) end """ ```julia get_rdataset_names() ``` Returns a list of all the available RDataset names present """ function get_rdataset_names() rt.get_rdataset_names() end """ ```julia get_script_citation(repo::String="") ``` Get citation for the data retriever or scripts. """ function get_script_citation(dataset::String = "") rt.get_script_citation(dataset) end """ ```julia get_script_upstream(dataset, repo::String="") ``` Get upstream retriever-recipe's scripts. """ function get_script_upstream(dataset, repo::String = "") rt.get_script_upstream(dataset, repo) end """ ```julia install_csv(dataset; table_name::String="", compile::Bool=false, data_dir=pwd(), debug::Bool=false, use_cache::Bool=true) ``` Install Retriever scripts in csv format. """ function install_csv( dataset; table_name::String = "{db}_{table}", data_dir = pwd(), debug::Bool = false, use_cache::Bool = true, ) rt.install_csv(dataset, table_name, data_dir, debug, use_cache) end """ ```julia install_json(dataset; table_name::String="", data_dir=pwd(), debug::Bool=false, use_cache::Bool=true) ``` Install Retriever scripts in json format. """ function install_json( dataset; table_name::String = "{db}_{table}.json", data_dir = pwd(), debug::Bool = false, use_cache::Bool = true, ) rt.install_json(dataset, table_name, data_dir, debug, use_cache) end """ ```julia install_msaccess(dataset; file::String="", table_name::String="", data_dir=pwd(), debug::Bool=false, use_cache::Bool=true) ``` Install Retriever scripts in msacces. """ function install_msaccess( dataset; file::String = "", table_name::String = "", data_dir = pwd(), debug::Bool = false, use_cache::Bool = true, ) rt.install_msaccess(dataset, file, table_name, data_dir, debug, quiet, use_cache) end """ ```julia install_mysql(dataset; user::String="root", password::String="", host::String="localhost", port::Int=3306, database_name::String="", table_name::String="", compile::Bool=false, debug::Bool=false, quiet::Bool=false, use_cache::Bool=true) ``` Install Retriever scripts in mysql database. """ function install_mysql( dataset; user::String = "root", password::String = "", host::String = "localhost", port::Int = 3306, database_name::String = "{db}", table_name::String = "{db}.{table}", debug::Bool = false, use_cache::Bool = true, ) rt.install_mysql( dataset, user, password, host, port, database_name, table_name, debug, use_cache, ) end """ ```julia install_postgres(dataset; user::String="postgres", password::String="", host::String="localhost", port::Int=5432, database::String="postgres", database_name::String="", table_name::String="", bbox::Any=[], debug::Bool=false, use_cache::Bool=true) ``` Install Retriever scripts in database. """ function install_postgres( dataset; user::String = "postgres", password::String = "", host::String = "localhost", port::Int = 5432, database::String = "postgres", database_name::String = "{db}", table_name::String = "{db}.{table}", bbox::Any = [], debug::Bool = false, use_cache::Bool = true, ) rt.install_postgres( dataset, user, password, host, port, database, database_name, table_name, bbox, debug, use_cache, ) end """ ```julia install_sqlite(dataset; file::String="", table_name::String="", data_dir=pwd(), debug::Bool=false, use_cache::Bool=true) ``` Install Retriever scripts in database. """ function install_sqlite( dataset; file::String = "", table_name::String = "{db}.{table}", data_dir = pwd(), debug::Bool = false, use_cache::Bool = true, ) return rt.install_sqlite(dataset, file, table_name, data_dir, debug, use_cache) end """ ```julia install_xml(dataset; table_name::String="", compile::Bool=false, data_dir=pwd(), debug::Bool=false, use_cache::Bool=true) ``` Install Retriever scripts in xml format. """ function install_xml( dataset; table_name::String = "{db}_{table}.xml", data_dir = pwd(), debug::Bool = false, use_cache::Bool = true, ) rt.install_xml(dataset, table_name, data_dir, debug, use_cache) end """ ```julia reload_scripts() ``` Retriever reload scripts. """ function reload_scripts() rt.reload_scripts() end """ ```julia reset_retriever(scope::String="all", ask_permission::Bool=true) ``` Retriever reset scripts or data or all. """ function reset_retriever(scope::String = "all", ask_permission::Bool = true) rt.reset_retriever(scope, ask_permission) end """ ```julia update_rdataset_catalog(test::Bool=false) ``` Updates the datasets_url.json from the github repo """ function update_rdataset_catalog(test::Bool = false) rt.update_rdataset_catalog(test) end """ ```julia update_rdataset_contents(data_obj::Dict{String, String}, package::String, dataset_name::String, json_file::Dict{String, String}) ``` Update the contents of json script """ function update_rdataset_contents( data_obj::Dict{String,String}, package::String, dataset_name::String, json_file::Dict{String,String}, ) rt.update_rdataset_contents(data_obj, package, dataset_name, json_file) end """ ```julia update_rdataset_script(data_obj, dataset_name, package, script_path) ``` Renames and updates the RDataset script """ function update_rdataset_script( data_obj::Dict{String,String}, dataset_name::String, package::String, script_path::String, ) rt.update_rdataset_script(data_obj, dataset_name, package, script_path) end end # module
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
code
147
# !/usr/bin/env julia using MySQL using Pkg using PyCall using Retriever using SQLite using Test # Run tests @time include("test_retriever.jl")
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
code
6477
#!/usr/bin/env julia os = pyimport("os") Retriever.check_for_updates() # datasets to test test_datasets = ["bird-size", "Iris"] # Service host names # Use service names on travis as host names else localhost # Set in Docker compose pgdb = mysqldb = "localhost" os_password = "" if haskey(ENV, "TRAVIS_OR_DOCKER") == true pgdb = "pgdb" mysqldb = "mysqldb" os_password = "Password12!" end sqlite_opts = Dict("engine" => "sqlite", "file" => "dbfile", "table_name" => "{db}.{table}") postgres_opts = Dict( "engine" => "postgres", "user" => "postgres", "host" => pgdb, "password" => os_password, "port" => 5432, "database" => "testdb", "database_name" => "testschema2", "table_name" => "{db}.{table}", ) csv_opts = Dict("engine" => "csv", "table_name" => "{db}_{table}.csv") mysql_opt = Dict( "engine" => "mysql", "user" => "travis", "password" => os_password, "host" => mysqldb, "port" => 3306, "database_name" => "testdb", "table_name" => "{db}.{table}", ) json_opt = Dict("engine" => "json", "table_name" => "{db}_{table}.json") xml_opt = Dict("engine" => "xml", "table_name" => "{db}_{table}.xml") function setup() # result end function teardown() end function reset_reload_scripts() # Test reset and reload_scripts dataset = test_datasets[0] Retriever.reset_retriever(dataset, ask_permission = false) Retriever.reload_scripts() @test dataset in rdataretriever::datasets()["offline"] == false Retriever.get_updates() Retriever.reload_scripts() @test dataset in rdataretriever::datasets()["offline"] == true end function empty_files(path, ext) for (root, dirs, files) in walkdir(path) for file in files relative_path = joinpath(root, file) if endswith(relative_path, ext) println(relative_path) @test filesize(relative_path) > 10 end end end end function dataset_name_upstream() # Test get_dataset_names_upstream using a list of keywords or licenses Retriever.reset_retriever(scope = "all", ask_permission = false) license_datasets = Retriever.get_dataset_names_upstream(licenses = ["CC0-1.0"]) @test "bird-size" in license_datasets == true keyword_datasets = Retriever.get_dataset_names_upstream(keywords = ["plants"]) @test "biodiversity-response" in keyword_datasets == true datasets = Retriever.get_dataset_names_upstream() @test "portal" in datasets == true end function install_csv_engine(data_arg) try mktempdir() do dir_tmp cd(dir_tmp) do # Install dataset into Json database Retriever.install_csv(data_arg, table_name = csv_opts["table_name"]) empty_files(dir_tmp, ".csv") end end return true catch return false end end my_tempdir = tempdir() @test isdir(my_tempdir) == true function install_json_engine(data_arg) try mktempdir() do dir_tmp cd(dir_tmp) do # Install dataset into Json database Retriever.install_json(data_arg, table_name = json_opt["table_name"]) empty_files(dir_tmp, ".json") end end return true catch return false end end function install_xml_engine(data_arg) try mktempdir() do dir_tmp cd(dir_tmp) do # Install dataset into Json database Retriever.install_xml(data_arg, table_name = xml_opt["table_name"]) empty_files(dir_tmp, ".xml") end end return true catch return false end end function install_mysql_engine(data_arg) try # Drop database conn = MySQL.connect( mysql_opt["host"], mysql_opt["user"], mysql_opt["password"], db = mysql_opt["database_name"], ) db = mysql_opt["database_name"] command = "DROP TABLE IF EXISTS $db" MySQL.Stmt(conn, command) # dframe = mysql_execute(con, command) MySQL.disconnect(conn) # Install dataset into mysql database Retriever.install_mysql( data_arg, user = mysql_opt["user"], password = mysql_opt["password"], host = mysql_opt["host"], port = mysql_opt["port"], database_name = mysql_opt["database_name"], table_name = mysql_opt["table_name"], ) return true catch return false end end function install_postgres_engine(data_arg::String) try # Use python to drop table. usr = postgres_opts["user"] prt = postgres_opts["port"] cmd = "psql -U $usr -d testdb -h $pgdb -p $prt -w -c" drop_sql = "\"DROP SCHEMA IF EXISTS testschema CASCADE\"" query_stm = "$cmd $drop_sql" os.system(query_stm) # Install dataset into mysql database Retriever.install_postgres( data_arg, user = postgres_opts["user"], password = postgres_opts["password"], host = postgres_opts["host"], port = postgres_opts["port"], database_name = postgres_opts["database_name"], table_name = postgres_opts["table_name"], ) return true catch return false end end function install_sqlite_engine(data_arg) try mktempdir() do dir_tmp cd(dir_tmp) do # Install dataset into SQLite database Retriever.install_sqlite( data_arg, file = sqlite_opts["file"], table_name = sqlite_opts["table_name"], ) return true end end catch return false end end @testset "Regression" begin @test true work_dir = pwd() for datset_n in test_datasets # Data DB test # MySQL is currently unstable, March 2020 # @test true == install_mysql_engine(datset_n) @test true == install_postgres_engine(datset_n) @test true == install_sqlite_engine(datset_n) # File engines use a temporary directory for tests @test true == install_csv_engine(datset_n) @test true == install_json_engine(datset_n) @test true == install_xml_engine(datset_n) end end # @testset Regression
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
docs
1294
Retriever v2.0.0 Release Notes ============================== New features and Changes ------------------------ Remove Travis and use GitHub actions Change default branch from master to main Update Kaggle API function Added tidycensus dataset Add support for clipping images Add Socrata API Added RDatasets API Add auto publish using CI Retriever v1.0.0 Release Notes ============================== New features and Changes ------------------------ * Add provenance support * Add get citation function * Change from mysql-client to mariadb-client * Install TagBot as a GitHub Action * Test get_dataset_names_upstream * Add Julia based retriever install to tutorial * Use pyimport_conda to automatically install retriever if not present * Autobuild documentation using Travis * Add support for Julia 1.0+ * Switch to new PyCall pyimport syntax Retriever v0.0.2 Release Notes ============================== New features and Changes ------------------------ * Add PostGis to docker-compose * Use Docker for tests * Make intro page as the default landing page * Add dependency explanation to the docs * Install data into custom director using data_dir option * Download data into custom directory using sub_dir * Add reload_scripts and reset_retriever
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
docs
5223
| **Documentation** | **PackageEvaluator** | **Build Status** | |:-------------------------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------:| | [![][docs-stable-img]][docs-stable-url] [![][docs-latest-img]][docs-latest-url] |[![][license-img]][license-url] | [![][GitHub-Actions-img]][GitHub-Actions-url] | [docs-stable-img]: https://img.shields.io/badge/docs-stable-green.svg [docs-stable-url]: https://weecology.github.io/Retriever.jl/stable/ [docs-latest-img]: https://img.shields.io/badge/docs-latest-blue.svg [docs-latest-url]: https://weecology.github.io/Retriever.jl/dev/ [GitHub-Actions-img]: https://github.com/weecology/Retriever.jl/actions/workflows/CI.yml/badge.svg [GitHub-Actions-url]: https://github.com/weecology/Retriever.jl/actions/workflows/CI.yml [license-img]: http://img.shields.io/badge/license-MIT-blue.svg [license-url]: https://raw.githubusercontent.com/weecology/Retriever.jl/main/LICENSE # Retriever The Julia wrapper for the Data Retriever software. The Data Retriever automates the tasks of finding, downloading, and cleaning up publicly available data, and then stores them in a local database or as .csv files. Simply put, it's a package manager for data. This enables data analysts to devote the majority of their time to analysis rather than data cleaning or management. ## Installation ### Deps - Python 3.7 and up - Julia 1.5+ is recommended - [PyCall](https://github.com/JuliaPy/PyCall.jl) - [Pkg](https://pkgdocs.julialang.org/v1/getting-started/) is needed, you can add packages using the `add` command or the `dev` command. ```julia pkg> add "[email protected]:JuliaPy/PyCall.jl.git ``` The Retriever.jl depends on a few Julia packages that will be installed automatically. Ensure that Pycall is using the same Python path where the retriever Python package is installed. You can change that path to a desired path as below. ```julia julia> ENV["PYTHON"]="Python path where the retriever python package is installed" # Build Pycall to enable the use of the new path Pkg.build("PyCall") ``` Install the core Python [retriever](https://github.com/weecology/retriever) package. If your Python path is set, you can use `Pip install retriever` or Use PyCall to install Python. ```julia # From release packages = retriever julia> run(`$(PyCall.pyprogramname) -m pip install --user -- $packages`) # Or from current dev branch julia> run(`$(PyCall.pyprogramname) -m pip install --user -- git+https://[email protected]/weecology/retriever.git`) ``` Install the Retriever Julia package. ```julia julia> Pkg.add("Retriever") ``` ### Install from a local source Download or checkout the source from the [github page](https://github.com/weecology/Retriever.jl.git). Go to `Retriever.jl` directory and. Run Julia. ```Julia julia> include("src/Retriever.jl") ``` Or use the [Pkg REPL](https://pkgdocs.julialang.org/v1/getting-started/) ```Julia pkg> add PyCall pkg> activate . using Retriever ``` ### Database Management Systems Depending on the database management system, you wish to use, follow the `Setting up servers` [documentation of the retriever](https://retriever.readthedocs.io/en/latest/developer.html#setting-up-servers). You can change the credentials to suit your server settings. ## Example of installing the Datasets ```julia # Using default parameter as the arguments julia> Retriever.install_postgres("iris") # Passing user specfic arguments julia> Retriever.install_postgres("iris", user = "postgres", password="Password12!", host="localhost", port=5432) ``` ```julia julia> Retriever.install_csv("iris") julia> Retriever.install_mysql("iris") julia> Retriever.install_sqlite("iris") julia> Retriever.install_msaccess("iris") julia> Retriever.install_json("iris") julia> Retriever.install_xml("iris") ``` Creating docs. To create docs, first refer to the [Documenter docs](https://juliadocs.github.io/Documenter.jl/stable/man/guide). To test the docs locally, run make.jl ```Shell julia --color=yes make.jl ``` or simply ```Shell julia make.jl ``` ## Using Docker To run tests using docker `docker-compose run --service-ports retrieverj julia test/runtests.jl` To run the image interactively `docker-compose run --service-ports retrieverj /bin/bash` To test docs in docker ` docker-compose run --service-ports retrieverj bash -c "cd docs && julia make.jl"` Acknowledgments --------------- Development of this software is funded by [the Gordon and Betty Moore Foundation's Data-Driven Discovery Initiative](http://www.moore.org/programs/science/data-driven-discovery) through [Grant GBMF4563](http://www.moore.org/grants/list/GBMF4563) to Ethan White and started as [Shivam Negi](https://www.linkedin.com/in/shivam-negi-64a227103/)'s [Google Summer of Code](https://summerofcode.withgoogle.com/)
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
docs
3193
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [INSERT EMAIL ADDRESS]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct/ [homepage]: https://www.contributor-covenant.org
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
docs
2191
# Developer documentation for Retriever Julia package Before you begin, make sure you have the retriever python package installed. Read about the [Pkg REPL](https://pkgdocs.julialang.org/v1/getting-started/) # All required packeges These packages will be installed once the Retriever.jl package is installed PyCall Compat DocStringExtensions Documenter MySQL Pkg SQLite Test JuliaFormatter ### PyCall Pycall julia is used to communicate with the retriever python package objects. ### Documenter Documenter tool is used for building documentation To test the documentations locally, install the current source ```Julia julia> include("src/Retriever.jl") ``` ### Tests Use Pkg REPL in the main directory ```Julia pkg> test ``` ### Linter ```Julia julia> using JuliaFormatter # Recursively formats all Julia files in the current directory julia> format(".") # Formats an individual file julia> format_file("foo.jl") ``` ### Register and Release Retriever ```Julia julia> ENV["PYTHON"]="Python path where retriever python package is installed" julia> Pkg.build("PyCall") julia> Pkg.add("PyCall") julia> Pkg.test("Retriever") julia> Pkg.update() julia> Pkg.add("PkgDev") julia> using PkgDev ``` ```Julia julia> PkgDev.register("Retriever") INFO: Registering Retriever at https://github.com/weecology/Retriever.jl.git INFO: Committing METADATA for Retriever ``` ```Julia julia> PkgDev.tag("Retriever") INFO: Tagging Retriever v0.0.1 ``` ```Julia julia> PkgDev.config() PkgDev.jl configuration: User name: provide git user name User email: provide git associated email Enter GitHub user [Defualt name]: Do you want to change this configuration? [N]:N ``` ```Shell julia> PkgDev.publish() INFO: Validating METADATA INFO: Creating a personal access token for Julia Package Manager on GitHub. You will be asked to provide credentials to your GitHub account. ...Git Credential authentication INFO: Pushing Retriever permanent tags: v0.0.1 INFO: Submitting METADATA changes INFO: Forking JuliaLang/METADATA.jl to henrykironde INFO: Pushing changes as branch pull-request/ceea745c INFO: To create a pull-request, open: https://[link to the Branch created] ```
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
docs
126
# Retriever Documentation Documentation for `Retriever.jl`'s interface. ## Modules ```@index Pages = ["lib/public.md"] ```
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
docs
1062
# Retriever Julia wrapper for the Data Retriever software. Data Retriever automates the tasks of finding, downloading, and cleaning up publicly available data, and then stores them in a local database or as .csv files. Simply put, it's a package manager for data. This allows data analysts to spend a majority of their time in analysing rather than in cleaning up or managing data. ## Installation To use Retriever, you first need to [install Retriever](https://www.data-retriever.org), a core python package. To install Retriever using the Julia package manager ```julia julia> Pkg.add("Retriever") ``` To install from Source, download or checkout the source from the [github page](https://github.com/weecology/Retriever.jl). Go to `Retriever.jl/src`. Run Julia. ```julia julia> include("Retriever.jl") ``` To create docs ``` julia --color=yes make.jl ``` or simply ``` julia make.jl ``` (Note: If you want help in installing Julia you can follow this [tutorial](https://medium.com/@shivamnegi2019/julia-beginners-guide-part-1-a9c369128c78)
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
docs
6301
# Data Retriever using Julia The wrapper module for [Data Retriever](https://www.data-retriever.org) has been implemented as [Retriever](https://github.com/weecology/Retriever.jl.git). All the functions work and feel the same as the python Retriever module. The module has been created using ``PyCall`` hence all the functions are analogous to the functions of Retriever python module. ## Installation To use Retriever, you first need to [install the core Python retriever package](https://www.data-retriever.org). The simplest way to do this is to let Julia install it into an isolated Python environment by setting an environmental variable prior to installation: ```julia julia> ENV["PYTHON"]="" julia> Pkg.add("Retriever") ``` Alternatively you can install it yourself using either `conda` or `pip` (Python's package managers) which will also provide access to the package in Python and the command line interface. ```bash conda install -c conda-forge retriever ``` ```bash pip install retriever ``` Then install the Julia package *without* setting the environmental variable: ```julia julia> Pkg.add("Retriever") ``` To install from Source, download or checkout the source from the [github page](https://github.com/weecology/Retriever.jl). Go to `Retriever.jl/src`. Run Julia. ```julia julia> include("Retriever.jl") ``` (Note: If you want help in installing Julia you can follow this [tutorial](https://medium.com/@shivamnegi2019/julia-beginners-guide-part-1-a9c369128c78) ## Tutorial The Retriever has both built-in and recipe scripts. The Retriever's built-in scripts as part of the installation. Each recipe provides the information to retriever on how to install a dataset. Recipes are contributed by a variety of users including data owners, data users, and the Retriever maintainers. Get list of all the available datasets in Retriever. ```julia """ Function Definition """ function dataset_names() ``` ```julia julia> Retriever.dataset_names() ``` Updating scripts to the latest version. ```julia """ Function Definition """ function check_for_updates() ``` ```julia julia> Retriever.check_for_updates() ``` Get list of datasets based on searching by keywords and licenses.. ```julia """ Function Definition """ function get_dataset_names_upstream(keywords::String="", licenses::String="", repo::String="") ``` ```julia julia> Retriever.get_dataset_names_upstream("birds data") ``` Get the recipe for a specific dataset. ```julia """ Function Definition """ function get_script_upstream(dataset, repo::String="") ``` ```julia julia> Retriever.get_script_upstream("fia-florida") ``` Reload scripts. ```julia """ Function Definition """ function reload_scripts() ``` ```julia julia> Retriever.reload_scripts() ``` Delete information stored by Retriever which could be scripts, connections or data. ```julia """ Function Definition """ function reset_retriever(; scope::AbstractString="all") ``` ```julia """ Using default variable all""" julia> Retriever.reset_retriever() """ Set scope as scripts """ julia> Retriever.reset_retriever(scope="scripts") ``` To download datasets the ``download`` function can be used. ```julia """ Function Definition """ function download(dataset; path::AbstractString="./", quite::Bool=false, subdir::Bool=false, use_cache::Bool=false, debug::Bool=false) ``` ```julia julia> Retriever.download("iris") ``` Installing scripts into engines. ```julia """ Function Definition """ function install_csv(dataset; table_name=nothing, compile::Bool=false, debug::Bool=false, quite::Bool=false, use_cache::Bool=true) function install_mysql(dataset; user::AbstractString="root", password::AbstractString="", host::AbstractString="localhost", port::Int=3306, database_name=nothing, table_name=nothing, compile::Bool=false, debug::Bool=false, quite::Bool=false, use_cache::Bool=true) function install_postgres(dataset; user::AbstractString="postgres", password::AbstractString="", host::AbstractString="localhost", port::Int=5432, database::AbstractString="postgres", database_name=nothing, table_name=nothing, compile::Bool=false, debug::Bool=false, quite::Bool=false, use_cache::Bool=true) function install_sqlite(dataset; file=nothing, table_name=nothing, compile::Bool=false, debug::Bool=false, quite::Bool=false, use_cache::Bool=true) function install_msaccess(dataset; file=nothing, table_name=nothing, compile::Bool=false, debug::Bool=false, quite::Bool=false, use_cache::Bool=true) function install_json(dataset; table_name=nothing, compile::Bool=false, debug::Bool=false, quite::Bool=false, use_cache::Bool=true) function install_xml(dataset; table_name=nothing, compile::Bool=false, debug::Bool=false, quite::Bool=false, use_cache::Bool=true) ``` ```julia julia> Retriever.install_csv("iris") julia> Retriever.install_mysql("iris") julia> Retriever.install_postgres("iris") julia> Retriever.install_sqlite("iris") julia> Retriever.install_msaccess("iris") julia> Retriever.install_json("iris") julia> Retriever.install_xml("iris") ``` ## Retriever Provenance Retriever allows committing of datasets and installation of the committed dataset into the database of your choice at a later date. This ensures that the previous outputs/results can be produced easily. Retriever supports committing of a dataset into a compressed archive. ```julia julia> Retriever.commit("portal") julia> Retriever.commit('abalone-age', 'First chapter data version 1') julia> Retriever.commit_log("portal") ``` You can install committed datasets by using the hash-value or by providing the path of the compressed archive. Installation using hash-value is supported only for datasets stored in the provenance directory. ```julia julia> Retriever.install_sqlite('abalone-age-02ee77.zip') julia> Retriever.install_sqlite('abalone-age', '02ee77') ```
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
2.0.0
7fd964d19a35488e51d0cc4db3f34614ab4a747b
docs
111
# Command Documentation ## Index ```@index Pages = ["public.md"] ``` ```@autodocs Modules = [Retriever] ```
Retriever
https://github.com/weecology/Retriever.jl.git
[ "MIT" ]
0.8.6
704ef2c93e301b6469ba63103a4e7bf935e6990c
code
978
using Documenter using ParallelUtilities DocMeta.setdocmeta!(ParallelUtilities, :DocTestSetup, :(using ParallelUtilities); recursive=true) makedocs(; modules=[ParallelUtilities], authors="Jishnu Bhattacharya", repo="https://github.com/jishnub/ParallelUtilities.jl/blob/{commit}{path}#L{line}", sitename="ParallelUtilities.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://jishnub.github.io/ParallelUtilities.jl", assets=String[], ), pages=[ "ParallelUtilities" => "index.md", "Mapreduce" => "pmapreduce.md", "Examples" => [ "pmapreduce" => "examples/pmapreduce.md", "SharedArrays" => "examples/sharedarrays.md", "Threads" => "examples/threads.md", ], "ClusterQueryUtils" => "clusterquery.md", "Reference" => "api.md", ], ) deploydocs(; repo="github.com/jishnub/ParallelUtilities.jl", )
ParallelUtilities
https://github.com/jishnub/ParallelUtilities.jl.git
[ "MIT" ]
0.8.6
704ef2c93e301b6469ba63103a4e7bf935e6990c
code
729
module PMapReduceTiming using ParallelUtilities using Distributed function initialize(sleeptime) A = Array{Int}(undef, 20, 20) for ind in eachindex(A) sleep(sleeptime) A[ind] = ind end return A end function main_mapreduce(sleeptime) mapreduce(x -> initialize(sleeptime), hcat, 1:20) end function main_pmapreduce(sleeptime) pmapreduce(x -> initialize(sleeptime), hcat, 1:20) end function compare_with_serial() # precompile main_mapreduce(0) main_pmapreduce(0) # time println("Tesing serial") A = @time main_mapreduce(5e-6) println("Tesing parallel") B = @time main_pmapreduce(5e-6) # check results println("Results match : ", A == B) end end
ParallelUtilities
https://github.com/jishnub/ParallelUtilities.jl.git
[ "MIT" ]
0.8.6
704ef2c93e301b6469ba63103a4e7bf935e6990c
code
1431
module SharedArraysTiming using ParallelUtilities using SharedArrays using Distributed function initialize_localpart(s, sleeptime) for ind in localindices(s) sleep(sleeptime) s[ind] = ind end end function initializenode_sharedarray(sleeptime) pids = ParallelUtilities.workers_myhost() s = SharedArray{Int}((2_000,), pids = pids) @sync for p in pids @spawnat p initialize_localpart(s, sleeptime) end return sdata(s) end function initialize_serial(sleeptime) pids = ParallelUtilities.workers_myhost() s = Array{Int}(undef, 2_000) for ind in eachindex(s) sleep(sleeptime) s[ind] = ind end return sdata(s) end function main_sharedarray(sleeptime) workers_node_pool = ParallelUtilities.workerpool_nodes() nw_node = nworkers(workers_node_pool) pmapreduce(x -> initializenode_sharedarray(sleeptime), hcat, workers_node_pool, 1:nw_node) end function main_serial(sleeptime) workers_node_pool = ParallelUtilities.workerpool_nodes() nw_node = nworkers(workers_node_pool) mapreduce(x -> initialize_serial(sleeptime), hcat, 1:nw_node) end function compare_with_serial() # precompile main_serial(0) main_sharedarray(0) # time println("Testing serial") A = @time main_serial(5e-3) println("Testing sharedarray") B = @time main_sharedarray(5e-3) println("Results match : ", A == B) end end
ParallelUtilities
https://github.com/jishnub/ParallelUtilities.jl.git
[ "MIT" ]
0.8.6
704ef2c93e301b6469ba63103a4e7bf935e6990c
code
1133
module ThreadsTiming using ParallelUtilities using Distributed function initialize_serial(sleeptime) s = zeros(Int, 2_000) for ind in eachindex(s) sleep(sleeptime) s[ind] = ind end return s end function initializenode_threads(sleeptime) s = zeros(Int, 2_000) Threads.@threads for ind in eachindex(s) sleep(sleeptime) s[ind] = ind end return s end function main_threads(sleeptime) workers_node_pool = ParallelUtilities.workerpool_nodes() nw_nodes = nworkers(workers_node_pool) pmapreduce(x -> initializenode_threads(sleeptime), hcat, workers_node_pool, 1:nw_nodes) end function main_serial(sleeptime) workers_node_pool = ParallelUtilities.workerpool_nodes() nw_nodes = nworkers(workers_node_pool) mapreduce(x -> initialize_serial(sleeptime), hcat, 1:nw_nodes) end function compare_with_serial() # precompile main_serial(0) main_threads(0) # time println("Testing serial") A = @time main_serial(5e-3); println("Testing threads") B = @time main_threads(5e-3); println("Results match : ", A == B) end end
ParallelUtilities
https://github.com/jishnub/ParallelUtilities.jl.git
[ "MIT" ]
0.8.6
704ef2c93e301b6469ba63103a4e7bf935e6990c
code
539
module ParallelUtilities using Distributed using SplittablesBase export pmapreduce export pmapreduce_productsplit export pmapbatch export pmapbatch_productsplit export workerrank include("productsplit.jl") include("clusterquery.jl") using .ClusterQueryUtils: procs_node using .ClusterQueryUtils: workerpool_nodes using .ClusterQueryUtils: workers_myhost using .ClusterQueryUtils: workersactive using .ClusterQueryUtils: maybetrimmedworkerpool include("trees.jl") include("reductionfunctions.jl") include("mapreduce.jl") end # module
ParallelUtilities
https://github.com/jishnub/ParallelUtilities.jl.git
[ "MIT" ]
0.8.6
704ef2c93e301b6469ba63103a4e7bf935e6990c
code
4342
module ClusterQueryUtils using Distributed using DataStructures export hostnames export nodenames export procs_node export nprocs_node export workersactive export chooseworkers export maybetrimmedworkerpool export workerpool_nodes export workers_myhost """ hostnames([procs = workers()]) Return the hostname of each worker in `procs`. This is obtained by evaluating `Libc.gethostname()` on each worker asynchronously. """ function hostnames(procs = workers()) hostnames = Vector{String}(undef, length(procs)) @sync for (ind,p) in enumerate(procs) @async hostnames[ind] = @fetchfrom p Libc.gethostname() end return hostnames end """ nodenames([procs = workers()]) Return the unique hostnames that the workers in `procs` lie on. On an HPC system these are usually the hostnames of the nodes involved. """ nodenames(procs = workers()) = nodenames(hostnames(procs)) function nodenames(hostnames::AbstractVector{String}) unique(hostnames) end """ procs_node([procs = workers()]) Return the worker ids on each host of the cluster. On an HPC system this would return the workers on each node. """ function procs_node(procs = workers()) hosts = hostnames(procs) nodes = nodenames(hosts) procs_node(procs, hosts, nodes) end function procs_node(procs, hosts, nodes) OrderedDict(node => procs[findall(isequal(node),hosts)] for node in nodes) end """ nprocs_node([procs = workers()]) Return the number of workers on each host. On an HPC system this would return the number of workers on each node. """ function nprocs_node(procs = workers()) nprocs_node(hostnames(procs)) end function nprocs_node(hostnames::AbstractVector{String}) nodes = nodenames(hostnames) nprocs_node(hostnames, nodes) end function nprocs_node(hostnames::AbstractVector, nodes::AbstractVector) OrderedDict(node => count(isequal(node), hostnames) for node in nodes) end function nprocs_node(d::AbstractDict) OrderedDict(node => length(procs) for (node, procs) in d) end function workersactive(pool::AbstractWorkerPool, len::Integer, workers_on_hosts::AbstractDict = procs_node(workers(pool))) nw = min(nworkers(pool), len) chooseworkers(workers(pool), len, workers_on_hosts) end function chooseworkers(workerspool, n::Integer, workers_on_hosts::AbstractDict = procs_node(workerspool)) n >= 1 || throw(ArgumentError("number of workers to choose must be >= 1")) length(workerspool) <= n && return workerspool myhost = Libc.gethostname() if myhost in keys(workers_on_hosts) if length(workers_on_hosts[myhost]) >= n return workers_on_hosts[myhost][1:n] else w_chosen = workers_on_hosts[myhost] np_left = n - length(w_chosen) for (host, workers_host) in workers_on_hosts np_left <= 0 && break host == myhost && continue workers_host_section = @view workers_host[1:min(length(workers_host), np_left)] w_chosen = vcat(w_chosen, workers_host_section) np_left -= length(workers_host_section) end return w_chosen end else return workerspool[1:n] end end function maybetrimmedworkerpool(workers, N) w = chooseworkers(workers, N) WorkerPool(w) end """ workerpool_nodes([pool::AbstractWorkerPool = WorkerPool(workers())]) Return a `WorkerPool` with one worker per machine/node of the cluster. """ workerpool_nodes(pool::AbstractWorkerPool) = WorkerPool(oneworkerpernode(workers(pool))) workerpool_nodes() = WorkerPool(oneworkerpernode(workers())) """ oneworkerpernode([workers::AbstractVector{<:Integer} = workers()]) Return a subsample of workers such that each `pid` in the returned vector is located on one machine/node of the cluster. """ function oneworkerpernode(workers::AbstractVector{<:Integer} = workers()) workers_on_hosts = procs_node(workers) [first(v) for v in values(workers_on_hosts)] end """ workers_myhost([workers::AbstractVector{<:Integer} = workers()]) Return a list of all workers that are on the local machine/node of the cluster. """ workers_myhost(workers::AbstractVector{<:Integer} = workers()) = procs_node(workers)[Libc.gethostname()] workers_myhost(pool::AbstractWorkerPool) = workers_myhost(workers(pool)) end
ParallelUtilities
https://github.com/jishnub/ParallelUtilities.jl.git