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.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 6370 | module HybridArrays
import Base: convert,
copy,
copyto!,
hcat,
vcat,
similar,
axes,
getindex,
dataids,
promote_rule,
pointer,
strides,
setindex!,
size,
length,
+,
-,
*
import Base.Array
using StaticArrays
using StaticArrays: Dynamic, StaticIndexing
import StaticArrays: _setindex!_scalar, Size
using LinearAlgebra
using Requires
@generated function hasdynamic(::Type{Size}) where Size<:Tuple
for s ∈ Size.parameters
if isa(s, Dynamic)
return true
end
end
return false
end
function all_dynamic_fixed_val(::Type{Tuple{}})
return Val(:dynamic_fixed_true)
end
function all_dynamic_fixed_val(::Type{Size}) where Size<:Tuple
return error("No indices given for size $Size")
end
function all_dynamic_fixed_val(::Type{Size}, inds::StaticArrays.StaticIndexing{<:Union{Int, AbstractArray, Colon}}...) where Size<:Tuple
return all_dynamic_fixed_val(Size, map(StaticArrays.unwrap, inds)...)
end
@generated function all_dynamic_fixed_val(::Type{Size}, inds::Union{Int, AbstractArray, Colon}...) where Size<:Tuple
all_fixed = true
for (i, param) in enumerate(Size.parameters)
destatizing = (inds[i] <: AbstractArray && !(
inds[i] <: StaticArray ||
inds[i] <: Base.Slice ||
inds[i] <: SOneTo))
nonstatizing = inds[i] == Colon || inds[i] <: Base.Slice || destatizing
if destatizing || (isa(param, Dynamic) && nonstatizing)
all_fixed = false
break
end
end
if all_fixed
return Val(:dynamic_fixed_true)
else
return Val(:dynamic_fixed_false)
end
end
function has_dynamic(::Type{Size}) where Size<:Tuple
for param in Size.parameters
if isa(param, Dynamic)
return true
end
end
return false
end
@generated function all_dynamic_fixed_val(::Type{Size}, inds::Union{Colon, Base.Slice}) where Size<:Tuple
if has_dynamic(Size)
return Val(:dynamic_fixed_false)
else
return Val(:dynamic_fixed_true)
end
end
@generated function tuple_nodynamic_prod(::Type{Size}) where Size<:Tuple
i = 1
for s ∈ Size.parameters
if !isa(s, Dynamic)
i *= s
end
end
return i
end
# conversion of SizedArray from StaticArrays.jl
"""
HybridArray{Tuple{dims...}}(array)
Wraps an `AbstractArray` with a combination of static and dynamic sizes,
so to take advantage of the (faster) methods defined by the StaticArrays
package. The size is checked once upon construction to determine if the
number of elements (`length`) match, but the array may be reshaped.
"""
struct HybridArray{S<:Tuple, T, N, M, TData<:AbstractArray{T,M}} <: AbstractArray{T, N}
data::TData
function HybridArray{S, T, N, M, TData}(a::TData) where {S, T, N, M, TData<:AbstractArray{T,M}}
tnp = tuple_nodynamic_prod(S)
lena = length(a)
dynamic_nodivisible = hasdynamic(S) && tnp != 0 && mod(lena, tnp) != 0
nodynamic_notequal = !hasdynamic(S) && lena != StaticArrays.tuple_prod(S)
if nodynamic_notequal || dynamic_nodivisible || (tnp == 0 && lena != 0)
error("Dimensions $(size(a)) don't match static size $S")
end
new{S,T,N,M,TData}(a)
end
function HybridArray{S, T, N, 1}(::UndefInitializer) where {S, T, N}
new{S, T, N, 1, Array{T, 1}}(Array{T, 1}(undef, StaticArrays.tuple_prod(S)))
end
function HybridArray{S, T, N, N}(::UndefInitializer) where {S, T, N}
new{S, T, N, N, Array{T, N}}(Array{T, N}(undef, size_to_tuple(S)...))
end
end
@inline HybridArray{S,T,N}(a::TData) where {S,T,N,M,TData<:AbstractArray{T,M}} = HybridArray{S,T,N,M,TData}(a)
@inline HybridArray{S,T}(a::TData) where {S,T,M,TData<:AbstractArray{T,M}} = HybridArray{S,T,StaticArrays.tuple_length(S),M,TData}(a)
@inline HybridArray{S}(a::TData) where {S,T,M,TData<:AbstractArray{T,M}} = HybridArray{S,T,StaticArrays.tuple_length(S),M,TData}(a)
@inline HybridArray{S,T,N}(::UndefInitializer) where {S,T,N} = HybridArray{S,T,N,N}(undef)
@inline HybridArray{S,T}(::UndefInitializer) where {S,T} = HybridArray{S,T,StaticArrays.tuple_length(S),StaticArrays.tuple_length(S)}(undef)
@inline HybridArray{S,T}(::UndefInitializer, d::Integer...) where {S,T} = HybridArray{S,T}(Array{T}(undef, d))
@generated function (::Type{HybridArray{S,T,N,M,TData}})(x::NTuple{L,Any}) where {S,T,N,M,TData,L}
if L != StaticArrays.tuple_prod(S)
error("Dimension mismatch")
end
exprs = [:(a[$i] = x[$i]) for i = 1:L]
return quote
$(Expr(:meta, :inline))
a = HybridArray{S,T,N,M}(undef)
@inbounds $(Expr(:block, exprs...))
return a
end
end
@inline HybridArray{S,T,N}(x::Tuple) where {S,T,N} = HybridArray{S,T,N,N,Array{T,N}}(x)
@inline HybridArray{S,T}(x::Tuple) where {S,T} = HybridArray{S,T,StaticArrays.tuple_length(S)}(x)
@inline HybridArray{S}(x::NTuple{L,T}) where {S,T,L} = HybridArray{S,T}(x)
HybridVector{S,T,M} = HybridArray{Tuple{S},T,1,M}
@inline HybridVector{S}(a::TData) where {S,T,M,TData<:AbstractArray{T,M}} = HybridArray{Tuple{S},T,1,M,TData}(a)
@inline HybridVector{S}(x::NTuple{L,T}) where {S,T,L} = HybridArray{Tuple{S},T,1,1,Vector{T}}(x)
@inline HybridVector{S,T}(::UndefInitializer, d::Integer) where {S,T} = HybridVector{S,T}(Vector{T}(undef, d))
HybridMatrix{S1,S2,T,M} = HybridArray{Tuple{S1,S2},T,2,M}
@inline HybridMatrix{S1,S2}(a::TData) where {S1,S2,T,M,TData<:AbstractArray{T,M}} = HybridArray{Tuple{S1,S2},T,2,M,TData}(a)
@inline HybridMatrix{S1,S2}(x::NTuple{L,T}) where {S1,S2,T,L} = HybridArray{Tuple{S1,S2},T,2,2,Matrix{T}}(x)
@inline HybridMatrix{S1,S2,T}(::UndefInitializer, d1::Integer, d2::Integer) where {S1,S2,T} = HybridMatrix{S1,S2,T}(Matrix{T}(undef, d1, d2))
export HybridArray, HybridMatrix, HybridVector
include("SSubArray.jl")
include("abstractarray.jl")
include("arraymath.jl")
include("broadcast.jl")
include("convert.jl")
include("indexing.jl")
include("linalg.jl")
include("utils.jl")
function __init__()
@require ArrayInterface="4fba245c-0d91-5ea0-9b3e-6abc04ee57a9" begin
include("array_interface_compat.jl")
end
@require StaticArrayInterface="0d7ed370-da01-4f52-bd93-41d350b8b718" begin
include("static_array_interface_compat.jl")
end
end
end # module
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 72 |
const SSubArray{S,T,N,P,I,L} = SizedArray{S,T,N,N,SubArray{T,N,P,I,L}}
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 4031 |
@inline Base.parent(sa::HybridArray) = sa.data
Base.dataids(sa::HybridArray) = Base.dataids(parent(sa))
@inline Base.elsize(sa::HybridArray) = Base.elsize(parent(sa))
@inline size(sa::HybridArray{S,T,N,N}) where {S<:Tuple,T,N} = size(parent(sa))
@inline length(sa::HybridArray) = length(parent(sa))
@inline strides(sa::HybridArray{S,T,N,N}) where {S<:Tuple,T,N} = strides(parent(sa))
@inline pointer(sa::HybridArray) = pointer(parent(sa))
@generated function _sized_abstract_array_axes(::Type{S}, ax::Tuple) where {S<:Tuple}
exprs = Any[]
map(enumerate(S.parameters)) do (i, si)
if isa(si, Dynamic)
push!(exprs, :(ax[$i]))
else
push!(exprs, SOneTo(si))
end
end
return Expr(:tuple, exprs...)
end
function axes(sa::HybridArray{S}) where {S<:Tuple}
ax = axes(parent(sa))
return _sized_abstract_array_axes(S, ax)
end
function promote_rule(::Type{<:HybridArray{S,T,N,M,TDataA}}, ::Type{<:HybridArray{S,U,N,M,TDataB}}) where {S<:Tuple,T,U,N,M,TDataA,TDataB}
TU = promote_type(T,U)
HybridArray{S,TU,N,M,promote_type(TDataA, TDataB)::Type{<:AbstractArray{TU}}}
end
@inline copy(a::HybridArray{S, T, N, M}) where {S<:Tuple, T, N, M} = begin
parentcopy = copy(parent(a))
HybridArray{S, T, N, M, typeof(parentcopy)}(parentcopy)
end
homogenized_last(::StaticArrays.HeterogeneousBaseShape) = StaticArrays.Dynamic()
homogenized_last(a::SOneTo) = last(a)
hybrid_homogenize_shape(::Tuple{}) = ()
hybrid_homogenize_shape(shape::Tuple{Vararg{StaticArrays.HeterogeneousShape}}) = Size(map(homogenized_last, shape))
hybrid_homogenize_shape(shape::Tuple{Vararg{StaticArrays.HeterogeneousBaseShape}}) = map(last, shape)
similar(a::HA, ::Type{T2}) where {S, HA<:HybridArray{S}, T2} = HybridArray{S, T2}(similar(parent(a), T2))
function similar(a::HybridArray, ::Type{T2}, shape::StaticArrays.HeterogeneousShapeTuple) where {T2}
s = hybrid_homogenize_shape(shape)
HT = hybridarray_similar_type(T2, s, StaticArrays.length_val(s))
return HT(similar(a.data, T2, shape))
end
function similar(a::HybridArray, shape::StaticArrays.HeterogeneousShapeTuple)
return similar(a, eltype(a), shape)
end
function similar(a::HybridArray, ::Type{T2}, shape::Tuple{SOneTo, Vararg{SOneTo}}) where {T2}
return similar(a.data, T2, StaticArrays.homogenize_shape(shape))
end
function similar(a::HybridArray, shape::Tuple{SOneTo, Vararg{SOneTo}})
return similar(a.data, StaticArrays.homogenize_shape(shape))
end
similar(::Type{<:HybridArray{S,T,N,M}},::Type{T2}) where {S,T,N,M,T2} = HybridArray{S,T2,N,M}(undef)
similar(::Type{SA},::Type{T},s::Size{S}) where {SA<:HybridArray,T,S} = hybridarray_similar_type(T,s,StaticArrays.length_val(s))(undef)
hybridarray_similar_type(::Type{T},s::Size{S},::Type{Val{D}}) where {T,S,D} = HybridArray{Tuple{S...},T,D,length(s)}
#disambiguation
function similar(a::HybridArray, t::Type{T2}, i::Tuple{Union{Integer, Base.OneTo}, Vararg{Union{Integer, Base.OneTo}}}) where T2
return invoke(similar, Tuple{AbstractArray, Type, Tuple{Union{Integer, Base.OneTo}, Vararg{Union{Integer, Base.OneTo}}}}, a, t, i)
end
function similar(a::HybridArray, t::Type{T2}, i::Tuple{Int64, Vararg{Int64}}) where T2
return invoke(similar, Tuple{AbstractArray, Type, Tuple{Int64, Vararg{Int64}}}, a, t, i)
end
# for internal use only (used in vcat and hcat)
# TODO: try to make this less hacky
# adding method to similar_type ends up being used in broadcasting for some reason?
_h_similar_type(::Type{A},::Type{T},s::Size{S}) where {A<:HybridArray,T,S} = hybridarray_similar_type(T,s,StaticArrays.length_val(s))
Size(::Type{<:HybridArray{S}}) where {S} = Size(S)
Base.IndexStyle(a::HybridArray) = Base.IndexStyle(parent(a))
Base.IndexStyle(::Type{HA}) where {S,T,N,M,TData,HA<:HybridArray{S,T,N,M,TData}} = Base.IndexStyle(TData)
Base.vec(a::HybridArray) = vec(parent(a))
StaticArrays.similar_type(::Type{<:SSubArray},::Type{T},s::Size{S}) where {S,T} = StaticArrays.default_similar_type(T,s,StaticArrays.length_val(s))
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 541 |
function ArrayInterface.ismutable(::Type{HybridArray{S,T,N,M,TData}}) where {S,T,N,M,TData}
return ArrayInterface.ismutable(TData)
end
function ArrayInterface.can_setindex(::Type{HybridArray{S,T,N,M,TData}}) where {S,T,N,M,TData}
return ArrayInterface.can_setindex(TData)
end
function ArrayInterface.parent_type(::Type{HybridArray{S,T,N,M,TData}}) where {S,T,N,M,TData}
return TData
end
function ArrayInterface.restructure(x::HybridArray{S}, y) where {S}
return HybridArray{S}(reshape(convert(Array, y), size(x)...))
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 668 |
Base.one(A::HA) where {HA<:HybridMatrix} = HA(one(parent(A)))
# This should make one(sized subarray) return SArray
@inline function StaticArrays._construct_sametype(a::Type{<:SSubArray{Tuple{S,S},T}}, elements) where {S,T}
return SMatrix{S,S,T}(elements)
end
@inline function StaticArrays._construct_sametype(a::SSubArray{Tuple{S,S},T}, elements) where {S,T}
return SMatrix{S,S,T}(elements)
end
Base.fill!(A::HybridArray, x) = fill!(parent(A), x)
@inline function Base.zero(a::HybridArray{S}) where {S}
return HybridArray{S}(zero(parent(a)))
end
@inline function Base.zero(a::SSubArray{S,T}) where {S,T}
return StaticArrays.zeros(SArray{S,T})
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 6189 |
import Base.Broadcast: BroadcastStyle
using Base.Broadcast: AbstractArrayStyle, Broadcasted, DefaultArrayStyle, _broadcast_getindex
# combine_sizes moved from StaticArrays after https://github.com/JuliaArrays/StaticArrays.jl/pull/1008
# see also https://github.com/JuliaArrays/HybridArrays.jl/issues/50
@generated function combine_sizes(s::Tuple{Vararg{Size}})
sizes = [sz.parameters[1] for sz ∈ s.parameters]
ndims = 0
for i = 1:length(sizes)
ndims = max(ndims, length(sizes[i]))
end
newsize = StaticArrays.StaticDimension[Dynamic() for _ = 1 : ndims]
for i = 1:length(sizes)
s = sizes[i]
for j = 1:length(s)
if s[j] isa Dynamic
continue
elseif newsize[j] isa Dynamic || newsize[j] == 1
newsize[j] = s[j]
elseif newsize[j] ≠ s[j] && s[j] ≠ 1
throw(DimensionMismatch("Tried to broadcast on inputs sized $sizes"))
end
end
end
quote
Base.@_inline_meta
Size($(tuple(newsize...)))
end
end
function broadcasted_index(oldsize, newindex)
index = ones(Int, length(oldsize))
for i = 1:length(oldsize)
if oldsize[i] != 1
index[i] = newindex[i]
end
end
return LinearIndices(oldsize)[index...]
end
scalar_getindex(x) = x
scalar_getindex(x::Ref) = x[]
# Add a new BroadcastStyle for StaticArrays, derived from AbstractArrayStyle
# A constructor that changes the style parameter N (array dimension) is also required
struct HybridArrayStyle{N} <: AbstractArrayStyle{N} end
HybridArrayStyle{M}(::Val{N}) where {M,N} = HybridArrayStyle{N}()
BroadcastStyle(::Type{<:HybridArray{<:Tuple, <:Any, N}}) where {N} = HybridArrayStyle{N}()
# Precedence rules
BroadcastStyle(::HybridArray{M}, ::DefaultArrayStyle{N}) where {M,N} =
DefaultArrayStyle(Val(max(M, N)))
BroadcastStyle(::HybridArray{M}, ::DefaultArrayStyle{0}) where {M} =
HybridArrayStyle{M}()
BroadcastStyle(::HybridArray{M}, ::StaticArrays.StaticArrayStyle{N}) where {M,N} =
StaticArrays.Hybrid(Val(max(M, N)))
BroadcastStyle(::HybridArray{M}, ::StaticArrays.StaticArrayStyle{0}) where {M} =
HybridArrayStyle{M}()
# copy overload
@inline function Base.copy(B::Broadcasted{HybridArrayStyle{M}}) where M
flat = Broadcast.flatten(B); as = flat.args; f = flat.f
argsizes = StaticArrays.broadcast_sizes(as...)
destsize = combine_sizes(argsizes)
if Length(destsize) === Length{StaticArrays.Dynamic()}()
# destination dimension cannot be determined statically; fall back to generic broadcast
return HybridArray{StaticArrays.size_tuple(destsize)}(copy(convert(Broadcasted{DefaultArrayStyle{M}}, B)))
end
_broadcast(f, destsize, argsizes, as...)
end
# copyto! overloads
@inline Base.copyto!(dest, B::Broadcasted{<:HybridArrayStyle}) = _copyto!(dest, B)
@inline Base.copyto!(dest::AbstractArray, B::Broadcasted{<:HybridArrayStyle}) = _copyto!(dest, B)
@inline function _copyto!(dest, B::Broadcasted{HybridArrayStyle{M}}) where M
flat = Broadcast.flatten(B); as = flat.args; f = flat.f
argsizes = StaticArrays.broadcast_sizes(as...)
destsize = combine_sizes((Size(dest), argsizes...))
if Length(destsize) === Length{StaticArrays.Dynamic()}()
# destination dimension cannot be determined statically; fall back to generic broadcast!
return copyto!(dest, convert(Broadcasted{DefaultArrayStyle{M}}, B))
end
_s_broadcast!(f, destsize, dest, argsizes, as...)
end
broadcast_getindex(::Tuple{}, i::Int, I::CartesianIndex) = return :(_broadcast_getindex(a[$i], $I))
broadcast_getindex(::Tuple{Dynamic}, i::Int, I::CartesianIndex) = return :(_broadcast_getindex(a[$i], $I))
function broadcast_getindex(oldsize::Tuple, i::Int, newindex::CartesianIndex)
li = LinearIndices(oldsize)
ind = _broadcast_getindex(li, newindex)
return :(a[$i][$ind])
end
@generated function _s_broadcast!(f, ::Size{newsize}, dest::AbstractArray, s::Tuple{Vararg{Size}}, a...) where {newsize}
sizes = [sz.parameters[1] for sz in s.parameters]
indices = CartesianIndices(newsize)
exprs = similar(indices, Expr)
for (j, current_ind) ∈ enumerate(indices)
exprs_vals = (broadcast_getindex(sz, i, current_ind) for (i, sz) in enumerate(sizes))
exprs[j] = :(dest[$j] = f($(exprs_vals...)))
end
return quote
Base.@_inline_meta
@inbounds $(Expr(:block, exprs...))
return dest
end
end
@generated function _broadcast(f, ::Size{newsize}, s::Tuple{Vararg{Size}}, a...) where newsize
first_staticarray = 0
for i = 1:length(a)
if a[i] <: StaticArray
first_staticarray = a[i]
break
end
end
if first_staticarray == 0
for i = 1:length(a)
if a[i] <: HybridArray
first_staticarray = a[i]
break
end
end
end
exprs = Array{Expr}(undef, newsize)
more = prod(newsize) > 0
current_ind = ones(Int, length(newsize))
sizes = [sz.parameters[1] for sz ∈ s.parameters]
make_expr(i) = begin
if !(a[i] <: AbstractArray)
return :(scalar_getindex(a[$i]))
elseif hasdynamic(Tuple{sizes[i]...})
return :(a[$i][$(current_ind...)])
else
:(a[$i][$(broadcasted_index(sizes[i], current_ind))])
end
end
while more
exprs_vals = [make_expr(i) for i = 1:length(sizes)]
exprs[current_ind...] = :(f($(exprs_vals...)))
# increment current_ind (maybe use CartesianIndices?)
current_ind[1] += 1
for i ∈ 1:length(newsize)
if current_ind[i] > newsize[i]
if i == length(newsize)
more = false
break
else
current_ind[i] = 1
current_ind[i+1] += 1
end
else
break
end
end
end
return quote
Base.@_inline_meta
@inbounds elements = tuple($(exprs...))
@inbounds return similar_type($first_staticarray, eltype(elements), Size(newsize))(elements)
end
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 3195 |
Base.@propagate_inbounds (::Type{HybridArray{S,T,N,M,TData}})(a::AbstractArray) where {S,T,N,M,TData<:AbstractArray{<:Any,M}} = convert(HybridArray{S,T,N,M,TData}, a)
Base.@propagate_inbounds (::Type{HybridArray{S,T,N,M}})(a::AbstractArray) where {S,T,N,M} = convert(HybridArray{S,T,N,M}, a)
Base.@propagate_inbounds (::Type{HybridArray{S,T,N}})(a::AbstractArray) where {S,T,N} = convert(HybridArray{S,T,N}, a)
Base.@propagate_inbounds (::Type{HybridArray{S,T}})(a::AbstractArray) where {S,T} = convert(HybridArray{S,T}, a)
# Overide some problematic default behaviour
@inline convert(::Type{SA}, sa::HybridArray) where {SA<:HybridArray} = SA(parent(sa))
@inline convert(::Type{SA}, sa::SA) where {SA<:HybridArray} = sa
# Back to Array (unfortunately need both convert and construct to overide other methods)
@inline Array(sa::HybridArray{S}) where {S} = Array(parent(sa))
@inline Array{T}(sa::HybridArray{S,T}) where {T,S} = Array{T}(parent(sa))
@inline Array{T,N}(sa::HybridArray{S,T,N}) where {T,S,N} = Array{T,N}(parent(sa))
@inline convert(::Type{Array}, sa::HybridArray) = convert(Array, parent(sa))
@inline convert(::Type{Array{T}}, sa::HybridArray{S,T}) where {T,S} = convert(Array, parent(sa))
@inline convert(::Type{Array{T,N}}, sa::HybridArray{S,T,N}) where {T,S,N} = convert(Array, parent(sa))
@inline convert(::Type{Array{T,N} where T}, sa::HybridArray{S}) where {S,N} = convert(Array, parent(sa))
function check_compatible_sizes(::Type{S}, a::NTuple{N,Int}) where {S,N}
st = size_to_tuple(S)
for (s1, s2) ∈ zip(st, a)
if !isa(s1, Dynamic) && s1 != s2
error("Array $a has size incompatible with $S.")
end
end
return true
end
@inline function convert(::Type{HybridArray{S,T,N,M,TData}}, a::AbstractArray{<:Any,M}) where {S,T,N,M,U,TData<:AbstractArray{U,M}}
check_compatible_sizes(S, size(a))
as = convert(TData, a)
return HybridArray{S,T,N,M,TData}(as)
end
@inline function convert(::Type{HybridArray{S,T,N,M}}, a::TData) where {S,T,N,M,U,TData<:AbstractArray{U,M}}
check_compatible_sizes(S, size(a))
as = similar(a, T)
copyto!(as, a)
return HybridArray{S,T,N,M,typeof(as)}(as)
end
@inline function convert(::Type{HybridArray{S,T,N,M}}, a::TData) where {S,T,N,M,TData<:AbstractArray{T,M}}
check_compatible_sizes(S, size(a))
return HybridArray{S,T,N,M,typeof(a)}(a)
end
@inline function convert(::Type{HybridArray{S,T,N}}, a::TData) where {S,T,N,M,U,TData<:AbstractArray{U,M}}
check_compatible_sizes(S, size(a))
as = similar(a, T)
copyto!(as, a)
return HybridArray{S,T,N,M,typeof(as)}(as)
end
@inline function convert(::Type{HybridArray{S,T}}, a::AbstractArray) where {S,T}
return convert(HybridArray{S,T,StaticArrays.tuple_length(S)}, a)
end
@inline function convert(::Type{HybridArray{S,T,N}}, a::TData) where {S,T,N,M,TData<:AbstractArray{T,M}}
check_compatible_sizes(S, size(a))
return HybridArray{S,T,N,M,typeof(a)}(a)
end
@inline function convert(::Type{HybridArray{S}}, a::TData) where {S,T,M,TData<:AbstractArray{T,M}}
convert(HybridArray{S,T}, a)
end
@inline Base.unsafe_convert(::Type{Ptr{T}}, A::HybridArray{S,T}) where {S,T} = pointer(parent(A))
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 11494 | Base.@propagate_inbounds function getindex(sa::HybridArray{S}, inds::Int...) where S
return getindex(sa.data, inds...)
end
Base.@propagate_inbounds function getindex(sa::HybridArray{S}, inds::Union{Int, StaticArray{<:Tuple, Int}, Colon}...) where S
_getindex(all_dynamic_fixed_val(S, inds...), sa, inds...)
end
# This plugs into a deeper level of indexing in base to catch custom
# indexing schemes based on `to_indices`.
# A minor version Julia release could potentially break this (though it seems unlikely).
Base.@propagate_inbounds function Base._getindex(l::IndexLinear, sa::HybridArray{S}, inds::Int...) where S
return Base._getindex(l, sa.data, inds...)
end
Base.@propagate_inbounds function Base._getindex(::IndexLinear, sa::HybridArray{S}, inds::Union{Int, StaticVector, Colon, Base.Slice}...) where S
_getindex(all_dynamic_fixed_val(S, inds...), sa, inds...)
end
Base.@propagate_inbounds function _getindex(::Val{:dynamic_fixed_true}, sa::HybridArray, inds::Union{Int, StaticVector, Colon, Base.Slice}...)
return _getindex_all_static(sa, inds...)
end
function _get_indices(i::Tuple{}, j::Int)
return ()
end
function _get_indices(i::Tuple, j::Int, ::Type{Int}, inds...)
return (:(inds[$j]), _get_indices(i, j+1, inds...)...)
end
function _get_indices(i::Tuple, j::Int, ::Type{T}, inds...) where T<:StaticVector
return (:(inds[$j][$(i[1])]), _get_indices(i[2:end], j+1, inds...)...)
end
function _get_indices(i::Tuple, j::Int, ::Type{<:Union{Colon, Base.Slice}}, inds...)
return (i[1], _get_indices(i[2:end], j+1, inds...)...)
end
_totally_linear() = true
_totally_linear(inds...) = false
_totally_linear(inds::Type{Int}...) = true
_totally_linear(inds::Type{<:Base.Slice}...) = true
_totally_linear(inds::Type{Colon}...) = true
_totally_linear(::Type{<:Base.Slice}, inds...) = _totally_linear(inds...)
_totally_linear(::Type{Colon}, inds...) = _totally_linear(inds...)
function new_out_size_nongen(::Type{Size}, inds...) where Size
os = []
@assert length(Size.parameters) == length(inds)
map(Size.parameters, inds) do s, i
if i == Int
elseif i <: StaticVector
push!(os, length(i))
elseif i == Colon || i <: Base.Slice
push!(os, s)
else
error("Unknown index type: $i")
end
end
return tuple(os...)
end
function new_out_size_nongen(::Type{Size}, i::Type{<:Union{Colon, Base.Slice}}) where Size
if has_dynamic(Size)
return (Dynamic(),)
else
return (tuple_nodynamic_prod(Size),)
end
end
"""
_get_linear_inds(S, inds...)
Returns linear indices for given size and access indices.
Order is selected to make setindex! with array input be linearly indexed by
position of index in returned vector.
"""
function _get_linear_inds(S, inds...)
newsize = new_out_size_nongen(S, inds...)
indices = CartesianIndices(newsize)
out_inds = Any[]
sizeprods = Union{Int, Expr}[1]
needs_dynsize = false
for (i, s) in enumerate(S.parameters[1:(end-1)])
if isa(s, Int) && isa(sizeprods[end], Int)
push!(sizeprods, s*sizeprods[end])
elseif isa(s, Int)
push!(sizeprods, :($s*$(sizeprods[end])))
elseif isa(s, Dynamic)
needs_dynsize = true
push!(sizeprods, :(dynsize[$i]*$(sizeprods[end])))
end
end
needs_sizeprod = false
if _totally_linear(inds...)
i1 = 0
for (iik, ik) ∈ enumerate(inds)
if isa(ik, Type{Int})
needs_sizeprod = true
i1 = :($i1 + (inds[$iik]-1)*sizeprods[$iik])
end
end
out_inds = tuple((:(i1 + $k) for k ∈ 1:StaticArrays.tuple_prod(newsize))...)
preamble = if needs_sizeprod && needs_dynsize
quote
dynsize = size(sa)
sizeprods = tuple($(sizeprods...))
i1 = $i1
end
elseif needs_sizeprod
quote
sizeprods = tuple($(sizeprods...))
i1 = $i1
end
else
quote
i1 = $i1
end
end
return preamble, out_inds
else
return nothing
end
end
@generated function _getindex_all_static(sa::HybridArray{S,T}, inds::Union{Int, StaticIndexing, Base.Slice, Colon, StaticArray}...) where {S,T}
newsize = new_out_size_nongen(S, inds...)
exprs = Vector{Expr}(undef, length(newsize))
indices = CartesianIndices(newsize)
exprs = similar(indices, Expr)
Tnewsize = Tuple{newsize...}
lininds = _get_linear_inds(S, inds...)
if lininds === nothing
for current_ind ∈ indices
cinds = _get_indices(current_ind.I, 1, inds...)
exprs[current_ind.I...] = :(getindex(sadata, $(cinds...)))
end
return quote
Base.@_propagate_inbounds_meta
sadata = parent(sa)
SArray{$Tnewsize,$T}(tuple($(exprs...)))
end
else
exprs = [:(getindex(sadata, $id)) for id ∈ lininds[2]]
return quote
Base.@_propagate_inbounds_meta
sadata = parent(sa)
$(lininds[1])
SArray{$Tnewsize,$T}(tuple($(exprs...)))
end
end
end
# _get_static_vector_length is used in a generated function so using a generic function
# may not be a good idea
_get_static_vector_length(::Type{<:StaticVector{N}}) where {N} = N
@generated function new_out_size(::Type{Size}, inds...) where Size
os = []
@assert length(Size.parameters) === length(inds)
map(Size.parameters, inds) do s, i
if i == Int
elseif i <: StaticVector
push!(os, _get_static_vector_length(i))
elseif i == Colon || i <: Base.Slice
push!(os, s)
elseif i <: SOneTo
push!(os, i.parameters[1])
elseif i <: Base.OneTo || i <: AbstractArray
push!(os, Dynamic())
else
error("Unknown index type: $i")
end
end
return Tuple{os...}
end
@generated function new_out_size(::Type{Size}, ::Union{Colon, Base.Slice}) where Size
if has_dynamic(Size)
return Tuple{Dynamic()}
else
return Tuple{tuple_nodynamic_prod(Size)}
end
end
function new_out_size(::Type{Size}, ::AbstractVector) where Size
return Tuple{Dynamic()}
end
@generated function new_out_size(::Type{Size}, ::StaticVector{N}) where {Size,N}
return Tuple{N}
end
maybe_unwrap(i) = i
maybe_unwrap(i::StaticIndexing) = i.ind
@inline function _getindex(::Val{:dynamic_fixed_false}, sa::HybridArray{S}, inds::Union{Int, StaticIndexing, StaticVector, Base.Slice, Colon}...) where S
uinds = map(maybe_unwrap, inds)
newsize = new_out_size(S, uinds...)
return HybridArray{newsize}(getindex(sa.data, uinds...))
end
# setindex stuff
Base.@propagate_inbounds function setindex!(a::HybridArray, value, inds::Int...)
Base.@boundscheck checkbounds(a, inds...)
_setindex!_scalar(Size(a), a, value, inds...)
end
@generated function _setindex!_scalar(::Size{S}, a::HybridArray, value, inds::Int...) where S
if length(inds) == 0
return quote
Base.@_propagate_inbounds_meta
a[1] = value
end
end
stride = :(1)
ind_expr = :()
for i ∈ 1:length(inds)
if i == 1
ind_expr = :(inds[1])
else
ind_expr = :($ind_expr + $stride * (inds[$i] - 1))
end
# it's possible that one of the trailing indices is an additional 1.
if length(S) < i || isa(S[i], StaticArrays.Dynamic)
stride = :($stride * size(a.data, $i))
else
stride = :($stride * $(S[i]))
end
end
return quote
Base.@_inline_meta
Base.@_propagate_inbounds_meta
a.data[$ind_expr] = value
end
end
Base.@propagate_inbounds function setindex!(sa::HybridArray{S}, value, inds::Union{Int, StaticArray{<:Tuple, Int}, Colon}...) where S
_setindex!(all_dynamic_fixed_val(S, inds...), sa, value, inds...)
end
@inline function _setindex!(::Val{:dynamic_fixed_false}, sa::HybridArray{S}, value, inds::Union{Int, StaticArray{<:Tuple, Int}, Colon}...) where S
newsize = new_out_size(S, inds...)
return HybridArray{newsize}(setindex!(parent(sa), value, inds...))
end
Base.@propagate_inbounds function _setindex!(::Val{:dynamic_fixed_true}, sa::HybridArray, value, inds::Union{Int, StaticArray{<:Tuple, Int}, Colon}...)
return _setindex!_all_static(sa, value, inds...)
end
@generated function _setindex!_all_static(sa::HybridArray{S,T}, v::AbstractArray, inds::Union{Int, StaticArray{<:Tuple, Int}, Colon}...) where {S,T}
newsize = new_out_size_nongen(S, inds...)
exprs = Vector{Expr}(undef, length(newsize))
indices = CartesianIndices(newsize)
Tnewsize = Tuple{newsize...}
if v <: StaticArray
newlen = StaticArrays.tuple_prod(newsize)
if Length(v) != newlen
return quote
throw(DimensionMismatch("tried to assign $(length(v))-element array to $($newlen) destination"))
end
end
end
lininds = _get_linear_inds(S, inds...)
if lininds === nothing
exprs = similar(indices, Expr)
for current_ind ∈ indices
cinds = _get_indices(current_ind.I, 1, inds...)
exprs[current_ind.I...] = :(setindex!(sadata, v[$(current_ind.I...)], $(cinds...)))
end
if v <: StaticArray
return quote
Base.@_propagate_inbounds_meta
sadata = parent(sa)
@inbounds $(Expr(:block, exprs...))
end
else
return quote
Base.@_propagate_inbounds_meta
if size(v) != $newsize
throw(DimensionMismatch("tried to assign array of size $(size(v)) to destination of size $($newsize)"))
end
sadata = parent(sa)
@inbounds $(Expr(:block, exprs...))
end
end
else
exprs = [:(setindex!(sadata, v[$iid], $id)) for (iid, id) ∈ enumerate(lininds[2])]
if v <: StaticArray
return quote
Base.@_propagate_inbounds_meta
$(lininds[1])
sadata = parent(sa)
@inbounds $(Expr(:block, exprs...))
end
else
return quote
Base.@_propagate_inbounds_meta
if size(v) != $newsize
throw(DimensionMismatch("tried to assign array of size $(size(v)) to destination of size $($newsize)"))
end
$(lininds[1])
sadata = parent(sa)
@inbounds $(Expr(:block, exprs...))
end
end
end
end
@inline function _view_hybrid(a::HybridArray{S}, ::Val{:dynamic_fixed_true}, inner_view, indices...) where {S}
new_size = new_out_size(S, indices...)
return SizedArray{new_size}(inner_view)
end
@inline function _view_hybrid(a::HybridArray{S}, ::Val{:dynamic_fixed_false}, inner_view, indices...) where {S}
new_size = new_out_size(S, indices...)
return HybridArray{new_size}(inner_view)
end
@inline function Base.view(
a::HybridArray{S},
indices::Union{Int, AbstractArray, Colon}...,
) where {S}
inner_view = invoke(view, Tuple{AbstractArray, typeof(indices).parameters...}, a, indices...)
return _view_hybrid(a, all_dynamic_fixed_val(S, indices...), inner_view, indices...)
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 2599 |
const HybridMatrixLike{T} = Union{
HybridMatrix{<:Any, <:Any, T},
Transpose{T, <:HybridMatrix{T}},
Adjoint{T, <:HybridMatrix{T}},
Symmetric{T, <:HybridMatrix{T}},
Hermitian{T, <:HybridMatrix{T}},
Diagonal{T, <:HybridMatrix{<:Any, T}}
}
const HybridVecOrMatLike{T} = Union{HybridVector{<:Any, T}, HybridMatrixLike{T}}
# Binary ops
# Between arrays
@inline +(a::HybridArray, b::HybridArray) = a .+ b
@inline +(a::AbstractArray, b::HybridArray) = a .+ b
@inline +(a::StaticArray, b::HybridArray) = a .+ b
@inline +(a::HybridArray, b::AbstractArray) = a .+ b
@inline +(a::HybridArray, b::StaticArray) = a .+ b
@inline -(a::HybridArray, b::HybridArray) = a .- b
@inline -(a::AbstractArray, b::HybridArray) = a .- b
@inline -(a::StaticArray, b::HybridArray) = a .- b
@inline -(a::HybridArray, b::AbstractArray) = a .- b
@inline -(a::HybridArray, b::StaticArray) = a .- b
# Scalar-array
@inline *(a::Number, b::HybridArray) = a .* b
@inline *(a::HybridArray, b::Number) = a .* b
@inline /(a::HybridArray, b::Number) = a ./ b
@inline \(a::Number, b::HybridArray) = a .\ b
@inline vcat(a::HybridVecOrMatLike) = a
@inline vcat(a::HybridVecOrMatLike, b::HybridVecOrMatLike) = _vcat(Size(a), Size(b), a, b)
@inline vcat(a::HybridVecOrMatLike, b::HybridVecOrMatLike, c::HybridVecOrMatLike...) = vcat(vcat(a,b), vcat(c...))
@generated function _vcat(::Size{Sa}, ::Size{Sb}, a::HybridVecOrMatLike, b::HybridVecOrMatLike) where {Sa, Sb}
if Size(Sa)[2] != Size(Sb)[2]
throw(DimensionMismatch("Tried to vcat arrays of size $Sa and $Sb"))
end
if a <: HybridVector && b <: HybridVector
Snew = (Sa[1] + Sb[1],)
else
Snew = (Sa[1] + Sb[1], Size(Sa)[2])
end
return quote
Base.@_inline_meta
@inbounds return _h_similar_type($a, promote_type(eltype(a), eltype(b)), Size($Snew))(vcat(parent(a), parent(b)))
end
end
@inline hcat(a::HybridVecOrMatLike, b::HybridVecOrMatLike) = _hcat(Size(a), Size(b), a, b)
@inline hcat(a::HybridVecOrMatLike, b::HybridVecOrMatLike, c::HybridVecOrMatLike...) = hcat(hcat(a,b), c...)
# used in _vcat and _hcat
@inline +(::Dynamic, ::Dynamic) = Dynamic()
@generated function _hcat(::Size{Sa}, ::Size{Sb}, a::HybridVecOrMatLike, b::HybridVecOrMatLike) where {Sa, Sb}
if Sa[1] != Sb[1]
throw(DimensionMismatch("Tried to hcat arrays of size $Sa and $Sb"))
end
Snew = (Sa[1], Size(Sa)[2] + Size(Sb)[2])
return quote
Base.@_inline_meta
return _h_similar_type($a, promote_type(eltype(a), eltype(b)), Size($Snew))(hcat(parent(a), parent(b)))
end
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 1681 | function StaticArrayInterface.strides(x::HybridArray)
return StaticArrayInterface.strides(parent(x))
end
@generated function StaticArrayInterface.strides(x::HybridArray{S,T,N,N,Array{T,N}}) where {S<:Tuple,T,N}
collected_strides = []
i = 1
for (argnum, Sarg) in enumerate(S.parameters)
if i > 0
push!(collected_strides, StaticArrayInterface.StaticInt(i))
else
push!(collected_strides, :(datastrides[$argnum]))
end
if Sarg isa Integer
i *= Sarg
else
i = -1
end
end
return quote
datastrides = strides(parent(x))
return tuple($(collected_strides...))
end
end
@generated function StaticArrayInterface.size(x::HybridArray{S}) where {S}
collected_sizes = []
for (argnum, Sarg) in enumerate(S.parameters)
if Sarg isa Integer
push!(collected_sizes, StaticArrayInterface.StaticInt(Sarg))
else
push!(collected_sizes, :(datasize[$argnum]))
end
end
return quote
datasize = StaticArrayInterface.size(parent(x))
return tuple($(collected_sizes...))
end
end
StaticArrayInterface.contiguous_axis(::Type{HybridArray{S,T,N,N,TData}}) where {S,T,N,TData} = StaticArrayInterface.contiguous_axis(TData)
StaticArrayInterface.contiguous_batch_size(::Type{HybridArray{S,T,N,N,TData}}) where {S,T,N,TData} = StaticArrayInterface.contiguous_batch_size(TData)
StaticArrayInterface.stride_rank(::Type{HybridArray{S,T,N,N,TData}}) where {S,T,N,TData} = StaticArrayInterface.stride_rank(TData)
StaticArrayInterface.dense_dims(x::HybridArray) = StaticArrayInterface.dense_dims(x.data)
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 224 |
"""
size_to_tuple(::Type{S}) where S<:Tuple
Converts a size given by `Tuple{N, M, ...}` into a tuple `(N, M, ...)`.
"""
Base.@pure function size_to_tuple(::Type{S}) where S<:Tuple
return tuple(S.parameters...)
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 5727 | using StaticArrays, HybridArrays, Test, LinearAlgebra
using StaticArrays: Dynamic
@testset "AbstractArray interface" begin
@testset "size and length" begin
M = HybridMatrix{2, Dynamic()}([1 2 3; 4 5 6])
@test length(M) == 6
@test size(M) == (2, 3)
@test Base.isassigned(M, 2, 2) == true
@test (@inferred Size(M)) == Size(Tuple{2, Dynamic()})
@test (@inferred Size(typeof(M))) == Size(Tuple{2, Dynamic()})
end
@testset "reshape" begin
# TODO?
end
@testset "convert" begin
MM = [1 2 3; 4 5 6]
M = HybridMatrix{2, Dynamic()}(MM)
@test parent(@inferred convert(HybridArray{Tuple{2,Dynamic()}}, MM)) == M
@test parent(@inferred convert(HybridArray{Tuple{2,Dynamic()},Int}, MM)) == M
@test parent(@inferred convert(HybridArray{Tuple{2,Dynamic()},Float64}, MM)) == M
@test parent(@inferred convert(HybridArray{Tuple{2,Dynamic()},Float64,2}, MM)) == M
@test parent(@inferred convert(HybridArray{Tuple{2,Dynamic()},Float64,2,2}, MM)) == M
@test parent(@inferred convert(HybridArray{Tuple{2,Dynamic()},Float64,2,2,Matrix{Float64}}, MM)) == M
@test convert(typeof(M), M) === M
if VERSION >= v"1.1"
@test convert(HybridArray{Tuple{2,Dynamic()},Float64}, M) == M
end
@test convert(Array, M) === parent(M)
@test convert(Array{Int}, M) === parent(M)
@test convert(Matrix, M) === parent(M)
@test convert(Matrix{Int}, M) === parent(M)
@test Array(M) == M
@test Array(M) !== parent(M)
@test Matrix(M) == M
@test Matrix(M) !== parent(M)
@test Matrix{Int}(M) == M
@test Matrix{Int}(M) !== parent(M)
@test_throws MethodError Vector(M)
end
@testset "copy" begin
M = HybridMatrix{2, Dynamic()}([1 2; 3 4])
@test @inferred(copy(M))::HybridMatrix == M
@test parent(copy(M)) !== parent(M)
@testset "subarrays" begin
M = HybridMatrix{Dynamic(), 2}(rand(4, 2))
ha = view(M, :, 1)
@test copy(ha) == ha
@test parent(copy(ha)) !== parent(ha)
end
end
@testset "similar" begin
M = HybridMatrix{2, Dynamic(), Int}([1 2; 3 4])
@test isa(@inferred(similar(M)), HybridMatrix{2, Dynamic(), Int})
@test isa(@inferred(similar(M, Float64)), HybridMatrix{2, Dynamic(), Float64})
@test isa(@inferred(similar(M, Float64, Size(Tuple{3, 3}))), HybridMatrix{3, 3, Float64})
@test isa(@inferred(similar(M, SOneTo(3))), SizedVector{3, Int})
@test isa(@inferred(similar(M, Float64, SOneTo(3))), SizedVector{3, Float64})
@test isa(@inferred(similar(M, (SOneTo(3), 10, Base.OneTo(12)))),
HybridArray{Tuple{3,Dynamic(),Dynamic()}, Int})
@test isa(@inferred(similar(M, Float64, (SOneTo(3), 10, Base.OneTo(12)))),
HybridArray{Tuple{3,Dynamic(),Dynamic()}, Float64})
@test size(similar(M, Float64, (SOneTo(3), 10, Base.OneTo(12)))) === (3, 10, 12)
end
@testset "IndexStyle" begin
M = HybridMatrix{2, Dynamic(), Int}([1 2; 3 4])
MT = HybridMatrix{2, Dynamic(), Int}([1 2; 3 4]')
@test (@inferred IndexStyle(M)) === IndexLinear()
@test (@inferred IndexStyle(MT)) === IndexCartesian()
@test (@inferred IndexStyle(typeof(M))) === IndexLinear()
@test (@inferred IndexStyle(typeof(MT))) === IndexCartesian()
end
@testset "vec" begin
M = HybridMatrix{2, Dynamic(), Int}([1 2; 3 4])
Mv = vec(M)
@test Mv == [1, 3, 2, 4]
@test Mv isa Vector{Int}
Mv[2] = 100
@test M[2, 1] == 100
end
@testset "errors" begin
@test_throws TypeError HybridArrays.new_out_size_nongen(Size{Tuple{1,2}}, 'a')
end
@testset "elsize, eltype" begin
for T in [Int8, Int16, Int32, Int64, Int128, Float16, Float32, Float64, BigFloat]
M_array = rand(T, 2, 2)
M_hybrid = HybridMatrix{2, Dynamic()}(M_array)
@test Base.eltype(M_hybrid) === Base.eltype(M_array)
@test Base.elsize(M_hybrid) === Base.elsize(M_array)
end
end
@testset "strides" begin
M = HybridMatrix{2, Dynamic(), Int}([1 2; 3 4])
@test strides(M) == strides(parent(M))
end
@testset "pointer" begin
M = HybridMatrix{2, Dynamic(), Int}([1 2; 3 4])
MT = HybridMatrix{2, Dynamic(), Int}([1 2; 3 4]')
@test pointer(M) == pointer(parent(M))
if VERSION >= v"1.5"
# pointer on Adjoint is not available on earilier versions of Julia
@test pointer(MT) == pointer(parent(MT))
end
end
@testset "unsafe_convert" begin
M = HybridMatrix{2, Dynamic(), Int}([1 2; 3 4])
@test Base.unsafe_convert(Ptr{Int}, M) === pointer(parent(M))
end
@test HybridArrays._totally_linear() === true
@testset "undef initializers" begin
M = HybridVector{3,Int}(undef, 3)
@test isa(M, HybridVector{3,Int,1,Vector{Int}})
@test_throws ErrorException HybridVector{3,Int}(undef, 4)
M2 = HybridMatrix{Dynamic(),4,Int}(undef, 6, 4)
@test isa(M2, HybridMatrix{Dynamic(),4,Int,2,Matrix{Int}})
@test size(M2) === (6, 4)
M3 = HybridArray{Tuple{Dynamic(),3,4},Int}(undef, 5, 3, 4)
@test isa(M3, HybridArray{Tuple{Dynamic(),3,4},Int,3,3,Array{Int,3}})
@test size(M3) === (5, 3, 4)
end
@testset "getindex" begin
A = HybridArray{Tuple{2,2,StaticArrays.Dynamic()}}(randn(2,2,100))
B = A[1:2]
@test B isa Vector
@test A[1] == B[1]
@test A[2] == B[2]
end
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 596 |
using HybridArrays, ArrayInterface, Test, StaticArrays
@testset "ArrayInterface compatibility" begin
M = HybridMatrix{2, StaticArrays.Dynamic()}([1 2; 4 5])
MV = HybridMatrix{3, StaticArrays.Dynamic()}(view(randn(10, 10), 1:2:5, 1:3:12))
@test ArrayInterface.ismutable(M)
@test ArrayInterface.can_setindex(M)
@test ArrayInterface.parent_type(M) === Matrix{Int}
@test ArrayInterface.restructure(M, [2, 4, 6, 8]) == HybridMatrix{2, StaticArrays.Dynamic()}([2 6; 4 8])
@test isa(ArrayInterface.restructure(M, [2, 4, 6, 8]), HybridMatrix{2, StaticArrays.Dynamic()})
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 904 | using StaticArrays, HybridArrays, Test, LinearAlgebra
@testset "AbstractArray interface" begin
@testset "one()" begin
M = HybridMatrix{2, StaticArrays.Dynamic()}([1 2; 4 5])
@test (@inferred one(M)) == @SMatrix [1 0; 0 1]
@test isa(one(M), HybridMatrix{2,StaticArrays.Dynamic(),Int})
Mv = view(M, :, SOneTo(2))
@test (@inferred one(Mv)) === @SMatrix [1 0; 0 1]
end
@testset "zero()" begin
M = HybridMatrix{2, StaticArrays.Dynamic()}([1 2; 4 5])
@test (@inferred zero(M)) == @SMatrix [0 0; 0 0]
@test isa(zero(M), HybridMatrix{2,StaticArrays.Dynamic(),Int})
Mv = view(M, :, SOneTo(2))
@test (@inferred zero(Mv)) === @SMatrix [0 0; 0 0]
end
@testset "fill!()" begin
M = HybridMatrix{2, StaticArrays.Dynamic(), Float64}([1 2; 4 5])
fill!(M, 3)
@test all(M .== 3.)
end
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 9150 | using HybridArrays
using StaticArrays
using Test
struct ScalarTest end
Base.:(+)(x::Number, y::ScalarTest) = x
Broadcast.broadcastable(x::ScalarTest) = Ref(x)
@testset "broadcasting" begin
Ai = rand(Int, 2, 3, 4)
Bi = HybridArray{Tuple{2,3,StaticArrays.Dynamic()}, Int, 3}(Ai)
Af = rand(Float64, 2, 3, 4)
Bf = HybridArray{Tuple{2,3,StaticArrays.Dynamic()}, Float64, 3}(Af)
Bi[1,2,:] .= [110, 111, 112, 113]
@test Bi[1,2,:] == @SVector [110, 111, 112, 113]
@testset "Scalar Broadcast" begin
@test Bf == @inferred(Bf .+ ScalarTest())
@test Bf .+ 1 == @inferred(Bf .+ Ref(1))
end
@testset "AbstractArray-of-HybridArray with scalar math" begin
v = [Bf]
@test @inferred(v .* 1.0)::typeof(v) == v
end
@testset "2x2 HybridMatrix with HybridVector" begin
m = HybridMatrix{2,StaticArrays.Dynamic()}([1 2; 3 4])
v = HybridVector{2}([1, 4])
@test @inferred(broadcast(+, m, v)) == @SMatrix [2 3; 7 8]
@test @inferred(m .+ v) == @SMatrix [2 3; 7 8]
@test @inferred(v .+ m) == @SMatrix [2 3; 7 8]
@test @inferred(m .* v) == @SMatrix [1 2; 12 16]
@test @inferred(v .* m) == @SMatrix [1 2; 12 16]
@test @inferred(m ./ v) == @SMatrix [1 2; 3/4 1]
@test @inferred(v ./ m) == @SMatrix [1 1/2; 4/3 1]
@test @inferred(m .- v) == @SMatrix [0 1; -1 0]
@test @inferred(v .- m) == @SMatrix [0 -1; 1 0]
@test @inferred(m .^ v) == @SMatrix [1 2; 81 256]
@test @inferred(v .^ m) == @SMatrix [1 1; 64 256]
# StaticArrays Issue #546
@test @inferred(m ./ (v .* v')) == @SMatrix [1.0 0.5; 0.75 0.25]
testinf(m, v) = m ./ (v .* v')
@test @inferred(testinf(m, v)) == @SMatrix [1.0 0.5; 0.75 0.25]
end
@testset "2x2 HybridMatrix with 1x2 HybridMatrix" begin
# StaticArrays Issues #197, #242: broadcast between SArray and row-like SMatrix
m1 = HybridMatrix{2,StaticArrays.Dynamic()}([1 2; 3 4])
m2 = HybridMatrix{1,StaticArrays.Dynamic()}([1 4])
@test @inferred(broadcast(+, m1, m2)) == @SMatrix [2 6; 4 8]
@test @inferred(m1 .+ m2) == @SMatrix [2 6; 4 8]
@test @inferred(m2 .+ m1) == @SMatrix [2 6; 4 8]
@test @inferred(m1 .* m2) == @SMatrix [1 8; 3 16]
@test @inferred(m2 .* m1) == @SMatrix [1 8; 3 16]
@test @inferred(m1 ./ m2) == @SMatrix [1 1/2; 3 1]
@test @inferred(m2 ./ m1) == @SMatrix [1 2; 1/3 1]
@test @inferred(m1 .- m2) == @SMatrix [0 -2; 2 0]
@test @inferred(m2 .- m1) == @SMatrix [0 2; -2 0]
@test @inferred(m1 .^ m2) == @SMatrix [1 16; 3 256]
end
@testset "1x2 HybridMatrix with SVector" begin
# StaticArrays Issues #197, #242: broadcast between SVector and row-like SVector
m = HybridMatrix{1,StaticArrays.Dynamic()}([1 2])
v = SVector(1, 4)
@test @inferred(broadcast(+, m, v)) == @SMatrix [2 3; 5 6]
@test @inferred(m .+ v) == @SMatrix [2 3; 5 6]
@test @inferred(v .+ m) == @SMatrix [2 3; 5 6]
@test @inferred(m .* v) == @SMatrix [1 2; 4 8]
@test @inferred(v .* m) == @SMatrix [1 2; 4 8]
@test @inferred(m ./ v) == @SMatrix [1 2; 1/4 1/2]
@test @inferred(v ./ m) == @SMatrix [1 1/2; 4 2]
@test @inferred(m .- v) == @SMatrix [0 1; -3 -2]
@test @inferred(v .- m) == @SMatrix [0 -1; 3 2]
@test @inferred(m .^ v) == @SMatrix [1 2; 1 16]
@test @inferred(v .^ m) == @SMatrix [1 1; 4 16]
end
@testset "HybridMatrix with HybridMatrix" begin
m1 = HybridMatrix{2,StaticArrays.Dynamic()}([1 2; 3 4])
m2 = HybridMatrix{2,StaticArrays.Dynamic()}([1 3; 4 5])
@test @inferred(broadcast(+, m1, m2)) == @SMatrix [2 5; 7 9]
@test @inferred(m1 .+ m2) == @SMatrix [2 5; 7 9]
@test @inferred(m2 .+ m1) == @SMatrix [2 5; 7 9]
@test @inferred(m1 .* m2) == @SMatrix [1 6; 12 20]
@test @inferred(m2 .* m1) == @SMatrix [1 6; 12 20]
# StaticArrays Issue #199: broadcast with empty SArray
@test @inferred(HybridVector{1}([1]) .+ HybridVector{0,Int}([])) === SVector{0,Union{}}()
@test_broken @inferred(HybridVector{0,Int}([]) .+ SVector(1)) === SVector{0,Union{}}()
# StaticArrays Issue #200: broadcast with Adjoint
@test @inferred(m1 .+ m2') == @SMatrix [2 6; 6 9]
@test @inferred(m1 .+ transpose(m2)) == @SMatrix [2 6; 6 9]
# StaticArrays Issue 382: infinite recursion in Base.Broadcast.broadcast_indices with Adjoint
@test @inferred(HybridVector{2}([1,1])' .+ [1, 1]) == [2 2; 2 2]
@test @inferred(transpose(HybridVector{2}([1,1])) .+ [1, 1]) == [2 2; 2 2]
@test @inferred(HybridVector{StaticArrays.Dynamic()}([1,1])' .+ [1, 1]) == [2 2; 2 2]
@test @inferred(transpose(HybridVector{StaticArrays.Dynamic()}([1,1])) .+ [1, 1]) == [2 2; 2 2]
end
@testset "HybridMatrix with Scalar" begin
m = HybridMatrix{2,StaticArrays.Dynamic()}([1 2; 3 4])
@test @inferred(broadcast(+, m, 2)) == @SMatrix [3 4; 5 6]
@test @inferred(m .+ 2) == @SMatrix [3 4; 5 6]
@test @inferred(2 .+ m) == @SMatrix [3 4; 5 6]
@test @inferred(m .* 2) == @SMatrix [2 4; 6 8]
@test @inferred(2 .* m) == @SMatrix [2 4; 6 8]
@test @inferred(m ./ 2) == @SMatrix [1/2 1; 3/2 2]
@test @inferred(2 ./ m) == @SMatrix [2 1; 2/3 1/2]
@test @inferred(m .- 2) == @SMatrix [-1 0; 1 2]
@test @inferred(2 .- m) == @SMatrix [1 0; -1 -2]
@test @inferred(m .^ 2) == @SMatrix [1 4; 9 16]
@test @inferred(2 .^ m) == @SMatrix [2 4; 8 16]
end
@testset "Empty arrays" begin
@test @inferred(1.0 .+ HybridMatrix{2,0,Float64}(zeros(2,0))) == HybridMatrix{2,0,Float64}(zeros(2,0))
@test @inferred(1.0 .+ HybridMatrix{0,2,Float64}(zeros(0,2))) == HybridMatrix{0,2,Float64}(zeros(0,2))
@test @inferred(1.0 .+ HybridArray{Tuple{2,StaticArrays.Dynamic(),0},Float64}(zeros(2,3,0))) == HybridArray{Tuple{2,StaticArrays.Dynamic(),0},Float64}(zeros(2,3,0))
@test @inferred(HybridVector{0,Float64}(zeros(0)) .+ HybridMatrix{0,2,Float64}(zeros(0,2))) == HybridMatrix{0,2,Float64}(zeros(0,2))
m = HybridMatrix{0,2,Float64}(zeros(0,2))
@test @inferred(broadcast!(+, m, m, HybridVector{0,Float64}(zeros(0)))) == HybridMatrix{0,2,Float64}(zeros(0,2))
end
@testset "Mutating broadcast!" begin
# No setindex! error
A = HybridMatrix{2,StaticArrays.Dynamic()}([1 0; 0 1])
@test @inferred(broadcast!(+, A, A, SVector(1, 4))) == @MMatrix [2 1; 4 5]
A = HybridMatrix{2,StaticArrays.Dynamic()}([1 0; 0 1])
@test @inferred(broadcast!(+, A, A, @SMatrix([1 4]))) == @MMatrix [2 4; 1 5]
A = HybridMatrix{1,StaticArrays.Dynamic()}([1 0])
@test_throws DimensionMismatch broadcast!(+, A, A, SVector(1, 4))
A = HybridMatrix{1,StaticArrays.Dynamic()}([1 0])
@test @inferred(broadcast!(+, A, A, @SMatrix([1 4]))) == @MMatrix [2 4]
A = HybridMatrix{1,StaticArrays.Dynamic()}([1 0])
@test @inferred(broadcast!(+, A, A, 2)) == @MMatrix [3 2]
end
@testset "broadcast! with mixtures of SArray and Array" begin
A = HybridVector{StaticArrays.Dynamic()}([0, 0])
@test @inferred(broadcast!(+, A, [1,2])) == [1,2]
end
@testset "eltype after broadcast" begin
# test cases StaticArrays issue #198
let a = HybridVector{4, Number}(Number[2, 2.0, 4//2, 2+0im])
@test eltype(a .+ 2) == Number
@test eltype(a .- 2) == Number
@test eltype(a * 2) == Number
@test eltype(a / 2) == Number
end
let a = HybridVector{3, Real}(Real[2, 2.0, 4//2])
@test eltype(a .+ 2) == Real
@test eltype(a .- 2) == Real
@test eltype(a * 2) == Real
@test eltype(a / 2) == Real
end
let a = HybridVector{3, Real}(Real[2, 2.0, 4//2])
@test eltype(a .+ 2.0) == Float64
@test eltype(a .- 2.0) == Float64
@test eltype(a * 2.0) == Float64
@test eltype(a / 2.0) == Float64
end
let a = broadcast(Float32, HybridVector{3}([3, 4, 5]))
@test eltype(a) == Float32
end
end
@testset "broadcast general scalars" begin
# StaticArrays Issue #239 - broadcast with non-numeric element types
@eval @enum Axis aX aY aZ
@test (HybridVector{3}([aX,aY,aZ]) .== Ref(aX)) == HybridVector{3}([true,false,false])
mv = HybridVector{3}([aX,aY,aZ])
@test broadcast!(identity, mv, Ref(aX)) == HybridVector{3}([aX,aX,aX])
@test mv == HybridVector{3}([aX,aX,aX])
end
@testset "broadcast! with Array destination" begin
# Issue #385
a = zeros(3, 3)
b = HybridMatrix{3,StaticArrays.Dynamic()}([1 2 3; 4 5 6; 7 8 9])
a .= b
@test a == b
c = HybridVector{3}([1, 2, 3])
a .= c
@test a == [1 1 1; 2 2 2; 3 3 3]
d = HybridVector{4}([1, 2, 3, 4])
@test_throws DimensionMismatch a .= d
end
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 250 | using Test, HybridArrays, ForwardDiff, StaticArrays
@testset "ForwardDiff" begin
x = [rand(SVector{3}) for _ in 1:4]
xh = HybridMatrix{3,StaticArrays.Dynamic()}(reduce(hcat,x))
f(x) = 1.0
@test iszero(ForwardDiff.gradient(f, xh))
end | HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 2117 | using HybridArrays
using StaticArrays
using Test
@testset "Linear algebra" begin
@testset "HybridMatrix as a (mathematical) vector space" begin
c = 2
a1 = [2 4; 6 8]
s1 = SMatrix{2,2}(a1)
m1 = HybridMatrix{2,StaticArrays.Dynamic()}(a1)
a2 = [4 3; 2 1]
s2 = SMatrix{2,2}(a2)
m2 = HybridMatrix{2,StaticArrays.Dynamic()}(a2)
@test @inferred(c * m1)::HybridMatrix == @SMatrix [4 8; 12 16]
@test @inferred(m1 * c)::HybridMatrix == @SMatrix [4 8; 12 16]
@test @inferred(m1 / c)::HybridMatrix == @SMatrix [1.0 2.0; 3.0 4.0]
@test @inferred(c \ m1)::HybridMatrix ≈ @SMatrix [1.0 2.0; 3.0 4.0]
@test @inferred(m1 + m2) == @SMatrix [6 7; 8 9]
@test @inferred(m1 - m2) == @SMatrix [-2 1; 4 7]
@test @inferred(a1 + m2) == @SMatrix [6 7; 8 9]
@test @inferred(a1 - m2) == @SMatrix [-2 1; 4 7]
@test @inferred(m1 + a2) == @SMatrix [6 7; 8 9]
@test @inferred(m1 - a2) == @SMatrix [-2 1; 4 7]
@test @inferred(s1 + m2) == @SMatrix [6 7; 8 9]
@test @inferred(s1 - m2) == @SMatrix [-2 1; 4 7]
@test @inferred(m1 + s2) == @SMatrix [6 7; 8 9]
@test @inferred(m1 - s2) == @SMatrix [-2 1; 4 7]
@test vcat(m1) == m1
@test hcat(m1) == m1
@test @inferred(vcat(m1, m2)) == vcat(a1, a2)
@test @inferred(hcat(m1, m2)) == hcat(a1, a2)
@test isa(vcat(m1, m2), HybridMatrix{4,StaticArrays.Dynamic()})
@test isa(vcat(m1, m2, m2), HybridMatrix{6,StaticArrays.Dynamic()})
@test isa(hcat(m1, m2), HybridMatrix{2,StaticArrays.Dynamic()})
@test isa(hcat(m1, m2, m2), HybridMatrix{2,StaticArrays.Dynamic()})
@test isa(vcat(HybridVector{2}([1, 2]), HybridVector{3}([1, 2, 3])), HybridVector{5, Int})
@test_throws DimensionMismatch hcat(HybridVector{2}([1, 2]), HybridVector{3}([1, 2, 3]))
if VERSION < v"1.10"
@test_throws ArgumentError vcat(m1, hcat(m1, m2))
else
@test_throws DimensionMismatch vcat(m1, hcat(m1, m2))
end
end
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 2962 |
module TestEllipsisNotationCompat # use a module to avoid cluttering the global namespace
using EllipsisNotation
using HybridArrays
using Test
if VERSION >= v"1.5"
@testset "Compatibility with EllipsisNotation" begin
u_array = rand(2, 10)
u_hybrid = HybridArray{Tuple{2, HybridArrays.Dynamic()}}(copy(u_array))
@test u_hybrid ≈ u_array
@test u_hybrid[1, ..] ≈ u_array[1, ..]
@test u_hybrid[.., 1] ≈ u_array[.., 1]
@test u_hybrid[..] ≈ u_array[..]
@test typeof(u_hybrid[1, ..]) == typeof(u_hybrid[1, :])
@test typeof(u_hybrid[.., 1]) == typeof(u_hybrid[:, 1])
@test typeof(u_hybrid[..]) == typeof(u_hybrid[:])
@test typeof(u_hybrid[..,..]) == typeof(u_hybrid[:, :])
@inferred u_hybrid[1, ..]
@inferred u_hybrid[.., 1]
@inferred u_hybrid[..]
let new_values = rand(10)
u_array[1, ..] .= new_values
u_hybrid[1, ..] .= new_values
@test u_hybrid ≈ u_array
@test u_hybrid[1, ..] ≈ u_array[1, ..]
@test u_hybrid[.., 1] ≈ u_array[.., 1]
@test u_hybrid[..] ≈ u_array[..]
end
let new_values = rand(2)
u_array[.., 1] .= new_values
u_hybrid[.., 1] .= new_values
@test u_hybrid ≈ u_array
@test u_hybrid[1, ..] ≈ u_array[1, ..]
@test u_hybrid[.., 1] ≈ u_array[.., 1]
@test u_hybrid[..] ≈ u_array[..]
end
let new_values = rand(2, 10)
u_array .= new_values
u_hybrid .= new_values
@test u_hybrid ≈ u_array
@test u_hybrid[1, ..] ≈ u_array[1, ..]
@test u_hybrid[.., 1] ≈ u_array[.., 1]
@test u_hybrid[..] ≈ u_array[..]
end
end
end
@testset "Compatibility with Cartesian indices" begin
u_array = rand(2, 3, 4)
u_hybrid = HybridArray{Tuple{2, 3, 4}}(copy(u_array))
@test u_hybrid ≈ u_array
@test u_hybrid[CartesianIndex(1, 2), :] ≈ u_array[CartesianIndex(1, 2), :]
@test u_hybrid[:, CartesianIndex(1, 2)] ≈ u_array[:, CartesianIndex(1, 2)]
@test typeof(u_hybrid[CartesianIndex(1, 2), :]) == typeof(u_hybrid[1, 2, :])
@test typeof(u_hybrid[:, CartesianIndex(1, 2)]) == typeof(u_hybrid[:, 1, 2])
@inferred u_hybrid[CartesianIndex(1, 2), :]
@inferred u_hybrid[:, CartesianIndex(1, 2)]
@inferred u_hybrid[CartesianIndex(1, 2, 3)]
let new_values = rand(4)
u_array[CartesianIndex(1, 2), :] .= new_values
u_hybrid[CartesianIndex(1, 2), :] .= new_values
@test u_hybrid ≈ u_array
@test u_hybrid[CartesianIndex(1, 2), :] ≈ u_array[CartesianIndex(1, 2), :]
@test u_hybrid[:, CartesianIndex(1, 2)] ≈ u_array[:, CartesianIndex(1, 2)]
end
let new_values = rand(2)
u_array[:, CartesianIndex(1, 2)] .= new_values
u_hybrid[:, CartesianIndex(1, 2)] .= new_values
@test u_hybrid ≈ u_array
@test u_hybrid[CartesianIndex(1, 2), :] ≈ u_array[CartesianIndex(1, 2), :]
@test u_hybrid[:, CartesianIndex(1, 2)] ≈ u_array[:, CartesianIndex(1, 2)]
end
end
end # module
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 7140 | using HybridArrays
using StaticArrays
using Test
if VERSION < v"1.6"
# Julia 1.6 has a stack overflow on this test :(
@test length(Test.detect_ambiguities(HybridArrays)) == 0
end
@testset "Inner Constructors" begin
@test parent(HybridArray{Tuple{2}, Int, 1, 1, Vector{Int}}((3, 4))) == [3, 4]
@test parent(HybridArray{Tuple{2}, Int, 1}([3, 4])) == [3, 4]
@test parent(HybridArray{Tuple{2, 2}, Int, 2}(collect(3:6))) == collect(3:6)
@test size(parent(HybridArray{Tuple{4, 5}, Int, 2}(undef))) == (4, 5)
@test size(parent(HybridArray{Tuple{4, 5}, Int}(undef))) == (4, 5)
# Bad input
@test_throws Exception SArray{Tuple{1},Int,1}([2 3])
# Bad parameters
@test_throws Exception HybridArray{Tuple{1},Int,2}(undef)
@test_throws Exception SArray{Tuple{3, 4},Int,1}(undef)
# Parameter/input size mismatch
@test_throws Exception HybridArray{Tuple{1},Int,2}([2; 3])
@test_throws Exception HybridArray{Tuple{1},Int,2}((2, 3))
end
@testset "Outer Constructors" begin
# From Array
@test @inferred(HybridArray{Tuple{2},Float64,1}([1,2]))::HybridArray{Tuple{2},Float64,1,1} == [1.0, 2.0]
@test @inferred(HybridArray{Tuple{2},Float64}([1,2]))::HybridArray{Tuple{2},Float64,1,1} == [1.0, 2.0]
@test @inferred(HybridArray{Tuple{2}}([1,2]))::HybridArray{Tuple{2},Int,1,1} == [1,2]
@test @inferred(HybridArray{Tuple{2,2}}([1 2;3 4]))::HybridArray{Tuple{2,2},Int,2,2} == [1 2; 3 4]
# Uninitialized
@test @inferred(HybridArray{Tuple{2,2},Int,2}(undef)) isa HybridArray{Tuple{2,2},Int,2,2}
@test @inferred(HybridArray{Tuple{2,2},Int}(undef)) isa HybridArray{Tuple{2,2},Int,2,2}
# From Tuple
@test @inferred(HybridArray{Tuple{2},Float64,1,1,Vector{Float64}}((1,2)))::HybridArray{Tuple{2},Float64,1,1} == [1.0, 2.0]
@test @inferred(HybridArray{Tuple{2},Float64}((1,2)))::HybridArray{Tuple{2},Float64,1,1} == [1.0, 2.0]
@test @inferred(HybridArray{Tuple{2}}((1,2)))::HybridArray{Tuple{2},Int,1,1} == [1,2]
@test @inferred(HybridArray{Tuple{2,2}}((1,2,3,4)))::HybridArray{Tuple{2,2},Int,2,2} == [1 3; 2 4]
end
@testset "HybridVector and HybridMatrix" begin
@test @inferred(HybridVector{2}([1,2]))::HybridArray{Tuple{2},Int,1,1} == [1,2]
@test @inferred(HybridVector{2}((1,2)))::HybridArray{Tuple{2},Int,1,1} == [1,2]
# Reshaping
@test @inferred(HybridVector{2}([1 2]))::HybridArray{Tuple{2},Int,1,2} == [1,2]
# Back to Vector
@test Vector(HybridVector{2}((1,2))) == [1,2]
@test convert(Vector, HybridVector{2}((1,2))) == [1,2]
@test @inferred(HybridMatrix{2,2}([1 2; 3 4]))::HybridArray{Tuple{2,2},Int,2,2} == [1 2; 3 4]
# Reshaping
@test @inferred(HybridMatrix{2,2}((1,2,3,4)))::HybridArray{Tuple{2,2},Int,2,2} == [1 3; 2 4]
# Back to Matrix
@test Matrix(HybridMatrix{2,2}([1 2;3 4])) == [1 2; 3 4]
@test convert(Matrix, HybridMatrix{2,2}([1 2;3 4])) == [1 2; 3 4]
end
@testset "setindex" begin
sa = HybridArray{Tuple{2}, Int, 1}([3, 4])
sa[1] = 2
@test parent(sa) == [2, 4]
end
@testset "aliasing" begin
a1 = rand(4)
a2 = copy(a1)
sa1 = HybridVector{4}(a1)
sa2 = HybridVector{4}(a2)
@test Base.mightalias(a1, sa1)
@test Base.mightalias(sa1, HybridVector{4}(a1))
@test !Base.mightalias(a2, sa1)
@test !Base.mightalias(sa1, HybridVector{4}(a2))
@test Base.mightalias(sa1, view(sa1, 1:2))
@test Base.mightalias(a1, view(sa1, 1:2))
@test Base.mightalias(sa1, view(a1, 1:2))
end
@testset "back to Array" begin
@test Array(HybridArray{Tuple{2}, Int, 1}([3, 4])) == [3, 4]
@test Array{Int}(HybridArray{Tuple{2}, Int, 1}([3, 4])) == [3, 4]
@test Array{Int, 1}(HybridArray{Tuple{2}, Int, 1}([3, 4])) == [3, 4]
@test Vector(HybridArray{Tuple{4}, Int, 1}(collect(3:6))) == collect(3:6)
@test convert(Vector, HybridArray{Tuple{4}, Int, 1}(collect(3:6))) == collect(3:6)
@test Matrix(SMatrix{2,2}((1,2,3,4))) == [1 3; 2 4]
@test convert(Matrix, SMatrix{2,2}((1,2,3,4))) == [1 3; 2 4]
@test convert(Array, HybridArray{Tuple{2,2,2,2}, Int}(ones(2,2,2,2))) == ones(2,2,2,2)
# Conversion after reshaping
@test_broken Array(HybridMatrix{2,2,Int,1,Vector{Int}}([1,2,3,4])) == [1 3; 2 4]
end
@testset "promotion" begin
@test @inferred(promote_type(HybridVector{1,Float64,1,Vector{Float64}}, HybridVector{1,BigFloat,1,Vector{BigFloat}})) == HybridVector{1,BigFloat,1,Vector{BigFloat}}
@test @inferred(promote_type(HybridVector{2,Int,1,Vector{Int}}, HybridVector{2,Float64,1,Vector{Float64}})) === HybridVector{2,Float64,1,Vector{Float64}}
@test @inferred(promote_type(HybridMatrix{2,3,Float32,2,Matrix{Float32}}, HybridMatrix{2,3,Complex{Float64},2,Matrix{Complex{Float64}}})) === HybridMatrix{2,3,Complex{Float64},2,Matrix{Complex{Float64}}}
end
@testset "dynamically sized axes" begin
A = rand(Int, 2, 3, 4)
B = HybridArray{Tuple{2,3,StaticArrays.Dynamic()}, Int, 3}(A)
C = rand(Int, 2, 3, 4, 5)
D = HybridArray{Tuple{2,3,StaticArrays.Dynamic(),StaticArrays.Dynamic()}, Int, 4}(C)
@test size(B) == size(A)
@test size(D) == size(C)
@test axes(B) == (SOneTo(2), SOneTo(3), axes(A, 3))
@test axes(B, 1) == SOneTo(2)
@test axes(B, 2) == SOneTo(3)
@test B[1,2,3] == A[1,2,3]
@test B[1,:,:] == A[1,:,:]
inds = @SVector [2, 1]
@test B[1,inds,:] == A[1,inds,:]
@test B[:,:,2] == A[:,:,2]
@test B[:,:,@SVector [2, 3]] == A[:,:,[2, 3]]
B[1,2,3] = 42
@test B[1,2,3] == 42
B[:,2,3] = @SVector [10, 11]
@test B[:,2,3] == @SVector [10, 11]
B[:,:,1] = @SMatrix [1 2 3; 4 5 6]
@test B[:,:,1] == @SMatrix [1 2 3; 4 5 6]
B[1,2,:] = [10, 11, 12, 13]
@test B[1,2,:] == @SVector [10, 11, 12, 13]
B[:,2,:] = @SMatrix [1 2 3 4; 5 6 7 8]
@test B[:,2,:] == @SMatrix [1 2 3 4; 5 6 7 8]
B[:,2,:] = [11 12 13 14; 15 16 17 18]
@test B[:,2,:] == [11 12 13 14; 15 16 17 18]
B[1,2,:] = @SVector [10, 11, 12, 13]
@test B[1,2,:] == @SVector [10, 11, 12, 13]
B[1,SA[2,1],SA[2,3]] = @SMatrix [10 11; 12 13]
@test B[1,SA[2,1],SA[2,3]] == @SMatrix [10 11; 12 13]
B[1,SA[2,1],SA[2,3]] = [14 15; 16 17]
@test B[1,SA[2,1],SA[2,3]] == @SMatrix [14 15; 16 17]
D[:,2,3,4] = @SVector [10, 11]
@test D[:,2,3,4] == @SVector [10, 11]
D[:,:,1,2] = @SMatrix [1 2 3; 4 5 6]
@test D[:,:,1,2] == @SMatrix [1 2 3; 4 5 6]
D[1,2,:,1] = [10, 11, 12, 13]
@test D[1,2,:,1] == @SVector [10, 11, 12, 13]
E = HybridArray{Tuple{}}(fill(10))
E[] = 12
@test E[] == 12
@test_throws DimensionMismatch (D[:,2,3,4] = @SVector [10, 11, 11])
@test_throws DimensionMismatch (D[:,2,3,4] = [10, 11, 11])
@test_throws DimensionMismatch (B[1,2,:] = [10, 11])
@test_throws ErrorException HybridArray.all_dynamic_fixed_val(typeof(B))
@test HybridArrays.all_dynamic_fixed_val(Tuple{}) === Val(:dynamic_fixed_true)
end
include("abstractarray.jl")
include("arraymath.jl")
include("broadcast.jl")
include("linalg.jl")
include("ssubarray.jl")
include("nonstandard_indices.jl")
include("array_interface_compat.jl")
include("static_array_interface_compat.jl")
include("forwarddiff.jl")
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 1063 | using Test, Random, HybridArrays, StaticArrays
######### Tests #########
@testset "Statically sized SubArray" begin
A = HybridArray{Tuple{2,2,StaticArrays.Dynamic()}}(fill(0.0, 2, 2, 10))
Av = view(A, :, :, SOneTo(3))
@test isa(Av, SizedArray{Tuple{2,2,3},Float64,3,3,SubArray{Float64,3,HybridArray{Tuple{2,2,StaticArrays.Dynamic()},Float64,3,3,Array{Float64,3}},Tuple{Base.Slice{SOneTo{2}},Base.Slice{SOneTo{2}},SOneTo{3}},true}})
@test (@inferred Av[:,:,1]) === SA[0.0 0.0; 0.0 0.0]
@test (@inferred Av[:,SOneTo(2),1]) === SA[0.0 0.0; 0.0 0.0]
@test StaticArrays.similar_type(Av) === SArray{Tuple{2,2,3},Float64,3,12}
# views that leave dynamically sized axes should return HybridArray (see issue #31)
B = HybridArray{Tuple{2,5,StaticArrays.Dynamic()}}(randn(2, 5, 3))
@test isa((@inferred view(B, :, StaticArrays.SUnitRange(2, 4), :)), HybridArray{Tuple{2,3,StaticArrays.Dynamic()},Float64,3,3,<:SubArray})
Bv = view(B, :, StaticArrays.SUnitRange(2, 4), :)
@test Bv == B[:, StaticArrays.SUnitRange(2, 4), :]
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | code | 1306 |
using HybridArrays, StaticArrayInterface, Test, StaticArrays
using StaticArrayInterface: StaticInt
@testset "StaticArrayInterface compatibility" begin
M = HybridMatrix{2, StaticArrays.Dynamic()}([1 2; 4 5])
MV = HybridMatrix{3, StaticArrays.Dynamic()}(view(randn(10, 10), 1:2:5, 1:3:12))
M2 = HybridArray{Tuple{2, 3, StaticArrays.Dynamic(), StaticArrays.Dynamic()}}(randn(2, 3, 5, 7))
@test (@inferred StaticArrayInterface.strides(M2)) === (StaticInt(1), StaticInt(2), StaticInt(6), 30)
@test (@inferred StaticArrayInterface.strides(MV)) === (2, 30)
@test StaticArrayInterface.contiguous_axis(typeof(M2)) === StaticArrayInterface.contiguous_axis(typeof(parent(M2)))
@test StaticArrayInterface.contiguous_batch_size(typeof(M2)) === StaticArrayInterface.contiguous_batch_size(typeof(parent(M2)))
@test StaticArrayInterface.stride_rank(typeof(M2)) === StaticArrayInterface.stride_rank(typeof(parent(M2)))
@test StaticArrayInterface.contiguous_axis(typeof(M')) === StaticArrayInterface.contiguous_axis(typeof(parent(M)'))
@test StaticArrayInterface.contiguous_batch_size(typeof(M')) === StaticArrayInterface.contiguous_batch_size(typeof(parent(M)'))
@test StaticArrayInterface.stride_rank(typeof(M')) === StaticArrayInterface.stride_rank(typeof(parent(M)'))
end
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.4.16 | 6c3e57bc26728b99f470b267a437f0d380eac4fc | docs | 2862 | | Status | Coverage |
| :----: | :----: |
| [](https://github.com/mateuszbaran/HybridArrays.jl/actions?query=workflow%3ACI+branch%3Amaster) | [ ](http://codecov.io/github/mateuszbaran/HybridArrays.jl?branch=master) |
# HybridArrays.jl
Arrays with both statically and dynamically sized axes in Julia. This is a convenient replacement for the commonly used `Arrays`s of `SArray`s which are fast but not easy to mutate. `HybridArray` makes this easier: any `AbstractArray` can be wrapped in a structure that specifies which axes are statically sized. Based on this information code for `getindex`, `setindex!` and broadcasting is (or should soon be, not all cases have been optimized yet) as efficient as for `Arrays`s of `SArray`s while mutation of single elements is possible, as well as other operations on the wrapped array.
Views are statically sized where possible for fast and convenient mutation of `HybridArray`s.
Example:
```julia
julia> using HybridArrays, StaticArrays
julia> A = HybridArray{Tuple{2,2,StaticArrays.Dynamic()}}(randn(2,2,100));
julia> A[1,1,10] = 12
12
julia> A[:,:,10]
2×2 SArray{Tuple{2,2},Float64,2,4} with indices SOneTo(2)×SOneTo(2):
12.0 -1.39943
-0.450564 -0.140096
julia> A[2,:,:]
2×100 HybridArray{Tuple{2,StaticArrays.Dynamic()},Float64,2,2,Array{Float64,2}} with indices SOneTo(2)×Base.OneTo(100):
-0.262977 1.40715 -0.110194 … -1.67315 2.30679 0.931161
-0.432229 3.04082 -0.00971933 -0.905037 -0.446818 0.777833
julia> A[:,:,10] .*= 2
2×2 SizedArray{Tuple{2,2},Float64,2,2,SubArray{Float64,2,HybridArray{Tuple{2,2,StaticArrays.Dynamic()},Float64,3,3,Array{Float64,3}},Tuple{Base.Slice{SOneTo{2}},Base.Slice{SOneTo{2}},Int64},true}} with indices SOneTo(2)×SOneTo(2):
24.0 -2.79886
-0.901128 -0.280193
julia> A[:,:,10] = SMatrix{2,2}(1:4)
2×2 SArray{Tuple{2,2},Int64,2,4} with indices SOneTo(2)×SOneTo(2):
1 3
2 4
```
`HybridArrays.jl` is implements (optionally loaded) [`ArrayInterface`](https://github.com/SciML/ArrayInterface.jl/) methods for compatibility with [`LoopVectorization`](https://github.com/chriselrod/LoopVectorization.jl).
Tips:
- If possible, statically known dimensions should come first. This way the most common access pattern where indices of dynamic dimensions are specified will be faster.
- Since version 0.4 of `HybridArrays`, Julia 1.5 or newer is required for best performance (most importantly the memory layout changes). It still works correctly on earlier versions of Julia but versions from the 0.3.x line may be faster in some cases on Julia <=1.4.
Code of this package is based on the code of the [`StaticArrays`](https://github.com/JuliaArrays/StaticArrays.jl).
| HybridArrays | https://github.com/JuliaArrays/HybridArrays.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 347 | using Documenter
using Starlight
makedocs(
sitename = "Starlight",
format = Documenter.HTML(),
modules = [Starlight]
)
# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
#=deploydocs(
repo = "<repository url>"
)=#
| Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 12025 | using Starlight
const window_width = 600
const window_height = 400
const paddle_width = 10
const paddle_height = 60
const ball_width = 10
const ball_height = 10
const wall_height = 10
const goal_width = 10
const hz = 1
# collision margins
const wmx = 0 # wall
const wmy = 0
const gmx = 0 # goal
const gmy = 0
const pmx = 0 # paddle
const pmy = 0
const bmx = 0 # ball
const bmy = 0
const pv = window_height # paddle velocity
const ball_vel_x_mult = 0.25
const ball_vel_y_mult = 1.5
const ball_vel_x = ball_vel_x_mult * window_width
const ball_vel_y_max = ball_vel_y_mult * window_height
const paddle_ball_x_tolerance = 2
ball_vel_y(i) = -i * ball_vel_y_max
const score_scale = 10
const score_y_offset = 50
const msg_scale = 2
const center_line_dash_w = 10
const center_line_dash_h = 40
const center_line_dash_spacing = 20
const asset_base = joinpath(artifact"test", "test")
const secs_between_rounds = 2
const score_to_win = 10
a = App(; wdth=window_width, hght=window_height, bgrd=colorant"black")
# center line
center_line = []
for i in (wall_height + center_line_dash_spacing):\
(center_line_dash_h + center_line_dash_spacing):\
(window_height - wall_height - center_line_dash_h - center_line_dash_spacing)
push!(center_line, ColorRect(center_line_dash_w, center_line_dash_h;
color=colorant"grey", pos=XYZ((window_width - center_line_dash_w) / 2, i)))
end
# working with Cellphone strings
cpchars = Dict(
' ' => [0,0],
'!' => [0,1],
'\"' => [0,2],
'#' => [0,3],
'$' => [0,4],
'%' => [0,5],
'&' => [0,6],
'\'' => [0,7],
'(' => [0,8],
')' => [0,9],
'*' => [0,10],
'+' => [0,11],
',' => [0,12],
'-' => [0,13],
'.' => [0,14],
'/' => [0,15],
'0' => [0,16],
'1' => [0,17],
'2' => [1,0],
'3' => [1,1],
'4' => [1,2],
'5' => [1,3],
'6' => [1,4],
'7' => [1,5],
'8' => [1,6],
'9' => [1,7],
':' => [1,8],
';' => [1,9],
'<' => [1,10],
'=' => [1,11],
'>' => [1,12],
'?' => [1,13],
'@' => [1,14],
'A' => [1,15],
'B' => [1,16],
'C' => [1,17],
'D' => [2,0],
'E' => [2,1],
'F' => [2,2],
'G' => [2,3],
'H' => [2,4],
'I' => [2,5],
'J' => [2,6],
'K' => [2,7],
'L' => [2,8],
'M' => [2,9],
'N' => [2,10],
'O' => [2,11],
'P' => [2,12],
'Q' => [2,13],
'R' => [2,14],
'S' => [2,15],
'T' => [2,16],
'U' => [2,17],
'V' => [3,0],
'W' => [3,1],
'X' => [3,2],
'Y' => [3,3],
'Z' => [3,4],
'[' => [3,5],
'\\' => [3,6],
']' => [3,7],
'^' => [3,8],
'_' => [3,9],
'`' => [3,10],
'a' => [3,11],
'b' => [3,12],
'c' => [3,13],
'd' => [3,14],
'e' => [3,15],
'f' => [3,16],
'g' => [3,17],
'h' => [4,0],
'i' => [4,1],
'j' => [4,2],
'k' => [4,3],
'l' => [4,4],
'm' => [4,5],
'n' => [4,6],
'o' => [4,7],
'p' => [4,8],
'q' => [4,9],
'r' => [4,10],
's' => [4,11],
't' => [4,12],
'u' => [4,13],
'v' => [4,14],
'w' => [4,15],
'x' => [4,16],
'y' => [4,17],
'z' => [5,0],
'{' => [5,1],
'|' => [5,2],
'}' => [5,3],
'~' => [5,4],
)
mutable struct CellphoneString <: Renderable
function CellphoneString(str="", white=true;
scale=XYZ(1,1), color=colorant"white", kw...)
instantiate!(new(); str=str, white=white, scale=scale, color=color, kw...)
end
end
function Starlight.draw(s::CellphoneString)
img = (s.white) ? joinpath(asset_base,
"sprites", "charmap-cellphone_white.png") : \
joinpath(asset_base,
"sprites", "charmap-cellphone_black.png")
for (i,c) in enumerate(s.str)
cell_ind = cpchars[c]
TS_VkCmdDrawSprite(img, vulkan_colors(s.color)...,
0, 0, 0, 0,
7, 9, cell_ind[1], cell_ind[2],
Int(floor(s.scale.x * 7)) * (i - 1) + s.abs_pos.x, s.abs_pos.y,
s.scale.x, s.scale.y)
end
end
# p1 score
score1 = CellphoneString('0'; color=colorant"grey",
scale=XYZ(score_scale, score_scale),
pos=XYZ((window_width / 2) - (window_width / 4) -
(7 * score_scale / 2), score_y_offset))
# p2 score
score2 = CellphoneString('0'; color=colorant"grey",
scale=XYZ(score_scale, score_scale),
pos=XYZ((window_width / 2) + (window_width / 4) -
(7 * score_scale / 2), score_y_offset))
# welcome message
msg = CellphoneString("Press SPACE to start", false;
scale=XYZ(msg_scale, msg_scale),
pos=XYZ((window_width - 140 * msg_scale) / 2,
(window_height - 9 * msg_scale) / 2))
@enum PongArenaSide LEFT RIGHT TOP BOTTOM
mutable struct PongPaddle <: Starlight.Renderable
function PongPaddle(w, h, side; kw...)
instantiate!(new(); w=w, h=h, side=side, color=colorant"white", kw...)
end
end
Starlight.draw(p::PongPaddle) = defaultDrawRect(p)
function Starlight.awake!(p::PongPaddle)
hw = paddle_width / 2
hh = paddle_height / 2
addTriggerBox!(p, hw, hh, hz, p.pos.x + hw, p.pos.y + hh, 0, pmx, pmy, 0)
end
function Starlight.shutdown!(p::PongPaddle)
removePhysicsObject!(p)
end
function Starlight.handleMessage!(p::PongPaddle, col::TS_CollisionEvent)
otherId = other(p, col)
if otherId == wallt.id
if p.id == p1.id
pg.p1TouchingTopWall = col.colliding
elseif p.id == p2.id
pg.p2TouchingTopWall = col.colliding
end
elseif otherId == wallb.id
if p.id == p1.id
pg.p1TouchingBottomWall = col.colliding
elseif p.id == p2.id
pg.p2TouchingBottomWall = col.colliding
end
end
end
# p1
p1 = PongPaddle(paddle_width, paddle_height, LEFT;
pos=XYZ(paddle_width, (window_height - paddle_height) / 2))
# p2
p2 = PongPaddle(paddle_width, paddle_height, RIGHT;
pos=XYZ(window_width - 2 * paddle_width,
(window_height - paddle_height) / 2))
mutable struct PongArenaWall <: Starlight.Renderable
function PongArenaWall(w, h, side; kw...)
instantiate!(new(); w=w, h=h, side=side, color=colorant"white", kw...)
end
end
Starlight.draw(p::PongArenaWall) = defaultDrawRect(p)
function Starlight.awake!(p::PongArenaWall)
hw = window_width / 2
hh = wall_height / 2
addTriggerBox!(p, hw, hh, hz, p.pos.x + hw, p.pos.y + hh, 0, wmx, wmy, 0)
end
function Starlight.shutdown!(p::PongArenaWall)
removePhysicsObject!(p)
end
# top wall
wallt = PongArenaWall(window_width, wall_height, TOP; pos=XYZ(0, 0))
# bottom wall
wallb = PongArenaWall(window_width, wall_height, BOTTOM;
pos=XYZ(0, window_height - wall_height))
mutable struct PongArenaGoal <: Starlight.Entity
function PongArenaGoal(w, h, side; kw...)
instantiate!(new(); w=w, h=h, side=side, kw...)
end
end
function Starlight.awake!(p::PongArenaGoal)
hw = goal_width / 2
hh = window_height / 2
addTriggerBox!(p, hw, hh, hz, p.pos.x + hw, p.pos.y + hh, 0, gmx, gmy, 0)
end
function Starlight.shutdown!(p::PongArenaGoal)
removePhysicsObject!(p)
end
# left goal
goal1 = PongArenaGoal(window_height * 2, goal_width, LEFT;
pos=XYZ(-goal_width, 0))
# right goal
goal2 = PongArenaGoal(window_height * 2, goal_width, RIGHT;
pos=XYZ(window_width, 0))
mutable struct PongBall <: Starlight.Renderable
function PongBall(w, h; kw...)
instantiate!(new(); w=w, h=h, color=colorant"white", kw...)
end
end
Starlight.draw(p::PongBall) = defaultDrawRect(p)
function Starlight.awake!(p::PongBall)
hw = ball_width / 2
hh = ball_height / 2
addTriggerBox!(p, hw, hh, hz, p.pos.x + hw, p.pos.y + hh, 0, bmx, bmy, 0)
end
function Starlight.shutdown!(p::PongBall)
removePhysicsObject!(p)
end
function hit_edge(p::PongBall, o::PongPaddle)
if o.side == LEFT
return p.abs_pos.x < (o.abs_pos.x + paddle_width - paddle_ball_x_tolerance)
else
return p.abs_pos.x > (o.abs_pos.x - ball_width + paddle_ball_x_tolerance)
end
end
function hit_angle(p::PongBall, o::PongPaddle)
paddle_top = o.abs_pos.y - ball_height / 2
ball_center = p.abs_pos.y + ball_height / 2
paddle_hit_area = paddle_height + ball_height
return -(2 * ((ball_center - paddle_top) / paddle_hit_area) - 1)
end
function wait_and_start_new_round(arg)
sleep(SLEEP_SEC(secs_between_rounds))
pg.ball = newball()
end
getP1Score() = parse(Int, score1.str)
getP2Score() = parse(Int, score2.str)
function Starlight.handleMessage!(p::PongBall, col::TS_CollisionEvent)
otherId = other(p, col)
vel = TS_BtGetLinearVelocity(p.id)
if col.colliding
if otherId ∈ [wallt.id, wallb.id]
TS_PlaySound(joinpath(asset_base,
"sounds", "ping_pong_8bit_plop.ogg"), 0, -1)
TS_BtSetLinearVelocity(p.id, vel.x, -vel.y, vel.z)
elseif otherId ∈ [goal1.id, goal2.id]
TS_PlaySound(joinpath(asset_base,
"sounds", "ping_pong_8bit_peeeeeep.ogg"), 0, -1)
destroy!(p)
if otherId == goal2.id
score1.str = string(getP1Score() + 1)
elseif otherId == goal1.id
score2.str = string(getP2Score() + 1)
end
if getP1Score() == score_to_win || getP2Score() == score_to_win
msg.hidden = false
score1.str = "0"
score2.str = "0"
else
oneshot!(clk(), wait_and_start_new_round)
end
elseif otherId ∈ [p1.id, p2.id]
TS_PlaySound(joinpath(asset_base,
"sounds", "ping_pong_8bit_beeep.ogg"), 0, -1)
o = getEntityById(otherId)
TS_BtSetLinearVelocity(p.id, (hit_edge(p, o) ? 1 : -1) * vel.x,
ball_vel_y(hit_angle(p, o)), vel.z)
end
end
end
mutable struct PongGame <: Starlight.Entity
function PongGame()
instantiate!(new(); ball=nothing, w=false, s=false, up=false, down=false,
p1TouchingTopWall=false, p2TouchingTopWall=false,
p1TouchingBottomWall=false, p2TouchingBottomWall=false)
end
end
function Starlight.awake!(p::PongGame)
listenFor(p, SDL_KeyboardEvent)
listenFor(p, SDL_QuitEvent)
TS_BtSetGravity(0, 0, 0)
end
function Starlight.shutdown!(p::PongGame)
unlistenFrom(p, SDL_KeyboardEvent)
unlistenFrom(p, SDL_QuitEvent)
end
function newball()
p = PongBall(ball_width, ball_height;
pos=XYZ((window_width - ball_width) / 2,
(window_height - ball_height) / 2))
TS_BtSetLinearVelocity(p.id,
((rand(Bool)) ? 1 : -1) * ball_vel_x, ball_vel_y(2 * rand() - 1), 0)
return p
end
function Starlight.handleMessage!(p::PongGame, key::SDL_KeyboardEvent)
if key.keysym.scancode == SDL_SCANCODE_SPACE && !msg.hidden
msg.hidden = true
p.ball = newball()
elseif key.keysym.scancode == SDL_SCANCODE_W
p.w = key.state == SDL_PRESSED
elseif key.keysym.scancode == SDL_SCANCODE_S
p.s = key.state == SDL_PRESSED
elseif key.keysym.scancode == SDL_SCANCODE_UP
p.up = key.state == SDL_PRESSED
elseif key.keysym.scancode == SDL_SCANCODE_DOWN
p.down = key.state == SDL_PRESSED
end
end
function Starlight.handleMessage!(p::PongGame, q::SDL_QuitEvent)
shutdown!(p)
end
function Starlight.update!(p::PongGame, Δ::AbstractFloat)
TS_BtSetLinearVelocity(p1.id, 0, 0, 0)
TS_BtSetLinearVelocity(p2.id, 0, 0, 0)
if p.w && !p.p1TouchingTopWall
TS_BtSetLinearVelocity(p1.id, 0, -pv, 0)
elseif p.s && !p.p1TouchingBottomWall
TS_BtSetLinearVelocity(p1.id, 0, pv, 0)
end
if p.up && !p.p2TouchingTopWall
TS_BtSetLinearVelocity(p2.id, 0, -pv, 0)
elseif p.down && !p.p2TouchingBottomWall
TS_BtSetLinearVelocity(p2.id, 0, pv, 0)
end
end
pg = PongGame()
run!(a)
# <!-- export handleMessage!, sendMessage, listenFor, unlistenFrom, handleException, dispatchMessage
# export App, awake!, shutdown!, run!, on, off
# export clk, ecs, inp, ts, phys, scn
# export Clock, TICK, SLEEP_NSEC, SLEEP_SEC
# export tick, job!, oneshot!
# export Entity, update!
# export ECS, XYZ, accumulate_XYZ
# export getEntityRow, getEntityById, getEntityRowById, getDfRowProp, setDfRowProp!
# export ECSIteratorState, Level
# export instantiate!, destroy!
# export Scene, scene_view
# export TS
# export to_ARGB, getSDLError, sdl_colors, vulkan_colors, clear
# export Root, Renderable
# export draw, ColorRect, Sprite
# export defaultDrawRect, defaultDrawSprite
# export Input
# export Physics
# export addRigidBox!, addStaticBox!, addTriggerBox!, removePhysicsObject!
# export other
# export Physics
# export addRigidBox!, addStaticBox!, addTriggerBox!, removePhysicsObject!
# export other --> | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 1284 | export Clock, TICK, SLEEP_NSEC, SLEEP_SEC
export tick, job!, oneshot!
mutable struct Clock
started::Base.Event
stopped::Bool
freq::AbstractFloat
Clock() = new(Base.Event(), true, 0.01667)
end
struct TICK
Δ::AbstractFloat # seconds
end
struct SLEEP_SEC
Δ::AbstractFloat
end
struct SLEEP_NSEC
Δ::UInt
end
function Base.sleep(s::SLEEP_SEC)
t1 = time()
while true
if time() - t1 >= s.Δ break end
yield()
end
return time() - t1
end
function Base.sleep(s::SLEEP_NSEC)
t1 = time_ns()
while true
if time_ns() - t1 >= s.Δ break end
yield()
end
return time_ns() - t1
end
function tick(Δ)
δ = sleep(SLEEP_NSEC(Δ * 1e9))
sendMessage(TICK(δ / 1e9))
@debug "tick"
end
function job!(c::Clock, f, arg=1)
function job()
Base.wait(c.started)
while !c.stopped
f(arg)
end
end
schedule(Task(job))
end
function oneshot!(c::Clock, f, arg=1)
function oneshot()
Base.wait(c.started)
f(arg)
end
schedule(Task(oneshot))
end
function awake!(c::Clock)
@debug "Clock awake!"
job!(c, tick, c.freq)
c.stopped = false
Base.notify(c.started)
end
function shutdown!(c::Clock)
@debug "Clock shutdown!"
c.stopped = true
c.started = Base.Event() # old one remains signaled no matter what, replace
end | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 7258 | export Entity, update!
export ECS, XYZ, accumulate_XYZ
export getEntityRow, getEntityById, getEntityRowById, getDfRowProp, setDfRowProp!
export ECSIteratorState, Level
export instantiate!, destroy!
export Scene, scene_view
abstract type Entity end
update!(e, Δ) = nothing
# magic symbols that getproperty and setproperty! (and end users) care about
const ENT = :ent
const TYPE = :type
const ID = :id
const PARENT = :parent
const CHILDREN = :children
const POSITION = :pos
const ROTATION = :rot
const ABSOLUTE_POSITION = :abs_pos
const ABSOLUTE_ROTATION = :abs_rot
const HIDDEN = :hidden
const PROPS = :props
# position, rotation, velocity, acceleration, whatever
mutable struct XYZ
x::Number
y::Number
z::Number
XYZ(x=0, y=0, z=0) = new(x, y, z)
end
import Base.+, Base.-, Base.*, Base.÷, Base./, Base.%
+(a::XYZ, b::XYZ) = XYZ(a.x+b.x,a.y+b.y,a.z+b.z)
-(a::XYZ, b::XYZ) = XYZ(a.x-b.x,a.y-b.y,a.z-b.z)
*(a::XYZ, b::Number) = XYZ(a.x*b,a.y*b,a.z*b)
÷(a::XYZ, b::Number) = XYZ(a.x÷b,a.y÷b,a.z÷b)
/(a::XYZ, b::Number) = XYZ(a.x/b,a.y/b,a.z/b)
%(a::XYZ, b::Number) = XYZ(a.x%b,a.y%b,a.z%b)
# columns of the in-memory database
const components = Dict(
ENT=>Entity,
TYPE=>DataType,
ID=>Number,
PARENT=>Number,
CHILDREN=>Set{Number},
POSITION=>XYZ,
ROTATION=>XYZ,
HIDDEN=>Bool,
PROPS=>Dict{Symbol, Any}
)
mutable struct ECS
df::DataFrame
awoken::Bool
lock::ReentrantLock
next_id::Number
function ECS()
df = DataFrame(
NamedTuple{Tuple(keys(components))}(
t[] for t in values(components)
))
return new(df, false, ReentrantLock(), 0)
end
end
# internally using Base.getproperty directly so
# as to not break if the symbol values change
getEntityRow(ent::Entity) = @view ecs().df[getproperty(ecs().df, ENT) .== [ent], :]
function getEntityById(id::Number)
arr = ecs().df[getproperty(ecs().df, ID) .== [id], ENT]
if length(arr) > 0
return arr[1]
end
return nothing
end
getEntityRowById(id::Number) = @view ecs().df[getproperty(ecs().df, ID) .== [id], :]
getDfRowProp(r, s) = r[!, s][1]
setDfRowProp!(r, s, x) = r[!, s][1] = x
function Base.propertynames(ent::Entity)
return (
keys(components)...,
ABSOLUTE_POSITION,
ABSOLUTE_ROTATION,
[n for n in keys(getproperty(ent, PROPS))]...
)
end
function Base.hasproperty(ent::Entity, s::Symbol)
return s in Base.propertynames(ent)
end
function accumulate_XYZ(r, s)
acc = XYZ()
while true
inc = getDfRowProp(r, s)
acc += inc
r = getEntityRowById(getDfRowProp(r, PARENT))
getDfRowProp(r, PARENT) != 0 || return acc
end
end
function Base.getproperty(ent::Entity, s::Symbol)
e = getEntityRow(ent)
if s == ABSOLUTE_POSITION return accumulate_XYZ(e, POSITION)
elseif s == ABSOLUTE_ROTATION return accumulate_XYZ(e, ROTATION)
elseif s in keys(components) return getDfRowProp(e, s)
elseif s in keys(getDfRowProp(e, PROPS)) return getDfRowProp(e, PROPS)[s]
else return getfield(ent, s)
end
end
function Base.setproperty!(ent::Entity, s::Symbol, x)
e = getEntityRow(ent)
if s in [
ENT, # immutable
TYPE, # automatically set
ID, # automatically set
ABSOLUTE_POSITION, # computed
ABSOLUTE_ROTATION # computed
]
error("cannot set property $(s) on Entity")
end
lock(ecs().lock)
if s == PARENT
par = getEntityById(getDfRowProp(e, PARENT))
push!(getproperty(par, CHILDREN), getDfRowProp(e, ID))
elseif s in keys(components) && s != PROPS
setDfRowProp!(e, s, x)
else
getDfRowProp(e, PROPS)[s] = x
end
unlock(ecs().lock)
end
Base.length(e::ECS) = size(e.df)[1]
# TODO: the type/struct approach feels clunky, fix with Vals?
abstract type ECSIterator end
mutable struct ECSIteratorState
root::Number
q::Queue{Number}
root_visited::Bool
index::Number
ECSIteratorState(; root=0, q=Queue{Number}(),
root_visited=false, index=1) = new(root, q, root_visited, index)
end
# refers to tree level, i.e. breadth-first,
# nothing special to see here
struct Level end
Base.length(l::Level) = length(ecs())
function Base.iterate(l::Level, state::ECSIteratorState=ECSIteratorState())
if isempty(state.q)
if !state.root_visited # just started
enqueue!(state.q, state.root)
state.root_visited = true
else # just finished
return nothing
end
end
ent = getEntityById(dequeue!(state.q))
for c in getproperty(ent, CHILDREN)
enqueue!(state.q, c)
end
return (ent, state)
end
function handleMessage!(e::ECS, m::TICK)
@debug "ECS tick"
try
map((ent) -> update!(ent, m.Δ), Level()) # TODO investigate parallelization
catch
handleException()
end
end
function awake!(e::ECS)
@debug "ECS awake!"
e.awoken = true
map(awake!, Level())
listenFor(e, TICK)
end
function shutdown!(e::ECS)
@debug "ECS shutdown!"
unlistenFrom(e, TICK)
map(shutdown!, Level())
e.awoken = false
end
function instantiate!(e::Entity; kw...)
lock(ecs().lock)
id = ecs().next_id
ecs().next_id += 1
# update ecs
# allows invalid parents and children for now
push!(ecs().df, Dict(
ENT=>e,
TYPE=>typeof(e),
ID=>id,
CHILDREN=>get(kw, CHILDREN, Set{Number}()),
PARENT=>get(kw, PARENT, 0),
POSITION=>get(kw, POSITION, XYZ()),
ROTATION=>get(kw, ROTATION, XYZ()),
HIDDEN=>get(kw, HIDDEN, false),
PROPS=>merge(get(kw, PROPS, Dict{Symbol, Any}()),
Dict(k=>v for (k,v) in kw if k ∉
[CHILDREN, PARENT, POSITION, ROTATION, HIDDEN, PROPS]))
))
if id != 0 # root has no parent but itself
par = getEntityById(get(kw, PARENT, 0))
push!(getproperty(par, CHILDREN), id)
end
unlock(ecs().lock)
if ecs().awoken awake!(e) end
return e
end
function destroy!(e::Entity)
shutdown!(e)
lock(ecs().lock)
p = getEntityById(getproperty(e, PARENT))
# if not root
if getproperty(p, ID) != getproperty(e, ID)
# update parent
delete!(getproperty(p, CHILDREN), getproperty(e, ID))
# update dataframe
deleteat!(ecs().df, getproperty(ecs().df, ENT) .== [e])
end
unlock(ecs().lock)
end
function destroy!(es...)
map(destroy!, es) # TODO investigate parallelization
end
# this is the scene graph, ladies and gentlemen,
# which we can traverse and mutate however we want
# during iteration, and initialize however we want
# and destroy however we want...sorry, it took me
# a long time to come up with this design, and i'm
# a little bit psyched about it. :)
scene_view() = ecs().df[(ecs().df.type .<: [Renderable]) .& (ecs().df.hidden .== [false]), :]
struct Scene end
Base.length(s::Scene) = size(scene_view())[1]
function Base.iterate(s::Scene, state::ECSIteratorState=ECSIteratorState())
# does reverse-z order for now, only
# suitable for simple 2d drawing
if state.index > length(s) return nothing end
ent = scene_view()[!, ENT][state.index]
state.index += 1
return (ent, state)
end
function awake!(s::Scene)
@debug "Scene awake!"
listenFor(s, TICK)
end
function shutdown!(s::Scene)
@debug "Scene shutdown!"
unlistenFrom(s, TICK)
end
function handleMessage!(s::Scene, m::TICK)
# sort just once per tick rather than every time we iterate
@debug "Scene tick"
try
sort!(ecs().df, [order(POSITION, rev=true, by=(pos)->pos.z)])
catch
handleException()
end
end | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 1571 | export Root, Renderable
export draw, ColorRect, Sprite
export defaultDrawRect, defaultDrawSprite
draw(e) = nothing
mutable struct Root <: Entity end # used for root of ECS tree
abstract type Renderable <: Entity end
mutable struct ColorRect <: Renderable
function ColorRect(w, h; color=colorant"white", kw...)
instantiate!(new(); w=w, h=h, color=color, kw...)
end
end
defaultDrawRect(r) = TS_VkCmdDrawRect(vulkan_colors(r.color)..., r.abs_pos.x, r.abs_pos.y, r.w, r.h)
draw(r::ColorRect) = defaultDrawRect(r)
mutable struct Sprite <: Renderable
# allow textures larger than a single sprite
# by supporting cell_size, cell_ind, and region
# fields. cell_size turns img into a matrix of
# adjacent regions of the same size starting in
# the top left of the texture. cell_ind is a 0-indexed
# (row,col) index into a particular cell. region
# overrides both and denotes the top-left corner
# of a rectangle, its width, and its height, and
# uses only that region of the texture.
function Sprite(img; cell_size=[0, 0], region=[0, 0, 0, 0], cell_ind=[0, 0],
color=colorant"white", scale=XYZ(1,1,1), kw...)
instantiate!(new(); img=img, cell_size=cell_size,
region=region, cell_ind=cell_ind, color=color,
scale=scale, kw...)
end
end
defaultDrawSprite(s) = TS_VkCmdDrawSprite(s.img, vulkan_colors(s.color)...,
s.region[1], s.region[2], s.region[3], s.region[4],
s.cell_size[1], s.cell_size[2], s.cell_ind[1], s.cell_ind[2],
s.abs_pos.x, s.abs_pos.y, s.scale.x, s.scale.y)
draw(s::Sprite) = defaultDrawSprite(s)
| Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 2167 | export Input
mutable struct Input end
function handleMessage!(i::Input, m::TICK)
@debug "Input tick"
evt_ref = Ref{SDL_Event}()
while Bool(SDL_PollEvent(evt_ref))
evt = evt_ref[]
ty = evt.type
if ty ∈ [SDL_AUDIODEVICEADDED, SDL_AUDIODEVICEREMOVED]
sendMessage(evt.adevice)
elseif ty == SDL_CONTROLLERAXISMOTION
sendMessage(evt.caxis)
elseif ty ∈ [SDL_CONTROLLERBUTTONDOWN, SDL_CONTROLLERBUTTONUP]
sendMessage(evt.cbutton)
elseif ty ∈ [SDL_CONTROLLERDEVICEADDED, SDL_CONTROLLERDEVICEREMOVED, SDL_CONTROLLERDEVICEREMAPPED]
sendMessage(evt.cdevice)
elseif ty ∈ [SDL_DOLLARGESTURE, SDL_DOLLARRECORD]
sendMessage(evt.dgesture)
elseif ty ∈ [SDL_DROPFILE, SDL_DROPTEXT, SDL_DROPBEGIN, SDL_DROPCOMPLETE]
sendMessage(evt.drop)
elseif ty ∈ [SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP]
sendMessage(evt.tfinger)
elseif ty ∈ [SDL_KEYDOWN, SDL_KEYUP]
sendMessage(evt.key)
elseif ty == SDL_JOYAXISMOTION
sendMessage(evt.jaxis)
elseif ty == SDL_JOYBALLMOTION
sendMessage(evt.jball)
elseif ty == SDL_JOYHATMOTION
sendMessage(evt.jhat)
elseif ty ∈ [SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP]
sendMessage(evt.jbutton)
elseif ty ∈ [SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED]
sendMessage(evt.jdevice)
elseif ty == SDL_MOUSEMOTION
sendMessage(evt.motion)
elseif ty ∈ [SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP]
sendMessage(evt.button)
elseif ty == SDL_MOUSEWHEEL
sendMessage(evt.wheel)
elseif ty == SDL_MULTIGESTURE
sendMessage(evt.mgesture)
elseif ty == SDL_QUIT
sendMessage(evt.quit)
elseif ty == SDL_SYSWMEVENT
sendMessage(evt.syswm)
elseif ty == SDL_TEXTEDITING
sendMessage(evt.edit)
elseif ty == SDL_TEXTINPUT
sendMessage(evt.text)
elseif ty == SDL_USEREVENT
sendMessage(evt.user)
elseif ty == SDL_WINDOWEVENT
sendMessage(evt.window)
else
sendMessage(evt)
end
end
end
function awake!(i::Input)
@debug "Input awake!"
listenFor(i, TICK)
end
function shutdown!(i::Input)
@debug "Input shutdown!"
unlistenFrom(i, TICK)
end
| Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 2251 | export Physics
export addRigidBox!, addStaticBox!, addTriggerBox!, removePhysicsObject!
export other
other(e::Entity, col::TS_CollisionEvent) = (e.id == col.id1) ? col.id2 : col.id1
mutable struct PhysicsObjectInfo
hx::AbstractFloat
hy::AbstractFloat
hz::AbstractFloat
m::AbstractFloat
isKinematic::Bool
mx::AbstractFloat
my::AbstractFloat
mz::AbstractFloat
PhysicsObjectInfo(hx = 0, hy = 0, hz = 0, m = 0, isKinematic = false, mx = 0, my = 0, mz = 0) = new(hx, hy, hz, m, isKinematic, mx, my, mz)
end
mutable struct Physics
ids::Dict{Number, PhysicsObjectInfo}
Physics() = new(Dict{Number, PhysicsObjectInfo}())
end
function addRigidBox!(e, hx, hy, hz, m, px, py, pz, isKinematic = false, mx = 0, my = 0, mz = 0)
phys().ids[e.id] = PhysicsObjectInfo(hx, hy, hz, m, isKinematic, mx, my, mz)
TS_BtAddRigidBox(e.id, hx + mx, hy + my, hz + mz, m, px, py, pz, isKinematic)
end
function addStaticBox!(e, hx, hy, hz, px, py, pz, mx = 0, my = 0, mz = 0)
phys().ids[e.id] = PhysicsObjectInfo(hx, hy, hz, 0.0, false, mx, my, mz)
TS_BtAddStaticBox(e.id, hx + mx, hy + my, hz + mz, px, py, pz)
end
function addTriggerBox!(e, hx, hy, hz, px, py, pz, mx = 0, my = 0, mz = 0)
phys().ids[e.id] = PhysicsObjectInfo(hx, hy, hz, 1.0, false, mx, my, mz)
TS_BtAddTriggerBox(e.id, hx + mx, hy + my, hz + mz, px, py, pz)
end
function removePhysicsObject!(e)
delete!(phys().ids, e.id)
TS_BtRemovePhysicsObject(e.id)
end
function handleMessage!(p::Physics, m::TICK)
@debug "Physics tick"
TS_BtStepSimulation()
for (id, pinfo) in p.ids
pos = TS_BtGetPosition(id)
# TODO: this is a bad hack for working specifically with rectangular objects, needs improvement
getEntityById(id).pos = XYZ(pos.x - pinfo.hx, pos.y - pinfo.hy, pos.z - pinfo.hz)
end
while true
col = TS_BtGetNextCollision()
if col.id1 == -1 && col.id2 == -1 break end
@debug "entities $(col.id1) and $(col.id2) have a collision event"
e1 = getEntityById(col.id1)
e2 = getEntityById(col.id2)
handleMessage!(e1, col)
handleMessage!(e2, col)
end
end
function awake!(p::Physics)
@debug "Physics awake!"
listenFor(p, TICK)
end
function shutdown!(p::Physics)
@debug "Physics shutdown!"
unlistenFrom(p, TICK)
end | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 4273 | module Starlight
using Reexport
@reexport using Base: ReentrantLock, lock, unlock
@reexport using FileIO: load
@reexport using Pkg.Artifacts
@reexport using LazyArtifacts
@reexport using DataStructures: Queue, enqueue!, dequeue!
@reexport using DataFrames
@reexport using Colors
@reexport using SimpleDirectMediaLayer
@reexport using SimpleDirectMediaLayer.LibSDL2
@reexport using Telescope
export handleMessage!, sendMessage, listenFor, unlistenFrom, handleException, dispatchMessage
export App, awake!, shutdown!, run!, on, off
export clk, ecs, inp, ts, phys, scn
const listeners = Dict{DataType, Set{Any}}()
const messages = Channel(Inf)
const listener_lock = ReentrantLock()
handleMessage!(l, m) = nothing
function sendMessage(m)
# drop if no one's listening
if haskey(listeners, typeof(m))
put!(messages, m)
end
end
function listenFor(e::Any, d::DataType)
lock(listener_lock)
if !haskey(listeners, d) listeners[d] = Set{Any}() end
push!(listeners[d], e)
unlock(listener_lock)
end
function unlistenFrom(e::Any, d::DataType)
lock(listener_lock)
if haskey(listeners, d) delete!(listeners[d], e) end
unlock(listener_lock)
end
function handleException()
for s in stacktrace(catch_backtrace())
println(s)
end
shutdown!(App())
end
# uses single argument to support
# being called as a job by a Clock,
# see Clock.jl for that interface
function dispatchMessage(arg)
@debug "dispatchMessage"
try
m = take!(messages) # NOTE messages are fully processed in the order they are received
d = typeof(m)
@debug "dequeued message $(m) of type $(d)"
if haskey(listeners, d)
# Threads.@threads doesn't work on raw sets
# because it needs to use indexing to split
# up memory, i work around it this way
Threads.@threads for l in Vector([listeners[d]...])
handleMessage!(l, m)
end
end
catch
handleException()
end
end
awake!(a) = nothing
shutdown!(a) = nothing
include("Clock.jl")
include("ECS.jl")
include("TS.jl")
include("Entities.jl")
include("Input.jl")
include("Physics.jl")
mutable struct App
systems::Dict{DataType, Any}
running::Bool
wdth::Int
hght::Int
bgrd::Colorant
function App(; wdth::Int=400, hght::Int=400, bgrd=colorant"grey")
# singleton pattern from Tom Kwong's book
global app
global app_lock
lock(app_lock)
try
if !isassigned(app)
a = new(Dict{DataType, Any}(), false, wdth, hght, bgrd)
system!(a, Clock())
system!(a, ECS())
system!(a, Scene())
system!(a, TS())
system!(a, Input())
system!(a, Physics())
app[] = finalizer(shutdown!, a)
# root pid is 0 (default) indicating "here and no further",
# always needed, also it will technically parent of itself.
# mutate at your own peril, but remember that a user can
# define update!(r::Root, Δ::AbstractFloat) if they want
instantiate!(Root())
end
catch e
rethrow()
finally
unlock(app_lock)
return app[]
end
end
end
const app = Ref{App}()
const app_lock = ReentrantLock()
# TODO: fix this, it feels hacky
clk() = app[].systems[Clock]
scn() = app[].systems[Scene]
ts() = app[].systems[TS]
inp() = app[].systems[Input]
ecs() = app[].systems[ECS]
phys() = app[].systems[Physics]
on(a::App) = a.running
off(a::App) = !a.running
# TODO: fix this with an ordered dict or something
systemAwakeOrder = () -> [clk(), ts(), inp(), phys(), ecs(), scn()]
systemShutdownOrder = () -> [clk(), inp(), phys(), scn(), ecs(), ts()]
# TODO: need an elegant way to remove systems
system!(a::App, s) = a.systems[typeof(s)] = s
# note that if running from a script the app will
# still exit when julia exits, it will never block.
# figuring out whether/how to keep it alive is
# on the user. see run! below for one method.
function awake!(a::App)
if !on(a)
job!(clk(), dispatchMessage) # this could be parallelized if not for mqueue_lock
map(awake!, systemAwakeOrder())
a.running = true
end
end
function shutdown!(a::App)
if !off(a)
map(shutdown!, systemShutdownOrder())
a.running = false
end
end
function run!(a::App)
awake!(a)
if !isinteractive()
while on(a)
yield()
end
end
end
end | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 1047 | export TS
export to_ARGB, getSDLError, sdl_colors, vulkan_colors, clear
mutable struct TS end
function draw()
TS_VkBeginDrawPass()
map(draw, scn()) # TODO investigate parallelization
TS_VkEndDrawPass(vulkan_colors(App().bgrd)...)
end
function handleMessage!(t::TS, m::TICK)
@debug "TS tick"
try
draw()
catch
handleException()
end
end
getSDLError() = unsafe_string(TS_SDLGetError())
to_ARGB(c) = c
to_ARGB(c::ARGB) = c
to_ARGB(c::Colorant) = ARGB(c)
sdl_colors(c::Colorant) = sdl_colors(convert(ARGB{Colors.FixedPointNumbers.Normed{UInt8,8}}, c))
sdl_colors(c::ARGB) = Int.(reinterpret.((red(c), green(c), blue(c), alpha(c))))
vulkan_colors(c::Colorant) = Cfloat.(sdl_colors(c) ./ 255)
clear() = fill(App().bgrd)
function Base.fill(c::Colorant)
TS_VkCmdClearColorImage(vulkan_colors(c)...)
end
function awake!(t::TS)
@debug "TS awake!"
TS_Init("Hello SDL!", App().wdth, App().hght)
draw()
listenFor(t, TICK)
end
function shutdown!(t::TS)
@debug "TS shutdown!"
unlistenFrom(t, TICK)
TS_Quit()
end | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | code | 1473 | using Starlight
using Test
# the namespace in front of the method name is important, apparently
Starlight.update!(r::Root, Δ::AbstractFloat) = r.updated = true
mutable struct TestEntity <: Entity end
Starlight.update!(t::TestEntity, Δ::AbstractFloat) = t.updated = true
@testset "Starlight" begin
# load test file
a = App()
# no systems should be running
@test off(a)
# kick off
awake!(a)
# all systems should be running
@test on(a)
# close
shutdown!(a)
# systems should no longer be running
@test off(a)
# ok back on
awake!(a)
# visual testing
# NOTE in SDL, (0,0) is top-left and y goes down
shapes = [
ColorRect(200, 200; color=colorant"blue", pos=XYZ(200, 200)),
Sprite(artifact"test/test/sprites/charmap-cellphone_black.png"; color=RGBA(1.0, 0, 0, 0.5), pos=XYZ(100, 100)),
]
# test manipulations on root
root = getEntityById(0)
root.updated = false
@test !root.updated
# takes just a little longer than a second
# for the first update to propagate when
# JULIA_DEBUG=Starlight, this fixes it
sleep(1.5)
@test root.updated
# manipulations on test entity
tst = TestEntity()
instantiate!(tst, props=Dict(
:updated=>false
))
@test !tst.updated
sleep(1)
@test tst.updated
destroy!(tst)
@test length(ecs()) == 3
destroy!(shapes...)
@test length(ecs()) == 1
shutdown!(a)
# root should remain and be unmodified
@test root.updated
@test off(a)
end
| Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | docs | 3120 | # Starlight.jl
Julia is a [greedy language](https://julialang.org/blog/2012/02/why-we-created-julia/), surrounded by a community of greedy people, who deserve greedy frameworks to make their greedy applications.
With a focus on flexibility and code quality, Starlight aims to be such a framework. It includes a suite of components and integrations that make it particuarly well-suited for video games, so it is not a stretch to call it a "game engine". However, Starlight is most fundamentally a scripting layer for [SDL](http://www.libsdl.org/), [Vulkan](https://www.vulkan.org/), and [Bullet](https://pybullet.org/wordpress/) (via the [Telescope](https://github.com/jhigginbotham64/Telescope) backend), meaning it can be used for any application that needs high-performance rendering and physics. Furthermore, there are plans to allow selective enabling of different subsystems, meaning it could be used for GUI apps or pure physics simulation or anything else you can imagine.
### Installation
In your Julia environment, you can simply
```julia-repl
julia> ] add Starlight
```
### Basic Usage
Starlight projects are simply Julia projects, no special structure or anything, so you simply declare that you are
```julia
julia> using Starlight
```
To take advantage of the magic of Starlight you must first create an App:
```julia
julia> a = App()
```
This gets you an internal clock, message bus, entity component system, rendering, physics, input, and sound, although it doesn't do anything with them yet. To open a window and start running the initialized subsystems, you can call
```julia
julia> awake!(a)
```
To close everything down, call
```julia
julia> shutdown!(a)
```
If running in a script you will need to keep the Julia process alive, so instead of `awake!(a)` you can use
```julia
julia> run!(a)
```
...which, as shown, works in the REPL as well.
Before you try doing anything interesting with the library, it is recommended that you read the docs.
### Contributing
We welcome issues, pull requests, everything. If there's a feature or use case we don't support and you don't have time to implement it yourself, create an issue. If you do have time, create a pull request. There's a ton of work to be done and only one active contributor. Anything you have to offer will be appreciated. Authors of pull requests will also get a special mention and a description of the work they did further down here in the README.
The maintainer is willing to personally mentor anyone who wants to either contribute or to learn Starlight for their own use cases. Contact information below. Please reach out.
#### Bounties
Some issues may have monetary rewards attached to them. Pull requests addressing these issues will be scrutinized more thoroughly than others. Get in touch with the maintainer to discuss payment arrangements.
##### No advance payments will be made under any circumstances
### Contact
You are invited to join us on [Discord](https://discord.gg/jUwaymK2as).
The maintainer is also reachable by [email](mailto:[email protected]) and typically answers within 24 hours. | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | docs | 3658 | # App Lifecycle
Everything begins with "the app". Your great idea. The grand plan. The next big thing.
Living organisms have a lifecycle. Products have a development lifecycle. Software has a runtime lifecycle.
Your app is going to have a lifecycle. In fact, it's going to have multiple layers of lifecycles. Your framework needs to help you manage all of them.
Let's start with the basics. Apps manage a variety of interlocking components that need to communicate with each other.
You can imagine having one "master" app managing a variety of "components" or "subsystems", which may be added or removed at random. These subsystems serve different purposes which can be represented by their types, and they manage data which may be contained in their instance.
So we can start with something like the following:
```julia
mutable struct App
systems::Dict{DataType, Any}
end
system!(a::App, s) = a.systems[typeof(s)] = s
```
This provides us with a simple mechanism to create a master app and add systems to it. But what kind of initialization needs to be performed? And how do you synchronize the initialization of the app with the initialization of the subsystems?
Well, for one thing, we're speaking in terms of a "master" app, so the [singleton pattern](https://en.wikipedia.org/wiki/Singleton_pattern) may be appropriate (see Tom Kwong's [book](https://www.ebooks.com/en-us/book/209928557/hands-on-design-patterns-and-best-practices-with-julia/tom-kwong/) for an explanation of how this works in Julia).
```julia
const app = Ref{App}()
const app_lock = ReentrantLock()
function App()
global app
global app_lock
lock(app_lock)
if !isassigned(app)
app[] = new(Dict{DataType, Any}())
end
unlock(app_lock)
return app[]
end
```
Systems may be added or removed at any time, but they all need to be synchronized with the master app. This means we have a second initialization phase, as well as the need for a shutdown phase, and some indication of whether the master app is "running". Having a common subsystem interface for initialization and shutdown would greatly simplify things.
We can add a field to our `App`, update the constructor, and add a couple of helper functions to get at on/off state:
```julia
mutable struct App
systems::Dict{DataType, Any}
running::Bool
end
function App()
...
app[] = new(Dict{DataType, Any}(), false)
...
end
on(a::App) = a.running
off(a::App) = !a.running
```
Now we can implement the following `App` lifecycle functions and use them as a starting point for our subsystem lifecycle interface:
```julia
awake!(s) = nothing
shutdown!(s) = nothing
function awake!(a::App)
if !on(a)
map(awake!, values(a.systems))
a.running = true
end
end
function shutdown!(a::App)
if !off(a)
map(shutdown!, values(a.systems))
a.running = false
end
end
```
Let's throw in a little helper for use in scripts:
```julia
function run!(a::App)
awake!(a)
if !isinteractive()
while on(a)
yield()
end
end
end
```
We now have a ready-made "destructor" for our `App`, trust us that our lives will be much easier if it gets called automatically:
```julia
function App()
...
app[] = finalizer(shutdown!,
new(Dict{DataType, Any}(), false))
...
end
```
We can now define subsystems in terms of their `awake!` and `shutdown!` methods and add them to our `App`. We can also access the master `App` by simply calling its constructor with no arguments, i.e. `App()`.
But we have no subsystems, and if they did they wouldn't do anything. Or rather, we have no mechanism for telling them what to do besides turning on and off. Time to fix that. | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | docs | 3587 | # Clock
So we need a `Clock` subsystem which uses its `awake!` and `shutdown!` functions to synchronize coroutines, and which also fires a periodic time event or "tick".
All of our coroutines need to be able to wait for the `Clock` to start, since they can be schedule any time before `awake!` is called. Ones that run periodically in the background need to be able to check whether the clock is still running, and the `Clock` itself needs to know how often to fire its tick event.
We can start with the following struct:
```julia
mutable struct Clock
started::Base.Event
stopped::Bool
freq::AbstractFloat
Clock() = new(Base.Event(), true, 0.01667) # 60 Hz
end
```
Background tasks might be scheduled as follows, with an optional `arg` parameter in case arguments need to be passed:
```julia
function job!(c::Clock, f, arg=1)
function job()
Base.wait(c.started)
while !c.stopped
f(arg)
end
end
schedule(Task(job))
end
```
One-off tasks might look similar, just without the loop:
```julia
function oneshot!(c::Clock, f, arg=1)
function oneshot()
Base.wait(c.started)
f(arg)
end
schedule(Task(oneshot))
end
```
What about firing tick events? How do we tell a background job to wait a certain length of time between executions, since it just gets called in an infinite loop? We could try using `sleep`, but that only gives us millisecond resolution. Fortunately Julia provides the tools we need to implement our own nanosecond `sleep` function, and it's not likely we'll need finer resolution than that.
```julia
struct TICK
Δ::AbstractFloat
end
struct SLEEP_NSEC
Δ::UInt
end
function Base.sleep(s::SLEEP_NSEC)
t1 = time_ns()
while true
if time_ns() - t1 >= s.Δ break end
yield()
end
return time_ns() - t1
end
function tick(Δ)
δ = sleep(SLEEP_NSEC(Δ * 1e9))
sendMessage(TICK(δ / 1e9))
end
```
Now we have everything we need to implement the `Clock`'s `awake!` and `shutdown!` functions:
```julia
function awake!(c::Clock)
job!(c, tick, c.freq)
c.stopped = false
Base.notify(c.started)
end
function shutdown!(c::Clock)
c.stopped = true
c.started = Base.Event() # old one remains signaled no matter what, replace
end
```
But we still need to tell the `App` about the `Clock`. Change the constructor's `if` block:
```julia
...
a = new(Dict{DataType, Any}(), false)
system!(a, Clock())
...
```
We can add an accessor function to get the "global clock":
```julia
clk() = app[].systems[Clock]
```
And now we can add the message dispatcher to `awake!`:
```julia
function awake!(a::App)
if !on(a)
job!(clk(), dispatchMessage)
map(awake!, values(a.systems))
a.running = true
end
end
```
If you add debug output to your code so far and run it, you'll notice it merrily dispatching and processing tick events at 60 Hz (after some startup lag from the compiler) much like in our earlier example.
The current approach of adding subsystems to the `App` doesn't scale well, since it requires modifying the constructor and adding a helper function for each subsystem. It's fine for a few important "static" systems that are considered part of the framework itself, but not for the vast number of objects that will be dynamically created, updated, used, and deleted within the lifetime of even a moderately complex program. And yet we still want these objects to be able to hook into the framework somehow so that they can be shared among subsystes and managed by the `App`. We can accomplish this with an [Entity Component System](https://en.wikipedia.org/wiki/Entity_component_system). | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | docs | 10876 | An [Entity Component System](https://en.wikipedia.org/wiki/Entity_component_system) (or "ECS" for short) is an in-memory object database where rows are instances and columns are properties. Arbitrary properties can be supported if one or more of the columns contain dictionaries.
Are we going to use database connectors and [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping)? Not exactly, but sort of. We definitely *could* do it that way, but it would be much more difficult to set up. We can achieve a similar effect, however, if we use a [DataFrame](https://dataframes.juliadata.org/stable/), an abstract type, and special methods for `getproperty` and `setproperty!`.
But what attributes is our DataFrame going to have? That depends on what semantics we want our data to have.
GUI applications, including video games, typically arrange objects in a tree, where child nodes move with their parent nodes. So we want to know what a node's local position and rotation are, and what its "absolute" (inherited + local) position and rotation are. We also need to keep track of parent nodes and lists of children. We need to be able to fetch nodes at any time, so being able to look them up by ID will be useful. Keeping track of the node's Julia type and instance will allow us to reuse the property-accessing semantics and apply operations to type-based subsets of nodes. Having a way to distinguish between what's visible in a window and what isn't may be useful. Finally, having a dictionary column will not only allow arbitrary properties, but it will allow users to create arbitrary custom types with appropriate semantics. This will come in handy later. A lot.
Let's start with that abstract type we mentioned. From here on out we're going to start referring to "entities", since they are not only nodes in a tree but also members of an entity component system.
```julia
abstract type Entity end
```
Let's establish what symbolic names we're going to use for our columns:
```julia
const ENT = :ent # entity, the original Julia object instance
const TYPE = :type
const ID = :id
const PARENT = :parent
const CHILDREN = :children
const POSITION = :pos
const ROTATION = :rot
const ABSOLUTE_POSITION = :abs_pos
const ABSOLUTE_ROTATION = :abs_rot
const HIDDEN = :hidden
const PROPS = :props
```
Position and rotation usually have X, Y, and Z components, and it's helpful to be able to refer to those components as properties. We're looking for a better way to do things, but for now the following will suffice:
```julia
mutable struct XYZ
x::Number
y::Number
z::Number
XYZ(x=0, y=0, z=0) = new(x, y, z)
end
import Base.+, Base.-, Base.*, Base.÷, Base./, Base.%
+(a::XYZ, b::XYZ) = XYZ(a.x+b.x,a.y+b.y,a.z+b.z)
-(a::XYZ, b::XYZ) = XYZ(a.x-b.x,a.y-b.y,a.z-b.z)
*(a::XYZ, b::Number) = XYZ(a.x*b,a.y*b,a.z*b)
÷(a::XYZ, b::Number) = XYZ(a.x÷b,a.y÷b,a.z÷b)
/(a::XYZ, b::Number) = XYZ(a.x/b,a.y/b,a.z/b)
%(a::XYZ, b::Number) = XYZ(a.x%b,a.y%b,a.z%b)
```
Now we can define the types that the columns of our DataFrame will have:
```julia
const components = Dict(
ENT=>Entity,
TYPE=>DataType,
ID=>Number,
PARENT=>Number,
CHILDREN=>Set{Number},
POSITION=>XYZ,
ROTATION=>XYZ,
HIDDEN=>Bool,
PROPS=>Dict{Symbol, Any}
)
```
Now we're almost ready to create our DataFrame. But first, a few more observations. We're still assuming a parallel environment where we don't know what order systems will be running in, so we need to synchronize access to the DataFrame. A simple lock will suffice. The ECS can also be responsible for calling the lifecycle functions of entities, but since these can be added or removed at any time, we need to know whether `awake!` has already been called. Finally, we need to keep track of what IDs are available and in use. A simple integer will do the trick.
With that our DataFrame and ECS struct become surprisingly simple:
```julia
mutable struct ECS
df::DataFrame
awoken::Bool
lock::ReentrantLock
next_id::Number
function ECS()
df = DataFrame(
NamedTuple{Tuple(keys(components))}(
t[] for t in values(components)
))
return new(df, false, ReentrantLock(), 0)
end
end
```
...but don't worry, there's plenty of complexity just around the corner. The reason is that we we're going to be implementing a tree structure on top of this DataFrame. We can now add an `ECS` to our `App`'s constructor...
```julia
...
system!(a, ECS())
...
```
...and the associated helper function...
```julia
ecs() = a.systems[ECS]
```
...but we're not ready to implement the `ECS`'s `awake!` and `shutdown!` just yet. We'll need to have tree traversal in place first, and for that we're going to need some custom iterators. And for that...well, we'll be looking at our entities' parent and children properties, so we'll need to start with getters and setters.
First, some helpers. The names are self-explanatory, but we encourage you to read up on the DataFrames documentation so as to understand what exactly they do.
```julia
# internally using Base.getproperty directly so
# as to not break if the symbol values change
getEntityRow(ent::Entity) = @view ecs().df[getproperty(ecs().df, ENT) .== [ent], :]
function getEntityById(id::Number)
arr = ecs().df[getproperty(ecs().df, ID) .== [id], ENT]
if length(arr) > 0
return arr[1]
end
return nothing
end
getEntityRowById(id::Number) = @view ecs().df[getproperty(ecs().df, ID) .== [id], :]
getDfRowProp(r, s) = r[!, s][1]
setDfRowProp!(r, s, x) = r[!, s][1] = x
```
Then a bit more custom-property boilerplate:
```julia
function Base.propertynames(ent::Entity)
return (
keys(components)...,
ABSOLUTE_POSITION,
ABSOLUTE_ROTATION,
[n for n in keys(getproperty(ent, PROPS))]...
)
end
function Base.hasproperty(ent::Entity, s::Symbol)
return s in Base.propertynames(ent)
end
```
Then the fun part:
```julia
function accumulate_XYZ(r, s)
acc = XYZ()
while true
inc = getDfRowProp(r, s)
acc += inc
r = getEntityRowById(getDfRowProp(r, PARENT))
getDfRowProp(r, PARENT) != 0 || return acc
end
end
function Base.getproperty(ent::Entity, s::Symbol)
e = getEntityRow(ent)
if s == ABSOLUTE_POSITION return accumulate_XYZ(e, POSITION)
elseif s == ABSOLUTE_ROTATION return accumulate_XYZ(e, ROTATION)
elseif s in keys(components) return getDfRowProp(e, s)
elseif s in keys(getDfRowProp(e, PROPS)) return getDfRowProp(e, PROPS)[s]
else return getfield(ent, s)
end
end
function Base.setproperty!(ent::Entity, s::Symbol, x)
e = getEntityRow(ent)
if s in [
ENT, # immutable
TYPE, # automatically set
ID, # automatically set
ABSOLUTE_POSITION, # computed
ABSOLUTE_ROTATION # computed
]
error("cannot set property $(s) on Entity")
end
lock(ecs().lock)
if s == PARENT
par = getEntityById(getDfRowProp(e, PARENT))
push!(getproperty(par, CHILDREN), getDfRowProp(e, ID))
elseif s in keys(components) && s != PROPS
setDfRowProp!(e, s, x)
else
getDfRowProp(e, PROPS)[s] = x
end
unlock(ecs().lock)
end
```
We just threw a lot at you. Take some time to digest it before moving on.
We're going to want to use `map` with `awake!` on entities, which means we need a custom iterator type for the `ECS` as well as a `length` function. Since we'll eventually want to iterate multiple different ways, we'll define special iterator types rather than just an iterator for `ECS`. The first one will be `Level`, i.e. traversing nodes by tree level, or in breadth-first order.
This is all we need to make that happen:
```julia
Base.length(e::ECS) = size(e.df)[1]
struct Level end
Base.length(l::Level) = length(ecs())
mutable struct ECSIteratorState
root::Number
q::Queue{Number}
root_visited::Bool
index::Number
ECSIteratorState(; root=0, q=Queue{Number}(),
root_visited=false, index=1) = new(root, q, root_visited, index)
end
function Base.iterate(l::Level, state::ECSIteratorState=ECSIteratorState())
if isempty(state.q)
if !state.root_visited # just started
enqueue!(state.q, state.root)
state.root_visited = true
else # just finished
return nothing
end
end
ent = getEntityById(dequeue!(state.q))
for c in getproperty(ent, CHILDREN)
enqueue!(state.q, c)
end
return (ent, state)
end
```
Now we can add `awake!` and `shutdown!`:
```julia
function awake!(e::ECS)
e.awoken = true
map(awake!, Level())
listenFor(e, TICK)
end
function shutdown!(e::ECS)
unlistenFrom(e, TICK)
map(shutdown!, Level())
e.awoken = false
end
```
And about that tick handler...having entities that call an update function every frame is a very common use case that we want to support. We could just define tick handlers for all new entity types, but that's a lot of boilerplate and doesn't allow us to ensure that entities are updated in a deterministic order, in case that becomes important. So we have the following:
```julia
update!(e, Δ) = nothing
function handleMessage!(e::ECS, m::TICK)
map((ent) -> update!(ent, m.Δ), Level())
end
```
Now entities can simply define an `update!` method and it will be called every frame deterministically.
So we can work with entities and with the `ECS`, but how do we actually add and remove entities?
We have to handle assigning their ID's, keeping parent and child information updated, and also allow users to define any initial values for custom properties. Notice that we've been assuming that there is a "root" note with an ID of 0. This is the first entity that will be created, and we'll get to it in a moment.
But first, here's how you add a new entity instance to the `ECS`:
```julia
function instantiate!(e::Entity; kw...)
lock(ecs().lock)
id = ecs().next_id
ecs().next_id += 1
push!(ecs().df, Dict(
ENT=>e,
TYPE=>typeof(e),
ID=>id,
CHILDREN=>get(kw, CHILDREN, Set{Number}()),
PARENT=>get(kw, PARENT, 0),
POSITION=>get(kw, POSITION, XYZ()),
ROTATION=>get(kw, ROTATION, XYZ()),
HIDDEN=>get(kw, HIDDEN, false),
PROPS=>merge(get(kw, PROPS, Dict{Symbol, Any}()),
Dict(k=>v for (k,v) in kw if k ∉
[CHILDREN, PARENT, POSITION, ROTATION, HIDDEN, PROPS]))
))
if id != 0
par = getEntityById(get(kw, PARENT, 0))
push!(getproperty(par, CHILDREN), id)
end
unlock(ecs().lock)
if ecs().awoken awake!(e) end
return e
end
```
And here's how you remove them:
```julia
function destroy!(e::Entity)
shutdown!(e)
lock(ecs().lock)
p = getEntityById(getproperty(e, PARENT))
# if not root
if getproperty(p, ID) != getproperty(e, ID)
# update parent
delete!(getproperty(p, CHILDREN), getproperty(e, ID))
# update dataframe
deleteat!(ecs().df, getproperty(ecs().df, ENT) .== [e])
end
unlock(ecs().lock)
end
function destroy!(es...)
map(destroy!, es)
end
```
And now we have a functioning entity component system. | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | docs | 3265 | # Getting Started
Starlight aims to offload as much work as possible onto the underlying libraries while still giving you, the developer, fine-grained control over your application's behavior: it provides useful abstraction, but gets out of the way when you need it to. The reason it can do this is its microkernel architecture, which models all subsystems as running independently of each other while exchanging data through a message bus. What exactly this means and how it works will be explained shortly. To give you an idea what to expect, let's review some content from the README.
To get started with Starlight, first add it to your project:
```julia-repl
julia> ] add Starlight
```
You can then declare that you are
```julia-repl
julia> using Starlight
```
From there, in order to initialize the various subsystems, you must create an `App`:
```julia-repl
julia> a = App()
```
To kick everything off and open a window, you can call
```julia-repl
julia> awake!(a)
```
To shut everything down, you (fittingly) call
```julia-repl
julia> shutdown!(a)
```
Starlight scripts should use `run!` instead of `awake!` to keep the Julia process alive. A minimal Starlight script could look something like the following:
```julia
using Starlight
a = App()
run!(a)
```
Doing that in a shell session with debug output enabled gives you an idea of just how much is going on behind the blank window that gets created:
```
jhigginbotham64:Starlight (main) $ JULIA_DEBUG=Starlight julia -e 'using Starlight; a = App(); run!(a)'
┌ Debug: Clock awake!
└ @ Starlight ~/.julia/dev/Starlight/src/Clock.jl:66
┌ Debug: TS awake!
└ @ Starlight ~/.julia/dev/Starlight/src/TS.jl:41
┌ Debug: dispatchMessage
└ @ Starlight ~/.julia/dev/Starlight/src/Starlight.jl:57
┌ Debug: Input awake!
└ @ Starlight ~/.julia/dev/Starlight/src/Input.jl:64
┌ Debug: tick
└ @ Starlight ~/.julia/dev/Starlight/src/Clock.jl:44
┌ Debug: Physics awake!
└ @ Starlight ~/.julia/dev/Starlight/src/Physics.jl:64
┌ Debug: dequeued message TICK(1.99813325) of type TICK
└ @ Starlight ~/.julia/dev/Starlight/src/Starlight.jl:61
┌ Debug: ECS awake!
└ @ Starlight ~/.julia/dev/Starlight/src/ECS.jl:198
┌ Debug: tick
└ @ Starlight ~/.julia/dev/Starlight/src/Clock.jl:44
┌ Debug: Scene awake!
└ @ Starlight ~/.julia/dev/Starlight/src/ECS.jl:289
┌ Debug: TS tick
└ @ Starlight ~/.julia/dev/Starlight/src/TS.jl:15
┌ Debug: Input tick
└ @ Starlight ~/.julia/dev/Starlight/src/Input.jl:6
┌ Debug: tick
└ @ Starlight ~/.julia/dev/Starlight/src/Clock.jl:44
┌ Debug: Physics tick
└ @ Starlight ~/.julia/dev/Starlight/src/Physics.jl:45
┌ Debug: dispatchMessage
└ @ Starlight ~/.julia/dev/Starlight/src/Starlight.jl:57
┌ Debug: dequeued message TICK(0.191819018) of type TICK
└ @ Starlight ~/.julia/dev/Starlight/src/Starlight.jl:61
```
There are several things to notice here. First and most importantly is that all subsystems (including the clock) communicate using the same event bus (you'll soon see that they even define methods for the same functions). Second is that pretty much nothing happens until `awake!` is called on the `App`. Finally, there is a clock synchronizing everything.
We're going to dwell on each of these points in turn before diving into the more specialized individual subsystems. | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | docs | 1524 | # Starlight.jl
Welcome to the documentation for Starlight.jl, a greedy application framework for [greedy developers](https://julialang.org/blog/2012/02/why-we-created-julia/). Its primary use case is video games, but the power of Julia, [SDL](http://www.libsdl.org/), [Vulkan](https://www.vulkan.org/), and [Bullet](https://pybullet.org/wordpress/) can be leveraged to make just about anything you want.
The walkthrough follows a storytelling approach where a Starlight-like framework is built from scratch. Hopefully this will help you understand the source code better. In any case it is highly recommended that you read everything in order, at least the first time.
It also presupposes knowledge of the Julia programming language. Patterns will be discussed, but core features like multiple dispatch will not. [Make sure you have a good grasp of Julia before proceeding](https://docs.julialang.org/en/v1/).
!!! note
The struct and method names used in the walkthrough are mostly
the same as the ones used in Starlight's own source code. By
reading the guide you learn not only Starlight's API but its
source code as well, albeit in slightly simplified form.
!!! warning
The purpose of the walkthrough is to prepare you to read the API
docs and source code, but not everything there is the same as in
the walkthgouh. Use the walkthrough to ground yourself in
Starlight's design philosophy and core concepts, but try not to
confuse the "classroom" and "real world" versions. | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.0 | 250c012ae1ab51ce9b514ed85c9c77dbf964f76b | docs | 3919 | # Message Passing
We alluded earlier to Starlight's [microkernel](https://en.wikipedia.org/wiki/Microkernel) architecture. This architecture is essentially a combination of Starlight's lifecycle functions and its message passing system.
Returning to our "framework from scratch" narrative, we need a mechanism for telling subsystems what to do. Ideally we wouldn't have them busy-waiting for instructions, and we also want to maintain our mental model of subsystems executing independently of each other (even if running on a single thread). What we're describing is an [event-driven programming model](https://en.wikipedia.org/wiki/Event-driven_programming), and in fact the terms "event handling" and "message passing" are mostly interchangeable in Starlight's vocabulary.
We'll need to manage a set of event handlers for each type of event. These "handlers" might also be called "listeners", and we can start by keeping them in a dictionary:
```julia
const listeners = Dict{DataType, Set{Any}}()
```
Event order may be important, and access to the queue needs to be synchronized since even on a single thread we don't know what order the subsystems will be running in. Julia provides [Channels](https://docs.julialang.org/en/v1/base/parallel/#Channels) for exactly this use case:
```julia
const messages = Channel(Inf)
```
Now we can define simple functions for sending and listening for messages, throwing in a synchronization primitive since we're assuming a parallel environment:
```julia
function sendMessage(m)
if haskey(listeners, typeof(m))
put!(messages, m)
end
end
const listener_lock = ReentrantLock()
function listenFor(e::Any, d::DataType)
lock(listener_lock)
if !haskey(listeners, d) listeners[d] = Set{Any}() end
push!(listeners[d], e)
unlock(listener_lock)
end
function unlistenFrom(e::Any, d::DataType)
lock(listener_lock)
if haskey(listeners, d) delete!(listeners[d], e) end
unlock(listener_lock)
end
```
...but receiving messages is a little bit trickier. We have listeners, but who tells them about events? Keeping that question in mind, we can write a function to dispatch a single message that can be called from wherever-because-we-don't-know-yet (note the trivial parallelization):
```julia
handleMessage!(l, m) = nothing
function dispatchMessage()
m = take!(messages)
d = typeof(m)
if haskey(listeners, d)
Threads.@threads for l in Vector([listeners[d]...])
handleMessage!(l, m)
end
end
end
```
...so, in theory, anyone who wants to receive an event could
1. Define a custom data type
2. Create an instance of that data type
3. Call `listenFor` with their instance
4. Have their `handleMessage!` function invoked automatically when events are processed
5. Call `unlistenFrom` when finished
This is, in fact, exactly the workflow that subsystems implement in order to process events. Their `awake!` and `shutdown!` functions even provide the perfect opportunity to call `listenFor` and `unlistenFrom` respectively.
But whose job is it to call `dispatchMessage`?
Let's outline some requirements:
1. Start processing messages when the `App` `awake!`s
2. Stop processing messages when the `App` `shutdown!`s
3. Run "in the background" so that it can yield to other processes if there are no messages
Sounds like our event dispatcher needs to run inside a coroutine managed by a subsystem that synchronizes tasks.
But we're not quite there yet. To finally answer the question of what we actually need, we need to ask one further question: what events do the various subsystems listen for? We've assumed that they'll be running continuously, but also responding to events. How do you do both at the same time?
One way is to model the passage of time as an event that subsystems listen for, and fire that event from another coroutine.
For that we could use a `Clock`, which will be the first subsystem we implement. | Starlight | https://github.com/jhigginbotham64/Starlight.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 416 | using Documenter, NbodyGradient
makedocs(sitename="NbodyGradient",
modules = [NbodyGradient],
format = Documenter.HTML(
prettyurls = get(ENV, "CI", nothing) == "true"
),
pages = [
"Index" => "index.md",
"Tutorials" => ["basic.md", "gradients.md"],
"API" => "api.md"
]
)
deploydocs(
repo = "github.com/ericagol/NbodyGradient.jl.git",
devbranch="master"
)
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 5435 |
using NbodyGradient, LinearAlgebra, Statistics
export State
#include("../src/ttv.jl")
#include("/Users/ericagol/Software/TRAPPIST1_Spitzer/src/NbodyGradient/src/ttv.jl")
# Specify the initial conditions for the outer solar
# system
#n=6
n=5
xout = zeros(3,n)
# Positions at time September 5, 1994 at 0h00 in days (from Hairer, Lubich & Wanner
# 2006, Geometric Numerical Integration, 2nd Edition, Springer, pp. 13-14):
xout .= transpose([-2.079997415328555E-04 7.127853194812450E-03 -1.352450694676177E-05;
-3.502576700516146E+00 -4.111754741095586E+00 9.546978009906396E-02;
9.075323061767737E+00 -3.443060862268533E+00 -3.008002403885198E-01;
8.309900066449559E+00 -1.782348877489204E+01 -1.738826162402036E-01;
1.147049510166812E+01 -2.790203169301273E+01 3.102324955757055E-01]) #;
#-1.553841709421204E+01 -2.440295115792555E+01 7.105854443660053E+00])
vout = zeros(3,n)
vout .= transpose([-6.227982601533108E-06 2.641634501527718E-06 1.564697381040213E-07;
5.647185656190083E-03 -4.540768041260330E-03 -1.077099720398784E-04;
1.677252499111402E-03 5.205044577942047E-03 -1.577215030049337E-04;
3.535508197097127E-03 1.479452678720917E-03 -4.019422185567764E-05;
2.882592399188369E-03 1.211095412047072E-03 -9.118527716949448E-05]) #;
#2.754640676017983E-03 -2.105690992946069E-03 -5.607958889969929E-04]);
# Units of velocity are AU/day
# Specify masses, including terrestrial planets in the Sun:
m = [1.00000597682,0.000954786104043,0.000285583733151,
0.0000437273164546,0.0000517759138449] #,6.58086572e-9];
# Compute the center-of-mass:
vcm = zeros(3);
xcm = zeros(3);
for j=1:n
vcm .+= m[j]*vout[:,j];
xcm .+= m[j]*xout[:,j];
end
vcm ./= sum(m);
xcm ./= sum(m);
# Adjust so CoM is stationary
for j=1:n
vout[:,j] .-= vcm[:];
xout[:,j] .-= xcm[:];
end
struct CartesianElements{T} <: NbodyGradient.InitialConditions{T}
x::Matrix{T}
v::Matrix{T}
m::Vector{T}
nbody::Int64
end
ic = CartesianElements(xout,vout,m,5);
function NbodyGradient.State(ic::NbodyGradient.InitialConditions{T}) where T<:AbstractFloat
n = ic.nbody
x = copy(ic.x)
v = copy(ic.v)
jac_init = zeros(7*n,7*n)
xerror = zeros(T,size(x))
verror = zeros(T,size(v))
jac_step = Matrix{T}(I,7*n,7*n)
dqdt = zeros(T,7*n)
dqdt_error = zeros(T,size(dqdt))
jac_error = zeros(T,size(jac_step))
rij = zeros(T,3)
a = zeros(T,3,n)
aij = zeros(T,3)
x0 = zeros(T,3)
v0 = zeros(T,3)
input = zeros(T,8)
delxv = zeros(T,6)
rtmp = zeros(T,3)
return State(x,v,[0.0],copy(ic.m),jac_step,dqdt,jac_init,xerror,verror,dqdt_error,jac_error,n,
rij,a,aij,x0,v0,input,delxv,rtmp)
end
function compute_energy(m::Array{T,1},x::Array{T,2},v::Array{T,2},n::Int64) where {T <: Real}
KE = 0.0
for j=1:n
KE += 0.5*m[j]*(v[1,j]^2+v[2,j]^2+v[3,j]^2)
end
PE = 0.0
for j=1:n-1
for k=j+1:n
PE += -NbodyGradient.GNEWT*m[j]*m[k]/norm(x[:,j] .- x[:,k])
end
end
ang_mom = zeros(3)
for j=1:n
ang_mom .+= m[j]*cross(x[:,j],v[:,j])
end
return KE,PE,ang_mom
end
# Now, integrate this forward in time:
hgrid = [50.0]
#power = 30
power = 22
#power = 20
#power = 15
nstepgrid = [2^power]
# 50 days x 1e8 time steps ~ 13,700,000 yr (should take about 1500 seconds to run)
grad = false
nstepmax = maximum(nstepgrid)
ngrid = 1
#xsave = zeros(3,n,nstepmax,ngrid)
#vsave = zeros(3,n,nstepmax,ngrid)
nskip = 1
energy = zeros(div(nstepmax,nskip))
#PE = zeros(nstepmax,ngrid); KE=zeros(nstepmax,ngrid); ang_mom = zeros(3,nstepmax,ngrid)
t = zeros(div(nstepmax,nskip))
telapse = zeros(ngrid)
nprint = 2^18
etmp = zeros(nskip)
for j=1:ngrid
h = hgrid[j]
nstep = nstepgrid[j];
s = State(ic)
pair = zeros(Bool,s.n,s.n)
if grad; d = Derivatives(T,s.n); end
# Set up array to save the state as a function of time:
# Save the potential & kinetic energy, as well as angular momentum:
# Time the integration:
tstart = time()
# Carry out the integration:
itmp = 1
for i=1:nstep
if grad
ahl21!(s,d,h,pair)
else
ahl21!(s,h,pair)
end
# xsave[:,:,i,j] .= s.x
# vsave[:,:,i,j] .= s.v
KE_step,PE_step,ang_mom_step=compute_energy(s.m,s.x,s.v,n)
# KE[i,j] = KE_step
# PE[i,j] = PE_step
# ang_mom[:,i,j] = ang_mom_step
etmp[itmp] = KE_step+PE_step
# println(itmp," ",etmp[itmp])
if itmp == nskip
t[div(i,nskip)] = h*i
energy[div(i,nskip)] = mean(etmp)
# println(itmp," ",t[div(i,nskip)]," ",energy[div(i,nskip)])
itmp = 0
end
if mod(i,nprint) == 0
println(i," ",i/nstep*100.0," ",time()-tstart)
end
itmp += 1
end
s.t[1] = h*nstep
telapse[j] = time()- tstart
println("h: ",h," nstep: ",nstep," time: ",telapse[j])
end
using PyPlot,Statistics
clf()
#energy = KE[:,1] .+ PE[:,1]
emean = mean(energy)
energy .-= emean
#plot(t,energy)
escatter = Float64[]
nbin = Int64[]
for i=1:power-2
binsize = 2^i
tbin = zeros(div(nstepmax,binsize*nskip))
ebin = zeros(div(nstepmax,binsize*nskip))
for j=1:div(nstepmax,binsize*nskip)
tbin[j] = mean(t[(j-1)*binsize+1:j*binsize])
ebin[j] = mean(energy[(j-1)*binsize+1:j*binsize])
end
if i == 10
plot(tbin,ebin,label=string("bin size ",binsize))
end
push!(nbin,binsize)
push!(escatter,std(ebin))
end
legend()
xlabel("Time [d]")
ylabel(L"Energy $M_\odot$ AU$^2$ day$^{-2}$")
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 5883 |
using NbodyGradient, LinearAlgebra
export State
#include("../src/ttv.jl")
#include("/Users/ericagol/Software/TRAPPIST1_Spitzer/src/NbodyGradient/src/ttv.jl")
# Specify the initial conditions for the outer solar
# system
#n=6
n=5
xout = zeros(3,n)
# Positions at time September 5, 1994 at 0h00 in days (from Hairer, Lubich & Wanner
# 2006, Geometric Numerical Integration, 2nd Edition, Springer, pp. 13-14):
xout .= transpose([0.0,0.0,0.0;
-3.5023653, -3.8169847, -1.5507963;
9.0755314, -3.0458353, -1.6483708;
8.3101420, -16.2901086, -7.2521278;
11.4707666, -25.7294829, -10.8169456])
vout .= transpose([0.0,0.0,0.0;
0.00565429, -0.00412490, -0.00190589;
.00168318, .00483525, .00192462;
.00354178, .00137102, .00055029;
.00288930, .00114527, .00039677])
#xout .= transpose([-2.079997415328555E-04 7.127853194812450E-03 -1.352450694676177E-05;
# -3.502576700516146E+00 -4.111754741095586E+00 9.546978009906396E-02;
# 9.075323061767737E+00 -3.443060862268533E+00 -3.008002403885198E-01;
# 8.309900066449559E+00 -1.782348877489204E+01 -1.738826162402036E-01;
# 1.147049510166812E+01 -2.790203169301273E+01 3.102324955757055E-01]) #;
# #-1.553841709421204E+01 -2.440295115792555E+01 7.105854443660053E+00])
vout = zeros(3,n)
#vout .= transpose([-6.227982601533108E-06 2.641634501527718E-06 1.564697381040213E-07;
# 5.647185656190083E-03 -4.540768041260330E-03 -1.077099720398784E-04;
# 1.677252499111402E-03 5.205044577942047E-03 -1.577215030049337E-04;
# 3.535508197097127E-03 1.479452678720917E-03 -4.019422185567764E-05;
# 2.882592399188369E-03 1.211095412047072E-03 -9.118527716949448E-05]) #;
# #2.754640676017983E-03 -2.105690992946069E-03 -5.607958889969929E-04]);
# Units of velocity are AU/day
# Specify masses, including terrestrial planets in the Sun:
m = [1.00000597682,0.000954786104043,0.000285583733151,
0.0000437273164546,0.0000517759138449] #,6.58086572e-9];
# Compute the center-of-mass:
vcm = zeros(3);
xcm = zeros(3);
for j=1:n
vcm .+= m[j]*vout[:,j];
xcm .+= m[j]*xout[:,j];
end
vcm ./= sum(m);
xcm ./= sum(m);
# Adjust so CoM is stationary
for j=1:n
vout[:,j] .-= vcm[:];
xout[:,j] .-= xcm[:];
end
struct CartesianElements{T} <: NbodyGradient.InitialConditions{T}
x::Matrix{T}
v::Matrix{T}
m::Vector{T}
nbody::Int64
end
ic = CartesianElements(xout,vout,m,5);
function NbodyGradient.State(ic::NbodyGradient.InitialConditions{T}) where T<:AbstractFloat
n = ic.nbody
x = copy(ic.x)
v = copy(ic.v)
jac_init = zeros(7*n,7*n)
xerror = zeros(T,size(x))
verror = zeros(T,size(v))
jac_step = Matrix{T}(I,7*n,7*n)
dqdt = zeros(T,7*n)
dqdt_error = zeros(T,size(dqdt))
jac_error = zeros(T,size(jac_step))
rij = zeros(T,3)
a = zeros(T,3,n)
aij = zeros(T,3)
x0 = zeros(T,3)
v0 = zeros(T,3)
input = zeros(T,8)
delxv = zeros(T,6)
rtmp = zeros(T,3)
return State(x,v,[0.0],copy(ic.m),jac_step,dqdt,jac_init,xerror,verror,dqdt_error,jac_error,n,
rij,a,aij,x0,v0,input,delxv,rtmp)
end
function compute_energy(m::Array{T,1},x::Array{T,2},v::Array{T,2},n::Int64) where {T <: Real}
KE = 0.0
for j=1:n
KE += 0.5*m[j]*(v[1,j]^2+v[2,j]^2+v[3,j]^2)
end
PE = 0.0
for j=1:n-1
for k=j+1:n
PE += -NbodyGradient.GNEWT*m[j]*m[k]/norm(x[:,j] .- x[:,k])
end
end
ang_mom = zeros(3)
for j=1:n
ang_mom .+= m[j]*cross(x[:,j],v[:,j])
end
return KE,PE,ang_mom
end
# Now, integrate this forward in time:
hgrid = [50.0]
#power = 30
power = 32
#power = 20
#power = 15
nstepgrid = [2^power]
# 50 days x 1e8 time steps ~ 13,700,000 yr (should take about 1500 seconds to run)
grad = false
nstepmax = maximum(nstepgrid)
ngrid = 1
#xsave = zeros(3,n,nstepmax,ngrid)
#vsave = zeros(3,n,nstepmax,ngrid)
nskip = 2^8
energy = zeros(div(nstepmax,nskip))
#PE = zeros(nstepmax,ngrid); KE=zeros(nstepmax,ngrid); ang_mom = zeros(3,nstepmax,ngrid)
t = zeros(div(nstepmax,nskip))
telapse = zeros(ngrid)
nprint = 2^26
etmp = zeros(nskip)
for j=1:ngrid
h = hgrid[j]
nstep = nstepgrid[j];
s = State(ic)
pair = zeros(Bool,s.n,s.n)
if grad; d = Derivatives(T,s.n); end
# Set up array to save the state as a function of time:
# Save the potential & kinetic energy, as well as angular momentum:
# Time the integration:
tstart = time()
# Carry out the integration:
itmp = 1
for i=1:nstep
if grad
ahl21!(s,d,h,pair)
else
ahl21!(s,h,pair)
end
# xsave[:,:,i,j] .= s.x
# vsave[:,:,i,j] .= s.v
KE_step,PE_step,ang_mom_step=compute_energy(s.m,s.x,s.v,n)
# KE[i,j] = KE_step
# PE[i,j] = PE_step
# ang_mom[:,i,j] = ang_mom_step
etmp[itmp] = KE_step+PE_step
# println(itmp," ",etmp[itmp])
if itmp == nskip
t[div(i,nskip)] = h*i
energy[div(i,nskip)] = mean(etmp)
# println(itmp," ",t[div(i,nskip)]," ",energy[div(i,nskip)])
itmp = 0
end
if mod(i,nprint) == 0
println(i," ",i/nstep*100.0," ",time()-tstart)
end
itmp += 1
end
s.t[1] = h*nstep
telapse[j] = time()- tstart
println("h: ",h," nstep: ",nstep," time: ",telapse[j])
end
using PyPlot,Statistics
clf()
#energy = KE[:,1] .+ PE[:,1]
emean = mean(energy)
energy .-= emean
#plot(t,energy)
escatter = Float64[]
nbin = Int64[]
for i=1:power-14
binsize = 2^i
tbin = zeros(div(nstepmax,binsize*nskip))
ebin = zeros(div(nstepmax,binsize*nskip))
for j=1:div(nstepmax,binsize*nskip)
tbin[j] = mean(t[(j-1)*binsize+1:j*binsize])
ebin[j] = mean(energy[(j-1)*binsize+1:j*binsize])
end
if i == 11
plot(tbin,ebin,label=string("bin size ",binsize))
end
push!(nbin,binsize)
push!(escatter,std(ebin))
end
legend()
xlabel("Time [d]")
ylabel(L"Energy $M_\odot$ AU$^2$ day$^{-2}$")
tight_layout()
savefig("Energy_error_vs_timestep.pdf",bbox_inches="tight")
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 5685 |
using NbodyGradient, LinearAlgebra
export State
#include("../src/ttv.jl")
#include("/Users/ericagol/Software/TRAPPIST1_Spitzer/src/NbodyGradient/src/ttv.jl")
# Specify the initial conditions for the outer solar
# system
#n=6
n=5
xout = zeros(3,n)
# Positions at time September 5, 1994 at 0h00 in days (from Hairer, Lubich & Wanner
# 2006, Geometric Numerical Integration, 2nd Edition, Springer, pp. 13-14):
xout .= transpose([-2.079997415328555E-04 7.127853194812450E-03 -1.352450694676177E-05;
-3.502576700516146E+00 -4.111754741095586E+00 9.546978009906396E-02;
9.075323061767737E+00 -3.443060862268533E+00 -3.008002403885198E-01;
8.309900066449559E+00 -1.782348877489204E+01 -1.738826162402036E-01;
1.147049510166812E+01 -2.790203169301273E+01 3.102324955757055E-01]) #;
#-1.553841709421204E+01 -2.440295115792555E+01 7.105854443660053E+00])
vout = zeros(3,n)
vout .= transpose([-6.227982601533108E-06 2.641634501527718E-06 1.564697381040213E-07;
5.647185656190083E-03 -4.540768041260330E-03 -1.077099720398784E-04;
1.677252499111402E-03 5.205044577942047E-03 -1.577215030049337E-04;
3.535508197097127E-03 1.479452678720917E-03 -4.019422185567764E-05;
2.882592399188369E-03 1.211095412047072E-03 -9.118527716949448E-05]) #;
#2.754640676017983E-03 -2.105690992946069E-03 -5.607958889969929E-04]);
# Units of velocity are AU/day
# Specify masses, including terrestrial planets in the Sun:
m = [1.00000597682,0.000954786104043,0.000285583733151,
0.0000437273164546,0.0000517759138449] #,6.58086572e-9];
# Compute the center-of-mass:
vcm = zeros(3);
xcm = zeros(3);
for j=1:n
vcm .+= m[j]*vout[:,j];
xcm .+= m[j]*xout[:,j];
end
vcm ./= sum(m);
xcm ./= sum(m);
# Adjust so CoM is stationary
for j=1:n
vout[:,j] .-= vcm[:];
xout[:,j] .-= xcm[:];
end
struct CartesianElements{T} <: NbodyGradient.InitialConditions{T}
x::Matrix{T}
v::Matrix{T}
m::Vector{T}
nbody::Int64
end
ic = CartesianElements(xout,vout,m,5);
function NbodyGradient.State(ic::NbodyGradient.InitialConditions{T}) where T<:AbstractFloat
n = ic.nbody
x = copy(ic.x)
v = copy(ic.v)
jac_init = zeros(7*n,7*n)
xerror = zeros(T,size(x))
verror = zeros(T,size(v))
jac_step = Matrix{T}(I,7*n,7*n)
dqdt = zeros(T,7*n)
dqdt_error = zeros(T,size(dqdt))
jac_error = zeros(T,size(jac_step))
rij = zeros(T,3)
a = zeros(T,3,n)
aij = zeros(T,3)
x0 = zeros(T,3)
v0 = zeros(T,3)
input = zeros(T,8)
delxv = zeros(T,6)
rtmp = zeros(T,3)
return State(x,v,[0.0],copy(ic.m),jac_step,dqdt,jac_init,xerror,verror,dqdt_error,jac_error,n,
rij,a,aij,x0,v0,input,delxv,rtmp)
end
function compute_energy(m::Array{T,1},x::Array{T,2},v::Array{T,2},n::Int64) where {T <: Real}
KE = 0.0
for j=1:n
KE += 0.5*m[j]*(v[1,j]^2+v[2,j]^2+v[3,j]^2)
end
PE = 0.0
for j=1:n-1
for k=j+1:n
PE += -NbodyGradient.GNEWT*m[j]*m[k]/norm(x[:,j] .- x[:,k])
end
end
ang_mom = zeros(3)
for j=1:n
ang_mom .+= m[j]*cross(x[:,j],v[:,j])
end
return KE,PE,ang_mom
end
# Now, integrate this forward in time:
hgrid = [1.5625,3.125,6.25,12.5,25.0,50.0,100.0,200.0]
nstepgrid = [32000000,16000000,8000000,4000000,2000000,1000000,500000,250000]
nskip = [128,64,32,16,8,4,2,1]
#h = 200.0 # 200-day time-step chosen to be <1/20 of the orbital period of Jupiter
#h = 100.0 # 100-day time-step chosen to check conservation of energy/angular momentum with time step
#h = 50.0 # 50-day time-step chosen to check conservation of energy/angular momentum with time step
h = 25.0 # 25-day time-step chosen to check conservation of energy/angular momentum with time step
#h = 12.5 # 12.5-day time-step chosen to check conservation of energy/angular momentum with time step
#h = 6.25 # 6.25-day time-step chosen to check conservation of energy/angular momentum with time step
#h = 3.125 # 3.125-day time-step chosen to check conservation of energy/angular momentum with time step
#h = 1.5625 # 1.5625-day time-step chosen to check conservation of energy/angular momentum with time step
# 50 days x 1e6 time steps ~ 137,000 yr (takes about 15 seconds to run)
grad = false
nstep = maximum(nstepgrid)
ngrid = 8
xsave = zeros(3,n,nstep,ngrid)
vsave = zeros(3,n,nstep,ngrid)
PE = zeros(nstep,ngrid); KE=zeros(nstep,ngrid); ang_mom = zeros(3,nstep,ngrid)
telapse = zeros(ngrid)
for j=1:8
h = hgrid[j]
nstep = nstepgrid[j];
s = State(ic)
pair = zeros(Bool,s.n,s.n)
if grad; d = Derivatives(T,s.n); end
# Set up array to save the state as a function of time:
# Save the potential & kinetic energy, as well as angular momentum:
# Time the integration:
tstart = time()
# Carry out the integration:
for i=1:nstep
if grad
ahl21!(s,d,h,pair)
else
ahl21!(s,h,pair)
end
xsave[:,:,i,j] .= s.x
vsave[:,:,i,j] .= s.v
KE_step,PE_step,ang_mom_step=compute_energy(s.m,s.x,s.v,n)
KE[i,j] = KE_step
PE[i,j] = PE_step
ang_mom[:,i,j] = ang_mom_step
end
s.t[1] = h*nstep
telapse[j] = time()- tstart
println("h: ",h," nstep: ",nstep," time: ",telapse[j])
end
using PyPlot,Statistics
for j=8:-1:1
plot(collect(1:1:nstepgrid[j])*hgrid[j],KE[1:nstepgrid[j],j] .+ PE[1:nstepgrid[j],j]); println(j," ",hgrid[j]," ",std(KE[1:nstepgrid[j],j] .+ PE[1:nstepgrid[j],j])); Emean[j] = mean(KE[1:nstepgrid[j],j] .+ PE[1:nst
end
read(stdin,Char)
clf()
loglog(hgrid,(Emean .- minimum(Emean)) ./abs(minimum(Emean)) ,"o")
loglog(hgrid,(Emean[8] .- minimum(Emean) ) ./abs(minimum(Emean)) .* (hgrid ./ hgrid[8]).^4 )
xlabel("Time step [d]")
ylabel("Fractional change in mean energy")
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 2055 | function insolarpluto(m::Array{T,1},xout::Array{T,2},vout::Array{T,2},pair::Array{Int64,2}) where {T <: Real}
# global YEAR GNEWT
# Below data from Hairer pg. 13-14. Convert time to years.
# Distance is in AU, mass in solar masses.
fac = 1;
m = fac*[1.00000597682,0.000954786104043,0.000285583733151,
0.0000437273164546,0.0000517759138449,6.58086572e-9];
m[1] = 1.00000;
n = length(m);
for i=1:n
for j=1:n
# Kepler solver group
if i == 1 || j == 1
pair[i,j] = 0;
pair[j,i] = 0;
else
pair[i,j] = 1;
pair[j,i] = 1;
end
end
end
xout = [-2.079997415328555E-04, 7.127853194812450E-03,-1.352450694676177E-05,
-3.502576700516146E+00,-4.111754741095586E+00, 9.546978009906396E-02,
9.075323061767737E+00,-3.443060862268533E+00,-3.008002403885198E-01,
8.309900066449559E+00,-1.782348877489204E+01,-1.738826162402036E-01,
1.147049510166812E+01,-2.790203169301273E+01, 3.102324955757055E-01,
-1.553841709421204E+01,-2.440295115792555E+01, 7.105854443660053E+00]
xout = xout';
vout = [-6.227982601533108E-06, 2.641634501527718E-06, 1.564697381040213E-07,
5.647185656190083E-03,-4.540768041260330E-03,-1.077099720398784E-04,
1.677252499111402E-03, 5.205044577942047E-03,-1.577215030049337E-04,
3.535508197097127E-03, 1.479452678720917E-03,-4.019422185567764E-05,
2.882592399188369E-03, 1.211095412047072E-03,-9.118527716949448E-05,
2.754640676017983E-03,-2.105690992946069E-03,-5.607958889969929E-04];
vout = vout';
vout = vout*YEAR;
xout = xout[:,1:n];
vout = vout[:,1:n];
vcm = zeros(3,1);
xcm = zeros(3,1);
for j=1:n
vcm[:] = vcm[:]+m[j]*vout[:,j];
xcm[:] = xcm[:]+m[j]*xout[:,j];
end
vcm = vcm/sum(m);
xcm = xcm/sum(m);
# Adjust so CoM is stationary
for j=1:n
vout[:,j] = vout[:,j]-vcm[:];
xout[:,j] = xout[:,j]-xcm[:];
end
# Add CoM velocity
vcm = 100*vcm;
vcm = 0*vcm;
for j=1:n
vout[:,j] = vout[:,j] + vcm[:];
end
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 992 | """
NbodyGradient
An N-body itegrator that computes derivatives with respect to initial conditions for TTVs, RV, Photodynamics, and more.
"""
module NbodyGradient
using LinearAlgebra, DelimitedFiles
using FileIO, JLD2
# Constants used by most functions
# Need to clean this up
const NDIM = 3
const YEAR = 365.242
const GNEWT = 39.4845/(YEAR*YEAR)
const third = 1.0/3.0
const alpha0 = 0.0
# Types
export Elements, ElementsIC, CartesianIC, InitialConditions
export State, dState
export Integrator
export Jacobian, dTime
export CartesianOutput, ElementsOutput
export TransitTiming, TransitParameters, TransitSnapshot
# Integrator methods
export ahl21!, dh17!
# Utility functions
export available_systems, get_default_ICs
# Source code
include("PreAllocArrays.jl")
include("ics/InitialConditions.jl")
include("integrator/Integrator.jl")
include("utils.jl")
include("outputs/Outputs.jl")
include("transits/Transits.jl")
# To be cleaned up
# include("integrator/ah18/ah18_old.jl")
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 3602 | abstract type PreAllocArrays end
abstract type AbstractDerivatives{T} <: PreAllocArrays end
struct Jacobian{T<:AbstractFloat} <: AbstractDerivatives{T}
jac_phi::Matrix{T}
jac_kick::Matrix{T}
jac_copy::Matrix{T}
jac_ij::Matrix{T}
jac_tmp1::Matrix{T}
jac_tmp2::Matrix{T}
jac_err1::Matrix{T}
dqdt_ij::Vector{T}
dqdt_phi::Vector{T}
dqdt_kick::Vector{T}
function Jacobian(::Type{T},n::Integer) where T<:AbstractFloat
sevn::Int64 = 7*n
jac_phi = zeros(T,sevn,sevn)
jac_kick = zeros(T,sevn,sevn)
jac_copy = zeros(T,sevn,sevn)
jac_ij = zeros(T,14,14)
jac_tmp1 = zeros(T,14,sevn)
jac_tmp2 = zeros(T,14,sevn)
jac_err1 = zeros(T,14,sevn)
dqdt_ij = zeros(T,14)
dqdt_phi = zeros(T,sevn)
dqdt_kick = zeros(T,sevn)
return new{T}(jac_phi,jac_kick,jac_copy,jac_ij,jac_tmp1,jac_tmp2,jac_err1,
dqdt_ij,dqdt_phi,dqdt_kick)
end
end
struct dTime{T<:AbstractFloat} <: AbstractDerivatives{T}
jac_phi::Matrix{T}
jac_kick::Matrix{T}
jac_ij::Matrix{T}
dqdt_phi::Vector{T}
dqdt_kick::Vector{T}
dqdt_ij::Vector{T}
dqdt_tmp1::Vector{T}
dqdt_tmp2::Vector{T}
jac_kepler::Matrix{T}
jac_mass::Vector{T}
function dTime(::Type{T},n::Integer) where T<:AbstractFloat
sevn::Int64 = 7*n
jac_phi = zeros(T,sevn,sevn)
jac_kick = zeros(T,sevn,sevn)
jac_ij = zeros(T,14,14)
dqdt_phi = zeros(T,sevn)
dqdt_kick = zeros(T,sevn)
dqdt_ij = zeros(T,14)
dqdt_tmp1 = zeros(T,14)
dqdt_tmp2 = zeros(T,14)
jac_kepler = zeros(T,6,8)
jac_mass = zeros(T,6)
return new{T}(jac_phi,jac_kick,jac_ij,dqdt_phi,dqdt_kick,dqdt_ij,
dqdt_tmp1,dqdt_tmp2,jac_kepler,jac_mass)
end
end
struct Derivatives{T<:AbstractFloat} <: AbstractDerivatives{T}
jac_phi::Matrix{T}
jac_kick::Matrix{T}
jac_copy::Matrix{T}
jac_ij::Matrix{T}
jac_tmp1::Matrix{T}
jac_tmp2::Matrix{T}
jac_err1::Matrix{T}
dqdt_phi::Vector{T}
dqdt_kick::Vector{T}
dqdt_ij::Vector{T}
dqdt_tmp1::Vector{T}
dqdt_tmp2::Vector{T}
jac_kepler::Matrix{T}
jac_mass::Vector{T}
dadq::Array{T,4}
dotdadq::Matrix{T}
tmp7n::Vector{T}
tmp14::Vector{T}
ctime::Vector{T}
function Derivatives(::Type{T},n::Integer) where T<:AbstractFloat
sevn::Int64 = 7*n
jac_phi = zeros(T,sevn,sevn)
jac_kick = zeros(T,sevn,sevn)
jac_copy = zeros(T,sevn,sevn)
jac_ij = zeros(T,14,14)
jac_tmp1 = zeros(T,14,sevn)
jac_tmp2 = zeros(T,14,sevn)
jac_err1 = zeros(T,14,sevn)
dqdt_phi = zeros(T,sevn)
dqdt_kick = zeros(T,sevn)
dqdt_ij = zeros(T,14)
dqdt_tmp1 = zeros(T,14)
dqdt_tmp2 = zeros(T,14)
jac_kepler = zeros(T,6,8)
jac_mass = zeros(T,6)
dadq = zeros(T,3,n,4,n)
dotdadq = zeros(T,4,n)
tmp7n = zeros(T,sevn)
tmp14 = zeros(T,14)
ctime = zeros(T,1)
return new{T}(jac_phi,jac_kick,jac_copy,jac_ij,jac_tmp1,jac_tmp2,jac_err1,
dqdt_phi,dqdt_kick,dqdt_ij,dqdt_tmp1,dqdt_tmp2,jac_kepler,jac_mass,
dadq,dotdadq,tmp7n,tmp14,ctime)
end
end
"""Zero out each array in Derivatives."""
@generated function zero_out!(d::Derivatives{T}) where T<:AbstractFloat
exprs = Vector{Expr}()
for f in fieldnames(Derivatives)
expr = :(d.$f .= 0.0)
push!(exprs,expr)
end
return Expr(:block, exprs..., nothing)
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 14177 |
# Some utility functions
#================================ Compensated Summation =================================#
"""
comp_sum(sum_value,sum_error,addend)
Kahan (1965) compensated summation for `T<:Real`.
...
# Arguments
- `sum_value::Real` : Current value of the sum.
- `sum_error::Real` : Error from truncation/rounding accumulated from prior steps.
- `addend::Real` : New value to be added to the sum.
...
"""
function comp_sum(sum_value::T,sum_error::T,addend::T) where {T <: Real}
tmp = zero(T)
sum_error += addend
tmp = sum_value + sum_error
sum_error = (sum_value - tmp) + sum_error
sum_value = tmp
return sum_value,sum_error
end
"""
comp_sum_matrix!(sum_value,sum_error,addend)
Kahan (1965) compenstated summation for `::Matrix{<:Real}`.
...
# Arguments
- `sum_value::Matrix{<:Real}` : Current value of the sum.
- `sum_error::Matrix{<:Real}` : Error from truncation/rounding accumulated from prior steps.
- `addend::Matrix{<:Real}` : New value to be added to the sum.
...
"""
function comp_sum_matrix!(sum_value::Array{T,2},sum_error::Array{T,2},addend::Array{T,2}) where {T <: Real}
tmp = zero(T)
@inbounds for i in eachindex(sum_value)
sum_error[i] += addend[i]
tmp = sum_value[i] + sum_error[i]
# sum_error[i] = (sum_value[i] - tmp) + sum_error[i]
sum_error[i] += sum_value[i] - tmp
sum_value[i] = tmp
end
return
end
"""
Copies portion of Jacobian for multiplication
"""
function copy_submatrix!(s::State{T},d::Derivatives{T},indi::Int64,indj::Int64,sevn::Int64) where T <: AbstractFloat
# Pick out indices for bodies i & j:
@inbounds for k2=1:sevn, k1=1:7
d.jac_tmp1[k1,k2] = s.jac_step[ indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
d.jac_err1[k1,k2] = s.jac_error[indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
d.jac_tmp1[7+k1,k2] = s.jac_step[ indj+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
d.jac_err1[7+k1,k2] = s.jac_error[indj+k1,k2]
end
# Copy current time derivatives for multiplication purposes:
@inbounds for k1=1:7
d.dqdt_tmp1[ k1] = s.dqdt[indi+k1]
end
@inbounds for k1=1:7
d.dqdt_tmp1[7+k1] = s.dqdt[indj+k1]
end
return
end
"""
Copies back:
"""
function ypoc_submatrix!(s::State{T},d::Derivatives{T},indi::Int64,indj::Int64,sevn::Int64) where T <: AbstractFloat
# Copy back to the Jacobian:
@inbounds for k2=1:sevn, k1=1:7
s.jac_step[ indi+k1,k2]=d.jac_tmp1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
s.jac_error[indi+k1,k2]=d.jac_err1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
s.jac_step[ indj+k1,k2]=d.jac_tmp1[7+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
s.jac_error[indj+k1,k2]=d.jac_err1[7+k1,k2]
end
# Copy back time derivatives:
@inbounds for k1=1:7
s.dqdt[indi+k1] = d.dqdt_ij[ k1]
end
@inbounds for k1=1:7
s.dqdt[indj+k1] = d.dqdt_ij[7+k1]
end
return
end
#================================ Integrator Utilities ==================================#
function cubic1(a::T, b::T, c::T) where {T <: Real}
a3 = a*third
Q = a3^2 - b*third
R = a3^3 + 0.5*(-a3*b + c)
R2 = R^2; Q3=Q^3
if R2 < Q3
# println("Error in cubic solver ",R^2," ",Q^3)
return -c/b
else
A = -sign(R)*cbrt(abs(R) + sqrt(R2 - Q3))
if A == 0.0
B = 0.0
else
B = Q/A
end
x1 = A + B - a3
return x1
end
return
end
function G3(gamma::T,beta::T,sqb::T;gc=convert(T,0.5)) where {T <: Real}
if gamma < gc
return G3_series(gamma,beta,sqb)
else
# sqb = sqrt(abs(beta))
if beta >= 0
return (gamma-sin(gamma))/(sqb*beta)
else
return (gamma-sinh(gamma))/(sqb*beta)
end
end
end
function G3_series(gamma::T,beta::T,sqb::T) where {T <: Real}
#epsilon = eps(gamma)
# Computes G_3(\beta,s) using a series tailored to the precision of s.
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = one(T)
g3 = one(T)
g31 = 2g3
g32 = 2g3
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(g3)
while true
g32 = g31
g31 = g3
n += 1
term *= x2/((2n+3)*(2n+2))
g3 += term
iter +=1
if iter >= ITMAX || g3 == g32 || g3 == g31
break
end
end
# g3 *= gamma^3/(6*sqrt(abs(beta^3)))
g3 *= -x2*gamma/(6*beta*sqb)
return g3::T
end
function H1(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
#x=sqrt(abs(beta))*s
if gamma < gc
return H1_series(gamma,beta)
else
if beta >= 0
return (4sin(0.5*gamma)^2 -gamma*sin(gamma))/beta^2
else
return (-4sinh(0.5*gamma)^2+gamma*sinh(gamma))/beta^2
end
end
end
function H1_series(gamma::T,beta::T) where {T <: Real}
# Computes H_1(\beta,s) using a series tailored to the precision of s.
#epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = one(T)
h1 = one(T)
h11 = 2h1
h12 = 2h1
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h1)
while true
h12 = h11
h11 = h1
n += 1
term *= x2*(n+1)
term /= (2n+4)*(2n+3)*n
h1 += term
iter +=1
if iter >= ITMAX || h1 == h12 || h1 == h11
break
end
end
# h1 *= gamma^4/(12*beta^2)
h1 *= x2^2/(12*beta^2)
return h1::T
end
function H2(gamma::T,beta::T,sqb::T;gc=convert(T,0.5)) where {T <: Real}
#x=sqb*s
if gamma < gc
return H2_series(gamma,beta,sqb)
else
# sqb = sqrt(abs(beta))
if beta >= 0
return (sin(gamma)-gamma*cos(gamma))/(sqb*beta)
else
return (sinh(gamma)-gamma*cosh(gamma))/(sqb*beta)
end
end
end
function H2_series(gamma::T,beta::T,sqb::T) where {T <: Real}
# Computes H_2(\beta,s) using a series tailored to the precision of s.
#epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = one(T)
h2 = one(T)
h21 = 2h2
h22 = 2h2
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h2)
while true
h22 = h21
h21 = h2
n += 1
term *= x2
term /= (4n+6)*n
h2 += term
iter += 1
if iter >= ITMAX || h2 == h22 || h2 == h21
break
end
end
# h2 *= gamma^3/(3*sqrt(abs(beta^3)))
h2 *= -x2*gamma/(3*beta*sqb)
return h2::T
end
function H3(gamma::T,beta::T,sqb::T;gc=convert(T,0.5)) where {T <: Real}
# This is H_3 = G_1 G_2 - 3 G_3:
if gamma < gc
return H3_series(gamma,beta,sqb)
else
if beta >= 0
# return (4*sin(gamma)-sin(gamma)*cos(gamma)-3*gamma)/(beta*sqrt(beta))
return (4*sin(gamma)-sin(gamma)*cos(gamma)-3*gamma)/(beta*sqb)
else
# return (4*sinh(gamma)-sinh(gamma)*cosh(gamma)-3*gamma)/(beta*sqrt(-beta))
return (4*sinh(gamma)-sinh(gamma)*cosh(gamma)-3*gamma)/(beta*sqb)
end
end
end
function H3_series(gamma::T,beta::T,sqb::T) where {T <: Real}
# Computes H_3(\beta,s) using a series tailored to the precision of gamma:
#epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = convert(T,1//30)
h3 = convert(T,1//10)
h31 = 2h3
h32 = 2h3
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h3)
four2n = one(T)*4
while true
h32 = h31
h31 = h3
n += 1
term *= x2
term /= (2n+4)*(2n+5)
four2n *= 4
# h3 += term*(4^(n+1)-1)
h3 += term*(four2n-1)
iter += 1
if iter >= ITMAX || h3 == h32 || h3 == h31
break
end
end
# h3 *= -gamma^5/(beta*sqrt(abs(beta)))
h3 *= -x2^2*gamma/(beta*sqb)
return h3::T
end
function H5(gamma::T,beta::T,sqb::T;gc=convert(T,0.5)) where {T <: Real}
# This is G_1 G_2 -(2+G_0) G_3 = H_2 - 2 G_3:
if gamma < gc
return H5_series(gamma,beta,sqb)
else
if beta >= 0
# return (3sin(gamma)-2gamma-gamma*cos(gamma))/(beta*sqrt(beta))
return (3sin(gamma)-2gamma-gamma*cos(gamma))/(beta*sqb)
else
# return (3sinh(gamma)-2gamma-gamma*cosh(gamma))/(beta*sqrt(-beta))
return (3sinh(gamma)-2gamma-gamma*cosh(gamma))/(beta*sqb)
end
end
end
function H5_series(gamma::T,beta::T,sqb::T) where {T <: Real}
# Computes H_5(\beta,s) using a series tailored to the precision of gamma:
#epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = one(T)/60
h5 = copy(term)
h51 = 2h5
h52 = 2h5
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h5)
while true
h52 = h51
h51 = h5
n += 1
term *= x2*(n+1)
term /= (2n+5)*(2n+4)*n
h5 += term
iter += 1
if iter >= ITMAX || h5 == h52 || h5 == h51
break
end
end
# h5 *= -gamma^5/(beta*sqrt(abs(beta)))
h5 *= -x2^2*gamma/(beta*sqb)
return h5::T
end
function H6(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
# This is 2 G_2^2 -3 G_1 G_3:
if gamma < gc
return H6_series(gamma,beta)
else
if beta >= 0
return (9-8cos(gamma) -cos(2gamma) -6gamma*sin(gamma))/(2beta^2)
else
return (9-8cosh(gamma)-cosh(2gamma)+6gamma*sinh(gamma))/(2beta^2)
end
end
end
function H6_series(gamma::T,beta::T) where {T <: Real}
# Computes H_6(\beta,s) using a series tailored to the precision of gamma:
#epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = convert(T,1//360)
h6 = convert(T,1//40)
h61 = 2h6
h62 = 2h6
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h6)
four2n = one(T)*16
while true
h62 = h61
h61 = h6
n += 1
term *= x2
term /= (2n+5)*(2n+6)
four2n *= 4
# h6 += term*(4^(n+2)-3*n-7)
h6 += term*(four2n-3*n-7)
iter +=1
if iter >= ITMAX || h6 == h62 || h6 == h61
break
end
end
# h6 *= gamma^6/(beta*abs(beta))
h6 *= -x2^3/(beta^2)
return h6::T
end
function H7(gamma::T,beta::T,sqb::T;gc=convert(T,0.5)) where {T <: Real}
# This is H_7 = G_1 G_2 (1-2 G_0) + 3 G_0^2 G_3:
if gamma < gc
return H7_series(gamma,beta,sqb)
else
if beta >= 0
# return (3*cos(gamma)*(gamma*cos(gamma)-sin(gamma))+sin(gamma)^3)/(beta*sqrt(beta))
return (3*cos(gamma)*(gamma*cos(gamma)-sin(gamma))+sin(gamma)^3)/(beta*sqb)
else
# return (3*cosh(gamma)*(gamma*cosh(gamma)-sinh(gamma))-sinh(gamma)^3)/(beta*sqrt(-beta))
return (3*cosh(gamma)*(gamma*cosh(gamma)-sinh(gamma))-sinh(gamma)^3)/(beta*sqb)
end
end
end
function H7_series(gamma::T,beta::T,sqb::T) where {T <: Real}
# Computes H_7(\beta,s) using a series tailored to the precision of gamma:
#epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = -convert(T,3//20160)*x2
h7 = convert(T,1//10-11//840*x2)
h71 = 2h7
h72 = 2h7
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h7)
four2n = one(T)*128
nine2n = one(T)*729
while true
h72 = h71
h71 = h7
n += 1
term *= x2
term /= (2n+6)*(2n+7)
four2n *= 4
nine2n *= 9
# h7 += term*(9^(3+n)-1-(5+2*n)*2^(7+2*n))
h7 += term*(nine2n-1-(5+2*n)*four2n)
iter += 1
if iter >= ITMAX || h7 == h72 || h7 == h71
break
end
end
# h7 *= gamma^5/(beta*sqrt(abs(beta)))
h7 *= x2^2*gamma/(beta*sqb)
return h7::T
end
function H8(gamma::T,beta::T,sqb::T;gc=convert(T,0.5)) where {T <: Real}
# This is H_8 = G_1 G_2 - 3 G_0 G_3:
if gamma < gc
return H8_series(gamma,beta,sqb)
else
if beta >= 0
# return (-3gamma*cos(gamma) +sin(gamma) +sin(2gamma))/(beta*sqrt(beta))
return (-3gamma*cos(gamma) +sin(gamma) +sin(2gamma))/(beta*sqb)
else
# return (-3gamma*cosh(gamma)+sinh(gamma)+sinh(2gamma))/(beta*sqrt(-beta))
return (-3gamma*cosh(gamma)+sinh(gamma)+sinh(2gamma))/(beta*sqb)
end
end
end
function H8_series(gamma::T,beta::T,sqb::T) where {T <: Real}
# Computes H_8(\beta,s) using a series tailored to the precision of gamma:
#epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = convert(T,1//120)
h8 = convert(T,3//20)
h81 = 2h8
h82 = 2h8
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h8)
four2n = one(T)*32
while true
h82 = h81
h81 = h8
n += 1
term *= x2
term /= (2n+4)*(2n+5)
four2n *= 4
# h8 += term*(2^(5+2n)-14-6n)
h8 += term*(four2n-14-6n)
iter +=1
# println("H8: ",iter," ",h8," ",gamma," ",beta)
if iter >= ITMAX || h8 == h82 || h8 == h81
break
end
end
# h8 *= gamma^5/(beta*sqrt(abs(beta)))
h8 *= x2^2*gamma/(beta*sqb)
return h8::T
end
# Faster dot product; assumes 3D vector
@inline function dot_fast(a::Vector{T}, b::Vector{T}) where T<:Real
a[1]*b[1] + a[2]*b[2] + a[3]*b[3]
end
@inline function dot_fast(a::Vector{T}) where T<:Real
a[1]*a[1] + a[2]*a[2] + a[3]*a[3]
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 7731 |
# Define a dummy function for automatic differentiation:
function G3(param::Array{T,1}) where {T <: Real}
return G3(param[1],param[2])
end
function G3(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
sqb = sqrt(abs(beta))
#x = sqb*s
if gamma < gc
return G3_series(gamma,beta)
else
if beta >= 0
return (gamma-sin(gamma))/(sqb*beta)
else
return (gamma-sinh(gamma))/(sqb*beta)
end
end
end
y = zeros(2)
dG3 = y -> ForwardDiff.gradient(G3,y);
function H2(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
sqb = sqrt(abs(beta))
#x=sqb*s
if gamma < gc
return H2_series(gamma,beta)
else
if beta >= 0
return (sin(gamma)-gamma*cos(gamma))/(sqb*beta)
else
return (sinh(gamma)-gamma*cosh(gamma))/(sqb*beta)
end
end
end
function H1(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
#x=sqrt(abs(beta))*s
if gamma < gc
return H1_series(gamma,beta)
else
if beta >= 0
return (4sin(0.5*gamma)^2 -gamma*sin(gamma))/beta^2
else
return (-4sinh(0.5*gamma)^2+gamma*sinh(gamma))/beta^2
end
end
end
function G3_series(gamma::T,beta::T) where {T <: Real}
epsilon = eps(gamma)
# Computes G_3(\beta,s) using a series tailored to the precision of s.
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = one(T)
g3 = one(T)
g31 = 2g3
g32 = 2g3
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(g3)
while true
g32 = g31
g31 = g3
n += 1
term *= x2/((2n+3)*(2n+2))
g3 += term
iter +=1
if iter >= ITMAX || g3 == g32 || g3 == g31
break
end
end
g3 *= gamma^3/(6*sqrt(abs(beta^3)))
return g3::T
end
dG3_series = y -> ForwardDiff.gradient(G3_series,y);
# Define a dummy function for automatic differentiation:
function G3_series(param::Array{T,1}) where {T <: Real}
return G3_series(param[1],param[2])
end
function H2_series(gamma::T,beta::T) where {T <: Real}
# Computes H_2(\beta,s) using a series tailored to the precision of s.
epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = one(T)
h2 = one(T)
h21 = 2h2
h22 = 2h2
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h2)
while true
h22 = h21
h21 = h2
n += 1
term *= x2
term /= (4n+6)*n
h2 += term
iter += 1
if iter >= ITMAX || h2 == h22 || h2 == h21
break
end
end
h2 *= gamma^3/(3*sqrt(abs(beta^3)))
return h2::T
end
function H1_series(gamma::T,beta::T) where {T <: Real}
# Computes H_1(\beta,s) using a series tailored to the precision of s.
epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = one(T)
h1 = one(T)
h11 = 2h1
h12 = 2h1
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h1)
while true
h12 = h11
h11 = h1
n += 1
term *= x2*(n+1)
term /= (2n+4)*(2n+3)*n
h1 += term
iter +=1
if iter >= ITMAX || h1 == h12 || h1 == h11
break
end
end
h1 *= gamma^4/(12*beta^2)
return h1::T
end
function H5(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
# This is G_1 G_2 -(2+G_0) G_3 = H_2 - 2 G_3:
if gamma < gc
return H5_series(gamma,beta)
else
if beta >= 0
return (3sin(gamma)-2gamma-gamma*cos(gamma))/(beta*sqrt(beta))
else
return (3sinh(gamma)-2gamma-gamma*cosh(gamma))/(beta*sqrt(-beta))
end
end
end
function H5_series(gamma::T,beta::T) where {T <: Real}
# Computes H_5(\beta,s) using a series tailored to the precision of gamma:
epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = one(T)/60
h5 = copy(term)
h51 = 2h5
h52 = 2h5
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h5)
while true
h52 = h51
h51 = h5
n += 1
term *= x2*(n+1)
term /= (2n+5)*(2n+4)*n
h5 += term
iter += 1
if iter >= ITMAX || h5 == h52 || h5 == h51
break
end
end
h5 *= -gamma^5/(beta*sqrt(abs(beta)))
return h5::T
end
function H6(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
# This is 2 G_2^2 -3 G_1 G_3:
if gamma < gc
return H6_series(gamma,beta)
else
if beta >= 0
return (9-8cos(gamma) -cos(2gamma) -6gamma*sin(gamma))/(2beta^2)
else
return (9-8cosh(gamma)-cosh(2gamma)+6gamma*sinh(gamma))/(2beta^2)
end
end
end
function H6_series(gamma::T,beta::T) where {T <: Real}
# Computes H_6(\beta,s) using a series tailored to the precision of gamma:
epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = convert(T,1//360)
h6 = convert(T,1//40)
h61 = 2h6
h62 = 2h6
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h6)
while true
h62 = h61
h61 = h6
n += 1
term *= x2
term /= (2n+5)*(2n+6)
h6 += term*(4^(n+2)-3*n-7)
iter +=1
if iter >= ITMAX || h6 == h62 || h6 == h61
break
end
end
h6 *= gamma^6/(beta*abs(beta))
return h6::T
end
function H3(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
# This is H_3 = G_1 G_2 - 3 G_3:
if gamma < gc
return H3_series(gamma,beta)
else
if beta >= 0
return (4*sin(gamma)-sin(gamma)*cos(gamma)-3*gamma)/(beta*sqrt(beta))
else
return (4*sinh(gamma)-sinh(gamma)*cosh(gamma)-3*gamma)/(beta*sqrt(-beta))
end
end
end
function H3_series(gamma::T,beta::T) where {T <: Real}
# Computes H_3(\beta,s) using a series tailored to the precision of gamma:
epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = convert(T,1//30)
h3 = convert(T,1//10)
h31 = 2h3
h32 = 2h3
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h3)
while true
h32 = h31
h31 = h3
n += 1
term *= x2
term /= (2n+4)*(2n+5)
h3 += term*(4^(n+1)-1)
iter += 1
if iter >= ITMAX || h3 == h32 || h3 == h31
break
end
end
h3 *= -gamma^5/(beta*sqrt(abs(beta)))
return h3::T
end
function H7(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
# This is H_7 = G_1 G_2 (1-2 G_0) + 3 G_0^2 G_3:
if gamma < gc
return H7_series(gamma,beta)
else
if beta >= 0
return (3*cos(gamma)*(gamma*cos(gamma)-sin(gamma))+sin(gamma)^3)/(beta*sqrt(beta))
else
return (3*cosh(gamma)*(gamma*cosh(gamma)-sinh(gamma))-sinh(gamma)^3)/(beta*sqrt(-beta))
end
end
end
function H7_series(gamma::T,beta::T) where {T <: Real}
# Computes H_7(\beta,s) using a series tailored to the precision of gamma:
epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = -convert(T,3//20160)*x2
h7 = convert(T,1//10-11//840*x2)
h71 = 2h7
h72 = 2h7
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h7)
while true
h72 = h71
h71 = h7
n += 1
term *= x2
term /= (2n+6)*(2n+7)
h7 += term*(9^(3+n)-1-(5+2*n)*2^(7+2*n))
iter += 1
if iter >= ITMAX || h7 == h72 || h7 == h71
break
end
end
h7 *= gamma^5/(beta*sqrt(abs(beta)))
return h7::T
end
function H8(gamma::T,beta::T;gc=convert(T,0.5)) where {T <: Real}
# This is H_8 = G_1 G_2 - 3 G_0 G_3:
if gamma < gc
return H8_series(gamma,beta)
else
if beta >= 0
return (-3gamma*cos(gamma) +sin(gamma) +sin(2gamma))/(beta*sqrt(beta))
else
return (-3gamma*cosh(gamma)+sinh(gamma)+sinh(2gamma))/(beta*sqrt(-beta))
end
end
end
function H8_series(gamma::T,beta::T) where {T <: Real}
# Computes H_8(\beta,s) using a series tailored to the precision of gamma:
epsilon = eps(gamma)
#x2 = -beta*s^2
x2 = -sign(beta)*gamma^2
term = convert(T,1//120)
h8 = convert(T,3//20)
h81 = 2h8
h82 = 2h8
n=0
iter = 0
ITMAX = 100
# Terminate series when required precision reached:
#while abs(term) > epsilon*abs(h8)
while true
h82 = h81
h81 = h8
n += 1
term *= x2
term /= (2n+4)*(2n+5)
h8 += term*(2^(5+2n)-14-6n)
iter +=1
if iter >= ITMAX || h8 == h82 || h8 == h81
break
end
end
h8 *= gamma^5/(beta*sqrt(abs(beta)))
return h8::T
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 10879 |
include("kepler_init.jl")
# Initializes N-body integration for a plane-parallel hierarchical system
# (see Hamers & Portugies-Zwart 2016 (HPZ16); Beust 2003).
# We want to define a "simplex" hierarchy which can be decomposed into N-1 Keplerian binaries.
# This can be diagramed with a "mobile" diagram, pioneered by Evans (1968). Here's an example:
# Level |
# 4 _______|_______
# 3 _____|____ |
# 2 | | ____|_____
# 1 | | | ___|____
# | | | | |
# 5 4 3 2 1
# Number of levels: n_level
# Number of bodies: n_body
# - Problem is divided up into N-1 Kepler problems: there is a single Kepler problem at each level.
# - For example, in the above "mobile" diagram, 1-2 could be a binary star,
# while 3 is an interior planets orbiting the stars, and 4/5 are a planet/moon orbiting exterior.
# - We compute the N-body positions with each Keplerian connection (one at each level), starting
# at the bottom and moving upwards.
#
function init_nbody(elements::Array{T,2},t0::T,n_body::Int64) where {T <: Real}
# the "_plane" is to remind us that this is currently plane-parallel, so inclination & Omega are zero
n_level = n_body-1
# Input -
# elements: masses & orbital elements for each Keplerian (in this case, each planet plus star)
# Output -
# x: NDIM x n_body array of positions of each planet.
# v: NDIM x n_body array of velocities " " "
#
# Read in the orbital elements:
# elements = readdlm("elements.txt",',')
# Initialize N-body for each Keplerian:
# Get the indices:
indices = get_indices_planetary(n_body)
# Set up "A" matrix (Hamers & Portegies-Zwart 2016) which transforms from
# cartesian coordinates to Keplerian orbits (we are using opposite sign
# convention of HPZ16, for example, r_1 = R_2-R_1).
amat = zeros(T,n_body,n_body)
# Mass vector:
mass = vcat(elements[:,1])
# Set up array for orbital positions of each Keplerian:
rkepler = zeros(T,n_body,NDIM)
rdotkepler = zeros(T,n_body,NDIM)
# Fill in the A matrix & compute the Keplerian elements:
for i=1:n_body-1
# Sums of masses for two components of Keplerian:
m1 = zero(T)
m2 = zero(T)
for j=1:n_body
if indices[i,j] == 1
m1 += mass[j]
end
if indices[i,j] == -1
m2 += mass[j]
end
end
# Compute Kepler problem: r is a vector of positions of "body" 2 with respect to "body" 1; rdot is velocity vector
# For now set inclination to Inclination = pi/2 and longitude of nodes to Omega = pi:
# r,rdot = kepler_init(t0,m1+m2,[elements[i+1,2:5];pi/2;pi])
r,rdot = kepler_init(t0,m1+m2,elements[i+1,2:7])
# rbig,rdotbig = kepler_init(big(t0),big(m1+m2),big.(elements[i+1,2:7]))
# r = convert(Array{T,1},rbig); rdot = convert(Array{T,1},rdotbig)
for j=1:NDIM
rkepler[i,j] = r[j]
rdotkepler[i,j] = rdot[j]
end
# Now, fill in the A matrix
for j=1:n_body
if indices[i,j] == 1
amat[i,j] = -mass[j]/m1
end
if indices[i,j] == -1
amat[i,j] = mass[j]/m2
end
end
end
mtot = sum(mass)
# Final row is for center-of-mass of system:
for j=1:n_body
amat[n_body,j] = mass[j]/mtot
end
# Compute inverse of A matrix to convert from Keplerian coordinates
# to Cartesian coordinates:
ainv = inv(amat)
# Now, compute the Cartesian coordinates (eqn A6 from HPZ16):
x = zeros(T,NDIM,n_body)
v = zeros(T,NDIM,n_body)
#for i=1:n_body
# for j=1:NDIM
# for k=1:n_body
# x[j,i] += ainv[i,k]*rkepler[k,j]
# v[j,i] += ainv[i,k]*rdotkepler[k,j]
# end
# end
#end
#x = transpose(*(ainv,rkepler))
x = permutedims(*(ainv,rkepler))
#v = transpose(*(ainv,rdotkepler))
v = permutedims(*(ainv,rdotkepler))
# Return the cartesian position & velocity matrices:
#return x,v,amat,ainv
return x,v
end
# Version including derivatives:
function init_nbody(elements::Array{T,2},t0::T,n_body::Int64,jac_init::Array{T,2}) where {T <: Real}
# the "_plane" is to remind us that this is currently plane-parallel, so inclination & Omega are zero
n_level = n_body-1
# Input -
# elements: masses & orbital elements for each Keplerian (in this case, each planet plus star)
# Output -
# x: NDIM x n_body array of positions of each planet.
# v: NDIM x n_body array of velocities " " "
# jac_init: derivative of cartesian coordinates, (x,v,m) for each body, with respect to initial conditions
# n_body x (period, t0, e*cos(omega), e*sin(omega), inclination, Omega, mass) for each Keplerian, with
# the first body having orbital elements set to zero, so the first six derivatives are zero.
#jac_init = zeros(T,7*n_body,7*n_body)
fill!(jac_init,0.0)
#
# Read in the orbital elements:
# elements = readdlm("elements.txt",',')
# Initialize N-body for each Keplerian:
# Get the indices:
indices = get_indices_planetary(n_body)
#println("Indices: ",indices)
# Set up "A" matrix (Hamers & Portegies-Zwart 2016) which transforms from
# cartesian coordinates to Keplerian orbits (we are using opposite sign
# convention of HPZ16, for example, r_1 = R_2-R_1).
amat = zeros(T,n_body,n_body)
# Derivative of i,jth element of A matrix with respect to mass of body k:
damatdm = zeros(T,n_body,n_body,n_body)
# Mass vector:
mass = vcat(elements[:,1])
# Set up array for orbital positions of each Keplerian:
rkepler = zeros(T,n_body,NDIM)
rdotkepler = zeros(T,n_body,NDIM)
# Set up Jacobian for transformation from n_body-1 Keplerian elements & masses
# to (x,v,m) - the last is center-of-mass, which is taken to be zero.
jac_21 = zeros(T,7,7)
# jac_kepler saves jac_21 for each set of bodies:
jac_kepler = zeros(T,n_body*6,n_body*7)
# Fill in the A matrix & compute the Keplerian elements:
for i=1:n_body-1 # i labels the row of matrix, which weights masses in current Keplerian
# Sums of masses for two components of Keplerian:
m1 = 0.0 ; m2 = 0.0
for j=1:n_body
if indices[i,j] == 1
m1 += mass[j]
end
if indices[i,j] == -1
m2 += mass[j]
end
end
# Compute Kepler problem: r is a vector of positions of "body" 2 with respect to "body" 1; rdot is velocity vector:
r,rdot = kepler_init(t0,m1+m2,elements[i+1,2:7],jac_21)
# rbig,rdotbig = kepler_init(big(t0),big(m1+m2),big.(elements[i+1,2:7]))
# r = convert(Array{T,1},rbig); rdot = convert(Array{T,1},rdotbig)
for j=1:NDIM
rkepler[i,j] = r[j]
rdotkepler[i,j] = rdot[j]
end
# Save Keplerian Jacobian to a matrix. First, positions/velocities vs. elements:
for j=1:6, k=1:6
jac_kepler[(i-1)*6+j,i*7+k] = jac_21[j,k]
end
# Now add in mass derivatives:
for j=1:n_body
# Check which bodies participate in current Keplerian:
if indices[i,j] != 0
for k=1:6
jac_kepler[(i-1)*6+k,j*7] = jac_21[k,7]
end
end
end
# Now, fill in the A matrix:
for j=1:n_body
if indices[i,j] == 1
amat[i,j] = -mass[j]/m1
damatdm[i,j,j] += -1.0/m1
for k=1:n_body
if indices[i,k] == 1
damatdm[i,j,k] += mass[j]/m1^2
end
end
end
if indices[i,j] == -1
amat[i,j] = mass[j]/m2
damatdm[i,j,j] += 1.0/m2
for k=1:n_body
if indices[i,k] == -1
damatdm[i,j,k] -= mass[j]/m2^2
end
end
end
end
end
mtot = sum(mass)
for j=1:n_body
amat[n_body,j] = mass[j]/mtot
damatdm[n_body,j,j] = 1.0/mtot
for k=1:n_body
damatdm[n_body,j,k] -= mass[j]/mtot^2
end
end
ainv = inv(amat)
# Propagate mass uncertainties (11/17/17 notes):
dainvdm = zeros(T,n_body,n_body,n_body)
#dainvdm_num = zeros(T,n_body,n_body,n_body)
#damatdm_num = zeros(T,n_body,n_body,n_body)
#dlnq = 2e-3
#elements_tmp = zeros(T,n_body,7)
for k=1:n_body
dainvdm[:,:,k]=-ainv*damatdm[:,:,k]*ainv
# Compute derivatives numerically:
# elements_tmp = copy(elements)
# elements_tmp .= elements
# elements_tmp[k,1] *= (1.0-dlnq)
# x_minus,v_minus,amat_minus,ainv_minus = init_nbody(elements_tmp,t0,n_body)
# elements_tmp[k,1] *= (1.0+dlnq)/(1.0-dlnq)
# x_plus,v_plus,amat_plus,ainv_plus = init_nbody(elements_tmp,t0,n_body)
# dainvdm_num[:,:,k] = (ainv_plus.-ainv_minus)/(2dlnq*elements[k,1])
# damatdm_num[:,:,k] = (amat_plus.-amat_minus)/(2dlnq*elements[k,1])
end
#println("damatdm: ",maximum(abs.(damatdm-damatdm_num)))
#println("dainvdm: ",maximum(abs.(dainvdm-dainvdm_num)))
#for k=1:n_body
# println("damatdm: ",k," ",abs.(damatdm[k,:,:]-damatdm_num[k,:,:]))
## println("damatdm_num: ",k," ",abs.(damatdm_num[k,:,:]))
#end
#println("dainvdm: ",abs.(dainvdm))
#println("dainvdm_num: ",abs.(dainvdm_num))
# Now, compute the Cartesian coordinates (eqn A6 from HPZ16):
x = zeros(T,NDIM,n_body)
v = zeros(T,NDIM,n_body)
#for i=1:n_body
# for j=1:NDIM
# for k=1:n_body
# x[j,i] += ainv[i,k]*rkepler[k,j]
# v[j,i] += ainv[i,k]*rdotkepler[k,j]
# end
# end
#end
#x = transpose(*(ainv,rkepler))
x = permutedims(*(ainv,rkepler))
#v = transpose(*(ainv,rdotkepler))
v = permutedims(*(ainv,rdotkepler))
# Finally, compute the overall Jacobian.
# First, compute it for the orbital elements:
dxdm = zeros(T,3,n_body); dvdm = zeros(T,3,n_body)
for i=1:n_body
# Propagate derivatives of Kepler coordinates with respect to
# orbital elements to the Cartesian coordinates:
for k=1:n_body
for j=1:3, l=1:7*n_body
jac_init[(i-1)*7+j,l] += ainv[i,k]*jac_kepler[(k-1)*6+j,l]
jac_init[(i-1)*7+3+j,l] += ainv[i,k]*jac_kepler[(k-1)*6+3+j,l]
end
end
# Include the mass derivatives of the A matrix:
# dainvdm .= -ainv*damatdm[:,:,i]*ainv # derivative with respect to the ith body
# Multiply the derivative time Kepler positions/velocities to convert to
# Cartesian coordinates:
# Cartesian coordinates of all of the bodies can depend on the masses
# of all the others so we need to loop over indices of each body, k:
for k=1:n_body
# dxdm = transpose(dainvdm[:,:,k]*rkepler)
dxdm = permutedims(dainvdm[:,:,k]*rkepler)
# dvdm = transpose(dainvdm[:,:,k]*rdotkepler)
dvdm = permutedims(dainvdm[:,:,k]*rdotkepler)
jac_init[(i-1)*7+1:(i-1)*7+3,k*7] += dxdm[1:3,i]
jac_init[(i-1)*7+4:(i-1)*7+6,k*7] += dvdm[1:3,i]
end
# Masses are conserved:
jac_init[i*7,i*7] = 1.0
end
return x,v
end
function get_indices_planetary(n_body)
# This sets up a planetary-hierarchy index matrix
indices = zeros(Int64,n_body,n_body)
for i=1:n_body-1
for j=1:i
indices[i,j ]=-1
end
indices[i,i+1]= 1
indices[n_body,i]=1
end
indices[n_body,n_body]=1
# This is an example for TRAPPIST-1
# indices = [[-1, 1, 0, 0, 0, 0, 0, 0], # first two bodies orbit in a binary
# [-1,-1, 1, 0, 0, 0, 0, 0], # next planet orbits about these
# [-1,-1,-1, 1, 0, 0, 0, 0], # etc...
# [-1,-1,-1,-1, 1, 0, 0, 0],
# [-1,-1,-1,-1,-1, 1, 0, 0],
# [-1,-1,-1,-1,-1,-1, 1, 0],
# [-1,-1,-1,-1,-1,-1,-1, 1],
# [ 1, 1, 1, 1, 1, 1, 1, 1] # center of mass of the system
return indices
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 29211 |
# Wisdom & Hernandez version of Kepler solver, with Rein & Tamayo convergence test.
# Now using \gamma = \sqrt{\abs{\beta}}s rather than s now to solve Kepler's equation.
using ForwardDiff, DiffResults
include("g3.jl")
function cubic1(a::T, b::T, c::T) where {T <: Real}
a3 = a*third
Q = a3^2 - b*third
R = a3^3 + 0.5*(-a3*b + c)
if R^2 < Q^3
# println("Error in cubic solver ",R^2," ",Q^3)
return -c/b
else
A = -sign(R)*cbrt(abs(R) + sqrt(R*R - Q*Q*Q))
if A == 0.0
B = 0.0
else
B = Q/A
end
x1 = A + B - a3
return x1
end
return
end
function jac_delxv_gamma!(x0::Array{T,1},v0::Array{T,1},k::T,h::T,drift_first::Bool;grad::Bool=false,auto::Bool=false,dlnq::T=convert(T,0.0),debug=false) where {T <: Real}
# Using autodiff, computes Jacobian of delx & delv with respect to x0, v0, k & h.
# Autodiff requires a single-vector input, so create an array to hold the independent variables:
input = zeros(T,8)
input[1:3]=x0; input[4:6]=v0; input[7]=k; input[8]=h
if grad
if debug
# Also output gamma, r, fm1, dfdt, gmh, dgdtm1, and for debugging:
delxv_jac = zeros(T,12,8)
else
# Output \delta x & \delta v only:
delxv_jac = zeros(T,6,8)
end
end
# Create a closure so that the function knows value of drift_first:
function delx_delv(input::Array{T2,1}) where {T2 <: Real} # input = x0,v0,k,h,drift_first
# Compute delx and delv from h, s, k, beta0, x0 and v0:
x0 = input[1:3]; v0 = input[4:6]; k = input[7]; h = input[8]
# Compute r0:
drift_first ? r0 = norm(x0-h*v0) : r0 = norm(x0)
# And its inverse:
r0inv = inv(r0)
# Compute beta_0:
beta0 = 2k*r0inv-dot(v0,v0)
beta0inv = inv(beta0)
signb = sign(beta0)
sqb = sqrt(signb*beta0)
zeta = k-r0*beta0
gamma_guess = zero(T2)
# Compute \eta_0 = x_0 . v_0:
drift_first ? eta = dot(x0-h*v0,v0) : eta = dot(x0,v0)
if zeta != zero(T2)
# Make sure we have a cubic in gamma (and don't divide by zero):
gamma_guess = cubic1(3eta*sqb/zeta,6r0*signb*beta0/zeta,-6h*signb*beta0*sqb/zeta)
else
# Check that we have a quadratic in gamma (and don't divide by zero):
if eta != zero(T2)
reta = r0/eta
disc = reta^2+2h/eta
disc > zero(T2) ? gamma_guess = sqb*(-reta+sqrt(disc)) : gamma_guess = h*r0inv*sqb
else
gamma_guess = h*r0inv*sqb
end
end
gamma = copy(gamma_guess)
# Make sure prior two steps differ:
gamma1 = 2*copy(gamma)
gamma2 = 3*copy(gamma)
iter = 0
ITMAX = 20
# Compute coefficients: (8/28/19 notes)
# c1 = k; c2 = -zeta; c3 = -eta*sqb; c4 = sqb*(eta-h*beta0); c5 = eta*signb*sqb
c1 = k; c2 = -2zeta; c3 = 2*eta*signb*sqb; c4 = -sqb*h*beta0; c5 = 2eta*signb*sqb
# Solve for gamma:
while true
gamma2 = gamma1
gamma1 = gamma
xx = 0.5*gamma
# xx = gamma
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
sx = sinh(xx); cx = exp(-xx)+sx
end
# gamma -= (c1*gamma+c2*sx+c3*cx+c4)/(c2*cx+c5*sx+c1)
gamma -= (k*gamma+c2*sx*cx+c3*sx^2+c4)/(2signb*zeta*sx^2+c5*sx*cx+r0*beta0)
iter +=1
if iter >= ITMAX || gamma == gamma2 || gamma == gamma1
break
end
end
# if typeof(gamma) == Float64
# println("s: ",gamma/sqb)
# end
# Set up a single output array for delx and delv:
if debug
delxv = zeros(T2,12)
else
delxv = zeros(T2,6)
end
# Since we updated gamma, need to recompute:
xx = 0.5*gamma
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
sx = sinh(xx); cx = exp(-xx)+sx
end
# Now, compute final values. Compute Wisdom/Hernandez G_i^\beta(s) functions:
g1bs = 2sx*cx/sqb
g2bs = 2signb*sx^2*beta0inv
g0bs = one(T2)-beta0*g2bs
g3bs = G3(gamma,beta0)
h1 = zero(T2); h2 = zero(T2)
# if typeof(g1bs) == Float64
# println("g1: ",g1bs," g2: ",g2bs," g3: ",g3bs)
# end
# Compute r from equation (35):
r = r0*g0bs+eta*g1bs+k*g2bs
# if typeof(r) == Float64
# println("r: ",r)
# end
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv # [x]
if drift_first
# Drift backwards before Kepler step: (1/22/2018)
fm1 = -k*r0inv*g2bs # [x]
# This is given in 2/7/2018 notes: g-h*f
# gmh = k*r0inv*(r0*(g1bs*g2bs-g3bs)+eta*g2bs^2+k*g3bs*g2bs) # [x]
# println("Old gmh: ",gmh," new gmh: ",k*r0inv*(h*g2bs-r0*g3bs)) # [x]
gmh = k*r0inv*(h*g2bs-r0*g3bs) # [x]
else
# Drift backwards after Kepler step: (1/24/2018)
# The following line is f-1-h fdot:
h1= H1(gamma,beta0); h2= H2(gamma,beta0)
# fm1 = k*rinv*(g2bs-k*r0inv*H1(gamma,beta0)) # [x]
fm1 = k*rinv*(g2bs-k*r0inv*h1) # [x]
# This is g-h*dgdt
# gmh = k*rinv*(r0*H2(gamma,beta0)+eta*H1(gamma,beta0)) # [x]
gmh = k*rinv*(r0*h2+eta*h1) # [x]
end
# Compute velocity component functions:
if drift_first
# This is gdot - h fdot - 1:
# dgdtm1 = k*r0inv*rinv*(r0*g0bs*g2bs+eta*g1bs*g2bs+k*g1bs*g3bs) # [x]
# println("gdot-h fdot-1: ",dgdtm1," alternative expression: ",k*r0inv*rinv*(h*g1bs-r0*g2bs))
dgdtm1 = k*r0inv*rinv*(h*g1bs-r0*g2bs)
else
# This is gdot - 1:
dgdtm1 = -k*rinv*g2bs # [x]
end
# if typeof(fm1) == Float64
# println("fm1: ",fm1," dfdt: ",dfdt," gmh: ",gmh," dgdt-1: ",dgdtm1)
# end
@inbounds for j=1:3
# Compute difference vectors (finish - start) of step:
delxv[ j] = fm1*x0[j]+gmh*v0[j] # position x_ij(t+h)-x_ij(t) - h*v_ij(t) or -h*v_ij(t+h)
end
@inbounds for j=1:3
delxv[3+j] = dfdt*x0[j]+dgdtm1*v0[j] # velocity v_ij(t+h)-v_ij(t)
end
if debug
delxv[7] = gamma
delxv[8] = r
delxv[9] = fm1
delxv[10] = dfdt
delxv[11] = gmh
delxv[12] = dgdtm1
end
if grad == true && auto == false && dlnq == 0.0
# Compute gradient analytically:
jac_mass = zeros(T,6)
compute_jacobian_gamma!(gamma,g0bs,g1bs,g2bs,g3bs,h1,h2,dfdt,fm1,gmh,dgdtm1,r0,r,r0inv,rinv,k,h,beta0,beta0inv,eta,sqb,zeta,x0,v0,delxv_jac,jac_mass,drift_first,debug)
end
return delxv
end
# Use autodiff to compute Jacobian:
if grad
if auto
# delxv_jac = ForwardDiff.jacobian(delx_delv,input)
if debug
delxv = zeros(T,12)
else
delxv = zeros(T,6)
end
out = DiffResults.JacobianResult(delxv,input)
ForwardDiff.jacobian!(out,delx_delv,input)
delxv_jac = DiffResults.jacobian(out)
delxv = DiffResults.value(out)
elseif dlnq != 0.0
# Use finite differences to compute Jacobian:
if debug
delxv_jac = zeros(T,12,8)
else
delxv_jac = zeros(T,6,8)
end
delxv = delx_delv(input)
@inbounds for j=1:8
# Difference the jth component:
inputp = copy(input); dp = dlnq*inputp[j]; inputp[j] += dp
delxvp = delx_delv(inputp)
inputm = copy(input); inputm[j] -= dp
delxvm = delx_delv(inputm)
delxv_jac[:,j] = (delxvp-delxvm)/(2*dp)
end
else
# If grad = true and dlnq = 0.0, then the above routine will compute Jacobian analytically.
delxv = delx_delv(input)
end
# Return Jacobian:
return delxv::Array{T,1},delxv_jac::Array{T,2}
else
return delx_delv(input)::Array{T,1}
end
end
function jac_delxv_gamma!(x0::Array{T,1},v0::Array{T,1},k::T,h::T,drift_first::Bool,delxv::Array{T,1},delxv_jac::Array{T,2},jac_mass::Array{T,1},debug::Bool) where {T <: Real}
# Analytically computes Jacobian of delx & delv with respect to x0, v0, k & h.
# Compute r0:
drift_first ? r0 = norm(x0-h*v0) : r0 = norm(x0)
# And its inverse:
r0inv = inv(r0)
# Compute beta_0:
beta0 = 2k*r0inv-dot(v0,v0)
beta0inv = inv(beta0)
signb = sign(beta0)
sqb = sqrt(signb*beta0)
zeta = k-r0*beta0
gamma_guess = zero(T)
# Compute \eta_0 = x_0 . v_0:
drift_first ? eta = dot(x0-h*v0,v0) : eta = dot(x0,v0)
if zeta != zero(T)
# Make sure we have a cubic in gamma (and don't divide by zero):
gamma_guess = cubic1(3eta*sqb/zeta,6r0*signb*beta0/zeta,-6h*signb*beta0*sqb/zeta)
else
# Check that we have a quadratic in gamma (and don't divide by zero):
if eta != zero(T)
reta = r0/eta
disc = reta^2+2h/eta
disc > zero(T) ? gamma_guess = sqb*(-reta+sqrt(disc)) : gamma_guess = h*r0inv*sqb
else
gamma_guess = h*r0inv*sqb
end
end
gamma = copy(gamma_guess)
# Make sure prior two steps differ:
gamma1 = 2*copy(gamma)
gamma2 = 3*copy(gamma)
iter = 0
ITMAX = 20
# Compute coefficients: (8/28/19 notes)
# c1 = k; c2 = -zeta; c3 = -eta*sqb; c4 = sqb*(eta-h*beta0); c5 = eta*signb*sqb
c1 = k; c2 = -2zeta; c3 = 2*eta*signb*sqb; c4 = -sqb*h*beta0; c5 = 2eta*signb*sqb
# Solve for gamma:
while true
gamma2 = gamma1
gamma1 = gamma
xx = 0.5*gamma
# xx = gamma
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
sx = sinh(xx); cx = exp(-xx)+sx
end
# gamma -= (c1*gamma+c2*sx+c3*cx+c4)/(c2*cx+c5*sx+c1)
gamma -= (k*gamma+c2*sx*cx+c3*sx^2+c4)/(2signb*zeta*sx^2+c5*sx*cx+r0*beta0)
iter +=1
if iter >= ITMAX || gamma == gamma2 || gamma == gamma1
break
end
end
# Set up a single output array for delx and delv:
fill!(delxv,zero(T))
# Since we updated gamma, need to recompute:
xx = 0.5*gamma
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
sx = sinh(xx); cx = exp(-xx)+sx
end
# Now, compute final values. Compute Wisdom/Hernandez G_i^\beta(s) functions:
g1bs = 2sx*cx/sqb
g2bs = 2signb*sx^2*beta0inv
g0bs = one(T)-beta0*g2bs
g3bs = G3(gamma,beta0)
h1 = zero(T); h2 = zero(T)
# Compute r from equation (35):
r = r0*g0bs+eta*g1bs+k*g2bs
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv # [x]
if drift_first
# Drift backwards before Kepler step: (1/22/2018)
fm1 = -k*r0inv*g2bs # [x]
# This is given in 2/7/2018 notes: g-h*f
# gmh = k*r0inv*(r0*(g1bs*g2bs-g3bs)+eta*g2bs^2+k*g3bs*g2bs) # [x]
gmh = k*r0inv*(h*g2bs-r0*g3bs) # [x]
else
# Drift backwards after Kepler step: (1/24/2018)
# The following line is f-1-h fdot:
h1= H1(gamma,beta0); h2= H2(gamma,beta0)
# fm1 = k*rinv*(g2bs-k*r0inv*H1(gamma,beta0)) # [x]
fm1 = k*rinv*(g2bs-k*r0inv*h1) # [x]
# This is g-h*dgdt
# gmh = k*rinv*(r0*H2(gamma,beta0)+eta*H1(gamma,beta0)) # [x]
gmh = k*rinv*(r0*h2+eta*h1) # [x]
end
# Compute velocity component functions:
if drift_first
# This is gdot - h fdot - 1:
# dgdtm1 = k*r0inv*rinv*(r0*g0bs*g2bs+eta*g1bs*g2bs+k*g1bs*g3bs) # [x]
dgdtm1 = k*r0inv*rinv*(h*g1bs-r0*g2bs)
else
# This is gdot - 1:
dgdtm1 = -k*rinv*g2bs # [x]
end
@inbounds for j=1:3
# Compute difference vectors (finish - start) of step:
delxv[ j] = fm1*x0[j]+gmh*v0[j] # position x_ij(t+h)-x_ij(t) - h*v_ij(t) or -h*v_ij(t+h)
end
@inbounds for j=1:3
delxv[3+j] = dfdt*x0[j]+dgdtm1*v0[j] # velocity v_ij(t+h)-v_ij(t)
end
if debug
delxv[7] = gamma
delxv[8] = r
delxv[9] = fm1
delxv[10] = dfdt
delxv[11] = gmh
delxv[12] = dgdtm1
end
# Compute gradient analytically:
compute_jacobian_gamma!(gamma,g0bs,g1bs,g2bs,g3bs,h1,h2,dfdt,fm1,gmh,dgdtm1,r0,r,r0inv,rinv,k,h,beta0,beta0inv,eta,sqb,zeta,x0,v0,delxv_jac,jac_mass,drift_first,debug)
end
function compute_jacobian_gamma!(gamma::T,g0::T,g1::T,g2::T,g3::T,h1::T,h2::T,dfdt::T,fm1::T,gmh::T,dgdtm1::T,r0::T,r::T,r0inv::T,rinv::T,k::T,h::T,beta::T,betainv::T,eta::T,
sqb::T,zeta::T,x0::Array{T,1},v0::Array{T,1},delxv_jac::Array{T,2},jac_mass::Array{T,1},drift_first::Bool,debug::Bool) where {T <: Real}
# Computes Jacobian:
if drift_first
# First, x0 derivatives:
# delxv[ j] = fm1*x0[j]+gmh*v0[j] # position x_ij(t+h)-x_ij(t) - h*v_ij(t) or -h*v_ij(t+h)
# delxv[3+j] = dfdt*x0[j]+dgdtm1*v0[j] # velocity v_ij(t+h)-v_ij(t)
# First, the diagonal terms:
# Now the off-diagonal terms:
d = (h + eta*g2 + 2*k*g3)*betainv
c1 = d-r0*g3
c2 = eta*g0+g1*zeta
c3 = d*k+g1*r0^2
c4 = eta*g1+2*g0*r0
c13 = g1*h-g2*r0
# c9 = g2*r-h1*k
# c10 = c3*c9*rinv+g2*r0*h-k*(2*g2*h+3*g3*r0)*betainv
c9 = 2*g2*h-3*g3*r0
c10 = k*r0inv^4*(-g2*r0*h+k*c9*betainv-c3*c13*rinv)
c24 = r0inv^3*(r0*(2*k*r0inv-beta)*betainv-g1*c3*rinv/g2)
h6 = H6(gamma,beta)
# Derivatives of \delta x with respect to x0, v0, k & h:
dfm1dxx = fm1*c24
dfm1dxv = -fm1*(g1*rinv+h*c24)
dfm1dvx = dfm1dxv
# dfm1dvv = fm1*(2*betainv-g1*rinv*(d/g2-2*h)+h^2*c24)
dfm1dvv = fm1*rinv*(-r0*g2 + k*h6*betainv/g2 + h*(2*g1+h*r*c24))
dfm1dh = fm1*(g1*rinv*(1/g2+2*k*r0inv-beta)-eta*c24)
dfm1dk = fm1*(1/k+g1*c1*rinv*r0inv/g2-2*betainv*r0inv)
# dfm1dk2 = 2g2*betainv-c1*g1*rinv
h4 = -H1(gamma,beta)*beta
# h5 = g1*g2-g3*(2+g0)
h5 = H5(gamma,beta)
# println("H5 : ",g1*g2-g3*(2+g0)," ",H2(gamma,beta)-2*G3(gamma,beta)," ",h5)
# h6 = 2*g2^2-3*g1*g3
# println("H6: ",2*g2^2-3*g1*g3," ",h6)
# dfm1dk2 = (r0*h4+k*h6)*betainv*rinv
dfm1dk2 = (r0*h4+k*h6)
# println("dfm1dk2: ",dfm1dk2," ", (r0*h4+k*h6)*betainv*rinv)
dgmhdxx = c10
dgmhdxv = -g2*k*c13*rinv*r0inv-h*c10
dgmhdvx = dgmhdxv
# dgmhdvv = -d*k*c13*rinv*r0inv+2*g2*h*k*c13*rinv*r0inv+k*c9*betainv*r0inv+h^2*c10
h8 = H8(gamma,beta)
dgmhdvv = 2*g2*h*k*c13*rinv*r0inv+h^2*c10+
k*betainv*rinv*r0inv*(r0^2*h8-beta*h*r0*g2^2 + (h*k+eta*r0)*h6)
dgmhdh = g2*k*r0inv+k*c13*rinv*r0inv+g2*k*(2*k*r0inv-beta)*c13*rinv*r0inv-eta*c10
dgmhdk = r0inv*(k*c1*c13*rinv*r0inv+g2*h-g3*r0-k*c9*betainv*r0inv)
# dgmhdk2 = c1*c13*rinv-c9*betainv
# dgmhdk2 = -betainv*rinv*(h6*g3*k^2+eta*r0*(h6+g2*h4)+r0^2*g0*h5+k*eta*g2*h6+(g1*h6+g3*h4)*k*r0)
dgmhdk2 = -(h6*g3*k^2+eta*r0*(h6+g2*h4)+r0^2*g0*h5+k*eta*g2*h6+(g1*h6+g3*h4)*k*r0)
# println("dgmhdk2: ",dgmhdk2," ",-betainv*rinv*(h6*g3*k^2+eta*r0*(h6+g2*h4)+r0^2*g0*h5+k*eta*g2*h6+(g1*h6+g3*h4)*k*r0))
@inbounds for j=1:3
# First, compute the \delta x-derivatives:
delxv_jac[ j, j] = fm1
delxv_jac[ j,3+j] = gmh
@inbounds for i=1:3
delxv_jac[j, i] += (dfm1dxx*x0[i]+dfm1dxv*v0[i])*x0[j] + (dgmhdxx*x0[i]+dgmhdxv*v0[i])*v0[j]
delxv_jac[j,3+i] += (dfm1dvx*x0[i]+dfm1dvv*v0[i])*x0[j] + (dgmhdvx*x0[i]+dgmhdvv*v0[i])*v0[j]
end
delxv_jac[ j, 7] = dfm1dk*x0[j] + dgmhdk*v0[j]
delxv_jac[ j, 8] = dfm1dh*x0[j] + dgmhdh*v0[j]
# Compute the mass jacobian separately since otherwise cancellations happen in kepler_driftij_gamma:
jac_mass[ j] = (GNEWT*r0inv)^2*betainv*rinv*(dfm1dk2*x0[j]+dgmhdk2*v0[j])
end
# Derivatives of \delta v with respect to x0, v0, k & h:
c5 = (r0-k*g2)*rinv/g1
c6 = (r0*g0-k*g2)*betainv
c7 = g2*(1/g1+c2*rinv)
c8 = (k*c6+r*r0+c3*c5)*r0inv^3
c12 = g0*h-g1*r0
c17 = r0-r-g2*k
c18 = eta*g1+2*g2*k
c20 = k*(g2*k+r)-g0*r0*zeta
c21 = (g2*k-r0)*(beta*c3-k*g1*r)*betainv*rinv^2*r0inv^3/g1+eta*g1*rinv*r0inv^2-2r0inv^2
c22 = rinv*(-g1-g0*g2/g1+g2*c2*rinv)
c25 = k*rinv*r0inv^2*(-g2+k*(c13-g2*r0)*betainv*r0inv^2-c13*r0inv-c12*c3*rinv*r0inv^2+
c13*c2*c3*rinv^2*r0inv^2-c13*(k*(g2*k+r)-g0*r0*zeta)*betainv*rinv*r0inv^2)
c26 = k*rinv^2*r0inv*(-g2*c12-g1*c13+g2*c13*c2*rinv)
ddfdtdxx = dfdt*c21
ddfdtdxv = dfdt*(c22-h*c21)
ddfdtdvx = ddfdtdxv
# ddfdtdvv = dfdt*(betainv*(1-c18*rinv)+d*(g1*c2-g0*r)*rinv^2/g1-h*(2c22-h*c21))
c34 = (-beta*eta^2*g2^2-eta*k*h8-h6*k^2-2beta*eta*r0*g1*g2+(g2^2-3*g1*g3)*beta*k*r0
- beta*g1^2*r0^2)*betainv*rinv^2+(eta*g2^2)*rinv/g1 + (k*h8)*betainv*rinv/g1
ddfdtdvv = dfdt*(c34 - 2*h*c22 +h^2*c21)
ddfdtdk = dfdt*(1/k-betainv*r0inv-c17*betainv*rinv*r0inv-c1*(g1*c2-g0*r)*rinv^2*r0inv/g1)
# ddfdtdk2 = -g1*(-betainv*r0inv-c17*betainv*rinv*r0inv-c1*(g1*c2-g0*r)*rinv^2*r0inv/g1)
#ddfdtdk2 = -(g2*k-r0)*(g1*r-beta*c1)*betainv*rinv^2*r0inv
ddfdtdk2 = -(g2*k-r0)*(beta*r0*(g3-g1*g2)-beta*eta*g2^2+k*H3(gamma,beta))*betainv*rinv^2*r0inv
ddfdtdh = dfdt*(g0*rinv/g1-c2*rinv^2-(2*k*r0inv-beta)*c22-eta*c21)
dgdtmhdfdtm1dxx = c25
dgdtmhdfdtm1dxv = c26-h*c25
dgdtmhdfdtm1dvx = c26-h*c25
h2 = H2(gamma,beta)
# dgdtmhdfdtm1dvv = d*k*rinv^3*r0inv*(c13*c2-r*c12)+k*(c13*(r0*g0-k*g2)-g2*r*r0)*betainv*rinv^2*r0inv-2*h*c26+h^2*c25
# dgdtmhdfdtm1dvv = d*k*rinv^3*r0inv*k*(r0*(g1*g2-g3)+eta*g2^2+k*g2*g3)+k*(c13*(r0*g0-k*g2)-g2*r*r0)*betainv*rinv^2*r0inv-2*h*c26+h^2*c25
# println("\dot g - h \dot f -1, dv0 terms: ",d*k*rinv^3*r0inv*c13*c2," ",-d*k*rinv^3*r0inv*r*c12," ",k*c13*r0*g0*betainv*rinv^2*r0inv," ",-k*c13*k*g2*betainv*rinv^2*r0inv," ",-k*g2*r*r0*betainv*rinv^2*r0inv," ",-2*h*c26," ",h^2*c25)
# println("second version of dv0 terms: ",d*k*rinv^3*r0inv*k*r0*g1*g2," ",-d*k*rinv^3*r0inv*k*r0*g3," ",d*k*rinv^3*r0inv*k*eta*g2^2," ",d*k*rinv^3*r0inv*k*k*g2*g3," ",-k*eta*k*g1*g2^2*betainv*rinv^2*r0inv," ",-k*g1*g2*g3*k^2*betainv*rinv^2*r0inv," ",-k*r0*eta*beta*g1*g2^2*betainv*rinv^2*r0inv," ",-r0*k*k*g1*h2*betainv*rinv^2*r0inv," ",-beta*k*g2^2*g0*r0^2*betainv*rinv^2*r0inv," ",-2*h*c26," ",h^2*c25)
c33 = d*k*rinv^3*r0inv*k*(h*g2- r0*g3)+k*(-eta*k*g1*g2^2-g1*g2*g3*k^2-r0*eta*beta*g1*g2^2-r0*k*g1*h2 - beta*g2^2*g0*r0^2)*betainv*rinv^2*r0inv
dgdtmhdfdtm1dvv = c33-2*h*c26+h^2*c25
dgdtmhdfdtm1dk = rinv*r0inv*(-k*(c13-g2*r0)*betainv*r0inv+c13-k*c13*c17*betainv*rinv*r0inv+k*c1*c12*rinv*r0inv-k*c1*c2*c13*rinv^2*r0inv)
# dgdtmhdfdtm1dk2 = -(c13-g2*r0)*betainv*r0inv-c13*c17*betainv*rinv*r0inv+c1*c12*rinv*r0inv-c1*c2*c13*rinv^2*r0inv
#dgdtmhdfdtm1dk2 = g2*betainv+rinv*r0inv*(c1*c12+c13*((k*g2-r0)*betainv-c1*c2*rinv))
h3 = H3(gamma,beta)
dgdtmhdfdtm1dk2 = k*betainv*rinv^2*r0inv*(-beta*eta^2*g2^4+eta*g2*(g1*g2^2+g1^2*g3-5*g2*g3)*k+g2*g3*h3*k^2+
2eta*r0*beta*g2^2*(g3-g1*g2)+(4g3-g0*g3-g1*g2)*(g3-g1*g2)*r0*k+beta*(2g1*g3*g2-g1^2*g2^2-g3^2)*r0^2)
dgdtmhdfdtm1dh = g1*k*rinv*r0inv+k*c12*rinv^2*r0inv-k*c2*c13*rinv^3*r0inv-(2*k*r0inv-beta)*c26-eta*c25
@inbounds for j=1:3
# Next, compute the \delta v-derivatives:
delxv_jac[3+j, j] = dfdt
delxv_jac[3+j,3+j] = dgdtm1
@inbounds for i=1:3
delxv_jac[3+j, i] += (ddfdtdxx*x0[i]+ddfdtdxv*v0[i])*x0[j] + (dgdtmhdfdtm1dxx*x0[i]+dgdtmhdfdtm1dxv*v0[i])*v0[j]
delxv_jac[3+j,3+i] += (ddfdtdvx*x0[i]+ddfdtdvv*v0[i])*x0[j] + (dgdtmhdfdtm1dvx*x0[i]+dgdtmhdfdtm1dvv*v0[i])*v0[j]
end
delxv_jac[3+j, 7] = ddfdtdk*x0[j] + dgdtmhdfdtm1dk*v0[j]
delxv_jac[3+j, 8] = ddfdtdh*x0[j] + dgdtmhdfdtm1dh*v0[j]
# Compute the mass jacobian separately since otherwise cancellations happen in kepler_driftij_gamma:
jac_mass[3+j] = GNEWT^2*r0inv*rinv*(ddfdtdk2*x0[j]+dgdtmhdfdtm1dk2*v0[j])
end
if debug
# Now include derivatives of gamma, r, fm1, dfdt, gmh, and dgdtmhdfdtm1:
@inbounds for i=1:3
delxv_jac[ 7,i] = -sqb*rinv*((g2-h*c3*r0inv^3)*v0[i]+c3*x0[i]*r0inv^3); delxv_jac[7,3+i] = sqb*rinv*((-d+2*g2*h-h^2*c3*r0inv^3)*v0[i]+(-g2+h*c3*r0inv^3)*x0[i])
delxv_jac[ 8,i] = (c20*betainv-c2*c3*rinv)*r0inv^3*x0[i]+((eta*g2+g1*r0)*rinv+h*r0inv^3*(c2*c3*rinv-c20*betainv))*v0[i]
# delxv_jac[8,3+i] = (g1-g2*c2*rinv+h*r0inv^3*(c2*c3*rinv-c20*betainv))*x0[i]+(-2g1*h+c18*betainv+(2g2*h-d)*c2*rinv+h^2*r0inv^3*(c20*betainv-c2*c3*rinv))*v0[i]
# delxv_jac[8,3+i] = ((g1*r0+eta*g2)*rinv+h*r0inv^3*(c2*c3*rinv-c20*betainv))*x0[i]+(-2g1*h+c18*betainv+(2g2*h-d)*c2*rinv+h^2*r0inv^3*(c20*betainv-c2*c3*rinv))*v0[i]
drdv0x0 = (beta*g1*g2+((eta*g2+k*g3)*eta*g0*c3)*rinv*r0inv^3 + (g1*g0*(2k*eta^2*g2+3eta*k^2*g3))*betainv*rinv*r0inv^2-
k*betainv*r0inv^3*(eta*g1*(eta*g2+k*g3)+g3*g0*r0^2*beta+2h*g2*k)+(g1*zeta)*rinv*((h*c3)*r0inv^3 - g2) -
(eta*(beta*g2*g0*r0+k*g1^2)*(eta*g1+k*g2))*betainv*rinv*r0inv^2)
# delxv_jac[8,3+i] = drdv0x0*x0[i]+ (k*betainv*rinv*(eta*(2g0*g3-g1*g2+g3) - h6*k^2 + (g2^2 - 2*g1*g3)*beta*k*r0) + h*drdv0x0)*v0[i]
delxv_jac[8,3+i] = drdv0x0*x0[i] - (k*betainv*rinv*(eta*(beta*g2*g3-h8) - h6*k + (g2^2 - 2*g1*g3)*beta*r0) + h*drdv0x0)*v0[i]
# +(-2g1*h+c18*betainv+(2g2*h-d)*c2*rinv+h^2*r0inv^3*(c20*betainv-c2*c3*rinv))*v0[i]
# delxv_jac[8,3+i] = ((eta*g2+g1*r0)*rinv+h*betainv*rinv*r0inv^3*((3g1*g3 - 2g2^2)*k^3 - k^2*eta*h8 +
# beta*k^2*(g2^2 - 3*g1*g3)*r0 - beta*r0^3 - k*g2*beta*(eta^2*g2 + 2eta*g1*r0 + g0*r0^2)))*x0[i]+(-2g1*h+c18*betainv+((g1*r0-g3*k-2*g0*h)*c2)*betainv*rinv +
# h^2*((2*g2^2 - 3*g1*g3)*k^3 + beta*r0^3 + k^2*(eta*(g1*g2 - 3*g0*g3) + beta*(3*g1*g3 - g2^2)*r0) +
# k*beta*g2*(eta*(eta*g2 + g1*r0) + r0*(eta*g1 + g0*r0)))*betainv*rinv*r0inv^3)*v0[i]
delxv_jac[ 9,i] = dfm1dxx*x0[i]+dfm1dxv*v0[i]; delxv_jac[ 9,3+i]=dfm1dvx*x0[i]+dfm1dvv*v0[i]
delxv_jac[10,i] = ddfdtdxx*x0[i]+ddfdtdxv*v0[i]; delxv_jac[10,3+i]=ddfdtdvx*x0[i]+ddfdtdvv*v0[i]
delxv_jac[11,i] = dgmhdxx*x0[i]+dgmhdxv*v0[i]; delxv_jac[11,3+i]=dgmhdvx*x0[i]+dgmhdvv*v0[i]
delxv_jac[12,i] = dgdtmhdfdtm1dxx*x0[i]+dgdtmhdfdtm1dxv*v0[i]; delxv_jac[12,3+i]=dgdtmhdfdtm1dvx*x0[i]+dgdtmhdfdtm1dvv*v0[i]
end
delxv_jac[ 7,7] = sqb*c1*r0inv*rinv; delxv_jac[7,8] = sqb*rinv*(1+eta*c3*r0inv^3+g2*(2k*r0inv-beta))
# delxv_jac[ 8,7] = (c17*betainv+c1*c2*rinv)*r0inv
delxv_jac[ 8,7] = betainv*r0inv*rinv*(-g2*r0^2*beta-eta*g1*g2*(k+beta*r0)+eta*g0*g3*(2*k+zeta)-
g2^2*(beta*eta^2+2*k*zeta)+g1*g3*zeta*(3*k-beta*r0)); delxv_jac[8,8] = c2*rinv
delxv_jac[ 8,8] = ((r0*g1+eta*g2)*rinv)*(beta-2*k*r0inv)+c2*rinv+eta*r0inv^3*(c2*c3*rinv-c20*betainv)
delxv_jac[ 9,7] = dfm1dk; delxv_jac[ 9,8] = dfm1dh
delxv_jac[10,7] = ddfdtdk; delxv_jac[10,8] = ddfdtdh
delxv_jac[11,7] = dgmhdk; delxv_jac[11,8] = dgmhdh
delxv_jac[12,7] = dgdtmhdfdtm1dk; delxv_jac[12,8] = dgdtmhdfdtm1dh
end
else
# Now compute the Kepler-Drift Jacobian terms:
# First, x0 derivatives:
# delxv[ j] = fm1*x0[j]+gmh*v0[j] # position x_ij(t+h)-x_ij(t) - h*v_ij(t) or -h*v_ij(t+h)
# delxv[3+j] = dfdt*x0[j]+dgdtm1*v0[j] # velocity v_ij(t+h)-v_ij(t)
# First, the diagonal terms:
# Now the off-diagonal terms:
d = (h + eta*g2 + 2*k*g3)*betainv
c1 = d-r0*g3
c2 = eta*g0+g1*zeta
c3 = d*k+g1*r0^2
c4 = eta*g1+2*g0*r0
c6 = (r0*g0-k*g2)*betainv
c9 = g2*r-h1*k
c14 = r0*g2-k*h1
c15 = eta*h1+h2*r0
c16 = eta*h2+g1*gamma*r0/sqb
c17 = r0-r-g2*k
c18 = eta*g1+2*g2*k
c19 = 4*eta*h1+3*h2*r0
c23 = h2*k-r0*g1
h6 = H6(gamma,beta)
h8 = H8(gamma,beta)
# Derivatives of \delta x with respect to x0, v0, k & h:
dfm1dxx = k*rinv^3*betainv*r0inv^4*(k*h1*r^2*r0*(beta-2*k*r0inv)+beta*c3*(r*c23+c14*c2)+c14*r*(k*(r-g2*k)+g0*r0*zeta))
dfm1dxv = k*rinv^2*r0inv*(k*(g2*h2+g1*h1)-2g1*g2*r0+g2*c14*c2*rinv)
dfm1dvx = dfm1dxv
# dfm1dvv = k*r0inv*rinv^2*betainv*(r*(2*g2*r0-4*h1*k)+d*beta*c23-c18*c14+d*beta*c14*c2*rinv)
dfm1dvv = k*r0inv*rinv^2*betainv*(2eta*k*(g2*g3-g1*h1)+(3g3*h2-4h1*g2)*k^2 +
beta*g2*r0*(3h1*k-g2*r0)+c14*rinv*(-beta*g2^2*eta^2+eta*k*(2g0*g3-h2)-
h6*k^2+(-2eta*g1*g2+k*(h1-2g1*g3))*beta*r0-beta*g1^2*r0^2))
dfm1dh = (g1*k-h2*k^2*r0inv-k*c14*c2*rinv*r0inv)*rinv^2
dfm1dk = rinv*r0inv*(4*h1*k^2*betainv*r0inv-k*h1-2*g2*k*betainv+c14-k*c14*c17*betainv*rinv*r0inv+
k*(g1*r0-k*h2)*c1*rinv*r0inv-k*c14*c1*c2*rinv^2*r0inv)
# dfm1dk2_old = 4*h1*k*betainv*r0inv-h1-2*g2*betainv-c14*c17*betainv*rinv*r0inv+ (g1*r0-k*h2)*c1*rinv*r0inv-c14*c1*c2*rinv^2*r0inv
# New expression for d(f-1-h \dot f)/dk with cancellations of higher order terms in gamma is:
dfm1dk2 = betainv*r0inv*rinv^2*(r*(2eta*k*(g1*h1-g3*g2)+(4g2*h1-3g3*h2)*k^2-eta*r0*beta*g1*h1 + (g3*h2-4g2*h1)*beta*k*r0 + g2*h1*beta^2*r0^2) -
# In the following line I need to replace 3g0*g3-g1*g2 by -H8:
c14*(-eta^2*beta*g2^2 - k*eta*h8 - k^2*h6 - eta*r0*beta*(g1*g2 + g0*g3) + 2*(h1 - g1*g3)*beta*k*r0 - (g2 - beta*g1*g3)*beta*r0^2))
# println("dfm1dk2: old ",dfm1dk2_old," new: ",dfm1dk2)
dgmhdxx = k*rinv*r0inv*(h2+k*c19*betainv*r0inv^2-c16*c3*rinv*r0inv^2+c2*c3*c15*(rinv*r0inv)^2-c15*(k*(g2*k+r)-g0*r0*zeta)*betainv*rinv*r0inv^2)
dgmhdxv = k*rinv^2*(h1*r-g2*c16-g1*c15+g2*c2*c15*rinv)
dgmhdvx = dgmhdxv
# dgmhdvv = k*rinv^2*(-d*c16-c15*c18*betainv+r*c19*betainv+d*c2*c15*rinv)
dgmhdvv = k*betainv*rinv^2*(2*eta^2*(g1*h1-g2*g3)+eta*k*(4g2*h1-3h2*g3)+r0*eta*(4g0*h1-2g1*g3)+
# In the following lines I need to replace g1*g2-3g0*g3-g1*g2 by H8:
3r0*k*((g1+beta*g3)*h1-g3*g2)+(g0*h8-beta*g1*(g2^2+g1*g3))*r0^2 -
c15*rinv*(beta*g2^2*eta^2+eta*k*h8+h6*k^2+(2eta*g1*g2-k*(g2^2-3g1*g3))*beta*r0+beta*g1^2*r0^2))
dgmhdk = rinv*(k*c1*c16*rinv*r0inv+c15-k*c15*c17*betainv*rinv*r0inv-k*c19*betainv*r0inv-k*c1*c2*c15*rinv^2*r0inv)
# dgmhdk2_old = c1*c16*rinv-c15*c17*betainv*rinv-c19*betainv-c1*c2*c15*rinv^2
h7 = H7(gamma,beta)
dgmhdk2 = betainv*rinv^2*(r*(2eta^2*(g3*g2-g1*h1) + eta*k*(3g3*h2 - 4g2*h1) +
r0*eta*(beta*g3*(g1*g2 + g0*g3) - 2g0*h6) + (-h6*(g1 + beta*g3) + g2*(2g3 - h2))*r0*k +
(h7 - beta^2*g1*g3^2)*r0^2)- c15*(-beta*eta^2*g2^2 + eta*k*(-h2 + 2g0*g3) - h6*k^2 -
r0*eta*beta*(h2 + 2g0*g3) + 2beta*(2*h1 - g2^2)*r0*k + beta*(beta*g1*g3 - g2)*r0^2))
# println("gmhgdot: old ",dgmhdk2_old," new: ",dgmhdk2)
dgmhdh = k*rinv^3*(r*c16-c2*c15)
@inbounds for j=1:3
# First, compute the \delta x-derivatives:
delxv_jac[ j, j] = fm1
delxv_jac[ j,3+j] = gmh
@inbounds for i=1:3
delxv_jac[j, i] += (dfm1dxx*x0[i]+dfm1dxv*v0[i])*x0[j] + (dgmhdxx*x0[i]+dgmhdxv*v0[i])*v0[j]
delxv_jac[j,3+i] += (dfm1dvx*x0[i]+dfm1dvv*v0[i])*x0[j] + (dgmhdvx*x0[i]+dgmhdvv*v0[i])*v0[j]
end
delxv_jac[ j, 7] = dfm1dk*x0[j] + dgmhdk*v0[j]
delxv_jac[ j, 8] = dfm1dh*x0[j] + dgmhdh*v0[j]
jac_mass[ j] = GNEWT^2*rinv*r0inv*(dfm1dk2*x0[j]+dgmhdk2*v0[j])
end
# Derivatives of \delta v with respect to x0, v0, k & h:
c5 = (r0-k*g2)*rinv/g1
c7 = g2*(1/g1+c2*rinv)
c8 = (k*c6+r*r0+c3*c5)*r0inv^3
c12 = g0*h-g1*r0
c20 = k*(g2*k+r)-g0*r0*zeta
ddfdtdxx = dfdt*(eta*g1*rinv-2-g0*c3*rinv*r0inv/g1+c2*c3*r0inv*rinv^2-k*(k*g2-r0)*betainv*rinv*r0inv)*r0inv^2
ddfdtdxv = -dfdt*(g0*g2/g1+(r0*g1+eta*g2)*rinv)*rinv
ddfdtdvx = ddfdtdxv
# ddfdtdvv = dfdt*(betainv-d*g0*rinv/g1-c18*betainv*rinv+d*c2*rinv^2)
ddfdtdvv = -k*rinv^3*r0inv*betainv*((beta*eta*g2^2+k*h8)*(r0*g0+k*g2)+
g1*(- h6*k^2 + (-2eta*g1*g2+(h1-2g1*g3)*k)*beta*r0 - beta*g1^2*r0^2))
ddfdtdk = dfdt*(1/k+c1*(r0-g2*k)*r0inv*rinv^2/g1-betainv*r0inv*(1+c17*rinv))
# ddfdtdk2 = -g1*(c1*(r0-g2*k)*r0inv*rinv^2/g1-betainv*r0inv*(1+c17*rinv))
# ddfdtdk2 = r0inv*(g1*c17*betainv*rinv+g1*betainv-g1*c1*c2*rinv^2-c1*g0*rinv)
h3 = H3(gamma,beta)
ddfdtdk2 = (r0-g2*k)*betainv*r0inv*rinv^2*(-eta*beta*g2^2+h3*k+(g3-g1*g2)*beta*r0)
ddfdtdh = dfdt*(r0-g2*k)*rinv^2/g1
dgdotm1dxx = rinv^2*r0inv^3*((eta*g2+g1*r0)*k*c3*rinv+g2*k*(k*(g2*k-r)-g0*r0*zeta)*betainv)
dgdotm1dxv = k*g2*rinv^3*(r*g1+r0*g1+eta*g2)
dgdotm1dvx = dgdotm1dxv
# dgdotm1dvv = k*rinv^2*(d*g1+g2*c18*betainv-2*r*g2*betainv-d*g2*c2*rinv)
dgdotm1dvv = k*betainv*rinv^3*(eta^2*beta*g2^3-eta*k*g2*h3+3r0*eta*beta*g1*g2^2 +
r0*k*(-g0*h6+3beta*g1*g2*g3)+beta*g2*(g0*g2+g1^2)*r0^2)
dgdotm1dk = rinv*r0inv*(-r0*g2+g2*k*(r+r0-g2*k)*betainv*rinv-k*g1*c1*rinv+k*g2*c1*c2*rinv^2)
# dgdotm1dk2 = rinv*(g2*(r+r0-g2*k)*betainv-g1*c1+g2*c1*c2*rinv)
dgdotm1dk2 = betainv*rinv^2*(-beta*eta^2*g2^3+eta*k*g2*h3+eta*r0*beta*g2*(g3-2g1*g2)+
(h6-beta*g2^3)*r0*k + beta*g1*(g3 - g1*g2)*r0^2)
# (g2^2*(1+g0)-3*g1*g3)*r0*k + beta*g1*(g3 - g1*g2)*r0^2)
dgdotm1dh = k*rinv^3*(g2*c2-r*g1)
@inbounds for j=1:3
# Next, compute the \delta v-derivatives:
delxv_jac[3+j, j] = dfdt
delxv_jac[3+j,3+j] = dgdtm1
@inbounds for i=1:3
delxv_jac[3+j, i] += (ddfdtdxx*x0[i]+ddfdtdxv*v0[i])*x0[j] + (dgdotm1dxx*x0[i]+dgdotm1dxv*v0[i])*v0[j]
delxv_jac[3+j,3+i] += (ddfdtdvx*x0[i]+ddfdtdvv*v0[i])*x0[j] + (dgdotm1dvx*x0[i]+dgdotm1dvv*v0[i])*v0[j]
end
delxv_jac[3+j, 7] = ddfdtdk*x0[j] + dgdotm1dk*v0[j]
delxv_jac[3+j, 8] = ddfdtdh*x0[j] + dgdotm1dh*v0[j]
jac_mass[3+j] = GNEWT^2*rinv*r0inv*(ddfdtdk2*x0[j]+dgdotm1dk2*v0[j])
end
if debug
# Now include derivatives of gamma, r, fm1, gmh, dfdt, and dgdtmhdfdtm1:
@inbounds for i=1:3
delxv_jac[ 7,i] = -sqb*rinv*(g2*v0[i]+c3*x0[i]*r0inv^3); delxv_jac[7,3+i] = -sqb*rinv*(d*v0[i]+g2*x0[i])
delxv_jac[ 8,i] = (c20*betainv-c2*c3*rinv)*r0inv^3*x0[i]+((r0*g1+eta*g2)*rinv)*v0[i]
delxv_jac[8,3+i] = (c18*betainv-d*c2*rinv)*v0[i]+((r0*g1+eta*g2)*rinv)*x0[i]
# delxv_jac[8,3+i] = (g2*(2k*(r-r0)+beta*(r0^2+eta^2*g2)-zeta*eta*g1) + c2*g3*(2k+zeta))*betainv*rinv*r0inv*v0[i]+((r0*g1+eta*g2)*rinv)*x0[i]
delxv_jac[ 9,i] = dfm1dxx*x0[i]+dfm1dxv*v0[i]; delxv_jac[ 9,3+i]=dfm1dvx*x0[i]+dfm1dvv*v0[i]
delxv_jac[10,i] = ddfdtdxx*x0[i]+ddfdtdxv*v0[i]; delxv_jac[10,3+i]=ddfdtdvx*x0[i]+ddfdtdvv*v0[i]
delxv_jac[11,i] = dgmhdxx*x0[i]+dgmhdxv*v0[i]; delxv_jac[11,3+i]=dgmhdvx*x0[i]+dgmhdvv*v0[i]
delxv_jac[12,i] = dgdotm1dxx*x0[i]+dgdotm1dxv*v0[i]; delxv_jac[12,3+i]=dgdotm1dvx*x0[i]+dgdotm1dvv*v0[i]
end
delxv_jac[ 7,7] = sqb*c1*r0inv*rinv; delxv_jac[7,8] = sqb*rinv
# delxv_jac[ 8,7] = (c17*betainv+c1*c2*rinv)*r0inv; delxv_jac[8,8] = c2*rinv
delxv_jac[ 8,7] = betainv*r0inv*rinv*(-g2*r0^2*beta-eta*g1*g2*(k+beta*r0)+eta*g0*g3*(2*k+zeta)-
g2^2*(beta*eta^2+2*k*zeta)+g1*g3*zeta*(3*k-beta*r0)); delxv_jac[8,8] = c2*rinv
delxv_jac[ 9,7] = dfm1dk; delxv_jac[ 9,8] = dfm1dh
delxv_jac[10,7] = ddfdtdk; delxv_jac[10,8] = ddfdtdh
delxv_jac[11,7] = dgmhdk; delxv_jac[11,8] = dgmhdh
delxv_jac[12,7] = dgdotm1dk; delxv_jac[12,8] = dgdotm1dh
end
end
#return delxv_jac::Array{T,2}
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 14636 |
# Wisdom & Hernandez version of Kepler solver, but with quartic convergence.
using ForwardDiff
include("g3.jl")
#function calc_ds_opt(y::T,yp::T,ypp::T,yppp::T) where {T <: Real}
## Computes quartic Newton's update to equation y=0 using first through 3rd derivatives.
## Uses techniques outlined in Murray & Dermott for Kepler solver.
## Rearrange to reduce number of divisions:
#num = y*yp
#den1 = yp*yp-y*ypp*.5
#den12 = den1*den1
#den2 = yp*den12-num*.5*(ypp*den1-third*num*yppp)
#return -y*den12/den2
#end
function solve_kepler_drift!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,
r0::T,s0::T,state::Array{T,1},drift_first::Bool) where {T <: Real}
# Solves elliptic Kepler's equation for both elliptic and hyperbolic cases,
# along with a drift before or after the kepler step.
# Initial guess (if s0 = 0):
r0inv = inv(r0)
beta0inv = inv(beta0)
signb = sign(beta0)
if s0 == zero(T)
s = h*r0inv
else
s = copy(s0)
end
s0 = copy(s)
sqb = sqrt(signb*beta0)
y = zero(T); yp = one(T)
iter = 0
ds = Inf
zeta = k-r0*beta0
if drift_first
eta = dot(x0-h*v0,v0)
else
eta = dot(x0,v0)
end
KEPLER_TOL = sqrt(eps(h))
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < 10)
xx = sqb*s
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
sx *= sqb
# Third derivative:
yppp = zeta*cx - signb*eta*sx
# First derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = signb*zeta*beta0inv*sx + eta*cx
y = (-ypp + eta +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
end
# Since we updated s, need to recompute:
xx = 0.5*sqb*s
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
# Now, compute final values. Compute Wisdom/Hernandez G_i^\beta(s) functions:
g1bs = 2.0*sx*cx/sqb
g2bs = 2.0*signb*sx^2*beta0inv
g0bs = 1.0-beta0*g2bs
# This should be computed to prevent roundoff error. [ ]
#g3bs = (1.0-g1bs)*beta0inv
g3bs = G3(s*sqb,beta0)
#if typeof(g1bs) == Float64
# println("g1: ",g1bs," g2: ",g2bs," g3: ",g3bs)
#end
# Compute Gauss' Kepler functions:
f = one(T) - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + eta*g2bs # eqn (27)
if drift_first
r = norm(f*(x0-h*v0)+g*v0)
else
r = norm(f*x0+g*v0)
end
#if typeof(r) == Float64
# println("r: ",r)
#end
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
if drift_first
# Drift backwards before Kepler step: (1/22/2018)
fm1 = -k*r0inv*g2bs
# This is given in 2/7/2018 notes:
gmh = k*r0inv*(r0*(g1bs*g2bs-g3bs)+eta*g2bs^2+k*g3bs*g2bs)
else
# Drift backwards after Kepler step: (1/24/2018)
fm1 = k*rinv*(g2bs-k*r0inv*H1(s*sqb,beta0))
# This is g-h*dgdt
gmh = k*rinv*(r0*H2(s*sqb,beta0)+eta*H1(s*sqb,beta0))
end
# Compute velocity component functions:
if drift_first
# 2/1/18 notes:
dgdtm1 = k*r0inv*rinv*(r0*g0bs*g2bs+eta*g1bs*g2bs+k*g1bs*g3bs)
else
# 1/22/18 notes:
dgdtm1 = -k*rinv*g2bs
end
#if typeof(fm1) == Float64
# println("fm1: ",fm1," dfdt: ",dfdt," gmh: ",gmh," dgdt-1: ",dgdtm1)
#end
for j=1:3
# Compute difference vectors (finish - start) of step:
state[1+j] = fm1*x0[j]+gmh*v0[j] # position x_ij(t+h)-x_ij(t) - h*v_ij(t) or -h*v_ij(t+h)
state[4+j] = dfdt*x0[j]+dgdtm1*v0[j] # velocity v_ij(t+h)-v_ij(t)
end
return s,f,g,dfdt,dgdtm1,cx,sx,g1bs,g2bs,g3bs,r,rinv,ds,iter
end
function jac_delxv(x0::Array{T,1},v0::Array{T,1},k::T,s::T,beta0::T,h::T,drift_first::Bool) where {T <: Real}
# Using autodiff, computes Jacobian of delx & delv with respect to x0, v0, k, s, beta0 & h.
# Autodiff requires a single-vector input, so create an array to hold the independent variables:
input = zeros(T,10)
input[1:3]=x0; input[4:6]=v0; input[7]=k; input[8]=s; input[9]=beta0; input[10]=h
# Create a closure so that the function knows value of drift_first:
function delx_delv(input::Array{T2,1}) where {T2 <: Real} # input = x0,v0,k,s,beta0,h,drift_first
# Compute delx and delv from h, s, k, beta0, x0 and v0:
x0 = input[1:3]; v0 = input[4:6]; k = input[7]
s = input[8]; beta0=input[9]; h = input[10]
# Set up a single output array for delx and delv:
delxv = zeros(T2,6)
# Compute square root of beta0:
signb = sign(beta0)
sqb = sqrt(abs(beta0))
beta0inv=inv(beta0)
if drift_first
r0 = norm(x0-h*v0)
eta = dot(x0-h*v0,v0)
else
r0 = norm(x0)
eta = dot(x0,v0)
end
r0inv = inv(r0)
# Since we updated s, need to recompute:
xx = 0.5*sqb*s
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
# Now, compute final values. Compute Wisdom/Hernandez G_i^\beta(s) functions:
g1bs = 2.0*sx*cx/sqb
g2bs = 2.0*signb*sx^2*beta0inv
g0bs = 1.0-beta0*g2bs
g3bs = G3(s*sqb,beta0)
# Compute Gauss' Kepler functions:
f = 1.0 - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + eta*g2bs # eqn (27)
if drift_first
r = norm(f*(x0-h*v0)+g*v0)
else
r = norm(f*x0+g*v0)
end
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
if drift_first
# Drift backwards before Kepler step: (1/22/2018)
fm1 = -k*r0inv*g2bs
# This is given in 2/7/2018 notes:
gmh = k*r0inv*(r0*(g1bs*g2bs-g3bs)+eta*g2bs^2+k*g3bs*g2bs)
else
# Drift backwards after Kepler step: (1/24/2018)
fm1 = k*rinv*(g2bs-k*r0inv*H1(s*sqb,beta0))
# This is g-h*dgdt
gmh = k*rinv*(r0*H2(s*sqb,beta0)+eta*H1(s*sqb,beta0))
end
# Compute velocity component functions:
if drift_first
dgdtm1 = k*r0inv*rinv*(r0*g0bs*g2bs+eta*g1bs*g2bs+k*g1bs*g3bs)
else
dgdtm1 = -k*rinv*g2bs
end
for j=1:3
# Compute difference vectors (finish - start) of step:
delxv[ j] = fm1*x0[j]+gmh*v0[j] # position x_ij(t+h)-x_ij(t) - h*v_ij(t) or -h*v_ij(t+h)
delxv[3+j] = dfdt*x0[j]+dgdtm1*v0[j] # velocity v_ij(t+h)-v_ij(t)
end
return delxv
end
# Use autodiff to compute Jacobian:
delxv_jac = ForwardDiff.jacobian(delx_delv,input)
# Return Jacobian:
return delxv_jac
end
function kep_drift_ell_hyp!(x0::Array{T,1},v0::Array{T,1},k::T,h::T,
s0::T,state::Array{T,1},drift_first::Bool) where {T <: Real}
if drift_first
r0 = norm(x0-h*v0)
else
r0 = norm(x0)
end
beta0 = 2*k/r0-dot(v0,v0)
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
# Now, solve for s in elliptical Kepler case:
f = zero(T); g=zero(T); dfdt=zero(T); dgdtm1=zero(T); cx=zero(T);sx=zero(T);g1bs=zero(T);g2bs=zero(T);g3bs=zero(T)
s=zero(T); ds = zero(T); r = zero(T);rinv=zero(T); iter=0
if beta0 > zero(T) || beta0 < zero(T)
s,f,g,dfdt,dgdtm1,cx,sx,g1bs,g2bs,g3bs,r,rinv,ds,iter = solve_kepler_drift!(h,k,x0,v0,beta0,r0,
s0,state,drift_first)
else
# println("Not elliptic or hyperbolic ",beta0," x0 ",x0)
r= zero(T); fill!(state,zero(T)); rinv=zero(T); s=zero(T); ds=zero(T); iter = 0
end
state[8]= r
# These need to be updated. [ ]
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# recompute beta:
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
function kep_drift_ell_hyp!(x0::Array{T,1},v0::Array{T,1},k::T,h::T,
s0::T,state::Array{T,1},jacobian::Array{T,2},drift_first::Bool,d::Derivatives{T}) where {T <: Real}
if drift_first
r0 = norm(x0-h*v0)
else
r0 = norm(x0)
end
beta0 = 2*k/r0-dot(v0,v0)
# Computes the Jacobian as well
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in elliptical Kepler case:
f = zero(T); g=zero(T); dfdt=zero(T); dgdtm1=zero(T); cx=zero(T);sx=zero(T);g1bs=zero(T);g2bs=zero(T);g3bs=zero(T)
s=zero(T); ds=zero(T); r = zero(T);rinv=zero(T); iter=0
if beta0 > zero(T) || beta0 < zero(T)
s,f,g,dfdt,dgdtm1,cx,sx,g1bs,g2bs,g3bs,r,rinv,ds,iter = solve_kepler_drift!(h,k,x0,v0,beta0,r0,
s0,state,drift_first)
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v} & q0 = {x0,v0}.
delxv_jac = jac_delxv(x0,v0,k,s,beta0,h,drift_first)
# println("computed jacobian with autodiff")
# Add in partial derivatives with respect to x0, v0 and k:
jacobian[1:6,1:7] = delxv_jac[1:6,1:7]
# Add in s and beta0 derivatives:
compute_jacobian_kep_drift!(h,k,x0,v0,beta0,s,f,g,dfdt,dgdtm1,cx,sx,g1bs,g2bs,r0,r,jacobian,delxv_jac,drift_first,d)
else
# println("Not elliptic or hyperbolic ",beta0," x0 ",x0)
r= zero(T); fill!(state,zero(T)); rinv=zero(T); s=zero(T); ds=zero(T); iter = 0
end
# recompute beta:
state[8]= r
# These need to be updated. [ ]
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
function compute_jacobian_kep_drift!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,s::T,
f::T,g::T,dfdt::T,dgdtm1::T,cx::T,sx::T,g1::T,g2::T,r0::T,r::T,jacobian::Array{T,2},drift_first::Bool,d::Derivatives{T}) where {T <: Real}
# This needs to be updated to incorporate backwards drifts. [ ]
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v,k} & q0 = {x0,v0,k}.
# Now, compute the Jacobian: (9/18/2017 notes)
g0 = one(T)-beta0*g2
# Expand g3 as a series if s is small:
sqb = sqrt(abs(beta0))
g3bs = G3(s*sqb,beta0)
# g3bs = (s-g1)/beta0
if drift_first
eta = dot(x0-h*v0,v0)
else
eta = dot(x0,v0)
end
absv0 = norm(v0)
#dsdbeta = (2h-r0*(s*g0+g1)+k/beta0*(s*g0-g1)-eta*s*g1)/(2beta0*r)
# New expression derived on 8/14/2019:
dsdbeta = (h+eta*g2+2*k*g3bs-s*r)/(2beta0*r)
dsdr0 = -(2k/r0^2*dsdbeta+g1/r)
dsda0 = -g2/r
dsdv0 = -2absv0*dsdbeta
dsdk = 2/r0*dsdbeta-g3bs/r
dbetadr0 = -2k/r0^2
dbetadv0 = -2absv0
dbetadk = 2/r0
# "p" for partial derivative:
for i=1:3
d.pxpr0[i] = k/r0^2*g2*x0[i]+g1*v0[i]
d.pxpa0[i] = g2*v0[i]
d.pxpk[i] = -g2/r0*x0[i]
d.pxps[i] = -k/r0*g1*x0[i]+(r0*g0+eta*g1)*v0[i]
d.pxpbeta[i] = -k/(2beta0*r0)*(s*g1-2g2)*x0[i]+1/(2beta0)*(s*r0*g0-r0*g1+s*eta*g1-2*eta*g2)*v0[i]
d.prvpr0[i] = k*g1/r0^2*x0[i]+g0*v0[i]
d.prvpa0[i] = g1*v0[i]
d.prvpk[i] = -g1/r0*x0[i]
d.prvps[i] = -k*g0/r0*x0[i]+(-beta0*r0*g1+eta*g0)*v0[i]
d.prvpbeta[i] = -k/(2beta0*r0)*(s*g0-g1)*x0[i]+1/(2beta0)*(-s*r0*beta0*g1+eta*s*g0-eta*g1)*v0[i]
end
prpr0 = g0
prpa0 = g1
prpk = g2
prps = (k-beta0*r0)*g1+eta*g0
prpbeta = 1/(2beta0)*(s*(k-beta0*r0)*g1+eta*s*g0-eta*g1-2k*g2)
for i=1:3
d.dxdr0[i] = d.pxps[i]*dsdr0 + d.pxpbeta[i]*dbetadr0 + d.pxpr0[i]
d.dxda0[i] = d.pxps[i]*dsda0 + d.pxpa0[i]
d.dxdv0[i] = d.pxps[i]*dsdv0 + d.pxpbeta[i]*dbetadv0
d.dxdk[i] = d.pxps[i]*dsdk + d.pxpbeta[i]*dbetadk + d.pxpk[i]
d.drvdr0[i] = d.prvps[i]*dsdr0 + d.prvpbeta[i]*dbetadr0 + d.prvpr0[i]
d.drvda0[i] = d.prvps[i]*dsda0 + d.prvpa0[i]
d.drvdv0[i] = d.prvps[i]*dsdv0 + d.prvpbeta[i]*dbetadv0
d.drvdk[i] = d.prvps[i]*dsdk + d.prvpbeta[i]*dbetadk + d.prvpk[i]
end
drdr0 = prpr0 + prps*dsdr0 + prpbeta*dbetadr0
drda0 = prpa0 + prps*dsda0
drdv0 = prps*dsdv0 + prpbeta*dbetadv0
drdk = prpk + prps*dsdk + prpbeta*dbetadk
for i=1:3
d.vtmp[i] = dfdt*x0[i]+(dgdtm1+1.0)*v0[i]
d.dvdr0[i] = (d.drvdr0[i]-drdr0*d.vtmp[i])/r
d.dvda0[i] = (d.drvda0[i]-drda0*d.vtmp[i])/r
d.dvdv0[i] = (d.drvdv0[i]-drdv0*d.vtmp[i])/r
d.dvdk[i] = (d.drvdk[i] -drdk *d.vtmp[i])/r
end
# Now, compute Jacobian:
for i=1:3
jacobian[ i, i] = f
jacobian[ i,3+i] = g
jacobian[3+i, i] = dfdt
jacobian[3+i,3+i] = dgdt+1.0
jacobian[ i,7] = d.dxdk[i]
jacobian[3+i,7] = d.dvdk[i]
end
for j=1:3
for i=1:3
jacobian[ i, j] += d.dxdr0[i]*x0[j]/r0 + d.dxda0[i]*v0[j]
jacobian[ i,3+j] += d.dxdv0[i]*v0[j]/absv0 + d.dxda0[i]*x0[j]
jacobian[3+i, j] += d.dvdr0[i]*x0[j]/r0 + d.dvda0[i]*v0[j]
jacobian[3+i,3+j] += d.dvdv0[i]*v0[j]/absv0 + d.dvda0[i]*x0[j]
end
end
jacobian[7,7]=one(T)
return
end
function compute_jacobian_kep_drift!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,s::T,
f::T,g::T,dfdt::T,dgdtm1::T,cx::T,sx::T,g1::T,g2::T,r0::T,r::T,jacobian::Array{T,2},
delxv_jac::Array{T,2},drift_first::Bool,d::Derivatives{T}) where {T <: Real}
# This needs to be updated to incorporate backwards drifts. [ ]
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v,k} & q0 = {x0,v0,k}.
# Now, compute the Jacobian: (9/18/2017 notes)
g0 = one(T)-beta0*g2
# Expand g3 as a series if s is small:
sqb = sqrt(abs(beta0))
g3bs = G3(s*sqb,beta0)
# g3bs = (s-g1)/beta0
if drift_first
eta = dot(x0-h*v0,v0)
r0 = norm(x0-h*v0)
else
eta = dot(x0,v0)
r0 = norm(x0)
end
absv0 = norm(v0)
r0inv = inv(r0)
#dsdbeta = (2h-r0*(s*g0+g1)+k/beta0*(s*g0-g1)-eta*s*g1)/(2beta0*r)
# New expression derived on 8/14/2019:
dsdbeta = (h+eta*g2+2*k*g3bs-s*r)/(2beta0*r)
dsdr0 = -(2k*r0inv^2*dsdbeta+g1/r)
dsda0 = -g2/r
dsdv0 = -2absv0*dsdbeta
dsdk = 2*r0inv*dsdbeta-g3bs/r
dbetadr0 = -2k*r0inv^2
dbetadv0 = -2absv0
dbetadk = 2r0inv
# Compute s & beta components of x0 & v0 derivatives:
for i=1:3
d.dxdr0[i] = delxv_jac[ i,8]*dsdr0 + delxv_jac[ i,9]*dbetadr0
d.dxda0[i] = delxv_jac[ i,8]*dsda0
d.dxdv0[i] = delxv_jac[ i,8]*dsdv0 + delxv_jac[ i,9]*dbetadv0
d.dxdk[i] = delxv_jac[ i,8]*dsdk + delxv_jac[ i,9]*dbetadk
d.dvdr0[i] = delxv_jac[3+i,8]*dsdr0 + delxv_jac[3+i,9]*dbetadr0
d.dvda0[i] = delxv_jac[3+i,8]*dsda0
d.dvdv0[i] = delxv_jac[3+i,8]*dsdv0 + delxv_jac[3+i,9]*dbetadv0
d.dvdk[i] = delxv_jac[3+i,8]*dsdk + delxv_jac[3+i,9]*dbetadk
end
# Now, compute Jacobian:
# Add in s & beta components of k derivative:
for i=1:3
jacobian[ i,7] += d.dxdk[i]
jacobian[3+i,7] += d.dvdk[i]
end
# Add in s & beta components of x0 & v0 derivatives:
for j=1:3
for i=1:3
if drift_first
jacobian[ i, j] += d.dxdr0[i]*(x0[j]-h*v0[j])*r0inv + d.dxda0[i]*v0[j]
jacobian[ i,3+j] += -h*d.dxdr0[i]*(x0[j]-h*v0[j])*r0inv + d.dxdv0[i]*v0[j]/absv0 + d.dxda0[i]*(x0[j]-2*h*v0[j])
jacobian[3+i, j] += d.dvdr0[i]*(x0[j]-h*v0[j])*r0inv + d.dvda0[i]*v0[j]
jacobian[3+i,3+j] += -h*d.dvdr0[i]*(x0[j]-h*v0[j])*r0inv + d.dvdv0[i]*v0[j]/absv0 + d.dvda0[i]*(x0[j]-2*h*v0[j])
else
jacobian[ i, j] += d.dxdr0[i]*x0[j]*r0inv + d.dxda0[i]*v0[j]
jacobian[ i,3+j] += d.dxdv0[i]*v0[j]/absv0 + d.dxda0[i]*x0[j]
jacobian[3+i, j] += d.dvdr0[i]*x0[j]*r0inv + d.dvda0[i]*v0[j]
jacobian[3+i,3+j] += d.dvdv0[i]*v0[j]/absv0 + d.dvda0[i]*x0[j]
end
end
end
# Mass doesn't change:
jacobian[7,7]=one(T)
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 936 | include("kepler_drift_solver.jl")
# Takes a single kepler step, with reverse drift, calling Wisdom & Hernandez solver
#
function kepler_drift_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1},drift_first::Bool) where {T <: Real}
# compute beta, r0, get x/v from state vector & call correct subroutine
x0 = zeros(eltype(state0),3)
v0 = zeros(eltype(state0),3)
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
s0=state0[11]
iter = kep_drift_ell_hyp!(x0,v0,gm,h,s0,state,drift_first)
return
end
function kepler_drift_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1},jacobian::Array{T,2},drift_first::Bool,d::Derivatives{T}) where {T <: Real}
# compute beta, r0, get x/v from state vector & call correct subroutine
x0 = zeros(eltype(state0),3)
v0 = zeros(eltype(state0),3)
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
s0=state0[11]
iter = kep_drift_ell_hyp!(x0,v0,gm,h,s0,state,jacobian,drift_first,d)
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 8228 |
function cubic1(a::T, b::T, c::T) where {T <: Real}
a3 = a*third
Q = a3^2 - b*third
R = a3^3 + 0.5*(-a3*b + c)
if R^2 < Q^3
# println("Error in cubic solver ",R^2," ",Q^3)
return -c/b
else
A = -sign(R)*cbrt(abs(R) + sqrt(R*R - Q*Q*Q))
if A == 0.0
B = 0.0
else
B = Q/A
end
x1 = A + B - a3
return x1
end
return
end
function calc_ds_opt(y::T,yp::T,ypp::T,yppp::T) where {T <: Real}
# Computes quartic Newton's update to equation y=0 using first through 3rd derivatives.
# Uses techniques outlined in Murray & Dermott for Kepler solver.
# Rearrange to reduce number of divisions:
num = y*yp
den1 = yp*yp-y*ypp*.5
den12 = den1*den1
den2 = yp*den12-num*.5*(ypp*den1-third*num*yppp)
return -y*den12/den2
end
function solve_kepler!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,
r0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Solves elliptic Kepler's equation for both elliptic and hyperbolic cases.
# Initial guess (if s0 = 0):
r0inv = inv(r0)
beta0inv = inv(beta0)
signb = sign(beta0)
sqb = sqrt(signb*beta0)
zeta = k-r0*beta0
#eta = dot(x0,v0)
eta = x0[1]*v0[1]+x0[2]*v0[2]+x0[3]*v0[3]
sguess = 0.0
if s0 == zero(T)
# Use cubic estimate:
if zeta != zero(T)
sguess = cubic1(3eta/zeta,6r0/zeta,-6h/zeta)
else
if eta != zero(T)
reta = r0/eta
disc = reta^2+2h/eta
if disc > zero(T)
sguess =-reta+sqrt(disc)
else
sguess = h*r0inv
end
else
sguess = h*r0inv
end
end
s = copy(sguess)
else
s = copy(s0)
end
s0 = copy(s)
y = zero(T); yp = one(T)
iter = 0
ds = Inf
KEPLER_TOL = sqrt(eps(h))
ITMAX = 20
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < ITMAX)
xx = sqb*s
if beta0 > 0
# sx = sin(xx); cx = cos(xx)
sx,cx = sincos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
sx *= sqb
# Third derivative:
yppp = zeta*cx - signb*eta*sx
# First derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = signb*zeta*beta0inv*sx + eta*cx
y = (-ypp + eta +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
# ds = calc_ds_opt(y,yp,ypp,yppp)
ds = -y/yp
s += ds
iter +=1
end
if iter == ITMAX
println("Reached max iterations in solve_kepler: h ",h," s0: ",s0," s: ",s," ds: ",ds)
end
#println("sguess: ",sguess," s: ",s," s-sguess: ",s-sguess," ds: ",ds," iter: ",iter)
# Since we updated s, need to recompute:
xx = 0.5*sqb*s
if beta0 > 0
# sx = sin(xx); cx = cos(xx)
sx,cx = sincos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
# Now, compute final values:
g1bs = 2.0*sx*cx/sqb
g2bs = 2.0*signb*sx^2*beta0inv
f = one(T) - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + eta*g2bs # eqn (27)
for j=1:3
# Position is components 2-4 of state:
state[1+j] = x0[j]*f+v0[j]*g
end
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = (r0-r0*beta0*g2bs+eta*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
return s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter
end
function kep_ell_hyp!(x0::Array{T,1},v0::Array{T,1},r0::T,k::T,h::T,
beta0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
# Now, solve for s in elliptical Kepler case:
f = zero(T); g=zero(T); dfdt=zero(T); dgdt=zero(T); cx=zero(T);sx=zero(T);g1bs=zero(T);g2bs=zero(T)
s=zero(T); ds = zero(T); r = zero(T);rinv=zero(T); iter=0
if beta0 > zero(T) || beta0 < zero(T)
s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter = solve_kepler!(h,k,x0,v0,beta0,r0,
s0,state)
else
println("Not elliptic or hyperbolic ",beta0," x0 ",x0)
r= zero(T); fill!(state,zero(T)); rinv=zero(T); s=zero(T); ds=zero(T); iter = 0
end
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# recompute beta:
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
function kep_ell_hyp!(x0::Array{T,1},v0::Array{T,1},r0::T,k::T,h::T,
beta0::T,s0::T,state::Array{T,1},jacobian::Array{T,2},d::Derivatives{T}) where {T <: Real}
# Computes the Jacobian as well
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in elliptical Kepler case:
f = zero(T); g=zero(T); dfdt=zero(T); dgdt=zero(T); cx=zero(T);sx=zero(T);g1bs=zero(T);g2bs=zero(T)
s=zero(T); ds=zero(T); r = zero(T);rinv=zero(T); iter=0
if beta0 > zero(T) || beta0 < zero(T)
s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter = solve_kepler!(h,k,x0,v0,beta0,r0,
s0,state)
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v} & q0 = {x0,v0}.
fill!(jacobian,zero(T))
compute_jacobian!(h,k,x0,v0,beta0,s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r0,r,jacobian,d)
else
println("Not elliptic or hyperbolic ",beta0," x0 ",x0)
r= zero(T); fill!(state,zero(T)); rinv=zero(T); s=zero(T); ds=zero(T); iter = 0
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
function compute_jacobian!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,s::T,
f::T,g::T,dfdt::T,dgdt::T,cx::T,sx::T,g1::T,g2::T,r0::T,r::T,jacobian::Array{T,2},
d::Derivatives{T}) where {T <: Real}
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v,k} & q0 = {x0,v0,k}.
# Now, compute the Jacobian: (9/18/2017 notes)
g0 = one(T)-beta0*g2
g3 = (s-g1)/beta0
eta = dot(x0,v0) # unnecessary to divide by r0 for multiply for \dot\alpha_0
absv0 = sqrt(dot(v0,v0))
dsdbeta = (2h-r0*(s*g0+g1)+k/beta0*(s*g0-g1)-eta*s*g1)/(2beta0*r)
dsdr0 = -(2k/r0^2*dsdbeta+g1/r)
dsda0 = -g2/r
dsdv0 = -2absv0*dsdbeta
dsdk = 2/r0*dsdbeta-g3/r
dbetadr0 = -2k/r0^2
dbetadv0 = -2absv0
dbetadk = 2/r0
# "p" for partial derivative:
for i=1:3
d.pxpr0[i] = k/r0^2*g2*x0[i]+g1*v0[i]
d.pxpa0[i] = g2*v0[i]
d.pxpk[i] = -g2/r0*x0[i]
d.pxps[i] = -k/r0*g1*x0[i]+(r0*g0+eta*g1)*v0[i]
d.pxpbeta[i] = -k/(2beta0*r0)*(s*g1-2g2)*x0[i]+1/(2beta0)*(s*r0*g0-r0*g1+s*eta*g1-2*eta*g2)*v0[i]
d.prvpr0[i] = k*g1/r0^2*x0[i]+g0*v0[i]
d.prvpa0[i] = g1*v0[i]
d.prvpk[i] = -g1/r0*x0[i]
d.prvps[i] = -k*g0/r0*x0[i]+(-beta0*r0*g1+eta*g0)*v0[i]
d.prvpbeta[i] = -k/(2beta0*r0)*(s*g0-g1)*x0[i]+1/(2beta0)*(-s*r0*beta0*g1+eta*s*g0-eta*g1)*v0[i]
end
prpr0 = g0
prpa0 = g1
prpk = g2
prps = (k-beta0*r0)*g1+eta*g0
prpbeta = 1/(2beta0)*(s*(k-beta0*r0)*g1+eta*s*g0-eta*g1-2k*g2)
for i=1:3
d.dxdr0[i] = d.pxps[i]*dsdr0 + d.pxpbeta[i]*dbetadr0 + d.pxpr0[i]
d.dxda0[i] = d.pxps[i]*dsda0 + d.pxpa0[i]
d.dxdv0[i] = d.pxps[i]*dsdv0 + d.pxpbeta[i]*dbetadv0
d.dxdk[i] = d.pxps[i]*dsdk + d.pxpbeta[i]*dbetadk + d.pxpk[i]
d.drvdr0[i] = d.prvps[i]*dsdr0 + d.prvpbeta[i]*dbetadr0 + d.prvpr0[i]
d.drvda0[i] = d.prvps[i]*dsda0 + d.prvpa0[i]
d.drvdv0[i] = d.prvps[i]*dsdv0 + d.prvpbeta[i]*dbetadv0
d.drvdk[i] = d.prvps[i]*dsdk + d.prvpbeta[i]*dbetadk +d.prvpk[i]
end
drdr0 = prpr0 + prps*dsdr0 + prpbeta*dbetadr0
drda0 = prpa0 + prps*dsda0
drdv0 = prps*dsdv0 + prpbeta*dbetadv0
drdk = prpk + prps*dsdk + prpbeta*dbetadk
for i=1:3
d.vtmp[i] = dfdt*x0[i]+dgdt*v0[i]
d.dvdr0[i] = (d.drvdr0[i]-drdr0*d.vtmp[i])/r
d.dvda0[i] = (d.drvda0[i]-drda0*d.vtmp[i])/r
d.dvdv0[i] = (d.drvdv0[i]-drdv0*d.vtmp[i])/r
d.dvdk[i] = (d.drvdk[i] -drdk *d.vtmp[i])/r
end
# Now, compute Jacobian:
for i=1:3
jacobian[ i, i] = f
jacobian[ i,3+i] = g
jacobian[3+i, i] = dfdt
jacobian[3+i,3+i] = dgdt
jacobian[ i,7] = d.dxdk[i]
jacobian[3+i,7] = d.dvdk[i]
end
for j=1:3
for i=1:3
jacobian[ i, j] += d.dxdr0[i]*x0[j]/r0 + d.dxda0[i]*v0[j]
jacobian[ i,3+j] += d.dxdv0[i]*v0[j]/absv0 + d.dxda0[i]*x0[j]
jacobian[3+i, j] += d.dvdr0[i]*x0[j]/r0 + d.dvda0[i]*v0[j]
jacobian[3+i,3+j] += d.dvdv0[i]*v0[j]/absv0 + d.dvda0[i]*x0[j]
end
end
jacobian[7,7]=one(T)
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 8039 | # Wisdom & Hernandez version of Kepler solver, but with quartic convergence.
function cubic1(a::T, b::T, c::T) where {T <: Real}
a3 = a*third
Q = a3^2 - b*third
R = a3^3 + 0.5*(-a3*b + c)
if R^2 < Q^3
# println("Error in cubic solver ",R^2," ",Q^3)
return -c/b
else
A = -sign(R)*cbrt(abs(R) + sqrt(R*R - Q*Q*Q))
if A == 0.0
B = 0.0
else
B = Q/A
end
x1 = A + B - a3
return x1
end
return
end
function calc_ds_opt(y::T,yp::T,ypp::T,yppp::T) where {T <: Real}
# Computes quartic Newton's update to equation y=0 using first through 3rd derivatives.
# Uses techniques outlined in Murray & Dermott for Kepler solver.
# Rearrange to reduce number of divisions:
num = y*yp
den1 = yp*yp-y*ypp*.5
den12 = den1*den1
den2 = yp*den12-num*.5*(ypp*den1-third*num*yppp)
return -y*den12/den2
end
function solve_kepler!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,
r0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Solves elliptic Kepler's equation for both elliptic and hyperbolic cases.
# Initial guess (if s0 = 0):
r0inv = inv(r0)
beta0inv = inv(beta0)
signb = sign(beta0)
sqb = sqrt(signb*beta0)
zeta = k-r0*beta0
eta = dot(x0,v0)
sguess = 0.0
if s0 == zero(T)
# Use cubic estimate:
if zeta != zero(T)
sguess = cubic1(3eta/zeta,6r0/zeta,-6h/zeta)
else
if eta != zero(T)
reta = r0/eta
disc = reta^2+2h/eta
if disc > zero(T)
sguess =-reta+sqrt(disc)
else
sguess = h*r0inv
end
else
sguess = h*r0inv
end
end
s = copy(sguess)
else
s = copy(s0)
end
s0 = copy(s)
y = zero(T); yp = one(T)
iter = 0
ds = Inf
KEPLER_TOL = sqrt(eps(h))
ITMAX = 20
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < ITMAX)
xx = sqb*s
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
sx *= sqb
# Third derivative:
yppp = zeta*cx - signb*eta*sx
# First derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = signb*zeta*beta0inv*sx + eta*cx
y = (-ypp + eta +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
end
if iter == ITMAX
println("Reached max iterations in solve_kepler: h ",h," s0: ",s0," s: ",s," ds: ",ds)
end
#println("sguess: ",sguess," s: ",s," s-sguess: ",s-sguess," ds: ",ds," iter: ",iter)
# Since we updated s, need to recompute:
xx = 0.5*sqb*s
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
# Now, compute final values:
g1bs = 2.0*sx*cx/sqb
g2bs = 2.0*signb*sx^2*beta0inv
f = one(T) - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + eta*g2bs # eqn (27)
for j=1:3
# Position is components 2-4 of state:
state[1+j] = x0[j]*f+v0[j]*g
end
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = (r0-r0*beta0*g2bs+eta*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
return s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter
end
function kep_ell_hyp!(x0::Array{T,1},v0::Array{T,1},r0::T,k::T,h::T,
beta0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
# Now, solve for s in elliptical Kepler case:
f = zero(T); g=zero(T); dfdt=zero(T); dgdt=zero(T); cx=zero(T);sx=zero(T);g1bs=zero(T);g2bs=zero(T)
s=zero(T); ds = zero(T); r = zero(T);rinv=zero(T); iter=0
if beta0 > zero(T) || beta0 < zero(T)
s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter = solve_kepler!(h,k,x0,v0,beta0,r0,
s0,state)
else
println("Not elliptic or hyperbolic ",beta0," x0 ",x0)
r= zero(T); fill!(state,zero(T)); rinv=zero(T); s=zero(T); ds=zero(T); iter = 0
end
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# recompute beta:
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
function kep_ell_hyp!(x0::Array{T,1},v0::Array{T,1},r0::T,k::T,h::T,
beta0::T,s0::T,state::Array{T,1},jacobian::Array{T,2}) where {T <: Real}
# Computes the Jacobian as well
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in elliptical Kepler case:
f = zero(T); g=zero(T); dfdt=zero(T); dgdt=zero(T); cx=zero(T);sx=zero(T);g1bs=zero(T);g2bs=zero(T)
s=zero(T); ds=zero(T); r = zero(T);rinv=zero(T); iter=0
if beta0 > zero(T) || beta0 < zero(T)
s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter = solve_kepler!(h,k,x0,v0,beta0,r0,
s0,state)
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v} & q0 = {x0,v0}.
fill!(jacobian,zero(T))
compute_jacobian!(h,k,x0,v0,beta0,s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r0,r,jacobian)
else
println("Not elliptic or hyperbolic ",beta0," x0 ",x0)
r= zero(T); fill!(state,zero(T)); rinv=zero(T); s=zero(T); ds=zero(T); iter = 0
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
function compute_jacobian!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,s::T,
f::T,g::T,dfdt::T,dgdt::T,cx::T,sx::T,g1::T,g2::T,r0::T,r::T,jacobian::Array{T,2}) where {T <: Real}
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v,k} & q0 = {x0,v0,k}.
# Now, compute the Jacobian: (9/18/2017 notes)
g0 = one(T)-beta0*g2
g3 = (s-g1)/beta0
eta = dot(x0,v0) # unnecessary to divide by r0 for multiply for \dot\alpha_0
absv0 = sqrt(dot(v0,v0))
dsdbeta = (2h-r0*(s*g0+g1)+k/beta0*(s*g0-g1)-eta*s*g1)/(2beta0*r)
dsdr0 = -(2k/r0^2*dsdbeta+g1/r)
dsda0 = -g2/r
dsdv0 = -2absv0*dsdbeta
dsdk = 2/r0*dsdbeta-g3/r
dbetadr0 = -2k/r0^2
dbetadv0 = -2absv0
dbetadk = 2/r0
# "p" for partial derivative:
for i=1:3
pxpr0[i] = k/r0^2*g2*x0[i]+g1*v0[i]
pxpa0[i] = g2*v0[i]
pxpk[i] = -g2/r0*x0[i]
pxps[i] = -k/r0*g1*x0[i]+(r0*g0+eta*g1)*v0[i]
pxpbeta[i] = -k/(2beta0*r0)*(s*g1-2g2)*x0[i]+1/(2beta0)*(s*r0*g0-r0*g1+s*eta*g1-2*eta*g2)*v0[i]
prvpr0[i] = k*g1/r0^2*x0[i]+g0*v0[i]
prvpa0[i] = g1*v0[i]
prvpk[i] = -g1/r0*x0[i]
prvps[i] = -k*g0/r0*x0[i]+(-beta0*r0*g1+eta*g0)*v0[i]
prvpbeta[i] = -k/(2beta0*r0)*(s*g0-g1)*x0[i]+1/(2beta0)*(-s*r0*beta0*g1+eta*s*g0-eta*g1)*v0[i]
end
prpr0 = g0
prpa0 = g1
prpk = g2
prps = (k-beta0*r0)*g1+eta*g0
prpbeta = 1/(2beta0)*(s*(k-beta0*r0)*g1+eta*s*g0-eta*g1-2k*g2)
for i=1:3
dxdr0[i] = pxps[i]*dsdr0 + pxpbeta[i]*dbetadr0 + pxpr0[i]
dxda0[i] = pxps[i]*dsda0 + pxpa0[i]
dxdv0[i] = pxps[i]*dsdv0 + pxpbeta[i]*dbetadv0
dxdk[i] = pxps[i]*dsdk + pxpbeta[i]*dbetadk + pxpk[i]
drvdr0[i] = prvps[i]*dsdr0 + prvpbeta[i]*dbetadr0 + prvpr0[i]
drvda0[i] = prvps[i]*dsda0 + prvpa0[i]
drvdv0[i] = prvps[i]*dsdv0 + prvpbeta[i]*dbetadv0
drvdk[i] = prvps[i]*dsdk + prvpbeta[i]*dbetadk +prvpk[i]
end
drdr0 = prpr0 + prps*dsdr0 + prpbeta*dbetadr0
drda0 = prpa0 + prps*dsda0
drdv0 = prps*dsdv0 + prpbeta*dbetadv0
drdk = prpk + prps*dsdk + prpbeta*dbetadk
for i=1:3
vtmp[i] = dfdt*x0[i]+dgdt*v0[i]
dvdr0[i] = (drvdr0[i]-drdr0*vtmp[i])/r
dvda0[i] = (drvda0[i]-drda0*vtmp[i])/r
dvdv0[i] = (drvdv0[i]-drdv0*vtmp[i])/r
dvdk[i] = (drvdk[i] -drdk *vtmp[i])/r
end
# Now, compute Jacobian:
for i=1:3
jacobian[ i, i] = f
jacobian[ i,3+i] = g
jacobian[3+i, i] = dfdt
jacobian[3+i,3+i] = dgdt
jacobian[ i,7] = dxdk[i]
jacobian[3+i,7] = dvdk[i]
end
for j=1:3
for i=1:3
jacobian[ i, j] += dxdr0[i]*x0[j]/r0 + dxda0[i]*v0[j]
jacobian[ i,3+j] += dxdv0[i]*v0[j]/absv0 + dxda0[i]*x0[j]
jacobian[3+i, j] += dvdr0[i]*x0[j]/r0 + dvda0[i]*v0[j]
jacobian[3+i,3+j] += dvdv0[i]*v0[j]/absv0 + dvda0[i]*x0[j]
end
end
jacobian[7,7]=one(T)
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 2538 | include("kepler_solver_derivative.jl")
# Takes a single kepler step, calling Wisdom & Hernandez solver
#
#function kepler_step!(gm::Float64,h::Float64,state0::Array{Float64,1},state::Array{Float64,1})
function kepler_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1}) where {T <: Real}
# compute beta, r0, get x/v from state vector & call correct subroutine
x0 = zeros(eltype(state0),3)
v0 = zeros(eltype(state0),3)
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
# x0=state0[2:4]
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
# v0 = state0[5:7]
beta0 = 2*gm/r0-(v0[1]*v0[1]+v0[2]*v0[2]+v0[3]*v0[3])
s0=state0[11]
iter = kep_ell_hyp!(x0,v0,r0,gm,h,beta0,s0,state)
# if beta0 > zero
# iter = kep_elliptic!(x0,v0,r0,gm,h,beta0,s0,state)
# else
# iter = kep_hyperbolic!(x0,v0,r0,gm,h,beta0,s0,state)
# end
return
end
# Takes a single kepler step, calling Wisdom & Hernandez solver
#
#function kepler_step!(gm::Float64,h::Float64,state0::Array{Float64,1},state::Array{Float64,1})
function kepler_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1},x0::Array{T,1},v0::Array{T,1}) where {T <: Real}
# compute beta, r0, get x/v from state vector & call correct subroutine
#x0 = zeros(eltype(state0),3)
#v0 = zeros(eltype(state0),3)
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
# x0=state0[2:4]
# r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
r0 = norm(x0)
# v0 = state0[5:7]
beta0 = 2*gm/r0-(v0[1]*v0[1]+v0[2]*v0[2]+v0[3]*v0[3])
s0=state0[11]
iter = kep_ell_hyp!(x0,v0,r0,gm,h,beta0,s0,state)
# if beta0 > zero
# iter = kep_elliptic!(x0,v0,r0,gm,h,beta0,s0,state)
# else
# iter = kep_hyperbolic!(x0,v0,r0,gm,h,beta0,s0,state)
# end
return
end
#function kepler_step!(gm::Float64,h::Float64,state0::Array{Float64,1},state::Array{Float64,1},jacobian::Array{Float64,2})
function kepler_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1},jacobian::Array{T,2},d::Derivatives{T}) where {T <: Real}
# compute beta, r0, get x/v from state vector & call correct subroutine
x0 = zeros(eltype(state0),3)
v0 = zeros(eltype(state0),3)
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
# x0=state0[2:4]
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
# v0 = state0[5:7]
beta0 = 2*gm/r0-(v0[1]*v0[1]+v0[2]*v0[2]+v0[3]*v0[3])
s0=state0[11]
iter = kep_ell_hyp!(x0,v0,r0,gm,h,beta0,s0,state,jacobian,d)
# if beta0 > zero
# iter = kep_elliptic!(x0,v0,r0,gm,h,beta0,s0,state,jacobian)
# else
# iter = kep_hyperbolic!(x0,v0,r0,gm,h,beta0,s0,state,jacobian)
# end
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 3277 | include("/Users/ericagol/Computer/Julia/regress.jl")
n = 8
include("ttv.jl")
t0 = 7257.93115525
#h = 0.12
h = 0.05
#h = 0.025
tmax = 600.0
#tmax = 80.0
# Read in initial conditions:
elements = readdlm("../test/elements.txt",',')
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
ntt = zeros(Int64,n)
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
println("ntt: ",ntt)
tt = zeros(n,maximum(ntt))
tt1 = zeros(n,maximum(ntt))
tt2 = zeros(n,maximum(ntt))
tt3 = zeros(n,maximum(ntt))
tt4 = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
count1 = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
dq = ttv_elements!(n,t0,h,tmax,elements,tt1,count1,0.0,0,0,rstar)
@time dq = ttv_elements!(n,t0,h,tmax,elements,tt1,count1,0.0,0,0,rstar)
# Now, try calling with kicks between planets rather than -drift+Kepler:
pair_input = ones(Bool,n,n)
# We want Keplerian between star & planets, and impulses between
# planets. Impulse is indicated with 'true', -drift+Kepler with 'false':
for i=2:n
pair_input[1,i] = false
# We don't need to define this, but let's anyways:
pair_input[i,1] = false
end
# Now, only include Kepler solver for adjacent planets:
for i=2:n-1
pair_input[i,i+1] = false
pair_input[i+1,i] = false
end
# Now call with smaller timestep:
count2 = zeros(Int64,n)
count3 = zeros(Int64,n)
dq = ttv_elements!(n,t0,h/4.,tmax,elements,tt2,count2,0.0,0,0,rstar)
for i=2:n
println("Timing error -drift+Kepler: ",i-1," ",maximum(abs.(tt2[i,:]-tt1[i,:]))*24.*3600.)
end
@time dq = ttv_elements!(n,t0,h,tmax,elements,tt3,count1,0.0,0,0,rstar;pair=pair_input)
dq = ttv_elements!(n,t0,h/4.,tmax,elements,tt4,count2,0.0,0,0,rstar;pair=pair_input)
for i=2:n
println("Timing error kickfast: ",i-1," ",maximum(abs.(tt3[i,:]-tt4[i,:]))*24.*3600.)
end
for i=2:n
println("Timing kickfast-(-drift+Kepler): ",i-1," ",maximum(abs.(tt1[i,:]-tt3[i,:]))*24.*3600.)
end
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdq1 = zeros(n,maximum(ntt),7,n)
dtdq2 = zeros(n,maximum(ntt),7,n)
dtdq_kick1 = zeros(n,maximum(ntt),7,n)
dtdq_kick2 = zeros(n,maximum(ntt),7,n)
dtdelements1 = zeros(n,maximum(ntt),7,n)
dtdelements2 = zeros(n,maximum(ntt),7,n)
dtdelements_kick1 = zeros(n,maximum(ntt),7,n)
dtdelements_kick2 = zeros(n,maximum(ntt),7,n)
dtdelements1 = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq1,rstar)
@time dtdelements1 = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq1,rstar)
dtdelements2 = ttv_elements!(n,t0,h/2,tmax,elements,tt,count,dtdq2,rstar)
@time dtdelements_kick1 = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq_kick1,rstar;pair=pair_input)
@time dtdelements_kick2 = ttv_elements!(n,t0,h/2,tmax,elements,tt,count,dtdq_kick2,rstar;pair=pair_input)
println(maximum(abs.(asinh.(dtdelements1)-asinh.(dtdelements2))))
println(maximum(abs.(asinh.(dtdelements_kick1)-asinh.(dtdelements_kick2))))
println(maximum(abs.(asinh.(dtdelements2)-asinh.(dtdelements_kick2))))
Profile.clear()
Profile.init(10^7,0.01)
#@profile dtdelements0 = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq0,rstar);
@profile dtdelements0 = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq1,rstar);
Profile.print()
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 2200 | # Reads in the string that describes the hierarchy,
# and sets up A matrix and masses for each Keplerian.
# There are N bodies, and N-1 Keplerians.
function get_indices(string)
# Takes a Kepler hierarchy vector, and returns indices of all planets
ind1 = readdlm(IOBuffer(hierarchy[1:i]))
# Converts strings to integers
nm = size(string)
for j=1:nm
replace(string[j],"(","")
replace(string[j],")","")
end
indices = zeros(Int64,nm)
for j=1:nm
indice[j]=parse(string[j])
end
return indices
end
function split_kepler(hierarchy,mass)
# Splits the hierarchy into components
ndelim = count(c -> c == ',' , hierarchy)
if ndelim > 1
# Find first complete Keplerian:
i = 1
nleft = 0
nright = 0
c = collect(hierarchy)
nchar = endof(hierarchy)
while (nleft == 0) || (nleft != nright) || i == nchar
if c[i] == '('
nleft += 1
end
if c[i] == ')'
nright += 1
end
if c[i] == ','
ndelim += 1
end
end
@assert(nleft == nright)
@assert(nleft == ndelim)
# Compute sum of masses of both Kepler components:
# First find the indices of planets:
ind1 = get_indices(hierarchy[1:i])
ind2 = get_indices(hierarchy[i+1:nchar])
m1 = sum(mss[ind1])
m2 = sum(mss[ind2])
return m1,m2,hierarchy[1:i],hierarchy[i+1:nchar]
elseif ndelim == 1
# Found a Keplerian of two bodies
ind = get_indices(hierarchy)
return mass[ind[1]],mass[ind[2]],split(hierarchy,",")
else
# Down to a single body
ind = get_indices(hierarchy)
return mass[ind[1]],0.0,hierarchy,""
end
end
function strip_parentheses(hierarchy)
# Strips the leading and trailing parentheses (if they exist):
nchar = endof(hierarchy)
if hierarchy[1] == '(' && hierarchy[nchar] == ')'
return hierarchy[2:nchar-1]
else
return hierarchy
end
end
nleft = count(c -> c == '(',hierarchy)
nright = count(c -> c == ')',hierarchy)
@assert(nleft == nright)
return
end
function setup_hierarchy(hierarchy,nbody,mass)
# Creates a routine which computes the matrix
# and total masses in each Keplerian.
nleft = count(c -> c == '(',hierarchy)
nright = count(c -> c == ')',hierarchy)
ndelim = count(c -> c == ',',hierarchy)
@assert(nleft == nright)
@assert(nleft == ndelim)
return A,mtot
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 136973 |
# Translation of David Hernandez's nbody.c for integrating hiercharical
# system with BH15 integrator. Please cite Hernandez & Bertschinger (2015)
# if using this in a paper.
if ~@isdefined YEAR
const YEAR = 365.242
const GNEWT = 39.4845/YEAR^2
const NDIM = 3
#const TRANSIT_TOL = 1e-8
# const TRANSIT_TOL = 10.0*sqrt(eps(1.0))
#const TRANSIT_TOL = 10.0*eps(1.0)
const third = 1.0/3.0
const alpha0 = 0.0
end
include("PreAllocArrays.jl")
include("kepler_step.jl")
include("kepler_drift_step.jl")
include("kepler_drift_gamma.jl")
include("init_nbody.jl")
using LinearAlgebra
function comp_sum(sum_value::T,sum_error::T,addend::T) where {T <: Real}
# Function for compensated summation using the Kahan (1965) algorithm.
# sum_value: current value of the sum
# sum_error: truncation/rounding error accumulated from prior steps in sum
# addend: new value to be added to the sum
sum_error += addend
tmp = sum_value + sum_error
sum_error = (sum_value - tmp) + sum_error
sum_value = tmp
return sum_value::T,sum_error::T
end
function comp_sum_matrix!(sum_value::Array{T,2},sum_error::Array{T,2},addend::Array{T,2}) where {T <: Real}
# Function for compensated summation using the Kahan (1965) algorithm.
# sum_value: current value of the sum
# sum_error: truncation/rounding error accumulated from prior steps in sum
# addend: new value to be added to the sum
@inbounds for i in eachindex(sum_value)
sum_error[i] += addend[i]
tmp = sum_value[i] + sum_error[i]
sum_error[i] = (sum_value[i] - tmp) + sum_error[i]
sum_value[i] = tmp
end
return
end
#= These "constants" pre-allocate memory for matrices used in the derivative computation (to save time with allocation and garbage collection):
if ~@isdefined pxpr0
const pxpr0 = zeros(Float64,3);const pxpa0=zeros(Float64,3);const pxpk=zeros(Float64,3);const pxps=zeros(Float64,3);const pxpbeta=zeros(Float64,3)
const dxdr0 = zeros(Float64,3);const dxda0=zeros(Float64,3);const dxdk=zeros(Float64,3);const dxdv0 =zeros(Float64,3)
const prvpr0 = zeros(Float64,3);const prvpa0=zeros(Float64,3);const prvpk=zeros(Float64,3);const prvps=zeros(Float64,3);const prvpbeta=zeros(Float64,3)
const drvdr0 = zeros(Float64,3);const drvda0=zeros(Float64,3);const drvdk=zeros(Float64,3);const drvdv0=zeros(Float64,3)
const vtmp = zeros(Float64,3);const dvdr0 = zeros(Float64,3);const dvda0=zeros(Float64,3);const dvdv0=zeros(Float64,3);const dvdk=zeros(Float64,3)
end
=#
# Computes TTVs as a function of orbital elements, allowing for a single log perturbation of dlnq for body jq and element iq
function ttv_elements!(H::Union{Int64,Array{Int64,1}},t0::T,h::T,tmax::T,elements::Array{T,2},tt::Array{T,2},count::Array{Int64,1},dlnq::T,iq::Int64,jq::Int64,rstar::T;fout="",iout=-1,pair = zeros(Bool,H[1],H[1])) where {T <: Real}
#
# Input quantities:
# n = number of bodies
# t0 = initial time of integration [days]
# h = time step [days]
# tmax = duration of integration [days]
# elements[i,j] = 2D n x 7 array of the masses & orbital elements of the bodies (currently first body's orbital elements are ignored)
# elements are ordered as: mass, period, t0, e*cos(omega), e*sin(omega), inclination, longitude of ascending node (Omega)
# tt = pre-allocated array to hold transit times of size [n x max(ntt)] (currently only compute transits of star, so first row is zero) [days]
# upon output, set to transit times of planets.
# count = pre-allocated array of the number of transits for each body upon output
#
# dlnq = fractional variation in initial parameter jq of body iq for finite-difference calculation of
# derivatives [this is only needed for testing derivative code, below].
#
# Example: see test_ttv_elements.jl in test/ directory
#
#fcons = open("fcons.txt","w");
# Set up mass, position & velocity arrays. NDIM =3
n = H[1]
m=zeros(T,n)
x=zeros(T,NDIM,n)
v=zeros(T,NDIM,n)
# Fill the transit-timing array with zeros:
fill!(tt,0.0)
# Counter for transits of each planet:
fill!(count,0)
# Insert masses from the elements array:
for i=1:n
m[i] = elements[i,1]
end
# Allow for perturbations to initial conditions: jq labels body; iq labels phase-space element (or mass)
# iq labels phase-space element (1-3: x; 4-6: v; 7: m)
dq = zero(T)
if iq == 7 && dlnq != 0.0
dq = m[jq]*dlnq
m[jq] += dq
end
# Initialize the N-body problem using nested hierarchy of Keplerians:
init = ElementsIC(elements,H,t0)
x,v,_ = init_nbody(init)
elements_big=big.(elements); t0big = big(t0)
init_big = ElementsIC(elements_big,H,t0big)
xbig,vbig,_ = init_nbody(init_big)
#if T != BigFloat
# println("Difference in x,v init: ",x-convert(Array{T,2},xbig)," ",v-convert(Array{T,2},vbig)," (dlnq version)")
#end
x = convert(Array{T,2},xbig); v = convert(Array{T,2},vbig)
# Perturb the initial condition by an amount dlnq (if it is non-zero):
if dlnq != 0.0 && iq > 0 && iq < 7
if iq < 4
if x[iq,jq] != 0
dq = x[iq,jq]*dlnq
else
dq = dlnq
end
x[iq,jq] += dq
else
# Same for v
if v[iq-3,jq] != 0
dq = v[iq-3,jq]*dlnq
else
dq = dlnq
end
v[iq-3,jq] += dq
end
end
ttv!(n,t0,h,tmax,m,x,v,tt,count,fout,iout,rstar,pair)
return dq
end
# Computes TTVs, v_sky & b_sky^2 as a function of orbital elements, allowing for a single log perturbation of dlnq for body jq and element iq
function ttvbv_elements!(H::Union{Int64,Array{Int64,1}},t0::T,h::T,tmax::T,elements::Array{T,2},ttbv::Array{T,3},count::Array{Int64,1},dlnq::T,iq::Int64,jq::Int64,rstar::T;fout="",iout=-1,pair = zeros(Bool,H[1],H[1])) where {T <: Real}
#
# Input quantities:
# n = number of bodies
# t0 = initial time of integration [days]
# h = time step [days]
# tmax = duration of integration [days]
# elements[i,j] = 2D n x 7 array of the masses & orbital elements of the bodies (currently first body's orbital elements are ignored)
# elements are ordered as: mass, period, t0, e*cos(omega), e*sin(omega), inclination, longitude of ascending node (Omega)
# ttbv = pre-allocated array to hold transit times (& v_sky/b_sky^2) of size [1-3] x [n x max(ntt)] (currently only compute transits of star, so first row is zero) [days]
# upon output, set to transit times (& v_sky/b_sky^2) of planets.
# count = pre-allocated array of the number of transits for each body upon output
#
# dlnq = fractional variation in initial parameter jq of body iq for finite-difference calculation of
# derivatives [this is only needed for testing derivative code, below].
#
# Example: see test_ttvbv_elements.jl in test/ directory
#
#fcons = open("fcons.txt","w");
# Set up mass, position & velocity arrays. NDIM =3
H = [3,1,1]
n = H[1]
m=zeros(T,n)
x=zeros(T,NDIM,n)
v=zeros(T,NDIM,n)
# Fill the transit-timing array with zeros:
fill!(ttbv,0.0)
# Counter for transits of each planet:
fill!(count,0)
# Insert masses from the elements array:
for i=1:n
m[i] = elements[i,1]
end
# Allow for perturbations to initial conditions: jq labels body; iq labels phase-space element (or mass)
# iq labels phase-space element (1-3: x; 4-6: v; 7: m)
dq = zero(T)
if iq == 7 && dlnq != 0.0
dq = m[jq]*dlnq
m[jq] += dq
end
# Initialize the N-body problem using nested hierarchy of Keplerians:
init = ElementsIC(elements,H,t0)
x,v,_ = init_nbody(init)
elements_big=big.(elements); t0big = big(t0)
init_big = ElementsIC(elements_big,H,t0big)
xbig,vbig,_ = init_nbody(init_big)
#if T != BigFloat
# println("Difference in x,v init: ",x-convert(Array{T,2},xbig)," ",v-convert(Array{T,2},vbig)," (dlnq version)")
#end
x = convert(Array{T,2},xbig); v = convert(Array{T,2},vbig)
# Perturb the initial condition by an amount dlnq (if it is non-zero):
if dlnq != 0.0 && iq > 0 && iq < 7
if iq < 4
if x[iq,jq] != 0
dq = x[iq,jq]*dlnq
else
dq = dlnq
end
x[iq,jq] += dq
else
# Same for v
if v[iq-3,jq] != 0
dq = v[iq-3,jq]*dlnq
else
dq = dlnq
end
v[iq-3,jq] += dq
end
end
ttvbv!(n,t0,h,tmax,m,x,v,ttbv,count,fout,iout,rstar,pair)
return dq
end
# Computes TTVs as a function of orbital elements, and computes Jacobian of transit times with respect to initial orbital elements.
# This version is used to test/debug findtransit2 by computing finite difference derivative of findtransit2.
function ttv_elements!(H::Union{Int64,Array{Int64,1}},t0::Float64,h::Float64,tmax::Float64,elements::Array{Float64,2},tt::Array{Float64,2},count::Array{Int64,1},dtdq0::Array{Float64,4},dtdq0_num::Array{BigFloat,4},dlnq::BigFloat,rstar::Float64;pair=zeros(Bool,H[1],H[1]))
#
# Input quantities:
# n = number of bodies
# t0 = initial time of integration [days]
# h = time step [days]
# tmax = duration of integration [days]
# elements[i,j] = 2D n x 7 array of the masses & orbital elements of the bodies (currently first body's orbital elements are ignored)
# elements are ordered as: mass, period, t0, e*cos(omega), e*sin(omega), inclination, longitude of ascending node (Omega)
# tt = array of transit times of size [n x max(ntt)] (currently only compute transits of star, so first row is zero) [days]
# count = array of the number of transits for each body
# dtdq0 = derivative of transit times with respect to initial x,v,m [various units: day/length (3), day^2/length (3), day/mass]
# 4D array [n x max(ntt) ] x [n x 7] - derivatives of transits of each planet with respect to initial positions/velocities
# masses of *all* bodies. Note: mass derivatives are *after* positions/velocities, even though they are at start
# of the elements[i,j] array.
#
# Output quantity:
# dtdelements = 4D array [n x max(ntt) ] x [n x 7] - derivatives of transits of each planet with respect to initial orbital
# elements/masses of *all* bodies. Note: mass derivatives are *after* elements, even though they are at start
# of the elements[i,j] array
#
# Example: see test_ttv_elements.jl in test/ directory
#
# Define initial mass, position & velocity arrays:
n = H[1]
m=zeros(Float64,n)
x=zeros(Float64,NDIM,n)
v=zeros(Float64,NDIM,n)
# Fill the transit-timing & jacobian arrays with zeros:
fill!(tt,0.0)
fill!(dtdq0,0.0)
fill!(dtdq0_num,0.0)
# Create an array for the derivatives with respect to the masses/orbital elements:
dtdelements = copy(dtdq0)
# Counter for transits of each planet:
fill!(count,0)
for i=1:n
m[i] = elements[i,1]
end
# Initialize the N-body problem using nested hierarchy of Keplerians:
#jac_init = zeros(Float64,7*n,7*n)
init = ElementsIC(elements,H,t0)
x,v,jac_init = init_nbody(init)
elements_big=big.(elements); t0big = big(t0); #jac_init_big = zeros(BigFloat,7*n,7*n)
init_big = ElementsIC(elements_big,H,t0big)
xbig,vbig,jac_init_big = init_nbody(init_big)
println("Difference in x,v init: ",x-convert(Array{Float64,2},xbig)," ",v-convert(Array{Float64,2},vbig)," (transit derivative version)")
# x = convert(Array{Float64,2},xbig); v = convert(Array{Float64,2},vbig); jac_init=convert(Array{Float64,2},jac_init_big)
#x,v = init_nbody(elements,t0,n)
ttv!(n,t0,h,tmax,m,x,v,tt,count,dtdq0,dtdq0_num,dlnq,rstar,pair)
# Need to apply initial jacobian TBD - convert from
# derivatives with respect to (x,v,m) to (elements,m):
ntt_max = size(tt)[2]
@inbounds for i=1:n, j=1:count[i]
if j <= ntt_max
# Now, multiply by the initial Jacobian to convert time derivatives to orbital elements:
@inbounds for k=1:n, l=1:7
dtdelements[i,j,l,k] = 0.0
@inbounds for p=1:n, q=1:7
dtdelements[i,j,l,k] += dtdq0[i,j,q,p]*jac_init[(p-1)*7+q,(k-1)*7+l]
end
end
end
end
return dtdelements
end
# Computes TTVs as a function of orbital elements, and computes Jacobian of transit times with respect to initial orbital elements.
# This version is used to test/debug findtransit2 by computing finite difference derivative of findtransit2.
function ttvbv_elements!(H::Union{Int64,Array{Int64,1}},t0::Float64,h::Float64,tmax::Float64,elements::Array{Float64,2},ttbv::Array{Float64,3},
count::Array{Int64,1},dtbvdq0::Array{Float64,5},dtbvdq0_num::Array{BigFloat,5},dlnq::BigFloat,rstar::Float64;pair=zeros(Bool,H[1],H[1]))
#
# Input quantities:
# n = number of bodies
# t0 = initial time of integration [days]
# h = time step [days]
# tmax = duration of integration [days]
# elements[i,j] = 2D n x 7 array of the masses & orbital elements of the bodies (currently first body's orbital elements are ignored)
# elements are ordered as: mass, period, t0, e*cos(omega), e*sin(omega), inclination, longitude of ascending node (Omega)
# ttbv = array of transit times of size 3 x [n x max(ntt)] (currently only compute transits of star, so first row is zero) [days]
# count = array of the number of transits for each body
# dtbvdq0 = derivative of transit times, impact parameters, and sky velocities with respect to initial x,v,m [various units: day/length (3), day^2/length (3), day/mass]
# 5D array [1-3] x [n x max(ntt) ] x [n x 7] - derivatives of transits times (and v_sky/b_sky^2) of each planet with respect to initial positions/velocities
# masses of *all* bodies. Note: mass derivatives are *after* positions/velocities, even though they are at start
# of the elements[i,j] array.
# Output quantity:
# dtbvdelements = 5D array [1-3]x[n x max(ntt) ] x [n x 7] - derivatives of transits, impact parameters, and sky velocities of each planet
# with respect to initial orbital elements/masses of *all* bodies. Note: mass derivatives are *after* elements, even
# though they are at start of the elements[i,j] array
#
# Example: see test_ttvbv_elements.jl in test/ directory
#
# Define initial mass, position & velocity arrays:
n = H[1]
m=zeros(Float64,n)
x=zeros(Float64,NDIM,n)
v=zeros(Float64,NDIM,n)
# Fill the transit-timing & jacobian arrays with zeros:
fill!(ttbv,0.0)
fill!(dtbvdq0,0.0)
fill!(dtbvdq0_num,0.0)
# Create an array for the derivatives with respect to the masses/orbital elements:
dtbvdelements = copy(dtbvdq0)
# Counter for transits of each planet:
fill!(count,0)
for i=1:n
m[i] = elements[i,1]
end
# Initialize the N-body problem using nested hierarchy of Keplerians:
#jac_init = zeros(Float64,7*n,7*n)
init = ElementsIC(elements,H,t0)
x,v,jac_init = init_nbody(init)
elements_big=big.(elements); t0big = big(t0); #jac_init_big = zeros(BigFloat,7*n,7*n)
init_big = ElementsIC(elements_big,H,t0big)
xbig,vbig,jac_init_big = init_nbody(init)
println("Difference in x,v init: ",x-convert(Array{Float64,2},xbig)," ",v-convert(Array{Float64,2},vbig)," (transit derivative version)")
# x = convert(Array{Float64,2},xbig); v = convert(Array{Float64,2},vbig); jac_init=convert(Array{Float64,2},jac_init_big)
#x,v = init_nbody(elements,t0,n)
ttvbv!(n,t0,h,tmax,m,x,v,ttbv,count,dtbvdq0,dtbvdq0_num,dlnq,rstar,pair)
# Need to apply initial jacobian TBD - convert from
# derivatives with respect to (x,v,m) to (elements,m):
ntt_max = size(ttbv)[3]
ntbv = size(ttbv)[1] # = 1 for just times; = 3 for times + v_sky + b_sky^2
@inbounds for itbv=1:ntbv, i=1:n, j=1:count[i]
if j <= ntt_max
# Now, multiply by the initial Jacobian to convert time derivatives to orbital elements:
@inbounds for k=1:n, l=1:7
dtbvdelements[itbv,i,j,l,k] = 0.0
@inbounds for p=1:n, q=1:7
dtbvdelements[itbv,i,j,l,k] += dtbvdq0[itbv,i,j,q,p]*jac_init[(p-1)*7+q,(k-1)*7+l]
end
end
end
end
return dtbvdelements
end
function ttv_elements!(H::Union{Int64,Array{Int64,1}},t0::T,h::T,tmax::T,elements::Array{T,2},tt::Array{T,2},count::Array{Int64,1},dtdq0::Array{T,4},rstar::T;fout="",iout=-1,pair=zeros(Bool,H[1],H[1])) where {T <: Real}
#
# Input quantities:
# n = number of bodies
# t0 = initial time of integration [days]
# h = time step [days]
# tmax = duration of integration [days]
# elements[i,j] = 2D n x 7 array of the masses & orbital elements of the bodies (currently first body's orbital elements are ignored)
# elements are ordered as: mass, period, t0, e*cos(omega), e*sin(omega), inclination, longitude of ascending node (Omega)
# tt = array of transit times of size [n x max(ntt)] (currently only compute transits of star, so first row is zero) [days]
# count = array of the number of transits for each body
# dtdq0 = derivative of transit times with respect to initial x,v,m [various units: day/length (3), day^2/length (3), day/mass]
# 4D array [n x max(ntt) ] x [n x 7] - derivatives of transits of each planet with respect to initial positions/velocities
# masses of *all* bodies. Note: mass derivatives are *after* positions/velocities, even though they are at start
# of the elements[i,j] array.
#
# Output quantity:
# dtdelements = 4D array [n x max(ntt) ] x [n x 7] - derivatives of transits of each planet with respect to initial orbital
# elements/masses of *all* bodies. Note: mass derivatives are *after* elements, even though they are at start
# of the elements[i,j] array
#
# Example: see test_ttv_elements.jl in test/ directory
#
# Define initial mass, position & velocity arrays:
n = H[1]
m=zeros(T,n)
x=zeros(T,NDIM,n)
v=zeros(T,NDIM,n)
# Fill the transit-timing & jacobian arrays with zeros:
fill!(tt,zero(T))
fill!(dtdq0,zero(T))
# Create an array for the derivatives with respect to the masses/orbital elements:
dtdelements = copy(dtdq0)
# Counter for transits of each planet:
fill!(count,0)
for i=1:n
m[i] = elements[i,1]
end
# Initialize the N-body problem using nested hierarchy of Keplerians:
#jac_init = zeros(T,7*n,7*n)
init = ElementsIC(elements,H,t0)
x,v,jac_init = init_nbody(init)
elements_big=big.(elements); t0big = big(t0); #jac_init_big = zeros(BigFloat,7*n,7*n)
init_big = ElementsIC(elements_big,H,t0big)
xbig,vbig,jac_init_big = init_nbody(init_big)
#if T != BigFloat
# println("Difference in x,v init: ",x-convert(Array{T,2},xbig)," ",v-convert(Array{T,2},vbig)," (Jacobian version)")
# println("Difference in Jacobian: ",jac_init-convert(Array{T,2},jac_init_big)," (Jacobian version)")
#end
x = convert(Array{T,2},xbig); v = convert(Array{T,2},vbig); jac_init=convert(Array{T,2},jac_init_big)
#x,v = init_nbody(elements,t0,n)
ttv!(n,t0,h,tmax,m,x,v,tt,count,dtdq0,rstar,pair;fout=fout,iout=iout)
# Need to apply initial jacobian TBD - convert from
# derivatives with respect to (x,v,m) to (elements,m):
ntt_max = size(tt)[2]
for i=1:n, j=1:count[i]
if j <= ntt_max
# Now, multiply by the initial Jacobian to convert time derivatives to orbital elements:
for k=1:n, l=1:7
dtdelements[i,j,l,k] = zero(T)
for p=1:n, q=1:7
dtdelements[i,j,l,k] += dtdq0[i,j,q,p]*jac_init[(p-1)*7+q,(k-1)*7+l]
end
end
end
end
return dtdelements
end
# Computes TTVs as a function of orbital elements, and computes Jacobian of transit times with respect to initial orbital elements.
function ttvbv_elements!(H::Union{Int64,Array{Int64,1}},t0::T,h::T,tmax::T,elements::Array{T,2},ttbv::Array{T,3},
count::Array{Int64,1},dtbvdq0::Array{T,5},rstar::T;fout="",iout=-1,pair=zeros(Bool,H[1],H[1])) where {T <: Real}
#
# Input quantities:
# n = number of bodies
# t0 = initial time of integration [days]
# h = time step [days]
# tmax = duration of integration [days]
# elements[i,j] = 2D n x 7 array of the masses & orbital elements of the bodies (currently first body's orbital elements are ignored)
# elements are ordered as: mass, period, t0, e*cos(omega), e*sin(omega), inclination, longitude of ascending node (Omega)
# ttbv = array of transit times, impact parameter & sky velocity of size [1-3] x [n x max(ntt)] (currently only compute transits of star, so first row is zero) [days]
# count = array of the number of transits for each body
# dtbvdq0 = derivative of transit times, impact parameters & sky velocities with respect to initial x,v,m [various units: day/length (3), day^2/length (3), day/mass]
# 5D array [1-3] x [n x max(ntt) ] x [n x 7] - derivatives of transits of each planet with respect to initial positions/velocities
# masses of *all* bodies. Note: mass derivatives are *after* positions/velocities, even though they are at start
# of the elements[i,j] array.
#
# Output quantity:
# dtbvdelements = 5D array [1-3] x [n x max(ntt) ] x [n x 7] - derivatives of transits of each planet with respect to initial orbital
# elements/masses of *all* bodies. Note: mass derivatives are *after* elements, even though they are at start
# of the elements[i,j] array
#
# Example: see test_ttvbv_elements.jl in test/ directory
#
# Define initial mass, position & velocity arrays:
n = H[1]
m=zeros(T,n)
x=zeros(T,NDIM,n)
v=zeros(T,NDIM,n)
# Fill the transit-timing & jacobian arrays with zeros:
fill!(ttbv,zero(T))
fill!(dtbvdq0,zero(T))
# Create an array for the derivatives with respect to the masses/orbital elements:
dtbvdelements = copy(dtbvdq0)
# Counter for transits of each planet:
fill!(count,0)
for i=1:n
m[i] = elements[i,1]
end
# Initialize the N-body problem using nested hierarchy of Keplerians:
#jac_init = zeros(T,7*n,7*n)
init = ElementsIC(elements,H,t0)
x,v,jac_init = init_nbody(init)
elements_big=big.(elements); t0big = big(t0); jac_init_big = zeros(BigFloat,7*n,7*n)
init_big = ElementsIC(elements_big,H,t0big)
xbig,vbig,jac_init_big = init_nbody(init_big)
#if T != BigFloat
# println("Difference in x,v init: ",x-convert(Array{T,2},xbig)," ",v-convert(Array{T,2},vbig)," (Jacobian version)")
# println("Difference in Jacobian: ",jac_init-convert(Array{T,2},jac_init_big)," (Jacobian version)")
#end
x = convert(Array{T,2},xbig); v = convert(Array{T,2},vbig); jac_init=convert(Array{T,2},jac_init_big)
#x,v = init_nbody(elements,t0,n)
ttvbv!(n,t0,h,tmax,m,x,v,ttbv,count,dtbvdq0,rstar,pair;fout=fout,iout=iout)
# Need to apply initial jacobian TBD - convert from
# derivatives with respect to (x,v,m) to (elements,m):
ntt_max = size(ttbv)[3]
ntbv = size(ttbv)[1] # = 1 for just times; = 3 for times + v_sky + b_sky^2
@inbounds for itbv=1:ntbv, i=1:n, j=1:count[i]
if j <= ntt_max
# Now, multiply by the initial Jacobian to convert time derivatives to orbital elements:
@inbounds for k=1:n, l=1:7
dtbvdelements[itbv,i,j,l,k] = zero(T)
@inbounds for p=1:n, q=1:7
dtbvdelements[itbv,i,j,l,k] += dtbvdq0[itbv,i,j,q,p]*jac_init[(p-1)*7+q,(k-1)*7+l]
end
end
end
end
return dtbvdelements
end
# Computes TTVs for initial x,v, as well as timing derivatives with respect to x,v,m (dtdq0).
function ttv!(n::Int64,t0::T,h::T,tmax::T,m::Array{T,1},
x::Array{T,2},v::Array{T,2},tt::Array{T,2},count::Array{Int64,1},dtdq0::Array{T,4},rstar::T,pair::Array{Bool,2};fout="",iout=-1) where {T <: Real}
xprior = copy(x)
vprior = copy(v)
xtransit = copy(x)
vtransit = copy(v)
xerror = zeros(T,size(x)); verror=zeros(T,size(v))
xerr_trans = zeros(T,size(x)); verr_trans =zeros(T,size(v))
xerr_prior = zeros(T,size(x)); verr_prior =zeros(T,size(v))
# Set the time to the initial time:
t = t0
# Define error estimate based on Kahan (1965):
s2 = zero(T)
# Set step counter to zero:
istep = 0
# Jacobian for each step (7- 6 elements+mass, n_planets, 7 - 6 elements+mass, n planets):
jac_prior = zeros(T,7*n,7*n)
jac_error_prior = zeros(T,7*n,7*n)
jac_transit = zeros(T,7*n,7*n)
jac_trans_err= zeros(T,7*n,7*n)
# Initialize matrix for derivatives of transit times with respect to the initial x,v,m:
dtdq = zeros(T,1,7,n)
# Initialize the Jacobian to the identity matrix:
#jac_step = eye(T,7*n)
jac_step = Matrix{T}(I,7*n,7*n)
# Initialize Jacobian error array:
jac_error = zeros(T,7*n,7*n)
if fout != ""
# Open file for output:
file_handle =open(fout,"a")
end
# Output initial conditions:
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n))]') # Transpose to write each line
end
# Save the g function, which computes the relative sky velocity dotted with relative position
# between the planets and star:
gsave = zeros(T,n)
for i=2:n
# Compute the relative sky velocity dotted with position:
gsave[i]= g!(i,1,x,v)
end
# Loop over time steps:
dt = zero(T)
gi = zero(T)
ntt_max = size(tt)[2]
d = Derivatives(T)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
while t < (t0+tmax) && param_real
# Carry out a dh17 mapping step:
ah18!(x,v,xerror,verror,h,m,n,jac_step,jac_error,pair,d)
#dh17!(x,v,h,m,n,jac_step,pair)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
# Check to see if a transit may have occured. Sky is x-y plane; line of sight is z.
# Star is body 1; planets are 2-nbody (note that this could be modified to see if
# any body transits another body):
for i=2:n
# Compute the relative sky velocity dotted with position:
gi = g!(i,1,x,v)
ri = sqrt(x[1,i]^2+x[2,i]^2+x[3,i]^2) # orbital distance
# See if sign of g switches, and if planet is in front of star (by a good amount):
# (I'm wondering if the direction condition means that z-coordinate is reversed? EA 12/11/2017)
if gi > 0 && gsave[i] < 0 && x[3,i] > 0.25*ri && ri < rstar
# A transit has occurred between the time steps - integrate dh17! between timesteps
count[i] += 1
if count[i] <= ntt_max
dt0 = -gsave[i]*h/(gi-gsave[i]) # Starting estimate
xtransit .= xprior; vtransit .= vprior; jac_transit .= jac_prior; jac_trans_err .= jac_error_prior
xerr_trans .= xerr_prior; verr_trans .= verr_prior
# dt = findtransit2!(1,i,n,h,dt0,m,xtransit,vtransit,jac_transit,dtdq,pair) # 20%
dt = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_trans,verr_trans,jac_transit,jac_trans_err,dtdq,pair) # 20%
#tt[i,count[i]]=t+dt
tt[i,count[i]],stmp = comp_sum(t,s2,dt)
# Save for posterity:
for k=1:7, p=1:n
dtdq0[i,count[i],k,p] = dtdq[1,k,p]
end
end
end
gsave[i] = gi
end
# Save the current state as prior state:
xprior .= x
vprior .= v
jac_prior .= jac_step
jac_error_prior .= jac_error
xerr_prior .= xerror
verr_prior .= verror
# Increment time by the time step using compensated summation:
#s2 += h; tmp = t + s2; s2 = (t - tmp) + s2
#t = tmp
t,s2 = comp_sum(t,s2,h)
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n));convert(Array{Float64,1},reshape(jac_step,49n^2))]') # Transpose to write each line
end
# t += h <- this leads to loss of precision
# Increment counter by one:
istep +=1
end
if fout != ""
# Close output file:
close(file_handle)
end
return
end
# Computes TTVs for initial x,v, as well as timing derivatives with respect to x,v,m (dtdq0).
function ttvbv!(n::Int64,t0::T,h::T,tmax::T,m::Array{T,1},
x::Array{T,2},v::Array{T,2},ttbv::Array{T,3},count::Array{Int64,1},dtbvdq0::Array{T,5},rstar::T,pair::Array{Bool,2};fout="",iout=-1) where {T <: Real}
xprior = copy(x)
vprior = copy(v)
xtransit = copy(x)
vtransit = copy(v)
xerror = zeros(T,size(x)); verror=zeros(T,size(v))
xerr_trans = zeros(T,size(x)); verr_trans =zeros(T,size(v))
xerr_prior = zeros(T,size(x)); verr_prior =zeros(T,size(v))
# Set the time to the initial time:
t = t0
# Define error estimate based on Kahan (1965):
s2 = zero(T)
# Set step counter to zero:
istep = 0
# Jacobian for each step (7- 6 elements+mass, n_planets, 7 - 6 elements+mass, n planets):
jac_prior = zeros(T,7*n,7*n)
jac_error_prior = zeros(T,7*n,7*n)
jac_transit = zeros(T,7*n,7*n)
jac_trans_err= zeros(T,7*n,7*n)
# Initialize matrix for derivatives of transit times, impact parameters & sky velocity with respect to the initial x,v,m:
ntbv = size(dtbvdq0)[1]
if ntbv == 3
calcbvsky = true
else
calcbvsky = false
end
dtbvdq = zeros(T,ntbv,7,n)
# Initialize the Jacobian to the identity matrix:
#jac_step = eye(T,7*n)
jac_step = Matrix{T}(I,7*n,7*n)
# Initialize Jacobian error array:
jac_error = zeros(T,7*n,7*n)
if fout != ""
# Open file for output:
file_handle =open(fout,"a")
end
# Output initial conditions:
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n))]') # Transpose to write each line
end
# Save the g function, which computes the relative sky velocity dotted with relative position
# between the planets and star:
gsave = zeros(T,n)
for i=2:n
# Compute the relative sky velocity dotted with position:
gsave[i]= g!(i,1,x,v)
end
# Loop over time steps:
dt = zero(T)
gi = zero(T)
ntt_max = size(ttbv)[3]
d = Derivatives(T)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
while t < (t0+tmax) && param_real
# Carry out a dh17 mapping step:
ah18!(x,v,xerror,verror,h,m,n,jac_step,jac_error,pair,d)
#dh17!(x,v,h,m,n,jac_step,pair)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
# Check to see if a transit may have occured. Sky is x-y plane; line of sight is z.
# Star is body 1; planets are 2-nbody (note that this could be modified to see if
# any body transits another body):
for i=2:n
# Compute the relative sky velocity dotted with position:
gi = g!(i,1,x,v)
ri = sqrt(x[1,i]^2+x[2,i]^2+x[3,i]^2) # orbital distance
# See if sign of g switches, and if planet is in front of star (by a good amount):
# (I'm wondering if the direction condition means that z-coordinate is reversed? EA 12/11/2017)
if gi > 0 && gsave[i] < 0 && x[3,i] > 0.25*ri && ri < rstar
# A transit has occurred between the time steps - integrate dh17! between timesteps
count[i] += 1
if count[i] <= ntt_max
dt0 = -gsave[i]*h/(gi-gsave[i]) # Starting estimate
xtransit .= xprior; vtransit .= vprior; jac_transit .= jac_prior; jac_trans_err .= jac_error_prior
xerr_trans .= xerr_prior; verr_trans .= verr_prior
# dt = findtransit2!(1,i,n,h,dt0,m,xtransit,vtransit,jac_transit,dtbvdq,pair) # 20%
if calcbvsky
dt,vsky,bsky2 = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_trans,verr_trans,jac_transit,jac_trans_err,dtbvdq,pair) # 20%
ttbv[2,i,count[i]] = vsky
ttbv[3,i,count[i]] = bsky2
else
dt = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_trans,verr_trans,jac_transit,jac_trans_err,dtbvdq,pair) # 20%
end
#tt[i,count[i]]=t+dt
ttbv[1,i,count[i]],stmp = comp_sum(t,s2,dt)
# Save for posterity:
@inbounds for itbv=1:ntbv, k=1:7, p=1:n
dtbvdq0[itbv,i,count[i],k,p] = dtbvdq[itbv,k,p]
end
end
end
gsave[i] = gi
end
# Save the current state as prior state:
xprior .= x
vprior .= v
jac_prior .= jac_step
jac_error_prior .= jac_error
xerr_prior .= xerror
verr_prior .= verror
# Increment time by the time step using compensated summation:
#s2 += h; tmp = t + s2; s2 = (t - tmp) + s2
#t = tmp
t,s2 = comp_sum(t,s2,h)
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n));convert(Array{Float64,1},reshape(jac_step,49n^2))]') # Transpose to write each line
end
# t += h <- this leads to loss of precision
# Increment counter by one:
istep +=1
end
if fout != ""
# Close output file:
close(file_handle)
end
return
end
# Computes TTVs for initial x,v, as well as timing derivatives with respect to x,v,m (dtdq0).
# This version is used to test findtransit2 by computing finite difference derivative of findtransit2.
function ttv!(n::Int64,t0::Float64,h::Float64,tmax::Float64,m::Array{Float64,1},x::Array{Float64,2},v::Array{Float64,2},tt::Array{Float64,2},count::Array{Int64,1},dtdq0::Array{Float64,4},dtdq0_num::Array{BigFloat,4},dlnq::BigFloat,rstar::Float64,pair::Array{Bool,2})
xprior = copy(x)
vprior = copy(v)
#xtransit = big.(x); xtransit_plus = big.(x); xtransit_minus = big.(x)
#vtransit = big.(v); vtransit_plus = big.(v); vtransit_minus = big.(v)
xtransit = copy(x); xtransit_plus = big.(x); xtransit_minus = big.(x)
vtransit = copy(v); vtransit_plus = big.(v); vtransit_minus = big.(v)
xerror = zeros(Float64,size(x)); verror = zeros(Float64,size(x))
xerr_trans = zeros(Float64,size(x)); verr_trans = zeros(Float64,size(x))
xerr_prior = zeros(Float64,size(x)); verr_prior = zeros(Float64,size(x))
xerr_big = zeros(BigFloat,size(x)); verr_big = zeros(BigFloat,size(x))
m_plus = big.(m); m_minus = big.(m); hbig = big(h); dq = big(0.0)
if h == 0
println("h is zero ",h)
end
# Set the time to the initial time:
t = t0
# Define error estimate based on Kahan (1965):
s2 = 0.0
# Set step counter to zero:
istep = 0
# Initialize matrix for derivatives of transit times with respect to the initial x,v,m:
dtdqbig = zeros(BigFloat,1,7,n)
dtdq = zeros(Float64,1,7,n)
dtdq3 = zeros(Float64,1,7,n)
# Initialize the Jacobian to the identity matrix:
jac_prior = zeros(Float64,7*n,7*n)
#jac_step = eye(Float64,7*n)
jac_step = Matrix{Float64}(I,7*n,7*n)
# Initialize Jacobian error matrix
jac_error = zeros(Float64,7*n,7*n)
jac_trans_err = zeros(Float64,7*n,7*n)
jac_error_prior = zeros(Float64,7*n,7*n)
# Save the g function, which computes the relative sky velocity dotted with relative position
# between the planets and star:
gsave = zeros(Float64,n)
for i=2:n
# Compute the relative sky velocity dotted with position:
gsave[i]= g!(i,1,x,v)
end
# Loop over time steps:
dt::Float64 = 0.0
gi = 0.0
ntt_max = size(tt)[2]
d = Derivatives(Float64)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
while t < t0+tmax && param_real
# Carry out a dh17 mapping step:
ah18!(x,v,xerror,verror,h,m,n,jac_step,jac_error,pair,d)
#dh17!(x,v,h,m,n,jac_step,pair)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
# Check to see if a transit may have occured. Sky is x-y plane; line of sight is z.
# Star is body 1; planets are 2-nbody (note that this could be modified to see if
# any body transits another body):
for i=2:n
# Compute the relative sky velocity dotted with position:
gi = g!(i,1,x,v)
ri = sqrt(x[1,i]^2+x[2,i]^2+x[3,i]^2)
# See if sign of g switches, and if planet is in front of star (by a good amount):
# (I'm wondering if the direction condition means that z-coordinate is reversed? EA 12/11/2017)
if gi > 0 && gsave[i] < 0 && x[3,i] > 0.25*ri && ri < rstar
# A transit has occurred between the time steps - integrate dh17! between timesteps
count[i] += 1
if count[i] <= ntt_max
# dt0 = big(-gsave[i]*h/(gi-gsave[i])) # Starting estimate
dt0 = -gsave[i]*h/(gi-gsave[i]) # Starting estimate
# xtransit .= big.(xprior); vtransit .= big.(vprior)
# xtransit .= xprior; vtransit .= vprior
# jac_transit = eye(jac_step)
# dt,gdot = findtransit2!(1,i,n,h,dt0,m,xtransit,vtransit,jac_transit,dtdq,pair) # Just computing derivative since prior timestep, so start with identity matrix
# dt = findtransit2!(1,i,n,h,dt0,m,xtransit,vtransit,jac_transit,dtdq,pair) # Just computing derivative since prior timestep, so start with identity matrix
# jac_transit = eye(BigFloat,7*n)
# hbig = big(h)
# dtbig = findtransit2!(1,i,n,hbig,dt0,big.(m),xtransit,vtransit,jac_transit,dtdqbig,pair) # Just computing derivative since prior timestep, so start with identity matrix
# dtdq = convert(Array{Float64,2},dtdqbig)
# dt0 = -gsave[i]*h/(gi-gsave[i]) # Starting estimate
# Now, recompute with findtransit3:
xtransit .= xprior; vtransit .= vprior; xerr_trans .= xerr_prior; verr_trans .= verr_prior
# jac_transit = eye(jac_step); jac_trans_err .= jac_error_prior
jac_transit = Matrix{Float64}(I,7*n,7*n); jac_trans_err .= jac_error_prior
dt = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_trans,verr_trans,jac_transit,jac_trans_err,dtdq3,pair) # Just computing derivative since prior timestep, so start with identity matrix
# Save for posterity:
#tt[i,count[i]]=t+dt
tt[i,count[i]],stmp = comp_sum(t,s2,dt)
for k=1:7, p=1:n
# dtdq0[i,count[i],k,p] = dtdq[k,p]
dtdq0[i,count[i],k,p] = dtdq3[1,k,p]
# Compute numerical approximation of dtdq:
dt_plus = big(dt) # Starting estimate
# dt_plus = dtbig # Starting estimate
xtransit_plus .= big.(xprior); vtransit_plus .= big.(vprior); m_plus .= big.(m); fill!(xerr_big,zero(BigFloat)); fill!(verr_big,zero(BigFloat))
if k < 4; dq = dlnq*xtransit_plus[k,p]; xtransit_plus[k,p] += dq; elseif k < 7; dq =vtransit_plus[k-3,p]*dlnq; vtransit_plus[k-3,p] += dq; else; dq = m_plus[p]*dlnq; m_plus[p] += dq; end
# dt_plus = findtransit2!(1,i,n,hbig,dt_plus,m_plus,xtransit_plus,vtransit_plus,pair) # 20%
dt_plus = findtransit3!(1,i,n,hbig,dt_plus,m_plus,xtransit_plus,vtransit_plus,xerr_big,verr_big,pair) # 20%
dt_minus= big(dt) # Starting estimate
# dt_minus= dtbig # Starting estimate
xtransit_minus .= big.(xprior); vtransit_minus .= big.(vprior); m_minus .= big.(m); fill!(xerr_big,zero(BigFloat)); fill!(verr_big,zero(BigFloat))
if k < 4; dq = dlnq*xtransit_minus[k,p];xtransit_minus[k,p] -= dq; elseif k < 7; dq =vtransit_minus[k-3,p]*dlnq; vtransit_minus[k-3,p] -= dq; else; dq = m_minus[p]*dlnq; m_minus[p] -= dq; end
hbig = big(h)
# dt_minus= findtransit2!(1,i,n,hbig,dt_minus,m_minus,xtransit_minus,vtransit_minus,pair) # 20%
dt_minus= findtransit3!(1,i,n,hbig,dt_minus,m_minus,xtransit_minus,vtransit_minus,xerr_big,verr_big,pair) # 20%
# Compute finite-different derivative:
dtdq0_num[i,count[i],k,p] = (dt_plus-dt_minus)/(2dq)
if abs(dtdq0_num[i,count[i],k,p] - dtdq0[i,count[i],k,p]) > 1e-10
# Compute gdot_num:
dt_minus = big(dt)*(1-dlnq) # Starting estimate
xtransit_minus .= big.(xprior); vtransit_minus .= big.(vprior); m_minus .= big.(m); fill!(xerr_big,zero(BigFloat)); fill!(verr_big,zero(BigFloat))
ah18!(xtransit_minus,vtransit_minus,xerr_big,verr_big,dt_minus,m_minus,n,pair)
#dh17!(xtransit_minus,vtransit_minus,dt_minus,m_minus,n,pair)
# Compute time offset:
gsky_minus = g!(i,1,xtransit_minus,vtransit_minus)
dt_plus = big(dt)*(1+dlnq) # Starting estimate
xtransit_plus .= big.(xprior); vtransit_plus .= big.(vprior); m_plus .= big.(m); fill!(xerr_big,zero(BigFloat)); fill!(verr_big,zero(BigFloat))
ah18!(xtransit_plus,vtransit_plus,xerr_big,verr_big,dt_plus,m_plus,n,pair)
#dh17!(xtransit_plus,vtransit_plus,dt_plus,m_plus,n,pair)
# Compute time offset:
gsky_plus = g!(i,1,xtransit_plus,vtransit_plus)
gdot_num = convert(Float64,(gsky_plus-gsky_minus)/(2dlnq*big(dt)))
# println("i: ",i," count: ",count[i]," k: ",k," p: ",p," dt: ",dt," dq: ",dq," dtdq0: ",dtdq0[i,count[i],k,p]," dtdq0_num: ",convert(Float64,dtdq0_num[i,count[i],k,p])," ratio-1: ",dtdq0[i,count[i],k,p]/convert(Float64,dtdq0_num[i,count[i],k,p])-1.0," gdot_num: ",gdot_num) #," ratio-1: ",gdot/gdot_num-1.0)
# println("x0: ",xprior)
# println("v0: ",vprior)
# println("x: ",x)
# println("v: ",v)
# read(STDIN,Char)
end
end
end
end
gsave[i] = gi
end
# Save the current state as prior state:
xprior .= x
vprior .= v
jac_prior .= jac_step
jac_error_prior .= jac_error
xerr_prior .= xerror; verr_prior .= verror
# Increment time by the time step using compensated summation:
#s2 += h; tmp = t + s2; s2 = (t - tmp) + s2
#t = tmp
t,s2 = comp_sum(t,s2,h)
# t += h <- this leads to loss of precision
# Increment counter by one:
istep +=1
end
return
end
# Computes TTVs, v_sky, b_sky^2 for initial x,v, as well as timing derivatives with respect to x,v,m (dtbvdq0).
# This version is used to test findtransit2 by computing finite difference derivative of findtransit2.
function ttvbv!(n::Int64,t0::Float64,h::Float64,tmax::Float64,m::Array{Float64,1},x::Array{Float64,2},v::Array{Float64,2},ttbv::Array{Float64,3},count::Array{Int64,1},dtbvdq0::Array{Float64,5},dtbvdq0_num::Array{BigFloat,5},dlnq::BigFloat,rstar::Float64,pair::Array{Bool,2})
xprior = copy(x)
vprior = copy(v)
#xtransit = big.(x); xtransit_plus = big.(x); xtransit_minus = big.(x)
#vtransit = big.(v); vtransit_plus = big.(v); vtransit_minus = big.(v)
xtransit = copy(x); xtransit_plus = big.(x); xtransit_minus = big.(x)
vtransit = copy(v); vtransit_plus = big.(v); vtransit_minus = big.(v)
xerror = zeros(Float64,size(x)); verror = zeros(Float64,size(x))
xerr_trans = zeros(Float64,size(x)); verr_trans = zeros(Float64,size(x))
xerr_prior = zeros(Float64,size(x)); verr_prior = zeros(Float64,size(x))
xerr_big = zeros(BigFloat,size(x)); verr_big = zeros(BigFloat,size(x))
m_plus = big.(m); m_minus = big.(m); hbig = big(h); dq = big(0.0)
if h == 0
println("h is zero ",h)
end
# Set the time to the initial time:
t = t0
# Define error estimate based on Kahan (1965):
s2 = 0.0
# Set step counter to zero:
istep = 0
# Initialize matrix for derivatives of transit times with respect to the initial x,v,m:
ntbv = size(ttbv)[1]
if ntbv == 3
# Compute times, vsky & bsky^2:
calcbvsky = true
else
# Just compute transit times:
calcbvsky = false
end
dtbvdqbig = zeros(BigFloat,ntbv,7,n)
dtbvdq = zeros(Float64,ntbv,7,n)
dtbvdq3 = zeros(Float64,ntbv,7,n)
# Initialize the Jacobian to the identity matrix:
jac_prior = zeros(Float64,7*n,7*n)
#jac_step = eye(Float64,7*n)
jac_step = Matrix{Float64}(I,7*n,7*n)
# Initialize Jacobian error matrix
jac_error = zeros(Float64,7*n,7*n)
jac_trans_err = zeros(Float64,7*n,7*n)
jac_error_prior = zeros(Float64,7*n,7*n)
# Save the g function, which computes the relative sky velocity dotted with relative position
# between the planets and star:
gsave = zeros(Float64,n)
for i=2:n
# Compute the relative sky velocity dotted with position:
gsave[i]= g!(i,1,x,v)
end
# Loop over time steps:
dt::Float64 = 0.0
gi = 0.0
ntt_max = size(tt)[2]
d = Derivatives(T)
dBig = Derivatives(BigFloat)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
while t < t0+tmax && param_real
# Carry out a dh17 mapping step:
ah18!(x,v,xerror,verror,h,m,n,jac_step,jac_error,pair,d)
#dh17!(x,v,h,m,n,jac_step,pair)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
# Check to see if a transit may have occured. Sky is x-y plane; line of sight is z.
# Star is body 1; planets are 2-nbody (note that this could be modified to see if
# any body transits another body):
for i=2:n
# Compute the relative sky velocity dotted with position:
gi = g!(i,1,x,v)
ri = sqrt(x[1,i]^2+x[2,i]^2+x[3,i]^2)
# See if sign of g switches, and if planet is in front of star (by a good amount):
# (I'm wondering if the direction condition means that z-coordinate is reversed? EA 12/11/2017)
if gi > 0 && gsave[i] < 0 && x[3,i] > 0.25*ri && ri < rstar
# A transit has occurred between the time steps - integrate dh17! between timesteps
count[i] += 1
if count[i] <= ntt_max
dt0 = -gsave[i]*h/(gi-gsave[i]) # Starting estimate
# Now, recompute with findtransit3:
xtransit .= xprior; vtransit .= vprior; xerr_trans .= xerr_prior; verr_trans .= verr_prior
jac_transit = Matrix{Float64}(I,7*n,7*n); jac_trans_err .= jac_error_prior
if calcbvsky
# Compute time of transit, vsky, and bsky^2:
dt,vsky,bsky2 = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_trans,verr_trans,jac_transit,jac_trans_err,dtbvdq3,pair) # Just computing derivative since prior timestep, so start with identity matrix
ttbv[2,i,count[i]] = vsky
ttbv[3,i,count[i]] = bsky2
else
# Compute only time of transit:
dt = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_trans,verr_trans,jac_transit,jac_trans_err,dtbvdq3,pair) # Just computing derivative since prior timestep, so start with identity matrix
end
# Save for posterity:
#tt[i,count[i]]=t+dt
ttbv[1,i,count[i]],stmp = comp_sum(t,s2,dt)
for itbv=1:ntbv, k=1:7, p=1:n
dtbvdq0[itbv,i,count[i],k,p] = dtbvdq3[itbv,k,p]
# Compute numerical approximation of dtbvdq:
dt_plus = big(dt) # Starting estimate
if calcbvsky
dvsky_plus = big(vsky) # Starting estimate
dbsky2_plus = big(bsky2) # Starting estimate
end
xtransit_plus .= big.(xprior); vtransit_plus .= big.(vprior); m_plus .= big.(m); fill!(xerr_big,zero(BigFloat)); fill!(verr_big,zero(BigFloat))
if k < 4; dq = dlnq*xtransit_plus[k,p]; xtransit_plus[k,p] += dq; elseif k < 7; dq =vtransit_plus[k-3,p]*dlnq; vtransit_plus[k-3,p] += dq; else; dq = m_plus[p]*dlnq; m_plus[p] += dq; end
if calcbvsky
dt_plus,dvsky_plus,dbsky2_plus = findtransit3!(1,i,n,hbig,dt_plus,m_plus,xtransit_plus,vtransit_plus,xerr_big,verr_big,pair;calcbvsky=calcbvsky) # 20%
dvsky_minus = big(vsky)
dbsky2_minus = big(bsky2)
else
dt_plus = findtransit3!(1,i,n,hbig,dt_plus,m_plus,xtransit_plus,vtransit_plus,xerr_big,verr_big,pair) # 20%
end
dt_minus= big(dt) # Starting estimate
xtransit_minus .= big.(xprior); vtransit_minus .= big.(vprior); m_minus .= big.(m); fill!(xerr_big,zero(BigFloat)); fill!(verr_big,zero(BigFloat))
if k < 4; dq = dlnq*xtransit_minus[k,p];xtransit_minus[k,p] -= dq; elseif k < 7; dq =vtransit_minus[k-3,p]*dlnq; vtransit_minus[k-3,p] -= dq; else; dq = m_minus[p]*dlnq; m_minus[p] -= dq; end
hbig = big(h)
if calcbvsky
dt_minus,dvsky_minus,dbsky2_minus= findtransit3!(1,i,n,hbig,dt_minus,m_minus,xtransit_minus,vtransit_minus,xerr_big,verr_big,pair;calcbvsky=calcbvsky) # 20%
dtbvdq0_num[2,i,count[i],k,p] = (dvsky_plus-dvsky_minus)/(2dq)
dtbvdq0_num[3,i,count[i],k,p] = (dbsky2_plus-dbsky2_minus)/(2dq)
else
dt_minus= findtransit3!(1,i,n,hbig,dt_minus,m_minus,xtransit_minus,vtransit_minus,xerr_big,verr_big,pair) # 20%
end
# Compute finite-different derivative:
dtbvdq0_num[1,i,count[i],k,p] = (dt_plus-dt_minus)/(2dq)
if abs(dtdq0_num[1,i,count[i],k,p] - dtdq0[1,i,count[i],k,p]) > 1e-10
# Compute gdot_num:
dt_minus = big(dt)*(1-dlnq) # Starting estimate
xtransit_minus .= big.(xprior); vtransit_minus .= big.(vprior); m_minus .= big.(m); fill!(xerr_big,zero(BigFloat)); fill!(verr_big,zero(BigFloat))
ah18!(xtransit_minus,vtransit_minus,xerr_big,verr_big,dt_minus,m_minus,n,pair,dBig)
#dh17!(xtransit_minus,vtransit_minus,dt_minus,m_minus,n,pair)
# Compute time offset:
gsky_minus = g!(i,1,xtransit_minus,vtransit_minus)
dt_plus = big(dt)*(1+dlnq) # Starting estimate
xtransit_plus .= big.(xprior); vtransit_plus .= big.(vprior); m_plus .= big.(m); fill!(xerr_big,zero(BigFloat)); fill!(verr_big,zero(BigFloat))
ah18!(xtransit_plus,vtransit_plus,xerr_big,verr_big,dt_plus,m_plus,n,pair,dBig)
#dh17!(xtransit_plus,vtransit_plus,dt_plus,m_plus,n,pair)
# Compute time offset:
gsky_plus = g!(i,1,xtransit_plus,vtransit_plus)
gdot_num = convert(Float64,(gsky_plus-gsky_minus)/(2dlnq*big(dt)))
end
end
end
end
gsave[i] = gi
end
# Save the current state as prior state:
xprior .= x
vprior .= v
jac_prior .= jac_step
jac_error_prior .= jac_error
xerr_prior .= xerror; verr_prior .= verror
# Increment time by the time step using compensated summation:
#s2 += h; tmp = t + s2; s2 = (t - tmp) + s2
#t = tmp
t,s2 = comp_sum(t,s2,h)
# t += h <- this leads to loss of precision
# Increment counter by one:
istep +=1
end
return
end
# Computes TTVs as a function of initial x,v,m.
function ttv!(n::Int64,t0::T,h::T,tmax::T,m::Array{T,1},x::Array{T,2},v::Array{T,2},tt::Array{T,2},count::Array{Int64,1},fout::String,iout::Int64,rstar::T,pair::Array{Bool,2}) where {T <: Real}
# Make some copies to allocate space for saving prior step and computing coordinates at the times of transit.
xprior = copy(x)
vprior = copy(v)
xtransit = copy(x)
vtransit = copy(v)
#xerror = zeros(x); verror = zeros(v)
xerror = copy(x); verror = copy(v)
fill!(xerror,zero(T)); fill!(verror,zero(T))
#xerr_prior = zeros(x); verr_prior = zeros(v)
xerr_prior = copy(xerror); verr_prior = copy(verror)
# Set the time to the initial time:
t = t0
# Define error estimate based on Kahan (1965):
s2 = zero(T)
# Set step counter to zero:
istep = 0
# Jacobian for each step (7 elements+mass, n_planets, 7 elements+mass, n planets):
# Save the g function, which computes the relative sky velocity dotted with relative position
# between the planets and star:
gsave = zeros(T,n)
gi = 0.0
dt::T = 0.0
# Loop over time steps:
ntt_max = size(tt)[2]
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m))
if fout != ""
# Open file for output:
file_handle =open(fout,"a")
end
# Output initial conditions:
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n))]') # Transpose to write each line
end
while t < t0+tmax && param_real
# Carry out a phi^2 mapping step:
# phi2!(x,v,h,m,n)
ah18!(x,v,xerror,verror,h,m,n,pair)
# xbig = big.(x); vbig = big.(v); hbig = big(h); mbig = big.(m)
#dh17!(x,v,xerror,verror,h,m,n,pair)
# dh17!(xbig,vbig,hbig,mbig,n,pair)
# x .= convert(Array{Float64,2},xbig); v .= convert(Array{Float64,2},vbig)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m))
# Check to see if a transit may have occured. Sky is x-y plane; line of sight is z.
# Star is body 1; planets are 2-nbody:
for i=2:n
# Compute the relative sky velocity dotted with position:
gi = g!(i,1,x,v)
ri = sqrt(x[1,i]^2+x[2,i]^2+x[3,i]^2)
# See if sign switches, and if planet is in front of star (by a good amount):
if gi > 0 && gsave[i] < 0 && x[3,i] > 0.25*ri && ri < rstar
# A transit has occurred between the time steps.
# Approximate the planet-star motion as a Keplerian, weighting over timestep:
count[i] += 1
# tt[i,count[i]]=t+findtransit!(i,h,gi,gsave[i],m,xprior,vprior,x,v,pair)
if count[i] <= ntt_max
dt0 = -gsave[i]*h/(gi-gsave[i])
xtransit .= xprior
vtransit .= vprior
# dt = findtransit2!(1,i,n,h,dt0,m,xtransit,vtransit,pair)
#hbig = big(h); dt0big=big(dt0); mbig=big.(m); xtbig = big.(xtransit); vtbig = big.(vtransit)
#dtbig = findtransit2!(1,i,n,hbig,dt0big,mbig,xtbig,vtbig,pair)
#dt = convert(Float64,dtbig)
dt = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_prior,verr_prior,pair)
#tt[i,count[i]]=t+dt
tt[i,count[i]],stmp = comp_sum(t,s2,dt)
end
# tt[i,count[i]]=t+findtransit2!(1,i,n,h,gi,gsave[i],m,xprior,vprior,pair)
end
gsave[i] = gi
end
# Save the current state as prior state:
xprior .= x
vprior .= v
xerr_prior .= xerror
verr_prior .= verror
# Increment time by the time step using compensated summation:
#s2 += h; tmp = t + s2; s2 = (t - tmp) + s2
#t = tmp
t,s2 = comp_sum(t,s2,h)
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n))]') # Transpose to write each line
end
# t += h <- this leads to loss of precision
# Increment counter by one:
istep +=1
# println("xerror: ",xerror)
# println("verror: ",verror)
end
#println("xerror: ",xerror)
#println("verror: ",verror)
if fout != ""
# Close output file:
close(file_handle)
end
return
end
# Computes TTVs, sky velocities, and impact parameters as a function of initial x,v,m.
function ttvbv!(n::Int64,t0::T,h::T,tmax::T,m::Array{T,1},x::Array{T,2},v::Array{T,2},ttbv::Array{T,3},count::Array{Int64,1},fout::String,iout::Int64,rstar::T,pair::Array{Bool,2}) where {T <: Real}
# Make some copies to allocate space for saving prior step and computing coordinates at the times of transit.
xprior = copy(x)
vprior = copy(v)
xtransit = copy(x)
vtransit = copy(v)
#xerror = zeros(x); verror = zeros(v)
xerror = copy(x); verror = copy(v)
fill!(xerror,zero(T)); fill!(verror,zero(T))
#xerr_prior = zeros(x); verr_prior = zeros(v)
xerr_prior = copy(xerror); verr_prior = copy(verror)
# Set the time to the initial time:
t = t0
# Define error estimate based on Kahan (1965):
s2 = zero(T)
# Set step counter to zero:
istep = 0
# Jacobian for each step (7 elements+mass, n_planets, 7 elements+mass, n planets):
# Save the g function, which computes the relative sky velocity dotted with relative position
# between the planets and star:
gsave = zeros(T,n)
gi = 0.0
dt::T = 0.0
# Loop over time steps:
ntt_max = size(ttbv)[3]
# How many variables are we computing? 1 = just times; 3 = times + v_sky + b_sky^2:
ntbv = size(ttbv)[1]
if ntbv == 3
calcbvsky = true
else
calcbvsky = false
end
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m))
if fout != ""
# Open file for output:
file_handle =open(fout,"a")
end
# Output initial conditions:
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n))]') # Transpose to write each line
end
while t < t0+tmax && param_real
# Carry out a phi^2 mapping step:
# phi2!(x,v,h,m,n)
ah18!(x,v,xerror,verror,h,m,n,pair)
# xbig = big.(x); vbig = big.(v); hbig = big(h); mbig = big.(m)
#dh17!(x,v,xerror,verror,h,m,n,pair)
# dh17!(xbig,vbig,hbig,mbig,n,pair)
# x .= convert(Array{Float64,2},xbig); v .= convert(Array{Float64,2},vbig)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m))
# Check to see if a transit may have occured. Sky is x-y plane; line of sight is z.
# Star is body 1; planets are 2-nbody:
for i=2:n
# Compute the relative sky velocity dotted with position:
gi = g!(i,1,x,v)
ri = sqrt(x[1,i]^2+x[2,i]^2+x[3,i]^2)
# See if sign switches, and if planet is in front of star (by a good amount):
if gi > 0 && gsave[i] < 0 && x[3,i] > 0.25*ri && ri < rstar
# A transit has occurred between the time steps.
# Approximate the planet-star motion as a Keplerian, weighting over timestep:
count[i] += 1
if count[i] <= ntt_max
dt0 = -gsave[i]*h/(gi-gsave[i])
xtransit .= xprior
vtransit .= vprior
#hbig = big(h); dt0big=big(dt0); mbig=big.(m); xtbig = big.(xtransit); vtbig = big.(vtransit)
#dtbig = findtransit2!(1,i,n,hbig,dt0big,mbig,xtbig,vtbig,pair)
#dt = convert(Float64,dtbig)
if calcbvsky
dt,vsky,bsky2 = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_prior,verr_prior,pair;calcbvsky=calcbvsky)
ttbv[2,i,count[i]] = vsky
ttbv[3,i,count[i]] = bsky2
else
dt = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_prior,verr_prior,pair)
end
ttbv[1,i,count[i]],stmp = comp_sum(t,s2,dt)
end
end
gsave[i] = gi
end
# Save the current state as prior state:
xprior .= x
vprior .= v
xerr_prior .= xerror
verr_prior .= verror
# Increment time by the time step using compensated summation:
#s2 += h; tmp = t + s2; s2 = (t - tmp) + s2
#t = tmp
t,s2 = comp_sum(t,s2,h)
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n))]') # Transpose to write each line
end
# t += h <- this leads to loss of precision
# Increment counter by one:
istep +=1
# println("xerror: ",xerror)
# println("verror: ",verror)
end
#println("xerror: ",xerror)
#println("verror: ",verror)
if fout != ""
# Close output file:
close(file_handle)
end
return
end
# Advances the center of mass of a binary (any pair of bodies)
#function centerm!(m::Array{Float64,1},mijinv::Float64,x::Array{Float64,2},v::Array{Float64,2},vcm::Array{Float64,1},delx::Array{Float64,1},delv::Array{Float64,1},i::Int64,j::Int64,h::Float64)
function centerm!(m::Array{T,1},mijinv::T,x::Array{T,2},v::Array{T,2},vcm::Array{T,1},delx::Array{T,1},delv::Array{T,1},i::Int64,j::Int64,h::T) where {T <: Real}
for k=1:NDIM
x[k,i] += m[j]*mijinv*delx[k] + h*vcm[k]
x[k,j] += -m[i]*mijinv*delx[k] + h*vcm[k]
v[k,i] += m[j]*mijinv*delv[k]
v[k,j] += -m[i]*mijinv*delv[k]
end
return
end
# Advances the center of mass of a binary (any pair of bodies) with compensated summation:
function centerm!(m::Array{T,1},mijinv::T,x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},vcm::Array{T,1},delx::Array{T,1},delv::Array{T,1},i::Int64,j::Int64,h::T) where {T <: Real}
for k=1:NDIM
#x[k,i] += m[j]*mijinv*delx[k] + h*vcm[k]
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],m[j]*mijinv*delx[k])
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],h*vcm[k])
#x[k,j] += -m[i]*mijinv*delx[k] + h*vcm[k]
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],-m[i]*mijinv*delx[k])
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],h*vcm[k])
#v[k,i] += m[j]*mijinv*delv[k]
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],m[j]*mijinv*delv[k])
#v[k,j] += -m[i]*mijinv*delv[k]
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*mijinv*delv[k])
end
return
end
# Drifts bodies i & j
#function driftij!(x::Array{Float64,2},v::Array{Float64,2},i::Int64,j::Int64,h::Float64)
function driftij!(x::Array{T,2},v::Array{T,2},i::Int64,j::Int64,h::T) where {T <: Real}
for k=1:NDIM
x[k,i] += h*v[k,i]
x[k,j] += h*v[k,j]
end
return
end
# Drifts bodies i & j with compensated summation:
#function driftij!(x::Array{Float64,2},v::Array{Float64,2},i::Int64,j::Int64,h::Float64)
function driftij!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T) where {T <: Real}
for k=1:NDIM
#x[k,i] += h*v[k,i]
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],h*v[k,i])
#x[k,j] += h*v[k,j]
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],h*v[k,j])
end
return
end
# Drifts bodies i & j with computation of dqdt:
function driftij!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T,dqdt::Array{T,1},fac::T) where {T <: Real}
indi = (i-1)*7
indj = (j-1)*7
for k=1:NDIM
#x[k,i] += h*v[k,i]
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],h*v[k,i])
#x[k,j] += h*v[k,j]
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],h*v[k,j])
# Time derivatives:
dqdt[indi+k] += fac*v[k,i] + h*dqdt[indi+3+k]
dqdt[indj+k] += fac*v[k,j] + h*dqdt[indj+3+k]
end
return
end
# Drifts bodies i & j and computes Jacobian:
function driftij!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T,jac_step::Array{T,2},jac_error::Array{T,2},nbody::Int64) where {T <: Real}
indi = (i-1)*7
indj = (j-1)*7
for k=1:NDIM
#x[k,i] += h*v[k,i]
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],h*v[k,i])
#x[k,j] += h*v[k,j]
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],h*v[k,j])
end
# Now for Jacobian:
for m=1:7*nbody, k=1:NDIM
#jac_step[indi+k,m] += h*jac_step[indi+3+k,m]
jac_step[indi+k,m],jac_error[indi+k,m] = comp_sum(jac_step[indi+k,m],jac_error[indi+k,m], h*jac_step[indi+3+k,m])
end
for m=1:7*nbody, k=1:NDIM
#jac_step[indj+k,m] += h*jac_step[indj+3+k,m]
jac_step[indj+k,m],jac_error[indi+k,m] = comp_sum(jac_step[indj+k,m],jac_error[indi+k,m],h*jac_step[indj+3+k,m])
end
return
end
# Carries out a Kepler step and reverse drift for bodies i & j
function kepler_driftij!(m::Array{T,1},x::Array{T,2},v::Array{T,2},i::Int64,j::Int64,h::T,drift_first::Bool) where {T <: Real}
# The state vector has: 1 time; 2-4 position; 5-7 velocity; 8 r0; 9 dr0dt; 10 beta; 11 s; 12 ds
# Initial state:
state0 = zeros(T,12)
# Final state (after a step):
state = zeros(T,12)
for k=1:NDIM
state0[1+k] = x[k,i] - x[k,j]
state0[4+k] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
if gm == 0
# Do nothing
# for k=1:3
# x[k,i] += h*v[k,i]
# x[k,j] += h*v[k,j]
# end
else
# predicted value of s
kepler_drift_step!(gm, h, state0, state,drift_first)
mijinv =1.0/(m[i] + m[j])
for k=1:3
# Add kepler-drift differences, weighted by masses, to start of step:
x[k,i] += m[j]*mijinv*state[1+k]
x[k,j] -= m[i]*mijinv*state[1+k]
v[k,i] += m[j]*mijinv*state[4+k]
v[k,j] -= m[i]*mijinv*state[4+k]
end
end
return
end
# Carries out a Kepler step and reverse drift for bodies i & j with compensated summation:
function kepler_driftij!(m::Array{T,1},x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T,drift_first::Bool) where {T <: Real}
# The state vector has: 1 time; 2-4 position; 5-7 velocity; 8 r0; 9 dr0dt; 10 beta; 11 s; 12 ds
# Initial state:
state0 = zeros(T,12)
# Final state (after a step):
state = zeros(T,12)
for k=1:NDIM
state0[1+k] = x[k,i] - x[k,j]
state0[4+k] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
if gm == 0
# Do nothing
# for k=1:3
# x[k,i] += h*v[k,i]
# x[k,j] += h*v[k,j]
# end
else
# predicted value of s
kepler_drift_step!(gm, h, state0, state,drift_first)
mijinv =1.0/(m[i] + m[j])
mi = m[i]*mijinv # Normalize the masses
mj = m[j]*mijinv
for k=1:3
# Add kepler-drift differences, weighted by masses, to start of step:
#x[k,i] += mj*state[1+k]
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i], mj*state[1+k])
#x[k,j] -= mi*state[1+k]
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],-mi*state[1+k])
#v[k,i] += mj*state[4+k]
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], mj*state[4+k])
#v[k,j] -= mi*state[4+k]
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-mi*state[4+k])
end
end
return
end
# Carries out a Kepler step and reverse drift for bodies i & j, and computes Jacobian:
function kepler_driftij!(m::Array{T,1},x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T,jac_ij::Array{T,2},dqdt::Array{T,1},drift_first::Bool,d::Derivatives{T}) where {T <: Real}
# The state vector has: 1 time; 2-4 position; 5-7 velocity; 8 r0; 9 dr0dt; 10 beta; 11 s; 12 ds
# Initial state:
state0 = zeros(T,12)
# Final state (after a step):
state = zeros(T,12)
@inbounds for k=1:NDIM
state0[1+k] = x[k,i] - x[k,j]
state0[4+k] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
# jac_ij should be the Jacobian for going from (x_{0,i},v_{0,i},m_i) & (x_{0,j},v_{0,j},m_j)
# to (x_i,v_i,m_i) & (x_j,v_j,m_j), a 14x14 matrix for the 3-dimensional case.
# Fill with zeros for now:
#jac_ij .= eye(T,14)
fill!(jac_ij,zero(h))
if gm == 0
# Do nothing
# for k=1:3
# x[k,i] += h*v[k,i]
# x[k,j] += h*v[k,j]
# end
else
jac_kepler = zeros(T,7,7)
# predicted value of s
kepler_drift_step!(gm, h, state0, state,jac_kepler,drift_first,d)
mijinv =1.0/(m[i] + m[j])
mi = m[i]*mijinv # Normalize the masses
mj = m[j]*mijinv
@inbounds for k=1:3
# Add kepler-drift differences, weighted by masses, to start of step:
#x[k,i] += mj*state[1+k]
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i], mj*state[1+k])
#x[k,j] -= mi*state[1+k]
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],-mi*state[1+k])
#v[k,i] += mj*state[4+k]
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], mj*state[4+k])
#v[k,j] -= mi*state[4+k]
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-mi*state[4+k])
end
# Compute Jacobian:
@inbounds for l=1:6, k=1:6
# Compute derivatives of x_i,v_i with respect to initial conditions:
jac_ij[ k, l] += mj*jac_kepler[k,l]
jac_ij[ k,7+l] -= mj*jac_kepler[k,l]
# Compute derivatives of x_j,v_j with respect to initial conditions:
jac_ij[7+k, l] -= mi*jac_kepler[k,l]
jac_ij[7+k,7+l] += mi*jac_kepler[k,l]
end
@inbounds for k=1:6
# Compute derivatives of x_i,v_i with respect to the masses:
jac_ij[ k, 7] = -mj*state[1+k]*mijinv + GNEWT*mj*jac_kepler[ k,7]
jac_ij[ k,14] = mi*state[1+k]*mijinv + GNEWT*mj*jac_kepler[ k,7]
# Compute derivatives of x_j,v_j with respect to the masses:
jac_ij[ 7+k, 7] = -mj*state[1+k]*mijinv - GNEWT*mi*jac_kepler[ k,7]
jac_ij[ 7+k,14] = mi*state[1+k]*mijinv - GNEWT*mi*jac_kepler[ k,7]
end
end
# The following lines are meant to compute dq/dt for kepler_driftij,
# but they currently contain an error (test doesn't pass in test_ah18.jl). [ ]
@inbounds for k=1:NDIM
# Define relative velocity and acceleration:
vij = state[1+NDIM+k]-state0[1+NDIM+k]
acc_ij = gm*state[1+k]/state[8]^3
# Position derivative, body i:
dqdt[ k] = mj*vij
# Velocity derivative, body i:
dqdt[ 3+k] = -mj*acc_ij
# Time derivative of mass is zero, so we skip this.
# Position derivative, body j:
dqdt[ 7+k] = -mi*vij
# Velocity derivative, body j:
dqdt[10+k] = mi*acc_ij
# Time derivative of mass is zero, so we skip this.
end
return
return
end
# Carries out a Kepler step and reverse drift for bodies i & j with compensated summation.
# Uses new version of the code with gamma in favor of s, and full auto-diff of Kepler step.
function kepler_driftij_gamma!(m::Array{T,1},x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T,drift_first::Bool) where {T <: Real}
x0 = zeros(T,NDIM) # x0 = positions of body i relative to j
v0 = zeros(T,NDIM) # v0 = velocities of body i relative to j
@inbounds for k=1:NDIM
x0[k] = x[k,i] - x[k,j]
v0[k] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
if gm == 0
# Do nothing
# for k=1:3
# x[k,i] += h*v[k,i]
# x[k,j] += h*v[k,j]
# end
else
# Compute differences in x & v over time step:
delxv = jac_delxv_gamma!(x0,v0,gm,h,drift_first)
# kepler_drift_step!(gm, h, state0, state,drift_first)
mijinv =1.0/(m[i] + m[j])
mi = m[i]*mijinv # Normalize the masses
mj = m[j]*mijinv
@inbounds for k=1:3
# Add kepler-drift differences, weighted by masses, to start of step:
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i], mj*delxv[k])
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],-mi*delxv[k])
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], mj*delxv[3+k])
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-mi*delxv[3+k])
end
end
return
end
# Carries out a Kepler step and reverse drift for bodies i & j, and computes Jacobian:
# Uses new version of the code with gamma in favor of s, and full auto-diff of Kepler step.
function kepler_driftij_gamma!(m::Array{T,1},x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T,jac_ij::Array{T,2},dqdt::Array{T,1},drift_first::Bool) where {T <: Real}
# Initial state:
x0 = zeros(T,NDIM) # x0 = positions of body i relative to j
v0 = zeros(T,NDIM) # v0 = velocities of body i relative to j
@inbounds for k=1:NDIM
x0[k] = x[k,i] - x[k,j]
v0[k] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
# jac_ij should be the Jacobian for going from (x_{0,i},v_{0,i},m_i) & (x_{0,j},v_{0,j},m_j)
# to (x_i,v_i,m_i) & (x_j,v_j,m_j), a 14x14 matrix for the 3-dimensional case.
# Fill with zeros for now:
#jac_ij .= eye(T,14)
fill!(jac_ij,zero(T))
if gm == 0
# Do nothing
# for k=1:3
# x[k,i] += h*v[k,i]
# x[k,j] += h*v[k,j]
# end
else
delxv = zeros(T,6)
jac_kepler = zeros(T,6,8)
jac_mass = zeros(T,6)
jac_delxv_gamma!(x0,v0,gm,h,drift_first,delxv,jac_kepler,jac_mass,false)
# kepler_drift_step!(gm, h, state0, state,jac_kepler,drift_first)
mijinv::T =one(T)/(m[i] + m[j])
mi::T = m[i]*mijinv # Normalize the masses
mj::T = m[j]*mijinv
@inbounds for k=1:3
# Add kepler-drift differences, weighted by masses, to start of step:
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i], mj*delxv[k])
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],-mi*delxv[k])
end
@inbounds for k=1:3
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], mj*delxv[3+k])
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-mi*delxv[3+k])
end
# Compute Jacobian:
@inbounds for l=1:6, k=1:6
# Compute derivatives of x_i,v_i with respect to initial conditions:
jac_ij[ k, l] += mj*jac_kepler[k,l]
jac_ij[ k,7+l] -= mj*jac_kepler[k,l]
# Compute derivatives of x_j,v_j with respect to initial conditions:
jac_ij[7+k, l] -= mi*jac_kepler[k,l]
jac_ij[7+k,7+l] += mi*jac_kepler[k,l]
end
@inbounds for k=1:6
# Compute derivatives of x_i,v_i with respect to the masses:
# println("Old dxv/dm_i: ",-mj*delxv[k]*mijinv + GNEWT*mj*jac_kepler[ k,7])
# jac_ij[ k, 7] = -mj*delxv[k]*mijinv + GNEWT*mj*jac_kepler[ k,7]
# println("New dx/dm_i: ",jac_mass[k]*m[j])
jac_ij[ k, 7] = jac_mass[k]*m[j]
jac_ij[ k,14] = mi*delxv[k]*mijinv + GNEWT*mj*jac_kepler[ k,7]
# Compute derivatives of x_j,v_j with respect to the masses:
jac_ij[ 7+k, 7] = -mj*delxv[k]*mijinv - GNEWT*mi*jac_kepler[ k,7]
# println("Old dxv/dm_j: ",mi*delxv[k]*mijinv - GNEWT*mi*jac_kepler[ k,7])
# jac_ij[ 7+k,14] = mi*delxv[k]*mijinv - GNEWT*mi*jac_kepler[ k,7]
# println("New dxv/dm_j: ",-jac_mass[k]*m[i])
jac_ij[ 7+k,14] = -jac_mass[k]*m[i]
end
end
# The following lines are meant to compute dq/dt for kepler_driftij,
# but they currently contain an error (test doesn't pass in test_ah18.jl). [ ]
@inbounds for k=1:6
# Position/velocity derivative, body i:
dqdt[ k] = mj*jac_kepler[k,8]
# Position/velocity derivative, body j:
dqdt[7+k] = -mi*jac_kepler[k,8]
end
return
end
# Carries out a Kepler step for bodies i & j
#function keplerij!(m::Array{Float64,1},x::Array{Float64,2},v::Array{Float64,2},i::Int64,j::Int64,h::Float64)
function keplerij!(m::Array{T,1},x::Array{T,2},v::Array{T,2},i::Int64,j::Int64,h::T) where {T <: Real}
# The state vector has: 1 time; 2-4 position; 5-7 velocity; 8 r0; 9 dr0dt; 10 beta; 11 s; 12 ds
# Initial state:
state0 = zeros(T,12)
# Final state (after a step):
state = zeros(T,12)
delx = zeros(T,NDIM)
delv = zeros(T,NDIM)
#println("Masses: ",i," ",j)
for k=1:NDIM
state0[1+k ] = x[k,i] - x[k,j]
state0[1+k+NDIM] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
if gm == 0
for k=1:NDIM
x[k,i] += h*v[k,i]
x[k,j] += h*v[k,j]
end
else
# predicted value of s
kepler_step!(gm, h, state0, state)
for k=1:NDIM
delx[k] = state[1+k] - state0[1+k]
delv[k] = state[1+NDIM+k] - state0[1+NDIM+k]
end
# Advance center of mass:
# Compute COM coords:
mijinv =1.0/(m[i] + m[j])
vcm = zeros(T,NDIM)
for k=1:NDIM
vcm[k] = (m[i]*v[k,i] + m[j]*v[k,j])*mijinv
end
centerm!(m,mijinv,x,v,vcm,delx,delv,i,j,h)
end
return
end
# Carries out a Kepler step for bodies i & j with compensated summation:
function keplerij!(m::Array{T,1},x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T) where {T <: Real}
# The state vector has: 1 time; 2-4 position; 5-7 velocity; 8 r0; 9 dr0dt; 10 beta; 11 s; 12 ds
# Initial state:
state0 = zeros(T,12)
# Final state (after a step):
state = zeros(T,12)
delx = zeros(T,NDIM)
delv = zeros(T,NDIM)
#println("Masses: ",i," ",j)
for k=1:NDIM
state0[1+k ] = x[k,i] - x[k,j]
state0[1+k+NDIM] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
if gm == 0
for k=1:NDIM
#x[k,i] += h*v[k,i]
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],h*v[k,i])
#x[k,j] += h*v[k,j]
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],h*v[k,j])
end
else
# predicted value of s
kepler_step!(gm, h, state0, state)
for k=1:NDIM
delx[k] = state[1+k] - state0[1+k]
delv[k] = state[1+NDIM+k] - state0[1+NDIM+k]
end
# Advance center of mass:
# Compute COM coords:
mijinv =1.0/(m[i] + m[j])
vcm = zeros(T,NDIM)
for k=1:NDIM
vcm[k] = (m[i]*v[k,i] + m[j]*v[k,j])*mijinv
end
centerm!(m,mijinv,x,v,xerror,verror,vcm,delx,delv,i,j,h)
end
return
end
# Carries out a Kepler step for bodies i & j with dqdt and Jacobian:
function keplerij!(m::Array{T,1},x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T,jac_ij::Array{T,2},dqdt::Array{T,1},d::Derivatives{T}) where {T <: Real}
# The state vector has: 1 time; 2-4 position; 5-7 velocity; 8 r0; 9 dr0dt; 10 beta; 11 s; 12 ds
# Initial state:
state0 = zeros(T,12)
# Final state (after a step):
state = zeros(T,12)
delx = zeros(T,NDIM)
delv = zeros(T,NDIM)
# jac_ij should be the Jacobian for going from (x_{0,i},v_{0,i},m_i) & (x_{0,j},v_{0,j},m_j)
# to (x_i,v_i,m_i) & (x_j,v_j,m_j), a 14x14 matrix for the 3-dimensional case.
# Fill with zeros for now:
fill!(jac_ij,0.0)
for k=1:NDIM
state0[1+k ] = x[k,i] - x[k,j]
state0[1+k+NDIM] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
# The following jacobian is just computed for the Keplerian coordinates (i.e. doesn't include
# center-of-mass motion, or scale to motion of bodies about their common center of mass):
jac_kepler = zeros(T,7,7)
kepler_step!(gm, h, state0, state, jac_kepler,d)
for k=1:NDIM
delx[k] = state[1+k] - state0[1+k]
delv[k] = state[1+NDIM+k] - state0[1+NDIM+k]
end
# Compute COM coords:
mijinv =1.0/(m[i] + m[j])
xcm = zeros(T,NDIM)
vcm = zeros(T,NDIM)
mi = m[i]*mijinv # Normalize the masses
mj = m[j]*mijinv
#println("Masses: ",i," ",j)
for k=1:NDIM
xcm[k] = mi*x[k,i] + mj*x[k,j]
vcm[k] = mi*v[k,i] + mj*v[k,j]
end
# Compute the Jacobian:
jac_ij[ 7, 7] = 1.0 # the masses don't change with time!
jac_ij[14,14] = 1.0
for k=1:NDIM
jac_ij[ k, k] = mi
jac_ij[ k, 3+k] = h*mi
jac_ij[ k, 7+k] = mj
jac_ij[ k,10+k] = h*mj
jac_ij[ 3+k, 3+k] = mi
jac_ij[ 3+k,10+k] = mj
jac_ij[ 7+k, k] = mi
jac_ij[ 7+k, 3+k] = h*mi
jac_ij[ 7+k, 7+k] = mj
jac_ij[ 7+k,10+k] = h*mj
jac_ij[10+k, 3+k] = mi
jac_ij[10+k,10+k] = mj
end
for l=1:NDIM, k=1:NDIM
# Compute derivatives of \delta x_i with respect to initial conditions:
jac_ij[ k, l] += mj*jac_kepler[ k, l]
jac_ij[ k, 3+l] += mj*jac_kepler[ k,3+l]
jac_ij[ k, 7+l] -= mj*jac_kepler[ k, l]
jac_ij[ k,10+l] -= mj*jac_kepler[ k,3+l]
# Compute derivatives of \delta v_i with respect to initial conditions:
jac_ij[ 3+k, l] += mj*jac_kepler[3+k, l]
jac_ij[ 3+k, 3+l] += mj*jac_kepler[3+k,3+l]
jac_ij[ 3+k, 7+l] -= mj*jac_kepler[3+k, l]
jac_ij[ 3+k,10+l] -= mj*jac_kepler[3+k,3+l]
# Compute derivatives of \delta x_j with respect to initial conditions:
jac_ij[ 7+k, l] -= mi*jac_kepler[ k, l]
jac_ij[ 7+k, 3+l] -= mi*jac_kepler[ k,3+l]
jac_ij[ 7+k, 7+l] += mi*jac_kepler[ k, l]
jac_ij[ 7+k,10+l] += mi*jac_kepler[ k,3+l]
# Compute derivatives of \delta v_j with respect to initial conditions:
jac_ij[10+k, l] -= mi*jac_kepler[3+k, l]
jac_ij[10+k, 3+l] -= mi*jac_kepler[3+k,3+l]
jac_ij[10+k, 7+l] += mi*jac_kepler[3+k, l]
jac_ij[10+k,10+l] += mi*jac_kepler[3+k,3+l]
end
for k=1:NDIM
# Compute derivatives of \delta x_i with respect to the masses:
jac_ij[ k, 7] = (x[k,i]+h*v[k,i]-xcm[k]-h*vcm[k]-mj*state[1+k])*mijinv + GNEWT*mj*jac_kepler[ k,7]
jac_ij[ k,14] = (x[k,j]+h*v[k,j]-xcm[k]-h*vcm[k]+mi*state[1+k])*mijinv + GNEWT*mj*jac_kepler[ k,7]
# Compute derivatives of \delta v_i with respect to the masses:
jac_ij[ 3+k, 7] = (v[k,i]-vcm[k]-mj*state[4+k])*mijinv + GNEWT*mj*jac_kepler[3+k,7]
jac_ij[ 3+k,14] = (v[k,j]-vcm[k]+mi*state[4+k])*mijinv + GNEWT*mj*jac_kepler[3+k,7]
# Compute derivatives of \delta x_j with respect to the masses:
jac_ij[ 7+k, 7] = (x[k,i]+h*v[k,i]-xcm[k]-h*vcm[k]-mj*state[1+k])*mijinv - GNEWT*mi*jac_kepler[ k,7]
jac_ij[ 7+k,14] = (x[k,j]+h*v[k,j]-xcm[k]-h*vcm[k]+mi*state[1+k])*mijinv - GNEWT*mi*jac_kepler[ k,7]
# Compute derivatives of \delta v_j with respect to the masses:
jac_ij[10+k, 7] = (v[k,i]-vcm[k]-mj*state[4+k])*mijinv - GNEWT*mi*jac_kepler[3+k,7]
jac_ij[10+k,14] = (v[k,j]-vcm[k]+mi*state[4+k])*mijinv - GNEWT*mi*jac_kepler[3+k,7]
end
# Advance center of mass & individual Keplerian motions:
centerm!(m,mijinv,x,v,xerror,verror,vcm,delx,delv,i,j,h)
# Compute the time derivatives:
for k=1:NDIM
# Define relative velocity and acceleration:
vij = state[1+NDIM+k]
acc_ij = gm*state[1+k]/state[8]^3
# Position derivative, body i:
dqdt[ k] = vcm[k] + mj*vij
# Velocity derivative, body i:
dqdt[ 3+k] = -mj*acc_ij
# Time derivative of mass is zero, so we skip this.
# Position derivative, body j:
dqdt[ 7+k] = vcm[k] - mi*vij
# Velocity derivative, body j:
dqdt[10+k] = mi*acc_ij
# Time derivative of mass is zero, so we skip this.
end
return
end
# Drifts all particles:
#function drift!(x::Array{Float64,2},v::Array{Float64,2},h::Float64,n::Int64)
function drift!(x::Array{T,2},v::Array{T,2},h::T,n::Int64) where {T <: Real}
@inbounds for i=1:n, j=1:NDIM
x[j,i] += h*v[j,i]
end
return
end
# Drifts all particles with compensated summation:
#function drift!(x::Array{Float64,2},v::Array{Float64,2},h::Float64,n::Int64)
function drift!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,n::Int64) where {T <: Real}
@inbounds for i=1:n, j=1:NDIM
#x[j,i] += h*v[j,i]
x[j,i],xerror[j,i] = comp_sum(x[j,i],xerror[j,i],h*v[j,i])
end
return
end
# Drifts all particles:
function drift!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,n::Int64,jac_step::Array{T,2},jac_error::Array{T,2}) where {T <: Real}
indi = 0
@inbounds for i=1:n
indi = (i-1)*7
for j=1:NDIM
# x[j,i] += h*v[j,i]
x[j,i],xerror[j,i] = comp_sum(x[j,i],xerror[j,i],h*v[j,i])
end
# Now for Jacobian:
for k=1:7*n, j=1:NDIM
#jac_step[indi+j,k] += h*jac_step[indi+3+j,k]
jac_step[indi+j,k],jac_error[indi+j,k] = comp_sum(jac_step[indi+j,k],jac_error[indi+j,k],h*jac_step[indi+3+j,k])
end
end
return
end
# Computes "fast" kicks for pairs of bodies in lieu of -drift+Kepler:
function kickfast!(x::Array{T,2},v::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
rij = zeros(T,3)
@inbounds for i=1:n-1
for j = i+1:n
if pair[i,j]
r2 = 0.0
for k=1:3
rij[k] = x[k,i] - x[k,j]
r2 += rij[k]^2
end
r3_inv = 1.0/(r2*sqrt(r2))
for k=1:3
fac = h*GNEWT*rij[k]*r3_inv
v[k,i] -= m[j]*fac
v[k,j] += m[i]*fac
end
end
end
end
return
end
# Version of kickfast with compensated summation:
# Computes "fast" kicks for pairs of bodies in lieu of -drift+Kepler with compensated summation:
function kickfast!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
rij = zeros(T,3)
@inbounds for i=1:n-1
for j = i+1:n
if pair[i,j]
r2 = 0.0
for k=1:3
rij[k] = x[k,i] - x[k,j]
r2 += rij[k]^2
end
r3_inv = 1.0/(r2*sqrt(r2))
for k=1:3
fac = h*GNEWT*rij[k]*r3_inv
# v[k,i] -= m[j]*fac
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],-m[j]*fac)
#v[k,j] += m[i]*fac
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j], m[i]*fac)
end
end
end
end
return
end
# Version of kickfast which computes the Jacobian with compensated summation:
function kickfast!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,jac_step::Array{T,2},
dqdt_kick::Array{T,1},pair::Array{Bool,2}) where {T <: Real}
rij = zeros(T,3)
# Getting rid of identity since we will add that back in in calling routines:
fill!(jac_step,zero(T))
#jac_step.=eye(T,7*n)
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
indj = (j-1)*7
if pair[i,j]
for k=1:3
rij[k] = x[k,i] - x[k,j]
end
r2inv = 1.0/(rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3])
r3inv = r2inv*sqrt(r2inv)
for k=1:3
fac = h*GNEWT*rij[k]*r3inv
# Apply impulses:
#v[k,i] -= m[j]*fac
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],-m[j]*fac)
#v[k,j] += m[i]*fac
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j], m[i]*fac)
# Compute time derivative:
dqdt_kick[indi+3+k] -= m[j]*fac/h
dqdt_kick[indj+3+k] += m[i]*fac/h
# Computing the derivative
# Mass derivative of acceleration vector (10/6/17 notes):
# Impulse of ith particle depends on mass of jth particle:
jac_step[indi+3+k,indj+7] -= fac
# Impulse of jth particle depends on mass of ith particle:
jac_step[indj+3+k,indi+7] += fac
# x derivative of acceleration vector:
fac *= 3.0*r2inv
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
jac_step[indi+3+k,indi+p] += fac*m[j]*rij[p]
jac_step[indi+3+k,indj+p] -= fac*m[j]*rij[p]
jac_step[indj+3+k,indj+p] += fac*m[i]*rij[p]
jac_step[indj+3+k,indi+p] -= fac*m[i]*rij[p]
end
# Final term has no dot product, so just diagonal:
fac = h*GNEWT*r3inv
jac_step[indi+3+k,indi+k] -= fac*m[j]
jac_step[indi+3+k,indj+k] += fac*m[j]
jac_step[indj+3+k,indj+k] -= fac*m[i]
jac_step[indj+3+k,indi+k] += fac*m[i]
end
end
end
end
return
end
# Computes the 4th-order correction:
function phisalpha!(x::Array{T,2},v::Array{T,2},h::T,m::Array{T,1},alpha::T,n::Int64,pair::Array{Bool,2}) where {T <: Real}
#function [v] = phisalpha(x,v,h,m,alpha,pair)
#n = size(m,2);
a = zeros(T,3,n)
rij = zeros(T,3)
aij = zeros(T,3)
coeff = alpha*h^3/96*2*GNEWT
fac = zero(T) ; fac1 = zero(T); fac2 = zero(T); r1 = zero(T); r2 = zero(T); r3 = zero(T)
@inbounds for i=1:n-1
for j = i+1:n
if ~pair[i,j] # correction for Kepler pairs
for k=1:3
rij[k] = x[k,i] - x[k,j]
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r3 = r2*sqrt(r2)
for k=1:3
fac = GNEWT*rij[k]/r3
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
end
end
end
end
# Next, compute \tilde g_i acceleration vector (this is rewritten
# slightly to avoid reference to \tilde a_i):
@inbounds for i=1:n-1
for j=i+1:n
if ~pair[i,j] # correction for Kepler pairs
for k=1:3
aij[k] = a[k,i] - a[k,j]
# aij[k] = 0.0
rij[k] = x[k,i] - x[k,j]
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r1 = sqrt(r2)
ardot = aij[1]*rij[1]+aij[2]*rij[2]+aij[3]*rij[3]
fac1 = coeff/r1^5
fac2 = (2*GNEWT*(m[i]+m[j])/r1 + 3*ardot)
for k=1:3
# fac = coeff/r1^5*(rij[k]*(2*GNEWT*(m[i]+m[j])/r1 + 3*ardot) - r2*aij[k])
fac = fac1*(rij[k]*fac2- r2*aij[k])
v[k,i] += m[j]*fac
v[k,j] -= m[i]*fac
end
end
end
end
return
end
# Computes the 4th-order correction with compensated summation:
function phisalpha!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},alpha::T,n::Int64,pair::Array{Bool,2}) where {T <: Real}
#function [v] = phisalpha(x,v,h,m,alpha,pair)
#n = size(m,2);
a = zeros(T,3,n)
rij = zeros(T,3)
aij = zeros(T,3)
coeff = alpha*h^3/96*2*GNEWT
fac = zero(T); fac1 = zero(T); fac2 = zero(T); r1 = zero(T); r2 = zero(T); r3 = zero(T)
@inbounds for i=1:n-1
for j = i+1:n
if ~pair[i,j] # correction for Kepler pairs
for k=1:3
rij[k] = x[k,i] - x[k,j]
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r3 = r2*sqrt(r2)
for k=1:3
fac = GNEWT*rij[k]/r3
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
end
end
end
end
# Next, compute \tilde g_i acceleration vector (this is rewritten
# slightly to avoid reference to \tilde a_i):
@inbounds for i=1:n-1
for j=i+1:n
if ~pair[i,j] # correction for Kepler pairs
for k=1:3
aij[k] = a[k,i] - a[k,j]
# aij[k] = 0.0
rij[k] = x[k,i] - x[k,j]
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r1 = sqrt(r2)
ardot = aij[1]*rij[1]+aij[2]*rij[2]+aij[3]*rij[3]
fac1 = coeff/r1^5
fac2 = (2*GNEWT*(m[i]+m[j])/r1 + 3*ardot)
for k=1:3
# fac = coeff/r1^5*(rij[k]*(2*GNEWT*(m[i]+m[j])/r1 + 3*ardot) - r2*aij[k])
fac = fac1*(rij[k]*fac2- r2*aij[k])
#v[k,i] += m[j]*fac
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], m[j]*fac)
#v[k,j] -= m[i]*fac
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*fac)
end
end
end
end
return
end
# Computes the 4th-order correction with Jacobian, dq/dt, and compensated summation:
function phisalpha!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},
alpha::T,n::Int64,jac_step::Array{T,2},dqdt_phi::Array{T,1},pair::Array{Bool,2}) where {T <: Real}
#function [v] = phisalpha(x,v,h,m,alpha,pair)
#n = size(m,2);
a = zeros(T,3,n)
dadq = zeros(T,3,n,4,n) # There is no velocity dependence
dotdadq = zeros(T,4,n) # There is no velocity dependence
rij = zeros(T,3)
aij = zeros(T,3)
coeff = alpha*h^3/96*2*GNEWT
fac = 0.0; fac1 = 0.0; fac2 = 0.0; fac3 = 0.0; r1 = 0.0; r2 = 0.0; r3 = 0.0
#jac_step.=eye(T,7*n)
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if ~pair[i,j] # correction for Kepler pairs
indj = (j-1)*7
for k=1:3
rij[k] = x[k,i] - x[k,j]
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r3 = r2*sqrt(r2)
for k=1:3
fac = GNEWT*rij[k]/r3
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
# Mass derivative of acceleration vector (10/6/17 notes):
# Since there is no velocity dependence, this is fourth parameter.
# Acceleration of ith particle depends on mass of jth particle:
dadq[k,i,4,j] -= fac
dadq[k,j,4,i] += fac
# x derivative of acceleration vector:
fac *= 3.0/r2
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
dadq[k,i,p,i] += fac*m[j]*rij[p]
dadq[k,i,p,j] -= fac*m[j]*rij[p]
dadq[k,j,p,j] += fac*m[i]*rij[p]
dadq[k,j,p,i] -= fac*m[i]*rij[p]
end
# Final term has no dot product, so just diagonal:
fac = GNEWT/r3
dadq[k,i,k,i] -= fac*m[j]
dadq[k,i,k,j] += fac*m[j]
dadq[k,j,k,j] -= fac*m[i]
dadq[k,j,k,i] += fac*m[i]
end
end
end
end
# Next, compute \tilde g_i acceleration vector (this is rewritten
# slightly to avoid reference to \tilde a_i):
# Note that jac_step[(i-1)*7+k,(j-1)*7+p] is the derivative of the kth coordinate
# of planet i with respect to the pth coordinate of planet j.
indi = 0; indj=0; indd = 0
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if ~pair[i,j] # correction for Kepler pairs
indj = (j-1)*7
for k=1:3
aij[k] = a[k,i] - a[k,j]
# aij[k] = 0.0
rij[k] = x[k,i] - x[k,j]
end
# Compute dot product of r_ij with \delta a_ij:
fill!(dotdadq,0.0)
@inbounds for d=1:n, p=1:4, k=1:3
dotdadq[p,d] += rij[k]*(dadq[k,i,p,d]-dadq[k,j,p,d])
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r1 = sqrt(r2)
ardot = aij[1]*rij[1]+aij[2]*rij[2]+aij[3]*rij[3]
fac1 = coeff/r1^5
fac2 = (2*GNEWT*(m[i]+m[j])/r1 + 3*ardot)
for k=1:3
# fac = coeff/r1^5*(rij[k]*(2*GNEWT*(m[i]+m[j])/r1 + 3*ardot) - r2*aij[k])
fac = fac1*(rij[k]*fac2- r2*aij[k])
#v[k,i] += m[j]*fac
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], m[j]*fac)
#v[k,j] -= m[i]*fac
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*fac)
# Compute time derivative:
dqdt_phi[indi+3+k] += 3/h*m[j]*fac
dqdt_phi[indj+3+k] -= 3/h*m[i]*fac
# Mass derivative (first part is easy):
jac_step[indi+3+k,indj+7] += fac
jac_step[indj+3+k,indi+7] -= fac
# Position derivatives:
fac *= 5.0/r2
for p=1:3
jac_step[indi+3+k,indi+p] -= fac*m[j]*rij[p]
jac_step[indi+3+k,indj+p] += fac*m[j]*rij[p]
jac_step[indj+3+k,indj+p] -= fac*m[i]*rij[p]
jac_step[indj+3+k,indi+p] += fac*m[i]*rij[p]
end
# Second mass derivative:
fac = 2*GNEWT*fac1*rij[k]/r1
jac_step[indi+3+k,indi+7] += fac*m[j]
jac_step[indi+3+k,indj+7] += fac*m[j]
jac_step[indj+3+k,indj+7] -= fac*m[i]
jac_step[indj+3+k,indi+7] -= fac*m[i]
# (There's also a mass term in dadq [x]. See below.)
# Diagonal position terms:
fac = fac1*fac2
jac_step[indi+3+k,indi+k] += fac*m[j]
jac_step[indi+3+k,indj+k] -= fac*m[j]
jac_step[indj+3+k,indj+k] += fac*m[i]
jac_step[indj+3+k,indi+k] -= fac*m[i]
# Dot product \delta rij terms:
fac = -2*fac1*(rij[k]*GNEWT*(m[i]+m[j])/(r2*r1)+aij[k])
for p=1:3
fac3 = fac*rij[p] + fac1*3.0*rij[k]*aij[p]
jac_step[indi+3+k,indi+p] += m[j]*fac3
jac_step[indi+3+k,indj+p] -= m[j]*fac3
jac_step[indj+3+k,indj+p] += m[i]*fac3
jac_step[indj+3+k,indi+p] -= m[i]*fac3
end
# Diagonal acceleration terms:
fac = -fac1*r2
# Duoh. For dadq, have to loop over all other parameters!
@inbounds for d=1:n
indd = (d-1)*7
for p=1:3
jac_step[indi+3+k,indd+p] += fac*m[j]*(dadq[k,i,p,d]-dadq[k,j,p,d])
jac_step[indj+3+k,indd+p] -= fac*m[i]*(dadq[k,i,p,d]-dadq[k,j,p,d])
end
# Don't forget mass-dependent term:
jac_step[indi+3+k,indd+7] += fac*m[j]*(dadq[k,i,4,d]-dadq[k,j,4,d])
jac_step[indj+3+k,indd+7] -= fac*m[i]*(dadq[k,i,4,d]-dadq[k,j,4,d])
end
# Now, for the final term: (\delta a_ij . r_ij ) r_ij
fac = 3.0*fac1*rij[k]
@inbounds for d=1:n
indd = (d-1)*7
for p=1:3
jac_step[indi+3+k,indd+p] += fac*m[j]*dotdadq[p,d]
jac_step[indj+3+k,indd+p] -= fac*m[i]*dotdadq[p,d]
end
jac_step[indi+3+k,indd+7] += fac*m[j]*dotdadq[4,d]
jac_step[indj+3+k,indd+7] -= fac*m[i]*dotdadq[4,d]
end
end
end
end
end
return
end
# Computes correction for pairs which are kicked:
function phic!(x::Array{T,2},v::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
a = zeros(T,3,n)
rij = zeros(T,3)
aij = zeros(T,3)
@inbounds for i=1:n-1, j = i+1:n
if pair[i,j] # kick group
r2 = 0.0
for k=1:3
rij[k] = x[k,i] - x[k,j]
r2 += rij[k]^2
end
r3_inv = 1.0/(r2*sqrt(r2))
for k=1:3
fac = GNEWT*rij[k]*r3_inv
v[k,i] -= m[j]*fac*2h/3
v[k,j] += m[i]*fac*2h/3
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
end
end
end
coeff = h^3/36*GNEWT
@inbounds for i=1:n-1 ,j=i+1:n
if pair[i,j] # kick group
for k=1:3
aij[k] = a[k,i] - a[k,j]
rij[k] = x[k,i] - x[k,j]
end
r2 = dot(rij,rij)
r5inv = 1.0/(r2^2*sqrt(r2))
ardot = dot(aij,rij)
for k=1:3
fac = coeff*r5inv*(rij[k]*3*ardot-r2*aij[k])
v[k,i] += m[j]*fac
v[k,j] -= m[i]*fac
end
end
end
return
end
# Computes correction for pairs which are kicked:
function phic!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
a = zeros(T,3,n)
rij = zeros(T,3)
aij = zeros(T,3)
@inbounds for i=1:n-1, j = i+1:n
if pair[i,j] # kick group
r2 = 0.0
for k=1:3
rij[k] = x[k,i] - x[k,j]
r2 += rij[k]^2
end
r3_inv = 1.0/(r2*sqrt(r2))
for k=1:3
fac = GNEWT*rij[k]*r3_inv
facv = fac*2*h/3
#v[k,i] -= m[j]*facv
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],-m[j]*facv)
#v[k,j] += m[i]*facv
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],m[i]*facv)
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
end
end
end
coeff = h^3/36*GNEWT
@inbounds for i=1:n-1 ,j=i+1:n
if pair[i,j] # kick group
for k=1:3
aij[k] = a[k,i] - a[k,j]
rij[k] = x[k,i] - x[k,j]
end
r2 = dot(rij,rij)
r5inv = 1.0/(r2^2*sqrt(r2))
ardot = dot(aij,rij)
for k=1:3
fac = coeff*r5inv*(rij[k]*3*ardot-r2*aij[k])
#v[k,i] += m[j]*fac
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],m[j]*fac)
#v[k,j] -= m[i]*fac
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*fac)
end
end
end
return
end
# Computes correction for pairs which are kicked, with Jacobian, and computes dq/dt:
function phic!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,jac_step::Array{T,2},dqdt_phi::Array{T,1},pair::Array{Bool,2}) where {T <: Real}
a = zeros(T,3,n)
rij = zeros(T,3)
aij = zeros(T,3)
dadq = zeros(T,3,n,4,n) # There is no velocity dependence
dotdadq = zeros(T,4,n) # There is no velocity dependence
# Set jac_step to zeros:
#jac_step.=eye(T,7*n)
fill!(jac_step,zero(T))
fac = 0.0; fac1 = 0.0; fac2 = 0.0; fac3 = 0.0; r1 = 0.0; r2 = 0.0; r3 = 0.0
coeff = h^3/36*GNEWT
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if pair[i,j]
indj = (j-1)*7
for k=1:3
rij[k] = x[k,i] - x[k,j]
end
r2inv = inv(dot(rij,rij))
r3inv = r2inv*sqrt(r2inv)
for k=1:3
# Apply impulses:
fac = GNEWT*rij[k]*r3inv
facv = fac*2*h/3
#v[k,i] -= m[j]*facv
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],-m[j]*facv)
#v[k,j] += m[i]*facv
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],m[i]*facv)
# Compute time derivative:
dqdt_phi[indi+3+k] -= 3/h*m[j]*facv
dqdt_phi[indj+3+k] += 3/h*m[i]*facv
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
# Impulse of ith particle depends on mass of jth particle:
jac_step[indi+3+k,indj+7] -= facv
# Impulse of jth particle depends on mass of ith particle:
jac_step[indj+3+k,indi+7] += facv
# x derivative of acceleration vector:
facv *= 3.0*r2inv
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
jac_step[indi+3+k,indi+p] += facv*m[j]*rij[p]
jac_step[indi+3+k,indj+p] -= facv*m[j]*rij[p]
jac_step[indj+3+k,indj+p] += facv*m[i]*rij[p]
jac_step[indj+3+k,indi+p] -= facv*m[i]*rij[p]
end
# Final term has no dot product, so just diagonal:
facv = 2h/3*GNEWT*r3inv
jac_step[indi+3+k,indi+k] -= facv*m[j]
jac_step[indi+3+k,indj+k] += facv*m[j]
jac_step[indj+3+k,indj+k] -= facv*m[i]
jac_step[indj+3+k,indi+k] += facv*m[i]
# Mass derivative of acceleration vector (10/6/17 notes):
# Since there is no velocity dependence, this is fourth parameter.
# Acceleration of ith particle depends on mass of jth particle:
dadq[k,i,4,j] -= fac
dadq[k,j,4,i] += fac
# x derivative of acceleration vector:
fac *= 3.0*r2inv
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
dadq[k,i,p,i] += fac*m[j]*rij[p]
dadq[k,i,p,j] -= fac*m[j]*rij[p]
dadq[k,j,p,j] += fac*m[i]*rij[p]
dadq[k,j,p,i] -= fac*m[i]*rij[p]
end
# Final term has no dot product, so just diagonal:
fac = GNEWT*r3inv
dadq[k,i,k,i] -= fac*m[j]
dadq[k,i,k,j] += fac*m[j]
dadq[k,j,k,j] -= fac*m[i]
dadq[k,j,k,i] += fac*m[i]
end
end
end
end
# Next, compute g_i acceleration vector.
# Note that jac_step[(i-1)*7+k,(j-1)*7+p] is the derivative of the kth coordinate
# of planet i with respect to the pth coordinate of planet j.
indi = 0; indj=0; indd = 0
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if pair[i,j] # correction for Kepler pairs
indj = (j-1)*7
for k=1:3
aij[k] = a[k,i] - a[k,j]
rij[k] = x[k,i] - x[k,j]
end
# Compute dot product of r_ij with \delta a_ij:
fill!(dotdadq,0.0)
@inbounds for d=1:n, p=1:4, k=1:3
dotdadq[p,d] += rij[k]*(dadq[k,i,p,d]-dadq[k,j,p,d])
end
r2 = dot(rij,rij)
r1 = sqrt(r2)
ardot = dot(aij,rij)
fac1 = coeff/r1^5
fac2 = 3*ardot
for k=1:3
fac = fac1*(rij[k]*fac2- r2*aij[k])
#v[k,i] += m[j]*fac
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],m[j]*fac)
#v[k,j] -= m[i]*fac
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*fac)
# Mass derivative (first part is easy):
jac_step[indi+3+k,indj+7] += fac
jac_step[indj+3+k,indi+7] -= fac
# Position derivatives:
fac *= 5.0/r2
for p=1:3
jac_step[indi+3+k,indi+p] -= fac*m[j]*rij[p]
jac_step[indi+3+k,indj+p] += fac*m[j]*rij[p]
jac_step[indj+3+k,indj+p] -= fac*m[i]*rij[p]
jac_step[indj+3+k,indi+p] += fac*m[i]*rij[p]
end
# Diagonal position terms:
fac = fac1*fac2
jac_step[indi+3+k,indi+k] += fac*m[j]
jac_step[indi+3+k,indj+k] -= fac*m[j]
jac_step[indj+3+k,indj+k] += fac*m[i]
jac_step[indj+3+k,indi+k] -= fac*m[i]
# Dot product \delta rij terms:
fac = -2*fac1*aij[k]
for p=1:3
fac3 = fac*rij[p] + fac1*3.0*rij[k]*aij[p]
jac_step[indi+3+k,indi+p] += m[j]*fac3
jac_step[indi+3+k,indj+p] -= m[j]*fac3
jac_step[indj+3+k,indj+p] += m[i]*fac3
jac_step[indj+3+k,indi+p] -= m[i]*fac3
end
# Diagonal acceleration terms:
fac = -fac1*r2
# Duoh. For dadq, have to loop over all other parameters!
@inbounds for d=1:n
indd = (d-1)*7
for p=1:3
jac_step[indi+3+k,indd+p] += fac*m[j]*(dadq[k,i,p,d]-dadq[k,j,p,d])
jac_step[indj+3+k,indd+p] -= fac*m[i]*(dadq[k,i,p,d]-dadq[k,j,p,d])
end
# Don't forget mass-dependent term:
jac_step[indi+3+k,indd+7] += fac*m[j]*(dadq[k,i,4,d]-dadq[k,j,4,d])
jac_step[indj+3+k,indd+7] -= fac*m[i]*(dadq[k,i,4,d]-dadq[k,j,4,d])
end
# Now, for the final term: (\delta a_ij . r_ij ) r_ij
fac = 3.0*fac1*rij[k]
@inbounds for d=1:n
indd = (d-1)*7
for p=1:3
jac_step[indi+3+k,indd+p] += fac*m[j]*dotdadq[p,d]
jac_step[indj+3+k,indd+p] -= fac*m[i]*dotdadq[p,d]
end
jac_step[indi+3+k,indd+7] += fac*m[j]*dotdadq[4,d]
jac_step[indj+3+k,indd+7] -= fac*m[i]*dotdadq[4,d]
end
end
end
end
end
return
end
# Carries out the AH18 mapping:
function ah18!(x::Array{T,2},v::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
# New version of solver that consolidates keplerij and driftij, and sets
# alpha = 0:
h2 = 0.5*h
drift!(x,v,h2,n)
#kickfast!(x,v,h2,m,n,pair)
kickfast!(x,v,h/6,m,n,pair)
@inbounds for i=1:n-1
for j=i+1:n
if ~pair[i,j]
kepler_driftij!(m,x,v,i,j,h2,true)
end
end
end
# Missing phic here [ ]
phic!(x,v,h,m,n,pair)
phisalpha!(x,v,h,m,convert(T,2),n,pair)
for i=n-1:-1:1
for j=n:-1:i+1
if ~pair[i,j]
kepler_driftij!(m,x,v,i,j,h2,false)
end
end
end
#kickfast!(x,v,h2,m,n,pair)
kickfast!(x,v,h/6,m,n,pair)
drift!(x,v,h2,n)
return
end
# Carries out the AH18 mapping with compensated summation:
function ah18!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
# New version of solver that consolidates keplerij and driftij, and sets
# alpha = 0:
h2 = 0.5*h
drift!(x,v,xerror,verror,h2,n)
#kickfast!(x,v,xerror,verror,h2,m,n,pair)
kickfast!(x,v,xerror,verror,h/6,m,n,pair)
@inbounds for i=1:n-1
for j=i+1:n
if ~pair[i,j]
# kepler_driftij!(m,x,v,xerror,verror,i,j,h2,true)
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,true)
end
end
end
# Missing phic here [ ]
phic!(x,v,xerror,verror,h,m,n,pair)
phisalpha!(x,v,xerror,verror,h,m,convert(T,2),n,pair)
for i=n-1:-1:1
for j=n:-1:i+1
if ~pair[i,j]
# kepler_driftij!(m,x,v,xerror,verror,i,j,h2,false)
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,false)
end
end
end
#kickfast!(x,v,xerror,verror,h2,m,n,pair)
kickfast!(x,v,xerror,verror,h/6,m,n,pair)
drift!(x,v,xerror,verror,h2,n)
return
end
# Carries out the AH18 mapping & computes the Jacobian:
function ah18!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},
h::T,m::Array{T,1},n::Int64,jac_step::Array{T,2},jac_error::Array{T,2},pair::Array{Bool,2},d::Derivatives{T}) where {T <: Real}
zilch = zero(T); uno = one(T); half = convert(T,0.5); two = convert(T,2.0)
h2 = half*h
sevn = 7*n
jac_phi = zeros(T,sevn,sevn)
jac_kick = zeros(T,sevn,sevn)
jac_copy = zeros(T,sevn,sevn)
jac_ij = zeros(T,14,14)
dqdt_ij = zeros(T,14)
dqdt_phi = zeros(T,sevn)
dqdt_kick = zeros(T,sevn)
jac_tmp1 = zeros(T,14,sevn)
jac_tmp2 = zeros(T,14,sevn)
jac_err1 = zeros(T,14,sevn)
# Edit this routine to do compensated summation for Jacobian [x]
drift!(x,v,xerror,verror,h2,n,jac_step,jac_error)
#kickfast!(x,v,h2,m,n,jac_kick,dqdt_kick,pair)
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
# Multiply Jacobian from kick step:
if T == BigFloat
jac_copy .= *(jac_kick,jac_step)
else
BLAS.gemm!('N','N',uno,jac_kick,jac_step,zilch,jac_copy)
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(jac_step,jac_error,jac_copy)
indi = 0; indj = 0
@inbounds for i=1:n-1
indi = (i-1)*7
@inbounds for j=i+1:n
indj = (j-1)*7
if ~pair[i,j] # Check to see if kicks have not been applied
# kepler_driftij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,true)
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,true)
# Pick out indices for bodies i & j:
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[k1,k2] = jac_step[ indi+k1,k2]
jac_err1[k1,k2] = jac_error[indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[7+k1,k2] = jac_step[ indj+k1,k2]
jac_err1[7+k1,k2] = jac_error[indj+k1,k2]
end
# Carry out multiplication on the i/j components of matrix:
if T == BigFloat
jac_tmp2 .= *(jac_ij,jac_tmp1)
else
BLAS.gemm!('N','N',uno,jac_ij,jac_tmp1,zilch,jac_tmp2)
end
# Add back in the Jacobian with compensated summation:
comp_sum_matrix!(jac_tmp1,jac_err1,jac_tmp2)
# Copy back to the Jacobian:
@inbounds for k2=1:sevn, k1=1:7
jac_step[ indi+k1,k2]=jac_tmp1[k1,k2]
jac_error[indi+k1,k2]=jac_err1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_step[ indj+k1,k2]=jac_tmp1[7+k1,k2]
jac_error[indj+k1,k2]=jac_err1[7+k1,k2]
end
end
end
end
# Missing phic here [x]
phic!(x,v,xerror,verror,h,m,n,jac_phi,dqdt_phi,pair)
#hbig = big(h); mbig = big.(m)
#xbig = big.(x); vbig = big.(v)
#xerr_big = big.(xerror); verr_big = big.(verror)
#jac_phi_big = big.(jac_phi); dqdt_phi_big = big.(dqdt_phi)
#phisalpha!(xbig,vbig,xerr_big,verr_big,hbig,mbig,big(two),n,jac_phi_big,dqdt_phi_big,pair)
#xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
#x .= xcompare; v .= vcompare; jac_phi .= convert(Array{T,2},jac_phi_big)
#xerror .= convert(Array{T,2},xerr_big); verror .= convert(Array{T,2},verr_big)
phisalpha!(x,v,xerror,verror,h,m,two,n,jac_phi,dqdt_phi,pair) # 10%
# jac_step .= jac_phi*jac_step # < 1% Perhaps use gemm?! [ ]
if T == BigFloat
jac_copy .= *(jac_phi,jac_step)
else
BLAS.gemm!('N','N',uno,jac_phi,jac_step,zilch,jac_copy)
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(jac_step,jac_error,jac_copy)
indi=0; indj=0
@inbounds for i=n-1:-1:1
indi=(i-1)*7
@inbounds for j=n:-1:i+1
indj=(j-1)*7
if ~pair[i,j] # Check to see if kicks have not been applied
# kepler_driftij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,false)
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,false)
# Pick out indices for bodies i & j:
# Carry out multiplication on the i/j components of matrix:
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[k1,k2] = jac_step[ indi+k1,k2]
jac_err1[k1,k2] = jac_error[indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[7+k1,k2] = jac_step[ indj+k1,k2]
jac_err1[7+k1,k2] = jac_error[indj+k1,k2]
end
# Carry out multiplication on the i/j components of matrix:
if T == BigFloat
jac_tmp2 .= *(jac_ij,jac_tmp1)
else
BLAS.gemm!('N','N',uno,jac_ij,jac_tmp1,zilch,jac_tmp2)
end
# Add back in the Jacobian with compensated summation:
comp_sum_matrix!(jac_tmp1,jac_err1,jac_tmp2)
# Copy back to the Jacobian:
@inbounds for k2=1:sevn, k1=1:7
jac_step[ indi+k1,k2]=jac_tmp1[k1,k2]
jac_error[indi+k1,k2]=jac_err1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_step[ indj+k1,k2]=jac_tmp1[7+k1,k2]
jac_error[indj+k1,k2]=jac_err1[7+k1,k2]
end
end
end
end
#kickfast!(x,v,h2,m,n,jac_kick,dqdt_kick,pair)
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
# Multiply Jacobian from kick step:
if T == BigFloat
jac_copy .= *(jac_kick,jac_step)
else
BLAS.gemm!('N','N',uno,jac_kick,jac_step,zilch,jac_copy)
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(jac_step,jac_error,jac_copy)
# Edit this routine to do compensated summation for Jacobian [x]
drift!(x,v,xerror,verror,h2,n,jac_step,jac_error)
return
end
# Carries out the AH18 mapping & computes the derivative with respect to time step, h:
function ah18!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,dqdt::Array{T,1},pair::Array{Bool,2},d::Derivatives{T}) where {T <: Real}
# [Currently this routine is not giving the correct dqdt values. -EA 8/12/2019]
zilch = zero(T); uno = one(T); half = convert(T,0.5); two = convert(T,2.0)
h2 = half*h
# This routine assumes that alpha = 0.0
sevn = 7*n
jac_phi = zeros(T,sevn,sevn)
jac_kick = zeros(T,sevn,sevn)
jac_ij = zeros(T,14,14)
dqdt_ij = zeros(T,14)
dqdt_phi = zeros(T,sevn)
dqdt_kick = zeros(T,sevn)
dqdt_tmp1 = zeros(T,14)
dqdt_tmp2 = zeros(T,14)
fill!(dqdt,zilch)
#dqdt_save =copy(dqdt)
drift!(x,v,xerror,verror,h2,n)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
dqdt[(i-1)*7+k] = half*v[k,i] + h2*dqdt[(i-1)*7+3+k]
end
#println("dqdt 1: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
dqdt_kick /= 6 # Since step is h/6
# Since I removed identity from kickfast, need to add in dqdt:
dqdt .+= dqdt_kick + *(jac_kick,dqdt)
#println("dqdt 2: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
@inbounds for i=1:n-1
indi = (i-1)*7
@inbounds for j=i+1:n
indj = (j-1)*7
if ~pair[i,j] # Check to see if kicks have not been applied
# kepler_driftij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,true)
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,true)
# Copy current time derivatives for multiplication purposes:
@inbounds for k1=1:7
dqdt_tmp1[ k1] = dqdt[indi+k1]
dqdt_tmp1[7+k1] = dqdt[indj+k1]
end
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
# BLAS.gemm!('N','N',uno,jac_ij,dqdt_tmp1,half,dqdt_ij)
dqdt_ij .*= half
dqdt_ij .+= *(jac_ij,dqdt_tmp1) + dqdt_tmp1
# Copy back time derivatives:
@inbounds for k1=1:7
dqdt[indi+k1] = dqdt_ij[ k1]
dqdt[indj+k1] = dqdt_ij[7+k1]
end
# println("dqdt 4: i: ",i," j: ",j," diff: ",dqdt-dqdt_save)
# dqdt_save .= dqdt
end
end
end
# Looks like we are missing phic! here: [ ]
# Since I haven't added dqdt to phic yet, for now, set jac_phi equal to identity matrix
# (since this is commented out within phisalpha):
#jac_phi .= eye(T,sevn)
phic!(x,v,xerror,verror,h,m,n,jac_phi,dqdt_phi,pair)
phisalpha!(x,v,xerror,verror,h,m,two,n,jac_phi,dqdt_phi,pair) # 10%
# Add in time derivative with respect to prior parameters:
#BLAS.gemm!('N','N',uno,jac_phi,dqdt,uno,dqdt_phi)
# Copy result to dqdt:
dqdt .+= dqdt_phi + *(jac_phi,dqdt)
#println("dqdt 5: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
indi=0; indj=0
@inbounds for i=n-1:-1:1
indi=(i-1)*7
@inbounds for j=n:-1:i+1
if ~pair[i,j] # Check to see if kicks have not been applied
indj=(j-1)*7
# kepler_driftij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,false) # 23%
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,false) # 23%
# Copy current time derivatives for multiplication purposes:
@inbounds for k1=1:7
dqdt_tmp1[ k1] = dqdt[indi+k1]
dqdt_tmp1[7+k1] = dqdt[indj+k1]
end
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
#BLAS.gemm!('N','N',uno,jac_ij,dqdt_tmp1,half,dqdt_ij)
dqdt_ij .*= half
dqdt_ij .+= *(jac_ij,dqdt_tmp1) + dqdt_tmp1
# Copy back time derivatives:
@inbounds for k1=1:7
dqdt[indi+k1] = dqdt_ij[ k1]
dqdt[indj+k1] = dqdt_ij[7+k1]
end
# dqdt_save .= dqdt
# println("dqdt 7: ",dqdt-dqdt_save)
# println("dqdt 6: i: ",i," j: ",j," diff: ",dqdt-dqdt_save)
# dqdt_save .= dqdt
end
end
end
fill!(dqdt_kick,zilch)
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
dqdt_kick /= 6 # Since step is h/6
# Copy result to dqdt:
dqdt .+= dqdt_kick + *(jac_kick,dqdt)
#println("dqdt 8: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
drift!(x,v,xerror,verror,h2,n)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
dqdt[(i-1)*7+k] += half*v[k,i] + h2*dqdt[(i-1)*7+3+k]
end
#println("dqdt 9: ",dqdt-dqdt_save)
return
end
# Carries out the DH17 mapping:
function dh17!(x::Array{T,2},v::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
alpha = convert(T,alpha0)
h2 = 0.5*h
# alpha = 0. is similar in precision to alpha=0.25
kickfast!(x,v,h/6,m,n,pair)
if alpha != 0.0
phisalpha!(x,v,h,m,alpha,n,pair)
end
drift!(x,v,h2,n)
@inbounds for i=1:n-1
@inbounds for j=i+1:n
if ~pair[i,j]
driftij!(x,v,i,j,-h2)
keplerij!(m,x,v,i,j,h2)
end
end
end
# kick and correction for pairs which are kicked:
phic!(x,v,h,m,n,pair)
if alpha != 1.0
phisalpha!(x,v,h,m,2.0*(1.0-alpha),n,pair)
end
@inbounds for i=n-1:-1:1
@inbounds for j=n:-1:i+1
if ~pair[i,j]
keplerij!(m,x,v,i,j,h2)
driftij!(x,v,i,j,-h2)
end
end
end
drift!(x,v,h2,n)
if alpha != 0.0
phisalpha!(x,v,h,m,alpha,n,pair)
end
kickfast!(x,v,h/6,m,n,pair)
return
end
# Carries out the DH17 mapping with compensated summation:
function dh17!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
alpha = convert(T,alpha0)
h2 = 0.5*h
# alpha = 0. is similar in precision to alpha=0.25
kickfast!(x,v,xerror,verror,h/6,m,n,pair)
if alpha != 0.0
phisalpha!(x,v,xerror,verror,h,m,alpha,n,pair)
end
#mbig = big.(m); h2big = big(h2)
#xbig = big.(x); vbig = big.(v)
drift!(x,v,xerror,verror,h2,n)
#drift!(xbig,vbig,h2big,n)
#xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
#x .= xcompare; v .= vcompare
#hbig = big(h)
@inbounds for i=1:n-1
@inbounds for j=i+1:n
if ~pair[i,j]
# xbig = big.(x); vbig = big.(v)
driftij!(x,v,xerror,verror,i,j,-h2)
# driftij!(xbig,vbig,i,j,-h2big)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
# x .= xcompare; v .= vcompare
# xbig = big.(x); vbig = big.(v)
# keplerij!(mbig,xbig,vbig,i,j,h2big)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
keplerij!(m,x,v,xerror,verror,i,j,h2)
# x .= xcompare; v .= vcompare
end
end
end
# kick and correction for pairs which are kicked:
phic!(x,v,xerror,verror,h,m,n,pair)
if alpha != 1.0
# xbig = big.(x); vbig = big.(v)
phisalpha!(x,v,xerror,verror,h,m,2.0*(1.0-alpha),n,pair)
# phisalpha!(xbig,vbig,hbig,mbig,2*(1-big(alpha)),n,pair)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
# x .= xcompare; v .= vcompare
end
@inbounds for i=n-1:-1:1
@inbounds for j=n:-1:i+1
if ~pair[i,j]
# xbig = big.(x); vbig = big.(v)
# keplerij!(mbig,xbig,vbig,i,j,h2big)
#x = convert(Array{T,2},xbig); v = convert(Array{T,2},vbig)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
keplerij!(m,x,v,xerror,verror,i,j,h2)
# x .= xcompare; v .= vcompare
# xbig = big.(x); vbig = big.(v)
driftij!(x,v,xerror,verror,i,j,-h2)
# driftij!(xbig,vbig,i,j,-h2big)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
# x .= xcompare; v .= vcompare
end
end
end
#xbig = big.(x); vbig = big.(v)
drift!(x,v,xerror,verror,h2,n)
#drift!(xbig,vbig,h2big,n)
#xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
#x .= xcompare; v .= vcompare
if alpha != 0.0
phisalpha!(x,v,xerror,verror,h,m,alpha,n,pair)
end
kickfast!(x,v,xerror,verror,h/6,m,n,pair)
return
end
# Used in computing the transit time:
function g!(i::Int64,j::Int64,x::Array{T,2},v::Array{T,2}) where {T <: Real}
# See equation 8-10 Fabrycky (2008) in Seager Exoplanets book
g = (x[1,j]-x[1,i])*(v[1,j]-v[1,i])+(x[2,j]-x[2,i])*(v[2,j]-v[2,i])
return g
end
# Carries out the DH17 mapping & computes the Jacobian:
function dh17!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,jac_step::Array{T,2},pair::Array{Bool,2}) where {T <: Real}
zilch = zero(T); uno = one(T); half = convert(T,0.5); two = convert(T,2.0)
h2 = half*h
alpha = convert(T,alpha0)
sevn = 7*n
jac_phi = zeros(T,sevn,sevn)
jac_kick = zeros(T,sevn,sevn)
jac_copy = zeros(T,sevn,sevn)
jac_error = zeros(T,sevn,sevn)
jac_ij = zeros(T,14,14)
dqdt_ij = zeros(T,14)
dqdt_phi = zeros(T,sevn)
dqdt_kick = zeros(T,sevn)
jac_tmp1 = zeros(T,14,sevn)
jac_tmp2 = zeros(T,14,sevn)
jac_err1 = zeros(T,14,sevn)
kickfast!(x,v,xerror,verror,h/6,m,n,jac_phi,dqdt_kick,pair)
# alpha = 0. is similar in precision to alpha=0.25
if alpha != zilch
phisalpha!(x,v,xerror,verror,h,m,alpha,n,jac_phi,dqdt_phi,pair)
# jac_step .= jac_phi*jac_step # < 1%
end
# Multiply Jacobian from kick/phisalpha steps:
if T == BigFloat
jac_copy = *(jac_phi,jac_step)
else
BLAS.gemm!('N','N',uno,jac_phi,jac_step,zilch,jac_copy)
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(jac_step,jac_error,jac_copy)
# Modify drift! to account for error in Jacobian: [x]
drift!(x,v,xerror,verror,h2,n,jac_step,jac_error)
indi = 0; indj = 0
@inbounds for i=1:n-1
indi = (i-1)*7
@inbounds for j=i+1:n
indj = (j-1)*7
if ~pair[i,j] # Check to see if kicks have not been applied
driftij!(x,v,xerror,verror,i,j,-h2,jac_step,jac_error,n)
keplerij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij) # 21%
# Pick out indices for bodies i & j:
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[k1,k2] = jac_step[indi+k1,k2]
jac_err1[k1,k2] = jac_error[indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[7+k1,k2] = jac_step[indj+k1,k2]
jac_err1[7+k1,k2] = jac_error[indj+k1,k2]
end
# Carry out multiplication on the i/j components of matrix:
# jac_tmp2 = BLAS.gemm('N','N',jac_ij,jac_tmp1)
if T == BigFloat
jac_tmp2 = *(jac_ij,jac_tmp1)
else
BLAS.gemm!('N','N',uno,jac_ij,jac_tmp1,zilch,jac_tmp2)
end
# # Add back in the Jacobian with compensated summation:
# comp_sum_matrix!(jac_tmp1,jac_err1,jac_tmp2)
# Copy back to the Jacobian:
@inbounds for k2=1:sevn, k1=1:7
jac_step[indi+k1,k2]=jac_tmp2[k1,k2]
jac_error[indi+k1,k2]=jac_err1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_step[indj+k1,k2]=jac_tmp2[7+k1,k2]
jac_error[indj+k1,k2]=jac_err1[7+k1,k2]
end
end
end
end
# kick and correction for pairs which are kicked:
phic!(x,v,xerror,verror,h,m,n,jac_phi,dqdt_phi,pair)
if alpha != uno
# phisalpha!(x,v,h,m,2.0*(1.0-alpha),n,jac_phi,pair) # 10%
phisalpha!(x,v,xerror,verror,h,m,two*(uno-alpha),n,jac_phi,dqdt_phi,pair) # 10%
# @inbounds for i in eachindex(jac_step)
# jac_copy[i] = jac_step[i]
# end
# jac_step .= jac_phi*jac_step # < 1% Perhaps use gemm?! [ ]
# if T == BigFloat
# jac_step = *(jac_phi,jac_copy)
# else
# BLAS.gemm!('N','N',uno,jac_phi,jac_copy,zilch,jac_step)
# end
end
@inbounds for i in eachindex(jac_step)
jac_copy[i] = jac_step[i]
end
if T == BigFloat
jac_step = *(jac_phi,jac_copy)
else
BLAS.gemm!('N','N',uno,jac_phi,jac_copy,zilch,jac_step)
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(jac_step,jac_error,jac_copy)
indi=0; indj=0
@inbounds for i=n-1:-1:1
indi=(i-1)*7
@inbounds for j=n:-1:i+1
indj=(j-1)*7
if ~pair[i,j] # Check to see if kicks have not been applied
keplerij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij) # 23%
# Pick out indices for bodies i & j:
# Carry out multiplication on the i/j components of matrix:
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[k1,k2] = jac_step[indi+k1,k2]
jac_err1[k1,k2] = jac_error[indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[7+k1,k2] = jac_step[indj+k1,k2]
jac_err1[7+k1,k2] = jac_error[indj+k1,k2]
end
# Carry out multiplication on the i/j components of matrix:
# jac_tmp2 = BLAS.gemm('N','N',jac_ij,jac_tmp1)
if T == BigFloat
jac_tmp2 = *(jac_ij,jac_tmp1)
else
BLAS.gemm!('N','N',uno,jac_ij,jac_tmp1,zilch,jac_tmp2)
end
# # Add back in the Jacobian with compensated summation:
# comp_sum_matrix!(jac_tmp1,jac_err1,jac_tmp2)
# Copy back to the Jacobian:
@inbounds for k2=1:sevn, k1=1:7
jac_step[indi+k1,k2]=jac_tmp2[k1,k2]
jac_error[indi+k1,k2]=jac_err1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_step[indj+k1,k2]=jac_tmp2[7+k1,k2]
jac_error[indj+k1,k2]=jac_err1[7+k1,k2]
end
driftij!(x,v,xerror,verror,i,j,-h2,jac_step,jac_error,n)
end
end
end
drift!(x,v,xerror,verror,h2,n,jac_step,jac_error)
if alpha != zilch
# phisalpha!(x,v,h,m,alpha,n,jac_phi)
phisalpha!(x,v,xerror,verror,h,m,alpha,n,jac_phi,dqdt_phi,pair) # 10%
# jac_step .= jac_phi*jac_step # < 1%
end
kickfast!(x,v,xerror,verror,h/6,m,n,jac_phi,dqdt_kick,pair)
# Multiply Jacobian from kick step:
if T == BigFloat
jac_copy = *(jac_phi,jac_step)
else
BLAS.gemm!('N','N',uno,jac_phi,jac_step,zilch,jac_copy)
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(jac_step,jac_error,jac_copy)
#println("jac_step: ",T," ",convert(Array{Float64,2},jac_step))
return #jac_step
end
# Carries out the DH17 mapping & computes the derivative with respect to time step, h:
function dh17!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,dqdt::Array{T,1},pair::Array{Bool,2}) where {T <: Real}
zilch = zero(T); uno = one(T); half = convert(T,0.5); two = convert(T,2.0)
h2 = half*h
# This routine assumes that alpha = 0.0
sevn = 7*n
jac_phi = zeros(T,sevn,sevn)
jac_kick = zeros(T,sevn,sevn)
jac_ij = zeros(T,14,14)
dqdt_ij = zeros(T,14)
dqdt_phi = zeros(T,sevn)
dqdt_kick = zeros(T,sevn)
dqdt_tmp1 = zeros(T,14)
fill!(dqdt,zilch)
# dqdt_save is for debugging:
#dqdt_save = copy(dqdt)
drift!(x,v,xerror,verror,h2,n)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
dqdt[(i-1)*7+k] = half*v[k,i] + h2*dqdt[(i-1)*7+3+k]
end
#println("dqdt 1: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
dqdt_kick /= 6 # Since step is h/6
dqdt_kick .+= *(jac_kick,dqdt)
# Copy result to dqdt:
dqdt .+= dqdt_kick
#println("dqdt 2: ",dqdt-dqdt_save)
# dqdt_save .= dqdt
@inbounds for i=1:n-1
indi = (i-1)*7
@inbounds for j=i+1:n
indj = (j-1)*7
if ~pair[i,j] # Check to see if kicks have not been applied
driftij!(x,v,xerror,verror,i,j,-h2,dqdt,-half)
# println("dqdt 3: i: ",i," j: ",j," diff: ",dqdt-dqdt_save)
# dqdt_save .= dqdt
keplerij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij) # 21%
# Copy current time derivatives for multiplication purposes:
@inbounds for k1=1:7
dqdt_tmp1[ k1] = dqdt[indi+k1]
dqdt_tmp1[7+k1] = dqdt[indj+k1]
end
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
# BLAS.gemm!('N','N',uno,jac_ij,dqdt_tmp1,half,dqdt_ij)
dqdt_ij .*= half
dqdt_ij .+= *(jac_ij,dqdt_tmp1)
# Copy back time derivatives:
@inbounds for k1=1:7
dqdt[indi+k1] = dqdt_ij[ k1]
dqdt[indj+k1] = dqdt_ij[7+k1]
end
# println("dqdt 4: i: ",i," j: ",j," diff: ",dqdt-dqdt_save)
# dqdt_save .= dqdt
end
end
end
# Looks like we are missing phic! here: [ ]
# Since I haven't added dqdt to phic yet, for now, set jac_phi equal to identity matrix
# (since this is commented out within phisalpha):
#jac_phi .= eye(T,sevn)
phic!(x,v,xerror,verror,h,m,n,jac_phi,dqdt_phi,pair)
phisalpha!(x,v,xerror,verror,h,m,two,n,jac_phi,dqdt_phi,pair) # 10%
# Add in time derivative with respect to prior parameters:
#BLAS.gemm!('N','N',uno,jac_phi,dqdt,uno,dqdt_phi)
dqdt_phi .+= *(jac_phi,dqdt)
# Copy result to dqdt:
dqdt .+= dqdt_phi
#println("dqdt 5: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
indi=0; indj=0
@inbounds for i=n-1:-1:1
indi=(i-1)*7
@inbounds for j=n:-1:i+1
if ~pair[i,j] # Check to see if kicks have not been applied
indj=(j-1)*7
keplerij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij) # 23%
# Copy current time derivatives for multiplication purposes:
@inbounds for k1=1:7
dqdt_tmp1[ k1] = dqdt[indi+k1]
dqdt_tmp1[7+k1] = dqdt[indj+k1]
end
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
#BLAS.gemm!('N','N',uno,jac_ij,dqdt_tmp1,half,dqdt_ij)
dqdt_ij .*= half
dqdt_ij .+= *(jac_ij,dqdt_tmp1)
# Copy back time derivatives:
@inbounds for k1=1:7
dqdt[indi+k1] = dqdt_ij[ k1]
dqdt[indj+k1] = dqdt_ij[7+k1]
end
# println("dqdt 6: i: ",i," j: ",j," diff: ",dqdt-dqdt_save)
# dqdt_save .= dqdt
driftij!(x,v,xerror,verror,i,j,-h2,dqdt,-half)
# println("dqdt 7: ",dqdt-dqdt_save)
# dqdt_save .= dqdt
end
end
end
fill!(dqdt_kick,zilch)
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
dqdt_kick /= 6 # Since step is h/6
dqdt_kick .+= *(jac_kick,dqdt)
#println("dqdt 8: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
# Copy result to dqdt:
dqdt .+= dqdt_kick
drift!(x,v,xerror,verror,h2,n)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
dqdt[(i-1)*7+k] += half*v[k,i] + h2*dqdt[(i-1)*7+3+k]
end
#println("dqdt 9: ",dqdt-dqdt_save)
return
end
# Finds the transit by taking a partial dh17 step from prior times step:
#function findtransit2!(i::Int64,j::Int64,n::Int64,h::Float64,tt::Float64,m::Array{Float64,1},x1::Array{Float64,2},v1::Array{Float64,2})
function findtransit2!(i::Int64,j::Int64,n::Int64,h::T,tt::T,m::Array{T,1},x1::Array{T,2},v1::Array{T,2},pair::Array{Bool,2}) where {T <: Real}
# Computes the transit time, approximating the motion as a fraction of a DH17 step forward in time.
# Initial guess using linear interpolation:
dt = one(T)
iter = 0
r3 = zero(T)
gdot = zero(T)
gsky = zero(T)
x = copy(x1)
v = copy(v1)
#TRANSIT_TOL = 10*sqrt(eps(dt))
TRANSIT_TOL = 10*eps(dt)
#println("h: ",h,", TRANSIT_TOL: ",TRANSIT_TOL)
while abs(dt) > TRANSIT_TOL && iter < 20
x .= x1
v .= v1
# Advance planet state at start of step to estimated transit time:
dh17!(x,v,tt,m,n,pair)
# Compute time offset:
gsky = g!(i,j,x,v)
# Compute gravitational acceleration in sky plane dotted with sky position:
gdot = zero(T)
@inbounds for k=1:n
if k != i
r3 = sqrt((x[1,k]-x[1,i])^2+(x[2,k]-x[2,i])^2 +(x[3,k]-x[3,i])^2)^3
gdot -= GNEWT*m[k]*((x[1,k]-x[1,i])*(x[1,j]-x[1,i])+(x[2,k]-x[2,i])*(x[2,j]-x[2,i]))/r3
end
if k != j
r3 = sqrt((x[1,k]-x[1,j])^2+(x[2,k]-x[2,j])^2 +(x[3,k]-x[3,j])^2)^3
gdot += GNEWT*m[k]*((x[1,k]-x[1,j])*(x[1,j]-x[1,i])+(x[2,k]-x[2,j])*(x[2,j]-x[2,i]))/r3
end
end
# Compute derivative of g with respect to time:
gdot += (v[1,j]-v[1,i])^2+(v[2,j]-v[2,i])^2
# Refine estimate of transit time with Newton's method:
dt = -gsky/gdot
# Add refinement to estimated time:
tt += dt
iter +=1
end
#x = copy(x1)
#v = copy(v1)
#dh17!(x,v,tt,m,n,pair)
# Compute time offset:
#gsky = g!(i,j,x,v)
#println("gsky: ",convert(Float64,gsky))
if iter >= 20
# println("Exceeded iterations: planet ",j," iter ",iter," dt ",dt," gsky ",gsky," gdot ",gdot)
end
# Note: this is the time elapsed *after* the beginning of the timestep:
return tt::T
end
# Finds the transit by taking a partial dh17 step from prior times step, computes timing Jacobian, dtdq, wrt initial cartesian coordinates, masses:
#function findtransit2!(i::Int64,j::Int64,n::Int64,h::Float64,tt::Float64,m::Array{Float64,1},x1::Array{Float64,2},v1::Array{Float64,2},jac_step::Array{Float64,2},dtdq::Array{Float64,2},pair::Array{Bool,2})
function findtransit2!(i::Int64,j::Int64,n::Int64,h::T,tt::T,m::Array{T,1},x1::Array{T,2},v1::Array{T,2},jac_step::Array{T,2},dtdq::Array{T,2},pair::Array{Bool,2}) where {T <: Real}
# Computes the transit time, approximating the motion as a fraction of a DH17 step forward in time.
# Also computes the Jacobian of the transit time with respect to the initial parameters, dtdq[7,n].
# Initial guess using linear interpolation:
#dt = 1.0
dt = one(T)
iter = 0
#r3 = 0.0
r3 = zero(T)
#gdot = 0.0
gdot = zero(T)
#gsky = 0.0
gsky = zero(T)
x = copy(x1)
v = copy(v1)
#TRANSIT_TOL = 10*sqrt(eps(dt))
TRANSIT_TOL = 10*eps(dt)
#println("h: ",h,", TRANSIT_TOL: ",TRANSIT_TOL)
while abs(dt) > TRANSIT_TOL && iter < 20
x .= x1
v .= v1
# Advance planet state at start of step to estimated transit time:
dh17!(x,v,tt,m,n,pair)
# Compute time offset:
gsky = g!(i,j,x,v)
# Compute gravitational acceleration in sky plane dotted with sky position:
#gdot = 0.0
gdot = zero(T)
@inbounds for k=1:n
if k != i
r3 = sqrt((x[1,k]-x[1,i])^2+(x[2,k]-x[2,i])^2 +(x[3,k]-x[3,i])^2)^3
gdot -= GNEWT*m[k]*((x[1,k]-x[1,i])*(x[1,j]-x[1,i])+(x[2,k]-x[2,i])*(x[2,j]-x[2,i]))/r3
# g = (x[1,j]-x[1,i])*(v[1,j]-v[1,i])+(x[2,j]-x[2,i])*(v[2,j]-v[2,i])
end
if k != j
r3 = sqrt((x[1,k]-x[1,j])^2+(x[2,k]-x[2,j])^2 +(x[3,k]-x[3,j])^2)^3
gdot += GNEWT*m[k]*((x[1,k]-x[1,j])*(x[1,j]-x[1,i])+(x[2,k]-x[2,j])*(x[2,j]-x[2,i]))/r3
end
end
# Compute derivative of g with respect to time:
gdot += (v[1,j]-v[1,i])^2+(v[2,j]-v[2,i])^2
# Refine estimate of transit time with Newton's method:
dt = -gsky/gdot
# Add refinement to estimated time:
tt += dt
iter +=1
end
if iter >= 20
# println("Exceeded iterations: planet ",j," iter ",iter," dt ",dt," gsky ",gsky," gdot ",gdot)
end
# Compute time derivatives:
x = copy(x1)
v = copy(v1)
#xerror = zeros(x1); verror = zeros(v1)
xerror = copy(x1); verror = copy(v1)
fill!(xerror,0.0); fill!(verror,0.0)
# Compute dgdt with the updated time step.
dh17!(x,v,xerror,verror,tt,m,n,jac_step,pair)
#println("\Delta t: ",tt)
#println("jac_step: ",jac_step)
# Compute time offset:
gsky = g!(i,j,x,v)
#println("gsky: ",convert(Float64,gsky))
# Compute gravitational acceleration in sky plane dotted with sky position:
#gdot = 0.0
gdot = (v[1,j]-v[1,i])^2+(v[2,j]-v[2,i])^2
gdot_acc = zero(T)
@inbounds for k=1:n
if k != i
r3 = sqrt((x[1,k]-x[1,i])^2+(x[2,k]-x[2,i])^2 +(x[3,k]-x[3,i])^2)^3
# Does this have the wrong sign?!
gdot_acc -= GNEWT*m[k]*((x[1,k]-x[1,i])*(x[1,j]-x[1,i])+(x[2,k]-x[2,i])*(x[2,j]-x[2,i]))/r3
# g = (x[1,j]-x[1,i])*(v[1,j]-v[1,i])+(x[2,j]-x[2,i])*(v[2,j]-v[2,i])
end
if k != j
r3 = sqrt((x[1,k]-x[1,j])^2+(x[2,k]-x[2,j])^2 +(x[3,k]-x[3,j])^2)^3
# Does this have the wrong sign?!
gdot_acc += GNEWT*m[k]*((x[1,k]-x[1,j])*(x[1,j]-x[1,i])+(x[2,k]-x[2,j])*(x[2,j]-x[2,i]))/r3
end
end
gdot += gdot_acc
#println("gdot_acc/gdot: ",gdot_acc/gdot)
# Compute derivative of g with respect to time:
# Set dtdq to zero:
fill!(dtdq,zero(T))
indj = (j-1)*7+1
indi = (i-1)*7+1
@inbounds for p=1:n
indp = (p-1)*7
@inbounds for k=1:7
# Compute derivatives:
#g = (x[1,j]-x[1,i])*(v[1,j]-v[1,i])+(x[2,j]-x[2,i])*(v[2,j]-v[2,i])
dtdq[k,p] = -((jac_step[indj ,indp+k]-jac_step[indi ,indp+k])*(v[1,j]-v[1,i])+(jac_step[indj+1,indp+k]-jac_step[indi+1,indp+k])*(v[2,j]-v[2,i])+
(jac_step[indj+3,indp+k]-jac_step[indi+3,indp+k])*(x[1,j]-x[1,i])+(jac_step[indj+4,indp+k]-jac_step[indi+4,indp+k])*(x[2,j]-x[2,i]))/gdot
end
end
# Note: this is the time elapsed *after* the beginning of the timestep:
return tt::T,gdot::T
end
# Finds the transit by taking a partial dh17 step from prior times step, computes timing Jacobian, dtdq, wrt initial cartesian coordinates, masses:
function findtransit3!(i::Int64,j::Int64,n::Int64,h::T,tt::T,m::Array{T,1},x1::Array{T,2},v1::Array{T,2},xerror::Array{T,2},verror::Array{T,2},pair::Array{Bool,2};calcbvsky=false) where {T <: Real}
# Computes the transit time, approximating the motion as a fraction of a DH17 step forward in time.
# Also computes the Jacobian of the transit time with respect to the initial parameters, dtdq[7,n].
# This version is same as findtransit2, but uses the derivative of dh17 step with respect to time
# rather than the instantaneous acceleration for finding transit time derivative (gdot).
# Initial guess using linear interpolation:
dt = one(T)
iter = 0
r3 = zero(T)
gdot = zero(T)
gsky = gdot
x = copy(x1); v = copy(v1); xerr_trans = copy(xerror); verr_trans = copy(verror)
dqdt = zeros(T,7*n)
d = Derivatives(T)
#TRANSIT_TOL = 10*sqrt(eps(dt)
TRANSIT_TOL = 10*eps(dt)
ITMAX = 20
tt1 = tt + 1
tt2 = tt + 2
#while abs(dt) > TRANSIT_TOL && iter < 20
while true
tt2 = tt1
tt1 = tt
x .= x1; v .= v1; xerr_trans .= xerror; verr_trans .= verror
# Advance planet state at start of step to estimated transit time:
# dh17!(x,v,tt,m,n,pair)
#dh17!(x,v,xerror,verror,tt,m,n,dqdt,pair)
ah18!(x,v,xerr_trans,verr_trans,tt,m,n,dqdt,pair,d)
# Compute time offset:
gsky = g!(i,j,x,v)
# # Compute derivative of g with respect to time:
gdot = ((x[1,j]-x[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(x[2,j]-x[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5])
+ (v[1,j]-v[1,i])*(dqdt[(j-1)*7+1]-dqdt[(i-1)*7+1])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+2]-dqdt[(i-1)*7+2]))
# Refine estimate of transit time with Newton's method:
dt = -gsky/gdot
# Add refinement to estimated time:
tt += dt
iter +=1
# Break out if we have reached maximum iterations, or if
# current transit time estimate equals one of the prior two steps:
if (iter >= ITMAX) || (tt == tt1) || (tt == tt2)
break
end
end
if iter >= 20
# println("Exceeded iterations: planet ",j," iter ",iter," dt ",dt," gsky ",gsky," gdot ",gdot)
end
# Note: this is the time elapsed *after* the beginning of the timestep:
if calcbvsky
# Compute the sky velocity and impact parameter:
vsky = sqrt((v[1,j]-v[1,i])^2 + (v[2,j]-v[2,i])^2)
bsky2 = (x[1,j]-x[1,i])^2 + (x[2,j]-x[2,i])^2
# return the transit time, impact parameter, and sky velocity:
return tt::T,vsky::T,bsky2::T
else
return tt::T
end
end
# Finds the transit by taking a partial ah18 step from prior times step, computes timing Jacobian, dtbvdq, wrt initial cartesian coordinates, masses:
function findtransit3!(i::Int64,j::Int64,n::Int64,h::T,tt::T,m::Array{T,1},x1::Array{T,2},v1::Array{T,2},xerror::Array{T,2},verror::Array{T,2},jac_step::Array{T,2},jac_error::Array{T,2},dtbvdq::Array{T,3},pair::Array{Bool,2}) where {T <: Real}
# Computes the transit time, approximating the motion as a fraction of a DH17 step forward in time.
# Also computes the Jacobian of the transit time with respect to the initial parameters, dtbvdq[1-3,7,n].
# This version is same as findtransit2, but uses the derivative of dh17 step with respect to time
# rather than the instantaneous acceleration for finding transit time derivative (gdot).
# Initial guess using linear interpolation:
dt = one(T)
iter = 0
r3 = zero(T)
gdot = zero(T)
gsky = zero(T)
x = copy(x1)
v = copy(v1)
#xerror = zeros(T,size(x1)); verror = zeros(T,size(v1))
xerr_trans = copy(xerror); verr_trans = copy(verror)
dqdt = zeros(T,7*n)
d = Derivatives(T)
#TRANSIT_TOL = 10*sqrt(eps(dt))
TRANSIT_TOL = 10*eps(dt)
tt1 = tt + 1
tt2 = tt + 2
ITMAX = 20
#while abs(dt) > TRANSIT_TOL && iter < 20
while true
tt2 = tt1
tt1 = tt
x .= x1; v .= v1; xerr_trans .= xerror; verr_trans .= verror
# Advance planet state at start of step to estimated transit time:
# dh17!(x,v,tt,m,n,pair)
#dh17!(x,v,xerror,verror,tt,m,n,dqdt,pair)
ah18!(x,v,xerr_trans,verr_trans,tt,m,n,dqdt,pair,d)
# Compute time offset:
gsky = g!(i,j,x,v)
# # Compute derivative of g with respect to time:
gdot = ((x[1,j]-x[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(x[2,j]-x[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5])
+ (v[1,j]-v[1,i])*(dqdt[(j-1)*7+1]-dqdt[(i-1)*7+1])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+2]-dqdt[(i-1)*7+2]))
# Refine estimate of transit time with Newton's method:
dt = -gsky/gdot
# Add refinement to estimated time:
tt += dt
iter +=1
# Break out if we have reached maximum iterations, or if
# current transit time estimate equals one of the prior two steps:
if (iter >= ITMAX) || (tt == tt1) || (tt == tt2)
break
end
end
if iter >= 20
# println("Exceeded iterations: planet ",j," iter ",iter," dt ",dt," gsky ",gsky," gdot ",gdot)
end
# Compute time derivatives:
x .= x1; v .= v1; xerr_trans .= xerror; verr_trans .= verror
# Compute dgdt with the updated time step.
#dh17!(x,v,xerror,verror,tt,m,n,jac_step,pair)
#ah18!(x,v,xerror,verror,tt,m,n,jac_step,pair)
ah18!(x,v,xerr_trans,verr_trans,tt,m,n,jac_step,jac_error,pair,d)
# Need to reset to compute dqdt:
x .= x1; v .= v1; xerr_trans .= xerror; verr_trans .= verror
#dh17!(x,v,xerror,verror,tt,m,n,dqdt,pair)
ah18!(x,v,xerr_trans,verr_trans,tt,m,n,dqdt,pair,d)
# Compute time offset:
gsky = g!(i,j,x,v)
# Compute derivative of g with respect to time:
gdot = ((x[1,j]-x[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(x[2,j]-x[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5])
+ (v[1,j]-v[1,i])*(dqdt[(j-1)*7+1]-dqdt[(i-1)*7+1])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+2]-dqdt[(i-1)*7+2]))
# Set dtbvdq to zero:
fill!(dtbvdq,zero(T))
indj = (j-1)*7+1
indi = (i-1)*7+1
@inbounds for p=1:n
indp = (p-1)*7
@inbounds for k=1:7
# Compute derivatives:
#g = (x[1,j]-x[1,i])*(v[1,j]-v[1,i])+(x[2,j]-x[2,i])*(v[2,j]-v[2,i])
dtbvdq[1,k,p] = -((jac_step[indj ,indp+k]-jac_step[indi ,indp+k])*(v[1,j]-v[1,i])+(jac_step[indj+1,indp+k]-jac_step[indi+1,indp+k])*(v[2,j]-v[2,i])+
(jac_step[indj+3,indp+k]-jac_step[indi+3,indp+k])*(x[1,j]-x[1,i])+(jac_step[indj+4,indp+k]-jac_step[indi+4,indp+k])*(x[2,j]-x[2,i]))/gdot
end
end
# Note: this is the time elapsed *after* the beginning of the timestep:
ntbv = size(dtbvdq)[1]
if ntbv == 3
# Compute the impact parameter and sky velocity:
vsky = sqrt((v[1,j]-v[1,i])^2 + (v[2,j]-v[2,i])^2)
bsky2 = (x[1,j]-x[1,i])^2 + (x[2,j]-x[2,i])^2
# partial derivative v_{sky} with respect to time:
dvdt = ((v[1,j]-v[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5]))/vsky
# (note that \partial b/\partial t = 0 at mid-transit since g_{sky} = 0 mid-transit).
@inbounds for p=1:n
indp = (p-1)*7
@inbounds for k=1:7
# Compute derivatives:
#v_{sky} = sqrt((v[1,j]-v[1,i])^2+(v[2,j]-v[2,i])^2)
dtbvdq[2,k,p] = ((jac_step[indj+3,indp+k]-jac_step[indi+3,indp+k])*(v[1,j]-v[1,i])+(jac_step[indj+4,indp+k]-jac_step[indi+4,indp+k])*(v[2,j]-v[2,i]))/vsky + dvdt*dtbvdq[1,k,p]
#b_{sky}^2 = (x[1,j]-x[1,i])^2+(x[2,j]-x[2,i])^2
dtbvdq[3,k,p] = 2*((jac_step[indj ,indp+k]-jac_step[indi ,indp+k])*(x[1,j]-x[1,i])+(jac_step[indj+1,indp+k]-jac_step[indi+1,indp+k])*(x[2,j]-x[2,i]))
end
end
# return the transit time, impact parameter, and sky velocity:
return tt::T,vsky::T,bsky2::T
else
return tt::T
end
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 24411 | # Collection of functions to compute transit timing variations, using the AH18 integrator.
# wrapper for testing new ics.
@inline function ttv_elements!(el::ElementsIC{T},t0::T,h::T,tmax::T,tt::Array{T,2},count::Array{Int64,1},rstar::T) where T <: Real
return ttv_elements!(el.H,t0,h,tmax,el.elements,tt,count,0.0,0,0,rstar)
end
"""
Computes Transit Timing Variations (TTVs) as a function of orbital elements, and computes Jacobian of transit times with respect to the initial orbital elements.
"""
function ttv_elements!(H::Union{Int64,Array{Int64,1}},t0::T,h::T,tmax::T,elements::Array{T,2},tt::Array{T,2},count::Array{Int64,1},dtdq0::Array{T,4},rstar::T;fout="",iout=-1,pair=zeros(Bool,H[1],H[1])) where {T <: Real}
#
# Input quantities:
# n = number of bodies
# t0 = initial time of integration [days]
# h = time step [days]
# tmax = duration of integration [days]
# elements[i,j] = 2D n x 7 array of the masses & orbital elements of the bodies (currently first body's orbital elements are ignored)
# elements are ordered as: mass, period, t0, e*cos(omega), e*sin(omega), inclination, longitude of ascending node (Omega)
# tt = array of transit times of size [n x max(ntt)] (currently only compute transits of star, so first row is zero) [days]
# count = array of the number of transits for each body
# dtdq0 = derivative of transit times with respect to initial x,v,m [various units: day/length (3), day^2/length (3), day/mass]
# 4D array [n x max(ntt) ] x [n x 7] - derivatives of transits of each planet with respect to initial positions/velocities
# masses of *all* bodies. Note: mass derivatives are *after* positions/velocities, even though they are at start
# of the elements[i,j] array.
#
# Output quantity:
# dtdelements = 4D array [n x max(ntt) ] x [n x 7] - derivatives of transits of each planet with respect to initial orbital
# elements/masses of *all* bodies. Note: mass derivatives are *after* elements, even though they are at start
# of the elements[i,j] array
#
# Example: see test_ttv_elements.jl in test/ directory
#
# Define initial mass, position & velocity arrays:
n = H[1]
m=zeros(T,n)
x=zeros(T,NDIM,n)
v=zeros(T,NDIM,n)
# Fill the transit-timing & jacobian arrays with zeros:
fill!(tt,zero(T))
fill!(dtdq0,zero(T))
# Create an array for the derivatives with respect to the masses/orbital elements:
dtdelements = copy(dtdq0)
# Counter for transits of each planet:
fill!(count,0)
for i=1:n
m[i] = elements[i,1]
end
# Initialize the N-body problem using nested hierarchy of Keplerians:
init = ElementsIC(t0,H,elements)
x,v,jac_init = init_nbody(init)
#= Why is this here??
elements_big=big.(elements); t0big = big(t0); #jac_init_big = zeros(BigFloat,7*n,7*n)
init_big = ElementsIC(elements_big,H,t0big)
xbig,vbig,jac_init_big = init_nbody(init_big)
x = convert(Array{T,2},xbig); v = convert(Array{T,2},vbig); jac_init=convert(Array{T,2},jac_init_big)
=#
ttv!(n,t0,h,tmax,m,x,v,tt,count,dtdq0,rstar,pair;fout=fout,iout=iout)
# Need to apply initial jacobian TBD - convert from
# derivatives with respect to (x,v,m) to (elements,m):
ntt_max = size(tt)[2]
for i=1:n, j=1:count[i]
if j <= ntt_max
# Now, multiply by the initial Jacobian to convert time derivatives to orbital elements:
for k=1:n, l=1:7
dtdelements[i,j,l,k] = zero(T)
for p=1:n, q=1:7
dtdelements[i,j,l,k] += dtdq0[i,j,q,p]*jac_init[(p-1)*7+q,(k-1)*7+l]
end
end
end
end
return dtdelements
end
"""
Computes TTVs as a function of initial x,v,m, and derivatives (dtdq0).
"""
function ttv!(n::Int64,t0::T,h::T,tmax::T,m::Array{T,1},x::Array{T,2},v::Array{T,2},tt::Array{T,2},count::Array{Int64,1},dtdq0::Array{T,4},rstar::T,pair::Array{Bool,2};fout="",iout=-1) where {T <: Real}
xprior = copy(x)
vprior = copy(v)
xtransit = copy(x)
vtransit = copy(v)
xerror = zeros(T,size(x)); verror=zeros(T,size(v))
xerr_trans = zeros(T,size(x)); verr_trans =zeros(T,size(v))
xerr_prior = zeros(T,size(x)); verr_prior =zeros(T,size(v))
# Set the time to the initial time:
t = t0
# Define error estimate based on Kahan (1965):
s2 = zero(T)
# Set step counter to zero:
istep = 0
# Jacobian for each step (7- 6 elements+mass, n_planets, 7 - 6 elements+mass, n planets):
jac_prior = zeros(T,7*n,7*n)
jac_error_prior = zeros(T,7*n,7*n)
jac_transit = zeros(T,7*n,7*n)
jac_trans_err= zeros(T,7*n,7*n)
# Initialize matrix for derivatives of transit times with respect to the initial x,v,m:
dtdq = zeros(T,1,7,n)
# Initialize the Jacobian to the identity matrix:
#jac_step = eye(T,7*n)
jac_step = Matrix{T}(I,7*n,7*n)
# Initialize Jacobian error array:
jac_error = zeros(T,7*n,7*n)
if fout != ""
# Open file for output:
file_handle =open(fout,"a")
end
# Output initial conditions:
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n))]') # Transpose to write each line
end
# Save the g function, which computes the relative sky velocity dotted with relative position
# between the planets and star:
gsave = zeros(T,n)
for i=2:n
# Compute the relative sky velocity dotted with position:
gsave[i]= g!(i,1,x,v)
end
# Loop over time steps:
dt = zero(T)
gi = zero(T)
ntt_max = size(tt)[2]
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
while t < (t0+tmax) && param_real
# Carry out a ah18 mapping step:
ah18!(x,v,xerror,verror,h,m,n,jac_step,jac_error,pair)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m)) && all(isfinite.(jac_step))
# Check to see if a transit may have occured. Sky is x-y plane; line of sight is z.
# Star is body 1; planets are 2-nbody (note that this could be modified to see if
# any body transits another body):
for i=2:n
# Compute the relative sky velocity dotted with position:
gi = g!(i,1,x,v)
ri = sqrt(x[1,i]^2+x[2,i]^2+x[3,i]^2) # orbital distance
# See if sign of g switches, and if planet is in front of star (by a good amount):
# (I'm wondering if the direction condition means that z-coordinate is reversed? EA 12/11/2017)
if gi > 0 && gsave[i] < 0 && x[3,i] > 0.25*ri && ri < rstar
# A transit has occurred between the time steps - integrate ah18! between timesteps
count[i] += 1
if count[i] <= ntt_max
dt0 = -gsave[i]*h/(gi-gsave[i]) # Starting estimate
xtransit .= xprior; vtransit .= vprior; jac_transit .= jac_prior; jac_trans_err .= jac_error_prior
xerr_trans .= xerr_prior; verr_trans .= verr_prior
dt = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_trans,verr_trans,jac_transit,jac_trans_err,dtdq,pair) # 20%
tt[i,count[i]],stmp = comp_sum(t,s2,dt)
# Save for posterity:
for k=1:7, p=1:n
dtdq0[i,count[i],k,p] = dtdq[1,k,p]
end
end
end
gsave[i] = gi
end
# Save the current state as prior state:
xprior .= x
vprior .= v
jac_prior .= jac_step
jac_error_prior .= jac_error
xerr_prior .= xerror
verr_prior .= verror
# Increment time by the time step using compensated summation:
t,s2 = comp_sum(t,s2,h)
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n));convert(Array{Float64,1},reshape(jac_step,49n^2))]') # Transpose to write each line
end
# t += h <- this leads to loss of precision
# Increment counter by one:
istep +=1
end
if fout != ""
# Close output file:
close(file_handle)
end
return
end
"""
Finds the transit by taking a partial ah18 step from prior time step, computes timing Jacobian, dtbvdq, with respect to initial cartesian coordinates and masses.
"""
function findtransit3!(i::Int64,j::Int64,n::Int64,h::T,tt::T,m::Array{T,1},x1::Array{T,2},v1::Array{T,2},xerror::Array{T,2},verror::Array{T,2},jac_step::Array{T,2},jac_error::Array{T,2},dtbvdq::Array{T,3},pair::Array{Bool,2}) where {T <: Real}
# Computes the transit time, approximating the motion as a fraction of a AH17 step forward in time.
# Also computes the Jacobian of the transit time with respect to the initial parameters, dtbvdq[1-3,7,n].
# This version is same as findtransit2, but uses the derivative of AH17 step with respect to time
# rather than the instantaneous acceleration for finding transit time derivative (gdot).
# Initial guess using linear interpolation:
dt = one(T)
iter = 0
r3 = zero(T)
gdot = zero(T)
gsky = zero(T)
x = copy(x1)
v = copy(v1)
xerr_trans = copy(xerror); verr_trans = copy(verror)
dqdt = zeros(T,7*n)
TRANSIT_TOL = 10*eps(dt)
tt1 = tt + 1
tt2 = tt + 2
ITMAX = 20
#while abs(dt) > TRANSIT_TOL && iter < 20
while true # while true is kind of a no-no...
tt2 = tt1
tt1 = tt
x .= x1; v .= v1; xerr_trans .= xerror; verr_trans .= verror
# Advance planet state at start of step to estimated transit time:
ah18!(x,v,xerr_trans,verr_trans,tt,m,n,dqdt,pair)
# Compute time offset:
gsky = g!(i,j,x,v)
# # Compute derivative of g with respect to time:
gdot = ((x[1,j]-x[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(x[2,j]-x[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5])
+ (v[1,j]-v[1,i])*(dqdt[(j-1)*7+1]-dqdt[(i-1)*7+1])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+2]-dqdt[(i-1)*7+2]))
# Refine estimate of transit time with Newton's method:
dt = -gsky/gdot
# Add refinement to estimated time:
tt += dt
iter +=1
# Break out if we have reached maximum iterations, or if
# current transit time estimate equals one of the prior two steps:
if (iter >= ITMAX) || (tt == tt1) || (tt == tt2)
break
end
end
if iter >= 20
# println("Exceeded iterations: planet ",j," iter ",iter," dt ",dt," gsky ",gsky," gdot ",gdot)
end
# Compute time derivatives:
x .= x1; v .= v1; xerr_trans .= xerror; verr_trans .= verror
# Compute dgdt with the updated time step.
ah18!(x,v,xerr_trans,verr_trans,tt,m,n,jac_step,jac_error,pair)
# Need to reset to compute dqdt:
x .= x1; v .= v1; xerr_trans .= xerror; verr_trans .= verror
ah18!(x,v,xerr_trans,verr_trans,tt,m,n,dqdt,pair)
# Compute time offset:
gsky = g!(i,j,x,v)
# Compute derivative of g with respect to time:
gdot = ((x[1,j]-x[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(x[2,j]-x[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5])
+ (v[1,j]-v[1,i])*(dqdt[(j-1)*7+1]-dqdt[(i-1)*7+1])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+2]-dqdt[(i-1)*7+2]))
# Set dtbvdq to zero:
fill!(dtbvdq,zero(T))
indj = (j-1)*7+1
indi = (i-1)*7+1
@inbounds for p=1:n
indp = (p-1)*7
@inbounds for k=1:7
# Compute derivatives:
dtbvdq[1,k,p] = -((jac_step[indj ,indp+k]-jac_step[indi ,indp+k])*(v[1,j]-v[1,i])+(jac_step[indj+1,indp+k]-jac_step[indi+1,indp+k])*(v[2,j]-v[2,i])+
(jac_step[indj+3,indp+k]-jac_step[indi+3,indp+k])*(x[1,j]-x[1,i])+(jac_step[indj+4,indp+k]-jac_step[indi+4,indp+k])*(x[2,j]-x[2,i]))/gdot
end
end
# Note: this is the time elapsed *after* the beginning of the timestep:
ntbv = size(dtbvdq)[1]
if ntbv == 3
# Compute the impact parameter and sky velocity:
vsky = sqrt((v[1,j]-v[1,i])^2 + (v[2,j]-v[2,i])^2)
bsky2 = (x[1,j]-x[1,i])^2 + (x[2,j]-x[2,i])^2
# partial derivative v_{sky} with respect to time:
dvdt = ((v[1,j]-v[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5]))/vsky
# (note that \partial b/\partial t = 0 at mid-transit since g_{sky} = 0 mid-transit).
@inbounds for p=1:n
indp = (p-1)*7
@inbounds for k=1:7
# Compute derivatives:
#v_{sky} = sqrt((v[1,j]-v[1,i])^2+(v[2,j]-v[2,i])^2)
dtbvdq[2,k,p] = ((jac_step[indj+3,indp+k]-jac_step[indi+3,indp+k])*(v[1,j]-v[1,i])+(jac_step[indj+4,indp+k]-jac_step[indi+4,indp+k])*(v[2,j]-v[2,i]))/vsky + dvdt*dtbvdq[1,k,p]
#b_{sky}^2 = (x[1,j]-x[1,i])^2+(x[2,j]-x[2,i])^2
dtbvdq[3,k,p] = 2*((jac_step[indj ,indp+k]-jac_step[indi ,indp+k])*(x[1,j]-x[1,i])+(jac_step[indj+1,indp+k]-jac_step[indi+1,indp+k])*(x[2,j]-x[2,i]))
end
end
# return the transit time, impact parameter, and sky velocity:
return tt::T,vsky::T,bsky2::T
else
return tt::T
end
end
"""
Finds the transit by taking a partial ah18 step from prior times step, computes timing Jacobian, dtdq, wrt initial cartesian coordinates, masses:
"""
function findtransit3!(i::Int64,j::Int64,n::Int64,h::T,tt::T,m::Array{T,1},x1::Array{T,2},v1::Array{T,2},xerror::Array{T,2},verror::Array{T,2},pair::Array{Bool,2};calcbvsky=false) where {T <: Real}
# Computes the transit time, approximating the motion as a fraction of a DH17 step forward in time.
# Also computes the Jacobian of the transit time with respect to the initial parameters, dtdq[7,n].
# This version is same as findtransit2, but uses the derivative of dh17 step with respect to time
# rather than the instantaneous acceleration for finding transit time derivative (gdot).
# Initial guess using linear interpolation:
dt = one(T)
iter = 0
r3 = zero(T)
gdot = zero(T)
gsky = gdot
x = copy(x1); v = copy(v1); xerr_trans = copy(xerror); verr_trans = copy(verror)
dqdt = zeros(T,7*n)
#TRANSIT_TOL = 10*sqrt(eps(dt)
TRANSIT_TOL = 10*eps(dt)
ITMAX = 20
tt1 = tt + 1
tt2 = tt + 2
#while abs(dt) > TRANSIT_TOL && iter < 20
while true
tt2 = tt1
tt1 = tt
x .= x1; v .= v1; xerr_trans .= xerror; verr_trans .= verror
# Advance planet state at start of step to estimated transit time:
# dh17!(x,v,tt,m,n,pair)
#dh17!(x,v,xerror,verror,tt,m,n,dqdt,pair)
ah18!(x,v,xerr_trans,verr_trans,tt,m,n,dqdt,pair)
# Compute time offset:
gsky = g!(i,j,x,v)
# # Compute derivative of g with respect to time:
gdot = ((x[1,j]-x[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(x[2,j]-x[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5])
+ (v[1,j]-v[1,i])*(dqdt[(j-1)*7+1]-dqdt[(i-1)*7+1])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+2]-dqdt[(i-1)*7+2]))
# Refine estimate of transit time with Newton's method:
dt = -gsky/gdot
# Add refinement to estimated time:
tt += dt
iter +=1
# Break out if we have reached maximum iterations, or if
# current transit time estimate equals one of the prior two steps:
if (iter >= ITMAX) || (tt == tt1) || (tt == tt2)
break
end
end
if iter >= 20
# println("Exceeded iterations: planet ",j," iter ",iter," dt ",dt," gsky ",gsky," gdot ",gdot)
end
# Note: this is the time elapsed *after* the beginning of the timestep:
if calcbvsky
# Compute the sky velocity and impact parameter:
vsky = sqrt((v[1,j]-v[1,i])^2 + (v[2,j]-v[2,i])^2)
bsky2 = (x[1,j]-x[1,i])^2 + (x[2,j]-x[2,i])^2
# return the transit time, impact parameter, and sky velocity:
return tt::T,vsky::T,bsky2::T
else
return tt::T
end
end
"""Used in computing transit time inside `findtransit3`."""
function g!(i::Int64,j::Int64,x::Array{T,2},v::Array{T,2}) where {T <: Real}
# See equation 8-10 Fabrycky (2008) in Seager Exoplanets book
g = (x[1,j]-x[1,i])*(v[1,j]-v[1,i])+(x[2,j]-x[2,i])*(v[2,j]-v[2,i])
return g
end
"""
Computes TTVs as a function of orbital elements, allowing for a single log perturbation of dlnq for body jq and element iq. (NO GRADIENT)
"""
function ttv_elements!(H::Union{Int64,Array{Int64,1}},t0::T,h::T,tmax::T,elements::Array{T,2},tt::Array{T,2},count::Array{Int64,1},dlnq::T,iq::Int64,jq::Int64,rstar::T;fout="",iout=-1,pair = zeros(Bool,H[1],H[1])) where {T <: Real}
#
# Input quantities:
# n = number of bodies
# t0 = initial time of integration [days]
# h = time step [days]
# tmax = duration of integration [days]
# elements[i,j] = 2D n x 7 array of the masses & orbital elements of the bodies (currently first body's orbital elements are ignored)
# elements are ordered as: mass, period, t0, e*cos(omega), e*sin(omega), inclination, longitude of ascending node (Omega)
# tt = pre-allocated array to hold transit times of size [n x max(ntt)] (currently only compute transits of star, so first row is zero) [days]
# upon output, set to transit times of planets.
# count = pre-allocated array of the number of transits for each body upon output
#
# dlnq = fractional variation in initial parameter jq of body iq for finite-difference calculation of
# derivatives [this is only needed for testing derivative code, below].
#
# Example: see test_ttv_elements.jl in test/ directory
#
#fcons = open("fcons.txt","w");
# Set up mass, position & velocity arrays. NDIM =3
n = H[1]
m=zeros(T,n)
x=zeros(T,NDIM,n)
v=zeros(T,NDIM,n)
# Fill the transit-timing array with zeros:
fill!(tt,0.0)
# Counter for transits of each planet:
fill!(count,0)
# Insert masses from the elements array:
for i=1:n
m[i] = elements[i,1]
end
# Allow for perturbations to initial conditions: jq labels body; iq labels phase-space element (or mass)
# iq labels phase-space element (1-3: x; 4-6: v; 7: m)
dq = zero(T)
if iq == 7 && dlnq != 0.0
dq = m[jq]*dlnq
m[jq] += dq
end
# Initialize the N-body problem using nested hierarchy of Keplerians:
init = ElementsIC(t0,H,elements)
x,v,_ = init_nbody(init)
#elements_big=big.(elements); t0big = big(t0)
#init_big = ElementsIC(elements_big,H,t0big)
#xbig,vbig,_ = init_nbody(init_big)
#if T != BigFloat
# println("Difference in x,v init: ",x-convert(Array{T,2},xbig)," ",v-convert(Array{T,2},vbig)," (dlnq version)")
#end
#x = convert(Array{T,2},xbig); v = convert(Array{T,2},vbig)
# Perturb the initial condition by an amount dlnq (if it is non-zero):
if dlnq != 0.0 && iq > 0 && iq < 7
if iq < 4
if x[iq,jq] != 0
dq = x[iq,jq]*dlnq
else
dq = dlnq
end
x[iq,jq] += dq
else
# Same for v
if v[iq-3,jq] != 0
dq = v[iq-3,jq]*dlnq
else
dq = dlnq
end
v[iq-3,jq] += dq
end
end
ttv!(n,t0,h,tmax,m,x,v,tt,count,fout,iout,rstar,pair)
return dq
end
"""
Computes TTVs as a function of initial x,v,m. (NO GRADIENT).
"""
function ttv!(n::Int64,t0::T,h::T,tmax::T,m::Array{T,1},x::Array{T,2},v::Array{T,2},tt::Array{T,2},count::Array{Int64,1},fout::String,iout::Int64,rstar::T,pair::Array{Bool,2}) where {T <: Real}
# Make some copies to allocate space for saving prior step and computing coordinates at the times of transit.
xprior = copy(x)
vprior = copy(v)
xtransit = copy(x)
vtransit = copy(v)
#xerror = zeros(x); verror = zeros(v)
xerror = copy(x); verror = copy(v)
fill!(xerror,zero(T)); fill!(verror,zero(T))
#xerr_prior = zeros(x); verr_prior = zeros(v)
xerr_prior = copy(xerror); verr_prior = copy(verror)
# Set the time to the initial time:
t = t0
# Define error estimate based on Kahan (1965):
s2 = zero(T)
# Set step counter to zero:
istep = 0
# Jacobian for each step (7 elements+mass, n_planets, 7 elements+mass, n planets):
# Save the g function, which computes the relative sky velocity dotted with relative position
# between the planets and star:
gsave = zeros(T,n)
gi = 0.0
dt::T = 0.0
# Loop over time steps:
ntt_max = size(tt)[2]
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m))
if fout != ""
# Open file for output:
file_handle =open(fout,"a")
end
# Output initial conditions:
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n))]') # Transpose to write each line
end
while t < t0+tmax && param_real
# Carry out a phi^2 mapping step:
# phi2!(x,v,h,m,n)
ah18!(x,v,xerror,verror,h,m,n,pair)
# xbig = big.(x); vbig = big.(v); hbig = big(h); mbig = big.(m)
#dh17!(x,v,xerror,verror,h,m,n,pair)
# dh17!(xbig,vbig,hbig,mbig,n,pair)
# x .= convert(Array{Float64,2},xbig); v .= convert(Array{Float64,2},vbig)
param_real = all(isfinite.(x)) && all(isfinite.(v)) && all(isfinite.(m))
# Check to see if a transit may have occured. Sky is x-y plane; line of sight is z.
# Star is body 1; planets are 2-nbody:
for i=2:n
# Compute the relative sky velocity dotted with position:
gi = g!(i,1,x,v)
ri = sqrt(x[1,i]^2+x[2,i]^2+x[3,i]^2)
# See if sign switches, and if planet is in front of star (by a good amount):
if gi > 0 && gsave[i] < 0 && x[3,i] > 0.25*ri && ri < rstar
# A transit has occurred between the time steps.
# Approximate the planet-star motion as a Keplerian, weighting over timestep:
count[i] += 1
# tt[i,count[i]]=t+findtransit!(i,h,gi,gsave[i],m,xprior,vprior,x,v,pair)
if count[i] <= ntt_max
dt0 = -gsave[i]*h/(gi-gsave[i])
xtransit .= xprior
vtransit .= vprior
# dt = findtransit2!(1,i,n,h,dt0,m,xtransit,vtransit,pair)
#hbig = big(h); dt0big=big(dt0); mbig=big.(m); xtbig = big.(xtransit); vtbig = big.(vtransit)
#dtbig = findtransit2!(1,i,n,hbig,dt0big,mbig,xtbig,vtbig,pair)
#dt = convert(Float64,dtbig)
dt = findtransit3!(1,i,n,h,dt0,m,xtransit,vtransit,xerr_prior,verr_prior,pair)
#tt[i,count[i]]=t+dt
tt[i,count[i]],stmp = comp_sum(t,s2,dt)
end
# tt[i,count[i]]=t+findtransit2!(1,i,n,h,gi,gsave[i],m,xprior,vprior,pair)
end
gsave[i] = gi
end
# Save the current state as prior state:
xprior .= x
vprior .= v
xerr_prior .= xerror
verr_prior .= verror
# Increment time by the time step using compensated summation:
#s2 += h; tmp = t + s2; s2 = (t - tmp) + s2
#t = tmp
t,s2 = comp_sum(t,s2,h)
if mod(istep,iout) == 0 && iout > 0
# Write to file:
writedlm(file_handle,[convert(Float64,t);convert(Array{Float64,1},reshape(x,3n));convert(Array{Float64,1},reshape(v,3n))]') # Transpose to write each line
end
# t += h <- this leads to loss of precision
# Increment counter by one:
istep +=1
# println("xerror: ",xerror)
# println("verror: ",verror)
end
#println("xerror: ",xerror)
#println("verror: ",verror)
if fout != ""
# Close output file:
close(file_handle)
end
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 12728 | # Written by Jack Wisdom in June and July, 2015.
# David M. Hernandez helped test and improve it.
# Translated to Julia by Eric Agol August 2018.
#include "universal.h"
int solve_universal_newton(double kc, double r0, double beta, double b, double eta, double zeta, double h,
double *X, double *S2, double *C2)
{
double x;
double g1, g2, g3, arg;
double s2, c2, xnew;
int count;
double cc;
double adx;
xnew = *X;
count = 0;
do {
x = xnew;
arg = b*x/2.0;
s2 = sin(arg);
c2 = cos(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/beta;
g3 = (x - g1)/beta;
cc = eta*g1 + zeta*g2;
xnew = (h + (x*cc - (eta*g2 + zeta*g3)))/(r0 + cc);
if(count++ > 10) {
return(FAILURE);
}
} while(fabs((x-xnew)/xnew) > 1.e-8);
/* compute the output */
x = xnew;
arg = b*x/2.0;
s2 = sin(arg);
c2 = cos(arg);
*X = x;
*S2 = s2;
*C2 = c2;
return(SUCCESS);
}
int solve_universal_laguerre(double kc, double r0, double beta, double b, double eta, double zeta, double h,
double *X, double *S2, double *C2)
{
double x;
double g1, g2, g3;
double arg, s2, c2, xnew, dx;
double f, fp, fpp, g0;
int count;
double cc;
xnew = *X;
count = 0;
do {
double c5=5.0, c16 = 16.0, c20 = 20.0;
x = xnew;
arg = b*x/2.0;
s2 = sin(arg);
c2 = cos(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/beta;
g3 = (x - g1)/beta;
f = r0*x + eta*g2 + zeta*g3 - h;
fp = r0 + eta*g1 + zeta*g2;
g0 = 1.0 - beta*g2;
fpp = eta*g0 + zeta*g1;
dx = -c5*f/(fp + sqrt(fabs(c16*fp*fp - c20*f*fpp)));
xnew = x + dx;
if(count++ > 10) {
return(FAILURE);
}
} while(fabs(dx) > 2.e-7*fabs(xnew));
/* refine with a last newton */
x = xnew;
arg = b*x/2.0;
s2 = sin(arg);
c2 = cos(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/beta;
g3 = (x - g1)/beta;
cc = eta*g1 + zeta*g2;
xnew = (h + (x*cc - (eta*g2 + zeta*g3)))/(r0 + cc);
x = xnew;
arg = b*x/2.0;
s2 = sin(arg);
c2 = cos(arg);
*X = x;
*S2 = s2;
*C2 = c2;
return(SUCCESS);
}
int solve_universal_bisection(double kc, double r0, double beta, double b, double eta, double zeta, double h,
double *X, double *S2, double *C2)
{
double x;
double g1, g2, g3;
double arg, s2, c2;
double f;
double X_min, X_max, X_per_period, invperiod;
int count;
double xnew;
double err;
xnew = *X;
err = 1.e-9*fabs(xnew);
/* bisection limits due to Rein et al. */
invperiod = b*beta/(2.*M_PI*kc);
X_per_period = 2.*M_PI/b;
X_min = X_per_period * floor(h*invperiod);
X_max = X_min + X_per_period;
xnew = (X_max + X_min)/2.;
count = 0;
do {
x = xnew;
arg = b*x/2.0;
s2 = sin(arg);
c2 = cos(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/beta;
g3 = (x - g1)/beta;
f = r0*x + eta*g2 + zeta*g3 - h;
if (f>=0.){
X_max = x;
}else{
X_min = x;
}
xnew = (X_max + X_min)/2.;
if(count++ > 100) return(FAILURE);
} while(fabs(x - xnew) > err);
x = xnew;
arg = b*x/2.0;
s2 = sin(arg);
c2 = cos(arg);
*X = x;
*S2 = s2;
*C2 = c2;
return(SUCCESS);
}
double sign(double x)
{
if(x > 0.0) {
return(1.0);
} else if(x < 0.0) {
return(-1.0);
} else {
return(0.0);
}
}
function cubic1(a::T, b::T, c::T) where{T <: Real}
{
double Q, R;
double theta, A, B, x1;
Q = (a*a - 3.0*b)/9.0;
R = (2.0*a*a*a - 9.0*a*b + 27.0*c)/54.0;
if(R*R < Q*Q*Q)
theta = acos(R/sqrt(Q*Q*Q));
println("three cubic roots %.16le %.16le %.16le\n",
-2.0*sqrt(Q)*cos(theta/3.0) - a/3.0,
-2.0*sqrt(Q)*cos((theta + 2.0*M_PI)/3.0) - a/3.0,
-2.0*sqrt(Q)*cos((theta - 2.0*M_PI)/3.0) - a/3.0);
exit(-1)
return x1
else
A = -sign(R)*pow(fabs(R) + sqrt(R*R - Q*Q*Q), 1./3.);
if(A == 0.0) {
B = 0.0;
} else {
B = Q/A;
}
x1 = (A + B) - a/3.0;
return(x1);
end
end
int solve_universal_parabolic(double kc, double r0, double beta, double b, double eta, double zeta, double h,
double *X, double *S2, double *C2)
{
double x;
double s2, c2;
b = 0.0;
s2 = 0.0;
c2 = 1.0;
/*
g1 = x;
g2 = x*x/2.0;
g3 = x*x*x/6.0;
g = eta*g1 + zeta*g2;
*/
/* f = r0*x + eta*g2 + zeta*g3 - h; */
/* this is just a cubic equation */
x = cubic1(3.0*eta/zeta, 6.0*r0/zeta, -6.0*h/zeta);
s2 = 0.0;
c2 = 1.0;
/* g1 = 2.0*s2*c2/b; */
/* g2 = 2.0*s2*s2/beta; */
*X = x;
*S2 = s2;
*C2 = c2;
return(SUCCESS);
}
int solve_universal_hyperbolic_newton(double kc, double r0, double minus_beta, double b, double eta, double zeta, double h,
double *X, double *S2, double *C2)
{
double x;
double g1, g2, g3;
double arg, s2, c2, xnew;
int count;
double g;
xnew = *X;
count = 0;
do {
x = xnew;
arg = b*x/2.0;
if(fabs(arg)>200.0) return(FAILURE);
s2 = sinh(arg);
c2 = cosh(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/minus_beta;
g3 = -(x - g1)/minus_beta;
g = eta*g1 + zeta*g2;
xnew = (x*g - eta*g2 - zeta*g3 + h)/(r0 + g);
if(count++ > 10) return(FAILURE);
} while(fabs(x - xnew) > 1.e-9*fabs(xnew));
x = xnew;
arg = b*x/2.0;
s2 = sinh(arg);
c2 = cosh(arg);
*X = x;
*S2 = s2;
*C2 = c2;
return(SUCCESS);
}
int solve_universal_hyperbolic_laguerre(double kc, double r0, double minus_beta, double b, double eta, double zeta, double h,
double *X, double *S2, double *C2)
{
double x;
double g0, g1, g2, g3;
double arg, s2, c2, xnew;
int count;
double f;
xnew = *X;
count = 0;
do {
double c5=5.0, c16 = 16.0, c20 = 20.0;
double fp, fpp, dx;
double den;
x = xnew;
arg = b*x/2.0;
if(fabs(arg)>50.0) return(FAILURE);
s2 = sinh(arg);
c2 = cosh(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/minus_beta;
g3 = -(x - g1)/minus_beta;
f = r0*x + eta*g2 + zeta*g3 - h;
fp = r0 + eta*g1 + zeta*g2;
g0 = 1.0 + minus_beta*g2;
fpp = eta*g0 + zeta*g1;
den = (fp + sqrt(fabs(c16*fp*fp - c20*f*fpp)));
if(den == 0.0) return(FAILURE);
dx = -c5*f/den;
xnew = x + dx;
if(count++ > 20) return(FAILURE);
} while(fabs(x - xnew) > 1.e-9*fabs(xnew));
/* refine with a step of Newton */
{
double g;
x = xnew;
arg = b*x/2.0;
if(fabs(arg)>200.0) return(FAILURE);
s2 = sinh(arg);
c2 = cosh(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/minus_beta;
g3 = -(x - g1)/minus_beta;
g = eta*g1 + zeta*g2;
xnew = (x*g - eta*g2 - zeta*g3 + h)/(r0 + g);
}
x = xnew;
arg = b*x/2.0;
s2 = sinh(arg);
c2 = cosh(arg);
*X = x;
*S2 = s2;
*C2 = c2;
return(SUCCESS);
}
int solve_universal_hyperbolic_bisection(double kc, double r0, double minus_beta, double b, double eta, double zeta, double h,
double *X, double *S2, double *C2)
{
double x;
double g1, g2, g3;
double arg, s2, c2, xnew;
int count;
double X_min, X_max;
double f;
double err;
xnew = *X;
err = 1.e-10*fabs(xnew);
X_min = 0.5*xnew;
X_max = 10.0*xnew;
{
double fmin, fmax;
x = X_min;
arg = b*x/2.0;
if(fabs(arg)>200.0) return(FAILURE);
s2 = sinh(arg);
c2 = cosh(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/minus_beta;
g3 = -(x - g1)/minus_beta;
fmin = r0*x + eta*g2 + zeta*g3 - h;
x = X_max;
arg = b*x/2.0;
if(fabs(arg)>200.0) {
x = 200.0/(b/2.0);
arg = 200.0;
}
s2 = sinh(arg);
c2 = cosh(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/minus_beta;
g3 = -(x - g1)/minus_beta;
fmax = r0*x + eta*g2 + zeta*g3 - h;
if(fmin*fmax > 0.0) {
return(FAILURE);
}
}
count = 0;
do {
x = xnew;
arg = b*x/2.0;
if(fabs(arg)>200.0) return(FAILURE);
s2 = sinh(arg);
c2 = cosh(arg);
g1 = 2.0*s2*c2/b;
g2 = 2.0*s2*s2/minus_beta;
g3 = -(x - g1)/minus_beta;
f = r0*x + eta*g2 + zeta*g3 - h;
if (f>=0.){
X_max = x;
}else{
X_min = x;
}
xnew = (X_max + X_min)/2.;
if(count++ > 100) return(FAILURE);
} while(fabs(x - xnew) > err);
x = xnew;
arg = b*x/2.0;
s2 = sinh(arg);
c2 = cosh(arg);
*X = x;
*S2 = s2;
*C2 = c2;
return(SUCCESS);
}
void kepler_step(double kc, double dt, State *s0, State *s)
{
void kepler_step_depth();
double r0, v2, eta, beta, zeta, b;
r0 = sqrt(s0->x*s0->x + s0->y*s0->y + s0->z*s0->z);
v2 = s0->xd*s0->xd + s0->yd*s0->yd + s0->zd*s0->zd;
eta = s0->x*s0->xd + s0->y*s0->yd + s0->z*s0->zd;
beta = 2.0*kc/r0 - v2;
zeta = kc - beta*r0;
b = sqrt(fabs(beta));
kepler_step_depth(kc, dt, beta, b, s0, s, 0, r0, v2, eta, zeta);
}
void kepler_step_depth(double kc, double dt, double beta, double b,
State *s0, State *s, int depth,
double r0, double v2, double eta, double zeta)
{
int flag;
State ss;
int kepler_step_internal();
if(depth > 30) {
printf("kepler depth exceeded\n");
exit(-1);
}
flag = kepler_step_internal(kc, dt, beta, b, s0, s, r0, v2, eta, zeta);
if(flag == FAILURE) {
kepler_step_depth(kc, dt/4.0, beta, b, s0, &ss, depth+1, r0, v2, eta, zeta);
r0 = sqrt(ss.x*ss.x + ss.y*ss.y + ss.z*ss.z);
v2 = ss.xd*ss.xd + ss.yd*ss.yd + ss.zd*ss.zd;
eta = ss.x*ss.xd + ss.y*ss.yd + ss.z*ss.zd;
zeta = kc - beta*r0;
kepler_step_depth(kc, dt/4.0, beta, b, &ss, s, depth+1, r0, v2, eta, zeta);
r0 = sqrt(s->x*s->x + s->y*s->y + s->z*s->z);
v2 = s->xd*s->xd + s->yd*s->yd + s->zd*s->zd;
eta = s->x*s->xd + s->y*s->yd + s->z*s->zd;
zeta = kc - beta*r0;
kepler_step_depth(kc, dt/4.0, beta, b, s, &ss, depth+1, r0, v2, eta, zeta);
r0 = sqrt(ss.x*ss.x + ss.y*ss.y + ss.z*ss.z);
v2 = ss.xd*ss.xd + ss.yd*ss.yd + ss.zd*ss.zd;
eta = ss.x*ss.xd + ss.y*ss.yd + ss.z*ss.zd;
zeta = kc - beta*r0;
kepler_step_depth(kc, dt/4.0, beta, b, &ss, s, depth+1, r0, v2, eta, zeta);
}
}
function new_guess(r0::T, eta::T, zeta::T, dt::T) where {T <: Real}
nil = zero(T)
if (zeta != zro)
s = cubic1(3eta/zeta, 6r0/zeta, -6dt/zeta)
elseif (eta != nil)
reta = r0/eta
disc = reta*reta + 2dt/eta
if (disc >= nil)
s = -reta + sqrt(disc)
else
s = dt/r0
end
else
s = dt/r0
end
return s
end
int kepler_step_internal(double kc, double dt, double beta, double b,
State *s0, State *s,
double r0, double v2, double eta, double zeta)
{
double r;
double c2, s2;
double G1, G2;
double a, x;
int flag;
double c, ca, bsa;
if(beta < 0.0) {
double x0;
x0 = new_guess(r0, eta, zeta, dt);
x = x0;
flag = solve_universal_hyperbolic_newton(kc, r0, -beta, b, eta, zeta, dt, &x, &s2, &c2);
if(flag == FAILURE) {
x = x0;
flag = solve_universal_hyperbolic_laguerre(kc, r0, -beta, b, eta, zeta, dt, &x, &s2, &c2);
}
/*
if(flag == FAILURE) {
x = x0;
flag = solve_universal_hyperbolic_bisection(kc, r0, -beta, b, eta, zeta, dt, &x, &s2, &c2);
}
*/
if(flag == FAILURE) {
return(FAILURE);
}
a = kc/(-beta);
G1 = 2.0*s2*c2/b;
c = 2.0*s2*s2;
G2 = c/(-beta);
ca = c*a;
r = r0 + eta*G1 + zeta*G2;
bsa = (a/r)*(b/r0)*2.0*s2*c2;
} else if(beta > 0.0) {
double x0;
double ff, fp;
/* x0 = dt/r0; */
x0 = dt/r0;
ff = zeta*x0*x0*x0 + 3.0*eta*x0*x0;
fp = 3.0*zeta*x0*x0 + 6.0*eta*x0 + 6.0*r0;
x0 -= ff/fp;
x = x0;
flag = solve_universal_newton(kc, r0, beta, b, eta, zeta, dt, &x, &s2, &c2);
if(flag == FAILURE) {
x = x0;
flag = solve_universal_laguerre(kc, r0, beta, b, eta, zeta, dt, &x, &s2, &c2);
}
/*
if(flag == FAILURE) {
x = x0;
flag = solve_universal_bisection(kc, r0, beta, b, eta, zeta, dt, &x, &s2, &c2);
}
*/
if(flag == FAILURE) {
return(FAILURE);
}
a = kc/beta;
G1 = 2.0*s2*c2/b;
c = 2.0*s2*s2;
G2 = c/beta;
ca = c*a;
r = r0 + eta*G1 + zeta*G2;
bsa = (a/r)*(b/r0)*2.0*s2*c2;
} else {
x = dt/r0;
flag = solve_universal_parabolic(kc, r0, beta, b, eta, zeta, dt, &x, &s2, &c2);
if(flag == FAILURE) {
exit(-1);
}
G1 = x;
G2 = x*x/2.0;
ca = kc*G2;
r = r0 + eta*G1 + zeta*G2;
bsa = kc*x/(r*r0);
}
{
double g, fdot, fhat, gdothat;
/* f = 1.0 - (ca/r0); */
fhat = -(ca/r0);
g = eta*G2 + r0*G1;
fdot = -bsa;
/* gdot = 1.0 - (ca/r); */
gdothat = -(ca/r);
s->x = s0->x + (fhat*s0->x + g*s0->xd);
s->y = s0->y + (fhat*s0->y + g*s0->yd);
s->z = s0->z + (fhat*s0->z + g*s0->zd);
s->xd = s0->xd + (fdot*s0->x + gdothat*s0->xd);
s->yd = s0->yd + (fdot*s0->y + gdothat*s0->yd);
s->zd = s0->zd + (fdot*s0->z + gdothat*s0->zd);
}
return(SUCCESS);
}
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4377 | # Wisdom & Hernandez version of Kepler solver, but with quartic
# convergence.
function calc_ds_opt(y,yp,ypp,yppp)
# Computes quartic Newton's update to equation y=0 using first through 3rd derivatives.
# Uses techniques outlined in Murray & Dermott for Kepler solver.
# Rearrange to reduce number of divisions:
num = y*yp
den1 = yp*yp-y*ypp*.5
den12 = den1*den1
den2 = yp*den12-num*.5*(ypp*den1-third*num*yppp)
return -y*den12/den2
end
function kep_elliptic!(x0::Array{Float64,1},v0::Array{Float64,1},r0::Float64,dr0dt::Float64,k::Float64,h::Float64,beta0::Float64,s0::Float64,state::Array{Float64,1})
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in elliptical Kepler case:
if beta0 > 1e-15
# Initial guess (if s0 = 0):
if s0 == 0.0
s = h*r0inv
else
s = copy(s0)
end
s0 = copy(s)
sqb = sqrt(beta0)
y = 0.0; yp = 1.0
iter = 0
ds = Inf
fac1 = k-r0*beta0
fac2 = r0*dr0dt
while iter == 0 || (abs(ds) > 1e-8 && iter < 10)
xx = sqb*s
sx = sqb*sin(xx)
cx = cos(xx)
# Third derivative:
yppp = fac1*cx - fac2*sx
# Take derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = fac1*beta0inv*sx + fac2*cx
y = (-ypp + fac2 +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
end
# if iter > 2
# println(iter," ",s," ",s/s0-1," ds: ",ds)
# end
# Since we updated s, need to recompute:
xx = 0.5*sqb*s; sx = sin(xx) ; cx = cos(xx)
# Now, compute final values:
g1bs = 2.*sx*cx/sqb
g2bs = 2.*sx^2*beta0inv
f = 1.0 - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + fac2*g2bs # eqn (27)
for j=1:3
# Position is components 2-4 of state:
state[1+j] = x0[j]*f+v0[j]*g
end
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = r0*(1.0-beta0*g2bs+dr0dt*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
else
println("Not elliptic ",beta0," x0 ",x0)
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
function kep_hyperbolic!(x0::Array{Float64,1},v0::Array{Float64,1},r0::Float64,dr0dt::Float64,k::Float64,h::Float64,beta0::Float64,s0::Float64,state::Array{Float64,1})
# Solves equation (35) from Wisdom & Hernandez for the hyperbolic case.
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in hyperbolic Kepler case:
if beta0 < -1e-15
# Initial guess (if s0 = 0):
if s0 == 0.0
s = h*r0inv
else
s = copy(s0)
end
s0 = copy(s)
sqb = sqrt(-beta0)
y = 0.0; yp = 1.0
iter = 0
ds = Inf
fac1 = k-r0*beta0
fac2 = r0*dr0dt
while iter == 0 || (abs(ds) > 1e-8 && iter < 10)
xx = sqb*s; cx = cosh(xx); sx = sqb*(exp(xx)-cx)
# Third derivative:
yppp = fac1*cx + fac2*sx
# Take derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = -fac1*beta0inv*sx + fac2*cx
y = (-ypp +fac2 +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
end
# if iter > 2
# #println("iter: ",iter," ds/s: ",ds/s0)
# println(iter," ",s," ",s/s0-1," ds: ",ds)
# end
xx = 0.5*sqb*s; cx = cosh(xx); sx = exp(xx)-cx
# Now, compute final values:
g1bs = 2.0*sx*cx/sqb
g2bs = -2.0*sx^2*beta0inv
f = 1.0 - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + fac2*g2bs # eqn (27)
for j=1:3
state[1+j] = x0[j]*f+v0[j]*g
end
# r = norm(x)
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = r0*(1.0-beta0*g2bs+dr0dt*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
else
println("Not hyperbolic",beta0," x0 ",x0)
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 12409 | # Wisdom & Hernandez version of Kepler solver, but with quartic
# convergence.
function calc_ds_opt(y::T,yp::T,ypp::T,yppp::T) where {T <: Real}
# Computes quartic Newton's update to equation y=0 using first through 3rd derivatives.
# Uses techniques outlined in Murray & Dermott for Kepler solver.
# Rearrange to reduce number of divisions:
num = y*yp
den1 = yp*yp-y*ypp*.5
den12 = den1*den1
den2 = yp*den12-num*.5*(ypp*den1-third*num*yppp)
return -y*den12/den2
end
function solve_kepler!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,
r0::T,dr0dt::T,s0::T,state::Array{T,1}) where {T <: Real}
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
# Solves elliptic Kepler's equation for both elliptic and hyperbolic cases.
# Initial guess (if s0 = 0):
r0inv = inv(r0)
beta0inv = inv(beta0)
signb = sign(beta0)
if s0 == zero
s = h*r0inv
else
s = copy(s0)
end
s0 = copy(s)
sqb = sqrt(signb*beta0)
y = zero; yp = one
iter = 0
ds = Inf
fac1 = k-r0*beta0
fac2 = r0*dr0dt
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < 10)
xx = sqb*s
# sx = sqb*sin(xx)
# cx = cos(xx)
# eval(Expr(:call,trig,xx,cx,sx))
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
sx *= sqb
# Third derivative:
yppp = fac1*cx - signb*fac2*sx
# Take derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = signb*fac1*beta0inv*sx + fac2*cx
y = (-ypp + fac2 +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
end
#println("iter: ",iter," s0: ",s0," s: ",s," ds: ",ds)
# Since we updated s, need to recompute:
xx = 0.5*sqb*s #; sx = sin(xx) ; cx = cos(xx)
#xx = 0.5*sqb*s; cx = cosh(xx); sx = exp(xx)-cx
#eval(Expr(:call,trig,xx,cx,sx))
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
#if beta0 > 0
# cos_sin!(xx,cx,sx)
#else
# cosh_sinh!(xx,cx,sx)
#end
#println("beta0: ",beta0," xx: ",xx," cx: ",cx," sx: ",sx)
# Now, compute final values:
g1bs = 2.*sx*cx/sqb
g2bs = 2.*signb*sx^2*beta0inv
f = one - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + fac2*g2bs # eqn (27)
#println("f: ",f," g: ",g)
#println("k: ",k," r0inv: ",r0inv," g2bs: ",g2bs," r0: ",r0," g1bs: ",g1bs," fac2: ",fac2)
for j=1:3
# Position is components 2-4 of state:
state[1+j] = x0[j]*f+v0[j]*g
end
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = r0*(one-beta0*g2bs+dr0dt*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
return s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter
end
#function kep_elliptic!(x0::Array{Float64,1},v0::Array{Float64,1},r0::Float64,dr0dt::Float64,k::Float64,h::Float64,beta0::Float64,s0::Float64,state::Array{Float64,1})
function kep_ell_hyp!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,
beta0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
# Now, solve for s in elliptical Kepler case:
f = zero; g=zero; dfdt=zero; dgdt=zero; cx=zero;sx=zero;g1bs=zero;g2bs=zero
s=zero; ds = zero; r = zero;rinv=zero; iter=0
if beta0 > zero || beta0 < zero
s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter = solve_kepler!(h,k,x0,v0,beta0,r0,dr0dt,
s0,state)
else
println("Not elliptic or hyperbolic ",beta0," x0 ",x0)
r= zero; fill!(state,zero); rinv=zero; s=zero; ds=zero; iter = 0
end
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# recompute beta:
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
#function kep_elliptic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1},jacobian::Array{T,2})
function kep_ell_hyp!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1},jacobian::Array{T,2}) where {T <: Real}
# Computes the Jacobian as well
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in elliptical Kepler case:
f = zero; g=zero; dfdt=zero; dgdt=zero; cx=zero;sx=zero;g1bs=zero;g2bs=zero
s=zero; ds=zero; r = zero;rinv=zero; iter=0
if beta0 > zero || beta0 < zero
# solve_kepler!(h,k,x0,v0,beta0,s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r0,dr0dt,r,
# rinv,ds,s0,state,iter)
s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter = solve_kepler!(h,k,x0,v0,beta0,r0,dr0dt,
s0,state)
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v} & q0 = {x0,v0}.
fill!(jacobian,zero)
compute_jacobian!(h,k,x0,v0,beta0,s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r0,dr0dt,r,jacobian)
else
println("Not elliptic or hyperbolic ",beta0," x0 ",x0)
r= zero; fill!(state,zero); rinv=zero; s=zero; ds=zero; iter = 0
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
#function kep_hyperbolic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1})
function kep_hyperbolic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Solves equation (35) from Wisdom & Hernandez for the hyperbolic case.
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in hyperbolic Kepler case:
if beta0 < zero
# solve_kepler!()
else
println("Not hyperbolic",beta0," x0 ",x0)
r= zero; fill!(state,zero); rinv=zero; s=zero; ds=zero; iter = 0
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
#function kep_hyperbolic!(x0::Array{Float64,1},v0::Array{Float64,1},r0::Float64,dr0dt::Float64,k::Float64,h::Float64,beta0::Float64,s0::Float64,state::Array{Float64,1},jacobian::Array{Float64,2})
function kep_hyperbolic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1},jacobian::Array{T,2}) where {T <: Real}
# Solves equation (35) from Wisdom & Hernandez for the hyperbolic case.
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in hyperbolic Kepler case:
if beta0 < zero
# Initial guess (if s0 = 0):
if s0 == zero
s = h*r0inv
else
s = copy(s0)
end
s0 = copy(s)
sqb = sqrt(-beta0)
y = zero; yp = one
iter = 0
ds = Inf
fac1 = k-r0*beta0
fac2 = r0*dr0dt
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < 10)
xx = sqb*s; cx = cosh(xx); sx = sqb*(exp(xx)-cx)
# Third derivative:
yppp = fac1*cx + fac2*sx
# Take derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = -fac1*beta0inv*sx + fac2*cx
y = (-ypp +fac2 +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
# println(iter," ds: ",ds)
end
# if iter > 1
# #println("iter: ",iter," ds/s: ",ds/s0)
# println(iter," ",s," ",s/s0-1," ds: ",ds)
# end
xx = 0.5*sqb*s; cx = cosh(xx); sx = exp(xx)-cx
# Now, compute final values:
g1bs = 2.0*sx*cx/sqb
g2bs = -2.0*sx^2*beta0inv
f = one - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + fac2*g2bs # eqn (27)
for j=1:3
state[1+j] = x0[j]*f+v0[j]*g
end
# r = norm(x)
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = r0*(one-beta0*g2bs+dr0dt*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
# Now, compute the jacobian:
fill!(jacobian,zero)
compute_jacobian!(h,k,x0,v0,beta0,s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r0,dr0dt,r,jacobian)
else
println("Not hyperbolic",beta0," x0 ",x0)
r= zero; fill!(state,zero); rinv=zero; s=zero; ds=zero; iter = 0
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
# function compute_jacobian!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,s::T,f::T,g::T,dfdt::T,dgdt::T,cx::T,sx::T,g1::T,g2::T,r0::T,dr0dt::T,r::T,jacobian::Array{T,2})
function compute_jacobian!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,s::T,f::T,g::T,dfdt::T,dgdt::T,cx::T,sx::T,g1::T,g2::T,r0::T,dr0dt::T,r::T,jacobian::Array{T,2}) where {T <: Real}
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v,k} & q0 = {x0,v0,k}.
# Now, compute the Jacobian: (9/18/2017 notes)
#g0 = cx^2-sx^2
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
g0 = one-beta0*g2
g3 = (s-g1)/beta0
dotalpha0 = r0*dr0dt # unnecessary to divide by r0 for dr0dt & multiply for \dot\alpha_0
absv0 = sqrt(dot(v0,v0))
dsdbeta = (2h-r0*(s*g0+g1)+k/beta0*(s*g0-g1)-dotalpha0*s*g1)/(2beta0*r)
dsdr0 = -(2k/r0^2*dsdbeta+g1/r)
dsda0 = -g2/r
dsdv0 = -2absv0*dsdbeta
dsdk = 2/r0*dsdbeta-g3/r
dbetadr0 = -2k/r0^2
dbetadv0 = -2absv0
dbetadk = 2/r0
# "p" for partial derivative:
#pxpr0 = zeros(Float64,3); pxpa0=zeros(Float64,3); pxpk=zeros(Float64,3); pxps=zeros(Float64,3); pxpbeta=zeros(Float64,3)
#dxdr0 = zeros(Float64,3); dxda0=zeros(Float64,3); dxdk=zeros(Float64,3); dxdv0 =zeros(Float64,3)
#prvpr0 = zeros(Float64,3); prvpa0=zeros(Float64,3); prvpk=zeros(Float64,3); prvps=zeros(Float64,3); prvpbeta=zeros(Float64,3)
#drvdr0 = zeros(Float64,3); drvda0=zeros(Float64,3); drvdk=zeros(Float64,3); drvdv0=zeros(Float64,3)
#vtmp = zeros(Float64,3); dvdr0 = zeros(Float64,3); dvda0=zeros(Float64,3); dvdv0=zeros(Float64,3); dvdk=zeros(Float64,3)
for i=1:3
pxpr0[i] = k/r0^2*g2*x0[i]+g1*v0[i]
pxpa0[i] = g2*v0[i]
pxpk[i] = -g2/r0*x0[i]
pxps[i] = -k/r0*g1*x0[i]+(r0*g0+dotalpha0*g1)*v0[i]
pxpbeta[i] = -k/(2beta0*r0)*(s*g1-2g2)*x0[i]+1/(2beta0)*(s*r0*g0-r0*g1+s*dotalpha0*g1-2*dotalpha0*g2)*v0[i]
prvpr0[i] = k*g1/r0^2*x0[i]+g0*v0[i]
prvpa0[i] = g1*v0[i]
prvpk[i] = -g1/r0*x0[i]
prvps[i] = -k*g0/r0*x0[i]+(-beta0*r0*g1+dotalpha0*g0)*v0[i]
prvpbeta[i] = -k/(2beta0*r0)*(s*g0-g1)*x0[i]+1/(2beta0)*(-s*r0*beta0*g1+dotalpha0*s*g0-dotalpha0*g1)*v0[i]
end
prpr0 = g0
prpa0 = g1
prpk = g2
prps = (k-beta0*r0)*g1+dotalpha0*g0
prpbeta = 1/(2beta0)*(s*(k-beta0*r0)*g1+dotalpha0*s*g0-dotalpha0*g1-2k*g2)
for i=1:3
dxdr0[i] = pxps[i]*dsdr0 + pxpbeta[i]*dbetadr0 + pxpr0[i]
dxda0[i] = pxps[i]*dsda0 + pxpa0[i]
dxdv0[i] = pxps[i]*dsdv0 + pxpbeta[i]*dbetadv0
dxdk[i] = pxps[i]*dsdk + pxpbeta[i]*dbetadk + pxpk[i]
drvdr0[i] = prvps[i]*dsdr0 + prvpbeta[i]*dbetadr0 + prvpr0[i]
drvda0[i] = prvps[i]*dsda0 + prvpa0[i]
drvdv0[i] = prvps[i]*dsdv0 + prvpbeta[i]*dbetadv0
drvdk[i] = prvps[i]*dsdk + prvpbeta[i]*dbetadk +prvpk[i]
end
drdr0 = prpr0 + prps*dsdr0 + prpbeta*dbetadr0
drda0 = prpa0 + prps*dsda0
drdv0 = prps*dsdv0 + prpbeta*dbetadv0
drdk = prpk + prps*dsdk + prpbeta*dbetadk
for i=1:3
vtmp[i] = dfdt*x0[i]+dgdt*v0[i]
dvdr0[i] = (drvdr0[i]-drdr0*vtmp[i])/r
dvda0[i] = (drvda0[i]-drda0*vtmp[i])/r
dvdv0[i] = (drvdv0[i]-drdv0*vtmp[i])/r
dvdk[i] = (drvdk[i] -drdk *vtmp[i])/r
end
# Now, compute Jacobian:
for i=1:3
jacobian[ i, i] = f
jacobian[ i,3+i] = g
jacobian[3+i, i] = dfdt
jacobian[3+i,3+i] = dgdt
jacobian[ i,7] = dxdk[i]
jacobian[3+i,7] = dvdk[i]
end
for j=1:3
for i=1:3
jacobian[ i, j] += dxdr0[i]*x0[j]/r0 + dxda0[i]*v0[j]
jacobian[ i,3+j] += dxdv0[i]*v0[j]/absv0 + dxda0[i]*x0[j]
jacobian[3+i, j] += dvdr0[i]*x0[j]/r0 + dvda0[i]*v0[j]
jacobian[3+i,3+j] += dvdv0[i]*v0[j]/absv0 + dvda0[i]*x0[j]
end
end
jacobian[7,7]=one
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 13593 | # Wisdom & Hernandez version of Kepler solver, but with quartic
# convergence.
function calc_ds_opt(y::T,yp::T,ypp::T,yppp::T) where {T <: Real}
# Computes quartic Newton's update to equation y=0 using first through 3rd derivatives.
# Uses techniques outlined in Murray & Dermott for Kepler solver.
# Rearrange to reduce number of divisions:
num = y*yp
den1 = yp*yp-y*ypp*.5
den12 = den1*den1
den2 = yp*den12-num*.5*(ypp*den1-third*num*yppp)
return -y*den12/den2
end
#function kep_elliptic!(x0::Array{Float64,1},v0::Array{Float64,1},r0::Float64,dr0dt::Float64,k::Float64,h::Float64,beta0::Float64,s0::Float64,state::Array{Float64,1})
function kep_elliptic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,
beta0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in elliptical Kepler case:
if beta0 > zero
# Initial guess (if s0 = 0):
if s0 == zero
s = h*r0inv
else
s = copy(s0)
end
s0 = copy(s)
sqb = sqrt(beta0)
y = zero; yp = one
iter = 0
ds = Inf
fac1 = k-r0*beta0
fac2 = r0*dr0dt
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < 10)
xx = sqb*s
sx = sqb*sin(xx)
cx = cos(xx)
# Third derivative:
yppp = fac1*cx - fac2*sx
# Take derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = fac1*beta0inv*sx + fac2*cx
y = (-ypp + fac2 +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
# println(iter," ds: ",ds)
end
# if iter > 1
# println(iter," ",s," ",s/s0-1," ds: ",ds)
# end
# Since we updated s, need to recompute:
xx = 0.5*sqb*s; sx = sin(xx) ; cx = cos(xx)
# Now, compute final values:
g1bs = 2.*sx*cx/sqb
g2bs = 2.*sx^2*beta0inv
f = one - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + fac2*g2bs # eqn (27)
for j=1:3
# Position is components 2-4 of state:
state[1+j] = x0[j]*f+v0[j]*g
end
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = r0*(one-beta0*g2bs+dr0dt*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
else
println("Not elliptic ",beta0," x0 ",x0)
r= zero; fill!(state,zero); rinv=zero; s=zero; ds=zero; iter = 0
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
#function kep_elliptic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1},jacobian::Array{T,2})
function kep_elliptic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1},jacobian::Array{T,2}) where {T <: Real}
# Computes the Jacobian as well
# Solves equation (35) from Wisdom & Hernandez for the elliptic case.
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in elliptical Kepler case:
if beta0 > zero
# Initial guess (if s0 = 0):
if s0 == zero
s = h*r0inv
else
s = copy(s0)
end
s0 = copy(s)
sqb = sqrt(beta0)
y = zero; yp = one
iter = 0
ds = Inf
fac1 = k-r0*beta0
fac2 = r0*dr0dt
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < 10)
xx = sqb*s
sx = sqb*sin(xx)
cx = cos(xx)
# Third derivative:
yppp = fac1*cx - fac2*sx
# Take derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = fac1*beta0inv*sx + fac2*cx
y = (-ypp + fac2 +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
# println(iter," ds: ",ds)
end
# if iter > 1
# println(iter," ",s," ",s/s0-1," ds: ",ds)
# end
# Since we updated s, need to recompute:
xx = 0.5*sqb*s; sx = sin(xx) ; cx = cos(xx)
# Now, compute final values:
g1bs = 2.*sx*cx/sqb
g2bs = 2.*sx^2*beta0inv
f = one - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + fac2*g2bs # eqn (27)
for j=1:3
# Position is components 2-4 of state:
state[1+j] = x0[j]*f+v0[j]*g
end
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = r0*(one-beta0*g2bs+dr0dt*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
# Now, compute the jacobian:
fill!(jacobian,zero)
compute_jacobian!(h,k,x0,v0,beta0,s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r0,dr0dt,r,jacobian)
else
println("Not elliptic ",beta0," x0 ",x0)
r= zero; fill!(state,zero); rinv=zero; s=zero; ds=zero; iter = 0
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v} & q0 = {x0,v0}.
return iter
end
#function kep_hyperbolic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1})
function kep_hyperbolic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Solves equation (35) from Wisdom & Hernandez for the hyperbolic case.
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in hyperbolic Kepler case:
if beta0 < zero
# Initial guess (if s0 = 0):
if s0 == zero
s = h*r0inv
else
s = copy(s0)
end
s0 = copy(s)
sqb = sqrt(-beta0)
y = zero; yp = one
iter = 0
ds = Inf
fac1 = k-r0*beta0
fac2 = r0*dr0dt
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < 10)
xx = sqb*s; cx = cosh(xx); sx = sqb*(exp(xx)-cx)
# Third derivative:
yppp = fac1*cx + fac2*sx
# Take derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = -fac1*beta0inv*sx + fac2*cx
y = (-ypp +fac2 +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
# println(iter," ds: ",ds)
end
# if iter > 1
# #println("iter: ",iter," ds/s: ",ds/s0)
# println(iter," ",s," ",s/s0-1," ds: ",ds)
# end
xx = 0.5*sqb*s; cx = cosh(xx); sx = exp(xx)-cx
# Now, compute final values:
g1bs = 2.0*sx*cx/sqb
g2bs = -2.0*sx^2*beta0inv
f = one - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + fac2*g2bs # eqn (27)
for j=1:3
state[1+j] = x0[j]*f+v0[j]*g
end
# r = norm(x)
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = r0*(one-beta0*g2bs+dr0dt*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
else
println("Not hyperbolic",beta0," x0 ",x0)
r= zero; fill!(state,zero); rinv=zero; s=zero; ds=zero; iter = 0
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
#function kep_hyperbolic!(x0::Array{Float64,1},v0::Array{Float64,1},r0::Float64,dr0dt::Float64,k::Float64,h::Float64,beta0::Float64,s0::Float64,state::Array{Float64,1},jacobian::Array{Float64,2})
function kep_hyperbolic!(x0::Array{T,1},v0::Array{T,1},r0::T,dr0dt::T,k::T,h::T,beta0::T,s0::T,state::Array{T,1},jacobian::Array{T,2}) where {T <: Real}
# Solves equation (35) from Wisdom & Hernandez for the hyperbolic case.
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
r0inv = inv(r0)
beta0inv = inv(beta0)
# Now, solve for s in hyperbolic Kepler case:
if beta0 < zero
# Initial guess (if s0 = 0):
if s0 == zero
s = h*r0inv
else
s = copy(s0)
end
s0 = copy(s)
sqb = sqrt(-beta0)
y = zero; yp = one
iter = 0
ds = Inf
fac1 = k-r0*beta0
fac2 = r0*dr0dt
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < 10)
xx = sqb*s; cx = cosh(xx); sx = sqb*(exp(xx)-cx)
# Third derivative:
yppp = fac1*cx + fac2*sx
# Take derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = -fac1*beta0inv*sx + fac2*cx
y = (-ypp +fac2 +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
# println(iter," ds: ",ds)
end
# if iter > 1
# #println("iter: ",iter," ds/s: ",ds/s0)
# println(iter," ",s," ",s/s0-1," ds: ",ds)
# end
xx = 0.5*sqb*s; cx = cosh(xx); sx = exp(xx)-cx
# Now, compute final values:
g1bs = 2.0*sx*cx/sqb
g2bs = -2.0*sx^2*beta0inv
f = one - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + fac2*g2bs # eqn (27)
for j=1:3
state[1+j] = x0[j]*f+v0[j]*g
end
# r = norm(x)
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = r0*(one-beta0*g2bs+dr0dt*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
# Now, compute the jacobian:
fill!(jacobian,zero)
compute_jacobian!(h,k,x0,v0,beta0,s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r0,dr0dt,r,jacobian)
else
println("Not hyperbolic",beta0," x0 ",x0)
r= zero; fill!(state,zero); rinv=zero; s=zero; ds=zero; iter = 0
end
# recompute beta:
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
# function compute_jacobian!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,s::T,f::T,g::T,dfdt::T,dgdt::T,cx::T,sx::T,g1::T,g2::T,r0::T,dr0dt::T,r::T,jacobian::Array{T,2})
function compute_jacobian!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,s::T,f::T,g::T,dfdt::T,dgdt::T,cx::T,sx::T,g1::T,g2::T,r0::T,dr0dt::T,r::T,jacobian::Array{T,2}) where {T <: Real}
# Compute the Jacobian. jacobian[i,j] is derivative of final state variable q[i]
# with respect to initial state variable q0[j], where q = {x,v,k} & q0 = {x0,v0,k}.
# Now, compute the Jacobian: (9/18/2017 notes)
#g0 = cx^2-sx^2
zero = convert(typeof(h),0.0); one = convert(typeof(h),1.0)
g0 = one-beta0*g2
g3 = (s-g1)/beta0
dotalpha0 = r0*dr0dt # unnecessary to divide by r0 for dr0dt & multiply for \dot\alpha_0
absv0 = sqrt(dot(v0,v0))
dsdbeta = (2h-r0*(s*g0+g1)+k/beta0*(s*g0-g1)-dotalpha0*s*g1)/(2beta0*r)
dsdr0 = -(2k/r0^2*dsdbeta+g1/r)
dsda0 = -g2/r
dsdv0 = -2absv0*dsdbeta
dsdk = 2/r0*dsdbeta-g3/r
dbetadr0 = -2k/r0^2
dbetadv0 = -2absv0
dbetadk = 2/r0
# "p" for partial derivative:
#pxpr0 = zeros(Float64,3); pxpa0=zeros(Float64,3); pxpk=zeros(Float64,3); pxps=zeros(Float64,3); pxpbeta=zeros(Float64,3)
#dxdr0 = zeros(Float64,3); dxda0=zeros(Float64,3); dxdk=zeros(Float64,3); dxdv0 =zeros(Float64,3)
#prvpr0 = zeros(Float64,3); prvpa0=zeros(Float64,3); prvpk=zeros(Float64,3); prvps=zeros(Float64,3); prvpbeta=zeros(Float64,3)
#drvdr0 = zeros(Float64,3); drvda0=zeros(Float64,3); drvdk=zeros(Float64,3); drvdv0=zeros(Float64,3)
#vtmp = zeros(Float64,3); dvdr0 = zeros(Float64,3); dvda0=zeros(Float64,3); dvdv0=zeros(Float64,3); dvdk=zeros(Float64,3)
for i=1:3
pxpr0[i] = k/r0^2*g2*x0[i]+g1*v0[i]
pxpa0[i] = g2*v0[i]
pxpk[i] = -g2/r0*x0[i]
pxps[i] = -k/r0*g1*x0[i]+(r0*g0+dotalpha0*g1)*v0[i]
pxpbeta[i] = -k/(2beta0*r0)*(s*g1-2g2)*x0[i]+1/(2beta0)*(s*r0*g0-r0*g1+s*dotalpha0*g1-2*dotalpha0*g2)*v0[i]
prvpr0[i] = k*g1/r0^2*x0[i]+g0*v0[i]
prvpa0[i] = g1*v0[i]
prvpk[i] = -g1/r0*x0[i]
prvps[i] = -k*g0/r0*x0[i]+(-beta0*r0*g1+dotalpha0*g0)*v0[i]
prvpbeta[i] = -k/(2beta0*r0)*(s*g0-g1)*x0[i]+1/(2beta0)*(-s*r0*beta0*g1+dotalpha0*s*g0-dotalpha0*g1)*v0[i]
end
prpr0 = g0
prpa0 = g1
prpk = g2
prps = (k-beta0*r0)*g1+dotalpha0*g0
prpbeta = 1/(2beta0)*(s*(k-beta0*r0)*g1+dotalpha0*s*g0-dotalpha0*g1-2k*g2)
for i=1:3
dxdr0[i] = pxps[i]*dsdr0 + pxpbeta[i]*dbetadr0 + pxpr0[i]
dxda0[i] = pxps[i]*dsda0 + pxpa0[i]
dxdv0[i] = pxps[i]*dsdv0 + pxpbeta[i]*dbetadv0
dxdk[i] = pxps[i]*dsdk + pxpbeta[i]*dbetadk + pxpk[i]
drvdr0[i] = prvps[i]*dsdr0 + prvpbeta[i]*dbetadr0 + prvpr0[i]
drvda0[i] = prvps[i]*dsda0 + prvpa0[i]
drvdv0[i] = prvps[i]*dsdv0 + prvpbeta[i]*dbetadv0
drvdk[i] = prvps[i]*dsdk + prvpbeta[i]*dbetadk +prvpk[i]
end
drdr0 = prpr0 + prps*dsdr0 + prpbeta*dbetadr0
drda0 = prpa0 + prps*dsda0
drdv0 = prps*dsdv0 + prpbeta*dbetadv0
drdk = prpk + prps*dsdk + prpbeta*dbetadk
for i=1:3
vtmp[i] = dfdt*x0[i]+dgdt*v0[i]
dvdr0[i] = (drvdr0[i]-drdr0*vtmp[i])/r
dvda0[i] = (drvda0[i]-drda0*vtmp[i])/r
dvdv0[i] = (drvdv0[i]-drdv0*vtmp[i])/r
dvdk[i] = (drvdk[i] -drdk *vtmp[i])/r
end
# Now, compute Jacobian:
for i=1:3
jacobian[ i, i] = f
jacobian[ i,3+i] = g
jacobian[3+i, i] = dfdt
jacobian[3+i,3+i] = dgdt
jacobian[ i,7] = dxdk[i]
jacobian[3+i,7] = dvdk[i]
end
for j=1:3
for i=1:3
jacobian[ i, j] += dxdr0[i]*x0[j]/r0 + dxda0[i]*v0[j]
jacobian[ i,3+j] += dxdv0[i]*v0[j]/absv0 + dxda0[i]*x0[j]
jacobian[3+i, j] += dvdr0[i]*x0[j]/r0 + dvda0[i]*v0[j]
jacobian[3+i,3+j] += dvdv0[i]*v0[j]/absv0 + dvda0[i]*x0[j]
end
end
jacobian[7,7]=one
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 1839 | include("kepler_solver_derivative.jl")
# Takes a single kepler step, calling Wisdom & Hernandez solver
#
#function kepler_step!(gm::Float64,h::Float64,state0::Array{Float64,1},state::Array{Float64,1})
function kepler_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1}) where {T <: Real}
# compute beta, r0, dr0dt, get x/v from state vector & call correct subroutine
x0 = zeros(eltype(state0),3)
v0 = zeros(eltype(state0),3)
zero = 0.0*h
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
# x0=state0[2:4]
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
# v0 = state0[5:7]
dr0dt = (x0[1]*v0[1]+x0[2]*v0[2]+x0[3]*v0[3])/r0
beta0 = 2*gm/r0-(v0[1]*v0[1]+v0[2]*v0[2]+v0[3]*v0[3])
s0=state0[11]
iter = kep_ell_hyp!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state)
# if beta0 > zero
# iter = kep_elliptic!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state)
# else
# iter = kep_hyperbolic!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state)
# end
return
end
#function kepler_step!(gm::Float64,h::Float64,state0::Array{Float64,1},state::Array{Float64,1},jacobian::Array{Float64,2})
function kepler_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1},jacobian::Array{T,2}) where {T <: Real}
# compute beta, r0, dr0dt, get x/v from state vector & call correct subroutine
x0 = zeros(eltype(state0),3)
v0 = zeros(eltype(state0),3)
zero = 0.0*h
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
# x0=state0[2:4]
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
# v0 = state0[5:7]
dr0dt = (x0[1]*v0[1]+x0[2]*v0[2]+x0[3]*v0[3])/r0
beta0 = 2*gm/r0-(v0[1]*v0[1]+v0[2]*v0[2]+v0[3]*v0[3])
s0=state0[11]
iter = kep_ell_hyp!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state,jacobian)
# if beta0 > zero
# iter = kep_elliptic!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state,jacobian)
# else
# iter = kep_hyperbolic!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state,jacobian)
# end
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 1704 | include("kepler_solver_derivative.jl")
# Takes a single kepler step, calling Wisdom & Hernandez solver
#
#function kepler_step!(gm::Float64,h::Float64,state0::Array{Float64,1},state::Array{Float64,1})
function kepler_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1}) where {T <: Real}
# compute beta, r0, dr0dt, get x/v from state vector & call correct subroutine
x0 = zeros(eltype(state0),3)
v0 = zeros(eltype(state0),3)
zero = 0.0*h
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
# x0=state0[2:4]
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
# v0 = state0[5:7]
dr0dt = (x0[1]*v0[1]+x0[2]*v0[2]+x0[3]*v0[3])/r0
beta0 = 2*gm/r0-(v0[1]*v0[1]+v0[2]*v0[2]+v0[3]*v0[3])
s0=state0[11]
if beta0 > zero
iter = kep_elliptic!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state)
else
iter = kep_hyperbolic!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state)
end
return
end
#function kepler_step!(gm::Float64,h::Float64,state0::Array{Float64,1},state::Array{Float64,1},jacobian::Array{Float64,2})
function kepler_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1},jacobian::Array{T,2}) where {T <: Real}
# compute beta, r0, dr0dt, get x/v from state vector & call correct subroutine
x0 = zeros(eltype(state0),3)
v0 = zeros(eltype(state0),3)
zero = 0.0*h
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
# x0=state0[2:4]
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
# v0 = state0[5:7]
dr0dt = (x0[1]*v0[1]+x0[2]*v0[2]+x0[3]*v0[3])/r0
beta0 = 2*gm/r0-(v0[1]*v0[1]+v0[2]*v0[2]+v0[3]*v0[3])
s0=state0[11]
if beta0 > zero
iter = kep_elliptic!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state,jacobian)
else
iter = kep_hyperbolic!(x0,v0,r0,dr0dt,gm,h,beta0,s0,state,jacobian)
end
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4037 | # Carries out a Kepler step for bodies i & j
function keplerij!(m::Array{Float64,1},x::Array{Float64,2},v::Array{Float64,2},i::Int64,j::Int64,h::Float64,jac_ij::Array{Float64,2})
# The state vector has: 1 time; 2-4 position; 5-7 velocity; 8 r0; 9 dr0dt; 10 beta; 11 s; 12 ds
# Initial state:
state0 = zeros(Float64,12)
# Final state (after a step):
state = zeros(Float64,12)
delx = zeros(Float64,NDIM)
delv = zeros(Float64,NDIM)
# jac_ij should be the Jacobian for going from (x_{0,i},v_{0,i},m_i) & (x_{0,j},v_{0,j},m_j)
# to (x_i,v_i,m_i) & (x_j,v_j,m_j), a 14x14 matrix for the 3-dimensional case.
# Fill with zeros for now:
fill!(jac_ij,0.0)
for k=1:NDIM
state0[1+k ] = x[k,i] - x[k,j]
state0[1+k+NDIM] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
# The following jacobian is just computed for the Keplerian coordinates (i.e. doesn't include
# center-of-mass motion, or scale to motion of bodies about their common center of mass):
jac_kepler = zeros(Float64,7,7)
kepler_step!(gm, h, state0, state, jac_kepler)
for k=1:NDIM
delx[k] = state[1+k] - state0[1+k]
delv[k] = state[1+NDIM+k] - state0[1+NDIM+k]
end
# Compute COM coords:
mijinv =1.0/(m[i] + m[j])
xcm = zeros(Float64,NDIM)
vcm = zeros(Float64,NDIM)
mi = m[i]*mijinv # Normalize the masses
mj = m[j]*mijinv
for k=1:NDIM
xcm[k] = mi*x[k,i] + mj*x[k,j]
vcm[k] = mi*v[k,i] + mj*v[k,j]
end
# Compute the Jacobian:
jac_ij[ 7, 7] = 1.0 # the masses don't change with time!
jac_ij[14,14] = 1.0
for k=1:NDIM
jac_ij[ k, k] += mi
jac_ij[ k, 3+k] += h*mi
jac_ij[ k, 7+k] += mj
jac_ij[ k,10+k] += h*mj
jac_ij[ 3+k, 3+k] += mi
jac_ij[ 3+k,10+k] += mj
jac_ij[ 7+k, k] += mi
jac_ij[ 7+k, 3+k] += h*mi
jac_ij[ 7+k, 7+k] += mj
jac_ij[ 7+k,10+k] += h*mj
jac_ij[10+k, 3+k] += mi
jac_ij[10+k,10+k] += mj
for l=1:NDIM
# Compute derivatives of \delta x_i with respect to initial conditions:
jac_ij[ k, l] += mj*jac_kepler[ k, l]
jac_ij[ k, 3+l] += mj*jac_kepler[ k,3+l]
jac_ij[ k, 7+l] -= mj*jac_kepler[ k, l]
jac_ij[ k,10+l] -= mj*jac_kepler[ k,3+l]
# Compute derivatives of \delta v_i with respect to initial conditions:
jac_ij[ 3+k, l] += mj*jac_kepler[3+k, l]
jac_ij[ 3+k, 3+l] += mj*jac_kepler[3+k,3+l]
jac_ij[ 3+k, 7+l] -= mj*jac_kepler[3+k, l]
jac_ij[ 3+k,10+l] -= mj*jac_kepler[3+k,3+l]
# Compute derivatives of \delta x_j with respect to initial conditions:
jac_ij[ 7+k, l] -= mi*jac_kepler[ k, l]
jac_ij[ 7+k, 3+l] -= mi*jac_kepler[ k,3+l]
jac_ij[ 7+k, 7+l] += mi*jac_kepler[ k, l]
jac_ij[ 7+k,10+l] += mi*jac_kepler[ k,3+l]
# Compute derivatives of \delta v_j with respect to initial conditions:
jac_ij[10+k, l] -= mi*jac_kepler[3+k, l]
jac_ij[10+k, 3+l] -= mi*jac_kepler[3+k,3+l]
jac_ij[10+k, 7+l] += mi*jac_kepler[3+k, l]
jac_ij[10+k,10+l] += mi*jac_kepler[3+k,3+l]
end
# Compute derivatives of \delta x_i with respect to the masses:
jac_ij[ k, 7] += (x[k,i]+h*v[k,i]-xcm[k]-mj*state[1+k])*mijinv + GNEWT*mj*jac_kepler[ k,7]
jac_ij[ k,14] += (x[k,j]+h*v[k,j]-xcm[k]+mi*state[1+k])*mijinv + GNEWT*mj*jac_kepler[ k,7]
# Compute derivatives of \delta v_i with respect to the masses:
jac_ij[ 3+k, 7] += (v[k,i]-vcm[k]-mj*state[4+k])*mijinv + GNEWT*mj*jac_kepler[3+k,7]
jac_ij[ 3+k,14] += (v[k,j]-vcm[k]+mi*state[4+k])*mijinv + GNEWT*mj*jac_kepler[3+k,7]
# Compute derivatives of \delta x_j with respect to the masses:
jac_ij[ 7+k, 7] += (x[k,i]+h*v[k,i]-xcm[k]-mj*state[1+k])*mijinv - GNEWT*mi*jac_kepler[ k,7]
jac_ij[ 7+k,14] += (x[k,j]+h*v[k,j]-xcm[k]+mi*state[1+k])*mijinv - GNEWT*mi*jac_kepler[ k,7]
# Compute derivatives of \delta v_j with respect to the masses:
jac_ij[10+k, 7] += (v[k,i]-vcm[k]-mj*state[4+k])*mijinv - GNEWT*mi*jac_kepler[3+k,7]
jac_ij[10+k,14] += (v[k,j]-vcm[k]+mi*state[4+k])*mijinv - GNEWT*mi*jac_kepler[3+k,7]
end
# Advance center of mass & individual Keplerian motions:
centerm!(m,mijinv,x,v,vcm,delx,delv,i,j,h)
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 5580 | # Translation of David Hernandez's nbody.c for integrating hiercharical
# system with BH15 integrator. Please cite Hernandez & Bertschinger (2015)
# if using this in a paper.
const YEAR = 365.242
const GNEWT = 39.4845/YEAR^2
const NDIM = 3
const third = 1./3.
include("kepler_step.jl")
include("init_nbody.jl")
function nbody!(t0::Float64,h::Float64,tmax::Float64,elements::Array{Float64,2},t_out::Array{Float64,1},state_out::Array{Float64,2},nstep::Int64)
fcons = open("fcons.txt","w");
n=8
m=zeros(n)
x=zeros(NDIM,n)
v=zeros(NDIM,n)
L0=zeros(NDIM)
p0=zeros(NDIM)
xcm0=zeros(NDIM)
ssave = zeros(n,n,3)
# Read in the initial orbital elements from a file (this
# should be moved to an input parameter):
elements = readdlm("elements.txt",',')
for i=1:n
m[i] = elements[i,1]
end
# Initialize the N-body problem using nested hierarchy of Keplerians:
x,v = init_nbody(elements,t0,n)
# infig1!(m,x,v,n)
# Compute the conserved quantities:
E0=consq!(m,x,v,n,L0,p0,xcm0)
#println("E0: ",E0," L0: ",L0," p0: ",p0," xcm0: ",xcm0)
#read(STDIN,Char)
# Set the time to the initial time:
t = t0
# Set step counter to zero:
i=0
#nstep = 1
# Loop over time steps:
while t < t0+tmax
# Increment time by the time step:
t += h
# Increment counter by one:
i +=1
# Carry out a phi^2 mapping step:
phi2!(x,v,h,m,n)
# Every nstep steps, output the state of the system:
if mod(i,nstep) == 0
state_string = @sprintf("%18.12f",t)
for j=1:n
state_string = string(state_string,@sprintf("%18.12f",x[1,j]),@sprintf("%18.12f",x[3,j]),@sprintf("%18.12f",v[1,j]),@sprintf("%18.12f",v[3,j]))
end
state_string = state_string*"\n"
print(fcons,state_string)
end
#
end
# Compute the final values of the conserved quantities:
L=zeros(NDIM)
p=zeros(NDIM)
xcm=zeros(NDIM)
E=consq!(m,x,v,n,L,p,xcm)
println("dE/E=",(E0-E)/E0)
# Close the output file:
close(fcons)
return
end
# Advances the center of mass of a binary
function centerm!(m::Array{Float64,1},x::Array{Float64,2},v::Array{Float64,2},delx::Array{Float64,1},delv::Array{Float64,1},i::Int64,j::Int64,h::Float64)
vcm=zeros(NDIM)
mij =m[i] + m[j]
if mij == 0
for k=1:NDIM
vcm[k] = (v[k,i]+v[k,j])/2
x[k,i] += h*vcm[k]
x[k,j] += h*vcm[k]
end
else
for k=1:NDIM
vcm[k] = (m[i]*v[k,i] + m[j]*v[k,j])/mij
x[k,i] += m[j]/mij*delx[k] + h*vcm[k]
x[k,j] += -m[i]/mij*delx[k] + h*vcm[k]
v[k,i] += m[j]/mij*delv[k]
v[k,j] += -m[i]/mij*delv[k]
end
end
return
end
# Drifts bodies i & j
function driftij!(x::Array{Float64,2},v::Array{Float64,2},i::Int64,j::Int64,h::Float64)
for k=1:NDIM
x[k,i] += h*v[k,i]
x[k,j] += h*v[k,j]
end
return
end
# Carries out a Kepler step for bodies i & j
function keplerij!(m::Array{Float64,1},x::Array{Float64,2},v::Array{Float64,2},i::Int64,j::Int64,h::Float64)
# The state vector has: 1 time; 2-4 position; 5-7 velocity; 8 r0; 9 dr0dt; 10 beta; 11 s; 12 ds
# Initial state:
s0 = zeros(Float64,12)
# Final state (after a step):
s = zeros(Float64,12)
delx = zeros(NDIM)
delv = zeros(NDIM)
for k=1:NDIM
s0[1+k ] = x[k,i] - x[k,j]
s0[1+k+NDIM] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
if gm == 0
for k=1:NDIM
x[k,i] += h*v[k,i]
x[k,j] += h*v[k,j]
end
else
kepler_step!(gm, h, s0, s)
for k=1:NDIM
delx[k] = s[1+k] - s0[1+k]
delv[k] = s[1+NDIM+k] - s0[1+NDIM+k]
end
# Advance center of mass:
centerm!(m,x,v,delx,delv,i,j,h)
end
return
end
# Drifts all particles:
function drift!(x::Array{Float64,2},v::Array{Float64,2},h::Float64,n::Int64)
for i=1:n
for j=1:NDIM
x[j,i] += h*v[j,i]
end
end
return
end
# Carries out the phi^2 mapping
function phi2!(x::Array{Float64,2},v::Array{Float64,2},h::Float64,m::Array{Float64,1},n::Int64)
drift!(x,v,h/2,n)
for i=1:n-1
for j=i+1:n
driftij!(x,v,i,j,-h/2)
keplerij!(m,x,v,i,j,h/2)
end
end
for i=n-1:-1:1
for j=n:-1:i+1
keplerij!(m,x,v,i,j,h/2)
driftij!(x,v,i,j,-h/2)
end
end
drift!(x,v,h/2,n)
return
end
# Initializes the system for a specific dynamical problem: eccentric binary orbiting
# a larger body. Units in ~AU & yr.
function infig1!(m::Array{Float64,1},x::Array{Float64,2},v::Array{Float64,2},n::Int64)
a0 = 0.0125
a1 = 1.0
e0 = 0.6
e1 = 0
m[1] = 1e-3
m[2] = 1e-3
m[3] = 1.0
mu0 = (m[1]*m[2])/(m[1]+m[2])
mt0 = m[1]+m[2]
mu1 = (m[3]*mt0)/(m[3]+mt0)
mt1 = m[3]+mt0
x0 = a0*(1+e0)
x1 = a1*(1+e1)
v0 = sqrt(GNEWT*mt0/a0*(1-e0)/(1+e0))
v1 = sqrt(GNEWT*mt1/a1*(1-e1)/(1+e1))
fa0 = m[1]/mt0
fb0 = m[2]/mt0
fa1 = mt0/mt1
fb1 = m[3]/mt1
x[1,1] = -fb1*x1-fb0*x0
x[1,2] = -fb1*x1+fa0*x0
x[1,3] = fa1*x1
v[2,1] = -fb1*v1-fb0*v0
v[2,2] = -fb1*v1+fa0*v0
v[2,3] = fa1*v1
return
end
# Computes conserved quantities:
function consq!(m::Array{Float64,1},x::Array{Float64,2},v::Array{Float64,2},n::Int64,
L::Array{Float64,1},p::Array{Float64,1},xcm::Array{Float64,1})
fill!(p,0.0) # =zeros(NDIM)
fill!(xcm,0.0) # =zeros(NDIM)
fill!(L,0.0) # =zeros(NDIM)
E = 0.0
for i=1:n
if m[i] != 0
for j=1:NDIM
p[j] += m[i]*v[j,i];
xcm[j] += m[i]*x[j,i];
end
L[1] += m[i]*(x[2,i]*v[3,i]-x[3,i]*v[2,i]);
L[2] += m[i]*(x[3,i]*v[1,i]-x[1,i]*v[3,i]);
L[3] += m[i]*(x[1,i]*v[2,i]-x[2,i]*v[1,i]);
end
for j=1:NDIM
E += 1.0/2.0*m[i]*v[j,i]*v[j,i];
end
for j=i+1:n
if m[j] != 0
rij = 0.;
for k=1:NDIM
rij += (x[k,i]-x[k,j])*(x[k,i]-x[k,j]);
end
rij = sqrt(rij);
E -= GNEWT*m[i]*m[j]/rij;
end
end
end
mt=sum(m)
if mt != 0
for i=1:NDIM
xcm[i] /= mt;
p[i] /= mt;
end
end
println("L: ",L)
println("p: ",p)
println("xcm: ",xcm)
return E
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 10897 | abstract type AbstractInitialConditions end
"""
Elements{T<:AbstractFloat} <: AbstractInitialConditions
Orbital elements of a binary, and mass of a 'outer' body. See [Tutorials](@ref) for units and conventions.
# Fields
- `m::T` : Mass of outer body.
- `P::T` : Period [Days].
- `t0::T` : Initial time of transit [Days].
- `ecosω::T` : Eccentricity vector x-component (eccentricity times cosine of the argument of periastron)
- `esinω::T` : Eccentricity vector y-component (eccentricity times sine of the argument of periastron)
- `I::T` : Inclination, as measured from sky-plane [Radians].
- `Ω::T` : Longitude of ascending node, as measured from +x-axis [Radians].
- `a::T` : Orbital semi-major axis [AU].
- `e::T` : Eccentricity.
- `ω::T` : Argument of periastron [Radians].
- `tp::T` : Time of periastron passage [Days].
"""
struct Elements{T<:AbstractFloat} <: AbstractInitialConditions
m::T
P::T
t0::T
ecosω::T
esinω::T
I::T
Ω::T
a::T
e::T
ω::T
tp::T
end
"""
Elements(m,P,t0,ecosω,esinω,I,Ω)
Main [`Elements`](@ref) constructor. May use keyword arguments, see [Tutorials](@ref).
"""
function Elements(m::T,P::T,t0::T,ecosω::T,esinω::T,I::T,Ω::T) where T<:Real
e = sqrt(ecosω^2 + esinω^2)
ω = atan(esinω,ecosω)
Elements(m,P,t0,ecosω,esinω,I,Ω,0.0,e,ω,0.0)
end
function Base.show(io::IO, ::MIME"text/plain", elems::Elements{T}) where T <: Real
fields = fieldnames(typeof(elems))
vals = [fn => getfield(elems,fn) for fn in fields]
println(io, "Elements{$T}")
for pair in vals
println(io,first(pair),": ",last(pair))
end
if elems.a == 0.0
println(io, "Orbital semi-major axis: undefined")
end
return
end
iszeroall(x...) = all(iszero.(x))
isnanall(x...) = all(isnan.(x))
replacenan(x) = isnan(x) ? zero(x) : x
"""Allows keyword arguments"""
function Elements(;m::Real,P::Real=NaN,t0::Real=NaN,ecosω::Real=NaN,esinω::Real=NaN,I::Real=NaN,Ω::Real=NaN,a::Real=NaN,ω::Real=NaN,e::Real=NaN,tp::Real=NaN)
# Promote everything
m,P,t0,ecosω,esinω,I,Ω,a,ω,e,tp = promote(m,P,t0,ecosω,esinω,I,Ω,a,ω,e,tp)
T = typeof(P)
# Assume if only mass is set, we want the elements for the star (or central body in binary)
if isnanall(P,t0,ecosω,esinω,I,Ω,a,ω,e,tp); return Elements(m, zeros(T, length(fieldnames(Elements))-1)...); end
if isnanall(P,a); throw(ArgumentError("Must specify either P or a.")); end
if P > zero(T) && a > zero(T); throw(ArgumentError("Only one of P (period) or a (semi-major axis) can be defined")); end
if P < zero(T); throw(ArgumentError("Period must be positive")); end
if a < zero(T); throw(ArgumentError("Orbital semi-major axis must be positive")); end
if !(zero(T) <= e < one(T)) && !isnan(e); throw(ArgumentError("Eccentricity must be in [0,1), e=$(e)")); end
if !(isnan(ecosω) && isnan(esinω)) && !isnan(e); error("Must specify either e and ecosω/esinω, but not both."); end
if !(isnan(tp) || isnan(t0)); error("Must specify either initial transit time or time of periastron passage, but not both."); end
ω = replacenan(ω)
if isnanall(e,ecosω,esinω); e = ecosω = esinω = zero(T); end
if isnan(e)
ecosω = replacenan(ecosω)
esinω = replacenan(esinω)
e = sqrt(ecosω*ecosω + esinω*esinω)
@assert zero(T) <= e < one(T) "Eccentricity must be in [0,1)"
ω = atan(esinω, ecosω)
else
esinω, ecosω = e.*sincos(ω)
esinω = abs(esinω) < eps(T) ? zero(T) : esinω
ecosω = abs(ecosω) < eps(T) ? zero(T) : ecosω
end
t0 = replacenan(t0)
n = 2π/P
if isnan(tp) && !iszero(e)
tp = (t0 - sqrt(1.0-e*e)*ecosω/(n*(1.0-esinω)) - (2.0/n)*atan(sqrt(1.0-e)*(esinω+ecosω+e), sqrt(1.0+e)*(esinω-ecosω-e))) % P
elseif isnan(tp)
θ = π/2 + ω
tp = θ / n
end
a = replacenan(a)
I = replacenan(I)
Ω = replacenan(Ω)
return Elements(m,P,t0,ecosω,esinω,I,Ω,a,e,ω,tp)
end
# Handle the deprecated fields
function Base.getproperty(obj::Elements, sym::Symbol)
if (sym === :ecosϖ)
Base.depwarn("ecosϖ (\\varpi) will be removed, use ecosω (\\omega).", :getproperty, force=true)
return obj.ecosω
end
if (sym === :esinϖ)
Base.depwarn("esinϖ (\\varpi) will be removed, use esinω (\\omega).", :getproperty, force=true)
return obj.esinω
end
if (sym === :ϖ)
Base.depwarn("ϖ (\\varpi) will be removed, use ω (\\omega).", :getproperty, force=true)
return obj.ω
end
return getfield(obj, sym)
end
"""Abstract type for initial conditions specifications."""
abstract type InitialConditions{T} end
"""
ElementsIC{T<:AbstractFloat} <: InitialConditions{T}
Initial conditions, specified by a hierarchy vector and orbital elements.
# Fields
- `elements::Matrix{T}` : Masses and orbital elements.
- `ϵ::Matrix{T}` : Matrix of Jacobi coordinates
- `amat::Matrix{T}` : 'A' matrix from [Hamers and Portegies Zwart 2016](https://doi.org/10.1093/mnras/stw784).
- `nbody::Int64` : Number of bodies.
- `m::Vector{T}` : Masses of bodies.
- `t0::T` : Initial time [Days].
"""
struct ElementsIC{T<:AbstractFloat} <: InitialConditions{T}
elements::Matrix{T}
ϵ::Matrix{T}
amat::Matrix{T}
nbody::Int64
m::Vector{T}
t0::T
der::Bool
function ElementsIC(t0::T, H::Matrix{T}, elements::Matrix{T}; der::Bool=true) where T<:AbstractFloat
nbody = size(H)[1]
m = elements[1:nbody, 1]
A = amatrix(H, m)
# Allow user to input more orbital elements than used, but only use N
if size(elements) != (nbody, 7)
elements = copy(elements[1:nbody,:])
end
return new{T}(copy(elements), copy(H), A, nbody, m, t0, der)
end
end
ElementsIC(t0::T, H::Matrix{<:Real}, elements::Matrix{T}) where T<:Real = ElementsIC(t0, T.(H), elements)
"""
ElementsIC(t0,H,elems)
Collects `Elements` and produces an `ElementsIC` struct.
# Arguments
- `t0::T` : Initial time [Days].
- `H` : Hierarchy specification.
- `elems` : The orbital elements and masses of the system.
------------
There are a number of way to specify the initial conditions. Below we've described the arguments `ElementsIC` takes. Any combination of `H` and `elems` may be used. For a concrete example see [Tutorials](@ref).
# Elements
- `elems...` : A sequence of `Elements{T}`. Elements should be passed in the order they appear in the hierarchy (left to right).
- `elems::Vector{Elements}` : A vector of `Elements`. As above, Elements should be in order.
- `elems::Matrix{T}` : An matrix containing the masses and orbital elements.
- `elems::String` : Name of a file containing the masses and orbital elements.
Each method is simply populating the `ElementsIC.elements` field, which is a `Matrix{T}`.
# Hierarchy
- Number of bodies: `H::Int64`: The system will be given by a 'fully-nested' Keplerian.
`H = 4` corresponds to:
```raw
3 ____|____
| |
2 ___|___ d
| |
1 __|__ c
| |
a b
```
- Hierarchy Vector: `H::Vector{Int64}`: The first elements is the number of bodies. Each subsequent is the number of binaries on a level of the hierarchy.
`H = [4,2,1]`. Two binaries on level 1, one on level 2.
```raw
2 ____|____
| |
1 __|__ __|__
| | | |
a b c d
```
- Full Hierarchy Matrix: `H::Matrix{<:Real}`: Provide the hierarchy matrix, directly.
`H = [-1 1 0 0; 0 0 -1 1; -1 -1 1 1; -1 -1 -1 -1]`. Produces the same system as `H = [4,2,1]`.
"""
function ElementsIC(t0::T, H::Matrix{<:Real}, elems::Elements{T}...) where T<:AbstractFloat
elements = zeros(T,size(H)[1],7)
fields = [:m, :P, :t0, :ecosω, :esinω, :I, :Ω]
for i in eachindex(elems)
elements[i,:] .= [getfield(elems[i],f) for f in fields]
end
return ElementsIC(t0,T.(H),elements)
end
"""Allows for vector of `Elements` argument."""
ElementsIC(t0::T,H::Matrix{<:Real},elems::Vector{Elements{T}}) where T<:AbstractFloat = ElementsIC(t0,T.(H),elems...)
"""Allow user to pass a file containing orbital elements."""
function ElementsIC(t0::T,H::Matrix{<:Real},elems::String) where T<:AbstractFloat
elements = T.(readdlm(elems, ',', comments=true)[1:size(H)[1],:])
return ElementsIC(t0, T.(H), elements)
end
## Let user pass hierarchy vector; dispatch on different elements ##
ElementsIC(t0::T,H::Vector{Int64},elems::Elements{T}...) where T <: AbstractFloat = ElementsIC(t0,hierarchy(H),elems...)
ElementsIC(t0::T,H::Vector{Int64},elems::Vector{Elements{T}}) where T<:AbstractFloat = ElementsIC(t0,hierarchy(H),elems...)
ElementsIC(t0::T,H::Vector{Int64},elems::Matrix{T}) where T<:AbstractFloat = ElementsIC(t0,hierarchy(H),elems)
ElementsIC(t0::T,H::Vector{Int64},elems::String) where T<:AbstractFloat = ElementsIC(t0,hierarchy(H),elems)
## Let user specify only the number of bodies; the hierarchy is filled in as fully-nested; dispatch on different elements ##
ElementsIC(t0::T,H::Int64,elems::Elements{T}...) where T<:AbstractFloat = ElementsIC(t0,[H, ones(Int64,H-1)...],elems...)
ElementsIC(t0::T,H::Int64,elems::Vector{Elements{T}}) where T<:AbstractFloat = ElementsIC(t0,[H, ones(Int64,H-1)...],elems...)
ElementsIC(t0::T,H::Int64,elems::Matrix{T}) where T<:AbstractFloat = ElementsIC(t0,[H, ones(Int64,H-1)...],elems)
ElementsIC(t0::T,H::Int64,elems::String) where T<:AbstractFloat = ElementsIC(t0,[H, ones(Int64, H-1)...],elems)
"""Shows the elements array."""
Base.show(io::IO,::MIME"text/plain",ic::ElementsIC{T}) where {T} = begin
println(io,"ElementsIC{$T}\nOrbital Elements: "); show(io,"text/plain",ic.elements); end;
"""
CartesianIC{T<:AbstractFloat} <: InitialConditions{T}
Initial conditions, specified by the Cartesian coordinates and masses of each body.
# Fields
- `x::Matrix{T}` : Positions of each body [dimension, body].
- `v::Matrix{T}` : Velocities of each body [dimension, body].
- `m::Vector{T}` : masses of each body.
- `nbody::Int64` : Number of bodies in system.
- `t0::T` : Initial time.
"""
struct CartesianIC{T<:AbstractFloat} <: InitialConditions{T}
x::Matrix{T}
v::Matrix{T}
m::Vector{T}
nbody::Int64
t0::T
end
"""Allow user to pass matrix of row-vectors for `CartesianIC`."""
function CartesianIC(t0::T, N::Int64, coords::Matrix{T}) where T<:AbstractFloat
m = coords[1:N,1]
x = permutedims(coords[1:N,2:4])
v = permutedims(coords[1:N,5:7])
return CartesianIC(x,v,m,N,t0)
end
"""Allow input of Cartesian coordinate file."""
function CartesianIC(t0::T, N::Int64, coordinateFile::String) where T <: AbstractFloat
coords = readdlm(coordinateFile,',')
m = coords[1:N,1]
x = permutedims(coords[1:N,2:4])
v = permutedims(coords[1:N,5:7])
return CartesianIC(x,v,m,N,t0)
end
# Include ics source files
const ics = ["kepler","kepler_init","setup_hierarchy","init_nbody","defaults"]
for i in ics; include("$(i).jl"); end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 3458 | # Some default initial conditions for testing and quick usage.
function get_trappist1_elements(t0=0.0, n=0)
# Trappist-1 orbital elements from Agol et al. 2021
elements = [
1.0 0.0 0.0 0.0 0.0 0.0 0.0
2.5901135977661885e-5 1.510880055106516 7257.547487248826 0.02436651768325364 0.018169884000968452 1.5707963267948966 0.0
5.7871255112412840e-5 2.4218013609356652 7258.592163817471 0.020060810686211832 0.011189705094395375 1.5707963267948966 0.0
1.4602772830539989e-6 4.0503542353950355 7257.023855669221 0.007411490159357976 -0.02016424872931776 1.5707963267948966 0.0
1.9235328222249013e-5 6.099281590191818 7257.816770447013 0.0011801938769616127 0.000731913417670215 1.5707963267948966 0.0
2.7302687390082730e-5 9.20618480814173 7257.1228936246725 -699952921060827e-19 0.0002252519365921506 1.5707963267948966 0.0
3.5331017018761430e-5 12.353988709624156 7257.667328639113 -0.0009722026578612578 0.001276000403979281 1.5707963267948966 0.0
1.6410627049780406e-6 18.733535095576702 7250.524231929195 -0.010402303111464135 -0.014289870200773339 1.5707963267948966 0.0
]
return elements
end
function get_kepler36_elements(t0=0.0, n=0)
# Mean Kepler-36 orbital elements from Carter et al. 2012
# Eccentricity chosen at random from e < 0.04, inclination co-planar
# Unit conversions using UnitfulAstro
elements = [
1.0 0.0 0.0 0.0 0.0 0.0 0.0
1.2479484222582662e-5 13.83989 0.0 0.002 -0.004 1.5707963267948966 0.0
2.2659378094037732e-5 16.23855 5.062100000213832 -0.01 0.007 1.5707963267948966 0.0
]
return elements
end
# Available names for users to specify to get initial conditions
# The first element in each tuple should be the key for ELEMENTS_FUNCTIONS
# rest are "aliases" for the system, if any.
const AVAILABLE_SYSTEMS = (
("trappist-1", "trappist 1"),
("kepler-36", "kepler 36")
)
const ELEMENTS_FUNCTIONS = Dict(
"trappist-1" => get_trappist1_elements,
"kepler-36" => get_kepler36_elements
)
"""Return the AVAILABLE_SYSTEMS tuple. ONLY FOR TESTS."""
_available_systems() = AVAILABLE_SYSTEMS
"""Show the available default systems with implemented initial conditions."""
function available_systems()
println(stdout, "Available Systems: ")
for s in AVAILABLE_SYSTEMS
key = first(s)
rest = setdiff(s, (first(s),))
if isempty(rest)
println(stdout, "\"$(key)\"")
else
println(stdout, "\"$(key)\" ", rest)
end
end
flush(stdout)
end
"""Get the default initial conditions for a particular system"""
function get_default_ICs(system_name, t0=0.0, n=0)
# Get the key for the elements function to call
system_key = ""
for available_names in AVAILABLE_SYSTEMS
if lowercase(system_name) ∈ available_names
system_key = first(available_names)
end
end
system_key == "" && throw(ArgumentError("$(system_name) not an available system name."))
# Get the orbital elements for the selected system
elements = ELEMENTS_FUNCTIONS[system_key]()
# Use all the bodies if user did not specify n
nmax = size(elements)[1]
if n == 0
n = nmax
elseif n > nmax
@warn "Maximum n is $(nmax). User asked for $(n). Setting to $(nmax)."
n = nmax
end
return ElementsIC(t0, n, elements)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 6294 | """
init_nbody(ic,t0)
Converts initial orbital elements into Cartesian coordinates.
# Arguments
- `ic::ElementsIC{T<:Real}`: Initial conditions of the system. See [`InitialConditions`](@ref).
# Outputs
- `x::Array{<:Real,2}`: Cartesian positions of each body.
- `v::Array{<:Real,2}`: Cartesian velocites of each body.
- `jac_init::Array{<:Real,2}`: Derivatives of A-matrix and x,v with respect to the masses of each object.
"""
function init_nbody(ic::ElementsIC{T}) where T <: AbstractFloat
r, rdot, jac_init = kepcalc(ic)
Ainv = inv(ic.amat)
# Cartesian coordinates
x = zeros(T,NDIM,ic.nbody)
x = permutedims(*(Ainv,r))
v = zeros(T,NDIM,ic.nbody)
v = permutedims(*(Ainv,rdot))
return x,v,jac_init
end
"""Return the cartesian coordinates."""
function init_nbody(ic::CartesianIC{T}) where T <: AbstractFloat
x = copy(ic.x)
v = copy(ic.v)
n = size(x)[2]
jac_init = Matrix{T}(I,7*n,7*n)
return x,v,jac_init
end
"""
kepcalc(ic,t0)
Computes Kepler's problem for each pair of bodies in the system.
# Arguments
- `ic::ElementsIC{T<:Real}`: Initial conditions structure.
# Outputs
- `rkepler::Array{T<:Real,2}`: Matrix of initial position vectors for each keplerian.
- `rdotkepler::Array{T<:Real,2}`: Matrix of initial velocity vectors for each keplerian.
- `jac_init::Array{T<:Real,2}`: Derivatives of the A-matrix and cartesian positions and velocities with respect to the masses of each object.
"""
function kepcalc(ic::ElementsIC{T}) where T<:AbstractFloat
n = ic.nbody
rkepler = zeros(T,n,NDIM)
rdotkepler = zeros(T,n,NDIM)
if ic.der
jac_kepler = zeros(T,6*n,7*n)
jac_21 = zeros(T,7,7)
end
# Compute Kepler's problem for each binary
i = 1; b = 0
while i < ic.nbody
ind = Bool.(abs.(ic.ϵ[i,:]))
μ = sum(ic.m[ind])
# Check for a new binary.
if first(ind) == zero(T)
b += 1
end
# Solve Kepler's problem
if ic.der
r,rdot = kepler_init(ic.t0,μ,ic.elements[i+1+b,2:7],jac_21)
else
r,rdot = kepler_init(ic.t0,μ,ic.elements[i+1+b,2:7])
end
rkepler[i,:] .= r
rdotkepler[i,:] .= rdot
if ic.der
for j=1:6, k=1:6
jac_kepler[(i-1)*6+j,i*7+k] = jac_21[j,k]
end
for j in 1:n
if ic.ϵ[i,j] != 0
for k = 1:6
jac_kepler[(i-1)*6+k,j*7] = jac_21[k,7]
end
end
end
end
# Check if last binary was a new branch.
if b > 0
b -= 2
elseif b < 0
b = 0
#i += 1
end
i += 1
end
if ic.der
jac_init = d_dm(ic,rkepler,rdotkepler,jac_kepler)
return rkepler,rdotkepler,jac_init
else
return rkepler,rdotkepler,zeros(T,0,0)
end
end
"""
d_dm(ic,rkepler,rdotkepler,jac_kepler)
Computes derivatives of A-matrix, position, and velocity with respect to the masses of each object.
# Arguments
- `ic::IC`: Initial conditions structure.
- `rkepler::Array{<:Real,2}`: Position vectors for each Keplerian.
- `rdotkepler::Array{<:Real,2}`: Velocity vectors for each Keplerian.
- `jac_kepler::Array{<:Real,2}`: Keplerian Jacobian matrix.
# Outputs
- `jac_init::Array{<:Real,2}`: Derivatives of the A-matrix and cartesian positions and velocities with respect to the masses of each object.
"""
function d_dm(ic::ElementsIC{T},rkepler::Array{T,2},rdotkepler::Array{T,2},jac_kepler::Array{T,2}) where T <: AbstractFloat
N = ic.nbody
m = ic.m
ϵ = ic.ϵ
jac_init = zeros(T,7*N,7*N)
dAdm = zeros(T,N,N,N)
dxdm = zeros(T,NDIM,N)
dvdm = zeros(T,NDIM,N)
# Differentiate A matrix wrt the mass of each body
for k in 1:N, i in 1:N, j in 1:N
dAdm[i,j,k] = ((δ_(k,j)*ϵ[i,j])/Σm(m,i,j,ϵ)) -
((δ_(ϵ[i,j],ϵ[i,k]))*ϵ[i,j]*m[j]/(Σm(m,i,j,ϵ)^2))
end
# Calculate inverse of dAdm
Ainv = inv(ic.amat)
dAinvdm = zeros(T,N,N,N)
for k in 1:N
dAinvdm[:,:,k] .= -Ainv * dAdm[:,:,k] * Ainv
end
# Fill in jac_init array
for i in 1:N
for k in 1:N
for j in 1:3, l in 1:7*N
jac_init[(i-1)*7+j,l] += Ainv[i,k]*jac_kepler[(k-1)*6+j,l]
jac_init[(i-1)*7+3+j,l] += Ainv[i,k]*jac_kepler[(k-1)*6+3+j,l]
end
end
# Derivatives of cartesian coordinates wrt masses
for k in 1:N
dxdm = transpose(dAinvdm[:,:,k]*rkepler)
dvdm = transpose(dAinvdm[:,:,k]*rdotkepler)
jac_init[(i-1)*7+1:(i-1)*7+3,k*7] += dxdm[1:3,i]
jac_init[(i-1)*7+4:(i-1)*7+6,k*7] += dvdm[1:3,i]
end
jac_init[i*7,i*7] = 1.0
end
return jac_init
end
"""
amatrix(elements,ϵ,m)
Creates the A matrix presented in Hamers & Portegies Zwart 2016 (HPZ16).
# Arguments
- `elements::Array{<:Real,2}`: Array of masses and orbital elements. See [`IC`](@ref)
- `ϵ::Array{<:Real,2}`: Epsilon matrix. See [`IC.elements`]
- `m::Array{<:Real,2}`: Array of masses of each body.
# Outputs
- `A::Array{<:Real,2}`: A matrix.
"""
function amatrix(ϵ::Array{T,2},m::Array{T,1}) where T<:AbstractFloat
A = zeros(T,size(ϵ)) # Empty A matrix
N = length(ϵ[:,1]) # Number of bodies in system
for i in 1:N, j in 1:N
A[i,j] = (ϵ[i,j]*m[j])/(Σm(m,i,j,ϵ))
end
return A
end
function amatrix(ic::ElementsIC{T}) where T <: Real
ic.amat .= amatrix(ic.ϵ,ic.m)
end
"""
Σm(masses,i,j,ϵ)
Sums masses in current Keplerian.
# Arguments
- `masses::Array{<:Real,2}`: Array of masses in system.
- `i::Integer`: Summation index.
- `j::Integer`: Summation index.
- `ϵ::Array{<:Real,2}`: Epsilon matrix.
# Outputs
- `m<:Real`: Sum of the masses.
"""
function Σm(masses::Array{T,1},i::Integer,j::Integer,
ϵ::Array{T,2}) where T <: AbstractFloat
m = 0.0
for l in 1:length(masses)
m += masses[l]*δ_(ϵ[i,j],ϵ[i,l])
end
return m
end
"""
δ_(i,j)
An NxN Kronecker Delta function.
# Arguements
- `i<:Real`: First arguement.
- `j<:Real`: Second arguement.
# Outputs
- `::Bool`
"""
function δ_(i::T,j::T) where T <: Real
if i == j
return 1.0
else
return 0.0
end
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 2800 | function ekepler(m::T,ecc::T) where {T <: Real}
KEPLER_TOL = sqrt(eps(m))
if m != zero(T)
#real*8 e,e0,eps,m,ms,pi2,f0,f1,f2,f3,d1,d2,d3
# This routine solves Kepler's equation for E as a function of (e,M)
# using the procedure outlined in Murray & Dermott:
pi2=2pi
ms=mod(m,pi2)
d3 =one(T)
de0=ecc*0.85*sign(ms)
de1=2*de0
de2=3*de0
iter = 0
ITMAX = 20
# while abs(d3) > KEPLER_TOL
while true
de2 = de1
de1 = de0
f3=ecc*cos(de0+ms)
f2=ecc*sin(de0+ms)
# f1=1.0-f3
# f0=de0-f2
# d1=-f0/f1
# d2=-f0/(f1+0.5*d1*f2)
# d3=-f0/(f1+d2*0.5*(f2+d2*f3/3.))
# de0 += d3
de0 = (f2-de1*f3)/(1-f3)
iter += 1
if iter >= ITMAX || de0 == de1 || de0 == de2
break
end
end
if iter >= ITMAX && !(T == BigFloat && minimum([abs(de0-de1),abs(de0-de2)]) < eps(one(T)))
# println("iterations in ekepler: ",iter," de0: ",de0," de1-de0: ",de1-de0," de2-de0: ",de2-de0)
end
ekep=de0+m
else
ekep = zero(T)
end
return ekep::typeof(m)
end
function ekepler2(m::T,ecc::T) where {T <: Real}
KEPLER_TOL = sqrt(eps(m))
if m != 0.0
#real*8 e,e0,eps,m,ms,pi2,f0,f1,f2,f3,d1,d2,d3
# This routine solves Kepler's equation for E as a function of (e,M)
# using the procedure outlined in Murray & Dermott:
pi2=2.0*pi
ms=mod(m,pi2)
d3 =one(T)
e0=ms+ecc*0.85*sin(ms)/abs(sin(ms))
e1=2*e0
e2=3*e0
# while abs(d3) > KEPLER_TOL
ITMAX = 50
while true
e2 = e1
e1 = e0
f3=ecc*cos(e0)
f2=ecc*sin(e0)
f1=1.0-f3
f0=e0-ms-f2
d1=-f0/f1
d2=-f0/(f1+0.5*d1*f2)
d3=-f0/(f1+d2*0.5*(f2+d2*f3/3.))
e0=e0+d3
if iter >= ITMAX || e0 == e1 || e0 == e2
break
end
end
if iter >= ITMAX
# println("iterations in ekepler2: ",iter," de0: ",de0," de1-de0: ",de1-de0," de2-de0: ",de2-de0)
end
ekep=e0+m-ms
else
ekep = 0.0
end
return ekep::typeof(m)
end
function kepler(m,ecc)
@assert(ecc >= 0.0)
@assert(ecc <= 1.0)
f=m
if ecc > 0
ekep=ekepler(m,ecc)
# println(m-ekep+ecc*sin(ekep))
# f=2.0*atan(sqrt((1.0+ecc)/(1.0-ecc))*tan(0.5*ekep))
# f=2.0*atan2(sqrt(1.0+ecc)*sin(0.5*ekep),sqrt(1.0-ecc)*cos(0.5*ekep))
f=2.0*atan(sqrt(1.0+ecc)*sin(0.5*ekep),sqrt(1.0-ecc)*cos(0.5*ekep))
end
return f
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 10181 | function kepler_init(time::T,mass::T,elements::Array{T,1}) where {T <: Real}
# Takes orbital elements of a single Keplerian; returns positions & velocities.
# This is 3D), so 6 orbital elements specified, the code returns 3D. For
# Inclination = pi/2, motion is in X-Z plane; sky plane is X-Y.
# Elements are given by: period, t0, e*cos(omega), e*sin(omega), Inclination, Omega
period = elements[1]
# Compute the semi-major axis in AU (or other units specified by GNEWT):
semi = cbrt(GNEWT*mass*period^2/4/pi^2)
# Convert to eccentricity & longitude of periastron:
ecc2=elements[3]^2+elements[4]^2
ecc=sqrt(ecc2)
#omega = atan2(elements[4],elements[3])
omega = atan(elements[4],elements[3])
# The true anomaly at the time of transit:
f1 = 1.5*pi-omega
# Compute the time of periastron passage:
sqrt1mecc2 = sqrt(1.0-ecc^2)
tp=(elements[2]+period*sqrt1mecc2/2.0/pi*(ecc*sin(f1)/(1.0+ecc*cos(f1))
# -2.0/sqrt1mecc2*atan2(sqrt1mecc2*tan(0.5*f1),1.0+ecc)))
-2.0/sqrt1mecc2*atan(sqrt1mecc2*tan(0.5*f1),1.0+ecc)))
# Compute the mean anomaly
n = 2pi/period
m=n*(time-tp)
# Kepler solver:
if ecc > 0.0
f = kepler(m,ecc)
else
f = m
end
ecosfp1 = 1.0+ecc*cos(f)
fdot = n*ecosfp1^2/sqrt1mecc2^3
# Compute the radial distance:
r=semi*(1.0-ecc^2)/ecosfp1
rdot = semi*n/sqrt1mecc2*ecc*sin(f)
# For now assume plane-parallel:
#inc = pi/2
#capomega = pi
inc = elements[5]
capomega = elements[6]
# Now, compute the positions
x = zeros(eltype(elements),3)
v = zeros(eltype(elements),3)
if abs(capomega-pi) > 1e-15
coscapomega = cos(capomega) ; sincapomega = sin(capomega)
else
coscapomega = -1.0 ; sincapomega = 0.0
end
cosomegapf = cos(omega+f) ; sinomegapf = sin(omega+f)
if abs(inc-pi/2) > 1e-15
cosinc = cos(inc) ; sininc = sin(inc)
else
cosinc = 0.0 ; sininc = 1.0
end
x[1]=r*(coscapomega*cosomegapf-sincapomega*sinomegapf*cosinc)
x[2]=r*(sincapomega*cosomegapf+coscapomega*sinomegapf*cosinc)
x[3]=r*sinomegapf*sininc
rdotonr = rdot/r
# Compute the velocities:
rfdot = r*fdot
v[1]=x[1]*rdotonr+rfdot*(-coscapomega*sinomegapf-sincapomega*cosomegapf*cosinc)
v[2]=x[2]*rdotonr+rfdot*(-sincapomega*sinomegapf+coscapomega*cosomegapf*cosinc)
v[3]=x[3]*rdotonr+rfdot*cosomegapf*sininc
return x,v
end
function kepler_init(time::T,mass::T,elements::Array{T,1},jac_init::Array{T,2}) where {T <: Real}
# Takes orbital elements of a single Keplerian; returns positions & velocities.
# This is 3D), so 6 orbital elements specified, the code returns 3D. For
# Inclination = pi/2, motion is in X-Z plane; sky plane is X-Y.
# Elements are given by: period, t0, e*cos(omega), e*sin(omega), Inclination, Omega
# Returns the position & velocity of Keplerian.
# jac_init is the derivative of (x,v,m) with respect to (elements,m).
period = elements[1]
n = 2pi/period
t0 = elements[2]
# Compute the semi-major axis in AU (or other units specified by GNEWT):
semi = cbrt(GNEWT*mass*period^2/4/pi^2)
dsemidp = 2third*semi/period
dsemidm = third*semi/mass
# Convert to eccentricity & longitude of periastron:
ecosomega = elements[3]
esinomega = elements[4]
ecc=sqrt(esinomega^2+ecosomega^2)
deccdecos = ecc != 0.0 ? ecosomega/ecc : zero(T)
deccdesin = ecc != 0.0 ? esinomega/ecc : zero(T)
#omega = atan2(esinomega,ecosomega)
# The true anomaly at the time of transit:
#f1 = 1.5*pi-omega
# Compute the time of periastron passage:
sqrt1mecc2 = sqrt(1.0-ecc^2)
#tp=(t0+period*sqrt1mecc2/2.0/pi*(ecc*sin(f1)/(1.0+ecc*cos(f1))
# -2.0/sqrt1mecc2*atan2(sqrt1mecc2*tan(0.5*f1),1.0+ecc)))
den1 = esinomega-ecosomega-ecc
tp = if ecc == 0.0
# If circular orbit, take periastron to be along +x-axis
t0 - 3*period/4
else
(t0 - sqrt1mecc2/n*ecosomega/(1.0-esinomega)-2/n*atan(sqrt(1.0-ecc)*(esinomega+ecosomega+ecc),sqrt(1.0+ecc)*den1))
end
dtpdp = (tp-t0)/period
fac = sqrt((1.0-ecc)/(1.0+ecc))
den2 = 1.0/den1^2
theta = fac*(esinomega+ecosomega+ecc)/den1
#println("theta: ",theta," tan(atan2()): ",tan(atan2(sqrt(1.0-ecc)*(esinomega+ecosomega+ecc),sqrt(1.0+ecc)*den1)))
dthetadecc = ((ecc+ecosomega)^2+2*(1.0-ecc^2)*esinomega-esinomega^2)/(sqrt1mecc2*(1.0+ecc))*den2
dthetadecos = 2fac*esinomega*den2
dthetadesin = -2fac*(ecosomega+ecc)*den2
dtpdecc = ecc/sqrt1mecc2/n*ecosomega/(1.0-esinomega)-2/n/(1.0+theta^2)*dthetadecc
dtpdecos = dtpdecc*deccdecos -sqrt1mecc2/n/(1.0-esinomega)-2/n/(1.0+theta^2)*dthetadecos
dtpdesin = dtpdecc*deccdesin -sqrt1mecc2/n*ecosomega/(1.0-esinomega)^2-2/n/(1.0+theta^2)*dthetadesin
dtpdt0 = 1.0
# Compute the mean anomaly
m=n*(time-tp)
dmdp = -m/period
dmdtp = -n
# Kepler solver: instead of true anomaly, return eccentric anomaly:
ekep=ekepler(m,ecc)
cosekep = cos(ekep); sinekep = sin(ekep)
# Compute the radial distance:
r=semi*(1.0-ecc*cosekep)
drdekep = semi*ecc*sinekep
drdecc = -semi*cosekep
denom = semi/r
dekepdecos = sinekep*denom*deccdecos
dekepdesin = sinekep*denom*deccdesin
dekepdm = denom
inc = elements[5]
capomega = elements[6]
# Now, compute the positions
coscapomega = cos(capomega) ; sincapomega = sin(capomega)
cosomega = ecc != 0.0 ? ecosomega/ecc : one(T)
sinomega = ecc != 0.0 ? esinomega/ecc : zero(T)
cosinc = cos(inc) ; sininc = sin(inc)
# Define rotation matrices (M&D 2.119-2.120):
P1 = [cosomega -sinomega 0.0; sinomega cosomega 0.0; 0.0 0.0 1.0]
P2 = [1.0 0.0 0.0; 0.0 cosinc -sininc; 0.0 sininc cosinc]
P3 = [coscapomega -sincapomega 0.0; sincapomega coscapomega 0.0; 0.0 0.0 1.0]
P321 = P3*P2*P1
# Express x & v in terms of eccentric anomaly (2.121, 2.41, 2.68):
xplane = semi*[cosekep-ecc; sqrt1mecc2*sinekep; 0.0] # position vector in orbital plane
vplane = [-sinekep; sqrt1mecc2*cosekep; 0.0]
x = P321*xplane
# Now derivatives:
dxda = x/semi
dxdekep = P321*semi*vplane
P32 = P3*P2
#dxdecc = -x/ecc + P321*semi*[-1.0; -ecc/sqrt1mecc2*sinekep; 0.0]
# Get rid of cancellations in the prior expression:
dxdecc = -P321*semi/ecc*[cosekep; sinekep/sqrt1mecc2; zero(T)]
# These may need to be rewritten to flag ecc = 0.0 case:
dxdecos = dxdecc*deccdecos + P32/ecc*xplane
dxdesin = dxdecc*deccdesin + P32/ecc*[-xplane[2]; xplane[1]; 0.0]
dxdinc = P3*[0.0 0.0 0.0; 0.0 -sininc -cosinc; 0.0 cosinc -sininc]*P1*xplane
dxdcom = [-sincapomega -coscapomega 0.0; coscapomega -sincapomega 0.0; 0.0 0.0 0.0]*P2*P1*xplane
# Compute the velocities:
v = P321*n*semi*denom*vplane
#decc = 1e-5
#dvp = P321*ecc/(ecc+decc)*n*semi/(1.0-(ecc+decc)*cosekep)*[-sinekep; sqrt(1.0-(ecc+decc)^2)*cosekep; 0.0]
#dvm = P321*ecc/(ecc-decc)*n*semi/(1.0-(ecc-decc)*cosekep)*[-sinekep; sqrt(1.0-(ecc-decc)^2)*cosekep; 0.0]
dvda = v/semi
dvdp = -v/period
dvdekep = -v*ecc*sinekep*denom+P321*n*semi*denom*[-cosekep; -sqrt1mecc2*sinekep; 0.0]
dvdecc = -v/ecc + v*cosekep*denom + P321*n*semi*denom*[0.0; -ecc/sqrt1mecc2*cosekep; 0.0]
#dvdecc_num = .5*(dvp-dvm)/decc
#println("dvdecc: ",dvdecc," dvdecc_num: ",dvdecc_num)
#dvdecc = dvdecc_num
dvdecos = dvdecc*deccdecos + P32*n*semi*denom/ecc*vplane
dvdesin = dvdecc*deccdesin + P32*n*semi*denom/ecc*[-vplane[2]; vplane[1]; 0.0]
dvdinc = P3*[0.0 0.0 0.0; 0.0 -sininc -cosinc; 0.0 cosinc -sininc]*P1*n*semi*denom*vplane
dvdcom = [-sincapomega -coscapomega 0.0; coscapomega -sincapomega 0.0; 0.0 0.0 0.0]*P2*P1*n*semi*denom*vplane
# Now, take derivatives (11/15/2017 notes):
# Elements are given by: period, t0, e*cos(omega), e*sin(omega), Inclination, Omega
fill!(jac_init,0.0)
jac_init[1:3,1] = dxda*dsemidp + dxdekep*dekepdm*(dmdp+dmdtp*dtpdp)
#if T != BigFloat
# println("position vs. period: term 1 ",dxda*dsemidp," term 2: ",dxdekep*dekepdm*dmdp," term 3: ",dxdekep*dekepdm*dmdtp*dtpdp," sum: ",jac_init[1:3,1])
#end
jac_init[1:3,2] = dxdekep*dekepdm*dmdtp*dtpdt0
jac_init[1:3,3] .= ecc != 0.0 ? dxdecos + dxdekep*(dekepdm*dmdtp*dtpdecos + dekepdecos) : zero(T)
#if T != BigFloat
# println("position vs. ecosom : term 1 ",dxdecos," term 2: ",dxdekep*dekepdm*dmdtp*dtpdecos," term 3: ",dxdekep*dekepdm*dekepdecos," sum: ",jac_init[1:3,3])
#end
jac_init[1:3,4] .= ecc != 0.0 ? dxdesin + dxdekep*(dekepdm*dmdtp*dtpdesin + dekepdesin) : zero(T)
#if T != BigFloat
# println("position vs. esinom : term 1 ",dxdesin," term 2: ",dxdekep*dekepdm*dmdtp*dtpdesin," term 3: ",dxdekep*dekepdm*dekepdesin," sum: ",jac_init[1:3,4])
#end
jac_init[1:3,5] = dxdinc
jac_init[1:3,6] = dxdcom
jac_init[1:3,7] = dxda*dsemidm
jac_init[4:6,1] = dvdp + dvda*dsemidp + dvdekep*dekepdm*(dmdp+dmdtp*dtpdp)
#if T != BigFloat
# println("velocity vs. period: term 1 ",dvdp," term 2: ",dvda*dsemidp," term 3: ",dvdekep*dekepdm*dmdp," term 4: ",dvdekep*dekepdm*dmdtp*dtpdp," sum: ",jac_init[4:6,1])
#end
jac_init[4:6,2] = dvdekep*dekepdm*dmdtp*dtpdt0
jac_init[4:6,3] .= ecc != 0.0 ? dvdecos + dvdekep*(dekepdm*dmdtp*dtpdecos + dekepdecos) : zero(T)
#if T != BigFloat
# println("velocity vs. ecosom : term 1 ",dvdecos," term 2: ",dvdekep*dekepdm*dmdtp*dtpdecos," term 3: ",dvdekep*dekepdm*dekepdecos," sum: ",jac_init[4:6,3])
#end
jac_init[4:6,4] .= ecc != 0.0 ? dvdesin + dvdekep*(dekepdm*dmdtp*dtpdesin + dekepdesin) : zero(T)
#if T != BigFloat
# println("velocity vs. esinom : term 1 ",dvdesin," term 2: ",dvdekep*dekepdm*dmdtp*dtpdesin," term 3: ",dvdekep*dekepdm*dekepdesin," sum: ",jac_init[4:6,4])
#end
jac_init[4:6,5] = dvdinc
jac_init[4:6,6] = dvdcom
jac_init[4:6,7] = dvda*dsemidm
jac_init[7,7] = 1.0
#return x,v,tp,dtpdecos,dtpdesin
#return x,v,ekep,dekepdm*dmdtp*dtpdecos + dekepdecos,dekepdm*dmdtp*dtpdesin + dekepdesin
return x,v
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 6242 | # using Distributed: clear!
# Functions to generate ϵ matrix.
################################################################################
# Sets up planetary-hierarchy index matrix using an initial condition file
# of the form "test.txt" (included in "test/" directory), or in a 2d array of
# the form file = [x ; "x,y,z,..."] where x,y,z are Int64
################################################################################
function hierarchy(ic_vec::Array{Int64,1})
# Separates the initial array into variables
nbody = ic_vec[1]
bins = ic_vec[2:end]
#bins = replace(bins,"," => " ")
#bins = readdlm(IOBuffer(bins),Int64)
# checks that the hierarchy can be created
bins[end] == 1 ? level = length(bins) : level = length(bins) - 1
@assert bins[1] <= nbody/2 && bins[1] <= 2^level "Invalid hierarchy."
@assert sum(bins[1:level]) == nbody - 1 "Invalid hierarchy. Total # of binaries should = N-1"
# Creates an empty array of the proper size
h = zeros(Float64,nbody,nbody)
# Starts filling the array and returns it
bottom_level(nbody,bins,h,1)
h[end,:] .= -1
return h
end
################################################################################
# Sets up the first level of the hierchary.
################################################################################
function bottom_level(nbody::Int64,bins::Array{Int64,1},h::Array{Float64},iter::Int64)
# Fills the very first level of the hierarchy and iterates related variables
h[1,1] = -1.0
h[1,2] = 1.0
if bins[1] > 1
bins[end] == 1 ? j = 1 : j::Int64 = nbody/2 - 1
for i=1:bins[1]-1
if (j+3) <= nbody
h[i+1,j+2] = -1
h[i+1,j+3] = 1
j += 2
end
end
end
binsp = bins[1]
row = binsp[1] + 1
bodies = bins[1] * 2
# checks whether the desired hierarchy is symmetric and calls appropriate
# filling functions
if bins[end] > 1
bins = bins[1:end-1]
symmetric_nest(nbody,bodies,bins,binsp,row,h,iter+1)
elseif 2*binsp == nbody
symmetric(nbody,bodies,bins,binsp,row,h,iter+1)
else
nlevel(nbody,bodies,bins,binsp,row,h,iter+1)
end
end
################################################################################
# Fills subsequent levels of the hierarchy, recursively.
#
# *** Only works for hierarchies with a max binaries per level of 2 (unless
# symmetric). ***
################################################################################
function nlevel(nbody::Int64,bodies::Int64,bins::Array{Int64,1},binsp::Int64,row::Int64,h::Array{Float64},iter::Int64)
#print("nbody: ", nbody, "\n")
#print("bodies: ", bodies, "\n")
#print("row: ", row, "\n")
# Series of checks to know which level to fill and which bins number to use
if iter <= length(bins)
if nbody != bodies
if bins[iter] == binsp
bodies = bodies + bins[iter]
elseif bins[iter] > binsp
bodies = bodies + 2*(bins[iter]) - 1
end
elseif nbody == bodies
if row == nbody-1
if (bodies%4) > 2
h[row,1:row-2] .= -1
h[row,row-1:bodies] .= 1
return h
elseif (bodies%4) <= 2
h[row,1:row-1] .= -1
h[row,row:bodies] .= 1
return h
end
end
end
# Looks at the previous and current bins and calls nlevel again
if nbody >= bodies
if binsp == 1
if bins[iter] == 1
h[row,1:bodies-binsp] .= -1
h[row,bodies-binsp + 1:bodies] .= 1
row = row + binsp
binsp = bins[iter]
nlevel(nbody,bodies,bins,binsp,row,h,iter+1)
elseif bins[iter] == 2
h[row,1:bodies-(2*binsp)-1] .= -1
h[row,bodies-(2*binsp)] = 1
h[row+1,bodies-(2*binsp)+1] = -1
h[row+1,bodies] = 1
row = row + 2
binsp = bins[iter]
nlevel(nbody,bodies,bins,binsp,row,h,iter+1)
end
elseif binsp == 2
if bins[iter] == 1
h[row,1:row-1] .= -1
h[row,row:bodies] .= 1
row = row + 1
binsp = bins[iter]
nlevel(nbody,bodies,bins,binsp,row,h,iter+1)
elseif bins[iter] == 2
h[row,1:row-1] .= -1
h[row,row:bodies-2*(binsp-1)] .= 1
h[row+1,bodies-2*(binsp-1)+1] = -1
h[row+1,bodies] = 1
row = row + 2
binsp = bins[iter]
nlevel(nbody,bodies,bins,binsp,row,h,iter+1)
end
elseif binsp == 3
if bins[iter] == 2
h[row,1:Int64(bodies/2)-1] .= -1
h[row,Int64(bodies/2):2*Int64(bodies/3)] .= 1
h[row+1,2*Int64(bodies/3)+1:bodies] .= -1
h[row+1,bodies+1] = 1
row = row + 2
binsp = bins[iter]
bodies = bodies + 1
nlevel(nbody,bodies,bins,binsp,row,h,iter+1)
end
end
end
end
end
################################################################################
# Called if the hierarchy is symmetric (or if the hierarchy has all of the
# bodies on the bottom level). Fills the remaining rows.
################################################################################
function symmetric(nbody::Int64,bodies::Int64,bins::Array{Int64,1},binsp::Int64,row::Int64,h::Array{Float64},iter::Int64)
#global j = 0
j = 0
while row < nbody-1
h[row,1+j:2+j] .= -1
h[row,j+3:j+4] .= 1
j = j + 4
row = row + 1
end
h[row,1:binsp] .= -1
h[row,binsp+1:nbody] .= 1
#clear!(:j)
end
function symmetric_nest(nbody,bodies,bins,binsp,row,h,iter)
hlf::Int64 = nbody/2
j = 0
while row < nbody-1
println(j)
h[row,1:2+j] .= -1
h[row,3+j] = 1
h[row+1,hlf+1:hlf+2+j] .= -1
h[row+1,hlf+3+j] = 1
j += 1
row += 2
end
h[row,1:hlf] .= -1
h[row,hlf+1:nbody] .= 1
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 6931 | import NbodyGradient: InitialConditions
#========== Integrator ==========#
abstract type AbstractIntegrator end
"""
Integrator{T<:AbstractFloat}
Integrator. Used as a functor to integrate a [`State`](@ref).
# Fields
- `scheme::Function` : The integration scheme to use.
- `h::T` : Step size.
- `t0::T` : Initial time.
- `tmax::T` : Duration of simulation.
"""
mutable struct Integrator{T<:AbstractFloat, schemeT} <: AbstractIntegrator
scheme::schemeT
h::T
t0::T
tmax::T
end
Integrator(scheme,h::T,tmax::T) where T<:AbstractFloat = Integrator(scheme,h,0.0,tmax)
Integrator(h::T,tmax::T) where T<:AbstractFloat = Integrator(ahl21!,h,tmax)
# Default to ahl21!
Integrator(h::T,t0::T,tmax::T) where T<:AbstractFloat = Integrator(ahl21!,h,t0,tmax)
# Deprecated
@deprecate Integrator(h,t0,tmax) Integrator(h,tmax)
#========== State ==========#
abstract type AbstractState end
"""
State{T<:AbstractFloat} <: AbstractState
Current state of simulation.
# Fields (relevant to the user)
- `x::Matrix{T}` : Positions of each body [dimension, body].
- `v::Matrix{T}` : Velocities of each body [dimension, body].
- `t::Vector{T}` : Current time of simulation.
- `m::Vector{T}` : Masses of each body.
- `jac_step::Matrix{T}` : Current Jacobian.
- `dqdt::Vector{T}` : Derivative with respect to time.
"""
struct State{T<:AbstractFloat} <: AbstractState
x::Matrix{T}
v::Matrix{T}
t::Vector{T}
m::Vector{T}
jac_step::Matrix{T}
dqdt::Vector{T}
jac_init::Matrix{T}
n::Int64
pair::Matrix{Bool}
xerror::Matrix{T}
verror::Matrix{T}
dqdt_error::Vector{T}
jac_error::Matrix{T}
rij::Vector{T}
a::Matrix{T}
aij::Vector{T}
x0::Vector{T}
v0::Vector{T}
input::Vector{T}
delxv::Vector{T}
rtmp::Vector{T}
end
"""
State(ic)
Constructor for [`State`](@ref) type.
# Arguments
- `ic::InitialConditions{T}` : Initial conditions for the system.
"""
function State(ic::InitialConditions{T}) where T<:AbstractFloat
x,v,jac_init = init_nbody(ic)
n = ic.nbody
xerror = zeros(T,size(x))
verror = zeros(T,size(v))
jac_step = Matrix{T}(I,7*n,7*n)
dqdt = zeros(T,7*n)
dqdt_error = zeros(T,size(dqdt))
jac_error = zeros(T,size(jac_step))
pair = zeros(Bool,n,n)
rij = zeros(T,3)
a = zeros(T,3,n)
aij = zeros(T,3)
x0 = zeros(T,3)
v0 = zeros(T,3)
input = zeros(T,8)
delxv = zeros(T,6)
rtmp = zeros(T,3)
return State(x,v,[ic.t0],ic.m,jac_step,dqdt,jac_init,ic.nbody,
pair,xerror,verror,dqdt_error,jac_error,rij,a,aij,x0,v0,input,delxv,rtmp)
end
"""Initialize and return a `State` and a `Derivatives`."""
function dState(ic::InitialConditions{T}) where T<:AbstractFloat
d = Derivatives(T, ic.nbody)
return State(ic), d
end
"""Set `State` to initial conditions without reallocating."""
function initialize!(s::State{T}, ic::InitialConditions{T}) where T<:Real
x,v,jac_init = init_nbody(ic)
s.x .= x
s.v .= v
s.jac_init .= jac_init
s.xerror .= 0.0
s.verror .= 0.0
return
end
function set_state!(s_old::State{T},s_new::State{T}) where T<:AbstractFloat
s_old.t .= s_new.t
s_old.x .= s_new.x
s_old.v .= s_new.v
s_old.jac_step .= s_new.jac_step
s_old.xerror .= s_new.xerror
s_old.verror .= s_new.verror
s_old.jac_error .= s_new.jac_error
s_old.dqdt .= s_new.dqdt
s_old.dqdt_error .= s_new.dqdt_error
return
end
"""Shows if the positions, velocities, and Jacobian are finite."""
Base.show(io::IO,::MIME"text/plain",s::State{T}) where {T} = begin
println(io,"State{$T}:");
println(io,"Positions : ", all(isfinite.(s.x)) ? "finite" : "infinite!");
println(io,"Velocities : ", all(isfinite.(s.v)) ? "finite" : "infinite!");
println(io,"Jacobian : ", all(isfinite.(s.jac_step)) ? "finite" : "infinite!");
return
end
#========== Running Methods ==========#
"""
(::Integrator)(s, time; grad=true)
Callable [`Integrator`](@ref) method. Integrate to specific time.
# Arguments
- `s::State{T}` : The current state of the simulation.
- `time::T` : Time to integrate to.
### Optional
- `grad::Bool` : Choose whether to calculate gradients. (Default = true)
"""
function (intr::Integrator)(s::State{T},time::T;grad::Bool=true) where T<:AbstractFloat
t0 = s.t[1]
# Calculate number of steps
nsteps = abs(round(Int64,(time - t0)/intr.h))
# Step either forward or backward
h = intr.h * check_step(t0,time)
# Calculate last step (if needed)
#while t0 + (h * nsteps) <= time; nsteps += 1; end
tmax = t0 + (h * nsteps)
# Preallocate struct of arrays for derivatives
if grad; d = Derivatives(T,s.n); end
for i in 1:nsteps
# Take integration step and advance time
if grad
intr.scheme(s,d,h)
else
intr.scheme(s,h)
end
end
# Do last step (if needed)
if nsteps == 0; hf = time; end
if tmax != time
hf = time - tmax
if grad
intr.scheme(s,d,hf)
else
intr.scheme(s,hf)
end
end
s.t[1] = time
return
end
"""
(::Integrator)(s, N; grad=true)
Callable [`Integrator`](@ref) method. Integrate for N steps.
# Arguments
- `s::State{T}` : The current state of the simulation.
- `N::Int64` : Number of steps.
### Optional
- `grad::Bool` : Choose whether to calculate gradients. (Default = true)
"""
function (intr::Integrator)(s::State{T},N::Int64;grad::Bool=true) where T<:AbstractFloat
s2 = zero(T) # For compensated summation
# Preallocate struct of arrays for derivatives
if grad; d = Derivatives(T,s.n); end
# check to see if backward step
if N < 0; intr.h *= -1; N *= -1; end
h = intr.h
for n in 1:N
# Take integration step and advance time
if grad
intr.scheme(s,d,h)
else
intr.scheme(s,h)
end
s.t[1],s2 = comp_sum(s.t[1],s2,intr.h)
end
# Return time step to forward if needed
if intr.h < 0; intr.h *= -1; end
return
end
"""
(::Integrator)(s; grad=true)
Callable [`Integrator`](@ref) method. Integrate from `s.t` to `tmax` -- specified in constructor.
# Arguments
- `s::State{T}` : The current state of the simulation.
### Optional
- `grad::Bool` : Choose whether to calculate gradients. (Default = true)
"""
(intr::Integrator)(s::State{T};grad::Bool=true) where T<:AbstractFloat = intr(s,s.t[1]+intr.tmax,grad=grad)
function check_step(t0::T,tmax::T) where T<:AbstractFloat
if abs(tmax) > abs(t0)
return sign(tmax)
else
if sign(tmax) != sign(t0)
return sign(tmax)
else
return -1 * sign(tmax)
end
end
end
#========== Includes ==========#
const ints = ["ahl21"]
for i in ints; include(joinpath(i,"$i.jl")); end
const ints_no_grad = ["ahl21","dh17"]
for i in ints_no_grad; include(joinpath(i,"$(i)_no_grad.jl")); end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 3229 | # Collection of functions to convert cartesian coordinate to orbital elements
using LinearAlgebra, NbodyGradient
import NbodyGradient: InitialConditions
## Utils ##
const GNEWT = 39.4845/(365.242 * 365.242) # AU^3 Msol^-1 Day^-2
# h vector
function hvec(x::V,v::V) where V <: Vector{<:Real}
hx,hy,hz = cross(x,v)
hz >= 0.0 ? hy *= -1 : hx *= -1
return [hx,hy,hz]
end
# R dot
Rdotmag(R::T,V::T,x::Vector{T},v::Vector{T},h::T) where T<:AbstractFloat = sign(dot(x,v))*sqrt(V^2 - (h/R)^2)
## Elements ##
# Semi-major axis
calc_a(R::T,V::T,Gm::T) where T<:AbstractFloat = 1.0/((2.0/R) - (V*V)/(Gm))
# Eccentricity
calc_e(h::T,Gm::T,a::T) where T<:AbstractFloat = sqrt(1.0 - (h*h/(Gm*a)))
# Inclination
calc_I(hz::T,h::T) where T<:AbstractFloat = acos(hz/h)
# Long. of Ascending Node
function calc_Ω(h::T,hx::T,hy::T,sI::T) where T<:AbstractFloat
sΩ = hx/(h*sI)
cΩ = hy/(h*sI)
return atan(sΩ,cΩ)
end
# Long. of Pericenter
function calc_ϖ(x::Vector{T},R::T,Ṙ::T,Ω::T,I::T,e::T,h::T,a::T) where T<:AbstractFloat
X,_,Z = x
sΩ,cΩ = sincos(Ω)
sI,cI = sincos(I)
# ω + f
swpf = Z/(R*sI)
cwpf= ((X/R) + sΩ*swpf*cI)/cΩ
wpf = atan(swpf,cwpf)
# true anomaly, f
sf = a*Ṙ*(1.0 - e^2)/(h*e)
cf = (a*(1.0-e^2)/R - 1.0)/e
f = atan(sf,cf)
# ϖ: Ω + ω
return Ω + (wpf - f - π)
end
# Time of pericenter passage
function calc_t0(R::T,a::T,e::T,Gm::T,t::T) where T<:AbstractFloat
E = acos((1.0 - (R/a)) / e)
return t - (E - e*sin(E))/sqrt(Gm/(a*a*a))
end
# Period
calc_P(a::T,Gm::T) where T<:AbstractFloat = (2.0*π)*sqrt(a*a*a/Gm)
# Get relative hierarchy positions
function calc_X(s::State{T},ic::InitialConditions{T}) where T<:AbstractFloat
X = zeros(3,s.n-1)
V = zeros(3,s.n-1)
for i in 1:s.n-1
for k in 1:s.n
X[:,i] .+= ic.amat[i,k] .* s.x[:,k]
V[:,i] .+= ic.amat[i,k] .* s.v[:,k]
end
end
return X,V
end
function gmass(m::Vector{T}) where T<:AbstractFloat
N = length(m)
M = zeros(N - 1)
for i in 1:N-1
for j in 1:N
M[i] += abs(ic.ϵ[i,j])*m[j]
end
end
return GNEWT .* M
end
"""
Converts cartesian coordinates to orbital elements. (t0 : time of transit)
"""
function get_orbital_elements(s::State{T},ic::InitialConditions{T}) where T<:AbstractFloat
X::Matrix{T},Xdot::Matrix{T} = calc_X(s,ic)
Gm = gmass(s.m)
R = [norm(X[:,i]) for i in 1:s.n-1]
V = [norm(Xdot[:,i]) for i in 1:s.n-1]
h_vec::Matrix{T} = hcat([hvec(X[:,i],Xdot[:,i]) for i in 1:s.n-1]...)
hx,hy,hz = h_vec[1,:],h_vec[2,:],h_vec[3,:]
h = norm.([hx[i],hy[i],hz[i]] for i in 1:s.n-1)
Rdot = [Rdotmag(R[i],V[i],X[:,i],Xdot[:,i],h[i]) for i in 1:s.n-1]
a = calc_a.(R,V,Gm)
e = calc_e.(h,Gm,a)
I = calc_I.(hz,h)
Ω = calc_Ω.(h,hx,hy,sin.(I))
ϖ = [calc_ϖ(X[:,i],R[i],Rdot[i],Ω[i],I[i],e[i],h[i],a[i]) for i in 1:s.n-1]
#t0 = calc_t0.(R,a,e,Gm,s.t) # Our elements use the initial transit time
t0 = ic.elements[2:end,3]
P = calc_P.(a,Gm)
elements = zeros(size(ic.elements))
elements[1] = ic.elements[1]
elements[2:end,:] = hcat(s.m[2:end],P,t0,e .* cos.(ϖ),e .* sin.(ϖ),I,Ω)
return elements
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 54482 | """
Carry out AHL21 mapping and calculates both the Jacobian and derivative with respect to the time step.
"""
function ahl21!(s::State{T},d::Derivatives{T},h::T) where T<:AbstractFloat
zilch = zero(T); half::T = 0.5; two::T = 2.0;
h2::T = half*h; n = s.n; sevn = 7*n; h6::T = h/6.0
zero_out!(d)
fill!(s.dqdt,zilch)
kickfast!(s,d,h6)
d.dqdt_kick ./= 6.0 # Since step is h/6
# Since I removed identity from kickfast, need to add in dqdt:
mul!(d.tmp7n, d.jac_kick, s.dqdt)
s.dqdt .+= d.dqdt_kick .+ d.tmp7n #*(d.jac_kick,s.dqdt)
# Multiply Jacobian from kick step:
mul!(d.jac_copy, d.jac_kick, s.jac_step)
drift_grad!(s,h2)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
s.dqdt[(i-1)*7+k] = half*s.v[k,i] + h2*s.dqdt[(i-1)*7+3+k]
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(s.jac_step,s.jac_error,d.jac_copy)
indi = 0; indj = 0
@inbounds for i=1:s.n-1
indi = (i-1)*7
@inbounds for j=i+1:s.n
indj = (j-1)*7
if ~s.pair[i,j] # Check to see if kicks have not been applied
kepler_driftij_gamma!(s,d,i,j,h2,true)
copy_submatrix!(s,d,indi,indj,sevn)
# Carry out multiplication on the i/j components of matrix:
mul!(d.jac_tmp2, d.jac_ij, d.jac_tmp1)
# Add back in the Jacobian with compensated summation:
comp_sum_matrix!(d.jac_tmp1,d.jac_err1,d.jac_tmp2)
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
d.dqdt_ij .*= half
mul!(d.tmp14, d.jac_ij, d.dqdt_tmp1)
d.dqdt_ij .+= d.dqdt_tmp1 .+ d.tmp14#*(d.jac_ij,d.dqdt_tmp1)
# Copy back time derivatives:
ypoc_submatrix!(s,d,indi,indj,sevn)
end
end
end
phic!(s,d,h)
phisalpha!(s,d,h,two)
mul!(d.jac_copy, d.jac_phi, s.jac_step)
# Add in time derivative with respect to prior parameters:
# Copy result to dqdt:
mul!(d.tmp7n, d.jac_phi, s.dqdt)
s.dqdt .+= d.dqdt_phi .+ d.tmp7n #*(d.jac_phi,s.dqdt)
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(s.jac_step,s.jac_error,d.jac_copy)
indi=0; indj=0
@inbounds for i=s.n-1:-1:1
indi=(i-1)*7
@inbounds for j=s.n:-1:i+1
indj=(j-1)*7
if ~s.pair[i,j] # Check to see if kicks have not been applied
kepler_driftij_gamma!(s,d,i,j,h2,false)
# Pick out indices for bodies i & j:
# Carry out multiplication on the i/j components of matrix:
copy_submatrix!(s,d,indi,indj,sevn)
# Carry out multiplication on the i/j components of matrix:
mul!(d.jac_tmp2,d.jac_ij,d.jac_tmp1)
# Add back in the Jacobian with compensated summation:
comp_sum_matrix!(d.jac_tmp1,d.jac_err1,d.jac_tmp2)
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
d.dqdt_ij .*= half
mul!(d.tmp14, d.jac_ij, d.dqdt_tmp1)
d.dqdt_ij .+= d.dqdt_tmp1 .+ d.tmp14#*(d.jac_ij,d.dqdt_tmp1)
# Copy back derivatives:
ypoc_submatrix!(s,d,indi,indj,sevn)
end
end
end
drift_grad!(s,h2)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
s.dqdt[(i-1)*7+k] += half*s.v[k,i] + h2*s.dqdt[(i-1)*7+3+k]
end
fill!(d.dqdt_kick,zilch)
kickfast!(s,d,h6)
d.dqdt_kick ./= 6.0 # Since step is h/6
# Copy result to dqdt:
mul!(d.tmp7n, d.jac_kick, s.dqdt)
s.dqdt .+= d.dqdt_kick .+ d.tmp7n#*(d.jac_kick,s.dqdt)
# Multiply Jacobian from kick step:
mul!(d.jac_copy,d.jac_kick,s.jac_step)
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(s.jac_step,s.jac_error,d.jac_copy)
# Edit this routine to do compensated summation for Jacobian [x]
end
function ahl21!(s::State{T},d::Jacobian{T},h::T) where T<:AbstractFloat
zilch = zero(T); uno = one(T); half = convert(T,0.5); two = convert(T,2.0); h2 = half*h; sevn = 7*s.n
zero_out!(d)
#drift!(s.x,s.v,s.xerror,s.verror,h2,s.n,s.jac_step,s.jac_error)
#kickfast!(s.x,s.v,s.xerror,s.verror,h/6,s.m,s.n,d.jac_kick,d.dqdt_kick,pair)
kickfast!(s,d,h/6)
# Multiply Jacobian from kick step:
if T == BigFloat
d.jac_copy .= *(d.jac_kick,s.jac_step)
else
start = time()
#BLAS.gemm!('N','N',uno,d.jac_kick,s.jac_step,zilch,d.jac_copy)
mul!(d.jac_copy,d.jac_kick,s.jac_step)
d.ctime[1] += time()-start
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(s.jac_step,s.jac_error,d.jac_copy)
drift_grad!(s,h2)
indi = 0; indj = 0
@inbounds for i=1:s.n-1
indi = (i-1)*7
@inbounds for j=i+1:s.n
indj = (j-1)*7
if ~s.pair[i,j] # Check to see if kicks have not been applied
kepler_driftij_gamma!(s,d,i,j,h2,true)
#kepler_driftij_gamma!(s.m,s.x,s.v,s.xerror,s.verror,i,j,h2,d.jac_ij,d.dqdt_ij,true)
# Pick out indices for bodies i & j:
@inbounds for k2=1:sevn, k1=1:7
d.jac_tmp1[k1,k2] = s.jac_step[ indi+k1,k2]
d.jac_err1[k1,k2] = s.jac_error[indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
d.jac_tmp1[7+k1,k2] = s.jac_step[ indj+k1,k2]
d.jac_err1[7+k1,k2] = s.jac_error[indj+k1,k2]
end
# Carry out multiplication on the i/j components of matrix:
if T == BigFloat
d.jac_tmp2 .= *(d.jac_ij,d.jac_tmp1)
else
start = time()
#BLAS.gemm!('N','N',uno,d.jac_ij,d.jac_tmp1,zilch,d.jac_tmp2)
mul!(d.jac_tmp2,d.jac_ij,d.jac_tmp1)
d.ctime[1] += time()-start
end
# Add back in the Jacobian with compensated summation:
comp_sum_matrix!(d.jac_tmp1,d.jac_err1,d.jac_tmp2)
# Copy back to the Jacobian:
@inbounds for k2=1:sevn, k1=1:7
s.jac_step[ indi+k1,k2]=d.jac_tmp1[k1,k2]
s.jac_error[indi+k1,k2]=d.jac_err1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
s.jac_step[ indj+k1,k2]=d.jac_tmp1[7+k1,k2]
s.jac_error[indj+k1,k2]=d.jac_err1[7+k1,k2]
end
end
end
end
#phic!(s.x,s.v,s.xerror,s.verror,h,s.m,s.n,d.jac_phi,d.dqdt_phi,pair)
#phisalpha!(s.x,s.v,s.xerror,s.verror,h,s.m,two,s.n,d.jac_phi,d.dqdt_phi,pair) # 10%
phic!(s,d,h)
phisalpha!(s,d,h,two)
if T == BigFloat
d.jac_copy .= *(d.jac_phi,s.jac_step)
else
start = time()
#BLAS.gemm!('N','N',uno,d.jac_phi,s.jac_step,zilch,d.jac_copy)
mul!(d.jac_copy,d.jac_phi,s.jac_step)
d.ctime[1] += time()-start
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(s.jac_step,s.jac_error,d.jac_copy)
indi=0; indj=0
@inbounds for i=s.n-1:-1:1
indi=(i-1)*7
@inbounds for j=s.n:-1:i+1
indj=(j-1)*7
if ~s.pair[i,j] # Check to see if kicks have not been applied
#kepler_driftij_gamma!(s.m,s.x,s.v,s.xerror,s.verror,i,j,h2,d.jac_ij,d.dqdt_ij,false)
kepler_driftij_gamma!(s,d,i,j,h2,false)
# Pick out indices for bodies i & j:
# Carry out multiplication on the i/j components of matrix:
@inbounds for k2=1:sevn, k1=1:7
d.jac_tmp1[k1,k2] = s.jac_step[ indi+k1,k2]
d.jac_err1[k1,k2] = s.jac_error[indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
d.jac_tmp1[7+k1,k2] = s.jac_step[ indj+k1,k2]
d.jac_err1[7+k1,k2] = s.jac_error[indj+k1,k2]
end
# Carry out multiplication on the i/j components of matrix:
if T == BigFloat
d.jac_tmp2 .= *(d.jac_ij,d.jac_tmp1)
else
start = time()
#BLAS.gemm!('N','N',uno,d.jac_ij,d.jac_tmp1,zilch,d.jac_tmp2)
mul!(d.jac_tmp2,d.jac_ij,d.jac_tmp1)
d.ctime[1] += time()-start
end
# Add back in the Jacobian with compensated summation:
comp_sum_matrix!(d.jac_tmp1,d.jac_err1,d.jac_tmp2)
# Copy back to the Jacobian:
@inbounds for k2=1:sevn, k1=1:7
s.jac_step[ indi+k1,k2]=d.jac_tmp1[k1,k2]
s.jac_error[indi+k1,k2]=d.jac_err1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
s.jac_step[ indj+k1,k2]=d.jac_tmp1[7+k1,k2]
s.jac_error[indj+k1,k2]=d.jac_err1[7+k1,k2]
end
end
end
end
drift_grad!(s,h2)
#kickfast!(x,v,h2,m,n,jac_kick,dqdt_kick,pair)
#kickfast!(s.x,s.v,s.xerror,s.verror,h/6,s.m,s.n,d.jac_kick,d.dqdt_kick,pair)
kickfast!(s,d,h/6)
# Multiply Jacobian from kick step:
if T == BigFloat
d.jac_copy .= *(d.jac_kick,s.jac_step)
else
start = time()
#BLAS.gemm!('N','N',uno,d.jac_kick,s.jac_step,zilch,d.jac_copy)
mul!(d.jac_copy,d.jac_kick,s.jac_step)
d.ctime[1] += time()-start
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(s.jac_step,s.jac_error,d.jac_copy)
# Edit this routine to do compensated summation for Jacobian [x]
#drift!(s.x,s.v,s.xerror,s.verror,h2,s.n,s.jac_step,s.jac_error)
return
end
function ahl21!(s::State{T},d::dTime{T},h::T) where T<:AbstractFloat
# [Currently this routine is not giving the correct dqdt values. -EA 8/12/2019]
n = s.n
zilch = zero(T); uno = one(T); half = convert(T,0.5); two = convert(T,2.0); h2 = half*h; sevn = 7*n
zero_out!(d)
fill!(s.dqdt,zilch)
kickfast!(s,d,h/6)
d.dqdt_kick ./= 6 # Since step is h/6
# Since I removed identity from kickfast, need to add in dqdt:
s.dqdt .+= d.dqdt_kick + *(d.jac_kick,s.dqdt)
drift!(s,h2)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
s.dqdt[(i-1)*7+k] = half*s.v[k,i] + h2*s.dqdt[(i-1)*7+3+k]
end
@inbounds for i=1:n-1
indi = (i-1)*7
@inbounds for j=i+1:n
indj = (j-1)*7
if ~s.pair[i,j] # Check to see if kicks have not been applied
kepler_driftij_gamma!(s,d,i,j,h2,true)
# Copy current time derivatives for multiplication purposes:
@inbounds for k1=1:7
d.dqdt_tmp1[ k1] = s.dqdt[indi+k1]
d.dqdt_tmp1[7+k1] = s.dqdt[indj+k1]
end
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
d.dqdt_ij .*= half
d.dqdt_ij .+= *(d.jac_ij,d.dqdt_tmp1) + d.dqdt_tmp1
# Copy back time derivatives:
@inbounds for k1=1:7
s.dqdt[indi+k1] = d.dqdt_ij[ k1]
s.dqdt[indj+k1] = d.dqdt_ij[7+k1]
end
end
end
end
# Looks like we are missing phic! here: [ ]
# Since I haven't added dqdt to phic yet, for now, set jac_phi equal to identity matrix
# (since this is commented out within phisalpha):
phic!(s,d,h)
phisalpha!(s,d,h,two)
# Add in time derivative with respect to prior parameters:
# Copy result to dqdt:
s.dqdt .+= d.dqdt_phi + *(d.jac_phi,s.dqdt)
indi=0; indj=0
@inbounds for i=n-1:-1:1
indi=(i-1)*7
@inbounds for j=n:-1:i+1
if ~s.pair[i,j] # Check to see if kicks have not been applied
indj=(j-1)*7
kepler_driftij_gamma!(s,d,i,j,h2,false)
# Copy current time derivatives for multiplication purposes:
@inbounds for k1=1:7
d.dqdt_tmp1[ k1] = s.dqdt[indi+k1]
d.dqdt_tmp1[7+k1] = s.dqdt[indj+k1]
end
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
d.dqdt_ij .*= half
d.dqdt_ij .+= *(d.jac_ij,d.dqdt_tmp1) + d.dqdt_tmp1
# Copy back time derivatives:
@inbounds for k1=1:7
s.dqdt[indi+k1] = d.dqdt_ij[ k1]
s.dqdt[indj+k1] = d.dqdt_ij[7+k1]
end
end
end
end
drift_grad!(s,h2)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
s.dqdt[(i-1)*7+k] += half*s.v[k,i] + h2*s.dqdt[(i-1)*7+3+k]
end
fill!(d.dqdt_kick,zilch)
kickfast!(s,d,h/6)
d.dqdt_kick ./= 6 # Since step is h/6
# Copy result to dqdt:
s.dqdt .+= d.dqdt_kick + *(d.jac_kick,s.dqdt)
return
end
"""
AHL21 drift step. Drifts all particles with compensated summation. (with Jacobian)
"""
function drift_grad!(s::State{T},h::T) where {T <: Real}
indi::Int64 = 0
@inbounds for i=1:s.n
indi = (i-1)*7
@inbounds for j=1:NDIM
s.x[j,i],s.xerror[j,i] = comp_sum(s.x[j,i],s.xerror[j,i],h*s.v[j,i])
end
# Now for Jacobian:
@inbounds for k=1:7*s.n, j=1:NDIM
s.jac_step[indi+j,k],s.jac_error[indi+j,k] = comp_sum(s.jac_step[indi+j,k],s.jac_error[indi+j,k],h*s.jac_step[indi+3+j,k])
end
end
return
end
"""
AHL21 kick step. Computes "fast" kicks for pairs of bodies (in lieu of -drift+Kepler). Include Jacobian and compensated summation.
"""
function kickfast!(s::State{T},d::AbstractDerivatives{T},h::T) where {T <: Real}
n::Int64 = s.n
s.rij .= 0.0
# Getting rid of identity since we will add that back in in calling routines:
d.jac_kick .= 0.0
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
indj = (j-1)*7
if s.pair[i,j]
for k=1:3
s.rij[k] = s.x[k,i] - s.x[k,j]
end
r2inv::T = 1.0/dot_fast(s.rij)
r3inv::T = r2inv*sqrt(r2inv)
fac2::T = h*GNEWT*r3inv
for k=1:3
fac::T = fac2*s.rij[k]
# Apply impulses:
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i],-s.m[j]*fac)
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j], s.m[i]*fac)
# Compute time derivative:
d.dqdt_kick[indi+3+k] -= s.m[j]*fac/h
d.dqdt_kick[indj+3+k] += s.m[i]*fac/h
# Computing the derivative
# Mass derivative of acceleration vector (10/6/17 notes):
# Impulse of ith particle depends on mass of jth particle:
d.jac_kick[indi+3+k,indj+7] -= fac
# Impulse of jth particle depends on mass of ith particle:
d.jac_kick[indj+3+k,indi+7] += fac
# x derivative of acceleration vector:
fac *= 3.0*r2inv
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
d.jac_kick[indi+3+k,indi+p] += fac*s.m[j]*s.rij[p]
d.jac_kick[indi+3+k,indj+p] -= fac*s.m[j]*s.rij[p]
d.jac_kick[indj+3+k,indj+p] += fac*s.m[i]*s.rij[p]
d.jac_kick[indj+3+k,indi+p] -= fac*s.m[i]*s.rij[p]
end
# Final term has no dot product, so just diagonal:
d.jac_kick[indi+3+k,indi+k] -= fac2*s.m[j]
d.jac_kick[indi+3+k,indj+k] += fac2*s.m[j]
d.jac_kick[indj+3+k,indj+k] -= fac2*s.m[i]
d.jac_kick[indj+3+k,indi+k] += fac2*s.m[i]
end
end
end
end
return
end
"""
Computes correction for pairs which are kicked, with Jacobian, dq/dt, and compensated summation.
"""
function phic!(s::State{T},d::AbstractDerivatives{T},h::T) where {T <: Real}
s.a .= 0.0
s.rij .= 0.0
s.aij .= 0.0
d.dadq .= 0.0 # There is no velocity dependence
d.dotdadq .= 0.0 # There is no velocity dependence
# Set jac_step to zeros:
fill!(d.jac_phi,zero(T))
fac::T = 0.0; fac1::T = 0.0; fac2::T = 0.0; fac3::T = 0.0; r1::T = 0.0; r2::T = 0.0; r3::T = 0.0
coeff::T = h^3/36*GNEWT
n::Int64 = s.n
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if s.pair[i,j]
indj = (j-1)*7
for k=1:3
s.rij[k] = s.x[k,i] - s.x[k,j]
end
r2inv::T = inv(dot_fast(s.rij))
r3inv::T = r2inv*sqrt(r2inv)
for k=1:3
# Apply impulses:
fac = GNEWT*s.rij[k]*r3inv
facv = fac*2*h/3
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i],-s.m[j]*facv)
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j],s.m[i]*facv)
# Compute time derivative:
d.dqdt_phi[indi+3+k] -= 1/h*s.m[j]*facv
d.dqdt_phi[indj+3+k] += 1/h*s.m[i]*facv
s.a[k,i] -= s.m[j]*fac
s.a[k,j] += s.m[i]*fac
# Impulse of ith particle depends on mass of jth particle:
d.jac_phi[indi+3+k,indj+7] -= facv
# Impulse of jth particle depends on mass of ith particle:
d.jac_phi[indj+3+k,indi+7] += facv
# x derivative of acceleration vector:
facv *= 3.0*r2inv
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
d.jac_phi[indi+3+k,indi+p] += facv*s.m[j]*s.rij[p]
d.jac_phi[indi+3+k,indj+p] -= facv*s.m[j]*s.rij[p]
d.jac_phi[indj+3+k,indj+p] += facv*s.m[i]*s.rij[p]
d.jac_phi[indj+3+k,indi+p] -= facv*s.m[i]*s.rij[p]
end
# Final term has no dot product, so just diagonal:
facv = 2h/3*GNEWT*r3inv
d.jac_phi[indi+3+k,indi+k] -= facv*s.m[j]
d.jac_phi[indi+3+k,indj+k] += facv*s.m[j]
d.jac_phi[indj+3+k,indj+k] -= facv*s.m[i]
d.jac_phi[indj+3+k,indi+k] += facv*s.m[i]
# Mass derivative of acceleration vector (10/6/17 notes):
# Since there is no velocity dependence, this is fourth parameter.
# Acceleration of ith particle depends on mass of jth particle:
d.dadq[k,i,4,j] -= fac
d.dadq[k,j,4,i] += fac
# x derivative of acceleration vector:
fac *= 3.0*r2inv
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
d.dadq[k,i,p,i] += fac*s.m[j]*s.rij[p]
d.dadq[k,i,p,j] -= fac*s.m[j]*s.rij[p]
d.dadq[k,j,p,j] += fac*s.m[i]*s.rij[p]
d.dadq[k,j,p,i] -= fac*s.m[i]*s.rij[p]
end
# Final term has no dot product, so just diagonal:
fac = GNEWT*r3inv
d.dadq[k,i,k,i] -= fac*s.m[j]
d.dadq[k,i,k,j] += fac*s.m[j]
d.dadq[k,j,k,j] -= fac*s.m[i]
d.dadq[k,j,k,i] += fac*s.m[i]
end
end
end
end
# Next, compute g_i acceleration vector.
# Note that jac_step[(i-1)*7+k,(j-1)*7+p] is the derivative of the kth coordinate
# of planet i with respect to the pth coordinate of planet j.
indi::Int64 = 0; indj::Int64 = 0; indd::Int64 = 0
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if s.pair[i,j] # correction for Kepler pairs
indj = (j-1)*7
for k=1:3
s.aij[k] = s.a[k,i] - s.a[k,j]
s.rij[k] = s.x[k,i] - s.x[k,j]
end
# Compute dot product of r_ij with \delta a_ij:
fill!(d.dotdadq,0.0)
@inbounds for di=1:n, p=1:4, k=1:3
d.dotdadq[p,di] += s.rij[k]*(d.dadq[k,i,p,di]-d.dadq[k,j,p,di])
end
r2 = dot_fast(s.rij)
r1 = sqrt(r2)
ardot = dot_fast(s.aij,s.rij)
fac1 = coeff/(r2*r2*r1)
fac2 = 3*ardot
for k=1:3
fac = fac1*(s.rij[k]*fac2- r2*s.aij[k])
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i],s.m[j]*fac)
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j],-s.m[i]*fac)
# Compute time derivative of 4th order correction
d.dqdt_phi[indi+3+k] += 3/h*s.m[j]*fac
d.dqdt_phi[indj+3+k] -= 3/h*s.m[i]*fac
# Mass derivative (first part is easy):
d.jac_phi[indi+3+k,indj+7] += fac
d.jac_phi[indj+3+k,indi+7] -= fac
# Position derivatives:
fac *= 5.0/r2
for p=1:3
d.jac_phi[indi+3+k,indi+p] -= fac*s.m[j]*s.rij[p]
d.jac_phi[indi+3+k,indj+p] += fac*s.m[j]*s.rij[p]
d.jac_phi[indj+3+k,indj+p] -= fac*s.m[i]*s.rij[p]
d.jac_phi[indj+3+k,indi+p] += fac*s.m[i]*s.rij[p]
end
# Diagonal position terms:
fac = fac1*fac2
d.jac_phi[indi+3+k,indi+k] += fac*s.m[j]
d.jac_phi[indi+3+k,indj+k] -= fac*s.m[j]
d.jac_phi[indj+3+k,indj+k] += fac*s.m[i]
d.jac_phi[indj+3+k,indi+k] -= fac*s.m[i]
# Dot product \delta rij terms:
fac = -2*fac1*s.aij[k]
for p=1:3
fac3 = fac*s.rij[p] + fac1*3.0*s.rij[k]*s.aij[p]
d.jac_phi[indi+3+k,indi+p] += s.m[j]*fac3
d.jac_phi[indi+3+k,indj+p] -= s.m[j]*fac3
d.jac_phi[indj+3+k,indj+p] += s.m[i]*fac3
d.jac_phi[indj+3+k,indi+p] -= s.m[i]*fac3
end
# Diagonal acceleration terms:
fac = -fac1*r2
# Duoh. For dadq, have to loop over all other parameters!
@inbounds for di=1:n
indd = (di-1)*7
for p=1:3
d.jac_phi[indi+3+k,indd+p] += fac*s.m[j]*(d.dadq[k,i,p,di]-d.dadq[k,j,p,di])
d.jac_phi[indj+3+k,indd+p] -= fac*s.m[i]*(d.dadq[k,i,p,di]-d.dadq[k,j,p,di])
end
# Don't forget mass-dependent term:
d.jac_phi[indi+3+k,indd+7] += fac*s.m[j]*(d.dadq[k,i,4,di]-d.dadq[k,j,4,di])
d.jac_phi[indj+3+k,indd+7] -= fac*s.m[i]*(d.dadq[k,i,4,di]-d.dadq[k,j,4,di])
end
# Now, for the final term: (\delta a_ij . r_ij ) r_ij
fac = 3.0*fac1*s.rij[k]
@inbounds for di=1:n
indd = (di-1)*7
for p=1:3
d.jac_phi[indi+3+k,indd+p] += fac*s.m[j]*d.dotdadq[p,di]
d.jac_phi[indj+3+k,indd+p] -= fac*s.m[i]*d.dotdadq[p,di]
end
d.jac_phi[indi+3+k,indd+7] += fac*s.m[j]*d.dotdadq[4,di]
d.jac_phi[indj+3+k,indd+7] -= fac*s.m[i]*d.dotdadq[4,di]
end
end
end
end
end
return
end
"""
Computes the 4th-order correction, with Jacobian, dq/dt, and compensated summation.
"""
function phisalpha!(s::State{T},d::AbstractDerivatives{T},h::T,alpha::T) where {T <: Real}
s.a .= 0.0
d.dadq .= 0.0 # There is no velocity dependence
d.dotdadq .= 0.0 # There is no velocity dependence
s.rij .= 0.0
s.aij .= 0.0
coeff::T = alpha*h^3/96*2*GNEWT
fac::T = 0.0; fac1::T = 0.0; fac2::T = 0.0; fac3::T = 0.0; r1::T = 0.0; r2::T = 0.0; r3::T = 0.0
n::Int64 = s.n
@inbounds for i=1:n-1
for j=i+1:n
if ~s.pair[i,j] # correction for Kepler pairs
for k=1:3
s.rij[k] = s.x[k,i] - s.x[k,j]
end
r2 = dot_fast(s.rij)
r3 = r2*sqrt(r2)
fac2 = GNEWT/r3
for k=1:3
fac = fac2*s.rij[k]
s.a[k,i] -= s.m[j]*fac
s.a[k,j] += s.m[i]*fac
# Mass derivative of acceleration vector (10/6/17 notes):
# Since there is no velocity dependence, this is fourth parameter.
# Acceleration of ith particle depends on mass of jth particle:
d.dadq[k,i,4,j] -= fac
d.dadq[k,j,4,i] += fac
# x derivative of acceleration vector:
fac *= 3.0/r2
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
d.dadq[k,i,p,i] += fac*s.m[j]*s.rij[p]
d.dadq[k,i,p,j] -= fac*s.m[j]*s.rij[p]
d.dadq[k,j,p,j] += fac*s.m[i]*s.rij[p]
d.dadq[k,j,p,i] -= fac*s.m[i]*s.rij[p]
end
# Final term has no dot product, so just diagonal:
d.dadq[k,i,k,i] -= fac2*s.m[j]
d.dadq[k,i,k,j] += fac2*s.m[j]
d.dadq[k,j,k,j] -= fac2*s.m[i]
d.dadq[k,j,k,i] += fac2*s.m[i]
end
end
end
end
# Next, compute \tilde g_i acceleration vector (this is rewritten
# slightly to avoid reference to \tilde a_i):
# Note that jac_step[(i-1)*7+k,(j-1)*7+p] is the derivative of the kth coordinate
# of planet i with respect to the pth coordinate of planet j.
indi = 0; indj=0; indd = 0
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if ~s.pair[i,j] # correction for Kepler pairs
indj = (j-1)*7
for k=1:3
s.aij[k] = s.a[k,i] - s.a[k,j]
s.rij[k] = s.x[k,i] - s.x[k,j]
end
# Compute dot product of r_ij with \delta a_ij:
fill!(d.dotdadq,0.0)
@inbounds for di=1:n, p=1:4, k=1:3
d.dotdadq[p,di] += s.rij[k]*(d.dadq[k,i,p,di]-d.dadq[k,j,p,di])
end
r2 = dot_fast(s.rij)
r1 = sqrt(r2)
ardot = dot_fast(s.aij, s.rij)
fac1 = coeff/(r2*r2*r1)
fac2 = (2*GNEWT*(s.m[i]+s.m[j])/r1 + 3*ardot)
for k=1:3
fac = fac1*(s.rij[k]*fac2-r2*s.aij[k])
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i], s.m[j]*fac)
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j],-s.m[i]*fac)
# Compute time derivative:
d.dqdt_phi[indi+3+k] += 3/h*s.m[j]*fac
d.dqdt_phi[indj+3+k] -= 3/h*s.m[i]*fac
# Mass derivative (first part is easy):
d.jac_phi[indi+3+k,indj+7] += fac
d.jac_phi[indj+3+k,indi+7] -= fac
# Position derivatives:
fac *= 5.0/r2
for p=1:3
d.jac_phi[indi+3+k,indi+p] -= fac*s.m[j]*s.rij[p]
d.jac_phi[indi+3+k,indj+p] += fac*s.m[j]*s.rij[p]
d.jac_phi[indj+3+k,indj+p] -= fac*s.m[i]*s.rij[p]
d.jac_phi[indj+3+k,indi+p] += fac*s.m[i]*s.rij[p]
end
# Second mass derivative:
fac = 2*GNEWT*fac1*s.rij[k]/r1
d.jac_phi[indi+3+k,indi+7] += fac*s.m[j]
d.jac_phi[indi+3+k,indj+7] += fac*s.m[j]
d.jac_phi[indj+3+k,indj+7] -= fac*s.m[i]
d.jac_phi[indj+3+k,indi+7] -= fac*s.m[i]
# (There's also a mass term in dadq [x]. See below.)
# Diagonal position terms:
fac = fac1*fac2
d.jac_phi[indi+3+k,indi+k] += fac*s.m[j]
d.jac_phi[indi+3+k,indj+k] -= fac*s.m[j]
d.jac_phi[indj+3+k,indj+k] += fac*s.m[i]
d.jac_phi[indj+3+k,indi+k] -= fac*s.m[i]
# Dot product \delta rij terms:
fac = -2*fac1*(s.rij[k]*GNEWT*(s.m[i]+s.m[j])/(r2*r1)+s.aij[k])
for p=1:3
fac3 = fac*s.rij[p] + fac1*3.0*s.rij[k]*s.aij[p]
d.jac_phi[indi+3+k,indi+p] += s.m[j]*fac3
d.jac_phi[indi+3+k,indj+p] -= s.m[j]*fac3
d.jac_phi[indj+3+k,indj+p] += s.m[i]*fac3
d.jac_phi[indj+3+k,indi+p] -= s.m[i]*fac3
end
# Diagonal acceleration terms:
fac = -fac1*r2
# Duoh. For dadq, have to loop over all other parameters!
@inbounds for di=1:n
indd = (di-1)*7
for p=1:3
d.jac_phi[indi+3+k,indd+p] += fac*s.m[j]*(d.dadq[k,i,p,di]-d.dadq[k,j,p,di])
end
for p=1:3
d.jac_phi[indj+3+k,indd+p] -= fac*s.m[i]*(d.dadq[k,i,p,di]-d.dadq[k,j,p,di])
end
# Don't forget mass-dependent term:
d.jac_phi[indi+3+k,indd+7] += fac*s.m[j]*(d.dadq[k,i,4,di]-d.dadq[k,j,4,di])
d.jac_phi[indj+3+k,indd+7] -= fac*s.m[i]*(d.dadq[k,i,4,di]-d.dadq[k,j,4,di])
end
# Now, for the final term: (\delta a_ij . r_ij ) r_ij
fac = 3.0*fac1*s.rij[k]
@inbounds for di=1:n
indd = (di-1)*7
for p=1:3
d.jac_phi[indi+3+k,indd+p] += fac*s.m[j]*d.dotdadq[p,di]
end
for p=1:3
d.jac_phi[indj+3+k,indd+p] -= fac*s.m[i]*d.dotdadq[p,di]
end
d.jac_phi[indi+3+k,indd+7] += fac*s.m[j]*d.dotdadq[4,di]
d.jac_phi[indj+3+k,indd+7] -= fac*s.m[i]*d.dotdadq[4,di]
end
end
end
end
end
return
end
"""
Carries out a Kepler step and reverse drift for bodies i & j, and computes Jacobian. Uses new version of the code with gamma in favor of s.
"""
function kepler_driftij_gamma!(s::State{T},d::AbstractDerivatives{T},i::Int64,j::Int64,h::T,drift_first::Bool) where {T <: Real}
# Initial state:
@inbounds for k=1:NDIM
s.x0[k] = s.x[k,i] - s.x[k,j] # x0 = positions of body i relative to j
s.v0[k] = s.v[k,i] - s.v[k,j] # v0 = velocities of body i relative to j
end
gm = GNEWT*(s.m[i]+s.m[j])
if gm == 0; return; end
# jac_ij should be the Jacobian for going from (x_{0,i},v_{0,i},m_i) & (x_{0,j},v_{0,j},m_j)
# to (x_i,v_i,m_i) & (x_j,v_j,m_j), a 14x14 matrix for the 3-dimensional case.:
fill!(d.jac_ij,zero(T))
s.delxv .= 0.0
d.jac_kepler .= 0.0
d.jac_mass .= 0.0
params::NTuple{22,T} = jac_delxv_gamma!(s,gm,h,drift_first)
compute_jacobian_gamma!(params...,s.x0,s.v0,d.jac_kepler,d.jac_mass,drift_first,false)
mijinv::T = one(T)/(s.m[i] + s.m[j])
mi::T = s.m[i]*mijinv # Normalize the masses
mj::T = s.m[j]*mijinv
@inbounds for k=1:3
# Add kepler-drift differences, weighted by masses, to start of step:
s.x[k,i],s.xerror[k,i] = comp_sum(s.x[k,i],s.xerror[k,i], mj*s.delxv[k])
s.x[k,j],s.xerror[k,j] = comp_sum(s.x[k,j],s.xerror[k,j],-mi*s.delxv[k])
end
@inbounds for k=1:3
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i], mj*s.delxv[3+k])
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j],-mi*s.delxv[3+k])
end
# Compute Jacobian:
@inbounds for l=1:6, k=1:6
# Compute derivatives of x_i,v_i with respect to initial conditions:
d.jac_ij[ k, l] += mj*d.jac_kepler[k,l]
d.jac_ij[ k,7+l] -= mj*d.jac_kepler[k,l]
# Compute derivatives of x_j,v_j with respect to initial conditions:
d.jac_ij[7+k, l] -= mi*d.jac_kepler[k,l]
d.jac_ij[7+k,7+l] += mi*d.jac_kepler[k,l]
end
@inbounds for k=1:6
# Compute derivatives of x_i,v_i with respect to the masses:
d.jac_ij[ k, 7] = d.jac_mass[k]*s.m[j]
d.jac_ij[ k,14] = mi*s.delxv[k]*mijinv + GNEWT*mj*d.jac_kepler[ k,7]
# Compute derivatives of x_j,v_j with respect to the masses:
d.jac_ij[ 7+k, 7] = -mj*s.delxv[k]*mijinv - GNEWT*mi*d.jac_kepler[ k,7]
d.jac_ij[ 7+k,14] = -d.jac_mass[k]*s.m[i]
end
# The following lines are meant to compute dq/dt for kepler_driftij,
# but they currently contain an error (test doesn't pass in test_ahl21.jl). [ ]
@inbounds for k=1:6
# Position/velocity derivative, body i:
d.dqdt_ij[ k] = mj*d.jac_kepler[k,8]
# Position/velocity derivative, body j:
d.dqdt_ij[7+k] = -mi*d.jac_kepler[k,8]
end
return
end
"""
Computes Jacobian of delx and delv with respect to x0, v0, k, and h.
"""
function jac_delxv_gamma!(s::State{T},k::T,h::T,drift_first::Bool;debug::Bool=false,grad::Bool=true) where {T <: Real}
# Compute r0:
r0 = zero(T)
s.rtmp[1] = s.x0[1]-h*s.v0[1]
s.rtmp[2] = s.x0[2]-h*s.v0[2]
s.rtmp[3] = s.x0[3]-h*s.v0[3]
drift_first ? r0 = norm(s.rtmp) : r0 = norm(s.x0)
# And its inverse:
r0inv::T = inv(r0)
# Compute beta_0:
beta0::T = 2k*r0inv-dot_fast(s.v0,s.v0)
beta0inv::T = inv(beta0)
signb::T = sign(beta0)
sqb::T = sqrt(signb*beta0)
zeta::T = k-r0*beta0
gamma_guess = zero(T)
# Compute \eta_0 = x_0 . v_0:
eta = zero(T)
#drift_first ? eta = dot(s.x0 .- h .* s.v0, s.v0) : eta = dot(s.x0,s.v0)
if drift_first
eta = dot_fast(s.rtmp,s.v0)
else
eta = dot_fast(s.x0,s.v0)
end
if zeta != zero(T)
# Make sure we have a cubic in gamma (and don't divide by zero):
zinv = 6/zeta
gamma_guess = cubic1(0.5*eta*sqb*zinv,r0*signb*beta0*zinv,-h*signb*beta0*sqb*zinv)
else
# Check that we have a quadratic in gamma (and don't divide by zero):
if eta != zero(T)
reta = r0/eta
disc = reta^2+2h/eta
disc > zero(T) ? gamma_guess = sqb*(-reta+sqrt(disc)) : gamma_guess = h*r0inv*sqb
else
gamma_guess = h*r0inv*sqb
end
end
gamma = copy(gamma_guess)
# Make sure prior two steps differ:
gamma1::T = 2*copy(gamma)
gamma2::T = 3*copy(gamma)
iter = 0
ITMAX = 20
# Compute coefficients: (8/28/19 notes)
c1 = k; c2 = -2zeta; c3 = 2*eta*signb*sqb; c4 = -sqb*h*beta0; c5 = 2eta*signb*sqb
# Solve for gamma:
while iter < ITMAX
gamma2 = gamma1
gamma1 = gamma
xx = 0.5*gamma
if beta0 > 0
sx,cx = sincos(xx);
else
sx = sinh(xx); cx = exp(-xx)+sx
end
gamma -= (k*gamma+c2*sx*cx+c3*sx^2+c4)/(2signb*zeta*sx^2+c5*sx*cx+r0*beta0)
iter +=1
if gamma == gamma2 || gamma == gamma1
break
end
end
# Set up a single output array for delx and delv:
if debug
s.delxv = zeros(T,12)
else
s.delxv .= zero(T)
end
# Since we updated gamma, need to recompute:
xx = 0.5*gamma
if beta0 > 0
sx,cx = sincos(xx)
else
sx = sinh(xx); cx = exp(-xx)+sx
end
# Now, compute final values. Compute Wisdom/Hernandez G_i^\beta(s) functions:
g1bs = 2sx*cx/sqb
g2bs = 2signb*sx^2*beta0inv
g0bs = one(T)-beta0*g2bs
g3bs = G3(gamma,beta0,sqb)
h1 = zero(T); h2 = zero(T)
# Compute r from equation (35):
r = r0*g0bs+eta*g1bs+k*g2bs
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv # [x]
if drift_first
# Drift backwards before Kepler step: (1/22/2018)
fm1 = -k*r0inv*g2bs # [x]
# This is given in 2/7/2018 notes: g-h*f
gmh = k*r0inv*(h*g2bs-r0*g3bs)
else
# Drift backwards after Kepler step: (1/24/2018)
# The following line is f-1-h fdot:
h1= H1(gamma,beta0); h2= H2(gamma,beta0,sqb)
fm1 = k*rinv*(g2bs-k*r0inv*h1)
# This is g-h*dgdt
gmh = k*rinv*(r0*h2+eta*h1)
end
# Compute velocity component functions:
if drift_first
# This is gdot - h fdot - 1:
dgdtm1 = k*r0inv*rinv*(h*g1bs-r0*g2bs)
else
# This is gdot - 1:
dgdtm1 = -k*rinv*g2bs # [x]
end
@inbounds for j=1:3
# Compute difference vectors (finish - start) of step:
s.delxv[ j] = fm1*s.x0[j]+gmh*s.v0[j] # position x_ij(t+h)-x_ij(t) - h*v_ij(t) or -h*v_ij(t+h)
end
@inbounds for j=1:3
s.delxv[3+j] = dfdt*s.x0[j]+dgdtm1*s.v0[j] # velocity v_ij(t+h)-v_ij(t)
end
if debug
s.delxv[7] = gamma
s.delxv[8] = r
s.delxv[9] = fm1
s.delxv[10] = dfdt
s.delxv[11] = gmh
s.delxv[12] = dgdtm1
end
if grad
return gamma,g0bs,g1bs,g2bs,g3bs,h1,h2,dfdt,fm1,gmh,dgdtm1,r0,r,r0inv,rinv,k,h,beta0,beta0inv,eta,sqb,zeta
end
end
"""
Computes the gradient analytically.
"""
function compute_jacobian_gamma!(gamma::T,g0::T,g1::T,g2::T,g3::T,h1::T,h2::T,dfdt::T,fm1::T,gmh::T,dgdtm1::T,
r0::T,r::T,r0inv::T,rinv::T,k::T,h::T,beta::T,betainv::T,eta::T,sqb::T,zeta::T,x0::Array{T,1},v0::Array{T,1},
delxv_jac::Array{T,2},jac_mass::Array{T,1},drift_first::Bool,debug::Bool) where {T <: Real}
# Computes Jacobian:
r0inv2 = r0inv^2
r0inv3 = r0inv2*r0inv
rinv2 = rinv^2
rinv3 = rinv2*rinv
hsq = h^2
ksq = k^2
if drift_first
# First, the diagonal terms:
# Now the off-diagonal terms:
d = (h + eta*g2 + 2*k*g3)*betainv
c1 = d-r0*g3
c2 = eta*g0+g1*zeta
c3 = d*k+g1*r0^2
c4 = eta*g1+2*g0*r0
c13 = g1*h-g2*r0
c9 = 2*g2*h-3*g3*r0
c10 = k*r0inv2^2*(-g2*r0*h+k*c9*betainv-c3*c13*rinv)
c24 = r0inv3*(r0*(2*k*r0inv-beta)*betainv-g1*c3*rinv/g2)
h6 = H6(gamma,beta)
# Derivatives of \delta x with respect to x0, v0, k & h:
dfm1dxx = fm1*c24
dfm1dxv = -fm1*(g1*rinv+h*c24)
dfm1dvx = dfm1dxv
dfm1dvv = fm1*rinv*(-r0*g2 + k*h6*betainv/g2 + h*(2*g1+h*r*c24))
dfm1dh = fm1*(g1*rinv*(1/g2+2*k*r0inv-beta)-eta*c24)
dfm1dk = fm1*(1/k+g1*c1*rinv*r0inv/g2-2*betainv*r0inv)
h4 = -H1(gamma,beta)*beta
h5 = H5(gamma,beta,sqb)
dfm1dk2 = (r0*h4+k*h6)
dgmhdxx = c10
dgmhdxv = -g2*k*c13*rinv*r0inv-h*c10
dgmhdvx = dgmhdxv
h3 = H3(gamma,beta,sqb)
h8 = -2h3+3h5
dgmhdvv = 2*g2*h*k*c13*rinv*r0inv+hsq*c10+
k*betainv*rinv*r0inv*(r0^2*h8-beta*h*r0*g2^2 + (h*k+eta*r0)*h6)
dgmhdh = g2*k*r0inv+k*c13*rinv*r0inv+g2*k*(2*k*r0inv-beta)*c13*rinv*r0inv-eta*c10
dgmhdk = r0inv*(k*c1*c13*rinv*r0inv+g2*h-g3*r0-k*c9*betainv*r0inv)
dgmhdk2 = (h6*g3*ksq+eta*r0*(h6+g2*h4)+r0^2*g0*h5+k*eta*g2*h6+(g1*h6+g3*h4)*k*r0)
@inbounds for j=1:3
# First, compute the \delta x-derivatives:
delxv_jac[ j, j] = fm1
delxv_jac[ j,3+j] = gmh
@inbounds for i=1:3
delxv_jac[j, i] += (dfm1dxx*x0[i]+dfm1dxv*v0[i])*x0[j] + (dgmhdxx*x0[i]+dgmhdxv*v0[i])*v0[j]
delxv_jac[j,3+i] += (dfm1dvx*x0[i]+dfm1dvv*v0[i])*x0[j] + (dgmhdvx*x0[i]+dgmhdvv*v0[i])*v0[j]
end
delxv_jac[ j, 7] = dfm1dk*x0[j] + dgmhdk*v0[j]
delxv_jac[ j, 8] = dfm1dh*x0[j] + dgmhdh*v0[j]
# Compute the mass jacobian separately since otherwise cancellations happen in kepler_driftij_gamma:
jac_mass[ j] = (GNEWT*r0inv)^2*betainv*rinv*(dfm1dk2*x0[j]-dgmhdk2*v0[j])
end
# Derivatives of \delta v with respect to x0, v0, k & h:
c5 = (r0-k*g2)*rinv/g1
c6 = (r0*g0-k*g2)*betainv
c7 = g2*(1/g1+c2*rinv)
c8 = (k*c6+r*r0+c3*c5)*r0inv3
c12 = g0*h-g1*r0
c17 = r0-r-g2*k
c18 = eta*g1+2*g2*k
c20 = k*(g2*k+r)-g0*r0*zeta
c21 = (g2*k-r0)*(beta*c3-k*g1*r)*betainv*rinv2*r0inv3/g1+eta*g1*rinv*r0inv2-2r0inv2
c22 = rinv*(-g1-g0*g2/g1+g2*c2*rinv)
c25 = k*rinv*r0inv2*(-g2+k*(c13-g2*r0)*betainv*r0inv2-c13*r0inv-c12*c3*rinv*r0inv2+
c13*c2*c3*rinv2*r0inv2-c13*(k*(g2*k+r)-g0*r0*zeta)*betainv*rinv*r0inv2)
c26 = k*rinv2*r0inv*(-g2*c12-g1*c13+g2*c13*c2*rinv)
ddfdtdxx = dfdt*c21
ddfdtdxv = dfdt*(c22-h*c21)
ddfdtdvx = ddfdtdxv
c34 = (-beta*eta^2*g2^2-eta*k*h8-h6*ksq-2beta*eta*r0*g1*g2+(g2^2-3*g1*g3)*beta*k*r0
- beta*g1^2*r0^2)*betainv*rinv2+(eta*g2^2)*rinv/g1 + (k*h8)*betainv*rinv/g1
ddfdtdvv = dfdt*(c34 - 2*h*c22 +hsq*c21)
ddfdtdk = dfdt*(1/k-betainv*r0inv-c17*betainv*rinv*r0inv-c1*(g1*c2-g0*r)*rinv2*r0inv/g1)
ddfdtdk2 = -(g2*k-r0)*(beta*r0*(g3-g1*g2)-beta*eta*g2^2+k*h3)*betainv*rinv2*r0inv
ddfdtdh = dfdt*(g0*rinv/g1-c2*rinv2-(2*k*r0inv-beta)*c22-eta*c21)
dgdtmhdfdtm1dxx = c25
dgdtmhdfdtm1dxv = c26-h*c25
dgdtmhdfdtm1dvx = c26-h*c25
h2 = H2(gamma,beta,sqb)
c33 = d*k*rinv3*r0inv*k*(h*g2- r0*g3)+k*(-eta*k*g1*g2^2-g1*g2*g3*ksq-r0*eta*beta*g1*g2^2-r0*k*g1*h2 - beta*g2^2*g0*r0^2)*betainv*rinv2*r0inv
dgdtmhdfdtm1dvv = c33-2*h*c26+hsq*c25
dgdtmhdfdtm1dk = rinv*r0inv*(-k*(c13-g2*r0)*betainv*r0inv+c13-k*c13*c17*betainv*rinv*r0inv+k*c1*c12*rinv*r0inv-k*c1*c2*c13*rinv2*r0inv)
dgdtmhdfdtm1dk2 = k*betainv*rinv2*r0inv*(-beta*eta^2*g2^4+eta*g2*(g1*g2^2+g1^2*g3-5*g2*g3)*k+g2*g3*h3*ksq+
2eta*r0*beta*g2^2*(g3-g1*g2)+(4g3-g0*g3-g1*g2)*(g3-g1*g2)*r0*k+beta*(2g1*g3*g2-g1^2*g2^2-g3^2)*r0^2)
dgdtmhdfdtm1dh = g1*k*rinv*r0inv+k*c12*rinv2*r0inv-k*c2*c13*rinv3*r0inv-(2*k*r0inv-beta)*c26-eta*c25
@inbounds for j=1:3
# Next, compute the \delta v-derivatives:
delxv_jac[3+j, j] = dfdt
delxv_jac[3+j,3+j] = dgdtm1
@inbounds for i=1:3
delxv_jac[3+j, i] += (ddfdtdxx*x0[i]+ddfdtdxv*v0[i])*x0[j] + (dgdtmhdfdtm1dxx*x0[i]+dgdtmhdfdtm1dxv*v0[i])*v0[j]
delxv_jac[3+j,3+i] += (ddfdtdvx*x0[i]+ddfdtdvv*v0[i])*x0[j] + (dgdtmhdfdtm1dvx*x0[i]+dgdtmhdfdtm1dvv*v0[i])*v0[j]
end
delxv_jac[3+j, 7] = ddfdtdk*x0[j] + dgdtmhdfdtm1dk*v0[j]
delxv_jac[3+j, 8] = ddfdtdh*x0[j] + dgdtmhdfdtm1dh*v0[j]
# Compute the mass jacobian separately since otherwise cancellations happen in kepler_driftij_gamma:
jac_mass[3+j] = GNEWT^2*r0inv*rinv*(ddfdtdk2*x0[j]+dgdtmhdfdtm1dk2*v0[j])
end
if debug
# Now include derivatives of gamma, r, fm1, dfdt, gmh, and dgdtmhdfdtm1:
@inbounds for i=1:3
delxv_jac[ 7,i] = -sqb*rinv*((g2-h*c3*r0inv3)*v0[i]+c3*x0[i]*r0inv3); delxv_jac[7,3+i] = sqb*rinv*((-d+2*g2*h-hsq*c3*r0inv3)*v0[i]+(-g2+h*c3*r0inv3)*x0[i])
delxv_jac[ 8,i] = (c20*betainv-c2*c3*rinv)*r0inv3*x0[i]+((eta*g2+g1*r0)*rinv+h*r0inv3*(c2*c3*rinv-c20*betainv))*v0[i]
drdv0x0 = (beta*g1*g2+((eta*g2+k*g3)*eta*g0*c3)*rinv*r0inv3 + (g1*g0*(2k*eta^2*g2+3eta*ksq*g3))*betainv*rinv*r0inv2-
k*betainv*r0inv3*(eta*g1*(eta*g2+k*g3)+g3*g0*r0^2*beta+2h*g2*k)+(g1*zeta)*rinv*((h*c3)*r0inv3 - g2) -
(eta*(beta*g2*g0*r0+k*g1^2)*(eta*g1+k*g2))*betainv*rinv*r0inv2)
delxv_jac[8,3+i] = drdv0x0*x0[i] - (k*betainv*rinv*(eta*(beta*g2*g3-h8) - h6*k + (g2^2 - 2*g1*g3)*beta*r0) + h*drdv0x0)*v0[i]
delxv_jac[ 9,i] = dfm1dxx*x0[i]+dfm1dxv*v0[i]; delxv_jac[ 9,3+i]=dfm1dvx*x0[i]+dfm1dvv*v0[i]
delxv_jac[10,i] = ddfdtdxx*x0[i]+ddfdtdxv*v0[i]; delxv_jac[10,3+i]=ddfdtdvx*x0[i]+ddfdtdvv*v0[i]
delxv_jac[11,i] = dgmhdxx*x0[i]+dgmhdxv*v0[i]; delxv_jac[11,3+i]=dgmhdvx*x0[i]+dgmhdvv*v0[i]
delxv_jac[12,i] = dgdtmhdfdtm1dxx*x0[i]+dgdtmhdfdtm1dxv*v0[i]; delxv_jac[12,3+i]=dgdtmhdfdtm1dvx*x0[i]+dgdtmhdfdtm1dvv*v0[i]
end
delxv_jac[ 7,7] = sqb*c1*r0inv*rinv; delxv_jac[7,8] = sqb*rinv*(1+eta*c3*r0inv3+g2*(2k*r0inv-beta))
delxv_jac[ 8,7] = betainv*r0inv*rinv*(-g2*r0^2*beta-eta*g1*g2*(k+beta*r0)+eta*g0*g3*(2*k+zeta)-
g2^2*(beta*eta^2+2*k*zeta)+g1*g3*zeta*(3*k-beta*r0)); delxv_jac[8,8] = c2*rinv
delxv_jac[ 8,8] = ((r0*g1+eta*g2)*rinv)*(beta-2*k*r0inv)+c2*rinv+eta*r0inv3*(c2*c3*rinv-c20*betainv)
delxv_jac[ 9,7] = dfm1dk; delxv_jac[ 9,8] = dfm1dh
delxv_jac[10,7] = ddfdtdk; delxv_jac[10,8] = ddfdtdh
delxv_jac[11,7] = dgmhdk; delxv_jac[11,8] = dgmhdh
delxv_jac[12,7] = dgdtmhdfdtm1dk; delxv_jac[12,8] = dgdtmhdfdtm1dh
end
else
# Now compute the Kepler-Drift Jacobian terms:
# First, the diagonal terms:
# Now the off-diagonal terms:
d = (h + eta*g2 + 2*k*g3)*betainv
c1 = d-r0*g3
c2 = eta*g0+g1*zeta
c3 = d*k+g1*r0^2
c4 = eta*g1+2*g0*r0
c6 = (r0*g0-k*g2)*betainv
c9 = g2*r-h1*k
c14 = r0*g2-k*h1
c15 = eta*h1+h2*r0
c16 = eta*h2+g1*gamma*r0/sqb
c17 = r0-r-g2*k
c18 = eta*g1+2*g2*k
c19 = 4*eta*h1+3*h2*r0
c23 = h2*k-r0*g1
h6 = H6(gamma,beta)
h3 = H3(gamma,beta,sqb)
h5 = H5(gamma,beta,sqb)
h8 = -2h3+3h5
# Derivatives of \delta x with respect to x0, v0, k & h:
dfm1dxx = k*rinv3*betainv*r0inv^4*(k*h1*r^2*r0*(beta-2*k*r0inv)+beta*c3*(r*c23+c14*c2)+c14*r*(k*(r-g2*k)+g0*r0*zeta))
dfm1dxv = k*rinv2*r0inv*(k*(g2*h2+g1*h1)-2g1*g2*r0+g2*c14*c2*rinv)
dfm1dvx = dfm1dxv
dfm1dvv = k*r0inv*rinv2*betainv*(2eta*k*(g2*g3-g1*h1)+(3g3*h2-4h1*g2)*ksq +
beta*g2*r0*(3h1*k-g2*r0)+c14*rinv*(-beta*g2^2*eta^2+eta*k*(2g0*g3-h2)-
h6*ksq+(-2eta*g1*g2+k*(h1-2g1*g3))*beta*r0-beta*g1^2*r0^2))
dfm1dh = (g1*k-h2*ksq*r0inv-k*c14*c2*rinv*r0inv)*rinv2
dfm1dk = rinv*r0inv*(4*h1*ksq*betainv*r0inv-k*h1-2*g2*k*betainv+c14-k*c14*c17*betainv*rinv*r0inv+
k*(g1*r0-k*h2)*c1*rinv*r0inv-k*c14*c1*c2*rinv2*r0inv)
# New expression for d(f-1-h \dot f)/dk with cancellations of higher order terms in gamma is:
dfm1dk2 = betainv*r0inv*rinv2*(r*(2eta*k*(g1*h1-g3*g2)+(4g2*h1-3g3*h2)*ksq-eta*r0*beta*g1*h1 + (g3*h2-4g2*h1)*beta*k*r0 + g2*h1*beta^2*r0^2) -
# In the following line I need to replace 3g0*g3-g1*g2 by -H8:
c14*(-eta^2*beta*g2^2 - k*eta*h8 - ksq*h6 - eta*r0*beta*(g1*g2 + g0*g3) + 2*(h1 - g1*g3)*beta*k*r0 - (g2 - beta*g1*g3)*beta*r0^2))
dgmhdxx = k*rinv*r0inv*(h2+k*c19*betainv*r0inv2-c16*c3*rinv*r0inv2+c2*c3*c15*(rinv*r0inv)^2-c15*(k*(g2*k+r)-g0*r0*zeta)*betainv*rinv*r0inv2)
dgmhdxv = k*rinv2*(h1*r-g2*c16-g1*c15+g2*c2*c15*rinv)
dgmhdvx = dgmhdxv
dgmhdvv = k*betainv*rinv2*(2*eta^2*(g1*h1-g2*g3)+eta*k*(4g2*h1-3h2*g3)+r0*eta*(4g0*h1-2g1*g3)+
# In the following lines I need to replace g1*g2-3g0*g3-g1*g2 by H8:
3r0*k*((g1+beta*g3)*h1-g3*g2)+(g0*h8-beta*g1*(g2^2+g1*g3))*r0^2 -
c15*rinv*(beta*g2^2*eta^2+eta*k*h8+h6*ksq+(2eta*g1*g2-k*(g2^2-3g1*g3))*beta*r0+beta*g1^2*r0^2))
dgmhdk = rinv*(k*c1*c16*rinv*r0inv+c15-k*c15*c17*betainv*rinv*r0inv-k*c19*betainv*r0inv-k*c1*c2*c15*rinv2*r0inv)
h7 = beta*g1*g2^2-g0*h8
dgmhdk2 = betainv*rinv2*(r*(2eta^2*(g3*g2-g1*h1) + eta*k*(3g3*h2 - 4g2*h1) +
r0*eta*(beta*g3*(g1*g2 + g0*g3) - 2g0*h6) + (-h6*(g1 + beta*g3) + g2*(2g3 - h2))*r0*k +
(h7 - beta^2*g1*g3^2)*r0^2)- c15*(-beta*eta^2*g2^2 + eta*k*(-h2 + 2g0*g3) - h6*ksq -
r0*eta*beta*(h2 + 2g0*g3) + 2beta*(2*h1 - g2^2)*r0*k + beta*(beta*g1*g3 - g2)*r0^2))
dgmhdh = k*rinv3*(r*c16-c2*c15)
@inbounds for j=1:3
# First, compute the \delta x-derivatives:
delxv_jac[ j, j] = fm1
delxv_jac[ j,3+j] = gmh
@inbounds for i=1:3
delxv_jac[j, i] += (dfm1dxx*x0[i]+dfm1dxv*v0[i])*x0[j] + (dgmhdxx*x0[i]+dgmhdxv*v0[i])*v0[j]
delxv_jac[j,3+i] += (dfm1dvx*x0[i]+dfm1dvv*v0[i])*x0[j] + (dgmhdvx*x0[i]+dgmhdvv*v0[i])*v0[j]
end
delxv_jac[ j, 7] = dfm1dk*x0[j] + dgmhdk*v0[j]
delxv_jac[ j, 8] = dfm1dh*x0[j] + dgmhdh*v0[j]
jac_mass[ j] = GNEWT^2*rinv*r0inv*(dfm1dk2*x0[j]+dgmhdk2*v0[j])
end
# Derivatives of \delta v with respect to x0, v0, k & h:
c5 = (r0-k*g2)*rinv/g1
c7 = g2*(1/g1+c2*rinv)
c8 = (k*c6+r*r0+c3*c5)*r0inv3
c12 = g0*h-g1*r0
c20 = k*(g2*k+r)-g0*r0*zeta
ddfdtdxx = dfdt*(eta*g1*rinv-2-g0*c3*rinv*r0inv/g1+c2*c3*r0inv*rinv2-k*(k*g2-r0)*betainv*rinv*r0inv)*r0inv2
ddfdtdxv = -dfdt*(g0*g2/g1+(r0*g1+eta*g2)*rinv)*rinv
ddfdtdvx = ddfdtdxv
ddfdtdvv = -k*rinv3*r0inv*betainv*((beta*eta*g2^2+k*h8)*(r0*g0+k*g2)+
g1*(- h6*ksq + (-2eta*g1*g2+(h1-2g1*g3)*k)*beta*r0 - beta*g1^2*r0^2))
ddfdtdk = dfdt*(1/k+c1*(r0-g2*k)*r0inv*rinv2/g1-betainv*r0inv*(1+c17*rinv))
ddfdtdk2 = (r0-g2*k)*betainv*r0inv*rinv2*(-eta*beta*g2^2+h3*k+(g3-g1*g2)*beta*r0)
ddfdtdh = dfdt*(r0-g2*k)*rinv2/g1
dgdotm1dxx = rinv2*r0inv3*((eta*g2+g1*r0)*k*c3*rinv+g2*k*(k*(g2*k-r)-g0*r0*zeta)*betainv)
dgdotm1dxv = k*g2*rinv3*(r*g1+r0*g1+eta*g2)
dgdotm1dvx = dgdotm1dxv
dgdotm1dvv = k*betainv*rinv3*(eta^2*beta*g2^3-eta*k*g2*h3+3r0*eta*beta*g1*g2^2 +
r0*k*(-g0*h6+3beta*g1*g2*g3)+beta*g2*(g0*g2+g1^2)*r0^2)
dgdotm1dk = rinv*r0inv*(-r0*g2+g2*k*(r+r0-g2*k)*betainv*rinv-k*g1*c1*rinv+k*g2*c1*c2*rinv2)
dgdotm1dk2 = betainv*rinv2*(-beta*eta^2*g2^3+eta*k*g2*h3+eta*r0*beta*g2*(g3-2g1*g2)+
(h6-beta*g2^3)*r0*k + beta*g1*(g3 - g1*g2)*r0^2)
dgdotm1dh = k*rinv3*(g2*c2-r*g1)
@inbounds for j=1:3
# Next, compute the \delta v-derivatives:
delxv_jac[3+j, j] = dfdt
delxv_jac[3+j,3+j] = dgdtm1
@inbounds for i=1:3
delxv_jac[3+j, i] += (ddfdtdxx*x0[i]+ddfdtdxv*v0[i])*x0[j] + (dgdotm1dxx*x0[i]+dgdotm1dxv*v0[i])*v0[j]
delxv_jac[3+j,3+i] += (ddfdtdvx*x0[i]+ddfdtdvv*v0[i])*x0[j] + (dgdotm1dvx*x0[i]+dgdotm1dvv*v0[i])*v0[j]
end
delxv_jac[3+j, 7] = ddfdtdk*x0[j] + dgdotm1dk*v0[j]
delxv_jac[3+j, 8] = ddfdtdh*x0[j] + dgdotm1dh*v0[j]
jac_mass[3+j] = GNEWT^2*rinv*r0inv*(ddfdtdk2*x0[j]+dgdotm1dk2*v0[j])
end
if debug
# Now include derivatives of gamma, r, fm1, gmh, dfdt, and dgdtmhdfdtm1:
@inbounds for i=1:3
delxv_jac[ 7,i] = -sqb*rinv*(g2*v0[i]+c3*x0[i]*r0inv3); delxv_jac[7,3+i] = -sqb*rinv*(d*v0[i]+g2*x0[i])
delxv_jac[ 8,i] = (c20*betainv-c2*c3*rinv)*r0inv3*x0[i]+((r0*g1+eta*g2)*rinv)*v0[i]
delxv_jac[8,3+i] = (c18*betainv-d*c2*rinv)*v0[i]+((r0*g1+eta*g2)*rinv)*x0[i]
delxv_jac[ 9,i] = dfm1dxx*x0[i]+dfm1dxv*v0[i]; delxv_jac[ 9,3+i]=dfm1dvx*x0[i]+dfm1dvv*v0[i]
delxv_jac[10,i] = ddfdtdxx*x0[i]+ddfdtdxv*v0[i]; delxv_jac[10,3+i]=ddfdtdvx*x0[i]+ddfdtdvv*v0[i]
delxv_jac[11,i] = dgmhdxx*x0[i]+dgmhdxv*v0[i]; delxv_jac[11,3+i]=dgmhdvx*x0[i]+dgmhdvv*v0[i]
delxv_jac[12,i] = dgdotm1dxx*x0[i]+dgdotm1dxv*v0[i]; delxv_jac[12,3+i]=dgdotm1dvx*x0[i]+dgdotm1dvv*v0[i]
end
delxv_jac[ 7,7] = sqb*c1*r0inv*rinv; delxv_jac[7,8] = sqb*rinv
delxv_jac[ 8,7] = betainv*r0inv*rinv*(-g2*r0^2*beta-eta*g1*g2*(k+beta*r0)+eta*g0*g3*(2*k+zeta)-
g2^2*(beta*eta^2+2*k*zeta)+g1*g3*zeta*(3*k-beta*r0)); delxv_jac[8,8] = c2*rinv
delxv_jac[ 9,7] = dfm1dk; delxv_jac[ 9,8] = dfm1dh
delxv_jac[10,7] = ddfdtdk; delxv_jac[10,8] = ddfdtdh
delxv_jac[11,7] = dgmhdk; delxv_jac[11,8] = dgmhdh
delxv_jac[12,7] = dgdotm1dk; delxv_jac[12,8] = dgdotm1dh
end
end
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 6500 | # The AHL21 integrator WITHOUT derivatives.
"""
Carries out AHL21 mapping with compensated summation, WITHOUT derivatives
"""
function ahl21!(s::State{T},h::T) where T<:AbstractFloat
h2 = 0.5*h;
h6 = h/6
kickfast!(s,h6)
drift!(s,h2)
drift_kepler!(s,h2)
phic!(s,h)
phisalpha!(s,h,T(2.0))
kepler_drift!(s,h2)
drift!(s,h2)
kickfast!(s,h6)
return
end
"""
Drifts all particles with compensated summation.
"""
function drift!(s::State{T},h::T) where {T <: Real}
@inbounds for i=1:s.n, j=1:NDIM
s.x[j,i],s.xerror[j,i] = comp_sum(s.x[j,i],s.xerror[j,i],h*s.v[j,i])
end
return
end
"""
Computes "fast" kicks for pairs of bodies in lieu of -drift+Kepler with compensated summation
"""
function kickfast!(s::State{T},h::T) where {T <: Real}
s.rij .= zero(T)
@inbounds for i=1:s.n-1
for j = i+1:s.n
if s.pair[i,j]
for k=1:3
s.rij[k] = s.x[k,i] - s.x[k,j]
#r2 += s.rij[k]*s.rij[k]
end
r2inv = 1.0/dot_fast(s.rij)
r3inv = r2inv*sqrt(r2inv)
fac2 = h*GNEWT*r3inv
for k=1:3
fac = fac2*s.rij[k]
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i],-s.m[j]*fac)
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j], s.m[i]*fac)
end
end
end
end
return
end
"""
Computes correction for pairs which are kicked.
"""
function phic!(s::State{T},h::T) where {T <: Real}
s.a .= zero(T)
s.rij .= zero(T)
s.aij .= zero(T)
@inbounds for i=1:s.n-1, j = i+1:s.n
if s.pair[i,j] # kick group
for k=1:3
s.rij[k] = s.x[k,i] - s.x[k,j]
#r2 += s.rij[k]^2
end
r2inv = inv(dot_fast(s.rij))
r3inv = r2inv*sqrt(r2inv)
for k=1:3
fac = GNEWT*s.rij[k]*r3inv
facv = fac*2*h/3
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i],-s.m[j]*facv)
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j],s.m[i]*facv)
s.a[k,i] -= s.m[j]*fac
s.a[k,j] += s.m[i]*fac
end
end
end
coeff = h^3/36*GNEWT
@inbounds for i=1:s.n-1 ,j=i+1:s.n
if s.pair[i,j] # kick group
for k=1:3
s.aij[k] = s.a[k,i] - s.a[k,j]
s.rij[k] = s.x[k,i] - s.x[k,j]
end
r2 = dot_fast(s.rij)
r1 = sqrt(r2)
ardot = dot_fast(s.aij,s.rij)
fac1 = coeff/(r2*r2*r1)
fac2 = 3*ardot
for k=1:3
fac = fac1*(s.rij[k]*fac2-r2*s.aij[k])
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i],s.m[j]*fac)
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j],-s.m[i]*fac)
end
end
end
return
end
"""
Computes the 4th-order correction with compensated summation.
"""
function phisalpha!(s::State{T},h::T,alpha::T) where {T <: Real}
s.a .= zero(T)
s.rij .= zero(T)
s.aij .= zero(T)
coeff = alpha*h^3/96*2*GNEWT
fac = zero(T); fac1 = zero(T); fac2 = zero(T); r1 = zero(T); r2 = zero(T); r3 = zero(T)
@inbounds for i=1:s.n-1
for j = i+1:s.n
if ~s.pair[i,j] # correction for Kepler pairs
for k=1:3
s.rij[k] = s.x[k,i] - s.x[k,j]
end
r2 = dot_fast(s.rij)
r3 = r2*sqrt(r2)
fac2 = GNEWT/r3
for k=1:3
fac = fac2*s.rij[k]
s.a[k,i] -= s.m[j]*fac
s.a[k,j] += s.m[i]*fac
end
end
end
end
# Next, compute \tilde g_i acceleration vector (this is rewritten
# slightly to avoid reference to \tilde a_i):
@inbounds for i=1:s.n-1
for j=i+1:s.n
if ~s.pair[i,j] # correction for Kepler pairs
for k=1:3
s.aij[k] = s.a[k,i] - s.a[k,j]
s.rij[k] = s.x[k,i] - s.x[k,j]
end
r2 = dot_fast(s.rij)
r1 = sqrt(r2)
ardot = dot_fast(s.aij,s.rij)
# fac1 = coeff/r1^5
fac1 = coeff/(r2*r2*r1)
fac2 = (2*GNEWT*(s.m[i]+s.m[j])/r1 + 3*ardot)
for k=1:3
fac = fac1*(s.rij[k]*fac2-r2*s.aij[k])
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i], s.m[j]*fac)
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j],-s.m[i]*fac)
end
end
end
end
return
end
"""
Take a combined -drift+kepler step for each pair of bodies.
"""
function drift_kepler!(s::State{T}, h::T) where T<:Real
n = s.n
@inbounds for i in 1:n-1, j in i+1:n
if ~s.pair[i,j]
kepler_driftij_gamma!(s,i,j,h,true)
end
end
return
end
"""
Take a combined kepler-drift step for each pair of bodies
"""
function kepler_drift!(s::State{T}, h::T) where T<:Real
n = s.n
@inbounds for i in n-1:-1:1, j in n:-1:i+1
if ~s.pair[i,j]
kepler_driftij_gamma!(s,i,j,h,false)
end
end
return
end
"""
Carries out a Kepler step and reverse drift for bodies i & j with compensated summation.
"""
function kepler_driftij_gamma!(s::State{T},i::Int64,j::Int64,h::T,drift_first::Bool) where {T <: Real}
@inbounds for k=1:NDIM
s.x0[k] = s.x[k,i] - s.x[k,j] # x0 = positions of body i relative to j
s.v0[k] = s.v[k,i] - s.v[k,j] # v0 = velocities of body i relative to j
end
gm = GNEWT*(s.m[i]+s.m[j])
if gm == 0; return; end
# Compute differences in x & v over time step:
jac_delxv_gamma!(s,gm,h,drift_first,grad=false)
mijinv =1.0/(s.m[i] + s.m[j])
mi = s.m[i]*mijinv # Normalize the masses
mj = s.m[j]*mijinv
@inbounds for k=1:3
# Add kepler-drift differences, weighted by masses, to start of step:
s.x[k,i],s.xerror[k,i] = comp_sum(s.x[k,i],s.xerror[k,i], mj*s.delxv[k])
s.x[k,j],s.xerror[k,j] = comp_sum(s.x[k,j],s.xerror[k,j],-mi*s.delxv[k])
s.v[k,i],s.verror[k,i] = comp_sum(s.v[k,i],s.verror[k,i], mj*s.delxv[3+k])
s.v[k,j],s.verror[k,j] = comp_sum(s.v[k,j],s.verror[k,j],-mi*s.delxv[3+k])
end
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 49305 | # Old versions of AHL21 methods
function ahl21!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,jac_step::Array{T,2},jac_error::Array{T,2},pair::Array{Bool,2}) where {T <: Real}
zilch = zero(T); uno = one(T); half = convert(T,0.5); two = convert(T,2.0)
h2 = half*h; sevn = 7*n
## Replace with PreAllocArrays
jac_phi = zeros(T,sevn,sevn)
jac_kick = zeros(T,sevn,sevn)
jac_copy = zeros(T,sevn,sevn)
jac_ij = zeros(T,14,14)
dqdt_ij = zeros(T,14)
dqdt_phi = zeros(T,sevn)
dqdt_kick = zeros(T,sevn)
jac_tmp1 = zeros(T,14,sevn)
jac_tmp2 = zeros(T,14,sevn)
jac_err1 = zeros(T,14,sevn)
##
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
# Multiply Jacobian from kick step:
if T == BigFloat
jac_copy .= *(jac_kick,jac_step)
else
BLAS.gemm!('N','N',uno,jac_kick,jac_step,zilch,jac_copy)
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(jac_step,jac_error,jac_copy)
drift!(x,v,xerror,verror,h2,n,jac_step,jac_error)
indi = 0; indj = 0
@inbounds for i=1:n-1
indi = (i-1)*7
@inbounds for j=i+1:n
indj = (j-1)*7
if ~pair[i,j] # Check to see if kicks have not been applied
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,true)
# Pick out indices for bodies i & j:
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[k1,k2] = jac_step[ indi+k1,k2]
jac_err1[k1,k2] = jac_error[indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[7+k1,k2] = jac_step[ indj+k1,k2]
jac_err1[7+k1,k2] = jac_error[indj+k1,k2]
end
# Carry out multiplication on the i/j components of matrix:
if T == BigFloat
jac_tmp2 .= *(jac_ij,jac_tmp1)
else
BLAS.gemm!('N','N',uno,jac_ij,jac_tmp1,zilch,jac_tmp2)
end
# Add back in the Jacobian with compensated summation:
comp_sum_matrix!(jac_tmp1,jac_err1,jac_tmp2)
# Copy back to the Jacobian:
@inbounds for k2=1:sevn, k1=1:7
jac_step[ indi+k1,k2]=jac_tmp1[k1,k2]
jac_error[indi+k1,k2]=jac_err1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_step[ indj+k1,k2]=jac_tmp1[7+k1,k2]
jac_error[indj+k1,k2]=jac_err1[7+k1,k2]
end
end
end
end
phic!(x,v,xerror,verror,h,m,n,jac_phi,dqdt_phi,pair)
phisalpha!(x,v,xerror,verror,h,m,two,n,jac_phi,dqdt_phi,pair) # 10%
if T == BigFloat
jac_copy .= *(jac_phi,jac_step)
else
BLAS.gemm!('N','N',uno,jac_phi,jac_step,zilch,jac_copy)
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(jac_step,jac_error,jac_copy)
indi=0; indj=0
@inbounds for i=n-1:-1:1
indi=(i-1)*7
@inbounds for j=n:-1:i+1
indj=(j-1)*7
if ~pair[i,j] # Check to see if kicks have not been applied
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,false)
# Pick out indices for bodies i & j:
# Carry out multiplication on the i/j components of matrix:
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[k1,k2] = jac_step[ indi+k1,k2]
jac_err1[k1,k2] = jac_error[indi+k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_tmp1[7+k1,k2] = jac_step[ indj+k1,k2]
jac_err1[7+k1,k2] = jac_error[indj+k1,k2]
end
# Carry out multiplication on the i/j components of matrix:
if T == BigFloat
jac_tmp2 .= *(jac_ij,jac_tmp1)
else
BLAS.gemm!('N','N',uno,jac_ij,jac_tmp1,zilch,jac_tmp2)
end
# Add back in the Jacobian with compensated summation:
comp_sum_matrix!(jac_tmp1,jac_err1,jac_tmp2)
# Copy back to the Jacobian:
@inbounds for k2=1:sevn, k1=1:7
jac_step[ indi+k1,k2]=jac_tmp1[k1,k2]
jac_error[indi+k1,k2]=jac_err1[k1,k2]
end
@inbounds for k2=1:sevn, k1=1:7
jac_step[ indj+k1,k2]=jac_tmp1[7+k1,k2]
jac_error[indj+k1,k2]=jac_err1[7+k1,k2]
end
end
end
end
drift!(x,v,xerror,verror,h2,n,jac_step,jac_error)
#kickfast!(x,v,h2,m,n,jac_kick,dqdt_kick,pair)
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
# Multiply Jacobian from kick step:
if T == BigFloat
jac_copy .= *(jac_kick,jac_step)
else
BLAS.gemm!('N','N',uno,jac_kick,jac_step,zilch,jac_copy)
end
# Add back in the identity portion of the Jacobian with compensated summation:
comp_sum_matrix!(jac_step,jac_error,jac_copy)
# Edit this routine to do compensated summation for Jacobian [x]
return
end
function ahl21!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,dqdt::Array{T,1},pair::Array{Bool,2}) where {T <: Real}
# [Currently this routine is not giving the correct dqdt values. -EA 8/12/2019]
zilch = zero(T); uno = one(T); half = convert(T,0.5); two = convert(T,2.0)
h2 = half*h
# This routine assumes that alpha = 0.0
sevn = 7*n
jac_phi = zeros(T,sevn,sevn)
jac_kick = zeros(T,sevn,sevn)
jac_ij = zeros(T,14,14)
dqdt_ij = zeros(T,14)
dqdt_phi = zeros(T,sevn)
dqdt_kick = zeros(T,sevn)
dqdt_tmp1 = zeros(T,14)
dqdt_tmp2 = zeros(T,14)
fill!(dqdt,zilch)
#dqdt_save =copy(dqdt)
#println("dqdt 1: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
dqdt_kick /= 6 # Since step is h/6
# Since I removed identity from kickfast, need to add in dqdt:
dqdt .+= dqdt_kick + *(jac_kick,dqdt)
#println("dqdt 2: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
drift!(x,v,xerror,verror,h2,n)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
dqdt[(i-1)*7+k] = half*v[k,i] + h2*dqdt[(i-1)*7+3+k]
end
@inbounds for i=1:n-1
indi = (i-1)*7
@inbounds for j=i+1:n
indj = (j-1)*7
if ~pair[i,j] # Check to see if kicks have not been applied
# kepler_driftij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,true)
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,true)
# Copy current time derivatives for multiplication purposes:
@inbounds for k1=1:7
dqdt_tmp1[ k1] = dqdt[indi+k1]
dqdt_tmp1[7+k1] = dqdt[indj+k1]
end
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
# BLAS.gemm!('N','N',uno,jac_ij,dqdt_tmp1,half,dqdt_ij)
dqdt_ij .*= half
dqdt_ij .+= *(jac_ij,dqdt_tmp1) + dqdt_tmp1
# Copy back time derivatives:
@inbounds for k1=1:7
dqdt[indi+k1] = dqdt_ij[ k1]
dqdt[indj+k1] = dqdt_ij[7+k1]
end
# println("dqdt 4: i: ",i," j: ",j," diff: ",dqdt-dqdt_save)
# dqdt_save .= dqdt
end
end
end
# Looks like we are missing phic! here: [ ]
# Since I haven't added dqdt to phic yet, for now, set jac_phi equal to identity matrix
# (since this is commented out within phisalpha):
#jac_phi .= eye(T,sevn)
phic!(x,v,xerror,verror,h,m,n,jac_phi,dqdt_phi,pair)
phisalpha!(x,v,xerror,verror,h,m,two,n,jac_phi,dqdt_phi,pair) # 10%
# Add in time derivative with respect to prior parameters:
#BLAS.gemm!('N','N',uno,jac_phi,dqdt,uno,dqdt_phi)
# Copy result to dqdt:
dqdt .+= dqdt_phi + *(jac_phi,dqdt)
#println("dqdt 5: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
indi=0; indj=0
@inbounds for i=n-1:-1:1
indi=(i-1)*7
@inbounds for j=n:-1:i+1
if ~pair[i,j] # Check to see if kicks have not been applied
indj=(j-1)*7
# kepler_driftij!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,false) # 23%
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,jac_ij,dqdt_ij,false) # 23%
# Copy current time derivatives for multiplication purposes:
@inbounds for k1=1:7
dqdt_tmp1[ k1] = dqdt[indi+k1]
dqdt_tmp1[7+k1] = dqdt[indj+k1]
end
# Add in partial derivatives with respect to time:
# Need to multiply by 1/2 since we're taking 1/2 time step:
#BLAS.gemm!('N','N',uno,jac_ij,dqdt_tmp1,half,dqdt_ij)
dqdt_ij .*= half
dqdt_ij .+= *(jac_ij,dqdt_tmp1) + dqdt_tmp1
# Copy back time derivatives:
@inbounds for k1=1:7
dqdt[indi+k1] = dqdt_ij[ k1]
dqdt[indj+k1] = dqdt_ij[7+k1]
end
# dqdt_save .= dqdt
# println("dqdt 7: ",dqdt-dqdt_save)
# println("dqdt 6: i: ",i," j: ",j," diff: ",dqdt-dqdt_save)
# dqdt_save .= dqdt
end
end
end
drift!(x,v,xerror,verror,h2,n)
# Compute time derivative of drift step:
@inbounds for i=1:n, k=1:3
dqdt[(i-1)*7+k] += half*v[k,i] + h2*dqdt[(i-1)*7+3+k]
end
fill!(dqdt_kick,zilch)
kickfast!(x,v,xerror,verror,h/6,m,n,jac_kick,dqdt_kick,pair)
dqdt_kick /= 6 # Since step is h/6
# Copy result to dqdt:
dqdt .+= dqdt_kick + *(jac_kick,dqdt)
#println("dqdt 8: ",dqdt-dqdt_save)
#dqdt_save .= dqdt
#println("dqdt 9: ",dqdt-dqdt_save)
return
end
function ahl21!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
h2 = 0.5*h
kickfast!(x,v,xerror,verror,h/6,m,n,pair)
drift!(x,v,xerror,verror,h2,n)
@inbounds for i=1:n-1
for j=i+1:n
if ~pair[i,j]
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,true)
end
end
end
phic!(x,v,xerror,verror,h,m,n,pair)
phisalpha!(x,v,xerror,verror,h,m,convert(T,2),n,pair)
for i=n-1:-1:1
for j=n:-1:i+1
if ~pair[i,j]
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h2,false)
end
end
end
drift!(x,v,xerror,verror,h2,n)
kickfast!(x,v,xerror,verror,h/6,m,n,pair)
return
end
function drift!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,n::Int64,jac_step::Array{T,2},jac_error::Array{T,2}) where {T <: Real}
indi = 0
@inbounds for i=1:n
indi = (i-1)*7
for j=1:NDIM
x[j,i],xerror[j,i] = comp_sum(x[j,i],xerror[j,i],h*v[j,i])
end
# Now for Jacobian:
for k=1:7*n, j=1:NDIM
jac_step[indi+j,k],jac_error[indi+j,k] = comp_sum(jac_step[indi+j,k],jac_error[indi+j,k],h*jac_step[indi+3+j,k])
end
end
return
end
function drift!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,n::Int64) where {T <: Real}
@inbounds for i=1:n, j=1:NDIM
x[j,i],xerror[j,i] = comp_sum(x[j,i],xerror[j,i],h*v[j,i])
end
return
end
function kickfast!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,jac_step::Array{T,2},dqdt_kick::Array{T,1},pair::Array{Bool,2}) where {T <: Real}
rij = zeros(T,3)
# Getting rid of identity since we will add that back in in calling routines:
fill!(jac_step,zero(T))
#jac_step.=eye(T,7*n)
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
indj = (j-1)*7
if pair[i,j]
for k=1:3
rij[k] = x[k,i] - x[k,j]
end
r2inv = 1.0/(rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3])
r3inv = r2inv*sqrt(r2inv)
for k=1:3
fac = h*GNEWT*rij[k]*r3inv
# Apply impulses:
#v[k,i] -= m[j]*fac
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],-m[j]*fac)
#v[k,j] += m[i]*fac
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j], m[i]*fac)
# Compute time derivative:
dqdt_kick[indi+3+k] -= m[j]*fac/h
dqdt_kick[indj+3+k] += m[i]*fac/h
# Computing the derivative
# Mass derivative of acceleration vector (10/6/17 notes):
# Impulse of ith particle depends on mass of jth particle:
jac_step[indi+3+k,indj+7] -= fac
# Impulse of jth particle depends on mass of ith particle:
jac_step[indj+3+k,indi+7] += fac
# x derivative of acceleration vector:
fac *= 3.0*r2inv
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
jac_step[indi+3+k,indi+p] += fac*m[j]*rij[p]
jac_step[indi+3+k,indj+p] -= fac*m[j]*rij[p]
jac_step[indj+3+k,indj+p] += fac*m[i]*rij[p]
jac_step[indj+3+k,indi+p] -= fac*m[i]*rij[p]
end
# Final term has no dot product, so just diagonal:
fac = h*GNEWT*r3inv
jac_step[indi+3+k,indi+k] -= fac*m[j]
jac_step[indi+3+k,indj+k] += fac*m[j]
jac_step[indj+3+k,indj+k] -= fac*m[i]
jac_step[indj+3+k,indi+k] += fac*m[i]
end
end
end
end
return
end
function kickfast!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
rij = zeros(T,3)
@inbounds for i=1:n-1
for j = i+1:n
if pair[i,j]
r2 = zero(T)
for k=1:3
rij[k] = x[k,i] - x[k,j]
r2 += rij[k]*rij[k]
end
r3_inv = 1.0/(r2*sqrt(r2))
for k=1:3
fac = h*GNEWT*rij[k]*r3_inv
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],-m[j]*fac)
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j], m[i]*fac)
end
end
end
end
return
end
function phic!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,jac_step::Array{T,2},dqdt_phi::Array{T,1},pair::Array{Bool,2}) where {T <: Real}
a = zeros(T,3,n)
rij = zeros(T,3)
aij = zeros(T,3)
dadq = zeros(T,3,n,4,n) # There is no velocity dependence
dotdadq = zeros(T,4,n) # There is no velocity dependence
# Set jac_step to zeros:
#jac_step.=eye(T,7*n)
fill!(jac_step,zero(T))
fac = 0.0; fac1 = 0.0; fac2 = 0.0; fac3 = 0.0; r1 = 0.0; r2 = 0.0; r3 = 0.0
coeff = h^3/36*GNEWT
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if pair[i,j]
indj = (j-1)*7
for k=1:3
rij[k] = x[k,i] - x[k,j]
end
r2inv = inv(dot(rij,rij))
r3inv = r2inv*sqrt(r2inv)
for k=1:3
# Apply impulses:
fac = GNEWT*rij[k]*r3inv
facv = fac*2*h/3
#v[k,i] -= m[j]*facv
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],-m[j]*facv)
#v[k,j] += m[i]*facv
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],m[i]*facv)
# Compute time derivative:
dqdt_phi[indi+3+k] -= 3/h*m[j]*facv
dqdt_phi[indj+3+k] += 3/h*m[i]*facv
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
# Impulse of ith particle depends on mass of jth particle:
jac_step[indi+3+k,indj+7] -= facv
# Impulse of jth particle depends on mass of ith particle:
jac_step[indj+3+k,indi+7] += facv
# x derivative of acceleration vector:
facv *= 3.0*r2inv
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
jac_step[indi+3+k,indi+p] += facv*m[j]*rij[p]
jac_step[indi+3+k,indj+p] -= facv*m[j]*rij[p]
jac_step[indj+3+k,indj+p] += facv*m[i]*rij[p]
jac_step[indj+3+k,indi+p] -= facv*m[i]*rij[p]
end
# Final term has no dot product, so just diagonal:
facv = 2h/3*GNEWT*r3inv
jac_step[indi+3+k,indi+k] -= facv*m[j]
jac_step[indi+3+k,indj+k] += facv*m[j]
jac_step[indj+3+k,indj+k] -= facv*m[i]
jac_step[indj+3+k,indi+k] += facv*m[i]
# Mass derivative of acceleration vector (10/6/17 notes):
# Since there is no velocity dependence, this is fourth parameter.
# Acceleration of ith particle depends on mass of jth particle:
dadq[k,i,4,j] -= fac
dadq[k,j,4,i] += fac
# x derivative of acceleration vector:
fac *= 3.0*r2inv
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
dadq[k,i,p,i] += fac*m[j]*rij[p]
dadq[k,i,p,j] -= fac*m[j]*rij[p]
dadq[k,j,p,j] += fac*m[i]*rij[p]
dadq[k,j,p,i] -= fac*m[i]*rij[p]
end
# Final term has no dot product, so just diagonal:
fac = GNEWT*r3inv
dadq[k,i,k,i] -= fac*m[j]
dadq[k,i,k,j] += fac*m[j]
dadq[k,j,k,j] -= fac*m[i]
dadq[k,j,k,i] += fac*m[i]
end
end
end
end
# Next, compute g_i acceleration vector.
# Note that jac_step[(i-1)*7+k,(j-1)*7+p] is the derivative of the kth coordinate
# of planet i with respect to the pth coordinate of planet j.
indi = 0; indj=0; indd = 0
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if pair[i,j] # correction for Kepler pairs
indj = (j-1)*7
for k=1:3
aij[k] = a[k,i] - a[k,j]
rij[k] = x[k,i] - x[k,j]
end
# Compute dot product of r_ij with \delta a_ij:
fill!(dotdadq,0.0)
@inbounds for d=1:n, p=1:4, k=1:3
dotdadq[p,d] += rij[k]*(dadq[k,i,p,d]-dadq[k,j,p,d])
end
r2 = dot(rij,rij)
r1 = sqrt(r2)
ardot = dot(aij,rij)
fac1 = coeff/r1^5
fac2 = 3*ardot
for k=1:3
fac = fac1*(rij[k]*fac2- r2*aij[k])
#v[k,i] += m[j]*fac
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],m[j]*fac)
#v[k,j] -= m[i]*fac
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*fac)
# Mass derivative (first part is easy):
jac_step[indi+3+k,indj+7] += fac
jac_step[indj+3+k,indi+7] -= fac
# Position derivatives:
fac *= 5.0/r2
for p=1:3
jac_step[indi+3+k,indi+p] -= fac*m[j]*rij[p]
jac_step[indi+3+k,indj+p] += fac*m[j]*rij[p]
jac_step[indj+3+k,indj+p] -= fac*m[i]*rij[p]
jac_step[indj+3+k,indi+p] += fac*m[i]*rij[p]
end
# Diagonal position terms:
fac = fac1*fac2
jac_step[indi+3+k,indi+k] += fac*m[j]
jac_step[indi+3+k,indj+k] -= fac*m[j]
jac_step[indj+3+k,indj+k] += fac*m[i]
jac_step[indj+3+k,indi+k] -= fac*m[i]
# Dot product \delta rij terms:
fac = -2*fac1*aij[k]
for p=1:3
fac3 = fac*rij[p] + fac1*3.0*rij[k]*aij[p]
jac_step[indi+3+k,indi+p] += m[j]*fac3
jac_step[indi+3+k,indj+p] -= m[j]*fac3
jac_step[indj+3+k,indj+p] += m[i]*fac3
jac_step[indj+3+k,indi+p] -= m[i]*fac3
end
# Diagonal acceleration terms:
fac = -fac1*r2
# Duoh. For dadq, have to loop over all other parameters!
@inbounds for d=1:n
indd = (d-1)*7
for p=1:3
jac_step[indi+3+k,indd+p] += fac*m[j]*(dadq[k,i,p,d]-dadq[k,j,p,d])
jac_step[indj+3+k,indd+p] -= fac*m[i]*(dadq[k,i,p,d]-dadq[k,j,p,d])
end
# Don't forget mass-dependent term:
jac_step[indi+3+k,indd+7] += fac*m[j]*(dadq[k,i,4,d]-dadq[k,j,4,d])
jac_step[indj+3+k,indd+7] -= fac*m[i]*(dadq[k,i,4,d]-dadq[k,j,4,d])
end
# Now, for the final term: (\delta a_ij . r_ij ) r_ij
fac = 3.0*fac1*rij[k]
@inbounds for d=1:n
indd = (d-1)*7
for p=1:3
jac_step[indi+3+k,indd+p] += fac*m[j]*dotdadq[p,d]
jac_step[indj+3+k,indd+p] -= fac*m[i]*dotdadq[p,d]
end
jac_step[indi+3+k,indd+7] += fac*m[j]*dotdadq[4,d]
jac_step[indj+3+k,indd+7] -= fac*m[i]*dotdadq[4,d]
end
end
end
end
end
return
end
function phic!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
a = zeros(T,3,n)
rij = zeros(T,3)
aij = zeros(T,3)
@inbounds for i=1:n-1, j = i+1:n
if pair[i,j] # kick group
r2 = 0.0
for k=1:3
rij[k] = x[k,i] - x[k,j]
r2 += rij[k]^2
end
r3_inv = 1.0/(r2*sqrt(r2))
for k=1:3
fac = GNEWT*rij[k]*r3_inv
facv = fac*2*h/3
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],-m[j]*facv)
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],m[i]*facv)
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
end
end
end
coeff = h^3/36*GNEWT
@inbounds for i=1:n-1 ,j=i+1:n
if pair[i,j] # kick group
for k=1:3
aij[k] = a[k,i] - a[k,j]
rij[k] = x[k,i] - x[k,j]
end
r2 = dot(rij,rij)
r5inv = 1.0/(r2^2*sqrt(r2))
ardot = dot(aij,rij)
for k=1:3
fac = coeff*r5inv*(rij[k]*3*ardot-r2*aij[k])
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],m[j]*fac)
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*fac)
end
end
end
return
end
function phisalpha!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},alpha::T,n::Int64,jac_step::Array{T,2},dqdt_phi::Array{T,1},pair::Array{Bool,2}) where {T <: Real}
a = zeros(T,3,n)
dadq = zeros(T,3,n,4,n) # There is no velocity dependence
dotdadq = zeros(T,4,n) # There is no velocity dependence
rij = zeros(T,3)
aij = zeros(T,3)
coeff = alpha*h^3/96*2*GNEWT
fac = 0.0; fac1 = 0.0; fac2 = 0.0; fac3 = 0.0; r1 = 0.0; r2 = 0.0; r3 = 0.0
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if ~pair[i,j] # correction for Kepler pairs
indj = (j-1)*7
for k=1:3
rij[k] = x[k,i] - x[k,j]
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r3 = r2*sqrt(r2)
for k=1:3
fac = GNEWT*rij[k]/r3
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
# Mass derivative of acceleration vector (10/6/17 notes):
# Since there is no velocity dependence, this is fourth parameter.
# Acceleration of ith particle depends on mass of jth particle:
dadq[k,i,4,j] -= fac
dadq[k,j,4,i] += fac
# x derivative of acceleration vector:
fac *= 3.0/r2
# Dot product x_ij.\delta x_ij means we need to sum over components:
for p=1:3
dadq[k,i,p,i] += fac*m[j]*rij[p]
dadq[k,i,p,j] -= fac*m[j]*rij[p]
dadq[k,j,p,j] += fac*m[i]*rij[p]
dadq[k,j,p,i] -= fac*m[i]*rij[p]
end
# Final term has no dot product, so just diagonal:
fac = GNEWT/r3
dadq[k,i,k,i] -= fac*m[j]
dadq[k,i,k,j] += fac*m[j]
dadq[k,j,k,j] -= fac*m[i]
dadq[k,j,k,i] += fac*m[i]
end
end
end
end
# Next, compute \tilde g_i acceleration vector (this is rewritten
# slightly to avoid reference to \tilde a_i):
# Note that jac_step[(i-1)*7+k,(j-1)*7+p] is the derivative of the kth coordinate
# of planet i with respect to the pth coordinate of planet j.
indi = 0; indj=0; indd = 0
@inbounds for i=1:n-1
indi = (i-1)*7
for j=i+1:n
if ~pair[i,j] # correction for Kepler pairs
indj = (j-1)*7
for k=1:3
aij[k] = a[k,i] - a[k,j]
rij[k] = x[k,i] - x[k,j]
end
# Compute dot product of r_ij with \delta a_ij:
fill!(dotdadq,0.0)
@inbounds for d=1:n, p=1:4, k=1:3
dotdadq[p,d] += rij[k]*(dadq[k,i,p,d]-dadq[k,j,p,d])
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r1 = sqrt(r2)
ardot = aij[1]*rij[1]+aij[2]*rij[2]+aij[3]*rij[3]
fac1 = coeff/r1^5
fac2 = (2*GNEWT*(m[i]+m[j])/r1 + 3*ardot)
for k=1:3
fac = fac1*(rij[k]*fac2- r2*aij[k])
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], m[j]*fac)
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*fac)
# Compute time derivative:
dqdt_phi[indi+3+k] += 3/h*m[j]*fac
dqdt_phi[indj+3+k] -= 3/h*m[i]*fac
# Mass derivative (first part is easy):
jac_step[indi+3+k,indj+7] += fac
jac_step[indj+3+k,indi+7] -= fac
# Position derivatives:
fac *= 5.0/r2
for p=1:3
jac_step[indi+3+k,indi+p] -= fac*m[j]*rij[p]
jac_step[indi+3+k,indj+p] += fac*m[j]*rij[p]
jac_step[indj+3+k,indj+p] -= fac*m[i]*rij[p]
jac_step[indj+3+k,indi+p] += fac*m[i]*rij[p]
end
# Second mass derivative:
fac = 2*GNEWT*fac1*rij[k]/r1
jac_step[indi+3+k,indi+7] += fac*m[j]
jac_step[indi+3+k,indj+7] += fac*m[j]
jac_step[indj+3+k,indj+7] -= fac*m[i]
jac_step[indj+3+k,indi+7] -= fac*m[i]
# (There's also a mass term in dadq [x]. See below.)
# Diagonal position terms:
fac = fac1*fac2
jac_step[indi+3+k,indi+k] += fac*m[j]
jac_step[indi+3+k,indj+k] -= fac*m[j]
jac_step[indj+3+k,indj+k] += fac*m[i]
jac_step[indj+3+k,indi+k] -= fac*m[i]
# Dot product \delta rij terms:
fac = -2*fac1*(rij[k]*GNEWT*(m[i]+m[j])/(r2*r1)+aij[k])
for p=1:3
fac3 = fac*rij[p] + fac1*3.0*rij[k]*aij[p]
jac_step[indi+3+k,indi+p] += m[j]*fac3
jac_step[indi+3+k,indj+p] -= m[j]*fac3
jac_step[indj+3+k,indj+p] += m[i]*fac3
jac_step[indj+3+k,indi+p] -= m[i]*fac3
end
# Diagonal acceleration terms:
fac = -fac1*r2
# Duoh. For dadq, have to loop over all other parameters!
@inbounds for d=1:n
indd = (d-1)*7
for p=1:3
jac_step[indi+3+k,indd+p] += fac*m[j]*(dadq[k,i,p,d]-dadq[k,j,p,d])
jac_step[indj+3+k,indd+p] -= fac*m[i]*(dadq[k,i,p,d]-dadq[k,j,p,d])
end
# Don't forget mass-dependent term:
jac_step[indi+3+k,indd+7] += fac*m[j]*(dadq[k,i,4,d]-dadq[k,j,4,d])
jac_step[indj+3+k,indd+7] -= fac*m[i]*(dadq[k,i,4,d]-dadq[k,j,4,d])
end
# Now, for the final term: (\delta a_ij . r_ij ) r_ij
fac = 3.0*fac1*rij[k]
@inbounds for d=1:n
indd = (d-1)*7
for p=1:3
jac_step[indi+3+k,indd+p] += fac*m[j]*dotdadq[p,d]
jac_step[indj+3+k,indd+p] -= fac*m[i]*dotdadq[p,d]
end
jac_step[indi+3+k,indd+7] += fac*m[j]*dotdadq[4,d]
jac_step[indj+3+k,indd+7] -= fac*m[i]*dotdadq[4,d]
end
end
end
end
end
return
end
function phisalpha!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},alpha::T,n::Int64,pair::Array{Bool,2}) where {T <: Real}
a = zeros(T,3,n)
rij = zeros(T,3)
aij = zeros(T,3)
coeff = alpha*h^3/96*2*GNEWT
fac = zero(T); fac1 = zero(T); fac2 = zero(T); r1 = zero(T); r2 = zero(T); r3 = zero(T)
@inbounds for i=1:n-1
for j = i+1:n
if ~pair[i,j] # correction for Kepler pairs
for k=1:3
rij[k] = x[k,i] - x[k,j]
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r3 = r2*sqrt(r2)
for k=1:3
fac = GNEWT*rij[k]/r3
a[k,i] -= m[j]*fac
a[k,j] += m[i]*fac
end
end
end
end
# Next, compute \tilde g_i acceleration vector (this is rewritten
# slightly to avoid reference to \tilde a_i):
@inbounds for i=1:n-1
for j=i+1:n
if ~pair[i,j] # correction for Kepler pairs
for k=1:3
aij[k] = a[k,i] - a[k,j]
rij[k] = x[k,i] - x[k,j]
end
r2 = rij[1]*rij[1]+rij[2]*rij[2]+rij[3]*rij[3]
r1 = sqrt(r2)
ardot = aij[1]*rij[1]+aij[2]*rij[2]+aij[3]*rij[3]
fac1 = coeff/r1^5
fac2 = (2*GNEWT*(m[i]+m[j])/r1 + 3*ardot)
for k=1:3
fac = fac1*(rij[k]*fac2- r2*aij[k])
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], m[j]*fac)
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*fac)
end
end
end
end
return
end
function kepler_driftij_gamma!(m::Array{T,1},x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T,jac_ij::Array{T,2},dqdt::Array{T,1},drift_first::Bool) where {T <: Real}
# Initial state:
x0 = zeros(T,NDIM) # x0 = positions of body i relative to j
v0 = zeros(T,NDIM) # v0 = velocities of body i relative to j
@inbounds for k=1:NDIM
x0[k] = x[k,i] - x[k,j]
v0[k] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
# jac_ij should be the Jacobian for going from (x_{0,i},v_{0,i},m_i) & (x_{0,j},v_{0,j},m_j)
# to (x_i,v_i,m_i) & (x_j,v_j,m_j), a 14x14 matrix for the 3-dimensional case.
# Fill with zeros for now:
#jac_ij .= eye(T,14)
fill!(jac_ij,zero(T))
if gm == 0
# Do nothing
# for k=1:3
# x[k,i] += h*v[k,i]
# x[k,j] += h*v[k,j]
# end
else
delxv = zeros(T,6)
jac_kepler = zeros(T,6,8)
jac_mass = zeros(T,6)
jac_delxv_gamma!(x0,v0,gm,h,drift_first,delxv,jac_kepler,jac_mass,false)
# kepler_drift_step!(gm, h, state0, state,jac_kepler,drift_first)
mijinv::T =one(T)/(m[i] + m[j])
mi::T = m[i]*mijinv # Normalize the masses
mj::T = m[j]*mijinv
@inbounds for k=1:3
# Add kepler-drift differences, weighted by masses, to start of step:
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i], mj*delxv[k])
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],-mi*delxv[k])
end
@inbounds for k=1:3
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], mj*delxv[3+k])
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-mi*delxv[3+k])
end
# Compute Jacobian:
@inbounds for l=1:6, k=1:6
# Compute derivatives of x_i,v_i with respect to initial conditions:
jac_ij[ k, l] += mj*jac_kepler[k,l]
jac_ij[ k,7+l] -= mj*jac_kepler[k,l]
# Compute derivatives of x_j,v_j with respect to initial conditions:
jac_ij[7+k, l] -= mi*jac_kepler[k,l]
jac_ij[7+k,7+l] += mi*jac_kepler[k,l]
end
@inbounds for k=1:6
# Compute derivatives of x_i,v_i with respect to the masses:
# println("Old dxv/dm_i: ",-mj*delxv[k]*mijinv + GNEWT*mj*jac_kepler[ k,7])
# jac_ij[ k, 7] = -mj*delxv[k]*mijinv + GNEWT*mj*jac_kepler[ k,7]
# println("New dx/dm_i: ",jac_mass[k]*m[j])
jac_ij[ k, 7] = jac_mass[k]*m[j]
jac_ij[ k,14] = mi*delxv[k]*mijinv + GNEWT*mj*jac_kepler[ k,7]
# Compute derivatives of x_j,v_j with respect to the masses:
jac_ij[ 7+k, 7] = -mj*delxv[k]*mijinv - GNEWT*mi*jac_kepler[ k,7]
# println("Old dxv/dm_j: ",mi*delxv[k]*mijinv - GNEWT*mi*jac_kepler[ k,7])
# jac_ij[ 7+k,14] = mi*delxv[k]*mijinv - GNEWT*mi*jac_kepler[ k,7]
# println("New dxv/dm_j: ",-jac_mass[k]*m[i])
jac_ij[ 7+k,14] = -jac_mass[k]*m[i]
end
end
# The following lines are meant to compute dq/dt for kepler_driftij,
# but they currently contain an error (test doesn't pass in test_ahl21.jl). [ ]
@inbounds for k=1:6
# Position/velocity derivative, body i:
dqdt[ k] = mj*jac_kepler[k,8]
# Position/velocity derivative, body j:
dqdt[7+k] = -mi*jac_kepler[k,8]
end
return
end
function kepler_driftij_gamma!(m::Array{T,1},x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T,drift_first::Bool) where {T <: Real}
x0 = zeros(T,NDIM) # x0 = positions of body i relative to j
v0 = zeros(T,NDIM) # v0 = velocities of body i relative to j
@inbounds for k=1:NDIM
x0[k] = x[k,i] - x[k,j]
v0[k] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
if gm == 0
# Do nothing
# for k=1:3
# x[k,i] += h*v[k,i]
# x[k,j] += h*v[k,j]
# end
else
# Compute differences in x & v over time step:
delxv = jac_delxv_gamma!(x0,v0,gm,h,drift_first)
mijinv =1.0/(m[i] + m[j])
mi = m[i]*mijinv # Normalize the masses
mj = m[j]*mijinv
@inbounds for k=1:3
# Add kepler-drift differences, weighted by masses, to start of step:
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i], mj*delxv[k])
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],-mi*delxv[k])
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i], mj*delxv[3+k])
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-mi*delxv[3+k])
end
end
return
end
function jac_delxv_gamma!(x0::Array{T,1},v0::Array{T,1},k::T,h::T,drift_first::Bool;grad::Bool=false,auto::Bool=false,dlnq::T=convert(T,0.0),debug=false) where {T <: Real}
# Using autodiff, computes Jacobian of delx & delv with respect to x0, v0, k & h.
# Autodiff requires a single-vector input, so create an array to hold the independent variables:
input = zeros(T,8)
input[1:3]=x0; input[4:6]=v0; input[7]=k; input[8]=h
if grad
if debug
# Also output gamma, r, fm1, dfdt, gmh, dgdtm1, and for debugging:
delxv_jac = zeros(T,12,8)
else
# Output \delta x & \delta v only:
delxv_jac = zeros(T,6,8)
end
end
# Create a closure so that the function knows value of drift_first:
function delx_delv(input::Array{T2,1}) where {T2 <: Real} # input = x0,v0,k,h,drift_first
# Compute delx and delv from h, s, k, beta0, x0 and v0:
x0 = input[1:3]; v0 = input[4:6]; k = input[7]; h = input[8]
# Compute r0:
drift_first ? r0 = norm(x0-h*v0) : r0 = norm(x0)
# And its inverse:
r0inv = inv(r0)
# Compute beta_0:
beta0 = 2k*r0inv-dot(v0,v0)
beta0inv = inv(beta0)
signb = sign(beta0)
sqb = sqrt(signb*beta0)
zeta = k-r0*beta0
gamma_guess = zero(T2)
# Compute \eta_0 = x_0 . v_0:
drift_first ? eta = dot(x0-h*v0,v0) : eta = dot(x0,v0)
if zeta != zero(T2)
# Make sure we have a cubic in gamma (and don't divide by zero):
gamma_guess = cubic1(3eta*sqb/zeta,6r0*signb*beta0/zeta,-6h*signb*beta0*sqb/zeta)
else
# Check that we have a quadratic in gamma (and don't divide by zero):
if eta != zero(T2)
reta = r0/eta
disc = reta^2+2h/eta
disc > zero(T2) ? gamma_guess = sqb*(-reta+sqrt(disc)) : gamma_guess = h*r0inv*sqb
else
gamma_guess = h*r0inv*sqb
end
end
gamma = copy(gamma_guess)
# Make sure prior two steps differ:
gamma1 = 2*copy(gamma)
gamma2 = 3*copy(gamma)
iter = 0
ITMAX = 20
# Compute coefficients: (8/28/19 notes)
# c1 = k; c2 = -zeta; c3 = -eta*sqb; c4 = sqb*(eta-h*beta0); c5 = eta*signb*sqb
c1 = k; c2 = -2zeta; c3 = 2*eta*signb*sqb; c4 = -sqb*h*beta0; c5 = 2eta*signb*sqb
# Solve for gamma:
while true
gamma2 = gamma1
gamma1 = gamma
xx = 0.5*gamma
# xx = gamma
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
sx = sinh(xx); cx = exp(-xx)+sx
end
# gamma -= (c1*gamma+c2*sx+c3*cx+c4)/(c2*cx+c5*sx+c1)
gamma -= (k*gamma+c2*sx*cx+c3*sx^2+c4)/(2signb*zeta*sx^2+c5*sx*cx+r0*beta0)
iter +=1
if iter >= ITMAX || gamma == gamma2 || gamma == gamma1
break
end
end
# if typeof(gamma) == Float64
# println("s: ",gamma/sqb)
# end
# Set up a single output array for delx and delv:
if debug
delxv = zeros(T2,12)
else
delxv = zeros(T2,6)
end
# Since we updated gamma, need to recompute:
xx = 0.5*gamma
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
sx = sinh(xx); cx = exp(-xx)+sx
end
# Now, compute final values. Compute Wisdom/Hernandez G_i^\beta(s) functions:
g1bs = 2sx*cx/sqb
g2bs = 2signb*sx^2*beta0inv
g0bs = one(T2)-beta0*g2bs
g3bs = G3(gamma,beta0)
h1 = zero(T2); h2 = zero(T2)
# if typeof(g1bs) == Float64
# println("g1: ",g1bs," g2: ",g2bs," g3: ",g3bs)
# end
# Compute r from equation (35):
r = r0*g0bs+eta*g1bs+k*g2bs
# if typeof(r) == Float64
# println("r: ",r)
# end
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv # [x]
if drift_first
# Drift backwards before Kepler step: (1/22/2018)
fm1 = -k*r0inv*g2bs # [x]
# This is given in 2/7/2018 notes: g-h*f
# gmh = k*r0inv*(r0*(g1bs*g2bs-g3bs)+eta*g2bs^2+k*g3bs*g2bs) # [x]
# println("Old gmh: ",gmh," new gmh: ",k*r0inv*(h*g2bs-r0*g3bs)) # [x]
gmh = k*r0inv*(h*g2bs-r0*g3bs) # [x]
else
# Drift backwards after Kepler step: (1/24/2018)
# The following line is f-1-h fdot:
h1= H1(gamma,beta0); h2= H2(gamma,beta0)
# fm1 = k*rinv*(g2bs-k*r0inv*H1(gamma,beta0)) # [x]
fm1 = k*rinv*(g2bs-k*r0inv*h1) # [x]
# This is g-h*dgdt
# gmh = k*rinv*(r0*H2(gamma,beta0)+eta*H1(gamma,beta0)) # [x]
gmh = k*rinv*(r0*h2+eta*h1) # [x]
end
# Compute velocity component functions:
if drift_first
# This is gdot - h fdot - 1:
# dgdtm1 = k*r0inv*rinv*(r0*g0bs*g2bs+eta*g1bs*g2bs+k*g1bs*g3bs) # [x]
# println("gdot-h fdot-1: ",dgdtm1," alternative expression: ",k*r0inv*rinv*(h*g1bs-r0*g2bs))
dgdtm1 = k*r0inv*rinv*(h*g1bs-r0*g2bs)
else
# This is gdot - 1:
dgdtm1 = -k*rinv*g2bs # [x]
end
# if typeof(fm1) == Float64
# println("fm1: ",fm1," dfdt: ",dfdt," gmh: ",gmh," dgdt-1: ",dgdtm1)
# end
@inbounds for j=1:3
# Compute difference vectors (finish - start) of step:
delxv[ j] = fm1*x0[j]+gmh*v0[j] # position x_ij(t+h)-x_ij(t) - h*v_ij(t) or -h*v_ij(t+h)
end
@inbounds for j=1:3
delxv[3+j] = dfdt*x0[j]+dgdtm1*v0[j] # velocity v_ij(t+h)-v_ij(t)
end
if debug
delxv[7] = gamma
delxv[8] = r
delxv[9] = fm1
delxv[10] = dfdt
delxv[11] = gmh
delxv[12] = dgdtm1
end
if grad == true && auto == false && dlnq == 0.0
# Compute gradient analytically:
jac_mass = zeros(T,6)
compute_jacobian_gamma!(gamma,g0bs,g1bs,g2bs,g3bs,h1,h2,dfdt,fm1,gmh,dgdtm1,r0,r,r0inv,rinv,k,h,beta0,beta0inv,eta,sqb,zeta,x0,v0,delxv_jac,jac_mass,drift_first,debug)
end
return delxv
end
# Use autodiff to compute Jacobian:
if grad
if auto
# delxv_jac = ForwardDiff.jacobian(delx_delv,input)
if debug
delxv = zeros(T,12)
else
delxv = zeros(T,6)
end
out = DiffResults.JacobianResult(delxv,input)
ForwardDiff.jacobian!(out,delx_delv,input)
delxv_jac = DiffResults.jacobian(out)
delxv = DiffResults.value(out)
elseif dlnq != 0.0
# Use finite differences to compute Jacobian:
if debug
delxv_jac = zeros(T,12,8)
else
delxv_jac = zeros(T,6,8)
end
delxv = delx_delv(input)
@inbounds for j=1:8
# Difference the jth component:
inputp = copy(input); dp = dlnq*inputp[j]; inputp[j] += dp
delxvp = delx_delv(inputp)
inputm = copy(input); inputm[j] -= dp
delxvm = delx_delv(inputm)
delxv_jac[:,j] = (delxvp-delxvm)/(2*dp)
end
else
# If grad = true and dlnq = 0.0, then the above routine will compute Jacobian analytically.
delxv = delx_delv(input)
end
# Return Jacobian:
return delxv::Array{T,1},delxv_jac::Array{T,2}
else
return delx_delv(input)::Array{T,1}
end
end
function jac_delxv_gamma!(x0::Array{T,1},v0::Array{T,1},k::T,h::T,drift_first::Bool,delxv::Array{T,1},delxv_jac::Array{T,2},jac_mass::Array{T,1},debug::Bool) where {T <: Real}
# Compute r0:
drift_first ? r0 = norm(x0-h*v0) : r0 = norm(x0)
# And its inverse:
r0inv = inv(r0)
# Compute beta_0:
beta0 = 2k*r0inv-dot(v0,v0)
beta0inv = inv(beta0)
signb = sign(beta0)
sqb = sqrt(signb*beta0)
zeta = k-r0*beta0
gamma_guess = zero(T)
# Compute \eta_0 = x_0 . v_0:
drift_first ? eta = dot(x0-h*v0,v0) : eta = dot(x0,v0)
if zeta != zero(T)
# Make sure we have a cubic in gamma (and don't divide by zero):
gamma_guess = cubic1(3eta*sqb/zeta,6r0*signb*beta0/zeta,-6h*signb*beta0*sqb/zeta)
else
# Check that we have a quadratic in gamma (and don't divide by zero):
if eta != zero(T)
reta = r0/eta
disc = reta^2+2h/eta
disc > zero(T) ? gamma_guess = sqb*(-reta+sqrt(disc)) : gamma_guess = h*r0inv*sqb
else
gamma_guess = h*r0inv*sqb
end
end
gamma = copy(gamma_guess)
# Make sure prior two steps differ:
gamma1 = 2*copy(gamma)
gamma2 = 3*copy(gamma)
iter = 0
ITMAX = 20
# Compute coefficients: (8/28/19 notes)
c1 = k; c2 = -2zeta; c3 = 2*eta*signb*sqb; c4 = -sqb*h*beta0; c5 = 2eta*signb*sqb
# Solve for gamma:
while true
gamma2 = gamma1
gamma1 = gamma
xx = 0.5*gamma
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
sx = sinh(xx); cx = exp(-xx)+sx
end
gamma -= (k*gamma+c2*sx*cx+c3*sx^2+c4)/(2signb*zeta*sx^2+c5*sx*cx+r0*beta0)
iter +=1
if iter >= ITMAX || gamma == gamma2 || gamma == gamma1
break
end
end
# Set up a single output array for delx and delv:
fill!(delxv,zero(T))
# Since we updated gamma, need to recompute:
xx = 0.5*gamma
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
sx = sinh(xx); cx = exp(-xx)+sx
end
# Now, compute final values. Compute Wisdom/Hernandez G_i^\beta(s) functions:
g1bs = 2sx*cx/sqb
g2bs = 2signb*sx^2*beta0inv
g0bs = one(T)-beta0*g2bs
g3bs = G3(gamma,beta0)
h1 = zero(T); h2 = zero(T)
# Compute r from equation (35):
r = r0*g0bs+eta*g1bs+k*g2bs
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv # [x]
if drift_first
# Drift backwards before Kepler step: (1/22/2018)
fm1 = -k*r0inv*g2bs # [x]
# This is given in 2/7/2018 notes: g-h*f
gmh = k*r0inv*(h*g2bs-r0*g3bs) # [x]
else
# Drift backwards after Kepler step: (1/24/2018)
# The following line is f-1-h fdot:
h1= H1(gamma,beta0); h2= H2(gamma,beta0)
fm1 = k*rinv*(g2bs-k*r0inv*h1) # [x]
# This is g-h*dgdt
gmh = k*rinv*(r0*h2+eta*h1) # [x]
end
# Compute velocity component functions:
if drift_first
# This is gdot - h fdot - 1:
dgdtm1 = k*r0inv*rinv*(h*g1bs-r0*g2bs)
else
# This is gdot - 1:
dgdtm1 = -k*rinv*g2bs # [x]
end
@inbounds for j=1:3
# Compute difference vectors (finish - start) of step:
delxv[ j] = fm1*x0[j]+gmh*v0[j] # position x_ij(t+h)-x_ij(t) - h*v_ij(t) or -h*v_ij(t+h)
end
@inbounds for j=1:3
delxv[3+j] = dfdt*x0[j]+dgdtm1*v0[j] # velocity v_ij(t+h)-v_ij(t)
end
if debug
delxv[7] = gamma
delxv[8] = r
delxv[9] = fm1
delxv[10] = dfdt
delxv[11] = gmh
delxv[12] = dgdtm1
end
# Compute gradient analytically:
compute_jacobian_gamma!(gamma,g0bs,g1bs,g2bs,g3bs,h1,h2,dfdt,fm1,gmh,dgdtm1,r0,r,r0inv,rinv,k,h,beta0,beta0inv,eta,sqb,zeta,x0,v0,delxv_jac,jac_mass,drift_first,debug)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 10896 | # The DH17 integrator WITHOUT derivatives.
"""
Carries out the DH17 mapping with compensated summation.
"""
function dh17!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},h::T,m::Array{T,1},n::Int64,pair::Array{Bool,2}) where {T <: Real}
alpha = convert(T,alpha0)
h2 = 0.5*h
# alpha = 0. is similar in precision to alpha=0.25
kickfast!(x,v,xerror,verror,h/6,m,n,pair)
if alpha != 0.0
phisalpha!(x,v,xerror,verror,h,m,alpha,n,pair)
end
#mbig = big.(m); h2big = big(h2)
#xbig = big.(x); vbig = big.(v)
drift!(x,v,xerror,verror,h2,n)
#drift!(xbig,vbig,h2big,n)
#xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
#x .= xcompare; v .= vcompare
#hbig = big(h)
@inbounds for i=1:n-1
@inbounds for j=i+1:n
if ~pair[i,j]
# xbig = big.(x); vbig = big.(v)
driftij!(x,v,xerror,verror,i,j,-h2)
# driftij!(xbig,vbig,i,j,-h2big)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
# x .= xcompare; v .= vcompare
# xbig = big.(x); vbig = big.(v)
# keplerij!(mbig,xbig,vbig,i,j,h2big)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
keplerij!(m,x,v,xerror,verror,i,j,h2)
# x .= xcompare; v .= vcompare
end
end
end
# kick and correction for pairs which are kicked:
phic!(x,v,xerror,verror,h,m,n,pair)
if alpha != 1.0
# xbig = big.(x); vbig = big.(v)
phisalpha!(x,v,xerror,verror,h,m,2.0*(1.0-alpha),n,pair)
# phisalpha!(xbig,vbig,hbig,mbig,2*(1-big(alpha)),n,pair)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
# x .= xcompare; v .= vcompare
end
@inbounds for i=n-1:-1:1
@inbounds for j=n:-1:i+1
if ~pair[i,j]
# xbig = big.(x); vbig = big.(v)
# keplerij!(mbig,xbig,vbig,i,j,h2big)
#x = convert(Array{T,2},xbig); v = convert(Array{T,2},vbig)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
keplerij!(m,x,v,xerror,verror,i,j,h2)
# x .= xcompare; v .= vcompare
# xbig = big.(x); vbig = big.(v)
driftij!(x,v,xerror,verror,i,j,-h2)
# driftij!(xbig,vbig,i,j,-h2big)
# xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
# x .= xcompare; v .= vcompare
end
end
end
#xbig = big.(x); vbig = big.(v)
drift!(x,v,xerror,verror,h2,n)
#drift!(xbig,vbig,h2big,n)
#xcompare = convert(Array{T,2},xbig); vcompare = convert(Array{T,2},vbig)
#x .= xcompare; v .= vcompare
if alpha != 0.0
phisalpha!(x,v,xerror,verror,h,m,alpha,n,pair)
end
kickfast!(x,v,xerror,verror,h/6,m,n,pair)
return
end
"""
Drifts bodies i & j with compensated summation:
"""
function driftij!(x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T) where {T <: Real}
for k=1:NDIM
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],h*v[k,i])
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],h*v[k,j])
end
return
end
"""
Carries out a Kepler step for bodies i & j with compensated summation:
"""
function keplerij!(m::Array{T,1},x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},i::Int64,j::Int64,h::T) where {T <: Real}
# The state vector has: 1 time; 2-4 position; 5-7 velocity; 8 r0; 9 dr0dt; 10 beta; 11 s; 12 ds
# Initial state:
state0 = zeros(T,12)
# Final state (after a step):
state = zeros(T,12)
delx = zeros(T,NDIM)
delv = zeros(T,NDIM)
#println("Masses: ",i," ",j)
for k=1:NDIM
state0[1+k ] = x[k,i] - x[k,j]
state0[1+k+NDIM] = v[k,i] - v[k,j]
end
gm = GNEWT*(m[i]+m[j])
if gm == 0
for k=1:NDIM
#x[k,i] += h*v[k,i]
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],h*v[k,i])
#x[k,j] += h*v[k,j]
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],h*v[k,j])
end
else
# predicted value of s
kepler_step!(gm, h, state0, state)
for k=1:NDIM
delx[k] = state[1+k] - state0[1+k]
delv[k] = state[1+NDIM+k] - state0[1+NDIM+k]
end
# Advance center of mass:
# Compute COM coords:
mijinv =1.0/(m[i] + m[j])
vcm = zeros(T,NDIM)
for k=1:NDIM
vcm[k] = (m[i]*v[k,i] + m[j]*v[k,j])*mijinv
end
centerm!(m,mijinv,x,v,xerror,verror,vcm,delx,delv,i,j,h)
end
return
end
"""
Advances the center of mass of a binary (any pair of bodies) with compensated summation:
"""
function centerm!(m::Array{T,1},mijinv::T,x::Array{T,2},v::Array{T,2},xerror::Array{T,2},verror::Array{T,2},vcm::Array{T,1},delx::Array{T,1},delv::Array{T,1},i::Int64,j::Int64,h::T) where {T <: Real}
for k=1:NDIM
#x[k,i] += m[j]*mijinv*delx[k] + h*vcm[k]
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],m[j]*mijinv*delx[k])
x[k,i],xerror[k,i] = comp_sum(x[k,i],xerror[k,i],h*vcm[k])
#x[k,j] += -m[i]*mijinv*delx[k] + h*vcm[k]
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],-m[i]*mijinv*delx[k])
x[k,j],xerror[k,j] = comp_sum(x[k,j],xerror[k,j],h*vcm[k])
#v[k,i] += m[j]*mijinv*delv[k]
v[k,i],verror[k,i] = comp_sum(v[k,i],verror[k,i],m[j]*mijinv*delv[k])
#v[k,j] += -m[i]*mijinv*delv[k]
v[k,j],verror[k,j] = comp_sum(v[k,j],verror[k,j],-m[i]*mijinv*delv[k])
end
return
end
"""
Takes a single kepler step, calling Wisdom & Hernandez solver
"""
function kepler_step!(gm::T,h::T,state0::Array{T,1},state::Array{T,1}) where {T <: Real}
# compute beta, r0, get x/v from state vector & call correct subroutine
x0 = zeros(eltype(state0),3)
v0 = zeros(eltype(state0),3)
for k=1:3
x0[k]=state0[k+1]
v0[k]=state0[k+4]
end
# x0=state0[2:4]
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
# v0 = state0[5:7]
beta0 = 2*gm/r0-(v0[1]*v0[1]+v0[2]*v0[2]+v0[3]*v0[3])
s0=state0[11]
iter = kep_ell_hyp!(x0,v0,r0,gm,h,beta0,s0,state)
# if beta0 > zero
# iter = kep_elliptic!(x0,v0,r0,gm,h,beta0,s0,state)
# else
# iter = kep_hyperbolic!(x0,v0,r0,gm,h,beta0,s0,state)
# end
return
end
"""
Solves equation (35) from Wisdom & Hernandez for the elliptic case.
"""
function kep_ell_hyp!(x0::Array{T,1},v0::Array{T,1},r0::T,k::T,h::T,
beta0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Now, solve for s in elliptical Kepler case:
f = zero(T); g=zero(T); dfdt=zero(T); dgdt=zero(T); cx=zero(T);sx=zero(T);g1bs=zero(T);g2bs=zero(T)
s=zero(T); ds = zero(T); r = zero(T);rinv=zero(T); iter=0
if beta0 > zero(T) || beta0 < zero(T)
s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter = solve_kepler!(h,k,x0,v0,beta0,r0,
s0,state)
else
println("Not elliptic or hyperbolic ",beta0," x0 ",x0)
r= zero(T); fill!(state,zero(T)); rinv=zero(T); s=zero(T); ds=zero(T); iter = 0
end
state[8]= r
state[9] = (state[2]*state[5]+state[3]*state[6]+state[4]*state[7])*rinv
# recompute beta:
# beta is element 10 of state:
state[10] = 2.0*k*rinv-(state[5]*state[5]+state[6]*state[6]+state[7]*state[7])
# s is element 11 of state:
state[11] = s
# ds is element 12 of state:
state[12] = ds
return iter
end
"""
Solves elliptic Kepler's equation for both elliptic and hyperbolic cases.
"""
function solve_kepler!(h::T,k::T,x0::Array{T,1},v0::Array{T,1},beta0::T,
r0::T,s0::T,state::Array{T,1}) where {T <: Real}
# Initial guess (if s0 = 0):
r0inv = inv(r0)
beta0inv = inv(beta0)
signb = sign(beta0)
sqb = sqrt(signb*beta0)
zeta = k-r0*beta0
eta = dot(x0,v0)
sguess = 0.0
if s0 == zero(T)
# Use cubic estimate:
if zeta != zero(T)
sguess = cubic1(3eta/zeta,6r0/zeta,-6h/zeta)
else
if eta != zero(T)
reta = r0/eta
disc = reta^2+2h/eta
if disc > zero(T)
sguess =-reta+sqrt(disc)
else
sguess = h*r0inv
end
else
sguess = h*r0inv
end
end
s = copy(sguess)
else
s = copy(s0)
end
s0 = copy(s)
y = zero(T); yp = one(T)
iter = 0
ds = Inf
KEPLER_TOL = sqrt(eps(h))
ITMAX = 20
while iter == 0 || (abs(ds) > KEPLER_TOL && iter < ITMAX)
xx = sqb*s
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
sx *= sqb
# Third derivative:
yppp = zeta*cx - signb*eta*sx
# First derivative:
yp = (-yppp+ k)*beta0inv
# Second derivative:
ypp = signb*zeta*beta0inv*sx + eta*cx
y = (-ypp + eta +k*s)*beta0inv - h # eqn 35
# Now, compute fourth-order estimate:
ds = calc_ds_opt(y,yp,ypp,yppp)
s += ds
iter +=1
end
if iter == ITMAX
println("Reached max iterations in solve_kepler: h ",h," s0: ",s0," s: ",s," ds: ",ds)
end
#println("sguess: ",sguess," s: ",s," s-sguess: ",s-sguess," ds: ",ds," iter: ",iter)
# Since we updated s, need to recompute:
xx = 0.5*sqb*s
if beta0 > 0
sx = sin(xx); cx = cos(xx)
else
cx = cosh(xx); sx = exp(xx)-cx
end
# Now, compute final values:
g1bs = 2.0*sx*cx/sqb
g2bs = 2.0*signb*sx^2*beta0inv
f = one(T) - k*r0inv*g2bs # eqn (25)
g = r0*g1bs + eta*g2bs # eqn (27)
for j=1:3
# Position is components 2-4 of state:
state[1+j] = x0[j]*f+v0[j]*g
end
r = sqrt(state[2]*state[2]+state[3]*state[3]+state[4]*state[4])
rinv = inv(r)
dfdt = -k*g1bs*rinv*r0inv
dgdt = (r0-r0*beta0*g2bs+eta*g1bs)*rinv
for j=1:3
# Velocity is components 5-7 of state:
state[4+j] = x0[j]*dfdt+v0[j]*dgdt
end
return s,f,g,dfdt,dgdt,cx,sx,g1bs,g2bs,r,rinv,ds,iter
end
"""
Computes quartic Newton's update to equation y=0 using first through 3rd derivatives.
Uses techniques outlined in Murray & Dermott for Kepler solver.
"""
function calc_ds_opt(y::T,yp::T,ypp::T,yppp::T) where {T <: Real}
# Rearrange to reduce number of divisions:
num = y*yp
den1 = yp*yp-y*ypp*.5
den12 = den1*den1
den2 = yp*den12-num*.5*(ypp*den1-third*num*yppp)
return -y*den12/den2
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 1658 | abstract type AbstractOutput{T} end
"""
Preallocates and holds arrays for positions, velocities, and Jacobian at every integrator step
"""
# Should add option to choose out intervals, checkpointing, etc.
struct CartesianOutput{T<:AbstractFloat} <: AbstractOutput{T}
states::Vector{State{T}}
nstep::Int64
filename::String
file::Bool
function CartesianOutput(::Type{T},nbody::Int64,nstep::Int64;filename="data.jld2",file=false) where T <: AbstractFloat
states = Array{State,1}(undef,nstep)
return new{T}(states,nstep,filename,file)
end
end
# Allow user to not have to specify type. Defaults to Float64
CartesianOutput(nbody::T,nstep::T;filename="data.jld2") where T<:Int64 = CartesianOutput(Float64,nbody,nstep,filename=filename)
"""
Runs integrator like (*insert doc reference here*) and output positions, velocities, and Jacobian to a JLD2 file.
"""
function (intr::Integrator)(s::State{T},o::CartesianOutput{T}) where T<:AbstractFloat
t0 = s.t[1] # Initial time
time = intr.tmax
nsteps = o.nstep
# Integrate in proper direction
h = intr.h * check_step(t0,time)
tmax = t0 + (h * nsteps)
# Preallocate struct of arrays for derivatives (and pair)
d = Derivatives(T,s.n)
for i in 1:nsteps
# Save State from current step
o.states[i] = deepcopy(s)
# Take integration step and advance time
intr.scheme(s,d,h)
s.t[1] = t0 + (h * i)
end
# Output to jld2 file if desired
if o.file; save(o.filename,Dict("states" => o.states)); end
return
end
# Includes
const outputs = ["elements"]
for i in outputs; include("$(i).jl"); end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 3240 | # Converting cartesian coordinates to orbital elements
"""
A 3d point in cartesian space
"""
struct Point{T<:AbstractFloat}
x::T
y::T
z::T
end
# Constructors
Point(x::AbstractVector) = Point(x...)
Point(x::AbstractMatrix) = [Point(x[:,i]) for i in eachindex(x[1,:])]
Point(x::Real) = Point(float(x),float(x),float(x))
unpack(x::Point) = (x.x,x.y,x.z)
# Overloads for products
LinearAlgebra.dot(x::Point,v::Point) = x.x*v.x + x.y*v.y + x.z*v.z
LinearAlgebra.dot(x::Point) = x.x*x.x + x.y*x.y + x.z*x.z
LinearAlgebra.cross(x::Point,v::Point) = Point(x.y*v.z - x.z*v.y,-(x.x*v.z - x.z*v.x),x.x*v.y - x.y*v.x)
""" Calculate the relative positions from the A-Matrix. """
function get_relative_positions(x,v,ic::InitialConditions)
n = ic.nbody
X = zeros(3,n)
V = zeros(3,n)
X .= permutedims(ic.amat*x')
V .= permutedims(ic.amat*v')
return Point(X), Point(V)
end
""" Get relative masses(*G) from initial conditions. """
function get_relative_masses(ic::InitialConditions)
N = length(ic.m)
M = zeros(N-1)
G = 39.4845/(365.242 * 365.242) # AU^3 Msol^-1 Day^-2
for i in 1:N-1
for j in 1:N
M[i] += abs(ic.ϵ[i,j])*ic.m[j]
end
end
return G .* M
end
# Position and velocity magnitudes
mag(x) = sqrt(dot(x))
mag(x,v) = sqrt(dot(x,v))
Rdotmag(R,V,h) = sqrt(V^2 - (h/R)^2)
function hvec(r,rdot)
hx,hy,hz = unpack(cross(r,rdot))
hz >= 0.0 ? hy *= -1 : hx *= -1
return Point(hx,hy,hz)
end
function calc_Ω(hx,hy,h,I)
sinΩ = hx/(h*sin(I))
cosΩ = hy/(h*sin(I))
return atan(sinΩ,cosΩ)
end
function calc_ω(x,R,Rdot,I,Ω,a,e,h)
# Find ω + f
wpf = 0.0
if I != 0.0
sinwpf = x.z/(R*sin(I))
coswpf = ((x.x/R) + sin(Ω)*sinwpf*cos(I))/cos(Ω)
wpf = atan(sinwpf,coswpf)
end
# Find f
sinf = a*Rdot*(1.0 - e^2)/(h*e)
cosf = (a*(1.0-e^2)/R - 1.0)/e
f = atan(sinf,cosf)
return wpf - f
end
function convert_to_elements(x,v,M)
R = mag(x)
V = mag(v)
h = mag(hvec(x,v))
hx,hy,hz = unpack(hvec(x,v))
Rdot = sign(dot(x,v))*Rdotmag(R,V,h)
Gmm = M
a = 1.0/((2.0/R) - (V*V)/(Gmm))
e = sqrt(1.0 - (h*h/(Gmm*a)))
I = acos(hz/h)
# Make sure Ω is defined
I != 0.0 ? Ω = calc_Ω(hx,hy,h,I) : Ω = 0.0
ω = calc_ω(x,R,Rdot,I,Ω,a,e,h)
P = (2.0*π)*sqrt(a*a*a/Gmm)
n = 2π/P
ecosω, esinω = e.*sincos(ω)
tp = (-sqrt(1.0-e*e)*ecosω/(n*(1.0-esinω)) - (2.0/n)*atan(sqrt(1.0-e)*(esinω+ecosω+e), sqrt(1.0+e)*(esinω-ecosω-e))) % P
return [P,0.0,ecosω,esinω,I,Ω,a,e,ω,tp]
end
function get_orbital_elements(s::State{T},ic::InitialConditions{T}) where T<:AbstractFloat
elems = Elements{T}[]
μ = get_relative_masses(ic)
X,V = get_relative_positions(s.x,s.v,ic)
N = ic.nbody
push!(elems,Elements(m=ic.m[1]))
i = 1; b = 0
while i < N
# Check if new binary
if first(ic.ϵ[i,:]) == zero(T)
b+=1
end
new_elems = convert_to_elements(X[i+b],V[i+b],μ[i+b])
push!(elems,Elements(ic.m[i+1],new_elems...))
# Compensate for new binary in step
if b > 0
b -= 2
elseif b < 0
i += 1
end
i+=1
end
return elems
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 6735 | # Transit structures
abstract type TransitOutput{T} <: AbstractOutput{T} end
"""
TransitTiming{T<:AbstractFloat} <: TransitOutput{T}
Transit times and derivatives.
# (User-facing) Fields
- `tt::Matrix{T}` : The transit times of each body.
- `dtdq0::Array{T,4}` : Derivatives of the transit times with respect to the initial Cartesian coordinates and masses.
- `dtdelements::Array{T,4}` : Derivatives of the transit times with respect to the initial orbital elements and masses.
"""
struct TransitTiming{T<:AbstractFloat} <: TransitOutput{T}
tt::Matrix{T}
dtdq0::Array{T,4}
dtdelements::Array{T,4}
# Internal
count::Vector{Int64}
ntt::Int64
ti::Int64
occs::Vector{Int64}
dtdq::Array{T,3}
gsave::Vector{T}
s_prior::State{T}
s_transit::State{T}
end
"""
TransitTiming(tmax, ic; ti)
Constructor for [`TransitTiming`](@ref) type.
# Arguments
- `tmax::T` : Expected total elapsed integration time. (Allocates arrays accordingly)
- `ic::ElementsIC{T}` : Initial conditions for the system
## Optional
- `ti::Int64=1` : Index of the body with respect to which transits are measured. (Default is the central body)
"""
function TransitTiming(tmax::T,ic::ElementsIC{T},ti::Int64=1) where T<:AbstractFloat
n = ic.nbody
ind = isfinite.(tmax./ic.elements[:,2])
ntt = maximum(ceil.(Int64,abs.(tmax./ic.elements[ind,2])).+3)
tt = zeros(T,n,ntt)
dtdq0 = zeros(T,n,ntt,7,n)
dtdelements = zeros(T,n,ntt,7,n)
count = zeros(Int64,n)
occs = setdiff(collect(1:n),ti)
dtdq = zeros(T,1,7,n)
gsave = zeros(T,n)
s_prior = State(ic)
s_transit = State(ic)
return TransitTiming(tt,dtdq0,dtdelements,count,ntt,ti,occs,dtdq,gsave,s_prior,s_transit)
end
"""
TransitParameters{T<:AbstractFloat} <: TransitOutput{T}
Transit times, impact parameters, sky-velocities, and derivatives.
# (User-facing) Fields
- `ttbv::Matrix{T}` : The transit times, impact parameter, and sky-velocity of each body.
- `dtbvdq0::Array{T,5}` : Derivatives of the transit times, impact parameters, and sky-velocities with respect to the initial Cartesian coordinates and masses.
- `dtbvdelements::Array{T,5}` : Derivatives of the transit times, impact parameters, and sky-velocities with respect to the initial orbital elements and masses.
"""
struct TransitParameters{T<:AbstractFloat} <: TransitOutput{T}
ttbv::Array{T,3}
dtbvdq0::Array{T,5}
dtbvdelements::Array{T,5}
# Internal
count::Vector{Int64}
ntt::Int64
ti::Int64
occs::Vector{Int64}
dtbvdq::Array{T,3}
gsave::Vector{T}
s_prior::State{T}
s_transit::State{T}
end
"""
TransitParameters(tmax, ic; ti)
Constructor for [`TransitParameters`](@ref) type.
# Arguments
- `tmax::T` : Expected total elapsed integration time. (Allocates arrays accordingly)
- `ic::ElementsIC{T}` : Initial conditions for the system
## Optional
- `ti::Int64=1` : Index of the body with respect to which transits are measured. (Default is the central body)
"""
function TransitParameters(tmax::T,ic::ElementsIC{T},ti::Int64=1) where T<:AbstractFloat
n = ic.nbody
ind = isfinite.(tmax./ic.elements[:,2])
ntt = maximum(ceil.(Int64,abs.(tmax./ic.elements[ind,2])).+3)
ttbv = zeros(T,3,n,ntt)
dtbvdq0 = zeros(T,3,n,ntt,7,n)
dtbvdelements = zeros(T,3,n,ntt,7,n)
count = zeros(Int64,n)
occs = setdiff(collect(1:n),ti)
dtbvdq = zeros(T,3,7,n)
gsave = zeros(T,n)
s_prior = State(ic)
s_transit = State(ic)
return TransitParameters(ttbv,dtbvdq0,dtbvdelements,count,ntt,ti,occs,dtbvdq,gsave,s_prior,s_transit)
end
struct TransitSnapshot{T<:AbstractFloat} <: TransitOutput{T}
nt::Int64
times::Vector{T}
bsky2::Matrix{T}
vsky::Matrix{T}
dbvdq0::Array{T,5}
dbvdelements::Array{T,5}
end
function TransitSnapshot(times::Vector{T},ic::ElementsIC{T}) where T<:AbstractFloat
n = ic.nbody
nt = length(times)
return TransitSeries(nt,times,zeros(T,n,nt),zeros(T,n,nt),zeros(T,2,n,nt,7,n),zeros(T,2,n,nt,7,n))
end
function zero_out!(tt::TransitOutput{T}) where T
for i in 1:length(fieldnames(typeof(tt)))
if typeof(getfield(tt,i)) <: Array{T}
getfield(tt,i) .= zero(T)
end
end
tt.count .= 0
end
"""
Main integrator method for Transit calculations.
"""
function (intr::Integrator)(s::State{T}, tt::TransitOutput{T}, d::Derivatives{T}; grad::Bool=true) where T<:AbstractFloat
t0 = s.t[1] # Initial time
nsteps = abs(round(Int64,intr.tmax/intr.h))
h = intr.h * check_step(t0, intr.tmax+t0) # get direction of integration
for i in tt.occs
# Compute the relative sky velocity dotted with position:
tt.gsave[i] = g!(i,tt.ti,s.x,s.v)
end
istep = 0
for _ in 1:nsteps
# Take an integration step
if grad
intr.scheme(s,d,h)
else
intr.scheme(s,h)
end
istep += 1
s.t[1] = t0 + (istep * h)
# Check if a transit occured; record time.
detect_transits!(s,d,tt,intr,grad=grad)
end
# Calculate derivatives
if grad
calc_dtdelements!(s,tt)
end
end
"""Wrapper so the user doesn't need to create a `Derivatives` type."""
function (intr::Integrator)(s::State{T}, tt::TransitOutput{T}; grad::Bool=true, return_arrays::Bool=false) where T<:AbstractFloat
# Preallocate arrays
d = Derivatives(T, s.n)
intr(s, tt, d, grad=grad)
if return_arrays; return d; end # Return preallocated arrays
return
end
"""
Integrator method for outputting `TransitSnapshot`.
"""
function (intr::Integrator)(s::State{T},ts::TransitSnapshot{T};grad::Bool=true) where T<:AbstractFloat
# Integrate to, and output b and v_sky for each body, for a list of times.
# Should be sorted times.
# NOTE: Need to fix so that if initial time is a 0, s.dqdt isn't 0s.
if grad; dbvdq = zeros(T,2,7,s.n); end
# Integrate to each time, using intr.h, and output b and vsky (only want primary transits for now)
t0 = s.t[1]
for (j,ti) in enumerate(ts.times)
intr(s,ti;grad=grad)
for i in 2:s.n
if grad
ts.vsky[i,j],ts.bsky2[i,j] = calc_dbvdq!(s,dbvdq,1,i)
for ibv=1:2, k=1:7, p=1:s.n
ts.dbvdq0[ibv,i,j,k,p] = dbvdq[ibv,k,p]
end
else
ts.vsky[i,j],ts.bsky2[i,j] = calc_bv(s,1,i)
end
end
# Step to the next full time step, as measured from t0.
#steps = round(Int64 ,(s.t[1] - t0) / intr.h, RoundUp)
#intr(s,t0 + (steps * intr.h); grad=grad)
end
calc_dbvdelements!(s,ts)
return
end
# Includes for source
files = ["timing.jl","snapshot.jl"]
include.(files) | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 2377 | # Collection of functions to calculate impact parameter and sky velocity
"""
Calculate impact parameter and sky velocity
"""
function calc_bv(s::State{T},i::Int64,j::Int64) where T<:AbstractFloat
vsky = sqrt((s.v[1,j]-s.v[1,i])^2 + (s.v[2,j]-s.v[2,i])^2)
bsky2 = (s.x[1,j]-s.x[1,i])^2 + (s.x[2,j]-s.x[2,i])^2
return vsky,bsky2
end
"""
Calculate derivative of impact parameter and sky velocity wrt cartesian coordinates
"""
function calc_dbvdq!(s::State{T},dbvdq::Array{T},i::Int64,j::Int64) where T<:AbstractFloat
vsky,bsky2 = calc_bv(s,i,j)
gsky = g!(i,j,s.x,s.v)
gdot = gd!(i,j,s.x,s.v,s.dqdt)
fill!(dbvdq,zero(T))
# partial derivative b and v_{sky} with respect to time:
dvdt = ((s.v[1,j]-s.v[1,i])*(s.dqdt[(j-1)*7+4]-s.dqdt[(i-1)*7+4])+(s.v[2,j]-s.v[2,i])*(s.dqdt[(j-1)*7+5]-s.dqdt[(i-1)*7+5]))/vsky
dbdt = 2.0 * gsky
# Compute derivatives:
indj = (j-1)*7+1
indi = (i-1)*7+1
for p=1:s.n
indp = (p-1)*7
for k=1:7
dtdq = -((s.jac_step[indj ,indp+k]-s.jac_step[indi ,indp+k])*(s.v[1,j]-s.v[1,i])+(s.jac_step[indj+1,indp+k]-s.jac_step[indi+1,indp+k])*(s.v[2,j]-s.v[2,i])+
(s.jac_step[indj+3,indp+k]-s.jac_step[indi+3,indp+k])*(s.x[1,j]-s.x[1,i])+(s.jac_step[indj+4,indp+k]-s.jac_step[indi+4,indp+k])*(s.x[2,j]-s.x[2,i]))/gdot
#v_{sky} = sqrt((v[1,j]-v[1,i])^2+(v[2,j]-v[2,i])^2)
dbvdq[1,k,p] = ((s.jac_step[indj+3,indp+k]-s.jac_step[indi+3,indp+k])*(s.v[1,j]-s.v[1,i])+(s.jac_step[indj+4,indp+k]-s.jac_step[indi+4,indp+k])*(s.v[2,j]-s.v[2,i]))/vsky + dvdt*dtdq
#b_{sky}^2 = (x[1,j]-x[1,i])^2+(x[2,j]-x[2,i])^2
dbvdq[2,k,p] = 2*((s.jac_step[indj ,indp+k]-s.jac_step[indi ,indp+k])*(s.x[1,j]-s.x[1,i])+(s.jac_step[indj+1,indp+k]-s.jac_step[indi+1,indp+k])*(s.x[2,j]-s.x[2,i])) + dbdt*dtdq
end
end
return vsky,bsky2
end
function calc_dbvdelements!(s::State{T},ts::TransitSnapshot{T}) where T <: AbstractFloat
for ibv = 1:2, i=1:s.n, j=1:ts.nt
# Now, multiply by the initial Jacobian to convert time derivatives to orbital elements:
for k=1:s.n, l=1:7
ts.dbvdelements[ibv,i,j,l,k] = zero(T)
for p=1:s.n, q=1:7
ts.dbvdelements[ibv,i,j,l,k] += ts.dbvdq0[ibv,i,j,q,p]*s.jac_init[(p-1)*7+q,(k-1)*7+l]
end
end
end
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 7987 | # Collection of functions to compute transit times, impact parameters, sky-velocity, and derivatives.
function detect_transits!(s::State{T},d::Derivatives{T},tt::TransitOutput{T},intr::Integrator{T}; grad::Bool=true) where T<:AbstractFloat
rstar::T = 1e12 # Could this be removed?
# Save current state as prior state
set_state!(tt.s_prior, s)
# Check to see if a transit may have occured before current state.
# Sky is x-y plane; line of sight is z.
# Body being transited is tt.ti, tt.occs is list of occultors:
for i in tt.occs
# Compute the relative sky velocity dotted with position:
gi = g!(i,tt.ti,s.x,s.v)
ri = sqrt(s.x[1,i]^2+s.x[2,i]^2+s.x[3,i]^2) # orbital distance
# See if sign of g switches, and if planet is in front of star (by a good amount):
if gi > 0 && tt.gsave[i] < 0 && -s.x[3,i] > 0.25*ri && ri < rstar
# A transit has occurred between the time steps - integrate ahl21!
tt.count[i] += 1
if tt.count[i] <= tt.ntt
dt0 = -gi*intr.h/(gi-tt.gsave[i]) # Starting estimate
set_state!(s,tt.s_prior)
findtransit!(tt.ti,i,dt0,s,d,tt,intr;grad=grad) # Search for transit time (integrating 'backward')
end
end
tt.gsave[i] = gi
set_state!(s,tt.s_prior)
end
return
end
function findtransit!(i::Int64,j::Int64,dt0::T,s::State{T},d::Derivatives{T},tt::TransitOutput{T},intr::Integrator;grad::Bool=true) where T<:AbstractFloat
# Computes the transit time approximating the motion as a fraction of a AHL21 step backward in time.
# Computes the impact parameter and sky-velocity, if passed a TransitParameters.
# Also computes the Jacobian of the transit time with respect to the initial parameters, dtbvdq[1-3,7,n].
# Initial guess using linear interpolation:
s.dqdt .= 0.0
#set_state!(tt.s_transit,s)
dt = one(T)
iter = 0
r3 = zero(T)
gdot = zero(T)
gsky = zero(T)
stmp = zero(T)
TRANSIT_TOL = 10*eps(dt)
tt1 = dt0 + 1
tt2 = dt0 + 2
ITMAX = 20
#while abs(dt) > TRANSIT_TOL && iter < 20
while true
tt2 = tt1
tt1 = dt0
set_state!(s,tt.s_prior)
# Advance planet state at start of step to estimated transit time:
zero_out!(d)
intr.scheme(s,d,dt0)
# Compute time offset:
gsky = g!(i,j,s.x,s.v)
# # Compute derivative of g with respect to time:
gdot = gd!(i,j,s.x,s.v,s.dqdt)
# Refine estimate of transit time with Newton's method:
dt = -gsky/gdot
# Add refinement to estimated time:
#dt0 += dt
dt0,stmp = comp_sum(dt0,stmp,dt)
iter += 1
# Break out if we have reached maximum iterations, or if
# current transit time estimate equals one of the prior two steps:
if (iter >= ITMAX) || (dt0 == tt1) || (dt0 == tt2)
break
end
end
if grad
# Compute derivatives with updated time step
set_state!(s,tt.s_prior)
zero_out!(d)
intr.scheme(s,d,dt0)
end
if tt isa TransitParameters
# Compute the impact parameter and sky velocity, save to tt along with transit time.
tt.ttbv[1,j,tt.count[j]] = s.t[1] + dt0
if grad
# Compute derivative of transit time, impact parameter, and sky velocity.
vsky,bsky2 = dtbvdq!(i,j,s.x,s.v,s.jac_step,s.dqdt,tt.dtbvdq)
tt.ttbv[2,j,tt.count[j]] = vsky
tt.ttbv[3,j,tt.count[j]] = bsky2
for itbv=1:3, k=1:7, p=1:s.n
tt.dtbvdq0[itbv,j,tt.count[j],k,p] = tt.dtbvdq[itbv,k,p]
end
return
end
tt.ttbv[2,j,tt.count[j]] = calc_vsky(s.v,i,j)
tt.ttbv[3,j,tt.count[j]] = calc_bsky2(s.x,i,j)
return
end
tt.tt[j,tt.count[j]] = s.t[1] + dt0
if grad
# Compute derivative of transit time
dtbvdq!(i,j,s.x,s.v,s.jac_step,s.dqdt,tt.dtdq)
for k=1:7, p=1:s.n
tt.dtdq0[j,tt.count[j],k,p] = tt.dtdq[1,k,p]
end
end
return
end
function calc_dtdelements!(s::State{T},tt::TransitTiming{T}) where T <: AbstractFloat
for i=1:s.n, j=1:tt.count[i]
if j <= tt.ntt
# Now, multiply by the initial Jacobian to convert time derivatives to orbital elements:
for k=1:s.n, l=1:7
tt.dtdelements[i,j,l,k] = zero(T)
for p=1:s.n, q=1:7
tt.dtdelements[i,j,l,k] += tt.dtdq0[i,j,q,p]*s.jac_init[(p-1)*7+q,(k-1)*7+l]
end
end
end
end
end
function calc_dtdelements!(s::State{T},ttbv::TransitParameters{T}) where T <: AbstractFloat
for itbv = 1:3, i=1:s.n, j = 1:ttbv.count[i]
if j <= ttbv.ntt
# Now, multiply by the initial Jacobian to convert time derivatives to orbital elements:
for k=1:s.n, l=1:7
ttbv.dtbvdelements[itbv,i,j,l,k] = zero(T)
for p=1:s.n, q=1:7
ttbv.dtbvdelements[itbv,i,j,l,k] += ttbv.dtbvdq0[itbv,i,j,q,p]*s.jac_init[(p-1)*7+q,(k-1)*7+l]
end
end
end
end
end
"""Used in computing transit time inside `findtransit3`."""
function g!(i::Int64,j::Int64,x::Array{T,2},v::Array{T,2}) where {T <: Real}
# See equation 8-10 Fabrycky (2008) in Seager Exoplanets book
g = (x[1,j]-x[1,i])*(v[1,j]-v[1,i])+(x[2,j]-x[2,i])*(v[2,j]-v[2,i])
return g
end
function gd!(i::Int64,j::Int64,x::Matrix{T},v::Matrix{T},dqdt::Array{T}) where T<:AbstractFloat
return ((x[1,j]-x[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(x[2,j]-x[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5])
+(v[1,j]-v[1,i])*(dqdt[(j-1)*7+1]-dqdt[(i-1)*7+1])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+2]-dqdt[(i-1)*7+2]))
end
calc_bsky2(x::Matrix{T},i::Int64,j::Int64) where T<:AbstractFloat = (x[1,j]-x[1,i])^2 + (x[2,j]-x[2,i])^2
calc_vsky(v::Matrix{T},i::Int64,j::Int64) where T<:AbstractFloat = sqrt((v[1,j]-v[1,i])^2 + (v[2,j]-v[2,i])^2)
function dtbvdq!(i::Int64,j::Int64,x::Matrix{T},v::Matrix{T},jac_step::Matrix{T},dqdt::Vector{T},dtbvdq::Array{T}) where T<:AbstractFloat
n = size(x)[2]
# Compute time offset:
gsky = g!(i,j,x,v)
# Compute derivative of g with respect to time:
gdot = gd!(i,j,x,v,dqdt)
fill!(dtbvdq,zero(typeof(x[1])))
indj = (j-1)*7+1
indi = (i-1)*7+1
for p=1:n
indp = (p-1)*7
for k=1:7
# Compute derivatives:
dtbvdq[1,k,p] = -((jac_step[indj ,indp+k]-jac_step[indi ,indp+k])*(v[1,j]-v[1,i])+(jac_step[indj+1,indp+k]-jac_step[indi+1,indp+k])*(v[2,j]-v[2,i])+
(jac_step[indj+3,indp+k]-jac_step[indi+3,indp+k])*(x[1,j]-x[1,i])+(jac_step[indj+4,indp+k]-jac_step[indi+4,indp+k])*(x[2,j]-x[2,i]))/gdot
end
end
ntbv = size(dtbvdq)[1]
if ntbv == 3
# Compute the impact parameter and sky velocity:
vsky = calc_vsky(v,i,j)
bsky2 = calc_bsky2(x,i,j)
# partial derivative v_{sky} with respect to time:
dvdt = ((v[1,j]-v[1,i])*(dqdt[(j-1)*7+4]-dqdt[(i-1)*7+4])+(v[2,j]-v[2,i])*(dqdt[(j-1)*7+5]-dqdt[(i-1)*7+5]))/vsky
# (note that \partial b/\partial t = 0 at mid-transit since g_{sky} = 0 mid-transit).
for p=1:n
indp = (p-1)*7
for k=1:7
# Compute derivatives:
#v_{sky} = sqrt((v[1,j]-v[1,i])^2+(v[2,j]-v[2,i])^2)
dtbvdq[2,k,p] = ((jac_step[indj+3,indp+k]-jac_step[indi+3,indp+k])*(v[1,j]-v[1,i])+(jac_step[indj+4,indp+k]-jac_step[indi+4,indp+k])*(v[2,j]-v[2,i]))/vsky + dvdt*dtbvdq[1,k,p]
#b_{sky}^2 = (x[1,j]-x[1,i])^2+(x[2,j]-x[2,i])^2
dtbvdq[3,k,p] = 2*((jac_step[indj ,indp+k]-jac_step[indi ,indp+k])*(x[1,j]-x[1,i])+(jac_step[indj+1,indp+k]-jac_step[indi+1,indp+k])*(x[2,j]-x[2,i]))
end
end
return vsky,bsky2
end
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 308 | # Replacement for deprecated functions:
function linearspace(a,b,n)
if VERSION >= v"0.7"
return range(a,stop=b,length=n)
else
return linspace(a,b,n)
end
return
end
function logarithmspace(a,b,n)
if VERSION >= v"0.7"
return 10.0 .^range(a,stop=b,length=n)
else
return logspace(a,b,n)
end
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 1179 | using NbodyGradient
import NbodyGradient: kepler_init, init_nbody
maxabs(x) = maximum(abs.(x))
# For backwards compatability
include("loglinspace.jl")
if VERSION >= v"0.7"
using Test
using LinearAlgebra
using Statistics
using DelimitedFiles
else
using Base.Test
end
@testset "NbodyGradient" begin
print("Initial Conditions... ")
@testset "Initial Conditions" begin
include("test_kepler_init.jl")
include("test_init_nbody.jl")
include("test_initial_conditions.jl")
end;
println("Finished.")
print("Integrator... ")
@testset "Integrator" begin
include("test_kickfast.jl")
include("test_phic.jl")
include("test_kepler_driftij_gamma.jl")
include("test_phisalpha.jl")
include("test_integrator.jl")
end;
println("Finished.")
print("Outputs... ")
@testset "Outputs" begin
include("test_cartesian_to_elements.jl")
end
println("Finished.")
print("TTVs... ")
@testset "TTVs" begin
include("test_findtransit.jl")
include("test_transit_timing.jl")
include("test_transit_parameters.jl")
end;
println("Finished.")
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 889 | import NbodyGradient: get_orbital_elements
function Base.isapprox(a::Elements,b::Elements;tol=1e-10)
fields = setdiff(fieldnames(Elements),[:a,:e,:ϖ])
for i in fields
af = getfield(a,i)
bf = getfield(b,i)
if abs(af - bf) > tol
return false
end
end
return true
end
@testset "Cartesian to Elements" begin
# Get known Elements
fname = "elements.txt"
t0 = 7257.93115525-7300.0
H = [4,1,1,1]
ic = ElementsIC(t0,H,fname)
a = Elements(ic.elements[1,:]...)
b = Elements(ic.elements[2,:]...)
c = Elements(ic.elements[3,:]...)
d = Elements(ic.elements[4,:]...)
system = [a,b,c,d]
# Convert to Cartesian coordinates
s = State(ic)
# Convert back to elements
elems = get_orbital_elements(s,ic)
for i in eachindex(system)
@test isapprox(elems[1],system[1])
end
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 662 | @testset "Timing Accuracy" begin
n = 7
t0 = 7257.0
h = 0.01
tmax = 10.0
intr = Integrator(ahl21!,h,t0,tmax)
# Read in initial conditions:
H = [n,ones(Int64, n - 1)...]
elements = readdlm("elements.txt", ',')[1:n,:]
ic = ElementsIC(t0,H,elements)
s = State(ic)
# Holds transit times, derivatives, etc.
tt = TransitTiming(tmax,ic);
# Run integrator and calculate times
intr(s,tt,grad=false)
# Check that we get back the initial transit time (up to tolerance)
tol = 1e-6 # Percent error
for i in 1:n-1
@test abs((ic.elements[i+1,3] - tt.tt[i+1,1])/ic.elements[i+1,3]) < tol
end
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 3892 | import NbodyGradient: init_nbody
@testset "init_nbody" begin
elements = "elements.txt"
H = [3,1,1]
t0 = 7257.93115525 - 7300.0
init = ElementsIC(t0, H, elements)
init.elements[:,3] .-= 7300.0
x, v, jac_init = init_nbody(init)
elements_big = big.(init.elements)
t0big = big(t0)
init_big = ElementsIC(t0big, H, elements_big)
xbig, vbig, jac_init_big = init_nbody(init_big)
# elements = readdlm("elements.txt",',')
# elements[2:3,1] /= 100.0
# n_body = 4
n_body = 3
# jac_init = zeros(Float64,7*n_body,7*n_body)
# jac_init_big = zeros(BigFloat,7*n_body,7*n_body)
jac_init_num = zeros(BigFloat, 7 * n_body, 7 * n_body)
# x,v = init_nbody(elements,t0,n_body,jac_init)
# elements_big = big.(elements)
# t0big = big(t0)
# xbig,vbig = init_nbody(elements_big,t0big,n_body,jac_init_big)
elements0 = copy(init.elements)
# dq = big.([1e-10,1e-5,1e-6,1e-6,1e-6,1e-5,1e-5])
# dq = big.([1e-10,1e-8,1e-8,1e-8,1e-8,1e-8,1e-8])
dq = big.([1e-12,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10])
# dq = big.([1e-15,1e-15,1e-15,1e-15,1e-15,1e-15,1e-15])
# t0big = big(t0)
# Now, compute derivatives numerically:
for j = 1:n_body
for k = 1:7
elementsbig = big.(elements0)
dq0 = dq[k]; if j == 1 && k == 1 ; dq0 = big(1e-15); end
elementsbig[j,k] += dq0
initp = ElementsIC(t0big, H, elementsbig)
xp, vp, _ = init_nbody(initp)
elementsbig[j,k] -= 2dq0
initm = ElementsIC(t0big, H, elementsbig)
xm, vm, _ = init_nbody(initm)
for l in 1:n_body, p in 1:3
i1 = (l - 1) * 7 + p
if k == 1
j1 = j * 7
else
j1 = (j - 1) * 7 + k - 1
end
jac_init_num[i1, j1] = (xp[p,l] - xm[p,l]) / dq0 * .5
jac1 = jac_init[i1,j1]; jac2 = jac_init_num[i1,j1]
# if abs(jac1-jac2) > 1e-4*abs(jac1+jac2) && abs(jac1+jac2) > 1e-14
# println(l," ",p," ",j," ",k," ",jac_init_num[i1,j1]," ",jac_init[i1,j1]," ",jac_init_num[i1,j1]/jac_init[i1,j1])
# end
jac_init_num[i1 + 3,j1] = (vp[p,l] - vm[p,l]) / dq0 * .5
jac1 = jac_init[i1 + 3,j1]; jac2 = jac_init_num[i1 + 3,j1]
# if abs(jac1-jac2) > 1e-4*abs(jac1+jac2) && abs(jac1+jac2) > 1e-14
# println(l," ",p+3," ",j," ",k," ",jac_init_num[i1+3,j1]," ",jac_init[i1+3,j1]," ",jac_init_num[i1+3,j1]/jac_init[i1+3,j1])
# end
end
end
jac_init_num[j * 7,j * 7] = 1.0
end
# println("Maximum jac_init-jac_init_num: ",maximum(abs.(jac_init-jac_init_num)))
# println("Maximum jac_init-jac_init_num: ",maximum(abs.(asinh.(jac_init)-asinh.(jac_init_num))))
# println("Maximum jac_init-jac_init_big: ",maximum(abs.(asinh.(jac_init)-asinh.(jac_init_big))))
# println("Maximum jac_init/jac_init_big-1: ",maximum(abs.(jac_init[jac_init_big .!= 0.0]./jac_init_big[jac_init_big .!= 0.0].-1)))
# println("Maximum jac_init_big-jac_init_num: ",maximum(abs.(asinh.(jac_init_num)-asinh.(jac_init_big))))
# println(convert(Array{Float64,2},jac_init_big-jac_init_num))
# @test isapprox(jac_init_num,jac_init)
@test isapprox(jac_init_num, jac_init;norm=maxabs)
@test isapprox(jac_init, convert(Array{Float64,2}, jac_init_big);norm=maxabs)
# end
for i in 1:21, j in 1:21
if jac_init_big[i,j] != 0.0
dij = abs(jac_init[i,j] / jac_init_big[i,j] - 1)
if dij > 1e-12
jac_max = dij
println(i, " ", j, " ", convert(Float64, jac_max), " ", jac_init[i,j], " ", convert(Float64, jac_init_big[i,j]), " ", convert(Float64, jac_init[i,j] - jac_init_big[i,j]))
end
end
end
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4757 | # Make sure that each IC specification method yields the same orbital elements
# or Cartesian coordinates.
using DelimitedFiles
function compare_ics(ic1::T, ic2::T) where T<:InitialConditions
# Compare the fields of the structs (https://stackoverflow.com/questions/62336686/struct-equality-with-arrays)
fns = fieldnames(T)
f1 = getfield.(Ref(ic1), fns)
f2 = getfield.(Ref(ic2), fns)
return f1 == f2
end
function get_elements_ic_array(t0, H, N)
fname = "elements.txt"
elements = readdlm(fname, ',', comments=true)
ic = ElementsIC(t0, H, elements)
return ic
end
function get_elements_ic_file(t0, H, N)
fname = "elements.txt"
ic = ElementsIC(t0, H, fname)
return ic
end
function get_elements_ic_elems(t0, H, N)
fname = "elements.txt"
elements = readdlm(fname, ',', comments=true)
elems = Elements{Float64}[]
for i in 1:N
push!(elems, Elements(elements[i,:]..., zeros(4)...))
end
ic = ElementsIC(t0, H, elems)
return ic
end
function get_cartesian_ic_file(t0, N)
fname = "coordinates.txt"
ic = CartesianIC(t0, N, fname)
return ic
end
function get_cartesian_ic_array(t0, N)
fname = "coordinates.txt"
coords = readdlm(fname, ',', comments=true)
ic = CartesianIC(t0, N, coords)
return ic
end
# Run tests for given H type (int, vector, matrix)
@generated function run_elements_tests(t0, H, N)
inputs = ["file", "array", "elems"]
funcs = [Symbol("get_elements_ic_$(i)") for i in inputs]
ics = [Symbol("ic_$(i)") for i in inputs]
# Get ICs for each method
setup = Vector{Expr}()
for (ic, f) in zip(ics, funcs)
ex = :($ic = $f(t0, H, N))
push!(setup, ex)
end
# Compare outputs of each method
tests = Vector{Expr}()
for ic in ics
ex = :(@test compare_ics($(ics[1]), $ic))
push!(tests, ex)
end
return Expr(:block, setup..., tests...)
end
function run_elements_H_tests(t0, n)
H_vec = [n, ones(Int64, n - 1)...]
H_mat = NbodyGradient.hierarchy(H_vec)
ic_n = get_elements_ic_file(t0, n, n)
ic_vec = get_elements_ic_file(t0, H_vec, n)
ic_mat = get_elements_ic_file(t0, H_mat, n)
@test compare_ics(ic_n, ic_vec)
@test compare_ics(ic_n, ic_mat)
return
end
# Run tests for given H type (int, vector)
@generated function run_cartesian_tests(t0, H)
inputs = ["file", "array"]
funcs = [Symbol("get_cartesian_ic_$(i)") for i in inputs]
ics = [Symbol("ic_$(i)") for i in inputs]
# Get ICs for each method
setup = Vector{Expr}()
for (ic, f) in zip(ics, funcs)
ex = :($ic = $f(t0, H))
push!(setup, ex)
end
# Compare the outputs of each method
tests = Vector{Expr}()
fields = [:x, :v, :m]
for ic1 in ics, ic2 in ics, f in fields
ex = :(@test $ic1.$f == $ic2.$f)
push!(tests, ex)
end
return Expr(:block, setup..., tests...)
end
function test_default_trappist()
# Check that default ics match those produced by the test file
fname = "elements.txt"
t0 = 0.0
for n in 2:8
ic_file = ElementsIC(t0, n, fname)
ic_default = get_default_ICs("trappist-1", t0, n)
@test compare_ics(ic_file, ic_default)
end
# Check that each input string works correctly
sysnames = NbodyGradient._available_systems()[1]
ic_true = ElementsIC(t0, 7, fname)
for sn in sysnames
@test compare_ics(ic_true, get_default_ICs(sn, t0, 7))
end
end
@testset "Initial Conditions" begin
@testset "Elements" begin
N = 8
t0 = 7257.93115525 - 7300.0
for n in 2:N
H_vec = [n,ones(Int64, n - 1)...]
H_mat = NbodyGradient.hierarchy(H_vec)
# Test each specification method with static hierarchy
run_elements_tests(t0, H_mat, n)
run_elements_tests(t0, H_vec, n) # Test hierarchy vector specification
run_elements_tests(t0, n, n) # Test number-of-bodies specification
# Now test each hierarchy method with file method
run_elements_H_tests(t0, n)
end
end
@testset "Cartesian" begin
N = 8
t0 = 7257.93115525 - 7300.0
for n in 2:N
run_cartesian_tests(t0, n)
end
end
@testset "Defaults" begin
test_default_trappist()
end
@testset "Deprecated" begin
el = Elements(m=1.0, P=1.0)
@test_logs (:warn, "ecosϖ (\\varpi) will be removed, use ecosω (\\omega).") Base.getproperty(el, :ecosϖ)
@test_logs (:warn, "esinϖ (\\varpi) will be removed, use esinω (\\omega).") Base.getproperty(el, :esinϖ)
@test_logs (:warn, "ϖ (\\varpi) will be removed, use ω (\\omega).") Base.getproperty(el, :ϖ)
end
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 5520 | # Test for the integrator methods, without outputs.
@testset "Integrator" begin
###### Float64 ######
# Initial Conditions for Float64 version
H = [3,1,1]
n = 3
t0 = 7257.93115525
elements = readdlm("elements.txt", ',')
# Increase mass of inner planets:
elements[2,1] *= 100.0
elements[3,1] *= 100.0
# Set Ωs to 0.0
elements[:,end] .= 0.0
# Generate ICs
ic = ElementsIC(t0, H, elements[1:n,:])
# Setup State and tilt orbits
function perturb!(s::State{<:AbstractFloat})
s.x[2,1] = 5e-1 * sqrt(s.x[1,1]^2 + s.x[3,1]^2)
s.x[2,2] = -5e-1 * sqrt(s.x[1,2]^2 + s.x[3,2]^2)
s.x[2,3] = -5e-1 * sqrt(s.x[1,2]^2 + s.x[3,2]^2)
s.v[2,1] = 5e-1 * sqrt(s.v[1,1]^2 + s.v[3,1]^2)
s.v[2,2] = -5e-1 * sqrt(s.v[1,2]^2 + s.v[3,2]^2)
s.v[2,3] = -5e-1 * sqrt(s.v[1,2]^2 + s.v[3,2]^2)
return
end
s0 = State(ic)
perturb!(s0)
# Setup integrator
h = 0.05
nstep = 100
tmax = nstep * h
AHL21 = Integrator(ahl21!, h, t0, tmax)
# Integrate
AHL21(s0)
####################
##### BigFloat #####
t0_big = big(t0)
elements_big = big.(elements)
ic_big = ElementsIC(t0_big, H, elements_big)
s_big = State(ic_big)
perturb!(s_big)
h_big = big(h)
tmax_big = nstep * h_big
AHL21_big = Integrator(ahl21!, h_big, t0_big, tmax_big)
AHL21_big(s_big, grad=false)
####################
## Numerical Derivatives ##
# Vary the initial parameters of planet j:
n = 3
dlnq = big(1e-20)
jac_step_num = zeros(BigFloat, 7 * n, 7 * n)
for j = 1:n
# Vary the initial phase-space elements:
for jj = 1:3
# Position derivatives:
sm = deepcopy(State(ic_big))
perturb!(sm)
dq = dlnq * sm.x[jj,j]
if sm.x[jj,j] != 0.0
sm.x[jj,j] -= dq
else
dq = dlnq
sm.x[jj,j] = -dq
end
AHL21_big(sm, grad=false)
sp = deepcopy(State(ic_big))
perturb!(sp)
dq = dlnq * sp.x[jj,j]
if sp.x[jj,j] != 0.0
sp.x[jj,j] += dq
else
dq = dlnq
sp.x[jj,j] = dq
end
AHL21_big(sp, grad=false)
# Now x & v are final positions & velocities after time step
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,(j - 1) * 7 + jj] = .5 * (sp.x[k,i] - sm.x[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,(j - 1) * 7 + jj] = .5 * (sp.v[k,i] - sm.v[k,i]) / dq
end
end
# Next, velocity derivatives:
sm = deepcopy(State(ic_big))
perturb!(sm)
dq = dlnq * sm.v[jj,j]
if sm.v[jj,j] != 0.0
sm.v[jj,j] -= dq
else
dq = dlnq
sm.v[jj,j] = -dq
end
AHL21_big(sm, grad=false)
sp = deepcopy(State(ic_big))
perturb!(sp)
dq = dlnq * sp.v[jj,j]
if sp.v[jj,j] != 0.0
sp.v[jj,j] += dq
else
dq = dlnq
sp.v[jj,j] = dq
end
AHL21_big(sp;grad=false)
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,(j - 1) * 7 + 3 + jj] = .5 * (sp.x[k,i] - sm.x[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,(j - 1) * 7 + 3 + jj] = .5 * (sp.v[k,i] - sm.v[k,i]) / dq
end
end
end
# Now vary mass of planet:
sm = deepcopy(State(ic_big))
perturb!(sm)
dq = sm.m[j] * dlnq
sm.m[j] -= dq
AHL21_big(sm;grad=false)
sp = deepcopy(State(ic_big))
perturb!(sp)
dq = sp.m[j] * dlnq
sp.m[j] += dq
AHL21_big(sp;grad=false)
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,j * 7] = .5 * (sp.x[k,i] - sm.x[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,j * 7] = .5 * (sp.v[k,i] - sm.v[k,i]) / dq
end
end
# Mass unchanged -> identity
jac_step_num[j * 7,j * 7] = 1.0
end
# dqdt
s_dt = State(ic)
AHL21(s_dt, 1)
dqdt_num = zeros(BigFloat, 7 * n)
s_dtm = deepcopy(State(ic_big))
hbig = big(h)
dq = hbig * dlnq
hbig -= dq
AHL21_big = Integrator(ahl21!, hbig, t0_big, tmax_big)
AHL21_big(s_dtm, 1;grad=false)
s_dtp = deepcopy(State(ic_big))
hbig += 2dq
AHL21_big = Integrator(ahl21!, hbig, t0_big, tmax_big)
AHL21_big(s_dtp, 1;grad=false)
for i in 1:n, k in 1:3
dqdt_num[(i - 1) * 7 + k] = .5 * (s_dtp.x[k,i] - s_dtm.x[k,i]) / dq
dqdt_num[(i - 1) * 7 + 3 + k] = .5 * (s_dtp.v[k,i] - s_dtm.v[k,i]) / dq
end
dqdt_num = convert(Array{Float64,1}, dqdt_num)
####################
###### Tests #######
# Check analytic vs finite difference derivatives
@test isapprox(asinh.(s0.jac_step), asinh.(jac_step_num);norm=maxabs)
@test isapprox(s_dt.dqdt, dqdt_num, norm=maxabs)
# Check that the positions and velocities for the derivatives and non-
# derivatives versions match
s_nograd = State(ic)
s_grad = State(ic)
tmax = 2000.0
Integrator(h, tmax)(s_nograd, grad=false)
Integrator(h, tmax)(s_grad, grad=true)
@test s_nograd.x == s_grad.x
@test s_nograd.v == s_grad.v
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 11155 | # This code tests the function kepler_driftij_gamma
import NbodyGradient: kepler_driftij_gamma!, Derivatives, init_nbody
@testset "kepler_driftij_gamma" begin
for drift_first in [true,false]
# Next, try computing two-body Keplerian Jacobian:
NDIM = 3
n = 3
H = [3,1,1]
t0 = 7257.93115525
h = 0.25
hbig = big(h)
tmax = 600.0
dlnq = big(1e-15)
elements = readdlm("elements.txt", ',')
m = zeros(n)
x0 = zeros(NDIM, n)
v0 = zeros(NDIM, n)
for k = 1:n
m[k] = elements[k,1]
end
for iter = 1:2
init = ElementsIC(t0, H, elements)
ic_big = ElementsIC(big(t0), H, big.(elements))
x0, v0, _ = init_nbody(init)
s0 = State(init)
sbig = State(ic_big)
if iter == 2
# Reduce masses to trigger hyperbolic routine:
m[1:n] *= 1e-3
s0.m[1:n] *= 1e-3
sbig.m[1:n] *= 1e-3
hbig = big(h)
end
# Tilt the orbits a bit:
x0[2,1] = 5e-1 * sqrt(x0[1,1]^2 + x0[3,1]^2)
x0[2,2] = -5e-1 * sqrt(x0[1,2]^2 + x0[3,2]^2)
v0[2,1] = 5e-1 * sqrt(v0[1,1]^2 + v0[3,1]^2)
v0[2,2] = -5e-1 * sqrt(v0[1,2]^2 + v0[3,2]^2)
i = 1 ; j = 2
x = copy(x0) ; v = copy(v0)
s = deepcopy(State(init))
s.x .= x; s.v .= v
d = Derivatives(Float64, s.n)
kepler_driftij_gamma!(s,d,i,j,h,drift_first)
x0 = copy(s.x) ; v0 = copy(s.v)
xerror = zeros(NDIM, n); verror = zeros(NDIM, n)
xbig = big.(s.x) ; vbig = big.(s.v); mbig = big.(m)
xerr_big = zeros(BigFloat, NDIM, n); verr_big = zeros(BigFloat, NDIM, n)
kepler_driftij_gamma!(s,d,i,j,h,drift_first)
d.jac_ij .+= Matrix{Float64}(I, size(d.jac_ij))
# Now, compute the derivatives numerically:
jac_ij_num = zeros(BigFloat, 14, 14)
dqdt_num = zeros(BigFloat, 14)
xsave = big.(x)
vsave = big.(v)
msave = big.(m)
sbig.x .= copy(xsave)
sbig.v .= copy(vsave)
sbig.m .= copy(msave)
# Compute the time derivatives:
# Initial positions, velocities & masses:
sm = deepcopy(State(ic_big))
sm.x .= big.(x0)
sm.v .= big.(v0)
sm.m .= big.(msave)
dq = dlnq * hbig
hbig -= dq
sm.xerror .= 0.0; sm.verror .= 0.0
kepler_driftij_gamma!(sm,i,j,hbig,drift_first)
sp = deepcopy(State(ic_big))
sp.x .= big.(x0)
sp.v .= big.(v0)
sp.m .= big.(msave)
hbig += 2dq
sp.xerror .= 0.0; sp.verror .= 0.0
kepler_driftij_gamma!(sp,i,j,hbig,drift_first)
# Now x & v are final positions & velocities after time step
for k = 1:3
dqdt_num[ k] = 0.5 * (sp.x[k,i] - sm.x[k,i]) / dq
dqdt_num[ 3 + k] = 0.5 * (sp.v[k,i] - sm.v[k,i]) / dq
dqdt_num[ 7 + k] = 0.5 * (sp.x[k,j] - sm.x[k,j]) / dq
dqdt_num[10 + k] = 0.5 * (sp.v[k,j] - sm.v[k,j]) / dq
end
hbig = big(h)
# Compute position, velocity & mass derivatives:
for jj = 1:3
# Initial positions, velocities & masses:
sm = deepcopy(State(ic_big))
sm.x .= big.(x0)
sm.v .= big.(v0)
sm.m .= big.(msave)
dq = dlnq * sm.x[jj,i]
if sm.x[jj,i] != 0.0
sm.x[jj,i] -= dq
else
dq = dlnq
sm.x[jj,i] = -dq
end
sm.xerror .= 0.0; sm.verror .= 0.0
kepler_driftij_gamma!(sm, i, j, hbig, drift_first)
sp = deepcopy(State(ic_big))
sp.x .= big.(x0)
sp.v .= big.(v0)
sp.m .= big.(msave)
if sm.x[jj,i] != 0.0
sp.x[jj,i] += dq
else
dq = dlnq
sp.x[jj,i] = dq
end
sp.xerror .= 0.0; sp.verror .= 0.0
kepler_driftij_gamma!(sp, i, j, hbig, drift_first)
# Now x & v are final positions & velocities after time step
for k = 1:3
jac_ij_num[ k, jj] = .5 * (sp.x[k,i] - sm.x[k,i]) / dq
jac_ij_num[ 3 + k, jj] = .5 * (sp.v[k,i] - sm.v[k,i]) / dq
jac_ij_num[ 7 + k, jj] = .5 * (sp.x[k,j] - sm.x[k,j]) / dq
jac_ij_num[10 + k, jj] = .5 * (sp.v[k,j] - sm.v[k,j]) / dq
end
sm = deepcopy(State(ic_big))
sm.x .= big.(x0)
sm.v .= big.(v0)
sm.m .= big.(msave)
dq = dlnq * sm.v[jj,i]
if sm.v[jj,i] != 0.0
sm.v[jj,i] -= dq
else
dq = dlnq
sm.v[jj,i] = -dq
end
sm.xerror .= 0.0; sm.verror .= 0.0
kepler_driftij_gamma!(sm, i, j, hbig, drift_first)
sp = deepcopy(State(ic_big))
sp.x .= big.(x0)
sp.v .= big.(v0)
sp.m .= big.(msave)
if sp.v[jj,i] != 0.0
sp.v[jj,i] += dq
else
dq = dlnq
sp.v[jj,i] = dq
end
sp.xerror .= 0.0; sp.verror .= 0.0
kepler_driftij_gamma!(sp, i, j, hbig, drift_first)
for k = 1:3
jac_ij_num[ k,3 + jj] = .5 * (sp.x[k,i] - sm.x[k,i]) / dq
jac_ij_num[ 3 + k,3 + jj] = .5 * (sp.v[k,i] - sm.v[k,i]) / dq
jac_ij_num[ 7 + k,3 + jj] = .5 * (sp.x[k,j] - sm.x[k,j]) / dq
jac_ij_num[10 + k,3 + jj] = .5 * (sp.v[k,j] - sm.v[k,j]) / dq
end
end
# Now vary mass of inner planet:
sm = deepcopy(State(ic_big))
sm.x .= big.(x0)
sm.v .= big.(v0)
sm.m .= big.(msave)
dq = sm.m[i] * dlnq
sm.m[i] -= dq
sm.xerror .= 0.0; sm.verror .= 0.0
kepler_driftij_gamma!(sm,i,j,hbig,drift_first)
sp = deepcopy(State(ic_big))
sp.x .= big.(x0)
sp.v .= big.(v0)
sp.m .= big.(msave)
dq = sp.m[i] * dlnq
sp.m[i] += dq
sp.xerror .= 0.0; sp.verror .= 0.0
kepler_driftij_gamma!(sp,i,j,hbig,drift_first)
for k = 1:3
jac_ij_num[ k,7] = .5 * (sp.x[k,i] - sm.x[k,i]) / dq
jac_ij_num[ 3 + k,7] = .5 * (sp.v[k,i] - sm.v[k,i]) / dq
jac_ij_num[ 7 + k,7] = .5 * (sp.x[k,j] - sm.x[k,j]) / dq
jac_ij_num[10 + k,7] = .5 * (sp.v[k,j] - sm.v[k,j]) / dq
end
# The mass doesn't change:
jac_ij_num[7,7] = 1.0
for jj = 1:3
# Now vary parameters of outer planet:
sm = deepcopy(State(ic_big))
sm.x .= big.(x0)
sm.v .= big.(v0)
sm.m .= big.(msave)
dq = dlnq * sm.x[jj,j]
if sm.x[jj,j] != 0.0
sm.x[jj,j] -= dq
else
dq = dlnq
sm.x[jj,j] = -dq
end
sm.xerror .= 0.0; sm.verror .= 0.0
kepler_driftij_gamma!(sm, i, j, hbig, drift_first)
sp = deepcopy(State(ic_big))
sp.x .= big.(x0)
sp.v .= big.(v0)
sp.m .= big.(msave)
if sp.x[jj,j] != 0.0
sp.x[jj,j] += dq
else
dq = dlnq
sp.x[jj,j] = dq
end
sp.xerror .= 0.0; sp.verror .= 0.0
kepler_driftij_gamma!(sp, i, j, hbig, drift_first)
for k = 1:3
jac_ij_num[ k,7 + jj] = .5 * (sp.x[k,i] - sm.x[k,i]) / dq
jac_ij_num[ 3 + k,7 + jj] = .5 * (sp.v[k,i] - sm.v[k,i]) / dq
jac_ij_num[ 7 + k,7 + jj] = .5 * (sp.x[k,j] - sm.x[k,j]) / dq
jac_ij_num[10 + k,7 + jj] = .5 * (sp.v[k,j] - sm.v[k,j]) / dq
end
sm = deepcopy(State(ic_big))
sm.x .= big.(x0)
sm.v .= big.(v0)
sm.m .= big.(msave)
dq = dlnq * sm.v[jj,j]
if sm.v[jj,j] != 0.0
sm.v[jj,j] -= dq
else
dq = dlnq
sm.v[jj,j] = -dq
end
sm.xerror .= 0.0; sm.verror .= 0.0
kepler_driftij_gamma!(sm, i, j, hbig, drift_first)
sp = deepcopy(State(ic_big))
sp.x .= big.(x0)
sp.v .= big.(v0)
sp.m .= big.(msave)
if sp.v[jj,j] != 0.0
sp.v[jj,j] += dq
else
dq = dlnq
sp.v[jj,j] = dq
end
sp.xerror .= 0.0; sp.verror .= 0.0
kepler_driftij_gamma!(sp, i, j, hbig, drift_first)
for k = 1:3
jac_ij_num[ k,10 + jj] = .5 * (sp.x[k,i] - sm.x[k,i]) / dq
jac_ij_num[ 3 + k,10 + jj] = .5 * (sp.v[k,i] - sm.v[k,i]) / dq
jac_ij_num[ 7 + k,10 + jj] = .5 * (sp.x[k,j] - sm.x[k,j]) / dq
jac_ij_num[10 + k,10 + jj] = .5 * (sp.v[k,j] - sm.v[k,j]) / dq
end
end
# Now vary mass of outer planet:
sm = deepcopy(State(ic_big))
sm.x .= big.(x0)
sm.v .= big.(v0)
sm.m .= big.(msave)
dq = sm.m[j] * dlnq
sm.m[j] -= dq
sm.xerror .= 0.0; sm.verror .= 0.0
kepler_driftij_gamma!(sm,i,j,hbig,drift_first)
sp = deepcopy(State(ic_big))
sp.x .= big.(x0)
sp.v .= big.(v0)
sp.m .= big.(msave)
dq = sp.m[j] * dlnq
sp.m[j] += dq
sp.xerror .= 0.0; sp.verror .= 0.0
kepler_driftij_gamma!(sp,i,j,hbig,drift_first)
for k = 1:3
jac_ij_num[ k,14] = .5 * (sp.x[k,i] - sm.x[k,i]) / dq
jac_ij_num[ 3 + k,14] = .5 * (sp.v[k,i] - sm.v[k,i]) / dq
jac_ij_num[ 7 + k,14] = .5 * (sp.x[k,j] - sm.x[k,j]) / dq
jac_ij_num[10 + k,14] = .5 * (sp.v[k,j] - sm.v[k,j]) / dq
end
# The mass doesn't change:
jac_ij_num[14,14] = 1.0
@test isapprox(jac_ij_num, d.jac_ij ;norm=maxabs)
@test isapprox(d.dqdt_ij, dqdt_num ;norm=maxabs)
end
end
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 5849 | import NbodyGradient: kepler_init
# Runs a simple test of kepler_init.jl
# Not sure why this test can't see these from the module...
const GNEWT = 39.4845 / 365.242^2
const third = 1.0 / 3.0
@testset "kepler_init" begin
ntrial = 10
for itrial = 1:ntrial
t0 = 2.4
mass = 1.0
period = 1.5
elements = ones(Float64, 6)
while elements[3]^2 + elements[4]^2 >= 0.2^2
elements = [period,rand() * period,randn(),randn(),rand() * pi,rand() * pi]
end
elements_diff = zeros(Float64, 6)
ecc = sqrt(elements[3]^2 + elements[4]^2)
ntime = 1000
time = linearspace(t0, t0 + period, ntime)
xvec = zeros(Float64, 3, ntime)
vvec = zeros(Float64, 3, ntime)
vfvec = zeros(Float64, 3, ntime)
timebig = big.(time)
# dt = 1e-8
dt = period / ntime
dtbig = big(dt)
jac_init = zeros(Float64, 7, 7)
# Compute Jacobian in BigFloat precision with analytic formulae:
jac_init_big = zeros(BigFloat, 7, 7)
# Compute Jacobian in BigFloat precision with finite differences:
jac_init_num = zeros(BigFloat, 7, 7)
# Variations in the elements for finite differences:
delements = big.([1e-15,1e-15,1e-15,1e-15,1e-15,1e-15,1e-15])
elements_name = ["P","t0","ecosom","esinom","inc","Omega","Mass"]
cartesian_name = ["x","y","z","vx","vy","vz","mass"]
# println("Elements: ",elements)
massbig = big(mass)
for i = 1:ntime
x, v = kepler_init(timebig[i], massbig, big.(elements))
if i == 1
x_ekep, v_ekep = kepler_init(time[i], mass, elements, jac_init)
# Redo in BigFloat
elements_big = big.(elements)
x_ekep_big, v_ekep_big = kepler_init(timebig[i], massbig, elements_big, jac_init_big)
# Check that these agree:
# println("x-x_ekep: ",maximum(abs.(x-x_ekep))," v-v_ekep: ",maximum(abs.(v-v_ekep)))
# Now take some derivatives:
for j = 1:7
elements_diff = big.(elements)
if j <= 6
elements_diff[j] -= delements[j]
else
massbig -= delements[7]
end
x_minus, v_minus = kepler_init(timebig[i], massbig, elements_diff)
elements_diff .= elements
if j <= 6
elements_diff[j] += delements[j]
else
massbig += 2.0 * delements[7]
end
x_plus, v_plus = kepler_init(timebig[i], massbig, elements_diff)
if j == 7
massbig -= delements[7]
end
for k = 1:3
jac_init_num[ k,j] = .5 * (x_plus[k] - x_minus[k]) / delements[j]
jac_init_num[3 + k,j] = .5 * (v_plus[k] - v_minus[k]) / delements[j]
end
end
jac_init_num[7,7] = 1.0
#= Dont need for CI Testing
#for j=1:7, k=1:7
if abs(jac_init[k,j]-jac_init_num[k,j]) > 1e-8
println(elements_name[j]," ",cartesian_name[k]," ",jac_init[k,j]," ",jac_init_num[k,j]," ",jac_init[k,j]-jac_init_num[k,j])
end
if abs(jac_init[k,j]/jac_init_num[k,j]-1) > 1e-12 && jac_init_num[k,j] != 0.0
println(elements_name[j]," ",cartesian_name[k]," ",jac_init[k,j]," ",jac_init_num[k,j]," ",jac_init[k,j]/jac_init_num[k,j]-1)
end
end
println("Jacobians: difference ",maximum(abs.(jac_init-jac_init_num)))
println("Jacobians: log diff ",maximum(abs.(jac_init[jac_init_num .!= 0.0]./jac_init_num[jac_init_num .!= 0.0].-1))) =#
end
xvec[:,i] = x
vvec[:,i] = v
# Compute finite difference velocity:
xf, vf = kepler_init(timebig[i] + dtbig, massbig, big.(elements))
vfvec[:,i] = (xf - x) / dt
end
period = elements[1]
# omega=atan2(elements[4],elements[3])
omega = atan(elements[4], elements[3])
semi = (GNEWT * mass * period^2 / 4 / pi^2)^third
# Compute the focus:
focus = [semi * ecc,0.,0.]
xfocus = semi * ecc * (-cos(omega) - sin(omega))
zfocus = semi * ecc * sin(omega)
# Check that we have an ellipse (we're assuming that the motion is in the x-z plane; no longer true):
Atot = 0.0
dAdt = zeros(Float64, ntime)
dx = xvec[1,1] - xvec[1,ntime - 1]
dy = xvec[2,1] - xvec[2,ntime - 1]
dz = xvec[3,1] - xvec[3,ntime - 1]
dAvec = 0.5 * [xvec[2,1] * dz - xvec[3,1] * dy;xvec[3,1] * dx - xvec[1,1] * dz;xvec[1,1] * dy - xvec[2,1] * dx]
# println("dA: ",norm(dAvec)," ",dAvec/norm(dAvec))
# dA = 0.5*(xvec[3,1]*dx-xvec[1,1]*dz)
dAdt[1] = norm(dAvec) / (time[2] - time[1])
Atot += norm(dAvec)
for i = 2:ntime
dx = xvec[1,i] - xvec[1,i - 1]
dy = xvec[2,i] - xvec[2,i - 1]
dz = xvec[3,i] - xvec[3,i - 1]
dAvec = 0.5 * [xvec[2,i] * dz - xvec[3,i] * dy;xvec[3,i] * dx - xvec[1,i] * dz;xvec[1,i] * dy - xvec[2,i] * dx]
# println("dA: ",norm(dAvec)," ",dAvec/norm(dAvec))
# dA = 0.5*(xvec[3,i]*dx-xvec[1,i]*dz)
dAdt[i] = norm(dAvec) / (time[i] - time[i - 1])
Atot += norm(dAvec)
end
# println("Total area: ",Atot," ",pi*sqrt(1-ecc^2)*semi^2," ratio: ",Atot/pi/semi^2/sqrt(1-ecc^2))
# using PyPlot
# plot(time,dAdt)
# axis([minimum(time),maximum(time),0.,1.5*maximum(dAdt)])
# println("Scatter in dAdt: ",std(dAdt))
# plot(time,vvec[1,:])
# plot(time,vfvec[1,:],".")
# plot(time,vvec[1,:]-vfvec[1,:],".")
# plot(time,vvec[3,:])
# plot(time,vfvec[3,:],".")
# plot(time,vvec[3,:]-vfvec[3,:],".")
# Check that velocities match finite difference values
@test isapprox(jac_init, jac_init_num;norm=maxabs)
@test isapprox(jac_init, convert(Array{Float64,2}, jac_init_big);norm=maxabs)
end
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4999 | # Tests the routine kickfast jacobian. This routine
# computes the impulse gradient after Dehnen & Hernandez (2017).
import NbodyGradient: kickfast!, Derivatives
# Next, try computing three-body Keplerian Jacobian:
@testset "kickfast" begin
n = 3
H = [3,1,1]
t0 = 7257.93115525
h = 0.05
tmax = 600.0
dlnq = big(1e-15)
elements = readdlm("elements.txt", ',')
elements[2,1] = 1.0
elements[3,1] = 1.0
m = zeros(n)
x0 = zeros(3, n)
v0 = zeros(3, n)
# Define which pairs will have impulse rather than -drift+Kepler:
pair = ones(Bool, n, n) # This does impulses
# We want Keplerian between star & planets, and impulses between
# planets. Impulse is indicated with 'true', -drift+Kepler with 'false':
for i = 2:n
pair[1,i] = false # This does a Kepler + drift
# We don't need to define this, but let's anyways:
pair[i,1] = false
end
# jac_step = zeros(7*n,7*n)
for k = 1:n
m[k] = elements[k,1]
end
m0 = copy(m)
init = ElementsIC(t0, H, elements)
ic_big = ElementsIC(big(t0), H, big.(elements))
s0 = State(init)
s0.pair .= pair
s0big = State(ic_big)
s0big.pair .= pair
# Tilt the orbits a bit:
s0.x[2,1] = 5e-1 * sqrt(s0.x[1,1]^2 + s0.x[3,1]^2)
s0.x[2,2] = -5e-1 * sqrt(s0.x[1,2]^2 + s0.x[3,2]^2)
s0.x[2,3] = -5e-1 * sqrt(s0.x[1,2]^2 + s0.x[3,2]^2)
s0.v[2,1] = 5e-1 * sqrt(s0.v[1,1]^2 + s0.v[3,1]^2)
s0.v[2,2] = -5e-1 * sqrt(s0.v[1,2]^2 + s0.v[3,2]^2)
s0.v[2,3] = -5e-1 * sqrt(s0.v[1,2]^2 + s0.v[3,2]^2)
# Take a step:
s0big.x .= big.(s0.x)
s0big.v .= big.(s0.v)
ahl21!(s0,h)
ahl21!(s0big,big(h))
# Now, copy these to compute Jacobian (so that I don't step
# x0 & v0 forward in time):
s = deepcopy(s0)
s.xerror .= 0.0; s.verror .= 0.0
# Compute jacobian exactly:
d = Derivatives(Float64, s.n);
s.jac_step .= 0.0
d.dqdt_kick .= 0.0
kickfast!(s,d,h)
# Add in identity matrix:
for i = 1:7 * n
d.jac_kick[i,i] += 1
end
# Now compute numerical derivatives, using BigFloat to avoid
# round-off errors:
jac_step_num = zeros(BigFloat, 7 * n, 7 * n)
# Save these so that I can compute derivatives numerically:
xsave = copy(s0big.x)
vsave = copy(s0big.v)
msave = copy(s0big.m)
hbig = big(h)
sbig = deepcopy(s0big)
sbig.x .= xsave
sbig.v .= vsave
sbig.m .= msave
sbig.xerror .= 0.0; sbig.verror .= 0.0
# Carry out step using BigFloat for extra precision:
kickfast!(sbig,hbig)
# Save back to use in derivative calculations
xsave .= sbig.x
vsave .= sbig.v
msave .= sbig.m
sbig = deepcopy(s0big)
sbig.xerror .= 0.0; sbig.verror .= 0.0
# Compute numerical derivatives wrt time:
dqdt_num = zeros(BigFloat, 7 * n)
# Vary time:
kickfast!(sbig,hbig)
# Initial positions, velocities & masses:
sbig = deepcopy(s0big)
sbig.xerror .= 0.0; sbig.verror .= 0.0
hbig = big(h)
dq = dlnq * hbig
hbig += dq
kickfast!(sbig,hbig)
# Now x & v are final positions & velocities after time step
for i in 1:n, k in 1:3
dqdt_num[(i - 1) * 7 + k] = (sbig.x[k,i] - xsave[k,i]) / dq
dqdt_num[(i - 1) * 7 + 3 + k] = (sbig.v[k,i] - vsave[k,i]) / dq
end
hbig = big(h)
# Vary the initial parameters of planet j:
for j = 1:n
# Vary the initial phase-space elements:
for jj = 1:3
# Initial positions, velocities & masses:
sbig = deepcopy(s0big)
sbig.xerror .= 0.0; sbig.verror .= 0.0
dq = dlnq * sbig.x[jj,j]
if sbig.x[jj,j] != 0.0
sbig.x[jj,j] += dq
else
dq = dlnq
sbig.x[jj,j] = dq
end
kickfast!(sbig, hbig)
# Now x & v are final positions & velocities after time step
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,(j - 1) * 7 + jj] = (sbig.x[k,i] - xsave[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,(j - 1) * 7 + jj] = (sbig.v[k,i] - vsave[k,i]) / dq
end
end
sbig = deepcopy(s0big)
sbig.xerror .= 0.0; sbig.verror .= 0.0
dq = dlnq * sbig.v[jj,j]
if sbig.v[jj,j] != 0.0
sbig.v[jj,j] += dq
else
dq = dlnq
sbig.v[jj,j] = dq
end
kickfast!(sbig, hbig)
for i in 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,(j - 1) * 7 + 3 + jj] = (sbig.x[k,i] - xsave[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,(j - 1) * 7 + 3 + jj] = (sbig.v[k,i] - vsave[k,i]) / dq
end
end
end
# Now vary mass of planet:
sbig = deepcopy(s0big)
sbig.xerror .= 0.0; sbig.verror .= 0.0
dq = sbig.m[j] * dlnq
sbig.m[j] += dq
kickfast!(sbig, hbig)
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,j * 7] = (sbig.x[k,i] - xsave[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,j * 7] = (sbig.v[k,i] - vsave[k,i]) / dq
end
# Mass unchanged -> identity
jac_step_num[7 * i,7 * i] = big(1.0)
end
end
jac_step_num = convert(Array{Float64,2}, jac_step_num)
dqdt_num = convert(Array{Float64,1}, dqdt_num)
@test isapprox(d.jac_kick, jac_step_num;norm=maxabs)
@test isapprox(d.dqdt_kick, dqdt_num;norm=maxabs)
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4758 | # Tests the routine phic jacobian. This routine
# computes the force gradient correction after Dehnen & Hernandez (2017).
import NbodyGradient: phic!, init_nbody
# Next, try computing three-body Keplerian Jacobian:
@testset "phic" begin
n = 3
H = [3,1,1]
t0 = 7257.93115525
h = 0.05
tmax = 600.0
dlnq = big(1e-15)
elements = readdlm("elements.txt", ',')
elements[2,1] = 1.0
elements[3,1] = 1.0
m = zeros(n)
x0 = zeros(3, n)
v0 = zeros(3, n)
# Define which pairs will have impulse rather than -drift+Kepler:
pair = ones(Bool, n, n)
# We want Keplerian between star & planets, and impulses between
# planets. Impulse is indicated with 'true', -drift+Kepler with 'false':
for i=2:n
pair[1,i] = false
pair[i,1] = false
end
for k = 1:n
m[k] = elements[k,1]
end
m0 = copy(m)
init = ElementsIC(t0, H, elements)
ic_big = ElementsIC(big(t0), H, big.(elements))
x0, v0, _ = init_nbody(init)
# Tilt the orbits a bit:
x0[2,1] = 5e-1 * sqrt(x0[1,1]^2 + x0[3,1]^2)
x0[2,2] = -5e-1 * sqrt(x0[1,2]^2 + x0[3,2]^2)
x0[2,3] = -5e-1 * sqrt(x0[1,2]^2 + x0[3,2]^2)
v0[2,1] = 5e-1 * sqrt(v0[1,1]^2 + v0[3,1]^2)
v0[2,2] = -5e-1 * sqrt(v0[1,2]^2 + v0[3,2]^2)
v0[2,3] = -5e-1 * sqrt(v0[1,2]^2 + v0[3,2]^2)
# Save to state
s = State(init)
s.x .= x0; s.v .= v0
s.pair .= pair
# Take a step:
ahl21!(s,h)
x0 .= s.x; v0 .= s.v
# Now, copy these to compute Jacobian (so that I don't step
# x0 & v0 forward in time):
x = copy(s.x); v = copy(s.v); m = copy(s.m)
# Compute jacobian exactly:
d = Derivatives(Float64, s.n)
phic!(s,d,h)
d.jac_phi .+= Matrix{Float64}(I, size(d.jac_phi))
# Now compute numerical derivatives, using BigFloat to avoid
# round-off errors:
jac_step_num = zeros(BigFloat, 7 * n, 7 * n)
# Save these so that I can compute derivatives numerically:
xsave = big.(x0)
vsave = big.(v0)
msave = big.(m0)
hbig = big(h)
sbig = deepcopy(State(ic_big))
sbig.x .= xsave; sbig.v .= vsave; sbig.m .= msave
sbig.pair .= pair
# Carry out step using BigFloat for extra precision:
phic!(sbig,hbig)
# Copy back to saves
xsave .= sbig.x; vsave .= sbig.v; msave .= sbig.m
# Compute numerical derivatives wrt time:
dqdt_num = zeros(BigFloat, 7 * n)
# Initial positions, velocities & masses:
hbig = big(h)
dq = dlnq * hbig
hbig += dq
sbig = deepcopy(State(ic_big))
sbig.x .= big.(x0); sbig.v .= big.(v0); sbig.m .= big.(m0)
sbig.pair .= pair
phic!(sbig,hbig)
# Now x & v are final positions & velocities after time step
for i in 1:n, k in 1:3
dqdt_num[(i - 1) * 7 + k] = (sbig.x[k,i] - xsave[k,i]) / dq
dqdt_num[(i - 1) * 7 + 3 + k] = (sbig.v[k,i] - vsave[k,i]) / dq
end
hbig = big(h)
# Vary the initial parameters of planet j:
for j = 1:n
# Vary the initial phase-space elements:
for jj = 1:3
# Initial positions, velocities & masses:
sbig = deepcopy(State(ic_big))
sbig.x .= big.(x0); sbig.v .= big.(v0); sbig.m .= big.(m0)
sbig.pair .= pair
dq = dlnq * sbig.x[jj,j]
if sbig.x[jj,j] != 0.0
sbig.x[jj,j] += dq
else
dq = dlnq
sbig.x[jj,j] = dq
end
phic!(sbig, hbig)
# Now x & v are final positions & velocities after time step
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,(j - 1) * 7 + jj] = (sbig.x[k,i] - xsave[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,(j - 1) * 7 + jj] = (sbig.v[k,i] - vsave[k,i]) / dq
end
end
sbig = deepcopy(State(ic_big))
sbig.x .= big.(x0); sbig.v .= big.(v0); sbig.m .= big.(m0)
sbig.pair .= pair
dq = dlnq * sbig.v[jj,j]
if sbig.v[jj,j] != 0.0
sbig.v[jj,j] += dq
else
dq = dlnq
sbig.v[jj,j] = dq
end
phic!(sbig, hbig)
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,(j - 1) * 7 + 3 + jj] = (sbig.x[k,i] - xsave[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,(j - 1) * 7 + 3 + jj] = (sbig.v[k,i] - vsave[k,i]) / dq
end
end
end
# Now vary mass of planet:
sbig = deepcopy(State(ic_big))
sbig.x .= big.(x0); sbig.v .= big.(v0); sbig.m .= big.(m0)
sbig.pair .= pair
dq = sbig.m[j] * dlnq
sbig.m[j] += dq
phic!(sbig, hbig)
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,j * 7] = (sbig.x[k,i] - xsave[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,j * 7] = (sbig.v[k,i] - vsave[k,i]) / dq
end
# Mass unchanged -> identity
jac_step_num[7 * i,7 * i] = big(1.0)
end
end
# Now, compare the results:
dqdt_num = convert(Array{Float64,1}, dqdt_num)
@test isapprox(d.jac_phi, jac_step_num;norm=maxabs)
@test isapprox(d.dqdt_phi, dqdt_num;norm=maxabs)
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4520 | # Tests the routine phisalpha jacobian. This routine
# computes the force gradient correction after Dehnen & Hernandez (2017).
import NbodyGradient: phisalpha!, init_nbody
# Next, try computing three-body Keplerian Jacobian:
@testset "phisalpha" begin
n = 3
H = [3,1,1]
t0 = 7257.93115525
h = 0.05
tmax = 600.0
dlnq = big(1e-15)
elements = readdlm("elements.txt", ',')
m = zeros(n)
x0 = zeros(3, n)
v0 = zeros(3, n)
alpha = 2.0
# Define which pairs will have impulse rather than -drift+Kepler:
pair = zeros(Bool, n, n)
for k = 1:n
m[k] = elements[k,1]
end
m0 = copy(m)
init = ElementsIC(t0, H, elements)
ic_big = ElementsIC(big(t0), H, big.(elements))
x0, v0, _ = init_nbody(init)
# Tilt the orbits a bit:
x0[2,1] = 5e-1 * sqrt(x0[1,1]^2 + x0[3,1]^2)
x0[2,2] = -5e-1 * sqrt(x0[1,2]^2 + x0[3,2]^2)
x0[2,3] = -5e-1 * sqrt(x0[1,2]^2 + x0[3,2]^2)
v0[2,1] = 5e-1 * sqrt(v0[1,1]^2 + v0[3,1]^2)
v0[2,2] = -5e-1 * sqrt(v0[1,2]^2 + v0[3,2]^2)
v0[2,3] = -5e-1 * sqrt(v0[1,2]^2 + v0[3,2]^2)
# Save to state
s = State(init)
s.x .= x0; s.v .= v0
s.pair .= pair
# Take a step:
ahl21!(s,h)
x0 .= s.x; v0 .= s.v
# Now, copy these to compute Jacobian (so that I don't step
# x0 & v0 forward in time):
x = copy(s.x); v = copy(s.v); m = copy(s.m)
# Compute jacobian exactly:
d = Derivatives(Float64, s.n)
phisalpha!(s,d,h,alpha)
d.jac_phi .+= Matrix{Float64}(I, size(d.jac_phi))
# Now compute numerical derivatives, using BigFloat to avoid
# round-off errors:
jac_step_num = zeros(BigFloat, 7 * n, 7 * n)
# Save these so that I can compute derivatives numerically:
xsave = big.(x0)
vsave = big.(v0)
msave = big.(m0)
hbig = big(h)
abig = big(alpha)
sbig = deepcopy(State(ic_big))
sbig.x .= xsave; sbig.v .= vsave; sbig.m .= msave
# Carry out step using BigFloat for extra precision:
phisalpha!(sbig,hbig,abig)
# Copy back to saves
xsave .= sbig.x; vsave .= sbig.v; msave .= sbig.m
# Compute numerical derivatives wrt time:
dqdt_num = zeros(BigFloat, 7 * n)
# Initial positions, velocities & masses:
hbig = big(h)
dq = dlnq * hbig
hbig += dq
sbig = deepcopy(State(ic_big))
sbig.x .= big.(x0); sbig.v .= big.(v0); sbig.m .= big.(m0)
phisalpha!(sbig,hbig,abig)
# Now x & v are final positions & velocities after time step
for i in 1:n, k in 1:3
dqdt_num[(i - 1) * 7 + k] = (sbig.x[k,i] - xsave[k,i]) / dq
dqdt_num[(i - 1) * 7 + 3 + k] = (sbig.v[k,i] - vsave[k,i]) / dq
end
hbig = big(h)
# Vary the initial parameters of planet j:
for j = 1:n
# Vary the initial phase-space elements:
for jj = 1:3
# Initial positions, velocities & masses:
sbig = deepcopy(State(ic_big))
sbig.x .= big.(x0); sbig.v .= big.(v0); sbig.m .= big.(m0)
dq = dlnq * sbig.x[jj,j]
if sbig.x[jj,j] != 0.0
sbig.x[jj,j] += dq
else
dq = dlnq
sbig.x[jj,j] = dq
end
phisalpha!(sbig, hbig, abig)
# Now x & v are final positions & velocities after time step
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,(j - 1) * 7 + jj] = (sbig.x[k,i] - xsave[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,(j - 1) * 7 + jj] = (sbig.v[k,i] - vsave[k,i]) / dq
end
end
sbig = deepcopy(State(ic_big))
sbig.x .= big.(x0); sbig.v .= big.(v0); sbig.m .= big.(m0)
dq = dlnq * sbig.v[jj,j]
if sbig.v[jj,j] != 0.0
sbig.v[jj,j] += dq
else
dq = dlnq
sbig.v[jj,j] = dq
end
phisalpha!(sbig, hbig, abig)
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,(j - 1) * 7 + 3 + jj] = (sbig.x[k,i] - xsave[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,(j - 1) * 7 + 3 + jj] = (sbig.v[k,i] - vsave[k,i]) / dq
end
end
end
# Now vary mass of planet:
sbig = deepcopy(State(ic_big))
sbig.x .= big.(x0); sbig.v .= big.(v0); sbig.m .= big.(m0)
dq = sbig.m[j] * dlnq
sbig.m[j] += dq
phisalpha!(sbig, hbig, abig)
for i = 1:n
for k = 1:3
jac_step_num[(i - 1) * 7 + k,j * 7] = (sbig.x[k,i] - xsave[k,i]) / dq
jac_step_num[(i - 1) * 7 + 3 + k,j * 7] = (sbig.v[k,i] - vsave[k,i]) / dq
end
# Mass unchanged -> identity
jac_step_num[7 * i,7 * i] = big(1.0)
end
end
# Now, compare the results:
dqdt_num = convert(Array{Float64,1}, dqdt_num)
@test isapprox(d.jac_phi, jac_step_num;norm=maxabs)
@test isapprox(d.dqdt_phi, dqdt_num;norm=maxabs)
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 3294 | import NbodyGradient: set_state!, zero_out!, amatrix
@testset "Transit Parameters" begin
N = 3
t0 = 7257.93115525 - 7300.0 - 0.5 # Initialize IC before first transit
h = 0.04
itime = 10.0 # Time integrator will run
tmax = itime
# Setup initial conditions:
elements = readdlm("elements.txt", ',')[1:N,:]
elements[2:end,3] .-= 7300.0
elements[:,end] .= 0.0 # Set Ωs to 0
elements[2,1] *= 10.0
elements[3,1] *= 10.0
ic = ElementsIC(t0, N, elements)
function calc_times(h)
intr = Integrator(ahl21!, h, 0.0, tmax)
s = State(ic)
ttbv = TransitParameters(itime, ic)
intr(s, ttbv)
return ttbv
end
# Calculate transit times
tts = calc_times(h)
mask = zeros(Bool, size(tts.dtbvdq0));
for jq = 1:N
for iq = 1:7
if iq == 7; ivary = 1; else; ivary = iq + 1; end # Shift mass variation to end
for i = 2:N
for k = 1:tts.count[i]
for itbv = 1:3
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[itbv,i,k,iq,jq] = true
end
end
end
end
end
end
function calc_finite_diff(h, t0, itime, tmax, elements)
# Now do finite difference with big float
dq0 = big(1e-10)
ic_big = ElementsIC(big(t0), N, big.(elements))
elements_big = copy(ic_big.elements)
sp, dp = dState(ic_big)
sm, dm = dState(ic_big)
ttp = TransitParameters(big(itime), ic_big);
ttm = TransitParameters(big(itime), ic_big);
dtde_num = zeros(BigFloat, size(ttp.dtbvdelements));
intr_big = Integrator(big(h), zero(BigFloat), big(tmax))
for jq in 1:N
for iq in 1:7
zero_out!(ttp); zero_out!(ttm); zero_out!(dp); zero_out!(dm);
ic_big.elements .= elements_big
ic_big.m .= elements_big[:,1]
if iq == 7; ivary = 1; else; ivary = iq + 1; end
ic_big.elements[jq,ivary] += dq0
if ivary == 1; ic_big.m[jq] += dq0; amatrix(ic_big); end # Masses don't update with elements array
initialize!(sp, ic_big)
intr_big(sp, ttp, dp; grad=false)
ic_big.elements[jq,ivary] -= 2dq0
if ivary == 1; ic_big.m[jq] -= 2dq0; amatrix(ic_big); end
initialize!(sm, ic_big)
intr_big(sm, ttm, dm; grad=false)
for i in 2:N
for k in 1:ttm.count[i]
for itbv=1:3
# Compute double-sided derivative for more accuracy:
dtde_num[itbv,i,k,iq,jq] = (ttp.ttbv[itbv,i,k] - ttm.ttbv[itbv,i,k]) / (2dq0)
end
end
end
end
end
return dtde_num
end
dtde_num = calc_finite_diff(h, t0, itime, tmax, elements)
@test isapprox(asinh.(tts.dtbvdelements[mask]), asinh.(dtde_num[mask]);norm=maxabs)
@test isapprox(asinh.(tts.dtbvdelements), asinh.(dtde_num);norm=maxabs)
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4489 | using FiniteDifferences
import NbodyGradient: set_state!, zero_out!, amatrix
@testset "Transit Series" begin
N = 3
t0 = 7257.93115525 - 7300.0 - 0.5 # Initialize IC before first transit
h = 0.04
itime = 10.0
tmax = itime
# Setup initial conditions:
elements = readdlm("elements.txt", ',')[1:N,:]
elements[2:end,3] .-= 7300.0
elements[:,end] .= 0.0 # Set Ωs to 0
elements[2,1] *= 10.0
elements[3,1] *= 10.0
ic = ElementsIC(t0, N, elements)
# Calculate transit times and b,vsky
function calc_times(h;grad=false)
intr = Integrator(ahl21!, h, 0.0, tmax)
s = State(ic)
ttbv = TransitParameters(itime, ic)
intr(s, ttbv;grad=grad)
return ttbv
end
# Calculate b,vsky for specified times
function calc_pd(h, times;grad=false)
intr = Integrator(ahl21!, h, 0.0, tmax)
s = State(ic)
ts = TransitSeries(times, ic)
intr(s, ts; grad=grad)
return ts
end
ttbv = calc_times(h; grad=true)
mask = ttbv.ttbv[1,2,:] .!= 0.0
ts = calc_pd(h, ttbv.ttbv[1,2,mask]; grad=true)
tol = 1e-10
# Test whether TransitSeries can reproduce b,vsky at transit time from TransitParameters
@test all(abs.(ttbv.ttbv[2,2,mask] .- ts.vsky[2,:]) .< tol)
@test all(abs.(ttbv.ttbv[3,2,mask] .- ts.bsky2[2,:]) .< tol)
# Now make set of times to calc b and vsky and compare derivatives
times = [t0, t0 + 1.0]
ts = calc_pd(h, times; grad=true)
# method for finite diff
function calc_b(θ,i=1;b=true,times=ttbv.ttbv[1,2,mask])
elements = reshape(θ,3,7)
intr = Integrator(ahl21!, h, 0.0, 10.0)
ic = ElementsIC(t0,N,elements)
s = State(ic)
pd = Photodynamics(times, ic)
intr(s, pd; grad=true)
if b
return pd.bsky2[i,:]
else
return pd.vsky[i,:]
end
end
# Now test derivatives
function calc_finite_diff(h, t0, times, tmax, elements)
# Now do finite difference with big float
dq0 = big(1e-10)
ic_big = ElementsIC(big(t0), N, big.(elements))
elements_big = copy(ic_big.elements)
s_big = State(ic_big)
pdp = TransitSeries(big.(times), ic_big);
pdm = TransitSeries(big.(times), ic_big);
dbvde_num = zeros(BigFloat, size(pdp.dbvdelements));
intr_big = Integrator(big(h), zero(BigFloat), big(tmax))
for jq in 1:N
for iq in 1:7
zero_out!(pdp); zero_out!(pdm);
ic_big.elements .= elements_big
ic_big.m .= elements_big[:,1]
if iq == 7; ivary = 1; else; ivary = iq + 1; end
ic_big.elements[jq,ivary] += dq0
if ivary == 1; ic_big.m[jq] += dq0; amatrix(ic_big); end # Masses don't update with elements array
sp = State(ic_big);
intr_big(sp, pdp; grad=false)
ic_big.elements[jq,ivary] -= 2dq0
if ivary == 1; ic_big.m[jq] -= 2dq0; amatrix(ic_big); end
sm = State(ic_big)
intr_big(sm, pdm; grad=false)
for i in 2:N
for k in 1:ts.nt
# Compute double-sided derivative for more accuracy:
dbvde_num[1,i,k,iq,jq] = (pdp.vsky[i,k] - pdm.vsky[i,k]) / (2dq0)
dbvde_num[2,i,k,iq,jq] = (pdp.bsky2[i,k] - pdm.bsky2[i,k]) / (2dq0)
end
end
end
end
return dbvde_num
end
mask = zeros(Bool, size(ts.dbvdelements));
for jq = 1:N
for iq = 1:7
if iq == 7; ivary = 1; else; ivary = iq + 1; end # Shift mass variation to end
for i = 2:N
for k = 1:ts.nt
for itbv = 1:2
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[2,i,k,iq,jq] = true
end
end
end
end
end
end
dbvde_num = calc_finite_diff(h, t0, ts.times, tmax, elements)
@test isapprox(asinh.(ts.dbvdelements[mask]), asinh.(dbvde_num[mask]); norm=maxabs)
#mask_times = ttbv.ttbv[1,2,:] .!= 0.0
#@test isapprox(asinh.(ts.dbvdelements[mask]), asinh.(ttbv.dtbvdelements[2:3,:,mask_times,:,:][mask]); norm=maxabs)
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 3745 | import NbodyGradient: set_state!, zero_out!, amatrix, initialize!
@testset "Transit Timing" begin
N = 3
t0 = 7257.93115525 - 7300.0 - 0.5 # Initialize IC before first transit
h = 0.04
itime = 10.0 # Amount of time the integrator will run
tmax = itime
# Setup initial conditions:
elements = readdlm("elements.txt", ',')[1:N,:]
elements[2:end,3] .-= 7300.0
elements[:,end] .= 0.0 # Set Ωs to 0
elements[2,1] *= 10.0
elements[3,1] *= 10.0
ic = ElementsIC(t0, N, elements)
function calc_times(h, ti)
intr = Integrator(ahl21!, h, 0.0, tmax)
s = State(ic)
tt = TransitTiming(itime, ic, ti)
intr(s, tt)
return tt
end
function calc_finite_diff(h, t0, itime, tmax, elements, ti)
# Now do finite difference with big float
dq0 = big(1e-10)
ic_big = ElementsIC(big(t0), N, big.(elements))
elements_big = copy(ic_big.elements)
sp, dp = dState(ic_big)
sm, dm = dState(ic_big)
ttp = TransitTiming(big(itime), ic_big, ti);
ttm = TransitTiming(big(itime), ic_big, ti);
dtde_num = zeros(BigFloat, size(ttp.dtdelements));
intr_big = Integrator(big(h), zero(BigFloat), big(tmax))
for jq in 1:N
for iq in 1:7
zero_out!(ttp); zero_out!(ttm); zero_out!(dp); zero_out!(dm);
ic_big.elements .= elements_big
ic_big.m .= elements_big[:,1]
if iq == 7; ivary = 1; else; ivary = iq + 1; end
ic_big.elements[jq,ivary] += dq0
if ivary == 1; ic_big.m[jq] += dq0; amatrix(ic_big); end # Masses don't update with elements array
initialize!(sp, ic_big)
intr_big(sp, ttp, dp; grad=false)
ic_big.elements[jq,ivary] -= 2dq0
if ivary == 1; ic_big.m[jq] -= 2dq0; amatrix(ic_big); end
initialize!(sm, ic_big)
intr_big(sm, ttm, dm; grad=false)
for i in ttm.occs
for k in 1:ttm.count[i]
# Compute double-sided derivative for more accuracy:
dtde_num[i,k,iq,jq] = (ttp.tt[i,k] - ttm.tt[i,k]) / (2dq0)
end
end
end
end
return dtde_num
end
for ti in 1:N
# Calculate transit times
hs = h ./ [1.0,2.0,4.0,8.0]
tts = TransitTiming[]
for h in hs
push!(tts, calc_times(h, ti))
end
mask = zeros(Bool, size(tts[2].dtdq0));
for jq = 1:N
for iq = 1:7
if iq == 7; ivary = 1; else; ivary = iq + 1; end # Shift mass variation to end
for i = tts[1].occs
for k = 1:tts[1].count[i]
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
dtde_num = calc_finite_diff(h, t0, itime, tmax, elements, ti)
@test isapprox(asinh.(tts[1].dtdelements[mask]), asinh.(dtde_num[mask]);norm=maxabs)
@test isapprox(asinh.(tts[1].dtdelements), asinh.(dtde_num);norm=maxabs)
end
# Test that the transit times for the derivatives and non-derivatives match
tmax = 2000.0
s_nograd = State(ic); tt_nograd = TransitTiming(tmax, ic);
s_grad = State(ic); tt_grad = TransitTiming(tmax, ic);
Integrator(h, tmax)(s_nograd, tt_nograd, grad=false)
Integrator(h, tmax)(s_grad, tt_grad, grad=true)
@test tt_nograd.tt == tt_grad.tt
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 7291 | # Approximate G_3 for small \sqrt{|\beta|s}:
using ForwardDiff
#const cg3 = 1./[6.0,-120.0,5040.0,-362880.0,39916800.0,-6227020800.0]
#const cH2 = 1./[3.0,-30.0,840.0,-45360.0,3991680.0,-518918400.0]
#const cH1 = 1./[12.0,-180.0,6720.0,-453600.0,47900160.0,-7264857600.0]
# Define a dummy function for automatic differentiation:
function G3(param::Array{T,1}) where {T <: Real}
return G3(param[1],param[2])
end
function G3(s::T,beta::T) where {T <: Real}
sqb = sqrt(abs(beta))
x = sqb*s
if beta >= 0
return (x-sin(x))/(sqb*beta)
else
return (x-sinh(x))/(sqb*beta)
end
end
y = zeros(2)
dg3 = y -> ForwardDiff.gradient(g3,y);
function H2(s::T,beta::T) where {T <: Real}
sqb = sqrt(abs(beta))
x=sqb*s
if beta >= 0
return (sin(x)-x*cos(x))/(sqb*beta)
else
return (sinh(x)-x*cosh(x))/(sqb*beta)
end
end
function H1(s::T,beta::T) where {T <: Real}
x=sqrt(abs(beta))*s
if beta >= 0
return (2.0-2cos(x)-x*sin(x))/beta^2
else
return (2.0-2cosh(x)+x*sinh(x))/beta^2
end
end
function g3_series(s::T,beta::T) where {T <: Real}
epsilon = eps(s)
# Computes G_3(\beta,s) using a series tailored to the precision of s.
x2 = -beta*s^2
term = one(s)
g3 = one(s)
n=0
# Terminate series when required precision reached:
while abs(term) > epsilon*abs(g3)
n += 1
term *= x2/((2n+3)*(2n+2))
g3 += term
end
g3 *= s^3/6
return g3::T
end
dg3_series = y -> ForwardDiff.gradient(g3_series,y);
# Define a dummy function for automatic differentiation:
function g3_series(param::Array{T,1}) where {T <: Real}
return g3_series(param[1],param[2])
end
#function H2_series(s::T,beta::T) where {T <: Real}
#x2 = abs(beta)*s^2
#pm = sign(beta)
#return s^3*(cH2[1]+x2*(pm*cH2[2]+x2*(cH2[3]+
# x2*(pm*cH2[4]+x2*(cH2[5]+x2*pm*cH2[6])))))
#end
function H2_series(s::T,beta::T) where {T <: Real}
# Computes H_2(\beta,s) using a series tailored to the precision of s.
epsilon = eps(s)
x2 = -beta*s^2
term = one(s)
h2 = one(s)
n=0
# Terminate series when required precision reached:
while abs(term) > epsilon*abs(h2)
n += 1
term *= x2
term /= (4n+6)*n
h2 += term
end
h2 *= s^3/3
return h2::T
end
#function H1_series(s::T,beta::T) where {T <: Real}
#x2 = abs(beta)*s^2
#pm = sign(beta)
#return x2*x2*(cH1[1]+x2*(pm*cH1[2]+x2*(cH1[3]+
# x2*(pm*cH1[4]+x2*(cH1[5]+x2*pm*cH1[6])))))/beta^2
#end
function H1_series(s::T,beta::T) where {T <: Real}
# Computes H_1(\beta,s) using a series tailored to the precision of s.
epsilon = eps(s)
x2 = -beta*s^2
term = one(s)
h1 = one(s)
n=0
# Terminate series when required precision reached:
while abs(term) > epsilon*abs(h1)
n += 1
term *= x2*(n+1)
term /= (2n+4)*(2n+3)*n
h1 += term
end
h1 *= s^4/12
return h1::T
end
nx = 10001
s = linearspace(-3.0,3.0,nx)
#s = linearspace(-0.5,0.5,nx)
beta = -rand(); epsilon = eps(beta)
sqb = sqrt(abs(beta))
x = sqb*s
g31_bigm= g3.(convert(Array{BigFloat,1},s),big(beta))
println(typeof(x))
g31m= g3.(s,beta)
@time g31m= g3.(s,beta)
e31m = convert(Array{Float64,1},1.0-g31m./g31_bigm)
e31m[isnan.(e31m)]=epsilon
g32m = g3_series.(s,beta)
@time g32m = g3_series.(s,beta)
e32m = convert(Array{Float64,1},1.0-g32m./g31_bigm)
e32m[isnan.(e32m)]=epsilon
H21_bigm= H2.(convert(Array{BigFloat,1},s),big(beta))
H21m= H2.(s,beta)
@time H21m= H2.(s,beta)
eH21m = convert(Array{Float64,1},1.0-H21m./H21_bigm)
eH21m[isnan.(eH21m)]=epsilon
H22m = H2_series.(s,beta)
@time H22m = H2_series.(s,beta)
eH22m = convert(Array{Float64,1},1.0-H22m./H21_bigm)
eH22m[isnan.(eH22m)]=epsilon
H11_bigm= H1.(convert(Array{BigFloat,1},s),big(beta))
H11m= H1.(s,beta)
@time H11m= H1.(s,beta)
eH11m = convert(Array{Float64,1},1.0-H11m./H11_bigm)
eH11m[isnan.(eH11m)]=epsilon
H12m = H1_series.(s,beta)
@time H12m = H1_series.(s,beta)
eH12m = convert(Array{Float64,1},1.0-H12m./H11_bigm)
eH12m[isnan.(eH12m)]=epsilon
beta = rand()
sqb = sqrt(abs(beta))
x = sqb*s
g31_bigp= g3.(convert(Array{BigFloat,1},s),big(beta))
println(typeof(x))
@time g31p= g3.(s,beta)
e31p = convert(Array{Float64,1},1.0-g31p./g31_bigp)
e31p[isnan.(e31p)]=epsilon
@time g32p = g3_series.(s,beta)
e32p = convert(Array{Float64,1},1.0-g32p./g31_bigp)
e32p[isnan.(e32p)]=epsilon
H21_bigp= H2.(convert(Array{BigFloat,1},s),big(beta))
@time H21p= H2.(s,beta)
eH21p = convert(Array{Float64,1},1.0-H21p./H21_bigp)
eH21p[isnan.(eH21p)]=epsilon
@time H22p = H2_series.(s,beta)
eH22p = convert(Array{Float64,1},1.0-H22p./H21_bigp)
eH22p[isnan.(eH22p)]=epsilon
H11_bigp= H1.(convert(Array{BigFloat,1},s),big(beta))
@time H11p= H1.(s,beta)
eH11p = convert(Array{Float64,1},1.0-H11p./H11_bigp)
eH11p[isnan.(eH11p)]=epsilon
@time H12p = H1_series.(s,beta)
eH12p = convert(Array{Float64,1},1.0-H12p./H11_bigp)
eH12p[isnan.(eH12p)]=epsilon
# It looks like for x < 0.5, the fractional error on g3_series is <epsilon for
# float64 numbers.
# So, for x > 0.5, we can use x-sin(x), while for x < 0.5, we can use the series.
# Also need to consider what happens for negative values.
using PyPlot
clf()
semilogy(x,abs.(e31m),label="G3, exact, beta<0 ")
println("e31m: ",minimum(abs.(e31m)))
semilogy(x,abs.(e32m),label="G3, series, beta<0 ")
#semilogy([.5,.5],[1e-16,maxabs(e31m)],linestyle="dashed")
println("e32m: ",minimum(abs.(e32m)))
#semilogy(-[.5,.5],[1e-16,maxabs(e31m)],linestyle="dashed")
semilogy(x,0.*x+eps(1.0))
read(STDIN,Char)
clf()
semilogy(x,abs.(e31p),label="G3, exact, beta>0 ")
println("e31p: ",minimum(abs.(e31p)))
#semilogy([.5,.5],[1e-16,1.],linestyle="dashed")
semilogy(x,abs.(e32p),label="G3, series, beta>0 ")
println("e32p: ",minimum(abs.(e32p)))
#semilogy(-[.5,.5],[1e-16,maxabs(e31p)],linestyle="dashed")
semilogy(x,0.*x+eps(1.0))
read(STDIN,Char)
clf()
semilogy(x,abs.(eH21m),label="G1G2-G0G3, exact, beta<0 ")
println("eH21m: ",minimum(abs.(eH21m)))
#semilogy( [.5,.5],[1e-16,1.],linestyle="dashed")
semilogy(x,abs.(eH22m),label="G1G2-G0G3, series, beta<0 ")
println("eH22m: ",minimum(abs.(eH22m)))
#semilogy(-[.5,.5],[1e-16,maxabs(eH21m)],linestyle="dashed")
semilogy(x,0.*x+eps(1.0))
read(STDIN,Char)
clf()
semilogy(x,abs.(eH21p),label="G1G2-G0G3, exact, beta>0 ")
println("eH21p: ",minimum(abs.(eH21p)))
#semilogy( [.5,.5],[1e-16,1.],linestyle="dashed")
semilogy(x,abs.(eH22p),label="G1G2-G0G3, series, beta>0 ")
println("eH22p: ",minimum(abs.(eH22p)))
#semilogy(-[.5,.5],[1e-16,maxabs(abs.(eH21p))],linestyle="dashed")
semilogy(x,0.*x+eps(1.0))
read(STDIN,Char)
clf()
semilogy(x,abs.(eH11m),label="G2^2-G1G3, exact, beta<0 ")
println("eH11m: ",minimum(abs.(eH11m)))
#semilogy( [.5,.5],[1e-16,1.],linestyle="dashed")
semilogy(x,abs.(eH12m),label="G2^2-G1G3, series, beta<0 ")
println("eH12m: ",minimum(abs.(eH11p)))
#semilogy(-[.5,.5],[1e-16,maxabs(eH11m)],linestyle="dashed")
semilogy(x,0.*x+eps(1.0))
read(STDIN,Char)
clf()
semilogy(x,abs.(eH11p),label="G2^2-G1G3, exact, beta>0 ")
println("eH11p: ",minimum(abs.(eH11p)))
#semilogy( [.5,.5],[1e-16,1.],linestyle="dashed")
semilogy(x,abs.(eH12p),label="G2^2-G1G3, series, beta>0 ")
println("eH12p: ",minimum(abs.(eH12p)))
semilogy(x,0.*x+eps(1.0))
#semilogy(-[.5,.5],[1e-16,maxabs(eH11p)],linestyle="dashed")
#legend(loc="lower left")
read(STDIN,Char)
clf()
plot(x,abs.(g31m))
plot(x,abs.(g32m))
plot(x,abs.(g31p))
plot(x,abs.(g32p))
plot(x,abs.(H21m))
plot(x,abs.(H22m))
plot(x,abs.(H21p))
plot(x,abs.(H22p))
plot(x,abs.(H11m))
plot(x,abs.(H12m))
plot(x,abs.(H11p))
plot(x,abs.(H12p))
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.