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.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 2320 | module TestFundamentals
using AlphaVantage
using Test
TEST_SLEEP_TIME = parse(Float64, get(ENV, "TEST_SLEEP_TIME", "15"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))
@testset "Fundamentals" begin
symbol = "IBM"
@testset "Overview" begin
data = company_overview(symbol, datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 59
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
@testset "Income Statement" begin
data = income_statement(symbol, datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 3
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
@testset "Balance Sheet" begin
data = balance_sheet(symbol, datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 3
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
@testset "Cash Flow" begin
data = cash_flow(symbol, datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 3
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
@testset "Earnings" begin
data = earnings(symbol, datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 3
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
@testset "Listing Status" begin
@testset "Default" begin
data = listing_status()
@test length(data) == 2
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
@testset "Delisted and Date" begin
data = listing_status(state = "delisted", date = "2020-12-17")
@test length(data) == 2
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end
@testset "Earnings Calendar" begin
data = earnings_calendar(3)
@test length(data) == 2
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
@testset "IPO Calendar" begin
data = ipo_calendar()
@test length(data) == 2
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end
end # module
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 378 | module AlphaVantageResponseTest
using AlphaVantage
using Test
@testset "Response" begin
names = Matrix{AbstractString}(["a" "b"])
data = Matrix{Any}(rand(2, 2))
response = AlphaVantageResponse(data, names)
@test isa(response, AlphaVantageResponse)
response = AlphaVantageResponse(tuple(data, names))
@test isa(response, AlphaVantageResponse)
end
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 576 | using AlphaVantage
using Test
using JSON3
TEST_SLEEP_TIME = parse(Float64, get(ENV, "TEST_SLEEP_TIME", "20"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))
@test haskey(ENV, "ALPHA_VANTAGE_API_KEY")
@testset "AlphaVantage" begin
include("client_test.jl")
include("stock_time_series_test.jl")
include("foreign_exchange_curency_test.jl")
include("sector_performance_test.jl")
include("digital_currency_test.jl")
include("technical_indicators_test.jl")
include("fundamentals_test.jl")
include("fundamental_values_test.jl")
include("economic_indicators_test.jl")
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 377 | module TestSectorPerformance
using AlphaVantage
using Test
TEST_SLEEP_TIME = parse(Float64, get(ENV, "TEST_SLEEP_TIME", "15"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))
@testset "Sector Performance" begin
data = sector_performance()
@test isa(data, AlphaVantageResponse)
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end # module
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 2136 | module TestStockTimeSeries
using AlphaVantage
using Test
using JSON3
TEST_SLEEP_TIME = parse(Float64, get(ENV, "TEST_SLEEP_TIME", "15"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))
stock_time_series_functions = [:time_series_daily, :time_series_daily_adjusted, :time_series_weekly, :time_series_weekly_adjusted, :time_series_monthly, :time_series_monthly_adjusted]
stock_time_series_functions_test = vcat(:time_series_intraday, stock_time_series_functions[1:MAX_TESTS])
@testset "Stock Time Series" begin
for f in stock_time_series_functions_test
@eval begin
testname = string($f)
@testset "$testname" begin
@testset "AlphaVantageResponse" begin
data = $f("MSFT")
@test isa(data, AlphaVantageResponse)
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "JSON" begin
data = $f("MSFT", datatype="json")
@test typeof(data) === Dict{String,Any}
@test length(data) === 2
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "CSV" begin
data = $f("MSFT", datatype="csv")
@test typeof(data) === Tuple{Array{Any, 2}, Array{AbstractString, 2}}
@test length(data) === 2
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "JSON3" begin
data = $f("MSFT", datatype="json", parser = x -> JSON3.read(x.body))
@test typeof(data) === JSON3.Object{Vector{UInt8}, Vector{UInt64}}
@test length(data) === 2
end
end
end
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
f = :time_series_intraday_extended
@eval begin
testname = string($f)
@testset "$testname" begin
data = $f("MSFT")
@test typeof(data) === Tuple{Array{Any, 2}, Array{AbstractString, 2}}
@test length(data) === 2
end
end
end
end # module
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 4481 | module TestTechnicalIndicators
using AlphaVantage
using Test
TEST_SLEEP_TIME = parse(Float64, get(ENV, "TEST_SLEEP_TIME", "15"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))
@testset "Technical Indicators" begin
@testset "Interval, Time Period, Series Type" begin
for ti in Symbol.(AlphaVantage.interval_timeperiod_seriestype_indicators[1:MAX_TESTS])
@eval begin
tiname = string($ti)
@testset "technical_indicator: $tiname" begin
@testset "JSON" begin
data = $ti("MSFT", "weekly", 10, "open", datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 2
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "CSV" begin
data = $ti("MSFT", "weekly", 10, "open", datatype="csv")
@test typeof(data) === Tuple{Array{Any, 2}, Array{AbstractString, 2}}
@test length(data) === 2
end
end
end
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end
@testset "Interval, Time Period" begin
for ti in Symbol.(AlphaVantage.interval_timeperiod_indicators[1:MAX_TESTS])
@eval begin
tiname = string($ti)
@testset "technical_indicator: $tiname" begin
@testset "JSON" begin
data = $ti("MSFT", "weekly", 10, datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 2
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "CSV" begin
data = $ti("MSFT", "weekly", 10, datatype="csv")
@test typeof(data) === Tuple{Array{Any, 2}, Array{AbstractString, 2}}
@test length(data) === 2
end
end
end
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end
@testset "Interval, Series Type" begin
for ti in Symbol.(AlphaVantage.interval_seriestype_indicators[1:MAX_TESTS])
@eval begin
tiname = string($ti)
@testset "technical_indicator: $tiname" begin
@testset "JSON" begin
data = $ti("MSFT", "weekly", "open", datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 2
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "CSV" begin
data = $ti("MSFT", "weekly", "open", datatype="csv")
@test typeof(data) === Tuple{Array{Any, 2}, Array{AbstractString, 2}}
@test length(data) === 2
end
end
end
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end
@testset "Interval" begin
for ti in Symbol.(AlphaVantage.interval_indicators[1:MAX_TESTS])
@eval begin
tiname = string($ti)
@testset "technical_indicator: $tiname" begin
@testset "JSON" begin
data = $ti("MSFT", "15min", datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 2
end
sleep(TEST_SLEEP_TIME + 2*rand())
@testset "CSV" begin
data = $ti("MSFT", "15min", datatype="csv")
@test typeof(data) === Tuple{Array{Any, 2}, Array{AbstractString, 2}}
@test length(data) === 2
end
end
end
sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end
end
@testset "Optional Arguments" begin
data = MACD("MSFT", "5min", "high", fastperiod = 13, slowperiod = 25, datatype="json")
@test typeof(data) === Dict{String, Any}
@test length(data) === 2
@test data["Meta Data"]["5.2: Slow Period"] == 25
@test data["Meta Data"]["5.1: Fast Period"] == 13
end
end
end # module
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | code | 332 | module UtilsTest
using AlphaVantage
using HTTP
using Test
@testset "Utils" begin
resp = HTTP.Messages.Response(
200,
[
Pair("Content-Type", "application/json")
];
body="""{"Note": "API limit exceeded"}"""
)
@test_throws Exception AlphaVantage._check_api_limit(resp)
end
end
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | docs | 1403 | # Contributing
AlphaVantage.jl is an **Open Source** project and there are different ways to contribute.
Please, use [GitHub issues](https://github.com/ellisvalentiner/AlphaVantage.jl/issues) to **report errors/bugs** or to **ask for new features**.
Contributions are welcome in the form of **pull requests**. Please follow these guidelines:
- Follow the Alpha Vantage API documentation (e.g. preserves the response contents).
- Write code against the master branch but pull request against the dev branch.
- By making a pull request, you're agreeing to license your code under a [MIT license](https://github.com/ellisvalentiner/AlphaVantage.jl/blob/dev/LICENSE.md).
- Types and functions should be documented using Julia's docstrings.
- All significant code should be tested.
## Style
- Type names are camel case, with the first letter capitalized.
- Function names, apart from constructors, are all lowercase. Include underscores between words only if the name would be hard to read without.
- Names of private (unexported) functions begin with underscore.
- Separate logical blocks of code with blank lines.
- Generally try to keep lines below 92-columns, unless splitting a long line onto multiple
lines makes it harder to read.
- Use 4 spaces for indentation.
- Remove trailing whitespace.
## Conduct
We adhere to the [Julia community standards](http://julialang.org/community/standards/).
| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | docs | 2192 | # AlphaVantage
[](https://travis-ci.org/ellisvalentiner/AlphaVantage.jl)
[](http://codecov.io/github/ellisvalentiner/AlphaVantage.jl?branch=master)
[](https://coveralls.io/github/ellisvalentiner/AlphaVantage.jl?branch=master)
A Julia wrapper for the Alpha Vantage API.
## Overview
This package is a Julia wrapper for the Alpha Vantage API. Alpha Vantage provides free realtime and historical data for equities, physical currencies, digital currencies (i.e. cryptocurrencies), and more than 50 technical indicators (e.g. SMA, EMA, WMA, etc.).
The Alpha Vantage API requires a [free API key](https://www.alphavantage.co/support/#api-key).
## Installation
```julia
Pkg.add("AlphaVantage")
```
and once you have obtained your API key pass it to the client as follows:.
```julia
using AlphaVantage
client = AlphaVantage.GLOBAL[]
client.key = "YOURKEY"
```
or set it as an environment variable
```bash
export ALPHA_VANTAGE_API_KEY=YOURKEY
```
and check that it is set using:
```julia
using AlphaVantage
AlphaVantage.GLOBAL[]
```
If you encounter a clear bug, please file a minimal reproducible example on GitHub.
## Features
* Intraday prices for stocks, currencies and cryptocurrencies.
* Daily, weekly and monthly prices for stocks, currencies and cryptocurrencies.
* Technical indicators for stock prices.
* Crypto currency health index from Flipside Crypto.
* Fundamental data for stocks.
* Economic Indicators
## Usage
```julia
using AlphaVantage
using DataFrames, StatsPlots, Dates
gr(size=(800,470))
# Get daily S&P 500 data
spy = time_series_daily("SPY");
# Convert to a DataFrame
data = DataFrame(spy);
# Convert timestamp column to Date type
data[!, :timestamp] = Dates.Date.(data[!, :timestamp]);
data[!, :open] = Float64.(data[!, :open])
# Plot the timeseries
plot(data[!, :timestamp], data[!, :open], label=["Open"])
savefig("sp500.png")
```

| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.4.1 | 893a38118dc5a7554a52bbbc58d6de591e58f7b6 | docs | 1634 |
# AlphaVantage.jl Documentation
*A Julia wrapper for the Alpha Vantage API.*
## Overview
This package is a Julia wrapper for the Alpha Vantage API. Alpha Vantage provides free realtime and historical data for equities, digital currencies (i.e. cryptocurrencies), and more than 50 technical indicators (e.g. SMA, EMA, WMA, etc.).
The Alpha Vantage API requires a [free API key](https://www.alphavantage.co/support/#api-key).
## Installation
```
# AlphaVantage.jl is not currently registered as an official package
# Please install the development version from GitHub:
Pkg.clone("git://GitHub.com/ellisvalentiner/AlphaVantage.jl")
```
If you encounter a clear bug, please file a minimal reproducible example on GitHub.
## Functions
### Stock Time Series
```
time_series_intraday()
time_series_daily()
time_series_daily_adjusted()
time_series_weekly()
time_series_weekly_adjusted()
time_series_monthly()
time_series_monthly_adjusted()
```
### Digital Currencies
```
digital_currencies_daily()
digital_currencies_weekly()
digital_currencies_monthly()
```
## Usage
```
using AlphaVantage
using DataFrames
using Plots
gr(size=(800,470))
# Get daily S&P 500 data
gspc = time_series_daily("^GSPC", apikey=ENV["ALPHA_VANTAGE_API_KEY"]);
# Convert to a DataFrame
data = DataFrame(gspc[2:end, :]);
# Add column names
names!(data, convert.(Symbol, gspc[1,:]));
# Convert timestamp column to Date type
data[:timestamp] = Dates.Date.(data[:timestamp]);
# Plot the timeseries
@df data plot(:timestamp, [:low :high :close], label=["Low" "High" "Close"], colour=[:red :green :blue], w=2)
savefig("sp500.png")
```

| AlphaVantage | https://github.com/ellisvalentiner/AlphaVantage.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 578 | using Documenter
using DocStringExtensions
using GeneralAstrodynamics
using DifferentialEquations
using Plots
makedocs(
format=Documenter.HTML(),
sitename="GeneralAstrodynamics.jl",
authors = "Joey Carpinelli",
pages=[
"Quick Start" => [
"Getting Started" => "index.md",
"Docstrings" => "docstrings.md"
]
]
)
deploydocs(
target = "build",
repo="github.com/cadojo/GeneralAstrodynamics.jl.git",
branch = "gh-pages",
devbranch = "main",
versions = ["stable" => "v^", "manual", "v#.#", "v#.#.#"],
)
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1126 | """
A superpackage for handling common astrodynamics
problems. See the __Extended Help__ section
for more information!
# Extended Help
## License
$(LICENSE)
## Imports
$(IMPORTS)
## Exports
$(EXPORTS)
"""
module GeneralAstrodynamics
using Reexport, Requires
using DocStringExtensions
@template (FUNCTIONS, METHODS, MACROS) =
"""
$(SIGNATURES)
$(DOCSTRING)
$(METHODLIST)
"""
@template (TYPES, CONSTANTS) =
"""
$(TYPEDEF)
$(DOCSTRING)
"""
include(joinpath("Calculations", "Calculations.jl"))
include(joinpath("CoordinateFrames", "CoordinateFrames.jl"))
include(joinpath("States", "States.jl"))
@reexport using .Calculations
@reexport using .CoordinateFrames
@reexport using .States
function __init__()
@require DifferentialEquations="0c46a032-eb83-5123-abaf-570d42b7fbaa" begin
include(joinpath("Propagation", "Propagation.jl"))
@reexport using .Propagation
end
@require Plots="91a5bcdd-55d7-5caf-9e0b-520d859cae80" begin
include(joinpath("Visualizations", "Visualizations.jl"))
@reexport using .Visualizations
end
end
end # module
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1545 | """
A module which provides common astrodynamics
calculations.
# Extended help
**Exports**
$(EXPORTS)
**Imports**
$(IMPORTS)
"""
module Calculations
export Circular, Elliptical, Parabolic, Hyperbolic
export conic, keplerian, cartesian
export perifocal, semimajor_axis
export kepler, lambert, lambert_universal, lambert_lancaster_blanchard
export specific_angular_momentum_vector, specific_angular_momentum
export specific_energy, C3, v_infinity, specific_potential_energy
export eccentricity_vector, eccentricity, semi_parameter
export distance, speed, periapsis_radius, apoapsis_radius, period
export true_anomoly, mean_motion, time_since_periapsis
export hohmann, SOI, SOA, normalize, redimension, analyticalhalo
export jacobi_constant, zerovelocity_curves
using DocStringExtensions
using Unitful
using Requires
using Contour
using StaticArrays
using AstroTime
using LinearAlgebra
import Dates
import Roots: find_zero
@template (FUNCTIONS, METHODS, MACROS) =
"""
$(SIGNATURES)
$(DOCSTRING)
"""
@template (TYPES, CONSTANTS) =
"""
$(TYPEDEF)
$(DOCSTRING)
"""
Unitful.@derived_dimension MassParameter Unitful.π^3/Unitful.π^2
@doc """
A unit dimension alias for length^3 / time^2. This is a common
dimension used in astrodynamics calculations.
"""
MassParameter
include(joinpath("R2BP", "Conics.jl"))
include(joinpath("R2BP", "R2BPCalculations.jl"))
include(joinpath("R2BP", "Kepler.jl"))
include(joinpath("R2BP", "Lambert.jl"))
include(joinpath("CR3BP", "CR3BPCalculations.jl"))
end # module
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 8821 | #
# Calculations for the Circular Restricted Three Body Problem.
#
"""
Normalizes a CR3BP orbit in the rotating reference frame.
"""
function LinearAlgebra.normalize(r::AbstractVector{<:Number}, v::AbstractVector{<:Number}, t::Number, a::Number, ΞΌs::Tuple{<:Number, <:Number}; lengthunit=u"km", timeunit=u"s")
rβ = r ./ a
Tβ = period(a, sum(ΞΌs))
vβ = v ./ (a / Tβ)
tβ = t / Tβ
ΞΌβ = min(ΞΌs[1], ΞΌs[2]) / (ΞΌs[1]+ΞΌs[2])
DU = a isa Unitful.Length ? a : a * lengthunit
DT = Tβ isa Unitful.Time ? Tβ : Tβ * timeunit
return rβ, vβ, tβ, ΞΌβ, DU, DT
end
"""
Redimensionalizes a CR3BP orbit in the rotating reference frame.
"""
function redimension(rβ::AbstractVector{<:Real}, vβ::AbstractVector{<:Real}, tβ::Real, ΞΌβ::Real, DU::Number, TU::Number)
r = rβ .* DU
v = vβ .* DU ./ TU
t = tβ * TU
sum_ΞΌs = DU^3 / ((TU / 2Ο)^2)
ΞΌβ = ΞΌβ * sum_ΞΌs
ΞΌβ = sum_ΞΌ - ΞΌβ
return r, v, t, DU, (ΞΌβ,ΞΌβ)
end
"""
Returns the spacecraft's nondimensional position w.r.t. body 1 (or 2).
"""
nondimensional_radius(r, xα΅’) = β( (r[1]-xα΅’)^2 + r[2]^2 + r[3]^2 )
"""
Returns synodic distance to primary body.
"""
distance_to_primary(r, ΞΌ) = norm(r .- SVector(-ΞΌ, 0, 0))
"""
Returns synodic distance to secondary body.
"""
distnace_to_secondary(r, ΞΌ) = norm(r .- SVector(one(ΞΌ)-ΞΌ, 0, 0))
"""
Returns the potential energy `U` in the Synodic frame with Normalized units.
"""
potential_energy(r, ΞΌ) = (r[1]^2 + r[2]^2)/2 + ((1-ΞΌ)/nondimensional_radius(r,-ΞΌ)) + (ΞΌ/nondimensional_radius(r,1-ΞΌ))
"""
Returns the Jacobi Constant, `C` in the Synodic frame with Normalized units.
"""
jacobi_constant(r, v, ΞΌ) = 2*potential_energy(r, ΞΌ) - (vβ
v)
"""
Given the Synodic frame vector, returns the vector in the barycenteric-inertial reference frame.
"""
function inertial(vecβ::AbstractVector, t, Ο::Unitful.AbstractQuantity=1.0u"rad"/unit(t))
ΞΈ = Ο*t
α΄΅Tβ = @SMatrix [
cos(ΞΈ) sin(ΞΈ) 0
-sin(ΞΈ) cos(ΞΈ) 0
0 0 1
]
return α΄΅Tβ * vecβ
end
"""
Given an `InertialCartesianState`, returns the state in the synodic (rotating) reference frame.
"""
function synodic(state::AbstractVector, t)
ΞΈ = Ο*t
Λ’Tα΅’ = inv(SMatrix{3,3}([
cos(ΞΈ) sin(ΞΈ) 0
-sin(ΞΈ) cos(ΞΈ) 0
0 0 1
]))
return Λ’Tα΅’ * state
end
"""
Position of primary body.
"""
function primary_position(ΞΌ)
SVector{3}(
-ΞΌ,
zero(ΞΌ),
zero(ΞΌ)
)
end
"""
Position of primary body.
"""
function secondary_position(ΞΌ)
SVector{3}(
one(ΞΌ)-ΞΌ,
zero(ΞΌ),
zero(ΞΌ)
)
end
"""
Returns the lagrange points for a CR3BP system.
__Arguments:__
- `ΞΌ`: Non-dimensional mass parameter for the CR3BP system.
- `L`: Langrange points requested, must be in range [1,5]
__Outputs:__
- Tuple of Lagrange points
- Throws `ArgumentError` if L is out of range [1,5]
__References:__
- [Rund, 2018](https://digitalcommons.calpoly.edu/theses/1853/)
"""
function lagrange(ΞΌ::Real, L=1:5)
if !all(L[i] β (1,2,3,4,5) for i β 1:length(L))
throw(ArgumentError("Requested lagrange points must be in range [1,5]"))
end
expressions = @SVector [
x -> x - (1-ΞΌ)/(x+ΞΌ)^2 + ΞΌ/(x+ΞΌ-1)^2,
x -> x - (1-ΞΌ)/(x+ΞΌ)^2 - ΞΌ/(x+ΞΌ-1)^2,
x -> x + (1-ΞΌ)/(x+ΞΌ)^2 + ΞΌ/(x+ΞΌ+1)^2
]
return (map(f->[find_zero(f, (-3,3)), 0, 0], expressions)...,
[(1/2) - ΞΌ, β(3)/2, 0], [(1/2) - ΞΌ, -β(3)/2, 0])[L]
end
"""
Returns an analytical solution for a Halo orbit about `L`.
__Arguments:__
- `ΞΌ`: Non-dimensional mass parameter for the CR3BP system.
- `Az`: Desired non-dimensional Z-amplitude for Halo orbit.
- `Ο`: Desired Halo orbit phase.
- `steps`: Number of non-dimensional timepoints in returned state.
- `L`: Lagrange point to orbit (L1 or L2).
- `hemisphere`: Specifies northern or southern Halo orbit.
__Outputs:__
- Synodic position vector `r::Array{<:AbstractFloat}`
- Synodic velocity vector `v::Array{<:Abstractfloat}`.
- Halo orbit period `Ξ€`.
- Throws `ArgumentError` if L is not `1` or `2`.
__References:__
- [Rund, 2018](https://digitalcommons.calpoly.edu/theses/1853/).
"""
function analyticalhalo(ΞΌ; Az=0.00, Ο=0.0, steps=1,
L=1, hemisphere=:northern)
if L == 1
point = first(lagrange(ΞΌ, 1))
Ξ³ = abs(one(ΞΌ) - ΞΌ - point)
n = collect(1:4) .* one(ΞΌ)
c = @. (ΞΌ + (-one(1))^n * (one(ΞΌ)-ΞΌ)Ξ³^(n+1)) / (Ξ³^3 * (one(ΞΌ) - Ξ³^(n+1)))
elseif L == 2
point = first(lagrange(ΞΌ, 2))
Ξ³ = abs(point - one(ΞΌ) + ΞΌ)
n = collect(1:4) .* one(ΞΌ)
c = @. ((-one(ΞΌ))^n * ΞΌ + (-one(ΞΌ))^n * (one(ΞΌ)-ΞΌ)Ξ³^(n+1)) / (Ξ³^3 * (one(ΞΌ) + Ξ³^(n+1)))
else
throw(ArgumentError("Only Halo orbits about L1 or L2 are supported."))
end
Οβ = β((2 - c[2] + β((9c[2]^2 - 8c[2])))/2)
k = (Οβ^2 + 1 + 2c[2]) / (2Οβ)
dβ = (3Οβ^2 / k) * (k*(6Οβ^2 - 1) - 2Οβ)
dβ = (8Οβ^2 / k) * (k*(11Οβ^2 - 1) - 2Οβ)
aββ = (3c[3] * (k^2 - 2)) / (4(1 + 2c[2]))
aββ = (3c[3]) / (4(1 + 2c[2]))
aββ = (-3c[3]Οβ / (4k*dβ)) * (3k^3 * Οβ - 6k*(k-Οβ) + 4)
aββ = (-3c[3]Οβ / (4k*dβ)) * (2 + 3k*Οβ)
bββ = (-3c[3]Οβ / (2dβ)) * (3k*Οβ - 4)
bββ = -3c[3]*Οβ / dβ
dββ = -c[3] / (2Οβ^2)
aββ = (-9Οβ / (4dβ)) * (4c[3] * (k*aββ-bββ) + k*c[4]*(4+k^2)) +
((9Οβ^2 + 1 - c[2]) / (2dβ)) * (3c[3]*(2aββ-k*bββ) + c[4]*(2+3k^2))
aββ = (-9Οβ / (4dβ)) * (4c[3] * (3k*aββ-bββ) + k*c[4]) -
(3 / (2dβ)) * (9Οβ^2 + 1 - c[2]) * (c[3]*(k*bββ+dββ-2aββ) - c[4])
bββ = (3 / (8dβ)) * 8Οβ * (3c[3] * (k*bββ - 2aββ) - c[4]*(2+3k^2)) +
(3/(8dβ)) * (9Οβ^2 + 1 + 2c[2]) * (4c[3]*(k*aββ-bββ) + k*c[4]*(4+k^2))
bββ = (9Οβ/dβ)*(c[3]*(k*bββ+dββ-2aββ)-c[4]) +
(3(9Οβ^2 + 1 + 2c[2]) / (8dβ) * (4c[3]*(k*aββ-bββ)+k*c[4]))
dββ = (3 / (64Οβ^2)) * (4c[3]*aββ + c[4])
dββ = (3 / (64 + Οβ^2)) * (4c[3]*(aββ - dββ) + c[4]*(4+k^2))
sβ = (1 / (2Οβ*(Οβ*(1+k^2) - 2k))) *
(3c[3]/2 * (2aββ*(k^2 - 2) - aββ*(k^2 + 2) - 2k*bββ) -
(3c[4]/8) * (3k^4 - 8k^2 + 8))
sβ = (1 / (2Οβ*(Οβ*(1+k^2) - 2k))) *
(3c[3]/2 * (2aββ*(k^2-2) + aββ*(k^2 + 2) + 2k*bββ + 5dββ) +
(3c[4]/8) * (12 - k^2))
lβ = (-3c[3] / 2) * (2aββ + aββ + 5dββ) - (3c[4]/8)*(12 - k^2) + 2Οβ^2 * sβ
lβ = (3c[3]/2) * (aββ - 2aββ) + (9c[4]/8) + 2Οβ^2 * sβ
Ξ = Οβ^2 - c[2]
Aα΅§ = Az / Ξ³
Aβ = β((-lβ*Aα΅§^2 - Ξ) / lβ)
Ξ½ = 1 + sβ*Aβ^2 + sβ*Aα΅§^2
Ξ€ = 2Ο / (Οβ*Ξ½)
Ο = Ξ½ .* (steps > 1 ? range(0, stop=Ξ€, length=steps) : range(0, stop=Ξ€, length=1000))
if hemisphere == :northern
m = 1.0
elseif hemisphere == :southern
m = 3.0
else
throw(ArgumentError("`hemisphere` must be `:northern` or `:southern`."))
end
Ξ΄β = 2 - m
Οβ = @. Οβ*Ο + Ο
x = @. Ξ³ * (aββ*Aβ^2 + aββ*Aα΅§^2 - Aβ*cos(Οβ) + (aββ*Aβ^2 -
aββ*Aα΅§^2)*cos(2Οβ) + (aββ*Aβ^3 - aββ*Aβ*Aα΅§^2)*cos(3Οβ)) + 1 - ΞΌ - (L == 1 ? Ξ³ : -Ξ³)
y = @. Ξ³ * (k*Aβ*sin(Οβ) + (bββ*Aβ^2 - bββ*Aα΅§^2)*sin(2Οβ) +
(bββ*Aβ^3 - bββ*Aβ*Aα΅§^2)*sin(3Οβ))
z = @. Ξ³ * (Ξ΄β*Aα΅§*cos(Οβ) + Ξ΄β*dββ*Aβ*Aα΅§*(cos(2Οβ)-3) +
Ξ΄β*(dββ*Aα΅§*Aβ^2 - dββ*Aα΅§^3)*cos(3Οβ))
xΜ = @. Ξ³ * (Οβ*Ξ½*Aβ*sin(Οβ) - 2Οβ*Ξ½*(aββ*Aβ^2 - aββ*Aα΅§^2)*sin(2Οβ) -
3Οβ*Ξ½*(aββ*Aβ^3 - aββ*Aβ*Aα΅§^2)*sin(3Οβ))
yΜ = @. Ξ³ * (Οβ*Ξ½*k*Aβ*cos(Οβ) + 2Οβ*Ξ½*(bββ*Aβ^2 - bββ*Aα΅§^2)*cos(2Οβ) +
3Οβ*Ξ½*(bββ*Aβ^3 - bββ*Aβ*Aα΅§^2)*cos(3Οβ))
zΜ = @. Ξ³ * (-Οβ*Ξ½*Ξ΄β*Aα΅§*sin(Οβ) - 2Οβ*Ξ½*Ξ΄β*dββ*Aβ*Aα΅§*sin(2Οβ) -
3Οβ*Ξ½*Ξ΄β*(dββ*Aα΅§*Aβ^2 - dββ*Aα΅§^2)*sin(3Οβ))
return hcat(x, y, z)[1:steps, :], hcat(xΜ, yΜ, zΜ)[1:steps, :], Ξ€
end
"""
Returns a `Vector` of `Matrix` values.
Each `Matrix` contains a 3-column nondimensional
position trajectory in the Synodic frame which
represents a Zero Velocity Curve.
"""
function zerovelocity_curves(r::AbstractVector, v::AbstractVector, ΞΌ::Real;
nondimensional_range = range(-2; stop=2, length=1000))
x = nondimensional_range
y = nondimensional_range
z = [
2 * potential_energy([xs, ys, 0.0], ΞΌ) - jacobi_constant(r, v, ΞΌ)
for xs β x, ys β y
]
zvc_contour = contours(x,y,z,[0.0])
curves = Vector{Matrix{Float64}}()
for zvc_level β Contour.levels(zvc_contour)
x = Float64[]
y = Float64[]
for zvc_line β Contour.lines(zvc_level)
xs, ys = coordinates(zvc_line)
if length(x) == length(y) == 0
x = xs
y = ys
else
x = vcat(x, xs)
y = vcat(y, ys)
end
end
if length(curves) == 0
curves = [hcat(x,y)]
else
curves = vcat(curves, [hcat(x, y)])
end
end
return curves
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 597 | #
# Definitions for conic sections within
# R2BP dynamics.
#
"""
An abstract type for all conic sections.
"""
abstract type ConicSection end
"""
An abstract type representing the Circular
conic section.
"""
abstract type Circular <: ConicSection end
"""
An abstract type representing the Elliptical
conic section.
"""
abstract type Elliptical <: ConicSection end
"""
An abstract type representing the Parabolic
conic section.
"""
abstract type Parabolic <: ConicSection end
"""
An abstract type representing the Hyperbolic
conic section.
"""
abstract type Hyperbolic <: ConicSection end
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 2007 | #
# Kepler.jl
#
# Solves Kepler's problem for TwoBody orbits.
#
"""
Solves Kepler's Problem for `orbit` and `Ξtα΅’`.
"""
function kepler(r::AbstractVector, v::AbstractVector, ΞΌ::Number, Ξt::Number = period(semimajor_axis(r,v,ΞΌ), ΞΌ); tol=1e-6, max_iter=100)
e, a, i, Ξ©, Ο, Ξ½ = keplerian(r, v, ΞΌ)
T = period(a, ΞΌ)
conic_section = conic(e)
# Guess Οβ
if conic_section == Hyperbolic
Οβ = sign(Ξt) * β(-a) * log(β―, (-2 * ΞΌ / a * Ξt) / (r β
v + (sign(Ξt) * β(-ΞΌ * a) * (1 - norm(r) / a))))
elseif conic_section == Parabolic
Οβ = β(a) * tan(Ξ½ / 2)
else
Ξt = mod(Ξt, T)
Οβ = β(ΞΌ) * Ξt / a
end
# Iteratively solve for Ο
# TODO: Compare loop vs. recursion performance here.
# There shouldn't be too large of a difference, since this tends
# to converge with only a few iterations.
Οβ, rβ, Ο, Cβ, Cβ = Οβ(Οβ, Ξt, r, v, a, ΞΌ, tol=tol, max_iter=max_iter)
# Convert to a Orbit
f = 1 - Οβ^2 / norm(r) * Cβ
fΜ = β(ΞΌ) / (norm(r) * rβ) * Οβ * (Ο * Cβ - 1)
g = Ξt - (Οβ^3 / β(ΞΌ)) * Cβ
gΜ = 1 - (Οβ^2 / rβ) * Cβ
return ((f * r) .+ (g * v), (fΜ * r) .+ (gΜ * v))
end
function Οβ(Οβ, Ξt, rα΅’β, vα΅’β, a, ΞΌ; iter=1, tol=1e-14, max_iter=100)
rβ = norm(rα΅’β)
Ο = upreferred(Οβ^2 / a)
if Ο > tol
Cβ = (1 - cos(β(Ο))) / Ο
Cβ = (β(Ο) - sin(β(Ο))) / β(Ο^3)
elseif Ο < -tol
Cβ = (1 - cosh(β(-Ο))) / Ο
Cβ = (sinh(β(-Ο)) - β(-Ο)) / β((-Ο)^3)
else
Cβ = 1.0 / 2.0
Cβ = 1.0 / 6.0
end
r = Οβ^2 * Cβ + (rα΅’β β
vα΅’β) * Οβ / β(ΞΌ) * (1 - Ο*Cβ) + rβ * (1 - Ο * Cβ)
Οβββ = Οβ + ((β(ΞΌ) * Ξt - Οβ^3 * Cβ - (rα΅’β β
vα΅’β) / β(ΞΌ) * Οβ^2 * Cβ - rβ * Οβ * (1 - Ο * Cβ)) / r)
if iter > max_iter
@error "Failed to converge!"
return Οβ, r, Ο, Cβ, Cβ
elseif abs(Οβββ - Οβ) < oneunit(Οβ) * tol
return Οβ, r, Ο, Cβ, Cβ
else
return Οβ(Οβββ, Ξt, rα΅’β, vα΅’β, a, ΞΌ; iter=iter+1, tol=tol, max_iter=max_iter)
end
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 34251 | #
# Solver for Lambert's problem
#
# References:
# [1] David, A. "Vallado. Fundamentals of Astrodynamics and Applications." (2013).
#
"""
Solves Lambert's problem through the use of univeral variables.
"""
function lambert_universal(rΜ
β::AbstractVector, rΜ
β::AbstractVector, ΞΌ::Number, Ξt::Number;
trajectory=:short, tolerance=1e-12, max_iter=25)
# Specify short way, or long way trajectory
if trajectory == :short
tβ = 1
elseif trajectory == :long
tβ = -1
else
throw(ArgumentError("`trajectory` must be set to `:short` or `:long`"))
end
rβ = norm(rΜ
β)
rβ = norm(rΜ
β)
cosΞΞ½ = (rΜ
ββ
rΜ
β) / (rβ*rβ)
ΞΞ½ = asin(u"rad", tβ * β(1 - (cosΞΞ½)^2))
A = upreferred(tβ * β(rβ*rβ * (1 + cosΞΞ½)))
if A β 0
throw(ErrorException("Can't calculate the orbit."))
end
Οβ = 0.0
Cβ = 1/2
Cβ = 1/6
Οβ = 4Ο^2
Οβ = -4Ο
yβ = rβ + rβ + (A * (Οβ*Cβ - 1) / β(Cβ))
Ξtβ = Ξt + 1u"s"
iter = 0
while (iter < max_iter) &&
(abs(Ξtβ - Ξt) > (tolerance * oneunit(Ξt))) || (A > 0 *oneunit(A) && yβ < 0 * oneunit(yβ))
yβ = rβ + rβ + (A * (Οβ*Cβ - 1) / β(Cβ))
Οβ = β(yβ / Cβ)
Ξtβ = (Οβ^3 * Cβ + A*β(yβ)) / β(ΞΌ)
if Ξtβ < Ξt
Οβ = Οβ
else
Οβ = Οβ
end
Οβ = (Οβ + Οβ) / 2
if Οβ > tolerance
Cβ = (1 - cos(β(Οβ))) / Οβ
Cβ = (β(Οβ) - sin(β(Οβ))) / β(Οβ^3)
elseif Οβ < -tolerance
Cβ = (1 - cosh(β(-Οβ))) / Οβ
Cβ = (sinh(β(-Οβ)) - β(-Οβ)) / β((-Οβ)^3)
else
Cβ = 1.0 / 2.0
Cβ = 1.0 / 6.0
end
iter += 1
end
f = 1 - yβ/rβ
gΜ = 1 - yβ/rβ
g = A * β(yβ/ΞΌ)
vΜ
β = upreferred.((rΜ
β .- (f .* rΜ
β)) ./ g)
vΜ
β = upreferred.(((gΜ .* rΜ
β) .- rΜ
β) ./ g)
return vΜ
β, vΜ
β
end
"""
The following code was converted to Julia, from a [GitHub repository](https://github.com/rodyo/FEX-Lambert)
that hosts a MATLAB implementation. At the time of writing, this respository has a BSD license. I'm providing the copyright notice here, as instructed by the license text.
```
Copyright (c) 2018, Rody Oldenhuis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of this project.
```
"""
function Οmax(y)
an = [
4.000000000000000e-001,
2.142857142857143e-001,
4.629629629629630e-002,
6.628787878787879e-003,
7.211538461538461e-004,
6.365740740740740e-005,
4.741479925303455e-006,
3.059406328320802e-007,
1.742836409255060e-008,
8.892477331109578e-010,
4.110111531986532e-011,
1.736709384841458e-012,
6.759767240041426e-014,
2.439123386614026e-015,
8.203411614538007e-017,
2.583771576869575e-018,
7.652331327976716e-020,
2.138860629743989e-021,
5.659959451165552e-023,
1.422104833817366e-024,
3.401398483272306e-026,
7.762544304774155e-028,
1.693916882090479e-029,
3.541295006766860e-031,
7.105336187804402e-033
]
powers = y.^(1:25)
Ο = 4/3 * powers β
an
βΟ_βx = ((1:25) .* vcat(1, powers[1:24])) β
an
βΒ²Ο_βxΒ² = ((1:25) .* (0:24) .* vcat(1/y, 1, powers[1:23])) β
an
βΒ³Ο_βxΒ³ = ((1:25) .* (0:24) .* (-1:23) .*
vcat(1/y/y, 1/y, 1, powers[1:22])) β
an
return Ο, βΟ_βx, βΒ²Ο_βxΒ², βΒ³Ο_βxΒ³
end;
"""
The following code was converted to Julia, from a [GitHub repository](https://github.com/rodyo/FEX-Lambert)
that hosts the MATLAB implementation. At the time of writing, the respository has a BSD license. I'm providing the copyright notice here, as instructed by the license text.
```
Copyright (c) 2018, Rody Oldenhuis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of this project.
```
"""
function LancasterBlanchard(x, q, m)
# Validate input
if x < -one(x)
@warn "`x` provided implies negative eccentricity. Correcting..."
x = abs(x) - 2 * one(x)
elseif x == -one(x)
@warn "`x` provided is invalid. Setting `x` to the next float..."
x = nextfloat(x)
end
# Parameter E
E = x*x - one(x)
if x == 1 # parabolic input βΉ analytical solution
T = 4/3 * (1 - q^3)
βT = 4/5 * (q^5 - 1)
βΒ²T = βT + 120/70 * (1 - q^7)
βΒ³T = 3 * (βΒ²T - βT) + 2400 / 1080 * (q^9 - 1)
elseif abs(x - one(x)) < 1e-2 # almost parabolic βΉ use series
# Series expansion for T & associated partials
Οβ, βΟ_βxβ, βΒ²Ο_βxββ, βΒ³Ο_βxββ = Οmax(-E)
Οβ, βΟ_βxβ, βΒ²Ο_βxββ, βΒ³Ο_βxββ = Οmax(-E * q * q)
T = Οβ - q^3 * Οβ
βT = 2 * x * (q^5 * βΟ_βxβ - βΟ_βxβ)
βΒ²T = βT/x + 4 * x^2 * (βΒ²Ο_βxββ - q^7 * βΒ²Ο_βxββ)
βΒ³T = 3 * (βΒ²T - βT/x) / x + 8 * x * x * (q^9 * βΒ³Ο_βxββ - βΒ³Ο_βxββ)
else
y = β(abs(E))
z = β(1 + q^2 * E)
f = y * (z - q * x)
g = x * z - q * E
if E < zero(E)
Ξ΄ = atan(f, g) + m*Ο
elseif E == zero(E)
Ξ΄ = zero(E)
else
Ξ΄ = log(β―, max(0, f+g))
end
T = 2 * (x - q * z - Ξ΄ / y) / E
βT = (4 - 4 * q^3 * x/z - 3 * x * T) / E
βΒ²T = (-4 * q^3/z * (1 - q^2 * x^2 / z^2) - 3*T - 3 * x * βT) / E
βΒ³T = (4 * q^3 / z^2 *
((1 - q^2 * x^2 / z^2) + 2 * q^2 * x/z^2 * (z - x)) -
8*βT - 7*x*βΒ²T) / E
end
return T, βT, βΒ²T, βΒ³T
end
"""
The following code was converted to Julia, from a [GitHub repository](https://github.com/rodyo/FEX-Lambert)
that hosts a MATLAB implementation. At the time of writing, this respository has a BSD license. I'm providing the copyright notice here, as instructed by the license text.
```
Copyright (c) 2018, Rody Oldenhuis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of this project.
```
"""
function minmax_distances(rΜ²β, rΜ²β, rβ, rβ, Ξ΄β, a, vΜ²β, vΜ²β, m, ΞΌ)
min_distance = min(rβ, rβ)
max_distance = max(rβ, rβ)
longway = abs(Ξ΄β) > Ο # check if longway trajectory was selected
# Find eccentricity vector using triple product identity
eΜ² = ((vΜ²ββ
vΜ²β) * rΜ²β - (vΜ²β β
rΜ²β) * vΜ²β) / ΞΌ - rΜ²β / rβ
# Scalar eccentricity
e = norm(eΜ²)
# Pericenter / apocenter
pericenter = a * (1 - e)
apocenter = Inf # For parabolic / hyperbolic case
if e < one(e)
apocenter = a * (1 + e) # elliptical case
end
# We have the eccentricity vector, so we know exactly
# where the pericenter is. Given Ξ΄β and that fact
# to cross-check if the trajectory goes past it
if m > zero(m) # always elliptical, both apses traversed
min_distance = pericenter
max_distance = apocenter
else # more complicated
pm1 = sign(rβ * rβ * (eΜ²β
vΜ²β) - (rΜ²ββ
eΜ²) * (rΜ²ββ
vΜ²β))
pm2 = sign(rβ * rβ * (eΜ²β
vΜ²β) - (rΜ²ββ
eΜ²) * (rΜ²ββ
vΜ²β))
# Make sure ΞΈβ, ΞΈβ β (-1, 1)
ΞΈβ = pm1 * acos(max(-1, min(1, (rΜ²β./rβ) β
(eΜ²./e))))
ΞΈβ = pm2 * acos(max(-1, min(1, (rΜ²β./rβ) β
(eΜ²./e))))
if ΞΈβ+ΞΈβ < zero(ΞΈβ)
if abs(ΞΈβ) + abs(ΞΈβ) == Ξ΄β # pericenter was passed
min_distance = pericenter
else
min_distance = apocenter # apocenter was passed
end
elseif longway
min_distance = pericenter
if e < one(e)
max_distance = apocenter
end
end
end
return min_distance, max_distance
end
"""
The following code was converted to Julia, from a [GitHub repository](https://github.com/rodyo/FEX-Lambert)
that hosts a MATLAB implementation. At the time of writing, this respository has a BSD license. I'm providing the copyright notice here, as instructed by the license text.
```
Copyright (c) 2018, Rody Oldenhuis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of this project.
```
"""
function lambert_lancaster_blanchard(
rΜ²β::AbstractVector, rΜ²β::AbstractVector,
ΞΌ::Number, Ξt::Number;
revolutions = 0,
branch=:left,
trajectory=:short,
tolerance=1e-12,
max_iter=25,
output_extrema=Val{false})
m = revolutions
if output_extrema == Val{true}
error_output = [NaN, NaN, NaN] * u"km/s", [NaN, NaN, NaN] * u"km/s", (NaN * u"km", NaN * u"km")
elseif output_extrema == Val{false}
error_output = [NaN, NaN, NaN] * u"km/s", [NaN, NaN, NaN] * u"km/s"
else
throw(ArgumentError("Keyword argument `output_extrema` must be set to Val{true} or Val{false}."))
end
if trajectory β (:short, :long)
throw(ArgumentError("Must specify :long or :short for trajectory kwarg."))
end
if Ξt < zero(Ξt)
throw(ArgumentError(string(
"Time of flight must be non-negative!",
"Use the `trajectory` kwarg to specify",
"longway or shortway trajectories.")))
end
if m < zero(m)
throw(ArgumentError(string(
"Number of revolutions must be non-negative!",
"Use the `branch` kwarg to specify",
"left or righht branch solutions.")))
end
# Collect unit vectors and magnitudes
# of provided position vectors
rβ = norm(rΜ²β)
rβ = norm(rΜ²β)
rΜβ = normalize(rΜ²β)
rΜβ = normalize(rΜ²β)
# Unit position vector orthogonal to
# position vectors
rΜβ = normalize(rΜ²β Γ rΜ²β)
# Tangential-direction unit vectors
tΜβ = rΜβ Γ rΜβ
tΜβ = rΜβ Γ rΜβ
# Turn angle
Ξ΄β = acos(max(-1, min(1, (rΜ²ββ
rΜ²β)/rβ/rβ)))
# If longway, account for final velocity
# direction by flipping Ξ΄β sign
if trajectory == :long
Ξ΄β -= 2Ο
end
# Constants
c = β(rβ^2 + rβ^2 - 2*rβ*rβ*cos(Ξ΄β))
s = (rβ + rβ + c) / 2
T = β(8ΞΌ / s^3) * Ξt
q = β(rβ * rβ) / s * cos(Ξ΄β/2)
# Initial values
Tβ = first(LancasterBlanchard(0, q, m))
Ξ΄T = Tβ - T
phr = mod(2 * atan(1 - q^2, 2 * q), 2Ο)
# Assume failure
vβ = [NaN, NaN, NaN]
vβ = vβ
rβ = (NaN, NaN)
if m == zero(m) # single revolution
xββ = Tβ * Ξ΄T / 4/ T
if Ξ΄T > zero(Ξt)
xβ = xββ
else
xββ = Ξ΄T / (4 - Ξ΄T)
xββ = -β(-Ξ΄T / (T + Tβ/2))
# TODO potential bug, see https://github.com/rodyo/FEX-Lambert/issues/1
W = xββ + 1.7 * β(2 - phr/Ο) # one of these is right! (1)
# W = xββ + 1.7 * β(2 - Ξ΄β/Ο) # is it this one? (2)
if W β₯ zero(W)
xββ = xββ
else
xββ = xββ + ((-W)^(1/16) * (xββ - xββ)) # one of these is right! (1)
# xββ = xββ + (-W^(1/16) * (xββ - xββ)) # is it this one? (2)
end
Ξ» = 1 + xββ * (1 + xββ)/2 - 0.03 * xββ^2 * β(1 + xββ)
xβ = Ξ» * xββ
end
# Check if solution can't be found
if xβ < -one(xβ)
@error "Unable to find solution."
return error_output
end
else
# Minumum βT(x)
xMΟ = 4 / (3Ο * (2m + 1))
if phr < Ο
xMβ = xMΟ * (phr / Ο)^(1/8)
elseif phr > Ο
xMβ = xMΟ * (2 - (2 - phr/Ο)^(1/8))
else
xMβ = zero(xMΟ)
end
# Halley's method
xM = xMβ
βT = Inf
iter = 0
while abs(βT) > tolerance
iter += 1
_, βT, βΒ²T, βΒ³T = LancasterBlanchard(xM, q, m)
xMp = xM
xM = xM - 2 * βT .* βΒ²T ./ (2 * βΒ²T.^2 - βT .* βΒ³T)
if mod(iter, 7) != 0
xM = (xMp + xM)/2
end
if iter > max_iter
@error "Unable to find solution."
return error_output
end
end
# xM should be elliptic: xM β (-1, 1)
if xM < -one(xM) || xM > one(xM)
@error "Unable to find solution."
return error_output
end
# Corresponding time
TM = first(LancasterBlanchard(xM, q, m))
# Check that T > minimum
if TM > T
@error "Unable to find solution."
return error_output
end
# Move onto initial values for second solution!
# Initial values
TmTM = T - TM
T0mTM = Tβ - TM
_, βT, βΒ²T, __ = LancasterBlanchard(xM, q, m)
# First estimate if m > 0
if branch == :left
x = β(TmTM / (βΒ²T/2 + TmTM / (1 - xM)^2))
W = xM + x
W = 4 * W / (4 + TmTM) + (1 - W)^2
xβ = x * (1 - (1 + m + (Ξ΄β - 1/2)) /
(1 + 0.15m) * x * (W/2 + 0.03x * βW)) + xM
if xβ > one(xβ)
@error "Unable to find solution."
return error_output
end
else # Second estimate if m > 0
if Ξ΄T > zero(Ξ΄T)
xβ = xM - β(TM / (βΒ²T/2 - TmTM * (βΒ²T/2/T0mTM - 1/xM^2)))
else
xββ = Ξ΄T / (4 - Ξ΄T)
W = xββ + 1.7 * βComplex(2 * (1 - phr))
if real(W) β₯ zero(real(W))
xββ = xββ
else
xββ = xββ - β((-W)^(1/8)) * (xββ + β(-Ξ΄T / (1.5*Tβ - Ξ΄T)))
end
W = 4 / (4 - Ξ΄T)
Ξ» = (1 + (1 + m + 0.24*(Ξ΄β - 1/2)) /
(1 + 0.15m) * xββ * (W/2 - 0.03xββ * β(W)))
xβ = xββ * Ξ»
end
if real(xβ) < -one(real(xβ))
@error "Unable to find solution."
return error_output
end
end
end
# Finally, find root of Lancaster & Blancard's function
# Halley's method
x = xβ
Tβ = Inf
iter = 0
while abs(Tβ) > tolerance
iter += 1
Tβ, βT, βΒ²T, _ = LancasterBlanchard(x, q, m)
# Find the root of the difference between Tβ and
# required time T
Tβ = Tβ - T
# New value of x
xβ = x
x = x - 2 * Tβ * βT ./ (2 * βT^2 - Tβ * βΒ²T)
if mod(iter, 7) != 0
x = (xβ + x) / 2
end
if iter > max_iter
@error "Unable to find solution."
return error_output
end
end
# Calculate terminal velocities
# Constants
Ξ³ = β(ΞΌ * s/2)
if c == zero(c)
Ο = one(x)
Ο = zero(x)
z = abs(x)
else
Ο = 2 * β(rβ*rβ / c^2) * sin(Ξ΄β/2)
Ο = (rβ - rβ) / c
z = β(1 + q^2 * (x^2 - 1))
end
# Radial component
vα΅£β = Ξ³ * ((q * z - x) - Ο * (q * z + x)) / rβ
vα΅£β = -Ξ³ * ((q * z - x) + Ο * (q * z + x)) / rβ
vΜ²α΅£β = vα΅£β * rΜβ
vΜ²α΅£β = vα΅£β * rΜβ
# Tangential component
vββ = Ο * Ξ³ * (z + q*x) / rβ
vββ = Ο * Ξ³ * (z + q*x) / rβ
vΜ²ββ = vββ * tΜβ
vΜ²ββ = vββ * tΜβ
# Cartesian velocity
vΜ²β = vΜ²ββ .+ vΜ²α΅£β
vΜ²β = vΜ²ββ .+ vΜ²α΅£β
if output_extrema == Val{true}
# Find min / max distances
a = s/2 / (1 - x^2)
rβ = minmax_distances(rΜ²β, rΜ²β, rβ, rβ, Ξ΄β, a, vΜ²β, vΜ²β, m, ΞΌ)
return vΜ²β, vΜ²β, rβ
else
return vΜ²β, vΜ²β
end
end
"""
The following code was converted to Julia, from a [GitHub repository](https://github.com/rodyo/FEX-Lambert)
that hosts a MATLAB implementation. At the time of writing, this respository has a BSD license. I'm providing the copyright notice here, as instructed by the license text.
```
Copyright (c) 2018, Rody Oldenhuis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of this project.
```
"""
function lambert(r1vec, r2vec, tf, m, muC)
# original documentation:
#=
This routine implements a new algorithm that solves Lambert's problem. The
algorithm has two major characteristics that makes it favorable to other
existing ones.
1) It describes the generic orbit solution of the boundary condition
problem through the variable X=log(1+cos(alpha/2)). By doing so the
graph of the time of flight become defined in the entire real axis and
resembles a straight line. Convergence is granted within few iterations
for all the possible geometries (except, of course, when the transfer
angle is zero). When multiple revolutions are considered the variable is
X=tan(cos(alpha/2)*pi/2).
2) Once the orbit has been determined in the plane, this routine
evaluates the velocity vectors at the two points in a way that is not
singular for the transfer angle approaching to pi (Lagrange coefficient
based methods are numerically not well suited for this purpose).
As a result Lambert's problem is solved (with multiple revolutions
being accounted for) with the same computational effort for all
possible geometries. The case of near 180 transfers is also solved
efficiently.
We note here that even when the transfer angle is exactly equal to pi
the algorithm does solve the problem in the plane (it finds X), but it
is not able to evaluate the plane in which the orbit lies. A solution
to this would be to provide the direction of the plane containing the
transfer orbit from outside. This has not been implemented in this
routine since such a direction would depend on which application the
transfer is going to be used in.
please report bugs to [email protected]
=#
# adjusted documentation:
#=
By default, the short-way solution is computed. The long way solution
may be requested by giving a negative value to the corresponding
time-of-flight [tf].
For problems with |m| > 0, there are generally two solutions. By
default, the right branch solution will be returned. The left branch
may be requested by giving a negative value to the corresponding
number of complete revolutions [m].
=#
# Authors
# .-`-.-`-.-`-.-`-.-`-.-`-.-`-.-`-.-`-.-`-.-`-.-`-.-`-.-`-.-`-.
# Name : Dr. Dario Izzo
# E-mail : [email protected]
# Affiliation: ESA / Advanced Concepts Team (ACT)
# Made more readible and optimized for speed by Rody P.S. Oldenhuis
# Code available in MGA.M on http://www.esa.int/gsp/ACT/inf/op/globopt.htm
# last edited 12/Dec/2009
# ADJUSTED FOR EML-COMPILATION 24/Dec/2009
# initial values
tol = 1e-14; bad = false; days = 86400;
# work with non-dimensional units
r1 = sqrt(dot(r1vec, r1vec)); r1vec = r1vec/r1;
V = sqrt(muC/r1); r2vec = r2vec/r1;
T = r1/V; tf = tf*days/T; # also transform to seconds
# relevant geometry parameters (non dimensional)
mr2vec = sqrt(dot(r2vec, r2vec));
# make 100# sure it's in (-1 <= dth <= +1)
dth = acos( max(-1, min(1, (dot(r1vec, r2vec))/mr2vec)) );
# decide whether to use the left or right branch (for multi-revolution
# problems), and the long- or short way
leftbranch = sign(m); longway = sign(tf);
m = abs(m); tf = abs(tf);
if (longway < 0)
dth = 2*pi - dth
end
# derived quantities
c = sqrt(1 + mr2vec^2 - 2*mr2vec*cos(dth)); # non-dimensional chord
s = (1 + mr2vec + c)/2; # non-dimensional semi-perimeter
a_min = s/2; # minimum energy ellipse semi major axis
Lambda = sqrt(mr2vec)*cos(dth/2)/s; # lambda parameter (from BATTIN's book)
crossprd = [r1vec[2]*r2vec[3] - r1vec[3]*r2vec[2],
r1vec[3]*r2vec[1] - r1vec[1]*r2vec[3], # non-dimensional normal vectors
r1vec[1]*r2vec[2] - r1vec[2]*r2vec[1]];
mcr = sqrt(dot(crossprd, crossprd)); # magnitues thereof
nrmunit = crossprd/mcr; # unit vector thereof
# Initial values
# ---------------------------------------------------------
# ELMEX requires this variable to be declared OUTSIDE the IF-statement
logt = log(tf); # avoid re-computing the same value
# single revolution (1 solution)
if (m == 0)
# initial values
inn1 = -0.5233; # first initial guess
inn2 = +0.5233; # second initial guess
x1 = log(1 + inn1);# transformed first initial guess
x2 = log(1 + inn2);# transformed first second guess
# multiple revolutions (0, 1 or 2 solutions)
# the returned soltuion depends on the sign of [m]
else
# select initial values
if (leftbranch < 0)
inn1 = -0.5234; # first initial guess, left branch
inn2 = -0.2234; # second initial guess, left branch
else
inn1 = +0.7234; # first initial guess, right branch
inn2 = +0.5234; # second initial guess, right branch
end
x1 = tan(inn1*pi/2);# transformed first initial guess
x2 = tan(inn2*pi/2);# transformed first second guess
end
# since (inn1, inn2) < 0, initial estimate is always ellipse
xx = [inn1, inn2]; aa = a_min ./ (1 .- xx.^2);
bbeta = longway * 2*asin.(sqrt.((s-c) / 2 ./ aa));
# make 100.4# sure it's in (-1 <= xx <= +1)
aalfa = 2*acos.( max.(-1, min.(1, xx)) );
# evaluate the time of flight via Lagrange expression
y12 = @. aa.*sqrt(aa).*((aalfa - sin(aalfa)) - (bbeta-sin(bbeta)) + 2*pi*m);
# initial estimates for y
if m == 0
y1 = log(y12[1]) - logt;
y2 = log(y12[2]) - logt;
else
y1 = y12[1] - tf;
y2 = y12[2] - tf;
end
# Solve for x
# ---------------------------------------------------------
# Newton-Raphson iterations
# NOTE - the number of iterations will go to infinity in case
# m > 0 and there is no solution. Start the other routine in
# that case
err = Inf; iterations = 0; xnew = 0;
while (err > tol)
# increment number of iterations
iterations = iterations + 1;
# new x
xnew = (x1*y2 - y1*x2) / (y2-y1);
# copy-pasted code (for performance)
if m == 0
x = exp(xnew) - 1;
else
x = atan(xnew)*2/pi;
end
a = a_min/(1 - x^2);
if (x < 1) # ellipse
beta = longway * 2*asin(sqrt((s-c)/2/a));
# make 100.4# sure it's in (-1 <= xx <= +1)
alfa = 2*acos( max(-1, min(1, x)) );
else # hyperbola
alfa = 2*acosh(x);
beta = longway * 2*asinh(sqrt((s-c)/(-2*a)));
end
# evaluate the time of flight via Lagrange expression
if (a > 0)
tof = a*sqrt(a)*((alfa - sin(alfa)) - (beta-sin(beta)) + 2*pi*m);
else
tof = -a*sqrt(-a)*((sinh(alfa) - alfa) - (sinh(beta) - beta));
end
# new value of y
if m ==0
ynew = log(tof) - logt;
else
ynew = tof - tf;
end
# save previous and current values for the next iterarion
# (prevents getting stuck between two values)
x1 = x2; x2 = xnew;
y1 = y2; y2 = ynew;
# update error
err = abs(x1 - xnew);
# escape clause
if (iterations > 15)
bad = true; break;
end
end
# If the Newton-Raphson scheme failed, try to solve the problem
# with the other Lambert targeter.
if bad
# NOTE: use the original, UN-normalized quantities
_branch = leftbranch > 0 ? :left : :right
_traj = longway > 0 ? :long : :short
_m = m
V1, V2, extremal_distances = lambert_lancaster_blanchard(
r1vec*r1, r2vec*r1, tf*T, muC;
revolutions = _m,
branch = _branch,
trajectory = _traj,
output_extrema = Val{true});
return V1, V2, extremal_distances, 1
end
# convert converged value of x
if m==0
x = exp(xnew) - 1;
else
x = atan(xnew)*2/pi;
end
#=
The solution has been evaluated in terms of log(x+1) or tan(x*pi/2), we
now need the conic. As for transfer angles near to pi the Lagrange-
coefficients technique goes singular (dg approaches a zero/zero that is
numerically bad) we here use a different technique for those cases. When
the transfer angle is exactly equal to pi, then the ih unit vector is not
determined. The remaining equations, though, are still valid.
=#
# Solution for the semi-major axis
a = a_min/(1-x^2);
# Calculate psi
if (x < 1) # ellipse
beta = longway * 2*asin(sqrt((s-c)/2/a));
# make 100.4# sure it's in (-1 <= xx <= +1)
alfa = 2*acos( max(-1, min(1, x)) );
psi = (alfa-beta)/2;
eta2 = 2*a*sin(psi)^2/s;
eta = sqrt(eta2);
else # hyperbola
beta = longway * 2*asinh(sqrt((c-s)/2/a));
alfa = 2*acosh(x);
psi = (alfa-beta)/2;
eta2 = -2*a*sinh(psi)^2/s;
eta = sqrt(eta2);
end
# unit of the normalized normal vector
ih = longway * nrmunit;
# unit vector for normalized [r2vec]
r2n = r2vec/mr2vec;
# cross-products
# don't use cross() (emlmex() would try to compile it, and this way it
# also does not create any additional overhead)
crsprd1 = [ih[2]*r1vec[3]-ih[3]*r1vec[2],
ih[3]*r1vec[1]-ih[1]*r1vec[3],
ih[1]*r1vec[2]-ih[2]*r1vec[1]];
crsprd2 = [ih[2]*r2n[3]-ih[3]*r2n[2],
ih[3]*r2n[1]-ih[1]*r2n[3],
ih[1]*r2n[2]-ih[2]*r2n[1]];
# radial and tangential directions for departure velocity
Vr1 = 1/eta/sqrt(a_min) * (2*Lambda*a_min - Lambda - x*eta);
Vt1 = sqrt(mr2vec/a_min/eta2 * sin(dth/2)^2);
# radial and tangential directions for arrival velocity
Vt2 = Vt1/mr2vec;
Vr2 = (Vt1 - Vt2)/tan(dth/2) - Vr1;
# terminal velocities
V1 = (Vr1*r1vec + Vt1*crsprd1)*V;
V2 = (Vr2*r2n + Vt2*crsprd2)*V;
# exitflag
exitflag = 1; # (success)
# also compute minimum distance to central body
# NOTE: use un-transformed vectors again!
extremal_distances = minmax_distances(r1vec*r1, r2vec*r1, r1, mr2vec*r1, dth, a*r1, V1, V2, m, muC);
return V1, V2, extremal_distances, exitflag
end
"""
Wrapper for Unitful inputs.
"""
function lambert(r1::AbstractVector{<:Unitful.Length}, r2::AbstractVector{<:Unitful.Length}, tf::Unitful.Time, m::Integer, mu::MassParameter)
v1, v2, ex, fl = lambert(
ustrip.(u"km", r1),
ustrip.(u"km", r2),
ustrip.(u"d", tf),
m,
ustrip.(u"km^3/s^2", mu)
)
return v1 .* u"km/s", v2 .* u"km/s", ex .* u"km", fl
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 6472 | #
# Provides Restricted Two-body Problem equations
#
"""
Returns the conic section, as specified by eccentricity `e`.
"""
function conic(e::T) where T<:Real
!isnan(e) || throw(ArgumentError("Provided eccentricity is not a number (NaN)."))
if e β zero(T)
return Circular
elseif e β one(T)
return Parabolic
elseif zero(T) < e && e < one(T)
return Elliptical
elseif e > one(T)
return Hyperbolic
else
throw(ArgumentError("Provided eccentricity, $e, is not valid."))
end
end
"""
Returns a Keplarian representation of a Cartesian orbital state.
Algorithm taught in ENAE601.
"""
function keplerian(rα΅’, vα΅’, ΞΌ)
safe_acos(num) = isapprox(num, one(num)) ?
acos(one(num)) :
isapprox(num, -one(num)) ?
acos(-one(num)) :
acos(num)
iΜ = SVector{3}(1, 0, 0)
jΜ = SVector{3}(0, 1, 0)
kΜ = SVector{3}(0, 0, 1)
hΜ
= specific_angular_momentum_vector(rα΅’, vα΅’)
a = semimajor_axis(norm(rα΅’), norm(vα΅’), ΞΌ)
nΜ
= kΜ Γ specific_angular_momentum_vector(rα΅’, vα΅’)
eΜ
= eccentricity_vector(rα΅’, vα΅’, ΞΌ)
e = norm(eΜ
)
i = safe_acos((hΜ
β
kΜ) / norm(hΜ
))
Ξ© = ustrip(nΜ
β
jΜ) > 0 ?
safe_acos((nΜ
β
iΜ) / norm(nΜ
)) :
2Ο - safe_acos((nΜ
β
iΜ) / norm(nΜ
))
Ο = ustrip(eΜ
β
kΜ) > 0 ?
safe_acos((nΜ
β
eΜ
) / (norm(nΜ
) * e)) :
2Ο - safe_acos((nΜ
β
eΜ
) / (norm(nΜ
) * e))
Ξ½ = ustrip(rα΅’ β
vα΅’) > 0 ?
safe_acos((eΜ
β
rα΅’) / (e * norm(rα΅’))) :
2Ο - safe_acos((eΜ
β
rα΅’) / (e * norm(rα΅’)))
return upreferred(e), a, i, Ξ©, Ο, Ξ½
end
"""
Returns a Cartesian representation of a Keplerian two-body orbital state
in an inertial frame, centered at the center of mass of the central body.
Algorithm taught in ENAE601.
"""
function cartesian(e, a, i, Ξ©, Ο, Ξ½, ΞΌ)
rα΅’, vα΅’ = spatial(i, Ξ©, Ο, perifocal(a, e, Ξ½, ΞΌ)...)
return rα΅’, vα΅’
end
"""
Returns a spatial representation of the provied Perifocal state.
"""
function spatial(i, Ξ©, Ο, rβ, vβ)
# Set up Perifocal βΆ Cartesian conversion
R_3Ξ© = SMatrix{3,3}(
[cos(Ξ©) -sin(Ξ©) 0.;
sin(Ξ©) cos(Ξ©) 0.;
0. 0. 1.])
R_1i = SMatrix{3,3}(
[1. 0. 0.;
0. cos(i) -sin(i);
0. sin(i) cos(i)])
R_3Ο = SMatrix{3,3}(
[cos(Ο) -sin(Ο) 0.
sin(Ο) cos(Ο) 0.
0. 0. 1.])
α΄΅Tβ = R_3Ξ© * R_1i * R_3Ο
return α΄΅Tβ * rβ, α΄΅Tβ * vβ
end
"""
Returns position and velocity vectors in the Perifocal frame.
"""
function perifocal(a, e, Ξ½, ΞΌ)
p = semi_parameter(a, e)
r = distance(p, e, Ξ½)
PΜ=SVector{3, Float64}(1, 0, 0)
QΜ=SVector{3, Float64}(0, 1, 0)
# WΜ=SVector{3, Float64}(0, 0, 1)
rβ = (r * cos(Ξ½) .* PΜ .+ r * sin(Ξ½) .* QΜ)
vβ = β(ΞΌ/p) * ((-sin(Ξ½) * PΜ) .+ ((e + cos(Ξ½)) .* QΜ))
return rβ, vβ
end
function perifocal(i, Ξ©, Ο, rα΅’, vα΅’)
# Set up Cartesian βΆ Perifocal conversion
R_3Ξ© = SMatrix{3,3}(
[cos(Ξ©) -sin(Ξ©) 0.;
sin(Ξ©) cos(Ξ©) 0.;
0. 0. 1.])
R_1i = SMatrix{3,3}(
[1. 0. 0.;
0. cos(i) -sin(i);
0. sin(i) cos(i)])
R_3Ο = SMatrix{3,3}(
[cos(Ο) -sin(Ο) 0.
sin(Ο) cos(Ο) 0.
0. 0. 1.])
α΅Tα΅’ = inv(R_3Ξ© * R_1i * R_3Ο)
return α΅Tα΅’*rα΅’, α΅Tα΅’*vα΅’
end
"""
Returns semimajor axis parameter, a.
"""
semimajor_axis(r, v, ΞΌ) = inv( (2 / r) - (v^2 / ΞΌ) )
"""
Returns specific angular momentum vector, hΜ
.
"""
specific_angular_momentum_vector(rα΅’, vα΅’) = rα΅’ Γ vα΅’
"""
Returns scalar specific angular momentum vector, h.
"""
specific_angular_momentum(rα΅’, vα΅’) = norm(specific_angular_momentum_vector(rα΅’, vα΅’))
"""
Returns specific orbital energy, Ο΅.
"""
specific_energy(a, ΞΌ) = ( -ΞΌ / (2 * a) )
specific_energy(r, v, ΞΌ) = (v^2 / 2) - (ΞΌ / r)
"""
Returns C3 value.
"""
C3(r, v, ΞΌ) = v^2 - 2ΞΌ/r
"""
Returns vβ.
"""
v_infinity(r, v, ΞΌ) = βC3(r, v, ΞΌ)
"""
Returns potential energy for an orbit about a `RestrictedTwoBodySystem`.
"""
specific_potential_energy(r, ΞΌ) = (ΞΌ/r)
specific_potential_energy(r, ΞΌ, R, Jβ, Ο) = (ΞΌ/r) * (1 - Jβ * (R/r)^2 * ((3/2) * (sin(Ο))^2 - (1/2)))
"""
Returns orbital eccentricity vector eΜ
.
"""
function eccentricity_vector(rα΅’, vα΅’, ΞΌ)
return map(x-> abs(x) < eps(typeof(x)) ? zero(x) : x, (1 / ΞΌ) * ((vα΅’ Γ specific_angular_momentum_vector(rα΅’, vα΅’)) - ΞΌ * rα΅’ / norm(rα΅’)))
end
"""
Returns orbital eccentricity, e.
"""
eccentricity(rα΅’, vα΅’, ΞΌ) = norm(eccentricity_vector(rα΅’, vα΅’, ΞΌ)) |> upreferred
"""
Returns semilatus parameter, p.
"""
semi_parameter(a, e) = a * (1 - e^2)
"""
Returns distance, r.
"""
distance(p, e, Ξ½) = upreferred(p / (1 + e * cos(Ξ½)))
"""
Returns instantaneous velocity, v, for any orbital representation.
"""
speed(r, a, ΞΌ) = upreferred(β( (2 * ΞΌ / r) - (ΞΌ / a)))
"""
Returns the instantaneous velocity, `v`, for any orbital representation.
"""
speed(p, e, Ξ½, a, ΞΌ) = speed(distance(p,e,Ξ½), a, ΞΌ)
"""
Returns periapsis distance, rβ.
"""
periapsis_radius(a, e) = a * (1 - e)
"""
Returns apoapsis distance, rβ.
"""
apoapsis_radius(a, e) = a * (1 + e)
"""
Returns the orbital period.
"""
period(a, ΞΌ) = 2Ο * β(upreferred(a^3 / ΞΌ))
"""
Returns true anomoly, Ξ½.
"""
function true_anomoly(r, h, e, ΞΌ)
val = (h^2 - ΞΌ * r) / (ΞΌ * r * e)
acos(isapprox(val, one(val)) ? one(val) : val)
end
"""
Returns mean motion, n.
"""
mean_motion(a, ΞΌ) = β(ΞΌ / a^3)
"""
Returns time since periapsis, t.
"""
time_since_periapsis(n, e, E) = (E - e * sin(E)) / (n)
"""
Sphere of influence.
"""
SOI(a, m, M) = a * (m / M)^(2/5)
"""
Sphere of activity.
"""
SOA(a, m, M) = a * (m / 3M)^(1/3)
"""
Computes a Hohmann transfer, and returns the departure and
arrival velocity vectors.
"""
function hohmann(rβ, rβ, ΞΌ)
vβ = β((2ΞΌ/rβ) - (2ΞΌ/(rβ+rβ)))
vβ = β((2ΞΌ/rβ) - (2ΞΌ/(rβ+rβ)))
return vβ, vβ
end
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 848 | """
A module which provides types, and transformations
for provided and user-provided orbital frames, e.g.
Earth-Centered-Inertial, Heliocentric-Inertial,
Synodic.
# Extended help
**Exports**
$(EXPORTS)
**Imports**
$(IMPORTS)
"""
module CoordinateFrames
# Frames
export OrbitalFrame, Inertial, Rotating
export BodycentricInertial, BarycentricInertial
export BodycentricRotating, BarycentricRotating
export isinertial, isrotating, isbodycentric, isbarycentric
export @frame
# Transforms
export AstrodynamicsTransform
export Transform
using Unitful
using DocStringExtensions
using CoordinateTransformations
@template (FUNCTIONS, METHODS, MACROS) =
"""
$(SIGNATURES)
$(DOCSTRING)
"""
@template (TYPES, CONSTANTS) =
"""
$(TYPEDEF)
$(DOCSTRING)
"""
include("Frames.jl")
include("Transforms.jl")
end # module
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 2780 | #
# Provides default frames, and the means for users to create their own.
#
"""
$(TYPEDEF)
A `supertype` for all coordinate frames used in space.
"""
abstract type OrbitalFrame end
"""
$(TYPEDEF)
A `supertype` for all inertial coordinate frames in space.
"""
abstract type Inertial <: OrbitalFrame end
"""
$(TYPEDEF)
A `supertype` for all bodycentric-inertial coordinate frames in space.
"""
abstract type BodycentricInertial <: Inertial end
"""
$(TYPEDEF)
A `supertype` for all barycentric-ineretial coordinate frames in space.
"""
abstract type BarycentricInertial <: Inertial end
"""
$(TYPEDEF)
A `supertype` for all rotating coordinate frames in space.
"""
abstract type Rotating <: OrbitalFrame end
"""
$(TYPEDEF)
A `supertype` for all bodycentric-rotating coordinate frames in space.
"""
abstract type BodycentricRotating <: Rotating end
"""
$(TYPEDEF)
A `supertype` for all barycentric-rotating coordinate frames in space.
"""
abstract type BarycentricRotating <: Rotating end
"""
$(SIGNATURES)
Returns `true` or `false` to indicate whether the provided frame is `Inertial`.
"""
isinertial(::Type{T}) where T <: OrbitalFrame = T <: Inertial
"""
$(SIGNATURES)
Returns `true` or `false` to indicate whether the provided frame is `Rotating`.
"""
isrotating(::Type{T}) where T <: OrbitalFrame = T <: Rotating
"""
$(SIGNATURES)
Returns `true` or `false` to indicate whether the provided frame is bodycentric.
"""
isbodycentric(::Type{T}) where T <: OrbitalFrame = T <: Union{<:BodycentricInertial, BodycentricRotating}
"""
$(SIGNATURES)
Returns `true` or `false` to indicate whether the provided frame is barycentric.
"""
isbarycentric(::Type{T}) where T <: OrbitalFrame = T <: Union{<:BarycentricInertial, BarycentricRotating}
"""
$(SIGNATURES)
A simple convenience macro for defining new coordinate frames in space.
Creates a new `abstract` sub-type of the final argument, `property`.
# Extended Help
**Usage**
`@frame <name>`
`@frame <name> is <property>`
Here, `<property>` is previously defined `OrbitalFrame`.
which must all be subtypes of `OrbitalFrames.OrbitalFrame`.
By using the shortened syntax, `@frame <name>`, your new `abstract`
type `<name>` will only have `OrbitalFrames.OrbitalFrame` as
a `supertype`.
**Examples**
```julia
@frame AbstractFrame # second argument defaults to the top-level `OrbitalFrame`
@frame EarthCenteredInertial is BodycentricInertial
@frame SunEarthSynodic is BarycentricInertial
```
"""
macro frame(name)
quote
abstract type $name <: $OrbitalFrame end
end
end
macro frame(name, _is, super)
@assert :($_is) == :is "Incorrect Usage! Use `is` as the second argument. For example: `@frame ECI is BodycentricInertialFrame`."
quote
abstract type $name <: $super end
end
end
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1233 | #
# Provides default transforms, and the means for users to create their own.
#
"""
$(TYPEDEF)
A `supertype` for all astrodynamics coordinate frame transformations.
"""
abstract type OrbitalFrameTransform end # should this be a subtype of CoordinateTransformations.Transformation?
"""
$(TYPEDEF)
A generic frame transformation between two `OrbitalFrame` types.
Converts `F1` to`F2`.
$(TYPEDFIELDS)
"""
struct Transform{F1<:OrbitalFrame, F2<:OrbitalFrame, T1<:CoordinateTransformations.Transformation, T2<:CoordinateTransformations.Transformation} <: OrbitalFrameTransform
transform_position::T1
transform_velocity::T2
end
"""
$(SIGNATURES)
An outer constructor for `Transform` instances.
Provide position and velocity transformations,
and the initial and final reference frames via
function arguments. This is an alternate syntax
for `Transform{InitialFrame, FinalFrame}(position_transform, velocity_transform)`.
"""
function Transform(position_transform::CoordinateTransformations.Transformation, velocity_transform::CoordinateTransformations.Transformation, from::F1, to::F2) where {F1 <: OrbitalFrameTransform, F2 <: OrbitalFrameTransform}
return Transform{F1, F2}(position_transform, velocity_transform)
end
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 4854 | #
# Iterative Halo orbit and manifold solvers
#
"""
Returns the Monodromy Matrix for a Halo orbit.
"""
function monodromy(orbit::CR3BPOrbit, T; verify=true, reltol = 1e-14, abstol = 1e-14)
initial = Orbit(CartesianStateWithSTM(state(orbit)), system(orbit), epoch(orbit); frame=frame(orbit))
final = propagate(initial, T; reltol=reltol, abstol=abstol, save_everystep=false)[end]
if verify && !(state(initial)[1:6] β final[1:6])
throw(ErrorException("The provided `orbit` is not periodic!"))
end
SMatrix{6,6}(final[7:end]...) |> Matrix
end
"""
Returns true if a `RestrictedThreeBodySystem` is numerically periodic.
"""
function isperiodic(orbit::CR3BPOrbit, T; reltol = 1e-14, abstol = 1e-14)
final = propagate(orbit, T; reltol=reltol, abstol=abstol, save_everystep=false)[end]
return state(orbit)[1:6] β final[1:6]
end
"""
Returns a numerical solution for a Halo orbit about `L`.
__Arguments:__
- `ΞΌ`: Non-dimensional mass parameter for the CR3BP system.
- `Az`: Desired non-dimensional Z-amplitude for Halo orbit.
- `Ο`: Desired Halo orbit phase.
- `L`: Lagrange point to orbit (L1 or L2).
- `hemisphere`: Specifies northern or southern Halo orbit.
__Outputs:__
- Tuple of initial states: `(r, v)` where `r::Vector{<:AbstractFloat}`, `v::Vector{<:Abstractfloat}`.
- Throws `ArgumentError` if L is not `:L1` or `:L2`
__References:__
The iterative scheme was pulled from directly from literature
and sample code, including Rund 2018,
and Dr. Mireles' lecture notes and EarthSunHaloOrbit_NewtonMewhod.m
file available on their website.
Specifically, the half-period iterative scheme (the `F` matrix
in the source code, and corresponding "next guess" computation)
was ported __directly__ from Dr. Mireles' public code and notes, which are
available online.
- [Dr. Mireles Notes](http://cosweb1.fau.edu/~jmirelesjames/hw5Notes.pdf)
- [Dr. Mireles Code](http://cosweb1.fau.edu/~jmirelesjames/notes.html)
- [Rund, 2018](https://digitalcommons.calpoly.edu/theses/1853/).
"""
function halo(ΞΌ; Az=0.0, L=1, hemisphere=:northern,
tolerance=1e-8, max_iter=100,
reltol=1e-14, abstol=1e-14,
nan_on_fail = true, disable_warnings = false)
rβ, vβ, Ξ€ = analyticalhalo(ΞΌ; Az=Az, Ο=0.0, L=L, hemisphere=hemisphere)
rβ = rβ[1,:]
vβ = vβ[1,:]
Ο = Ξ€/2
Ξ΄u = Vector{typeof(Ο)}(undef, 6)
Id = Matrix(I(6))
for i β 1:max_iter
problem = ODEProblem(
CR3BPFunction(; stm=true),
vcat(rβ, vβ, Id...),
(0.0, Ο),
(ΞΌ,)
)
retcode, rβ, vβ, Ξ¦ = let
sols = solve(problem, Vern9(); reltol=reltol, abstol=abstol)
final = sols.u[end]
sols.retcode, final[1:3], final[4:6], SMatrix{6,6}(final[7:end]...)
end
CR3BPFunction()(Ξ΄u, vcat(rβ, vβ), (ΞΌ,), NaN)
βvβ = Ξ΄u[4:6]
# All code in this `if, else, end` block is ported from
# Dr. Mireles' MATLAB code, which is available on his
# website: http://cosweb1.fau.edu/~jmirelesjames/notes.html.
# Lecture notes, which describe this algorithm further,
# are available for reference as well:
# http://cosweb1.fau.edu/~jmirelesjames/hw5Notes.pdf
if Az β 0
F = @SMatrix [
Ξ¦[4,1] Ξ¦[4,5] βvβ[1];
Ξ¦[6,1] Ξ¦[6,5] βvβ[3];
Ξ¦[2,1] Ξ¦[2,5] vβ[2]
]
xα΅ͺ = SVector(rβ[1], vβ[2], Ο) - inv(F) * SVector(vβ[1], vβ[3], rβ[2])
rβ[1] = xα΅ͺ[1]
vβ[2] = xα΅ͺ[2]
Ο = xα΅ͺ[3]
else
F = @SMatrix [
Ξ¦[4,3] Ξ¦[4,5] βvβ[1];
Ξ¦[6,3] Ξ¦[6,5] βvβ[3];
Ξ¦[2,3] Ξ¦[2,5] vβ[2]
]
xα΅ͺ = SVector(rβ[3], vβ[2], Ο) - inv(F) * SVector(vβ[1], vβ[3], rβ[2])
rβ[3] = xα΅ͺ[1]
vβ[2] = xα΅ͺ[2]
Ο = xα΅ͺ[3]
end
if abs(vβ[1]) β€ tolerance && abs(vβ[3]) β€ tolerance
break;
elseif Ο > 5 * one(Ο)
error("Unreasonably large halo period, $Ο, ending iterations.")
elseif i == max_iter
error("Desired tolerance was not reached, and iterations have hit the maximum number of iterations: $max_iter.")
end
end
return rβ, vβ, 2Ο
end
"""
A `halo` wrapper! Returns a `CircularRestrictedThreeBodyOrbit`.
Returns a tuple: `halo_orbit, halo_period`.
"""
function halo(sys::CR3BPParameters, epoch=TAIEpoch(now()); Az=0.0, kwargs...)
if Az isa Unitful.Length
Az = Az / lengthunit(sys)
end
r,v,T = halo(massparameter(sys); Az = Az, kwargs...)
cart = CartesianState(vcat(r,v); lengthunit=lengthunit(sys), timeunit=timeunit(sys), angularunit=angularunit(sys))
orbit = Orbit(cart, sys)
return (; orbit=orbit, period=T)
end
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 11418 | #
# Invariant manifolds in the CR3BP
#
"""
An alias for some abstract `EnsembleSolution`
with `States` state vector and parameter
vector types.
"""
const AbstractOrbitalEnsembleSolution = SciMLBase.AbstractEnsembleSolution{T,N,<:AbstractVector{U}} where {T,N,U<:Trajectory}
"""
An wrapper for a `SciMLBase.ODESolution` with a `GeneralAstrodynamics.States.AbstractState`
state vector type. This represents a `Manifold` in space!
"""
struct Manifold{FR, S, P, E, O<:AbstractOrbitalEnsembleSolution}
solution::O
end
"""
Returns the `solution` for the `Manifold`. Typically,
this is a `DifferentialEquations.ODESolution`.
"""
solution(man::Manifold) = man.solution
"""
Returns the system associated with the `Manifold`.
"""
States.system(man::Manifold) = solution(man).u[1].solution.prob.p
"""
The `length` of a `Manifold`.
"""
Base.length(man::Manifold) = length(solution(man).u)
"""
Returns the last index of a `Manifold`.
"""
Base.lastindex(man::Manifold) = length(man)
"""
Calls the underlying `solution`'s `getindex` function
to return the `CartesianState` of the `Manifold`
at time `t` past the `initialepoch`.
"""
Base.getindex(man::Manifold, args...) = getindex(solution(man), args...)
"""
The `size` of a `Manifold`.
"""
Base.size(man::Manifold) = size(solution(man))
"""
Returns the `OrbitalFrame` of the `Manifold`.
"""
Base.@pure States.frame(::Manifold{FR}) where FR = FR
"""
Returns the length unit for the `Trajectory`.
"""
States.lengthunit(man::Manifold) = lengthunit(solution(man).u[1])
"""
Returns the time unit for the `Trajectory`.
"""
States.timeunit(man::Manifold) = timeunit(solution(man).u[1])
"""
Returns the angular unit for the `Trajectory`.
"""
States.angularunit(man::Manifold) = angularunit(solution(man).u[1])
"""
Returns the velocity unit for the `Trajectory`.
"""
States.velocityunit(man::Manifold) = velocityunit(solution(man).u[1])
"""
Returns the mass unit for the `Manifold`.
"""
States.massunit(man::Manifold) = massunit(system(man))
"""
Returns the mass parameter unit for the `Trajectory`.
"""
States.massparamunit(man::Manifold) = massparamunit(system(man))
"""
Show a `Trajectory`.
"""
function Base.show(io::IO, man::Manifold)
println(io, "Invariant Manifold with $(length(man.solution.u)) trajectories")
end
"""
Calculates the eigenvector associated with the __stable manifold__
of a Monodromy matrix.
"""
function stable_eigenvector(monodromy::AbstractMatrix; atol=1e-6)
evals, evecs = eigen(monodromy)
evals = filter(isreal, evals) .|> real
evecs = filter(x->!isempty(x), map(vec->filter(x->all(isreal.(vec)), vec), eachcol(evecs))) .|> real
imin = findmin(evals)[2]
imax = findmax(evals)[2]
@assert isapprox((evals[imin] * evals[imax]), one(eltype(evals)), atol=atol) "Min and max eigenvalue should be multiplicative inverses. Invalid Monodromy matrix. Product equals $(evals[imin] * evals[imax]), not $(one(eltype(evals)))."
return evecs[imin]
end
"""
Calculates the eigenvector associated with the __unstable manifold__
of a Monodromy matrix.
"""
function unstable_eigenvector(monodromy::AbstractMatrix; atol=1e-6)
evals, evecs = eigen(monodromy)
evals = filter(isreal, evals) .|> real
evecs = filter(x->!isempty(x), map(vec->filter(x->all(isreal.(vec)), vec), eachcol(evecs))) .|> real
imin = findmin(evals)[2]
imax = findmax(evals)[2]
@assert isapprox((evals[imin] * evals[imax]), one(eltype(evals)), atol=atol) "Min and max eigenvalue should be multiplicative inverses. Invalid Monodromy matrix. Product equals $(evals[imin] * evals[imax]), not $(one(eltype(evals)))."
return evecs[imax]
end
"""
Perturbs a `CartesianStateWithSTM` in the direction of an
eigenvector `V`.
"""
function perturb(state::CartesianStateWithSTM, V::AbstractVector; eps = 1e-8)
if length(V) != 6
throw(ArgumentError("Perturbation vector `V` must have length 6. Vector provided has length $(length(V))"))
end
V = normalize(States.get_stm(state) * normalize(V))
r = States.get_r(state) + eps * V[1:3]
v = States.get_v(state) + eps * V[4:6]
return CartesianState(vcat(r,v); lengthunit=lengthunit(state), timeunit=timeunit(state), angularunit=angularunit(state))
end
"""
Returns an orbit perturbed in the direction of the local linearization right-multiplied
by the provided eigenvector `V`. Only available for `Trajectory` instances with
`CartesianStateWithSTM` state types.
"""
function perturb(traj::Trajectory{FR, S}, t, V::AbstractVector; eps=1e-8) where {FR, S<:CartesianStateWithSTM}
cart = perturb(state(traj, t), V; eps=eps)
return Orbit(cart, system(traj), epoch(traj,t))
end
"""
Returns an `EnsembleProblem` which represents perturbations
off of a Halo orbit onto a stable or unstable manifold.
Use `kwarg` `direction=Val{:stable}` or `direction=Val{:unstable}`
to specify whether you want to solve for the stable or unstable
invariant manifold about the provided Halo orbit.
All `kwargs` arguments are passed directly to `DifferentialEquations`
solvers.
"""
function SciMLBase.EnsembleProblem(halo::Trajectory{FR, <:CartesianStateWithSTM} where FR; duration::Number=(solution(halo).t[end] - solution(halo).t[1]), direction=Val{:unstable}, distributed=Val{false}, Trajectory=Val{false}, trajectories=length(traj), eps=1e-8, kwargs...)
if halo[1][1:6] β halo[end][1:6]
throw(ArgumentError("The Halo orbit `Trajectory` provided is not periodic!"))
end
if direction β (Val{:stable}, Val{:unstable})
throw(ArgumentError("Invalid direction provided: $(direction)"))
end
Tβ = solution(halo).t[1]
T = solution(halo).t[end]
dur = duration isa Unitful.Time ? duration / timeunit(halo) : duration
if direction == Val{:stable}
dur *= -1
end
Ξ¦ = monodromy(Orbit(halo, 0), T)
V = direction == Val{:stable} ? stable_eigenvector(Ξ¦) : unstable_eigenvector(Ξ¦)
start = CartesianState(state(halo, 0))
nominal = ODEProblem(Orbit(start, system(halo), initialepoch(halo)), dur; kwargs...)
prob_func = distributed == Val{true} ? DistributedManifoldIteration(halo, V, dur; trajectories=trajectories, eps=eps) : ManifoldIteration(halo, V, dur; trajectories=trajectories, eps=eps)
output_func = Trajectory == Val{true} ? ManifoldTrajectoryOutput(halo) : ManifoldSolutionOutput(halo)
return EnsembleProblem(
nominal; prob_func = prob_func, output_func = output_func, safetycopy = false
)
end
"""
Returns an `EnsembleProblem` which represents perturbations
off of a Halo orbit onto a stable or unstable manifold.
Use `kwarg` `direction=Val{:stable}` or `direction=Val{:unstable}`
to specify whether you want to solve for the stable or unstable
invariant manifold about the provided Halo orbit.
All `kwargs` arguments are passed directly to `DifferentialEquations`
solvers.
"""
function SciMLBase.EnsembleProblem(orbit::Orbit, period::Number; duration::Number=period, trajectories=nothing, kwargs...)
cart = state(orbit) isa CartesianStateWithSTM ? CartesianStateWithSTM(CartesianState(state(orbit))) : CartesianStateWithSTM(state(orbit))
start = Orbit(cart, system(orbit), epoch(orbit); frame=frame(orbit))
T = period isa Unitful.Time ? period / timeunit(orbit) : period
traj = isnothing(trajectories) ? propagate(start, T) : propagate(start, T; saveat=T/trajectories)
return EnsembleProblem(traj, duration; trajectories=length(traj), kwargs...)
end
"""
Distributed perturbation for `EnsembleProblem` itration.
"""
function DistributedManifoldIteration(traj::Trajectory, V::AbstractVector, dur::Real; trajectories=nothing, eps=1e-8)
Tβ = solution(traj).t[1]
T = solution(traj).t[end]
if isnothing(trajectories)
return @everywhere @eval function f(prob, i, repeat)
t = rand() * T
remake(prob, u0 = perturb(state(traj, t), V; eps=eps), tspan = (Tβ+t, Tβ+t+dur))
end
else
return @everywhere @eval function g(prob, i, repeat)
t = traj.solution.t[i]
remake(prob, u0 = perturb(traj[i], V; eps=eps), tspan = (Tβ+t, Tβ+t+dur))
end
end
end
"""
Non-distributed perturbation for `EnsembleProblem` itration.
"""
function ManifoldIteration(traj::Trajectory, V::AbstractVector, dur::Real; trajectories=nothing, eps=1e-8)
Tβ = solution(traj).t[1]
T = solution(traj).t[end]
if isnothing(trajectories)
return function f(prob, i, repeat)
t = rand() * T
remake(prob, u0 = perturb(state(traj, t), V; eps=eps), tspan = (Tβ+t, Tβ+t+dur))
end
else
return function g(prob, i, repeat)
t = traj.solution.t[i]
remake(prob, u0 = perturb(traj[i], V; eps=eps), tspan = (Tβ+t, Tβ+t+dur))
end
end
end
"""
Maps a solution iteration within an `EnsembleProblem` solver to a `Trajectory`.
"""
function ManifoldTrajectoryOutput(traj::Trajectory)
return function f(sol,i)
e = epoch(traj, sol.t[1])
return (
Trajectory{frame(traj), typeof(sol.prob.u0), typeof(sol.prob.p), typeof(e), typeof(sol)}(e, sol),
false
)
end
end
"""
Maps a solution iteration within an `EnsembleProblem` solver to a `Trajectory`.
"""
function ManifoldSolutionOutput(traj::Trajectory)
return function OutputSolution(sol,i)
return (sol, false)
end
end
"""
Perturbs a periodic orbit's `Trajectory` in the direction of the stable or
unstable eigenvector of its `monodromy` matrix to form a stable
or unstable `manifold`.
"""
function manifold(orbit::Orbit, period::Number; duration::Number=period, trajectories=50, kwargs...)
start = Orbit(CartesianStateWithSTM(state(orbit)), system(orbit), epoch(orbit); frame=frame(orbit))
if isnothing(trajectories)
traj = propagate(start, period)
return manifold(traj; duration=duration, trajectories=trajectories, kwargs...)
else
traj = propagate(start, period; saveat=period/trajectories)
return manifold(traj; duration=duration, trajectories=length(traj), kwargs...)
end
end
"""
Perturbs a periodic orbit `traj` in the direction of the stable or
unstable eigenvector of its `monodromy` matrix to form a stable
or unstable `manifold`.
"""
function manifold(traj::Trajectory{FR, S, P, E}; duration::Number=(solution(traj).t[end] - solution(traj).t[1]), eps=1e-8, direction=Val{:unstable}, algorithm=nothing, ensemble_algorithm=nothing, trajectories=length(traj), reltol=1e-14, abstol=1e-14, kwargs...) where {FR, S<:CartesianStateWithSTM, P, E}
problem = EnsembleProblem(traj; duration=duration, Trajectory=Val{true}, trajectories=trajectories, direction=direction, eps=eps)
if isnothing(algorithm)
isnothing(ensemble_algorithm) || @warn "Argument `algorithm` is nothing: `ensemble_algorithm` keyword argument will be ignored."
solutions = solve(problem; trajectories=trajectories, reltol=reltol, abstol=abstol, kwargs...)
else
if isnothing(ensemble_algorithm)
solutions = solve(problem, algorithm; trajectories=trajectories, reltol=reltol, abstol=abstol, kwargs...)
else
solutions = solve(problem, algorithm, ensemble_algorithm; trajectories=trajectories, reltol=reltol, abstol=abstol, kwargs...)
end
end
return Manifold{FR, typeof(initialstate(first(solutions.u))), P, E, typeof(solutions)}(solutions)
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1494 | """
A module which provides wrappers around
`DifferentialEquations` solvers and
`AstrodynamicalModels` for orbit
propagation, iterative Halo orbit solvers,
and manifold calculations.
# Extended Help
**Exports**
$(EXPORTS)
**Imports**
$(IMPORTS)
"""
module Propagation
export Trajectory, ODEProblem, propagate
export Manifold, EnsembleProblem
export initialstate, initialepoch, solution
export isperiodic, halo, monodromy
export manifold, perturb
export stable_eigenvector, unstable_eigenvector
using ..States
using ..Calculations
using ..CoordinateFrames
import Dates: now
import LinearAlgebra: I
import Roots: find_zero
using Unitful
using Requires
using AstroTime
using Distributed
using StaticArrays
using LinearAlgebra
using ModelingToolkit
using DocStringExtensions
using AstrodynamicalModels
using DifferentialEquations
@template (FUNCTIONS, METHODS, MACROS) = """
$(SIGNATURES)
$(DOCSTRING)
"""
@template (TYPES, CONSTANTS) = """
$(TYPEDEF)
$(DOCSTRING)
"""
include("Trajectories.jl")
include("Propagators.jl")
include("Halos.jl")
include("Manifolds.jl")
function __init__()
@require DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" begin
DataFrames.DataFrame(traj::Trajectory) = DataFrames.DataFrame(solution(traj))
end
end
end # module
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1830 | #
# Restricted Two-body problem propagation
#
"""
Create's an ODEProblem for a `R2BP` orbit.
"""
function SciMLBase.ODEProblem(orbit::R2BPOrbit, Ξt::Number)
u = state(orbit)
Ξt = eltype(state(orbit))(Ξt)
ts = Ξt isa Unitful.Time ? (zero(ustrip(timeunit(orbit), Ξt)), ustrip(timeunit(orbit), Ξt)) : (zero(Ξt), Ξt)
p = system(orbit)
return ODEProblem(R2BPFunction(), u, ts, p)
model = R2BP()
states = @nonamespace [
model.x => x,
model.y => y,
model.z => z,
model.xΜ => xΜ,
model.yΜ => yΜ,
model.zΜ => zΜ,
]
parameters = @nonamespace [
model.ΞΌ => ΞΌ,
]
return ODEProblem(model, states, ts, parameters)
end
"""
Create's an ODEProblem for a `R2BP` orbit.
"""
function SciMLBase.ODEProblem(orbit::CR3BPOrbit, Ξt::Real)
u = state(orbit)
Ξt = eltype(state(orbit))(Ξt)
ts = (zero(Ξt), Ξt)
p = system(orbit)
f = u isa CartesianStateWithSTM ? CR3BPFunction(; stm=true) : CR3BPFunction()
return ODEProblem(f, u, ts, p)
end
"""
Propagates an orbit forward or backward in time.
Use `algorithm` to set the desired numerical integration
algorithm, e.g. `algorithm = Tsit5()`. All other `kwargs`
are passed directly to `DifferentialEquations.solve`.
"""
function propagate(orbit::Orbit, Ξt::Number; algorithm=nothing, kwargs...)
defaults = (; reltol=1e-14, abstol=1e-14)
options = merge(defaults, kwargs)
problem = ODEProblem(orbit, Ξt)
if isnothing(algorithm)
solution = solve(problem; options...)
else
solution = solve(problem, algorithm; options...)
end
return Trajectory{
frame(orbit),
typeof(solution.prob.u0),
typeof(solution.prob.p),
typeof(epoch(orbit)),
typeof(solution)
}(
epoch(orbit), solution
)
end
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 5260 | #
# Types for orbital trajectories
#
"""
An alias for some abstract `ODESolution`
with `States` state vector and parameter
vector types.
"""
const AbstractOrbitalODESolution = SciMLBase.AbstractODESolution{T,N,<:AbstractVector{U}} where {T,N,U<:States.AbstractState}
"""
An wrapper for a `SciMLBase.ODESolution` with a `GeneralAstrodynamics.States.AbstractState`
state vector type. This represents an object's `Trajectory` in space!
"""
struct Trajectory{FR, S, P, E, O<:AbstractOrbitalODESolution}
epoch::E
solution::O
end
"""
Returns the start `epoch`. Typically,
This is a type defined in `AstroTime.Epochs`.
"""
initialepoch(traj::Trajectory) = traj.epoch
"""
Returns the `solution` for the `Trajectory`. Typically,
this is a `DifferentialEquations.ODESolution`.
"""
solution(traj::Trajectory) = traj.solution
"""
A wrapper for (::ODESolution-like)(args...). Returns a state
of type `initialstate)` at time `t` past `epoch`.
"""
(traj::Trajectory)(t::Number; idxs=nothing, continuity=:left) = traj.solution(t, Val{0}; idxs=idxs, continuity=continuity)
(traj::Trajectory)(t::AbstractVector{<:Number}; idxs=nothing, continuity=:left) = traj.solution(t, Val{0}; idxs=idxs, continuity=continuity)
"""
Returns the initial condition associated with the `Trajectory`.
"""
initialstate(traj::Trajectory) = solution(traj).prob.u0
"""
Returns the system associated with the `Trajectory`.
"""
States.system(traj::Trajectory) = solution(traj).prob.p
"""
Returns the `eltype` of the `Trajectory`.
"""
Base.eltype(traj::Trajectory) = eltype(solution(traj))
"""
The `length` of a `Trajectory`.
"""
Base.length(traj::Trajectory) = length(solution(traj))
"""
Returns the last index of a `Trajectory`.
"""
Base.lastindex(traj::Trajectory) = length(traj)
"""
Calls the underlying `solution`'s `getindex` function
to return the `CartesianState` of the `Trajectory`
at time `t` past the `initialepoch`.
"""
Base.getindex(traj::Trajectory, args...) = getindex(solution(traj), args...)
"""
The `size` of a `Trajectory`.
"""
Base.size(traj::Trajectory) = size(solution(traj))
"""
Returns the `OrbitalFrame` of the `Trajectory`.
"""
Base.@pure States.frame(::Trajectory{FR}) where FR = FR
"""
Returns the length unit for the `Trajectory`.
"""
States.lengthunit(traj::Trajectory) = lengthunit(initialstate(traj))
"""
Returns the time unit for the `Trajectory`.
"""
States.timeunit(traj::Trajectory) = timeunit(initialstate(traj))
"""
Returns the angular unit for the `Trajectory`.
"""
States.angularunit(traj::Trajectory) = angularunit(initialstate(traj))
"""
Returns the velocity unit for the `Trajectory`.
"""
States.velocityunit(traj::Trajectory) = velocityunit(initialstate(traj))
"""
Returns the mass unit for the `Trajectory`.
"""
States.massunit(traj::Trajectory) = massunit(system(traj))
"""
Returns the mass parameter unit for the `Trajectory`.
"""
States.massparamunit(traj::Trajectory) = massparamunit(system(traj))
"""
Returns the position of the `Trajectory` at `t` `timeunit`'s from
the `initialstate`'s `epoch`.
"""
Base.position(traj::Trajectory, t) = t isa Unitful.Time ? position(traj, t / timeunit(traj)) : traj(t, Val{0}; idxs=1:3, continuity=:left) * lengthunit(traj)
"""
Returns the scalar distance of the `Trajectory` at `t` `timeunit`'s from
the `initialstate`'s `epoch`.
"""
States.distance(traj::Trajectory, t) = t isa Unitful.Time ? distance(traj, t / timeunit(traj)) : norm(position(traj, t))
"""
Returns the position of the `Trajectory` at `t` `timeunit`'s from
the `initialstate`'s `epoch`.
"""
States.velocity(traj::Trajectory, t) = t isa Unitful.Time ? velocity(traj, t / timeunit(traj)) : traj(t, Val{0}; idxs=4:6, continuity=:left) * velocityunit(traj)
"""
Returns the scalar distance of the `Trajectory` at `t` `timeunit`'s from
the `initialstate`'s `epoch`.
"""
States.speed(traj::Trajectory, t) = t isa Unitful.Time ? speed(traj, t / timeunit(traj)) : norm(velocity(traj, t))
"""
Returns a `state` of type `typeof(initialstate)`
at time `t`.
"""
States.state(traj::Trajectory, t) = t isa Unitful.Time ? state(traj, t / timeunit(traj)) : typeof(initialstate(traj))(solution(traj)(t))
"""
Returns an `epoch` at time `t` past `initialepoch`.
"""
States.epoch(traj::Trajectory, t) = t isa Unitful.Time ? initialepoch(traj) + UnitfulToAstroTime(t) : epoch(traj, t * timeunit(traj))
"""
Converts `Unitful` types to `AstroTime` types.
Throws an `ArgumentError` if the unit of quantity
`t` is not a second, minute, hour, day, or year.
"""
function UnitfulToAstroTime(t::Unitful.Time)
un = Unitful.unit(t)
val = ustrip(un, t)
if un == u"s"
return val * AstroTime.seconds
elseif un == u"minute"
return val * Astrotime.minutes
elseif un == u"hr"
return val * AstroTime.hours
elseif un == u"d"
return val * AstroTime.days
elseif un == u"yr"
return val * AstroTime.years
else
throw(ArgumentError("Invalid time unit!"))
end
end
"""
Returns an `Orbit` at time `t`.
"""
States.Orbit(traj::Trajectory, t) = Orbit(state(traj, t), system(traj), epoch(traj, t))
"""
Show a `Trajectory`.
"""
function Base.show(io::IO, traj::Trajectory)
println(io, "Trajectory with $(length(traj)) timesteps and eltype $(eltype(solution(traj)))")
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1913 | """
A module which provides types for common
state representations in astrodynamics,
including Cartesian and Keplerian states,
and orbital states which include epoch and
coordinate frame information.
# Extended Help
**Exports**
$(EXPORTS)
**Imports**
$(IMPORTS)
"""
module States
export CartesianState, CartesianStateWithSTM, KeplerianState
export R2BPParameters, CR3BPParameters
export Orbit, state, system, epoch, frame
export position, velocity, statevector
export R2BPOrbit, KeplerianR2BPOrbit, CartesianR2BPOrbit, CartesianOrbitWithSTM, CR3BPOrbit
export lengthunit, timeunit, angularunit, velocityunit, massparamunit, name
export Sun, Mercury, Venus, Earth, Moon, Luna, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto
export SunVenus, SunEarth, EarthMoon, SunMars, SunJupiter, SunSaturn
export model, vectorfield
import Dates: now
import AstroTime: TAIEpoch
import Requires: @require
import LinearAlgebra: norm, I
using Unitful, UnitfulAstro
using StaticArrays
using ArrayInterface
using LabelledArrays
using DocStringExtensions
using ..CoordinateFrames
using ..Calculations
@template (FUNCTIONS, METHODS, MACROS) =
"""
$(SIGNATURES)
$(DOCSTRING)
"""
@template (TYPES, CONSTANTS) =
"""
$(TYPEDEF)
$(DOCSTRING)
"""
include(joinpath("Common","ParameterizedLabelledArrays.jl"))
include(joinpath("States", "StateVectors.jl"))
include(joinpath("Systems", "ParameterVectors.jl"))
include(joinpath("Orbits", "OrbitDescriptions.jl"))
include(joinpath("Systems", "R2BPSystems.jl"))
include(joinpath("Systems", "CR3BPSystems.jl"))
include("Calculations/Calculations.jl")
function __init__()
@require AstrodynamicalModels="4282b555-f590-4262-b575-3e516e1493a7" include(joinpath(@__DIR__, "Hooks", "AstrodynamicalModels.jl"))
@require SymbolicUtils="d1185830-fcd6-423d-90d6-eec64667417b" include(joinpath(@__DIR__, "Hooks", "SymbolicUtils.jl"))
end
end # module
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 497 | #
# Defines AstrodynamicalCalculations methods for
# OrbitalStates types
#
export massparameter, massparameters, normalized_massparameter
export primary_massparameter, secondary_massparameter
export RAAN, argument_of_periapsis, inclination
export periapsis_velocity, apoapsis_velocity
export mean_motion_vector
export distance_to_primary, distance_to_secondary
export massparameter, massparameters
export primary_massparameter, secondary_massparameter
include("States.jl")
include("Systems.jl") | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 6375 | #
# Methods for orbit states and state vectors.
#
Calculations.keplerian(state::CartesianStateVector, ΞΌ) = keplerian(position(state), velocity(state), ΞΌ)
Calculations.keplerian(orbit::CartesianR2BPOrbit) = keplerian(state(orbit), massparameter(system(orbit)))
Calculations.keplerian(orbit::KeplerianR2BPOrbit) = orbit
Calculations.cartesian(orbit::CartesianR2BPOrbit) = orbit
Calculations.cartesian(orbit::KeplerianR2BPOrbit) = cartesian(state(orbit), massparameter(system(orbit)))
Calculations.cartesian(state::KeplerianState, ΞΌ) = cartesian(
eccentricity(state),
semimajor_axis(state),
inclination(state),
RAAN(state),
argument_of_periapsis(state),
true_anomoly(state),
ΞΌ
)
Base.position(state::CartesianStateVector) = States.get_r(state) * lengthunit(state)
Base.position(orbit::KeplerianR2BPOrbit) = position(CartesianState(cartesian(state(orbit), massparameter(state(orbit)))))
Base.position(orbit::Orbit) = position(state(orbit))
Calculations.distance(state::CartesianStateVector) = norm(position(state))
Calculations.distance(orbit::Orbit) = norm(position(orbit))
velocity(state::CartesianStateVector) = States.get_v(state) * velocityunit(state)
velocity(orbit::Orbit) = velocity(state(orbit))
Calculations.speed(state::CartesianStateVector) = norm(velocity(state))
Calculations.speed(orbit::KeplerianR2BPOrbit) = speed(semi_parameter(semimajor_axis(state(orbit)), eccentricity(state(orbit))), semimajor_axis(state(orbit)), massparameter(system(orbit)))
Calculations.speed(orbit::Orbit) = norm(velocity(state(orbit)))
Calculations.eccentricity(state::KeplerianState) = States.get_e(state)
Calculations.eccentricity(orbit::KeplerianR2BPOrbit) = eccentricity(state(orbit))
Calculations.eccentricity(orbit::CartesianR2BPOrbit) = eccentricity(position(state(orbit)), velocity(state(orbit)), massparameter(system(orbit)))
Calculations.semimajor_axis(state::KeplerianState) = States.get_a(state) * lengthunit(state)
Calculations.semimajor_axis(orbit::CartesianR2BPOrbit) = semimajor_axis(distance(state(orbit)), speed(state(orbit)), massparameter(system(orbit)))
Calculations.semimajor_axis(orbit::KeplerianR2BPOrbit) = semimajor_axis(state(orbit))
inclination(state::KeplerianState) = States.get_i(state) * angularunit(state)
inclination(orbit::KeplerianR2BPOrbit) = inclination(state(orbit))
RAAN(state::KeplerianState) = States.get_Ξ©(state) * angularunit(state)
RAAN(orbit::KeplerianR2BPOrbit) = RAAN(state(orbit))
argument_of_periapsis(state::KeplerianState) = States.get_Ο(state) * angularunit(state)
argument_of_periapsis(orbit::KeplerianR2BPOrbit) = argument_of_periapsis(state(orbit))
Calculations.true_anomoly(state::KeplerianState) = States.get_Ξ½(state) * angularunit(state)
Calculations.true_anomoly(orbit::KeplerianR2BPOrbit) = true_anomoly(state(orbit))
Calculations.true_anomoly(orbit::CartesianR2BPOrbit) = true_anomoly(distance(orbit), specific_angular_momentum(orbit), eccentricity(orbit), massparameter(system(orbit)))
Calculations.conic(orbit::R2BPOrbit) = conic(eccentricity(orbit))
Calculations.specific_angular_momentum_vector(orbit::CartesianR2BPOrbit) = specific_angular_momentum_vector(position(state(orbit)), velocity(state(orbit)))
Calculations.specific_angular_momentum(orbit::CartesianR2BPOrbit) = specific_angular_momentum(position(state(orbit)), velocity(state(orbit)))
Calculations.specific_energy(orbit::CartesianR2BPOrbit) = specific_energy(distance(state(orbit)), speed(state(orbit)), massparameter(system(orbit)))
Calculations.specific_energy(orbit::KeplerianR2BPOrbit) = specific_energy(semimajor_axis(orbit), massparameter(system(orbit)))
Calculations.C3(orbit::R2BPOrbit) = C3(distance(orbit), speed(orbit), massparameter(system(orbit)))
Calculations.v_infinity(orbit::R2BPOrbit) = v_infinity(distance(orbit), speed(orbit), massparameter(system(orbit)))
Calculations.eccentricity_vector(orbit::CartesianR2BPOrbit) = eccentricity_vector(position(state(orbit)), velocity(state(orbit)), massparameter(system(orbit)))
Calculations.semi_parameter(orbit::R2BPOrbit) = semi_parameter(semimajor_axis(orbit), eccentricity(orbit))
Calculations.periapsis_radius(orbit::R2BPOrbit) = periapsis_radius(semimajor_axis(orbit), eccentricity(orbit))
Calculations.apoapsis_radius(orbit::R2BPOrbit) = apoapsis_radius(semimajor_axis(orbit), eccentricity(orbit))
periapsis_velocity(orbit::R2BPOrbit) = speed(periapsis_radius(orbit), semimajor_axis(orbit), massparameter(system(orbit)))
apoapsis_velocity(orbit::R2BPOrbit) = speed(apoapsis_radius(orbit), semimajor_axis(orbit), massparameter(system(orbit)))
Calculations.period(orbit::R2BPOrbit) = conic(orbit) β (Circular, Elliptical) ? period(semimajor_axis(orbit), massparameter(system(orbit))) : conic(orbit) == Parabolic ? Inf * timeunit(orbit) : NaN * timeunit(orbit)
Calculations.mean_motion(orbit::R2BPOrbit) = mean_motion(semimajor_axis(orbit), massparameter(system(orbit)))
function mean_motion_vector(orbit::R2BPOrbit)
# iΜ = SVector{3, Float64}([1, 0, 0])
# jΜ = SVector{3, Float64}([0, 1, 0])
kΜ = SVector{3}(0, 0, 1)
return kΜ Γ specific_angular_momentum_vector(orbit)
end
Calculations.time_since_periapsis(orbit::R2BPOrbit) = time_since_periapsis(mean_motion(orbit), eccentricity(orbit), eccentric_anomoly(orbit))
Calculations.specific_potential_energy(orbit::CartesianR2BPOrbit) = specific_potential_energy(distance(orbit.state), massparameter(system(orbit)))
Calculations.jacobi_constant(orbit::CR3BPOrbit) = Calculations.jacobi_constant(States.get_r(state(orbit)), States.get_v(state(orbit)), massparameter(system(orbit)))
Calculations.potential_energy(orbit::CR3BPOrbit) = potential_energy(States.get_r(state(orbit)), massparameter(system(orbit)))
distance_to_primary(orbit::CR3BPOrbit) = norm(States.get_r(state(orbit)) .- SVector(-massparameter(orbit), 0, 0))
distance_to_secondary(orbit::CR3BPOrbit) = norm(States.get_r(state(orbit)) .- SVector(1-massparameter(orbit), 0, 0))
function Calculations.kepler(orbit::Orbit, Ξt = period(orbit); kwargs...)
r, v = kepler(position(orbit), velocity(orbit), massparameter(orbit), Ξt; kwargs...)
cart = CartesianState(r, v)
return Orbit(cart, system(orbit))
end
function Calculations.zerovelocity_curves(orbit::CR3BPOrbit; kwargs...)
return Calculations.zerovelocity_curves(state(orbit).r, state(orbit).v, massparameter(system(orbit)); kwargs...)
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1355 | #
# Methods for orbital systems.
#
"""
Returns the mass parameter of the R2BP system.
"""
massparameter(system::R2BPParameters) = States.get_ΞΌ(system) * massparamunit(system)
massparameter(orbit::R2BPOrbit) = massparameter(system(orbit))
"""
Returns the mass parameter of the CR3BP system.
"""
massparameter(system::CR3BPParameters) = States.get_ΞΌ(system)
massparameter(orbit::CR3BPOrbit) = massparameter(system(orbit))
"""
Returns the mass parameters of the CR3BP system.
"""
massparameters(system::CR3BPParameters) = (primary_massparameter(system), secondary_massparameter(system))
massparameters(orbit::CR3BPOrbit) = massparameters(system(orbit))
"""
Returns the primary mass parameter of the CR3BP system.
"""
function primary_massparameter(system::CR3BPParameters)
DU = lengthunit(system)
TU = timeunit(system)
ΞΌ = massparameter(system)
βΞΌα΅’ = DU^3 / ((TU / 2Ο)^2)
return βΞΌα΅’ - ΞΌ * βΞΌα΅’
end
primary_massparameter(orbit::CR3BPOrbit) = primary_massparameter(system(orbit))
"""
Returns the secondary mass parameter of the CR3BP system.
"""
function secondary_massparameter(system::CR3BPParameters)
DU = lengthunit(system)
TU = timeunit(system)
ΞΌ = massparameter(system)
βΞΌα΅’ = DU^3 / ((TU / 2Ο)^2)
return ΞΌ * βΞΌα΅’
end
secondary_massparameter(orbit::CR3BPOrbit) = secondary_massparameter(system(orbit)) | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 7443 | #
# Using LabelledArrays source code and types to
# "pass through" all properties to an underlying
# LArray or SLArray. This allows us to write
# a new abstract type that *functions*
# like a LabelledArray type!
#
# All code in this file was copied, and modified
# from LabelledArrays.jl source code. Their license is shown below.
# All credit goes to LabelledArrays.jl developers.
#
const __LABELLED_ARRAYS_LICENSE = """
The LabelledArrays.jl package is licensed under the MIT "Expat" License:
> Copyright (c) 2017: Christopher Rackauckas.
>
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
>
> of this software and associated documentation files (the "Software"), to deal
>
> in the Software without restriction, including without limitation the rights
>
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
>
> copies of the Software, and to permit persons to whom the Software is
>
> furnished to do so, subject to the following conditions:
>
>
>
> The above copyright notice and this permission notice shall be included in all
>
> copies or substantial portions of the Software.
>
>
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
>
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
>
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
>
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
>
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
>
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
>
> SOFTWARE.
>
>
"""
const __LABELLED_ARRAYS_CREDITS = """
This source code which provides this functionality was copied directly from LabelledArrays.jl source code. The LabelledArrays.jl license text is provided in Julia's **Extended Help** section (accessible via `@doc`, or `??` in Julia's REPL).
# Extended Help
__LabelledArrays.jl License__
$__LABELLED_ARRAYS_LICENSE
"""
"""
$(TYPEDEF)
A supertype for types that *function* like
`LabelledArray.LArray` or `LabelledArray.SLArray`
instances, but are under a new type tree. This is
used in `GeneralAstrodynamics` for parameterizing
astrodynamics state vectors by physical units.
!!! note
All subtypes __must__ have only one field:
a `LabelledArrays.LArray` or `LabelledArrays.SLArray`
field called `__rawdata`. All methods on this abstract
type require this field to be called `__rawdata`!
Nearly all code which acts on this type is copied
and / or modified from LabelledArrays.jl source code.
All credit goes to LabelledArrays.jl developers.
The LabelledArrays.jl LICENSE file is provided
in this docstring under Julia's __Extended Help__
docstring section.
# Extended help
__LabelledArrays.jl License__
$__LABELLED_ARRAYS_LICENSE
"""
abstract type ParameterizedLabelledArray{F,N,T,L} <: DenseArray{F,N} end
"""
$(SIGNATURES)
Returns dot-accessible property names for a `ParameterizedLabelledArray`.
"""
Base.propertynames(::ParameterizedLabelledArray{F,N,T}) where {F,N,T} = T isa NamedTuple ? keys(T) : T
"""
$(SIGNATURES)
Overrides `Base.getproperty` for all `ParameterizedLabelledArray` instances.
$__LABELLED_ARRAYS_CREDITS
"""
Base.@propagate_inbounds function Base.getproperty(x::ParameterizedLabelledArray, s::Symbol)
if s β propertynames(x)
return getproperty(getfield(x, :__rawdata), s)
end
return getfield(x, s) # will throw an error if s is not :__rawdata!
end
"""
$(SIGNATURES)
Sets indices of a `ParameterizedLabelledArray` via label.
$__LABELLED_ARRAYS_CREDITS
"""
Base.@propagate_inbounds function Base.setproperty!(x::ParameterizedLabelledArray, s::Symbol,y)
if s β propertynames(x)
return setproperty!(getfield(x, :__rawdata), s, y)
end
setfield!(x, s, y)
end
"""
$(SIGNATURES)
Overrides `similar` for `ParameterizedLabelledArray` instances.
$__LABELLED_ARRAYS_CREDITS
"""
function Base.similar(x::ParameterizedLabelledArray)
return typeof(x)(similar(Vector(x)))
end
"""
$(SIGNATURES)
Overrides `similar` for `ParameterizedLabelledArray` instances.
$__LABELLED_ARRAYS_CREDITS
"""
function Base.similar(x::ParameterizedLabelledArray, ::Int)
return similar(x)
end
"""
$(SIGNATURES)
Overrides `zero` for `ParameterizedLabelledArray` instances.
$__LABELLED_ARRAYS_CREDITS
"""
function Base.zero(x::ParameterizedLabelledArray)
return typeof(x)(zero(x.__rawdata))
end
"""
$(SIGNATURES)
Overrides `one` for `ParameterizedLabelledArray` instances.
$__LABELLED_ARRAYS_CREDITS
"""
function Base.one(x::ParameterizedLabelledArray)
return typeof(x)(one(x.__rawdata))
end
"""
$(SIGNATURES)
Overrides `similar` for `ParameterizedLabelledArray` instances.
$__LABELLED_ARRAYS_CREDITS
"""
function Base.similar(x::ParameterizedLabelledArray, dims::NTuple{N,Int}...) where {N}
return similar(Vector(x), eltype(x), dims)
end
"""
$(SIGNATURES)
Shallow copies a `ParameterizedLabelledArray`.
$__LABELLED_ARRAYS_CREDITS
"""
Base.copy(x::ParameterizedLabelledArray) = typeof(x)(copy(getfield(x,:__rawdata)))
"""
$(SIGNATURES)
Deep copies a `ParameterizedLabelledArray`.
$__LABELLED_ARRAYS_CREDITS
"""
Base.deepcopy(x::ParameterizedLabelledArray) = typeof(x)(deepcopy(getfield(x, :__rawdata)))
"""
$(SIGNATURES)
Copies one `ParameterizedLabelledArray` to another.
$__LABELLED_ARRAYS_CREDITS
"""
Base.copyto!(x::C,y::C) where C <: ParameterizedLabelledArray = copyto!(getfield(x,:__rawdata),getfield(y,:__rawdata))
"""
$(SIGNATURES)
Provides `unsafe_convert` for `ParameterizedLabelledArray` types for use with LAPACK.
$__LABELLED_ARRAYS_CREDITS
"""
Base.unsafe_convert(::Type{Ptr{T}}, a::ParameterizedLabelledArray{F}) where {T, F} = Base.unsafe_convert(Ptr{T}, getfield(a,:__rawdata))
"""
$(SIGNATURES)
Converts the underlying floating point type for a `ParameterizedLabelledArray`.
$__LABELLED_ARRAYS_CREDITS
"""
Base.convert(::Type{T}, x) where {T<:ParameterizedLabelledArray} = T(x)
"""
$(SIGNATURES)
Converts the underlying floating point type for a `ParameterizedLabelledArray`.
$__LABELLED_ARRAYS_CREDITS
"""
Base.convert(::Type{T}, x::T) where {T<:ParameterizedLabelledArray} = x
"""
$(SIGNATURES)
Converts the underlying floating point type for a `ParameterizedLabelledArray`.
$__LABELLED_ARRAYS_CREDITS
"""
Base.convert(::Type{<:Array},x::ParameterizedLabelledArray) = convert(Array, getfield(x,:__rawdata))
"""
$(SIGNATURES)
Reshapes a `ParameterizedLabelledArray`.
$__LABELLED_ARRAYS_CREDITS
"""
ArrayInterface.restructure(x::ParameterizedLabelledArray{F1}, y::ParameterizedLabelledArray{F2}) where {F1, F2} = reshape(y, size(x)...)
"""
$(SIGNATURES)
Implements `dataids` for a `ParameterizedLabelledArray` instance.
$__LABELLED_ARRAYS_CREDITS
"""
Base.dataids(A::ParameterizedLabelledArray) = Base.dataids(A.__rawdata)
"""
$(SIGNATURES)
Returns the index of the `ParameterizedLabelledArray`.
$__LABELLED_ARRAYS_CREDITS
"""
Base.getindex(state::ParameterizedLabelledArray, args...) = Base.getindex(state.__rawdata, args...)
"""
$(SIGNATURES)
Sets the index of the `ParameterizedLabelledArray`.
$__LABELLED_ARRAYS_CREDITS
"""
Base.setindex!(state::ParameterizedLabelledArray, args...) = Base.setindex!(state.__rawdata, args...)
"""
$(SIGNATURES)
Returns the memory stride for any `ParameterizedLabelledArray`.
$__LABELLED_ARRAYS_CREDITS
"""
Base.elsize(::ParameterizedLabelledArray{F}) where F = sizeof(F)
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 845 | #
# Hooks into AstrodynamicalModels.jl
#
"""
$(SIGNATURES)
Returns the `ModelingToolkit.ODESystem` associated
with `R2BPParameters`, provided by `AstrodynamicalModels`.
"""
model(::R2BPParameters) = AstrodynamicalModels.R2BP
"""
$(SIGNATURES)
Returns the `ModelingToolkit.ODESystem` associated
with `CR3BPParameters`, provided by `AstrodynamicalModels`.
"""
model(::CR3BPParameters) = AstrodynamicalModels.CR3BP
"""
$(SIGNATURES)
Returns the `DifferentialEquations.ODEFunction` associated
with `R2BPParameters`, provided by `AstrodynamicalModels`.
"""
vectorfield(::R2BPParameters) = AstrodynamicalModels.R2BPVectorField
"""
$(SIGNATURES)
Returns the `DifferentialEquations.ODEFunction` associated
with `CR3BPParameters`, provided by `AstrodynamicalModels`.
"""
vectorfield(::CR3BPParameters) = AstrodynamicalModels.CR3BPVectorField | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 336 | using Core: Argument
#
# Provides `create_array` methods for `StateVector` and `ParameterVector`
# instances!
#
@inline function SymbolicUtils.Code.create_array(A::Type{<:StateVector}, T, nd::Val, d::Val{dims}, elems...) where {dims}
data = SymbolicUtils.Code.create_array(SArray, T, nd, d, elems...)
return (A)(data.data)
end
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 5228 | #
# Orbit descriptions.
#
"""
A supertype for all single-point orbit descriptions.
Parameterized by coordinate frame, floating point type,
mass unit, lenth unit, time unit, epoch type, state type,
and parameter type (in order).
"""
abstract type AbstractOrbit{FR, F, MU, LU, TU, AU, E, S<:AbstractState{F, LU, TU, AU}, P<:ParameterVector{F, MU, LU, TU, AU}} end
"""
An orbit, described by a `StateVector`, with parameters described by a `ParameterVector`.
"""
mutable struct Orbit{FR, F, MU, LU, TU, AU, E, S, P} <: AbstractOrbit{FR, F, MU, LU, TU, AU, E, S, P}
epoch::E
state::S
system::P
end
"""
Returns a default frame.
"""
function defaultframe(system::ParameterVector)
if system isa R2BPParameters
return CoordinateFrames.BodycentricInertial
elseif system isa CR3BPParameters
return CoordinateFrames.BarycentricRotating
else
return Inertial
end
end
"""
Outer constructor for `Orbit`s.
"""
function Orbit(state::AbstractState, system::ParameterVector, epoch=TAIEpoch(now()); frame = defaultframe(system))
S = eval(Base.typename(typeof(state)).name)
P = eval(Base.typename(typeof(system)).name)
if state isa KeplerianState && !(system isa R2BPParameters)
throw(ArgumentError("Orbits with $P must have CartesianState state vectors."))
end
FR = frame
F = promote_type(eltype(state), eltype(system))
MU = massunit(system)
if system isa CR3BPParameters
LU = lengthunit(system)
TU = timeunit(system)
else
LU = lengthunit(state)
TU = timeunit(state)
end
AU = angularunit(state)
E = typeof(epoch)
return Orbit{FR, F, MU, LU, TU, AU, E, S{F, LU, TU, AU}, P{F, MU, LU, TU, AU}}(
epoch,
convert(S{F, LU, TU, AU}, state),
convert(P{F, MU, LU, TU, AU}, system)
)
end
"""
Outer constructor for `Orbit`s.
"""
function Orbit(r::AbstractVecOrMat, v::AbstractVecOrMat, system::ParameterVector, epoch=TAIEpoch(now()); frame = defaultframe(system))
state = CartesianState(vcat(r..., v...))
return Orbit(state, system, epoch; frame=frame)
end
"""
Shows all `Orbit` instances.
"""
function Base.show(io::IO, orbit::Orbit)
if system(orbit) isa R2BPParameters
println(io, conic(orbit), " Restricted Two-body Orbit with eltype $(typeof(orbit).parameters[2])")
elseif system(orbit) isa CR3BPParameters
println(io, "Circular Restricted Three-body Orbit with eltype $(typeof(orbit).parameters[2])")
end
println(io, "")
Base.show(io, state(orbit); showfloats=false, space=" ")
println(io, "")
Base.show(io, system(orbit); showfloats=false, space=" ")
end
Base.show(io::IO, ::MIME"text/plain", orbit::Orbit) = show(io, orbit)
"""
Returns the epoch (timestamp) for the `Orbit`.
"""
epoch(orbit::Orbit) = orbit.epoch
"""
Returns the state vector for the `Orbit`.
"""
state(orbit::Orbit) = orbit.state
"""
Returns the parameter vector for the `Orbit`.
"""
system(orbit::Orbit) = orbit.system
"""
Returns the `lengthunit` for an `Orbit`.
"""
Base.@pure lengthunit(::Orbit{FR, F, MU, LU, TU, AU}) where {FR, F, MU, LU, TU, AU} = LU
"""
Returns the `timeunit` for an `Orbit`.
"""
Base.@pure timeunit(::Orbit{FR, F, MU, LU, TU, AU}) where {FR, F, MU, LU, TU, AU} = TU
"""
Returns the `angularunit` for an `Orbit`.
"""
Base.@pure angularunit(::Orbit{FR, F, MU, LU, TU, AU}) where {FR, F, MU, LU, TU, AU} = AU
"""
Returns the `massunit` for an `Orbit`.
"""
Base.@pure massunit(::Orbit{FR, F, MU, LU, TU, AU}) where {FR, F, MU, LU, TU, AU} = MU
"""
Returns the `velocityunit` for an `Orbit`.
"""
velocityunit(orbit::Orbit) = lengthunit(orbit) / timeunit(orbit)
"""
Returns the `massparamunit` for an `Orbit`.
"""
massparamunit(orbit::Orbit) = lengthunit(orbit)^3 / timeunit(orbit)^2
"""
Returns the `OrbitalFrame` for the `Orbit`.
"""
Base.@pure frame(::Orbit{FR}) where FR = FR
"""
An alias for `Orbit` instances about `R2BP` systems.
"""
const R2BPOrbit = Orbit{FR, F, MU, LU, TU, AU, E, S, P} where {FR, F, MU, LU, TU, AU, E, S<:Union{CartesianStateVector, KeplerianState}, P<:R2BPParameters}
"""
An alias for `Orbit` instances about `R2BP` systems with `KeplerianState` descriptions.
"""
const KeplerianR2BPOrbit = Orbit{FR, F, MU, LU, TU, AU, E, <:KeplerianState, <:R2BPParameters} where {FR, F, MU, LU, TU, AU, E}
"""
An alias for `Orbit` instances about `R2BP` systems with `CartesianState` descriptions.
"""
const CartesianR2BPOrbit = Orbit{FR, F, MU, LU, TU, AU, E, <:CartesianStateVector, <:R2BPParameters} where {FR, F, MU, LU, TU, AU, E}
"""
An alias for `Orbit` instances about `CR3BP` systems.
"""
const CR3BPOrbit = Orbit{FR, F, MU, LU, TU, AU, E, <:CartesianStateVector, <:CR3BPParameters} where {FR, F, MU, LU, TU, AU, E}
"""
An alias for `Orbit` instances about any systems with `CartesianState` descriptions.
"""
const CartesianOrbit = Orbit{FR, F, MU, LU, TU, AU, E, <:CartesianStateVector, <:ParameterVector} where {FR, F, MU, LU, TU, AU, E}
"""
An alias for `Orbit` instances about any systems with `CartesianStateWithSTM` descriptions.
"""
const CartesianOrbitWithSTM = Orbit{FR, F, MU, LU, TU, AU, E, <:CartesianStateWithSTM, <:ParameterVector} where {FR, F, MU, LU, TU, AU, E} | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 12748 | #
# State vector descriptions.
#
"""
A supertype for all states in astrodynamics.
"""
abstract type AbstractState{F, LU, TU, AU, T} <: ParameterizedLabelledArray{F, 1, T, LArray{F, 1, MVector{6, F}, T}} end
"""
A supertype for all state representations in astrodynamics.
"""
abstract type StateVector{F, LU, TU, AU, T} <: AbstractState{F, LU, TU, AU, T} end
"""
A supertype for all state representations with local linearizations in astrodynamics.
"""
abstract type StateVectorWithSTM{F, LU, TU, AU, T} <: AbstractState{F, LU, TU, AU, T} end
"""
Returns the lengthunit of the state vector.
"""
Base.@pure lengthunit(::AbstractState{F, LU, TU, AU}) where {F, LU, TU, AU} = LU
"""
Returns the timeunit of the state vector.
"""
Base.@pure timeunit(::AbstractState{F, LU, TU, AU}) where {F, LU, TU, AU} = TU
"""
Returns the angularunit of the state vector.
"""
Base.@pure angularunit(::AbstractState{F, LU, TU, AU}) where {F, LU, TU, AU} = AU
"""
Returns the angularunit of the state vector.
"""
velocityunit(::AbstractState{F, LU, TU, AU}) where {F, LU, TU, AU} = LU/TU
"""
The length of any `StateVector` is 6!
"""
Base.@pure Base.length(::StateVector) = 6
"""
The size of any `StateVector` is (6,)!
"""
Base.@pure Base.size(::StateVector) = (6,)
"""
The length of any `StateVector` is 6!
"""
Base.@pure Base.length(::StateVectorWithSTM) = 42
"""
The size of any `StateVector` is (6,)!
"""
Base.@pure Base.size(::StateVectorWithSTM) = (42,)
"""
A Cartesian state vector with length 6. Internally
uses `MVector` and `LVector` to store data.
Data is accessible via labels, which are
`x, y, z, αΊ, αΊ, ΕΌ, r, v`, where `r`
access `x,y,z` and `v` accesses `αΊ, αΊ, ΕΌ`.
"""
mutable struct CartesianState{F, LU, TU, AU} <: StateVector{F, LU, TU, AU, (x = 1, y = 2, z = 3, αΊ = 4, αΊ = 5, ΕΌ = 6, r = 1:3, v = 4:6)}
__rawdata::LArray{F, 1, MVector{6, F}, (x = 1, y = 2, z = 3, αΊ = 4, αΊ = 5, ΕΌ = 6, r = 1:3, v = 4:6)}
"""
$(SIGNATURES)
Constructs a `CartesianState` with types specified.
"""
CartesianState{F, LU, TU, AU}(data) where {F, LU, TU, AU} = new{F,LU,TU,AU}(LArray{F, 1, MVector{6, F}, (x = 1, y = 2, z = 3, αΊ = 4, αΊ = 5, ΕΌ = 6, r = 1:3, v = 4:6)}(data))
end
"""
Constructs a `CartesianState` from provided position and velocity vectors.
"""
function CartesianState(r::AbstractArray, v::AbstractArray;
lengthunit=(unit(eltype(r)) isa Unitful.Length ? unit(eltype(r)) : u"km"),
timeunit=(unit(eltype(v)) isa Unitful.Velocity ? lengthunit / unit(eltype(v)) : u"s"),
angularunit=u"rad")
rr = (eltype(r) <: Unitful.Length ? ustrip.(lengthunit, r) : r)
vv = (eltype(v) <: Unitful.Velocity ? ustrip.(lengthunit / timeunit, v) : v)
F = promote_type(eltype(rr), eltype(vv))
F isa AbstractFloat || (F = Float64)
return CartesianState(vcat(rr,vv); lengthunit = lengthunit, timeunit = timeunit, angularunit = angularunit)
end
"""
Constructs a `CartesianState`.
"""
function CartesianState(statevector; lengthunit=u"km", timeunit=u"s", angularunit=u"rad")
F = eltype(statevector)
F isa AbstractFloat || (F = Float64)
return CartesianState{F, lengthunit, timeunit, angularunit}(
LArray{F, 1, MVector{6, F}, (x = 1, y = 2, z = 3, αΊ = 4, αΊ = 5, ΕΌ = 6, r = 1:3, v = 4:6)}(
statevector
)
)
end
"""
A Cartesian state vector with local linearization
and length 42. Internally
uses `MVector` and `LVector` to store data.
Data is accessible via labels, which are
`x, y, z, αΊ, αΊ, ΕΌ, r, v`, where `r`
access `x,y,z` and `v` accesses `αΊ, αΊ, ΕΌ`.
"""
mutable struct CartesianStateWithSTM{F, LU, TU, AU} <: StateVectorWithSTM{F, LU, TU, AU, (x = 1, y = 2, z = 3, αΊ = 4, αΊ = 5, ΕΌ = 6, r = 1:3, v = 4:6, Ξ¦=(7:42))}
__rawdata::LArray{F, 1, MVector{42, F}, (x = 1, y = 2, z = 3, αΊ = 4, αΊ = 5, ΕΌ = 6, r = 1:3, v = 4:6, Ξ¦=(7:42))}
"""
$(SIGNATURES)
Constructs a `CartesianStateWithSTM` with types specified.
"""
CartesianStateWithSTM{F, LU, TU, AU}(data) where {F, LU, TU, AU} = new{F,LU,TU,AU}(LArray{F, 1, MVector{42, F}, (x = 1, y = 2, z = 3, αΊ = 4, αΊ = 5, ΕΌ = 6, r = 1:3, v = 4:6, Ξ¦=(7:42))}(data))
end
"""
Outer constructor for `CartesianStateWithSTM`.
"""
CartesianStateWithSTM(data; lengthunit=u"km", timeunit=u"s", angularunit=u"rad") = CartesianStateWithSTM{eltype(data), lengthunit, timeunit, angularunit}(data)
"""
Returns a `CartesianStateWithSTM`, given a `CartesianState`.
"""
CartesianStateWithSTM(cart::CartesianState, stm=Matrix{eltype(cart)}(I(6))) = CartesianStateWithSTM{eltype(cart), lengthunit(cart), timeunit(cart), angularunit(cart)}(MVector{42}(cart..., stm...))
"""
Returns a `CartesianState`, given a `CartesianStateWithSTM`.
"""
CartesianState(cart::CartesianStateWithSTM) = CartesianState(cart[1:6]; lengthunit=lengthunit(cart), timeunit=timeunit(cart), angularunit=angularunit(cart))
"""
All Cartesian state!
"""
const CartesianStateVector = Union{<:CartesianState, <:CartesianStateWithSTM}
"""
Returns `x`.
"""
get_x(state::CartesianStateVector) = state[1]
"""
Returns `y`.
"""
get_y(state::CartesianStateVector) = state[2]
"""
Returns `z`.
"""
get_z(state::CartesianStateVector) = state[3]
"""
Returns `xΜ`.
"""
get_xΜ(state::CartesianStateVector) = state[4]
"""
Returns `yΜ`.
"""
get_yΜ(state::CartesianStateVector) = state[5]
"""
Returns `zΜ`.
"""
get_zΜ(state::CartesianStateVector) = state[6]
"""
Returns `r`.
"""
get_r(state::CartesianStateVector) = state[1:3]
"""
Returns `v`.
"""
get_v(state::CartesianStateVector) = state[4:6]
"""
Returns `Ο`.
"""
get_Ο(state::CartesianStateWithSTM) = state[7:42]
"""
Returns the state transition matrix.
"""
get_stm(state::CartesianStateWithSTM) = MMatrix{6,6}(state[7:42])
"""
Returns the whole state vector, without units.
"""
statevector(state::CartesianState) = MVector{6}(get_x(state) * lengthunit(state), get_y(state) * lengthunit(state), get_z(state) * lengthunit(state), get_xΜ(state) * velocityunit(state), get_yΜ(state) * velocityunit(state), get_zΜ(state) * velocityunit(state))
"""
Returns the whole state vector, without units.
"""
statevector(state::CartesianStateWithSTM) = MVector{42}(get_x(state) * lengthunit(state), get_y(state) * lengthunit(state), get_z(state) * lengthunit(state), get_xΜ(state) * velocityunit(state), get_yΜ(state) * velocityunit(state), get_zΜ(state) * velocityunit(state), get_Ο(state)...)
"""
Displays a `CartesianState`.
"""
function Base.show(io::IO, state::CartesianState; showfloats=true, space="")
LU = isnormalized(state) ? one(eltype(state)) : lengthunit(state)
VU = isnormalized(state) ? one(eltype(state)) : velocityunit(state)
println(io, space, "Cartesian State", showfloats ? " with eltype $(eltype(state))" : "", "\n")
println(io, space, " ", "x = $(get_x(state) * LU)")
println(io, space, " ", "y = $(get_y(state) * LU)")
println(io, space, " ", "z = $(get_z(state) * LU)")
println(io, space, " ", "xΜ = $(get_xΜ(state) * VU)")
println(io, space, " ", "yΜ = $(get_yΜ(state) * VU)")
println(io, space, " ", "zΜ = $(get_zΜ(state) * VU)")
end
Base.show(io::IO, ::MIME"text/plain", state::CartesianState; showfloats=true, space="") = show(io, state; showfloats=showfloats, space=space)
"""
Displays a `CartesianStateWithSTM`.
"""
function Base.show(io::IO, state::CartesianStateWithSTM; showfloats=true, space="")
LU = isnormalized(state) ? one(eltype(state)) : lengthunit(state)
VU = isnormalized(state) ? one(eltype(state)) : velocityunit(state)
println(io, space, "Cartesian State with local linearization", showfloats ? " and eltype $(eltype(state))" : "", "\n")
println(io, space, " ", "x = $(get_x(state) * LU)")
println(io, space, " ", "y = $(get_y(state) * LU)")
println(io, space, " ", "z = $(get_z(state) * LU)")
println(io, space, " ", "xΜ = $(get_xΜ(state) * VU)")
println(io, space, " ", "yΜ = $(get_yΜ(state) * VU)")
println(io, space, " ", "zΜ = $(get_zΜ(state) * VU)")
end
Base.show(io::IO, ::MIME"text/plain", state::CartesianStateWithSTM; showfloats=true, space="") = show(io, state; showfloats=showfloats, space=space)
"""
A Keplerian state vector with length 6. Internally
uses `MVector` and `LVector` to store data.
Data is accessible via labels, which are
`e, a, i, Ξ©, Ο, Ξ½`.
"""
mutable struct KeplerianState{F, LU, TU, AU} <: StateVector{F, LU, TU, AU, (e=1, a=2, i=3, Ξ©=4, Ο=5, Ξ½=6)}
__rawdata::LArray{F, 1, MVector{6, F}, (e=1, a=2, i=3, Ξ©=4, Ο=5, Ξ½=6)}
function KeplerianState(statevector; lengthunit=u"km", timeunit=u"s", angularunit=u"rad")
F = eltype(statevector)
F isa AbstractFloat || (F = Float64)
return new{F, lengthunit, timeunit, angularunit}(
statevector
)
end
end
"""
Constructs a `KeplerianState` from any `AbstractVector`.
"""
KeplerianState{F, LU, TU, AU}(statevector::AbstractVector{<:Real}) where {F, LU, TU, AU} = KeplerianState(
convert(LArray{F, 1, MVector{6, F}, (e=1, a=2, i=3, Ξ©=4, Ο=5, Ξ½=6)}, statevector);
lengthunit = LU, timeunit=TU, angularunit=AU
)
"""
Constructs a `KeplerianState` from provided position and velocity vectors.
"""
function KeplerianState(e::Real, a, i, Ξ©, Ο, Ξ½;
lengthunit=(a isa Unitful.Length ? unit(a) : u"km"),
timeunit=u"s",
angularunit=(i isa DimensionlessQuantity ? unit(i) : u"rad"))
aa = (a isa Unitful.Length ? ustrip(lengthunit, a) : a)
ii = (i isa Unitful.DimensionlessQuantity ? ustrip(angularunit, i) : i)
ΩΩ = (Ω isa Unitful.DimensionlessQuantity ? ustrip(angularunit, Ω) : Ω)
ΟΟ = (Ο isa Unitful.DimensionlessQuantity ? ustrip(angularunit, Ο) : Ο)
Ξ½Ξ½ = (Ξ½ isa Unitful.DimensionlessQuantity ? ustrip(angularunit, Ξ½) : Ξ½)
F = promote_type(typeof(e), typeof(aa), typeof(ii), typeof(ΩΩ), typeof(ΟΟ), typeof(Ξ½Ξ½))
F <: AbstractFloat || (F = Float64)
return KeplerianState{F, lengthunit, timeunit, angularunit}(@LArray(MVector{6,F}(e,aa,ii,ΩΩ,ΟΟ,Ξ½Ξ½),(e=1, a=2, i=3, Ξ©=4, Ο=5, Ξ½=6)))
end
"""
Returns `e`.
"""
get_e(state::KeplerianState) = state[1]
"""
Returns `a`.
"""
get_a(state::KeplerianState) = state[2]
"""
Returns `i`.
"""
get_i(state::KeplerianState) = state[3]
"""
Returns `Ξ©`.
"""
get_Ξ©(state::KeplerianState) = state[4]
"""
Returns `Ο.
"""
get_Ο(state::KeplerianState) = state[5]
"""
Returns `Ξ½`.
"""
get_Ξ½(state::KeplerianState) = state[6]
"""
Returns the whole state vector, without units.
"""
statevector(state::KeplerianState) = MVector{6}(get_e(state), get_a(state) * lengthunit(state), get_i(state) * angularunit(state), get_Ξ©(state) * angularunit(state), get_Ο(state) * angularunit(state), get_Ξ½(state) * angularunit(state))
"""
Displays a `KeplerianState`.
"""
function Base.show(io::IO, state::KeplerianState; showfloats=true, space="")
println(io, space, "Keplerian State", showfloats ? " with eltype $(eltype(state))" : "", "\n")
println(io, space, " ", "e = $(get_e(state))")
println(io, space, " ", "a = $(get_a(state) * lengthunit(state))")
println(io, space, " ", "Ξ© = $(get_Ξ©(state) * angularunit(state))")
println(io, space, " ", "Ο = $(get_Ο(state) * angularunit(state))")
println(io, space, " ", "Ξ½ = $(get_Ξ½(state) * angularunit(state))")
end
Base.show(io::IO, ::MIME"text/plain", state::KeplerianState; showfloats=true, space="") = show(io, state; showfloats=showfloats, space=space)
"""
Returns `true` if the `AbstractState` has `lengthunit` and `timeunit`
parameters of some type `T <: AbstractQuantity`. This is
intended to be used for normalizing `CartesianState` vectors.
"""
isnormalized(state::AbstractState) = lengthunit(state) isa Unitful.AbstractQuantity && timeunit(state) isa Unitful.AbstractQuantity
"""
Converts types and units for a `CartesianState`.
"""
function Base.convert(::Type{CartesianState{F, LU, TU, AU}}, state::CartesianState) where {F, LU, TU, AU}
r = States.get_r(state) .* lengthunit(state) ./ LU .|> upreferred .|> F
v = States.get_v(state) .* velocityunit(state) ./ (LU/TU) .|> upreferred .|> F
return CartesianState(vcat(r,v); lengthunit=LU, timeunit=TU, angularunit=AU)
end
"""
Converts types and units for a `CartesianState`.
"""
function Base.convert(::Type{KeplerianState{F, LU, TU, AU}}, state::KeplerianState) where {F, LU, TU, AU}
e = get_e(state) |> F
a = ustrip(LU, get_a(state) * lengthunit(state)) |> F
i = ustrip(AU, get_i(state) * angularunit(state)) |> F
Ξ© = ustrip(AU, get_Ξ©(state) * angularunit(state)) |> F
Ο = ustrip(AU, get_Ο(state) * angularunit(state)) |> F
Ξ½ = ustrip(AU, get_Ξ½(state) * angularunit(state)) |> F
return KeplerianState(MVector{6}(e, a, i, Ξ©, Ο, Ξ½); lengthunit=LU, timeunit=TU, angularunit=AU)
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1167 | #
# CR3BP systems in our solar system
#
"""
The Sun-Earth CR3BP system.
"""
const SunVenus = CR3BPParameters(get_ΞΌ(Sun) * massparamunit(Sun), get_ΞΌ(Venus) * massparamunit(Venus), 108.2e6u"km"; primary=:Sun, secondary=:Venus)
"""
The Sun-Earth CR3BP system.
"""
const SunEarth = CR3BPParameters(get_ΞΌ(Sun) * massparamunit(Sun), get_ΞΌ(Earth) * massparamunit(Earth), 1.0u"AU"; primary=:Sun, secondary=:Earth)
"""
The Earth-Moon CR3BP system.
"""
const EarthMoon = CR3BPParameters(get_ΞΌ(Earth) * massparamunit(Earth), get_ΞΌ(Moon) * massparamunit(Moon), 384400u"km"; primary=:Earth, secondary=:Moon)
"""
The Sun-Mars CR3BP system.
"""
const SunMars = CR3BPParameters(get_ΞΌ(Sun) * massparamunit(Sun), get_ΞΌ(Mars) * massparamunit(Mars), 227.9e6u"km"; primary=:Sun, secondary=:Mars)
"""
The Sun-Jupiter CR3BP system.
"""
const SunJupiter = CR3BPParameters(get_ΞΌ(Sun) * massparamunit(Sun), get_ΞΌ(Jupiter) * massparamunit(Jupiter), 778.6e6u"km"; primary=:Sun, secondary=:Jupiter)
"""
The Sun-Saturn CR3BP system.
"""
const SunSaturn = CR3BPParameters(get_ΞΌ(Sun) * massparamunit(Sun), get_ΞΌ(Saturn) * massparamunit(Saturn), 1433.5e6u"km"; primary=:Sun, secondary=:Saturn)
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 5601 | #
# Provides concrete types under `ParameterizedLabelledArray`
# which contain parameters to describe astrodynamic systems.
#
"""
A supertype for parameter representations in astrodynamics.
"""
abstract type ParameterVector{F, MU, LU, TU, AU, N, T, B} <: ParameterizedLabelledArray{F, 1, T, SLArray{Tuple{N},F,1,N,T}} end
"""
Returns the mass unit of the parameter vector.
"""
Base.@pure massunit(::ParameterVector{F, MU, LU, TU, AU, N}) where {F, MU, LU, TU, AU, N} = MU
"""
Returns the length unit of the parameter vector.
"""
Base.@pure lengthunit(::ParameterVector{F, MU, LU, TU, AU, N}) where {F, MU, LU, TU, AU, N} = LU
"""
Returns the time unit of the parameter vector.
"""
Base.@pure timeunit(::ParameterVector{F, MU, LU, TU, AU, N}) where {F, MU, LU, TU, AU, N} = TU
"""
Returns the angular unit of the parameter vector.
"""
Base.@pure angularunit(::ParameterVector{F, MU, LU, TU, AU, N}) where {F, MU, LU, TU, AU, N} = AU
"""
Returns the velocity unit of the state vector.
"""
velocityunit(::ParameterVector{F, MU, LU, TU, AU}) where {F, MU, LU, TU, AU} = LU/TU
"""
Returns the mass-parameter unit of the state vector.
"""
massparamunit(::ParameterVector{F, MU, LU, TU, AU}) where {F, MU, LU, TU, AU} = LU^3/TU^2
"""
Returns the length of the parameter vector.
"""
Base.@pure Base.length(::ParameterVector{F, MU, LU, TU, AU, N}) where {F, MU, LU, TU, AU, N} = N
"""
Returns the size of the parameter vector.
"""
Base.@pure Base.size(::ParameterVector{F, MU, LU, TU, AU, N}) where {F, MU, LU, TU, AU, N} = (N,)
"""
Returns the name of the parameter vector.
"""
name(::ParameterVector{F, MU, LU, TU, AU, N, T, B}) where {F, MU, LU, TU, AU, N, T, B} = B
"""
All parameters required for the Restricted Two-body Problem.
"""
struct R2BPParameters{F, MU, LU, TU, AU, B} <: ParameterVector{F, MU, LU, TU, AU, 1, (:ΞΌ,), B}
__rawdata::SLArray{Tuple{1}, F, 1, 1, (:ΞΌ,)}
function R2BPParameters(ΞΌ; massunit=u"kg", lengthunit=u"km", timeunit=u"s", angularunit=u"Β°", name=:Primary)
ΞΌΞΌ = (ΞΌ isa Unitful.AbstractQuantity) ? ustrip(lengthunit^3/timeunit^2, ΞΌ) : ΞΌ
F = eltype(ΞΌΞΌ)
F isa AbstractFloat || (F = Float64)
B = Symbol(name)
return new{F, massunit, lengthunit, timeunit, angularunit, B}(SLArray{Tuple{1}, F, 1, 1, (:ΞΌ,)}(ΞΌΞΌ))
end
end
"""
Returns the normalized mass parameter, `ΞΌ`.
"""
get_ΞΌ(sys::R2BPParameters) = sys[1]
"""
Displays `R2BPParameters`.
"""
function Base.show(io::IO, state::R2BPParameters; showfloats=true, space="")
println(io, space, "R2BP parameters ", name(state) == "Primary" ? "" : "for the $(name(state)) system", showfloats ? " with eltype $(eltype(state))" : "", "\n")
println(io, space, " ", "ΞΌ = ", get_ΞΌ(state), " ", massparamunit(state))
end
Base.show(io::IO, ::MIME"text/plain", state::R2BPParameters; kwargs...) = Base.show(io, state; kwargs...)
"""
Converts types and units for a `R2BPParameters`.
"""
function Base.convert(::Type{R2BPParameters{F, MU, LU, TU, AU}}, system::R2BPParameters) where {F, MU, LU, TU, AU}
B = name(system)
ΞΌ = ustrip(LU^3/TU^2, get_ΞΌ(system) * massparamunit(system)) |> F
return R2BPParameters(ΞΌ; massunit=MU, lengthunit=LU, timeunit=TU, angularunit=AU, name=B)
end
"""
All parameters required for the Circular Restricted Three-body Problem.
"""
struct CR3BPParameters{F, MU, LU, TU, AU, B} <: ParameterVector{F, MU, LU, TU, AU, 1, (:ΞΌ,), B}
__rawdata::SLArray{Tuple{1}, F, 1, 1, (:ΞΌ,)}
function CR3BPParameters(ΞΌ::Real; massunit=u"kg", lengthunit=missing, timeunit=missing, angularunit=u"Β°", primary=:Primary, secondary=:Secondary)
@assert ΞΌ β€ 1//2 "Nondimensional mass parameter must be less than 1/2, by definition! Received $ΞΌ."
F = typeof(ΞΌ)
F isa AbstractFloat || (F = Float64)
B = (Symbol(primary), Symbol(secondary))
return new{F, massunit, lengthunit, timeunit, angularunit, B}(SLArray{Tuple{1}, F, 1, 1, (:ΞΌ,)}(ΞΌ))
end
function CR3BPParameters(ΞΌβ::Unitful.AbstractQuantity, ΞΌβ::Unitful.AbstractQuantity, a::Unitful.Length; massunit=u"kg", angularunit=u"Β°", primary=:Primary, secondary=:Secondary)
βΞΌα΅’ = ΞΌβ + ΞΌβ
ΞΌ = min(ΞΌβ, ΞΌβ) / βΞΌα΅’
TU = 2Ο * upreferred(β(a^3 / βΞΌα΅’))
F = typeof(ΞΌ)
F isa AbstractFloat || (F = Float64)
B = (Symbol(primary), Symbol(secondary))
return new{F, massunit, a, TU, angularunit, B}(SLArray{Tuple{1}, F, 1, 1, (:ΞΌ)}(F(ΞΌ)))
end
end
"""
Returns the normalized mass parameter, `ΞΌ`.
"""
get_ΞΌ(sys::CR3BPParameters) = sys[1]
"""
Displays a `CR3BPParameters` instance.
"""
function Base.show(io::IO, sys::CR3BPParameters; showfloats=true, space="")
sysname = all(name(sys) .== (:Primary, :Secondary)) ? "" : begin (n1, n2) = name(sys); string(" for the ", n1, "-", n2, " system") end
println(io, space, "CR3BP parameters", sysname, showfloats ? " with eltype $(eltype(sys))" : "", "\n")
println(io, space, " ", "ΞΌ = ", get_ΞΌ(sys))
end
Base.show(io::IO, ::MIME"text/plain", sys::CR3BPParameters; kwargs...) = Base.show(io::IO, sys::CR3BPParameters; kwargs...)
"""
Converts types and units for a `CR3BPParameters`.
"""
function Base.convert(::Type{CR3BPParameters{F, MU, LU, TU, AU}}, system::CR3BPParameters) where {F, MU, LU, TU, AU}
B = name(system)
ΞΌ = get_ΞΌ(system)
ΞΌβ, ΞΌβ = let
βΞΌα΅’ = TU^3 / (TU / 2Ο)^2
ΞΌβ = ΞΌ * βΞΌα΅’
ΞΌβ = βΞΌα΅’ - ΞΌβ
ΞΌβ, ΞΌβ
end
ΞΌβ = min(ΞΌβ, ΞΌβ) / (ΞΌβ + ΞΌβ)
return CR3BPParameters(ΞΌβ; massunit=MU, lengthunit=LU, timeunit=TU, angularunit=AU, primary=name(system)[1], secondary=name(system)[2])
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1487 | #
# R2BP systems in our solar system
#
"""
Constant `R2BPParameters` for our sun!
"""
const Sun = R2BPParameters(1.327124400419393e11u"km^3/s^2"; name=:Sun)
"""
Constant `R2BPParameters` for Mercury.
"""
const Mercury = R2BPParameters(22031.78000000002u"km^3/s^2"; name=:Mercury)
"""
Constant `R2BPParameters` for Venus.
"""
const Venus = R2BPParameters(324858.592u"km^3/s^2"; name=:Venus)
"""
Constant `R2BPParameters` for your home planet!
"""
const Earth = R2BPParameters(398600.4354360959u"km^3/s^2"; name=:Earth)
"""
Constant `R2BPParameters` for our moon.
"""
const Moon = R2BPParameters(4902.800066163796u"km^3/s^2"; name=:Moon)
"""
Constant `R2BPParameters` (alias for our mooon).
"""
const Luna = Moon
"""
Constant `R2BPParameters` for Mars.
"""
const Mars = R2BPParameters(42828.37362069909u"km^3/s^2"; name=:Mars)
"""
Constant `R2BPParameters` for Jupiter.
"""
const Jupiter = R2BPParameters(1.2668653492180079e8u"km^3/s^2"; name=:Jupiter)
"""
Constant `R2BPParameters` for Saturn.
"""
const Saturn = R2BPParameters(3.793120749865224e7u"km^3/s^2", name=:Saturn)
"""
Constant `R2BPParameters` for Uranus.
"""
const Uranus = R2BPParameters(5.793951322279009e6u"km^3/s^2"; name=:Uranus)
"""
Constant `R2BPParameters` for Neptune.
"""
const Neptune = R2BPParameters(6.835099502439672e6u"km^3/s^2"; name=:Neptune)
"""
Constant `R2BPParameters` for Pluto. We couldn't leave you out again!
"""
const Pluto = R2BPParameters(869.6138177608749u"km^3/s^2"; name=:Pluto)
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1537 | """
A module which provides visualizations
for `Trajectory` and `Manifold`
instances, as well as other
common astrodynamical visualizations.
# Extended Help
**Exports**
$(EXPORTS)
**Imports**
$(IMPORTS)
"""
module Visualizations
export zerovelocityplot, zerovelocityplot!
using Plots, RecipesBase
using DifferentialEquations
using ..Calculations
using ..CoordinateFrames
using ..States, ..Propagation
using DocStringExtensions
@template (FUNCTIONS, METHODS, MACROS) =
"""
$(SIGNATURES)
$(DOCSTRING)
"""
@template (TYPES, CONSTANTS) =
"""
$(TYPEDEF)
$(DOCSTRING)
"""
"""
Rather than supply indices, users can use `Symbol`
instances to select indices for plotting.
# Example
traj = propagate(orbit, period)
plot(traj; vars=:tx)
plot(traj; vars=xyz)
plot(traj; vars=xxΜ)
"""
function process_vars(vars::Symbol)
@assert 2 β€ length(string(vars)) β€ 3 "Keyword argument `vars` has an inproper length $(length(vars)). Choose a length in [2, 3]."
@assert sum(c -> count(c, lowercase(string(vars))), ("t", "x", "y", "z", "xΜ", "yΜ", "zΜ")) == length(string(vars)) "Invalid character provided in `vars`."
indices = Dict(
"t" => 0,
"x" => 1,
"y" => 2,
"z" => 3,
"xΜ" => 4,
"yΜ" => 5,
"zΜ" => 6
)
return [indices[string(char)] for char β lowercase(string(vars))]
end
include(joinpath("Trajectories", "Trajectories.jl"))
include(joinpath("Manifolds", "Manifolds.jl"))
include(joinpath("Energy", "Energy.jl"))
end # module
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1698 | #
# Visualizations related to orbital energy
#
# These are not fully implemented!
"""
Plot the zero velocity curves for the Synodic, normalized CR3BP system.
"""
function zerovelocityplot(orbit::CR3BPOrbit;
nondimensional_range = range(-2; stop=2, length=1000),
kwargs...)
curves = zerovelocity_curves(orbit; nondimensional_range = nondimensional_range)
default = (; title = "Zero Velocity Curves" * (name(system(orbit)) == (:Primary, :Secondary) ? "" : " for the $(name(system(orbit))[1])-$(name(system(orbit))[2]) System"),
xlabel = "X ($(lengthunit(orbit)))",
ylabel = "Y ($(lengthunit(orbit)))",
labels = :none,
formatter = :plain,
grid = :on,
linewidth = 2,
dpi = 150)
options = merge(default, kwargs)
fig = plot(; options...)
for curve β curves
plot!(fig, curve[:,1], curve[:,2]; kwargs...)
end
return fig
end
"""
Plot the zero velocity curves for the Synodic, normalized CR3BP
system to the last figure.
"""
function zerovelocityplot!(fig, orbit::CR3BPOrbit;
nondimensional_range = range(-2; stop=2, length=1000),
kwargs...)
curves = zerovelocity_curves(orbit; nondimensional_range = nondimensional_range)
default = (; )
options = merge(default, kwargs)
fig = plot!(; options...)
for (i,curve) β zip(1:length(curves), curves)
plot!(fig, curve[:,1], curve[:,2]; kwargs...)
end
return fig
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1885 | #
# Plots for CR3BP manifolds
#
function Plots.plot(manifold::Manifold; vars=:XYZ, kwargs...)
indices = vars isa Tuple ? vars : process_vars(vars)
labels = Dict(
0 => "Time" * " ($(timeunit(manifold)))",
1 => "X" * " ($(lengthunit(manifold)))",
2 => "Y" * " ($(lengthunit(manifold)))",
3 => "Z" * " ($(lengthunit(manifold)))",
4 => "XΜ" * " ($(velocityunit(manifold)))",
5 => "YΜ" * " ($(velocityunit(manifold)))",
6 => "ZΜ" * " ($(velocityunit(manifold)))"
)
defaults = (;
linewidth = 1,
linestyle = :dot,
title = "Manifold",
palette = :blues,
dpi = 150,
label = :none,
xguide = labels[indices[1]],
yguide = labels[indices[2]],
zguide = length(indices) == 3 ? labels[indices[3]] : :none,
)
options = merge(defaults, kwargs)
fig = plot(; options...)
for trajectory β manifold.solution.u
plot!(trajectory; vars=vars, options...)
end
return fig
end
function Plots.plot!(manifold::Manifold; vars=:XYZ, kwargs...)
defaults = (;
linewidth = 1,
linestyle = :dot,
palette = :blues,
dpi = 150,
label = :none,
)
options = merge(defaults, kwargs)
for trajectory β manifold.solution.u[1:end-1]
plot!(trajectory; vars=vars, options...)
end
plot!(manifold.solution.u[end]; vars=vars, options...)
end
function Plots.plot!(fig, manifold::Manifold; vars=:XYZ, kwargs...)
defaults = (;
linewidth = 1,
linestyle = :dot,
palette = :blues,
dpi = 150,
label = :none,
)
options = merge(defaults, kwargs)
for trajectory β manifold.solution.u
plot!(fig, trajectory; vars=vars, options...)
end
return fig
end | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 2026 | #
# Plot recipes for trajectories!
#
@recipe function f(trajectory::Trajectory; vars=:XYZ, timerange=range(first(trajectory.solution.t); stop=last(trajectory.solution.t), length=1000))
linewidth --> 1.75
title --> "Trajectory"
dpi --> 150
label --> :none
indices = vars isa Tuple ? vars : process_vars(vars)
labels = Dict(
0 => "Time" * " ($(timeunit(trajectory)))",
1 => "X" * " ($(lengthunit(trajectory)))",
2 => "Y" * " ($(lengthunit(trajectory)))",
3 => "Z" * " ($(lengthunit(trajectory)))",
4 => "XΜ" * " ($(velocityunit(trajectory)))",
5 => "YΜ" * " ($(velocityunit(trajectory)))",
6 => "ZΜ" * " ($(velocityunit(trajectory)))"
)
xguide --> labels[indices[1]]
yguide --> labels[indices[2]]
if length(indices) == 3
zguide --> labels[indices[3]]
end
getdata(index) = index == 0 ? timerange : map(t -> trajectory(t; idxs=index), timerange)
getdata.((indices...,))
end
@recipe function f(trajectory::AbstractVector{<:Orbit}; vars=:XYZ)
linewidth --> 1.75
title --> "Trajectory"
dpi --> 150
label --> :none
indices = vars isa Tuple ? vars : process_vars(vars)
labels = Dict(
0 => "Time" * " ($(timeunit(first(trajectory))))",
1 => "X" * " ($(lengthunit(first(trajectory))))",
2 => "Y" * " ($(lengthunit(first(trajectory))))",
3 => "Z" * " ($(lengthunit(first(trajectory))))",
4 => "XΜ" * " ($(velocityunit(first(trajectory))))",
5 => "YΜ" * " ($(velocityunit(first(trajectory))))",
6 => "ZΜ" * " ($(velocityunit(first(trajectory))))"
)
xguide --> labels[indices[1]]
yguide --> labels[indices[2]]
if length(indices) == 3
zguide --> labels[indices[3]]
end
getdata(index) = index == 0 ? map(epoch, trajectory) : map(orbit -> state(orbit)[index], trajectory)
getdata.((indices...,))
end
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1166 | """
Circular Restricted Three-body Model tests.
"""
module CR3BPTests
using LinearAlgebra, Unitful, UnitfulAstro, GeneralAstrodynamics, Test
@testset verbose=false "CR3BP Determination" begin
@testset "Unitful" begin
r = [1.007988, 0.0, 0.001864]u"AU"
v = [0, 0, 0]u"AU/s"
orbit = Orbit(CartesianState(r, v), SunEarth)
@test all(orbit.state.r .β [1.007988, 0.0, 0.001864])
@test all(orbit.state.v .β zeros(3))
end
@testset "No Units" begin
r = [1.2, 0, 0]
v = [0, -1.049357509830343, 0]
ΞΌ = 0.012150585609624
units = (; lengthunit=missing, timeunit=missing, angularunit=missing)
@test_broken Orbit(
CartesianState(r, v; units...),
CR3BPParameters(ΞΌ; massunit=missing, units...)
).state β vcat(r,v)
end
end
@testset verbose=false "CR3BP Calculations" begin
r = [1.007988, 0.0, 0.001864]u"AU"
v = [0, 0, 0]u"AU/s"
orbit = Orbit(CartesianState(r, v), SunEarth)
@test jacobi_constant(orbit) β 3.000907212196274
@test_broken synodic(inertial(orbit)) β orbit
end
end # module | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1562 | """
Circular Restricted Three-body Model tests.
"""
module PropagationTests
using LinearAlgebra, Unitful, UnitfulAstro, GeneralAstrodynamics, Test
using DifferentialEquations
@testset verbose = false "R2BP Propagation" begin
orbit = let planet = Mars
e = 0.4
a = 10_000
i = 0
Ξ© = 0
Ο = 0
Ξ½ = 0
state = KeplerianState(e, a, i, Ξ©, Ο, Ξ½)
state = CartesianState(cartesian(state, massparameter(planet))...)
Orbit(state, planet)
end
traj = propagate(orbit, period(orbit); save_everystep=false)
@test traj[end] β state(orbit)
end
@testset verbose = false "CR3BP Propagation" begin
@test isperiodic(halo(SunEarth; L=2, Az=0.0005)...)
@test isperiodic(halo(SunMars; L=1, Az=0.0005)...)
@test isperiodic(halo(EarthMoon; L=2, Az=0.0005)...)
@test isperiodic(halo(SunJupiter; L=1, Az=0.0005)...)
orbit, T = halo(SunJupiter; L=2, Az=0)
@test isapprox.(
monodromy(orbit, T), [
1177.6158450389235 -43.31366732210663 0.0 247.08544503455505 227.41064838834146 0.0
-1085.995406851377 40.86470821207657 0.0 -227.41064838735218 -209.97647807144125 0.0
0.0 0.0 0.9966422601737439 0.0 0.0 -0.09182654535515093
3446.1566018075323 -126.52938312132042 0.0 722.7945482654276 666.0424507143235 0.0
-2146.972890519174 79.03452084349573 0.0 -450.8572227441975 -413.95658856183604 0.0
0.0 0.0 0.07300944628976104 0.0 0.0 0.99664226017845
]; atol=1e-2
) |> all
end
end # module
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 2554 | """
Restricted Two-body Model tests.
"""
module R2BPTests
using LinearAlgebra, Unitful, GeneralAstrodynamics, Test
@testset verbose=false "R2BP Determination" begin
rα΅’ = [0.0, 11681.0, 0.0] * u"km"
vα΅’ = [5.134, 4.226, 2.787] * u"km/s"
corbit = Orbit(CartesianState(rα΅’, vα΅’), Earth)
@test all(
keplerian(corbit) .β (
0.723452708202361,
24509.265399338536u"km",
151.50460766373865u"Β°",
90.0u"Β°",
270.0034742609256u"Β°",
89.99652573907436u"Β°"
)
)
@test CartesianState(cartesian(KeplerianState(keplerian(corbit)...), massparameter(Earth))...) β state(corbit)
korbit = Orbit(
KeplerianState(
0.723452708202361,
24509.265399338536u"km",
151.50460766373865u"Β°",
90.0u"Β°",
270.0034742609256u"Β°",
89.99652573907436u"Β°"
),
Earth
)
@test all(
upreferred.(statevector(KeplerianState(keplerian(cartesian(korbit)..., massparameter(Earth))...))) .β
upreferred.(statevector(KeplerianState(keplerian(corbit)...)))
)
end
@testset verbose=false "Kepler's Algorithm" begin
@testset "Unitful" begin
rα΅’ = [0.0, 11681.0, 0.0] * u"km"
vα΅’ = [5.134, 4.226, 2.787] * u"km/s"
corbit = Orbit(CartesianState(rα΅’, vα΅’), Earth)
@test all(upreferred.(statevector(state(kepler(corbit)))) .β upreferred.(statevector(state(corbit))))
end
end
@testset verbose=true "Lambert Solvers" begin
@testset "Universal" begin
rα΅’ = [0.0, 11681.0, 0.0]u"km"
vα΅’ = [5.134, 4.226, 2.787]u"km/s"
initial = Orbit(CartesianState(rα΅’, vα΅’), Earth)
Ξt = 1000u"s"
final = kepler(initial, Ξt; tol=1e-12)
vβ, vβ = lambert_universal(position(initial), position(final), massparameter(Earth), Ξt; trajectory=:short, tolerance=1e-6, max_iter=1000)
@test all(vβ .β velocity(initial))
@test all(vβ .β velocity(final))
end
@testset "Oldenhuis" begin
rα΅’ = [0.0, 11681.0, 0.0]u"km"
vα΅’ = [5.134, 4.226, 2.787]u"km/s"
initial = Orbit(CartesianState(rα΅’, vα΅’), Earth)
Ξt = 1000u"s"
final = kepler(initial, Ξt; tol=1e-12)
m = 0
vβ, vβ = lambert(position(initial), position(final), Ξt, m, massparameter(Earth))
@test_skip all(vβ .β velocity(initial))
@test_skip all(vβ .β velocity(final))
end
end
end # module | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 1244 | """
Orbit visualization tests. Do plots run without error?
"""
module VisualizationTests
using LinearAlgebra, Unitful, UnitfulAstro, GeneralAstrodynamics, Test
using DifferentialEquations
using Plots
@testset verbose=false "Trajectory Plots" begin
# CR3BP trajectory
L2Halo = halo(SunEarth; Az = 30_000u"km", L = 2)
traj = propagate(L2Halo...)
try
plot(traj)
@test true
catch e
@test false
end
# Discrete trajectory
traj = map(t -> Orbit(traj, t), solution(traj).t)
try
plot(traj)
@test true
catch e
@test false
end
# Close all plots
Plots.closeall()
end
@testset verbose=false "Manifold Plots" begin
# CR3BP manifold
L2Halo = halo(SunEarth; Az = 30_000u"km", L = 2)
@test begin
plot(manifold(L2Halo...))
true
end
# Close all plots
Plots.closeall()
end
@testset verbose=false "Energy Plots" begin
# CR3BP trajectory
L2Halo = halo(EarthMoon; Az = 15_000u"km", L = 2)
# CR3BP zero velocity curves
try
zerovelocityplot(L2Halo.orbit)
@test true
catch e
@test false
end
# Close all plots
Plots.closeall()
end
end # module | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | code | 139 | #
# Unit tests for UnitfulAstrodynamics.jl
#
include("R2BP.jl")
include("CR3BP.jl")
include("Propagation.jl")
include("Visualizations.jl") | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | docs | 3353 | # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | docs | 3314 | [](https://github.com/cadojo/GeneralAstrodynamics.jl/actions?query=workflow%3ATests)
[](https://cadojo.github.io/GeneralAstrodynamics.jl/)
# GeneralAstrodynamics.jl
_Common astrodynamics calculations, with units!_
## JuliaCon Talk
Check out `GeneralAstrodynamics` in action at JuliaCon 2021! The talk
[_Going to Jupiter with Julia_](https://www.youtube.com/watch?v=WnvKaUsGv8w)
walks through a simple Jupiter mission design while gently introducing
astrodynamics, Julia, and `GeneralAstrodynamics`.
## Features
### Restricted Two-body Problem (R2BP)
- Structures for Cartesian and Keplerian states, and R2BP systems
- Functions which implement common R2BP equations
- Kepler and Lambert solvers
- Orbit propagation and plotting
### Circular Restricted Three-body Problem (CR3BP)
- Structures for dimensioned and normalized Cartesian states, and dimensioned
and normalized CR3BP systems
- Functions which implement common CR3BP equations
- Analytical and iterative (numerical) Halo orbit solvers
- Unstable and stable Halo orbit manifold computation
- Orbit propagation and plotting
- Zero-velocity curve computation and plotting
### N-body Problem (NBP)
- This was implemented in a previous package version, and is currently being
refactored
## Usage
Some quick examples are below!
```julia
# Installation
import Pkg
Pkg.add("GeneralAstrodynamics") # or julia> ]install GeneralAstrodynamics
# Loading
using GeneralAstrodynamics, Unitful
# Construct a R2BP orbit (massless spacecraft
# moving due to the gravity of one planet)
orbit = let e = 0.4, a = 10_000, i = Ξ© = Ο = Ξ½ = 0, planet = Earth
orbitalstate = KeplerianState(e, a, i, Ξ©, Ο, Ξ½)
Orbit(orbitalstate, Earth)
end
# Alternatively, use a `CartesianState`
orbit = Orbit(
CartesianState(randn(6)), # random state vector, [r..., v...]
Earth
)
# Construct a CR3BP orbit (massless spacecraft moving
# due to the gravity of two planets, both of which
# move in a circle about their common center of mass)
orbit = Orbit(
CartesianState(randn(6)), # random state vector (again!)
SunEarth
)
# Propagate any orbit in time (after `using DifferentialEquations`)
using DifferentialEquations
trajectory = propagate(orbit, 10u"d") # unitful times are convenient here!
# Constract a periodic orbit within CR3BP dynamics (Halo orbit),
# and the orbital period `T` (also requires `DifferentialEquations`)
orbit, T = halo(SunEarth; L=1, Az=75_000u"km")
# Construct a manifold which converges to (stable), or
# diverges from (unstable) the Halo orbit
superslide = manifold(orbit, T; duration=2T, eps=-1e8, direction=Val{:stable})
# Plot any `Trajectory` or `Manifold` (after `using Plots`)
using Plots
plot(trajectory; title="R2BP Trajectory")
plot(propagate(orbit, T); vars=:XY, label="Halo Orbit", aspect_ratio=1)
plot(superslide; vars=:XY, title="Stable Manifold near Earth")
```
In the coming years, the
[Getting Started](https://cadojo.github.io/GeneralAstrodynamics.jl/dev/) page
will have code examples, and other documentation for fundamental astrodynamics
concepts, and `GeneralAstrodynamics` usage. Stay tuned and/or submit pull
requests!
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | docs | 664 | # Docstrings
_Documentation for all types, and functions in `GeneralAstrodynamics`._
## `CoordinateFrames`
```@autodocs
Modules = [
GeneralAstrodynamics.CoordinateFrames
]
Order = [:type, :function]
```
## `Calculations`
```@autodocs
Modules = [
GeneralAstrodynamics.Calculations
]
Order = [:type, :function]
```
## `States`
```@autodocs
Modules = [
GeneralAstrodynamics.States
]
Order = [:type, :function]
```
## `Propagation`
```@autodocs
Modules = [
GeneralAstrodynamics.Propagation
]
Order = [:type, :function]
```
## `Visualizations`
```@autodocs
Modules = [
GeneralAstrodynamics.Visualizations
]
Order = [:type, :function]
``` | GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 0.11.0 | fa78fedc1f3000cbf10d9ba8e935aa2711444d5f | docs | 384 | # GeneralAstrodynamics.jl
_Common astrodynamics calculations in Julia, with units!_
!!! note
This package is fairly new, and documentation is even newer!
Thanks for your patience as we get these docs up and running.
For now, all we can offer are some humble docstrings.
If you check back in September, you'll probably find
some more detailed documentation, and examples!
| GeneralAstrodynamics | https://github.com/JuliaAstro/GeneralAstrodynamics.jl.git |
|
[
"MIT"
] | 1.1.5 | 8c6bb3edae13e0a3c5479baf23658384ac3576bd | code | 230 | using Documenter, MixedSubdivisions
makedocs(
sitename = "MixedSubdivisions.jl",
pages = [
"MixedSubdivisions" => "index.md",
]
)
deploydocs(
repo = "github.com/saschatimme/MixedSubdivisions.jl.git",
)
| MixedSubdivisions | https://github.com/saschatimme/MixedSubdivisions.jl.git |
|
[
"MIT"
] | 1.1.5 | 8c6bb3edae13e0a3c5479baf23658384ac3576bd | code | 56443 | module MixedSubdivisions
export mixed_volume,
MixedCellIterator,
MixedCell,
mixed_cells,
fine_mixed_cells,
is_fine,
volume,
normal,
indices,
support
import LinearAlgebra
import MultivariatePolynomials as MP
import ProgressMeter
import StaticArrays: SVector
import Base: checked_add, checked_sub
β(x::Integer, y::Integer) = Base.checked_mul(x, y)
β(x::Integer, y::Integer) = Base.checked_add(x, y)
β(x::Integer, y::Integer) = Base.checked_sub(x, y)
"""
MuliplicativeInverse(a::Signed)
Computes a multiplicative inverse of a signed integer `a`.
Currently the only supported function `div`.
"""
struct MuliplicativeInverse{T<:Signed}
a::T # a = p * 2^k
p::T
p_inv::T # multiplicative inverse of p
shift::UInt8
end
function MuliplicativeInverse(a)
k = convert(UInt8, trailing_zeros(a))
p = a >> k
p_inv = multiplicative_inverse_odd(p)
MuliplicativeInverse(a, p, p_inv, k)
end
shift!(x::T, inv::MuliplicativeInverse{T}) where {T} = x >> inv.shift
needs_shift(inv::MuliplicativeInverse) = inv.shift != 0
"""
multiplicative_inverse_odd(x)
Every odd integer has a multiplicative inverse in β€ / mod 2^M.
We can find this by using Newton's method.
See this blogpost for more details:
https://lemire.me/blog/2017/09/18/computing-the-inverse-of-odd-integers/
"""
function multiplicative_inverse_odd(x::Int32)
y = xor(Int32(3) * x, Int32(2)) # this gives an accuracy of 5 bits
Base.Cartesian.@nexprs 3 _ -> y = newton_step(x, y)
end
function multiplicative_inverse_odd(x::Int64)
y = xor(Int64(3) * x, Int64(2)) # this gives an accuracy of 5 bits
Base.Cartesian.@nexprs 4 _ -> y = newton_step(x, y)
end
function multiplicative_inverse_odd(x::Int128)
y = xor(Int128(3) * x, Int128(2)) # this gives an accuracy of 5 bits
Base.Cartesian.@nexprs 6 _ -> y = newton_step(x, y)
end
newton_step(x, y) = y * (oftype(x, 2) - y * x)
"""
cayley(Aα΅’...)
Construct the cayley matrix of the given point configurations.
"""
cayley(A::AbstractMatrix...) = cayley(A)
function cayley(A)
n = size(A[1], 1)
I = eltype(A[1])
# make sure that all matrices have the same number of rows
m = size(A[1], 2)
for i = 2:length(A)
size(A[i], 1) == n || error("Matrices do not have the same number of rows.")
m += size(A[i], 2)
end
C = zeros(I, 2n, m)
j = 1
for (i, Aα΅’) in enumerate(A), k = 1:size(Aα΅’, 2)
for l = 1:n
C[l, j] = Aα΅’[l, k]
end
C[n+i, j] = one(I)
j += 1
end
C
end
################
# Term Ordering
################
abstract type TermOrdering end
struct LexicographicOrdering <: TermOrdering end
"""
DotOrdering(w, tiebreaker=LexicographicOrdering())
The term ordering represented by
```math
cβ < cβ βΊ (β¨w,cββ© < β¨w,cββ©) β¨ (β¨w,cββ© = β¨w,cββ© β§ cβ βΊ cβ)
```
where ``βΊ`` is the term ordering represented by `tiebreaker`.
"""
struct DotOrdering{T<:Number,Ord<:TermOrdering} <: TermOrdering
w::Vector{T}
tiebraker::Ord
end
DotOrdering(w::Vector; tiebraker = LexicographicOrdering()) = DotOrdering(w, tiebraker)
#######################
# CayleyIndexing
#######################
"""
CayleyIndex(i, j, offset)
Fields:
* `config_index::Int`
* `col_index::Int`
* `offset::Int`
* `cayley_index::Int`
"""
struct CayleyIndex
config_index::Int
col_index::Int
offset::Int
cayley_index::Int
end
CayleyIndex(i, j, offset) = CayleyIndex(i, j, offset, offset + j)
function Base.show(io::IO, CI::CayleyIndex)
print(io, "(", CI.config_index, ",", CI.col_index, ")::", CI.cayley_index)
end
"""
CayleyIndexing
Utility to match the index of the `j`-th column in the `i`-th configuration to its index
in the cayley configuration.
Supports indexing with a configuration and column index.
"""
struct CayleyIndexing
configuration_sizes::Vector{Int}
ncolumns::Int # = sum(configuration_sizes)
nconfigurations::Int
offsets::Vector{Int}
end
function CayleyIndexing(configuration_sizes::Vector{<:Integer})
CayleyIndexing(convert(Vector{Int}, configuration_sizes))
end
function CayleyIndexing(configuration_sizes::Vector{Int})
ncolumns = sum(configuration_sizes)
nconfigurations = length(configuration_sizes)
offsets = [0]
for i = 1:(nconfigurations-1)
push!(offsets, offsets[i] + configuration_sizes[i])
end
CayleyIndexing(configuration_sizes, ncolumns, nconfigurations, offsets)
end
CayleyIndexing(config_sizes) = CayleyIndexing(collect(config_sizes))
function Base.copy(CI::CayleyIndexing)
CayleyIndexing(CI.configuration_sizes, CI.ncolumns, CI.nconfigurations, CI.offsets)
end
"""
offsets(cayley_indexing)
Precomputed offsets of the configuration.
"""
offsets(CI::CayleyIndexing) = CI.offsets
"""
offset(cayley_indexing, i)
Indexing offset of the `i`-th configuration.
"""
Base.@propagate_inbounds offset(CI::CayleyIndexing, i) = CI.offsets[i]
"""
nconfigurations(cayley_indexing)
The number of point configurations.
"""
nconfigurations(CI::CayleyIndexing) = CI.nconfigurations
"""
ncolumns(cayley_indexing)
The number of columns of the cayley matrix
"""
ncolumns(CI::CayleyIndexing) = CI.ncolumns
"""
ncolumns(cayley_indexing, i)
The number of columns of the i-th configuration of the cayley matrix
"""
Base.@propagate_inbounds ncolumns(CI::CayleyIndexing, i) = CI.configuration_sizes[i]
"""
configuration(cayley_indexing, i)
Returns an range indexing the columns of the cayley matrix corresponding to the
`i`-th configuration.
"""
Base.@propagate_inbounds function configuration(CI::CayleyIndexing, i)
off = offset(CI, i)
(off+1):(off+CI.configuration_sizes[i])
end
Base.@propagate_inbounds Base.getindex(CI::CayleyIndexing, i, j) = CI.offsets[i] + j
# iteration protocol
Base.length(C::CayleyIndexing) = C.ncolumns
Base.eltype(C::Type{CayleyIndexing}) = CayleyIndex
function Base.iterate(CI::CayleyIndexing)
i = j = 1
@inbounds mα΅’ = CI.configuration_sizes[i]
@inbounds offset = CI.offsets[i]
CayleyIndex(i, j, offset), (i, j, mα΅’, offset)
end
function Base.iterate(CI::CayleyIndexing, state)
i, j, mα΅’, offset = state
if j == mα΅’
i == CI.nconfigurations && return nothing
j = 1
i += 1
@inbounds offset = CI.offsets[i]
@inbounds mα΅’ = CI.configuration_sizes[i]
else
j += 1
end
CayleyIndex(i, j, offset), (i, j, mα΅’, offset)
end
mutable struct MixedCellTable
# A mixed cell is defined by two vectors our of each configuration.
# We assume that each point is in β€βΏ and the i-th configuration has mα΅’ points.
# Therefore, the Cayley configuration has β mα΅’ =: m columns and 2n rows.
# We store the indices of the columns.
indices::Vector{NTuple{2,Int}}
# The mixed cell cone of a mixed cell is the set of all weight vectors Ο such that
# this mixed cell is a mixed cell of the induced subdivision.
# The facets of the mixed cell cone can be described by inequalities of the form cβ
Ο β₯ 0.
# The cone is described by m - 2n facets, one for each column of the Cayley matrix
# which is not part of the mixed cell.
# The `c`s are sparse, they only have 2n+1 non-zero entries.
# The entries of the support of the `c`s are the 1-dimensional kernel of the 2n Γ 2n+1 matrix
# obtained by picking the 2n columns from the mixed cell and one additional column.
# We can scale the `c`s such that the entry corresponding
# to the additional column has the value -volume(mixed cell).
# Then the other entries of `c` are also integers.
# To compactly store the `c`s we only need to store n entries.
# There are two entries associated to each configuration but three entries to the
# configuration where we picked the addtional column from.
# If we only have two entries, these have the same absolute value and just different signs.
# If we have 3 values, then one value (the one corresponding to the additional column)
# has as value -volume(mixed cell) and the sum of all three needs to add to 0.
# So if we store the volume, we only need to store on other entry.
# So as a result it is suffcient to everything in a m Γ n matrix
circuit_table::Matrix{Int32}
volume::Int32
indexing::CayleyIndexing # we store these duplicates
# overflow checks
table_col_bound::Vector{Int32}
# caches
rotated_column::Vector{Int32}
rotated_in_ineq::Vector{Int32}
# dot products
dot_bound::Int128
dot::Vector{Int64}
dot_32::Vector{Int32}
dot_128::Vector{Int128}
end
function MixedCellTable(
indices,
cayley::Matrix,
indexing::CayleyIndexing;
fill_circuit_table::Bool = true,
)
circuit_table = zeros(Int32, ncolumns(indexing), nconfigurations(indexing))
if fill_circuit_table
volume = fill_circuit_table!(circuit_table, indices, cayley, indexing)
else
volume = zero(Int32)
end
table_col_bound = vec(maximum(circuit_table, dims = 1))
rotated_column = [zero(Int32) for _ in indexing]
rotated_in_ineq = zeros(Int32, size(circuit_table, 2))
dot_bound = zero(Int128)
dot = zeros(Int64, size(circuit_table, 1))
dot_32 = similar(dot, Int32)
dot_128 = similar(dot, Int128)
MixedCellTable(
convert(Vector{NTuple{2,Int}}, indices),
circuit_table,
volume,
indexing,
table_col_bound,
rotated_column,
rotated_in_ineq,
dot_bound,
dot,
dot_32,
dot_128,
)
end
function Base.copy(M::MixedCellTable)
MixedCellTable(
copy(M.indices),
copy(M.circuit_table),
copy(M.volume),
copy(M.indexing),
copy(M.table_col_bound),
copy(M.rotated_column),
copy(M.rotated_in_ineq),
M.dot_bound,
copy(M.dot),
copy(M.dot_32),
copy(M.dot_128),
)
end
function Base.:(==)(Mβ::MixedCellTable, Mβ::MixedCellTable)
Mβ.volume == Mβ.volume &&
Mβ.indices == Mβ.indices && Mβ.circuit_table == Mβ.circuit_table
end
function fill_circuit_table!(
table::Matrix{I},
mixed_cell_indices,
cayley::Matrix,
indexing::CayleyIndexing,
) where {I}
D = mixed_cell_submatrix(cayley, indexing, mixed_cell_indices)
n, m = nconfigurations(indexing), ncolumns(indexing)
lu = LinearAlgebra.lu(D)
volume = round(I, abs(LinearAlgebra.det(lu)))
x = zeros(2n)
y, b, bΜ = zeros(I, 2n), zeros(I, 2n), zeros(I, 2n)
# We need to compute the initial circuits from scratch
for ind in indexing
# compute a circuit
for i = 1:2n
b[i] = cayley[i, ind.cayley_index]
end
LinearAlgebra.ldiv!(x, lu, b)
x .*= volume
y .= round.(I, x)
# verify that we have a correct circuit
LinearAlgebra.mul!(bΜ, D, y)
b .*= volume
b == bΜ || error("Cannot construct initial circuit table.") # this should increase precision or similar
# we pick every second entry of x
for (k, l) in enumerate(1:2:2n)
table[ind.cayley_index, k] = y[l]
end
end
volume
end
function mixed_cell_submatrix(C::Matrix, indexing::CayleyIndexing, mixed_cell_indices)
mixed_cell_submatrix!(
similar(C, size(C, 1), size(C, 1)),
C,
indexing,
mixed_cell_indices,
)
end
function mixed_cell_submatrix!(D, C::Matrix, indexing::CayleyIndexing, mixed_cell_indices)
j = 1
for i = 1:nconfigurations(indexing)
aα΅’, bα΅’ = mixed_cell_indices[i]
for k = 1:size(C, 1)
D[k, j] = C[k, indexing[i, aα΅’]]
D[k, j+1] = C[k, indexing[i, bα΅’]]
end
j += 2
end
D
end
Base.@propagate_inbounds function is_valid_inquality(M::MixedCellTable, I::CayleyIndex)
aα΅’, bα΅’ = M.indices[I.config_index]
aα΅’ != I.col_index && bα΅’ != I.col_index
end
"""
circuit_first(cell::MixedCellTable, ineq::CayleyIndex, configuration::Integer)
Return the first entry of the circuit corresponding to the given configuration.
"""
Base.@propagate_inbounds function circuit_first(
cell::MixedCellTable,
ineq::CayleyIndex,
i::Integer,
)
cell.circuit_table[ineq.cayley_index, i]
end
"""
circuit_second(cell::MixedCellTable, ineq::CayleyIndex, configuration::Integer)
Return the second entry of the circuit corresponding to the given configuration.
"""
Base.@propagate_inbounds function circuit_second(
cell::MixedCellTable,
ineq::CayleyIndex,
i::Integer,
)
if i == ineq.config_index
cell.volume - cell.circuit_table[ineq.cayley_index, i]
else
-cell.circuit_table[ineq.cayley_index, i]
end
end
"""
inequality_coordinate(cell::MixedCellTable, ineq::CayleyIndex, coord::CayleyIndex)
inequality_coordinate(cell::MixedCellTable, ineq::CayleyIndex, i, j)
Get the coordinate given by `coord` of the mixed cell cone inequality given by `ineq`.
"""
Base.@propagate_inbounds function inequality_coordinate(
cell::MixedCellTable,
ineq::CayleyIndex,
coord::CayleyIndex,
)
inequality_coordinate(cell, ineq, coord.config_index, coord.col_index)
end
Base.@propagate_inbounds function inequality_coordinate(
cell::MixedCellTable,
ineq::CayleyIndex,
i::Integer,
j::Integer,
)
aα΅’, bα΅’ = cell.indices[i]
if i == ineq.config_index && j == ineq.col_index
-cell.volume
elseif j == aα΅’
circuit_first(cell, ineq, i)
elseif j == bα΅’
circuit_second(cell, ineq, i)
else
zero(cell.volume)
end
end
Base.@propagate_inbounds function inequality_coordinates(
cell::MixedCellTable,
ineq1,
ineq2,
coord...,
)
inequality_coordinate(cell, ineq1, coord...),
inequality_coordinate(cell, ineq2, coord...)
end
function inequality(cell::MixedCellTable, ineq::CayleyIndex)
[inequality_coordinate(cell, ineq, coord.config_index, coord.col_index) for coord in cell.indexing]
end
"""
compute_inequality_dots!(cell::MixedCellTable, Ο)
Compute the dot product of all inequalities with `Ο` and store in `result`.
"""
function compute_inequality_dots!(cell::MixedCellTable, Ο, Ο_bound = typemax(Int32))
n, m = nconfigurations(cell.indexing), ncolumns(cell.indexing)
if cell.dot_bound < typemax(Int32)
_compute_dot!(cell.dot_32, cell, Ο, Int32)
@inbounds for k = 1:m
cell.dot[k] = cell.dot_32[k]
end
elseif cell.dot_bound < typemax(Int64)
_compute_dot!(cell.dot, cell, Ο, Int64)
else
_compute_dot!(cell.dot_128, cell, Ο, Int64)
# Assign final result. Throws an InexactError in case of an overflow
max_128 = typemax(Int128)
@inbounds for k = 1:m
# We can ignore the case that
# cell.intermediate_dot[k] > typemax(Int128)
# since a positive dot product is irrelevant anyway
cell.dot[k] = min(cell.dot_128[k], max_128)
end
end
cell
end
function _compute_dot!(result, cell, Ο, ::Type{T}) where {T<:Integer}
n, m = nconfigurations(cell.indexing), ncolumns(cell.indexing)
# We do the accumulation in a higher precision in order to catch overflows.
@inbounds for k = 1:m
result[k] = -cell.volume * T(Ο[k])
end
@inbounds for i = 1:n
aα΅’, bα΅’ = cell.indices[i]
Ο_aα΅’ = Ο[cell.indexing[i, aα΅’]]
Ο_bα΅’ = Ο[cell.indexing[i, bα΅’]]
Οα΅’ = T(Ο_aα΅’ - Ο_bα΅’)
if !iszero(Οα΅’)
for k = 1:m
result[k] += cell.circuit_table[k, i] * Οα΅’
end
end
v_Ο_bα΅’ = cell.volume * T(Ο_bα΅’)
if !iszero(v_Ο_bα΅’)
for k in configuration(cell.indexing, i)
result[k] += v_Ο_bα΅’
end
end
end
# Correct our result for the bad indices
@inbounds for i = 1:n
aα΅’, bα΅’ = cell.indices[i]
result[cell.indexing[i, aα΅’]] = zero(T)
result[cell.indexing[i, bα΅’]] = zero(T)
end
result
end
"""
inequality_dot(cell::MixedCellTable, ineq::CayleyIndex, Ο)
Compute the dot product of the given inequality with `Ο`.
"""
function inequality_dot(cell::MixedCellTable, ineq::CayleyIndex, Ο)
if cell.dot_bound < typemax(Int32)
_inequality_dot(cell, ineq, Ο, Int32)
elseif cell.dot_bound < typemax(Int64)
_inequality_dot(cell, ineq, Ο, Int64)
else
_inequality_dot(cell, ineq, Ο, Int128)
end
end
@inline function _inequality_dot(
cell::MixedCellTable,
ineq::CayleyIndex,
Ο,
::Type{T},
) where {T<:Integer}
dot = -cell.volume * T(Ο[ineq.cayley_index])
@inbounds for i = 1:length(cell.indices)
aα΅’, bα΅’ = cell.indices[i]
Ο_aα΅’, Ο_bα΅’ = Ο[cell.indexing[i, aα΅’]], Ο[cell.indexing[i, bα΅’]]
Οα΅’ = T(Ο_aα΅’ - Ο_bα΅’)
if !iszero(Οα΅’)
dot += cell.circuit_table[ineq.cayley_index, i] * Οα΅’
end
if i == ineq.col_index
dot += cell.volume * T(Ο_bα΅’)
end
end
Int64(dot)
end
"""
first_violated_inequality(mixed_cell::MixedCellTable, Ο::Vector, ord::TermOrdering)
Compute the first violated inequality in the given mixed cell with respect to the given
term ordering and the target weight vector `Ο`.
"""
function first_violated_inequality(
mixed_cell::MixedCellTable,
Ο::Vector,
ord::TermOrdering,
Ο_bound::Int32,
)
empty = true
best_index = first(mixed_cell.indexing)
best_dot = zero(Int64)
compute_inequality_dots!(mixed_cell, Ο, Ο_bound)
@inbounds for I in mixed_cell.indexing
dot_I = mixed_cell.dot[I.cayley_index]
if dot_I < 0 # && is_valid_inquality(mixed_cell, I)
# TODO: Can we avoid this check sometimes? Yes if we have lex order
if empty || circuit_less(mixed_cell, best_index, dot_I, I, best_dot, ord)
empty = false
best_index = I
best_dot = dot_I
end
end
end
empty && return nothing
return best_index
end
"""
circuit_less(cell::MixedCellTable, indβ::CayleyIndex, Ξ»β, indβ::CayleyIndex, Ξ»β, ord::DotOrdering)
Decicdes whether `Ξ»βc[indβ] βΊ Ξ»βc[indβ]` where βΊ is the ordering given by `ord`.
"""
@inline function circuit_less(
cell::MixedCellTable,
indβ::CayleyIndex,
Ξ»β::Int64,
indβ::CayleyIndex,
Ξ»β::Int64,
ord::DotOrdering,
)
a = Ξ»β * inequality_dot(cell, indβ, ord.w)
b = Ξ»β * inequality_dot(cell, indβ, ord.w)
a == b ? circuit_less(cell, indβ, Ξ»β, indβ, Ξ»β, ord.tiebraker) : a < b
end
@inline function circuit_less(
cell::MixedCellTable,
indβ::CayleyIndex,
Ξ»β::Int64,
indβ::CayleyIndex,
Ξ»β::Int64,
ord::LexicographicOrdering,
)
@inbounds for i = 1:length(cell.indices)
aα΅’, bα΅’ = cell.indices[i]
# Optimize for the common case
if i β indβ.config_index && i β indβ.config_index
cβ_aα΅’ = Int64(cell.circuit_table[indβ.cayley_index, i])
cβ_aα΅’ = Int64(cell.circuit_table[indβ.cayley_index, i])
Ξ»cβ, Ξ»cβ = Ξ»β β cβ_aα΅’, Ξ»β β cβ_aα΅’
if Ξ»cβ β Ξ»cβ
# we have cβ_aα΅’=-cβ_bα΅’ and cβ_aα΅’ =-cβ_bα΅’
if aα΅’ < bα΅’
return Ξ»cβ < Ξ»cβ
else
return Ξ»cβ > Ξ»cβ
end
else
continue
end
end
sorted, n = begin
if indβ.config_index == indβ.config_index == i
swapsort4(aα΅’, bα΅’, indβ.col_index, indβ.col_index), 4
elseif indβ.config_index == i
swapsort4(aα΅’, bα΅’, indβ.col_index), 3
elseif indβ.config_index == i
swapsort4(aα΅’, bα΅’, indβ.col_index), 3
else # Don't remove this branch there is a compiler
# bug which would result in a wrong behaviour
swapsort4(aα΅’, bα΅’), 2
end
end
for k = 1:n
j = sorted[k]
cβ, cβ = inequality_coordinates(cell, indβ, indβ, i, j)
Ξ»cβ, Ξ»cβ = Ξ»β β Int64(cβ), Ξ»β β Int64(cβ)
if Ξ»cβ < Ξ»cβ
return true
elseif Ξ»cβ > Ξ»cβ
return false
end
end
end
return false
end
"""
swapsort4(a, b)
swapsort4(a, b, c)
swapsort4(a, b, c, d)
Sorting networks to sort 2, 3, and 4 elements. Always returns a tuple with 4 elements,
where if necessary the tuple is padded with zeros.
"""
@inline function swapsort4(a, b)
a, b = minmax(a, b)
SVector(a, b, zero(a), zero(a))
end
@inline function swapsort4(a, b, c)
b, c = minmax(b, c)
a, c = minmax(a, c)
a, b = minmax(a, b)
SVector(a, b, c, zero(a))
end
@inline function swapsort4(a, b, c, d)
a, b = minmax(a, b)
c, d = minmax(c, d)
a, c = minmax(a, c)
b, d = minmax(b, d)
b, c = minmax(b, c)
SVector(a, b, c, d)
end
@enum Exchange begin
exchange_first
exchange_second
end
"""
exchange_column!(cell::MixedCellTable, exchange::Exchange, ineq::CayleyIndex, Ο_bound::Integer)
Exchange either the first or second column (depending on `exchange`) in the
configuration defined by `ineq` with the column defined in `ineq`.
"""
function exchange_column!(
cell::MixedCellTable,
exchange::Exchange,
ineq::CayleyIndex,
Ο_bound,
)
rotated_column, rotated_in_ineq = cell.rotated_column, cell.rotated_in_ineq
table, table_col_bound = cell.circuit_table, cell.table_col_bound
i = ineq.config_index
n, m = nconfigurations(cell.indexing), ncolumns(cell.indexing)
@inbounds begin
d = circuit(cell, exchange, ineq, i)
# Read out the inequality associated to the column we want to rotate in
for k = 1:n
rotated_in_ineq[k] = flipsign(cell.circuit_table[ineq.cayley_index, k], d)
end
if exchange == exchange_first
rotated_in_ineq[i] = rotated_in_ineq[i] β flipsign(cell.volume, d)
end
if exchange == exchange_first
# equivalent to
# for ind in cell.indexing
# rotated_column[ind.cayley_index] = -circuit_first(ind, i)
# end
for k = 1:m
rotated_column[k] = -cell.circuit_table[k, i]
end
else # exchange == exchange_second
# equivalent to
# for ind in cell.indexing
# rotated_column[ind.cayley_index] = -circuit_second(ind, i)
# end
for k = 1:m
rotated_column[k] = cell.circuit_table[k, i]
end
for k in configuration(cell.indexing, i)
rotated_column[k] = rotated_column[k] β cell.volume
end
end
table_update!(cell, d, i)
# the violated ineq is now an ineq at the old index
if exchange == exchange_first
rotated_out = CayleyIndex(i, first(cell.indices[i]), ineq.offset)
else
rotated_out = CayleyIndex(i, last(cell.indices[i]), ineq.offset)
end
for k = 1:n
table[rotated_out.cayley_index, k] = -flipsign(rotated_in_ineq[k], d)
table_col_bound[k] = max(table_col_bound[k], abs(rotated_in_ineq[k]))
end
if exchange == exchange_first
v = table[rotated_out.cayley_index, i] β d
table[rotated_out.cayley_index, i] = v
table_col_bound[i] = max(table_col_bound[i], abs(v))
end
cell.volume = abs(d)
cell.indices[i] = begin
if exchange == exchange_first
(ineq.col_index, last(cell.indices[i]))
else # exchange == exchange_second
(first(cell.indices[i]), ineq.col_index)
end
end
end # end inbounds
# update dot bound since table_col_bound changed
compute_dot_bound!(cell, Ο_bound)
cell
end
function exchange_column(
cell::MixedCellTable,
exchange::Exchange,
ineq::CayleyIndex,
Ο_bound,
)
exchange_column!(copy(cell), exchange, ineq, Ο_bound)
end
function reverse_index(ineq::CayleyIndex, cell::MixedCellTable, exchange::Exchange)
if exchange == exchange_first
j = first(cell.indices[ineq.config_index])
else # exchange == exchange_second
j = last(cell.indices[ineq.config_index])
end
CayleyIndex(ineq.config_index, j, ineq.offset)
end
Base.@propagate_inbounds function circuit(
cell::MixedCellTable,
exchange::Exchange,
ineq::CayleyIndex,
i,
)
if exchange == exchange_first
circuit_first(cell, ineq, i)
else # exchange == exchange_second
circuit_second(cell, ineq, i)
end
end
@inline function table_update!(cell::MixedCellTable, d, rc_index::Integer)
rotated_column, rotated_in_ineq = cell.rotated_column, cell.rotated_in_ineq
table, table_col_bound = cell.circuit_table, cell.table_col_bound
d_bound = UInt64(abs(d))
rc_bound = UInt64(table_col_bound[rc_index])
m, n = size(table)
volβ»ΒΉ = MuliplicativeInverse(flipsign(cell.volume, d))
@inbounds for i in Base.OneTo(n)
rα΅’ = rotated_in_ineq[i] # we need to manual hoist this out of the loop
# computation in UInt64 -> no overflow possible
upper_bound = d_bound * table_col_bound[i] + abs(rα΅’) * rc_bound
# Can compute everything in Int32 since we divide early
if upper_bound < typemax(Int32) * UInt64(volβ»ΒΉ.p)
min_el = max_el = zero(Int32)
rΜα΅’ = rα΅’ * volβ»ΒΉ.p_inv
dΜ = d * volβ»ΒΉ.p_inv
# avoid shift
if needs_shift(volβ»ΒΉ)
for k in Base.OneTo(m)
v = shift!(dΜ * table[k, i] + rΜα΅’ * rotated_column[k], volβ»ΒΉ)
table[k, i] = v
min_el, max_el = min(min_el, v), max(max_el, v)
end
else
for k in Base.OneTo(m)
v = (dΜ * table[k, i] + rΜα΅’ * rotated_column[k])
table[k, i] = v
min_el, max_el = min(min_el, v), max(max_el, v)
end
end
table_col_bound[i] = max(-min_el, max_el)
else
min_el_64 = max_el_64 = zero(Int64)
volβ»ΒΉ_64 = MuliplicativeInverse(Int64(flipsign(cell.volume, d)))
rΜα΅’_64 = Int64(rα΅’) * volβ»ΒΉ_64.p_inv
dΜ_64 = Int64(d) * volβ»ΒΉ_64.p_inv
# avoid shift
if needs_shift(volβ»ΒΉ)
for k in Base.OneTo(m)
v = shift!(
dΜ_64 * Int64(table[k, i]) + rΜα΅’_64 * Int64(rotated_column[k]),
volβ»ΒΉ_64,
)
table[k, i] = Base.unsafe_trunc(Int32, v) # unsafe version to not loose vectorization
min_el_64, max_el_64 = min(min_el_64, v), max(max_el_64, v)
end
else
for k in Base.OneTo(m)
v = (dΜ_64 * Int64(table[k, i]) + rΜα΅’_64 * Int64(rotated_column[k]))
table[k, i] = Base.unsafe_trunc(Int32, v) # unsafe version to not loose vectorization
min_el_64, max_el_64 = min(min_el_64, v), max(max_el_64, v)
end
end
# this throws if an overflow happened
table_col_bound[i] = Int32(max(-min_el_64, max_el_64))
end
end
table
end
##############
# TRAVERSERS #
##############
abstract type AbstractTraverser end
#######################
# Mixed Cell Table Traverser
#######################
@enum MixedCellTableUpdates begin
update_first
update_second
update_first_and_second
no_update
end
"""
cell_updates(cell::MixedCellTable, violated_ineq::CayleyIndex)
Compute the updates to the given mixed cell for the first violated inequality.
This doesn't update anything yet but gives a plan what needs to be changed.
This follows the reverse search rule outlined in section 6.2.
"""
function cell_updates(cell::MixedCellTable, index::CayleyIndex)
i = index.config_index
@inbounds aα΅’, bα΅’ = cell.indices[i]
Ξ³α΅’ = index.col_index
@inbounds c_aα΅’ = inequality_coordinate(cell, index, index.config_index, aα΅’)
@inbounds c_bα΅’ = inequality_coordinate(cell, index, index.config_index, bα΅’)
@inbounds c_Ξ³α΅’ = inequality_coordinate(cell, index, index.config_index, Ξ³α΅’)
if c_aα΅’ > 0 && c_bα΅’ > 0
update_first_and_second
elseif c_aα΅’ > 0 && c_bα΅’ == 0
update_first
elseif c_aα΅’ == 0 && c_bα΅’ > 0
update_second
elseif c_aα΅’ > 0 && c_bα΅’ < 0 && bα΅’ < Ξ³α΅’
update_first
elseif c_aα΅’ < 0 && c_bα΅’ > 0 && aα΅’ < Ξ³α΅’
update_second
else
no_update
end
end
struct SearchTreeVertex
index::CayleyIndex
reverse_index::CayleyIndex
exchange::Exchange
update::MixedCellTableUpdates
back::Bool
end
function SearchTreeVertex(
cell::MixedCellTable,
index::CayleyIndex,
exchange::Exchange,
update,
back = false,
)
SearchTreeVertex(index, reverse_index(index, cell, exchange), exchange, update, back)
end
function Base.show(io::IO, v::SearchTreeVertex)
print(
io,
"SearchTreeVertex(index=$(v.index), reverse_index=$(v.reverse_index), $(v.exchange), $(v.update), back=$(v.back))",
)
end
function back(v::SearchTreeVertex)
SearchTreeVertex(v.index, v.reverse_index, v.exchange, v.update, true)
end
function exchange_column!(cell::MixedCellTable, v::SearchTreeVertex, Ο_bound)
exchange_column!(cell, v.exchange, v.index, Ο_bound)
end
function reverse_exchange_column!(cell::MixedCellTable, v::SearchTreeVertex, Ο_bound)
exchange_column!(cell, v.exchange, v.reverse_index, Ο_bound)
end
mutable struct MixedCellTableTraverser{Ord<:TermOrdering} <: AbstractTraverser
mixed_cell::MixedCellTable
cayley::Matrix{Int32}
target::Vector{Int32}
target_bound::Int32
ord::Ord
search_tree::Vector{SearchTreeVertex}
started::Bool
end
function MixedCellTableTraverser(
mixed_cell::MixedCellTable,
cayley::Matrix,
target,
ord = LexicographicOrdering(),
)
Ο = convert(Vector{Int32}, target)
Ο_bound = abs(maximum(abs, Ο))
A = convert(Matrix{Int32}, cayley)
MixedCellTableTraverser(mixed_cell, A, Ο, Ο_bound, ord, SearchTreeVertex[], false)
end
function add_vertex!(search_tree, cell, ineq)
updates = cell_updates(cell, ineq)
if updates == update_first_and_second
push!(search_tree, SearchTreeVertex(cell, ineq, exchange_first, updates))
elseif updates == update_first
push!(search_tree, SearchTreeVertex(cell, ineq, exchange_first, updates))
elseif updates == update_second
push!(search_tree, SearchTreeVertex(cell, ineq, exchange_second, updates))
else # no_update
return false
end
true
end
function next_cell!(traverser::MixedCellTableTraverser)
cell, search_tree = traverser.mixed_cell, traverser.search_tree
Ο, Ο_bound, ord = traverser.target, traverser.target_bound, traverser.ord
if !traverser.started
traverser.started = true
ineq = first_violated_inequality(cell, Ο, ord, Ο_bound)
# Handle case that we have nothing to do
if ineq === nothing
return false
else
add_vertex!(search_tree, cell, ineq)
end
end
while !isempty(search_tree)
v = search_tree[end]
if v.back
reverse_exchange_column!(cell, pop!(search_tree), Ο_bound)
if v.update == update_first_and_second && v.exchange == exchange_first
push!(
search_tree,
SearchTreeVertex(cell, v.index, exchange_second, v.update),
)
elseif !isempty(search_tree)
search_tree[end] = back(search_tree[end])
end
else
exchange_column!(cell, v, Ο_bound)
ineq = first_violated_inequality(cell, Ο, ord, Ο_bound)
if ineq === nothing
search_tree[end] = back(search_tree[end])
return false
else
vertex_added = add_vertex!(search_tree, cell, ineq)
if !vertex_added
search_tree[end] = back(search_tree[end])
end
end
end
end
traverser.started = false
true
end
mixed_cell(T::MixedCellTableTraverser) = T.mixed_cell
#########################
# Total Degree Homotopy #
#########################
struct TotalDegreeTraverser <: AbstractTraverser
traverser::MixedCellTableTraverser{LexicographicOrdering}
end
function TotalDegreeTraverser(As::Vector{Matrix{Int32}})
n = size(As[1], 1)
L = [zeros(eltype(As[1]), n) LinearAlgebra.I]
# construct padded cayley matrix
A = cayley(map(Aα΅’ -> [degree(Aα΅’) * L Aα΅’], As))
# Ο is the vector with an entry of each column in A having entries
# indexed by one of the additional columns equal to -1 and 0 otherwise
Ο = zeros(eltype(A), size(A, 2))
j = 1
for (i, Aα΅’) in enumerate(As)
Ο[j:j+n] .= -one(eltype(A))
j += n + size(Aα΅’, 2) + 1
end
# We start with only one mixed cell
# In the paper it's stated to use [(i, i+1) for i in 1:n]
# But this seems to be wrong.
# Instead if I use the same starting mixed cell as for the regeneration homotopy,
# [(i, i+1) for i in 1:n]
# things seem to work.
cell_indices = [(i, i + 1) for i = 1:n]
indexing = CayleyIndexing(size.(As, 2) .+ (n + 1))
mixed_cell = MixedCellTable(cell_indices, A, indexing)
compute_bounds!(mixed_cell, 1)
traverser = MixedCellTableTraverser(mixed_cell, A, Ο, LexicographicOrdering())
TotalDegreeTraverser(traverser)
end
function next_cell!(T::TotalDegreeTraverser)
complete = next_cell!(T.traverser)
cell = mixed_cell(T.traverser)
n = length(cell.indices)
while !complete
# ignore all cells where one of the artifical columns is part
valid_cell = true
for (aα΅’, bα΅’) in cell.indices
if (aα΅’ β€ n + 1 || bα΅’ β€ n + 1)
valid_cell = false
break
end
end
if !valid_cell
complete = next_cell!(T.traverser)
continue
end
return false
end
true
end
function degree(A::Matrix)
d = zero(eltype(A))
for j = 1:size(A, 2)
c = A[1, j]
for i = 2:size(A, 1)
c += A[i, j]
end
d = max(d, c)
end
d
end
mixed_cell(T::TotalDegreeTraverser) = mixed_cell(T.traverser)
##########################
# Regeneration Traverser #
##########################
mutable struct RegenerationTraverser <: AbstractTraverser
traversers::Vector{MixedCellTableTraverser{LexicographicOrdering}}
stage::Int
end
function RegenerationTraverser(As)
n = size(As[1], 1)
L = [zeros(eltype(As[1]), n) LinearAlgebra.I]
traversers = map(1:n) do k
# construct padded cayley matrix
systems = As[1:(k-1)]
push!(systems, [degree(As[k]) * L As[k]])
for i = k+1:n
push!(systems, L)
end
A = cayley(systems)
# Ο is the vector with an entry of each column in A having entries
# indexed by one of the additional columns equal to -1 and 0 otherwise
Ο = zeros(eltype(A), size(A, 2))
j = 1
for (i, Aα΅’) in enumerate(As)
if i == k
Ο[j:j+n] .= -one(eltype(A))
break
else# i < k
j += size(Aα΅’, 2)
end
end
# this is only a valid mixed cell of the first mixed cell
cell_indices = [(i, i + 1) for i = 1:n]
indexing = CayleyIndexing(size.(systems, 2))
mixed_cell = MixedCellTable(
cell_indices,
A,
indexing;
# only need to fill circuit table for first
fill_circuit_table = (k == 1),
)
if k == 1
compute_bounds!(mixed_cell, 1)
end
MixedCellTableTraverser(mixed_cell, A, Ο)
end
RegenerationTraverser(traversers, 1)
end
function next_cell!(T::RegenerationTraverser)
@inbounds while T.stage > 0
complete = next_cell!(T.traversers[T.stage])
if complete
T.stage -= 1
continue
end
cell = mixed_cell(T.traversers[T.stage])
n = length(cell.indices)
aα΅’, bα΅’ = cell.indices[T.stage]
(aα΅’ > n + 1 && bα΅’ > n + 1) || continue
# If last stage then we emit the cell
if T.stage == n
return false
end
# Move to the next stage
regeneration_stage_carry_over!(
T.traversers[T.stage+1],
T.traversers[T.stage],
T.stage,
)
T.stage += 1
end
# reset stage
T.stage = 1
true
end
function regeneration_stage_carry_over!(
T_B::MixedCellTableTraverser,
T_A::MixedCellTableTraverser,
stage::Integer,
)
A = T_A.mixed_cell
B = T_B.mixed_cell
# A is a mixed cell at stage i
# B will be the mixed cell at stage i + 1
# A has a linear polynomial (L), i.e., n + 1 columns in the current configuration
# B has the scaled simplex (d * L) + config matrix
n = nconfigurations(A.indexing)
@inbounds d = T_B.cayley[1, offset(B.indexing, stage + 1)+2]
B.indices .= A.indices
shift_indices!(B.indices, n + 1, stage)
B.volume = A.volume β d
# The circuit tables are nearly identical, A just has for each configuration n+1 rows too much.
@inbounds for config = 1:n
B_off = offset(B.indexing, config)
A_off = offset(A.indexing, config)
config_cols = ncolumns(B.indexing, config)
if config == stage + 1
# We need to compute the circuits for the new config matrix part
# We can compute them as a weighted sum of old circuits
# We can carry over the scaled circuits for the first part
for k = 1:n
if k == config
# we have to multiply by d since we scale the volume
for j = 1:n+1
B.circuit_table[B_off+j, k] = A.circuit_table[A_off+j, k]
end
else
# we have to multiply by d since we scale the volume
for j = 1:n+1
B.circuit_table[B_off+j, k] = A.circuit_table[A_off+j, k] β d
end
end
end
# Now we need to compute the new circuits
# We can compute them by using hte fact that the first n+1 columns
# are an affine basis of R^n.
aα΅’, bα΅’ = B.indices[stage]
for j = n+2:config_cols
for k = 1:n
c_0k = Int64(B.circuit_table[B_off+1, k])
# rest will we computed in Int64
b_jk = d * c_0k
for i = 1:n
b_jk += T_B.cayley[i, B_off+j] *
(B.circuit_table[B_off + i + 1, k] - c_0k)
end
B.circuit_table[B_off+j, k] = b_jk # converts back to Int32
end
end
for k = 1:n
for j = 1:n+1
# we have to multiply by d sine we change the system from L to (d * L)
B.circuit_table[B_off+j, k] = B.circuit_table[B_off+j, k] * d
end
end
else
# We can simply carry over things
if config == stage
A_off += n + 1
end
for k = 1:n
if k == stage + 1
for j = 1:config_cols
B.circuit_table[B_off+j, k] = A.circuit_table[A_off+j, k]
end
elseif A.table_col_bound[k] * Int64(d) < typemax(Int32) # no overflow
for j = 1:config_cols
B.circuit_table[B_off+j, k] = A.circuit_table[A_off+j, k] * d
end
else # possible overflow
for j = 1:config_cols
B.circuit_table[B_off+j, k] = A.circuit_table[A_off+j, k] β d
end
end
end
end
end
compute_bounds!(B, T_B.target_bound)
nothing
end
function compute_table_col_bound!(M::MixedCellTable)
m, n = size(M.circuit_table)
@inbounds for j = 1:n
max_el = min_el = zero(eltype(M.circuit_table))
for i = 1:m
v = M.circuit_table[i, j]
max_el = max(max_el, v)
min_el = max(min_el, v)
end
M.table_col_bound[j] = max(-min_el, max_el)
end
M
end
function compute_dot_bound!(M::MixedCellTable, target_bound)
n = Int128(nconfigurations(M.indexing))
M.dot_bound = Int128(target_bound) * (abs(M.volume) + n * maximum(M.table_col_bound))
M
end
function compute_bounds!(M::MixedCellTable, target_bound)
compute_table_col_bound!(M)
compute_dot_bound!(M, target_bound)
end
mixed_cell(T::RegenerationTraverser) = mixed_cell(T.traversers[end])
################
# Mixed Volume #
################
mutable struct MixedVolumeCounter{T}
volume::T
end
MixedVolumeCounter() = MixedVolumeCounter(0)
function (MVC::MixedVolumeCounter)(cell)
MVC.volume += cell.volume
end
Base.show(io::IO, MVC::MixedVolumeCounter) = print(io, "MixedVolume: $(MVC.volume)")
traverser(Aα΅’::Matrix...; kwargs...) = traverser(Aα΅’; kwargs...)
function traverser(As::Vector{<:Matrix}; algorithm = :regeneration)
length(As) == size(
As[1],
1,
) || throw(ArgumentError("Number of supports and number of variables doesn't match."))
if algorithm == :regeneration
RegenerationTraverser(As)
elseif algorithm == :total_degree
TotalDegreeTraverser(As)
else
throw(ArgumentError("Unknown `algorithm=$algorithm`. Possible choices are `:regeneration` and `:total_degree`."))
end
end
traverser(f::MP.AbstractPolynomialLike...; kwargs...) = traverser(f; kwargs...)
function traverser(F::Vector{<:MP.AbstractPolynomialLike}; kwargs...)
traverser(support(F); kwargs...)
end
"""
support(F::Vector{<:MP.AbstractPolynomialLike}, vars=MP.variables(F), T::Type{<:Integer}=Int32)
Compute the support of the polynomial system `F` with the given variables `vars`.
The returned matrices have element type `T`.
"""
function support(
F::Vector{<:MP.AbstractPolynomialLike},
vars = MP.variables(F),
T::Type{<:Integer} = Int32,
)
map(f -> [convert(T, MP.degree(t, v)) for v in vars, t in MP.terms(f)], F)
end
"""
mixed_volume(F::Vector{<:MP.AbstractPolynomialLike}; show_progress=true, algorithm=:regeneration)
mixed_volume(π¨::Vector{<:Matrix}; show_progress=true, algorithm=:regeneration)
Compute the mixed volume of the given polynomial system `F` resp. represented
by the support `π¨`.
There are two possible values for `algorithm`:
* `:total_degree`: Use the total degree homotopy algorithm described in Section 7.1
* `:regeneration`: Use the tropical regeneration algorithm described in Section 7.2
"""
function mixed_volume(args...; show_progress = true, kwargs...)
try
T = traverser(args...; kwargs...)
mv = 0
complete = next_cell!(T)
if show_progress
p = ProgressMeter.ProgressUnknown(desc="Mixed volume: ")
end
while !complete
mv += mixed_cell(T).volume
show_progress && ProgressMeter.update!(p, mv)
complete = next_cell!(T)
end
show_progress && ProgressMeter.finish!(p)
mv
catch e
if isa(e, InexactError)
throw(OverflowError("Mixed volume cannot since an integer overflow occured."))
else
rethrow(e)
end
end
end
"""
MixedCell
Data structure representing a (fine) mixed cell.
## Fields
* `indices::Vector{NTuple{2, Int}}`: The columns of the support creating the mixed cell.
* `normal::Vector{Float64}`: The inner normal vector of the lifted mixed cell.
* `Ξ²::Vector{Float64}`: The vector ``(\\min_{a \\in A_i} β¨a,Ξ³β©)_i`` where ``Ξ³`` is `normal`.
* `volume::Int`: The volume of the mixed cell.
"""
mutable struct MixedCell
indices::Vector{NTuple{2,Int}}
normal::Vector{Float64}
Ξ²::Vector{Float64}
is_fine::Bool
volume::Int
end
function MixedCell(n::Int, ::Type{T} = Int32) where {T}
indices = [(1, 1) for _ = 1:n]
normal = zeros(Float64, n)
Ξ² = zeros(Float64, n)
is_fine = false
MixedCell(indices, normal, Ξ², is_fine, 0)
end
Base.copy(C::MixedCell) =
MixedCell(copy(C.indices), copy(C.normal), copy(C.Ξ²), copy(C.is_fine), C.volume)
function Base.show(io::IO, C::MixedCell)
println(io, "MixedCell:")
println(io, " β’ volume β ", C.volume)
println(io, " β’ indices β ", C.indices)
println(io, " β’ normal β ", C.normal)
println(io, " β’ is_fine β ", C.is_fine)
print(io, " β’ Ξ² β ", C.Ξ²)
end
Base.show(io::IO, ::MIME"application/prs.juno.inline", C::MixedCell) = C
"""
volume(C::MixedCell)
Returns the volume of the mixed cell `C`.
"""
volume(C::MixedCell) = C.volume
"""
indices(C::MixedCell)
Returns the indices of the support creating the mixed cell.
"""
indices(C::MixedCell) = C.indices
"""
normal(C::MixedCell)
The inner normal vector of the lifted mixed cell.
"""
normal(C::MixedCell) = C.normal
"""
is_fine(cell::MixedCell)
Checks whether for a given mixed cell `cell` whether this is a fine mixed cell.
"""
is_fine(cell::MixedCell) = cell.is_fine
@deprecate(is_fully_mixed_cell(cell::MixedCell, support, lifting), is_fine(cell))
"""
MixedCellIterator(support:Vector{<:Matrix}, lifting::Vector{<:Vector{<:Integer}})
Returns an iterator over all (fine) mixed cells of the given `support` induced
by the given `lifting`. If the lifting is not sufficiently generic the mixed cells
induced by a sligtly perturbated lifting are computed.
The iterator returns in each iteration a [`MixedCell`](@ref). Note that due to efficiency
reason the same object is returned in each iteration, i.e., if you want to store the computed
cells you need to make a `copy`. Alternatively you can also use [`mixed_cells`](@ref)
to compute all mixed cells.
"""
struct MixedCellIterator{T<:AbstractTraverser}
start_traverser::T
target_traverser::MixedCellTableTraverser{LexicographicOrdering}
support::Vector{Matrix{Int32}}
lifting::Vector{Vector{Int32}}
# cache to not allocate during return
cell::MixedCell
# cache for cell computation
D::Matrix{Float64}
b::Vector{Float64}
end
function MixedCellIterator(
support::Vector{<:Matrix{<:Integer}},
lifting::Vector{<:Vector{<:Integer}};
kwargs...,
)
MixedCellIterator(
convert(Vector{Matrix{Int32}}, support),
convert(Vector{Vector{Int32}}, lifting);
kwargs...,
)
end
function MixedCellIterator(
support::Vector{Matrix{Int32}},
lifting::Vector{Vector{Int32}};
kwargs...,
)
# We need to chain two traversers
# 1) We compute a mixed subdivision w.r.t to the lexicographic ordering
# 2) Each cell we then track to the mixed cells wrt to the given lifting
start_traverser = traverser(support; kwargs...)
# intialize target mixed cell with some dummy data
indices = map(_ -> (1, 2), support)
indexing = CayleyIndexing(size.(support, 2))
A = cayley(support)
target_cell = MixedCellTable(indices, A, indexing; fill_circuit_table = false)
target_lifting = copy(lifting[1])
for i = 2:length(lifting)
append!(target_lifting, lifting[i])
end
# set traverser to -target lifting since we compute internally in the MAX setting
# but expect input in MIN setting
target_traverser = MixedCellTableTraverser(target_cell, A, -target_lifting)
# initial dummy cell
cell = MixedCell(length(support))
# cache
n = length(support)
D = zeros(n, n)
b = zeros(n)
MixedCellIterator(start_traverser, target_traverser, support, lifting, cell, D, b)
end
function Base.show(io::IO, iter::MixedCellIterator)
print(io, typeof(iter), "")
end
Base.show(io::IO, ::MIME"application/prs.juno.inline", x::MixedCellIterator) = x
Base.IteratorSize(::Type{<:MixedCellIterator}) = Base.SizeUnknown()
Base.IteratorEltype(::Type{<:MixedCellIterator}) = Base.HasEltype()
Base.eltype(::MixedCellIterator) = Cell
@inline function Base.iterate(iter::MixedCellIterator, using_start_traverser = true)
if using_start_traverser
complete = next_cell!(iter.start_traverser)
else
complete = next_cell!(iter.target_traverser)
end
while true
if complete && using_start_traverser
break
elseif complete
using_start_traverser = true
complete = next_cell!(iter.start_traverser)
continue
end
if !using_start_traverser
fill_cell!(iter, mixed_cell(iter.target_traverser))
return iter.cell, false
end
# Move to the target traverser
carry_over!(
mixed_cell(iter.target_traverser),
mixed_cell(iter.start_traverser),
iter.start_traverser,
iter.target_traverser.target_bound,
)
using_start_traverser = false
complete = next_cell!(iter.target_traverser)
end
nothing
end
"""
carry_over!(target_cell::MixedCellTable, start_cell::MixedCellTable, T::AbstractTraverser)
We carry over the state (including circuit table) of a start cell
to the cell corresponding to the final homotopy.
This assumes that the
"""
function carry_over!(B::MixedCellTable, A::MixedCellTable, ::TotalDegreeTraverser, Ο_bound)
n = nconfigurations(B.indexing)
B.indices .= A.indices
shift_indices!(indices, n + 1)
B.volume = A.volume
# The circuit tables are nearly identical,
# A just has for each configuration n+1 rows too much.
@inbounds for i = 1:n
off = offset(B.indexing, i)
A_off = offset(A.indexing, i) + n + 1
for j = 1:ncolumns(B.indexing, i), k = 1:n
B.circuit_table[off+j, k] = A.circuit_table[A_off+j, k]
end
end
compute_bounds!(B, Ο_bound)
B
end
function carry_over!(B::MixedCellTable, A::MixedCellTable, ::RegenerationTraverser, Ο_bound)
n = nconfigurations(B.indexing)
B.indices .= A.indices
shift_indices!(B.indices, n + 1, n)
B.volume = A.volume
# The circuit tables are nearly identical,
# A just has for the last configuration n+1 rows too much.
for i = 1:n
off = offset(B.indexing, i)
A_off = offset(A.indexing, i)
if i == n
A_off += n + 1
end
for j = 1:ncolumns(B.indexing, i), k = 1:n
B.circuit_table[off+j, k] = A.circuit_table[A_off+j, k]
end
end
compute_bounds!(B, Ο_bound)
B
end
function fill_cell!(iter::MixedCellIterator, mixed_cell_table::MixedCellTable)
cell = iter.cell
n = length(mixed_cell_table.indices)
for i = 1:n
(aα΅’, bα΅’) = mixed_cell_table.indices[i]
iter.cell.indices[i] = (Int(aα΅’), Int(bα΅’))
end
cell.volume = mixed_cell_table.volume
compute_normal!(cell, iter)
# compute smallest dot product of the normal and the lifted support
Ξ³ = cell.normal
for (i, Aα΅’) in enumerate(iter.support)
aα΅’ = first(mixed_cell_table.indices[i])
Ξ²α΅’ = Float64(iter.lifting[i][aα΅’])
for j = 1:n
Ξ²α΅’ += Ξ³[j] * Aα΅’[j, aα΅’]
end
iter.cell.Ξ²[i] = Ξ²α΅’
end
cell.is_fine = is_fine(cell, iter.support, iter.lifting)
iter.cell
end
function compute_normal!(cell::MixedCell, iter::MixedCellIterator)
n = length(iter.support)
for i = 1:n
aα΅’, bα΅’ = cell.indices[i]
for j = 1:n
iter.D[i, j] = iter.support[i][j, aα΅’] - iter.support[i][j, bα΅’]
end
iter.b[i] = (iter.lifting[i][bα΅’] - iter.lifting[i][aα΅’])
end
LinearAlgebra.ldiv!(LinearAlgebra.generic_lufact!(iter.D), iter.b)
cell.normal .= iter.b
end
function is_fine(cell::MixedCell, support, lifting)
n = length(support)
for i = 1:n
Aα΅’ = support[i]
wα΅’ = lifting[i]
for j = 1:length(wα΅’)
Ξ²β±Ό = Float64(wα΅’[j])
for k = 1:n
Ξ²β±Ό += Aα΅’[k, j] * cell.normal[k]
end
Ξ = abs(cell.Ξ²[i] - Ξ²β±Ό)
if (Ξ < 1e-12 || isapprox(cell.Ξ²[i], Ξ²β±Ό; rtol = 1e-7)) &&
!(j == cell.indices[i][1] || j == cell.indices[i][2])
return false
end
end
end
true
end
"""
mixed_cells(support::Vector{<:Matrix}, lifting::Vector{<:Vector})
Compute all (fine) mixed cells of the given `support` induced
by the given `lifting`. If the lifting is not sufficiently generic the mixed cells
induced by a sligtly perturbated lifting are computed.
The mixed cells are stored as a [`MixedCell`](@ref).
"""
function mixed_cells(support::Vector{<:Matrix}, lifting::Vector{<:Vector})
try
return [copy(c) for c in MixedCellIterator(support, lifting)]
catch e
if isa(e, InexactError)
throw(OverflowError("Mixed cells cannot be computed for this lift since an integer overflow occured."))
else
rethrow(e)
end
end
end
@inline function shift_indices!(ind::Vector{<:NTuple{2,<:Integer}}, m)
for i = 1:n
shift_indices!(ind, m, i)
end
end
@inline function shift_indices!(ind::Vector{<:NTuple{2,<:Integer}}, m, i)
@inbounds aα΅’, bα΅’ = ind[i]
@inbounds ind[i] = (aα΅’ - m, bα΅’ - m)
ind
end
"""
fine_mixed_cells(f::Vector{<:MP.AbstractPolynomialLike}; show_progress=true, max_tries = 10)
fine_mixed_cells(support::Vector{<:Matrix}; show_progress=true, max_tries = 10)
Compute all (fine) mixed cells of the given `support` induced
by a generic lifting. This guarantees that all induced initial forms are binomials.
If the chosen lifting is not generic, then the algorithm is restarted. This happens at most
`max_tries` times many.
Returns a `Vector` of all mixed cells and the corresponding lifting or `nothing` if the algorithm
wasn't able to compute fine mixed cells. This can happen due to some current technical limitations.
"""
function fine_mixed_cells(
f::Vector{<:MP.AbstractPolynomialLike},
lifting_sampler = uniform_lifting_sampler; kwargs...
)
fine_mixed_cells(support(f), lifting_sampler; kwargs...)
end
function fine_mixed_cells(
support::Vector{<:Matrix},
lifting_sampler = uniform_lifting_sampler;
show_progress = true,
max_tries = 10
)
if show_progress
p = ProgressMeter.ProgressUnknown(dt=0.25, desc="Computing mixed cells...")
else
p = nothing
end
try
ntries = 0
lifting = nothing
while ntries < max_tries
ntries += 1
# Try two versions to make a non-breaking api change
try
lifting = map(A -> lifting_sampler(size(A, 2), ntries)::Vector{Int32}, support)
catch
# deprecated
lifting = map(A -> lifting_sampler(size(A, 2))::Vector{Int32}, support)
end
iter = MixedCellIterator(support, lifting)
all_valid = true
cells = MixedCell[]
ncells = 0
mv = 0
for (k, cell) in enumerate(iter)
if !is_fine(cell)
all_valid = false
break
end
ncells += 1
mv += cell.volume
push!(cells, copy(cell))
if p !== nothing
ProgressMeter.update!(p, ncells; showvalues = ((:mixed_volume, mv),))
end
end
if all_valid
p !== nothing && ProgressMeter.finish!(
p;
showvalues = ((:mixed_volume, mv),),
)
return cells, lifting
end
end
return nothing
catch e
if isa(e, InexactError) || isa(e, LinearAlgebra.SingularException)
return nothing
else
rethrow(e)
end
end
end
uniform_lifting_sampler(nterms, attempt = 1) = rand(Int32(-2^(10+attempt)):Int32(2^(10+attempt)), nterms)
function gaussian_lifting_sampler(nterms, attempt = 1)
round.(Int32, randn(nterms) * 2^(11+attempt))
end
end # module
| MixedSubdivisions | https://github.com/saschatimme/MixedSubdivisions.jl.git |
|
[
"MIT"
] | 1.1.5 | 8c6bb3edae13e0a3c5479baf23658384ac3576bd | code | 6120 | using MixedSubdivisions
const MS = MixedSubdivisions
import MultivariatePolynomials
const MP = MultivariatePolynomials
import PolynomialTestSystems: equations, cyclic, ipp2, cyclooctane
using Test
@testset "MixedSubdivisions" begin
@testset "Basic" begin
Aβ = [0 0 1 1; 0 2 0 1]
Aβ = [0 0 1 2; 0 1 1 0]
A = MS.cayley(Aβ, Aβ)
@test A == [
0 0 1 1 0 0 1 2
0 2 0 1 0 1 1 0
1 1 1 1 0 0 0 0
0 0 0 0 1 1 1 1
]
@test_throws ErrorException MS.cayley([1 0; 0 1], [1 0; 0 0; 0 2])
wβ = [0, 0, 0, -2]
wβ = [0, -3, -4, -8]
w = [wβ; wβ]
vβ = [0, 0, 0, -1]
vβ = copy(wβ)
v = [vβ; vβ]
mixed_cell_indices = [(2, 3), (1, 3)]
indexing = MS.CayleyIndexing(size.((Aβ, Aβ), 2))
ord = MS.DotOrdering(Int32.(w))
cell = MS.MixedCellTable(mixed_cell_indices, A, indexing)
@test cell.volume == 3
@test cell.circuit_table == [1 2; 3 0; 0 0; 1 -1; 0 3; 1 2; 0 0; -2 -1]
ineq = MS.first_violated_inequality(cell, v, ord, typemax(Int32))
@test ineq.config_index == 1
@test ineq.col_index == 4
@test MS.exchange_column(cell, MS.exchange_first, ineq, 8) == MS.MixedCellTable(
[(4, 3), (1, 3)],
A,
indexing
)
@test MS.exchange_column(cell, MS.exchange_second, ineq, 8) == MS.MixedCellTable(
[(2, 4), (1, 3)],
A,
indexing,
)
ind_back = MS.reverse_index(ineq, cell, MS.exchange_second)
cell2 = MS.exchange_column(cell, MS.exchange_second, ineq, 8)
@test cell2.volume == 2
@test cell == MS.exchange_column(cell2, MS.exchange_second, ind_back, 8)
ind_back = MS.reverse_index(ineq, cell, MS.exchange_first)
cell2 = MS.exchange_column(cell, MS.exchange_first, ineq, 8)
@test cell2.volume == 1
@test cell == MS.exchange_column(cell2, MS.exchange_first, ind_back, 8)
end
@testset "Mixed Volume" begin
@test mixed_volume(equations(cyclic(5))) == 70
@test mixed_volume(equations(cyclic(7))) == 924
@test mixed_volume(equations(cyclic(10))) == 35940
@test mixed_volume(equations(cyclic(11))) == 184756
@test mixed_volume(equations(ipp2())) == 288
@test mixed_volume(equations(cyclic(5)), algorithm = :total_degree) == 70
@test mixed_volume(equations(ipp2()), algorithm = :total_degree) == 288
end
@testset "Mixed Cells" begin
Aβ = [0 0 1 1; 0 2 0 1]
Aβ = [0 0 1 2; 0 1 1 0]
A = [Aβ, Aβ]
wβ = [0, 0, 0, 2]
wβ = [0, 3, 4, 8]
w = [wβ, wβ]
vβ = [0, 0, 0, 1]
vβ = copy(wβ)
v = [vβ, vβ]
cells_v = mixed_cells(A, v)
@test length(cells_v) == 3
@test sum(volume, cells_v) == 4
@test sort(volume.(cells_v)) == [1, 1, 2]
@test all(cells_v) do c
all(sort.(map(A_i -> A_i' * normal(c), A) .+ v)) do r
isapprox(r[1], r[2], atol = 1e-12)
end
end
cells_w = mixed_cells(A, w)
@test length(cells_w) == 2
@test sum(volume, cells_w) == 4
@test sort(volume.(cells_w)) == [1, 3]
@test all(cells_w) do c
all(sort.(map(A_i -> A_i' * normal(c), A) .+ w)) do r
isapprox(r[1], r[2], atol = 1e-12)
end
end
end
@testset "Fine mixed cells" begin
f = equations(cyclic(7))
cells, lift = fine_mixed_cells(f)
@test sum(c -> c.volume, cells) == 924
@test lift isa Vector{Vector{Int32}}
@test isnothing(fine_mixed_cells(f, max_tries = 0))
end
@testset "Overflow error messages" begin
f = equations(cyclooctane())
@test_throws ArgumentError MS.mixed_volume(f)
F = [f; randn(2, 18) * [MP.variables(f); 1]]
A = support(F)
lifting = map(Ai -> rand(-Int32(2^20):Int32(2^20), size(Ai, 2)), A)
cells = mixed_cells(A, lifting)
@test_deprecated is_fully_mixed_cell(first(cells), A, lifting)
@test all(is_fine, cells)
@test sum(volume, cells) == 32768
@test sum(volume, first(fine_mixed_cells(F))) == 32768
end
@testset "Bugfix#1" begin
lift = Array{Int32,1}[
[-312, 347, 823, 901],
[-1021, -296, -421, -491, -9, 168, -905, -79, -610, -898],
[489, 385, -540, 612, 792, -986, 697, 695, 842, -731],
[-126, 677, -699, 96, -270, 186, 263, 75, -765, 68],
[-230, 173, 142, 531, 218, 668, -305, 177, -710, -94],
[283, -967, 530, 226, -452, -557, 501, -828],
[-656, -75, -709, -588],
[407, 920, 330, 265],
[157, 2, 524, 417, -449, -897, -19, -603, -209, 257],
[-683, 763, 1023, 983, -863, -727, 211, -466, 998, -644],
[-916, 661, 401, 808, 979, -793, -815, 155, -1018, -409],
[1015, -274, -71, 955, 100, 433, 249, -552],
[-523, -225, 997, -784, -884],
[457, -579, 749],
[624, -74, -563, 861, 86],
[
-428,
75,
274,
283,
691,
-782,
513,
-915,
-189,
279,
793,
624,
-741,
-698,
-94,
945,
-58,
-164,
],
[
533,
-156,
-488,
539,
718,
724,
-32,
-845,
441,
-273,
137,
511,
-1005,
-856,
-788,
824,
279,
-12,
],
]
f = equations(cyclooctane())
F = [f; randn(2, 18) * [MP.variables(f); 1]]
A = support(F)
cells = mixed_cells(A, lift)
@test !isempty(cells)
sum(volume, cells) == 32768
end
end
| MixedSubdivisions | https://github.com/saschatimme/MixedSubdivisions.jl.git |
|
[
"MIT"
] | 1.1.5 | 8c6bb3edae13e0a3c5479baf23658384ac3576bd | docs | 1793 | # MixedSubdivisions.jl
| **Documentation** | **Build Status** |
|:-----------------:|:----------------:|
| [![][docs-stable-img]][docs-stable-url] |  |
| [![][docs-latest-img]][docs-latest-url] | [![Codecov branch][codecov-img]][codecov-url] |
A Julia package for computing a (fine) mixed subdivision and the [mixed volume](https://en.wikipedia.org/wiki/Mixed_volume) of lattice polytopes.
The mixed volume of lattice polytopes arising as Newton polytopes of a polynomial system
gives an upper bound of the number of solutions of the system. This is the celebrated
[BKK-Theorem](https://en.wikipedia.org/wiki/BernsteinβKushnirenko_theorem).
A (fine) mixed subdivision can be used to efficiently solve sparse polynomial systems as
first described in [A Polyhedral Method for Solving Sparse Polynomial Systems](https://www.jstor.org/stable/2153370)
by Huber and Sturmfels.
There are many algorithms for computing mixed volumes and mixed subdivisions. This implementation
is based on the tropical homotopy continuation algorithm by Anders Jensen described in [arXiv:1601.02818](https://arxiv.org/abs/1601.02818).
## Installation
The package can be installed via the Julia package manager
```julia
pkg> add MixedSubdivisions
```
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-latest-img]: https://img.shields.io/badge/docs-latest-blue.svg
[docs-stable-url]: https://saschatimme.github.io/MixedSubdivisions.jl/stable
[docs-latest-url]: https://saschatimme.github.io/MixedSubdivisions.jl/latest
[codecov-img]: https://codecov.io/gh/saschatimme/MixedSubdivisions.jl/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/saschatimme/MixedSubdivisions.jl
| MixedSubdivisions | https://github.com/saschatimme/MixedSubdivisions.jl.git |
|
[
"MIT"
] | 1.1.5 | 8c6bb3edae13e0a3c5479baf23658384ac3576bd | docs | 3849 | # Introduction
[MixedSubdivisions.jl](https://github.com/saschatimme/MixedSubdivisions.jl)
is package for computing a (fine) mixed subdivision and the [mixed volume](https://en.wikipedia.org/wiki/Mixed_volume) of lattice polytopes.
The mixed volume of lattice polytopes arising as Newton polytopes of a polynomial system
gives an upper bound of the number of solutions of the system. This is the celebrated
[BKK-Theorem](https://en.wikipedia.org/wiki/BernsteinβKushnirenko_theorem).
A (fine) mixed subdivision can be used to efficiently solve sparse polynomial systems as
first described in [A Polyhedral Method for Solving Sparse Polynomial Systems](https://www.jstor.org/stable/2153370)
by Huber and Sturmfels.
There are many algorithms for computing mixed volumes and mixed subdivisions. This implementation
is based on the tropical homotopy continuation algorithm by Anders Jensen described in [arXiv:1601.02818](https://arxiv.org/abs/1601.02818).
## Installation
The package can be installed via the Julia package manager
```julia
pkg> add MixedSubdivisions
```
## Short introduction
We support polynomial input through the [DynamicPolynomials](https://github.com/JuliaAlgebra/DynamicPolynomials.jl) package.
```julia
@polyvar x y;
# create two polynomials
f = y^2 + x * y + x + 1;
g = x^2 + x * y + y + 1;
# mixed volume
mixed_volume([f, g])
```
```
4
```
Alternatively we could also give directly the supports to `mixed_volume`.
```julia
A = support([f, g])
```
```
2-element Array{Array{Int32,2},1}:
[1 0 1 0; 1 2 0 0]
[2 1 0 0; 0 1 1 0]
```
```julia
mixed_volume(A)
```
```
4
```
Now let's compute the mixed cells with respect to a given lift.
```julia
wβ = [2, 0, 0, 0];
wβ = [8, 4, 3, 0];
mixed_cells(A, [wβ, wβ])
```
```
2-element Array{MixedCell,1}:
MixedCell:
β’ volume β 3
β’ indices β Tuple{Int64,Int64}[(2, 3), (4, 2)]
β’ normal β [-2.66667, -1.33333]
β’ is_fine β true
MixedCell:
β’ volume β 1
β’ indices β Tuple{Int64,Int64}[(3, 1), (1, 2)]
β’ normal β [-6.0, -2.0]
β’ is_fine β true
```
Now let's compare that to another lift.
```julia
vβ = [1, 0, 0, 0];
vβ = [8, 4, 3, 0];
mixed_cells(A, [vβ, vβ])
```
```
3-element Array{MixedCell,1}:
MixedCell:
β’ volume β 2
β’ indices β Tuple{Int64,Int64}[(2, 1), (4, 2)]
β’ normal β [-2.5, -1.5]
β’ is_fine β true
MixedCell:
β’ volume β 1
β’ indices β Tuple{Int64,Int64}[(3, 1), (2, 4)]
β’ normal β [-3.0, -1.0]
β’ is_fine β true
MixedCell:
β’ volume β 1
β’ indices β Tuple{Int64,Int64}[(3, 1), (1, 2)]
β’ normal β [-5.0, -1.0]
β’ is_fine β true
```
If you don't want to wait until all mixed cells got computed you can also use the
`MixedCellIterator`
```
for cell in MixedCellIterator(A, [vβ, vβ])
println(cell)
end
```
```
MixedCell:
β’ volume β 2
β’ indices β Tuple{Int64,Int64}[(2, 1), (4, 2)]
β’ normal β [-2.5, -1.5]
β’ is_fine β true
MixedCell:
β’ volume β 1
β’ indices β Tuple{Int64,Int64}[(3, 1), (2, 4)]
β’ normal β [-3.0, -1.0]
β’ is_fine β true
MixedCell:
β’ volume β 1
β’ indices β Tuple{Int64,Int64}[(3, 1), (1, 2)]
β’ normal β [-5.0, -1.0]
β’ is_fine β true
```
Also if you just want to generate a random lift such that a fine mixed subdivision is obtained you can use the [`fine_mixed_cells`](@ref) function.
```julia
cells, lift = fine_mixed_cells(A);
cells
```
```
2-element Array{MixedCell,1}:
MixedCell:
β’ volume β 2
β’ indices β Tuple{Int64,Int64}[(2, 1), (4, 1)]
β’ normal β [-1762.5, -894.5]
β’ is_fine β true
β’ Ξ² β [-3674.0, -1517.0]
MixedCell:
β’ volume β 2
β’ indices β Tuple{Int64,Int64}[(3, 1), (1, 4)]
β’ normal β [-1762.5, 568.0]
β’ is_fine β true
β’ Ξ² β [-2211.5, -1517.0]
```
```julia
lift
```
```
2-element Array{Array{Int32,1},1}:
[-1017, -1885, -449, -1914]
[2008, 1735, 538, -1517]
```
## API
```@docs
mixed_volume
mixed_cells
fine_mixed_cells
MixedCell
volume
normal
indices
is_fine
MixedCellIterator
support
```
| MixedSubdivisions | https://github.com/saschatimme/MixedSubdivisions.jl.git |
|
[
"MIT"
] | 0.1.1 | d5e2ca382ea949d7d97c9acafbc54a8751349877 | code | 1865 | #=
Copyright (c) 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=#
module CBOR
using Printf, Serialization, Base64
num2hex(n) = string(n, base = 16, pad = sizeof(n) * 2)
num2hex(n::AbstractFloat) = num2hex(reinterpret(Unsigned, n))
hex2num(s) = reinterpret(Float64, parse(UInt64, s, base = 16))
hex(n) = string(n, base = 16)
struct Tag{T}
id::Int
data::T
end
Base.:(==)(a::Tag, b::Tag) = a.id == b.id && a.data == b.data
Tag(id::Integer, data) = Tag(Int(id), data)
include("constants.jl")
include("encode.jl")
include("decode.jl")
export encode
export decode, decode_with_iana
export Simple, Null, Undefined
function decode(data::Array{UInt8, 1})
return decode_internal(IOBuffer(data))
end
function decode(data::IO)
return decode(read(data))
end
function encode(data)
io = IOBuffer()
encode(io, data)
return take!(io)
end
end
| CBOR | https://github.com/JuliaIO/CBOR.jl.git |
|
[
"MIT"
] | 0.1.1 | d5e2ca382ea949d7d97c9acafbc54a8751349877 | code | 1508 | const TYPE_0 = zero(UInt8)
const TYPE_1 = one(UInt8) << 5
const TYPE_2 = UInt8(2) << 5
const TYPE_3 = UInt8(3) << 5
const TYPE_4 = UInt8(4) << 5
const TYPE_5 = UInt8(5) << 5
const TYPE_6 = UInt8(6) << 5
const TYPE_7 = UInt8(7) << 5
const BITS_PER_BYTE = UInt8(8)
const HEX_BASE = Int(16)
const LOWEST_ORDER_BYTE_MASK = 0xFF
const TYPE_BITS_MASK = UInt8(0b1110_0000)
const ADDNTL_INFO_MASK = UInt8(0b0001_1111)
const ADDNTL_INFO_UINT8 = UInt8(24)
const ADDNTL_INFO_UINT16 = UInt8(25)
const ADDNTL_INFO_UINT32 = UInt8(26)
const ADDNTL_INFO_UINT64 = UInt8(27)
const SINGLE_BYTE_SIMPLE_PLUS_ONE = UInt8(24)
const SIMPLE_FALSE = UInt8(20)
const SIMPLE_TRUE = UInt8(21)
const SIMPLE_NULL = UInt8(22)
const SIMPLE_UNDEF = UInt8(23)
const ADDNTL_INFO_FLOAT16 = UInt8(25)
const ADDNTL_INFO_FLOAT32 = UInt8(26)
const ADDNTL_INFO_FLOAT64 = UInt8(27)
const ADDNTL_INFO_INDEF = UInt8(31)
const BREAK_INDEF = TYPE_7 | UInt8(31)
const SINGLE_BYTE_UINT_PLUS_ONE = 24
const UINT8_MAX_PLUS_ONE = 0x100
const UINT16_MAX_PLUS_ONE = 0x10000
const UINT32_MAX_PLUS_ONE = 0x100000000
const UINT64_MAX_PLUS_ONE = 0x10000000000000000
const SIZE_OF_FLOAT64 = sizeof(Float64)
const SIZE_OF_FLOAT32 = sizeof(Float32)
const SIZE_OF_FLOAT16 = sizeof(Float16)
const POS_BIG_INT_TAG = UInt8(2)
const NEG_BIG_INT_TAG = UInt8(3)
const CBOR_FALSE_BYTE = UInt8(TYPE_7 | 20)
const CBOR_TRUE_BYTE = UInt8(TYPE_7 | 21)
const CBOR_NULL_BYTE = UInt8(TYPE_7 | 22)
const CBOR_UNDEF_BYTE = UInt8(TYPE_7 | 23)
const CUSTOM_LANGUAGE_TYPE = 27
| CBOR | https://github.com/JuliaIO/CBOR.jl.git |
|
[
"MIT"
] | 0.1.1 | d5e2ca382ea949d7d97c9acafbc54a8751349877 | code | 6175 | #=
Copyright (c) 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=#
function type_from_fields(::Type{T}, fields) where T
ccall(:jl_new_structv, Any, (Any, Ptr{Cvoid}, UInt32), T, fields, length(fields))
end
function peekbyte(io::IO)
mark(io)
byte = read(io, UInt8)
reset(io)
return byte
end
struct UndefIter{IO, F}
f::F
io::IO
end
Base.IteratorSize(::Type{<: UndefIter}) = Base.SizeUnknown()
function Base.iterate(x::UndefIter, state = nothing)
peekbyte(x.io) == BREAK_INDEF && return nothing
return x.f(x.io), nothing
end
function decode_ntimes(f, io::IO)
first_byte = peekbyte(io)
if (first_byte & ADDNTL_INFO_MASK) == ADDNTL_INFO_INDEF
skip(io, 1) # skip first byte
return UndefIter(f, io)
else
return (f(io) for i in 1:decode_unsigned(io))
end
end
function decode_unsigned(io::IO)
addntl_info = read(io, UInt8) & ADDNTL_INFO_MASK
if addntl_info < SINGLE_BYTE_UINT_PLUS_ONE
return addntl_info
elseif addntl_info == ADDNTL_INFO_UINT8
return bswap(read(io, UInt8))
elseif addntl_info == ADDNTL_INFO_UINT16
return bswap(read(io, UInt16))
elseif addntl_info == ADDNTL_INFO_UINT32
return bswap(read(io, UInt32))
elseif addntl_info == ADDNTL_INFO_UINT64
return bswap(read(io, UInt64))
else
error("Unknown Int type")
end
end
decode_internal(io::IO, ::Val{TYPE_0}) = decode_unsigned(io)
function decode_internal(io::IO, ::Val{TYPE_1})
data = signed(decode_unsigned(io))
if (i = Int128(data) + one(data)) > typemax(Int64)
return -i
else
return -(data + one(data))
end
end
"""
Decode Byte Array
"""
function decode_internal(io::IO, ::Val{TYPE_2})
if (peekbyte(io) & ADDNTL_INFO_MASK) == ADDNTL_INFO_INDEF
skip(io, 1)
result = IOBuffer()
while peekbyte(io) !== BREAK_INDEF
write(result, decode_internal(io))
end
return take!(result)
else
return read(io, decode_unsigned(io))
end
end
"""
Decode String
"""
function decode_internal(io::IO, ::Val{TYPE_3})
if (peekbyte(io) & ADDNTL_INFO_MASK) == ADDNTL_INFO_INDEF
skip(io, 1)
result = IOBuffer()
while peekbyte(io) !== BREAK_INDEF
write(result, decode_internal(io))
end
return String(take!(result))
else
return String(read(io, decode_unsigned(io)))
end
end
"""
Decode Vector of arbitrary elements
"""
function decode_internal(io::IO, ::Val{TYPE_4})
return map(identity, decode_ntimes(decode_internal, io))
end
"""
Decode Dict
"""
function decode_internal(io::IO, ::Val{TYPE_5})
return Dict(decode_ntimes(io) do io
decode_internal(io) => decode_internal(io)
end)
end
"""
Decode Tagged type
"""
function decode_internal(io::IO, ::Val{TYPE_6})
tag = decode_unsigned(io)
data = decode_internal(io)
if tag in (POS_BIG_INT_TAG, NEG_BIG_INT_TAG)
big_int = parse(
BigInt, bytes2hex(data), base = HEX_BASE
)
if tag == NEG_BIG_INT_TAG
big_int = -(big_int + 1)
end
return big_int
end
if tag == CUSTOM_LANGUAGE_TYPE # Type Tag
name = data[1]
object_serialized = data[2]
if startswith(name, "Julia/") # Julia Type
return deserialize(IOBuffer(object_serialized))
end
end
# TODO implement other common tags!
return Tag(tag, data)
end
function decode_internal(io::IO, ::Val{TYPE_7})
first_byte = read(io, UInt8)
addntl_info = first_byte & ADDNTL_INFO_MASK
if addntl_info < SINGLE_BYTE_SIMPLE_PLUS_ONE + 1
simple_val = if addntl_info < SINGLE_BYTE_SIMPLE_PLUS_ONE
addntl_info
else
read(io, UInt8)
end
if simple_val == SIMPLE_FALSE
return false
elseif simple_val == SIMPLE_TRUE
return true
elseif simple_val == SIMPLE_NULL
return nothing
elseif simple_val == SIMPLE_UNDEF
return Undefined()
else
return Simple(simple_val)
end
else
if addntl_info == ADDNTL_INFO_FLOAT64
return reinterpret(Float64, ntoh(read(io, UInt64)))
elseif addntl_info == ADDNTL_INFO_FLOAT32
return reinterpret(Float32, ntoh(read(io, UInt32)))
elseif addntl_info == ADDNTL_INFO_FLOAT16
return reinterpret(Float16, ntoh(read(io, UInt16)))
else
error("Unsupported Float Type!")
end
end
end
function decode_internal(io::IO)
# leave startbyte in io
first_byte = peekbyte(io)
typ = first_byte & TYPE_BITS_MASK
typ == TYPE_0 && return decode_internal(io, Val(TYPE_0))
typ == TYPE_1 && return decode_internal(io, Val(TYPE_1))
typ == TYPE_2 && return decode_internal(io, Val(TYPE_2))
typ == TYPE_3 && return decode_internal(io, Val(TYPE_3))
typ == TYPE_4 && return decode_internal(io, Val(TYPE_4))
typ == TYPE_5 && return decode_internal(io, Val(TYPE_5))
typ == TYPE_6 && return decode_internal(io, Val(TYPE_6))
typ == TYPE_7 && return decode_internal(io, Val(TYPE_7))
end
| CBOR | https://github.com/JuliaIO/CBOR.jl.git |
|
[
"MIT"
] | 0.1.1 | d5e2ca382ea949d7d97c9acafbc54a8751349877 | code | 7027 | #=
Copyright (c) 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=#
cbor_tag(::UInt8) = ADDNTL_INFO_UINT8
cbor_tag(::UInt16) = ADDNTL_INFO_UINT16
cbor_tag(::UInt32) = ADDNTL_INFO_UINT32
cbor_tag(::UInt64) = ADDNTL_INFO_UINT64
cbor_tag(::Float64) = ADDNTL_INFO_FLOAT64
cbor_tag(::Float32) = ADDNTL_INFO_FLOAT32
cbor_tag(::Float16) = ADDNTL_INFO_FLOAT16
function encode_unsigned_with_type(
io::IO, typ::UInt8, num::Unsigned
)
write(io, typ | cbor_tag(num))
write(io, bswap(num))
end
function encode_length(io::IO, typ::UInt8, x)
encode_smallest_int(io, typ, x isa String ? sizeof(x) : length(x))
end
"""
Array lengths and other integers (e.g. tags) in CBOR are encoded with smallest integer type,
which we do with this method!
"""
function encode_smallest_int(io::IO, typ::UInt8, num::Integer)
@assert num >= 0 "array lengths must be greater 0. Found: $num"
if num < SINGLE_BYTE_UINT_PLUS_ONE
write(io, typ | UInt8(num)) # smaller 24 gets directly stored in type tag
elseif num < UINT8_MAX_PLUS_ONE
encode_unsigned_with_type(io, typ, UInt8(num))
elseif num < UINT16_MAX_PLUS_ONE
encode_unsigned_with_type(io, typ, UInt16(num))
elseif num < UINT32_MAX_PLUS_ONE
encode_unsigned_with_type(io, typ, UInt32(num))
elseif num < UINT64_MAX_PLUS_ONE
encode_unsigned_with_type(io, typ, UInt64(num))
else
error("128-bits ints can't be encoded in the CBOR format.")
end
end
function encode(io::IO, float::Union{Float64, Float32, Float16})
write(io, TYPE_7 | cbor_tag(float))
# hton only works for 32 + 64, while bswap works for all
write(io, Base.bswap_int(float))
end
# ------- straightforward encoding for a few Julia types
function encode(io::IO, bool::Bool)
write(io, CBOR_FALSE_BYTE + bool)
end
function encode(io::IO, num::Unsigned)
encode_unsigned_with_type(io, TYPE_0, num)
end
function encode(io::IO, num::T) where T <: Signed
encode_unsigned_with_type(io, TYPE_1, unsigned(-num - one(T)))
end
function encode(io::IO, byte_string::Vector{UInt8})
encode_length(io, TYPE_2, byte_string)
write(io, byte_string)
end
function encode(io::IO, string::String)
encode_length(io, TYPE_3, string)
write(io, string)
end
function encode(io::IO, list::Vector)
encode_length(io, TYPE_4, list)
for e in list
encode(io, e)
end
end
function encode(io::IO, map::Dict)
encode_length(io, TYPE_5, map)
for (key, value) in map
encode(io, key)
encode(io, value)
end
end
function encode(io::IO, big_int::BigInt)
tag = if big_int < 0
big_int = -big_int - 1
NEG_BIG_INT_TAG
else
POS_BIG_INT_TAG
end
hex_str = hex(big_int)
if isodd(length(hex_str))
hex_str = "0" * hex_str
end
encode(io, Tag(tag, hex2bytes(hex_str)))
end
function encode(io::IO, tag::Tag)
tag.id >= 0 || error("Tag needs to be a positive integer")
encode_with_tag(io, Unsigned(tag.id), tag.data)
end
"""
Wrapper for collections with undefined length, that will then get encoded
in the cbor format. Underlying is just
"""
struct UndefLength{ET, A}
iter::A
end
function UndefLength(iter::T) where T
UndefLength{eltype(iter), T}(iter)
end
function UndefLength{T}(iter::A) where {T, A}
UndefLength{T, A}(iter)
end
Base.iterate(x::UndefLength) = iterate(x.iter)
Base.iterate(x::UndefLength, state) = iterate(x.iter, state)
# ------- encoding for indefinite length collections
function encode(
io::IO, iter::UndefLength{ET}
) where ET
if ET in (Vector{UInt8}, String)
typ = ET == Vector{UInt8} ? TYPE_2 : TYPE_3
write(io, typ | ADDNTL_INFO_INDEF)
foreach(x-> encode(io, x), iter)
else
typ = ET <: Pair ? TYPE_5 : TYPE_4 # Dict or any array
write(io, typ | ADDNTL_INFO_INDEF)
for e in iter
if e isa Pair
encode(io, e[1])
encode(io, e[2])
else
encode(io, e)
end
end
end
write(io, BREAK_INDEF)
end
# ------- encoding with tags
function encode_with_tag(io::IO, tag::Unsigned, data)
encode_smallest_int(io, TYPE_6, tag)
encode(io, data)
end
struct Undefined
end
function encode(io::IO, null::Nothing)
write(io, CBOR_NULL_BYTE)
end
function encode(io::IO, undef::Undefined)
write(io, CBOR_UNDEF_BYTE)
end
struct SmallInteger{T}
num::T
end
Base.convert(::Type{<: SmallInteger}, x) = SmallInteger(x)
Base.convert(::Type{<: SmallInteger}, x::SmallInteger) = x
Base.:(==)(a::SmallInteger, b::SmallInteger) = a.num == b.num
Base.:(==)(a::Number, b::SmallInteger) = a == b.num
Base.:(==)(a::SmallInteger, b::Number) = a.num == b
function encode(io::IO, small::SmallInteger{<: Unsigned})
encode_smallest_int(io, TYPE_0, small.num)
end
function encode(io::IO, small::SmallInteger{<: Signed})
if small.num >= 0
encode_smallest_int(io, TYPE_0, unsigned(small.num))
else
encode_smallest_int(io, TYPE_1, unsigned(-small.num - one(small.num)))
end
end
function fields2array(typ::T) where T
fnames = fieldnames(T)
getfield.((typ,), [fnames...])
end
"""
Any Julia type get's serialized as Tag 27
Tag 27
Data Item array [typename, constructargs...]
Semantics Serialised language-independent object with type name and constructor arguments
Reference http://cbor.schmorp.de/generic-object
Contact Marc A. Lehmann <[email protected]>
"""
function encode(io::IO, struct_type::T) where T
# TODO don't use Serialization for the whole struct!
# It almost works to deserialize from just the fields and type,
# but that ends up being problematic for
# anonymous functions (the type changes between serialization & deserialization)
tio = IOBuffer(); serialize(tio, struct_type)
encode(
io,
Tag(
CUSTOM_LANGUAGE_TYPE,
[string("Julia/", T), take!(tio), fields2array(struct_type)]
)
)
end
| CBOR | https://github.com/JuliaIO/CBOR.jl.git |
|
[
"MIT"
] | 0.1.1 | d5e2ca382ea949d7d97c9acafbc54a8751349877 | code | 7920 | using Test
using CBOR
using DataStructures
import CBOR: Tag, decode, encode, SmallInteger, UndefLength
# Taken (and modified) from Appendix A of RFC 7049
two_way_test_vectors = [
SmallInteger(0) => hex2bytes("00"),
SmallInteger(1) => hex2bytes("01"),
SmallInteger(10) => hex2bytes("0a"),
SmallInteger(23) => hex2bytes("17"),
SmallInteger(24) => hex2bytes("1818"),
SmallInteger(25) => hex2bytes("1819"),
UInt8(100) => hex2bytes("1864"),
UInt16(1000) => hex2bytes("1903e8"),
UInt32(1000000) => hex2bytes("1a000f4240"),
UInt64(1000000000000) => hex2bytes("1b000000e8d4a51000"),
# UInt128(18446744073709551615) => hex2bytes("1bffffffffffffffff"),
# Int128(-18446744073709551616) => hex2bytes("3bffffffffffffffff"),
SmallInteger(-1) => hex2bytes("20"),
SmallInteger(-10) => hex2bytes("29"),
Int8(-100) => hex2bytes("3863"),
Int16(-1000) => hex2bytes("3903e7"),
0.0f0 => hex2bytes("fa00000000"),
-0.0f0 => hex2bytes("fa80000000"),
1.0f0 => hex2bytes("fa3f800000"),
1.1 => hex2bytes("fb3ff199999999999a"),
1.5f0 => hex2bytes("fa3fc00000"),
65504f0 => hex2bytes("fa477fe000"),
100000f0 => hex2bytes("fa47c35000"),
Float32(3.4028234663852886e+38) => hex2bytes("fa7f7fffff"),
1.0e+300 => hex2bytes("fb7e37e43c8800759c"),
Float32(5.960464477539063e-8) => hex2bytes("fa33800000"),
Float32(0.00006103515625) => hex2bytes("fa38800000"),
-4f0 => hex2bytes("fac0800000"),
-4.1 => hex2bytes("fbc010666666666666"),
false => hex2bytes("f4"),
true => hex2bytes("f5"),
nothing => hex2bytes("f6"),
Undefined() => hex2bytes("f7"),
Tag(0, "2013-03-21T20:04:00Z") =>
hex2bytes("c074323031332d30332d32315432303a30343a30305a"),
Tag(1, SmallInteger(1363896240)) => hex2bytes("c11a514b67b0"),
Tag(1, 1363896240.5) => hex2bytes("c1fb41d452d9ec200000"),
Tag(23, hex2bytes("01020304")) => hex2bytes("d74401020304"),
Tag(24, hex2bytes("6449455446")) => hex2bytes("d818456449455446"),
Tag(32, "http://www.example.com") =>
hex2bytes("d82076687474703a2f2f7777772e6578616d706c652e636f6d"),
UInt8[] => hex2bytes("40"),
hex2bytes("01020304") => hex2bytes("4401020304"),
"" => hex2bytes("60"),
"a" => hex2bytes("6161"),
"IETF" => hex2bytes("6449455446"),
"\"\\" => hex2bytes("62225c"),
"\u00fc" => hex2bytes("62c3bc"),
"\u6c34" => hex2bytes("63e6b0b4"),
[] => hex2bytes("80"),
SmallInteger[1, 2, 3] => hex2bytes("83010203"),
[SmallInteger(1), SmallInteger[2, 3], SmallInteger[4, 5]] => hex2bytes("8301820203820405"),
SmallInteger[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] =>
hex2bytes("98190102030405060708090a0b0c0d0e0f101112131415161718181819"),
Dict() => hex2bytes("a0"),
OrderedDict(SmallInteger(1)=>SmallInteger(2), SmallInteger(3)=>SmallInteger(4)) => hex2bytes("a201020304"),
OrderedDict("a"=>SmallInteger(1), "b"=>SmallInteger[2, 3]) => hex2bytes("a26161016162820203"),
OrderedDict("a"=>"A", "b"=>"B", "c"=>"C", "d"=>"D", "e"=>"E") =>
hex2bytes("a56161614161626142616361436164614461656145"),
["a", Dict("b"=>"c")] => hex2bytes("826161a161626163")
]
# Some annoying problems with Small integers and indefinite lenght arrays
# for round tripping
cbor_equal(a, b) = a == b
cbor_equal(a::Vector{String}, b::String) = join(a, "") == b
cbor_equal(a::Vector{Vector{UInt8}}, b::Vector{UInt8}) = vcat(a...) == b
function cbor_equal(a::AbstractDict, b::AbstractDict)
for (ka, kb) in zip(keys(a), keys(b))
ka == kb || return false
end
for (ka, kb) in zip(values(a), values(b))
ka == kb || return false
end
return true
end
#=
The problem is, we want to preserver Julia types for non Base types that directly
map to basic CBOR protocol types. So we can't define encode(io::IO, x::AbstractDict)
since that would mean we can't preserver the type of any custom dict type.
But, since the CBOR protocol is expecting ordered dicts, Julia's default dict type
is unordered. I think it still makes more sense to use Julia's dict type instead of
taking the dependencies on DataStructures. But to pass the byte test, we need
an ordered dict type, so we overload it just here!
=#
function CBOR.encode(io::IO, x::OrderedDict)
CBOR.encode_length(io::IO, CBOR.TYPE_5, x)
for (key, value) in x
encode(io, key)
encode(io, value)
end
end
function CBOR.decode_internal(io::IO, ::Val{CBOR.TYPE_5})
return OrderedDict(CBOR.decode_ntimes(io) do io
CBOR.decode_internal(io) => CBOR.decode_internal(io)
end...)
end
@testset "two way" begin
for (data, bytes) in two_way_test_vectors
@test cbor_equal(data, decode(encode(data)))
@test isequal(bytes, encode(data))
@test cbor_equal(data, decode(bytes))
end
end
bytes_to_data_test_vectors = [
hex2bytes("fa7fc00000") => NaN32,
hex2bytes("fa7f800000") => Inf32,
hex2bytes("faff800000") => -Inf32,
hex2bytes("fb7ff8000000000000") => NaN,
hex2bytes("fb7ff0000000000000") => Inf,
hex2bytes("fbfff0000000000000") => -Inf
]
@testset "bytes to data" begin
for (bytes, data) in bytes_to_data_test_vectors
@test isequal(data, decode(bytes))
end
end
iana_test_vector = [
BigInt(18446744073709551616) => hex2bytes("c249010000000000000000"),
BigInt(-18446744073709551617) => hex2bytes("c349010000000000000000")
]
@testset "BigInt iana" begin
for (data, bytes) in iana_test_vector
@test isequal(bytes, encode(data))
@test isequal(data, decode(bytes))
end
end
indef_length_coll_test_vectors = [
["Hello", " ", "world"] =>
hex2bytes("7f6548656c6c6f612065776f726c64ff"),
Vector{UInt8}.(["Hello", " ", "world"]) =>
hex2bytes("5f4548656c6c6f412045776f726c64ff"),
[SmallInteger(1), 2.3, "Twiddle"] =>
hex2bytes("9f01fb40026666666666666754776964646c65ff"),
OrderedDict(SmallInteger(1)=>SmallInteger(2), 3.2=>"3.2") =>
hex2bytes("bf0102fb400999999999999a63332e32ff")
]
@testset "ifndef length collections" begin
@testset "basic types" begin
@test UInt8[1] == decode(encode(UndefLength(UInt8[1])))
@test "hi" == decode(encode("hi"))
@test [1, "2", UInt8[1]] == decode(encode([1, "2", UInt8[1]]))
@test Dict("a" => 2) == decode(encode(Dict("a" => 2)))
end
for (data, bytes) in indef_length_coll_test_vectors
@test isequal(bytes, encode(UndefLength(data)))
@test cbor_equal(data, decode(bytes))
end
end
#=
From the docs about undef length byte strings
5F -- Start indefinite-length byte string
44 -- Byte string of length 4
aabbccdd -- Bytes content
43 -- Byte string of length 3
eeff99 -- Bytes content
FF -- "break"
After decoding, this results in a single byte string with seven
bytes: 0xaabbccddeeff99.
=#
@testset "undef length bytestring" begin
@test decode(hex2bytes("5f44aabbccdd43eeff99FF")) == hex2bytes("aabbccddeeff99")
end
# tests from the readme
function producer(ch::Channel)
for i in 1:10
put!(ch,i*i)
end
end
@testset "indefinite length readme" begin
iter = Channel(producer)
@test ((1:10) .* (1:10)) == decode(encode(UndefLength(iter)))
end
function cubes(ch::Channel)
for i in 1:10
put!(ch,i) # key
put!(ch,i*i*i) # value
end
end
@testset "indefinite length readme Dict" begin
bytes = encode(UndefLength{Pair}(Channel(cubes)))
@test Dict(zip(1:10, (1:10) .^ 3)) == decode(bytes)
end
function producer(ch::Channel)
for c in ["F", "ire", " ", "and", " ", "Blo", "od"]
put!(ch, c)
end
end
@testset "indefinite length readme String" begin
bytes = encode(UndefLength{String}(Channel(producer)))
@test decode(bytes) == "Fire and Blood"
end
| CBOR | https://github.com/JuliaIO/CBOR.jl.git |
|
[
"MIT"
] | 0.1.1 | d5e2ca382ea949d7d97c9acafbc54a8751349877 | docs | 7996 | # CBOR.jl
[](https://travis-ci.org/saurvs/CBOR.jl)
[](https://ci.appveyor.com/project/saurvs/cbor-jl)
[](https://github.com/saurvs/jl/blob/master/LICENSE.md)
**CBOR.jl** is a Julia package for working with the **CBOR** data format,
providing straightforward encoding and decoding for Julia types.
## About CBOR
The **Concise Binary Object Representation** is a data format that's based upon
an extension of the JSON data model, whose stated design goals
include: small code size, small message size, and
extensibility without the need for version negotiation. The format is formally
defined in [RFC 7049](https://tools.ietf.org/html/rfc7049).
## Usage
Add the package
```julia
Pkg.add("CBOR")
```
and add the module
```julia
using CBOR
```
### Encoding and Decoding
Encoding and decoding follow the simple pattern
```julia
bytes = encode(data)
data = decode(bytes)
```
where `bytes` is of type `Array{UInt8, 1}`, and `data` returned from `decode()`
is *usually* of the same type that was passed into `encode()` but always
contains the original data.
#### Primitive Integers
All `Signed` and `Unsigned` types, *except* `Int128` and `UInt128`, are encoded
as CBOR `Type 0` or `Type 1`
```julia
> encode(21)
1-element Array{UInt8,1}: 0x15
> encode(-135713)
5-element Array{UInt8,1}: 0x3a 0x00 0x02 0x12 0x20
> bytes = encode(typemax(UInt64))
9-element Array{UInt8,1}: 0x1b 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
> decode(bytes)
18446744073709551615
```
#### Byte Strings
An `AbstractVector{UInt8}` is encoded as CBOR `Type 2`
```julia
> encode(UInt8[x*x for x in 1:10])
11-element Array{UInt8, 1}: 0x4a 0x01 0x04 0x09 0x10 0x19 0x24 0x31 0x40 0x51 0x64
```
#### Strings
`String` are encoded as CBOR `Type 3`
```julia
> encode("Valar morghulis")
16-element Array{UInt8,1}: 0x4f 0x56 0x61 0x6c 0x61 ... 0x68 0x75 0x6c 0x69 0x73
> bytes = encode("ΧΧͺΧ ΧΧΧΧ ΧΧ§ΧΧͺ ΧΧͺ Χ‘ΧΧ‘ ΧΧ ΧΧΧΧ, ΧΧΧ ΧΧͺΧ ΧΧ ΧΧΧΧ ΧΧΧΧΧΧ Χ©ΧΧ ΧΧΧ¨ ΧΧΧΧͺΧ")
119-element Array{UInt8,1}: 0x78 0x75 0xd7 0x90 0xd7 ... 0x99 0xd7 0xaa 0xd7 0x99
> decode(bytes)
"ΧΧͺΧ ΧΧΧΧ ΧΧ§ΧΧͺ ΧΧͺ Χ‘ΧΧ‘ ΧΧ ΧΧΧΧ, ΧΧΧ ΧΧͺΧ ΧΧ ΧΧΧΧ ΧΧΧΧΧΧ Χ©ΧΧ ΧΧΧ¨ ΧΧΧΧͺΧ"
```
#### Floats
`Float64`, `Float32` and `Float16` are encoded as CBOR `Type 7`
```julia
> encode(1.23456789e-300)
9-element Array{UInt8, 1}: 0xfb 0x01 0xaa 0x74 0xfe 0x1c 0x13 0x2c 0x0e
> bytes = encode(Float32(pi))
5-element Array{UInt8, 1}: 0xfa 0x40 0x49 0x0f 0xdb
> decode(bytes)
3.1415927f0
```
#### Arrays
`AbstractVector` and `Tuple` types, except of course `AbstractVector{UInt8}`,
are encoded as CBOR `Type 4`
```julia
> bytes = encode((-7, -8, -9))
4-element Array{UInt8, 1}: 0x83 0x26 0x27 0x28
> decode(bytes)
3-element Array{Any, 1}: -7 -8 -9
> bytes = encode(["Open", 1, 4, 9.0, "the pod bay doors hal"])
39-element Array{UInt8, 1}: 0x85 0x44 0x4f 0x70 0x65 ... 0x73 0x20 0x68 0x61 0x6c
> decode(bytes)
5-element Array{Any, 1}: "Open" 1 4 9.0 "the pod bay doors hal"
> bytes = encode([log2(x) for x in 1:10])
91-element Array{UInt8, 1}: 0x8a 0xfb 0x00 0x00 0x00 ... 0x4f 0x09 0x79 0xa3 0x71
> decode(bytes)
10-element Array{Any, 1}: 0.0 1.0 1.58496 2.0 2.32193 2.58496 2.80735 3.0 3.16993 3.32193
```
#### Maps
An `AbstractDict` type is encoded as CBOR `Type 5`
```julia
> d = Dict()
> d["GNU's"] = "not UNIX"
> d[Float64(e)] = [2, "+", 0.718281828459045]
> bytes = encode(d)
38-element Array{UInt8, 1}: 0xa2 0x65 0x47 0x4e 0x55 ... 0x28 0x6f 0x8a 0xd2 0x56
> decode(bytes)
Dict{Any,Any} with 2 entries:
"GNU's" => "not UNIX"
2.718281828459045 => Any[0x02, "+", 0.718281828459045]
```
#### Tagging
To *tag* one of the above types, encode a `Tag` with `first` being an
**non-negative** integer, and `second` being the data you want to tag.
```julia
> bytes = encode(Tag(80, "web servers"))
> data = decode(bytes)
0x50=>"HTTP Web Server"
```
There exists an [IANA registery](http://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml)
which assigns certain meanings to tags; for example, a string tagged
with a value of `32` is to be interpreted as a
[Uniform Resource Locater](https://tools.ietf.org/html/rfc3986). To decode a
tagged CBOR data item, and then to automatically interpret the meaning of the
tag, use `decode_with_iana`.
For example, a Julia `BigInt` type is encoded as an `Array{UInt8, 1}` containing
the bytes of it's hexadecimal representation, and tagged with a value of `2` or
`3`
```julia
> b = BigInt(factorial(20))
2432902008176640000
> bytes = encode(b * b * -b)
34-element Array{UInt8,1}: 0xc3 0x58 0x1f 0x13 0xd4 ... 0xff 0xff 0xff 0xff 0xff
```
To decode `bytes` *without* interpreting the meaning of the tag, use `decode`
```julia
> decode(bytes)
0x03 => UInt8[0x96, 0x58, 0xd1, 0x85, 0xdb .. 0xff 0xff 0xff 0xff 0xff]
```
To decode `bytes` and to interpret the meaning of the tag, use
`decode_with_iana`
```julia
> decode_with_iana(bytes)
-14400376622525549608547603031202889616850944000000000000
```
Currently, only `BigInt` is supported for automatically tagged encoding and
decoding; more Julia types will be added in the future.
#### Composite Types
A generic `DataType` that isn't one of the above types is encoded through
`encode` using reflection. This is supported only if all of the fields of the
type belong to one of the above types.
For example, say you have a user-defined type `Point`
```julia
mutable struct Point
x::Int64
y::Float64
space::String
end
point = Point(1, 3.4, "Euclidean")
```
When `point` is passed into `encode`, it is first converted to a `Dict`
containing the symbolic names of it's fields as keys associated to their
respective values and a `"type"` key associated to the type's
symbolic name, like so
```julia
Dict{Any, Any} with 3 entries:
"x" => 0x01
"type" => "Point"
"y" => 3.4
"space" => "Euclidean"
```
The `Dict` is then encoded as CBOR `Type 5`.
#### Indefinite length collections
To encode collections of *indefinite* length, you can just wrap any iterator
in the `CBOR.UndefLength` type. Make sure that your Iterator knows their eltype
to e.g. create a bytestring / string / Dict *indefinite* length encoding.
The eltype mapping is:
```julia
Vector{UInt8} -> bytestring
String -> bytestring
Pair -> Dict
Any -> List
```
If the eltype is unknown, but you still want to enforce it, use this constructor:
```Julia
CBOR.UndefLength{String}(iter)
```
First create some julia iterator with unknown length
```julia
function producer(ch::Channel)
for i in 1:10
put!(ch,i*i)
end
end
iter = Channel(producer)
```
encode it with UndefLength
```julia
> encode(UndefLength(iter))
18-element Array{UInt8, 1}: 0x9f 0x01 0x04 0x09 0x10 ... 0x18 0x51 0x18 0x64 0xff
> decode(bytes)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
```
While encoding an indefinite length `Map`, produce first the key and then the
value for each key-value pair, or produce pairs!
```julia
function cubes(ch::Channel)
for i in 1:10
put!(ch, i) # key
put!(ch, i*i*i) # value
end
end
> bytes = encode(UndefLength{Pair}(Channel(cubes)))
34-element Array{UInt8, 1}: 0xbf 0x01 0x01 0x02 0x08 ... 0x0a 0x19 0x03 0xe8 0xff
> decode(bytes)
Dict(7=>343,4=>64,9=>729,10=>1000,2=>8,3=>27,5=>125,8=>512,6=>216,1=>1)
```
Note that when an indefinite length CBOR `Type 2` or `Type 3` is decoded,
the result is a *concatenation* of the individual elements.
```julia
function producer(ch::Channel)
for c in ["F", "ire", " ", "and", " ", "Blo", "od"]
put!(ch,c)
end
end
> bytes = encode(UndefLength{String}(Channel(producer)))
23-element Array{UInt8, 1}: 0x7f 0x61 0x46 0x63 0x69 ... 0x6f 0x62 0x6f 0x64 0xff
> decode(bytes)
"Fire and Blood"
```
### Caveats
Encoding a `UInt128` and an `Int128` isn't supported; use a `BigInt` instead.
Decoding CBOR data that isn't well-formed is unpredictable.
| CBOR | https://github.com/JuliaIO/CBOR.jl.git |
|
[
"MIT"
] | 0.3.2 | cbdf14d1e8c7c8aacbe8b19862e0179fd08321c2 | code | 3947 | module FFTViews
using Base: tail, unsafe_length, @propagate_inbounds
using FFTW
# A custom rangetype that will be used for indices and never throws a
# boundserror because the domain is actually periodic.
using CustomUnitRanges
include(CustomUnitRanges.filename_for_urange)
@static if isdefined(Base, :IdentityUnitRange)
const indextypes = (URange, Base.IdentityUnitRange{<:URange})
const FFTVRange{T} = Union{URange{T}, Base.Slice{URange{T}}, Base.IdentityUnitRange{URange{T}}}
indrange(i) = Base.IdentityUnitRange(URange(first(i)-1, last(i)-1))
else
const indextypes = (URange, Base.Slice{<:URange})
const FFTVRange{T} = Union{URange{T}, Base.Slice{URange{T}}}
indrange(i) = Base.Slice(URange(first(i)-1, last(i)-1))
end
for T in indextypes
@eval begin
Base.checkindex(::Type{Bool}, ::$T, ::Base.Slice) = true
Base.checkindex(::Type{Bool}, ::$T, ::Base.LogicalIndex) = true
Base.checkindex(::Type{Bool}, ::$T, ::Real) = true
Base.checkindex(::Type{Bool}, ::$T, ::AbstractRange) = true
Base.checkindex(::Type{Bool}, ::$T, ::AbstractVector{Bool}) = true
Base.checkindex(::Type{Bool}, ::$T, ::AbstractArray{Bool}) = true
Base.checkindex(::Type{Bool}, ::$T, ::AbstractArray) = true
end
if isdefined(Base, :IdentityUnitRange)
@eval Base.checkindex(::Type{Bool}, ::$T, ::Base.IdentityUnitRange) = true
end
end
export FFTView
abstract type AbstractFFTView{T,N} <: AbstractArray{T,N} end
struct FFTView{T,N,A<:AbstractArray} <: AbstractFFTView{T,N}
parent::A
function FFTView{T,N,A}(parent::A) where {T,N,A}
new{T,N,A}(parent)
end
end
FFTView(parent::AbstractArray{T,N}) where {T,N} = FFTView{T,N,typeof(parent)}(parent)
FFTView{T,N}(dims::Dims{N}) where {T,N} = FFTView(Array{T,N}(undef, dims))
FFTView{T}(dims::Dims{N}) where {T,N} = FFTView(Array{T,N}(undef, dims))
# Note: there are no bounds checks because it's all periodic
@inline @propagate_inbounds function Base.getindex(F::FFTView{T,N}, I::Vararg{Int,N}) where {T,N}
P = parent(F)
@inbounds ret = P[reindex(FFTView, axes(P), I)...]
ret
end
@inline @propagate_inbounds function Base.setindex!(F::FFTView{T,N}, val, I::Vararg{Int,N}) where {T,N}
P = parent(F)
@inbounds P[reindex(FFTView, axes(P), I)...] = val
end
Base.parent(F::AbstractFFTView) = F.parent
Base.axes(F::AbstractFFTView) = map(indrange, axes(parent(F)))
Base.size(F::AbstractFFTView) = size(parent(F))
function Base.similar(A::AbstractArray, T::Type, shape::Tuple{FFTVRange,Vararg{FFTVRange}})
all(x->first(x)==0, shape) || throw(BoundsError("cannot allocate FFTView with the first element of the range non-zero"))
FFTView(similar(A, T, map(length, shape)))
end
function Base.similar(f::Union{Function,Type}, shape::Tuple{FFTVRange,Vararg{FFTVRange}})
all(x->first(x)==0, shape) || throw(BoundsError("cannot allocate FFTView with the first element of the range non-zero"))
FFTView(similar(f, map(length, shape)))
end
Base.reshape(F::FFTView{_,N}, ::Type{Val{N}}) where {_,N} = F
Base.reshape(F::FFTView{_,M}, ::Type{Val{N}}) where {_,M,N} = FFTView(reshape(parent(F), Val(N)))
FFTW.fft(F::FFTView; kwargs...) = fft(parent(F); kwargs...)
FFTW.rfft(F::FFTView; kwargs...) = rfft(parent(F); kwargs...)
FFTW.fft(F::FFTView, dims; kwargs...) = fft(parent(F), dims; kwargs...)
FFTW.rfft(F::FFTView, dims; kwargs...) = rfft(parent(F), dims; kwargs...)
@inline reindex(::Type{V}, inds, I) where {V} = (_reindex(V, inds[1], I[1]), reindex(V, tail(inds), tail(I))...)
reindex(::Type{V}, ::Tuple{}, ::Tuple{}) where {V} = ()
_reindex(::Type{FFTView}, ind, i) = modrange(i+1, ind)
if VERSION >= v"1.7.0-beta4"
# https://github.com/JuliaLang/julia/pull/40382
modrange(i, rng::AbstractUnitRange) = mod(i-first(rng), length(rng))+first(rng)
else
modrange(i, rng::AbstractUnitRange) = mod(i-first(rng), unsafe_length(rng))+first(rng)
end
end # module
| FFTViews | https://github.com/JuliaArrays/FFTViews.jl.git |
|
[
"MIT"
] | 0.3.2 | cbdf14d1e8c7c8aacbe8b19862e0179fd08321c2 | code | 4144 | using FFTViews
using FFTW
using Test
if VERSION < v"1.1"
# https://github.com/JuliaLang/julia/pull/29442
_oneunit(::CartesianIndex{N}) where {N} = _oneunit(CartesianIndex{N})
_oneunit(::Type{CartesianIndex{N}}) where {N} = CartesianIndex(ntuple(x -> 1, Val(N)))
else
const _oneunit = Base.oneunit
end
function test_approx_eq_periodic(a::FFTView, b)
for I in CartesianIndices(axes(b))
@test a[I-_oneunit(I)] β b[I]
end
nothing
end
function test_approx_eq_periodic(a::FFTView, b::FFTView)
for I in CartesianIndices(axes(b))
@test a[I] β b[I]
end
nothing
end
@testset "basics" begin
a = FFTView{Float64,2}((5,7))
@test axes(a) == (0:4, 0:6)
@test eltype(a) == Float64
a = FFTView{Float64}((5,7))
@test axes(a) == (0:4, 0:6)
@test eltype(a) == Float64
@test_throws MethodError FFTView{Float64,3}((5,7))
for i = 1:35
a[i] = i
end
@test a[3,1] == 9
@test a[:,0] == FFTView(collect(1:5))
@test a[0,:] == FFTView(collect(1:5:35))
@test a[1,0:7] == [2:5:35;2]
@test a[2,[0,1,0,-1]] == [3,8,3,33]
@test a[3,trues(9)] == [9,14,19,24,29,34,4,9,14]
@test a[3,FFTView(trues(9))] == [4,9,14,19,24,29,34,4,9]
b = similar(Array{Int}, axes(a))
@test isa(b, FFTView)
@test axes(b) == axes(a)
@test eltype(b) == Int
@test reshape(a, Val{2}) === a
@test reshape(a, Val{1}) == FFTView(convert(Vector{Float64}, collect(1:35)))
@test axes(reshape(a, Val{3})) == (0:4,0:6,0:0)
end
@testset "convolution-shift" begin
for l in (8,9)
a = zeros(l)
v = FFTView(a)
@test axes(v,1) == 0:l-1
v[0] = 1
p = rand(l)
pfilt = ifft(fft(p).*fft(v))
@test real(pfilt) β p
v[0] = 0
v[-1] = 1
pfilt = ifft(fft(p).*fft(v))
@test real(pfilt) β circshift(p, -1)
v[-1] = 0
v[+1] = 1
pfilt = ifft(fft(p).*fft(v))
@test real(pfilt) β circshift(p, +1)
end
for l2 in (8,9), l1 in (8,9)
a = zeros(l1,l2)
v = FFTView(a)
@test axes(v) == (0:l1-1, 0:l2-1)
p = rand(l1,l2)
for offset in ((0,0), (-1,0), (0,-1), (-1,-1),
(1,0), (0,1), (1,1), (1,-1), (-1,1),
(3,-5), (281,-14))
fill!(a, 0)
v[offset...] = 1
pfilt = ifft(fft(p).*fft(v))
@test real(pfilt) β circshift(p, offset)
end
end
end
using OffsetArrays
@testset "convolution-offset" begin
for l2 in (8,9), l1 in (8,9)
a = OffsetArray(zeros(l1,l2), (-2,-3))
v = FFTView(a)
@test axes(v) == (-2:l1-3, -3:l2-4)
p = rand(l1,l2)
po = OffsetArray(copy(p), (5,-1))
for offset in ((0,0), (-1,0), (0,-1), (-1,-1),
(1,0), (0,1), (1,1), (1,-1), (-1,1),
(3,-5), (281,-14))
fill!(a, 0)
v[offset...] = 1
pfilt = ifft(fft(p).*fft(v))
@test real(pfilt) β circshift(p, offset)
pofilt = ifft(fft(po).*fft(v))
test_approx_eq_periodic(FFTView(real(pofilt)), circshift(po, offset))
pfilt = irfft(rfft(p).*rfft(v), length(axes(v,1)))
@test real(pfilt) β circshift(p, offset)
pofilt = irfft(rfft(po).*rfft(v), length(axes(v,1)))
test_approx_eq_periodic(FFTView(real(pofilt)), circshift(po, offset))
dims = (1,2)
pfilt = ifft(fft(p, dims).*fft(v, dims), dims)
@test real(pfilt) β circshift(p, offset)
pofilt = ifft(fft(po, dims).*fft(v, dims), dims)
test_approx_eq_periodic(FFTView(real(pofilt)), circshift(po, offset))
pfilt = irfft(rfft(p, dims).*rfft(v, dims), length(axes(v,1)), dims)
@test real(pfilt) β circshift(p, offset)
pofilt = irfft(rfft(po, dims).*rfft(v, dims), length(axes(v,1)), dims)
test_approx_eq_periodic(FFTView(real(pofilt)), circshift(po, offset))
end
end
end
@testset "vector indexing" begin
v = FFTView(1:10)
@test v[-10:15] == [1:10;1:10;1:6]
end
nothing
| FFTViews | https://github.com/JuliaArrays/FFTViews.jl.git |
|
[
"MIT"
] | 0.3.2 | cbdf14d1e8c7c8aacbe8b19862e0179fd08321c2 | docs | 4140 | # FFTViews
[](https://travis-ci.org/JuliaArrays/FFTViews.jl)
[](http://codecov.io/github/JuliaArrays/FFTViews.jl?branch=master)
A package for simplifying operations that involve Fourier
transforms. An FFTView of an array uses periodic boundary conditions
for indexing, and shifts all indices of the array downward by 1.
# Usage
Let's create a random signal:
```julia
julia> using FFTViews
julia> a = rand(8)
8-element Array{Float64,1}:
0.720657
0.42337
0.207867
0.959567
0.371366
0.907781
0.852526
0.689934
```
Now let's take its Fourier transform, and wrap the result as an `FFTView`:
```julia
julia> afft = fft(a)
8-element Array{Complex{Float64},1}:
5.13307+0.0im
-0.183898+0.796529im
0.03163+0.31835im
0.88248-0.492787im
-0.828236+0.0im
0.88248+0.492787im
0.03163-0.31835im
-0.183898-0.796529im
julia> v = FFTView(afft)
FFTViews.FFTView{Complex{Float64},1,Array{Complex{Float64},1}} with indices FFTViews.URange(0,7):
5.13307+0.0im
-0.183898+0.796529im
0.03163+0.31835im
0.88248-0.492787im
-0.828236+0.0im
0.88248+0.492787im
0.03163-0.31835im
-0.183898-0.796529im
```
Now we can easily look at the zero-frequency bin:
```julia
julia> v[0]
5.133068739504999 + 0.0im
julia> sum(a)
5.133068739504998
```
or negative as well as positive frequencies:
```julia
julia> v[-4:3]
8-element Array{Complex{Float64},1}:
-0.828236+0.0im
0.88248+0.492787im
0.03163-0.31835im
-0.183898-0.796529im
5.13307+0.0im
-0.183898+0.796529im
0.03163+0.31835im
0.88248-0.492787im
```
Perhaps even more interestingly, one can also simplify the process of
convolution. Let's create a "delta-function" signal:
```julia
julia> b = zeros(8); b[3] = 1; b # the signal
8-element Array{Float64,1}:
0.0
0.0
1.0
0.0
0.0
0.0
0.0
0.0
```
and then create the kernel using an `FFTView`:
```julia
julia> kernel = FFTView(zeros(8))
FFTViews.FFTView{Float64,1,Array{Float64,1}} with indices FFTViews.URange(0,7):
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
julia> kernel[-1:1] = rand(3)
3-element Array{Float64,1}:
0.16202
0.446872
0.649135
julia> kernel
FFTViews.FFTView{Float64,1,Array{Float64,1}} with indices FFTViews.URange(0,7):
0.446872
0.649135
0.0
0.0
0.0
0.0
0.0
0.16202
```
Now compute the convolution via the FFT:
```julia
julia> real(ifft(fft(b).*fft(kernel)))
8-element Array{Float64,1}:
0.0
0.16202
0.446872
0.649135
0.0
-5.55112e-17
0.0
-6.93889e-17
```
or alternatively
```julia
julia> irfft(rfft(b).*rfft(kernel),8)
8-element Array{Float64,1}:
0.0
0.16202
0.446872
0.649135
0.0
-2.77556e-17
0.0
-5.55112e-17
```
This simplifies the process of remembering how to pack your kernel.
## Caution: FFTViews are not composable
In Julia, almost all other view types are composable: you can make a
`ReshapedArray` of a `SubArray` of a `StaticArray` of a .... In
contrast, `FFTViews` are *not safe* when placed inside other
containers. The reason is that the `*fft` methods are specialized for
`FFTViews`, and strip off the outer container; this does not happen if
you wrap an `FFTView` inside of some other array type. If you do wrap
`FFTViews`, you might see strange off-by-1 bugs due to the FFTView
translating the indices.
Another way of saying the same thing is the following: for a general vector `x`, its FFT is defined as

Here `x[n]` is defined with periodic boundary conditions, so that if the indices of `x` are not naturally from 1 to N, this formula still holds.
However, if `y = FFTView(x)`, then in terms of `y` we have

which is shifted by 1. Since `FFTView`s use a different definition of
the FFT compared to all other array types, they need to be used with
caution. It's recommended that the FFTView wrapper be applied only for
the process of setting up or analyzing the result of the transform;
for all other operations, pass the `parent` array (obtainable from
`parent(y)` or just by reference to `x` itself).
| FFTViews | https://github.com/JuliaArrays/FFTViews.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 789 | using PsychometricsBazaarBase
using Documenter
format = Documenter.HTML(
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://JuliaPsychometricsBazaar.github.io/PsychometricsBazaarBase.jl",
)
makedocs(;
modules=[PsychometricsBazaarBase],
authors="Frankie Robertson",
repo="https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl/blob/{commit}{path}#{line}",
sitename="PsychometricsBazaarBase.jl",
format=format,
pages=[
"Home" => "index.md",
"Modules" => ["integrators.md", "optimizers.md", "config_tools.md", "integral_coeffs.md", "const_distributions.md"]
],
warnonly = [:missing_docs],
)
deploydocs(;
repo="github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl",
devbranch="main",
)
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 3222 | """
This module contains utilities to implement highly configurible library code
where configuration is performed through structs, and smart defaults allow
sloppy or flat specification of otherwise deeply nested configuration structs.
"""
module ConfigTools
export @requiresome, @returnsome
export find1, find1_instance, find1_type, find1_type_sloppy
using MacroTools
using DocStringExtensions
"""
$(SIGNATURES)
This macro is passed an assignment like so
@requiresome foo = bar()
If `bar()` returns `nothing`, then the macro causes the current function to
return `nothing`. Otherwise, execution continues.
"""
macro requiresome(assign)
@capture(assign, name_ = expr_) || error("@requiresome must be passed an assignment")
quote
$(esc(assign))
if $(esc(name)) === nothing
return nothing
end
end
end
"""
$(SIGNATURES)
This macro is passed an expression like so
@returnsome foo()
If `foo()` return any value apart from `nothing`, the macro causes the current
function to return that value. Otherwise, execution continues.
"""
macro returnsome(expr)
quote
val = $(esc(expr))
if val !== nothing
return val
end
end
end
"""
$(SIGNATURES)
This macro is passed an expression and a function like so
@returnsome foo() do x
bar(x)
end
If `foo()` return any value apart from `nothing`, the macro executes the
function and returns the value as long as it is not `nothing`. In all other
cases, execution continues.
"""
macro returnsome(expr, func)
quote
val = $(esc(expr))
if val !== nothing
res = ($(esc(func)))(val)
if res !== nothing
return res
end
end
end
end
"""
$(SIGNATURES)
Given an iterable `iter` and a predicate `pred`, this function returns a match
or else `nothing` if no match. In case there are multiple matches, an error is
thrown.
"""
function find1(pred::F, iter, fail_msg) where {F}
res = nothing
cnt = 0
for bit in iter
if pred(bit)
res = bit
cnt += 1
end
end
if cnt > 1
error(fail_msg)
end
return res
end
"""
$(SIGNATURES)
Returns exactly one instance in `iter` of type `type` or else `nothing``. In
case there are multiple matches, an error is thrown.
"""
function find1_instance(type, iter)
find1(
x -> isa(x, type),
iter,
"Expected exactly one instance of " * repr(type)
)
end
"""
$(SIGNATURES)
Returns exactly one type in `iter` of which is a subtype of `type` or else
`nothing``. In case there are multiple matches, an error is thrown.
"""
function find1_type(type, iter)
return find1(
x -> (((x isa DataType) || (x isa UnionAll)) && x <: type),
iter,
"Expected exactly one type " * repr(type)
)
end
"""
$(SIGNATURES)
Returns exactly one type in `iter` of which is either a subtype of `type` or an
instance of `type` or else `nothing``. In case there are multiple matches, an
error is thrown.
"""
function find1_type_sloppy(type, iter)
@returnsome find1_type(type, iter)
@returnsome find1_instance(type, iter) inst -> typeof(inst)
end
end | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 794 | """
This module contains standard distributions for usage as transfer functions for IRT.
"""
module ConstDistributions
using Distributions: Logistic, Normal
using Lazy: @forward
using DocStringExtensions
export normal_scaled_logistic, std_normal
"""
This scaling facot seems to be the most commonly found exact value in the wild,
see e.g. the R package `mirt``
"""
const logistic_to_normal_scaling_factor = 1.702
"""
The normal scaled logistic distribution is an approximation to the normal
distribution based upon the logistic distribution. It has been commonly used in
IRT modelling, such as in the `mirt` package for R.
"""
const normal_scaled_logistic = Logistic(0.0, 1.0 / logistic_to_normal_scaling_factor)
"""
The standard normal distribution.
"""
const std_normal = Normal()
end
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 933 | """
These are helpers for weighting integrals of p.d.f.s for calculating basic
stats.
The main idea of doing it this way is to have a single instance of these to
reuse specializations and to use structs so as to be able to control the
level of specialization.
"""
module IntegralCoeffs
using Distributions: Distribution, pdf
using DocStringExtensions
"""
$(SIGNATURES)
"""
@inline function one(x_)::Float64
1.0
end
"""
$(SIGNATURES)
"""
@inline function id(x::T)::T where {T}
x
end
"""
$(SIGNATURES)
"""
struct SqDev{CenterT}
center::CenterT
end
@inline function (sq_dev::SqDev{CenterT})(x::CenterT)::CenterT where {CenterT}
(x .- sq_dev.center) .^ 2
end
struct Prior{Dist <: Distribution}
dist::Dist
end
"""
$(SIGNATURES)
"""
struct PriorApply{Dist, F}
prior::Prior{Dist}
func::F
end
@inline function (prior_apply::PriorApply)(x)
pdf(prior_apply.prior.dist, x) * prior_apply.func(x)
end
end | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 237 | module Interpolators
using Interpolations
function interp(xs, ys)
extrapolate(
interpolate(
xs,
ys,
SteffenMonotonicInterpolation()
),
Interpolations.Flat()
)
end
end | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 2743 | """
This module provides a common interface to different numerical optimization
techniques.
"""
module Optimizers
export Optimizer, OneDimOptimOptimizer, MultiDimOptimOptimizer
export
# Optimization algorithms
## Zeroth order methods (heuristics)
NelderMead,
ParticleSwarm,
SimulatedAnnealing,
## First order
### Quasi-Newton
GradientDescent,
BFGS,
LBFGS,
### Conjugate gradient
ConjugateGradient,
### Acceleration methods
AcceleratedGradientDescent,
MomentumGradientDescent,
### Nonlinear GMRES
NGMRES,
OACCEL,
## Second order
### (Quasi-)Newton
Newton,
### Trust region
NewtonTrustRegion,
# Constrained
## Box constraints, x_i in [lb_i, ub_i]
### Specifically Univariate, R -> R
GoldenSection,
Brent,
### Multivariate, R^N -> R
Fminbox,
SAMIN,
## Manifold constraints
Manifold,
Flat,
Sphere,
Stiefel,
## Non-linear constraints
IPNewton
using ..ConfigTools
using ..Parameters
using Optim
using DocStringExtensions
abstract type Optimizer end
function Optimizer(bits...)
@returnsome find1_instance(Optimizer, bits)
end
"""
Wraps an Optim.jl optimizer to optimize a single-dimensional domain function.
$(SIGNATURES)
"""
struct OneDimOptimOptimizer{OptimT <: Optim.AbstractOptimizer} <: Optimizer
lo::Float64
hi::Float64
initial::Float64
optim::OptimT
opts::Optim.Options
end
function OneDimOptimOptimizer(lo, hi, optim)
OneDimOptimOptimizer(lo, hi, lo + (hi - lo) / 2, optim, Optim.Options())
end
function(opt::OneDimOptimOptimizer)(
f::F;
lo=opt.lo,
hi=opt.hi,
initial=opt.initial,
optim=opt.optim,
opts=opt.opts
) where {F}
Optim.minimizer(optimize(
ΞΈ_arr -> -f(first(ΞΈ_arr)),
lo,
hi,
[initial],
optim,
opts
))[1]
end
"""
Wraps an Optim.jl optimizer to optimize a multi-dimensional domain function.
$(SIGNATURES)
"""
struct MultiDimOptimOptimizer{OptimT <: Optim.AbstractOptimizer} <: Optimizer
lo::Vector{Float64}
hi::Vector{Float64}
initial::Vector{Float64}
optim::OptimT
opts::Optim.Options
end
function MultiDimOptimOptimizer(lo, hi, optim)
MultiDimOptimOptimizer(lo, hi, lo + (hi - lo) / 2, optim, Optim.Options())
end
function(opt::MultiDimOptimOptimizer)(
f::F;
lo=opt.lo,
hi=opt.hi,
initial=opt.initial,
optim=opt.optim,
opts=opt.opts
) where {F}
Optim.minimizer(optimize(
ΞΈ_arr -> -f(ΞΈ_arr),
lo,
hi,
initial,
optim,
opts
))
end
end
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 288 | module PsychometricsBazaarBase
using DocStringExtensions
include("./vendor/Parameters.jl")
include("./ConfigTools.jl")
include("./IntegralCoeffs.jl")
include("./integrators/Integrators.jl")
include("./ConstDistributions.jl")
include("./Interpolators.jl")
include("./Optimizers.jl")
end | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 3207 | """
This module provides a common interface to different numerical integration techniques.
"""
module Integrators
export Integrator, QuadGKIntegrator, FixedGKIntegrator
export CubatureIntegrator, HCubatureIntegrator, MultiDimFixedGKIntegrator
export normdenom, intval, interr
export CubaVegas, CubaSuave, CubaDivonne, CubaCuhre
export IntReturnType, IntValue, IntMeasurement
export CubaIntegrator, CubaVegas, CubaSuave, CubaDivonne, CubaCuhre
export FixedGridIntegrator, even_grid, quasimontecarlo_grid
export BareIntegrationResult, ErrorIntegrationResult
using ..ConfigTools
using ..IntegralCoeffs: one
import Measurements
using DocStringExtensions
abstract type Integrator end
function Integrator(bits...)
@returnsome find1_instance(Integrator, bits)
end
abstract type IntReturnType end
struct IntValue <: IntReturnType end
struct IntMeasurement <: IntReturnType end
struct IntPassthrough <: IntReturnType end
function (::IntValue)(res)
intval(res)
end
function (::IntMeasurement)(res)
intmes(res)
end
function (::IntPassthrough)(res)
res
end
function normdenom(integrator::Integrator; options...)
normdenom(IntValue(), integrator; options...)
end
function normdenom(rett::IntReturnType, integrator::Integrator; lo=integrator.lo, hi=integrator.hi, options...)
# XXX: Presumably we can just return the analytic value here instead? Is this function even needed?
rett(integrator(one; lo=lo, hi=hi, options...))
end
struct ScaleUnitDomain{F}
f::F
lo::Vector{Float64}
interval::Vector{Float64}
scaler::Float64
function ScaleUnitDomain(f::F, lo, hi) where {F}
interval = hi .- lo
new{F}(
f,
lo,
interval,
prod(interval)
)
end
end
function (sud::ScaleUnitDomain)(x)
sud.scaler * sud.f(sud.lo .+ sud.interval .* x)
end
# Values from fscore() from mirt/mirtCAT
function mirtcat_quadpnts(nd)
if nd == 1
61
elseif nd == 2
31
elseif nd == 3
15
elseif nd == 4
9
elseif nd == 5
7
else
3
end
end
"""
The result of an integration technique which provides no error value.
$(TYPEDFIELDS)
"""
struct BareIntegrationResult{VecT}
vec::VecT
end
"""
The result of an integration technique which provides an error value. Note that
error values are not comparible between different integration techniques in
general.
$(TYPEDFIELDS)
"""
struct ErrorIntegrationResult{VecT, ErrT}
vec::VecT
err::ErrT
end
"""
Given any integration result, get the integral value.
$(SIGNATURES)
"""
function intval(res::Union{BareIntegrationResult, ErrorIntegrationResult})
res.vec
end
"""
Given any integration result, get the integral error. In case the integration
technique does not supply one, this returns `nothing`.
$(SIGNATURES)
"""
function interr end
function interr(::BareIntegrationResult)
nothing
end
function interr(res::ErrorIntegrationResult)
res.err
end
function intmes(res::ErrorIntegrationResult)
Measurements.measurement.(intval(res), interr(res))
end
include("./quadgk.jl")
include("./hcubature.jl")
include("./cubature.jl")
include("./cuba.jl")
include("./fixed.jl")
end
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 2259 | using Cuba
abstract type CubaAlgorithm end
"""
The VEGAS algorithm.
$(TYPEDEF)
"""
struct CubaVegas <: CubaAlgorithm end
"""
The Sauve algorithm.
$(TYPEDEF)
"""
struct CubaSuave <: CubaAlgorithm end
"""
The Divonne algorithm.
$(TYPEDEF)
"""
struct CubaDivonne <: CubaAlgorithm end
"""
The Cuhre algorithm.
$(TYPEDEF)
"""
struct CubaCuhre <: CubaAlgorithm end
"""
CubaIntegrator is a wrapper around the Cuba.jl integration functions.
$(TYPEDEF)
$(TYPEDFIELDS)
Usage example:
```julia
CubaIntegrator([0.0, 0.0], [1.0, 1.0], CubaVegas()) do x
x[1] * x[2]
end
```
"""
struct CubaIntegrator{AlgorithmT <: CubaAlgorithm, KwargsT} <: Integrator
lo::Vector{Float64}
hi::Vector{Float64}
algorithm::AlgorithmT
kwargs::KwargsT
end
function CubaIntegrator(lo, hi, algorithm; kwargs...)
CubaIntegrator(lo, hi, algorithm, kwargs)
end
get_cuba_integration_func(::CubaVegas) = Cuba.vegas
get_cuba_integration_func(::CubaSuave) = Cuba.suave
get_cuba_integration_func(::CubaDivonne) = Cuba.divonne
get_cuba_integration_func(::CubaCuhre) = Cuba.cuhre
function get_cuba_integration_func(::CubaIntegrator{T}) where {T}
get_cuba_integration_func(T)
end
struct PreallocatedOutputWrapper{F}
inner::F
end
function assign_output(r, y::Number)
r[1] = y
end
function assign_output(r, y::AbstractArray)
for i in 1:length(r)
r[i] = y[i]
end
end
function (wrapper::PreallocatedOutputWrapper)(x, r)
assign_output(r, wrapper.inner(x))
end
"""
(integrator::CubaIntegrator)(f[, ncomp, lo, hi; kwargs...])
Perform a Cuba integration.
"""
function (integrator::CubaIntegrator)(
f::F,
ncomp=0,
lo=integrator.lo,
hi=integrator.hi;
kwargs...
) where F
# TODO: Move ScaleUnitDomain to CubaIntegrator init
res = get_cuba_integration_func(integrator.algorithm)(
PreallocatedOutputWrapper(ScaleUnitDomain(f, lo, hi)),
length(lo),
ncomp == 0 ? 1 : ncomp;
merge(integrator.kwargs, kwargs)...
)
# XXX: Should this be specialised?
# TODO: Use OneDimContinuousDomain
if ncomp == 0
val = res.integral[1]
err = res.error[1]
ErrorIntegrationResult(val, err)
else
ErrorIntegrationResult(res.integral, res.error)
end
end | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 729 | import Cubature
"""
Construct a Cubature integrator based on `Cubature.jl` with on a specified interval.
$(TYPEDFIELDS)
"""
struct CubatureIntegrator{KwargsT} <: Integrator
lo::Vector{Float64}
hi::Vector{Float64}
kwargs::KwargsT
end
function CubatureIntegrator(lo, hi; kwargs...)
CubatureIntegrator(lo, hi, kwargs)
end
"""
(integrator::CubatureIntegrator)(f[, ncomp, lo, hi; kwargs...])
Perform a Cubature integration based on `Cubature.jl`.
"""
function (integrator::CubatureIntegrator)(
f::F,
ncomp=1,
lo=integrator.lo,
hi=integrator.hi;
kwargs...
) where F
ErrorIntegrationResult(Cubature.hcubature(
f, lo, hi;
merge(integrator.kwargs, kwargs)...
)...)
end
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 3279 | using QuasiMonteCarlo
struct FixedGridIntegrator{ContainerT <: Union{Vector{Float64}, Vector{Vector{Float64}}}} <: Integrator
grid::ContainerT
function FixedGridIntegrator(grid)
new{Vector{Float64}}(grid)
end
function FixedGridIntegrator(grid::Vector{Vector{Float64}})
new{Vector{Vector{Float64}}}(grid)
end
end
function even_grid(theta_lo::Number, theta_hi::Number, quadpts)
FixedGridIntegrator(range(theta_lo, theta_hi, quadpts))
end
function even_grid(theta_lo::AbstractVector, theta_hi::AbstractVector, quadpts_per_dim)
prod = Iterators.product((
range(lo, hi, length = quadpts_per_dim)
for (lo, hi)
in zip(theta_lo, theta_hi)
)...)
grid = reshape(collect.(prod), :)
FixedGridIntegrator(grid)
end
function quasimontecarlo_grid(theta_lo, theta_hi, quadpts, sampler)
grid = QuasiMonteCarlo.sample(quadpts, theta_lo, theta_hi, sampler)
FixedGridIntegrator(grid)
end
function (integrator::FixedGridIntegrator)(args...; kwargs...)
preallocate(integrator)(args...; kwargs...)
end
struct PreallocatedFixedGridIntegrator{ContainerT <: Union{Vector{Float64}, Matrix{Float64}}} <: Integrator
inner::FixedGridIntegrator
buf::ContainerT
function PreallocatedFixedGridIntegrator(inner::FixedGridIntegrator{Vector{Float64}})
quadpts = length(inner.grid)
buf = Vector{Float64}(undef, quadpts)
new{Vector{Float64}}(inner, buf)
end
function PreallocatedFixedGridIntegrator(inner::FixedGridIntegrator{Vector{Vector{Float64}}})
quadpts = length(inner.grid)
dim = length(inner.grid[1])
buf = Matrix{Float64}(undef, quadpts, dim)
new{Matrix{Float64}}(inner, buf)
end
end
function (integrator::PreallocatedFixedGridIntegrator)(
f::F,
ncomp::Int=0
) where F
if ncomp == 0
integrator.buf .= f.(integrator.inner.grid)
BareIntegrationResult(sum(integrator.buf))
else
buf_rows = eachrow(integrator.buf)
buf_rows .= f.(integrator.inner.grid)
BareIntegrationResult(dropdims(sum(integrator.buf, dims=1), dims=1))
end
end
function (integrator::PreallocatedFixedGridIntegrator)(
f::F,
init::AbstractVector{Float64},
ncomp::Int=0
) where F
if ncomp == 0
@. integrator.buf = (f.f)(integrator.inner.grid)
@. integrator.buf = integrator.buf * init
#@. integrator.buf = f(integrator.buf, integrator.inner.grid)
BareIntegrationResult(sum(integrator.buf))
else
buf_rows = eachrow(integrator.buf)
@. buf_rows = (f.f)(integrator.inner.grid)
@. buf_rows = buf_rows * init
BareIntegrationResult(dropdims(sum(integrator.buf, dims=1), dims=1))
end
end
function preallocate(integrator::FixedGridIntegrator)
PreallocatedFixedGridIntegrator(integrator)
end
function preallocate(integrator::Integrator)
integrator
end
struct IterativeFixedGridIntegrator <: Integrator
grid::Vector{Float64}
end
function (integrator::IterativeFixedGridIntegrator)(
f::F,
ncomp=0
) where F
if ncomp != 0
error("IterativeFixedGridIntegrator only supports ncomp == 0")
end
s = 0.0
for x in integrator.grid
s += f(x)
end
BareIntegrationResult(s)
end | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 735 | import HCubature
"""
Construct a Cubature integrator based on `HCubature.jl` with on a specified interval.
$(TYPEDFIELDS)
"""
struct HCubatureIntegrator{KwargsT} <: Integrator
lo::Vector{Float64}
hi::Vector{Float64}
kwargs::KwargsT
end
function HCubatureIntegrator(lo, hi; kwargs...)
HCubatureIntegrator(lo, hi, kwargs)
end
"""
(integrator::HCubatureIntegrator)(f[, ncomp, lo, hi; kwargs...])
Perform Cubature integration based on `HCubature.jl`.
"""
function (integrator::HCubatureIntegrator)(
f::F;
ncomp=1,
lo=integrator.lo,
hi=integrator.hi,
kwargs...
) where F
ErrorIntegrationResult(HCubature.hcubature(
f, lo, hi;
merge(integrator.kwargs, kwargs)...
)...)
end | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 3580 | using QuadGK
using QuadGK: cachedrule, evalrule, Segment
using LinearAlgebra: norm
using FillArrays
import Base.Iterators
function fixed_gk(f::F, lo, hi, n) where {F}
x, w, gw = cachedrule(Float64, n)
seg = evalrule(f, lo, hi, x, w, gw, norm)
(seg.I, seg.E)
end
"""
Construct a adaptive Gauss-Kronrod integrator based on `QuadGK.jl` with on a specified interval.
$(TYPEDFIELDS)
"""
struct QuadGKIntegrator <: Integrator
lo::Float64
hi::Float64
order::Int
end
# This could be unsafe if quadgk performed i/o. It might be wise to switch to
# explicitly passing this through from the caller at some point.
# Just preallocate an arbitrary size for now (easiest, would make more sense to use 'order' somehow but we don't have it)
# It's 24 * 100 * threads bytes, ~10kb for 4 threads which is unconditionally allocated when this library is used
segbufs = [Vector{Segment{Float64, Float64, Float64}}(undef, 100) for _ in Threads.nthreads()]
"""
(integrator::QuadGKIntegrator)(f[, ncomp, lo, hi; order=..., rtol=...])
Perform an adaptive Gauss-Kronrod integration using `QuadGK.jl`.
"""
function (integrator::QuadGKIntegrator)(
f::F,
ncomp=0,
lo=integrator.lo,
hi=integrator.hi;
order=integrator.order,
rtol=1e-4
) where F
if ncomp != 0
error("QuadGKIntegrator only supports ncomp == 0")
end
ErrorIntegrationResult(quadgk(f, lo, hi, rtol=rtol, segbuf=segbufs[Threads.threadid()], order=order)...)
end
"""
Construct a fixed-order Gauss-Kronrod integrator based on `QuadGK.jl` with on a specified interval.
$(TYPEDFIELDS)
"""
struct FixedGKIntegrator <: Integrator
lo::Float64
hi::Float64
order::Int
end
"""
(integrator::QuadGKIntegrator)(f[, ncomp, lo, hi; order=...])
Perform a fixed-order Gauss-Kronrod integration based on `QuadGK.jl`.
"""
function (integrator::FixedGKIntegrator)(
f::F,
ncomp=0,
lo=integrator.lo,
hi=integrator.hi;
order=integrator.order
) where F
if ncomp != 0
error("FixedGKIntegrator only supports ncomp == 0")
end
ErrorIntegrationResult(fixed_gk(f, lo, hi, order)...)
end
"""
Construct a fixed-order multi-dimensional Gauss-Kronrod integrator based on
`QuadGK.jl` with on a specified interval.
$(TYPEDFIELDS)
"""
struct MultiDimFixedGKIntegrator{OrderT <: AbstractVector{Int}} <: Integrator
lo::Vector{Float64}
hi::Vector{Float64}
order::OrderT
end
function MultiDimFixedGKIntegrator(lo, hi)
MultiDimFixedGKIntegrator(lo, hi, mirtcat_quadpnts(length(lo)))
end
function MultiDimFixedGKIntegrator(lo, hi, order::Int)
MultiDimFixedGKIntegrator(lo, hi, Fill(order, length(lo)))
end
"""
(integrator::QuadGKIntegrator)(f[, ncomp, lo, hi; order=...])
Perform a fixed-order multi-dimensional Gauss-Kronrod integrator based on `QuadGK.jl`.
"""
function (integrator::MultiDimFixedGKIntegrator)(
f::F,
ncomp=1,
lo=integrator.lo,
hi=integrator.hi;
order=integrator.order
) where F
x = Array{Float64}(undef, length(lo))
function inner(idx)
function integrate()
return fixed_gk(inner(idx + 1), lo[idx + 1], hi[idx + 1], order[idx + 1])[1]
end
function f1d(x1d)
x[idx] = x1d
if idx >= length(lo)
#@info "Calling f" x
return f(x)
else
return integrate()
end
end
if idx == 0
return integrate()
else
return f1d
end
end
# TODO: Combine errors somehow
BareIntegrationResult(inner(0))
end
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 22570 | # This module has been vendored from a pull request on
# https://github.com/mauro3/Parameters.jl/pull/147
# It can be removed when equivalent functionality is in Parameters.jl or another
# package
__precompile__()
"""
This is a package I use to handle numerical-model parameters,
thus the name. However, it should be useful otherwise too.
It has two main features:
- keyword type constructors with default values, and
- unpacking and packing of composite types and dicts.
The macro `@with_kw` which decorates a type definition to
allow default values and a keyword constructor:
```
julia> using PsychometricBazaarBase.Parameters
julia> @with_kw struct A
a::Int = 6
b::Float64 = -1.1
c::UInt8
end
julia> A(c=4)
A
a: 6
b: -1.1
c: 4
```
Unpacking is done with `@unpack` (`@pack!` is similar):
```
struct B
a
b
c
end
@unpack a, c = B(4,5,6)
# is equivalent to
BB = B(4,5,6)
a = BB.a
c = BB.c
```
"""
module Parameters
import Base: @__doc__
import OrderedCollections: OrderedDict
using UnPack: @unpack, @pack!
export @with_kw, @kw_only, @with_kw_noshow, type2dict, reconstruct, @unpack, @pack!, @consts
## Parser helpers
#################
# To iterate over code blocks dropping the line-number bits:
struct Lines
block::Expr
end
start(lns::Lines) = 1
function next(lns::Lines, nr)
for i=nr:length(lns.block.args)
if lns.block.args[i] isa LineNumberNode
continue
end
if ( lns.block.args[i] isa Symbol
|| lns.block.args[i] isa String # doc-string
|| !(lns.block.args[i].head==:line))
return lns.block.args[i], i+1
end
end
return -1
end
function done(lns::Lines, nr)
if next(lns::Lines, nr)==-1
true
else
false
end
end
function Base.iterate(lns::Lines, nr=start(lns))
nr = next(lns, nr)
return nr == -1 ? nothing : nr
end
# This is not O(1) but hey...
function Base.setindex!(lns::Lines, val, ind)
ii = 1
for i=1:length(lns.block.args)
if lns.block.args[i] isa LineNumberNode
continue
end
if lns.block.args[i] isa Symbol || !(lns.block.args[i].head==:line)
if ind==ii
lns.block.args[i] = val
return nothing
end
ii +=1
end
end
throw(BoundsError("Attempted to set line $ind of $(ii-1) length code-block"))
end
# Transforms :(a::b) -> :a
decolon2(a::Expr) = (@assert a.head==:(::); a.args[1])
decolon2(a::Symbol) = a
# Keep the ::T of the args if T β typparas,
# leave symbols as is, drop field-doc-strings.
function keep_only_typparas(args, typparas)
args = copy(args)
tokeep = Int[]
typparas_ = map(stripsubtypes, typparas)
for i=1:length(args)
isa(args[i], String) && continue # do not keep field doc-strings
push!(tokeep, i)
isa(args[i], Symbol) && continue
# keep the typepara if β typparas
@assert args[i].head==:(::)
T = args[i].args[2]
if !(symbol_in(typparas_, T))
args[i] = decolon2(args[i])
end
end
args[tokeep]
end
# check whether a symbol is contained in an expression
symbol_in(s::Symbol, ex::Symbol) = s==ex
symbol_in(s::Symbol, ex) = false
function symbol_in(s::Symbol, ex::Expr)
for a in ex.args
symbol_in(s,a) && return true
end
return false
end
symbol_in(s::Symbol, ex::Vector) = any(map(e->symbol_in(s, e), ex))
symbol_in(s::Vector, ex) = any(map(ss->symbol_in(ss, ex), s))
# Returns the name of the type as Symbol
function typename(typedef::Expr)
if typedef.args[2] isa Symbol
return typedef.args[2]
elseif typedef.args[2].args[1] isa Symbol
return typedef.args[2].args[1]
elseif typedef.args[2].args[1].args[1] isa Symbol
return typedef.args[2].args[1].args[1]
else
error("Could not parse type-head from: $typedef")
end
end
# Transforms: Expr(:<:, :A, :B) -> :A
stripsubtypes(s::Symbol) = s
function stripsubtypes(e::Expr)
e.args[1]
end
stripsubtypes(vec::Vector) = [stripsubtypes(v) for v in vec]
function check_inner_constructor(l)
if l.args[1].head==:where
fnhead = l.args[1].args[1]
else
fnhead = l.args[1]
end
if length(fnhead.args)==1
error("No inner constructors with zero positional arguments allowed!")
elseif (length(fnhead.args)==2 #1<length(fnhead.args)<=3
&& fnhead.args[2] isa Expr
&& fnhead.args[2].head==:parameters)
error("No inner constructors with zero positional arguments plus keyword arguments allowed!")
end
nothing
end
## Exported helper functions
#####################
"""
Transforms a type-instance into a dictionary.
```
julia> struct T
a
b
end
julia> type2dict(T(4,5))
Dict{Symbol,Any} with 2 entries:
:a => 4
:b => 5
```
Note that this uses `getproperty`.
"""
function type2dict(dt)
di = Dict{Symbol,Any}()
for n in propertynames(dt)
di[n] = getproperty(dt, n)
end
di
end
"""
reconstruct(pp; kws...
reconstruct(T::Type, pp; kws...)
Make a new instance of a type with the same values as the input type
except for the fields given in the keyword args. Works for types, Dicts,
and NamedTuples. Can also reconstruct to another type, which is probably
mostly useful for parameterised types where the parameter changes on
reconstruction.
Note: this is not very performant. Check Setfield.jl for a faster &
nicer implementation.
```
julia> using PsychometricBazaarBase.Parameters
julia> struct A
a
b
end
julia> x = A(3,4)
A(3, 4)
julia> reconstruct(x, b=99)
A(3, 99)
julia> struct B{T}
a::T
b
end
julia> y = B(sin, 1)
B{typeof(sin)}(sin, 1)
julia> reconstruct(B, y, a=cos) # note reconstruct(y, a=cos) errors!
B{typeof(cos)}(cos, 1)
```
"""
reconstruct(pp::T, di) where T = reconstruct(T, pp, di)
reconstruct(pp; kws...) = reconstruct(pp, kws)
reconstruct(T::Type, pp; kws...) = reconstruct(T, pp, kws)
function reconstruct(::Type{T}, pp, di) where T
di = !isa(di, AbstractDict) ? Dict(di) : copy(di)
ns = if T<:AbstractDict
if pp isa AbstractDict
keys(pp)
else
fieldnames(typeof(pp))
end
else
fieldnames(T)
end
args = []
for (i,n) in enumerate(ns)
if pp isa AbstractDict
push!(args, pop!(di, n, pp[n]))
else
push!(args, pop!(di, n, getfield(pp, n)))
end
end
length(di)!=0 && error("Fields $(keys(di)) not in type $T")
if T<:AbstractDict
return T(zip(ns,args))
elseif T <: NamedTuple
return T(Tuple(args))
else
return T(args...)
end
end
###########################
# Keyword constructors with @with_kw
##########################
# A type with fields (r,a) in variable aa becomes
# quote
# r = aa.r
# a = aa.a
# end
_unpack(binding, fields) = Expr(:block, [:($f = $binding.$f) for f in fields]...)
# Pack fields back into binding using reconstruct:
function _pack_mutable(binding, fields)
e = Expr(:block, [:($binding.$f = $f) for f in fields]...)
push!(e.args, binding)
e
end
function _pack_new(T, fields)
Expr(:call, T, fields...)
end
struct __Private end
"""
This function is called by the `@with_kw` macro and does the syntax
transformation from:
```julia
@with_kw struct MM{R}
r::R = 1000.
a::R
end
```
into
```julia
struct MM{R}
r::R
a::R
MM{R}(r,a) where {R} = new(r,a)
MM{R}(;r=1000., a=error("no default for a")) where {R} = MM{R}(r,a) # inner kw, type-paras are required when calling
end
MM(r::R,a::R) where {R} = MM{R}(r,a) # default outer positional constructor
MM(;r=1000,a=error("no default for a")) = MM(r,a) # outer kw, so no type-paras are needed when calling
MM(m::MM; kws...) = reconstruct(mm,kws)
MM(m::MM, di::Union{AbstractDict, Tuple{Symbol,Any}}) = reconstruct(mm, di)
macro unpack_MM(varname)
esc(quote
r = varname.r
a = varname.a
end)
end
macro pack_MM(varname)
esc(quote
varname = $Parameters.reconstruct(varname,r=r,a=a)
end)
end
```
"""
function with_kw(typedef, mod::Module, withshow=true, allow_default=true)
if typedef.head==:tuple # named-tuple
withshow==false && error("`@with_kw_noshow` not supported for named tuples")
return with_kw_nt(typedef, mod)
elseif typedef.head != :struct
error("""Only works on type-defs or named tuples.
Make sure to have a space after `@with_kw`, e.g. `@with_kw (a=1,)
Also, make sure to use a trailing comma for single-field NamedTuples.
""")
end
err1str = "Field \'"
err2str = "\' has no default, supply it with keyword."
inner_constructors = Any[]
# parse a few things
tn = typename(typedef) # the name of the type
ismutable = typedef.args[1]
# Returns M{...} (removes any supertypes)
if typedef.args[2] isa Symbol
typparas = Any[]
elseif typedef.args[2].head==:<:
if typedef.args[2].args[1] isa Symbol
typparas = Any[]
else
typparas = typedef.args[2].args[1].args[2:end]
end
else
typparas = typedef.args[2].args[2:end]
end
# error on types without fields
lns = Lines(typedef.args[3])
if done(lns, start(lns))
error("@with_kw only supported for types which have at least one field.")
end
# default type @deftype
l, i = next(lns, start(lns))
if l isa Expr && l.head == :macrocall && l.args[1] == Symbol("@deftype")
has_deftyp = true
if length(l.args) != 3
error("Malformed `@deftype` line $l")
end
deftyp = l.args[3]
if done(lns, i)
error("@with_kw only supported for types which have at least one field.")
end
else
has_deftyp = false
end
# Expand all macros (except @assert) in body now (only works at
# top-level)
# See issue https://github.com/mauro3/Parameters.jl/issues/21
lns2 = Any[] # need new lines as expanded macros may have many lines
for (i,l) in enumerate(lns) # loop over body of typedef
if i==1 && has_deftyp
push!(lns2, l)
continue
end
if l isa Symbol || l isa String
push!(lns2, l)
continue
end
if l.head==:macrocall && l.args[1]!=Symbol("@assert")
tmp = macroexpand(mod, l)
if tmp.head==:block
llns = Lines(tmp)
for ll in llns
push!(lns2, ll)
end
else
push!(lns2,tmp)
end
else
push!(lns2, l)
end
end
lns = lns2
# the vars for the unpack macro
unpack_vars = Any[]
# the type def
fielddefs = quote end # holds r::R etc
fielddefs.args = Any[]
kws = OrderedDict{Any, Any}()
# assertions in the body
asserts = Any[]
for (i,l) in enumerate(lns) # loop over body of typedef
if i==1 && has_deftyp
# ignore @deftype line
continue
end
if l isa Symbol # no default value and no type annotation
if has_deftyp
push!(fielddefs.args, :($l::$deftyp))
else
push!(fielddefs.args, l)
end
sym = l
syms = string(sym)
kws[sym] = :(error($err1str * $syms * $err2str))
# unwrap-macro
push!(unpack_vars, sym)
elseif l isa String # doc-string
push!(fielddefs.args, l)
elseif l.head==:(=) # default value and with or without type annotation
if l.args[1] isa Expr && (l.args[1].head==:call || # inner constructor
l.args[1].head==:where && l.args[1].args[1].head==:call) # inner constructor with `where`
check_inner_constructor(l)
push!(inner_constructors, l)
else
fld = l.args[1]
if fld isa Symbol && has_deftyp # no type annotation
fld = :($fld::$deftyp)
end
# add field doc-strings
docstring = string("Default: ", l.args[2])
if i > 1 && lns[i-1] isa String
# if the last line was a docstring, append the default
fielddefs.args[end] *= " " * docstring
else
# otherwise add a new line
push!(fielddefs.args, docstring)
end
push!(fielddefs.args, fld)
kws[decolon2(fld)] = l.args[2]
# unwrap-macro
push!(unpack_vars, decolon2(fld))
end
elseif l.head==:macrocall && l.args[1]==Symbol("@assert")
# store all asserts
push!(asserts, l)
elseif l.head==:function # inner constructor
check_inner_constructor(l)
push!(inner_constructors, l)
elseif l.head==:block
error("No nested begin-end allowed in type defintion")
else # no default value but with type annotation
push!(fielddefs.args, l)
sym = decolon2(l.args[1])
syms = string(sym)
kws[sym] = :(error($err1str *$syms * $err2str))
# unwrap-macro
push!(unpack_vars, l.args[1])
end
end
# The type definition without inner constructors:
typ = Expr(:struct, typedef.args[1:2]..., copy(fielddefs))
# Inner keyword constructor. Note that this calls the positional
# constructor under the hood and not `new`. That way a user can
# provide a special positional constructor (say enforcing
# invariants) which also gets used with the keywords.
args = Any[]
kwargs = Expr(:parameters)
for (k,w) in kws
push!(args, k)
push!(kwargs.args, Expr(:kw,k,w))
end
if allow_default
if length(typparas)>0
tps = stripsubtypes(typparas)
innerc = :( $tn{$(tps...)}($kwargs) where {$(tps...)} = $tn{$(tps...)}($(args...)))
else
innerc = :($tn($kwargs) = $tn($(args...)) )
end
else
if length(typparas)>0
tps = stripsubtypes(typparas)
innerc = :( $tn{$(tps...)}($kwargs) where {$(tps...)} = $tn{$(tps...)}(Parameters.__Private(), $(args...)))
else
innerc = :($tn($kwargs) = $tn(Parameters.__Private(), $(args...)) )
end
end
push!(typ.args[3].args, innerc)
# Inner positional constructor: only make it if no inner
# constructors are user-defined. If one or several are defined,
# assume that one has the standard positional signature.
if length(inner_constructors)==0 || !allow_default
if allow_default
if length(typparas)>0
tps = stripsubtypes(typparas)
innerc2 = :( $tn{$(tps...)}($(args...)) where {$(tps...)} = new{$(tps...)}($(args...)) )
else
innerc2 = :($tn($(args...)) = new($(args...)))
end
else
if length(typparas)>0
tps = stripsubtypes(typparas)
innerc2 = :( $tn{$(tps...)}(::Parameters.__Private, $(args...)) where {$(tps...)} = new{$(tps...)}($(args...)) )
else
innerc2 = :($tn(::Parameters.__Private, $(args...)) = new($(args...)))
end
end
prepend!(innerc2.args[2].args, asserts)
push!(typ.args[3].args, innerc2)
else
if length(asserts)>0
error("Assertions are only allowed in type-definitions with no inner constructors.")
end
append!(typ.args[3].args, inner_constructors)
end
# Outer positional constructor which does not need explicit
# type-parameters when called. Only make this constructor if
# (1) type parameters are used at all
# (2) all type parameters are used in the fields (otherwise get a
# "method is not callable" warning!)
# See also https://github.com/JuliaLang/julia/issues/17186
if typparas!=Any[] # condition (1)
# fields definitions stripped of ::Int etc., only keep ::T if Tβtypparas :
fielddef_strip_contT = keep_only_typparas(fielddefs.args, typparas)
if allow_default
outer_positional = :( $tn($(fielddef_strip_contT...)) where {$(typparas...)}
= $tn{$(stripsubtypes(typparas)...)}($(args...)))
else
outer_positional = :( $tn(private::Parameters.__Private, $(fielddef_strip_contT...)) where {$(typparas...)}
= $tn{$(stripsubtypes(typparas)...)}(private, $(args...)))
end
# Check condition (2)
checks = true
for tp in stripsubtypes(typparas)
checks = checks && symbol_in(tp, fielddefs.args)
end
if !checks
outer_positional = :()
end
else
outer_positional = :()
end
# Outer keyword constructor, useful to infer the type parameter
# automatically. This calls the outer positional constructor.
# only create if type parameters are used.
if typparas==Any[]
outer_kw=:()
else
if allow_default
outer_kw = :($tn($kwargs) = $tn($(args...)) )
else
outer_kw = :($tn($kwargs) = $tn(Parameters.__Private(), $(args...)) )
end
end
# NOTE: The reason to have both outer and inner keyword
# constructors are to allow both calls:
# `MT4(r=4, a=5.0)` (outer kwarg-constructor) and
# `MT4{Float32, Int}(r=4, a=5.)` (inner kwarg constructor).
#
# NOTE to above NOTE: this is probably not the case (anymore?),
# as Base.@kwdef does not define inner constructors:
# julia> Base.@kwdef struct MT4_{R,I}
# r::R=5
# a::I
# end
#
# julia> MT4_(r=4, a=5.0)
# MT4_{Int64,Float64}(4, 5.0)
#
# julia> MT4_{Float32, Int}(r=4, a=5.)
# MT4_{Float32,Int64}(4.0f0, 5)
## outer copy constructor
###
outer_copy = quote
$tn(pp::$tn; kws... ) = $Parameters.reconstruct(pp, kws)
# $tn(pp::$tn, di::Union(AbstractDict,Vararg{Tuple{Symbol,Any}}) ) = reconstruct(pp, di) # see issue https://github.com/JuliaLang/julia/issues/11537
# $tn(pp::$tn, di::Union(AbstractDict, Tuple{Vararg{Tuple{Symbol, Any}}}) ) = reconstruct(pp, di) # see issue https://github.com/JuliaLang/julia/issues/11537
$tn(pp::$tn, di::$Parameters.AbstractDict) = $Parameters.reconstruct(pp, di)
$tn(pp::$tn, di::Vararg{Tuple{Symbol,Any}} ) = $Parameters.reconstruct(pp, di)
end
# (un)pack macro from https://groups.google.com/d/msg/julia-users/IQS2mT1ITwU/hDtlV7K1elsJ
unpack_name = Symbol("unpack_"*string(tn))
pack!_name = Symbol("pack_"*string(tn)*"!")
pack_name = Symbol("pack_"*string(tn))
showfn = if withshow
:(function Base.show(io::IO, p::$tn)
if get(io, :compact, false) || get(io, :typeinfo, nothing)==$tn
Base.show_default(IOContext(io, :limit => true), p)
else
# just dumping seems to give ok output, in particular for big data-sets:
dump(IOContext(io, :limit => true), p, maxdepth=1)
end
end)
else
:nothing
end
if ismutable
pack_macros = quote
macro $pack!_name(ex)
esc($Parameters._pack_mutable(ex, $unpack_vars))
end
macro $pack_name()
esc($Parameters._pack_new($tn, $unpack_vars))
end
end
else
pack_macros = quote
macro $pack_name()
esc($Parameters._pack_new($tn, $unpack_vars))
end
end
end
# Finish up
quote
Base.@__doc__ $typ
$outer_positional
$outer_kw
$outer_copy
$showfn
macro $unpack_name(ex)
esc($Parameters._unpack(ex, $unpack_vars))
end
$pack_macros
$tn
end
end
"""
Do the with-kw stuff for named tuples.
"""
function with_kw_nt(typedef, mod)
kwargs = []
args = []
nt = []
for a in typedef.args
if a isa Expr
a.head != :(=) && error("NameTuple fields need to be of form: `k=val`")
sy = a.args[1]::Symbol
va = a.args[2]
push!(kwargs, Expr(:kw, sy, va))
push!(args, sy)
push!(nt, :($sy=$sy))
elseif a isa Symbol # no default value given
sy = a
push!(args, sy)
push!(nt, :($sy=$sy))
push!(kwargs, Expr(:kw, sy, :(error("Supply default value for $($(string(sy)))"))))
else
error("Cannot parse $(string(a))")
end
end
NT = gensym(:NamedTuple_kw)
nt = Expr(:tuple, nt...)
quote
$NT(; $(kwargs...)) =$nt
$NT($(args...)) = $nt
$NT
end
end
"""
Macro which allows default values for field types and a few other features.
Basic usage:
```julia
@with_kw struct MM{R}
r::R = 1000.
a::Int = 4
end
```
For more details see manual.
"""
macro with_kw(typedef)
return esc(with_kw(typedef, __module__, true))
end
macro with_kw(args...)
error("""Only works on type-defs or named tuples.
Did you try to construct a NamedTuple but omitted the space between the macro and the NamedTuple?
Do `@with_kw (a=1, b=2)` and not `@with_kw(a=1, b=2)`.
""")
end
"""
As `@with_kw` but does not declare a default constructor when no inner
constructor is found.
"""
macro kw_only(typedef)
return esc(with_kw(typedef, __module__, true, false))
end
"""
As `@with_kw` but does not define a `show` method to avoid annoying
redefinition warnings.
```julia
@with_kw_noshow struct MM{R}
r::R = 1000.
a::Int = 4
end
```
For more details see manual.
"""
macro with_kw_noshow(typedef)
return esc(with_kw(typedef, __module__, false))
end
###########
# @consts macro
"""
"""
macro consts(block)
@assert block.head == :block
args = block.args
for i in eachindex(args)
a = args[i]
if a isa LineNumberNode
continue
elseif a.head == :(=)
args[i] = Expr(:const, args[i])
else
error("Could not parse block")
end
end
return esc(block)
end
end # module | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 149 | using Aqua
using PsychometricsBazaarBase
Aqua.test_all(PsychometricsBazaarBase, ambiguities=false)
Aqua.test_ambiguities([PsychometricsBazaarBase])
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 205 | using XUnit
@testset runner=ParallelTestRunner() xml_report=true "top" begin
@testset "aqua" begin
include("./aqua.jl")
end
@testset "smoke" begin
include("./smoke.jl")
end
end
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | code | 276 | using PsychometricsBazaarBase.Integrators
using PsychometricsBazaarBase.Optimizers
using Optim
const things = [
OneDimOptimOptimizer(-6.0, 6.0, NelderMead()),
QuadGKIntegrator(-6, 6, 5),
FixedGKIntegrator(-6, 6, 80),
]
for thing in things
thing(x -> x)
end
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | docs | 387 | ## PsychometricsBazaarBase.jl
This module provides a base for the libraries in the JuliaPsychometricsBazaar
org. It contains abstractions over basic mathematical techniques such as
numerical integration, optimization and interpolation.
Ideally, the package will be transitional, since functionality may make its way
into more specific packages (including existing packages) over time.
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | docs | 132 | # ConfigTools
```@autodocs
Modules = [PsychometricsBazaarBase.ConfigTools]
```
## Index
```@index
Pages = ["config_tools.md"]
``` | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | docs | 154 | # ConstDistributions
```@autodocs
Modules = [PsychometricsBazaarBase.ConstDistributions]
```
## Index
```@index
Pages = ["const_distributions.md"]
```
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | docs | 669 | # PsychometricsBazaarBase.jl
This module provides a base for the libraries in the JuliaPsychometricsBazaar
org. It contains abstractions over basic mathematical techniques such as
numerical integration, optimization and interpolation.
Ideally, the package will be transitional, since functionality may make its way
into more specific packages (including existing packages) over time.
```@meta
CurrentModule = PsychometricsBazaarBase
```
```@autodocs
Modules = [PsychometricsBazaarBase]
```
## Contents
```@contents
Pages = ["integrators.md", "optimizers.md", "config_tools.md", "integral_coeffs.md", "const_distributions.md"]
Depth = 1
```
## Index
```@index
```
| PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | docs | 141 | # IntegralCoeffs
```@autodocs
Modules = [PsychometricsBazaarBase.IntegralCoeffs]
```
## Index
```@index
Pages = ["integral_coeffs.md"]
``` | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | docs | 131 | # Integrators
```@autodocs
Modules = [PsychometricsBazaarBase.Integrators]
```
## Index
```@index
Pages = ["integrators.md"]
``` | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.7.1 | 87584893ede30d7fd400a225c58b97bb9e43a00e | docs | 128 | # Optimizers
```@autodocs
Modules = [PsychometricsBazaarBase.Optimizers]
```
## Index
```@index
Pages = ["optimizers.md"]
``` | PsychometricsBazaarBase | https://github.com/JuliaPsychometricsBazaar/PsychometricsBazaarBase.jl.git |
|
[
"MIT"
] | 0.1.0 | 1307f039f3837b97d26fdfb1979ea75acb9b057f | code | 4834 | module DICOMTree
import Term.Trees: Tree, TreeCharSet, print_node, print_key, Theme, TERM_THEME, _TREE_PRINTING_TITLE
import Term.Style: apply_style
using DICOM
export Tree
function apply_style(text::AbstractString, style::String)
text = convert(String, text)
apply_style(text, style)
end
function get_name_from_tag(gelt::Tuple{UInt16,UInt16})
if gelt[1] & 0xff00 == 0x5000
gelt = (0x5000, gelt[2])
elseif gelt[1] & 0xff00 == 0x6000
gelt = (0x6000, gelt[2])
end
r = get(DICOM.dcm_dict, gelt, DICOM.empty_vr_lookup)
(r[1] == "") ? (return gelt) : (return r[1])
end
"""
Tree(
tree;
with_keys::Bool = false,
guides::Union{TreeCharSet,Symbol} = :standardtree,
theme::Theme = TERM_THEME[],
printkeys::Union{Nothing,Bool} = true,
print_node_function::Function = print_node,
print_key_function::Function = print_key,
title::Union{String, Nothing}=nothing,
prefix::String = " ",
kwargs...,
)
Constructor for `Tree`
It uses `AbstractTrees.print_tree` to get a string representation of `tree` (any object
compatible with the `AbstractTrees` packge). Applies style to the string and creates a
renderable `Tree`.
Arguments:
- `tree`: anything compatible with `AbstractTree`
- 'with_keys': if `true` print DICOM keys (e.g. : (0x0010, 0x0020)). If `false`, print DICOM tags( e.g. : PatientID).
- `guides`: if a symbol, the name of preset tree guides types. Otherwise an instance of
`AbstractTrees.TreeCharSet`
- `theme`: `Theme` used to set tree style.
- `printkeys`: If `true` print keys. If `false` don't print keys.
- `print_node_function`: Function used to print nodes.
- `print_key_function`: Function used to print keys.
- `title`: Title of the tree.
- `prefix`: Prefix to be used in `AbstractTrees.print_tree`
For other kwargs look at `AbstractTrees.print_tree`
"""
function Tree(
dicom::DICOM.DICOMData;
with_keys::Bool=false,
guides::Union{TreeCharSet,Symbol}=:standardtree,
theme::Theme=Theme(tree_max_leaf_width=displaysize(stdout)[2]),
printkeys::Union{Nothing,Bool}=true,
print_node_function::Function=print_node,
print_key_function::Function=print_key,
title::Union{String,Nothing}="",
prefix::String=" ",
kwargs...
)
_TREE_PRINTING_TITLE[] = title
_theme = TERM_THEME[]
TERM_THEME[] = theme
md = haskey(kwargs, :maxdepth) ? kwargs[:maxdepth] : 2
format(x, md) = x
function format(x::AbstractArray, md)::Tree
return (Tree(Dict("Size" => string(size(x)), "Type" => typeof(x)),
with_keys=with_keys,
guides=guides,
title="Array",
maxdepth=md))
end
function format(x::Vector, md)::Tree
if length(x) <= 6
return Tree(string(x), with_keys=with_keys, guides=guides)
else
return Tree(Dict("Length" => length(x),
"ElementsType" => eltype(x),
"Overview" => string(x[begin:begin+2])[1:end-1] * ", ..., " * string(x[end-3:end-1])[2:end]), guides=guides, title="Vector", maxdepth=md)
end
end
function format(x::DICOM.DICOMData, md)::Tree
return Tree(x.meta, with_keys=with_keys, guides=guides, title="", maxdepth=md)
end
function format(x::Vector{DICOM.DICOMData}, md)::Tree
if md >= 2
return Tree(Tree.(x, with_keys=with_keys, guides=guides, title="", maxdepth=md), with_keys=with_keys, guides=guides, title="", maxdepth=md)
else
return Tree(Dict("Length" => length(keys(x))), with_keys=with_keys, guides=guides, title="Vector of DICOMData", maxdepth=md)
end
end
tree = Dict()
if with_keys
for symbol in keys(dicom.meta)
tree[symbol] = format(dicom[symbol], md - 1)
end
else
for symbol in get_name_from_tag.(keys(dicom.meta))
tree[symbol] = format(dicom[symbol], md - 1)
end
end
if haskey(tree, :PatientID)
title = string(tree[:PatientID])
else
title = ""
end
return Tree(tree, with_keys=with_keys, guides=guides, title=title, maxdepth=md - 1)
end
function Tree(
dicom_vector::Vector{DICOM.DICOMData};
with_keys::Bool=false,
guides::Union{TreeCharSet,Symbol}=:standardtree,
theme::Theme=Theme(tree_max_leaf_width=displaysize(stdout)[2]),
printkeys::Union{Nothing,Bool}=true,
print_node_function::Function=print_node,
print_key_function::Function=print_key,
title::Union{String,Nothing}="",
prefix::String=" ",
kwargs...
)
md = haskey(kwargs, :maxdepth) ? kwargs[:maxdepth] : 2
return Tree(Tree.(dicom_vector, with_keys=with_keys, guides=guides, title="", maxdepth=md), with_keys=with_keys, guides=guides, title="", maxdepth=md)
end
end
| DICOMTree | https://github.com/fdekerme/DICOMTree.jl.git |
|
[
"MIT"
] | 0.1.0 | 1307f039f3837b97d26fdfb1979ea75acb9b057f | code | 91 | using DICOMTree
using Test
@testset "DICOMTree.jl" begin
# Write your tests here.
end
| DICOMTree | https://github.com/fdekerme/DICOMTree.jl.git |
|
[
"MIT"
] | 0.1.0 | 1307f039f3837b97d26fdfb1979ea75acb9b057f | docs | 4633 | # DICOMTree
A little Julia package for visualizing DICOM file metadata in the form of a tree. The main function is the Tree function, which is simply a dispatch of the eponymous function in the Term.jl package to the DICOMData type in the DICOM.jl package.
The package have been tested with CT Scanner, RTDose and RTStruct files.
## Documentation & installation
Install with:
```
julia> ] # enters the pkg interface
pkg> add DICOMTree
```
## How to use DICOMTree.jl ?
```julia
using DICOM
using DICOMTree
dcm_file = dcm_parse(dcm_path)
Tree(dcm_file, with_keys::Bool=false, maxdepth = 2)
```
Output (with colours in the REPL) :
```
PatientID
ββ StructureSetName β ART: Unapproved
ββ StudyDate β 20180802
ββ StructureSetROISequence β Vector of DICOMData
β ββ Length β 46
β
ββ SeriesInstanceUID β 1.2.276
ββ MediaStorageSOPClassUID β 1.2.840
ββ SoftwareVersions β v1.0
ββ ImplementationVersionName β OFFIS_DCMTK_364
ββ Modality β RTSTRUCT
ββ PatientName β xxx
ββ OperatorsName β xxx
ββ ApprovalStatus β UNAPPROVED
ββ InstitutionName β Any[]
β
ββ ReferencedFrameOfReferenceSequence β Vector of DICOMData
β ββ Length β 1
β
ββ SOPInstanceUID β 1.2.276
ββ SpecificCharacterSet β ISO_IR 100
ββ PatientID β xxx
ββ ImplementationClassUID β 1.2.276
ββ StudyTime β xxx
ββ StructureSetTime β 123456
ββ StudyDescription β Brain
ββ ROIContourSequence β Vector of DICOMData
β ββ Length β 46
β
ββ ReviewTime β Any[]
β
ββ StudyID β 123456
ββ SeriesNumber β 1
ββ SOPClassUID β 1.2.840
ββ StudyInstanceUID β 1.2.826
ββ TransferSyntaxUID β 1.2.840
ββ AccessionNumber β Any[]
β
ββ StructureSetDate β 12345678
ββ ManufacturerModelName β xxx
ββ PatientSex β Any[]
β
ββ InstanceNumber β 1
ββ FileMetaInformationGroupLength β 202
ββ ReferringPhysicianName β Unspecified
ββ Manufacturer β TheraPanacea
ββ ReviewDate β Any[]
β
ββ InstanceCreationTime β 123456
ββ FileMetaInformationVersion β UInt8[0x00, 0x01]
β
ββ RTROIObservationsSequence β Vector of DICOMData
β ββ Length β 46
β
ββ MediaStorageSOPInstanceUID β 1.2.276
ββ StructureSetLabel β ART: Unapproved
ββ SeriesDescription β xxx
ββ PatientBirthDate β 12345678
ββ InstanceCreationDate β 12345678
```
- `with_keys = true` will replace the name with the associated tag (e.g. : (0x0010, 0x0020) if true and PatientID if false). Default is false.
- `maxdepth` defines the depth at which the DICOM tree is explored. Default is 2. Note that a high scan depth may take a few seconds to be displayed.
Then, we can focus on a specifi tag :
```Julia
Tree(rs.ROIContourSequence, maxdepth = 3)
```
Output (with colours in the REPL) :
```
ββ 1 β
ββ ContourSequence β
β ββ 1 β
β β ββ ContourGeometricType β CLOSED_PLANAR
β β ββ ContourData β Vector
β β β ββ Length β 3948
β β β ββ ElementsType β Float64
β β β ββ Overview β [5.12, -245.33, -124.0, ..., -124.0, 4.4, -245.2]
β β β
β β ββ ContourNumber β 0
β β ββ NumberOfContourPoints β 1316
β β ββ ContourImageSequence β Vector of DICOMData
β β ββ Length β 1
β β
β β
β ββ 2 β
β β ββ ContourGeometricType β CLOSED_PLANAR
β β ββ ContourData β Vector
β β β ββ Length β 3936
β β β ββ ElementsType β Float64
β β β ββ Overview β [12.78, -245.33, -122.0, ..., -122.0, 12.06, -245.2]
β β β
β β ββ ContourNumber β 1
β β ββ NumberOfContourPoints β 1312
β β ββ ContourImageSequence β Vector of DICOMData
β β ββ Length β 1
...
``` | DICOMTree | https://github.com/fdekerme/DICOMTree.jl.git |
|
[
"MIT"
] | 1.0.0 | 5d44a4f56f7902c4414c0a477b021f17cf088cb3 | code | 723 | using Documenter, SkewLinearAlgebra, LinearAlgebra
using .DocMeta: setdocmeta!
setdocmeta!(SkewLinearAlgebra, :DocTestSetup, :(using SkewLinearAlgebra, LinearAlgebra);
recursive=true)
makedocs(
modules = [SkewLinearAlgebra],
clean = false,
sitename = "SkewLinearAlgebra Documentation",
authors = "Simon Mataigne, Steven G. Johnson, and contributors.",
pages = [
"Home" => "index.md",
"Matrix Types" => "types.md",
"Eigenproblems" => "eigen.md",
"Exponential/Trigonometric functions" => "trig.md",
"Pfaffians" => "pfaffian.md",
"Skew-Cholesky" => "skewchol.md",
],
)
deploydocs(repo="github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl")
| SkewLinearAlgebra | https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git |
|
[
"MIT"
] | 1.0.0 | 5d44a4f56f7902c4414c0a477b021f17cf088cb3 | code | 785 | # This file is a part of Julia. License is MIT: https://julialang.org/license
"""
This module based on the LinearAlgebra module provides specialized functions
and types for skew-symmetricmatrices, i.e A=-A^T
"""
module SkewLinearAlgebra
using LinearAlgebra
import LinearAlgebra as LA
export
#Types
SkewHermitian,
SkewHermTridiagonal,
SkewCholesky,
JMatrix,
#functions
isskewhermitian,
isskewsymmetric,
skewhermitian,
skewhermitian!,
pfaffian,
pfaffian!,
logabspfaffian,
logabspfaffian!,
skewchol,
skewchol!
include("skewhermitian.jl")
include("tridiag.jl")
include("jmatrix.jl")
include("hessenberg.jl")
include("skeweigen.jl")
include("eigen.jl")
include("exp.jl")
include("cholesky.jl")
include("pfaffian.jl")
end
| SkewLinearAlgebra | https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git |
|
[
"MIT"
] | 1.0.0 | 5d44a4f56f7902c4414c0a477b021f17cf088cb3 | code | 3577 | # This file is a part of Julia. License is MIT: https://julialang.org/license
struct SkewCholesky{T,R<:UpperTriangular{<:T},J<:JMatrix{<:T},P<:AbstractVector{<:Integer}}
R::R #Uppertriangular matrix
J::J # Block diagonal skew-symmetric matrix of type JMatrix
p::P #Permutation vector
function SkewCholesky{T,R,J,P}(Rm,Jm,pv) where {T,R,J,P}
LA.require_one_based_indexing(Rm)
new{T,R,J,P}(Rm,Jm,pv)
end
end
"""
SkewCholesky(R,p)
Construct a `SkewCholesky` structure from the `UpperTriangular`
matrix `R` and the permutation vector `p`. A matrix `J` of type `JMatrix`
is build calling this function.
The `SkewCholesky` structure has three arguments: `R`,`J` and `p`.
"""
function SkewCholesky(R::UpperTriangular{<:T},p::AbstractVector{<:Integer}) where {T<:Real}
n = size(R, 1)
return SkewCholesky{T,typeof(R),JMatrix{T,+1},typeof(p)}(R, JMatrix{T,+1}(n), p)
end
function _skewchol!(A::SkewHermitian{<:Real})
@views B = A.data
tol = 1e-15 * norm(B)
m = size(B,1)
m == 1 && return [1]
J2 = similar(B,2,2)
J2[1,1] = 0; J2[2,1] = -1; J2[1,2] = 1; J2[2,2] = 0
ii = 0; jj = 0; kk = 0
P = Array(1:m)
tempM = similar(B,2,m-2)
for j = 1:mΓ·2
j2 = 2*j
M = findmax(B[j2-1:m,j2-1:m])
ii = M[2][1] + j2 - 2
jj = M[2][2] + j2 - 2
abs(B[ii,jj])<tol && return P
kk= (jj == j2-1 ? ii : jj)
if ii != j2-1
P[ii],P[j2-1] = P[j2-1],P[ii]
for t = 1:m
B[t,ii], B[t,j2-1] = B[t,j2-1], B[t,ii]
end
for t = 1:m
B[ii,t], B[j2-1,t] = B[j2-1,t], B[ii,t]
end
end
if kk != j2
P[kk],P[j2] = P[j2],P[kk]
for t = 1:m
B[t,kk], B[t,j2] = B[t,j2], B[t,kk]
end
for t = 1:m
B[kk,t], B[j2,t] = B[j2,t], B[kk,t]
end
end
l = m-j2
r = sqrt(B[j2-1,j2])
B[j2-1,j2-1] = r
B[j2,j2] = r
B[j2-1,j2] = 0
@views mul!(tempM[:,1:l], J2, B[j2-1:j2,j2+1:m])
B[j2-1:j2,j2+1:m] .= tempM[:,1:l]
B[j2-1:j2,j2+1:m] .*= (-1/r)
@views mul!(tempM[:,1:l], J2, B[j2-1:j2,j2+1:m])
@views mul!(B[j2+1:m,j2+1:m], transpose(B[j2-1:j2,j2+1:m]), tempM[:,1:l],-1,1)
end
return P
end
copyeigtype(A::AbstractMatrix) = copyto!(similar(A, LA.eigtype(eltype(A))), A)
@views function skewchol!(A::SkewHermitian)
P = _skewchol!(A)
return SkewCholesky(UpperTriangular(A.data), P)
end
skewchol(A::SkewHermitian) = skewchol!(copyeigtype(A))
"""
skewchol!(A)
Similar to [`skewchol!`](@ref), but overwrites `A` in-place with intermediate calculations.
"""
skewchol!(A::AbstractMatrix) = @views skewchol!(SkewHermitian(A))
"""
skewchol(A)
Computes a Cholesky-like factorization of the real skew-symmetric matrix `A`.
The function returns a `SkewCholesky` structure composed of three fields:
`R`,`J`,`p`. `R` is `UpperTriangular`, `J` is a `JMatrix`,
`p` is an array of integers. Let `S` be the returned structure, then the factorization
is such that `S.R'*S.J*S.R = A[S.p,S.p]`
This factorization (and the underlying algorithm) is described in from P. Benner et al,
"[Cholesky-like factorizations of skew-symmetric matrices](https://etna.ricam.oeaw.ac.at/vol.11.2000/pp85-93.dir/pp85-93.pdf)"(2000).
"""
function skewchol(A::AbstractMatrix)
isskewhermitian(A) || throw(ArgumentError("Pfaffian requires a skew-Hermitian matrix"))
return skewchol!(SkewHermitian(copyeigtype(A)))
end
| SkewLinearAlgebra | https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git |
|
[
"MIT"
] | 1.0.0 | 5d44a4f56f7902c4414c0a477b021f17cf088cb3 | code | 4447 | # Based on eigen.jl in Julia. License is MIT: https://julialang.org/license
@views function LA.eigvals!(A::SkewHermitian{<:Real}, sortby::Union{Function,Nothing}=nothing)
vals = imag.(skeweigvals!(A))
!isnothing(sortby) && sort!(vals, by = sortby)
return complex.(0, vals)
end
@views function LA.eigvals!(A::SkewHermitian{<:Real}, irange::UnitRange)
vals = skeweigvals!(A, irange)
return complex.(0, vals)
end
@views function LA.eigvals!(A::SkewHermitian{<:Real}, vl::Real,vh::Real)
vals = skeweigvals!(A, -vh, -vl)
return complex.(0, vals)
end
@views function LA.eigvals!(A::SkewHermitian{<:Complex}, sortby::Union{Function,Nothing}=nothing)
H = Hermitian(A.data.*1im)
if sortby === nothing
return complex.(0, - eigvals!(H))
end
vals = eigvals!(H, sortby)
reverse!(vals)
vals.= .-vals
return complex.(0, vals)
end
@views function LA.eigvals!(A::SkewHermitian{<:Complex}, irange::UnitRange)
H = Hermitian(A.data.*1im)
vals = eigvals!(H,-irange)
vals .= .-vals
return complex.(0, vals)
end
@views function LA.eigvals!(A::SkewHermitian{<:Complex}, vl::Real,vh::Real)
H = Hermitian(A.data.*1im)
vals = eigvals!(H,-vh,-vl)
vals .= .-vals
return complex.(0, vals)
end
LA.eigvals(A::SkewHermitian, sortby::Union{Function,Nothing}) = eigvals!(copyeigtype(A), sortby)
LA.eigvals(A::SkewHermitian, irange::UnitRange) = eigvals!(copyeigtype(A), irange)
LA.eigvals(A::SkewHermitian, vl::Real,vh::Real) = eigvals!(copyeigtype(A), vl,vh)
# no need to define LA.eigen(...) since the generic methods should work
@views function skeweigvals!(S::SkewHermitian{<:Real})
n = size(S.data, 1)
n == 1 && return [S.data[1,1]]
E = skewblockedhess!(S)[2]
H = SkewHermTridiagonal(E)
return skewtrieigvals!(H)
end
@views function skeweigvals!(S::SkewHermitian{<:Real},irange::UnitRange)
n = size(S.data,1)
n == 1 && return [S.data[1,1]]
E = skewblockedhess!(S)[2]
H = SymTridiagonal(zeros(eltype(E), n), E)
vals = eigvals!(H,irange)
return vals .= .-vals
end
@views function skeweigvals!(S::SkewHermitian{<:Real},vl::Real,vh::Real)
n = size(S.data,1)
n == 1 && imag(S.data[1,1]) > vl && imag(S.data[1,1]) < vh && return [S.data[1,1]]
E = skewblockedhess!(S)[2]
H = SymTridiagonal(zeros(eltype(E), n), E)
vals = eigvals!(H,vl,vh)
return vals .= .-vals
end
@views function skeweigen!(S::SkewHermitian{T}) where {T<:Real}
n = size(S.data, 1)
if n == 1
return [S.data[1,1]], ones(T,1,1), zeros(T,1,1)
end
tau, E = skewblockedhess!(S)
Tr = SkewHermTridiagonal(E)
H1 = Hessenberg{typeof(zero(eltype(S.data))),typeof(Tr),typeof(S.data),typeof(tau),typeof(false)}(Tr, 'L', S.data, tau, false)
vectorsreal = similar(S, T, n, n)
vectorsim = similar(S, T, n, n)
Q = Matrix(H1.Q)
vals, Qr, Qim = skewtrieigen_divided!(Tr)
mul!(vectorsreal, Q, Qr)
mul!(vectorsim, Q, Qim)
return vals, vectorsreal, vectorsim
end
@views function LA.eigen!(A::SkewHermitian{<:Real})
vals, Qr, Qim = skeweigen!(A)
return Eigen(vals,complex.(Qr, Qim))
end
copyeigtype(A::SkewHermitian) = copyto!(similar(A, LA.eigtype(eltype(A))), A)
@views function LA.eigen!(A::SkewHermitian{T}) where {T<:Complex}
H = Hermitian(A.data.*1im)
Eig = eigen!(H)
skew_Eig = Eigen(complex.(0,-Eig.values), Eig.vectors)
return skew_Eig
end
LA.eigen(A::SkewHermitian) = LA.eigen!(copyeigtype(A))
@views function LA.svdvals!(A::SkewHermitian{<:Real})
vals = imag.(skeweigvals!(A))
vals .= abs.(vals)
return sort!(vals; rev = true)
end
LA.svdvals!(A::SkewHermitian{<:Complex}) = svdvals!(Hermitian(A.data.*1im))
LA.svdvals(A::SkewHermitian) = svdvals!(copyeigtype(A))
@views function LA.svd!(A::SkewHermitian{<:Real})
n = size(A, 1)
E = eigen!(A)
U = E.vectors
vals = imag.(E.values)
I = sortperm(vals; by = abs, rev = true)
permute!(vals, I)
Base.permutecols!!(U, I)
V = U .* -1im
@inbounds for i=1:n
if vals[i] < 0
vals[i]=-vals[i]
@simd for j=1:n
V[j,i]=-V[j,i]
end
end
end
return LA.SVD(U, vals, adjoint(V))
end
@views function LA.svd(A::SkewHermitian{T}) where {T<:Complex}
H = Hermitian(A.data.*1im)
Svd = svd(H)
return SVD(Svd.U , Svd.S, (Svd.Vt).*(-1im))
end
LA.svd(A::SkewHermitian{<:Real}) = svd!(copyeigtype(A))
| SkewLinearAlgebra | https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git |
|
[
"MIT"
] | 1.0.0 | 5d44a4f56f7902c4414c0a477b021f17cf088cb3 | code | 8404 | # This file is a part of Julia. License is MIT: https://julialang.org/license
function skewexp!(A::Union{SkewHermitian{T},SkewHermTridiagonal{T}}) where {T<:Real}
n = size(A, 1)
if typeof(A) <:SkewHermitian
vals, Qr, Qim = skeweigen!(A)
else
E = eigen!(A)
vals = E.values
Qr = real(E.vectors)
Qim = imag(E.vectors)
end
temp2 = similar(A, n, n)
Q1 = similar(A, n, n)
Q2 = similar(A, n, n)
Cos = similar(A, n)
Sin = similar(A, n)
@simd for i = 1 : n
@inbounds Sin[i], Cos[i] = sincos(imag(vals[i]))
end
C = Diagonal(Cos)
S = Diagonal(Sin)
mul!(Q1, Qr, C)
mul!(Q2, Qim, S)
Q1 .-= Q2
mul!(temp2, Q1, transpose(Qr))
mul!(Q1, Qr, S)
mul!(Q2, Qim, C)
Q1 .+= Q2
mul!(Q2, Q1, transpose(Qim))
temp2 .+= Q2
return temp2
end
@views function skewexp!(A::Union{SkewHermitian{<:Complex},SkewHermTridiagonal{<:Complex}})
n = size(A, 1)
Eig = eigen!(A)
eig = exp.(Eig.values)
temp = similar(A, n, n)
Exp = similar(A, n, n)
mul!(temp, Diagonal(eig), Eig.vectors')
mul!(Exp,Eig.vectors,temp)
return Exp
end
Base.exp(A::Union{SkewHermitian,SkewHermTridiagonal}) = skewexp!(copyeigtype(A))
function skewlog!(A::Union{SkewHermitian{T},SkewHermTridiagonal{T}}) where {T<:Real}
n = size(A, 1)
isodd(n) && throw(DomainError("Logarithm of a singular matrix doesn't exist"))
if typeof(A) <:SkewHermitian
vals, Qr, Qim = skeweigen!(A)
else
E = eigen!(A)
vals = E.values
Qr = real(E.vectors)
Qim = imag(E.vectors)
end
temp2 = similar(A, n, n)
Q1 = similar(A, n, n)
Q2 = similar(A, n, n)
r = similar(A, n)
ΞΈ = similar(A, n)
@simd for i = 1 : n
iszero(vals[i]) && throw(DomainError("Logarithm of a singular matrix doesn't exist"))
@inbounds r[i], ΞΈ[i] = log(abs(vals[i])), sign(imag(vals[i])) * Ο / 2
end
R = Diagonal(r)
Ξ = Diagonal(ΞΈ)
mul!(Q1, Qr, R)
mul!(Q2, Qim, Ξ )
Q1 .-= Q2
mul!(temp2, Q1, transpose(Qr))
mul!(Q1, Qr, Ξ)
mul!(Q2, Qim, R)
Q1 .+= Q2
mul!(Q2, Q1, transpose(Qim))
temp2 .+= Q2
return temp2
end
@views function skewlog!(A::Union{SkewHermitian{<:Complex},SkewHermTridiagonal{<:Complex}})
n = size(A, 1)
Eig = eigen!(A)
eig = log.(Eig.values)
temp = similar(A, n, n)
Exp = similar(A, n, n)
mul!(temp, Diagonal(eig), Eig.vectors')
mul!(Exp,Eig.vectors,temp)
return Exp
end
Base.log(A::Union{SkewHermitian,SkewHermTridiagonal}) = skewlog!(copyeigtype(A))
@views function skewcis!(A::Union{SkewHermitian{T},SkewHermTridiagonal{T}}) where {T<:Real}
n = size(A, 1)
Eig = eigen!(A)
Q = Eig.vectors
temp = similar(Q, n, n)
temp2 = similar(Q, n, n)
eig = @. exp(-imag(Eig.values))
E = Diagonal(eig)
mul!(temp, Q, E)
mul!(temp2, temp, adjoint(Q))
return Hermitian(temp2)
end
@views function skewcis!(A::Union{SkewHermitian{<:Complex},SkewHermTridiagonal{<:Complex}})
n = size(A,1)
Eig = eigen!(A)
eig = @. exp(-imag(Eig.values))
Cis = similar(A, n, n)
temp = similar(A, n, n)
mul!(temp, Eig.vectors, Diagonal(eig))
mul!(Cis, temp, Eig.vectors')
return Hermitian(Cis)
end
@views function skewcos!(A::Union{SkewHermitian{T},SkewHermTridiagonal{T}}) where {T<:Real}
n = size(A,1)
if typeof(A) <:SkewHermitian
vals, Qr, Qim = skeweigen!(A)
else
E = eigen!(A)
vals = E.values
Qr = real(E.vectors)
Qim = imag(E.vectors)
end
temp2 = similar(A, n, n)
Q1 = similar(A, n, n)
Q2 = similar(A, n, n)
eig = @. exp(-imag(vals))
E = Diagonal(eig)
mul!(Q1, Qr, E)
mul!(Q2, Qim, E)
mul!(temp2, Q1, transpose(Qr))
mul!(Q1, Q2, transpose(Qim))
Q1 .+= temp2
return Hermitian(Q1)
end
@views function skewcos!(A::Union{SkewHermitian{<:Complex},SkewHermTridiagonal{<:Complex}})
n = size(A,1)
Eig = eigen!(A)
eig1 = @. exp(-imag(Eig.values))
eig2 = @. exp(imag(Eig.values))
Cos = similar(A, n, n)
temp = similar(A, n, n)
temp2 = similar(A, n, n)
mul!(temp, Eig.vectors, Diagonal(eig1))
mul!(temp2, temp, Eig.vectors')
mul!(temp, Eig.vectors, Diagonal(eig2))
mul!(Cos, temp, Eig.vectors')
Cos .+= temp2
Cos ./= 2
return Hermitian(Cos)
end
@views function skewsin!(A::Union{SkewHermitian{T},SkewHermTridiagonal{T}}) where {T<:Real}
n = size(A, 1)
if typeof(A) <:SkewHermitian
vals, Qr, Qim = skeweigen!(A)
else
E = eigen!(A)
vals = E.values
Qr = real(E.vectors)
Qim = imag(E.vectors)
end
temp2 = similar(A, n, n)
Q1 = similar(A, n, n)
Q2 = similar(A, n, n)
eig = @. exp(-imag(vals))
E = Diagonal(eig)
mul!(Q1, Qr, E)
mul!(Q2, Qim, E)
mul!(temp2, Q1, transpose(Qim))
mul!(Q1, Q2, transpose(Qr))
Q1 .-= temp2
return skewhermitian!(Q1)
end
@views function skewsin!(A::Union{SkewHermitian{<:Complex},SkewHermTridiagonal{<:Complex}})
n = size(A,1)
Eig = eigen!(A)
eig1 = @. exp(-imag(Eig.values))
eig2 = @. exp(imag(Eig.values))
Sin = similar(A,n,n)
temp = similar(A,n,n)
temp2 = similar(A,n,n)
mul!(temp,Eig.vectors,Diagonal(eig1))
mul!(Sin,temp,Eig.vectors')
mul!(temp,Eig.vectors,Diagonal(eig2))
mul!(temp2,temp,Eig.vectors')
Sin .-= temp2
Sin ./= -2
Sin .*= 1im
return skewhermitian!(Sin)
end
Base.cis(A::Union{SkewHermitian,SkewHermTridiagonal}) = skewcis!(copyeigtype(A))
Base.cos(A::Union{SkewHermitian,SkewHermTridiagonal}) = skewcos!(copyeigtype(A))
Base.sin(A::Union{SkewHermitian,SkewHermTridiagonal}) = skewsin!(copyeigtype(A))
@views function skewsincos!(A::Union{SkewHermitian{T},SkewHermTridiagonal{T}}) where {T<:Real}
n = size(A,1)
if typeof(A) <:SkewHermitian
vals, Qr, Qim = skeweigen!(A)
else
E = eigen!(A)
vals = E.values
Qr = real(E.vectors)
Qim = imag(E.vectors)
end
temp2 = similar(A, n, n)
Cos = similar(A, n, n)
Sin = similar(A, n, n)
Q2 = similar(A, n, n)
eig = @. exp(-imag(vals))
E = Diagonal(eig)
mul!(Sin, Qr, E)
mul!(Q2, Qim, E)
mul!(temp2, Sin, transpose(Qr))
mul!(Cos, Q2, transpose(Qim))
Cos .+= temp2
mul!(temp2, Sin, transpose(Qim))
mul!(Sin, Q2, transpose(Qr))
Sin .-= temp2
return skewhermitian!(Sin), Hermitian(Cos)
end
@views function skewsincos!(A::Union{SkewHermitian{<:Complex},SkewHermTridiagonal{<:Complex}})
n = size(A, 1)
Eig = eigen!(A)
eig1 = @. exp(-imag(Eig.values))
eig2 = @. exp(imag(Eig.values))
Sin = similar(A, n, n)
Cos = similar(A, n, n)
temp = similar(A, n, n)
temp2 = similar(A, n, n)
mul!(temp, Eig.vectors, Diagonal(eig1))
mul!(Sin, temp, Eig.vectors')
mul!(temp, Eig.vectors, Diagonal(eig2))
mul!(temp2, temp, Eig.vectors')
Cos .= Sin
Cos .+= temp2
Cos ./= 2
Sin .-= temp2
Sin .*= -1im/2
return skewhermitian!(Sin), Hermitian(Cos)
end
Base.sincos(A::Union{SkewHermitian,SkewHermTridiagonal}) = skewsincos!(copyeigtype(A))
Base.sinh(A::Union{SkewHermitian,SkewHermTridiagonal}) = skewhermitian!(exp(A))
Base.cosh(A::Union{SkewHermitian{T},SkewHermTridiagonal{T}}) where {T<:Real} = hermitian!(exp(A))
function Base.cosh(A::Union{SkewHermitian{<:Complex},SkewHermTridiagonal{<:Complex}})
B = hermitian!(exp(A))
return Hermitian(complex.(real(B),-imag(B)))
end
function Base.tan(A::Union{SkewHermitian,SkewHermTridiagonal})
S, C = sincos(A)
return skewhermitian!(C \ S)
end
function Base.tanh(A::Union{SkewHermitian,SkewHermTridiagonal})
E = exp(2A)
return skewhermitian!((E+I)\(E-I))
end
function Base.cot(A::Union{SkewHermitian,SkewHermTridiagonal})
S, C = sincos(A)
return skewhermitian!(S \ C)
end
function Base.coth(A::Union{SkewHermitian,SkewHermTridiagonal})
E = exp(2A)
return skewhermitian!((E-I) \ (E+I))
end
# someday this should be in LinearAlgebra: https://github.com/JuliaLang/julia/pull/31836
function hermitian!(A::AbstractMatrix{<:Number})
LA.require_one_based_indexing(A)
n = LA.checksquare(A)
@inbounds for i in 1:n
A[i,i] = real(A[i,i])
for j = 1:i-1
A[i,j] = A[j,i] = (A[i,j] + A[j,i]')/2
end
end
return LA.Hermitian(A)
end | SkewLinearAlgebra | https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git |
|
[
"MIT"
] | 1.0.0 | 5d44a4f56f7902c4414c0a477b021f17cf088cb3 | code | 5204 | # This file is a part of Julia. License is MIT: https://julialang.org/license
LA.HessenbergQ(F::Hessenberg{<:Any,<:SkewHermTridiagonal,S,W}) where {S,W} = LA.HessenbergQ{eltype(F.factors),S,W,true}(F.uplo, F.factors, F.Ο)
@views function LA.hessenberg!(A::SkewHermitian{T}) where {T}
Ο, Ξ· = skewblockedhess!(A)
if T <: Complex
Tr=SkewHermTridiagonal(convert.(T, Ξ·), imag( diag(A.data)))
else
Tr=SkewHermTridiagonal(Ξ·)
end
return Hessenberg{typeof(zero(eltype(A.data))),typeof(Tr),typeof(A.data),typeof(Ο),typeof(false)}(Tr, 'L', A.data, Ο, false)
end
LA.hessenberg(A::SkewHermitian)=hessenberg!(copyeigtype(A))
"""
householder!(x,n)
Takes `x::AbstractVector{T}` and its size `n` as input.
Computes the associated householder reflector v overwitten in x.
The reflector matrix is H = I-Ο * v * v'.
Returns Ο as first output and Ξ² as second output where Ξ²
is the first element of the output vector of H*x.
"""
@views function householder!(x::AbstractVector{T},n::Integer) where {T}
if n == 1 && T <:Real
return T(0), real(x[1]) # no final 1x1 reflection for the real case
end
xnorm = norm(x[2:end])
Ξ± = x[1]
if !iszero(xnorm) || (!iszero(Ξ±))
Ξ² = (real(Ξ±) > 0 ? -1 : +1) * hypot(Ξ±,xnorm)
Ο = 1 - Ξ± / Ξ²
Ξ± = 1 / (Ξ± - Ξ²)
x[1] = 1
x[2:n] .*= Ξ±
else
Ο = T(0)
x .= 0
Ξ² = real(T)(0)
end
return Ο, Ξ²
end
@views function ger2!(Ο::Number , v::StridedVector{T} , s::StridedVector{T},
A::StridedMatrix{T}) where {T<:LA.BlasFloat}
Ο2 = promote(Ο, zero(T))[1]
if Ο2 isa Union{Bool,T}
return LA.BLAS.ger!(Ο2, v, s, A)
else
iszero(Ο2) && return
m = length(v)
n = length(s)
@inbounds for j = 1:n
temp = Ο2 * s[j]'
@simd for i=1:m
A[i,j] += v[i] * temp
end
end
end
end
@views function lefthouseholder!(A::AbstractMatrix,v::AbstractArray,s::AbstractArray,Ο::Number)
mul!(s, adjoint(A), v)
ger2!(-Ο', v, s, A)
return
end
@views function skewhess!(A::AbstractMatrix{T},Ο::AbstractVector,Ξ·::AbstractVector) where {T}
n = size(A, 1)
atmp = similar(A, n)
@inbounds (for i = 1:n-1
Ο_s, Ξ± = householder!(A[i+1:end,i], n - i)
@views v = A[i+1:end,i]
Ξ·[i] = Ξ±
lefthouseholder!(A[i+1:end,i+1:end], v, atmp[i+1:end], Ο_s)
s = mul!(atmp[i+1:end], A[i+1:end,i+1:end], v)
for j=i+1:n
A[j,j] -= Ο_s * s[j-i] * v[j-i]'
for k=j+1:n
A[k,j] -= Ο_s * s[k-i] * v[j-i]'
A[j,k] = -A[k,j]'
end
end
Ο[i] = Ο_s
end)
return
end
@views function skewlatrd!(A::AbstractMatrix{T},Ξ·::AbstractVector,W::AbstractMatrix,Ο::AbstractVector,tempconj::AbstractVector,n::Number,nb::Number) where {T}
@inbounds(for i=1:nb
if i>1
if T <: Complex
@simd for j = 1:i-1
tempconj[j] = conj(W[i,j])
end
mul!(A[i:n,i], A[i:n,1:i-1], tempconj[1:i-1], 1, 1)
@simd for j=1:i-1
tempconj[j] = conj(A[i,j])
end
mul!(A[i:n,i], W[i:n,1:i-1], tempconj[1:i-1], -1, 1)
else
mul!(A[i:n,i], A[i:n,1:i-1], W[i,1:i-1], 1, 1)
mul!(A[i:n,i], W[i:n,1:i-1], A[i,1:i-1], -1, 1)
end
end
#Generate elementary reflector H(i) to annihilate A(i+2:n,i)
Ο_s,Ξ± = householder!(A[i+1:n,i],n-i)
Ξ·[i] = Ξ±
mul!(W[i+1:n,i], A[i+1:n,i+1:n], A[i+1:n,i], 1, 0)
if i>1
mul!(W[1:i-1,i], adjoint(W[i+1:n,1:i-1]), A[i+1:n,i])
mul!(W[i+1:n,i], A[i+1:n,1:i-1], W[1:i-1,i], 1, 1)
mul!(W[1:i-1,i], adjoint(A[i+1:n,1:i-1]),A[i+1:n,i])
mul!(W[i+1:n,i], W[i+1:n,1:i-1], W[1:i-1,i], -1, 1)
end
W[i+1:n,i] .*= Ο_s
if T<:Complex
Ξ± = Ο_s * dot(W[i+1:n,i],A[i+1:n,i]) / 2
W[i+1:n,i] .+= Ξ±.*A[i+1:n,i]
end
Ο[i] = Ο_s
end)
return
end
function setnb(n::Integer)
if n<=12
return max(n-4,1)
elseif n<=100
return 10
else
return 60
end
return 1
end
@views function skewblockedhess!(S::SkewHermitian{T}) where {T}
n = size(S.data,1)
nb = setnb(n)
A = S.data
Ξ· = similar(A, real(T), n - 1)
Ο = similar(A, n - 1)
W = similar(A, n, nb)
Ξ© = similar(A, n - nb, n - nb)
tempconj = similar(A, nb)
oldi = 0
@inbounds(for i = 1:nb:n-nb-1
size = n-i+1
skewlatrd!(A[i:n,i:n], Ξ·[i:i+nb-1], W, Ο[i:i+nb-1], tempconj,size,nb)
mul!(Ξ©[1:n-nb-i+1,1:n-nb-i+1], A[i+nb:n,i:i+nb-1], adjoint(W[nb+1:size,:]))
s = i+nb-1
for k = 1:n-s
A[s+k,s+k] += Ξ©[k,k] - Ξ©[k,k]'
@simd for j = k+1:n-s
A[s+j,s+k] += Ξ©[j,k] - Ξ©[k,j]'
A[s+k,s+j] = - A[s+j,s+k]'
end
end
oldi = i
end)
oldi += nb
if oldi < n
skewhess!(A[oldi:n,oldi:n],Ο[oldi:end],Ξ·[oldi:end])
end
return Ο, Ξ·
end | SkewLinearAlgebra | https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git |
|
[
"MIT"
] | 1.0.0 | 5d44a4f56f7902c4414c0a477b021f17cf088cb3 | code | 3485 | """
JMatrix{T, Β±1}(n)
Creates an `AbstractMatrix{T}` of size `n x n`, representing a
block-diagonal matrix whose diagonal blocks are `Β±[0 1; -1 0]`.
If `n` is odd, then the last block is the `1 x 1` zero block.
The `Β±1` parameter allows us to transpose and invert the matrix,
and corresponds to an overall multiplicative sign factor.
"""
struct JMatrix{T<:Real, SGN} <: AbstractMatrix{T}
n::Int # size of the square matrix
function JMatrix{T, SGN}(n::Integer) where {T, SGN}
n β₯ 0 || throw(ArgumentError("size $n must be β₯ 0"))
(SGN === +1 || SGN === -1) || throw(ArgumentError("SGN parameter must be Β±1"))
new{T, SGN}(n)
end
end
JMatrix(n::Integer) = JMatrix{Int8,+1}(n) # default constructor using narrowest integer type
Base.size(J::JMatrix) = (J.n, J.n)
Base.size(J::JMatrix, n::Integer) = n in (1,2) ? J.n : 1
function Base.Matrix(J::JMatrix{T, SGN}) where {T, SGN}
M = zeros(T, J.n, J.n)
for i = 1:2:J.n-1
M[i+1,i] = -SGN
M[i,i+1] = SGN
end
return M
end
Base.Array(A::JMatrix) = Matrix(A)
function SkewHermTridiagonal(J::JMatrix{T, SGN}) where {T, SGN}
ev = zeros(T, J.n-1)
ev[1:2:end] .= -SGN
return SkewHermTridiagonal(ev)
end
Base.@propagate_inbounds function Base.getindex(J::JMatrix{T, SGN}, i::Integer, j::Integer) where {T, SGN}
@boundscheck checkbounds(J, i, j)
if i == j + 1 && iseven(i)
return T(-SGN)
elseif i + 1 == j && iseven(j)
return T(SGN)
else
return zero(T)
end
end
function Base.:*(J::JMatrix{T,SGN}, A::StridedVecOrMat) where {T,SGN}
LA.require_one_based_indexing(A)
m, k = size(A, 1), size(A, 2)
if m != J.n
throw(DimensionMismatch("J has second dimension $(size(J,2)), A has first dimension $(size(A,1))"))
end
B = similar(A, typeof(one(T) * oneunit(eltype(A))), J.n, k)
@inbounds for j = 1:k, i = 1:2:J.n-1
B[i,j] = SGN * A[i+1,j]
B[i+1,j] = (-SGN) * A[i,j]
end
if isodd(J.n)
B[J.n,:] .= 0
end
return B
end
function Base.:*(A::StridedVecOrMat, J::JMatrix{T,SGN}) where {T,SGN}
LA.require_one_based_indexing(A)
m, k = size(A, 1), size(A, 2)
if k != J.n
throw(DimensionMismatch("A has second dimension $(size(A,2)), J has first dimension $(size(J,1))"))
end
B = similar(A, typeof(one(T) * oneunit(eltype(A))), m, J.n)
@inbounds for i = 1:2:J.n-1, j = 1:m
B[j,i] = (-SGN) * A[j,i+1]
B[j,i+1] = SGN * A[j,i]
end
if isodd(J.n)
B[:,J.n] .= 0
end
return B
end
Base.:\(J::JMatrix, A::StridedVecOrMat) = inv(J) * A
Base.:/(A::StridedVecOrMat, J::JMatrix) = A * inv(J)
Base.:-(J::JMatrix{T,+1}) where T = JMatrix{T,-1}(J.n)
Base.:-(J::JMatrix{T,-1}) where T = JMatrix{T,+1}(J.n)
LA.transpose(J::JMatrix) = -J
LA.adjoint(J::JMatrix) = -J
function LA.inv(J::JMatrix)
iseven(J.n) || throw(LA.SingularException(J.n))
return -J
end
LA.tr(J::JMatrix{T}) where T = zero(T)
LA.det(J::JMatrix{T}) where T = T(iseven(J.n))
function LA.diag(J::JMatrix{T,SGN}, k::Integer=0) where {T,SGN}
v = zeros(T, max(0, J.n - abs(k)))
if k == 1
v[1:2:J.n-1] .= SGN
elseif k == -1
v[1:2:J.n-1] .= -SGN
end
return v
end
# show a "β
" for structural zeros when printing
function Base.replace_in_print_matrix(A::JMatrix, i::Integer, j::Integer, s::AbstractString)
(i == j+1 && iseven(i)) || (i+1 == j && iseven(j)) ? s : Base.replace_with_centered_mark(s)
end | SkewLinearAlgebra | https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git |
|
[
"MIT"
] | 1.0.0 | 5d44a4f56f7902c4414c0a477b021f17cf088cb3 | code | 8359 | # This file is a part of Julia. License is MIT: https://julialang.org/license
#using LinearAlgebra: exactdiv
if isdefined(LA,:exactdiv)
const exactdiv = LA.exactdiv
else
exactdiv(a,b) = a / b
exactdiv(a::Integer, b::Integer) = div(a, b)
end
if VERSION β₯ v"1.7"
argmaxabs(a) = argmax(Iterators.map(abs, a))
else
argmaxabs(a) = argmax(abs.(a))
end
# in-place O(nΒ³) algorithm to compute the exact Pfaffian of
# a skew-symmetric matrix over integers (or potentially any ring supporting exact division).
#
# G. Galbiati & F. Maffioli, "On the computation of pfaffians,"
# Discrete Appl. Math. 51, 269β275 (1994).
# https://doi.org/10.1016/0166-218X(92)00034-J
function _exactpfaffian!(A::AbstractMatrix)
n = size(A,1)
isodd(n) && return zero(eltype(A))
c = one(eltype(A))
signflip = false
n = n Γ· 2
while n > 1
# find last k with A[2n-1,k] β 0
k = 2n
while k > 0 && iszero(A[2n-1,k]); k -= 1; end
iszero(k) && return zero(eltype(A))
# swap rows/cols k and 2n
if k != 2n
for i = 1:2n
A[k,i], A[2n,i] = A[2n,i], A[k,i] # swap rows
end
for i = 1:2n
A[i,k], A[i,2n] = A[i,2n], A[i,k] # swap cols
end
signflip = !signflip
end
# update, A, c, n
for j = 1:2n-2, i = 1:j-1
Ξ΄ = A[2n-1,2n]*A[i,j] - A[i,2n-1]*A[j,2n] + A[j,2n-1]*A[i,2n]
A[j,i] = -(A[i,j] = exactdiv(Ξ΄, c))
# @assert A[i,j] * c == Ξ΄
end
c = A[2n-1,2n]
n -= 1
end
return signflip ? -A[1,2] : A[1,2]
end
function exactpfaffian!(A::AbstractMatrix)
LinearAlgebra.require_one_based_indexing(A)
isskewsymmetric(A) || throw(ArgumentError("Pfaffian requires a skew-symmetric matrix"))
return _exactpfaffian!(A)
end
exactpfaffian!(A::SkewHermitian) = _exactpfaffian!(A.data)
exactpfaffian(A::AbstractMatrix) = exactpfaffian!(copyto!(similar(A), A))
const ExactRational = Union{BigInt,Rational{BigInt}}
pfaffian!(A::AbstractMatrix{<:ExactRational}) = exactpfaffian!(A)
pfaffian(A::AbstractMatrix{<:ExactRational}) = pfaffian!(copy(A))
# prevent method ambiguities:
pfaffian(A::SkewHermitian{<:ExactRational}) = pfaffian!(copy(A))
pfaffian!(A::SkewHermitian{<:ExactRational}) = exactpfaffian!(A)
function _pfaffian!(A::SkewHermitian{<:Real})
n = size(A,1)
isodd(n) && return zero(eltype(A))
H = hessenberg!(A)
pf = one(eltype(A))
T = H.H
for i=1:2:n-1
pf *= -T.ev[i]
end
return pf * sign(det(H.Q))
end
function _pfaffian!(A::SkewHermTridiagonal{<:Real})
n = size(A,1)
isodd(n) && return zero(eltype(A.ev))
pf = one(eltype(A.ev))
for i=1:2:n-1
pf *= -A.ev[i]
end
return pf
end
# Using the Parley-Reid algorithm from https://arxiv.org/abs/1102.3440 as implented
# in https://github.com/KskAdch/TopologicalNumbers.jl/blob/42bda634d47aecb67cfcd495d97e0723b0e73a4f/src/pfaffian.jl#L332
function _pfaffian!(A::AbstractMatrix{<:Complex})
n = size(A, 1)
isodd(n) && return zero(eltype(A))
tau = Array{eltype(A)}(undef, n - 2)
pf = one(eltype(A))
@inbounds for k in 1:2:n-1
tauk = @view tau[k:end]
# Pivot if neccessary
@views kp = k + argmaxabs(A[k+1:end, k])
if kp != k + 1
@simd for l in k:n
A[k+1,l], A[kp,l] = A[kp,l], A[k+1,l]
end
@simd for l in k:n
A[l,k+1], A[l,kp] = A[l,kp], A[l,k+1]
end
pf *= -1
end
# Apply Gauss transformation and update `pf`
if A[k+1,k] != zero(eltype(A))
@views tauk .= A[k,k+2:end] ./ A[k,k+1]
pf *= A[k,k+1]
if k + 2 <= n
for l1 in eachindex(tauk)
@simd for l2 in eachindex(tauk)
@fastmath A[k+1+l2,k+1+l1] +=
tauk[l2] * A[k+1+l1,k+1] -
tauk[l1] * A[k+1+l2,k+1]
end
end
end
else
return zero(eltype(A)) # Pfaffian is zero if there is a zero on the super/subdiagonal
end
end
return pf
end
pfaffian!(A::Union{SkewHermitian{<:Real},SkewHermTridiagonal{<:Real}}) = _pfaffian!(A)
"""
pfaffian(A)
Returns the pfaffian of `A` where a is a skew-symmetric matrix.
If `A` is not of type `SkewHermitian{<:Real}`, then `isskewsymmetric(A)`
is checked to ensure that `A == -transpose(A)`
"""
pfaffian(A::AbstractMatrix) = pfaffian!(copyeigtype(A))
"""
pfaffian!(A)
Similar to [`pfaffian`](@ref), but overwrites `A` in-place with intermediate calculations.
"""
function pfaffian!(A::AbstractMatrix{<:Real})
isskewhermitian(A) || throw(ArgumentError("Pfaffian requires a skew-symmetric matrix"))
return _pfaffian!(SkewHermitian(A))
end
function pfaffian!(A::AbstractMatrix{<:Complex})
LinearAlgebra.require_one_based_indexing(A)
isskewsymmetric(A) || throw(ArgumentError("Pfaffian requires a skew-symmetric matrix"))
return _pfaffian!(A)
end
function _logabspfaffian!(A::SkewHermitian{<:Real})
n = size(A, 1)
isodd(n) && return convert(eltype(A), -Inf), zero(eltype(A))
H = hessenberg!(A)
logpf = zero(eltype(H))
T = H.H
sgn = one(eltype(H))
for i=1:2:n-1
logpf += log(abs(T.ev[i]))
sgn *= sign(-T.ev[i])
end
return logpf, sgn*sign(det(H.Q))
end
function _logabspfaffian!(A::SkewHermTridiagonal{<:Real})
n = size(A, 1)
isodd(n) && return convert(eltype(A.ev), -Inf), zero(eltype(A.ev))
logpf = zero(eltype(A.ev))
sgn = one(eltype(A.ev))
for i=1:2:n-1
logpf += log(abs(A.ev[i]))
sgn *= sign(-A.ev[i])
end
return logpf, sgn
end
function _logabspfaffian!(A::AbstractMatrix{<:Complex})
n = size(A, 1)
isodd(n) && return convert(real(eltype(A)), -Inf), zero(eltype(A))
tau = Array{eltype(A)}(undef, n - 2)
logpf = phase = zero(real(eltype(A)))
@inbounds for k in 1:2:n-1
tauk = @view tau[k:end]
# Pivot if neccessary
@views kp = k + argmaxabs(A[k+1:end, k])
if kp != k + 1
@simd for l in k:n
A[k+1,l], A[kp,l] = A[kp,l], A[k+1,l]
end
@simd for l in k:n
A[l,k+1], A[l,kp] = A[l,kp], A[l,k+1]
end
phase += Ο
end
# Apply Gauss transformation and update `pf`
if A[k+1,k] != zero(eltype(A))
@views tauk .= A[k,k+2:end] ./ A[k,k+1]
logpf += log(abs(A[k,k+1]))
phase += angle(A[k,k+1])
if k + 2 <= n
for l1 in eachindex(tauk)
@simd for l2 in eachindex(tauk)
@fastmath A[k+1+l2,k+1+l1] +=
tauk[l2] * A[k+1+l1,k+1] -
tauk[l1] * A[k+1+l2,k+1]
end
end
end
else
return convert(real(eltype(A)), -Inf), zero(eltype(A))
end
end
return logpf, cis(phase)
end
logabspfaffian!(A::Union{SkewHermitian{<:Real},SkewHermTridiagonal{<:Real}})= _logabspfaffian!(A)
logabspfaffian(A::Union{SkewHermitian{<:Real},SkewHermTridiagonal{<:Real}})= logabspfaffian!(copyeigtype(A))
"""
logabspfaffian(A)
Returns a tuple `(log|pf(A)|, sign)`, with the log of the absolute value of the pfaffian of
`A` as first output and the sign of the pfaffian as second output such that
`pfaffian(A) β sign * exp(log|pf(A)|)`. `A` must be a skew-symmetric matrix. If `A` is not of type
`SkewHermitian{<:Real}`, then `isskewsymmetric(A)` is checked to ensure that `A == -transpose(A)`
"""
logabspfaffian(A::AbstractMatrix) = logabspfaffian!(copyeigtype(A))
"""
logabspfaffian!(A)
Similar to [`logabspfaffian`](@ref), but overwrites `A` in-place with intermediate calculations.
"""
function logabspfaffian!(A::AbstractMatrix{<:Real})
isskewhermitian(A) || throw(ArgumentError("Pfaffian requires a skew-Hermitian matrix"))
return _logabspfaffian!(SkewHermitian(A))
end
function logabspfaffian!(A::AbstractMatrix{<:Complex})
LinearAlgebra.require_one_based_indexing(A)
isskewsymmetric(A) || throw(ArgumentError("Pfaffian requires a skew-symmetric matrix"))
return _logabspfaffian!(A)
end
| SkewLinearAlgebra | https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.