licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | code | 1394 | abstract type AbstractTestDistributions end
struct AsymptoticDist <: AbstractTestDistributions
shift::Float64
cutoff::Float64
end
"""
asymptotic_dists(sqrtqmuA; base_dist = :normal)
Return `S+B` and `B only` teststatistics distributions.
"""
function asymptotic_dists(sqrtqmuA; base_dist = :normal)
cutoff = base_dist == :normal ? -Inf : -sqrtqmuA
s_plus_b_dist = AsymptoticDist(-sqrtqmuA, cutoff)
b_dist = AsymptoticDist(0.0, cutoff)
return s_plus_b_dist, b_dist
end
"""
pvalue(d::AsymptoticDist, value) -> Real
Compute the p-value for a single teststatistics distribution.
"""
pvalue(d::AsymptoticDist, value) = cdf(Normal(), -(value - d.shift))
"""
pvalue(teststat, s_plus_b_dist::AsymptoticDist, b_only_dist::AsymptoticDist)
-> (CLsb, CLb, CLs)
Compute the confidence level for `S+B`, `B` only, and `S`.
"""
function pvalue(teststat, s_plus_b_dist::AsymptoticDist, b_only_dist::AsymptoticDist)
CLsb = pvalue(s_plus_b_dist, teststat)
CLb = pvalue(b_only_dist, teststat)
CLs = CLsb / CLb
return CLsb, CLb, CLs
end
expected_sigma(d::AsymptoticDist, nsigma) = max(d.cutoff, d.shift + nsigma)
function expected_pvalue(s_plus_b_dist::AsymptoticDist, b_only_dist::AsymptoticDist)
stats_range = expected_sigma.(Ref(b_only_dist), 2:-1:-2)
return [pvalue(s_plus_b_dist, i) / pvalue(b_only_dist, i) for i in stats_range]
end
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | code | 4517 | abstract type AbstractInterp end
const V64 = Vector{Float64}
"""
InterpCode0{T}
Callable struct for interpolation for additive modifier.
Code0 is the two-piece linear interpolation.
"""
struct InterpCode0 <: AbstractInterp
Δ_up::V64
Δ_down::V64
end
function InterpCode0(I0, I_up::T, I_down::T) where {T<:AbstractVector}
Δ_up = I_up - I0
Δ_down = I0 - I_down
InterpCode0(Float64.(Δ_up), Float64.(Δ_down))
end
function (i::InterpCode0)(α)
vs = Base.ifelse(α >= zero(α), i.Δ_up, i.Δ_down)
return vs*α
end
"""
InterpCode1{T}
Callable struct for interpolation for multiplicative modifier.
Code1 is the exponential interpolation.
"""
struct InterpCode1 <: AbstractInterp
f_up::Float64
f_down::Float64
end
function InterpCode1(I0, I_up::T, I_down::T) where {T<:AbstractVector}
f_up = first(I_up ./ I0)
f_down = first(I_down ./ I0)
InterpCode1(f_up, f_down)
end
function (i::InterpCode1)(α)
Base.ifelse(α >= zero(α), (i.f_up)^α, (i.f_down)^(-α))
end
struct InterpCode2 <: AbstractInterp
a::V64
b::V64
end
function InterpCode2(I0, I_up::T, I_down::T) where {T<:AbstractVector}
a = @. 0.5 * (I_up + I_down) - I0
b = @. 0.5 * (I_up - I_down)
InterpCode2(Float64.(a), Float64.(b))
end
function (i::InterpCode2)(α)
(; a, b) = i
if α > 1
@. (b + 2*a) * (α - 1)
elseif α >= -1
@. a * α^2 + b * α
else
@. (b - 2*a) * (α + 1)
end
end
"""
InterpCode4{T}
Callable struct for interpolation for additive modifier.
Code4 is the exponential + 6-order polynomial interpolation.
"""
struct InterpCode4 <: AbstractInterp
f_ups::V64
f_downs::V64
α0::Float64
inver::Matrix{Float64}
end
function InterpCode4(I0, I_up, I_down; α0=1.0)
inver = _interp4_inverse(α0)
InterpCode4(Float64.(I_up ./ I0), Float64.(I_down ./ I0), α0, inver)
end
function (i::InterpCode4)(α)
(; f_ups, f_downs, inver, α0) = i
delta_up = f_ups
delta_down = f_downs
mult = if α >= α0
@. (delta_up) ^ α
elseif α <= -α0
@. (delta_down) ^ (-α)
else
delta_up_alpha0 = @. delta_up^α0
delta_down_alpha0 = @. delta_down^α0
b = @. [
delta_up_alpha0 - 1,
delta_down_alpha0 - 1,
log(delta_up) * delta_up_alpha0,
-log(delta_down) * delta_down_alpha0,
log(delta_up)^2 * delta_up_alpha0,
log(delta_down)^2 * delta_down_alpha0,
]
coefficients = inver * b
1 .+ sum(coefficients[i] * α^i for i=1:6)
end
mult
end
function _interp4_inverse(α0)
alpha0 = α0
[15/(16*alpha0) -15/(16*alpha0) -7/16 -7/16 1/16*alpha0 -1/16*alpha0
3/(2*alpha0^2) 3/(2*alpha0^2) -9/(16*alpha0) 9/(16*alpha0) 1/16 1/16
-5/(8*alpha0^3) 5/(8*alpha0^3) 5/(8*alpha0^2) 5/(8*alpha0^2) -1/(8*alpha0) 1/(8*alpha0)
3/(-2*alpha0^4) 3/(-2*alpha0^4) -7/(-8*alpha0^3) 7/(-8*alpha0^3) -1/(8*alpha0^2) -1/(8*alpha0^2)
3/(16*alpha0^5) -3/(16*alpha0^5) -3/(16*alpha0^4) -3/(16*alpha0^4) 1/(16*alpha0^3) -1/(16*alpha0^3)
1/(2*alpha0^6) 1/(2*alpha0^6) -5/(16*alpha0^5) 5/(16*alpha0^5) 1/(16*alpha0^4) 1/(16*alpha0^4) ]
end
"""
MultOneHot{T} <: AbstractVector{T}
Internal type used to avoid allocation for per-bin multiplicative systematics. It behaves as a vector with length `nbins` and
only has value `α` on `nthbin`-th index, the rest being `one(T)`. See also [binidentity](@ref).
"""
struct MultOneHot{T} <: AbstractVector{T}
nbins::Int
nthbin::Int
α::T
end
Base.length(b::MultOneHot) = b.nbins
Base.getindex(b::MultOneHot{T}, n::Integer) where T = Base.ifelse(n==b.nthbin, b.α, one(T))
Base.size(b::MultOneHot) = (b.nbins, )
"""
binidentity(nbins, nthbin)
A functional that used to track per-bin systematics. Returns the closure function over `nbins, nthbin`:
```julia
α -> MultOneHot(nbins, nthbin, α)
```
"""
function binidentity(nbins, nthbin)
α -> MultOneHot(nbins, nthbin, α)
end
"""
Pseudo flat prior in the sense that `logpdf()` always evaluates to zero,
but `rand()`, `minimum()`, and `maximum()` behaves like `Uniform(a, b)`.
"""
struct FlatPrior <: Distributions.ContinuousUnivariateDistribution
a::Float64
b::Float64
end
Base.minimum(d::FlatPrior) = d.a
Base.maximum(d::FlatPrior) = d.b
Distributions.logpdf(d::FlatPrior, x::Real) = zero(x)
Base.rand(rng::Random.AbstractRNG, d::FlatPrior) = rand(rng, Uniform(d.a, d.b))
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | code | 5504 | using Unrolled
using SpecialFunctions: logabsgamma
using LogExpFunctions: xlogy
abstract type AbstractModifier end
function _prior end
function _init end
"""
Histosys is defined by two vectors represending bin counts
in `hi_data` and `lo_data`
"""
struct Histosys{T<:AbstractInterp} <: AbstractModifier
interp::T
function Histosys(interp::T) where T
@assert T <: Union{InterpCode0, InterpCode2, InterpCode4}
new{T}(interp)
end
end
Histosys(nominal, up, down) = Histosys(InterpCode0(nominal, up, down))
_prior(::Histosys) = Normal()
_init(::Histosys) = 0.0
struct Normsys{T<:AbstractInterp} <: AbstractModifier
interp::T
end
_prior(::Normsys) = Normal()
_init(::Normsys) = 0.0
"""
Normsys is defined by two multiplicative scalars
"""
Normsys(up::Number, down::Number) = Normsys(InterpCode1(up, down))
Normsys(nominal, ups, downs) = Normsys(InterpCode1(nominal, ups, downs))
"""
Normfactor is unconstrained, so `interp` is just identity.
"""
struct Normfactor <: AbstractModifier # is unconstrained
interp::typeof(identity)
Normfactor() = new(identity)
end
_prior(::Normfactor) = FlatPrior(0, 5)
_init(::Normfactor) = 1.0
"""
Shapefactor is unconstrained, so `interp` is just identity. Unlike `Normfactor`,
this is per-bin
"""
struct Shapefactor{T} <: AbstractModifier # is unconstrained
interp::T
function Shapefactor(nbins, nthbin)
f = binidentity(nbins, nthbin)
new{typeof(f)}(f)
end
end
_prior(::Shapefactor) = FlatPrior(0, 5)
_init(::Shapefactor) = 1.0
"""
Shapesys doesn't need interpolation, similar to `Staterror`
"""
struct Shapesys{T} <: AbstractModifier
σn2::Float64
interp::T
function Shapesys(σneg2, nbins, nthbin)
f = binidentity(nbins, nthbin)
new{typeof(f)}(σneg2, f)
end
end
"""
RelaxedPoisson
Poisson with `logpdf` continuous in `k`. Essentially by replacing denominator with `gamma` function.
!!! warning
The `Distributions.logpdf` has been redefined to be `logpdf(d::RelaxedPoisson, x) = logpdf(d, x*d.λ)`.
This is to reproduce the Poisson constraint term in `pyhf`, which is a hack introduced for Asimov dataset.
"""
struct RelaxedPoisson{T} <: Distributions.ContinuousUnivariateDistribution
λ::T
end
# https://github.com/scikit-hep/pyhf/blob/ce7057417ee8c4e845df8302c7375301901d2b7d/src/pyhf/tensor/numpy_backend.py#L390
@inline function _relaxedpoislogpdf(λ::T, x)::T where T
xlogy(x, λ) - λ - logabsgamma(x + one(x))[1]
end
Distributions.logpdf(d::RelaxedPoisson, x) = _relaxedpoislogpdf(d.λ*x, d.λ)
_prior(S::Shapesys) = RelaxedPoisson(S.σn2)
_init(S::Shapesys) = 1.0
"""
Staterror doesn't need interpolation, but it's a per-bin modifier.
Information regarding which bin is the target is recorded in `bintwoidentity`.
The `δ` is the absolute yield uncertainty in each bin, and the relative uncertainty:
`δ` / nominal is taken to be the `σ` of the prior, i.e. `α ~ Normal(1, δ/nominal)`
"""
struct Staterror{T} <: AbstractModifier
σ::Float64
interp::T
function Staterror(σ, nbins, nthbin)
f = binidentity(nbins, nthbin)
new{typeof(f)}(σ, f)
end
end
_prior(S::Staterror) = Normal(1, S.σ)
_init(S::Staterror) = 1.0
"""
Luminosity doesn't need interpolation, σ is provided at modifier construction time.
In `pyhf` JSON, this information lives in the "Measurement" section, usually near the end of
the JSON file.
"""
struct Lumi <: AbstractModifier
σ::Float64
interp::typeof(identity)
Lumi(σ) = new(σ, identity)
end
_prior(l::Lumi) = Normal(1, l.σ)
_init(l::Lumi) = 1.0
"""
struct ExpCounts{T, M} #M is a long Tuple for unrolling purpose.
nominal::T
modifier_names::Vector{Symbol}
modifiers::M
end
A callable struct that returns the expected count given modifier nuisance parameter values.
The # of parameters passed must equal to length of `modifiers`. See [_expkernel](@ref)
"""
struct ExpCounts{T<:Number, M}
nominal::Vector{T}
modifier_names::Vector{Symbol}
modifiers::M
end
# stop crazy stracktrace
function Base.show(io::IO, ::Type{<:ExpCounts})
println(io, "ExpCounts{}")
end
function exp_mod!(interp::InterpCode0, additive, factor, α)
additive .+= interp(α)
end
function exp_mod!(interp::InterpCode2, additive, factor, α)
additive .+= interp(α)
end
function exp_mod!(interp, additive, factor, α)
factor .*= interp(α)
end
ExpCounts(nominal::Vector{<:Number}, names::Vector{Symbol}, modifiers::AbstractVector) = ExpCounts(nominal, names, tuple(modifiers...))
"""
_expkernel(modifiers, nominal, αs)
The `Unrolled.@unroll` kernel function that computs the expected counts.
"""
@unroll function _expkernel(modifiers, nominal, αs)
T = eltype(αs)
additive = T.(nominal)
factor = ones(T, length(additive))
@unroll for i in 1:length(modifiers)
@inbounds exp_mod!(modifiers[i].interp, additive, factor, αs[i])
end
return factor .* additive
end
function (E::ExpCounts)(αs)
(; modifiers, nominal) = E
@assert length(modifiers) == length(αs)
return _expkernel(modifiers, nominal, αs)
end
for T in (Normsys, Normfactor, Histosys, Staterror, Lumi, Shapefactor)
@eval function Base.show(io::IO, E::$T)
interp = Base.typename(typeof(E.interp)).name
print(io, $T, "{$interp}")
end
end
function Base.show(io::IO, E::ExpCounts)
modifiers = E.modifiers
elip = length(modifiers) > 5 ? "...\n" : ""
println(io, "ExpCounts with $(length(modifiers)) modifiers:")
end
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | code | 6189 | """
struct PyHFModel{E, O, P} <: AbstractModel
expected::E
observed::O
priors::P
prior_names
inits::Vector{Float64}
end
Struct for holding result from [build_pyhf](@ref). List of accessor functions is
- expected(p::PyHFModel)
- observed(p::PyHFModel)
- priors(p::PyHFModel)
- prior_names(p::PyHFModel)
- inits(p::PyHFModel)
"""
mutable struct PyHFModel{E, O, P}
expected::E
observed::O
priors::P
prior_names
inits::Vector{Float64}
end
expected(p::PyHFModel) = p.expected
expected(p::PyHFModel, paras) = expected(p)(paras)
observed(p::PyHFModel) = p.observed
priors(p::PyHFModel) = p.priors
prior_names(p::PyHFModel) = p.prior_names
inits(p::PyHFModel) = p.inits
pyhf_logjointof(m::PyHFModel) = pyhf_logjointof(expected(m), observed(m), priors(m))
function Base.show(io::IO, P::PyHFModel)
Nprior = length(priors(P))
print(io, "PyHFModel with $(Nprior) nuisance parameters.")
end
"""
internal_expected(Es, Vs, αs)
The `@generated` function that computes expected counts in `expected(PyHFModel, parameters)` evaluation.
The `Vs::NTuple{N, Vector{Int64}}` has the same length as `Es::NTuple{N, ExpCounts}`.
In general `αs` is shorter than `Es` and `Vs` because a given nuisance parameter `α` may appear
in multiple sample / modifier.
!!! note
If for example `Vs[1] = [1,3,4]`, it means that the first `ExpCount` in `Es` is evaluated with
```
Es[1](@view αs[[1,3,4]])
```
and so on.
"""
@generated function internal_expected(Es, Vs, αs)
@assert Es <: Tuple
@views expand(i) = i == 1 ? :(Es[1](αs[Vs[1]])) : :(+(Es[$i](αs[Vs[$i]]), $(expand(i-1))))
return expand(length(Es.parameters))
end
function find_obs_data(name, observations)
i = findfirst(x->x[:name] == name, observations)
observations[i][:data]
end
"""
Ensure POI parameter always comes first in the input array.
"""
function sortpoi!(priornames, priors, poi_name)
poi_idx = findfirst(==(poi_name), priornames)
if poi_idx != 1
deleteat!(priornames, poi_idx)
pushfirst!(priornames, poi_name)
poi_mod = priors[poi_idx]
deleteat!(priors, poi_idx)
pushfirst!(priors, poi_mod)
end
nothing
end
"""
build_pyhf(load_pyhfjson(path)) -> PyHFModel
the `expected(αs)` is a function that takes vector or tuple of length `N`, where `N` is also the
length of `priors` and `priornames`. In other words, these three fields of the returned object
are aligned.
!!! note
The bins from different channels are put into a `NTuple{Nbins, Vector}`.
"""
function build_pyhf(pyhfmodel)
channels = [name => channel for (name, channel) in pyhfmodel if name != "misc"]
v_obs = Tuple(find_obs_data(name, pyhfmodel["misc"][:observations]) for (name, _) in channels)
poi_name = pyhfmodel["misc"][:measurements][1][:config][:poi] |> Symbol
global_unique = reduce(vcat, [sample[2].modifier_names for (name, C) in channels for sample in C]) |>
unique
# intentional type-insability, avoid latency
all_expected = []
all_lookup = Dict()
for c in channels
exp, lk = build_pyhfchannel(c, global_unique)
push!(all_expected, exp)
merge!(all_lookup, lk)
end
input_modifiers = [all_lookup[k] for k in global_unique]
priornames_v = Symbol.(global_unique)
priors_v = _prior.(input_modifiers)
sortpoi!(priornames_v, priors_v, poi_name)
priornames = Tuple(priornames_v)
priors = NamedTuple{priornames}(priors_v)
inits = Vector{Float64}(_init.(input_modifiers))
total_expected = let Es = Tuple(all_expected)
αs -> map(E->E(αs), Es)
end
return PyHFModel(total_expected, v_obs, priors, priornames, inits)
end
function build_pyhfchannel(channel, global_unique)
#### this is within the channel, we use `global_unique` vector to align back
name, samples = channel
all_expcounts = Tuple(sample[2] for sample in samples)
all_v_names = Any[E.modifier_names for E in all_expcounts]
all_names = reduce(vcat, all_v_names)
channel_unique = unique(all_names)
all_modifiers = []
for E in all_expcounts
append!(all_modifiers, E.modifiers)
end
lookup = Dict(all_names .=> all_modifiers)
# Special case: same name can appear multiple times with different modifier type
# if masks[1] == [1,2,4] that means the first `ExpCounts(αs[[1,2,4]])`
masks = Tuple([findfirst(==(i), global_unique) for i in names] for names in all_v_names)
expected = αs -> internal_expected(all_expcounts, masks, αs)
return expected, lookup
end
"""
pyhf_loglikelihoodof(expected, obs)
Return a callable Function `L(αs)` that would calculate the log likelihood. `expected` is a callable of
`αs` as well.
!!! note
The so called "constraint" terms (from priors) are NOT included here.
"""
function pyhf_loglikelihoodof(expected, obs)
f(e, o) = e < zero(e) ? oftype(e, -Inf) : _relaxedpoislogpdf(e, o)
return function log_likelihood(αs)
mapreduce(+, expected(αs), obs) do E, O # sum over channels
sum(Base.Broadcast.broadcasted(f, E, O))
end
end
end
@generated function internal_constrainteval(pris, αs)
@assert pris <: Tuple
@views expand(i) = i == 1 ? :(logpdf(pris[1], αs[1])) :
:(+(logpdf(pris[$i], αs[$i]), $(expand(i-1))))
return expand(length(pris.parameters))
end
"""
pyhf_logpriorof(priors)
Return a callable Function `L(αs)` that would calculate the log likelihood
for the priors.
!!! note
Sometimes these are called the "constraint" terms.
"""
function pyhf_logpriorof(priors)
pris = values(priors)
function (αs)
@assert length(αs) == length(pris)
internal_constrainteval(pris, αs)
end
end
"""
pyhf_logjointof(expected, obs, priors)
Return a callable Function that would calculate the joint log likelihood
of likelihood and priors.
Equivalent of adding `loglikelihood` and `logprior` together.
!!! note
The "constraint" terms are included here.
"""
function pyhf_logjointof(expected, obs, priors)
L1 = pyhf_loglikelihoodof(expected, obs)
L2 = pyhf_logpriorof(priors)
return αs -> L1(αs) + L2(αs)
end
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | code | 3649 | using JSON3
const _modifier_dict = Dict(
"normfactor" => Normfactor,
"histosys" => Histosys,
"normsys" => Normsys,
"shapesys" => Shapesys,
"staterror" => Staterror,
"lumi" => Lumi,
"shapefactor" => Shapefactor,
)
function hilo_data(jobj)
promote(collect(jobj[:hi_data]), collect(jobj[:lo_data]))
end
function hilo_factor(jobj)
jobj[:hi], jobj[:lo]
end
"""
build_modifier(rawjdict[:channels][1][:samples][2][:modifiers][1]) =>
<:AbstractModifier
"""
function build_modifier!(jobj, names; misc, mcstats, parent)
mod = build_modifier(jobj, _modifier_dict[jobj[:type]]; misc, mcstats, parent)
mod_name = Symbol(jobj[:name])
if mod isa Vector
# for stuff like Staterror, which inflates to multiple `γ`
for i in eachindex(mod)
push!(names, Symbol(mod_name, "_bin$i"))
end
else
push!(names, mod_name)
end
return mod
end
"""
build_modifier(...[:modifiers][1][:data], Type) =>
<:AbstractModifier
"""
function build_modifier(modobj, modifier_type::Type{T}; misc, mcstats, parent) where T
modname = modobj[:name]
moddata = modobj[:data]
nominal = parent[:data]
nbins = length(nominal)
if T == Histosys
hi,lo = hilo_data(moddata)
T(nominal, hi, lo)
elseif T == Normsys
T(hilo_factor(moddata)...)
elseif T == Staterror
# each Staterror keepds track of which bin it should modifier
nominalsums, sumδ2 = mcstats[modname]
T.(sqrt.(sumδ2) ./ nominalsums, nbins, eachindex(moddata))
elseif T == Lumi
paras = misc[:measurements][1][:config][:parameters]
lumi_idx = findfirst(x->x[:name] == modname, paras)
σ = only(paras[lumi_idx][:sigmas])
T(σ)
elseif T == Shapesys
T.((nominal ./ moddata).^2, nbins, eachindex(moddata))
elseif T == Shapefactor
T.(eachindex(moddata))
else
T()
end
end
"""
build_sample(rawjdict[:channels][1][:samples][2]) =>
ExpCounts
"""
function build_sample(jobj, names=Symbol[]; misc, mcstats)
modifiers = build_modifier!.(jobj[:modifiers], Ref(names); misc, mcstats, parent=jobj)
modifiers = any(x->x <: Vector, typeof.(modifiers)) ? reduce(vcat, modifiers) : modifiers #flatten it
@assert length(names) == length(modifiers)
ExpCounts(collect(jobj[:data]), names, modifiers)
end
"""
build_channel(rawjdict[:channels][1][:samples][2]) =>
Dict{String, ExpCounts}
"""
function build_channel(jobj; misc)
mcstats = Dict()
# accumulate MC stats related quantities
for sample in jobj[:samples], m in sample[:modifiers]
m[:type] != "staterror" && continue
modname = m[:name]
if haskey(mcstats, modname)
mcstats[modname] = mcstats[modname] .+ (sample[:data], m[:data] .^ 2)
else
mcstats[modname] = (sample[:data], m[:data] .^ 2)
end
end
# build modifiers
res = Dict()
for sample in jobj[:samples]
res[sample[:name]] = build_sample(sample; misc, mcstats)
end
res
end
"""
load_pyhfjson(path)
"""
function load_pyhfjson(path)
jobj = JSON3.read(read(path))
mes = get(jobj, :measurements, Dict())
obs = get(jobj, :observations, Dict())
misc = Dict(:measurements => mes, :observations => obs)
res = Dict{String, Any}(obj[:name] => build_channel(obj; misc) for obj in jobj[:channels])
res["misc"] = misc
res
end
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | code | 6601 | function free_maximize(f, inits; alg = Optim.LBFGS())
res = Optim.maximize(f, inits, alg, Optim.Options(g_tol = 1e-9, iterations=10^4); autodiff=:forward)
@assert Optim.converged(res)
maximum(res), Optim.maximizer(res)
end
free_maximize(m::PyHFModel; kwd...) = free_maximize(pyhf_logjointof(m), m.inits; kwd...)
function cond_maximize(LL, μ, partial_inits; kwd...)
cond_LL= get_condLL(LL, μ)
free_maximize(cond_LL, partial_inits; kwd...)
end
cond_maximize(m::PyHFModel, μ) = cond_maximize(pyhf_logjointof(m), μ, m.inits[2:end])
const fix_poi_fit = cond_maximize
"""
get_condLL(LL, μ)
Given the original log-likelihood function and a value for parameter of interest, return a function `condLL(nuisance_θs)`
that takes one less argument than the original `LL`. The `μ` is assumed to be the first element in input vector.
"""
function get_condLL(LL, μ)
function condLL(nuisance_θs)
θs = vcat(μ, nuisance_θs)
LL(θs)
end
end
@doc raw"""
get_lnLR(LL, inits)
A functional that returns a function `lnLR(μ::Number)` that evaluates to log of likelihood-ratio:
```math
\ln\lambda(\mu) = \ln(\frac{L(\mu, \hat{\hat\theta)}}{L(\hat\mu, \hat\theta)}) = LL(\mu, \hat{\hat\theta}) - LL(\hat\mu, \hat\theta)
```
!!! warning
we assume the POI is the first in the input array.
"""
function get_lnLR(LL, inits; POI_idx=1)
LL_hat, θ0_hat = free_maximize(LL, inits)
nuisance_inits = inits[2:end]
function lnLR(μ)
LL_doublehat, _ = cond_maximize(LL, μ, nuisance_inits)
return LL_doublehat - LL_hat
end
end
@doc raw"""
get_lnLRtilde(LL, inits)
A functional that returns a function `lnLRtilde(μ::Number)` that evaluates to log of likelihood-ratio:
```math
\ln\widetilde{\lambda(\mu)}
```
See equation 10 in: https://arxiv.org/pdf/1007.1727.pdf for refercen.
"""
function get_lnLRtilde(LL, inits)
LL_hat, θ_hat = free_maximize(LL, inits)
nuisance_inits = inits[2:end]
if θ_hat[1] < 0 # re-fit with μ set to 0
LL_hat, _ = cond_maximize(LL, 0.0, nuisance_inits)
end
function lnLRtilde(μ)
LL_doublehat, _ = cond_maximize(LL, μ, nuisance_inits)
return LL_doublehat - LL_hat
end
end
abstract type AbstractTestStatistics end
const ATS = AbstractTestStatistics
@doc raw"""
T_tmu
```math
t_\mu = -2\ln\lambda(\mu)
```
"""
struct T_tmu <: ATS end
@doc raw"""
T_tmutilde(LL, inits)
```math
\widetilde{t_\mu} = -2\ln\widetilde{\lambda(\mu)}
```
"""
struct T_tmutilde <: ATS end
@doc raw"""
Test statistic for discovery of a positive signal
q_0 = \tilde{t}_0
See equation 12 in: https://arxiv.org/pdf/1007.1727.pdf for reference.
Note that this IS NOT a special case of q_\mu for \mu = 0.
"""
struct T_q0 <: ATS end
@doc raw"""
Test statistic for upper limits
See equation 14 in: https://arxiv.org/pdf/1007.1727.pdf for reference.
Note that q_0 IS NOT a special case of q_\mu for \mu = 0.
"""
struct T_qmu <: ATS end
struct T_qmutilde <: ATS end
@doc raw"""
get_teststat(LL, inits, ::Type{T}) where T <: ATS
Return a callable function `t(μ)` that evaluates to the value of corresponding test statistics.
"""
function get_teststat(LL, inits, ::Type{T_tmu})
lnLR = get_lnLR(LL, inits)
function t(μ)
max(0.0, -2*lnLR(μ))
end
end
function get_teststat(LL, inits, ::Type{T_tmutilde})
lnLRtilde = get_lnLRtilde(LL, inits)
function tmutilde(μ)
max(0.0, -2*lnLRtilde(μ))
end
end
function get_teststat(LL, inits, ::Type{T_q0})
res = get_teststate(LL, inits, T_tmutilde)(0.0)
function q0(μ=0)
@assert iszero(μ) "q0 by definition demands μ=0" #q0 is forced to have μ == 0
return max(res, 0.0)
end
end
function get_teststat(LL, inits, ::Type{T_qmu})
_, θ0 = free_maximize(LL, inits)
μ_hat = θ0[1]
function qmu(μ)
if μ_hat <= μ
lnLR = get_lnLR(LL, inits)
-2*lnLR(μ)
else
0.0
end
end
end
function get_teststat(LL, inits, ::Type{T_qmutilde})
_, θ0 = free_maximize(LL, inits)
lnLRtilde = get_lnLRtilde(LL, inits)
μ_hat = θ0[1]
function qmutilde(μ)
if μ_hat <= μ
-2*lnLRtilde(μ)
else
0.0
end
end
end
"""
asimovdata(model::PyHFModel, μ)
Generate the Asimov dataset and asimov priors, which is the expected counts after fixing POI to `μ` and optimize the
nuisance parameters.
"""
function asimovdata(model::PyHFModel, μ)
LL = pyhf_logjointof(model)
nuisance_inits = inits(model)[2:end]
_, θs = cond_maximize(LL, μ, nuisance_inits)
asimov_params = vcat(μ, θs)
ps = priors(model)
new_priors = NamedTuple{keys(ps)}(map(asimovprior, ps, asimov_params))
expected(model, asimov_params), new_priors
end
"""
AsimovModel(model::PyHFModel, μ)::PyHFModel
Generate the Asimov model when fixing `μ` (POI) to a value. Notice this changes the `priors` and `observed` compare
to the original `model`.
"""
function AsimovModel(model::PyHFModel, μ)
A_data, A_priors = asimovdata(model, μ)
PyHFModel(expected(model), A_data, A_priors, prior_names(model), inits(model))
end
asimovprior(dist::Normal, θ) = Normal(θ, dist.σ)
asimovprior(dist::FlatPrior, θ) = dist
function T_qmu(model::PyHFModel, qmuA_f)
LL0 = pyhf_logjointof(model)
qmu_f = get_teststat(LL0, inits(model), T_qmu)
μ -> sqrt(qmu_f(μ)) - sqrt(qmuA_f(μ))
end
function T_qmu(model::PyHFModel)
A_model = AsimovModel(model, 0.0)
A_LL = pyhf_logjointof(A_model)
qmuA_f = get_teststat(A_LL, inits(A_model), T_qmu)
TS_q(model, qmuA_f)
end
function T_q0(model::PyHFModel, q0A_f)
LL0 = pyhf_logjointof(model)
q0_f = get_teststat(LL0, inits(model), T_q0)
function (μ=0)
return sqrt(q0_f(μ)) - sqrt(q0A_f(μ))
end
end
function T_q0(model::PyHFModel)
A_model = AsimovModel(model, 1.0)
A_LL = pyhf_logjointof(A_model)
q0A_f = get_q0(A_LL, inits(A_model))
TS_q0(model, q0A_f)
end
function T_qmutilde(model::PyHFModel, qtildeA_f)
LL0 = pyhf_logjointof(model)
qtilde_f = get_teststat(LL0, inits(model), T_qmutilde)
function (x)
qmu = qtilde_f(x)
qmu_A = qtildeA_f(x)
sqrtqmu = sqrt(qmu)
sqrtqmuA = sqrt(qmu_A)
if sqrtqmu < sqrtqmuA
sqrtqmu - sqrtqmuA
else
(qmu - qmu_A) / (2 * sqrtqmuA)
end
end
end
function T_qmutilde(model::PyHFModel)
A_model = AsimovModel(model, 0.0)
A_LL = pyhf_logjointof(A_model)
qtildeA_f = get_teststat(A_LL, inits(A_model), T_qmutilde)
TS_qtilde(model, qtildeA_f)
end
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | code | 4477 | using LiteHF, Optim
using Test
@testset "Interpolations" begin
# Ref https://cds.cern.ch/record/1456844/files/CERN-OPEN-2012-016.pdf
nominal = [2.5, 2.0]
hi_shape_var= [1.4, 3.8]
hi_shape_temp = nominal + hi_shape_var
lo_shape_var= [1.3, 1.2]
lo_shape_temp = nominal - lo_shape_var
@testset "InterpCode0" begin
i0 = LiteHF.InterpCode0(nominal, hi_shape_temp, lo_shape_temp)
i0two = LiteHF.InterpCode0(hi_shape_var, lo_shape_var)
@test i0.Δ_up ≈ i0two.Δ_up
@test i0.Δ_down ≈ i0two.Δ_down
@test i0(0.0) == zeros(2)
@test i0(1.0) + nominal == hi_shape_temp
@test i0(-1.0) + nominal == lo_shape_temp
@test i0(-0.5) + nominal == nominal - 0.5*lo_shape_var
end
@testset "InterpCode2" begin
i2 = LiteHF.InterpCode2(nominal, hi_shape_temp, lo_shape_temp)
@test i2.a == 0.5 * (hi_shape_temp + lo_shape_temp) - nominal
@test i2.b == 0.5 * (hi_shape_temp - lo_shape_temp)
@test i2(0.0) == zeros(2)
@test i2(1.0) + nominal == hi_shape_temp
@test i2(-1.0) + nominal ≈ lo_shape_temp
α = -0.5
@test i2(α) ≈ i2.a * α^2 + i2.b * α
α = 1.2
@test i2(α) ≈ @. (i2.b + 2*i2.a) * (α - 1)
α = -1.4
@test i2(α) ≈ @. (i2.b - 2*i2.a) * (α + 1)
end
@testset "InterpCode4" begin
i4 = LiteHF.InterpCode4(nominal, hi_shape_temp, lo_shape_temp)
@test i4(0.0) == ones(length(nominal))
@test i4(1.0) .* nominal ≈ hi_shape_temp
@test i4(-1.0) .* nominal ≈ lo_shape_temp
end
hi_sf= 1.1
lo_sf= 0.84
hi_sf_temp = hi_sf * nominal
lo_sf_temp = lo_sf * nominal
@testset "InterpCode1" begin
i1 = LiteHF.InterpCode1(nominal, hi_sf_temp, lo_sf_temp)
i1two = LiteHF.InterpCode1(hi_sf, lo_sf)
@test i1.f_up ≈ i1two.f_up
@test i1.f_down ≈ i1two.f_down
@test i1(1.0)*nominal ≈ hi_sf_temp
@test i1(-1.0)*nominal ≈ lo_sf_temp
end
end
function loadmodel(path)
pydict = load_pyhfjson(path)
pyhfmodel = build_pyhf(pydict)
end
testmodel(path::String, OPT = BFGS()) = testmodel(loadmodel(path), OPT)
function testmodel(pyhfmodel, OPT = BFGS())
LL = pyhf_logjointof(pyhfmodel)
res = maximize(LL, inits(pyhfmodel),
OPT, Optim.Options(g_tol=1e-5); autodiff=:forward)
best_paras = Optim.maximizer(res)
twice_nll = -2*LL(best_paras)
end
stateerror_shape = loadmodel(joinpath(@__DIR__, "./pyhfjson/sample_staterror_shapesys.json"))
@testset "Basic expected tests" begin
R = stateerror_shape
@test R.expected(ones(5))[1] == [23.0, 15.0]
@test R.expected(R.inits)[1] == [23.0, 15.0]
@test R.expected([0.81356312, 0.99389009, 1.01090199, 0.99097032, 1.00290362])[1] ≈
[22.210797046385544, 14.789399036653428]
end
@testset "loglikelihood" begin
test_f = pyhf_loglikelihoodof(x->([-x[1], -x[2]]), [1,2])
@test test_f(ones(2)) == -Inf
RR = loadmodel(joinpath(@__DIR__, "./pyhfjson/sample_normsys.json"))
likelihood, _ = cond_maximize(pyhf_logjointof(RR), 1.0, inits(RR)[2:end])
@test -2*likelihood <= 21.233919574137236 # better than pyhf value
likelihood, _ = cond_maximize(pyhf_logjointof(RR), 0.0, inits(RR)[2:end])
@test -2*likelihood <= 27.6021945001722
end
@testset "Full json MLE" begin
@test testmodel(joinpath(@__DIR__, "./pyhfjson/single_channel_big.json")) ≈ 80.67893633848638 rtol=0.0001
@test testmodel(joinpath(@__DIR__, "./pyhfjson/multi_channel.json")) ≈ 39.02800819146104 rtol=0.0001
@test testmodel(stateerror_shape) ≈ 16.66838236805484 rtol = 0.0001
end
@testset "qtilde CLs" begin
RR = loadmodel(joinpath(@__DIR__, "./pyhfjson/sample_normsys.json"))
A_model = AsimovModel(RR, 0.0)
A_LL = pyhf_logjointof(A_model)
Asimov_qtilde = LiteHF.get_teststat(A_LL, inits(A_model), T_qmutilde)
sqrtqmuA = sqrt(Asimov_qtilde(1.0))
SplusB, Bonly = asymptotic_dists(sqrtqmuA)
@test isapprox(expected_pvalue(SplusB, Bonly), [
0.002506004033129367,
0.01340873040275629,
0.06307942967469633,
0.23209511537562486,
0.5691591400023538
]; rtol=0.005
)
end
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | code | 410 | using LiteHF, BAT
pydict = load_pyhfjson("./test/sample.json");
pyhfmodel = build_pyhf(pydict);
# the 2-argument version does NOT include prior ("constraint") terms in likelihood
LL = pyhf_logjointpf(pyhfmodel)
mylikelihood(αs) = BAT.LogDVal(LL(αs))
posterior = PosteriorDensity(mylikelihood, pyhfmodel.priors)
@show bat_findmode(posterior).result
# (mu = 1.3064647047644158, theta = -0.06049852104383994)
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | code | 603 | using LiteHF, Turing, Optim
dict = load_pyhfjson("./test/pyhfjson/sample.json");
const pyhfmodel = build_pyhf(dict);
const priors_array = collect(values(pyhfmodel.priors))
@model function mymodel(observed)
αs ~ arraydist(priors_array)
expected = pyhfmodel.expected(αs)
@. observed ~ Poisson(expected)
end
observed_data = [34,22,13,11];
@show optimize(mymodel(observed_data), MAP(), pyhfmodel.inits)
#ModeResult with maximized lp of -13.51
# 2-element Named Vector{Float64}
# A │
# ────────────────┼───────────
# Symbol("αs[1]") │ 1.30648
# Symbol("αs[2]") │ -0.0605151
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | docs | 3369 | # LiteHF.jl
[](https://juliahep.github.io/LiteHF.jl/dev/)
[](https://github.com/JuliaHEP/LiteHF.jl/actions)
[](https://codecov.io/gh/JuliaHEP/LiteHF.jl)
[](https://zenodo.org/badge/latestdoi/482332815)
## TODO
- [ ] Implement teststatistics helper functions
- [ ] Re-structre the `PyHFModel` such that the `POI` component can be swapped out.
## Load `pyhf` JSON:
```julia
using LiteHF, Optim
dict = load_pyhfjson("./test/sample.json");
pyhfmodel = build_pyhf(dict);
LL = pyhf_logjointof(pyhfmodel)
@show Optim.maximizer(maximize(LL, pyhfmodel.inits))
# 2-element Vector{Float64}:
# 1.3064374172547253
# -0.060413406717672286
@show pyhfmodel.prior_names
# (:mu, :theta)
```
## `pyhf` JSON + Turing.jl:
```julia
using LiteHF, Turing, Optim
dict = load_pyhfjson("./test/sample.json");
const pyhfmodel = build_pyhf(dict);
# unpack `NamedTuple` into just an array of prior distributions
const priors_array = collect(values(priors(pyhfmodel)))
@model function mymodel(observed)
αs ~ arraydist(priors_array)
expected = pyhfmodel.expected(αs)
@. observed ~ Poisson(expected)
end
observed_data = [34,22,13,11];
@show optimize(mymodel(observed_data), MAP(), inits(pyhfmodel))
#ModeResult with maximized lp of -13.51
# 2-element Named Vector{Float64}
# A │
# ────────────────┼───────────
# Symbol("αs[1]") │ 1.30648
# Symbol("αs[2]") │ -0.0605151
```
## `pyhf` JSON + BAT.jl:
```julia
using LiteHF, BAT
pydict = load_pyhfjson("./test/sample.json");
pyhfmodel = build_pyhf(pydict);
LL = pyhf_logjointof(pyhfmodel)
mylikelihood(αs) = BAT.LogDVal(LL(αs))
posterior = PosteriorDensity(mylikelihood, priors(pyhfmodel))
@show bat_findmode(posterior).result
# (mu = 1.3064647047644158, theta = -0.06049852104383994)
```
## Manual Example
```julia
using Turing, LiteHF, Optim
###### Dummy data ######
const v_data = [34,22,13,11] # observed data
const v_sig = [2,3,4,5] # signal
const v_bg = [30,19,9,4] # BKG
const variations = [1,2,3,3]
###### Background and Signal modifier definitions ######
const bkgmodis =[
Histosys(v_bg .+ variations, v_bg .- variations),
Normsys(1.1, 0.9)
]
const bkgexp = ExpCounts(v_bg, ["theta1", "theta2"], bkgmodis)
const sigmodis = [Normfactor()];
const sigexp = ExpCounts(v_sig, ["mu"], sigmodis);
###### Expected counts as a function of μ and θs
function expected_bincounts2(μ, θs)
sigexp((mu = μ, )) + bkgexp((theta1=θs[1], theta2=θs[2]))
end
###### Turing.jl models
@model function binned_b(bincounts)
μ ~ Turing.Flat()
θs ~ filldist(Normal(), 2)
expected = expected_bincounts2(μ, θs)
@. bincounts ~ Poisson(expected)
end
###### Feed observed data to model to construct a posterior/likelihood object
const mymodel = binned_b(v_data);
###### Inference
chain_map = optimize(mymodel, MAP(), [1,1,1]) # initial guesses
display(chain_map)
```
Result:
```
ModeResult with maximized lp of -13.23
3-element Named Vector{Float64}
A │
────────────────┼───────────
:μ │ 1.0383
Symbol("θs[1]") │ 0.032979
Symbol("θs[2]") │ -0.0352236⏎
```
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | docs | 1400 | ## Frequentist <-> Bayesian usage
HistFactory and thus pyhf are not Bayesian procedure (some prefer to call them not frequentist
either, instead, they call what we do Likelihoodist).
However, there's a very straightforward connection between the two, with a subtle but important
twist -- evaluate prior at `x` (Bayesian) vs. shitfting "prior" to `x` and evlauate at `0` (pyhf).
To use a pyhf model in Bayesian procedure, it's almost enough to just take
`pyhf_logjointof(model::PyHFModel)` and sample posterior, bypassing all the
likelihood ratio, teststatistics, and Asimov data.
More specifically, these two likelihood are almost exactly the same:
- pyhf, frequentist likelihood of the bin counts (Poisson) + constraint terms for systematcs
- Bayesian joint likelihood of the bin counts (Poisson) + nuisance parameters priors.
In fact, if we only ever have priors like `Normal(0, 1)`, the above difference coincidentally
doesn't matter, because `pdf(x | Normal(0, 1)) === pdf(0 | Normal(x, 1))` -- it's numerically
equivalent to evaluate nuisance parameter prior at `x` (like a Bayesian), or shift the unit
Gaussian to `x` and evaluate at still `0`.
This numerical coincidence goes away for the (relaxed, continuous) Poisson prior we need
for MC Stat systematics. In this type of prior, the distribution is not symmetric around
the mean `λ` -- causing discrepency between the two procedures.
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | docs | 106 | # LiteHF.jl
Documentation for LiteHF.jl
```@autodocs
Modules = [LiteHF]
Order = [:type, :function]
```
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 65ed29fdaeaa926169e7d7a8be0b74dec60680db | docs | 298 | ```julia
function f(path)
pydict = load_pyhfjson(path)
pyhfmodel = build_pyhf(pydict)
pyhfmodel
end
R = f("./blah.json")
maximize(
R.LogLikelihood,
R.inits,
BFGS(),
Optim.Options(f_tol=1e-5, time_limit=10);
autodiff=:forward
);
```
| LiteHF | https://github.com/JuliaHEP/LiteHF.jl.git |
|
[
"MIT"
] | 0.1.0 | 7cfa221ecf6333b652d24c7216e1a986c8c65972 | code | 2621 | #Pkg.add("JuliaBerry")
#Pkg.add("PyCall")
#Run with `sudo` -- needed for keyboard.
using JuliaBerry
using JuliaBerry.ExplorerHat
using PyCall
@pyimport keyboard
function movef(x)
forward(ExplorerHat.motor[1], 50)
forward(ExplorerHat.motor[2], 50)
sleep(x)
stop(ExplorerHat.motor[1])
stop(ExplorerHat.motor[2])
end
function moveb(x)
on(ExplorerHat.led)
backward(ExplorerHat.motor[1], 50)
backward(ExplorerHat.motor[2], 50)
sleep(x)
stop(ExplorerHat.motor[1])
stop(ExplorerHat.motor[2])
on(ExplorerHat.led)
end
function movel(x)
forward(ExplorerHat.motor[2], 75)
forward(ExplorerHat.motor[1], 5)
sleep(x)
stop(ExplorerHat.motor[1])
stop(ExplorerHat.motor[2])
end
function mover(x)
forward(ExplorerHat.motor[2], 5)
forward(ExplorerHat.motor[1], 75)
sleep(x)
stop(ExplorerHat.motor[1])
stop(ExplorerHat.motor[2])
end
function movebl(x)
explorerhat.light.on()
backward(ExplorerHat.motor[2], 5)
backward(ExplorerHat.motor[1], 75)
sleep(x)
stop(ExplorerHat.motor[1])
stop(ExplorerHat.motor[2])
explorerhat.light.off()
end
function movebr(x)
explorerhat.light.on()
backward(ExplorerHat.motor[2], 75)
backward(ExplorerHat.motor[1], 5)
sleep(x)
stop(ExplorerHat.motor[1])
stop(ExplorerHat.motor[2])
explorerhat.light.off()
end
function square()
for i in 1:4
movef(3)
mover(2)
end
end
function eight()
for i in 1:3
movef(3)
mover(2)
end
movef(6)
for i in 1:3
movel(2)
movef(3)
end
end
function disco(x)
y = x/8
forward(ExplorerHat.motor[1], 50)
backward(ExplorerHat.motor[2], 50)
for i in 1:8
on(ExplorerHat.led)
sleep(y)
off(ExplorerHat.led)
sleep(y)
end
stop(ExplorerHat.motor[1])
stop(ExplorerHat.motor[2])
end
println("Starting main loop")
while true
if keyboard.is_pressed("w")
movef(0.01)
elseif keyboard.is_pressed("a")
movel(0.01)
elseif keyboard.is_pressed("d")
mover(0.01)
elseif keyboard.is_pressed("s")
moveb(0.01)
elseif keyboard.is_pressed("z")
movebl(0.01)
elseif keyboard.is_pressed("c")
movebr(0.01)
elseif keyboard.is_pressed("4")
square()
elseif keyboard.is_pressed("8")
eight()
elseif keyboard.is_pressed("l")
disco(7)
elseif keyboard.is_pressed(" ")
if is_on(ExplorerHat.output[1])
off(ExplorerHat.output[1])
else
on(ExplorerHat.output[1])
end
end
end
| JuliaBerry | https://github.com/JuliaBerry/JuliaBerry.jl.git |
|
[
"MIT"
] | 0.1.0 | 7cfa221ecf6333b652d24c7216e1a986c8c65972 | code | 2023 | module JuliaBerry
__precompile__(false)
using PiGPIO
export Pin, InputPin, OuputPin,
LED, Motor, forward, backward, speed, stop, on, off, is_on, is_off
# package code goes here
abstract type Thing
end
struct Pin <: Thing
pin::Int
function Pin(pin, mode)
PiGPIO.set_mode(_pi[], pin, mode)
new(pin)
end
end
InputPin(pin) = Pin(pin, PiGPIO.INPUT)
OutputPin(pin) = Pin(pin, PiGPIO.OUTPUT)
struct LED <: Thing
pin::Int
function LED(pin)
PiGPIO.set_mode(_pi[], pin, PiGPIO.OUTPUT)
new(pin)
end
end
function on(x::Thing)
PiGPIO.write(_pi[], x.pin, 1)
end
function off(x::Thing)
PiGPIO.write(_pi[], x.pin, 0)
end
on(x::Array{T}) where T<:Thing = on.(x)
off(x::Array{T}) where T<:Thing = off.(x)
is_off(x::Thing) = PiGPIO.read(_pi[], x.pin) == 0
is_on(x::Thing) = PiGPIO.read(_pi[], x.pin) == 1
struct Motor <: Thing
fw_pin::Int
bw_pin::Int
function Motor(fw_pin, bw_pin)
PiGPIO.set_mode(_pi[], fw_pin, PiGPIO.OUTPUT)
PiGPIO.set_mode(_pi[], bw_pin, PiGPIO.OUTPUT)
PiGPIO.set_PWM_range(_pi[], fw_pin, 100)
PiGPIO.set_PWM_range(_pi[], bw_pin, 100)
PiGPIO.set_PWM_dutycycle(_pi[], fw_pin, 0)
PiGPIO.set_PWM_dutycycle(_pi[], bw_pin, 0)
new(fw_pin, bw_pin)
end
end
function speed(x::Motor, speed::Int=100)
if speed>0
forward(x, speed)
elseif speed<0
backward(x, abs(speed))
end
end
function stop(x::Motor)
PiGPIO.set_PWM_dutycycle(_pi[], x.fw_pin, 0)
PiGPIO.set_PWM_dutycycle(_pi[], x.bw_pin, 0)
end
function forward(x::Motor, speed::Int)
PiGPIO.set_PWM_dutycycle(_pi[], x.fw_pin, speed)
PiGPIO.set_PWM_dutycycle(_pi[], x.bw_pin, 0)
end
function backward(x::Motor, speed::Int)
PiGPIO.set_PWM_dutycycle(_pi[], x.fw_pin, 0)
PiGPIO.set_PWM_dutycycle(_pi[], x.bw_pin, speed)
end
global const _pi = Ref{Pi}()
function __init__()
_pi[] = Pi()
end
#TODO remove
__init__()
setpi(p::Pi) = _pi[]=p
include("explorerhat.jl")
end # module
| JuliaBerry | https://github.com/JuliaBerry/JuliaBerry.jl.git |
|
[
"MIT"
] | 0.1.0 | 7cfa221ecf6333b652d24c7216e1a986c8c65972 | code | 1104 | module ExplorerHat
import JuliaBerry.Motor
import JuliaBerry.LED
import JuliaBerry.OutputPin
import JuliaBerry.InputPin
# Onboard LEDs above 1, 2, 3, 4
const LED1 = 4
const LED2 = 17
const LED3 = 27
const LED4 = 5
# Outputs via ULN2003A
const OUT1 = 6
const OUT2 = 12
const OUT3 = 13
const OUT4 = 16
# 5v Tolerant Inputs
const IN1 = 23
const IN2 = 22
const IN3 = 24
const IN4 = 25
# Motor, via DRV8833PWP Dual H-Bridge
const M1B = 19
const M1F = 20
const M2B = 21
const M2F = 26
# Number of times to update
# pulsing LEDs per second
const PULSE_FPS = 50
const PULSE_FREQUENCY = 1000
const DEBOUNCE_TIME = 20
const CAP_PRODUCT_ID = 107
function __init__()
global motor = [
Motor(M1F, M1B),
Motor(M2F, M2B)
]
global led = [
LED(LED1),
LED(LED2),
LED(LED3),
LED(LED4)
]
global output = [
OutputPin(OUT1),
OutputPin(OUT2),
OutputPin(OUT3),
OutputPin(OUT4)
]
global input = [
InputPin(OUT1),
InputPin(OUT2),
InputPin(OUT3),
InputPin(OUT4)
]
end
end
| JuliaBerry | https://github.com/JuliaBerry/JuliaBerry.jl.git |
|
[
"MIT"
] | 0.1.0 | 7cfa221ecf6333b652d24c7216e1a986c8c65972 | code | 142 | using JuliaBerry
@static if VERSION < v"0.7.0-DEV.2005"
using Base.Test
else
using Test
end
# write your own tests here
@test 1 == 2
| JuliaBerry | https://github.com/JuliaBerry/JuliaBerry.jl.git |
|
[
"MIT"
] | 0.1.0 | 7cfa221ecf6333b652d24c7216e1a986c8c65972 | docs | 592 | # JuliaBerry
An omnibus package with a high level API for controlling peripherals on the Raspberry Pi computer. Currently has support for the GPIO pins on the Pi, and the ExplorerHat.
## GPIO
### Generic Pins
```
x = OutputPin(17)
on(x)
off(x)
```
### LED
```
x = LED(17)
on(x)
off(x)
```
### Motors
```
x = Motor(17, 23)
forward(x, 50)
stop(x)
backward(x, 50)
stop(x)
```
## Explorer Hat
```
using JuliaBerry.ExplorerHat
on(ExplorerHat.led[1])
on.(ExplorerHat.led)
off.(ExplorerHat.led)
on(ExploerHat.output[1])
forward(ExplorerHat.motor[1], 75)
stop(ExplorerHat.motor[1])
```
| JuliaBerry | https://github.com/JuliaBerry/JuliaBerry.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | code | 480 | using FredMDQD
using Documenter
DocMeta.setdocmeta!(FredMDQD, :DocTestSetup, :(using FredMDQD); recursive=true)
makedocs(;
modules=[FredMDQD],
authors="Enrico Wegner",
sitename="FredMDQD.jl",
format=Documenter.HTML(;
canonical="https://enweg.github.io/FredMDQD.jl",
edit_link="main",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/enweg/FredMDQD.jl",
devbranch="main",
)
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | code | 232 | module FredMDQD
using DataFrames
using CSV
using Dates
using Pkg.Artifacts
include("utils.jl")
include("transforms.jl")
include("qd.jl")
include("md.jl")
include("search-appendix.jl")
export FredMD, FredQD, search_appendix
end
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | code | 2482 | function load_fred_md(fred_md::DataFrame)
fred_md = drop_missing_row(fred_md)
tcodes = Int.(collect(fred_md[1, 2:end])) # first column is the date
original = fred_md[2:end, :] # first two rows are transformation code and factor boolean
if length(split(original[1, 1], "/")[3]) < 4
@warn "FRED MD dates are ambiguous. I will therefore keep them as string"
else
original[!, 1] = Date.(original[:, 1], dateformat"mm/dd/yyyy")
end
transformed = copy(original)
for c=2:size(transformed, 2)
transformed[!, c] = fred_transform(Val(tcodes[c-1]), transformed[:, c])
end
return (original = original, tcodes = tcodes, transformed = transformed)
end
"""
FredMD(path::String)
FredMD(d::Date)
FredMD()
Load Fred MD data.
## Arguments
- `path::String`: Path to a manually downloaded version of Fred MD.
- `d::Date`: Date of a vintage.
## Details
- If no arguments are provided, the most recent version of Fred MD will be downloaded.
- If a `d::Date` is provided, the Fred MD vintage corresponding to the date will be downloaded.
- If a `path::String` is provided, then the Fred MD file at the `path` will be loaded.
## Notes
- Fred MD data is compiled by Michael W. McCracken at the Federal Reserve Bank of St. Louis. For more information check out the official website at https://research.stlouisfed.org/econ/mccracken/fred-databases/
"""
struct FredMD
original::DataFrame
transformed::DataFrame
tcodes::Vector{Union{Missing, Int64}}
function FredMD(path::String)
fred_md = CSV.read(path, DataFrame)
original, tcodes, transformed = load_fred_md(fred_md)
new(original, transformed, tcodes)
end
function FredMD(d::Date)
vintage = Dates.format(d, dateformat"yyyy-mm")
url = "https://files.stlouisfed.org/files/htdocs/fred-md/monthly/$(vintage).csv"
fred_md = CSV.read(download(url), DataFrame)
original, tcodes, transformed = load_fred_md(fred_md)
new(original, transformed, tcodes)
end
function FredMD()
@info "Retrieving the most recent FRED MD data. \n For publishable research it is better to specify the vintage using FredMD(d::Date)."
url = "https://files.stlouisfed.org/files/htdocs/fred-md/monthly/current.csv"
fred_md = CSV.read(download(url), DataFrame)
original, tcodes, transformed = load_fred_md(fred_md)
new(original, transformed, tcodes)
end
end
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | code | 2480 | function load_fred_qd(fred_qd::DataFrame)
fred_qd = drop_missing_row(fred_qd)
tcodes = Int.(collect(fred_qd[2, 2:end])) # first column is the date
original = fred_qd[3:end, :] # first two rows are transformation code and factor boolean
if length(split(original[1, 1], "/")[3]) < 4
@warn "FRED QD dates are ambiguous. I will therefore keep them as string"
else
original[!, 1] = Date.(original[:, 1], dateformat"mm/dd/yyyy")
end
transformed = copy(original)
for c = 2:size(transformed, 2)
transformed[!, c] = fred_transform(Val(tcodes[c-1]), transformed[:, c])
end
return (original=original, tcodes=tcodes, transformed=transformed)
end
"""
FredQD(path::String)
FredQD(d::Date)
FredQD()
Load Fred QD data.
## Arguments
- `path::String`: Path to a manually downloaded version of Fred QD.
- `d::Date`: Date of a vintage.
## Details
- If no arguments are provided, the most recent version of Fred QD will be downloaded.
- If a `d::Date` is provided, the Fred QD vintage corresponding to the date will be downloaded.
- If a `path::String` is provided, then the Fred QD file at the `path` will be loaded.
## Notes
- Fred QD data is compiled by Michael W. McCracken at the Federal Reserve Bank of St. Louis. For more information check out the official website at https://research.stlouisfed.org/econ/mccracken/fred-databases/
"""
struct FredQD
original::DataFrame
transformed::DataFrame
tcodes::Vector{Union{Missing,Int64}}
function FredQD(path::String)
fred_qd = CSV.read(path, DataFrame)
original, tcodes, transformed = load_fred_qd(fred_qd)
new(original, transformed, tcodes)
end
function FredQD(d::Date)
vintage = Dates.format(d, dateformat"yyyy-mm")
url = "https://files.stlouisfed.org/files/htdocs/fred-md/quarterly/$(vintage).csv"
fred_qd = CSV.read(download(url), DataFrame)
original, tcodes, transformed = load_fred_qd(fred_qd)
new(original, transformed, tcodes)
end
function FredQD()
@info "Retrieving the most recent FRED QD data. \n For publishable research it is better to specify the vintage using FredQD(d::Date)."
url = "https://files.stlouisfed.org/files/htdocs/fred-md/quarterly/current.csv"
fred_qd = CSV.read(download(url), DataFrame)
original, tcodes, transformed = load_fred_qd(fred_qd)
new(original, transformed, tcodes)
end
end
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | code | 1796 | APPENDIX_PATH = artifact"FredMDQD"
function search_appendix(path, needle; case_sensitive=false)
appendix = CSV.read(path, DataFrame)
if !isa(needle, Regex)
needle = case_sensitive ? Regex(needle) : Regex(needle, "i")
end
m = map(x -> contains.(string.(x), needle), eachcol(appendix))
m = reduce(hcat, m)
m = map(any, eachrow(m))
return(appendix[m, :])
end
"""
search_appendix(s::Symbol, args..., kwargs...)
Search the appendix for variable names.
## Arguments
- `s::Symbol`: Should be `:MD` for Fred MD and `:QD` for Fred QD.
- `needle::Union{String, Regex}`: Pattern to find in the appendix.
## Keyword Arguments
- `case_sensitive::Bool=false`: Should the search be case sensitive?
- `historic::Bool=false`: Should the search be in the current or historic appendix?
## Returns
- Returns a `DataFrame` of all the matches in the appendix.
"""
search_appendix(s::Symbol, args...; kwargs...) = search_appendix(Val(s), args...; kwargs...)
function search_appendix(::Val{:QD}, needle; case_sensitive=false, historic=false)
path_current = joinpath(APPENDIX_PATH, "FRED-QD-Appendix", "FRED-QD_updated_appendix.csv")
path_historic = joinpath(APPENDIX_PATH, "FRED-QD-Appendix", "FRED-QD_historic_appendix.csv")
path = historic ? path_historic : path_current
return search_appendix(path, needle; case_sensitive=case_sensitive)
end
function search_appendix(::Val{:MD}, needle; case_sensitive=false, historic=false)
path_current = joinpath(APPENDIX_PATH, "FRED-MD-Appendix", "FRED-MD_updated_appendix.csv")
path_historic = joinpath(APPENDIX_PATH, "FRED-MD-Appendix", "FRED-MD_historic_appendix.csv")
path = historic ? path_historic : path_current
return search_appendix(path, needle; case_sensitive=case_sensitive)
end
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | code | 1210 | """
return x
"""
function fred_transform(::Val{1}, x)
return x
end
"""
return Δx
"""
function fred_transform(::Val{2}, x)
return vcat(missing, x[2:end] - x[1:(end-1)])
end
"""
return Δ²x
"""
function fred_transform(::Val{3}, x)
x = fred_transform(Val(2), x)
return fred_transform(Val(2), x)
end
"""
return log(x)
"""
function fred_transform(::Val{4}, x)
return log.(x)
end
"""
return Δlog(x)
"""
function fred_transform(::Val{5}, x)
x = fred_transform(Val(4), x)
return fred_transform(Val(2), x)
end
"""
return Δ²log(x)
"""
function fred_transform(::Val{6}, x)
x = fred_transform(Val(4), x)
return fred_transform(Val(3), x)
end
"""
return Δ(xₜ₊₁ / xₜ - 1)
"""
function fred_transform(::Val{7}, x)
x = vcat(missing, x[2:end] ./ x[1:(end-1)] .- 1)
return fred_transform(Val(2), x)
end
@doc raw"""
Apply a FRED tranformation code
## Arguments
- `tcode`: FRED transformation code
- `x`: a vector of data
## Transformation Codes
The following transformation codes are currently supported
1. ``x``
2. ``\Delta x``
3. ``\Delta^2 x``
4. ``log(x)``
5. ``\Delta log(x)``
6. ``\Delta^2 log(x)``
7. ``Δ(x_{t+1} / x_t - 1)
"""
fred_transform(tcode::Int, x) = fred_transform(Val(tcode), x)
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | code | 347 | function drop_missing_row(df::DataFrame)
all_missing = map(row -> all(map(ismissing, row)), eachrow(df))
return df[(!).(all_missing), :]
end
"""
Provide information about `FredMDQD`.
"""
function info()
rootpath = artifact"FredMDQD"
path = joinpath(rootpath, "info.md")
info_text = read(path, String)
print(info_text)
end
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | code | 89 | using FredMDQD
using Test
@testset "FredMDQD.jl" begin
# Write your tests here.
end
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | docs | 3929 | # FredMDQD
[](https://enweg.github.io/FredMDQD.jl/stable/)
[](https://enweg.github.io/FredMDQD.jl/dev/)
[](https://github.com/enweg/FredMDQD.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/enweg/FredMDQD.jl)
## What is FredMDQD?
`FredMDQD` aims to make working with Fred MD and Fred QD data easy. It started as a small weekend project consisting of a set of scripts and evolved into a stand-alone package.
## What are Fred MD and Fred QD?
[Fred MD and Fred QD](https://research.stlouisfed.org/econ/mccracken/fred-databases/) are pre-compiled sets of monthly and quarterly indicators respectively. Both are compiled and maintained by Michael W. McCracken at the Federal Reserve Bank of St. Louis. Fred MD consists of 126 monthly indicators, while Fred QD consists of 245 quarterly indicators. The earliest observations for Fred MD are from January 1959 while the earliest observations for Fred QD are from Q1 1959.
## How do I load Fred MD or Fred QD data?
`FredMDQD` provides various ways to load Fred MD and Fred QD data. The easiest is to just load the current version of either of the data sets. This can be done using the following lines.
```julia
using FredMDQD
using DataFrames
fmd = FredMD() # Loads most recent version of Fred MD
fqd = FredQD() # Loads most recent version of Fred QD
```
`FredMD` and `FredQD` return a struct containing the following:
- `original::DataFrame`: Fred MD/QD data in without transformations.
- `transformed::DataFrame`: McCracken provides recommended transformation to make each variable stationary. The `transformed` DataFrame uses these recommended transformations.
- `tcodes::Vector{Int}`: provides the transformation codes used for each variable except the date column. The corresponding mathematical transformations are privided in `@doc fred_transform`.
`FredMDQD` also allows for loading a specific vintage of Fred MD/QD. This can be achieved by providing a date as an argument. To obtain the vintage from March 2022, the following code can be used.
```julia
using Dates
d = Date("2022/03", dateformat"yyyy/mm")
fmd = FredMD(d)
fqd = FredQD(d)
```
Lastly, if manual download of either Fred MD or QD exits, then `FredMDQD` can be used to load this manual download by providing a path to the file.
```julia
path_md = "path to manual download of Fred MD"
path_qd = "path to manual download of Fred QD"
fmd = FredMD(path_md)
fqd = FredQD(path_qd)
```
## What does a variable mean?
Fred MD/QD use abbreviations for variables that are not always intuitive. To find the meaning behind an abbreviation, or to find an abbreviation corresponding to a specific indicator, the `seach_appendix` function can be used. `search_appendix` searches through the Fred MD/QD appendices to find a specific search term. For example, Fred MD include the indicator DPCERA3M086SBEA. To find the meaning behind this indicator, we can run
```julia
search_appendix(:MD, "DPCERA3M086SBEA")
```
This returns a `DataFrame` search results matching our criteria. The indicator DPCERA3M086SBEA corresponds to "Real personal consumption expenditures".
Similarly, if we wanted to find an indicator in Fred QD corresponding to house prices, we can search for 'house' to see if any such indicator exists.
```julia
search_appendix(:QD, "house")
```
Thus, Fred QD includes USSTHPI corresponding to "All-Transactions House Price Index for the United States (Index 1980 Q1=100)".
## Where can I find more information?
More information can be found at the offical website for [Fred MD and Fred QD](https://research.stlouisfed.org/econ/mccracken/fred-databases/).
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 0.0.1 | 76f43ab7700a98292a7598543307ed5e7d44cbc0 | docs | 173 | ```@meta
CurrentModule = FredMDQD
```
# FredMDQD
Documentation for [FredMDQD](https://github.com/enweg/FredMDQD.jl).
```@index
```
```@autodocs
Modules = [FredMDQD]
```
| FredMDQD | https://github.com/enweg/FredMDQD.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | code | 834 | using PowerFlowData
using Documenter
using Tables
DocMeta.setdocmeta!(PowerFlowData, :DocTestSetup, :(using PowerFlowData); recursive=true)
makedocs(;
modules=[PowerFlowData],
authors="Nick Robinson <[email protected]> and contributors",
repo="https://github.com/nickrobinson251/PowerFlowData.jl/blob/{commit}{path}#{line}",
sitename="PowerFlowData.jl",
format=Documenter.HTML(
canonical="https://nickrobinson251.github.io/PowerFlowData.jl",
prettyurls=false,
),
pages=[
"Home" => "index.md",
"API" => "api.md",
"Alternatives" => "alternatives.md",
"Implementation" => "implementation.md",
],
strict=true,
checkdocs=:exports,
)
deploydocs(;
repo="github.com/nickrobinson251/PowerFlowData.jl",
devbranch="main",
push_preview=true,
)
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | code | 1007 | module PowerFlowData
using DocStringExtensions
using InlineStrings: InlineString1, InlineString3, InlineString15
using Parsers: Parsers, xparse, checkdelim!
using Parsers: codes, eof, invalid, invaliddelimiter, newline, valueok, peekbyte
using PrettyTables: pretty_table
using Tables
export parse_network
export Network
export CaseID, Buses, Buses30, Buses33, Branches, Branches30, Branches33
export FixedShunts, Loads, Generators, Transformers, AreaInterchanges
export SwitchedShunts, SwitchedShunts30, SwitchedShunts33
export TwoTerminalDCLines, TwoTerminalDCLines30, TwoTerminalDCLines33
export VSCDCLines, ImpedanceCorrections
export MultiTerminalDCLines, MultiTerminalDCLine, DCLineID, DCLineID30, DCLineID33
export ACConverters, DCBuses, DCLinks
export MultiSectionLineGroups, MultiSectionLineGroups30, MultiSectionLineGroups33
export Zones, InterAreaTransfers, Owners
export FACTSDevices, FACTSDevices30, FACTSDevices33
include("debug.jl")
include("types.jl")
include("parsing.jl")
end # module
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | code | 678 | # This is a simple `@debug` macro that we can use in the code
# without it slowing the code down, unlike `Base.@debug`.
const DEBUG_LEVEL = Ref(0)
function setdebug!(level::Int)
DEBUG_LEVEL[] = level
return nothing
end
"""
withdebug(level::Int) do
func()
end
"""
function withdebug(f, level)
lvl = DEBUG_LEVEL[]
try
setdebug!(level)
f()
finally
setdebug!(lvl)
end
end
"""
@debug 1 "msg"
"""
macro debug(level, msg)
esc(quote
if DEBUG_LEVEL[] >= $level
println(string("DEBUG: ", $(QuoteNode(__source__.file)), ":", $(QuoteNode(__source__.line)), " ", $msg))
end
end)
end
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | code | 17632 | ###
### parsing
###
# We currently support comma-delimited and space-delimited files,
# so just always create these two options, rather than having to
# create `Options` anew each time we parse a file.
const OPTIONS_COMMA = Parsers.Options(
sentinel=missing,
quoted=true,
openquotechar='\'',
closequotechar='\'',
stripquoted=true,
delim=',',
)
const OPTIONS_SPACE = Parsers.Options(
sentinel=missing,
quoted=true,
openquotechar='\'',
closequotechar='\'',
stripquoted=true,
delim=' ',
ignorerepeated=true,
wh1=0x00,
)
@inline getoptions(delim::Char) = ifelse(delim === ',', OPTIONS_COMMA, OPTIONS_SPACE)
getbytes(source::Vector{UInt8}) = source, 1, length(source)
getbytes(source::IOBuffer) = source.data, source.ptr, source.size
getbytes(source) = getbytes(read(source))
# `delim` can either be comma `','` or space `' '`
# The documented PSSE format specifies comma... but some files somehow use spaces instead.
# We look for commas in the first line and if found assume comma is the delim,
# but if none found we assume space is the delim.
function detectdelim(bytes, pos, len)
eof(bytes, pos, len) && return ',' # doesn't matter which we return
b = peekbyte(bytes, pos)
while b !== UInt8('\n') && b !== UInt8('\r')
b == UInt8(',') && return ','
pos += 1
eof(bytes, pos, len) && return ','
b = peekbyte(bytes, pos)
end
return ' '
end
"""
parse_network(source) -> Network
Read a PSS/E-format `.raw` Power Flow Data file and return a [`Network`](@ref) object.
The version of the PSS/E format can be specified with the `v` keyword, like `v=33`,
or else it will be automatically detected when parsing the file.
The delimiter can be specified with the `delim` keyword, like `delim=' '`,
or else it will be automatically detected when parsing the file.
"""
function parse_network(source; v::Union{Integer,Nothing}=nothing, delim::Union{Nothing,Char}=nothing)
@debug 1 "source = $source, v = $v"
bytes, pos, len = getbytes(source)
d = delim === nothing ? detectdelim(bytes, pos, len) : delim
options = getoptions(d)
if options.ignorerepeated # skip any delimiters at the very start of the file
pos = checkdelim!(bytes, pos, len, options)
end
caseid, pos = parse_idrow(CaseID, bytes, pos, len, options)
@debug 1 "Parsed CaseID: rev = $(caseid.rev), pos = $pos"
# when `v` not given, if `caseid.rev` missing we assume it is because data is v30 format
version = something(v, coalesce(caseid.rev, 30))
is_v33 = version == 33
@debug 1 "Set version = $version"
# Skip the 2 lines of comments
pos = next_line(bytes, pos, len, options)
pos = next_line(bytes, pos, len, options)
@debug 1 "Parsed comments: pos = $pos"
return if is_v33
parse_network33(source, version, caseid, bytes, pos, len, options)
else
parse_network30(source, version, caseid, bytes, pos, len, options)
end
end
function parse_network33(source, version, caseid, bytes, pos, len, options)
buses, pos = parse_records!(Buses33(len÷1000), bytes, pos, len, options)
nbuses = length(buses)
loads, pos = parse_records!(Loads(nbuses), bytes, pos, len, options)
fixed_shunts, pos = parse_records!(FixedShunts(), bytes, pos, len, options)
gens, pos = parse_records!(Generators(nbuses÷10), bytes, pos, len, options)
ngens = length(gens)
branches, pos = parse_records!(Branches33(nbuses), bytes, pos, len, options)
transformers, pos = parse_records!(Transformers(ngens*2), bytes, pos, len, options)
interchanges, pos = parse_records!(AreaInterchanges(), bytes, pos, len, options)
two_terminal_dc, pos = parse_records!(TwoTerminalDCLines33(), bytes, pos, len, options)
vsc_dc, pos = parse_records!(VSCDCLines(), bytes, pos, len, options)
impedance_corrections, pos = parse_records!(ImpedanceCorrections(), bytes, pos, len, options)
multi_terminal_dc, pos = parse_records!(MultiTerminalDCLines{DCLineID33}(), bytes, pos, len, options)
multi_section_lines, pos = parse_records!(MultiSectionLineGroups33(), bytes, pos, len, options)
zones, pos = parse_records!(Zones(), bytes, pos, len, options)
area_transfers, pos = parse_records!(InterAreaTransfers(), bytes, pos, len, options)
owners, pos = parse_records!(Owners(), bytes, pos, len, options)
facts, pos = parse_records!(FACTSDevices33(), bytes, pos, len, options)
switched_shunts, pos = parse_records!(SwitchedShunts33(nbuses÷11), bytes, pos, len, options)
return Network(
version,
caseid,
buses,
loads,
fixed_shunts,
gens,
branches,
transformers,
interchanges,
two_terminal_dc,
vsc_dc,
switched_shunts,
impedance_corrections,
multi_terminal_dc,
multi_section_lines,
zones,
area_transfers,
owners,
facts,
)
end
function parse_network30(source, version, caseid, bytes, pos, len, options)
buses, pos = parse_records!(Buses30(len÷1000), bytes, pos, len, options)
nbuses = length(buses)
loads, pos = parse_records!(Loads(nbuses), bytes, pos, len, options)
fixed_shunts = nothing
gens, pos = parse_records!(Generators(nbuses÷10), bytes, pos, len, options)
ngens = length(gens)
branches, pos = parse_records!(Branches30(nbuses), bytes, pos, len, options)
transformers, pos = parse_records!(Transformers(ngens*2), bytes, pos, len, options)
interchanges, pos = parse_records!(AreaInterchanges(), bytes, pos, len, options)
two_terminal_dc, pos = parse_records!(TwoTerminalDCLines30(), bytes, pos, len, options)
vsc_dc, pos = parse_records!(VSCDCLines(), bytes, pos, len, options)
switched_shunts, pos = parse_records!(SwitchedShunts30(nbuses÷11), bytes, pos, len, options)
impedance_corrections, pos = parse_records!(ImpedanceCorrections(), bytes, pos, len, options)
multi_terminal_dc, pos = parse_records!(MultiTerminalDCLines{DCLineID30}(), bytes, pos, len, options)
multi_section_lines, pos = parse_records!(MultiSectionLineGroups30(), bytes, pos, len, options)
zones, pos = parse_records!(Zones(), bytes, pos, len, options)
area_transfers, pos = parse_records!(InterAreaTransfers(), bytes, pos, len, options)
owners, pos = parse_records!(Owners(), bytes, pos, len, options)
facts, pos = parse_records!(FACTSDevices30(), bytes, pos, len, options)
return Network(
version,
caseid,
buses,
loads,
fixed_shunts,
gens,
branches,
transformers,
interchanges,
two_terminal_dc,
vsc_dc,
switched_shunts,
impedance_corrections,
multi_terminal_dc,
multi_section_lines,
zones,
area_transfers,
owners,
facts,
)
end
# identify `0` or `'0'`
@inline function _iszero(bytes, pos, len)
peekbyte(bytes, pos) == UInt8('0') ||
peekbyte(bytes, pos) == UInt8('\'') && !eof(bytes, pos+1, len) && peekbyte(bytes, pos+1) == UInt8('0')
end
function parse_records!(rec::R, bytes, pos, len, options)::Tuple{R, Int} where {R <: Records}
# Records terminated by specifying a bus number of zero or `Q`.
while !(
eof(bytes, pos, len) ||
_iszero(bytes, pos, len) ||
peekbyte(bytes, pos) == UInt8(' ') && !eof(bytes, pos+1, len) && _iszero(bytes, pos+1, len) ||
peekbyte(bytes, pos) == UInt8('Q')
)
_, pos = parse_row!(rec, bytes, pos, len, options)
end
pos = next_line(bytes, pos, len, options) # Move past a "0 bus" line.
@debug 1 "Parsed $R: nrows = $(length(rec)), pos = $pos"
return rec, pos
end
# Taken from `Parsers.checkcmtemptylines`
# TODO: move to Parsers.jl?
function next_line(bytes, pos, len, options)
eof(bytes, pos, len) && return pos
b = peekbyte(bytes, pos)
while b !== UInt8('\n') && b !== UInt8('\r')
pos += 1
eof(bytes, pos, len) && break
b = peekbyte(bytes, pos)
end
# Move forward to be past the `\r` or `\n` byte.
pos += 1
# if line ends `\r\n`, then we're at `\n`and need to move forward again.
if b === UInt8('\r') && !eof(bytes, pos, len) && peekbyte(bytes, pos) === UInt8('\n')
pos += 1
end
if options.ignorerepeated
# find the start of the values in the next line; if we're ignoring repeated
# delimiters, then we ignore any that start a row.
pos = checkdelim!(bytes, pos, len, options)
end
return pos
end
function parse_value(::Type{T}, bytes, pos, len, options) where {T}
res = xparse(T, bytes, pos, len, options)
code = res.code
if invalid(code)
if !(newline(code) && invaliddelimiter(code)) # not due to end-of-line comments
@warn codes(res.code) pos
end
end
pos += res.tlen
return res.val, pos, res.code
end
function parse_value!(rec, col::Int, ::Type{T}, bytes, pos, len, options) where {T}
val, pos, code = parse_value(nonmissingtype(T), bytes, pos, len, options)
push!(getfield(rec, col)::Vector{T}, val)
return rec, pos, code
end
@generated function parse_row!(rec::R, bytes, pos, len, options) where {R <: Records}
block = Expr(:block)
for col in 1:fieldcount(R)
T = eltype(fieldtype(R, col))
push!(block.args, quote
rec, pos, code = parse_value!(rec, $col, $T, bytes, pos, len, options)
end)
end
# @show block
return block
end
###
### transformers
###
function _setmissing(a::Int, b::Int)
exprs = Expr[]
for col in a:b
push!(exprs, :(push!(getfield(rec, $col), missing)))
end
return exprs
end
function _parse_values(::Type{R}, a::Int, b::Int) where {R <: Records}
exprs = Expr[]
for col in a:b
T = eltype(fieldtype(R, col))
push!(exprs, :((rec, pos, code) = parse_value!(rec, $col, $T, bytes, pos, len, options)))
end
return exprs
end
function _parse_maybemissing(R, col)
T = eltype(fieldtype(R, col))
return quote
if newline(code)
push!(getfield(rec, $col), missing)
else
(rec, pos, code) = parse_value!(rec, $col, $T, bytes, pos, len, options)
end
end
end
function _parse_maybemissing(R, col1, col2)
T1 = eltype(fieldtype(R, col1))
T2 = eltype(fieldtype(R, col2))
return quote
if newline(code)
push!(getfield(rec, $col1), missing)
push!(getfield(rec, $col2), missing)
else
(rec, pos, code) = parse_value!(rec, $col1, $T1, bytes, pos, len, options)
(rec, pos, code) = parse_value!(rec, $col2, $T2, bytes, pos, len, options)
end
end
end
function _parse_maybezero(R, col1, col2)
T1 = eltype(fieldtype(R, col1))
T2 = eltype(fieldtype(R, col2))
return quote
if newline(code)
push!(getfield(rec, $col1), zero($T1))
push!(getfield(rec, $col2), zero($T2))
else
(rec, pos, code) = parse_value!(rec, $col1, $T1, bytes, pos, len, options)
(rec, pos, code) = parse_value!(rec, $col2, $T2, bytes, pos, len, options)
end
end
end
function _parse_t2()
block = Expr(:block)
append!(block.args, _setmissing(EOL_COLS[1]+1+T2_COLS[2], EOL_COLS[2]))
append!(block.args, _parse_values(Transformers, EOL_COLS[2]+1, EOL_COLS[3]-1))
push!(block.args, _parse_maybemissing(Transformers, EOL_COLS[3]))
append!(block.args, _parse_values(Transformers, EOL_COLS[3]+1, EOL_COLS[3]+T2_COLS[4]))
append!(block.args, _setmissing(EOL_COLS[3]+1+T2_COLS[4], EOL_COLS[5]))
return block
end
function _parse_t3()
block = Expr(:block)
append!(block.args, _parse_values(Transformers, EOL_COLS[1]+1+T2_COLS[2], EOL_COLS[3]-1))
push!(block.args, _parse_maybemissing(Transformers, EOL_COLS[3]))
append!(block.args, _parse_values(Transformers, EOL_COLS[3]+1, EOL_COLS[4]-1))
push!(block.args, _parse_maybemissing(Transformers, EOL_COLS[4]))
append!(block.args, _parse_values(Transformers, EOL_COLS[4]+1, EOL_COLS[5]-1))
push!(block.args, _parse_maybemissing(Transformers, EOL_COLS[5]))
return block
end
# 2-winding transformers (T2) have a subset of the data for 3-winding transformers (T3).
# T2 has data over 4 lines, T3 has data for 5 lines:
# - Line 1 is the same for both
# - Line 2 has only 3 entries for T2 data, and more for T3
# - Line 3 is the same for both
# - Line 4 has only 2 entries for T2 data, and more for T3 (similar to line 2)
# - Line 5 only exists for T3 data
# We determine data is T2 if there is a newline after 3 entries of line 2, else it's T3.
# This means T2 data with a comment after the last entry on line 2 will fool us.
@generated function parse_row!(rec::R, bytes, pos, len, options) where {R <: Transformers}
block = Expr(:block)
# parse row 1
append!(block.args, _parse_values(R, 1, EOL_COLS[1]-7))
# parse possibly missing o2,f2,o3,f3,o4,f4
push!(block.args, _parse_maybemissing(Transformers, EOL_COLS[1]-6, EOL_COLS[1]-5))
push!(block.args, _parse_maybemissing(Transformers, EOL_COLS[1]-4, EOL_COLS[1]-3))
push!(block.args, _parse_maybemissing(Transformers, EOL_COLS[1]-2, EOL_COLS[1]-1))
push!(block.args, _parse_maybemissing(R, EOL_COLS[1])) # last col only in v33 data (not v30)
# parse first part of row 2
append!(block.args, _parse_values(R, EOL_COLS[1]+1, EOL_COLS[1]+T2_COLS[2]))
# now we can detect if it is two-winding or three-winding data
push!(block.args, :(newline(code) ? $(_parse_t2()) : $(_parse_t3())))
push!(block.args, :(return rec, pos))
# @show block
return block
end
###
### SwitchedShunts, ImpedanceCorrections
###
const N_SPECIAL = IdDict(
# SwitchedShunts can have anywhere between 1 - 8 `N` and `B` values in the data itself,
# if n2, b2, ..., n8, b8 are not present, we set them to zero.
# i.e. the last 14 = 7(n) + 7(b) columns reqire special handling.
SwitchedShunts30 => 14,
SwitchedShunts33 => 14,
# ImpedanceCorrections can have anywhere between 2 - 11 `T` and `F` values in the data itself,
# if t3, f3, ..., t11, f11 are not present, we set them to zero.
# i.e. the last 18 = 9(t) + 9(f) columns reqire special handling.
ImpedanceCorrections => 18,
# MultiSectionLineGroups can have between 1 - 9 `DUM_i` columns
MultiSectionLineGroups30 => 8,
MultiSectionLineGroups33 => 8,
# Loads have 2 extra columns in v33 compared to v30
Loads => 2,
# Generators have 1 - 4 `Oi`, `Fi` values, plus 2 extra columns in v33 compared to v30
Generators => 8, # 3*2 + 2
# Branches have 1 - 4 `Oi`, `Fi` values
Branches30 => 6, # 3*2
Branches33 => 6, # 3*2
)
@generated function parse_row!(rec::R, bytes, pos, len, options) where {R <: Union{SwitchedShunts, ImpedanceCorrections, Branches}}
block = Expr(:block)
N = fieldcount(R) - N_SPECIAL[R]
append!(block.args, _parse_values(R, 1, N))
coln = N + 1
colb = N + 2
for _ in 1:(N_SPECIAL[R] ÷ 2)
push!(block.args, _parse_maybezero(R, coln, colb))
coln += 2
colb += 2
end
push!(block.args, :(return rec, pos))
# @show block
return block
end
###
### Loads, Generators, MultiSectionLineGroups
###
@generated function parse_row!(
rec::R, bytes, pos, len, options
) where {R <: Union{Loads,Generators,MultiSectionLineGroups}}
block = Expr(:block)
N = fieldcount(R) - N_SPECIAL[R]
append!(block.args, _parse_values(R, 1, N))
for col in (N + 1):fieldcount(R)
push!(block.args, _parse_maybemissing(R, col))
end
push!(block.args, :(return rec, pos))
# @show block
return block
end
###
### MultiTerminalDCLines
###
function parse_row!(rec::R, bytes, pos, len, options) where {I, R <: MultiTerminalDCLines{I}}
line_id, pos = parse_idrow(I, bytes, pos, len, options)
nconv = line_id.nconv
converters = ACConverters(nconv)
for _ in 1:nconv
converters, pos = parse_row!(converters, bytes, pos, len, options)
end
ndcbs = line_id.ndcbs
dc_buses = DCBuses(ndcbs)
for _ in 1:ndcbs
dc_buses, pos = parse_row!(dc_buses, bytes, pos, len, options)
end
ndcln = line_id.ndcln
dc_links = DCLinks(ndcln)
for _ in 1:ndcln
dc_links, pos = parse_row!(dc_links, bytes, pos, len, options)
end
line = MultiTerminalDCLine(line_id, converters, dc_buses, dc_links)
push!(rec.lines, line)
return rec, pos
end
###
### IDRow
###
function parse_value!(args, ::Type{T}, bytes, pos, len, options) where {T}
res = xparse(T, bytes, pos, len, options)
code = res.code
val = ifelse(valueok(code), res.val, missing)
push!(args, val)
pos += res.tlen
return pos, code
end
@generated function parse_idrow(::Type{R}, bytes, pos, len, options) where {R <: IDRow}
block = Expr(:block)
nfields = fieldcount(R)
T = nonmissingtype(fieldtype(R, 1))
push!(block.args, quote
args = Any[]
(pos, code) = parse_value!(args, $T, bytes, pos, len, options)
end)
for i in 2:nfields
T = nonmissingtype(fieldtype(R, i))
push!(block.args, quote
if invalid(code) || newline(code)
push!(args, missing)
else
(pos, code) = parse_value!(args, $T, bytes, pos, len, options)
end
end)
end
push!(block.args, quote
if !newline(code)
pos = next_line(bytes, pos, len, options)
end
return R(args...), pos
end)
# @show block
return block
end
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | code | 120713 | ###
### types
###
abstract type IDRow <: Tables.AbstractRow end
# TODO: should the various bits of free text / comments / timestamps be in this struct?
# Data can look like:
# 0, 100.00 / PSS/E-30.3 WED, SEP 15 2021 21:04
# SE SNAPSHOT 09-15-2021 PEAK CASE 18:00
# FULL COPY OF ETC.
"""
$TYPEDEF
Case identification data.
# Fields
$TYPEDFIELDS
"""
struct CaseID <: IDRow
"""
IC Change code:
0 - base case (i.e., clear the working case before adding data to it).
1 - add data to the working case.
"""
ic::Int8
"System base MVA."
sbase::Float64
"PSSE revision number (if known)."
rev::Union{Int,Missing}
"""
Units of transformer ratings (see [`Transformers`](@ref)).
`xfrrat` ≤ 0 for MVA. `xfrrat` > 0 for current expressed as MVA.
"""
xfrrat::Union{Int8,Missing}
"""
Units of ratings of non-transformer branches (refer to Non-Transformer Branch Data).
`nxfrat` ≤ 0 for MVA. `nxfrat` > 0 for current expressed as MVA.
"""
nxfrat::Union{Int8,Missing}
"System base frequency in Hertz."
basfrq::Union{Float64,Missing}
end
function CaseID(; ic=0, sbase=100.0, rev=missing, xfrrat=missing, nxfrat=missing, basfrq=missing)
return CaseID(ic, sbase, rev, xfrrat, nxfrat, basfrq)
end
Tables.columnnames(::CaseID) = fieldnames(CaseID)
Tables.getcolumn(cid::CaseID, i::Int) = getfield(cid, i)
Tables.getcolumn(cid::CaseID, nm::Symbol) = getfield(cid, nm)
# So all tabular data records (buses, loads, ...) can be handled the same.
abstract type Records end
# Store data in column table so conversion to DataFrame efficient.
Tables.istable(::Type{<:Records}) = true
Tables.columnaccess(::Type{<:Records}) = true
Tables.columns(x::Records) = x
Tables.getcolumn(x::Records, i::Int) = getfield(x, i)
Tables.columnnames(R::Type{<:Records}) = fieldnames(R)
Tables.schema(x::R) where {R <: Records} = Tables.Schema(fieldnames(R), map(eltype, fieldtypes(R)))
Tables.rowcount(x::Records) = length(x) # faster than going via `columnnames`
Base.length(x::Records) = length(getfield(x, 1)::Vector)
Base.size(x::R) where {R <: Records} = (length(x), fieldcount(R))
Base.isempty(x::Records) = length(x) == 0
const BusNum = Int32
const AreaNum = Int16
const ZoneNum = Int16
const OwnerNum = Int16
const LineNum = Int16
"""
$TYPEDEF
Each network bus to be represented in PSSE is introduced by a bus data record.
The bus data record depends on the PSSE version:
- See [`Buses30`](@ref) for PSSE v30 files.
- See [`Buses33`](@ref) for PSSE v33 files.
"""
abstract type Buses <: Records end
"""
$TYPEDEF
Network bus data records (in PSSE v30 format).
Each bus data record includes not only data for the basic bus properties but also includes
information on an optionally connected shunt admittance to ground. That admittance can
represent a shunt capacitor or a shunt reactor (both with or without a real component) or a
shunt resistor. It must not represent line connected admittance, loads, line charging or
transformer magnetizing impedance, all of which are entered in other data categories.
# Fields
$TYPEDFIELDS
"""
struct Buses30 <: Buses
"Bus number (1 to 999997)."
i::Vector{BusNum}
"""
Alphanumeric identifier assigned to bus "I".
The name may be up to twelve characters and must be enclosed in single quotes.
NAME may contain any combination of blanks, uppercase letters, numbers and special characters, but the first character must not be a minus sign.
"""
name::Vector{InlineString15}
"Bus base voltage; entered in kV."
basekv::Vector{Float64}
"""
Bus type code:
1 - load bus or other bus without any generator boundary condition.
2 - generator or plant bus either regulating voltage or with a fixed reactive power (Mvar).
A generator that reaches its reactive power limit will no longer control voltage but rather hold reactive power at its limit.
3 - swing bus or slack bus.
It has no power or reactive limits and regulates voltage at a fixed reference angle.
4 - disconnected or isolated bus.
"""
ide::Vector{Int8} # 1, 2, 3 or 4
"""
Active component of shunt admittance to ground; entered in MW at one per unit voltage.
GL should not include any resistive admittance load, which is entered as part of load data.
"""
gl::Vector{Float64}
"""
Reactive component of shunt admittance to ground; entered in Mvar at one per unit voltage.
BL should not include any reactive impedance load, which is entered as part of load data;
line charging and line connected shunts, which are entered as part of non-transformer branch data;
or transformer magnetizing admittance, which is entered as part of transformer data.
BL is positive for a capacitor, and negative for a reactor or an inductive load.
"""
bl::Vector{Float64}
"Area number. 1 through the maximum number of areas at the current size level."
area::Vector{AreaNum}
"""
Zone number. 1 through the maximum number of zones at the current size level.
See [`Zones`](@ref).
"""
zone::Vector{ZoneNum}
"Bus voltage magnitude; entered in pu."
vm::Vector{Float64}
"Bus voltage phase angle; entered in degrees."
va::Vector{Float64}
"""
Owner number.
1 through the maximum number of owners at the current size level.
See [`Owners`](@ref).
"""
owner::Vector{OwnerNum}
end
"""
$TYPEDEF
Network bus data records (in PSSE v33 format).
# Fields
$TYPEDFIELDS
"""
struct Buses33 <: Buses
"Bus number (1 to 999997)."
i::Vector{BusNum}
"""
Alphanumeric identifier assigned to bus "I".
The name may be up to twelve characters and must be enclosed in single quotes.
NAME may contain any combination of blanks, uppercase letters, numbers and special characters, but the first character must not be a minus sign.
"""
name::Vector{InlineString15}
"Bus base voltage; entered in kV."
basekv::Vector{Float64}
"""
Bus type code:
1 - load bus or other bus without any generator boundary condition.
2 - generator or plant bus either regulating voltage or with a fixed reactive power (Mvar).
A generator that reaches its reactive power limit will no longer control voltage but rather hold reactive power at its limit.
3 - swing bus or slack bus.
It has no power or reactive limits and regulates voltage at a fixed reference angle.
4 - disconnected or isolated bus.
"""
ide::Vector{Int8} # 1, 2, 3 or 4
"Area number. 1 through the maximum number of areas at the current size level."
area::Vector{AreaNum}
"""
Zone number. 1 through the maximum number of zones at the current size level.
See [`Zones`](@ref).
"""
zone::Vector{ZoneNum}
"""
Owner number.
1 through the maximum number of owners at the current size level.
See [`Owners`](@ref).
"""
owner::Vector{OwnerNum}
"Bus voltage magnitude; entered in pu."
vm::Vector{Float64}
"Bus voltage phase angle; entered in degrees."
va::Vector{Float64}
"Normal voltage magnitude high limit; entered in pu. `nvhi` = 1.1 by default."
nvhi::Vector{Float64}
"Normal voltage magnitude low limit, entered in pu. `nvlo` = 0.9 by default."
nvlo::Vector{Float64}
"Emergency voltage magnitude high limit; entered in pu. `evhi` = 1.1 by default."
evhi::Vector{Float64}
"Emergency voltage magnitude low limit; entered in pu. `evlo` = 0.9 by default."
evlo::Vector{Float64}
end
"""
$TYPEDEF
Each network bus at which a load is to be represented must be specified in at least one load
data record. If multiple loads are to be represented at a bus, they must be individually
identified in a load data record for the bus with a different load identifier.
Each load at a bus can be a mixture of loads with different characteristics.
# Fields
$TYPEDFIELDS
"""
struct Loads <: Records
"Buses number, or extended buses name enclosed in single quotes."
i::Vector{BusNum}
"""
One- or two-character uppercase non blank alphanumeric load identifier used to distinguish among multiple loads at bus "I".
It is recommended that, at buses for which a single load is present, the load be designated as having the load identifier '1'.
"""
id::Vector{InlineString3} # TODO: confirm 3 is enough in practice, when whitespace can be present
"Initial load status of one for in-service and zero for out-of-service."
status::Vector{Bool}
"Area to which the load is assigned (1 through the maximum number of areas at the current size level)."
area::Vector{AreaNum}
"""
Zone to which the load is assigned (1 through the maximum number of zones at the current size level).
See [`Zones`](@ref).
"""
zone::Vector{ZoneNum}
"Active power component of constant MVA load; entered in MW."
pl::Vector{Float64}
"Reactive power component of constant MVA load; entered in Mvar."
ql::Vector{Float64}
"Active power component of constant current load; entered in MW at one per unit voltage."
ip::Vector{Float64}
"Reactive power component of constant current load; entered in Mvar at one per unit voltage."
iq::Vector{Float64}
"Active power component of constant admittance load; entered in MW at one per unit voltage."
yp::Vector{Float64}
"""
Reactive power component of constant admittance load; entered in Mvar at one per unit voltage.
YQ is a negative quantity for an inductive load and positive for a capacitive load.
"""
yq::Vector{Float64}
"""
Owner to which the load is assigned.
1 through the maximum number of owners at the current size level.
See [`Owners`](@ref).
"""
owner::Vector{OwnerNum}
"""
Load scaling flag of one for a scalable load and zero for a fixed load.
`scale` = 1 by default.
"""
scale::Vector{Union{Bool,Missing}}
"""
Interruptible load flag of one for an interruptible load for zero for a non interruptible load.
`intrpt`=0 by default.
"""
intrpt::Vector{Union{Bool,Missing}}
end
"""
$TYPEDEF
Each network bus at which fixed bus shunt is to be represented must be specified in at least
one fixed bus shunt data record. Multiple fixed bus shunts may be represented at a bus by
specifying more than one fixed bus shunt data record for the bus, each with a different shunt
identifier.
The admittance specified in the data record can represent a shunt capacitor or a shunt reactor
(both with or without a real component) or a shunt resistor. It must not represent line
connected admittance, switched shunts, loads, line charging or transformer magnetizing impedance,
all of which are entered in other data categories.
!!! compat "Not present in v30 files"
v30 files do not have `FixedShunts`; refer to [`Buses`](@ref) and [`SwitchedShunts`](@ref).
"""
struct FixedShunts <: Records
"Bus number, or extended bus name enclosed in single quotes. No default."
i::Vector{BusNum}
"""
One- or two-character uppercase non-blank alphanumeric shunt identifier used to
distinguish among multiple shunts at bus `i`. It is recommended that, at buses for which
a single shunt is present, the shunt be designated as having the shunt identifier 1.
`id` = 1 by default.
"""
id::Vector{InlineString3}
"Shunt status of one for in-service and zero for out-of-service. `status` = 1 by default."
status::Vector{Bool}
"""
Active component of shunt admittance to ground; entered in MW at one per unit voltage.
`gl` should not include any resistive impedance load, which is entered as part of load
data (see [`Loads`](@ref). `gl` = 0.0 by default.
"""
gl::Vector{Float64}
"""
Reactive component of shunt admittance to ground; entered in Mvar at one per unit voltage.
`bl` should not include any reactive impedance load, which is entered as part of load data
(see [`Loads`](@ref)); line charging and line connected shunts, which are entered as part
of non-transformer branch data (see [`Branches`](@ref)); transformer magnetizing
admittance, which is entered as part of transformer data (see [`Transformers`](@ref));
or switched shunt admittance, which is entered as part of switched shunt data (see
[`SwitchedShunts`](@ref). `bl` is positive for a capacitor, and negative for a reactor
or an inductive load. `bl` = 0.0 by default.
"""
bl::Vector{Float64}
end
"""
$TYPEDEF
Each network bus to be represented as a generator or plant bus in PSS/E must be specified
in a generator data record. In particular, each bus specified in the bus data input with a
type code of two (2) or three (3) must have a generator data record entered for it.
# Fields
$TYPEDFIELDS
"""
struct Generators <: Records
"Bus number, or extended bus name enclosed in single quotes."
i::Vector{BusNum}
"""
One- or two-character uppercase non blank alphanumeric machine identifier used to distinguish among multiple machines at bus "I".
It is recommended that, at buses for which a single machine is present, the machine be designated as having the machine identifier ’1’.
ID = ’1’ by default.
"""
id::Vector{InlineString3} # TODO: confirm 3 is enough in practice, when whitespace can be present
"Generator active power output; entered in MW. PG = 0.0 by default."
pg::Vector{Float64}
"""
Generator reactive power output; entered in Mvar.
QG needs to be entered only if the case, as read in, is to be treated as a solved case.
QG = 0.0 by default.
"""
qg::Vector{Float64}
"""
Maximum generator reactive power output; entered in Mvar.
For fixed output gen- erators (i.e., nonregulating), QT must be equal to the fixed Mvar output.
QT = 9999.0 by default.
"""
qt::Vector{Float64}
"""
Minimum generator reactive power output; entered in Mvar.
For fixed output generators, QB must be equal to the fixed Mvar output.
QB = -9999.0 by default.
"""
qb::Vector{Float64}
"Regulated voltage setpoint; entered in pu. VS = 1.0 by default."
vs::Vector{Float64}
"""
Bus number, or extended bus name enclosed in single quotes,
of a remote type 1 or 2 bus whose voltage is to be regulated by this plant to the value specified by VS.
If bus IREG is other than a type 1 or 2 bus, bus "I" regulates its own voltage to the value specified by VS.
IREG is entered as zero if the plant is to regulate its own voltage and must be zero for a type three (swing) bus.
IREG = 0 by default.
"""
ireg::Vector{BusNum}
"""
Total MVA base of the units represented by this machine; entered in MVA.
This quantity is not needed in normal power flow and equivalent onstruction work,
but is required for switching studies, fault analysis, and dynamic simulation.
MBASE = system base MVA by default.
"""
mbase::Vector{Float64}
"""
Complex machine impedance, ZSORCE; entered in pu on MBASE base.
This data is not needed in normal power flow and equivalent construction work,
but is required for switching studies, fault analysis, and dynamic simulation.
For dynamic simulation, this impedance must be set equal to the unsaturated subtransient impedance for those generators to be modeled by subtransient level machine models,
and to unsaturated transient impedance for those to be modeled by classical or transient level models.
For short-circuit studies, the saturated subtransient or transient impedance should be used.
ZR = 0.0 by default.
"""
zr::Vector{Float64}
"See `zr`. ZX = 1.0 by default."
zx::Vector{Float64}
"""
Step-up transformer impedance, XTRAN; entered in pu on MBASE base.
XTRAN should be entered as zero if the step-up transformer is explicitly modeled as a network branch and bus "I" is the terminal bus.
RT+jXT = 0.0 by default.
"""
rt::Vector{Float64}
"See `rt`. RT+jXT = 0.0 by default."
xt::Vector{Float64}
"""
Step-up transformer off-nominal turns ratio; entered in pu.
GTAP is used only if XTRAN is nonzero.
GTAP = 1.0 by default.
"""
gtap::Vector{Float64}
"""
Initial machine status of one for in-service and zero for out-of-service.
STAT = 1 by default.
"""
stat::Vector{Bool}
"""
Percent of the total Mvar required to hold the voltage at the bus controlled by this bus "I" that are to be contributed by the generation at bus "I";
RMPCT must be positive.
RMPCT is needed if IREG specifies a valid remote bus and there is more than one local or remote voltage controlling device
(plant, switched shunt, FACTS device shunt element, or VSC DC line converter) controlling the voltage at bus IREG to a setpoint.
RMPCT is needed also if bus "I" itself is being controlled locally or remotely by one or more other setpoint mode voltage controlling devices.
RMPCT = 100.0 by default.
"""
rmpct::Vector{Float64}
"Maximum generator active power output; entered in MW. PT = 9999.0 by default."
pt::Vector{Float64}
"Minimum generator active power output; entered in MW. PB = -9999.0 by default."
pb::Vector{Float64}
"""
Owner number (1 through the maximum number of owners at the current size level).
Each machine may have up to four owners. See [`Owners`](@ref).
By default, `o1` is the owner to which bus `i` is assigned and `o2`, `o3`, and `o4` are
zero.
"""
o1::Vector{OwnerNum}
"""
Fraction of total ownership assigned to owner `oi`; each `fi` must be positive.
The `fi` values are normalized such that they sum to 1.0 before they are placed in the working case.
By default, each `fi` is 1.0.
"""
f1::Vector{Union{Float64,Missing}}
o2::Vector{Union{OwnerNum,Missing}}
f2::Vector{Union{Float64,Missing}}
o3::Vector{Union{OwnerNum,Missing}}
f3::Vector{Union{Float64,Missing}}
o4::Vector{Union{OwnerNum,Missing}}
f4::Vector{Union{Float64,Missing}}
"""
Wind machine control mode; `wmod` is used to indicate whether a machine is a wind machine,
and, if it is, the type of reactive power limits to be imposed.
* 0 for a machine that is not a wind machine.
* 1 for a wind machine for which reactive power limits are specified by QT and QB.
* 2 for a wind machine for which reactive power limits are determined from the machine’s
active power output and `wpf`; limits are of equal magnitude and opposite sign.
* 3 for a wind machine with a fixed reactive power setting determined from the machine’s
active power output and `wpf`; when `wpf` is positive, the machine’s reactive power has
the same sign as its active power; when `wpf` is negative, the machine’s reactive power
has the opposite sign of its active power.
`wmod` = 0 by default.
"""
wmod::Vector{Union{Int8,Missing}} # 0, 1, 2, or 3
"""
Power factor used in calculating reactive power limits or output when `wmod` is 2 or 3.
`wpf` = 1.0 by default.
"""
wpf::Vector{Union{Float64,Missing}}
end
"""
$TYPEDEF
The branches data record depends on the PSSE version:
- See [`Branches30`](@ref) for PSSE v30 files.
- See [`Branches33`](@ref) for PSSE v33 files.
"""
abstract type Branches <: Records end
for v in (30, 33)
T = Symbol(:Branches, v)
met_doc, met_col = if v == 33
:("""
Metered end flag.
* ≤1 to designate bus `i` as the metered end.
* ≥2 to designate bus `j` as the metered end.
`met` = 1 by default.
"""),
:(met::Vector{Int8})
else
:(""), :("")
end
compat = if v == 33
"In PSSE v33, to represent shunts connected to buses, that shunt data should be entered in [`FixedShunts`](@ref) and/or [`SwitchedShunts`](@ref) data records."
else
"In PSSE v30, to represent shunts connected to buses, that shunt data should be entered in the [`Buses`](@ref) data records."
end
@eval begin
"""
$TYPEDEF
In PSS/E, the basic transmission line model is an Equivalent Pi connected between network buses.
Data for shunt equipment units, such as reactors, which are connected to and switched with the line,
are entered in the same data record.
!!! compat "Shunts connected to buses"
$($compat)
!!! note "Transformers"
Branches to be modeled as transformers are not specified in this data category;
rather, they are specified in the [`Transformers`](@ref) data category.
# Fields
$TYPEDFIELDS
"""
struct $T <: Branches
"Branch \"from bus\" number, or extended bus name enclosed in single quotes."
i::Vector{BusNum}
"""
Branch "to bus" number, or extended bus name enclosed in single quotes.
"J" is entered as a negative number, or with a minus sign before the first character of the extended bus name,
to designate it as the metered end; otherwise, bus "I" is assumed to be the metered end.
"""
j::Vector{BusNum}
"""
One- or two-character uppercase nonblank alphanumeric branch circuit identifier;
the first character of CKT must not be an ampersand "&".
It is recommended that single circuit branches be designated as having the circuit identifier '1'.
CKT = '1' by default.
"""
ckt::Vector{InlineString3}
"Branch resistance; entered in pu. A value of R must be entered for each branch."
r::Vector{Float64}
"Branch reactance; entered in pu. A nonzero value of X must be entered for each branch."
x::Vector{Float64}
"Total branch charging susceptance; entered in pu. B = 0.0 by default."
b::Vector{Float64}
"""
First loading rating; entered in MVA.
If RATEA is set to 0.0, the default value, this branch will not be included in any examination of circuit loading.
Ratings are entered as:
``MVA_{rated} = sqrt(3) × E_{base} × I_{rated} × 10^{-6}`` where:
- ``E_{base}`` is the base line-to-line voltage in volts of the buses to which the terminal of the branch is connected.
- ``I_{rated}`` is the branch rated phase current in amperes.
"""
rate_a::Vector{Float64}
"Second loading rating; entered in MVA. RATEB = 0.0 by default."
rate_b::Vector{Float64}
"Third loading rating; entered in MVA. RATEC = 0.0 by default."
rate_c::Vector{Float64}
"""
Complex admittance of the line shunt at the bus "I" end of the branch; entered in pu.
BI is negative for a line connected reactor and positive for line connected capacitor.
GI + jBI = 0.0 by default.
"""
gi::Vector{Float64}
"""
Complex admittance of the line shunt at the bus "I" end of the branch; entered in pu.
BI is negative for a line connected reactor and positive for line connected capacitor.
GI + jBI = 0.0 by default.
"""
bi::Vector{Float64}
"""
Complex admittance of the line shunt at the bus "J" end of the branch; entered in pu.
BJ is negative for a line connected reactor and positive for line connected capacitor.
GJ + jBJ = 0.0 by default.
"""
gj::Vector{Float64}
"""
Complex admittance of the line shunt at the bus "J" end of the branch; entered in pu.
BJ is negative for a line connected reactor and positive for line connected capacitor.
GJ + jBJ = 0.0 by default.
"""
bj::Vector{Float64}
"""
Initial branch status where 1 designates in-service and 0 designates out-of-service.
ST = 1 by default.
"""
st::Vector{Bool}
$met_doc
$met_col
"Line length; entered in user-selected units. LEN = 0.0 by default."
len::Vector{Float64}
"""
Owner number; 1 through the maximum number of owners at the current size level.
Each branch may have up to four owners. See [`Owners`](@ref).
By default, `o1` is the owner to which bus `i` is assigned and `o2`, `o3`, and `o4` are zero.
"""
o1::Vector{OwnerNum}
"""
Fraction of total ownership assigned to owner ``O_i``; each ``F_i`` must be positive.
The ``fi` values are normalized such that they sum to 1.0 before they are placed in the working case.
By default, each `fi` is 1.0.
"""
f1::Vector{Float64}
o2::Vector{Union{OwnerNum,Missing}}
f2::Vector{Union{Float64,Missing}}
o3::Vector{Union{OwnerNum,Missing}}
f3::Vector{Union{Float64,Missing}}
o4::Vector{Union{OwnerNum,Missing}}
f4::Vector{Union{Float64,Missing}}
end
end # eval
end
###
### Transformers
###
"""
$TYPEDEF
Each AC transformer to be represented in PSS/E is introduced through transformer data records
that specify all the data required to model transformers in power flow calculations, with
one exception.
That exception is a set of ancillary data, comprising transformer impedance correction records,
which define the manner in which transformer impedance changes as off-nominal turns ratio or
phase shift angle is adjusted. Those data records are described in Transformer Impedance
Correction Records, [`ImpedanceCorrections`](@ref).
Both two-winding and three-winding transformers are specified in the transformer data records.
The data records for the two-winding transformer are common to the three-winding transformer;
the data block for two-winding transformers is a subset of the data required for three-winding
transformers.
# Fields
$TYPEDFIELDS
"""
struct Transformers <: Records
# first row
"""
The bus number, or extended bus name enclosed in single quotes, of the bus to which the
first winding is connected. The transformer’s magnetizing admittance is modeled on winding one.
The first winding is the only winding of a two-winding transformer whose tap ratio or
phase shift angle may be adjusted by the power flow solution activities;
any winding(s) of a three-winding transformer may be adjusted. No default is allowed.
"""
i::Vector{BusNum}
"""
The bus number, or extended bus name enclosed in single quotes, of the bus to which the
second winding is connected. This winding may have a fixed, off-nominal tap ratio
assigned to it. No default is allowed.
"""
j::Vector{BusNum}
"""
The bus number, or extended bus name enclosed in single quotes, of the bus to which the
third winding is connected. Zero is used to indicate that no third winding is present.
_Always equal to zero for a two-winding transformer._
"""
k::Vector{BusNum}
"""
One- or two-character uppercase nonblank alphanumeric transformer circuit identifier;
the first character of `ckt` must not be an ampersand ('&').
"""
ckt::Vector{InlineString3}
"""
The winding data I/O code which defines the units in which the turns ratios `windv1` and
`windv2` are specified (the units of `rma1` and `rmi1` are also governed by `cw` when
`|cod1|` is 1 or 2):
* 1 for off-nominal turns ratio in pu of winding bus base voltage;
* 2 for winding voltage in kV.
`cw` = 1 by default.
"""
cw::Vector{Int8} # 1 or 2
"""
The impedance data I/O code that defines the units in which the winding impedances
`r1_2` and `x1_2` are specified:
* 1 for resistance and reactance in pu on system base quantities;
* 2 for resistance and reactance in pu on a specified base MVA and winding bus base voltage;
* 3 for transformer load loss in watts and impedance magnitude in pu on a specified base MVA
and winding bus base voltage.
`cz` = 1 by default.
"""
cz::Vector{Int8} # 1, 2 or 3
"""
The magnetizing admittance I/O code that defines the units in which `mag1` and `mag2` are specified:
* 1 for complex admittance in pu on system base quantities;
* 2 for no load loss in watts and exciting current in pu on winding one to two base MVA
and nominal voltage.
`cm` = 1 by default.
"""
cm::Vector{Int8} # 1 or 2
"""
When `cm` is 1, `mag1` is the magnetizing conductance in pu on system base quantities;
when `cm` is 2, `mag1` is the no load loss in watts.
`mag1` = 0.0 by default.
"""
mag1::Vector{Float64}
"""
When `cm` is 1, `mag2` is the magnetizing susceptance in pu on system base quantities;
when `cm` is 2, `mag2` is the exciting current in pu on winding one to two base MVA (`sbase1_2`)
and nominal voltage (`nomv1`).
`mag2` = 0.0 by default.
"""
mag2::Vector{Float64}
"""
The nonmetered end code of either:
* 1 (for the winding one bus), or
* 2 (for the winding two bus).
`nmetr` = 2 by default.
"""
nmetr::Vector{Int8} # 1 or 2
"""
An alphanumeric identifier assigned to the transformer. The name may be up to twelve characters.
`name` may contain any combination of blanks, uppercase letters, numbers and special characters.
`name` is twelve blanks by default.
"""
name::Vector{InlineString15}
"""
The initial transformer status, where 1 designates in-service and 0 designates out-of-service.
`stat` = 1 by default.
"""
stat::Vector{Bool}
"""
An owner number; (1 through the maximum number of owners at the current size level).
Each transformer may have up to four owners. See [`Owners`](@ref).
By default, O1 is the owner to which bus "I" is assigned
"""
o1::Vector{OwnerNum}
"""
The fraction of total ownership assigned to owner `Oi`; each Fi must be positive.
The Fi values are normalized such that they sum to 1.0 before they are placed in the working case.
By default, each `fi` is 1.0.
"""
f1::Vector{Float64}
o2::Vector{Union{OwnerNum,Missing}}
f2::Vector{Union{Float64,Missing}}
o3::Vector{Union{OwnerNum,Missing}}
f3::Vector{Union{Float64,Missing}}
o4::Vector{Union{OwnerNum,Missing}}
f4::Vector{Union{Float64,Missing}}
"""
Alphanumeric identifier specifying vector group based on transformer winding connections and phase angles.
`vecgrp` value is used for information purpose only.
`vecgrp` is 12 blanks by default.
"""
vecgrp::Vector{Union{InlineString15,Missing}}
# second row
"""
The measured impedance of the transformer between the buses to which its first and second
windings are connected (see also `x1_2`).
* When `cz` is 1, `r1_2` is the resistance in pu on system base quantities;
* when `cz` is 2, `r1_2` is the resistance in pu on winding one to two base MVA (`sbase1_2`) and winding one bus base voltage;
* when `cz` is 3, `r1_2` is the load loss in watts.
`r1_2` = 0.0 by default.
"""
r1_2::Vector{Float64}
"""
The measured impedance of the transformer between the buses to which its first and second
windings are connected (see also `r1_2`).
* When `cz` is 1, `x1_2` is the reactance in pu on system base quantities;
* when `cz` is 2, `x1_2` is the reactance in pu on winding one to two base MVA (`sbase1_2`) and winding one bus base voltage;
* when `cz` is 3, `x1_2` is the impedance magnitude in pu on winding one to two base MVA (`sbase1_2`) and winding one bus base voltage.
`x1_2` has no default.
"""
x1_2::Vector{Float64}
"""
The winding one to two base MVA of the transformer.
`sbase1_2` = `sbase` (the system base MVA) by default.
"""
sbase1_2::Vector{Float64}
# second row, but 3-winding transformers only
"""
The measured impedance of a three-winding transformer between the buses to which its
second and third windings are connected (see also `x2_3`).
* When `cz` is 1, `r2_3` is the resistance in pu on system base quantities;
* when `cz` is 2, `r2_3` is the resistance in pu on winding two to three base MVA (`sbase2_3`) and winding two bus base voltage;
* when `cz` is 3, `r2_3` is the load loss in watts
`r2_3` = 0.0 by default.
_Ignored for a two-winding transformer._
"""
r2_3::Vector{Union{Float64, Missing}}
"""
The measured impedance of a three-winding transformer between the buses to which its
second and third windings are connected (see also `x2_3`).
* When `cz` is 1, `x2_3` is the reactance in pu on system base quantities;
* when `cz` is 2, `x2_3` is the reactance in pu on winding one to two base MVA (`sbas2_3`) and winding one bus base voltage;
* when `cz` is 3, `x2_3` is the impedance magnitude in pu on winding two to three base MVA (`sbase2_3`) and winding two bus base voltage.
`x2_3` has no default.
_Ignored for a two-winding transformer._
"""
x2_3::Vector{Union{Float64, Missing}}
"""
The winding two to three base MVA of a three-winding transformer; ignored for a two-winding
transformer.
`sbase2_3` = `sbase` (the system base MVA) by default.
_Ignored for a two-winding transformer._
"""
sbase2_3::Vector{Union{Float64, Missing}}
"""
The measured impedance of a three-winding transformer between the buses to which its
third and first windings are connected (see also `x3_1`).
* When `cz` is 1, `r3_1` is the resistance in pu on system base quantities;
* when `cz` is 2, `r3_1` is the resistance in pu on winding three to one base MVA (`sbase3_1`) and winding three bus base voltage;
* when `cz` is 3, `r3_1` is the load loss in watts
`r3_1` = 0.0 by default.
_Ignored for a two-winding transformer._
"""
r3_1::Vector{Union{Float64, Missing}}
"""
The measured impedance of a three-winding transformer between the buses to which its
third and first windings are connected (see also `x3_1`).
* When `cz` is 1, `x3_1` is the reactance in pu on system base quantities;
* when `cz` is 2, `x3_1` is the reactance in pu on winding three to one base MVA (`sbas3_1`) and winding three bus base voltage;
* when `cz` is 3, `x3_1` is the impedance magnitude in pu on winding three to one base MVA (`sbase3_1`) and winding three bus base voltage.
`x3_1` has no default.
_Ignored for a two-winding transformer._
"""
x3_1::Vector{Union{Float64, Missing}}
"""
The winding three to one base MVA of a three-winding transformer.
`sbase3_1` = `sbase` (the system base MVA) by default.
_Ignored for a two-winding transformer._
"""
sbase3_1::Vector{Union{Float64, Missing}}
"""
The voltage magnitude at the hidden star point bus; entered in pu.
`vmstar` = 1.0 by default.
_Ignored for a two-winding transformer._
"""
vmstar::Vector{Union{Float64, Missing}}
"""
The bus voltage phase angle at the hidden star point bus; entered in degrees.
`anstar` = 0.0 by default.
_Ignored for a two-winding transformer._
"""
anstar::Vector{Union{Float64, Missing}}
# third row
"""
When `cw` is 1, `windv1` is the winding one off-nominal turns ratio in pu of winding one bus base voltage,
and windv1 = 1.0 by default.
When `cw` is 2, `windv1` is the actual winding one voltage in kV,
and `windv1` is equal to the base voltage of bus "I" by default.
"""
windv1::Vector{Float64}
"""
The nominal (rated) winding one voltage in kV, or zero to indicate that nominal winding
one voltage is to be taken as the base voltage of bus "I".
`nomv1` is used only in converting magnetizing data between per unit admittance values
and physical units when `cm` is 2.
`nomv1` = 0.0 by default.
"""
nomv1::Vector{Float64}
"""
The winding one phase shift angle in degrees.
`ang1` is positive for a positive phase shift from the winding one side to the winding two side (for a two-winding transformer).
`ang1` must be greater than -180.0 and less than or equal to +180.0.
`ang1` = 0.0 by default.
"""
ang1::Vector{Float64}
"""
The first winding’s first rating entered in MVA (not current expressed in MVA).
"""
rata1::Vector{Float64}
"""
The first winding’s second rating entered in MVA (not current expressed in MVA).
"""
ratb1::Vector{Float64}
"""
The first winding’s third rating entered in MVA (not current expressed in MVA).
"""
ratc1::Vector{Float64}
"""
The transformer control mode for automatic adjustments of the winding one tap or
phase shift angle during power flow solutions:
* 0 for no control (fixed tap and phase shift);
* ±1 for voltage control;
* ±2 for reactive power flow control;
* ±3 for active power flow control;
* ±4 for control of a DC line quantity.
If the control mode is entered as a positive number, automatic adjustment of this transformer
winding is enabled when the corresponding adjustment is activated during power flow solutions;
a negative control mode suppresses the automatic adjustment of this transformer winding.
`cod1` = 0 by default.
"""
cod1::Vector{Int8} # one of: -4, -3, -2, -1, 0, 1, 2, 3, 4
"""
The bus number, or extended bus name enclosed in single quotes, of the bus whose voltage
is to be controlled by the transformer turns ratio adjustment option of the power flow
solution activities when `cod1` is 1.
`cont1` should be non-zero only for voltage controlling transformer windings.
`cont1` may specify a bus other than "I", "J", or "K"; in this case, the sign of `cont1`
defines the location of the controlled bus relative to the transformer winding.
If `cont1` is entered as a positive number, the ratio is adjusted as if bus `cont1` is on the winding two side of the transformer;
if `cont1` is entered as a negative number, the ratio is adjusted as if bus `|cont1|` is on the winding one side of the transformer.
`cont1` = 0 by default.
"""
cont1::Vector{BusNum}
"""
`rma1` is the upper limit (and `rmi1` the lower limit) of either:
* Off-nominal turns ratio in pu of winding one bus base voltage when `|cod1|` is 1 or 2 and `cw` is 1;
`rma1` = 1.1 and `rmi1` = 0.9 by default.
* Actual winding one voltage in kV when `|cod1|` is 1 or 2 and `cw` is 2. No default is allowed.
* Phase shift angl e in degrees when `|cod1|` is 3. No default is allowed.
* Not used when `|cod1|` is 0 or 4;
`rma1` = 1.1 and `rmi1` = 0.9 by default.
"""
rma1::Vector{Float64}
"The lower limit to `rma1`'s upper limit. See `rma1` for details."
rmi1::Vector{Float64}
"""
`vma1` is the upper limit (and `vmi1` the lower limit) of either:
* Voltage at the controlled bus (bus `|cont1|`) in pu when `|cod1|` is 1. `vma1` = 1.1 and `vmi1` = 0.9 by default.
* Reactive power flow into the transformer at the winding one bus end in Mvar when `|cod1|` is 2. no default is allowed.
* Active power flow into the transformer at the winding one bus end in MW when `|cod1|` is 3. no default is allowed.
* Not used when `|cod1|` is 0 or 4; `vma1` = 1.1 and `vmi1` = 0.9 by default.
"""
vma1::Vector{Float64}
"The lower limit to `vma1`'s upper limit. See `vma1` for details."
vmi1::Vector{Float64}
"""
The number of tap positions available; used when `cod1` is 1 or 2.
`ntp1` must be between 2 and 9999.
`ntp1` = 33 by default.
"""
ntp1::Vector{Int16}
"""
The number of a transformer impedance correction record if this transformer winding’s
impedance is to be a function of either off-nominal turns ratio or phase shift angle,
or 0 if no transformer impedance correction is to be applied to this transformer winding.
See [`ImpedanceCorrections`](@ref).
`tab1` = 0 by default.
"""
tab1::Vector{Int}
"""
The load drop compensation impedance for voltage controlling transformers entered in pu
on system base quantities; used when `cod1` is 1.
`cr1` + j`cx1` = 0.0 by default.
"""
cr1::Vector{Float64}
"See `cr1` for details."
cx1::Vector{Float64}
"""
Winding connection angle in degrees; used when `cod1` is 5.
There are no restrictions on the value specified for `cnxa1`;
if it is outside of the range from -90.0 to +90.0, `cnxa1` is normalized to within this range.
`cnxa1` = 0.0 by default.
"""
cnxa1::Vector{Union{Float64,Missing}}
# fourth row
"""
When `cw` is 1, `windv2` is the winding two off-nominal turns ratio in pu of winding two bus base voltage,
and `windv2` = 1.0 by default.
When `cw` is 2, `windv2` is the actual winding two voltage in kV,
and `windv2` is equal to the base voltage of bus `j` by default.
"""
windv2::Vector{Float64}
"""
The nominal (rated) winding two voltage in kV, or zero to indicate that nominal winding
two voltage is to be taken as the base voltage of bus `j`.
`nomv2` is present for information purposes only; it is not used in any of the calculations
for modeling the transformer.
`nomv2` = 0.0 by default.
"""
nomv2::Vector{Float64}
# fourth row, but 3-winding transformers only
"""
The winding two phase shift angle in degrees.
`ang2` is positive for a positive phase shift from the winding two side to the "T"
(or star) point bus.
`ang2` must be greater than -180.0 and less than or equal to +180.0.
`ang2` = 0.0 by default.
_Ignored for a two-winding transformer._
"""
ang2::Vector{Union{Float64, Missing}}
"""
The second winding’s first rating entered in MVA (not current expressed in MVA).
_Ignored for a two-winding transformer._
"""
rata2::Vector{Union{Float64, Missing}}
"""
The second winding’s second rating entered in MVA (not current expressed in MVA).
_Ignored for a two-winding transformer._
"""
ratb2::Vector{Union{Float64, Missing}}
"""
The second winding’s third rating entered in MVA (not current expressed in MVA).
_Ignored for a two-winding transformer._
"""
ratc2::Vector{Union{Float64, Missing}}
"""
The transformer control mode for automatic adjustments of the winding two tap or phase
shift angle during power flow solutions:
* 0 for no control (fixed tap and phase shift);
* ±1 for voltage control;
* ±2 for reactive power flow control;
* ±3 for active power flow control.
If the control mode is entered as a positive number, automatic adjustment of this transformer
winding is enabled when the corresponding adjustment is activated during power flow solutions;
a negative control mode suppresses the automatic adjustment of this transformer winding.
`cod2` = 0 by default.
_Ignored for a two-winding transformer._
"""
cod2::Vector{Union{Int8, Missing}} # one of: -3, -2, -1, 0, 1, 2, 3
"""
The bus number, or extended bus name enclosed in single quotes, of the bus whose voltage
is to be controlled by the transformer turns ratio adjustment option of the power flow
solution activities when `cod2` is 1.
`cont2` should be nonzero only for voltage controlling transformer windings.
`cont2` may specify a bus other than `i`, `j`, or `k`; in this case, the sign of
`cont2` defines the location of the controlled bus relative to the transformer winding.
If `cont2` is entered as a positive number, or a quoted extended bus name, the ratio is
adjusted as if bus `cont2` is on the winding one or winding three side of the transformer;
if `cont2` is entered as a negative number, or a quoted extended bus name with a minus sign
preceding the first character, the ratio is adjusted as if bus `|cont2|` is on the winding
two side of the transformer. `cont2` = 0 by default.
_Ignored for a two-winding transformer._
"""
cont2::Vector{Union{BusNum, Missing}}
"""
`rma2` is the upper limit (and `rmi2` the lower limit) of either:
* Off-nominal turns ratio in pu of winding two bus base voltage when `|cod2|` is 1 or 2 and `cw` is 1;
`rma2` = 1.1 and `rmi2` = 0.9 by default.
* Actual winding one voltage in kV when `|cod2|` is 1 or 2 and `cw` is 2. No default is allowed.
* Phase shift angle in degrees when `|cod2|` is 3. No default is allowed.
* Not used when `|cod2|` is 0;
`rma2` = 1.1 and `rmi2` = 0.9 by default.
_Ignored for a two-winding transformer._
"""
rma2::Vector{Union{Float64, Missing}}
"""
The lower limit to `rma2`'s upper limit. See `rma2` for details.
_Ignored for a two-winding transformer._
"""
rmi2::Vector{Union{Float64, Missing}}
"""
`vma2` is the upper limit (and `vmi2` the lower limit) of either:
* Voltage at the controlled bus (bus `|cont2|`) in pu when `|cod2|` is 1.
`vma2` = 1.1 and `vmi2` = 0.9 by default.
* Reactive power flow into the transformer at the winding two bus end in Mvar when `|cod2|` is 2.
No default is allowed.
* Active power flow into the transformer at the winding two bus end in MW when `|cod2|` is 3.
No default is allowed.
* Not used when `|cod2|` is 0; `vma2` = 1.1 and `vmi2` = 0.9 by default.
_Ignored for a two-winding transformer._
"""
vma2::Vector{Union{Float64, Missing}}
"""
The lower limit to `vma1`'s upper limit. See `vma1` for details.
_Ignored for a two-winding transformer._
"""
vmi2::Vector{Union{Float64, Missing}}
"""
The number of tap positions available; used when `cod2` is 1 or 2.
`ntp2` must be between 2 and 9999.
`ntp2` = 33 by default.
_Ignored for a two-winding transformer._
"""
ntp2::Vector{Union{Int16, Missing}}
"""
The number of a transformer impedance correction record if this transformer winding’s
impedance is to be a function of either off-nominal turns ratio or phase shift angle,
or 0 if no transformer impedance correction is to be applied to this transformer winding.
See [`ImpedanceCorrections`](@ref).
`tab2` = 0 by default.
_Ignored for a two-winding transformer._
"""
tab2::Vector{Union{Int, Missing}}
"""
The load drop compensation impedance for voltage controlling transformers entered in pu
on system base quantities; used when `cod2` is 1.
`cr2` + j`cx2` = 0.0 by default.
_Ignored for a two-winding transformer._
"""
cr2::Vector{Union{Float64, Missing}}
"""
See `cr2` for details.
_Ignored for a two-winding transformer._
"""
cx2::Vector{Union{Float64, Missing}}
"""
Winding connection angle in degrees; used when `cod2` is 5.
There are no restrictions on the value specified for `cnxa2`;
if it is outside of the range from -90.0 to +90.0, `cnxa2` is normalized to within this range.
`cnxa2` = 0.0 by default.
"""
cnxa2::Vector{Union{Float64,Missing}}
# fifth row, only 3-winding transformers
"""
When `cw` is 1, `windv3` is the winding three off-nominal turns ratio in pu of winding three bus base voltage,
and windv3 = 1.0 by default.
When `cw` is 2, `windv3` is the actual winding three voltage in kV,
and `windv3` is equal to the base voltage of bus `k` by default.
_Ignored for a two-winding transformer._
"""
windv3::Vector{Union{Float64, Missing}}
"""
The nominal (rated) winding three voltage in kV, or zero to indicate that nominal winding
two voltage is to be taken as the base voltage of bus `j`.
`nomv3` is present for information purposes only; it is not used in any of the calculations
for modeling the transformer.
`nomv3` = 0.0 by default.
_Ignored for a two-winding transformer._
"""
nomv3::Vector{Union{Float64, Missing}}
"""
The winding three phase shift angle in degrees.
`ang3` is positive for a positive phase shift from the winding two side to the "T"
(or star) point bus.
`ang3` must be greater than -180.0 and less than or equal to +180.0.
`ang3` = 0.0 by default.
_Ignored for a two-winding transformer._
"""
ang3::Vector{Union{Float64, Missing}}
"""
The third winding’s first rating entered in MVA (not current expressed in MVA).
_Ignored for a two-winding transformer._
"""
rata3::Vector{Union{Float64, Missing}}
"""
The third winding’s second rating entered in MVA (not current expressed in MVA).
_Ignored for a two-winding transformer._
"""
ratb3::Vector{Union{Float64, Missing}}
"""
The third winding’s third rating entered in MVA (not current expressed in MVA).
_Ignored for a two-winding transformer._
"""
ratc3::Vector{Union{Float64, Missing}}
"""
The transformer control mode for automatic adjustments of the winding three tap or phase
shift angle during power flow solutions:
* 0 for no control (fixed tap and phase shift);
* ±1 for voltage control;
* ±2 for reactive power flow control;
* ±3 for active power flow control.
If the control mode is entered as a positive number, automatic adjustment of this transformer
winding is enabled when the corresponding adjustment is activated during power flow solutions;
a negative control mode suppresses the automatic adjustment of this transformer winding.
`cod3` = 0 by default.
_Ignored for a two-winding transformer._
"""
cod3::Vector{Union{Int8, Missing}} # one of: -3, -2, -1, 0, 1, 2, 3
"""
The bus number, or extended bus name enclosed in single quotes, of the bus whose voltage
is to be controlled by the transformer turns ratio adjustment option of the power flow
solution activities when `cod3` is 1.
`cont3` should be nonzero only for voltage controlling transformer windings.
`cont3` may specify a bus other than `i`, `j`, or `k`; in this case, the sign of
`cont3` defines the location of the controlled bus relative to the transformer winding.
If `cont3` is entered as a positive number, or a quoted extended bus name, the ratio is
adjusted as if bus `cont3` is on the winding one or winding two side of the transformer;
if `cont3` is entered as a negative number, or a quoted extended bus name with a minus sign
preceding the first character, the ratio is adjusted as if bus `|cont3|` is on the winding
three side of the transformer. `cont3` = 0 by default.
_Ignored for a two-winding transformer._
"""
cont3::Vector{Union{BusNum, Missing}}
"""
`rma3` is the upper limit (and `rmi3` the lower limit) of either:
* Off-nominal turns ratio in pu of winding three bus base voltage when `|cod3|` is 1 or 2 and `cw` is 1;
`rma3` = 1.1 and `rmi3` = 0.9 by default.
* Actual winding one voltage in kV when `|cod3|` is 1 or 2 and `cw` is 2. No default is allowed.
* Phase shift angle in degrees when `|cod3|` is 3. No default is allowed.
* Not used when `|cod3|` is 0;
`rma3` = 1.1 and `rmi3` = 0.9 by default.
_Ignored for a two-winding transformer._
"""
rma3::Vector{Union{Float64, Missing}}
"""
The lower limit to `rma3`'s upper limit. See `rma3` for details.
_Ignored for a two-winding transformer._
"""
rmi3::Vector{Union{Float64, Missing}}
"""
`vma3` is the upper limit (and `vmi3` the lower limit) of either:
* Voltage at the controlled bus (bus `|cont3|`) in pu when `|cod3|` is 1.
`vma3` = 1.1 and `vmi3` = 0.9 by default.
* Reactive power flow into the transformer at the winding three bus end in Mvar when `|cod3|` is 2.
No default is allowed.
* Active power flow into the transformer at the winding two bus end in MW when `|cod3|` is 3.
No default is allowed.
* Not used when `|cod3|` is 0; `vma3` = 1.1 and `vmi3` = 0.9 by default.
_Ignored for a two-winding transformer._
"""
vma3::Vector{Union{Float64, Missing}}
"""
The lower limit to `vma3`'s upper limit. See `vma3` for details.
_Ignored for a two-winding transformer._
"""
vmi3::Vector{Union{Float64, Missing}}
"""
The number of tap positions available; used when `cod3` is 1 or 2.
`ntp3` must be between 2 and 9999.
`ntp3` = 33 by default.
_Ignored for a two-winding transformer._
"""
ntp3::Vector{Union{Int16, Missing}}
"""
The number of a transformer impedance correction record if this transformer winding’s
impedance is to be a function of either off-nominal turns ratio or phase shift angle,
or 0 if no transformer impedance correction is to be applied to this transformer winding.
See [`ImpedanceCorrections`](@ref).
`tab3` = 0 by default.
_Ignored for a two-winding transformer._
"""
tab3::Vector{Union{Int, Missing}}
"""
The load drop compensation impedance for voltage controlling transformers entered in pu
on system base quantities; used when `cod3` is 1.
`cr3` + j`cx3` = 0.0 by default.
_Ignored for a two-winding transformer._
"""
cr3::Vector{Union{Float64, Missing}}
"""
See `cr3` for details.
_Ignored for a two-winding transformer._
"""
cx3::Vector{Union{Float64, Missing}}
"""
Winding connection angle in degrees; used when `cod3` is 5.
There are no restrictions on the value specified for `cnxa3`;
if it is outside of the range from -90.0 to +90.0, `cnxa3` is normalized to within this range.
`cnxa3` = 0.0 by default.
"""
cnxa3::Vector{Union{Float64,Missing}}
end
# Constants for Transformers data.
#
# Transformers data is a bit special, as records have 2 possible schemas
# see https://github.com/nickrobinson251/PowerFlowData.jl/issues/17
#
# Each two-winding transformer ("T2") is 4 lines with (20, 3, 16, 2) columns each in v30,
# or (21, 3, 17, 2) columns each in v33.
# In both cases, the o2,f2,o3,f3,o4,f4 on row 1 may or may not be present.
# Each three-winding transformer ("T3") is 5 lines with (14, 11, 16, 16, 16) columns each in v30,
# or (15, 11, 17, 17, 17) columns each in v33.
# `TX_COLS[i]` is the (expected) number of columns on line i of X-winding transformer data (in v33).
const T2_COLS = (21, 3, 17, 2)
const T3_COLS = (21, 11, 17, 17, 17)
@assert sum(T3_COLS) == fieldcount(Transformers)
# The "columns" (fields) which come at the end of a line in the data.
const EOL_COLS = cumsum(T3_COLS)
# The fields of the struct that contain data for two-winding transformers.
const T2_FIELDS = (
1:T2_COLS[1]...,
(EOL_COLS[1] + 1):(EOL_COLS[1] + T2_COLS[2])...,
(EOL_COLS[2] + 1):(EOL_COLS[2] + T2_COLS[3])...,
(EOL_COLS[3] + 1):(EOL_COLS[3] + T2_COLS[4])...,
)
_is_t2(x::Transformers) = all(ismissing, x.cx3)
# Since 2-winding data is a subset of 3-winding data, check at runtime if we have any
# 3-winding data and if not just return the subset of columns required for 2-winding data.
function Tables.columnnames(x::R) where {R <: Transformers}
if _is_t2(x)
fieldname.(R, T2_FIELDS)
else
fieldnames(R)
end
end
function Tables.schema(x::R) where {R <: Transformers}
cols = Tables.columnnames(x)
typs = eltype.(fieldtype.(R, cols))
return Tables.Schema(cols, typs)
end
# `DataFrame` just calls `columns`, so we need that to return something that respects the
# schema. For `Transformers` schema depends on the values, so cannot rely on the
# default `columns(::Records)` method.
Tables.columns(x::Transformers) = Tables.columntable(Tables.schema(x), x)
# Again, respect the schema.
Base.size(x::Transformers) = (length(x), length(Tables.columnnames(x)))
###
### AreaInterchanges
###
"""
$TYPEDEF
Area interchange is a required net export of power from, or net import of power to, a
specific area. This does not imply that the power is destined to be transferred to or from
any other specific area. To specify transfers between specific pairs of areas see
`InterAreaTransfers`.
# Fields
$TYPEDFIELDS
"""
struct AreaInterchanges <: Records
"""
Area number (1 through the maximum number of areas at the current size level)
"""
i::Vector{AreaNum}
"""
Bus number, or extended bus name enclosed in single quotes, of the area slack bus for
area interchange control. The bus must be a generator (type two) bus in the specified
area. Any area containing a system swing bus (type three) must have either that swing
bus or a bus number of zero specified for its area slack bus number.
`isw` = 0 by default.
"""
isw::Vector{BusNum}
"""
Desired net interchange leaving the area (export); entered in MW.
`pdes` = 0.0 by default.
"""
pdes::Vector{Float64}
"""
Interchange tolerance bandwidth; entered in MW.
`ptol` = 10.0 by default.
"""
ptol::Vector{Float64}
"""
Alphanumeric identifier assigned to area I.
The name may contain up to twelve characters.
`arname` is set to twelve blanks by default.
"""
arname::Vector{InlineString15}
end
###
### Two-terminal DC Lines
###
"""
$TYPEDEF
The TwoTerminalDCLines data record depends on the PSSE version:
- See [`TwoTerminalDCLines30`](@ref) for PSSE v30 files.
- See [`TwoTerminalDCLines33`](@ref) for PSSE v33 files.
"""
abstract type TwoTerminalDCLines <: Records end
for v in (30, 33)
T = Symbol(:TwoTerminalDCLines, v)
firstdoc, firstcol = if v == 30
:("The DC line number."),
:(i::Vector{LineNum})
else
:("""
The non-blank alphanumeric identifier assigned to this DC line.
Each two-terminal DC line must have a unique `name.
`name` may be up to twelve characters and may contain any combination of blanks, uppercase letters,
numbers and special characters. name must be enclosed in single or double quotes if it contains any
blanks or special characters. No default allowed.
"""),
:(name::Vector{InlineString15})
end
@eval begin
"""
$TYPEDEF
The two-terminal DC transmission line model is used to simulate either a point-to-point
system with rectifier and inverter separated by a bipolar or mono-polar transmission system
or a Back-to-Back system where the rectifier and inverter are physically located at the same
site and separated only by a short bus-bar.
The data requirements fall into three groups:
* Control parameters and set-points
* Converter transformers
* The DC line characteristics
The steady-state model comprising this data enables not only power flow analysis but also
establishes the initial steady-state for dynamic analysis.
# Fields
$TYPEDFIELDS
"""
struct $T <: TwoTerminalDCLines
# Data for each TwoTerminalDCLine is specified on three consecutive lines of the file.
# First line: defines various line quantities and control parameters
$firstdoc
$firstcol
"""
Control mode:
* 0 for blocked,
* 1 for power,
* 2 for current.
`mdc` = 0 by default.
"""
mdc::Vector{Int8} # 0, 1, or 2
"""
The DC line resistance; entered in ohms.
No default.
"""
rdc::Vector{Float64}
"""
Current (amps) or power (MW) demand.
When `mdc` is 1, a positive value of `setvl` specifies desired power at the rectifier
and a negative value specifies desired inverter power.
No default.
"""
setvl::Vector{Float64}
"""
Scheduled compounded DC voltage; entered in kV.
No default.
"""
vschd::Vector{Float64}
"""
Mode switch DC voltage; entered in kV.
When the inverter DC voltage falls below this value and the line is in power control mode
(i.e. `mdc` = 1), the line switches to current control mode with a desired current
corresponding to the desired power at scheduled DC voltage.
`vcmod` = 0.0 by default.
"""
vcmod::Vector{Float64}
"""
Compounding resistance; entered in ohms.
Gamma and/or TAPI is used to attempt to hold the compounded voltage (``vdci + dccur ∗ rcomp``) at `vschd`.
* To control the inverter end DC voltage VDCI, set `rcomp` to zero;
* to control the rectifier end DC voltage VDCR, set `rcomp` to the DC line resistance, `rdc`;
* otherwise, set `rcomp` to the appropriate fraction of `rdc`.
`rcomp` = 0.0 by default.
"""
rcomp::Vector{Float64}
"""
Margin entered in per unit of desired DC power or current.
This is the fraction by which the order is reduced when alpha is at its minimum (`alfmn`)
and the inverter is controlling the line current.
`delti` = 0.0 by default.
"""
delti::Vector{Float64}
"""
Metered end code of either "R" (for rectifier) or "I" (for inverter).
`meter` = "I" by default.
"""
meter::Vector{InlineString1} # I or R
"""
Minimum compounded DC voltage; entered in kV.
Only used in constant gamma operation (i.e. when `gammx` = `gammn`) when TAPI is held constant
and an AC transformer tap is adjusted to control DC voltage
(i.e. when `ifi`, `iti`, and `idi` specify a two-winding transformer).
`dcvmin` = 0.0 by default.
"""
dcvmin::Vector{Float64}
"""
Iteration limit for capacitor commutated two-terminal DC line Newton solution procedure.
`cccitmx` = 20 by default.
"""
cccitmx::Vector{Int32}
"""
Acceleration factor for capacitor commutated two-terminal DC line Newton solution procedure.
`cccacc` = 1.0 by default.
"""
cccacc::Vector{Float64}
# Second line: defines rectifier end data quantities and control parameters
"""
Rectifier converter bus number, or extended bus name enclosed in single quotes.
No default.
"""
ipr::Vector{BusNum}
"""
Number of bridges in series (rectifier).
No default.
"""
nbr::Vector{Int32}
"""
Nominal maximum rectifier firing angle; entered in degrees.
No default.
"""
alfmx::Vector{Float64}
"""
Minimum steady-state rectifier firing angle; entered in degrees.
No default.
"""
alfmn::Vector{Float64}
"""
Rectifier commutating transformer resistance per bridge; entered in ohms.
No default allowed.
"""
rcr::Vector{Float64}
"""
Rectifier commutating transformer reactance per bridge; entered in ohms.
No default allowed.
"""
xcr::Vector{Float64}
"""
Rectifier primary base AC voltage; entered in kV.
No default.
"""
ebasr::Vector{Float64}
"""
Rectifier transformer ratio.
`trr` = 1.0 by default.
"""
trr::Vector{Float64}
"""
Rectifier tap setting.
`tapr` = 1.0 by default.
"""
tapr::Vector{Float64}
"""
Maximum rectifier tap setting.
`tmxr` = 1.5 by default.
"""
tmxr::Vector{Float64}
"""
Minimum rectifier tap setting.
`tmnr` = 0.51 by default.
"""
tmnr::Vector{Float64}
"""
Rectifier tap step; must be positive.
`stpr` = 0.00625 by default.
"""
stpr::Vector{Float64}
"""
Rectifier firing angle measuring bus number, or extended bus name enclosed in single quotes.
The firing angle and angle limits used inside the DC model are adjusted by the difference
between the phase angles at this bus and the AC/DC interface (i.e. the converter bus, `ipr`).
`icr` = 0 by default.
"""
icr::Vector{BusNum}
"""
Winding one side "from bus" number, or extended bus name enclosed in single quotes,
of a two-winding transformer.
`ifr` = 0 by default.
"""
ifr::Vector{BusNum}
"""
Winding two side "to bus" number, or extended bus name enclosed in single quotes,
of a two-winding transformer.
`itr` = 0 by default.
"""
itr::Vector{BusNum}
"""
Circuit identifier; the branch described by `ifr`, `itr`, and `idr` must have been entered
as a two-winding transformer; an AC transformer may control at most only one DC converter.
`idr` = '1' by default.
If no branch is specified, `tapr` is adjusted to keep alpha within limits;
otherwise, `tapr` is held fixed and this transformer’s tap ratio is adjusted.
The adjustment logic assumes that the rectifier converter bus is on the winding two side
of the transformer. The limits `tmxr` and `tmnr` specified here are used; except for the
transformer control mode flag (`cod` of `Transformers`), the AC tap adjustment data is ignored.
"""
idr::Vector{InlineString3}
"""
Commutating capacitor reactance magnitude per bridge; entered in ohms.
`xcapr` = 0.0 by default.
"""
xcapr::Vector{Float64}
# Third line: contains the inverter quantities corresponding to the rectifier quantities
# specified on the second line above. The significant difference is that the control angle
# `ALFA` for the rectifier is replaced by the control angle `GAMMA` for the inverter.
"""
Inverter converter bus number, or extended bus name enclosed in single quotes.
"""
ipi::Vector{BusNum}
"""
Number of bridges in series (inverter).
"""
nbi::Vector{Int32}
"""
Nominal maximum inverter firing angle; entered in degrees.
"""
gammx::Vector{Float64}
"""
Minimum steady-state inverter firing angle; entered in degrees.
"""
gammn::Vector{Float64}
"""
Inverter commutating transformer resistance per bridge; entered in ohms.
"""
rci::Vector{Float64}
"""
Inverter commutating transformer reactance per bridge; entered in ohms.
"""
xci::Vector{Float64}
"""
Inverter primary base AC voltage; entered in kV.
"""
ebasi::Vector{Float64}
"""
Inverter transformer ratio.
"""
tri::Vector{Float64}
"""
Inverter tap setting.
"""
tapi::Vector{Float64}
"""
Maximum inverter tap setting.
"""
tmxi::Vector{Float64}
"""
Minimum inverter tap setting.
"""
tmni::Vector{Float64}
"""
Inverter tap step; must be positive.
"""
stpi::Vector{Float64}
"""
Inverter firing angle measuring bus number, or extended bus name enclosed in single quotes.
"""
ici::Vector{BusNum}
"""
Winding one side "from bus" number, or extended bus name enclosed in single quotes,
of a two-winding transformer.
"""
ifi::Vector{BusNum}
"""
Winding two side "to bus" number, or extended bus name enclosed in single quotes,
of a two-winding transformer.
"""
iti::Vector{BusNum}
"""
Circuit identifier; the branch described by `ifr`, `itr`, and `idr` must have been entered
as a two-winding transformer; an AC transformer may control at most only one DC converter.
"""
idi::Vector{InlineString3}
"""
Commutating capacitor reactance magnitude per bridge; entered in ohms.
"""
xcapi::Vector{Float64}
end
end # eval
end
"""
$TYPEDEF
Voltage source converter (VSC) DC lines.
Defines line quantities and control parameters, and the converter buses (converter 1 and
converter 2), along with their data quantities and control parameters.
# Fields
$TYPEDFIELDS
"""
struct VSCDCLines <: Records
# First line of data
"""
The non-blank alphanumeric identifier assigned to this VSC DC line.
Each VSC DC line must have a unique `name`. The name may be up to twelve characters and
must be enclosed in single quotes. `name` may contain any combination of blanks,
uppercase letters, numbers and special characters.
No default.
"""
name::Vector{InlineString15}
"""
Control mode:
* 0 for out-of-service,
* 1 for in-service.
`mdc` = 1 by default.
"""
mdc::Vector{Int8}
"""
The DC line resistance entered in ohms. `rdc` must be positive.
No default.
"""
rdc::Vector{Float64}
"""
An owner number; (1 through the maximum number of owners at the current size level).
Each VSC DC line may have up to four owners. See [`Owners`](@ref).
By default, `01` is 1, and O2, O3 and O4 are zero.
"""
o1::Vector{OwnerNum}
"""
The fraction of total ownership assigned to owner `o1`; each F_i must be positive.
The F_i values are normalized such that they sum to 1.0 before they are placed in the working case.
By default, each F_i is 1.0.
"""
f1::Vector{Float64}
# TODO: are o2, f2, o3, f3, o4, f4 always present?
"""
An owner number; (1 through the maximum number of owners at the current size level).
See [`Owners`](@ref).
By default, `o2` is zero.
"""
o2::Vector{OwnerNum}
"""
The fraction of total ownership assigned to owner `o2`; must be positive.
By default, `f2` is 1.0.
"""
f2::Vector{Float64}
"""
An owner number; (1 through the maximum number of owners at the current size level).
By default, `o3` is zero.
"""
o3::Vector{OwnerNum}
"""
The fraction of total ownership assigned to owner `o2`; must be positive.
By default, `f3` is 1.0.
"""
f3::Vector{Float64}
"""
An owner number; (1 through the maximum number of owners at the current size level).
By default, `o4` is zero.
"""
o4::Vector{OwnerNum}
"""
The fraction of total ownership assigned to owner `o2`; must be positive.
By default, `f4` is 1.0.
"""
f4::Vector{Float64}
# Second line: data for Converter 1
"Converter 1 bus number, or extended bus name enclosed in single quotes. No default."
ibus1::Vector{BusNum}
"""
Code for the type of converter 1 DC control:
* 0 for converter out-of-service,
* 1 for DC voltage control,
* 2 for MW control.
When both converters are in-service, exactly one converter of each VSC DC line must be type 1.
No default.
"""
type1::Vector{Int8} # 0, 1, or 2
"""
Converter 1 AC control mode:
* 1 for AC voltage control,
* 2 for fixed AC power factor.
`mode` = 1 by default.
"""
mode1::Vector{Int8} # 1 or 2
"""
Converter 1 DC setpoint.
* For `type` = 1, `dcset` is the scheduled DC voltage on the DC side of the converter bus;
entered in kV.
* For `type` = 2, `dcset` is the power demand, where a positive value specifies that the
converter is feeding active power into the AC network at bus `ibus`, and a negative value
specifies that the converter is withdrawing active power from the AC network at bus `ibus`;
entered in MW.
No default .
"""
docet1::Vector{Float64}
"""
Converter 1 AC setpoint.
* For `mode` = 1, `acset` is the regulated AC voltage setpoint; entered in pu.
* For `mode` = 2, `acset` is the power factor setpoint.
`acset` = 1.0 by default.
"""
acset1::Vector{Float64}
"""
Coefficients of the linear equation used to calculate converter 1 losses:
``KW_{conv loss} = A_{loss} + I_{dc} * B_{loss}``
`aloss` is entered in kW. `aloss` = `bloss` = 0.0 by default.
"""
aloss1::Vector{Float64}
"""
Coefficients of the linear equation used to calculate converter 1 losses:
``KW_{conv loss} = A_{loss} + I_{dc} * B_{loss}``
`bloss` is entered in kW/amp. `aloss` = `bloss` = 0.0 by default.
"""
bloss1::Vector{Float64}
"Minimum converter 1 losses; entered in kW. `minloss` = 0.0 by default."
minloss1::Vector{Float64}
"""
Converter 1 MVA rating; entered in MVA.
`smax` = 0.0 to allow unlimited converter MVA loading. `smax` = 0.0 by default.
"""
smax1::Vector{Float64}
"""
Converter 1 AC current rating; entered in amps.
`imax` = 0.0 to allow unlimited converter current loading.
If a positive `imax` is specified, the base voltage assigned to bus `ibus` must be positive.
`imax` = 0.0 by default.
"""
imax1::Vector{Float64}
"""
Power weighting factor fraction (0.0 < `pwf` < 1.0) used in reducing the active power order
and either the reactive power order (when `mode` is 2) or the reactive power limits (when `mode` is 1)
when the converter MVA or current rating is violated.
When `pwf` is 0.0, only the active power is reduced;
when `PWF` is 1.0, only the reactive power is reduced;
otherwise, a weighted reduction of both active and reactive power is applied.
`pwf` = 1.0 by default.
"""
pwf1::Vector{Float64}
"""
Reactive power upper limit; entered in Mvar.
A positive value of reactive power indicates reactive power flowing into the AC network
from the converter; a negative value of reactive power indicates reactive power withdrawn
from the AC network. Not used if `mode` = 2.
`maxq` = 9999.0 by default.
"""
maxq1::Vector{Float64}
"""
Reactive power lower limit; entered in Mvar.
A positive value of reactive power indicates reactive power flowing into the AC network
from the converter; a negative value of reactive power indicates reactive power withdrawn
from the AC network. Not used if `mode` = 2.
`minq` = -9999.0 by default.
"""
minq1::Vector{Float64}
"""
Bus number, or extended bus name enclosed in single quotes, of a remote type 1 or 2 bus
whose voltage is to be regulated by this converter to the value specified by `acset`.
If bus `remot` is other than a type 1 or 2 bus, bus `ibus` regulates its own voltage to
the value specified by `acset`. `remot` is entered as zero if the converter is to regulate
its own voltage. Not used if `mode` = 2.
`remot` = 0 by default.
"""
remot1::Vector{BusNum}
"""
Percent of the total Mvar required to hold the voltage at the bus controlled by bus `ibus`
that are to be contributed by this VSC; `rmpct` must be positive.
`rmpct` is needed only if `remot` specifies a valid remote bus and there is more than one
local or remote voltage controlling device (plant, switched shunt, FACTS device shunt element,
or VSC DC line converter) controlling the voltage at bus `remot` to a setpoint, or `remot`
is zero but bus `ibus` is the controlled bus, local or remote, of one or more other setpoint
mode voltage controlling devices. Not used if `mode` = 2.
`rmpct` = 100.0 by default.
"""
rmpct1::Vector{Float64}
# Third line: data for Converter 2
"Converter 2 bus number, or extended bus name enclosed in single quotes. No default."
ibus2::Vector{BusNum}
"Code for the type of converter 2 DC control"
type2::Vector{Int8} # 0, 1, or 2
"Converter 2 AC control mode"
mode2::Vector{Int8} # 1 or 2
"Converter 2 DC setpoint."
docet2::Vector{Float64}
" Converter 2 AC setpoint."
acset2::Vector{Float64}
"Coefficient ``A_{loss}`` of the linear equation used to calculate converter 2 losses."
aloss2::Vector{Float64}
"Coefficient ``B_{loss}`` of the linear equation used to calculate converter 2 losses."
bloss2::Vector{Float64}
"Minimum converter 2 losses; entered in kW. `minloss` = 0.0 by default."
minloss2::Vector{Float64}
"Converter 2 MVA rating; entered in MVA."
smax2::Vector{Float64}
"Converter 2 AC current rating; entered in amps."
imax2::Vector{Float64}
"Power weighting factor fraction (0.0 < `pwf` < 1.0) for converter 2."
pwf2::Vector{Float64}
"Reactive power upper limit for converter 2; entered in Mvar."
maxq2::Vector{Float64}
"Reactive power lower limit for converter 2; entered in Mvar."
minq2::Vector{Float64}
"Bus number to be regulated by converter 2 to the value specified by `acset2`."
remot2::Vector{BusNum}
rmpct2::Vector{Float64}
end
"""
$TYPEDEF
The SwitchedShunts data record depends on the PSSE version:
- See [`SwitchedShunts30`](@ref) for PSSE v30 files.
- See [`SwitchedShunts33`](@ref) for PSSE v33 files.
"""
abstract type SwitchedShunts <: Records end
for v in (30, 33)
T = Symbol(:SwitchedShunts, v)
adjm_doc, adjm_col = if v == 33
:("""
Adjustment method:
* 0 - steps and blocks are switched on in input order, and off in reverse input order;
this adjustment method was the only method available prior to PSS®E-32.0.
* 1 - steps and blocks are switched on and off such that the next highest
(or lowest, as appropriate) total admittance is achieved.
`adjm` = 0 by default.
"""),
:(adjm::Vector{Bool})
else
:(""), :("")
end
stat_doc, stat_col = if v == 33
:("""
Initial switched shunt status of one for in-service and zero for out-of-service.
`stat` = 1 by default.
"""),
:(stat::Vector{Bool})
else
:(""), :("")
end
@eval begin
"""
$TYPEDEF
Represents switched shunt devices, in the form of capacitors and/or reactors on a network bus.
The switched shunt elements at a bus may consist entirely of blocks of shunt reactors
(each Bi is a negative quantity) or entirely of blocks of capacitor banks
(each Bi is a positive quantity). Any bus can have both switched capacitors and reactors.
Each network bus to be represented in PSS/E with switched shunt admittance devices must have
a switched shunt data record specified for it. The switched shunts are represented with up to
eight blocks of admittance, each one of which consists of up to nine steps of the specified
block admittance.
# Fields
$TYPEDFIELDS
"""
struct $T <: SwitchedShunts
"""
Bus number, or extended bus name enclosed in single quotes.
"""
i::Vector{BusNum}
"""
Control mode:
* 0 - fixed
* 1 - discrete adjustment, controlling voltage locally or at bus `swrem`
* 2 - continuous adjustment, controlling voltage locally or at bus `swrem`
* 3 - discrete adjustment, controlling reactive power output of the plant at bus `swrem`
* 4 - discrete adjustment, controlling reactive power output of the VSC DC line converter
at bus `swrem` of the VSC DC line whose name is specified as `rmidnt`
* 5 - discrete adjustment, controlling admittance setting of the switched shunt at bus `swrem`
`modsw` = 1 by default.
"""
modsw::Vector{Int8} # 0, 1, 2, 3, 4, or 5
$adjm_doc
$adjm_col
$stat_doc
$stat_col
"""
When `modsw` is 1 or 2, the controlled voltage upper limit; entered in pu.
When `modsw` is 3, 4 or 5, the controlled reactive power range upper limit; entered in pu
of the total reactive power range of the controlled voltage controlling device.
`vswhi` is not used when `modsw` is 0.
`vswhi` = 1.0 by default.
"""
vswhi::Vector{Float64}
"""
When `modsw` is 1 or 2, the controlled voltage lower limit; entered in pu.
When `modsw` is 3, 4 or 5, the controlled reactive power range lower limit; entered in pu
of the total reactive power range of the controlled voltage controlling device.
`vswlo` is not used when `modsw` is 0.
`vswlo` = 1.0 by default.
"""
vswlo::Vector{Float64}
"""
Bus number, or extended bus name enclosed in single quotes, of the bus whose voltage or
connected equipment reactive power output is controlled by this switched shunt.
* When `modsw` is 1 or 2, `swrem` is entered as 0 if the switched shunt is to regulate its own voltage;
otherwise, `swrem` specifies the remote type one or two bus whose voltage is to be regulated by this switched shunt.
* When `modsw` is 3, `swrem` specifies the type two or three bus whose plant reactive power output is to be regulated by this switched shunt.
Set `swrem` to "I" if the switched shunt and the plant which it controls are connected to the same bus.
* When `modsw` is 4, `swrem` specifies the converter bus of a VSC dc line whose converter reactive power output is to be regulated by this switched shunt.
Set `swrem` to "I" if the switched shunt and the VSC dc line converter which it controls are connected to the same bus.
* When `modsw` is 5, `swrem` specifies the remote bus to which the switched shunt whose admittance setting is to be regulated by this switched shunt is connected.
* `swrem` is not used when `modsw` is 0.
`swrem` = 0 by default.
"""
swrem::Vector{BusNum}
"""
Percent of the total Mvar required to hold the voltage at the bus controlled by bus `I`
that are to be contributed by this switched shunt; `rmpct` must be positive.
`rmpct` is needed only if `swrem` specifies a valid remote bus and there is more than one
local or remote voltage controlling device (plant, switched shunt, FACTS device shunt element,
or VSC DC line converter) controlling the voltage at bus `swrem` to a setpoint, or `swrem` is
zero but bus I is the controlled bus, local or remote, of one or more other setpoint mode
voltage controlling devices. Only used if `modsw` = 1 or 2.
`rmpct` = 100.0 by default.
"""
rmpct::Vector{Float64}
"""
When `modsw` is 4, the name of the VSC DC line whose converter bus is specified in `swrem`.
`rmidnt` is not used for other values of `modsw`.
`rmidnt` is a blank name by default.
"""
rmidnt::Vector{InlineString15}
"""
Initial switched shunt admittance; entered in Mvar at unity voltage.
`binit` = 0.0 by default.
"""
binit::Vector{Float64}
"""
Number of steps for block i.
The first zero value of N_i or B_i is interpreted as the end of the switched shunt blocks
for bus I.
`ni` = 0 by default.
"""
n1::Vector{Int32}
"""
Admittance increment for each of N_i steps in block i; entered in Mvar at unity voltage.
`bi` = 0.0 by default.
"""
b1::Vector{Float64}
n2::Vector{Int32}
b2::Vector{Float64}
n3::Vector{Int32}
b3::Vector{Float64}
n4::Vector{Int32}
b4::Vector{Float64}
n5::Vector{Int32}
b5::Vector{Float64}
n6::Vector{Int32}
b6::Vector{Float64}
n7::Vector{Int32}
b7::Vector{Float64}
n8::Vector{Int32}
b8::Vector{Float64}
end
end # eval
end
"""
$TYPEDEF
Transformer impedance corrections are used to model a change of transformer impedance
as off-nominal turns ratio or phase shift angle is adjusted.
The ``T_i`` values on a transformer impedance correction record must all be either tap
ratios or phase shift angles. They must be entered in strictly ascending order;
i.e. for each ``i``, ``T_{i+1} > T_i``. Each ``F_i`` entered must be greater than zero.
On each record, at least 2 pairs of values must be specified and up to 11 may be entered.
The ``T_i`` values that are a function of tap ratio (rather than phase shift angle)
are in units of the controlling winding’s off-nominal turns ratio in pu of the controlling
winding’s bus base voltage.
Although a transformer winding is assigned to an impedance correction record, each record may
be shared among many transformer windings. If the first ``T`` in a record is less than 0.5 or
the last ``T`` entered is greater than 1.5, ``T`` is assumed to be the phase shift angle and
the impedance of each transformer winding assigned to the record is treated as a function of
phase shift angle. Otherwise, the impedances of the transformer windings assigned to the record
are made sensitive to off-nominal turns ratio.
# Fields
$TYPEDFIELDS
"""
struct ImpedanceCorrections <: Records
"Impedance correction record number."
i::Vector{Int16}
"""
Either off-nominal turns ratio in pu or phase shift angle in degrees.
`ti` = 0.0 by default.
"""
t1::Vector{Float64}
"""
Scaling factor by which transformer nominal impedance is to be multiplied to obtain the
actual transformer impedance for the corresponding `ti`.
`fi` = 0.0 by default.
"""
f1::Vector{Float64}
t2::Vector{Float64}
f2::Vector{Float64}
t3::Vector{Float64}
f3::Vector{Float64}
t4::Vector{Float64}
f4::Vector{Float64}
t5::Vector{Float64}
f5::Vector{Float64}
t6::Vector{Float64}
f6::Vector{Float64}
t7::Vector{Float64}
f7::Vector{Float64}
t8::Vector{Float64}
f8::Vector{Float64}
t9::Vector{Float64}
f9::Vector{Float64}
t10::Vector{Float64}
f10::Vector{Float64}
t11::Vector{Float64}
f11::Vector{Float64}
end
###
### MultiTerminalDCLines
###
# `MultiTerminalDCLines` records are a bit special...
# Each "record" is actually
# - a row of data about the line, followed by
# - arbitrary number of rows about the converters
# - arbitrary number of rows about the buses
# - arbitrary number of rows about the links
# So we treat `MultiTerminalDCLines` as a single column table, where each value is a
# dedicated `MultiTerminalDCLine` object. And each `MultiTerminalDCLine` is a bit like a
# `Network`, with a `DCLineID` (`CaseID`) and 3 `Records` (`ACConverters, `DCBuses`, `DCLinks`)
"""
$TYPEDEF
The DCLineID data record depends on the PSSE version:
- See [`DCLineID30`](@ref) for PSSE v30 files.
- See [`DCLineID33`](@ref) for PSSE v33 files.
"""
abstract type DCLineID <: IDRow end
for v in (30, 33)
T = Symbol(:DCLineID, v)
firstdoc, firstcol = if v == 30
:("Multi-terminal DC line number."),
:(i::LineNum)
else
:("""
The non-blank alphanumeric identifier assigned to this DC line.
Each multi-terminal DC line must have a unique `name.
`name` may be up to twelve characters and may contain any combination of blanks, uppercase letters,
numbers and special characters. name must be enclosed in single or double quotes if it contains any
blanks or special characters. No default allowed.
"""),
:(name::InlineString15)
end
@eval begin
"""
$TYPEDEF
# Fields
$TYPEDFIELDS
"""
struct $T <: DCLineID
$firstdoc
$firstcol
"Number of AC converter station buses in multi-terminal DC line `i`. No default."
nconv::Int8
"Number of DC buses in multi-terminal DC line `i` (`nconv` < `ndcbs`). No default."
ndcbs::Int8
"Number of DC links in multi-terminal DC line `i`. No default."
ndcln::Int
"""
Control mode
* 0 - blocked
* 1 - power
* 2 - current
`mdc` = 0 by default.
"""
mdc::Int8 # 0, 1, or 2
"""
Bus number, or extended bus name enclosed in single quotes, of the AC converter station
bus that controls DC voltage on the positive pole of multi-terminal DC line `i`.
Bus `vconv` must be a positive pole inverter. No default.
"""
vconv::BusNum
"""
Mode switch DC voltage; entered in kV.
When any inverter DC voltage magnitude falls below this value and the line is in power
control mode (i.e. `mdc` = 1), the line switches to current control mode with converter
current setpoints corresponding to their desired powers at scheduled DC voltage.
`vcmod` = 0.0 by default.
"""
vcmod::Float64
"""
Bus number, or extended bus name enclosed in single quotes, of the AC converter station
bus that controls DC voltage on the negative pole of multi-terminal DC line `i`.
If any negative pole converters are specified (see below), bus `vconvn` must be a
negative pole inverter. If the negative pole is not being modeled, `vconvn` must be
specified as zero. `vconvn` = 0 by default.
"""
vconvn::BusNum
end
# Accept arguments as keywords to get both a `repr` that's both pretty and parseable.
$T(; kwargs...) = $T(values(kwargs)...)
end # eval
end
Tables.columnnames(::T) where T<:DCLineID = fieldnames(T)
Tables.getcolumn(dcln::DCLineID, i::Int) = getfield(dcln, i)
Tables.getcolumn(dcln::DCLineID, nm::Symbol) = getfield(dcln, nm)
"""
$TYPEDEF
# Fields
$TYPEDFIELDS
"""
struct ACConverters <: Records
"""
AC converter bus number, or extended bus name enclosed in single quotes.
No default.
"""
ib::Vector{BusNum}
"Number of bridges in series. No default."
n::Vector{Int8}
"Nominal maximum ALPHA or GAMMA angle; entered in degrees. No default."
angmx::Vector{Float64}
"Minimum steady-state ALPHA or GAMMA angle; entered in degrees. No default."
angmn::Vector{Float64}
"Commutating resistance per bridge; entered in ohms. No default."
rc::Vector{Float64}
"Commutating reactance per bridge; entered in ohms. No default."
xc::Vector{Float64}
"Primary base AC voltage; entered in kV. No default."
ebas::Vector{Float64}
"Actual transformer ratio. `tr` = 1.0 by default."
tr::Vector{Float64}
"Tap setting. `tap` = 1.0 by default."
tap::Vector{Float64}
"Maximum tap setting. `tpmx` = 1.5 by default."
tpmx::Vector{Float64}
"Minimum tap setting. `tpmx` = 0.51 by default."
tpmn::Vector{Float64}
"Tap step; must be a positive number. `tstp` = 0.00625 by default."
tstp::Vector{Float64}
"""
Converter setpoint.
When `ib` is equal to `vconv` or `vconvn`, `setvl` specifies the scheduled DC voltage magnitude,
entered in kV, across the converter.
For other converter buses, `setvl` contains the converter current (amps) or power (MW) demand;
a positive value of `setvl` indicates that bus `ib` is a rectifier, and a negative value indicates an inverter.
No default.
"""
setvl::Vector{Float64}
"""
Converter participation factor.
When the order at any rectifier in the multi-terminal DC line is reduced,
either to maximum current or margin, the orders at the remaining converters on the same
pole are modified according to their ``DCPF``s to: ``SETVL + (DCPF/SUM)∗R```
where ``SUM`` is the sum of the ``DCPF``s at the unconstrained converte rs on the same
pole as the constrained rectifier, and ``R`` is the order reduction at the constrained rectifier.
`dcpf` = 1. by default.
"""
dcpf::Vector{Float64}
"""
Rectifier margin entered in per unit of desired DC power or current.
The converter order reduced by this fraction, ``(1.0 - MARG) ∗ SETVL``,
defines the minimum order for this rectifier. `marg` is used only at rectifiers.
`marg` = 0.0 by default.
"""
marg::Vector{Float64}
"""
Converter code.
A positive value or zero must be entered if the converter is on the positive pole of multi-terminal DC line `i`.
A negative value must be entered for negative pole converters. `cnvcod` = 1 by default.
"""
cnvcod::Vector{Int8}
end
"""
$TYPEDEF
# Fields
$TYPEDFIELDS
"""
struct DCBuses <: Records
"""
DC bus number (1 to `NDCBS`).
The DC buses are used internally within each multi-terminal DC line and must be numbered
1 through `ndcbs`. no default.
"""
idc::Vector{BusNum}
"""
AC converter bus number, or extended bus name enclosed in single quotes, or zero.
Each converter station bus specified in a converter record must be specified as `ib` in
exactly one DC bus record. DC buses that are connected only to other DC buses by DC links
and not to any AC converter buses must have a zero specified for `ib`. A DC bus specified
as `idc2` on one or more other DC bus records must have a zero specified for `ib` on its
own DC bus record. `ib` = 0 by default.
"""
ib::Vector{BusNum}
"""
Area number (1 through the maximum number of areas at the current size level).
`ia` = 1 by default.
"""
ia::Vector{AreaNum}
"""
Zone number (1 through the maximum number of zones at the current size level).
`zone` = 1 by default.
"""
zone::Vector{ZoneNum}
"""
Alphanumeric identifier assigned to DC bus `idc`.
The name may be up to twelve characters and must be enclosed in single quotes. `name`
may contain any combination of blanks, uppercase letters, numbers, and special characters.
`name` is twelve blanks by default.
"""
name::Vector{InlineString15}
idc2::Vector{BusNum}
"""
Second DC bus to which converter `ib` is connected, or zero if the converter is connected directly to ground.
* For voltage controlling converters, this is the DC bus with the lower DC voltage magnitude
and `setvl` specifies the voltage difference between buses `idc` and `idc2`.
* For rectifiers, DC buses should be specified such that power flows from bus `idc2` to bus `idc`.
* For inverters, DC buses should be specified such that power flows from bus `idc` to bus `idc2`.
`idc2` is ignored on those dc bus records that have `ib` specified as zero. `idc2` = 0 by default.
"""
rgrnd::Vector{Float64}
"""
Owner number (1 through the maximum number of owners at the current size level).
`owner` = 1 by default.
"""
owner::Vector{OwnerNum}
end
"""
$TYPEDEF
# Fields
$TYPEDFIELDS
"""
struct DCLinks <: Records
"Branch \"from bus\" DC bus number."
idc::Vector{BusNum}
"""
Branch "to bus" DC bus number.
`jdc` is entered as a negative number to designate it as the metered end for area and
zone interchange calculations. Otherwise, bus `idc` is assumed to be the metered end.
"""
jdc::Vector{BusNum}
"""
One-character uppercase alphanumeric branch circuit identifier.
It is recommended that single circuit branches be designated as having the circuit identifier "1".
`dcckt` = "1" by default.
"""
dcckt::Vector{InlineString1}
"DC link resistance, entered in ohms. No default."
rdc::Vector{Float64}
"""
DC link inductance, entered in mH. `ldc` is not used by the power flow solution activities
but is available to multi-terminal DC line dynamics models. `ldc` = 0.0 by default.
"""
ldc::Vector{Float64}
end
"""
$TYPEDEF
Each multi-terminal DC line record defines the number of converters, number of DC buses and
number of DC links as well as related bus numbers and control mode (see [`DCLineID`](@ref)),
then data for:
* each converter (see [`ACConverters`](@ref))
* each DC bus (see [`DCBuses`](@ref))
* each DC link (see [`DCLinks`](@ref))
# Fields
$TYPEDFIELDS
"""
struct MultiTerminalDCLine
"High-level data about this line."
line_id::DCLineID
"`line.nconv` converter records."
converters::ACConverters
"`line.ndcbs` DC bus records."
buses::DCBuses
"`line.ndcln` DC link records."
links::DCLinks
end
"""
$TYPEDEF
PSS/E allows the representation of up to 12 converter stations on one multi-terminal DC line.
Further, it allows the modelling of multi-terminal networks of up to 20 buses including the
AC convertor buses and the DC network buses.
## Notes
The following are notes on multi-terminal links:
* Conventional two-terminal and multi-terminal DC lines are stored separately.
Therefore, there may simultaneously exist, for example, a two-terminal DC line identified
as DC line number 1 along with a multi-terminal line numbered 1.
* Multi-terminal lines should have at least three converter terminals;
conventional DC lines consisting of two terminals should be modeled as two-terminal lines
(see [`TwoTerminalDCLines`](@ref).
* AC converter buses may be type one, two, or three buses. Generators, loads, fixed and
switched shunt elements, other DC line converters, and FACTS device sending ends are
permitted at converter buses.
* Each multi-terminal DC line is treated as a subnetwork of DC buses and DC links connecting
its AC converter buses. For each multi-terminal DC line, the DC buses must be numbered 1
through `ndcbs`.
* Each AC converter bus must be specified as `ib` on exactly one DC bus record; there may be
DC buses connected only to other DC buses by DC links but not to any AC converter bus.
* AC converter bus `ib` may be connected to a DC bus `idc`, which is connected directly to ground.
`ib` is specified on the DC bus record for DC bus `idc`; the `idc2` field is specified as zero.
* Alternatively, AC converter bus `ib` may be connected to two DC buses `idc` and `idc2`,
the second of which is connected to ground through a specified resistance.
`ib` and `idc2` are specified on the DC bus record for DC bus `idc`;
on the DC bus record for bus `idc2`, the AC converter bus and second DC bus fields
(`ib` and `idc2`, respectively) must be specified as zero and the grounding resistance is
specified as `rgrnd`.
* The same DC bus may be specified as the second DC bus for more than one AC converter bus.
* All DC buses within a multi-terminal DC line must be reachable from any other point within the subnetwork.
* The area number assigned to DC buses and the metered end designation of DC links are used in
calculating area interchange and assigning losses as well as in the interchange control option
of the power flow solution activities. Similarly, the zone assignment and metered end specification
are used in Zonal reporting activities.
# Fields
$TYPEDFIELDS
"""
struct MultiTerminalDCLines{I<:DCLineID} <: Records
lines::Vector{MultiTerminalDCLine}
# Avoid ambiguity with generic 1-arg Records constructor
MultiTerminalDCLines{I}(lines::AbstractVector) where I = new{I}(lines)
MultiTerminalDCLines{I}(sizehint::Integer=0) where I = new{I}(sizehint!(MultiTerminalDCLine[], sizehint))
end
MultiTerminalDCLines(args...) = MultiTerminalDCLines{DCLineID30}(args...)
###
### MultiSectionLineGroups
###
"""
$TYPEDEF
The MultiSectionLineGroups data record depends on the PSSE version:
- See [`MultiSectionLineGroups30`](@ref) for PSSE v30 files.
- See [`MultiSectionLineGroups33`](@ref) for PSSE v33 files.
"""
abstract type MultiSectionLineGroups <: Records end
for v in (30, 33)
T = Symbol(:MultiSectionLineGroups, v)
met_doc, met_col = if v == 33
:("""
Metered end flag.
* ≤1 to designate bus `i` as the metered end.
* ≥2 to designate bus `j` as the metered end.
`met` = 1 by default.
"""),
:(met::Vector{Int8})
else
:(""), :("")
end
@eval begin
"""
$TYPEDEF
Multi-section line groups.
Transmission lines commonly have a series of sections with varying physical structures.
The section might have different tower configurations, conductor types and bundles or various
combinations of these. The physical differences can result in the sections having different
resistance, reactance and charging.
A transmission line with several distinct sections can be represented as one
multi-section line group.
The DUM_i values on each record define the branches connecting bus `i` to bus `j`, and
are entered so as to trace the path from bus `i` to bus `j`.
## Example
For a multi-section line grouping consisting of three line sections (and hence two dummy buses):
| From | To | Circuit |
|------|----|---------|
| I | D1 | C1 |
| D1 | D2 | C2 |
| D2 | J | C3 |
If this multi-section line grouping is to be assigned the line identifier `id` "&1",
the corresponding multi-section line grouping data record is given by:
```
I, J, '&1', D1, D2
```
Or in v33 (and if I is the metered end):
```
I, J, '&1', 1, D1, D2
```
## Notes
The following notes apply to multi-section line groups:
* Up to 10 line sections (and hence 9 dummy buses) may be defined in each multi-section line grouping.
A branch may be a line section of at most one multi-section line grouping.
* Each dummy bus must have exactly two branches connected to it,
both of which must be members of the same multi-section line grouping.
A multi-section line dummy bus may not be a converter bus of a DC transmission line.
A FACTS control device may not be connected to a multi-section line dummy bus.
* The status of line sections and type codes of dummy buses are set such that the multi-section
line is treated as a single entity with regards to its service status.
# Fields
$TYPEDFIELDS
"""
struct $T <: MultiSectionLineGroups
"\"From bus\" number, or extended bus name enclosed in single quotes."
i::Vector{BusNum}
"""
"To bus" number, or extended bus name enclosed in single quotes.
`j` is entered as a negative number or with a minus sign before the first character of
the extended bus name to designate it as the metered end;
otherwise, bus `i` is assumed to be the metered end.
"""
j::Vector{BusNum}
"""
Two-character upper-case alphanumeric multi-section line grouping identifier.
The first character must be an ampersand ("&").
`id` = "&1" by default.
"""
id::Vector{InlineString3}
$met_doc
$met_col
"""
Bus numbers, or extended bus names enclosed in single quotes, of the dummy buses
connected by the branches that comprise this multi-section line grouping.
No defaults.
"""
dum1::Vector{BusNum}
dum2::Vector{Union{BusNum,Missing}}
dum3::Vector{Union{BusNum,Missing}}
dum4::Vector{Union{BusNum,Missing}}
dum5::Vector{Union{BusNum,Missing}}
dum6::Vector{Union{BusNum,Missing}}
dum7::Vector{Union{BusNum,Missing}}
dum8::Vector{Union{BusNum,Missing}}
dum9::Vector{Union{BusNum,Missing}}
end
end # eval
end
"""
$TYPEDEF
All buses (AC and DC) and loads can be assigned to reside in a zone of the network.
To enable this facility, each zone should be assigned a name and number.
Specifically, the zone number is entered as part of the data records for the [`Buses`](@ref) and [`Loads`](@ref).
The use of zones enables the user to develop reports and to check results on the basis of zones and,
consequently be highly specific when reporting and interpreting analytical results.
# Fields
$TYPEDFIELDS
"""
struct Zones <: Records
"Zone number (1 through the maximum number of zones at the current size level)"
i::Vector{ZoneNum}
"""
Alphanumeric identifier assigned to zone `i`.
The name may contain up to twelve characters and must be enclosed in single quotes.
`zoname` may be any combination of blanks, uppercase letters, numbers, and special characters.
`zoname` is set to twelve blanks by default.
"""
zoname::Vector{InlineString15}
end
"""
$TYPEDEF
Using PSS/E, the user has the capability to identify in which area each [bus](@ref Buses) or [load](@ref Loads) resides.
Further, the user can schedule active power transfers between pairs of areas.
See [`AreaInterchanges`](@ref) for desired net interchange.
# Fields
$TYPEDFIELDS
"""
struct InterAreaTransfers <: Records
"\"From area\" number (1 through the maximum number of areas at the current size level)."
arfrom::Vector{AreaNum}
"\"To area\" number (1 through the maximum number of areas at the current size level)."
arto::Vector{AreaNum}
"""
Single-character (0 through 9 or A through Z) upper-case interarea transfer identifier
used to distinguish among multiple transfers between areas `arfrom` and `arto`.
`trid` = "1" by default.
"""
trid::Vector{InlineString1}
"""
MW comprising this transfer.
A positive `ptran` indicates that area `arfrom` is selling to area `arto`.
`ptran` = 0.0 by default.
"""
ptran::Vector{Float64}
end
"""
$TYPEDEF
PSS/E allows the user to identify which organization or utility actually owns a facility,
a piece of equipment, or a load. Major network elements can have up to four different owners.
This facilitates interpretation of results and reporting of results on the basis of ownership.
# Fields
$TYPEDFIELDS
"""
struct Owners <: Records
"Owner number (1 through the maximum number of owners at the current size level)."
i::Vector{OwnerNum}
"""
Alphanumeric identifier assigned to owner `i`.
The name may contain up to twelve characters and must be enclosed in single quotes.
`owname` may be any combination of blanks, uppercase letters, numbers, and special characters.
`owname` is set to twelve blanks by default.
"""
owname::Vector{InlineString15}
end
"""
$TYPEDEF
The FACTSDevices data record depends on the PSSE version:
- See [`FACTSDevices30`](@ref) for PSSE v30 files.
- See [`FACTSDevices33`](@ref) for PSSE v33 files.
"""
abstract type FACTSDevices <: Records end
for v in (30, 33)
T = Symbol(:FACTSDevices, v)
firstdoc, firstcol = if v == 30
:("FACTS device number."),
:(n::Vector{Int16})
else
:("""
The non-blank alphanumeric identifier assigned to this FACTS device.
Each FACTS device must have a unique `name.
`name` may be up to twelve characters and may contain any combination of blanks, uppercase letters,
numbers and special characters. name must be enclosed in single or double quotes if it contains any
blanks or special characters. No default allowed.
"""),
:(name::Vector{InlineString15})
end
remot_doc, remot_col = if v == 33
:("""
Bus number, or extended bus name enclosed in single quotes, of a remote Type 1 or 2 bus
where voltage is to be regulated by the shunt element of this FACTS device to the value
specified by `vset`. if bus `remot` is other than a type 1 or 2 bus, the shunt element
regulates voltage at the sending end bus to the value specified by `vset`.
`remot` is entered as zero if the shunt element is to regulate voltage at the sending end
bus and must be zero if the sending end bus is a type 3 (swing) bus. `remot` = 0 by default.
"""),
:(remot::Vector{BusNum})
else
:(""), :("")
end
mname_doc, mname_col = if v == 33
:("""
The name of the FACTS device that is the IPFC master device when this FACTS device is
the "slave" device of an IPFC (i.e., its `mode` is specified as 6 or 8).
`mname` must be enclosed in single or double quotes if it contains any blanks or special
characters. `mname` is blank by default.
"""),
:(mname::Vector{InlineString15})
else
:(""), :("")
end
@eval begin
"""
$TYPEDEF
Flexible AC Transmission System devices.
There is a multiplicity of Flexible AC Transmission System devices currently available
comprising shunt devices, such as the Static Compensator (STATCOM), series devices such as
the Static Synchronous Series Compensator (SSSC), combined devices such as the
Unified Power Flow Controller (UPFC) and the Interline Power Flow Controllers (IPFC),
of which the latter are parallel series devices.
# Fields
$TYPEDFIELDS
"""
struct $T <: FACTSDevices
$firstdoc
$firstcol
"""
Sending end bus number, or extended bus name enclosed in single quotes.
No default.
"""
i::Vector{BusNum}
"""
Terminal end bus number, or extended bus name enclosed in single quotes.
0 for a STATCON.
`j` = 0 by default.
"""
j::Vector{BusNum}
"""
Control mode:
* 0 - out-of-service (i.e., series and shunt links open).
* 1 - series and shunt links operating.
* 2 - series link bypassed (i.e., like a zero impedance line) and shunt link operating as a STATCON.
* 3 - series and shunt links operating with series link at constant series impedance.
* 4 - series and shunt links operating with series link at constant series voltage.
* 5 - master device of an IPFC with P and Q setpoints specified;
FACTS device N+1 must be the slave device (i.e., its `mode` is 6 or 8) of this IPFC.
* 6 - slave device of an IPFC with P and Q setpoints specified;
FACTS device N-1 must be the master device (i.e., its `mode` is 5 or 7) of this IPFC.
The Q setpoint is ignored as the master device dictates the active power exchanged between the two devices.
* 7 - master device of an IPFC with constant series voltage setpoints specified;
FACTS device N+1 must be the slave device (i.e., its `mode` is 6 or 8) of this IPFC.
* 8 - slave device of an IPFC with constant series voltage setpoints specified;
FACTS device N-1 must be the master device (i.e., its `mode` is 5 or 7) of this IPFC.
The complex ``V_d + j V_q`` setpoint is modified during power flow solutions to reflect
the active power exchange determined by the master device.
If `j` is specified as 0, `mode` must be either 0 or 1.
`mode` = 1 by default.
"""
mode::Vector{Int8}
"""
Desired active power flow arriving at the terminal end bus; entered in MW.
`pdes` = 0.0 by default.
"""
pdes::Vector{Float64}
"""
Desired reactive power flow arriving at the terminal end bus; entered in MVAR.
`qdes` = 0.0 by default.
"""
qdes::Vector{Float64}
"Voltage setpoint at the sending end bus; entered in pu. `vset` = 1.0 by default."
vset::Vector{Float64}
"""
Maximum shunt current at the sending end bus; entered in MVA at unity voltage.
`shmx` = 9999.0 by default.
"""
shmx::Vector{Float64}
"Maximum bridge active power transfer; entered in MW. `trmx` = 9999.0 by default."
trmx::Vector{Float64}
"Minimum voltage at the terminal end bus; entered in pu. `vtmn` = 0.9 by default."
vtmn::Vector{Float64}
"Maximum voltage at the terminal end bus; entered in pu. `vtmx` = 1.1 by default."
vtmx::Vector{Float64}
"Maximum series voltage; entered in pu. `vsmx` = 1.0 by default."
vsmx::Vector{Float64}
"""
Maximum series current, or zero for no series current limit; entered in MVA at unity voltage.
`imx` = 0.0 by default.
"""
imx::Vector{Float64}
"""
Reactance of the dummy series element used during model solution; entered in pu.
`linx` = 0.05 by default.
"""
linx::Vector{Float64}
"""
Percent of the total Mvar required to hold the voltage at bus `i` that are to be contributed
by the shunt element of this FACTS device; `rmpct` must be positive.
`rmpct` is needed only if there is more than one local or remote voltage controlling device
(plant, switched shunt, FACTS device shunt element, or VSC dc line converter) controlling
the voltage at bus `i` to a setpoint. `rmpct` = 100.0 by default.
"""
rmpct::Vector{Float64}
"""
Owner number (1 through the maximum number of owners at the current size level).
`owner` = 1 by default.
"""
owner::Vector{OwnerNum}
"""
If `mode` is 3, resistance and reactance respectively of the constant impedance, entered in pu;
if `mode` is 4, the magnitude (in pu) and angle (in degrees) of the constant series voltage
with respect to the quantity indicated by `vsref`;
if `mode` is 7 or 8, the real (vd) and imaginary (vq) components (in pu) of the constant
series voltage with respect to the quantity indicated by `vsref`;
for other values of `mode`, `set1` and set2 are read, but not saved or used during power flow solutions.
`set1` = 0.0 by default.
"""
set1::Vector{Float64}
"See `set1`. `set2` = 0.0 by default."
set2::Vector{Float64}
"""
Series voltage reference code to indicate the series voltage reference of `set1` and `set2`
when `mode` is 4, 7 or 8: 0 for sending end voltage, 1 for series current.
`vsref` = 0 by default.
"""
vsref::Vector{Int8} # 0 or 1... i think
$remot_doc
$remot_col
$mname_doc
$mname_col
end
end # eval
end
###
### Network
###
"""
$TYPEDEF
Representation of a power network.
The PSS/E data format comprises 16 data categories of network and equipment
elements, each of which requires a particular type of data.
Similarly, a `Network` stores the data from each category in its own dedicated structure.
Currently supported are:
1. [`CaseID`](@ref)
1. [`Buses`](@ref)
1. [`Loads`](@ref)
1. [`FixedShunts`](@ref)
1. [`Generators`](@ref)
1. [`Branches`](@ref)
1. [`Transformers`](@ref)
1. [`AreaInterchanges`](@ref)
1. [`TwoTerminalDCLines`](@ref)
1. [`VSCDCLines`](@ref)
1. [`SwitchedShunts`](@ref)
1. [`ImpedanceCorrections`](@ref)
1. [`MultiTerminalDCLines`](@ref)
1. [`MultiSectionLineGroups`](@ref)
1. [`Zones`](@ref)
1. [`InterAreaTransfers`](@ref)
1. [`Owners`](@ref)
1. [`FACTSDevices`](@ref)
`CaseID` data is a single row (in the Tables.jl-sense).
You can access it like `network.caseid` and interact with it like a `NamedTuple`,
or even convert it to a `NamedTuple` with `NamedTuple(caseid)`.
All other records (buses, loads, etc.) can be accessed also via the fields, for example
`network.buses`, and each is returned as lightweight table structure (again, in the Tables.jl-sense).
That is, all structures implement the Tables.jl interface, so can be passed to any valid
sink, such as a `DataFrame` like `DataFrame(network.buses)`.
For more info on working with tables see [Tables.jl](https://tables.juliadata.org/), and for
common table operations see [TableOperations.jl](https://github.com/JuliaData/TableOperations.jl).
# Fields
$TYPEDFIELDS
"""
Base.@kwdef struct Network
"Version of the PSS/E data version given or detected when parsing."
version::Int8
"Case identification data."
caseid::CaseID=CaseID()
"Bus records."
buses::Buses=(version == 33 ? Buses33() : Buses30())
"Load records."
loads::Loads=Loads()
"Fixed Bus Shunt records."
fixed_shunts::Union{FixedShunts,Nothing}=(version == 33 ? FixedShunts() : nothing)
"Generator records."
generators::Generators=Generators()
"Non-transformer Branch records."
branches::Branches=(version == 33 ? Branches33() : Branches30())
"Transformer records."
transformers::Transformers=Transformers()
"Area Interchange records."
area_interchanges::AreaInterchanges=AreaInterchanges()
"Two-terminal DC Line records."
two_terminal_dc::TwoTerminalDCLines=(version == 33 ? TwoTerminalDCLines33() : TwoTerminalDCLines30())
"Voltage Source Converter DC Line records."
vsc_dc::VSCDCLines=VSCDCLines()
"Switched Shunt records."
switched_shunts::SwitchedShunts=(version == 33 ? SwitchedShunts33() : SwitchedShunts30())
"Transformer impedance correction records."
impedance_corrections::ImpedanceCorrections=ImpedanceCorrections()
"Multi-terminal DC Line records."
multi_terminal_dc::MultiTerminalDCLines=MultiTerminalDCLines()
"Multi-section line group records."
multi_section_lines::MultiSectionLineGroups=(version == 33 ? MultiSectionLineGroups33() : MultiSectionLineGroups30())
"Zone records."
zones::Zones=Zones()
"Inter-area transfer records."
area_transfers::InterAreaTransfers=InterAreaTransfers()
"Owner records."
owners::Owners=Owners()
"FACTS device records."
facts::FACTSDevices=(version == 33 ? FACTSDevices33() : FACTSDevices30())
end
###
### constructors
###
# Create a instance of a `Records` subtype, with all fields (assumed to be Vector)
# expected to be populated with roughly `sizehint` elements
# (::Type{R})(sizehint::Integer=0) where {R <: Records} = (R(map(T -> sizehint!(T(), sizehint), fieldtypes(R))...))::R
for R in (
:Buses30, :Buses33,
:Loads,
:FixedShunts,
:Generators,
:Branches30, :Branches33,
:Transformers,
:AreaInterchanges,
:TwoTerminalDCLines30, :TwoTerminalDCLines33,
:VSCDCLines,
:SwitchedShunts30, :SwitchedShunts33,
:ImpedanceCorrections,
:ACConverters, :DCLinks, :DCBuses,
:MultiSectionLineGroups30, :MultiSectionLineGroups33,
:Zones,
:InterAreaTransfers,
:Owners,
:FACTSDevices30, :FACTSDevices33,
)
@eval $R(sizehint::Integer=0) = $R(map(T -> sizehint!(T(), sizehint), fieldtypes($R))...)::$R
end
function Base.isempty(net::T) where {T <: Network}
for i in 1:fieldcount(T)
if fieldtype(T, i) <: Records && !isempty(getfield(net, i))
return false
end
end
return true
end
###
### show
###
function Base.show(io::IO, mime::MIME"text/plain", network::T) where {T <: Network}
show(io, mime, T)
get(io, :compact, false)::Bool && return nothing
print(io, " (v$(network.version))")
records = (getfield(network, i) for i in 2:fieldcount(T)) # version is field 1
nrec = count(!isnothing, records)
print(io, " with $nrec data categories:")
io_compact = IOContext(io, :compact => true)
for rec in records
rec === nothing && continue
print(io, "\n ")
show(io_compact, mime, rec)
end
return nothing
end
function Base.show(io::IO, dcline::T) where {T <: MultiTerminalDCLine}
# only show the `DCLineID` info when in containers, such as in the table shown by
# `network.multi_terminal_dc` or the vector shown by `multi_terminal_dc.lines`
if get(io, :limit, false)::Bool
show(io, dcline.line_id)
else
Base.show_default(io, dcline)
end
end
# Each MultiTerminalDCLine is its own little network-like thing...
function Base.show(io::IO, mime::MIME"text/plain", dcline::T) where {T <: MultiTerminalDCLine}
show(io, mime, dcline.line_id)
get(io, :compact, false)::Bool && return nothing
nfields = fieldcount(T)
foreach(2:nfields) do i
print(io, "\n")
show(io, mime, getfield(dcline, i))
end
return nothing
end
Base.show(io::IO, x::T) where {T <: IDRow} = print(io, T, NamedTuple(x)) # parseable repr
function Base.show(io::IO, ::MIME"text/plain", x::T) where {T <: IDRow}
print(io, T, ": ", NamedTuple(x))
end
Base.summary(io::IO, x::R) where {R <: Records} = print(io, _summary(R), " with $(length(x)) records")
_summary(::Type{R}) where {R} = string(R)
_summary(::Type{<:Buses}) = "Buses"
_summary(::Type{<:Branches}) = "Branches"
_summary(::Type{<:TwoTerminalDCLines}) = "TwoTerminalDCLines"
_summary(::Type{<:MultiTerminalDCLines}) = "MultiTerminalDCLines"
_summary(::Type{<:MultiSectionLineGroups}) = "MultiSectionLineGroups"
_summary(::Type{<:FACTSDevices}) = "FACTSDevices"
_summary(::Type{<:SwitchedShunts}) = "SwitchedShunts"
function Base.show(io::IO, mime::MIME"text/plain", x::R) where {R <: Records}
if get(io, :compact, false)::Bool || isempty(x)
Base.summary(io, x)
else
R_str = _summary(R)
printstyled(io, R_str; bold=true)
print(io, " with $(length(x)) records,")
print(io, " $(length(Tables.columnnames(x))) columns:\n")
(vsize, hsize) = displaysize(io)
pretty_table(
io, x;
alignment_anchor_fallback=:r, # align right as best for integers
alignment_anchor_regex=Dict(0 => [r"\."]), # align floating point numbers
compact_printing=true,
crop=:both,
display_size=(max(1, vsize-3), hsize), # save some vertical space for summary
header=collect(Symbol, Tables.columnnames(x)),
newline_at_end=false,
vcrop_mode=:middle, # show first and last rows
vlines=Int[], # no vertical lines
)
end
return nothing
end
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | code | 23281 | using DataFrames
using InteractiveUtils: subtypes
using InlineStrings: InlineStrings # for `eval(repr(...))`
using PowerFlowData
using Tables
using Test
@testset "PowerFlowData.jl" begin
@testset "Infers" begin
for T in subtypes(PowerFlowData.Records)
isabstracttype(T) && continue
@inferred T()
@inferred T(1)
end
end
@testset "Tables interface" begin
struct TestRecs <: PowerFlowData.Records
x1::Vector{Int}
yy::Vector{Float64}
end
recs = TestRecs([1, 2, 3], [3.14, 1.72, 0.05])
@test Tables.istable(TestRecs)
@test Tables.columnaccess(TestRecs)
@test Tables.columns(recs) === recs
@test Tables.columnnames(recs) == (:x1, :yy)
@test recs.x1 == [1, 2, 3]
@test Tables.getcolumn(recs, :x1) == [1, 2, 3]
@test Tables.getcolumn(recs, 1) == [1, 2, 3]
@test length(recs) == 3
@test size(recs) == (3, 2)
@test Tables.rowtable(recs)[1] == (x1=1, yy=3.14)
@test NamedTuple(first(Tables.rows(recs))) == (x1=1, yy=3.14)
@test first(Tables.namedtupleiterator(recs)) == (x1=1, yy=3.14)
df = DataFrame(recs)
@test df isa DataFrame
@test size(df) == (3, 2)
for T in (
Buses, Loads, Generators, Branches, Transformers, AreaInterchanges,
TwoTerminalDCLines, VSCDCLines, SwitchedShunts, ImpedanceCorrections,
MultiTerminalDCLines, MultiSectionLineGroups, Zones, InterAreaTransfers,
Owners, FACTSDevices
)
@test T <: PowerFlowData.Records
@test Tables.istable(T)
end
caseid = CaseID(ic=0, sbase=100.0)
@test caseid[1] == caseid[:ic]
@test caseid[2] == caseid[:sbase]
@test NamedTuple(caseid) isa NamedTuple
end
@testset "show" begin
# test of file which has MultiTerminalDCLines as they have their own `show`.
net = parse_network("testfiles/synthetic_data_v29.raw")
# CaseID should have a parseable `repr`; `AbstractRows` don't get this for free.
@test startswith(repr(net.caseid), "CaseID(ic = 0, sbase = 100.0, ")
@test isequal(eval(Meta.parse(repr(net.caseid))), CaseID(ic=0, sbase=100.0))
mime = MIME("text/plain")
context = :compact => true
@test repr(mime, net; context) == "Network"
@test repr(mime, net) == strip(
"""
Network (v30) with 17 data categories:
$(sprint(show, mime, net.caseid))
$(sprint(show, mime, net.buses; context))
$(sprint(show, mime, net.loads; context))
$(sprint(show, mime, net.generators; context))
$(sprint(show, mime, net.branches; context))
$(sprint(show, mime, net.transformers; context))
$(sprint(show, mime, net.area_interchanges; context))
$(sprint(show, mime, net.two_terminal_dc; context))
$(sprint(show, mime, net.vsc_dc; context))
$(sprint(show, mime, net.switched_shunts; context))
$(sprint(show, mime, net.impedance_corrections; context))
$(sprint(show, mime, net.multi_terminal_dc; context))
$(sprint(show, mime, net.multi_section_lines; context))
$(sprint(show, mime, net.zones; context))
$(sprint(show, mime, net.area_transfers; context))
$(sprint(show, mime, net.owners; context))
$(sprint(show, mime, net.facts; context))
"""
)
@test startswith(repr(mime, net.caseid), "CaseID: (ic = 0, sbase = 100.0, ")
@test repr(mime, net.buses; context=(:compact => true)) == "Buses with 2 records"
@test startswith(repr(mime, net.buses), "Buses with 2 records, 11 columns:\n──")
mt_dc_line = net.multi_terminal_dc.lines[1]
@test eval(Meta.parse(repr(mt_dc_line))) isa MultiTerminalDCLine
@test repr(mime, mt_dc_line) == strip(
"""
$(sprint(show, mime, mt_dc_line.line_id))
$(sprint(show, mime, mt_dc_line.converters))
$(sprint(show, mime, mt_dc_line.buses))
$(sprint(show, mime, mt_dc_line.links))
"""
)
line_id = mt_dc_line.line_id
@test eval(Meta.parse(repr(line_id))) isa DCLineID
end
@testset "v30 file" begin
net1 = parse_network("testfiles/synthetic_data_v30.raw")
@test net1 isa Network
caseid = net1.caseid
@test caseid.ic == 0
@test caseid.sbase == 100.0
# Test first and last columns are parsed as expected
buses = net1.buses
@test buses.i == [111, 112, 113]
@test buses.owner == [1, 2, 2]
# Test string column as expected
@test buses.name[2] == "D2JK"
loads = net1.loads
@test loads.i == [111, 113] # first col
@test loads.owner == [1, 2] # last col
@test isequal(loads.intrpt, [missing, missing])
gens = net1.generators
@test gens.i == [111, -112, 113]
@test gens.f1 == [1.0, 1.0, 1.0] # last col guaranteed to exist
@test isequal(gens.wpf, [missing, missing, missing])
@test gens.id[1] == "ST"
branches = net1.branches
@test branches.i == [111, 111, 112]
@test branches.j == [112, -113, 113] # negative numbers should be allowed
@test branches.f1 == [1.0, 1.0, 1.0]
@test branches.ckt[1] == "3"
transformers = net1.transformers
@test transformers.i == [112, 113] # 1st entry of 1st row
@test transformers.f1 == [1.0, 1.0] # last entry of 1st row
@test transformers.r1_2 == [0.032470, 0.039570] # 1st entry of 2nd row
@test transformers.sbase1_2 == [200.0, 200.0] # last entry of 2nd row (T2)
@test isequal(transformers.anstar, [missing, 1.01893]) # last entry of 2nd row (T3)
@test transformers.windv1 == [1.0, 1.0] # 1st entry of 3rd row
@test transformers.cx1 == [0.0, 0.0] # last entry of 3rd row
@test transformers.windv2 == [1.0, 1.0] # 1st entry of 4th row
@test transformers.nomv2 == [169.0, 169.0] # last entry of 4th row (T2)
@test isequal(transformers.cx2, [missing, 0.0]) # last entry of 4th row (T3)
@test isequal(transformers.windv3, [missing, 13.8]) # 1st entry of 5th row
@test isequal(transformers.cx3, [missing, 0.0]) # last entry of 5th row
@test transformers.ckt[1] == "G1" # string col
# v30 testfile has both 2-winding and 3-winding data, so should return all columns
@test length(Tables.columnnames(transformers)) == fieldcount(Transformers)
@test size(DataFrame(transformers)) == (2, fieldcount(Transformers))
@test size(transformers) == (2, fieldcount(Transformers))
@test length(transformers) == 2
area_interchanges = net1.area_interchanges
@test area_interchanges.i == [113]
@test area_interchanges.isw == [456]
@test area_interchanges.pdes == [2121.7211]
@test area_interchanges.ptol == [6.0]
@test area_interchanges.arname == ["ABC"]
two_terminal_dc = net1.two_terminal_dc
@test two_terminal_dc.i == [11] # 1st entry of 1st row
@test two_terminal_dc.cccacc == [1.0] # last entry of 1st row
@test two_terminal_dc.ipr == [112] # 1st entry of 2nd row
@test two_terminal_dc.xcapr == [0.0] # last entry of 2nd row
@test two_terminal_dc.ipi == [2222] # 1st entry of 3nd row
@test two_terminal_dc.xcapi == [2.0] # last entry of 3rd row
vsc_dc = net1.vsc_dc
@test vsc_dc.name == ["line 1"] # 1st entry of 1st row
@test vsc_dc.f4 == [1.0] # last entry of 1st row
@test vsc_dc.ibus1 == [1117] # 1st entry of 2nd row
@test vsc_dc.rmpct1 == [100.0] # last entry of 2nd row
@test vsc_dc.ibus2 == [114] # 1st entry of 3nd row
@test vsc_dc.rmpct2 == [100.0] # last entry of 3nd row
switched_shunts = net1.switched_shunts
@test switched_shunts.i == [113] # first col
@test switched_shunts.n1 == [1] # `n1` always present
@test switched_shunts.b1 == [26.0] # `b1` always present
@test switched_shunts.n8 == [0] # `n8` not present; should default to zero
@test switched_shunts.b8 == [0.0] # last col; `b8` not present; default to zero
impedance_corrections = net1.impedance_corrections
@test impedance_corrections.i == [1] # first col
@test impedance_corrections.f11 == [0.0] # last col; `f11` not present; default to zero
multi_terminal_dc = net1.multi_terminal_dc
@test isempty(multi_terminal_dc)
multi_section_lines = net1.multi_section_lines
@test multi_section_lines.i == [1, 114] # first col
@test multi_section_lines.id == ["&1", "&2"] # string col
@test isequal(multi_section_lines.dum2, [missing, 5]) # `dum2` present only for 1 row of the data
@test isequal(multi_section_lines.dum9, [missing, missing]) # last col; not present; default to missing
zones = net1.zones
@test zones.i == [117, 127, 227]
@test zones.zoname == ["ABC", "CDEF", "CDEG"]
area_transfers = net1.area_transfers
@test area_transfers.arfrom == [1, 1]
@test area_transfers.ptran == [10.0, -20.0]
owners = net1.owners
@test owners.i == [1, 2]
@test owners.owname == ["ABC", "CDE"]
facts = net1.facts
@test facts.n == [1]
@test facts.vsref == [0]
end
@testset "v29 file" begin
net2 = parse_network("testfiles/synthetic_data_v29.raw")
caseid = net2.caseid
@test caseid.ic == 0
@test caseid.sbase == 100.0
# Test first and last columns are parsed as expected
buses = net2.buses
@test buses.i == [1, 222222]
@test buses.owner == [1, 7]
# Test string column as expected
@test buses.name[2] == "PRPR C D"
loads = net2.loads
@test loads.i == [1, 222222] # first col
@test loads.owner == [1, 7] # last col
@test isequal(loads.intrpt, [missing, missing])
gens = net2.generators
@test gens.i == [104] # first col
@test gens.f1 == [1.0] # last col guaranteed to exist
@test isequal(gens.wpf, [missing])
@test gens.id[1] == "1" # string col
branches = net2.branches
@test branches.i == [1, 2, 222222]
@test branches.j == [-543210, 9, 333333] # negative numbers should be allowed
@test branches.f1 == [1.0, 1.0, 1.0]
@test branches.ckt[2] == "6"
transformers = net2.transformers
@test length(transformers.i) == 3
@test transformers.i == [42, 4774, 222222] # 1st entry of 1st row
@test transformers.f1 == [1.0, 1.0, 1.0] # last entry of 1st row
@test transformers.r1_2 == [0.0025, 0.0, 0.0005] # 1st entry of 2nd row
@test transformers.sbase1_2 == [100.0, 100.0, 100.0] # last entry of 2nd row
@test transformers.windv1 == [1.0, 1.0462, 1.0] # 1st entry of 3rd row
@test transformers.cx1 == [0.0, 0.0, 0.0] # last entry of 3rd row
# Important to test a row where the 1st character is '0', to get it does not
# get misinterpreted as the start of a "0 bus" records terminating the section.
@test transformers.windv2 == [1.0, 1.045, 0.98250] # 1st entry of 4th row
@test transformers.nomv2 == [138.0, 240.35, 345.0] # last entry of 4th row
@test transformers.ckt == ["K1", "90", "B1"] # string col
# v29 testfile has only 2-winding data, so should return only 2-winding columns
ncols_expected = 43
@test length(Tables.columnnames(transformers)) == ncols_expected
@test size(DataFrame(transformers)) == (3, ncols_expected)
@test size(transformers) == (3, ncols_expected)
@test length(transformers) == 3
area_interchanges = net2.area_interchanges
@test area_interchanges.i == [615, 762]
@test area_interchanges.isw == [615001, 1234]
@test area_interchanges.pdes == [32.677, -224.384]
@test area_interchanges.ptol == [5.0, 5.0]
@test area_interchanges.arname == ["RE", "OTP"]
two_terminal_dc = net2.two_terminal_dc
@test isempty(two_terminal_dc)
vsc_dc = net2.vsc_dc
@test isempty(vsc_dc)
switched_shunts = net2.switched_shunts
@test switched_shunts.i == [175, 177] # first col
@test switched_shunts.n1 == [2, 1] # `n1` col present for both
@test switched_shunts.b1 == [19.76, 15.60] # `b1` col present for both
@test switched_shunts.n2 == [0, 1] # `n2` col present only for second entry
@test switched_shunts.b2 == [0.0, 17.69] # `b2` col present only for second entry
@test switched_shunts.n8 == [0, 0] # `n8` col not present for either entry
@test switched_shunts.b8 == [0.0, 0.0] # last col; `b8` col not present for either entry
impedance_corrections = net2.impedance_corrections
@test impedance_corrections.i == [1, 2] # first col
@test impedance_corrections.f11 == [3.34, 1.129] # last col
multi_terminal_dc = net2.multi_terminal_dc
@test length(multi_terminal_dc) == 1
mt_dc = only(multi_terminal_dc.lines)
line_id = mt_dc.line_id
@test line_id.i == 1 # first val
@test line_id.vconvn == 0 # last val
converters = mt_dc.converters
@test length(converters) == line_id.nconv == 4
@test converters.ib == [402, 401, 212, 213]
@test converters.cnvcod == [3, 3, 1, 4]
dc_buses = mt_dc.buses
@test length(dc_buses) == line_id.ndcbs == 5
@test dc_buses.idc == [1, 2, 3, 4, 5]
@test dc_buses.owner == [4, 2, 4, 2, 4]
dc_links = mt_dc.links
@test length(dc_links) == line_id.ndcln == 4
@test dc_links.idc == [1, 2, 3, 4]
@test dc_links.ldc == [0.0, 0.0, 0.0, 0.0]
multi_section_lines = net2.multi_section_lines
@test isempty(multi_section_lines)
zones = net2.zones
@test zones.i == [1, 9]
@test zones.zoname == ["ABL", "EFGN"]
area_transfers = net2.area_transfers
@test isempty(area_transfers)
owners = net2.owners
@test owners.i == [1, 2]
@test owners.owname == ["EAI", "OUYK"]
facts = net2.facts
@test isempty(facts)
end
@testset "v33 file" begin
net33 = parse_network("testfiles/synthetic_data_v33.RAW")
@test net33 isa Network
@test net33.version == 33
caseid = net33.caseid
@test caseid.ic == 0
@test caseid.sbase == 100.0
@test caseid.rev == 33
buses = net33.buses
@test buses.i == [1, 500] # first col
@test buses.name == ["WINNSBORO 0", "MC CORMICK 0"] # string col
@test buses.evlo == [0.9, 0.9] # last col
loads = net33.loads
@test loads.i == [2, 500] # first col
@test loads.scale == [1, 1] # last col
@test isequal(loads.intrpt, [missing, missing]) # possible last col
fixed_shunts = net33.fixed_shunts
@test fixed_shunts.i == [320, 784] # first col
@test fixed_shunts.bl == [48.274, 19.939] # last col
gens = net33.generators
@test gens.i == [9, 498] # first col
@test gens.wpf == [1.0, 1.0] # last col
branches = net33.branches
@test branches.i == [2, 500] # first col
@test branches.met == [1, 1] # only in v33
@test branches.f4 == [1.0, 1.0] # last col
# v33 has extra columns on rows 1, 3, 4, 5.
transformers = net33.transformers
@test transformers.i == [8, 190, 498] # 1st entry of 1st row
@test all(transformers.vecgrp .== "") # last entry of 1st row
@test transformers.r1_2 == [3.55062E-4, 7.65222E-4, 4.00610E-3] # 1st entry of 2nd row
@test transformers.sbase1_2 == [100.0, 100.0, 100.0] # last entry of 2nd row (T2)
@test isequal(transformers.anstar, [missing, -65.843144, missing]) # last entry of 2nd row (T3)
@test transformers.windv1 == [1.0, 1.0, 1.0] # 1st entry of 3rd row
@test transformers.cnxa1 == [0.0, 0.0, 0.0] # last entry of 3rd row
@test transformers.windv2 == [1.0, 1.0, 1.0] # 1st entry of 4th row
@test transformers.nomv2 == [345.0, 115.0, 138.0] # last entry of 4th row (T2)
@test isequal(transformers.cnxa2, [missing, 0.0, missing]) # last entry of 4th row (T3)
@test isequal(transformers.windv3, [missing, 1.0, missing]) # 1st entry of 5th row
@test isequal(transformers.cnxa3, [missing, 0.0, missing]) # last entry of 5th row
@test transformers.ckt[1] == "1" # string col
# v33 testfile has both 2-winding and 3-winding data, so should return all columns
@test length(Tables.columnnames(transformers)) == fieldcount(Transformers)
@test size(DataFrame(transformers)) == (3, fieldcount(Transformers))
@test size(transformers) == (3, fieldcount(Transformers))
@test length(transformers) == 3
area_interchanges = net33.area_interchanges
@test area_interchanges.i == [1]
@test area_interchanges.arname == ["SouthCarolin"]
two_terminal_dc = net33.two_terminal_dc
@test two_terminal_dc.name == ["DC Line 1", "DC Line 1"] # first col
@test two_terminal_dc.cccacc == [0.0, 0.0] # last entry of 1st row
@test two_terminal_dc.ipr == [2060653, 3008030] # 1st entry of 2nd row
@test two_terminal_dc.xcapr == [0.0, 0.0] # last entry of 2nd row
@test two_terminal_dc.ipi == [66353, 61477] # 1st entry of 3nd row
@test two_terminal_dc.xcapi == [0.0, 0.0] # last entry of 3rd row
vsc_dc = net33.vsc_dc
@test isempty(vsc_dc)
impedance_corrections = net33.impedance_corrections
@test impedance_corrections.i == [1, 2, 3] # first col
@test impedance_corrections.f6 == [1.03, 0.0, 1.41] # col present on some rows not others
@test impedance_corrections.f11 == [0.0, 0.0, 0.0] # last col (missing, default to zero)
multi_terminal_dc = net33.multi_terminal_dc
@test length(multi_terminal_dc) == 1
mt_dc = only(multi_terminal_dc.lines)
line_id = mt_dc.line_id
@test line_id.name == "DC Line 1" # first val
@test line_id.vconvn == 0 # last val
multi_section_lines = net33.multi_section_lines
@test multi_section_lines.i == [1] # first col
@test multi_section_lines.id == ["&1"] # string col
@test multi_section_lines.met == [1] # only in v33 data
@test isequal(multi_section_lines.dum1, [3]) # `dum1` is last col present
@test isequal(multi_section_lines.dum9, [missing]) # last col; not present; default to missing
zones = net33.zones
@test zones.i == [1, 2]
@test zones.zoname == ["Upstate", "Midlands"]
area_transfers = net33.area_transfers
@test isempty(area_transfers)
owners = net33.owners
@test owners.i == [1]
@test owners.owname == ["1"]
facts = net33.facts
@test isempty(facts)
switched_shunts = net33.switched_shunts
@test switched_shunts.i == [27, 491] # first col
@test switched_shunts.adjm == [0, 0] # 3rd col (only in v33)
@test switched_shunts.stat == [1, 1] # 4th col (only in v33)
@test switched_shunts.n1 == [1, 1] # `n1` col always present
@test switched_shunts.b1 == [80.0, 50.0] # `b1` col always present
@test switched_shunts.n8 == [0, 0] # `n8` col not present; default to zero
@test switched_shunts.b8 == [0.0, 0.0] # `b8` col not present; default to zero
end
@testset "delim=' '" begin
net_space = parse_network("testfiles/spacedelim.raw")
caseid = net_space.caseid
@test caseid == CaseID(ic=0, sbase=100.0)
buses = net_space.buses
@test length(buses) == 2
@test buses.name == ["ABC", "ABCDEFGH"]
loads = net_space.loads
@test loads.i == [7, 8478]
gens = net_space.generators
@test gens.i == [24, 9008]
branches = net_space.branches
@test branches.i == [1, 8151]
transformers = net_space.transformers
@test transformers.i == [1, 8462]
area_interchanges = net_space.area_interchanges
@test area_interchanges.i == [1]
@test isempty(net_space.two_terminal_dc)
@test isempty(net_space.vsc_dc)
switched_shunts = net_space.switched_shunts
@test switched_shunts.i == [2, 8460]
@test isempty(net_space.impedance_corrections)
@test isempty(net_space.multi_terminal_dc)
@test isempty(net_space.multi_section_lines)
zones = net_space.zones
@test zones.zoname == ["FIRST", "ISOLATED"]
@test isempty(net_space.area_transfers)
owners = net_space.owners
@test owners.owname == ["OWNER1"]
@test isempty(net_space.facts)
# test we allow specifying the delimiter manually
net_space_manual = parse_network("testfiles/spacedelim.raw"; delim=' ')
@test net_space.branches.j == net_space_manual.branches.j
end
@testset "issues" begin
sz = parse_network("testfiles/spacezero.raw")
@test length(sz.buses) == 2
@test length(sz.loads) == 1
qz = parse_network("testfiles/quotedzero.raw")
@test length(qz.buses) == 2
# These records are after the quoted zero
@test length(qz.switched_shunts) == 2
@test length(qz.zones) == 2
end
@testset "`Tables.namedtupleiterator(::Records)`" begin
# https://github.com/nickrobinson251/PowerFlowData.jl/issues/76
net = parse_network("testfiles/synthetic_data_v30.raw")
buses = net.buses
@test first(Tables.namedtupleiterator(buses)).i == 111
# Transformers has own `Tables.schema` definition so needs testing specifically.
transformers = net.transformers
@test first(Tables.namedtupleiterator(transformers)).i == 112
end
@testset "empty network" begin
empty_net = Network(version=30)
@test isempty(empty_net)
nonempty_net = Network(version=30, owners=Owners([1], ["Owner1"]))
@test !isempty(nonempty_net)
end
end
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | docs | 1491 | # PowerFlowData
[](https://nickrobinson251.github.io/PowerFlowData.jl/dev)
[](https://github.com/nickrobinson251/PowerFlowData.jl/actions)
[](https://codecov.io/gh/nickrobinson251/PowerFlowData.jl)
[](https://github.com/invenia/BlueStyle)
[](https://github.com/SciML/ColPrac)
[PowerFlowData.jl](https://github.com/nickrobinson251/PowerFlowData.jl)
provides a parser for PSS/E-format `.raw` Power Flow Data Files.
To read a `.raw` file, use `parse_network`:
```julia
using PowerFlowData
parse_network("file.raw")
```
This will return a `Network` object, which contains the data parsed into dedicated structures matching the
[PSS/E](https://en.wikipedia.org/wiki/Power_system_simulator_for_engineering)-format specification.
**[Documentation](https://nickrobinson251.github.io/PowerFlowData.jl/dev)**
The format specification is based on old PSS/E user-manuals and example files I could find online.
Currently v30 and v33 of the format are supported.
Please open an issue if you run into any problems or missing features.
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | docs | 1782 | # Alternatives
## Julia
I am are aware of two other open-source packages with functionality to parse PSS/E files:
- [PowerModels.jl](https://lanl-ansi.github.io/PowerModels.jl/stable/parser/#PTI-Data-Files-(PSS/E))
- [PowerSystems.jl](https://nrel-siip.github.io/PowerSystems.jl/stable/modeler_guide/generated_parsing/)
I have not used either so cannot recommend one over the other.
From what I can see, these parsers are almost identical to each other.
It seems PowerSystems.jl originally vendored the PowerModels.jl code, but the parsers may have diverged slightly over time.
Both of these packages only support parsing v33 PSS/E files, and only parse a subset of the data categories in the file.
Whereas PowerFlowData.jl (this package) can parse all data categories from both v30 and v33 PSS/E files.
Importantly, these alternatives also take a completely different approach to this package.
These other parsers read the `.raw` files as a `String` (e.g. using `readlines`), then operate on string data, and parse strings into other Julia types as necessary.
PowerFlowData.jl reads the `.raw` files as a bytes buffer (`Vector{UInt8}`) then parses the bytes directly into Julia types,
which is much faster and more memory efficient.
This package was originally developed as a fun exercise, but should correctly implement the full data format specification.
Please feel encouraged to give this package a try, and open issues if you encounter any
problems or missing features.
## Others
In Python, there is a package named [`grg-pssedata`](https://github.com/lanl-ansi/grg-pssedata), which says it parses PSSE v33 data files.
In Matlab, the [`MATPOWER`](https://github.com/MATPOWER/matpower/) package says it has parsing functionality for (unspecified) PSSE data files.
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | docs | 1150 | # API
```@docs
parse_network
```
## Network
```@docs
Network
```
## Case ID
```@docs
CaseID
```
## Buses
```@docs
Buses
Buses30
Buses33
```
## Loads
```@docs
Loads
```
## Fixed Shunts
```@docs
FixedShunts
```
## Generators
```@docs
Generators
```
## Branches
```@docs
Branches
Branches30
Branches33
```
## Transformers
```@docs
Transformers
```
## Area Interchanges
```@docs
AreaInterchanges
```
## Two-Terminal DC Lines
```@docs
TwoTerminalDCLines
TwoTerminalDCLines30
TwoTerminalDCLines33
```
## VSC DC Lines
```@docs
VSCDCLines
```
## Switched Shunts
```@docs
SwitchedShunts
SwitchedShunts30
SwitchedShunts33
```
## Transformer Impedance Corrections
```@docs
ImpedanceCorrections
```
## Multi-Terminal DC Lines
```@docs
MultiTerminalDCLines
MultiTerminalDCLine
DCLineID
DCLineID30
DCLineID33
ACConverters
DCBuses
DCLinks
```
## Multi-Section Line Groups
```@docs
MultiSectionLineGroups
MultiSectionLineGroups30
MultiSectionLineGroups33
```
## Zones
```@docs
Zones
```
## Inter-Area Transfers
```@docs
InterAreaTransfers
```
## Owners
```@docs
Owners
```
## FACTS Devices
```@docs
FACTSDevices
FACTSDevices30
FACTSDevices33
```
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | docs | 1848 | # Implementation details
This page has rough notes about the internals of PowerFlowData.jl.
We use [Parsers.jl](https://github.com/JuliaData/Parsers.jl/) to parse bytes into Julia types.
Broadly speaking, we use `Parsers.Options` to configure the parsing based on the `.raw` format (e.g. `,` characters are delimiters), and then `Parsers.xparse` to actually parse the bytes between delimiters into the expected Julia types.
The expected Julia type depends on the category of data we are reading at that point in the file (buses, loads, …);
if the PSS/E user manual says "load records" should come after "bus records", and each load record should have 12 columns with the first column containing an integer "bus number", then we try to parse the first value in a load record as an `Int`, and so on.
The aim is to capture the domain knowledge / format specification in the types,
and keep the parsing code as minimal as possible (relying on the types for the domain knowledge).
When trying to support multiple versions of the format, the rough strategy is:
* if a wholly new data category exists in the new format, create a new `Records` subtype
* if a data category has added a new column to the end of a record, add a new `Union{T, Missing}` field to the existing `Records` subtype
* if a data category has added/removed columns in the middle of a record, or changed the element type of a column, create a new `Records` subtype with a common supertype as the existing `Records` subtype for the category
(e.g. `Buses30 <: Buses`, `Buses33 <: Buses`, `Buses <: Records`)
* if a version-specific `Records` subtype is being used, update the top-level `parse_network` function to parse the records into the appropriate type, and in the order expected by the version of the format
(using the version number extracted as part of the Case ID data).
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | docs | 2093 | ```@meta
CurrentModule = PowerFlowData
```
# PowerFlowData
[PowerFlowData.jl](https://github.com/nickrobinson251/PowerFlowData.jl)
provides a parser for PSS/E-format `.raw` Power Flow Data Files.
To read a `.raw` file, use [`parse_network`](@ref):
```julia
parse_network("file.raw")
```
This will return a [`Network`](@ref) object, which contains the data parsed into dedicated structures matching the PSS/E-format specification.
You can specify what version of the PSS/E data format the file is in using the `v` keyword,
like:
```julia
parse_network("file.raw"; v=33)
```
Alternatively, the version of the data format will automatically be determined when parsing.
Versions 30 and 33 of the format are currently supported.
You can specify which character separates values in the file using the `delim` keyword,
like:
```julia
parse_network("file.raw"; delim=' ')
```
If not specified, the delimiter will automatically be detected when parsing.
Comma delimited files `delim=','` and space delimited files `delim=' '` are currently supported.
## Example
Usually your data will be in a file, and you'd read it with `parse_network("file.raw")`,
but here we'll pass in the data directly, to show how it matches to the output:
```@repl example1
using PowerFlowData, DataFrames
data = IOBuffer("""
0, 100.00 / PSS/E-30.3 WED, SEP 15 2021 21:04
SE SNAPSHOT 15-09-2021 PEAK CASE 18:00
FULL COPY OF SYNTHETIC
1,'AAA 3 ', 111.0000,4, 0.000, 0.000, 327, 1,0.00000, 0.0000, 1
222222,'PRPR C D ', 42.0000,1, 0.000, 0.000, 694, 24,1.11117, 20.0606, 7
0 / END OF BUS DATA, BEGIN LOAD DATA
"""
);
network = parse_network(data; v=30);
NamedTuple(network.caseid) # Case Identification data is a single row.
DataFrame(network.buses) # Bus data, and all other data, is a table.
```
For working with the tabular data within a [`Network`](@ref) directly you can use Tables.jl.
For example, to iterate the [`Buses`](@ref):
```@repl example1
using Tables
for bus in Tables.rows(network.buses)
@show bus.name
end
```
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 1.5.0 | 04167df719ef1e8a1471a7033634c441f69bda1c | docs | 997 | # Test Files
### Synthetic Data
These were created by hand, to match the schema of realistic files, but using entirely made up data.
Note that the files are not representative of real data beyond the schema.
For example, the branches data might references buses which are not present in the buses data, which should never happen in realistic files.
1. `_v30.raw`: v30 format data.
2. `_v29.raw`: v29 format data.
3. `_v33.raw`: v33 format data.
### Issues
These files were created to demonstrate issues that the parser should now be able to handle.
1. `spacezero.raw`: v30 format data with a space before the `0` bus number that indicates the end of the records.
1. `spacedelim.raw`: v30 format data with space as the delimiter.
1. `quotedzero.raw`: v30 format data with a quoted zero `'0'` bus number indicating the end of one of the records.
Based on the `spacedelim.raw` file.
---
_This is a work of fiction. Any resemblance to actual datas, living or dead, is purely coincidental._
| PowerFlowData | https://github.com/nickrobinson251/PowerFlowData.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 267 | using Documenter, NLIDatasets
makedocs(sitename = "NLIDatasets.jl",
format = Documenter.HTML(),
modules = [NLIDatasets],
pages = ["Home" => "index.md"],
doctest = true)
deploydocs(repo = "github.com/dellison/NLIDatasets.jl.git")
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 691 | module NLIDatasets
using DataDeps
using HTTP
function getzip(url, file)
headers = ["User-Agent" => "NLIDatasets.jl",
"Accept" => "*/*",
"Accept-Encoding" => "gzip, deflate, br"]
HTTP.download(url, file, headers)
end
function register_data(name, descr, url, sha; fetch=getzip, postfetch=unpack)
kw = (fetch_method=fetch, post_fetch_method=postfetch)
DataDeps.register(DataDep(name, descr, url, sha; kw...))
end
include("snli.jl")
include("multinli.jl")
include("xnli.jl")
include("scitail.jl")
include("hans.jl")
include("breaking_nli.jl")
include("anli.jl")
using .SNLI, .MultiNLI, .XNLI, .SciTail, .HANS, .BreakingNLI, .ANLI
end # module
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 1382 | """
ANLI
For details, see the [GitHub page](https://github.com/facebookresearch/anli) or read the [2019 paper](https://arxiv.org/pdf/1910.14599.pdf).
Available data:
```julia
ANLI.R1_train_jsonl()
ANLI.R1_dev_jsonl()
ANLI.R1_test_jsonl()
ANLI.R2_train_jsonl()
ANLI.R2_dev_jsonl()
ANLI.R2_test_jsonl()
ANLI.R3_train_jsonl()
ANLI.R3_dev_jsonl()
ANLI.R3_test_jsonl()
```
"""
module ANLI
import ...register_data
using DataDeps: @datadep_str, unpack
anli_file(file, files...) = joinpath(datadep"ANLI", "anli_v0.1", file, files...)
R1_train_jsonl() = anli_file("R1", "train.jsonl")
R1_dev_jsonl() = anli_file("R1", "dev.jsonl")
R1_test_jsonl() = anli_file("R1", "test.jsonl")
R2_train_jsonl() = anli_file("R2", "train.jsonl")
R2_dev_jsonl() = anli_file("R2", "dev.jsonl")
R2_test_jsonl() = anli_file("R2", "test.jsonl")
R3_train_jsonl() = anli_file("R3", "train.jsonl")
R3_dev_jsonl() = anli_file("R3", "dev.jsonl")
R3_test_jsonl() = anli_file("R3", "test.jsonl")
function __init__()
register_data(
"ANLI",
"""
ANLI is the Adversarial Natural Language Inference Benchmark.
ANLI is licensed under Creative Commons-Non Commercial 4.0.
""",
"https://dl.fbaipublicfiles.com/anli/anli_v0.1.zip",
"16ac929a7e90ecf9093deaec89cc81fe86a379265a5320a150028efe50c5cde8",
postfetch=unpack
)
end
end # module
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 2086 | """
BreakingNLI
A dataset of 8193 premise-hypothesis sentence-pairs for NLI.
Each example is annotated to entailment, contradiction, and neutral.
The premise and the hypothesis are identical except for one
word/phrase that was replaced. This dataset is meant for testing
methods trained to solve the natural language inference task, and it
requires some lexical and world knowledge to achieve reasonable
performance on it.
For details, see the [GitHub page](https://github.com/BIU-NLP/Breaking_NLI) or read the [2018 paper](https://aclweb.org/anthology/P18-2103/).
Available data:
```julia
BreakingNLI.test_jsonl()
```
"""
module BreakingNLI
import ...register_data
using DataDeps: @datadep_str, unpack
test_jsonl() = joinpath(datadep"Breaking_NLI", "data", "dataset.jsonl")
function __init__()
register_data(
"Breaking_NLI",
"""
Each example is annotated to entailment, contradiction, and neutral.
The premise and the hypothesis are identical except for one
word/phrase that was replaced. This dataset is meant for testing
methods trained to solve the natural language inference task, and it
requires some lexical and world knowledge to achieve reasonable
performance on it.
For details, see the [GitHub page](https://github.com/BIU-NLP/Breaking_NLI) or read the [2018 paper](https://aclweb.org/anthology/P18-2103/).
This dataset is distributed as a
Licensed under a Creative Commons Attribution-ShareAlike 4.0
International License:
https://creativecommons.org/licenses/by-sa/4.0/
""",
"https://github.com/BIU-NLP/Breaking_NLI/archive/8a7658c1ce6b732f4e8af3b06560f1a13b8b18b0.zip",
"0ccf9e308245036dec52e369316b94326ef06c96729b336d0269974b0814581e",
postfetch = function (zip)
unpack(zip)
unpack(joinpath(datadep"Breaking_NLI",
"Breaking_NLI-8a7658c1ce6b732f4e8af3b06560f1a13b8b18b0",
"breaking_nli_dataset.zip"))
end
)
end
end # module
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 1439 | """
HANS
HANS (Heauristic Analysis for NLI Systems) is a dataset for NLI.
It contains the set of examples used in the 2019 paper "Right for the
Wrong Reasons: Diagnosing Syntactic Heuristics in Natural Language
Inference" by R. Tom McCoy, Ellie Pavlick, and Tal Linzen.
For details, see the [2019 paper](https://www.aclweb.org/anthology/P19-1334) "Right for the Wrong Reasons:
Diagnosing Syntactic Heuristics in Natural Language Inference"
by by R. Tom McCoy, Ellie Pavlick, and Tal Linzen.
Consists of a set of examples for evaluation, provided with `test_tsv`.
```julia
HANS.test_tsv()
```
"""
module HANS
import ...register_data
using DataDeps: @datadep_str
hansfile(filename) =
joinpath(datadep"HANS", "hans-0e52769572ab97da1b919baf222f355bdf481d88", filename)
test_tsv() = hansfile("heuristics_evaluation_set.txt")
function __init__()
register_data(
"HANS",
"""
HANS (Heauristic Analysis for NLI Systems) is a dataset for natural language inference.
It contains the set of examples used in the 2019 paper "Right for the Wrong Reasons: Diagnosing Syntactic Heuristics in Natural Language Inference" by R. Tom McCoy, Ellie Pavlick, and Tal Linzen.
""",
"https://github.com/tommccoy1/hans/archive/0e52769572ab97da1b919baf222f355bdf481d88.zip",
"24316fa3d7298dfd5198059ed1c4eab0b84876cfbc8851df48e96abaa36ead8c")
end
end # module
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 1822 | """
MultiNLI
A corpus of 433k sentence pairs for NLI.
For details, see the [MultiNLI home page](https://www.nyu.edu/projects/bowman/multinli/)
or read the [2018 paper](https://www.nyu.edu/projects/bowman/multinli/paper.pdf) "A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference" by Adina Williams, NIkita Nangia, and Samuel R. Bowman.
Included data:
```julia
MultiNLI.train_tsv()
MultiNLI.train_jsonl()
MultiNLI.dev_matched_tsv()
MultiNLI.dev_matched_jsonl()
MultiNLI.dev_mismatched_tsv()
MultiNLI.dev_mismatched_jsonl()
```
"""
module MultiNLI
import ...register_data
using DataDeps: @datadep_str
multinli_file(filename) = joinpath(datadep"MultiNLI", "multinli_1.0", filename)
train_tsv() = multinli_file("multinli_1.0_train.txt")
train_jsonl() = multinli_file("multinli_1.0_train.jsonl")
dev_matched_tsv() = multinli_file("multinli_1.0_dev_matched.txt")
dev_matched_jsonl() = multinli_file("multinli_1.0_dev_matched.jsonl")
dev_mismatched_tsv() = multinli_file("multinli_1.0_dev_mismatched.txt")
dev_mismatched_jsonl() = multinli_file("multinli_1.0_dev_mismatched.jsonl")
function __init__()
register_data(
"MultiNLI",
"""
The Multi-Genre Natural Language Inference (MultiNLI) corpus
is a crowd-sourced collection of 433k sentence pairs annotated
with textual entailment information.
https://www.nyu.edu/projects/bowman/multinli/
The dataset is distributed as a 227MB zip file.
For license details, see details the data description paper:
https://www.nyu.edu/projects/bowman/multinli/paper.pdf
""",
"https://www.nyu.edu/projects/bowman/multinli/multinli_1.0.zip",
"049f507b9e36b1fcb756cfd5aeb3b7a0cfcb84bf023793652987f7e7e0957822")
end
end # module
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 1516 | """
SciTail
SciTail is a NLI dataset created from multiple-choice science exams and web sentences.
For details, see the [2018 paper](http://ai2-website.s3.amazonaws.com/publications/scitail-aaai-2018_cameraready.pdf) "SciTail: A Textual Entailment Dataset from Science Question Answering"
by Tushar Khot, Asish Sabharwal, and Peter Clark.
```julia
SciTail.train_tsv()
SciTail.train_jsonl()
SciTail.dev_tsv()
SciTail.dev_jsonl()
SciTail.test_tsv()
SciTail.test_jsonl()
```
"""
module SciTail
import ...register_data
using DataDeps: @datadep_str
scitail_base() = joinpath(datadep"SciTailV1.1", "SciTailV1.1")
scitail_jsonl(filename) = joinpath(scitail_base(), "snli_format", filename)
scitail_tsv(filename) = joinpath(scitail_base(), "tsv_format", filename)
train_tsv() = scitail_tsv("scitail_1.0_train.tsv")
train_jsonl() = scitail_jsonl("scitail_1.0_train.txt")
dev_tsv() = scitail_tsv("scitail_1.0_dev.tsv")
dev_jsonl() = scitail_jsonl("scitail_1.0_dev.txt")
test_tsv() = scitail_tsv("scitail_1.0_test.tsv")
test_jsonl() = scitail_jsonl("scitail_1.0_test.txt")
function __init__()
register_data(
"SciTailV1.1",
"""
The SciTail dataset is an entailment dataset created from multiple-choice science exams and web sentences.
See:
http://data.allenai.org/scitail/
""",
"http://data.allenai.org.s3.amazonaws.com/downloads/SciTailV1.1.zip",
"3fccd37350a94ca280b75998568df85fc2fc62843a3198d644fcbf858e6943d5")
end
end # module
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 1965 | """
SNLI
A corpus of 570k human-written English sentence pairs for NLI.
SNLI sentence pairs are manually labeled with labels entailment, contradiction,
and neutral.
For details, see the [SNLI home page](https://nlp.stanford.edu/projects/snli/)
or read the [2015 paper](https://nlp.stanford.edu/pubs/snli_paper.pdf) "A large annotated corpus for learning natural language inference"
by Samuel R. Bowman, Gabor Angeli, Christopher Potts, and Christopher Manning.
Included data:
```julia
SNLI.train_tsv()
SNLI.train_jsonl()
SNLI.dev_tsv()
SNLI.dev_jsonl()
SNLI.test_tsv()
SNLI.test_jsonl()
```
"""
module SNLI
import ...register_data
using DataDeps: @datadep_str
snli_file(filename) = joinpath(datadep"SNLI", "snli_1.0", filename)
train_tsv() = snli_file("snli_1.0_train.txt")
train_jsonl() = snli_file("snli_1.0_train.jsonl")
dev_tsv() = snli_file("snli_1.0_dev.txt")
dev_jsonl() = snli_file("snli_1.0_dev.jsonl")
test_tsv() = snli_file("snli_1.0_test.txt")
test_jsonl() = snli_file("snli_1.0_test.jsonl")
function __init__()
register_data(
"SNLI",
"""
The SNLI corpus (version 1.0) is a collection of 570k human-written
English sentence pairs manually labeled for balanced classification
with the labels entailment, contradiction, and neutral, supporting
the task of natural language inference (NLI), also known as recognizing
textual entailment (RTE).
https://nlp.stanford.edu/projects/snli/
The dataset is distributed as a 100MB zip file.
The Stanford Natural Language Inference Corpus by The Stanford NLP Group
is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Based on a work at http://shannon.cs.illinois.edu/DenotationGraph/.
""",
"https://nlp.stanford.edu/projects/snli/snli_1.0.zip",
"afb3d70a5af5d8de0d9d81e2637e0fb8c22d1235c2749d83125ca43dab0dbd3e")
end
end # module
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 1012 | """
XNLI
A collection of 5,000 test and 2,500 dev pairs for the `MultiNLI` corpus.
For details, see the [2018 paper](https://www.aclweb.org/anthology/papers/D/D18/D18-1269/) "XNLI: Evaluating Cross-lingual Sentence Representations."
```julia
XNLI.dev_tsv()
XNLI.dev_jsonl()
XNLI.test_tsv()
XNLI.test_jsonl()
```
"""
module XNLI
import ...register_data
using DataDeps: @datadep_str
xnlifile(filename) = joinpath(datadep"XNLI", "XNLI-1.0", filename)
dev_tsv() = xnlifile("xnli.dev.tsv")
dev_jsonl() = xnlifile("xnli.dev.jsonl")
test_tsv() = xnlifile("xnli.test.tsv")
test_jsonl() = xnlifile("xnli.test.jsonl")
function __init__()
register_data(
"XNLI",
"""
The Cross-lingual Natural Language Inference (XNLI) corpus is a crowd-sourced collection of 5,000 test and 2,500 dev pairs for the `MultiNLI` corpus.
""",
"http://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip",
"4ba1d5e1afdb7161f0f23c66dc787802ccfa8a25a3ddd3b165a35e50df346ab1")
end
end
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | code | 1965 | using NLIDatasets, Test
@testset "NLIDatasets.jl" begin
@testset "SNLI" begin
using NLIDatasets: SNLI
@test isfile(SNLI.train_tsv())
@test isfile(SNLI.train_jsonl())
@test isfile(SNLI.dev_tsv())
@test isfile(SNLI.dev_jsonl())
@test isfile(SNLI.test_tsv())
@test isfile(SNLI.test_jsonl())
end
@testset "MultiNLI" begin
using NLIDatasets: MultiNLI
@test isfile(MultiNLI.train_tsv())
@test isfile(MultiNLI.train_jsonl())
@test isfile(MultiNLI.dev_matched_tsv())
@test isfile(MultiNLI.dev_matched_jsonl())
@test isfile(MultiNLI.dev_mismatched_tsv())
@test isfile(MultiNLI.dev_mismatched_jsonl())
end
@testset "XNLI" begin
using NLIDatasets: XNLI
@test isfile(XNLI.dev_tsv())
@test isfile(XNLI.dev_jsonl())
@test isfile(XNLI.test_tsv())
@test isfile(XNLI.test_jsonl())
end
@testset "SciTail" begin
using NLIDatasets: SciTail
@test isfile(SciTail.train_tsv())
@test isfile(SciTail.train_jsonl())
@test isfile(SciTail.dev_tsv())
@test isfile(SciTail.dev_jsonl())
@test isfile(SciTail.test_tsv())
@test isfile(SciTail.test_jsonl())
end
@testset "HANS" begin
using NLIDatasets: HANS
@test isfile(HANS.test_tsv())
end
@testset "Breaking_NLI" begin
using NLIDatasets: BreakingNLI
@test isfile(BreakingNLI.test_jsonl())
end
@testset "ANLI" begin
using NLIDatasets: ANLI
@test isfile(ANLI.R1_train_jsonl())
@test isfile(ANLI.R1_dev_jsonl())
@test isfile(ANLI.R1_test_jsonl())
@test isfile(ANLI.R2_train_jsonl())
@test isfile(ANLI.R2_dev_jsonl())
@test isfile(ANLI.R2_test_jsonl())
@test isfile(ANLI.R3_train_jsonl())
@test isfile(ANLI.R3_dev_jsonl())
@test isfile(ANLI.R3_test_jsonl())
end
end
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | docs | 1586 | # NLIDatasets.jl
[](https://dellison.github.io/NLIDatasets.jl/stable) [](https://dellison.github.io/NLIDatasets.jl/dev)
[](https://travis-ci.org/dellison/NLIDatasets.jl) [](https://codecov.io/gh/dellison/NLIDatasets.jl)
NLIDatasets.jl is a Julia package for working with Natural Language Inference datasets.
## Datasets
- [SNLI](https://nlp.stanford.edu/projects/snli/) (see [paper](https://nlp.stanford.edu/pubs/snli_paper.pdf))
- [MultiNLI](https://www.nyu.edu/projects/bowman/multinli/) (see [paper](https://www.nyu.edu/projects/bowman/multinli/paper.pdf))
- [XNLI](https://www.nyu.edu/projects/bowman/xnli/) (see [paper](https://www.aclweb.org/anthology/papers/D/D18/D18-1269/))
- [SciTail](http://data.allenai.org/scitail/) (see [paper](http://ai2-website.s3.amazonaws.com/publications/scitail-aaai-2018_cameraready.pdf))
- [HANS](https://github.com/tommccoy1/hans) (see [paper](https://www.aclweb.org/anthology/P19-1334))
- [BreakingNLI](https://github.com/BIU-NLP/Breaking_NLI) (see [paper](https://www.aclweb.org/anthology/P18-2103/))
- [ANLI](https://github.com/facebookresearch/anli) (see [paper](https://arxiv.org/abs/1910.14599))
## Usage
See the [documentation](https://dellison.github.io/NLIDatasets.jl/dev).
```julia
using NLIDatasets: SNLI
train, dev = SNLI.train_tsv(), SNLI.dev_tsv()
```
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | a7aa61929eb960c930fcb27e12c7a975f463c05f | docs | 689 | # NLIDatasets.jl
NLIDatasets.jl is a Julia package for working with datasets for the Natural Language Inference task (also called Relational Text Entailment, or RTE).
Provides an interface to the following datasets:
- [SNLI](@ref SNLI)
- [MultiNLI](@ref MultiNLI)
- [XNLI](@ref XNLI)
- [HANS](@ref HANS)
- [BreakingNLI](@ref BreakingNLI)
- [SciTail](@ref SciTail)
- [ANLI](@ref ANLI)
## SNLI
```@docs
NLIDatasets.SNLI
```
## MultiNLI
```@docs
NLIDatasets.MultiNLI
```
## XNLI
```@docs
NLIDatasets.XNLI
```
## HANS
```@docs
NLIDatasets.HANS
```
## BreakingNLI
```@docs
NLIDatasets.BreakingNLI
```
## SciTail
```@docs
NLIDatasets.SciTail
```
## ANLI
```@docs
NLIDatasets.ANLI
```
| NLIDatasets | https://github.com/dellison/NLIDatasets.jl.git |
|
[
"MIT"
] | 0.2.0 | 8d50c96f4ba5e1e2fd524116b4ef97b29d5f77da | code | 151 | module PolygonInbounds
export inpoly2, Demo
include("generic.jl")
include("utilities.jl")
include("inpoly2.jl")
include("polydemo.jl")
end # module
| PolygonInbounds | https://github.com/KlausC/PolygonInbounds.jl.git |
|
[
"MIT"
] | 0.2.0 | 8d50c96f4ba5e1e2fd524116b4ef97b29d5f77da | code | 8008 | """
PolygonMesh(nodes[, edges])
Polygon given by `nodes` and `edges`. Several formats are supported:
* nodes as nx2 matrix
* nodes as n-vector of 2-vectors or 2-tuples of x-y-coordinates
* edges as nx2 matrix of indices
* edges as n-vector of indices`
* edges empty
Incomplete edges are filles up by best guess. The columns must be permutations of `1:n`.
"""
struct PolygonMesh{A,U,E<:Union{Nothing,AbstractArray{<:Integer}}}
nodes::U
edges::E
function PolygonMesh(n::U, ed::E) where {U,E}
A = ed isa AbstractMatrix ? max(size(ed, 2) - 2, 0) : 0
# the number of stored area indices per edge
checkarguments(n, ed)
new{A,U,E}(n, ed)
end
PolygonMesh(n::U) where U = PolygonMesh(n, nothing)
end
"""
PointsInbound(p)
Vector of points. Several formats are supported for points:
* as 2-vector of real numbers (set of single point)
* as nx2 matrix of real numbers - each row represents `(x, y)`
* as n-vector of 2-vectors or 2-tuples of x-y-coordinates
"""
struct PointsInbound{V}
points::V
PointsInbound(p::V) where V = new{V}(p)
end
"""
see `InOnOut` and `InOnBit`
"""
abstract type AbstractOutputFormat end
"""
InOnOut{IN,ON,OUT}
Expected format of output is one of three constant values.
`InOnOut{1,0,-1}` returns `1`, `0`, `-1` if point is in, on, or out respectively.
"""
struct InOnOut{IN,ON,OUT} <: AbstractOutputFormat end
"""
InOnBit
Expected output is a pair of booleans, the first one, `inout`, indicating the point
is inside, the second one, `bnds`, indicating the point is close to the border.
Vectors are stored in `BitArray`s of 3 dimensions.
Depending on the used algorithm, the value of `inout` may be invalid, if `bnds` is true.
"""
struct InOnBit <: AbstractOutputFormat end
# interface for above structures standard cases
# access functions for PolygonMesh
function nodecount(poly::PolygonMesh)
size(poly.nodes, 1)
end
function Base.length(poly::PolygonMesh)
nodecount(poly)
end
function edgecount(poly::PolygonMesh{<:Any,<:Any,<:Union{Nothing,AbstractArray{<:Any,0}}})
length(poly)
end
function edgecount(poly::PolygonMesh{<:Any,<:Any,<:AbstractArray})
size(poly.edges, 1)
end
function edgeindex(poly::PolygonMesh{0,<:Any,<:Union{Nothing,AbstractArray{<:Any,0}}}, i::Integer, n::Integer)
n == 1 ? i : i % nodecount(poly) + 1
end
function edgeindex(poly::PolygonMesh{<:Any,<:Any,<:AbstractVector}, i::Integer, n::Integer)
n == 1 ? i : poly.edges[i]
end
function edgeindex(poly::PolygonMesh{<:Any,<:Any,<:AbstractMatrix}, i::Integer, n::Integer)
poly.edges[i,n]
end
function areaindex(poly::PolygonMesh{A}, i::Integer, a::Integer) where A
A >= 1 ? poly.edges[i,a+2] : 1
end
function areacount(poly::PolygonMesh{A}) where A
if A >= 1
maximum(view(poly.edges, :, 3:A+2))
else
1
end
end
function all_areas(poly::PolygonMesh{A}) where A
if A >= 1
edges = poly.edges
m = size(edges, 2)
m <= 2 ? [1] : [a for a in unique(vec(view(edges,:, 3:m))) if a != 0]
else
[1]
end
end
function edges_dict_for_area(poly::PolygonMesh{A}, a::Integer) where A
edges = poly.edges
n, m = size(edges)
if A >= 1
has(edges, i, a) = any(view(edges, i, 3:m) .== a)
Dict((edges[k,1], edges[k,2]) for k in 1:n if has(edges, k, a))
else
Dict((edges[k,1], edges[k,2]) for k in 1:n)
end
end
function all_edges(poly::PolygonMesh)
((edgeindex(poly, i, 1), edgeindex(poly, i, 2)) for i in 1:edgecount(poly))
end
function all_boxlengths(poly::PolygonMesh, xy::Integer)
(abs(vertex(poly,v,xy) - vertex(poly,w,xy)) for (v, w) in all_edges(poly))
end
function vertex(poly::PolygonMesh{<:Any,<:AbstractMatrix{<:Real}}, v::Integer, xy::Integer)
poly.nodes[v,xy]
end
function vertex(poly::PolygonMesh{<:Any,<:AbstractVector}, v::Integer, xy::Integer)
poly.nodes[v][xy]
end
# access functions for PointsInbounds
function Base.length(p::PointsInbound{<:AbstractVector{<:Real}})
1
end
function Base.length(p::PointsInbound{<:AbstractMatrix{<:Real}})
size(p.points, 1)
end
function Base.length(p::PointsInbound{<:AbstractVector})
length(p.points)
end
function vertex(p::PointsInbound{<:AbstractVector{<:Real}}, v::Integer, xy::Integer)
p.points[xy]
end
function vertex(p::PointsInbound{<:AbstractMatrix{<:Real}}, v::Integer, xy::Integer)
p.points[v,xy]
end
function vertex(p::PointsInbound{<:AbstractVector}, v::Integer, xy::Integer)
p.points[v][xy]
end
# standard functions for PointsInbound
function Base.minimum(p::Union{PointsInbound,PolygonMesh})
n = length(p)
minimum([[vertex(p, k, 1) for k = 1:n] [vertex(p, k, 2) for k = 1:n]], dims = 1)
end
function Base.maximum(p::Union{PointsInbound,PolygonMesh})
n = length(p)
maximum([[vertex(p, k, 1) for k = 1:n] [vertex(p, k, 2) for k = 1:n]], dims = 1)
end
function Base.sortperm(p::PointsInbound, ix::Integer)
n = length(p)
sortperm([vertex(p, k, ix) for k in 1:n])
end
function Base.sortperm(p::PointsInbound{<:AbstractMatrix}, ix::Integer)
sortperm(view(p.points, :, ix))
end
# conversion between different output formats
function convertout(to::Type{T}, from::Type{S}, args...) where {S<:AbstractOutputFormat,T<:AbstractOutputFormat}
T == S && return length(args) == 1 ? args[1] : args
convertto(to, convertfrom(from, args...)...)
end
function convertfrom(::Type{<:InOnBit}, stat::T, bnds::T) where T<:Bool
stat, bnds
end
function convertfrom(::Type{<:InOnBit}, stat::T) where T<:AbstractArray{Bool}
stat
end
function convertfrom(::Type{InOnOut{IN,ON,OUT}}, stat::Integer) where {IN,ON,OUT}
if stat == IN
true, false
elseif stat == OUT
false, false
elseif stat == ON
true, true
else
false, true
end
end
function convertfrom(::Type{OT}, stat::Union{AbstractVector{T},AbstractMatrix{T}}) where {T<:Integer,OT<:InOnOut}
n, m = size(stat)
inout = BitArray(undef, n, 2, m)
for j = 1:m
for i in 1:n
a, b = convertfrom(OT, stat[i,j])
inout[i,1,j] = a
inout[i,2,j] = a
end
end
inout, bnds
end
function convertto(::Type{<:InOnBit}, stat::T, bnds::T) where T<:Bool
stat, bnds
end
function convertto(::Type{<:InOnBit}, stat::T, bnds::T) where T<:BitArray
stat
end
function convertto(::Type{InOnOut{IN,ON,OUT}}, stat::Bool, bnds::Bool) where {IN,ON,OUT}
bnds ? ON : stat ? IN : OUT
end
function convertto(::Type{OT}, stat::T) where {OT<:InOnOut,T<:AbstractArray{Bool}}
convertto.(OT, view(stat, :,1,:), view(stat, :, 2, :))
end
# check functions for PolygonMesh constructor
function checknodes(nodes::AbstractMatrix)
size(nodes, 2) >= 2 || throw(ArgumentError("nodes require at least 2 coordinates"))
nothing
end
function checknodes(nodes::AbstractVector)
nothing
end
function checknodes(nodes)
nothing
end
function checkarguments(nodes, edges::Union{Nothing,AbstractArray{<:Integer,0}})
checknodes(nodes)
nothing
end
function checkarguments(nodes, edges::AbstractVector{<:Integer})
checknodes(nodes)
n = size(nodes, 1)
mi, ma = extrema(edges)
0 < mi <= ma <= n || throw(ArgumentError("invalid edge indices"))
nothing
end
function checkarguments(nodes, edges::AbstractMatrix{<:Integer})
checknodes(nodes)
n, m = size(edges)
m >= 2 || throw(ArgumentError("edges matrix requires at least 2 columns"))
m <= 5 || throw(ArgumentError("edges matrix accepts at most 3 area columns"))
mi, ma = extrema(view(edges, :, 1:2))
0 < mi <= ma <= n || throw(ArgumentError("invalid edge indices"))
if m > 2
mi, ma = extrema(view(edges, :, 3:m))
0 <= mi <= 4096 || throw(ArgumentError("invalid area indices ($mi, $ma)"))
end
if m <= 2 || m == 3 && mi == ma
check(i) = isperm(view(edges, :, i)) ||
throw(ArgumentError("edges column $i is no permutation"))
check(1)
check(2)
end
nothing
end
| PolygonInbounds | https://github.com/KlausC/PolygonInbounds.jl.git |
|
[
"MIT"
] | 0.2.0 | 8d50c96f4ba5e1e2fd524116b4ef97b29d5f77da | code | 6471 | """
s = inpoly2(vert, node, [edge=Nothing, atol=0.0, rtol=eps(), outformat=InOnOut{1,0,-1}])
Check all points defined by `vert` are inside, outside or on bounds of
polygon defined by `node` and `edge`.
`vert` and `node` are matrices with the x-coordinates in the first
and the y-coordinates in the second column.
`edge` is an integer matrix of same size as `node`. The first column contains
the index of the starting node, the second column the index of the ending node.
The polygon needs to be closed. It may contain unconnected cycles.
A point is considered on boundary, if its Euclidian distance to any edge is less
than or equal `max(atol, rtol * span)`, where span is the maximum extension of the
polygon in either direction.
If a point is considered on bounds, no further check is made to determine it it is inside or
outside numerically.
Expected effort of the algorithm is `(N+M)*log(M)`, where `M` is the number of points
and `N` is the number of polygon edges.
"""
function inpoly2(vert, node, edge=zeros(Int); atol::T=0.0, rtol::T=NaN, outformat=InOnBit) where T<:AbstractFloat
rtol = !isnan(rtol) ? rtol : iszero(atol) ? eps(T)^0.85 : zero(T)
poly = PolygonMesh(node, edge)
points = PointsInbound(vert)
npoints = length(points)
vmin = minimum(points)
vmax = maximum(points)
pmin = minimum(poly)
pmax = maximum(poly)
lbar = sum(pmax - pmin)
tol = max(abs(rtol * lbar), abs(atol))
ac = areacount(poly)
stat = ac > 1 ? falses(npoints,2,ac) : falses(npoints,2)
# flip coordinates so expected efford is minimal
dvert = vmax - vmin
ix = dvert[1] < dvert[2] ? 1 : 2
iyperm = sortperm(points, 3 - ix)
inpoly2!(points, iyperm, poly, ix, tol, stat)
convertout(outformat, InOnBit, stat)
end
"""
inpoly2_mat(vert, node, edge, fTolx, ftoly, stats)
INPOLY2_MAT the local m-code version of the crossing-number
test. Loop over edges; do a binary-search for the first ve-
rtex that intersects with the edge y-range; do crossing-nu-
mber comparisons; break when the local y-range is exceeded.
"""
function inpoly2!(points, iyperm, poly, ix::Integer, veps::T, stat::S) where {N,T<:AbstractFloat,S<:AbstractArray{Bool,N}}
nvrt = length(points) # number of points to be checked
nedg = edgecount(poly) # number of edges of the polygon mesh
vepsx = vepsy = veps
iy = 3 - ix
#----------------------------------- loop over polygon edges
for epos = 1:nedg
inod = edgeindex(poly, epos, 1) # from
jnod = edgeindex(poly, epos, 2) # to
# swap order of vertices
if vertex(poly, inod, iy) > vertex(poly, jnod, iy)
inod, jnod = jnod, inod
end
#------------------------------- calc. edge bounding-box
xone = vertex(poly, inod, ix)
yone = vertex(poly, inod, iy)
xtwo = vertex(poly, jnod, ix)
ytwo = vertex(poly, jnod, iy)
xmin0 = min(xone, xtwo)
xmax0 = max(xone, xtwo)
xmin = xmin0 - vepsx
xmax = xmax0 + vepsx
ymin = yone - vepsy
ymax = ytwo + vepsy
ydel = ytwo - yone
xdel = xtwo - xone
xysq = xdel^2 + ydel^2
feps = sqrt(xysq) * veps
# find top points[:,iy] < ymin by binary search
ilow = searchfirst(points, iy, iyperm, ymin)
#------------------------------- calc. edge-intersection
# loop over all points with y ∈ [ymin,ymax)
for jpos = ilow:nvrt
jorig = iyperm[jpos]
ypos = vertex(points, jorig, iy)
ypos > ymax && break
xpos = vertex(points, jorig, ix)
if xpos >= xmin
if xpos <= xmax
#--------- inside extended bounding box of edge
mul1 = ydel * (xpos - xone)
mul2 = xdel * (ypos - yone)
if abs(mul2 - mul1) <= feps
#------- distance from line through edge less veps
mul3 = xdel * (2xpos-xone-xtwo) + ydel * (2ypos-yone-ytwo)
if abs(mul3) <= xysq ||
hypot(xpos- xone, ypos - yone) <= veps ||
hypot(xpos- xtwo, ypos - ytwo) <= veps
# ---- round boundaries around endpoints of edge
setonbounds!(poly, stat, jorig, epos)
end
if mul1 < mul2 && yone <= ypos < ytwo
#----- left of line && ypos exact to avoid multiple counting
flipio!(poly, stat, jorig, epos)
end
elseif mul1 < mul2 && yone <= ypos < ytwo
#----- left of line && ypos exact to avoid multiple counting
flipio!(poly, stat, jorig, epos)
end
end
else # xpos < xmin - left of bounding box
if yone <= ypos < ytwo
#----- ypos exact to avoid multiple counting
flipio!(poly, stat, jorig, epos)
end
end
end
end
stat
end
"""
search lowest iy coordinate >= ymin
"""
function searchfirst(points::PointsInbound, iy::Integer, iyperm, ymin)
ilow = 0
iupp = length(points) + 1
@inbounds while ilow < iupp - 1
imid = ilow + (iupp-ilow) >>> 0x01
if vertex(points, iyperm[imid], iy) < ymin
ilow = imid
else
iupp = imid
end
end
iupp
end
"""
flipio!(poly, stat, p, epos)
Flip boolean value of in-out-status of point `p` for all areas associated with edge `epos`.
"""
function flipio!(poly::PolygonMesh, stat::AbstractArray{Bool}, i::Integer, j::Integer)
statop!((stat,j,a) -> begin stat[j,1,a] = !stat[j,1,a]; end, poly, stat, i, j)
end
"""
setonbounds!(poly, stat, p, epos)
Set boolean value of on-bounds-status of point `p` for all areas associated with edge `epos`.
"""
function setonbounds!(poly::PolygonMesh, stat::AbstractArray{Bool}, i::Integer, j::Integer)
statop!((stat, j,a) -> begin stat[j,2,a] = true; end, poly, stat, i, j)
end
function statop!(f!::Function, poly::PolygonMesh{A}, stat::AbstractArray{Bool,N}, p::Integer, ed::Integer) where {A,N}
for k in 1:max(A, 1)
area = N == 3 ? areaindex(poly, ed, k) : 1
if area > 0
f!(stat, p, area)
end
end
end
| PolygonInbounds | https://github.com/KlausC/PolygonInbounds.jl.git |
|
[
"MIT"
] | 0.2.0 | 8d50c96f4ba5e1e2fd524116b4ef97b29d5f77da | code | 8664 |
module Demo
using PolygonInbounds
using PolygonInbounds: PolygonMesh, all_areas, edges_dict_for_area, vertex
export polydemo
struct Dummy end
Base.getproperty(::Dummy,::Symbol) = dummy(a...;kw...) = nothing
setplot(x) = global Plot = x
Plot = Dummy()
plot(a...;kw...) = Plot.plot(a...;kw...)
plot!(a...;kw...) = Plot.plot!(a...;kw...)
scatter(a...;kw...) = Plot.scatter(a...;kw...)
scatter!(a...;kw...) = Plot.scatter!(a...;kw...)
savefig(a...) = Plot.savefig(a...)
display(a...) = Plot.display(a...)
const PLOTARG = (legend = :topleft, size = (1024, 780))
"""
%POLYDEMO run a series of point-in-polygon demos.
% POLYDEMO(II) runs the II-th demo, where +1 <= II <= +3.
% Demo problems illustrate varying functionality for the
% INPOLY2 routine.
%
% See also INPOLY2, INPOLYGON
% Darren Engwirda : 2018 --
% Email : [email protected]
% Last updated : 28/10/2018
"""
function polydemo(id::Integer=1; args...)
[demo1, demo2, demo3, demo4, demo5][id](;args...)
end
#-----------------------------------------------------------
function demo1(;tol=1e-2, r=10^5, do_plot=true)
do_plot && println("""
INPOLY2 provides fast point-in-polygon queries for ob-\n
jects in R^2. Like INPOLYGON, it detects points inside\n
and on the boundary of polygonal geometries.\n
""")
nodes = [ 2.0 0; 8 4; 4 8; 0 4; 5 0; 7 4; 3 6; 6 1 # inner nodes
3 3; 5 3; 5 5; 3 5 ] # outer nodes
edges = [ 1 2; 2 3; 3 4; 4 5; 5 6; 6 7; 7 8; 8 1
9 10; 10 11; 11 12; 12 9 ]
poly = PolygonMesh(nodes, edges)
dx = 10 * sqrt(1/r)
a = [(x,y) for x in -1:dx:9 for y in -1:dx:9]
xpos, ypos = [p[1] for p in a], [p[2] for p in a]
stat = @time inpoly2([xpos ypos], nodes, edges, atol=tol)
if do_plot
p = plot(title="demo1 (r $r, atol $tol)"; PLOTARG...)
p = plotpoints(p, xpos, ypos, stat)
p = plotpolygon(p, poly)
savefig(p, "demo1.png")
display(p)
end
stat
end
#-----------------------------------------------------------
function demo2(;r=2500, tol=1e-3, do_plot=true)
do_plot && println("""
INPOLY2 supports multiply-connected geometries, consi-\n
sting of arbitrarily nested sets of outer + inner bou-\n
ndaries.\n
""")
xpos, ypos, nodes, edges = testdata("lakes.msh", r)
poly = PolygonMesh(nodes, edges)
stat = @time inpoly2([xpos ypos], nodes, edges, rtol=tol)
if do_plot
p = plot(title="demo2 - lakes (r $r, rtol $tol)"; PLOTARG...)
p = plotpoints(p, xpos, ypos, stat)
p = plotpolygon(p, poly)
savefig(p, "demo2.png")
display(p)
end
stat
end
#-----------------------------------------------------------
function demo3(;r=2500, tol=1e-3, do_plot=true)
do_plot && println("""
INPOLY2 implements a "pre-sorted" variant of the cros-\n
sing-number test - returning queries in approximately \n
O((N+M)*LOG(N)) time for configurations consisting of \n
N test points and M edges. This is often considerably \n
faster than conventional approaches that typically re-\n
quire O(N*M) operations.\n
""");
xpos, ypos, nodes, edges = testdata("coast.msh", r)
poly = PolygonMesh(nodes, edges)
stat = @time inpoly2([xpos ypos], nodes, edges, rtol=tol)
if do_plot
p = plot(title="demo3 - coast (r $r, rtol $tol)"; PLOTARG...)
p = plotpoints(p, xpos, ypos, stat)
p = plotpolygon(p, poly)
savefig(p, "demo3.png")
display(p)
end
stat
end
#-----------------------------------------------------------
function demo4(;r=5*10^5, tol=1e-2, do_plot=true)
do_plot && println("""
INPOLY2 provides fast point-in-polygon queries for ob-\n
jects in R^2. Like INPOLYGON, it detects points inside\n
and on the boundary of polygonal geometries.\n
""")
nodes = [0.0 0; 3 4; 7 5; 10 0]
edges = [1 2; 2 3; 3 4; 4 1]
poly = PolygonMesh(nodes, edges)
rpts = testbox(r, [-1.0 -1.0], [ 11.0 6.0])
xpos, ypos = rpts[:,1], rpts[:,2]
stat = @time inpoly2(rpts, nodes, edges, atol=tol)
if do_plot
p = plot(title="demo4 (r $r, atol $tol)"; PLOTARG...)
p = plotpoints(p, xpos, ypos, stat)
p = plotpolygon(p, poly)
savefig(p, "demo4.png")
display(p)
end
stat
end
#-----------------------------------------------------------
function demo5(;r=5*10^5, tol=1e-2, do_plot=true)
do_plot && println("""
INPOLY2 provides fast point-in-polygon queries for ob-\n
jects in R^2. Like INPOLYGON, it detects points inside\n
and on the boundary of polygonal geometries.\n
""")
nodes = [0.0 0; 3 4; 7 5; 10 0; 11 4]
edges = [1 2 1; 2 3 1; 3 4 1; 4 1 1; 3 4 2; 4 5 2; 5 3 2]
poly = PolygonMesh(nodes, edges)
rpts = testbox(r, [-1.0 -1.0], [ 11.0 6.0])
xpos, ypos = rpts[:,1], rpts[:,2]
stat = @time inpoly2(rpts, nodes, edges, atol=tol)
if do_plot
p = plot(title="demo5 (r $r, atol $tol)"; PLOTARG...)
p = plotpoints(p, xpos, ypos, stat)
p = plotpolygon(p, poly)
savefig(p, "demo5.png")
display(p)
end
stat
end
#----- Utility functions
function testdata(dataset, r::Integer)
filepath = @__DIR__
nodes, edges = loadmsh(joinpath(filepath, "..", "test-data", dataset))
emid = .5 * nodes[edges[:,1],:] + .5 * nodes[edges[:,2],:]
ma, mi = maximum(nodes, dims=1), minimum(nodes, dims=1)
rpts = testbox(r, mi, ma)
vert = r <= 100 ? [rpts;] : [nodes; emid; rpts]
vert[:,1], vert[:,2], nodes, edges
end
function testbox(r::Integer, mi, ma)
mi = reshape(mi, 1, 2)
ma = reshape(ma, 1, 2)
half = (ma + mi) / 2
scal = ma - mi
rpts = (rand(r, 2) .- 0.5).* scal .* 1.1 .+ half
end
function plotpolygon(p, poly::PolygonMesh)
areas = all_areas(poly)
T = Float64
for a in areas
d = edges_dict_for_area(poly, a)
while !isempty(d)
start = j = minimum(keys(d))
n = length(d)
xpos = Vector{T}(undef, n+1)
ypos = Vector{T}(undef, n+1)
k = 0
while k <= n
k += 1
xpos[k] = vertex(poly, j,1)
ypos[k] = vertex(poly, j,2)
j == start && k > 1 && break
j = pop!(d, j)
end
resize!(xpos, k)
resize!(ypos, k)
p = plot!(p, xpos, ypos, color=:purple, width=1.5)
end
end
p
end
function plotpoints(p, xpos, ypos, stat)
function sca(ina, color=:black, mshape=:cross)
scatter!(p, xpos[ina], ypos[ina]; markershape=mshape, markersize=ms, color=color)
end
ms = 1.0
inside = onbound = nothing
for area in axes(stat,3)
inside = stat[:,1,area]
onbound = stat[:,2,area]
ina = inside .& (!).(onbound)
inb = inside .& onbound
sca(ina, area == 1 ? :green : :brown)
sca(inb, :yellow)
end
if size(stat,3) > 1
inside = BitVector([any(view(stat,i,1,:)) for i in axes(stat,1)])
onbound = BitVector([any(view(stat,i,2,:)) for i in axes(stat,1)])
end
outa = (!).(inside) .& (!).(onbound)
outb = (!).(inside) .& onbound
sca(outb, :blue)
sca(outa, :lightblue)
p
end
function loadmsh(file)
nodes = Float64[]
edges = Int[]
m = 0
n = 0
open(file) do io
name =""
while !eof(io)
line = readline(io)
startswith(line, "#") && continue
ls = split(line, "=")
if length(ls) == 2
name = ls[1]
if name == "point"
n = parse(Int, ls[2])
nodes = Vector{Float64}(undef, 2n)
m = 0
elseif name == "edge2"
n = parse(Int, ls[2])
edges = Vector{Int}(undef, 2n)
m = 0
end
continue
end
ls = split(line, ";")
if length(ls) >= 2
m >= 2n - 1 && continue
if name == "point"
nodes[m+=1] = parse(Float64, ls[1])
nodes[m+=1] = parse(Float64, ls[2])
elseif name == "edge2"
edges[m+=1] = parse(Int, ls[1]) + 1
edges[m+=1] = parse(Int, ls[2]) + 1
end
end
end
end
res(nodes) = permutedims(reshape(nodes, 2, length(nodes)÷2))
res(nodes), res(edges)
end
end # Demo
| PolygonInbounds | https://github.com/KlausC/PolygonInbounds.jl.git |
|
[
"MIT"
] | 0.2.0 | 8d50c96f4ba5e1e2fd524116b4ef97b29d5f77da | code | 2185 |
"""
mean_overlap(a, y0, x0, x1, y1)
Mean overlap of an interval of length `a` and interval `[x0,x1]`,
when moving inside `[y0,y1]`.
Assumptions `a <= y1 - y0` and ` y0 <= x0 <= x1 <= y1`.
Return `result` with `min(x1 - x0, a) <= result <= a`.
"""
function mean_overlap(a::T, y0::T, x0::T, x1::T, y1::T) where T <: Real
x0 = max(x0, y0)
x1 = min(x1, y1)
y0 <= x0 <= x1 <= y1 || throw(ArgumentError("violating ordering of boundaries"))
a = min(a, y1 - y0)
y10 = y1 - y0 - a
if y10 <= (eps())*a
return min(x1 - x0, a)
end
m11 = max(x0 - y0 - a, 0)
m12 = max(min(x0+a, x1) - max(y0+a, x0), 0)
d12 = (min(x0+a, x1) + max(y0+a, x0)) / 2 - x0
m13 = max(min(x0+a, y1) - max(y0+a, x1), 0)
m22 = max(x1 - x0 - a, 0)
m23 = max(min(x1+a, y1) - max(x0+a, x1), 0)
d23 = -(min(x1+a, y1) + max(x0+a, x1)) /2 + x1 + a
m33 = max(y1 - x1 - a, 0)
#println(m11 + m12 + m13 + m22 + m23 + m33 - y1 + y0 + a)
#display([m11 m12 m13 m22 m23 m33;0 d12 x1 - x0 a d23 0])
(m12*d12 + m13*(x1-x0) + m22*a + m23*d23) / y10
end
function sumeff(points, vmin, vmax, poly, pmin, pmax, xy, tol)
pmi = pmin[xy] - tol
pma = pmax[xy] + tol
vmi = vmin[xy] - tol
vma = vmax[xy] + tol
sum(mean_overlap.(all_boxlengths(poly, xy) .+ 2tol, pmi, vmi, vma, pma))
end
function countmid(points, pmin, pmax, xy, tol)
npoints = length(points)
v = (vertex(points, k, xy) for k = 1:npoints)
pmi = pmin[xy] - tol
pma = pmax[xy] + tol
low, mid, hi = sum([x < pmi, pmi <= x <= pma, x > pma] for x in v)
mid
end
function estimate_effort(points, vmin, vmax, poly, pmin, pmax, tol)
sumx = sumeff(points, vmin, vmax, poly, pmin, pmax, 1, tol)
sumy = sumeff(points, vmin, vmax, poly, pmin, pmax, 2, tol)
sumx0 = sumeff(points, vmin, vmax, poly, pmin, pmax, 1, 0.0)
sumy0 = sumeff(points, vmin, vmax, poly, pmin, pmax, 2, 0.0)
xmid = countmid(points, pmin, pmax, 1, tol)
ymid = countmid(points, pmin, pmax, 2, tol)
xmid0 = countmid(points, pmin, pmax, 1, 0.0)
ymid0 = countmid(points, pmin, pmax, 2, 0.0)
xmid * sumx, ymid * sumy, xmid0 * sumx0, ymid0 * sumy0
end
| PolygonInbounds | https://github.com/KlausC/PolygonInbounds.jl.git |
|
[
"MIT"
] | 0.2.0 | 8d50c96f4ba5e1e2fd524116b4ef97b29d5f77da | code | 1826 | using Test
using PolygonInbounds
using .Demo
@testset "PolygonInboundsTests" begin
@testset "argument checks" begin
@test inpoly2([0.0 0], [0.0 0]) == [false true]
@test_throws ArgumentError inpoly2([0.0 0], [0.0 0], [1;2])
@test inpoly2([0.0 0], [-1.0 1; 1 -1]) == [false true]
@test inpoly2([0.0 0], [-1.0 1; 1 -1], [1; 2]) == [false false]
@test inpoly2([0.0 0], [-1.0 1; 1 -1], [2; 1]) == [false true]
@test_throws ArgumentError inpoly2([0.0 0], [-1.0 1; 1 -1], [2 1])
@test inpoly2([0.0 0], [-1.0 1; 1 -1], [1 1]) == [false false]
@test_throws ArgumentError inpoly2([0.0 0], [-1.0 1; 1 -1], [2 1; 2 2])
@test_throws ArgumentError inpoly2([0.0 0], [-1.0 1; 1 -1], [2 2; 1 2])
@test_throws ArgumentError inpoly2([0.0 0], [-1.0 1; 1 -1], [1 1 1 2 3 4])
end
let stat = polydemo(4, r=10^5, tol=1e-2, do_plot=false)
@testset "functionality" begin
@test 300 <= count(stat[:,2]) < 600
@test 29000 <= count(stat[:,1]) < 32000
@test 67000 <= count((!).(stat[:,1])) < 70000
end
end
@testset "utilities" begin
@test PolygonInbounds.mean_overlap(0.0, 0.0, 2.0, 8.0, 10.0) == 0
@test PolygonInbounds.mean_overlap(2.0, 0.0, 2.0, 8.0, 10.0) == 1.5
@test PolygonInbounds.mean_overlap(8.0, 0.0, 2.0, 8.0, 10.0) == 6
@test PolygonInbounds.mean_overlap(11.0, 0.0, 2.0, 8.0, 10.0) == 6
end
@testset "means estimations" begin
r = 100
nodes = [0.0 0; 3 4; 7 5; 10 0]
edges = [1 2; 2 3; 3 4; 4 1]
poly = PolygonInbounds.PolygonMesh(nodes, edges)
rpts = PolygonInbounds.PointsInbound(Demo.testbox(r, [-1.0 -1.0], [ 11.0 6.0]))
x = PolygonInbounds.estimate_effort(rpts, [-1.0 -1.0], [11.0 6.0], poly, [0.0 0.0], [10.0 5.0], 1e-6)
@test length(x) == 4
end
end
# to improve test coverage
for i = 1:5
polydemo(i)
end
| PolygonInbounds | https://github.com/KlausC/PolygonInbounds.jl.git |
|
[
"MIT"
] | 0.2.0 | 8d50c96f4ba5e1e2fd524116b4ef97b29d5f77da | docs | 3237 | # PolygonInbounds
[](https://travis-ci.com/KlausC/PolygonInbounds.jl)
[](https://codecov.io/gh/KlausC/PolygonInbounds.jl)
## INPOLY: Fast points-in-polygon query in Julia
Implementation and improvement of function INPOLY2 in Julia. Some new
features have been added.
The implementation claims to be fast for multiple points to check at once.
The cost is `O((N+M)*(log(M)+1))` where `M` is the number of points to check and `N`
the number of edges.
Link to original Matlab sources: [inpoly2.m](https://github.com/dengwirda/inpoly)
The original algorithm was developed by Darren Engwirda in 2017.
The Euclidian distance definition of "on-boundary" and the support for multiple
areas has been added.
## Description
```
stat = inpoly2(points, nodes, edges[, atol=, rtol=])
```
determines for each point of `points`
two status bits: `inside` and `onboundary`. These bits are stored in the output
matrix `stat[:,1:2]` with the same row indices as `points`.
A point is considered "inside", if the ray starting from x heading east intersects an
odd number of edges.
A point is considered "on-boundary", if its Euclidian distance to any of the edges
of the polygon is less than `tol = max(atol, rtol*sizefactor)`. `sizefactor` is the
maximum extension of the smallest box containing all edges.
The cost factor depends severely on `tol`, if that is greater than the average
length of the edges.
`points` and `nodes` are matrices consisting of x, y in first and second column or
vectors of point-objects `p` with `p[1]` and `p[2]` the x and y coordinates.
`edges` is a matrix of indices into `nodes`, which define the egdges of a polygon
or collection of polygons.
The polygons may be unconnected and self-intersecting.
Each edge may be associated with one or more area indices, which are stored in adjacent
columns of `edges[:,3:end]`. If there is more than one additional area colum,
the output array becomes 3-dimensional with elements `stats[:,1:2,area]`. Here `area`
are the area indices as stored in the additional columns of `edges`.
The definitions of "inside" and "on-boundary" related to an area consider only edges,
which have this area associated in one of the added columns of `edges`.
Area index `0` indicates unused. It is possible to assign each edge to zero, one, or
more areas in this way.
The `polydemo` functions produce plots of some selected examples and may be used
to enjoy.
### Usage:
```julia
Pkg>add PolygonInbounds
using Plots
using PolygonInbounds
using .Demo
Demo.setplot(Plots)
polydemo(1; tol=0.2); # r is the number of points on a grid
polydemo(2; r = 10^5, tol=0.01); # polygons of the "lakes" mesh data set
polydemo(3; r = 10^5, tol=0.01); # polygons of the "coast" mesh data set
polydemo(4; tol=0.1) # simple tetragon
polydemo(5; tol=0.2) # two polygons with different areas
points = [0.05 0.0; 1 1; -1 1]
nodes = [0.0 0; 0 10; 10 10; 10 0]
edges = [1 2; 2 3; 3 4; 4 1]
tol = 1e-1
stat = inpoly2(points, nodes, edges, atol=tol)
```
Docu of the original Matlab implementation: [inpoly2](./doc/original.md).
| PolygonInbounds | https://github.com/KlausC/PolygonInbounds.jl.git |
|
[
"MIT"
] | 0.2.0 | 8d50c96f4ba5e1e2fd524116b4ef97b29d5f77da | docs | 2508 | ```
INPOLY2 compute "points-in-polygon" queries.
[STAT] = INPOLY2(VERT,NODE,EDGE) returns the "inside/ou-
tside" status for a set of vertices VERT and a polygon
{NODE,EDGE} embedded in a two-dimensional plane. General
non-convex and multiply-connected polygonal regions can
be handled. VERT is an N-by-2 array of XY coordinates to
be tested. STAT is an associated N-by-1 logical array,
with STAT(II) = TRUE if VERT(II,:) is an interior point.
The polygonal region is defined as a piecewise-straight-
line-graph, where NODE is an M-by-2 array of polygon ve-
rtices and EDGE is a P-by-2 array of edge indexing. Each
row in EDGE represents an edge of the polygon, such that
NODE(EDGE(KK,1),:) and NODE(EDGE(KK,2),:) are the coord-
inates of the endpoints of the KK-TH edge. If the argum-
ent EDGE is omitted it assumed that the vertices in NODE
are connected in ascending order.
[STAT,BNDS] = INPOLY2(..., FTOL) also returns an N-by-1
logical array BNDS, with BNDS(II) = TRUE if VERT(II,:)
lies "on" a boundary segment, where FTOL is a floating-
point tolerance for boundary comparisons. By default,
FTOL = EPS ^ 0.85.
See also INPOLYGON
This algorithm is based on a "crossing-number" test, co-
unting the number of times a line extending from each
point past the right-most region of the polygon interse-
cts with the polygonal boundary. Points with odd counts
are "inside". A simple implementation requires that each
edge intersection be checked for each point, leading to
O(N*M) complexity...
This implementation seeks to improve these bounds:
* Sorting the query points by y-value and determining can-
didate edge intersection sets via binary-search. Given a
configuration with N test points, M edges and an average
point-edge "overlap" of H, the overall complexity scales
like O(M*H + M*LOG(N) + N*LOG(N)), where O(N*LOG(N))
operations are required for sorting, O(M*LOG(N)) operat-
ions required for the set of binary-searches, and O(M*H)
operations required for the intersection tests, where H
is typically small on average, such that H << N.
* Carefully checking points against the bounding-box asso-
ciated with each polygon edge. This minimises the number
of calls to the (relatively) expensive edge intersection
test.
Darren Engwirda : 2017 --
Email : [email protected]
Last updated : 27/10/2018
```
| PolygonInbounds | https://github.com/KlausC/PolygonInbounds.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1427 | module DelayDiffEq
using Reexport
@reexport using OrdinaryDiffEq
using DataStructures
using LinearAlgebra
using Logging
using Printf
using RecursiveArrayTools
using SimpleUnPack
import ArrayInterface
import SimpleNonlinearSolve
using DiffEqBase: AbstractDDEAlgorithm, AbstractDDEIntegrator, AbstractODEIntegrator,
DEIntegrator, AbstractDDEProblem
using DiffEqBase: @..
if isdefined(OrdinaryDiffEq, :FastConvergence)
using OrdinaryDiffEq: FastConvergence, Convergence, SlowConvergence,
VerySlowConvergence,
Divergence, AbstractNLSolverCache, NLNewton,
NLAnderson, NLFunctional
else
using DiffEqBase: FastConvergence, Convergence, SlowConvergence, VerySlowConvergence,
Divergence, AbstractNLSolverCache
end
using OrdinaryDiffEq: RosenbrockMutableCache
import SciMLBase
export Discontinuity, MethodOfSteps
include("discontinuity_type.jl")
include("functionwrapper.jl")
include("integrators/type.jl")
include("integrators/utils.jl")
include("integrators/interface.jl")
include("fpsolve/type.jl")
include("fpsolve/fpsolve.jl")
include("fpsolve/utils.jl")
include("fpsolve/functional.jl")
include("cache_utils.jl")
include("interpolants.jl")
include("history_function.jl")
include("algorithms.jl")
include("track.jl")
include("alg_utils.jl")
include("solve.jl")
include("utils.jl")
end # module
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 2973 | ## SciMLBase Trait Definitions
function SciMLBase.isautodifferentiable(alg::AbstractMethodOfStepsAlgorithm)
SciMLBase.isautodifferentiable(alg.alg)
end
function SciMLBase.allows_arbitrary_number_types(alg::AbstractMethodOfStepsAlgorithm)
SciMLBase.allows_arbitrary_number_types(alg.alg)
end
function SciMLBase.allowscomplex(alg::AbstractMethodOfStepsAlgorithm)
SciMLBase.allowscomplex(alg.alg)
end
SciMLBase.isdiscrete(alg::AbstractMethodOfStepsAlgorithm) = SciMLBase.isdiscrete(alg.alg)
SciMLBase.isadaptive(alg::AbstractMethodOfStepsAlgorithm) = SciMLBase.isadaptive(alg.alg)
## DelayDiffEq Internal Traits
function isconstrained(alg::AbstractMethodOfStepsAlgorithm{constrained}) where {constrained}
constrained
end
OrdinaryDiffEq.uses_uprev(alg::AbstractMethodOfStepsAlgorithm, adaptive) = true
function OrdinaryDiffEq.isimplicit(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.isimplicit(alg.alg)
end
function OrdinaryDiffEq.isdtchangeable(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.isdtchangeable(alg.alg)
end
function OrdinaryDiffEq.ismultistep(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.ismultistep(alg.alg)
end
function OrdinaryDiffEq.isautoswitch(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.isautoswitch(alg.alg)
end
function OrdinaryDiffEq.get_chunksize(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.get_chunksize(alg.alg)
end
function OrdinaryDiffEq.get_chunksize_int(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.get_chunksize_int(alg.alg)
end
function OrdinaryDiffEq.alg_autodiff(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.alg_autodiff(alg.alg)
end
function OrdinaryDiffEq.alg_difftype(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.alg_difftype(alg.alg)
end
function OrdinaryDiffEq.standardtag(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.standardtag(alg.alg)
end
function OrdinaryDiffEq.concrete_jac(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.concrete_jac(alg.alg)
end
function OrdinaryDiffEq.alg_extrapolates(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.alg_extrapolates(alg.alg)
end
function OrdinaryDiffEq.alg_order(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.alg_order(alg.alg)
end
function OrdinaryDiffEq.alg_maximum_order(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.alg_maximum_order(alg.alg)
end
function OrdinaryDiffEq.alg_adaptive_order(alg::AbstractMethodOfStepsAlgorithm)
OrdinaryDiffEq.alg_adaptive_order(alg.alg)
end
"""
iscomposite(alg)
Return if algorithm `alg` is a composite algorithm.
"""
iscomposite(alg) = false
iscomposite(::OrdinaryDiffEq.OrdinaryDiffEqCompositeAlgorithm) = true
iscomposite(alg::AbstractMethodOfStepsAlgorithm) = iscomposite(alg.alg)
function DiffEqBase.prepare_alg(alg::MethodOfSteps, u0, p, prob)
MethodOfSteps(DiffEqBase.prepare_alg(alg.alg, u0, p, prob);
constrained = isconstrained(alg),
fpsolve = alg.fpsolve)
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1382 | abstract type DelayDiffEqAlgorithm <: AbstractDDEAlgorithm end
abstract type AbstractMethodOfStepsAlgorithm{constrained} <: DelayDiffEqAlgorithm end
struct MethodOfSteps{algType, F, constrained} <: AbstractMethodOfStepsAlgorithm{constrained}
alg::algType
fpsolve::F
end
"""
MethodOfSteps(alg; constrained = false, fpsolve = NLFunctional())
Construct an algorithm that solves delay differential equations by the method of steps,
where `alg` is an ODE algorithm from OrdinaryDiffEq.jl upon which the calculation of
steps is based.
If the algorithm is `constrained` only steps of size at most the minimal delay will be
taken. If it is unconstrained, fixed-point iteration `fpsolve` is applied for step sizes
that exceed the minimal delay.
Citations:
General Approach
ZivariPiran, Hossein, and Wayne H. Enright. "An efficient unified approach for the numerical
solution of delay differential equations." Numerical Algorithms 53.2-3 (2010): 397-417.
State-Dependent Delays
S. P. Corwin, D. Sarafyan and S. Thompson in "DKLAG6: a code based on continuously imbedded
sixth-order Runge-Kutta methods for the solution of state-dependent functional differential
equations", Applied Numerical Mathematics, 1997.
"""
function MethodOfSteps(alg; constrained = false, fpsolve = NLFunctional())
MethodOfSteps{typeof(alg), typeof(fpsolve), constrained}(alg, fpsolve)
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 385 | function DiffEqBase.unwrap_cache(integrator::DDEIntegrator, is_stiff)
alg = integrator.alg
cache = integrator.cache
iscomp = alg isa CompositeAlgorithm
if !iscomp
return cache
elseif alg.choice_function isa AutoSwitch
num = is_stiff ? 2 : 1
return cache.caches[num]
else
return cache.caches[integrator.cache.current]
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 2078 | """
Discontinuity(t, order)
Object of discontinuity of order `order` at time `t`, i.e. discontinuity of `order`th
derivative at time `t`.
"""
struct Discontinuity{tType, O}
t::tType
order::O
end
# ordering of discontinuities
Base.:<(a::Discontinuity, b::Discontinuity) = a.t < b.t || (a.t == b.t && a.order < b.order)
function Base.isless(a::Discontinuity, b::Discontinuity)
isless(a.t, b.t) || (isequal(a.t, b.t) && isless(a.order, b.order))
end
function Base.isequal(a::Discontinuity, b::Discontinuity)
isequal(a.t, b.t) && isequal(a.order, b.order)
end
Base.:(==)(a::Discontinuity, b::Discontinuity) = a.t == b.t && a.order == b.order
# ordering with numbers
Base.:<(a::Discontinuity, b::Number) = a.t < b
Base.:<(a::Number, b::Discontinuity) = a < b.t
Base.isless(a::Discontinuity, b::Number) = isless(a.t, b)
Base.isless(a::Number, b::Discontinuity) = isless(a, b.t)
Base.:(==)(a::Discontinuity, b::Number) = a.t == b
Base.:(==)(a::Number, b::Discontinuity) = a == b.t
Base.isequal(a::Discontinuity, b::Number) = isequal(a.t, b)
Base.isequal(a::Number, b::Discontinuity) = isequal(a, b.t)
# multiplication with numbers
Base.:*(a::Discontinuity, b::Number) = Discontinuity(a.t * b, a.order)
Base.:*(a::Number, b::Discontinuity) = Discontinuity(a * b.t, b.order)
# conversion to numbers
Base.convert(::Type{T}, d::Discontinuity) where {T <: Number} = convert(T, d.t)
Base.convert(::Type{T}, d::Discontinuity{T}) where {T <: Number} = d.t
# conversion to discontinuity
function Base.convert(::Type{Discontinuity{T}}, x::Number) where {T <: Number}
return convert(Discontinuity{T, Int}, x)
end
function Base.convert(::Type{Discontinuity{T, O}}, x::Number) where {T <: Number, O}
return Discontinuity{T, O}(convert(T, x), zero(O))
end
function Base.convert(::Type{Discontinuity{T, O}}, x::T) where {T <: Number, O}
return Discontinuity{T, O}(x, zero(O))
end
# display
Base.show(io::IO, d::Discontinuity) = print(io, d.t, " (order ", d.order, ")")
Base.show(io::IO, ::MIME"text/plain", d::Discontinuity) = print(io, typeof(d), ":\n ", d)
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1889 | # convenience macro
macro wrap_h(signature)
Meta.isexpr(signature, :call) ||
throw(ArgumentError("signature has to be a function call expression"))
name = signature.args[1]
args = signature.args[2:end]
args_wo_h = [arg for arg in args if arg !== :h]
quote
if f.$name === nothing
nothing
else
if isinplace(f)
let _f = f.$name, h = h
($(args_wo_h...),) -> _f($(args...))
end
else
let _f = f.$name, h = h
($(args_wo_h[2:end]...),) -> _f($(args[2:end]...))
end
end
end
end |> esc
end
struct ODEFunctionWrapper{iip, F, H, TMM, Ta, Tt, TJ, JP, SP, TW, TWt, TPJ, S, TCV} <:
DiffEqBase.AbstractODEFunction{iip}
f::F
h::H
mass_matrix::TMM
analytic::Ta
tgrad::Tt
jac::TJ
jac_prototype::JP
sparsity::SP
Wfact::TW
Wfact_t::TWt
paramjac::TPJ
sys::S
colorvec::TCV
end
function ODEFunctionWrapper(f::DiffEqBase.AbstractDDEFunction, h)
# wrap functions
jac = @wrap_h jac(J, u, h, p, t)
Wfact = @wrap_h Wfact(W, u, h, p, dtgamma, t)
Wfact_t = @wrap_h Wfact_t(W, u, h, p, dtgamma, t)
ODEFunctionWrapper{isinplace(f), typeof(f.f), typeof(h), typeof(f.mass_matrix),
typeof(f.analytic), typeof(f.tgrad), typeof(jac),
typeof(f.jac_prototype), typeof(f.sparsity),
typeof(Wfact), typeof(Wfact_t),
typeof(f.paramjac), typeof(f.sys), typeof(f.colorvec)}(f.f, h,
f.mass_matrix,
f.analytic,
f.tgrad, jac,
f.jac_prototype,
f.sparsity,
Wfact,
Wfact_t,
f.paramjac,
f.sys,
f.colorvec)
end
(f::ODEFunctionWrapper{true})(du, u, p, t) = f.f(du, u, f.h, p, t)
(f::ODEFunctionWrapper{false})(u, p, t) = f.f(u, f.h, p, t)
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 3105 | """
HistoryFunction(h, integrator)
Wrap history function `h` and integrator `integrator` to create a common
interface for retrieving values at any time point with varying accuracy.
Before the initial time point of the `integrator` values are calculated by
history function `h`, for time points up to the final time point of the solution
interpolated values of the solution are returned, and after the final time point an inter-
or extrapolation of the current state of the `integrator` is retrieved.
"""
mutable struct HistoryFunction{H, I <: DEIntegrator} <: DiffEqBase.AbstractHistoryFunction
h::H
integrator::I
isout::Bool
end
HistoryFunction(h, integrator) = HistoryFunction(h, integrator, false)
function (f::HistoryFunction)(p, t, ::Type{Val{deriv}} = Val{0};
idxs = nothing) where {deriv}
@unpack integrator = f
@unpack tdir, sol = integrator
tdir_t = tdir * t
if tdir_t < tdir * sol.prob.tspan[1]
if deriv == 0 && idxs === nothing
return f.h(p, t)
elseif idxs === nothing
return f.h(p, t, Val{deriv})
elseif deriv == 0
return f.h(p, t; idxs = idxs)
else
return f.h(p, t, Val{deriv}; idxs = idxs)
end
end
if !isempty(sol.t)
tdir_solt = tdir * sol.t[end]
if tdir_t <= tdir_solt
return sol.interp(t, idxs, Val{deriv}, p)
end
# history function is evaluated at time point past the final time point of
# the current solution
if tdir_t - tdir_solt > 10 * eps(tdir_t)
f.isout = true
end
else
f.isout = true
end
if integrator.t == sol.prob.tspan[1]
# handle extrapolations at initial time point
return constant_extrapolant(t, integrator, idxs, Val{deriv})
else
return integrator(t, Val{deriv}; idxs = idxs)
end
end
function (f::HistoryFunction)(val, p, t, ::Type{Val{deriv}} = Val{0};
idxs = nothing) where {deriv}
@unpack integrator = f
@unpack tdir, sol = integrator
tdir_t = tdir * t
if tdir_t < tdir * sol.prob.tspan[1]
if deriv == 0 && idxs === nothing
return f.h(val, p, t)
elseif idxs === nothing
return f.h(val, p, t, Val{deriv})
elseif deriv == 0
return f.h(val, p, t; idxs = idxs)
else
return f.h(val, p, t, Val{deriv}; idxs = idxs)
end
end
if !isempty(sol.t)
tdir_solt = tdir * sol.t[end]
if tdir_t <= tdir_solt
return sol.interp(val, t, idxs, Val{deriv}, p)
end
# history function is evaluated at time point past the final time point of
# the current solution
if tdir_t - tdir_solt > 10 * eps(tdir_t)
f.isout = true
end
else
f.isout = true
end
if integrator.t == sol.prob.tspan[1]
# handle extrapolations at initial time point
return constant_extrapolant!(val, t, integrator, idxs, Val{deriv})
else
return integrator(val, t, Val{deriv}; idxs = idxs)
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1885 | """
constant_extrapolant(t, integrator::DEIntegrator, idxs, deriv)
Calculate constant extrapolation of derivative `deriv` at time `t` and indices `idxs`
for `integrator`.
"""
function constant_extrapolant(t, integrator::DEIntegrator, idxs, deriv)
[constant_extrapolant(τ, integrator, idxs, deriv) for τ in t]
end
function constant_extrapolant(t::Number, integrator::DEIntegrator, idxs, T::Type{Val{0}})
idxs === nothing ? integrator.u : integrator.u[idxs]
end
function constant_extrapolant(t::Number, integrator::DEIntegrator, idxs, T::Type{Val{1}})
idxs === nothing ? zero(integrator.u) ./ oneunit(t) :
zero(integrator.u[idxs]) ./ oneunit(t)
end
"""
constant_extrapolant!(val, t, integrator::DEIntegrator, idxs, deriv)
Calculate constant extrapolation of derivative `deriv` at time `t` and indices `idxs`
for `integrator`, and save result in `val` if `val` is not `nothing`.
"""
function constant_extrapolant!(val, t, integrator::DEIntegrator, idxs, deriv)
[constant_extrapolant!(val, τ, integrator, idxs, deriv) for τ in t]
end
function constant_extrapolant!(val, t::Number, integrator::DEIntegrator, idxs,
T::Type{Val{0}})
if val === nothing
if idxs === nothing
return integrator.u
else
return integrator.u[idxs]
end
elseif idxs === nothing
@. val = integrator.u
else
@views @. val = integrator.u[idxs]
end
end
function constant_extrapolant!(val, t::Number, integrator::DEIntegrator, idxs,
T::Type{Val{1}})
if val === nothing
if idxs === nothing
return zero(integrator.u) ./ oneunit(t)
else
return zero(integrator.u[idxs]) ./ oneunit(t)
end
elseif idxs === nothing
val .= zero(integrator.u) ./ oneunit(t)
else
@views val .= zero(integrator.u[idxs]) ./ oneunit(t)
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 23204 | function DiffEqBase.__solve(prob::DiffEqBase.AbstractDDEProblem,
alg::AbstractMethodOfStepsAlgorithm, args...;
kwargs...)
integrator = DiffEqBase.__init(prob, alg, args...; kwargs...)
DiffEqBase.solve!(integrator)
integrator.sol
end
function DiffEqBase.__init(prob::DiffEqBase.AbstractDDEProblem,
alg::AbstractMethodOfStepsAlgorithm,
timeseries_init = (),
ts_init = (),
ks_init = ();
saveat = (),
tstops = (),
d_discontinuities = (),
save_idxs = nothing,
save_everystep = isempty(saveat),
save_on = true,
save_start = save_everystep || isempty(saveat) ||
saveat isa Number || prob.tspan[1] in saveat,
save_end = nothing,
callback = nothing,
dense = save_everystep && isempty(saveat),
calck = (callback !== nothing && callback != CallbackSet()) || # Empty callback
dense, # and no dense output
dt = zero(eltype(prob.tspan)),
dtmin = DiffEqBase.prob2dtmin(prob; use_end_time = false),
dtmax = eltype(prob.tspan)(prob.tspan[end] - prob.tspan[1]),
force_dtmin = false,
adaptive = DiffEqBase.isadaptive(alg),
gamma = OrdinaryDiffEq.gamma_default(alg.alg),
abstol = nothing,
reltol = nothing,
qmin = OrdinaryDiffEq.qmin_default(alg.alg),
qmax = OrdinaryDiffEq.qmax_default(alg.alg),
qsteady_min = OrdinaryDiffEq.qsteady_min_default(alg.alg),
qsteady_max = OrdinaryDiffEq.qsteady_max_default(alg.alg),
qoldinit = DiffEqBase.isadaptive(alg) ? 1 // 10^4 : 0,
controller = nothing,
fullnormalize = true,
failfactor = 2,
beta1 = nothing,
beta2 = nothing,
maxiters = adaptive ? 1000000 : typemax(Int),
internalnorm = DiffEqBase.ODE_DEFAULT_NORM,
internalopnorm = LinearAlgebra.opnorm,
isoutofdomain = DiffEqBase.ODE_DEFAULT_ISOUTOFDOMAIN,
unstable_check = DiffEqBase.ODE_DEFAULT_UNSTABLE_CHECK,
verbose = true,
timeseries_errors = true,
dense_errors = false,
advance_to_tstop = false,
stop_at_next_tstop = false,
initialize_save = true,
progress = false,
progress_steps = 1000,
progress_name = "DDE",
progress_message = DiffEqBase.ODE_DEFAULT_PROG_MESSAGE,
progress_id = :DelayDiffEq,
userdata = nothing,
allow_extrapolation = OrdinaryDiffEq.alg_extrapolates(alg),
initialize_integrator = true,
alias_u0 = false,
# keyword arguments for DDEs
discontinuity_interp_points::Int = 10,
discontinuity_abstol = eltype(prob.tspan)(1 // Int64(10)^12),
discontinuity_reltol = 0,
kwargs...)
if haskey(kwargs, :initial_order)
@warn "initial_order has been deprecated. Please specify order_discontinuity_t0 in the DDEProblem instead."
order_discontinuity_t0::Int = kwargs[:initial_order]
else
order_discontinuity_t0 = prob.order_discontinuity_t0
end
if alg.alg isa CompositeAlgorithm && alg.alg.choice_function isa AutoSwitch
auto = alg.alg.choice_function
alg = MethodOfSteps(CompositeAlgorithm(alg.alg.algs,
OrdinaryDiffEq.AutoSwitchCache(0, 0,
auto.nonstiffalg,
auto.stiffalg,
auto.stiffalgfirst,
auto.maxstiffstep,
auto.maxnonstiffstep,
auto.nonstifftol,
auto.stifftol,
auto.dtfac,
auto.stiffalgfirst,
auto.switch_max)))
end
if haskey(kwargs, :minimal_solution)
@warn "minimal_solution is ignored"
end
if !isempty(saveat) && dense
@warn("Dense output is incompatible with saveat. Please use the SavingCallback from the Callback Library to mix the two behaviors.")
end
progress && @logmsg(-1, progress_name, _id=progress_id, progress=0)
isdae = prob.f.mass_matrix !== I && !(prob.f.mass_matrix isa Tuple) &&
ArrayInterface.issingular(prob.f.mass_matrix)
# unpack problem
@unpack f, u0, h, tspan, p, neutral, constant_lags, dependent_lags = prob
# determine type and direction of time
tType = eltype(tspan)
t0 = first(tspan)
tdir = sign(last(tspan) - t0)
tTypeNoUnits = typeof(one(tType))
# Allow positive dtmax, but auto-convert
dtmax > zero(dtmax) && tdir < zero(tdir) && (dtmax *= tdir)
# no fixed-point iterations for constrained algorithms,
# and thus `dtmax` should match minimal lag
if isconstrained(alg) && has_constant_lags(prob)
dtmax = tdir * min(abs(dtmax), minimum(abs, constant_lags))
end
# get absolute and relative tolerances
abstol_internal = get_abstol(u0, tspan, alg.alg; abstol = abstol)
reltol_internal = get_reltol(u0, tspan, alg.alg; reltol = reltol)
# get rate prototype
rate_prototype = rate_prototype_of(u0, tspan)
# get states (possibly different from the ODE integrator!)
u, uprev, uprev2 = u_uprev_uprev2(u0, alg;
alias_u0 = alias_u0,
adaptive = adaptive,
allow_extrapolation = allow_extrapolation,
calck = calck)
uEltypeNoUnits = recursive_unitless_eltype(u)
uBottomEltypeNoUnits = recursive_unitless_bottom_eltype(u)
# get the differential vs algebraic variables
differential_vars = prob isa DAEProblem ? prob.differential_vars :
OrdinaryDiffEq.get_differential_vars(f, u)
# create a history function
history = build_history_function(prob, alg, rate_prototype, reltol_internal,
differential_vars;
dt = dt, dtmin = dtmin, calck = false,
adaptive = adaptive, internalnorm = internalnorm)
f_with_history = ODEFunctionWrapper(f, history)
# initialize output arrays of the solution
k = typeof(rate_prototype)[]
ts, timeseries, ks = solution_arrays(u, tspan, rate_prototype;
timeseries_init = timeseries_init,
ts_init = ts_init,
ks_init = ks_init,
save_idxs = save_idxs,
save_start = save_start)
# build cache
ode_integrator = history.integrator
cache = OrdinaryDiffEq.alg_cache(alg.alg, u, rate_prototype, uEltypeNoUnits,
uBottomEltypeNoUnits, tTypeNoUnits, uprev, uprev2,
f_with_history, t0, zero(tType), reltol_internal, p,
calck,
Val(isinplace(prob)))
# separate statistics of the integrator and the history
stats = SciMLBase.DEStats(0)
# create solution
alg_choice = iscomposite(alg) ? Int[] : nothing
id = OrdinaryDiffEq.InterpolationData(f_with_history, timeseries, ts, ks,
alg_choice, dense, cache, differential_vars, false)
sol = DiffEqBase.build_solution(prob, alg.alg, ts, timeseries;
dense = dense, k = ks, interp = id,
alg_choice = id.alg_choice, calculate_error = false,
stats = stats)
# retrieve time stops, time points at which solutions is saved, and discontinuities
tstops_internal = OrdinaryDiffEq.initialize_tstops(tType, tstops, d_discontinuities,
tspan)
saveat_internal = OrdinaryDiffEq.initialize_saveat(tType, saveat, tspan)
d_discontinuities_internal = OrdinaryDiffEq.initialize_d_discontinuities(
Discontinuity{
tType,
Int
},
d_discontinuities,
tspan)
maximum_order = OrdinaryDiffEq.alg_maximum_order(alg)
tstops_propagated, d_discontinuities_propagated = initialize_tstops_d_discontinuities_propagated(
tType,
tstops,
d_discontinuities,
tspan,
order_discontinuity_t0,
maximum_order,
constant_lags,
neutral)
# reserve capacity for the solution
sizehint!(sol, alg, tspan, tstops_internal, saveat_internal;
save_everystep = save_everystep, adaptive = adaptive, dt = tType(dt),
dtmin = dtmin, internalnorm = internalnorm)
# create array of tracked discontinuities
# used to find propagated discontinuities with callbacks and to keep track of all
# passed discontinuities
tracked_discontinuities = Discontinuity{tType, Int}[]
if order_discontinuity_t0 ≤ maximum_order
push!(tracked_discontinuities, Discontinuity(tdir * t0, order_discontinuity_t0))
end
# Create set of callbacks and its cache
callback_set, callback_cache = callback_set_and_cache(prob, callback)
# separate options of integrator and of dummy ODE integrator since ODE integrator always saves
# every step and every index (necessary for history function)
QT = tTypeNoUnits <: Integer ? typeof(qmin) : typeof(internalnorm(u, t0))
# Setting up the step size controller
if (beta1 !== nothing || beta2 !== nothing) && controller !== nothing
throw(ArgumentError("Setting both the legacy PID parameters `beta1, beta2 = $((beta1, beta2))` and the `controller = $controller` is not allowed."))
end
if (beta1 !== nothing || beta2 !== nothing)
message = "Providing the legacy PID parameters `beta1, beta2` is deprecated. Use the keyword argument `controller` instead."
Base.depwarn(message, :init)
Base.depwarn(message, :solve)
end
if controller === nothing
controller = OrdinaryDiffEq.default_controller(alg.alg, cache,
convert(QT, qoldinit)::QT, beta1,
beta2)
end
save_end_user = save_end
save_end = save_end === nothing ?
save_everystep || isempty(saveat) || saveat isa Number ||
prob.tspan[2] in saveat : save_end
# added in OrdinaryDiffEq.jl#2032
if hasfield(OrdinaryDiffEq.DEOptions, :progress_id)
opts = OrdinaryDiffEq.DEOptions{typeof(abstol_internal), typeof(reltol_internal),
QT, tType, typeof(controller),
typeof(internalnorm), typeof(internalopnorm),
typeof(save_end_user),
typeof(callback_set),
typeof(isoutofdomain),
typeof(progress_message), typeof(unstable_check),
typeof(tstops_internal),
typeof(d_discontinuities_internal), typeof(userdata),
typeof(save_idxs),
typeof(maxiters), typeof(tstops),
typeof(saveat), typeof(d_discontinuities)}(maxiters,
save_everystep,
adaptive,
abstol_internal,
reltol_internal,
QT(gamma),
QT(qmax),
QT(qmin),
QT(qsteady_max),
QT(qsteady_min),
QT(qoldinit),
QT(failfactor),
tType(dtmax),
tType(dtmin),
controller,
internalnorm,
internalopnorm,
save_idxs,
tstops_internal,
saveat_internal,
d_discontinuities_internal,
tstops,
saveat,
d_discontinuities,
userdata,
progress,
progress_steps,
progress_name,
progress_message,
progress_id,
timeseries_errors,
dense_errors,
dense,
save_on,
save_start,
save_end,
save_end_user,
callback_set,
isoutofdomain,
unstable_check,
verbose,
calck,
force_dtmin,
advance_to_tstop,
stop_at_next_tstop)
else
opts = OrdinaryDiffEq.DEOptions{typeof(abstol_internal), typeof(reltol_internal),
QT, tType, typeof(controller),
typeof(internalnorm), typeof(internalopnorm),
typeof(save_end_user),
typeof(callback_set),
typeof(isoutofdomain),
typeof(progress_message), typeof(unstable_check),
typeof(tstops_internal),
typeof(d_discontinuities_internal), typeof(userdata),
typeof(save_idxs),
typeof(maxiters), typeof(tstops),
typeof(saveat), typeof(d_discontinuities)}(maxiters,
save_everystep,
adaptive,
abstol_internal,
reltol_internal,
QT(gamma),
QT(qmax),
QT(qmin),
QT(qsteady_max),
QT(qsteady_min),
QT(qoldinit),
QT(failfactor),
tType(dtmax),
tType(dtmin),
controller,
internalnorm,
internalopnorm,
save_idxs,
tstops_internal,
saveat_internal,
d_discontinuities_internal,
tstops,
saveat,
d_discontinuities,
userdata,
progress,
progress_steps,
progress_name,
progress_message,
#progress_id,
timeseries_errors,
dense_errors,
dense,
save_on,
save_start,
save_end,
save_end_user,
callback_set,
isoutofdomain,
unstable_check,
verbose,
calck,
force_dtmin,
advance_to_tstop,
stop_at_next_tstop)
end
# create fixed point solver
fpsolver = build_fpsolver(alg, alg.fpsolve, u, uEltypeNoUnits, uBottomEltypeNoUnits,
Val(isinplace(prob)))
# initialize indices of u(t) and u(tprev) in the dense history
prev_idx = 1
prev2_idx = 1
# create integrator combining the new defined problem function with history
# information, the new solution, the parameters of the ODE integrator, and
# parameters of fixed-point iteration
# do not initialize fsalfirst and fsallast
# rate/state = (state/time)/state = 1/t units, internalnorm drops units
eigen_est = inv(one(tType))
tprev = t0
dtcache = tType(dt)
dtpropose = tType(dt)
iter = 0
kshortsize = 0
reeval_fsal = false
u_modified = false
EEst = QT(1)
just_hit_tstop = false
do_error_check = true
isout = false
accept_step = false
force_stepfail = false
last_stepfail = false
event_last_time = 0
vector_event_last_time = 1
last_event_error = zero(uBottomEltypeNoUnits)
dtchangeable = OrdinaryDiffEq.isdtchangeable(alg.alg)
q11 = QT(1)
success_iter = 0
erracc = QT(1)
dtacc = tType(1)
if isdefined(OrdinaryDiffEq, :get_fsalfirstlast)
fsalfirst, fsallast = OrdinaryDiffEq.get_fsalfirstlast(cache, rate_prototype)
integrator = DDEIntegrator{typeof(alg.alg), isinplace(prob), typeof(u0), tType,
typeof(p),
typeof(eigen_est), QT, typeof(tdir), typeof(k), typeof(sol),
typeof(f_with_history), typeof(cache),
typeof(ode_integrator), typeof(fpsolver),
typeof(opts), typeof(discontinuity_abstol),
typeof(discontinuity_reltol), typeof(history),
typeof(tstops_propagated),
typeof(d_discontinuities_propagated),
typeof(fsalfirst),
typeof(last_event_error), typeof(callback_cache),
typeof(differential_vars)}(sol, u, k,
t0,
tType(dt),
f_with_history,
p,
uprev,
uprev2,
tprev,
prev_idx,
prev2_idx,
fpsolver,
order_discontinuity_t0,
tracked_discontinuities,
discontinuity_interp_points,
discontinuity_abstol,
discontinuity_reltol,
tstops_propagated,
d_discontinuities_propagated,
alg.alg,
dtcache,
dtchangeable,
dtpropose,
tdir,
eigen_est,
EEst,
QT(qoldinit),
q11,
erracc,
dtacc,
success_iter,
iter,
length(ts),
length(ts),
cache,
callback_cache,
kshortsize,
force_stepfail,
last_stepfail,
just_hit_tstop,
do_error_check,
event_last_time,
vector_event_last_time,
last_event_error,
accept_step,
isout,
reeval_fsal,
u_modified,
isdae,
opts,
stats,
history,
differential_vars,
ode_integrator, fsalfirst, fsallast)
else
integrator = DDEIntegrator{typeof(alg.alg), isinplace(prob), typeof(u0), tType,
typeof(p),
typeof(eigen_est), QT, typeof(tdir), typeof(k), typeof(sol),
typeof(f_with_history), typeof(cache),
typeof(ode_integrator), typeof(fpsolver),
typeof(opts), typeof(discontinuity_abstol),
typeof(discontinuity_reltol), typeof(history),
typeof(tstops_propagated),
typeof(d_discontinuities_propagated),
OrdinaryDiffEq.fsal_typeof(alg.alg, rate_prototype),
typeof(last_event_error), typeof(callback_cache),
typeof(differential_vars)}(sol, u, k,
t0,
tType(dt),
f_with_history,
p,
uprev,
uprev2,
tprev,
prev_idx,
prev2_idx,
fpsolver,
order_discontinuity_t0,
tracked_discontinuities,
discontinuity_interp_points,
discontinuity_abstol,
discontinuity_reltol,
tstops_propagated,
d_discontinuities_propagated,
alg.alg,
dtcache,
dtchangeable,
dtpropose,
tdir,
eigen_est,
EEst,
QT(qoldinit),
q11,
erracc,
dtacc,
success_iter,
iter,
length(ts),
length(ts),
cache,
callback_cache,
kshortsize,
force_stepfail,
last_stepfail,
just_hit_tstop,
do_error_check,
event_last_time,
vector_event_last_time,
last_event_error,
accept_step,
isout,
reeval_fsal,
u_modified,
isdae,
opts,
stats,
history,
differential_vars,
ode_integrator)
end
# initialize DDE integrator
if initialize_integrator
initialize_solution!(integrator)
OrdinaryDiffEq.initialize_callbacks!(integrator, initialize_save)
OrdinaryDiffEq.initialize!(integrator)
end
# take care of time step dt = 0 and dt with incorrect sign
OrdinaryDiffEq.handle_dt!(integrator)
integrator
end
function DiffEqBase.solve!(integrator::DDEIntegrator)
@unpack tdir, opts, sol = integrator
@unpack tstops = opts
# step over all stopping time points, similar to solving with ODE integrators
@inbounds while !isempty(tstops)
while tdir * integrator.t < first(tstops)
# apply step or adapt step size
OrdinaryDiffEq.loopheader!(integrator)
# abort integration following same criteria as for ODEs:
# maxiters exceeded, dt <= dtmin, integration unstable
DiffEqBase.check_error!(integrator) == ReturnCode.Success || return sol
# calculate next step
OrdinaryDiffEq.perform_step!(integrator)
# calculate proposed next step size, handle callbacks, and update solution
OrdinaryDiffEq.loopfooter!(integrator)
isempty(tstops) && break
end
# remove hit or passed stopping time points
OrdinaryDiffEq.handle_tstop!(integrator)
end
# clean up solution
DiffEqBase.postamble!(integrator)
f = sol.prob.f
if DiffEqBase.has_analytic(f)
DiffEqBase.calculate_solution_errors!(sol;
timeseries_errors = opts.timeseries_errors,
dense_errors = opts.dense_errors)
end
sol.retcode == ReturnCode.Default || return sol
integrator.sol = DiffEqBase.solution_new_retcode(sol, ReturnCode.Success)
end
function OrdinaryDiffEq.initialize_callbacks!(integrator::DDEIntegrator,
initialize_save = true)
callbacks = integrator.opts.callback
prob = integrator.sol.prob
# set up additional initial values of newly created DDE integrator
# (such as fsalfirst) and its callbacks
integrator.u_modified = true
u_modified = initialize!(callbacks, integrator.u, integrator.t, integrator)
# if the user modifies u, we need to fix previous values before initializing
# FSAL in order for the starting derivatives to be correct
if u_modified
if isinplace(prob)
recursivecopy!(integrator.uprev, integrator.u)
else
integrator.uprev = integrator.u
end
if OrdinaryDiffEq.alg_extrapolates(integrator.alg)
if isinplace(prob)
recursivecopy!(integrator.uprev2, integrator.uprev)
else
integrator.uprev2 = integrator.uprev
end
end
# update heap of discontinuities
# discontinuity is assumed to be of order 0, i.e. solution x is discontinuous
add_next_discontinuities!(integrator, 0, integrator.t)
# reset this as it is now handled so the integrators should proceed as normal
reeval_internals_due_to_modification!(integrator, Val{false})
if initialize_save &&
(any((c) -> c.save_positions[2], callbacks.discrete_callbacks) ||
any((c) -> c.save_positions[2], callbacks.continuous_callbacks))
savevalues!(integrator, true)
end
end
# reset this as it is now handled so the integrators should proceed as normal
integrator.u_modified = false
end
function initialize_tstops_d_discontinuities_propagated(::Type{T}, tstops,
d_discontinuities, tspan,
order_discontinuity_t0,
alg_maximum_order,
constant_lags, neutral) where {T}
# create heaps for propagated discontinuities and corresponding time stops
tstops_propagated = BinaryMinHeap{T}()
d_discontinuities_propagated = BinaryMinHeap{Discontinuity{T, Int}}()
# add discontinuities and time stops propagated from initial discontinuity
if constant_lags !== nothing && !isempty(constant_lags) &&
order_discontinuity_t0 ≤ alg_maximum_order
sizehint!(tstops_propagated, length(constant_lags))
sizehint!(d_discontinuities_propagated, length(constant_lags))
t0, tf = tspan
tdir = sign(tf - t0)
maxlag = tdir * (tf - t0)
next_order = neutral ? order_discontinuity_t0 : order_discontinuity_t0 + 1
for lag in constant_lags
if tdir * lag < maxlag
t = tdir * (t0 + lag)
push!(tstops_propagated, t)
d = Discontinuity{T, Int}(t, next_order)
push!(d_discontinuities_propagated, d)
end
end
end
return tstops_propagated, d_discontinuities_propagated
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 5389 | """
track_propagated_discontinuities!(integrator::DDEIntegrator)
Try to find a propagated discontinuity in the time interval `[integrator.t, integrator.t +
integrator.dt]` and add it to the set of discontinuities and grid points of the
`integrator`.
"""
function track_propagated_discontinuities!(integrator::DDEIntegrator)
# calculate interpolation points
interp_points = integrator.discontinuity_interp_points
Θs = range(zero(integrator.t); stop = oneunit(integrator.t), length = interp_points)
# for dependent lags and previous discontinuities
for lag in integrator.sol.prob.dependent_lags,
discontinuity in integrator.tracked_discontinuities
# obtain time of previous discontinuity
T = discontinuity.t
# estimate subinterval of current integration step that contains a propagated
# discontinuity induced by the lag and the previous discontinuity
interval = discontinuity_interval(integrator, lag, T, Θs)
# if a discontinuity exists in the current integration step
if interval !== nothing
# estimate time point of discontinuity
t = discontinuity_time(integrator, lag, T, interval)
# add new discontinuity of correct order at the estimated time point
if integrator.sol.prob.neutral
d = Discontinuity(t, discontinuity.order)
else
d = Discontinuity(t, discontinuity.order + 1)
end
push!(integrator.opts.d_discontinuities, d)
push!(integrator.opts.tstops, t)
# analogously to RADAR5 we do not strive for finding the first discontinuity
break
end
end
nothing
end
"""
discontinuity_function(integrator::DDEIntegrator, lag, T, t)
Evaluate function ``f(x) = T + lag(u(x), p, x) - x`` at time point `t`, where `T` is time
point of a previous discontinuity and `lag` is a dependent delay.
"""
function discontinuity_function(integrator::DDEIntegrator, lag, T, t)
tmp = get_tmp_cache(integrator)
cache = tmp === nothing ? nothing : first(tmp)
# estimate state at the given time
if cache === nothing
ut = integrator(t, Val{0})
else
integrator(cache, t, Val{0})
ut = cache
end
T + lag(ut, integrator.p, t) - t
end
"""
discontinuity_interval(integrator::DDEIntegrator, lag, T, Θs)
Return an estimated subinterval of the current integration step of the `integrator` that
contains a propagated discontinuity induced by the dependent delay `lag` and the
discontinuity at time point `T`, or `nothing`.
The interval is estimated by checking the signs of `T + lag(u(t), p, t) - t` for time points
`integrator.t .+ θs` in the interval `[integrator.t, integrator.t + integrator.dt]`.
"""
function discontinuity_interval(integrator::DDEIntegrator, lag, T, Θs)
# use start and end point of last time interval to check for discontinuities
previous_condition = discontinuity_function(integrator, lag, T, integrator.t)
if isapprox(previous_condition, 0;
rtol = integrator.discontinuity_reltol,
atol = integrator.discontinuity_abstol)
prev_sign = 0
else
prev_sign = cmp(previous_condition, zero(previous_condition))
end
new_condition = discontinuity_function(integrator, lag, T, integrator.t + integrator.dt)
new_sign = cmp(new_condition, zero(new_condition))
# if signs are different we already know that a discontinuity exists
if prev_sign * new_sign < 0
return (zero(eltype(Θs)), one(eltype(Θs)))
end
# recheck interpolation intervals if no discontinuity found yet
prev_Θ = zero(eltype(Θs))
for i in 2:length(Θs)
# evaluate sign at next interpolation point
new_Θ = Θs[i]
new_t = integrator.t + new_Θ * integrator.dt
new_condition = discontinuity_function(integrator, lag, T, new_t)
new_sign = cmp(new_condition, zero(new_condition))
# return estimated interval if we find a root or observe a switch of signs
if new_sign == 0
return (new_Θ, new_Θ)
elseif prev_sign * new_sign < 0
return (prev_Θ, new_Θ)
else
# otherwise update lower estimate of subinterval
prev_sign = new_sign
prev_Θ = new_Θ
end
end
nothing
end
"""
discontinuity_time(integrator::DDEIntegrator, lag, T, interval)
Estimate time point of the propagated discontinuity induced by the dependent delay
`lag` and the discontinuity at time point `T` inside the `interval` of the current
integration step of the `integrator`.
"""
function discontinuity_time(integrator::DDEIntegrator, lag, T, (bottom_Θ, top_Θ))
if bottom_Θ == top_Θ
# in that case we have already found the time point of a discontinuity
Θ = top_Θ
else
# define function for root finding
zero_func = let integrator = integrator, lag = lag, T = T, t = integrator.t,
dt = integrator.dt
(θ, p = nothing) -> discontinuity_function(integrator, lag, T, t + θ * dt)
end
Θ = SimpleNonlinearSolve.solve(
SimpleNonlinearSolve.IntervalNonlinearProblem{false}(zero_func,
(bottom_Θ,
top_Θ)),
SimpleNonlinearSolve.Falsi()).left
end
integrator.t + Θ * integrator.dt
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 11687 | """
has_constant_lags(integrator::DDEIntegrator)
Return if the DDE problem of the `integrator` contains constant delays.
"""
has_constant_lags(integrator::DDEIntegrator) = has_constant_lags(integrator.sol.prob)
"""
has_dependent_lags(integrator::DDEIntegrator)
Return if the DDE problem of the `integrator` contains dependent delays.
"""
has_dependent_lags(integrator::DDEIntegrator) = has_dependent_lags(integrator.sol.prob)
"""
has_constant_lags(prob::DDEProblem)
Return if the DDE problem `prob` contains constant delays.
"""
function has_constant_lags(prob::DDEProblem)
prob.constant_lags !== nothing && !isempty(prob.constant_lags)
end
"""
has_dependent_lags(prob::DDEProblem)
Return if the DDE problem `prob` contains dependent delays.
"""
function has_dependent_lags(prob::DDEProblem)
prob.dependent_lags !== nothing && !isempty(prob.dependent_lags)
end
"""
u_uprev(u0, alg; kwargs...)
Return state vectors `u` and `uprev` (possibly aliased) for solving the
differential equation problem for initial state `u0` with algorithm `alg`.
"""
function u_uprev(u0, alg;
alias_u0 = false,
adaptive = DiffEqBase.isadaptive(alg),
calck = false)
if alias_u0
u = u0
else
u = recursivecopy(u0)
end
# Some algorithms do not use `uprev` explicitly. In that case, we can save
# some memory by aliasing `uprev = u`, e.g. for "2N" low storage methods.
if OrdinaryDiffEq.uses_uprev(alg, adaptive) || calck
uprev = recursivecopy(u)
else
uprev = u
end
u, uprev
end
"""
u_uprev_uprev2(u0, alg; kwargs...)
Return state vectors `u`, `uprev`, and `uprev2` (possibly aliased) for solving the
differential equation problem for initial state `u0` with algorithm `alg`.
"""
function u_uprev_uprev2(u0, alg;
allow_extrapolation = alg_extrapolates(alg),
kwargs...)
# compute u and uprev first
u, uprev = u_uprev(u0, alg; kwargs...)
if allow_extrapolation
uprev2 = recursivecopy(u)
else
uprev2 = uprev
end
u, uprev, uprev2
end
"""
get_abstol(u, tspan, alg; abstol = nothing)
Return the absolute tolerance for solving the differential equation problem with state
variable `u` and time span `tspan` with algorithm `alg`.
"""
function get_abstol(u, tspan, alg; abstol = nothing)
if alg isa FunctionMap
_abstol = real.(zero.(u))
elseif abstol === nothing
uBottomEltype = recursive_bottom_eltype(u)
uBottomEltypeNoUnits = recursive_unitless_bottom_eltype(u)
if uBottomEltypeNoUnits == uBottomEltype
_abstol = real(convert(uBottomEltype, oneunit(uBottomEltype) * 1 // 10^6))
else
_abstol = real.(oneunit.(u) .* 1 // 10^6)
end
else
_abstol = real.(abstol)
end
_abstol
end
"""
get_reltol(u, tspan, alg; reltol = nothing)
Return the relative tolerance for solving the differential equation problem with state
variable `u` and time span `tspan` with algorithm `alg`.
"""
function get_reltol(u, tspan, alg; reltol = nothing)
if alg isa FunctionMap
_reltol = real.(zero(first(u) / t))
elseif reltol === nothing
uBottomEltype = recursive_bottom_eltype(u)
uBottomEltypeNoUnits = recursive_unitless_bottom_eltype(u)
if uBottomEltypeNoUnits == uBottomEltype
_reltol = real(convert(uBottomEltype, oneunit(uBottomEltype) * 1 // 10^3))
else
_reltol = real.(oneunit.(u) .* 1 // 10^3)
end
else
_reltol = real.(reltol)
end
_reltol
end
"""
callback_set_and_cache(prob, callback)
Return set of callbacks and its cache for the differential equation problem `prob` and the
user-provided `callback`.
"""
function callback_set_and_cache(prob, callback)
callback_set = CallbackSet(callback)
max_len_cb = DiffEqBase.max_vector_callback_length(callback_set)
if max_len_cb isa VectorContinuousCallback
uBottomEltype = recursive_bottom_eltype(prob.u0)
callback_cache = DiffEqBase.CallbackCache(max_len_cb.len, uBottomEltype,
uBottomEltype)
else
callback_cache = nothing
end
callback_set, callback_cache
end
"""
rate_prototype_of(u0, tspan)
Return prototype of rates for a given differential equation problem with state `u` and
time span `tspan`.
"""
rate_prototype_of(u0, tspan) = DiffEqBase.@.. u0 * $(inv(oneunit(eltype(tspan))))
"""
solution_arrays(u, tspan, rate_prototype; kwargs...)
Return arrays of saved time points, states, and rates, initialized with the solution at the
first time point if `save_start = true` (the default).
"""
function solution_arrays(u, tspan, rate_prototype;
timeseries_init,
ts_init,
ks_init,
save_idxs,
save_start)
# determine types of time and state
uType = typeof(u)
tType = eltype(tspan)
# initialize vector of saved time points
ts = ts_init === () ? tType[] : convert(Vector{tType}, ts_init)
# initialize vector of saved states
if save_idxs === nothing
timeseries = timeseries_init === () ? uType[] :
convert(Vector{uType}, timeseries_init)
else
u_initial = u[save_idxs]
timeseries = timeseries_init === () ? typeof(u_initial)[] :
convert(Vector{typeof(u_initial)}, timeseries_init)
end
# initialize vector of saved rates
if save_idxs === nothing
ksEltype = Vector{typeof(rate_prototype)}
else
ks_prototype = rate_prototype[save_idxs]
ksEltype = Vector{typeof(ks_prototype)}
end
ks = ks_init === () ? ksEltype[] : convert(Vector{ksEltype}, ks_init)
# save solution at initial time point
if save_start
copyat_or_push!(ts, 1, first(tspan))
if save_idxs === nothing
copyat_or_push!(timeseries, 1, u)
copyat_or_push!(ks, 1, [rate_prototype])
else
u_initial = u[save_idxs]
copyat_or_push!(timeseries, 1, u_initial, Val{false})
copyat_or_push!(ks, 1, [ks_prototype])
end
end
ts, timeseries, ks
end
"""
sizehint!(sol::DESolution, n)
Suggest that solution `sol` reserves capacity for at least `n` elements.
"""
function Base.sizehint!(sol::DESolution, n)
sizehint!(sol.u, n)
sizehint!(sol.t, n)
sizehint!(sol.k, n)
nothing
end
"""
sizehint!(sol::DESolution, alg, tspan, tstops, saveat; kwargs...)
Suggest that solution `sol` reserves capacity for a number of elements that
depends on the parameter settings of the numerical solver.
"""
function Base.sizehint!(sol::DESolution, alg, tspan, tstops, saveat;
save_everystep, adaptive, internalnorm, dt, dtmin)
# obtain integration time
t0 = first(tspan)
integrationtime = last(tspan) - t0
if !adaptive && save_everystep && !isinf(integrationtime)
# determine number of steps if known a priori
if iszero(dt)
steps = length(tstops)
else
abs(dt) < dtmin && throw(ArgumentError("Supplied dt is smaller than dtmin"))
steps = ceil(Int, internalnorm(integrationtime / dt, t0))
end
sizehint!(sol, steps + 1)
elseif save_everystep
sizehint!(sol, 50)
elseif !isempty(saveat)
sizehint!(sol, length(saveat) + 1)
else
sizehint!(sol, 2)
end
nothing
end
function build_history_function(prob, alg, rate_prototype, reltol, differential_vars;
dt, dtmin, adaptive, calck, internalnorm)
@unpack f, u0, tspan, p = prob
t0 = first(tspan)
tType = eltype(tspan)
tTypeNoUnits = typeof(one(tType))
tdir = sign(last(tspan) - t0)
uEltypeNoUnits = recursive_unitless_eltype(u0)
uBottomEltypeNoUnits = recursive_unitless_bottom_eltype(u0)
# bootstrap an ODE integrator
# - whose solution captures the dense history of the simulation
# - that is used for extrapolation of the history for time points past the
# already fixed history
# - that is used for interpolation of the history for time points in the
# current integration step (so the interpolation is fixed while updating the stages)
# we wrap the user-provided history function such that function calls during the setup
# of the integrator do not fail
ode_f = ODEFunctionWrapper(f, prob.h)
ode_prob = ODEProblem{isinplace(prob)}(ode_f, u0, tspan, p)
# get states of ODE integrator (do not alias uprev)
ode_u, ode_uprev = u_uprev(u0, alg; alias_u0 = false, calck = true)
# initialize output arrays
ode_k = typeof(rate_prototype)[]
ode_ts, ode_timeseries, ode_ks = solution_arrays(ode_u, tspan, rate_prototype;
timeseries_init = (),
ts_init = (),
ks_init = (),
save_idxs = nothing,
save_start = true)
# obtain cache (we alias uprev2 and uprev)
ode_cache = OrdinaryDiffEq.alg_cache(alg.alg, ode_u, rate_prototype, uEltypeNoUnits,
uBottomEltypeNoUnits, tTypeNoUnits, ode_uprev,
ode_uprev, ode_f, t0, zero(tType), reltol, p,
calck,
Val(isinplace(prob)))
# build dense interpolation of history
ode_alg_choice = iscomposite(alg) ? Int[] : nothing
ode_id = OrdinaryDiffEq.InterpolationData(ode_f, ode_timeseries, ode_ts,
ode_ks,
ode_alg_choice, true, ode_cache,
differential_vars, false)
ode_sol = DiffEqBase.build_solution(ode_prob, alg.alg, ode_ts, ode_timeseries;
dense = true, k = ode_ks, interp = ode_id,
alg_choice = ode_alg_choice,
calculate_error = false,
stats = DiffEqBase.Stats(0))
# reserve capacity
sizehint!(ode_sol, alg.alg, tspan, (), ();
save_everystep = true, adaptive = adaptive, internalnorm = internalnorm,
dt = dt, dtmin = dtmin)
# create simple integrator
tdirType = typeof(sign(zero(tType)))
ode_integrator = HistoryODEIntegrator{
typeof(alg.alg), isinplace(prob), typeof(prob.u0),
tType, tdirType, typeof(ode_k),
typeof(ode_sol), typeof(ode_cache),
typeof(differential_vars)}(ode_sol,
ode_u, ode_k,
t0,
zero(tType),
ode_uprev,
t0, alg.alg,
zero(tType),
tdir, 1, 1,
ode_cache,
differential_vars)
# combine the user-provided history function and the ODE integrator with dense solution
# to a joint dense history of the DDE
# we use this history information to create a problem function of the DDE with all
# available history information that is of the form f(du,u,p,t) or f(u,p,t) such that
# ODE algorithms can be applied
HistoryFunction(prob.h, ode_integrator)
end
"""
initialize_solution!(integrator::DDEIntegrator)
Initialize the solution of an integrator by adjusting the cache for composite algorithms.
"""
function initialize_solution!(integrator::DDEIntegrator)
if iscomposite(integrator.alg)
copyat_or_push!(integrator.integrator.sol.alg_choice, 1, integrator.cache.current)
if integrator.opts.save_start
copyat_or_push!(integrator.sol.alg_choice, 1, integrator.cache.current)
end
end
nothing
end
function unwrap_alg(integrator::DDEIntegrator, is_stiff)
alg = integrator.alg
iscomp = alg isa CompositeAlgorithm
if !iscomp
return alg
elseif alg.choice_function isa AutoSwitch
num = is_stiff ? 2 : 1
return alg.algs[num]
else
return alg.algs[integrator.cache.current]
end
end
function OrdinaryDiffEq.nlsolve_f(integrator::DDEIntegrator)
OrdinaryDiffEq.nlsolve_f(integrator.f, unwrap_alg(integrator, true))
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 540 | OrdinaryDiffEq.initial_η(fpsolver::FPSolver, integrator::DDEIntegrator) = fpsolver.ηold
OrdinaryDiffEq.apply_step!(fpsolver::FPSolver, integrator::DDEIntegrator) = nothing
function DiffEqBase.postamble!(fpsolver::FPSolver, integrator::DDEIntegrator)
integrator.stats.nfpiter += fpsolver.iter
if OrdinaryDiffEq.nlsolvefail(fpsolver)
integrator.stats.nfpconvfail += 1
end
integrator.force_stepfail = OrdinaryDiffEq.nlsolvefail(fpsolver) ||
integrator.force_stepfail
nothing
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 4821 | function OrdinaryDiffEq.compute_step!(fpsolver::FPSolver{<:NLFunctional},
integrator::DDEIntegrator)
# update ODE integrator to next time interval together with correct interpolation
if fpsolver.iter == 1
advance_ode_integrator!(integrator)
else
update_ode_integrator!(integrator)
end
compute_step_fixedpoint!(fpsolver, integrator)
end
function OrdinaryDiffEq.compute_step!(fpsolver::FPSolver{<:NLAnderson, false},
integrator::DDEIntegrator)
@unpack cache, iter = fpsolver
@unpack aa_start = cache
# perform Anderson acceleration
previter = iter - 1
if previter == aa_start
# update cached values for next step of Anderson acceleration
cache.dzold = cache.dz
cache.z₊old = integrator.u
elseif previter > aa_start
# actually perform Anderson acceleration
integrator.u = OrdinaryDiffEq.anderson(integrator.u, cache)
integrator.stats.nsolve += 1
end
# update ODE integrator to next time interval together with correct interpolation
if iter == 1
advance_ode_integrator!(integrator)
else
# force recomputation of all interpolation data if Anderson acceleration was performed
update_ode_integrator!(integrator, previter > aa_start)
end
# compute next step
compute_step_fixedpoint!(fpsolver, integrator)
end
function OrdinaryDiffEq.compute_step!(fpsolver::FPSolver{<:NLAnderson, true},
integrator::DDEIntegrator)
@unpack cache, iter = fpsolver
@unpack aa_start = cache
# perform Anderson acceleration
previter = iter - 1
if previter == aa_start
# update cached values for next step of Anderson acceleration
@.. cache.dzold = cache.dz
@.. cache.z₊old = integrator.u
elseif previter > aa_start
# actually perform Anderson acceleration
OrdinaryDiffEq.anderson!(integrator.u, cache)
integrator.stats.nsolve += 1
end
# update ODE integrator to next time interval together with correct interpolation
if iter == 1
advance_ode_integrator!(integrator)
else
# force recomputation of all interpolation data if Anderson acceleration was performed
update_ode_integrator!(integrator, previter > aa_start)
end
# compute next step
compute_step_fixedpoint!(fpsolver, integrator)
end
function compute_step_fixedpoint!(
fpsolver::FPSolver{<:Union{NLFunctional, NLAnderson},
false},
integrator::DDEIntegrator)
@unpack t, opts = integrator
@unpack cache = fpsolver
ode_integrator = integrator.integrator
# recompute next integration step
OrdinaryDiffEq.perform_step!(integrator, integrator.cache, true)
# compute residuals
dz = integrator.u .- ode_integrator.u
atmp = OrdinaryDiffEq.calculate_residuals(dz, ode_integrator.u, integrator.u,
opts.abstol, opts.reltol, opts.internalnorm,
t)
# cache results
if isdefined(cache, :dz)
cache.dz = dz
end
opts.internalnorm(atmp, t)
end
function compute_step_fixedpoint!(
fpsolver::FPSolver{<:Union{NLFunctional, NLAnderson},
true},
integrator::DDEIntegrator)
@unpack t, opts = integrator
@unpack cache = fpsolver
@unpack dz, atmp = cache
ode_integrator = integrator.integrator
# recompute next integration step
OrdinaryDiffEq.perform_step!(integrator, integrator.cache, true)
# compute residuals
@.. dz = integrator.u - ode_integrator.u
OrdinaryDiffEq.calculate_residuals!(atmp, dz, ode_integrator.u, integrator.u,
opts.abstol, opts.reltol, opts.internalnorm, t)
opts.internalnorm(atmp, t)
end
## resize!
function Base.resize!(fpcache::FPFunctionalCache, i::Int)
resize!(fpcache.atmp, i)
resize!(fpcache.dz, i)
nothing
end
function Base.resize!(fpcache::FPAndersonCache, fpsolver::FPSolver{<:NLAnderson},
integrator::DDEIntegrator, i::Int)
resize!(fpcache, fpsolver.alg, i)
end
function Base.resize!(fpcache::FPAndersonCache, fpalg::NLAnderson, i::Int)
@unpack z₊old, Δz₊s = fpcache
resize!(fpcache.atmp, i)
resize!(fpcache.dz, i)
resize!(fpcache.dzold, i)
resize!(z₊old, i)
# update history of Anderson cache
max_history_old = length(Δz₊s)
max_history = min(fpalg.max_history, fpalg.max_iter, i)
resize!(fpcache.γs, max_history)
resize!(fpcache.Δz₊s, max_history)
if max_history != max_history_old
fpcache.Q = typeof(fpcache.Q)(undef, i, max_history)
fpcache.R = typeof(fpcache.R)(undef, max_history, max_history)
end
max_history = length(Δz₊s)
if max_history > max_history_old
for i in (max_history_old + 1):max_history
Δz₊s[i] = zero(z₊old)
end
end
nothing
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1200 | # solver
mutable struct FPSolver{algType, iip, uTolType, C <: AbstractNLSolverCache} <:
OrdinaryDiffEq.AbstractNLSolver{algType, iip}
alg::algType
κ::uTolType
fast_convergence_cutoff::uTolType
ηold::uTolType
iter::Int
maxiters::Int
status::OrdinaryDiffEq.NLStatus
cache::C
nfails::Int
end
# caches
struct FPFunctionalCache{uType, uNoUnitsType} <: AbstractNLSolverCache
atmp::uNoUnitsType
dz::uType
end
struct FPFunctionalConstantCache <: AbstractNLSolverCache end
mutable struct FPAndersonCache{uType, uNoUnitsType, uEltypeNoUnits, D} <:
AbstractNLSolverCache
atmp::uNoUnitsType
dz::uType
dzold::uType
z₊old::uType
Δz₊s::Vector{uType}
Q::Matrix{uEltypeNoUnits}
R::Matrix{uEltypeNoUnits}
γs::Vector{uEltypeNoUnits}
history::Int
aa_start::Int
droptol::D
end
mutable struct FPAndersonConstantCache{uType, uEltypeNoUnits, D} <:
AbstractNLSolverCache
dz::uType
dzold::uType
z₊old::uType
Δz₊s::Vector{uType}
Q::Matrix{uEltypeNoUnits}
R::Matrix{uEltypeNoUnits}
γs::Vector{uEltypeNoUnits}
history::Int
aa_start::Int
droptol::D
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 2904 | # construct solver for fixed-point iterations
function build_fpsolver(alg, fpalg::Union{NLFunctional, NLAnderson}, u, uEltypeNoUnits,
uBottomEltypeNoUnits, ::Val{true})
# no fixed-point iterations if the algorithm is constrained
isconstrained(alg) && return
# define unitless type
uTolType = real(uBottomEltypeNoUnits)
# could use integrator.cache.atmp if guaranteed to exist
atmp = similar(u, uEltypeNoUnits)
dz = similar(u)
# build cache
if fpalg isa NLFunctional
fpcache = FPFunctionalCache(atmp, dz)
elseif fpalg isa NLAnderson
max_history = min(fpalg.max_history, fpalg.max_iter, length(u))
Δz₊s = [zero(u) for i in 1:max_history]
Q = Matrix{uEltypeNoUnits}(undef, length(u), max_history)
R = Matrix{uEltypeNoUnits}(undef, max_history, max_history)
γs = Vector{uEltypeNoUnits}(undef, max_history)
dzold = zero(u)
z₊old = zero(u)
fpcache = FPAndersonCache(
atmp, dz, dzold, z₊old, Δz₊s, Q, R, γs, 0, fpalg.aa_start,
fpalg.droptol)
end
# build solver
ηold = one(uTolType)
FPSolver{typeof(fpalg), true, uTolType, typeof(fpcache)}(fpalg, uTolType(fpalg.κ),
uTolType(fpalg.fast_convergence_cutoff),
ηold, 10000,
fpalg.max_iter,
SlowConvergence, fpcache, 0)
end
function build_fpsolver(alg, fpalg::Union{NLFunctional, NLAnderson}, u, uEltypeNoUnits,
uBottomEltypeNoUnits, ::Val{false})
# no fixed-point iterations if the algorithm is constrained
isconstrained(alg) && return
# define unitless type
uTolType = real(uBottomEltypeNoUnits)
# build cache
if fpalg isa NLFunctional
fpcache = FPFunctionalConstantCache()
elseif fpalg isa NLAnderson
max_history = min(fpalg.max_history, fpalg.max_iter, length(u))
Δz₊s = Vector{typeof(u)}(undef, max_history)
Q = Matrix{uEltypeNoUnits}(undef, length(u), max_history)
R = Matrix{uEltypeNoUnits}(undef, max_history, max_history)
γs = Vector{uEltypeNoUnits}(undef, max_history)
dz = u
dzold = u
z₊old = u
fpcache = FPAndersonConstantCache(dz, dzold, z₊old, Δz₊s, Q, R, γs, 0,
fpalg.aa_start,
fpalg.droptol)
end
# build solver
ηold = one(uTolType)
FPSolver{typeof(fpalg), false, uTolType, typeof(fpcache)}(fpalg, uTolType(fpalg.κ),
uTolType(fpalg.fast_convergence_cutoff),
ηold, 10_000,
fpalg.max_iter,
SlowConvergence, fpcache, 0)
end
## resize
function resize_fpsolver!(integrator::DDEIntegrator, i::Int)
@unpack fpsolver = integrator
if fpsolver !== nothing
resize!(fpsolver, integrator, i)
end
nothing
end
function Base.resize!(fpsolver::FPSolver, integrator::DDEIntegrator, i::Int)
resize!(fpsolver.cache, fpsolver, integrator, i)
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 20564 | # accept/reject computed integration step, propose next step, and apply callbacks
function OrdinaryDiffEq.loopfooter!(integrator::DDEIntegrator)
# apply same logic as in OrdinaryDiffEq
OrdinaryDiffEq._loopfooter!(integrator)
if !integrator.accept_step
# reset ODE integrator to the cached values if the last step failed
move_back_ode_integrator!(integrator)
# track propagated discontinuities for dependent delays
if integrator.opts.adaptive && integrator.iter > 0 && has_dependent_lags(integrator)
track_propagated_discontinuities!(integrator)
end
end
nothing
end
# save current state of the integrator
function DiffEqBase.savevalues!(integrator::HistoryODEIntegrator, force_save = false,
reduce_size = false)::Tuple{Bool, Bool}
integrator.saveiter += 1
# TODO: save history only for a subset of components
copyat_or_push!(integrator.sol.t, integrator.saveiter, integrator.t)
copyat_or_push!(integrator.sol.u, integrator.saveiter, integrator.u)
integrator.saveiter_dense += 1
copyat_or_push!(integrator.sol.k, integrator.saveiter_dense, integrator.k)
if iscomposite(integrator.alg)
copyat_or_push!(integrator.sol.alg_choice, integrator.saveiter,
integrator.cache.current)
end
true, true
end
function DiffEqBase.savevalues!(integrator::DDEIntegrator, force_save = false,
reduce_size = false)::Tuple{Bool, Bool}
ode_integrator = integrator.integrator
# update time of ODE integrator (can be slightly modified (< 10ϵ) because of time stops)
# integrator.EEst has unitless type of integrator.t
if integrator.EEst isa AbstractFloat
if ode_integrator.t != integrator.t
abs(integrator.t - ode_integrator.t) < 100eps(integrator.t) ||
error("unexpected time discrepancy detected")
ode_integrator.t = integrator.t
ode_integrator.dt = ode_integrator.t - ode_integrator.tprev
end
end
# if forced, then the user or an event changed the state u directly.
if force_save
if isinplace(integrator.sol.prob)
ode_integrator.u .= integrator.u
else
ode_integrator.u = integrator.u
end
end
# update history
saved, savedexactly = DiffEqBase.savevalues!(ode_integrator, force_save,
false) # reduce_size = false
# check that history was actually updated
saved || error("dense history could not be updated")
# update prev2_idx to indices of tprev and u(tprev) in solution
# allows reset of ODE integrator (and hence history function) to the last
# successful time step after failed steps
integrator.prev2_idx = integrator.prev_idx
# cache dt of interval [tprev, t] of ODE integrator since it can only be retrieved by
# a possibly incorrect subtraction
# NOTE: does not interfere with usual use of dtcache for non-adaptive methods since ODE
# integrator is only used for inter- and extrapolation of future values and saving of
# the solution but does not affect the size of time steps
ode_integrator.dtcache = ode_integrator.dt
# update solution
OrdinaryDiffEq._savevalues!(integrator, force_save, reduce_size)
end
# clean up the solution of the integrator
function DiffEqBase.postamble!(integrator::HistoryODEIntegrator)
if integrator.saveiter == 0 || integrator.sol.t[integrator.saveiter] != integrator.t
integrator.saveiter += 1
copyat_or_push!(integrator.sol.t, integrator.saveiter, integrator.t)
copyat_or_push!(integrator.sol.u, integrator.saveiter, integrator.u)
integrator.saveiter_dense += 1
copyat_or_push!(integrator.sol.k, integrator.saveiter_dense, integrator.k)
if iscomposite(integrator.alg)
copyat_or_push!(integrator.sol.alg_choice, integrator.saveiter,
integrator.cache.current)
end
end
resize!(integrator.sol.t, integrator.saveiter)
resize!(integrator.sol.u, integrator.saveiter)
resize!(integrator.sol.k, integrator.saveiter_dense)
nothing
end
function DiffEqBase.postamble!(integrator::DDEIntegrator)
# clean up solution of the ODE integrator
DiffEqBase.postamble!(integrator.integrator)
# clean solution of the DDE integrator
OrdinaryDiffEq._postamble!(integrator)
end
# perform next integration step
function OrdinaryDiffEq.perform_step!(integrator::DDEIntegrator)
@unpack cache, history = integrator
# reset boolean which indicates if the history function was evaluated at a time point
# past the final point of the current solution
history.isout = false
# perform always at least one calculation of the stages
OrdinaryDiffEq.perform_step!(integrator, cache)
# if the history function was evaluated at time points past the final time point of the
# solution, i.e. returned extrapolated values, continue with a fixed-point iteration
if history.isout
# perform fixed-point iteration
OrdinaryDiffEq.nlsolve!(integrator.fpsolver, integrator)
end
# update ODE integrator to next time interval together with correct interpolation
advance_or_update_ode_integrator!(integrator)
nothing
end
# initialize the integrator
function OrdinaryDiffEq.initialize!(integrator::DDEIntegrator)
ode_integrator = integrator.integrator
# initialize the cache
OrdinaryDiffEq.initialize!(integrator, integrator.cache)
# copy interpolation data to the ODE integrator
@inbounds for i in 1:length(integrator.k)
copyat_or_push!(ode_integrator.k, i, integrator.k[i])
end
nothing
end
# signal the integrator that state u was modified
function DiffEqBase.u_modified!(integrator::DDEIntegrator, bool::Bool)
integrator.u_modified = bool
end
# return next integration time step
DiffEqBase.get_proposed_dt(integrator::DDEIntegrator) = integrator.dtpropose
# set next integration time step
function DiffEqBase.set_proposed_dt!(integrator::DDEIntegrator, dt)
integrator.dtpropose = dt
nothing
end
# obtain caches
function DiffEqBase.get_tmp_cache(integrator::DDEIntegrator)
get_tmp_cache(integrator, integrator.alg, integrator.cache)
end
DiffEqBase.user_cache(integrator::DDEIntegrator) = user_cache(integrator.cache)
DiffEqBase.u_cache(integrator::DDEIntegrator) = u_cache(integrator.cache)
DiffEqBase.du_cache(integrator::DDEIntegrator) = du_cache(integrator.cache)
DiffEqBase.full_cache(integrator::DDEIntegrator) = full_cache(integrator.cache)
# change number of components
Base.resize!(integrator::DDEIntegrator, i::Int) = resize!(integrator, integrator.cache, i)
function Base.resize!(integrator::DDEIntegrator, cache, i)
# resize ODE integrator (do only have to care about u and k)
ode_integrator = integrator.integrator
resize!(ode_integrator.u, i)
for k in ode_integrator.k
resize!(k, i)
end
# resize DDE integrator
for c in full_cache(cache)
resize!(c, i)
end
OrdinaryDiffEq.resize_nlsolver!(integrator, i)
OrdinaryDiffEq.resize_J_W!(cache, integrator, i)
resize_non_user_cache!(integrator, cache, i)
resize_fpsolver!(integrator, i)
nothing
end
DiffEqBase.resize_non_user_cache!(integrator::DDEIntegrator, cache, i) = nothing
function DiffEqBase.resize_non_user_cache!(integrator::DDEIntegrator,
cache::RosenbrockMutableCache, i)
cache.J = similar(cache.J, i, i)
cache.W = similar(cache.W, i, i)
OrdinaryDiffEq.resize_jac_config!(cache.jac_config, i)
OrdinaryDiffEq.resize_grad_config!(cache.grad_config, i)
nothing
end
# delete component(s)
function Base.deleteat!(integrator::DDEIntegrator, idxs)
# delete components of ODE integrator (do only have to care about u and k)
ode_integrator = integrator.integrator
deleteat!(ode_integrator.u, idxs)
for k in ode_integrator.k
deleteat!(k, idxs)
end
# delete components of DDE integrator
for c in full_cache(integrator)
deleteat!(c, idxs)
end
deleteat_non_user_cache!(integrator, integrator.cache, i)
end
function DiffEqBase.deleteat_non_user_cache!(integrator::DDEIntegrator, cache, idxs)
i = length(integrator.u)
resize_non_user_cache!(integrator, cache, i)
end
# add component(s)
function DiffEqBase.addat!(integrator::DDEIntegrator, idxs)
# add components to ODE integrator (do only have to care about u and k)
ode_integrator = integrator.integrator
addat!(ode_integrator.u, idxs)
for k in ode_integrator.k
addat!(k, idxs)
end
# add components to DDE integrator
for c in full_cache(integrator)
addat!(c, idxs)
end
addat_non_user_cache!(integrator, integrator.cache, idxs)
end
function DiffEqBase.addat_non_user_cache!(integrator::DDEIntegrator, cache, idxs)
i = length(integrator.u)
resize_non_user_cache!(integrator, cache, i)
end
# error check
function DiffEqBase.last_step_failed(integrator::DDEIntegrator)
integrator.last_stepfail && !integrator.opts.adaptive
end
# terminate integration
function DiffEqBase.terminate!(integrator::DDEIntegrator, retcode = ReturnCode.Terminated)
integrator.sol = DiffEqBase.solution_new_retcode(integrator.sol, retcode)
integrator.opts.tstops.valtree = typeof(integrator.opts.tstops.valtree)()
nothing
end
# integrator can be reinitialized
DiffEqBase.has_reinit(::HistoryODEIntegrator) = true
DiffEqBase.has_reinit(integrator::DDEIntegrator) = true
function DiffEqBase.reinit!(integrator::HistoryODEIntegrator, u0 = integrator.sol.prob.u0;
t0 = integrator.sol.prob.tspan[1],
tf = integrator.sol.prob.tspan[end],
erase_sol = true)
# reinit initial values of the integrator
if isinplace(integrator.sol.prob)
recursivecopy!(integrator.u, u0)
recursivecopy!(integrator.uprev, integrator.u)
else
integrator.u = u0
integrator.uprev = integrator.u
end
integrator.t = t0
integrator.tprev = t0
integrator.dt = zero(integrator.dt)
integrator.dtcache = zero(integrator.dtcache)
# erase solution
if erase_sol
# resize vectors in solution
resize!(integrator.sol.u, 1)
resize!(integrator.sol.t, 1)
resize!(integrator.sol.k, 1)
iscomposite(integrator.alg) && resize!(integrator.sol.alg_choice, 1)
# save initial values
copyat_or_push!(integrator.sol.t, 1, integrator.t)
copyat_or_push!(integrator.sol.u, 1, integrator.u)
# reset iteration counter
integrator.saveiter = 1
integrator.saveiter_dense = 1
end
nothing
end
"""
reinit!(integrator::DDEIntegrator[, u0 = integrator.sol.prob.u0;
t0 = integrator.sol.prob.tspan[1],
tf = integrator.sol.prob.tspan[2],
erase_sol = true,
kwargs...])
Reinitialize `integrator` with (optionally) different initial state `u0`, different
integration interval from `t0` to `tf`, and erased solution if `erase_sol = true`.
"""
function DiffEqBase.reinit!(integrator::DDEIntegrator, u0 = integrator.sol.prob.u0;
t0 = integrator.sol.prob.tspan[1],
tf = integrator.sol.prob.tspan[end],
erase_sol = true,
tstops = integrator.opts.tstops_cache,
saveat = integrator.opts.saveat_cache,
d_discontinuities = integrator.opts.d_discontinuities_cache,
order_discontinuity_t0 = t0 == integrator.sol.prob.tspan[1] &&
u0 == integrator.sol.prob.u0 ?
integrator.order_discontinuity_t0 : 0,
reset_dt = iszero(integrator.dtcache) &&
integrator.opts.adaptive,
reinit_callbacks = true, initialize_save = true,
reinit_cache = true)
# reinit history
reinit!(integrator.integrator, u0; t0 = t0, tf = tf, erase_sol = true)
# reinit initial values of the integrator
if isinplace(integrator.sol.prob)
recursivecopy!(integrator.u, u0)
recursivecopy!(integrator.uprev, integrator.u)
else
integrator.u = u0
integrator.uprev = integrator.u
end
if OrdinaryDiffEq.alg_extrapolates(integrator.alg)
if isinplace(integrator.sol.prob)
recursivecopy!(integrator.uprev2, integrator.uprev)
else
integrator.uprev2 = integrator.uprev
end
end
integrator.t = t0
integrator.tprev = t0
# reinit time stops, time points at which solution is saved, and discontinuities
tType = typeof(integrator.t)
tspan = (tType(t0), tType(tf))
integrator.opts.tstops = OrdinaryDiffEq.initialize_tstops(tType, tstops,
d_discontinuities, tspan)
integrator.opts.saveat = OrdinaryDiffEq.initialize_saveat(tType, saveat, tspan)
integrator.opts.d_discontinuities = OrdinaryDiffEq.initialize_d_discontinuities(
Discontinuity{
tType,
Int
},
d_discontinuities,
tspan)
# update order of initial discontinuity and propagated discontinuities
integrator.order_discontinuity_t0 = order_discontinuity_t0
maximum_order = OrdinaryDiffEq.alg_maximum_order(integrator.alg)
tstops_propagated, d_discontinuities_propagated = initialize_tstops_d_discontinuities_propagated(
tType,
tstops,
d_discontinuities,
tspan,
order_discontinuity_t0,
maximum_order,
integrator.sol.prob.constant_lags,
integrator.sol.prob.neutral)
integrator.tstops_propagated = tstops_propagated
integrator.d_discontinuities_propagated = d_discontinuities_propagated
# erase solution
if erase_sol
# resize vectors in solution
resize_start = integrator.opts.save_start ? 1 : 0
resize!(integrator.sol.u, resize_start)
resize!(integrator.sol.t, resize_start)
resize!(integrator.sol.k, resize_start)
iscomposite(integrator.alg) && resize!(integrator.sol.alg_choice, resize_start)
integrator.sol.u_analytic !== nothing && resize!(integrator.sol.u_analytic, 0)
# save initial values
if integrator.opts.save_start
copyat_or_push!(integrator.sol.t, 1, integrator.t)
if integrator.opts.save_idxs === nothing
copyat_or_push!(integrator.sol.u, 1, integrator.u)
else
u_initial = integrator.u[integrator.opts.save_idxs]
copyat_or_push!(integrator.sol.u, 1, u_initial, Val{false})
end
end
# reset iteration counter
integrator.saveiter = resize_start
if integrator.opts.dense
integrator.saveiter_dense = resize_start
end
# erase array of tracked discontinuities
if order_discontinuity_t0 ≤ OrdinaryDiffEq.alg_maximum_order(integrator.alg)
resize!(integrator.tracked_discontinuities, 1)
integrator.tracked_discontinuities[1] = Discontinuity(
integrator.tdir *
integrator.t,
order_discontinuity_t0)
else
resize!(integrator.tracked_discontinuities, 0)
end
# reset history counters
integrator.prev_idx = 1
integrator.prev2_idx = 1
end
# reset integration counters
integrator.iter = 0
integrator.success_iter = 0
# full re-initialize the PI in timestepping
integrator.qold = integrator.opts.qoldinit
integrator.q11 = one(integrator.t)
integrator.erracc = one(integrator.erracc)
integrator.dtacc = one(integrator.dtacc)
integrator.u_modified = false
if reset_dt
DiffEqBase.auto_dt_reset!(integrator)
end
if reinit_callbacks
OrdinaryDiffEq.initialize_callbacks!(integrator, initialize_save)
end
if reinit_cache
OrdinaryDiffEq.initialize!(integrator)
end
nothing
end
function DiffEqBase.auto_dt_reset!(integrator::DDEIntegrator)
@unpack f, u, t, tdir, opts, sol, stats = integrator
@unpack prob = sol
@unpack abstol, reltol, internalnorm = opts
# determine maximal time step
if has_constant_lags(prob)
dtmax = tdir * min(abs(opts.dtmax), minimum(abs, prob.constant_lags))
else
dtmax = opts.dtmax
end
# determine initial time step
ode_prob = ODEProblem(f, prob.u0, prob.tspan, prob.p)
integrator.dt = OrdinaryDiffEq.ode_determine_initdt(u, t, tdir, dtmax, opts.abstol,
opts.reltol, opts.internalnorm,
ode_prob, integrator)
# update statistics
stats.nf += 2
nothing
end
function DiffEqBase.add_tstop!(integrator::DDEIntegrator, t)
integrator.tdir * (t - integrator.t) < 0 &&
error("Tried to add a tstop that is behind the current time. This is strictly forbidden")
push!(integrator.opts.tstops, integrator.tdir * t)
end
function DiffEqBase.add_saveat!(integrator::DDEIntegrator, t)
integrator.tdir * (t - integrator.t) < 0 &&
error("Tried to add a saveat that is behind the current time. This is strictly forbidden")
push!(integrator.opts.saveat, integrator.tdir * t)
end
@inline function DiffEqBase.get_du(integrator::DDEIntegrator)
integrator.fsallast
end
@inline function DiffEqBase.get_du!(out, integrator::DDEIntegrator)
out .= integrator.fsallast
end
DiffEqBase.has_stats(::DDEIntegrator) = true
# https://github.com/SciML/OrdinaryDiffEq.jl/pull/1753
# Backwards compatability
@static if isdefined(OrdinaryDiffEq, :DEPRECATED_ADDSTEPS)
const _ode_addsteps! = OrdinaryDiffEq._ode_addsteps!
const ode_addsteps! = OrdinaryDiffEq.ode_addsteps!
else
const _ode_addsteps! = DiffEqBase.addsteps!
const ode_addsteps! = OrdinaryDiffEq._ode_addsteps!
end
function DiffEqBase.addsteps!(integrator::DDEIntegrator, args...)
ode_addsteps!(integrator, args...)
end
function DiffEqBase.change_t_via_interpolation!(integrator::DDEIntegrator,
t,
modify_save_endpoint::Type{Val{T}} = Val{
false
}) where {
T
}
OrdinaryDiffEq._change_t_via_interpolation!(integrator, t, modify_save_endpoint)
end
# update integrator when u is modified by callbacks
function OrdinaryDiffEq.handle_callback_modifiers!(integrator::DDEIntegrator)
integrator.reeval_fsal = true # recalculate fsalfirst after applying step
# update heap of discontinuities
# discontinuity is assumed to be of order 0, i.e. solution x is discontinuous
push!(integrator.opts.d_discontinuities,
Discontinuity(integrator.tdir * integrator.t, 0))
end
# recalculate interpolation data and update the ODE integrator
function DiffEqBase.reeval_internals_due_to_modification!(integrator::DDEIntegrator,
x::Type{Val{not_initialization}} = Val{
true
}) where {
not_initialization
}
ode_integrator = integrator.integrator
if not_initialization
# update interpolation data of the integrator using the old dense history
# of the ODE integrator
resize!(integrator.k, integrator.kshortsize)
ode_addsteps!(integrator, integrator.f, true, true, true)
# copy interpolation data to the ODE integrator
recursivecopy!(ode_integrator.k, integrator.k)
end
# adjust current interval of the ODE integrator
ode_integrator.t = integrator.t
ode_integrator.dt = integrator.dt
if isinplace(integrator.sol.prob)
recursivecopy!(ode_integrator.u, integrator.u)
else
ode_integrator.u = integrator.u
end
integrator.u_modified = false
end
# perform one step
function DiffEqBase.step!(integrator::DDEIntegrator)
@inbounds begin
if integrator.opts.advance_to_tstop
while integrator.tdir * integrator.t < first(integrator.opts.tstops)
OrdinaryDiffEq.loopheader!(integrator)
DiffEqBase.check_error!(integrator) == ReturnCode.Success || return
OrdinaryDiffEq.perform_step!(integrator)
OrdinaryDiffEq.loopfooter!(integrator)
end
else
OrdinaryDiffEq.loopheader!(integrator)
DiffEqBase.check_error!(integrator) == ReturnCode.Success || return
OrdinaryDiffEq.perform_step!(integrator)
OrdinaryDiffEq.loopfooter!(integrator)
while !integrator.accept_step
OrdinaryDiffEq.loopheader!(integrator)
OrdinaryDiffEq.perform_step!(integrator)
OrdinaryDiffEq.loopfooter!(integrator)
end
end
OrdinaryDiffEq.handle_tstop!(integrator)
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 8471 | mutable struct HistoryODEIntegrator{
algType, IIP, uType, tType, tdirType, ksEltype, SolType,
CacheType, DV} <:
AbstractODEIntegrator{algType, IIP, uType, tType}
sol::SolType
u::uType
k::ksEltype
t::tType
dt::tType
uprev::uType
tprev::tType
alg::algType
dtcache::tType
tdir::tdirType
saveiter::Int
saveiter_dense::Int
cache::CacheType
differential_vars::DV
end
function (integrator::HistoryODEIntegrator)(t, deriv::Type = Val{0}; idxs = nothing)
OrdinaryDiffEq.current_interpolant(t, integrator, idxs, deriv)
end
function (integrator::HistoryODEIntegrator)(val::AbstractArray,
t::Union{Number, AbstractArray},
deriv::Type = Val{0}; idxs = nothing)
OrdinaryDiffEq.current_interpolant!(val, t, integrator, idxs, deriv)
end
@static if isdefined(OrdinaryDiffEq, :get_fsalfirstlast)
mutable struct DDEIntegrator{algType, IIP, uType, tType, P, eigenType, tTypeNoUnits,
tdirType,
ksEltype, SolType, F, CacheType, IType, FP, O, dAbsType,
dRelType, H,
tstopsType, discType, FSALType, EventErrorType,
CallbackCacheType, DV} <:
AbstractDDEIntegrator{algType, IIP, uType, tType}
sol::SolType
u::uType
k::ksEltype
t::tType
dt::tType
f::F
p::P
uprev::uType
uprev2::uType
tprev::tType
prev_idx::Int
prev2_idx::Int
fpsolver::FP
order_discontinuity_t0::Int
"Discontinuities tracked by callback."
tracked_discontinuities::Vector{Discontinuity{tType, Int}}
discontinuity_interp_points::Int
discontinuity_abstol::dAbsType
discontinuity_reltol::dRelType
"Future time stops for propagated discontinuities."
tstops_propagated::tstopsType
"Future propagated discontinuities."
d_discontinuities_propagated::discType
alg::algType
dtcache::tType
dtchangeable::Bool
dtpropose::tType
tdir::tdirType
eigen_est::eigenType
EEst::tTypeNoUnits
qold::tTypeNoUnits
q11::tTypeNoUnits
erracc::tTypeNoUnits
dtacc::tType
success_iter::Int
iter::Int
saveiter::Int
saveiter_dense::Int
cache::CacheType
callback_cache::CallbackCacheType
kshortsize::Int
force_stepfail::Bool
last_stepfail::Bool
just_hit_tstop::Bool
do_error_check::Bool
event_last_time::Int
vector_event_last_time::Int
last_event_error::EventErrorType
accept_step::Bool
isout::Bool
reeval_fsal::Bool
u_modified::Bool
isdae::Bool
opts::O
stats::SciMLBase.DEStats
history::H
differential_vars::DV
integrator::IType
fsalfirst::FSALType
fsallast::FSALType
end
else
mutable struct DDEIntegrator{algType, IIP, uType, tType, P, eigenType, tTypeNoUnits,
tdirType,
ksEltype, SolType, F, CacheType, IType, FP, O, dAbsType,
dRelType, H,
tstopsType, discType, FSALType, EventErrorType,
CallbackCacheType, DV} <:
AbstractDDEIntegrator{algType, IIP, uType, tType}
sol::SolType
u::uType
k::ksEltype
t::tType
dt::tType
f::F
p::P
uprev::uType
uprev2::uType
tprev::tType
prev_idx::Int
prev2_idx::Int
fpsolver::FP
order_discontinuity_t0::Int
"Discontinuities tracked by callback."
tracked_discontinuities::Vector{Discontinuity{tType, Int}}
discontinuity_interp_points::Int
discontinuity_abstol::dAbsType
discontinuity_reltol::dRelType
"Future time stops for propagated discontinuities."
tstops_propagated::tstopsType
"Future propagated discontinuities."
d_discontinuities_propagated::discType
alg::algType
dtcache::tType
dtchangeable::Bool
dtpropose::tType
tdir::tdirType
eigen_est::eigenType
EEst::tTypeNoUnits
qold::tTypeNoUnits
q11::tTypeNoUnits
erracc::tTypeNoUnits
dtacc::tType
success_iter::Int
iter::Int
saveiter::Int
saveiter_dense::Int
cache::CacheType
callback_cache::CallbackCacheType
kshortsize::Int
force_stepfail::Bool
last_stepfail::Bool
just_hit_tstop::Bool
do_error_check::Bool
event_last_time::Int
vector_event_last_time::Int
last_event_error::EventErrorType
accept_step::Bool
isout::Bool
reeval_fsal::Bool
u_modified::Bool
isdae::Bool
opts::O
stats::SciMLBase.DEStats
history::H
differential_vars::DV
integrator::IType
fsalfirst::FSALType
fsallast::FSALType
# incomplete initialization without fsalfirst and fsallast
function DDEIntegrator{algType, IIP, uType, tType, P, eigenType, tTypeNoUnits,
tdirType, ksEltype, SolType, F, CacheType, IType, FP,
O, dAbsType, dRelType, H, tstopsType, discType,
FSALType, EventErrorType, CallbackCacheType, DV}(sol, u, k, t, dt, f,
p, uprev, uprev2,
tprev, prev_idx,
prev2_idx,
fpsolver,
order_discontinuity_t0,
tracked_discontinuities,
discontinuity_interp_points,
discontinuity_abstol,
discontinuity_reltol,
tstops_propagated,
d_discontinuities_propagated,
alg, dtcache,
dtchangeable,
dtpropose, tdir,
eigen_est, EEst,
qold,
q11, erracc, dtacc,
success_iter, iter,
saveiter,
saveiter_dense,
cache,
callback_cache,
kshortsize,
force_stepfail,
last_stepfail,
just_hit_tstop,
do_error_check,
event_last_time,
vector_event_last_time,
last_event_error,
accept_step, isout,
reeval_fsal,
u_modified, isdae,
opts, stats,
history,
differential_vars,
integrator) where
{
algType, IIP, uType, tType, P, eigenType, tTypeNoUnits, tdirType, ksEltype,
SolType, F,
CacheType, IType, FP, O, dAbsType, dRelType, H, tstopsType, discType,
FSALType, EventErrorType, CallbackCacheType, DV}
new{algType, IIP, uType, tType, P, eigenType, tTypeNoUnits, tdirType, ksEltype,
SolType, F,
CacheType, IType, FP, O, dAbsType, dRelType, H, tstopsType, discType, FSALType,
EventErrorType, CallbackCacheType, DV}(
sol, u, k, t, dt, f, p, uprev, uprev2, tprev,
prev_idx, prev2_idx, fpsolver,
order_discontinuity_t0,
tracked_discontinuities,
discontinuity_interp_points,
discontinuity_abstol, discontinuity_reltol,
tstops_propagated,
d_discontinuities_propagated, alg, dtcache,
dtchangeable, dtpropose, tdir,
eigen_est, EEst, qold, q11, erracc, dtacc,
success_iter, iter, saveiter, saveiter_dense,
cache, callback_cache, kshortsize,
force_stepfail, last_stepfail,
just_hit_tstop,
do_error_check, event_last_time,
vector_event_last_time,
last_event_error, accept_step, isout,
reeval_fsal, u_modified, isdae, opts,
stats, history, differential_vars, integrator)
end
end
end
function (integrator::DDEIntegrator)(t, deriv::Type = Val{0}; idxs = nothing)
OrdinaryDiffEq.current_interpolant(t, integrator, idxs, deriv)
end
function (integrator::DDEIntegrator)(val::AbstractArray, t::Union{Number, AbstractArray},
deriv::Type = Val{0}; idxs = nothing)
OrdinaryDiffEq.current_interpolant!(val, t, integrator, idxs, deriv)
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 10312 | """
advance_or_update_ode_integrator!(integrator::DDEIntegrator[, always_calc_begin = false])
Advance or update the ODE integrator of `integrator` to the next time interval by updating its
values and interpolation data with the current values and a full set of interpolation data of
`integrator`.
"""
function advance_or_update_ode_integrator!(integrator, always_calc_begin = false)
ode_integrator = integrator.integrator
if ode_integrator.t != integrator.t + integrator.dt
advance_ode_integrator!(integrator, always_calc_begin)
else
update_ode_integrator!(integrator, always_calc_begin)
end
end
"""
advance_ode_integrator!(integrator::DDEIntegrator[, always_calc_begin = false])
Advance the ODE integrator of `integrator` to the next time interval by updating its values
and interpolation data with the current values and a full set of interpolation data of
`integrator`.
"""
function advance_ode_integrator!(integrator::DDEIntegrator, always_calc_begin = false)
@unpack f, u, t, p, k, dt, uprev, alg, cache = integrator
ode_integrator = integrator.integrator
# algorithm only works if current time of DDE integrator equals final time point
# of solution
t != ode_integrator.sol.t[end] && error("cannot advance ODE integrator")
# complete interpolation data of DDE integrator for time interval [t, t+dt]
# and copy it to ODE integrator
# has to be done before updates to ODE integrator, otherwise history function
# is incorrect
if iscomposite(alg)
_ode_addsteps!(k, t, uprev, u, dt, f, p, cache.caches[cache.current],
always_calc_begin, true, true)
else
_ode_addsteps!(k, t, uprev, u, dt, f, p, cache, always_calc_begin,
true, true)
end
@inbounds for i in 1:length(k)
copyat_or_push!(ode_integrator.k, i, k[i])
end
# move ODE integrator to interval [t, t+dt]
ode_integrator.t = t + dt
ode_integrator.tprev = t
ode_integrator.dt = dt
if iscomposite(alg)
ode_integrator.cache.current = cache.current
end
if isinplace(integrator.sol.prob)
recursivecopy!(ode_integrator.u, u)
else
ode_integrator.u = u
end
# u(t) is not modified hence we do not have to copy it
ode_integrator.uprev = ode_integrator.sol.u[end]
# update prev_idx to index of t and u(t) in solution
integrator.prev_idx = length(ode_integrator.sol.t)
nothing
end
"""
update_ode_integrator!(integrator::DDEIntegrator[, always_calc_begin = false])
Update the ODE integrator of `integrator` by updating its values and interpolation data
with the current values and a full set of interpolation data of `integrator`.
"""
function update_ode_integrator!(integrator::DDEIntegrator, always_calc_begin = false)
@unpack f, u, t, p, k, dt, uprev, alg, cache = integrator
ode_integrator = integrator.integrator
# algorithm only works if the ODE integrator is already moved to the current integration
# interval
ode_integrator.t != t + dt && error("cannot update ODE integrator")
if iscomposite(alg)
_ode_addsteps!(k, t, uprev, u, dt, f, p, cache.caches[cache.current],
always_calc_begin, true, true)
else
_ode_addsteps!(k, t, uprev, u, dt, f, p, cache,
always_calc_begin, true, true)
end
@inbounds for i in 1:length(k)
copyat_or_push!(ode_integrator.k, i, k[i])
end
# update state of the dummy ODE solver
if isinplace(integrator.sol.prob)
recursivecopy!(ode_integrator.u, u)
else
ode_integrator.u = integrator.u
end
nothing
end
"""
move_back_ode_integrator!(integrator::DDEIntegrator)
Move the ODE integrator of `integrator` one integration step back by reverting its values
and interpolation data to the values saved in the dense history.
"""
function move_back_ode_integrator!(integrator::DDEIntegrator)
ode_integrator = integrator.integrator
@unpack sol = ode_integrator
# set values of the ODE integrator back to the values in the solution
if isinplace(sol.prob)
recursivecopy!(ode_integrator.u, sol.u[end])
else
ode_integrator.u = sol.u[end]
end
ode_integrator.t = sol.t[end]
ode_integrator.tprev = sol.t[integrator.prev2_idx]
# u(tprev) is not modified hence we do not have to copy it
ode_integrator.uprev = sol.u[integrator.prev2_idx]
# revert to the previous time step
ode_integrator.dt = ode_integrator.dtcache
# we do not have to reset the interpolation data in the initial time step since always a
# constant extrapolation is used (and interpolation data of solution at initial
# time point is not complete!)
if length(sol.t) > 1
recursivecopy!(ode_integrator.k, sol.k[end])
end
nothing
end
#=
Dealing with discontinuities
If we hit a discontinuity (this is checked in `apply_step!`), then we remove the
discontinuity, additional discontinuities at the current time point (if present), and
maybe also discontinuities and time stops coming shortly after the current time point
in `handle_discontinuities!`. The order of the discontinuity at the current time point is
defined as the lowest order of all these discontinuities.
If the problem is not neutral, we will only add additional discontinuities if
this order is less or equal to the order of the algorithm in
`add_next_discontinuities!`. If we add discontinuities, we add discontinuities
of the next order caused by constant lags (these we can calculate explicitly and
just add them to `d_discontinuities` and `tstops`) and we add the current
discontinuity to `tracked_discontinuities` which is the array of old
discontinuities that are checked by a `DiscontinuityCallback` (if existent).
=#
# handle discontinuities at the current time point of the `integrator`
function OrdinaryDiffEq.handle_discontinuities!(integrator::DDEIntegrator)
# remove all discontinuities at current time point and calculate minimal order
# of these discontinuities
d = OrdinaryDiffEq.pop_discontinuity!(integrator)
order = d.order
tdir_t = integrator.tdir * integrator.t
while OrdinaryDiffEq.has_discontinuity(integrator) &&
OrdinaryDiffEq.first_discontinuity(integrator) == tdir_t
d2 = OrdinaryDiffEq.pop_discontinuity!(integrator)
order = min(order, d2.order)
end
# remove all discontinuities close to the current time point as well and
# calculate minimal order of these discontinuities
# integrator.EEst has unitless type of integrator.t
if integrator.EEst isa AbstractFloat
maxΔt = 10eps(integrator.t)
while OrdinaryDiffEq.has_discontinuity(integrator) &&
abs(OrdinaryDiffEq.first_discontinuity(integrator).t - tdir_t) < maxΔt
d2 = OrdinaryDiffEq.pop_discontinuity!(integrator)
order = min(order, d2.order)
end
# also remove all corresponding time stops
while OrdinaryDiffEq.has_tstop(integrator) &&
abs(OrdinaryDiffEq.first_tstop(integrator) - tdir_t) < maxΔt
OrdinaryDiffEq.pop_tstop!(integrator)
end
end
# add discontinuities of next order to integrator
add_next_discontinuities!(integrator, order)
nothing
end
"""
add_next_discontinuities!(integrator::DDEIntegrator, order[, t=integrator.t])
Add discontinuities of next order that are propagated from discontinuity of
order `order` at time `t` in `integrator`, but only if `order` is less or equal
than the order of the applied method or the problem is neutral.
Discontinuities caused by constant delays are immediately calculated, and
discontinuities caused by dependent delays are tracked by a callback.
"""
function add_next_discontinuities!(integrator, order, t = integrator.t)
neutral = integrator.sol.prob.neutral
next_order = neutral ? order : order + 1
# only track discontinuities up to order of the applied method
alg_maximum_order = OrdinaryDiffEq.alg_maximum_order(integrator.alg)
next_order <= alg_maximum_order + 1 || return
# discontinuities caused by constant lags
if has_constant_lags(integrator)
constant_lags = integrator.sol.prob.constant_lags
maxlag = integrator.tdir * (integrator.sol.prob.tspan[end] - t)
for lag in constant_lags
if integrator.tdir * lag < maxlag
# calculate discontinuity and add it to heap of discontinuities and time stops
d = Discontinuity(integrator.tdir * (t + lag), next_order)
push!(integrator.d_discontinuities_propagated, d)
push!(integrator.tstops_propagated, d.t)
end
end
end
# track propagated discontinuities with callback
push!(integrator.tracked_discontinuities, Discontinuity(integrator.tdir * t, order))
nothing
end
# Interface for accessing and removing next time stops and discontinuities
function OrdinaryDiffEq.has_tstop(integrator::DDEIntegrator)
return _has(integrator.opts.tstops, integrator.tstops_propagated)
end
function OrdinaryDiffEq.first_tstop(integrator::DDEIntegrator)
return _first(integrator.opts.tstops, integrator.tstops_propagated)
end
function OrdinaryDiffEq.pop_tstop!(integrator::DDEIntegrator)
return _pop!(integrator.opts.tstops, integrator.tstops_propagated)
end
function OrdinaryDiffEq.has_discontinuity(integrator::DDEIntegrator)
return _has(integrator.opts.d_discontinuities,
integrator.d_discontinuities_propagated)
end
function OrdinaryDiffEq.first_discontinuity(integrator::DDEIntegrator)
return _first(integrator.opts.d_discontinuities,
integrator.d_discontinuities_propagated)
end
function OrdinaryDiffEq.pop_discontinuity!(integrator::DDEIntegrator)
return _pop!(integrator.opts.d_discontinuities,
integrator.d_discontinuities_propagated)
end
_has(x, y) = !isempty(x) || !isempty(y)
function _first(x, y)
if isempty(x)
return first(y)
elseif isempty(y)
return first(x)
else
return min(first(x), first(y))
end
end
function _pop!(x, y)
if isempty(x)
pop!(y)
elseif isempty(y)
pop!(x)
else
if first(x) < first(y)
pop!(x)
else
pop!(y)
end
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 3026 | using SafeTestsets
const GROUP = get(ENV, "GROUP", "All")
if GROUP == "All" || GROUP == "Interface"
@time @safetestset "AD Tests" begin
include("interface/ad.jl")
end
@time @safetestset "Backwards Tests" begin
include("interface/backwards.jl")
end
@time @safetestset "Composite Solution Tests" begin
include("interface/composite_solution.jl")
end
@time @safetestset "Constrained Time Steps Tests" begin
include("interface/constrained.jl")
end
@time @safetestset "Dependent Delay Tests" begin
include("interface/dependent_delays.jl")
end
@time @safetestset "Discontinuity Tests" begin
include("interface/discontinuities.jl")
end
@time @safetestset "Export Tests" begin
include("interface/export.jl")
end
@time @safetestset "Fixed-point Iteration Tests" begin
include("interface/fpsolve.jl")
end
@time @safetestset "History Function Tests" begin
include("interface/history_function.jl")
end
@time @safetestset "Jacobian Tests" begin
include("interface/jacobian.jl")
end
@time @safetestset "Mass matrix Tests" begin
include("interface/mass_matrix.jl")
end
@time @safetestset "Parameterized Function Tests" begin
include("interface/parameters.jl")
end
@time @safetestset "saveat Tests" begin
include("interface/saveat.jl")
end
@time @safetestset "save_idxs Tests" begin
include("interface/save_idxs.jl")
end
@time @safetestset "Unconstrained Time Steps Tests" begin
include("interface/unconstrained.jl")
end
@time @safetestset "Units Tests" begin
include("interface/units.jl")
end
end
if GROUP == "All" || GROUP == "Integrators"
@time @safetestset "Cache Tests" begin
include("integrators/cache.jl")
end
@time @safetestset "Event Tests" begin
include("integrators/events.jl")
end
@time @safetestset "Iterator Tests" begin
include("integrators/iterator.jl")
end
@time @safetestset "Reinitialization Tests" begin
include("integrators/reinit.jl")
end
@time @safetestset "Residual Control Tests" begin
include("integrators/residual_control.jl")
end
@time @safetestset "Return Code Tests" begin
include("integrators/retcode.jl")
end
@time @safetestset "Rosenbrock Tests" begin
include("integrators/rosenbrock.jl")
end
@time @safetestset "SDIRK Tests" begin
include("integrators/sdirk.jl")
end
@time @safetestset "Unique Timepoints Tests" begin
include("integrators/unique_times.jl")
end
@time @safetestset "Verner Tests" begin
include("integrators/verner.jl")
end
end
if GROUP == "All" || GROUP == "Regression"
@time @safetestset "Inference Tests" begin
include("regression/inference.jl")
end
@time @safetestset "Waltman Problem Tests" begin
include("regression/waltman.jl")
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1525 | using DelayDiffEq, Test
using Random
Random.seed!(213)
const CACHE_TEST_ALGS = [Vern7(), Euler(), Midpoint(), RK4(), SSPRK22(), SSPRK33(),
ORK256(), CarpenterKennedy2N54(), SHLDDRK64(), DGLDDRK73_C(),
CFRLDDRK64(), TSLDDRK74(),
CKLLSRK43_2(),
ParsaniKetchesonDeconinck3S32(),
BS3(), BS5(), DP5(), DP8(), Feagin10(), Feagin12(), Feagin14(), TanYam7(),
Tsit5(), TsitPap8(), Vern6(), Vern7(), Vern8(), Vern9(), OwrenZen3(), OwrenZen4(),
OwrenZen5()]
function f(du, u, h, p, t)
for i in 1:length(u)
du[i] = (0.3 / length(u)) * u[i]
end
nothing
end
condition(u, t, integrator) = 1 - maximum(u)
function affect!(integrator)
u = integrator.u
resize!(integrator, length(u) + 1)
maxidx = findmax(u)[2]
Θ = rand() / 5 + 0.25
u[maxidx] = Θ
u[end] = 1 - Θ
nothing
end
const prob = DDEProblem(f, [0.2], nothing, (0.0, 10.0);
callback = ContinuousCallback(condition, affect!))
println("Check for stochastic errors")
for i in 1:10
@test_nowarn solve(prob, MethodOfSteps(Tsit5()); dt = 0.5)
end
println("Check some other integrators")
println("Rosenbrock23")
@test_nowarn solve(prob, MethodOfSteps(Rosenbrock23(chunk_size = 1)); dt = 0.5)
for alg in CACHE_TEST_ALGS
println(nameof(typeof(alg)))
@test_nowarn solve(prob, MethodOfSteps(alg); dt = 0.5)
end
println("Rodas4")
@test_nowarn solve(prob, MethodOfSteps(Rodas4(chunk_size = 1)); dt = 0.5)
println("Rodas5")
@test_nowarn solve(prob, MethodOfSteps(Rodas5(chunk_size = 1)); dt = 0.5)
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 2208 | using DelayDiffEq, DDEProblemLibrary, DiffEqDevTools, DiffEqCallbacks
using Test
const prob = prob_dde_constant_1delay_scalar
const alg = MethodOfSteps(Tsit5(); constrained = false)
# continuous callback
@testset "continuous" begin
cb = ContinuousCallback((u, t, integrator) -> t - 2.60, # Event when event_f(t,u,k) == 0
integrator -> (integrator.u = -integrator.u))
sol1 = solve(prob, alg, callback = cb)
ts = findall(x -> x ≈ 2.6, sol1.t)
@test length(ts) == 2
@test sol1.u[ts[1]] == -sol1.u[ts[2]]
@test sol1(prevfloat(2.6);
continuity = :right)≈-sol1(prevfloat(2.6); continuity = :left) atol=1e-5
# fails on 32bit?!
# see https://github.com/SciML/DelayDiffEq.jl/pull/180
if Int === Int64
sol2 = solve(prob, alg, callback = cb, dtmax = 0.01)
ts = findall(x -> x ≈ 2.6, sol2.t)
@test length(ts) == 2
@test sol2.u[ts[1]] == -sol2.u[ts[2]]
@test sol2(prevfloat(2.6); continuity = :right) ≈
-sol2(prevfloat(2.6); continuity = :left)
sol3 = appxtrue(sol1, sol2)
@test sol3.errors[:L2] < 1.5e-2
@test sol3.errors[:L∞] < 3.5e-2
end
end
# discrete callback
@testset "discrete" begin
# Automatic absolute tolerances
cb = AutoAbstol()
sol1 = solve(prob, alg, callback = cb)
sol2 = solve(prob, alg, callback = cb, dtmax = 0.01)
sol3 = appxtrue(sol1, sol2)
@test sol3.errors[:L2] < 1.4e-3
@test sol3.errors[:L∞] < 4.1e-3
# Terminate early
cb = DiscreteCallback((u, t, integrator) -> t == 4, terminate!)
sol = @test_logs solve(prob, alg; callback = cb, tstops = [4.0])
@test sol.t[end] == 4
end
@testset "save discontinuity" begin
f(du, u, h, p, t) = (du .= 0)
prob = DDEProblem(f, [0.0], nothing, (0.0, 1.0))
condition(u, t, integrator) = t == 0.5
global iter
function affect!(integrator)
integrator.u[1] += 100
global iter = integrator.iter
end
cb = DiscreteCallback(condition, affect!)
sol = solve(prob, MethodOfSteps(Tsit5()), callback = cb, tstops = [0.5])
@test sol.t[iter + 1] == sol.t[iter + 2]
@test sol.u[iter + 1] == [0.0]
@test sol.u[iter + 2] != [0.0]
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 2356 | using DelayDiffEq, DDEProblemLibrary
using Test
const prob = prob_dde_constant_1delay_scalar
@testset "Basic iterator" begin
# compute the solution of the DDE
sol = solve(prob, MethodOfSteps(BS3());
dt = 1 // 2^(4), tstops = [1.5], saveat = 0.01, save_everystep = true)
# initialize integrator
integrator = init(prob, MethodOfSteps(BS3());
dt = 1 // 2^(4), tstops = [1.5], saveat = 0.01, save_everystep = true)
# perform one step
step!(integrator)
@test integrator.iter == 1
# move to next grid point
integrator.opts.advance_to_tstop = true
step!(integrator)
@test integrator.t == 1.5
# solve the DDE
solve!(integrator)
@test integrator.t == 10
@test integrator.sol(9) ≈ sol(9)
# move to next grid point
push!(integrator.opts.tstops, 15)
step!(integrator)
@test integrator.t == 15
# move just one step
integrator.opts.advance_to_tstop = false
step!(integrator)
@test integrator.t > 15
end
@testset "Advanced iterators" begin
# move to grid point in one step
integrator1 = init(prob, MethodOfSteps(Tsit5());
dt = 1 // 2^(4), tstops = [0.5], advance_to_tstop = true)
for (u, t) in tuples(integrator1)
@test 0.5 ≤ t ≤ 10
end
# move to grid point in one step and stop there
integrator2 = init(prob, MethodOfSteps(Tsit5());
dt = 1 // 2^(4), tstops = [0.5], advance_to_tstop = true,
stop_at_next_tstop = true)
for (u, t) in tuples(integrator2)
@test t == 0.5
end
integrator2([10; 20])
# step and show intervals
integrator3 = init(prob, MethodOfSteps(Tsit5()); dt = 1 // 2^(4), tstops = [0.5])
for (uprev, tprev, u, t) in intervals(integrator3)
@show tprev, t
end
integrator3([10; 20])
# iterator for chosen time points
integrator4 = init(prob, MethodOfSteps(Tsit5()); dt = 1 // 2^(4))
ts = 1:10
us = Float64[]
for (u, t) in TimeChoiceIterator(integrator4, ts)
push!(us, u)
end
@test us ≈ integrator4.sol(ts)
end
@testset "iter" begin
integrator = init(prob, MethodOfSteps(RK4()); dt = 1 // 2^(9), adaptive = false)
for i in Base.Iterators.take(integrator, 12)
end
@test integrator.iter == 12
for i in Base.Iterators.take(integrator, 12)
end
@test integrator.iter == 24
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1583 | using DelayDiffEq, DDEProblemLibrary, RecursiveArrayTools
using Test
const prob_ip = prob_dde_constant_1delay_ip
const prob_scalar = prob_dde_constant_1delay_scalar
const alg = MethodOfSteps(BS3(); constrained = false)
@testset for inplace in (true, false)
prob = inplace ? prob_ip : prob_scalar
@testset "integrator" begin
integrator = init(prob, alg, dt = 0.01)
solve!(integrator)
u = recursivecopy(integrator.sol.u)
t = copy(integrator.sol.t)
reinit!(integrator)
integrator.dt = 0.01
solve!(integrator)
@test u == integrator.sol.u
@test t == integrator.sol.t
end
@testset "solution" begin
integrator = init(prob, alg, dt = 0.01, tstops = [0.5], saveat = [0.33])
sol = solve!(integrator)
u = recursivecopy(sol.u)
t = copy(sol.t)
reinit!(integrator)
integrator.dt = 0.01
sol = solve!(integrator)
@test u == sol.u
@test t == sol.t
end
# https://github.com/SciML/OrdinaryDiffEq.jl/issues/1394
@testset "saveiter_dense" begin
integrator = init(prob, alg)
solve!(integrator)
# ensure that the counters were updated
for i in (integrator, integrator.integrator)
@test i.saveiter > 1
@test i.saveiter_dense > 1
end
reinit!(integrator)
# check that the counters are reset
for i in (integrator, integrator.integrator)
@test i.saveiter == 1
@test i.saveiter_dense == 1
end
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1607 | using DelayDiffEq, DDEProblemLibrary
using Test
const alg = MethodOfSteps(RK4(); constrained = false)
const prob = prob_dde_constant_1delay_scalar
# reference solution with delays specified
@testset "reference" begin
sol = solve(prob, alg)
@test sol.errors[:l∞] < 5.6e-5
@test sol.errors[:final] < 1.8e-6
@test sol.errors[:l2] < 2.0e-5
end
# problem without delays specified
const prob_wo = remake(prob; constant_lags = nothing)
# solutions with residual control
@testset "residual control" begin
sol = solve(prob_wo, alg)
@test sol.errors[:l∞] < 1.4e-4
@test sol.errors[:final] < 3.5e-6
@test sol.errors[:l2] < 6.5e-5
sol = solve(prob_wo, alg; abstol = 1e-9, reltol = 1e-6)
@test sol.errors[:l∞] < 6.0e-8
@test sol.errors[:final] < 3.4e-9
@test sol.errors[:l2] < 2.2e-8
sol = solve(prob_wo, alg; abstol = 1e-13, reltol = 1e-13)
# relaxed tests to prevent floating point issues
@test sol.errors[:l∞] < 5e-10
@test sol.errors[:final] < 4.5e-12
@test sol.errors[:l2] < 7.7e-11 # 7.7e-12
end
######## Now show that non-residual control is worse
# solutions without residual control
@testset "non-residual control" begin
sol = solve(prob_wo, MethodOfSteps(OwrenZen5(); constrained = false))
@test sol.errors[:l∞] > 1.1e-1
@test sol.errors[:final] > 1.2e-3
@test sol.errors[:l2] > 4.5e-2
sol = solve(prob_wo, MethodOfSteps(OwrenZen5(); constrained = false); abstol = 1e-13,
reltol = 1e-13)
@test sol.errors[:l∞] > 1.1e-1
@test sol.errors[:final] > 1.2e-3
@test sol.errors[:l2] > 5.5e-2
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 525 | using DelayDiffEq, DDEProblemLibrary
using Test
const prob = prob_dde_constant_1delay_ip
@testset for composite in (true, false)
alg = MethodOfSteps(composite ? AutoTsit5(Rosenbrock23()) : Tsit5();
constrained = false)
sol1 = solve(prob, alg)
@test sol1.retcode == ReturnCode.Success
sol2 = solve(prob, alg; maxiters = 1, verbose = false)
@test sol2.retcode == ReturnCode.MaxIters
sol3 = solve(prob, alg; dtmin = 5, verbose = false)
@test sol3.retcode == ReturnCode.DtLessThanMin
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 700 | using DelayDiffEq, DDEProblemLibrary
using Test
const prob_ip = prob_dde_constant_1delay_ip
const prob_scalar = prob_dde_constant_1delay_scalar
const ts = 0:0.1:10
# ODE algorithms
const algs = [Rosenbrock23(), Rosenbrock32(), ROS3P(), Rodas3(),
RosShamp4(), Veldd4(), Velds4(), GRK4T(), GRK4A(),
Ros4LStab(), Rodas4(), Rodas42(), Rodas4P(), Rodas5()]
@testset "Algorithm $(nameof(typeof(alg)))" for alg in algs
println(nameof(typeof(alg)))
stepsalg = MethodOfSteps(alg)
sol_ip = solve(prob_ip, stepsalg)
sol_scalar = solve(prob_scalar, stepsalg)
@test sol_ip(ts, idxs = 1) ≈ sol_scalar(ts)
@test sol_ip.t ≈ sol_scalar.t
@test sol_ip[1, :] ≈ sol_scalar.u
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1741 | using DelayDiffEq, DDEProblemLibrary
using Test
const prob_ip = prob_dde_constant_1delay_ip
const prob_scalar = prob_dde_constant_1delay_scalar
const ts = 0:0.1:10
# ODE algorithms
noreuse = NLNewton(fast_convergence_cutoff = 0)
const working_algs = [ImplicitMidpoint(), SSPSDIRK2(), KenCarp5(nlsolve = noreuse),
ImplicitEuler(nlsolve = noreuse), Trapezoid(nlsolve = noreuse),
TRBDF2(nlsolve = noreuse), SDIRK2(nlsolve = noreuse),
Kvaerno3(nlsolve = noreuse), KenCarp3(nlsolve = noreuse),
Cash4(nlsolve = noreuse), Hairer4(nlsolve = noreuse),
Hairer42(nlsolve = noreuse), Kvaerno4(nlsolve = noreuse), KenCarp4(nlsolve = noreuse),
Kvaerno5(nlsolve = noreuse)]
const broken_algs = [ImplicitEuler(), Trapezoid(),
TRBDF2(), SDIRK2(),
Kvaerno3(), KenCarp3(),
Cash4(), Hairer4(), Hairer42(), Kvaerno4(), KenCarp4(),
Kvaerno5()]
@testset "Algorithm $(nameof(typeof(alg)))" for alg in working_algs
println(nameof(typeof(alg)))
stepsalg = MethodOfSteps(alg)
sol_ip = solve(prob_ip, stepsalg; dt = 0.1)
sol_scalar = solve(prob_scalar, stepsalg; dt = 0.1)
@test sol_ip(ts, idxs = 1) ≈ sol_scalar(ts)
@test sol_ip.t ≈ sol_scalar.t
@test sol_ip[1, :] ≈ sol_scalar.u
end
@testset "Algorithm $(nameof(typeof(alg)))" for alg in broken_algs
println(nameof(typeof(alg)))
stepsalg = MethodOfSteps(alg)
sol_ip = solve(prob_ip, stepsalg; dt = 0.1)
sol_scalar = solve(prob_scalar, stepsalg; dt = 0.1)
@test_broken sol_ip(ts, idxs = 1) ≈ sol_scalar(ts)
# this test is not broken for KenCarp4
#if alg isa KenCarp4
# @test sol_ip.t ≈ sol_scalar.t
#else
@test_broken sol_ip.t ≈ sol_scalar.t
#end
@test_broken sol_ip[1, :] ≈ sol_scalar.u
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 243 | using DelayDiffEq, DDEProblemLibrary
using Test
const prob = prob_dde_constant_1delay_long_ip
@testset for constrained in (false, true)
sol = solve(prob, MethodOfSteps(Tsit5(); constrained = constrained))
@test allunique(sol.t)
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 2114 | using DelayDiffEq, DDEProblemLibrary
using Test
# simple problems
@testset "simple problems" begin
prob_ip = prob_dde_constant_1delay_ip
prob_scalar = prob_dde_constant_1delay_scalar
ts = 0:0.1:10
# Vern6
println("Vern6")
@testset "Vern6" begin
alg = MethodOfSteps(Vern6())
sol_ip = solve(prob_ip, alg)
@test sol_ip.errors[:l∞] < 8.7e-4
@test sol_ip.errors[:final] < 6e-6
@test sol_ip.errors[:l2] < 5.4e-4
sol_scalar = solve(prob_scalar, alg)
# fails due to floating point issues
@test sol_ip(ts, idxs = 1)≈sol_scalar(ts) atol=1e-5
end
# Vern7
println("Vern7")
@testset "Vern7" begin
alg = MethodOfSteps(Vern7())
sol_ip = solve(prob_ip, alg)
@test sol_ip.errors[:l∞] < 4.0e-4
@test sol_ip.errors[:final] < 3.5e-7
@test sol_ip.errors[:l2] < 1.9e-4
sol_scalar = solve(prob_scalar, alg)
@test sol_ip(ts, idxs = 1)≈sol_scalar(ts) atol=1e-5
end
# Vern8
println("Vern8")
@testset "Vern8" begin
alg = MethodOfSteps(Vern8())
sol_ip = solve(prob_ip, alg)
@test sol_ip.errors[:l∞] < 2.0e-3
@test sol_ip.errors[:final] < 1.8e-5
@test sol_ip.errors[:l2] < 8.8e-4
sol_scalar = solve(prob_scalar, alg)
@test sol_ip(ts, idxs = 1)≈sol_scalar(ts) atol=1e-5
end
# Vern9
println("Vern9")
@testset "Vern9" begin
alg = MethodOfSteps(Vern9())
sol_ip = solve(prob_ip, alg)
@test sol_ip.errors[:l∞] < 1.5e-3
@test sol_ip.errors[:final] < 3.8e-6
@test sol_ip.errors[:l2] < 6.5e-4
sol_scalar = solve(prob_scalar, alg)
@test sol_ip(ts, idxs = 1)≈sol_scalar(ts) atol=1e-5
end
end
# model of Mackey and Glass
println("Mackey and Glass")
@testset "Mackey and Glass" begin
prob = prob_dde_DDETST_A1
# Vern6
solve(prob, MethodOfSteps(Vern6()))
# Vern7
solve(prob, MethodOfSteps(Vern7()))
# Vern8
solve(prob, MethodOfSteps(Vern8()))
# Vern9
solve(prob, MethodOfSteps(Vern9()))
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 4252 | using DelayDiffEq
import FiniteDiff
import ForwardDiff
using Test
# Hutchinson's equation
f(u, h, p, t) = p[2] * u * (1 - h(p, t - p[1]) / p[3])
h(p, t) = p[4]
@testset "Gradient" begin
function test(p)
prob = DDEProblem(f, p[5], h, eltype(p).((0.0, 10.0)), copy(p);
constant_lags = (p[1],))
sol = solve(prob, MethodOfSteps(Tsit5()); abstol = 1e-14, reltol = 1e-14,
saveat = 1.0)
sum(sol)
end
# without delay length estimation
p = [1.5, 1.0, 0.5]
findiff = FiniteDiff.finite_difference_gradient(p -> test(vcat(1, p, p[end])), p)
fordiff = ForwardDiff.gradient(p -> test(vcat(1, p, p[end])), p)
@test maximum(abs.(findiff .- fordiff)) < 1e-6
# with delay length estimation and without discontinuity
p = [1.0, 1.5, 1.0, 0.5]
findiff2 = FiniteDiff.finite_difference_gradient(p -> test(vcat(p, p[end])), p)
fordiff2 = ForwardDiff.gradient(p -> test(vcat(p, p[end])), p)
@test_broken maximum(abs.(findiff2 .- fordiff2)) < 2
# with discontinuity and without delay length estimation
p = [1.5, 1.0, 0.5, 1.0]
findiff3 = FiniteDiff.finite_difference_gradient(p -> test(vcat(1, p)), p)
fordiff3 = ForwardDiff.gradient(p -> test(vcat(1, p)), p)
@test maximum(abs.(findiff3 .- fordiff3)) < 9
# consistency checks
@test findiff2[2:end] ≈ findiff
@test fordiff2[2:end] ≈ fordiff
@test_broken findiff3[1:(end - 1)] ≈ findiff
@test_broken fordiff3[1:(end - 1)] ≈ fordiff
end
@testset "Jacobian" begin
function test(p)
prob = DDEProblem(f, p[5], h, eltype(p).((0.0, 10.0)), copy(p);
constant_lags = (p[1],))
sol = solve(prob, MethodOfSteps(Tsit5()); abstol = 1e-14, reltol = 1e-14,
saveat = 1.0)
sol.u
end
# without delay length estimation
p = [1.5, 1.0, 0.5]
findiff = FiniteDiff.finite_difference_jacobian(p -> test(vcat(1, p, p[end])), p)
fordiff = ForwardDiff.jacobian(p -> test(vcat(1, p, p[end])), p)
@test maximum(abs.(findiff .- fordiff)) < 2e-6
# with delay length estimation and without discontinuity
p = [1.0, 1.5, 1.0, 0.5]
findiff2 = FiniteDiff.finite_difference_jacobian(p -> test(vcat(p, p[end])), p)
fordiff2 = ForwardDiff.jacobian(p -> test(vcat(p, p[end])), p)
@test_broken maximum(abs.(findiff2 .- fordiff2)) < 3
# with discontinuity and without delay length estimation
p = [1.5, 1.0, 0.5, 1.0]
findiff3 = FiniteDiff.finite_difference_jacobian(p -> test(vcat(1, p)), p)
fordiff3 = ForwardDiff.jacobian(p -> test(vcat(1, p)), p)
@test maximum(abs.(findiff3 .- fordiff3)) < 1
# consistency checks
@test findiff2[:, 2:end] ≈ findiff
@test fordiff2[:, 2:end] ≈ fordiff
@test_broken findiff3[:, 1:(end - 1)] ≈ findiff
@test_broken fordiff3[:, 1:(end - 1)] ≈ fordiff
end
@testset "Hessian" begin
function test(p)
prob = DDEProblem(f, p[5], h, eltype(p).((0.0, 10.0)), copy(p);
constant_lags = (p[1],))
sol = solve(prob, MethodOfSteps(Tsit5()); abstol = 1e-14, reltol = 1e-14,
saveat = 1.0)
sum(sol)
end
# without delay length estimation and without discontinuity
p = [1.5, 1.0, 0.5]
findiff = FiniteDiff.finite_difference_hessian(p -> test(vcat(1, p, p[end])), p)
fordiff = ForwardDiff.hessian(p -> test(vcat(1, p, p[end])), p)
@test maximum(abs.(findiff .- fordiff)) < 1e-5
# with delay length estimation and without discontinuity
p = [1.0, 1.5, 1.0, 0.5]
findiff2 = FiniteDiff.finite_difference_hessian(p -> test(vcat(p, p[end])), p)
fordiff2 = ForwardDiff.hessian(p -> test(vcat(p, p[end])), p)
@test_broken maximum(abs.(findiff2 .- fordiff2)) < 25
# with discontinuity and without delay length estimation
p = [1.5, 1.0, 0.5, 1.0]
findiff3 = FiniteDiff.finite_difference_hessian(p -> test(vcat(1, p)), p)
fordiff3 = ForwardDiff.hessian(p -> test(vcat(1, p)), p)
@test maximum(abs.(findiff3 .- fordiff3)) < 1
# consistency checks
@test findiff2[2:end, 2:end] ≈ findiff
@test fordiff2[2:end, 2:end] ≈ fordiff
@test_broken findiff3[1:(end - 1), 1:(end - 1)] ≈ findiff
@test_broken fordiff3[1:(end - 1), 1:(end - 1)] ≈ fordiff
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 2001 | using DelayDiffEq
using Test
h(p, t) = 1.0
const tspan = (2.0, 0.0)
f(u, h, p, t) = h(p, t + 1)
# solution on [0,2]
f_analytic(u₀, ::typeof(h), p, t) = t < 1 ? (t^2 - 1) / 2 : t - 1
const dde_f = DDEFunction(f, analytic = f_analytic)
@testset "Without lags" begin
sol = solve(DDEProblem(dde_f, h, tspan), MethodOfSteps(RK4()))
@test sol.errors[:l∞] < 1.2e-12 # 1.2e-16
end
@testset "Constant lags" begin
@testset "incorrect" begin
prob = DDEProblem(dde_f, h, tspan; constant_lags = [1.0])
@test_throws ErrorException solve(prob, MethodOfSteps(Tsit5()))
end
@testset "correct" begin
prob = DDEProblem(dde_f, h, tspan; constant_lags = [-1.0])
dde_int = init(prob, MethodOfSteps(Tsit5()))
@test dde_int.tracked_discontinuities == [Discontinuity(-2.0, 1)]
@test dde_int.d_discontinuities_propagated.valtree == [Discontinuity(-1.0, 2)]
@test isempty(dde_int.opts.d_discontinuities)
sol = solve!(dde_int)
@test sol.errors[:l∞] < 3.9e-12 # 3.9e-15
@test dde_int.tracked_discontinuities ==
[Discontinuity(-2.0, 1), Discontinuity(-1.0, 2)]
@test isempty(dde_int.d_discontinuities_propagated)
@test isempty(dde_int.opts.d_discontinuities)
end
end
@testset "Dependent lags" begin
prob = DDEProblem(dde_f, h, tspan; dependent_lags = ((u, p, t) -> -1.0,))
dde_int = init(prob, MethodOfSteps(Tsit5()))
@test isempty(dde_int.opts.d_discontinuities)
sol = solve!(dde_int)
@test sol.errors[:l∞] < 3.9e-12 # 3.9e-15
@test dde_int.tracked_discontinuities == [Discontinuity(-2.0, 1)]
end
@testset "dt and dtmax" begin
prob = DDEProblem(dde_f, h, tspan)
dde_int = init(prob, MethodOfSteps(RK4()); dt = 0.1, dtmax = 0.5)
@test dde_int.dt == -0.1
@test dde_int.opts.dtmax == -0.5
sol1 = solve!(dde_int)
sol2 = solve(prob, MethodOfSteps(RK4()); dt = -0.1, dtmax = -0.5)
@test sol1.t == sol2.t
@test sol1.u == sol2.u
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1371 | using DelayDiffEq, DDEProblemLibrary
using Test
@testset "integrator" begin
prob = prob_dde_constant_1delay_ip
integrator = init(prob, MethodOfSteps(AutoTsit5(Rosenbrock23())))
@test integrator.sol isa SciMLBase.ODESolution
@test integrator.integrator.sol isa SciMLBase.ODESolution
sol1 = solve!(integrator)
@test sol1 isa SciMLBase.ODESolution
# compare integration grid
sol2 = solve(prob, MethodOfSteps(Tsit5()))
@test sol1.t == sol2.t
@test sol1.u == sol2.u
# compare interpolation
@test sol1(0:0.1:1) == sol2(0:0.1:1)
end
@testset "issue #148" begin
alg = MethodOfSteps(Tsit5())
compositealg = MethodOfSteps(CompositeAlgorithm((Tsit5(), RK4()), integrator -> 1))
prob = DDEProblem((du, u, h, p, t) -> (du[1] = -h(p, t - 1)[1]; nothing),
[1.0], (p, t) -> [1.0], (0.0, 5.0))
sol = solve(prob, alg)
compositesol = solve(prob, compositealg)
@test compositesol isa SciMLBase.ODESolution
@test sol.t == compositesol.t
@test sol.u == compositesol.u
prob_oop = DDEProblem((u, h, p, t) -> -h(p, t - 1), [1.0], (p, t) -> [1.0],
(0.0, 5.0))
sol_oop = solve(prob_oop, alg)
compositesol_oop = solve(prob_oop, compositealg)
@test compositesol_oop isa SciMLBase.ODESolution
@test sol_oop.t == compositesol_oop.t
@test sol_oop.u == compositesol_oop.u
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1424 | using DelayDiffEq, DDEProblemLibrary
using Test
# Check that numerical solutions approximate analytical solutions,
# independent of problem structure
const alg = MethodOfSteps(BS3(); constrained = true)
# Single constant delay
@testset "single constant delay" begin
## Scalar function
sol_scalar = solve(prob_dde_constant_1delay_scalar, alg; dt = 0.1)
@test sol_scalar.errors[:l∞] < 3.0e-5
@test sol_scalar.errors[:final] < 2.1e-5
@test sol_scalar.errors[:l2] < 1.3e-5
## Out-of-place function
sol_oop = solve(prob_dde_constant_1delay_oop, alg; dt = 0.1)
@test sol_scalar.t ≈ sol_oop.t && sol_scalar.u ≈ sol_oop[1, :]
## In-place function
sol_ip = solve(prob_dde_constant_1delay_ip, alg; dt = 0.1)
@test sol_scalar.t ≈ sol_ip.t && sol_scalar.u ≈ sol_ip[1, :]
end
# Two constant delays
@testset "two constant delays" begin
## Scalar function
sol_scalar = solve(prob_dde_constant_2delays_scalar, alg; dt = 0.1)
@test sol_scalar.errors[:l∞] < 4.1e-6
@test sol_scalar.errors[:final] < 1.5e-6
@test sol_scalar.errors[:l2] < 2.3e-6
## Out-of-place function
sol_oop = solve(prob_dde_constant_2delays_oop, alg; dt = 0.1)
@test sol_scalar.t ≈ sol_oop.t && sol_scalar.u ≈ sol_oop[1, :]
## In-place function
sol_ip = solve(prob_dde_constant_2delays_ip, alg; dt = 0.1)
@test sol_scalar.t ≈ sol_ip.t && sol_scalar.u ≈ sol_ip[1, :]
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1707 | using DelayDiffEq, DDEProblemLibrary
using Test
const alg = MethodOfSteps(BS3())
const prob = prob_dde_constant_1delay_ip
const dde_int = init(prob, alg)
const sol = solve!(dde_int)
@testset "reference" begin
@test sol.errors[:l∞] < 3.0e-5
@test sol.errors[:final] < 2.1e-5
@test sol.errors[:l2] < 1.2e-5
end
@testset "constant lag function" begin
# constant delay specified as lag function
prob2 = remake(prob; constant_lags = nothing, dependent_lags = ((u, p, t) -> 1,))
dde_int2 = init(prob2, alg)
sol2 = solve!(dde_int2)
@test getfield.(dde_int.tracked_discontinuities, :t) ≈
getfield.(dde_int2.tracked_discontinuities, :t)
@test getfield.(dde_int.tracked_discontinuities, :order) ==
getfield.(dde_int2.tracked_discontinuities, :order)
# worse than results above with constant delays specified as scalars
@test sol2.errors[:l∞] < 3.2e-3
@test sol2.errors[:final] < 1.2e-4
@test sol2.errors[:l2] < 1.2e-3
# simple convergence tests
@testset "convergence" begin
sol3 = solve(prob2, alg; abstol = 1e-9, reltol = 1e-6)
@test sol3.errors[:l∞] < 3.0e-6
@test sol3.errors[:final] < 1.4e-7
@test sol3.errors[:l2] < 9.6e-7
sol4 = solve(prob2, alg; abstol = 1e-13, reltol = 1e-13)
@test sol4.errors[:l∞] < 6.0e-11
@test sol4.errors[:final] < 4.7e-11
@test sol4.errors[:l2] < 8e-12
end
end
# without any delays specified is worse
@testset "without delays" begin
prob2 = remake(prob; constant_lags = nothing)
sol2 = solve(prob2, alg)
@test sol2.errors[:l∞] > 1.0e-2
@test sol2.errors[:final] > 1e-6
@test sol2.errors[:l2] > 4.6e-3
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 2575 | using DelayDiffEq, DDEProblemLibrary
using Test
const prob = prob_dde_constant_2delays_ip
# total order
@testset "total order" begin
a = Discontinuity(1, 3)
@test a > 0
@test a < 2
@test a == 1
b = Discontinuity(2.0, 2)
@test !(a > b)
@test a < b
@test a != b
c = Discontinuity(1.0, 2)
@test a > c
@test !(a < c)
@test a != c
end
# simple DDE example
@testset "DDE" begin
integrator = init(prob, MethodOfSteps(BS3()))
# initial discontinuities
@testset "initial" begin
@test integrator.tracked_discontinuities == [Discontinuity(0.0, 0)]
@test length(integrator.d_discontinuities_propagated) == 2 &&
issubset([Discontinuity(1 / 5, 1), Discontinuity(1 / 3, 1)],
integrator.d_discontinuities_propagated.valtree)
@test isempty(integrator.opts.d_discontinuities)
@test isempty(integrator.opts.d_discontinuities_cache)
end
# tracked discontinuities
@testset "tracked" begin
solve!(integrator)
discs = [Discontinuity(t, order)
for (t, order) in ((0.0, 0), (1 / 5, 1), (1 / 3, 1), (2 / 5, 2),
(8 / 15, 2), (3 / 5, 3),
(2 / 3, 2), (11 / 15, 3), (13 / 15, 3))]
for (tracked, disc) in zip(integrator.tracked_discontinuities, discs)
@test tracked.t ≈ disc.t && tracked.order == disc.order
end
end
end
# additional discontinuities
@testset "DDE with discontinuities" begin
integrator = init(prob, MethodOfSteps(BS3());
d_discontinuities = [Discontinuity(0.3, 4), Discontinuity(0.6, 5)])
@test integrator.tracked_discontinuities == [Discontinuity(0.0, 0)]
@test length(integrator.d_discontinuities_propagated) == 2 &&
issubset([Discontinuity(1 / 5, 1), Discontinuity(1 / 3, 1)],
integrator.d_discontinuities_propagated.valtree)
@test length(integrator.opts.d_discontinuities) == 2 &&
issubset([Discontinuity(0.3, 4), Discontinuity(0.6, 5)],
integrator.opts.d_discontinuities.valtree)
@test integrator.opts.d_discontinuities_cache ==
[Discontinuity(0.3, 4), Discontinuity(0.6, 5)]
end
# discontinuities induced by callbacks
@testset "#190" begin
cb = ContinuousCallback((u, t, integrator) -> 1, integrator -> nothing)
integrator = init(prob_dde_constant_1delay_ip, MethodOfSteps(Tsit5());
callback = cb)
sol = solve!(integrator)
for t in 0:5
@test t ∈ sol.t
@test Discontinuity(Float64(t), t) ∈ integrator.tracked_discontinuities
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 96 | using DelayDiffEq, DiffEqBase
using Test
@test DiffEqBase.undefined_exports(DelayDiffEq) == []
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 2950 | using DelayDiffEq, DDEProblemLibrary, DiffEqDevTools
using LinearAlgebra
using Test
const prob = prob_dde_constant_2delays_long_ip
const prob_oop = prob_dde_constant_2delays_long_oop
const prob_scalar = prob_dde_constant_2delays_long_scalar
const testsol = TestSolution(solve(prob, MethodOfSteps(Vern9());
abstol = 1 / 10^14, reltol = 1 / 10^14))
@testset "NLFunctional" begin
alg = MethodOfSteps(Tsit5(); fpsolve = NLFunctional(; max_iter = 10))
## in-place problem
sol = solve(prob, alg)
# check statistics
@test sol.stats.nf > 3000
@test sol.stats.nsolve == 0
@test sol.stats.nfpiter > 300
@test sol.stats.nfpconvfail > 50
# compare it with the test solution
sol2 = appxtrue(sol, testsol)
@test sol2.errors[:L∞] < 2.7e-4
## out-of-place problem
sol_oop = solve(prob_oop, alg)
# compare it with the in-place solution
@test sol_oop.stats.nf == sol.stats.nf
@test sol_oop.stats.nsolve == sol.stats.nsolve
@test sol_oop.stats.nfpiter == sol.stats.nfpiter
@test sol_oop.stats.nfpconvfail == sol.stats.nfpconvfail
@test sol_oop.t≈sol.t atol=1e-3
@test sol_oop.u ≈ sol.u
@test isapprox(sol.u, sol_oop.u; atol = 1e-7)
## scalar problem
sol_scalar = solve(prob_scalar, alg)
# compare it with the in-place solution
@test sol_scalar.stats.nf == sol.stats.nf
@test sol_scalar.stats.nsolve == sol.stats.nsolve
@test sol_scalar.stats.nfpiter == sol.stats.nfpiter
@test sol_scalar.stats.nfpconvfail == sol.stats.nfpconvfail
@test sol_scalar.t≈sol.t atol=1e-3
@test sol_scalar.u ≈ sol[1, :]
end
@testset "NLAnderson" begin
alg = MethodOfSteps(Tsit5(); fpsolve = NLAnderson(; max_iter = 10))
## in-place problem
sol = solve(prob, alg)
# check statistics
@test sol.stats.nf < 2500
@test sol.stats.nsolve > 0
@test sol.stats.nfpiter < 250
@test sol.stats.nfpconvfail < 50
# compare it with the test solution
sol2 = appxtrue(sol, testsol)
@test sol2.errors[:L∞] < 2.7e-4
## out-of-place problem
sol_oop = solve(prob_oop, alg)
# compare it with the in-place solution
@test_broken sol_oop.stats.nf == sol.stats.nf
@test_broken sol_oop.stats.nsolve == sol.stats.nsolve
@test_broken sol_oop.stats.nfpiter == sol.stats.nfpiter
@test_broken sol_oop.stats.nfpconvfail == sol.stats.nfpconvfail
@test_broken sol_oop.t ≈ sol.t
@test_broken sol_oop.u ≈ sol.u
@test appxtrue(sol, sol_oop).errors[:L∞] < 3e-6
## scalar problem
sol_scalar = solve(prob_scalar, alg)
# compare it with the in-place solution
@test_broken sol_scalar.stats.nf == sol.stats.nf
@test_broken sol_scalar.stats.nsolve == sol.stats.nsolve
@test_broken sol_scalar.stats.nfpiter == sol.stats.nfpiter
@test_broken sol_scalar.stats.nfpconvfail == sol.stats.nfpconvfail
@test_broken sol_scalar.t ≈ sol.t
@test_broken sol_scalar.u ≈ sol[1, :]
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 4846 | using DelayDiffEq
using Test
# check constant extrapolation with problem with vanishing delays at t = 0
@testset "vanishing delays" begin
prob = DDEProblem((u, h, p, t) -> -h(p, t / 2), 1.0, (p, t) -> 1.0, (0.0, 10.0))
solve(prob, MethodOfSteps(RK4()))
end
@testset "general" begin
# naive history functions
h_notinplace(p, t; idxs = nothing) = idxs === nothing ? [t, -t] : [t, -t][idxs]
function h_inplace(val, p, t; idxs = nothing)
if idxs === nothing
val[1] = t
val[2] = -t
else
val .= [t; -t][idxs]
end
end
# ODE integrator
prob = ODEProblem((du, u, p, t) -> @.(du=p * u), ones(2), (0.0, 1.0), 1.01)
integrator = init(prob, Tsit5())
# combined history function
history_notinplace = DelayDiffEq.HistoryFunction(h_notinplace,
integrator)
history_inplace = DelayDiffEq.HistoryFunction(h_inplace,
integrator)
# test evaluation of history function
@testset "evaluation" for idxs in (nothing, [2])
# expected value
trueval = h_notinplace(nothing, -1; idxs = idxs)
# out-of-place
@test history_notinplace(nothing, -1, Val{0}; idxs = idxs) == trueval
# in-place
val = zero(trueval)
history_inplace(val, nothing, -1; idxs = idxs)
@test val == trueval
val = zero(trueval)
history_inplace(val, nothing, -1, Val{0}; idxs = idxs)
@test val == trueval
end
# test constant extrapolation
@testset "constant extrapolation" for deriv in (Val{0}, Val{1}), idxs in (nothing, [2])
# expected value
trueval = deriv == Val{0} ?
(idxs === nothing ? integrator.u : integrator.u[[2]]) :
(idxs === nothing ? zeros(2) : [0.0])
# out-of-place
history_notinplace.isout = false
@test history_notinplace(nothing, 1, deriv; idxs = idxs) == trueval
@test history_notinplace.isout
# in-place
history_inplace.isout = false
@test history_inplace(nothing, nothing, 1, deriv; idxs = idxs) == trueval
@test history_inplace.isout
history_inplace.isout = false
val = 1 .- trueval # ensures that val ≠ trueval
history_inplace(val, nothing, 1, deriv; idxs = idxs)
@test val == trueval
@test history_inplace.isout
end
# add step to integrator
@testset "update integrator" begin
OrdinaryDiffEq.loopheader!(integrator)
OrdinaryDiffEq.perform_step!(integrator, integrator.cache)
integrator.t = integrator.dt
@test 0.01 < integrator.t < 1
@test integrator.sol.t[end] == 0
end
# test integrator interpolation
@testset "integrator interpolation" for deriv in (Val{0}, Val{1}),
idxs in (nothing, [2])
# expected value
trueval = OrdinaryDiffEq.current_interpolant(0.01, integrator, idxs, deriv)
# out-of-place
history_notinplace.isout = false
@test history_notinplace(nothing, 0.01, deriv; idxs = idxs) == trueval
@test history_notinplace.isout
# in-place
history_inplace.isout = false
val = zero(trueval)
history_inplace(val, nothing, 0.01, deriv; idxs = idxs)
@test val == trueval
@test history_inplace.isout
end
# add step to solution
@testset "update solution" begin
integrator.t = 0
OrdinaryDiffEq.loopfooter!(integrator)
@test integrator.t == integrator.sol.t[end]
end
# test solution interpolation
@testset "solution interpolation" for deriv in (Val{0}, Val{1}), idxs in (nothing, [2])
# expected value
trueval = integrator.sol.interp(0.01, idxs, deriv, integrator.p)
# out-of-place
history_notinplace.isout = false
@test history_notinplace(nothing, 0.01, deriv; idxs = idxs) == trueval
@test !history_notinplace.isout
# in-place
history_inplace.isout = false
val = zero(trueval)
history_inplace(val, nothing, 0.01, deriv; idxs = idxs)
@test val == trueval
@test !history_inplace.isout
end
# test integrator extrapolation
@testset "integrator extrapolation" for deriv in (Val{0}, Val{1}), idxs in (0, [2])
idxs == 0 && (idxs = nothing)
# expected value
trueval = OrdinaryDiffEq.current_interpolant(1, integrator, idxs, deriv)
# out-of-place
history_notinplace.isout = false
@test history_notinplace(nothing, 1, deriv; idxs = idxs) == trueval
@test history_notinplace.isout
# in-place
history_inplace.isout = false
val = zero(trueval)
history_inplace(val, nothing, 1, deriv; idxs = idxs)
@test val == trueval
@test history_inplace.isout
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 5248 | using DelayDiffEq
using Test
@testset "in-place" begin
# define functions (Hutchinson's equation)
function f(du, u, h, p, t)
du[1] = u[1] * (1 - h(p, t - 1)[1])
nothing
end
njacs = Ref(0)
function jac(J, u, h, p, t)
njacs[] += 1
J[1, 1] = 1 - h(p, t - 1)[1]
nothing
end
nWfacts = Ref(0)
function Wfact(W, u, h, p, dtgamma, t)
nWfacts[] += 1
W[1, 1] = dtgamma * (1 - h(p, t - 1)[1]) - 1
nothing
end
nWfact_ts = Ref(0)
function Wfact_t(W, u, h, p, dtgamma, t)
nWfact_ts[] += 1
W[1, 1] = 1 - h(p, t - 1)[1] - inv(dtgamma)
nothing
end
h(p, t) = [0.0]
# define problems
prob = DDEProblem(DDEFunction{true}(f), [1.0], h, (0.0, 40.0); constant_lags = [1])
prob_jac = remake(prob; f = DDEFunction{true}(f; jac = jac))
prob_Wfact = remake(prob; f = DDEFunction{true}(f; Wfact = Wfact))
prob_Wfact_t = remake(prob; f = DDEFunction{true}(f; Wfact_t = Wfact_t))
# compute solutions
for alg in (Rosenbrock23(), TRBDF2())
sol = solve(prob, MethodOfSteps(alg))
## Jacobian
njacs[] = 0
sol_jac = solve(prob_jac, MethodOfSteps(alg))
# check number of function evaluations
@test !iszero(njacs[])
@test njacs[] == sol_jac.stats.njacs
@test njacs[] <= sol_jac.stats.nw
# check resulting solution
@test sol.t ≈ sol_jac.t
@test sol.u ≈ sol_jac.u
## Wfact
nWfacts[] = 0
sol_Wfact = solve(prob_Wfact, MethodOfSteps(alg))
# check number of function evaluations
if alg isa Rosenbrock23
@test !iszero(nWfacts[])
@test nWfacts[] >= njacs[]
@test iszero(sol_Wfact.stats.njacs)
else
@test_broken !iszero(nWfacts[])
@test_broken nWfacts[] >= njacs[]
@test_broken iszero(sol_Wfact.stats.njacs)
end
@test_broken nWfacts[] == sol_Wfact.stats.nw
# check resulting solution
@test sol.t ≈ sol_Wfact.t
@test sol.u ≈ sol_Wfact.u
## Wfact_t
nWfact_ts[] = 0
sol_Wfact_t = solve(prob_Wfact_t, MethodOfSteps(alg))
# check number of function evaluations
if alg isa Rosenbrock23
@test_broken !iszero(nWfact_ts[])
@test_broken nWfact_ts[] == njacs[]
@test_broken iszero(sol_Wfact_t.stats.njacs)
else
@test !iszero(nWfact_ts[])
@test_broken nWfact_ts[] == njacs[]
@test iszero(sol_Wfact_t.stats.njacs)
end
@test_broken nWfact_ts[] == sol_Wfact_t.stats.nw
# check resulting solution
if alg isa Rosenbrock23
@test sol.t ≈ sol_Wfact_t.t
@test sol.u ≈ sol_Wfact_t.u
else
@test_broken sol.t ≈ sol_Wfact_t.t
@test_broken sol.u ≈ sol_Wfact_t.u
end
end
end
@testset "out-of-place" begin
# define functions (Hutchinson's equation)
f(u, h, p, t) = u[1] .* (1 .- h(p, t - 1))
njacs = Ref(0)
function jac(u, h, p, t)
njacs[] += 1
reshape(1 .- h(p, t - 1), 1, 1)
end
nWfacts = Ref(0)
function Wfact(u, h, p, dtgamma, t)
nWfacts[] += 1
reshape(dtgamma .* (1 .- h(p, t - 1)) .- 1, 1, 1)
end
nWfact_ts = Ref(0)
function Wfact_t(u, h, p, dtgamma, t)
nWfact_ts[] += 1
reshape((1 - inv(dtgamma)) .- h(p, t - 1), 1, 1)
end
h(p, t) = [0.0]
# define problems
prob = DDEProblem(DDEFunction{false}(f), [1.0], h, (0.0, 40.0); constant_lags = [1])
prob_jac = remake(prob; f = DDEFunction{false}(f; jac = jac))
prob_Wfact = remake(prob; f = DDEFunction{false}(f; Wfact = Wfact))
prob_Wfact_t = remake(prob; f = DDEFunction{false}(f; Wfact_t = Wfact_t))
# compute solutions
for alg in (Rosenbrock23(), TRBDF2())
sol = solve(prob, MethodOfSteps(alg))
## Jacobian
njacs[] = 0
sol_jac = solve(prob_jac, MethodOfSteps(alg))
# check number of function evaluations
@test !iszero(njacs[])
@test_broken njacs[] == sol_jac.stats.njacs
@test_broken njacs[] == sol_jac.stats.nw
# check resulting solution
@test sol.t ≈ sol_jac.t
@test sol.u ≈ sol_jac.u
## Wfact
nWfacts[] = 0
sol_Wfact = solve(prob_Wfact, MethodOfSteps(alg))
# check number of function evaluations
@test_broken !iszero(nWfacts[])
@test_broken nWfacts[] == njacs[]
@test_broken iszero(sol_Wfact.stats.njacs)
@test_broken nWfacts[] == sol_Wfact.stats.nw
# check resulting solution
@test sol.t ≈ sol_Wfact.t
@test sol.u ≈ sol_Wfact.u
## Wfact_t
nWfact_ts[] = 0
sol_Wfact_t = solve(prob_Wfact_t, MethodOfSteps(alg))
# check number of function evaluations
@test_broken !iszero(nWfact_ts[])
@test_broken nWfact_ts[] == njacs[]
@test_broken iszero(sol_Wfact_ts.stats.njacs)
@test_broken nWfact_ts[] == sol_Wfact_t.stats.nw
# check resulting solution
@test sol.t ≈ sol_Wfact_t.t
@test sol.u ≈ sol_Wfact_t.u
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
|
[
"MIT"
] | 5.48.1 | 066f60231c1b0ae2905ffd2651e207accd91f627 | code | 1843 | using DelayDiffEq
using DiffEqDevTools
using LinearAlgebra
using Test
@testset "SIR" begin
function sir_dde!(du, u, h, p, t)
S, I, _ = u
γ, τ = p
infection = γ * I * S
Sd, Id, _ = h(p, t - τ)
recovery = γ * Id * Sd
@inbounds begin
du[1] = -infection
du[2] = infection - recovery
du[3] = recovery
end
nothing
end
u0 = [0.99, 0.01, 0.0]
sir_history(p, t) = [1.0, 0.0, 0.0]
tspan = (0.0, 40.0)
p = (γ = 0.5, τ = 4.0)
prob_dde = DDEProblem(sir_dde!, u0, sir_history, tspan, p; constant_lags = (p.τ,))
sol_dde = TestSolution(solve(prob_dde, MethodOfSteps(Vern9()); reltol = 1e-14,
abstol = 1e-14))
function sir_ddae!(du, u, h, p, t)
S, I, R = u
γ, τ = p
infection = γ * I * S
Sd, Id, _ = h(p, t - τ)
recovery = γ * Id * Sd
@inbounds begin
du[1] = -infection
du[2] = infection - recovery
du[3] = S + I + R - 1
end
nothing
end
prob_ddae = DDEProblem(
DDEFunction{true}(sir_ddae!;
mass_matrix = Diagonal([1.0, 1.0, 0.0])),
u0,
sir_history,
tspan,
p;
constant_lags = (p.τ,))
ode_f = DelayDiffEq.ODEFunctionWrapper(prob_ddae.f, prob_ddae.h)
@test ode_f.mass_matrix == Diagonal([1.0, 1.0, 0.0])
int = init(prob_ddae, MethodOfSteps(Rosenbrock23()))
@test int.isdae
@test int.f.mass_matrix == Diagonal([1.0, 1.0, 0.0])
for (alg, reltol) in ((Rosenbrock23(), nothing),
(Rodas4(), nothing),
(QNDF(), 1e-6),
(Trapezoid(), 1e-6))
sol_ddae = solve(prob_ddae, MethodOfSteps(alg); reltol = reltol)
sol = appxtrue(sol_ddae, sol_dde)
@test sol.errors[:L∞] < 5e-3
end
end
| DelayDiffEq | https://github.com/SciML/DelayDiffEq.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.