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.3.6 | b9a419e46fe4516f3c0b52041d84e2bb5be9cb81 | code | 163 | function concordiacurve end
function concordiacurve! end
function concordialine end
function concordialine! end
function rankorder end
function rankorder! end | Isoplot | https://github.com/JuliaGeochronology/Isoplot.jl.git |
|
[
"MIT"
] | 0.3.6 | b9a419e46fe4516f3c0b52041d84e2bb5be9cb81 | code | 25037 |
"""
```julia
dist_ll(dist::Collection, mu::Collection, sigma::Collection, tmin::Number, tmax::Number)
dist_ll(dist::Collection, analyses::Collection{<:Measurement}, tmin::Number, tmax::Number)
```
Return the log-likelihood of a set of mineral ages with means `mu` and
uncertianty `sigma` being drawn from a given source (i.e., crystallization / closure)
distribution `dist`, with terms to prevent runaway at low N.
### Examples
```julia
mu, sigma = collect(100:0.1:101), 0.01*ones(11)
ll = dist_ll(MeltsVolcanicZirconDistribution, mu, sigma, 100, 101)
```
"""
function dist_ll(dist::Collection, mu::Collection, sigma::Collection, tmin::Number, tmax::Number)
tmax >= tmin || return NaN
any(isnan, mu) && return NaN
any(x->!(x>0), sigma) && return NaN
@assert issorted(mu)
mu₋, sigma₋ = first(mu), first(sigma)
mu₊, sigma₊ = last(mu), last(sigma)
nbins = length(dist) - 1
dt = abs(tmax-tmin)
# Cycle through each datum in dataset
loglikelihood = zero(float(eltype(dist)))
@inbounds for j in eachindex(mu, sigma)
μⱼ, σⱼ = mu[j], sigma[j]
# Find equivalent index position of μⱼ in the `dist` array
ix = (μⱼ - tmin) / dt * nbins + 1
# If possible, prevent aliasing problems by interpolation
if (σⱼ < dt / nbins) && 1 < ix < length(dist)
# Interpolate corresponding distribution value
f = floor(Int, ix)
δ = ix - f
likelihood = (dist[f+1]*δ + dist[f]*(1-δ)) / dt
else
# Otherwise, sum contributions from Gaussians at each point in distribution
𝑖 = 1:length(dist)
likelihood = zero(float(eltype(dist)))
normconst = 1/(length(dist) * σⱼ * sqrt(2 * pi))
@turbo for i in eachindex(dist, 𝑖)
distx = tmin + dt * (𝑖[i] - 1) / nbins # time-position of distribution point
# Likelihood curve follows a Gaussian PDF. Note: dt cancels
likelihood += dist[i] * normconst * exp(-(distx - μⱼ)^2 / (2 * σⱼ * σⱼ))
end
end
loglikelihood += log(likelihood)
end
# Calculate a weighted mean and examine our MSWD
(wm, wsigma, mswd) = wmean(mu, sigma, corrected=true) # Height of MSWD distribution relative to height at MSWD = 1
# (see Wendt and Carl, 1991, Chemical geology)
f = length(mu) - 1
Zf = exp((f/2-1)*log(mswd) - f/2*(mswd-1)) * (f > 0)
Zf = max(min(Zf, 1.0), 0.0)
@assert 0 <= Zf <= 1
# To prevent instability / runaway of the MCMC for small datasets (low N),
# favor the weighted mean interpretation at high Zf (MSWD close to 1) and
# the youngest-zircon interpretation at low Zf (MSWD far from one). The
# penalty factors used here are determined by training against synthetic datasets.
# In other words, these are just context-dependent prior distributions on tmax and tmin
loglikelihood -= (2/log(1+length(mu))) * ( # Scaling factor that decreases with log number of data points (i.e., no penalty at high N)
log((abs(tmin - wm)+wsigma)/wsigma)*Zf + # Penalty for proposing tmin too far from the weighted mean at low MSWD (High Zf)
log((abs(tmax - wm)+wsigma)/wsigma)*Zf + # Penalty for proposing tmax too far from the weighted mean at low MSWD (High Zf)
log((abs(tmin - mu₋)+sigma₋)/sigma₋)*(1-Zf) + # Penalty for proposing tmin too far from youngest zircon at high MSWD (low Zf)
log((abs(tmax - mu₊)+sigma₊)/sigma₊)*(1-Zf) ) # Penalty for proposing tmax too far from oldest zircon at high MSWD (low Zf)
return loglikelihood
end
function dist_ll(dist::Collection, analyses::Collection{<:Measurement}, tmin::Number, tmax::Number)
tmax >= tmin || return NaN
any(isnan, analyses) && return NaN
any(x->!(err(x) > 0), analyses) && return NaN
old = maximum(analyses)
yng = minimum(analyses)
nbins = length(dist) - 1
dt = abs(tmax - tmin)
# Cycle through each datum in dataset
loglikelihood = zero(float(eltype(dist)))
@inbounds for j in eachindex(analyses)
dⱼ = analyses[j]
μⱼ, σⱼ = val(dⱼ), err(dⱼ)
# Find equivalent index position of μⱼ in the `dist` array
ix = (μⱼ - tmin) / dt * nbins + 1
# If possible, prevent aliasing problems by interpolation
if (σⱼ < dt / nbins) && 1 < ix < length(dist)
# Interpolate corresponding distribution value
f = floor(Int, ix)
δ = ix - f
likelihood = (dist[f+1]*δ + dist[f]*(1-δ)) / dt
else
# Otherwise, sum contributions from Gaussians at each point in distribution
𝑖 = 1:length(dist)
likelihood = zero(float(eltype(dist)))
normconst = 1/(length(dist) * σⱼ * sqrt(2 * pi))
@turbo for i in eachindex(dist, 𝑖)
distx = tmin + dt * (𝑖[i] - 1) / nbins # time-position of distribution point
# Likelihood curve follows a Gaussian PDF. Note: dt cancels
likelihood += dist[i] * normconst * exp(-(distx - μⱼ)^2 / (2 * σⱼ * σⱼ))
end
end
loglikelihood += log(likelihood)
end
# Calculate a weighted mean and examine our MSWD
(wm, mswd) = wmean(analyses, corrected=true)
@assert wm.err > 0
# Height of MSWD distribution relative to height at MSWD = 1
# (see Wendt and Carl, 1991, Chemical geology)
f = length(analyses) - 1
Zf = exp((f / 2 - 1) * log(mswd) - f / 2 * (mswd - 1)) * (f > 0)
Zf = max(min(Zf, 1.0), 0.0)
@assert 0 <= Zf <= 1
# To prevent instability / runaway of the MCMC for small datasets (low N),
# favor the weighted mean interpretation at high Zf (MSWD close to 1) and
# the youngest-zircon interpretation at low Zf (MSWD far from one). The
# penalties used here were determined by training against synthetic datasets.
# In other words, these are just context-dependent prior distributions on tmax and tmin
loglikelihood -= (2 / log(1 + length(analyses))) * ( # Scaling factor that decreases with log number of analyses points (i.e., no penalty at high N)
log((abs(tmin - wm.val) + wm.err) / wm.err) * Zf + # Penalty for proposing tmin too far from the weighted mean at low MSWD (High Zf)
log((abs(tmax - wm.val) + wm.err) / wm.err) * Zf + # Penalty for proposing tmax too far from the weighted mean at low MSWD (High Zf)
log((abs(tmin - yng.val) + yng.err) / yng.err) * (1 - Zf) + # Penalty for proposing tmin too far from youngest zircon at high MSWD (low Zf)
log((abs(tmax - old.val) + old.err) / old.err) * (1 - Zf)) # Penalty for proposing tmax too far from oldest zircon at high MSWD (low Zf)
return loglikelihood
end
"""
```julia
metropolis_min(nsteps::Integer, dist::Collection, data::Collection{<:Measurement}; burnin::Integer=0, t0prior=Uniform(0,minimum(age68.(analyses))), lossprior=Uniform(0,100))
metropolis_min(nsteps::Integer, dist::Collection, mu::AbstractArray, sigma::AbstractArray; burnin::Integer=0)
metropolis_min(nsteps::Integer, dist::Collection, analyses::Collection{<:UPbAnalysis; burnin::Integer=0)
```
Run a Metropolis sampler to estimate the minimum of a finite-range source
distribution `dist` using samples drawn from that distribution -- e.g., estimate
zircon eruption ages from a distribution of zircon crystallization ages.
### Examples
```julia
tmindist = metropolis_min(2*10^5, MeltsVolcanicZirconDistribution, mu, sigma, burnin=10^5)
tmindist, t0dist = metropolis_min(2*10^5, HalfNormalDistribution, analyses, burnin=10^5)
```
"""
metropolis_min(nsteps::Integer, dist::Collection, data::Collection{<:Measurement}; kwargs...) = metropolis_min(nsteps, dist, val.(data), err.(data); kwargs...)
function metropolis_min(nsteps::Integer, dist::Collection, mu::Collection, sigma::Collection; kwargs...)
# Allocate ouput array
tmindist = Array{float(eltype(mu))}(undef,nsteps)
# Run Metropolis sampler
return metropolis_min!(tmindist, nsteps, dist, mu, sigma; kwargs...)
end
function metropolis_min(nsteps::Integer, dist::Collection{T}, analyses::Collection{UPbAnalysis{T}}; kwargs...) where {T}
# Allocate ouput arrays
tmindist = Array{T}(undef,nsteps)
t0dist = Array{T}(undef,nsteps)
# Run Metropolis sampler
metropolis_min!(tmindist, t0dist, nsteps, dist, analyses; kwargs...)
return tmindist, t0dist
end
"""
```julia
metropolis_min!(tmindist::DenseArray, nsteps::Integer, dist::Collection, mu::AbstractArray, sigma::AbstractArray; burnin::Integer=0)
metropolis_min!(tmindist::DenseArray, t0dist::DenseArray, nsteps::Integer, dist::Collection, analyses::Collection{<:UPbAnalysis}; burnin::Integer=0) where {T}
```
In-place (non-allocating) version of `metropolis_min`, fills existing array `tmindist`.
Run a Metropolis sampler to estimate the minimum of a finite-range source
distribution `dist` using samples drawn from that distribution -- e.g., estimate
zircon eruption ages from a distribution of zircon crystallization ages.
### Examples
```julia
metropolis_min!(tmindist, 2*10^5, MeltsVolcanicZirconDistribution, mu, sigma, burnin=10^5)
```
"""
function metropolis_min!(tmindist::DenseArray, nsteps::Integer, dist::Collection, mu::AbstractArray, sigma::AbstractArray; burnin::Integer=0)
# standard deviation of the proposal function is stepfactor * last step; this is tuned to optimize accetance probability at 50%
stepfactor = 2.9
# Sort the dataset from youngest to oldest
sI = sortperm(mu)
mu_sorted = mu[sI] # Sort means
sigma_sorted = sigma[sI] # Sort uncertainty
youngest, oldest = first(mu_sorted), last(mu_sorted)
# Step sigma for Gaussian proposal distributions
dt = oldest - youngest + first(sigma_sorted) + last(sigma_sorted)
tmin_step = dt / length(mu)
tmax_step = dt / length(mu)
# Use oldest and youngest zircons for initial proposal
tminₚ = tmin = youngest - first(sigma_sorted)
tmaxₚ = tmax = oldest + last(sigma_sorted)
# Log likelihood of initial proposal
llₚ = ll = dist_ll(dist, mu_sorted, sigma_sorted, tmin, tmax)
# Burnin
for i=1:burnin
# Adjust upper or lower bounds
tminₚ, tmaxₚ = tmin, tmax
r = rand()
(r < 0.5) && (tmaxₚ += tmin_step*randn())
(r > 0.5) && (tminₚ += tmax_step*randn())
# Flip bounds if reversed
(tminₚ > tmaxₚ) && ((tminₚ, tmaxₚ) = (tmaxₚ, tminₚ))
# Calculate log likelihood for new proposal
llₚ = dist_ll(dist, mu_sorted, sigma_sorted, tminₚ, tmaxₚ)
# Decide to accept or reject the proposal
if log(rand()) < (llₚ-ll)
if tminₚ != tmin
tmin_step = abs(tminₚ-tmin)*stepfactor
end
if tmaxₚ != tmax
tmax_step = abs(tmaxₚ-tmax)*stepfactor
end
ll = llₚ
tmin = tminₚ
tmax = tmaxₚ
end
end
# Step through each of the N steps in the Markov chain
@inbounds for i in eachindex(tmindist)
# Adjust upper or lower bounds
tminₚ, tmaxₚ = tmin, tmax
r = rand()
(r < 0.5) && (tmaxₚ += tmin_step*randn())
(r > 0.5) && (tminₚ += tmax_step*randn())
# Flip bounds if reversed
(tminₚ > tmaxₚ) && ((tminₚ, tmaxₚ) = (tmaxₚ, tminₚ))
# Calculate log likelihood for new proposal
llₚ = dist_ll(dist, mu_sorted, sigma_sorted, tminₚ, tmaxₚ)
# Decide to accept or reject the proposal
if log(rand()) < (llₚ-ll)
if tminₚ != tmin
tmin_step = abs(tminₚ-tmin)*stepfactor
end
if tmaxₚ != tmax
tmax_step = abs(tmaxₚ-tmax)*stepfactor
end
ll = llₚ
tmin = tminₚ
tmax = tmaxₚ
end
tmindist[i] = tmin
end
return tmindist
end
function metropolis_min!(tmindist::DenseArray{T}, t0dist::DenseArray{T}, nsteps::Integer, dist::Collection{T}, analyses::Collection{UPbAnalysis{T}}; burnin::Integer=0, t0prior=Uniform(0,minimum(age68.(analyses))), lossprior=Uniform(0,100)) where {T}
# standard deviation of the proposal function is stepfactor * last step; this is tuned to optimize accetance probability at 50%
stepfactor = 2.9
# Sort the dataset from youngest to oldest
# These quantities will be used more than once
t0ₚ = t0 = 0.0
ellipses = Ellipse.(analyses)
ages68 = log.(one(T) .+ (ellipses .|> e->e.y₀))./val(λ238U)
ages = similar(ellipses, Measurement{T})
@. ages = upperintercept(t0ₚ, ellipses)
youngest = minimum(ages)
oldest = maximum(ages)
t0step = youngest.val/50
# t0prior = Uniform(0, youngest.val)
t0prior = truncated(t0prior, 0, minimum(age68.(analyses)))
lossprior = truncated(lossprior, 0, 100)
# Initial step sigma for Gaussian proposal distributions
dt = sqrt((oldest.val - youngest.val)^2 + oldest.err^2 + youngest.err^2)
tmin_step = tmax_step = dt / length(analyses)
# Use oldest and youngest zircons for initial proposal
tminₚ = tmin = val(youngest)
tmaxₚ = tmax = val(oldest)
# Log likelihood of initial proposal
ll = dist_ll(dist, ages, tmin, tmax) + logpdf(t0prior, t0)
for i in eachindex(ages, ages68)
loss = 100*max(one(T) - (ages68[i] - t0) / (val(ages[i]) - t0), zero(T))
ll += logpdf(lossprior, loss)
end
llₚ = ll
# Burnin
for i = 1:burnin
tminₚ, tmaxₚ, t0ₚ = tmin, tmax, t0
# Adjust upper or lower bounds, or Pb-loss time
r = rand()
if r < 0.35
tminₚ += tmin_step * randn()
elseif r < 0.70
tmaxₚ += tmax_step * randn()
else
t0ₚ += t0step * randn()
end
# Flip bounds if reversed
(tminₚ > tmaxₚ) && ((tminₚ, tmaxₚ) = (tmaxₚ, tminₚ))
# Calculate log likelihood for new proposal
@. ages = upperintercept(t0ₚ, ellipses)
llₚ = dist_ll(dist, ages, tminₚ, tmaxₚ)
llₚ += logpdf(t0prior, t0ₚ)
for i in eachindex(ages, ages68)
loss = 100*max(one(T) - (ages68[i] - t0ₚ) / (val(ages[i]) - t0ₚ), zero(T))
llₚ += logpdf(lossprior, loss)
end
# Decide to accept or reject the proposal
if log(rand()) < (llₚ - ll)
if tminₚ != tmin
tmin_step = abs(tminₚ - tmin) * stepfactor
end
if tmaxₚ != tmax
tmax_step = abs(tmaxₚ - tmax) * stepfactor
end
ll = llₚ
tmin = tminₚ
tmax = tmaxₚ
t0 = t0ₚ
end
end
# Step through each of the N steps in the Markov chain
@inbounds for i in eachindex(tmindist, t0dist)
tminₚ, tmaxₚ, t0ₚ = tmin, tmax, t0
# Adjust upper or lower bounds, or Pb-loss time
r = rand()
if r < 0.35
tminₚ += tmin_step * randn()
elseif r < 0.70
tmaxₚ += tmax_step * randn()
else
t0ₚ += t0step * randn()
end
# Flip bounds if reversed
(tminₚ > tmaxₚ) && ((tminₚ, tmaxₚ) = (tmaxₚ, tminₚ))
# Calculate log likelihood for new proposal
@. ages = upperintercept(t0ₚ, ellipses)
llₚ = dist_ll(dist, ages, tminₚ, tmaxₚ)
llₚ += logpdf(t0prior, t0ₚ)
for i in eachindex(ages, ages68)
loss = 100*max(one(T) - (ages68[i] - t0ₚ) / (val(ages[i]) - t0ₚ), zero(T))
llₚ += logpdf(lossprior, loss)
end
# Decide to accept or reject the proposal
if log(rand()) < (llₚ - ll)
if tminₚ != tmin
tmin_step = abs(tminₚ - tmin) * stepfactor
end
if tmaxₚ != tmax
tmax_step = abs(tmaxₚ - tmax) * stepfactor
end
ll = llₚ
tmin = tminₚ
tmax = tmaxₚ
t0 = t0ₚ
end
tmindist[i] = tmin
t0dist[i] = t0
end
return tmindist
end
"""
```julia
metropolis_minmax(nsteps::Integer, dist::Collection, data::Collection{<:Measurement}; burnin::Integer=0)
metropolis_minmax(nsteps::Integer, dist::AbstractArray, data::AbstractArray, uncert::AbstractArray; burnin::Integer=0)
```
Run a Metropolis sampler to estimate the extrema of a finite-range source
distribution `dist` using samples drawn from that distribution -- e.g.,
estimate zircon saturation and eruption ages from a distribution of zircon
crystallization ages.
### Examples
```julia
tmindist, tmaxdist, lldist, acceptancedist = metropolis_minmax(2*10^5, MeltsVolcanicZirconDistribution, mu, sigma, burnin=10^5)
```
"""
metropolis_minmax(nsteps::Integer, dist::Collection, data::Collection{<:Measurement}; kwargs...) = metropolis_minmax(nsteps, dist, val.(data), err.(data); kwargs...)
function metropolis_minmax(nsteps::Integer, dist::Collection, mu::AbstractArray, sigma::AbstractArray; kwargs...)
# Allocate ouput arrays
acceptancedist = falses(nsteps)
lldist = Array{float(eltype(dist))}(undef,nsteps)
tmaxdist = Array{float(eltype(mu))}(undef,nsteps)
tmindist = Array{float(eltype(mu))}(undef,nsteps)
# Run metropolis sampler
return metropolis_minmax!(tmindist, tmaxdist, lldist, acceptancedist, nsteps, dist, mu, sigma; kwargs...)
end
function metropolis_minmax(nsteps::Integer, dist::Collection{T}, analyses::Collection{<:UPbAnalysis{T}}; kwargs...) where T
# Allocate ouput arrays
acceptancedist = falses(nsteps)
lldist = Array{T}(undef,nsteps)
t0dist = Array{T}(undef,nsteps)
tmaxdist = Array{T}(undef,nsteps)
tmindist = Array{T}(undef,nsteps)
# Run metropolis sampler
return metropolis_minmax!(tmindist, tmaxdist, t0dist, lldist, acceptancedist, nsteps, dist, analyses; kwargs...)
end
"""
```julia
metropolis_minmax!(tmindist, tmaxdist, lldist, acceptancedist, nsteps::Integer, dist::AbstractArray, data::AbstractArray, uncert::AbstractArray; burnin::Integer=0)
metropolis_minmax!(tmindist, tmaxdist, t0dist, lldist, acceptancedist, nsteps::Integer, dist::Collection, analyses::Collection{<:UPbAnalysis}; burnin::Integer=0)
```
In-place (non-allocating) version of `metropolis_minmax`, filling existing arrays
Run a Metropolis sampler to estimate the extrema of a finite-range source
distribution `dist` using samples drawn from that distribution -- e.g.,
estimate zircon saturation and eruption ages from a distribution of zircon
crystallization ages.
### Examples
```julia
metropolis_minmax!(tmindist, tmaxdist, lldist, acceptancedist, 2*10^5, MeltsVolcanicZirconDistribution, mu, sigma, burnin=10^5)
```
"""
function metropolis_minmax!(tmindist::DenseArray, tmaxdist::DenseArray, lldist::DenseArray, acceptancedist::BitVector, nsteps::Integer, dist::Collection, mu::AbstractArray, sigma::AbstractArray; burnin::Integer=0)
# standard deviation of the proposal function is stepfactor * last step; this is tuned to optimize accetance probability at 50%
stepfactor = 2.9
# Sort the dataset from youngest to oldest
sI = sortperm(mu)
mu_sorted = mu[sI] # Sort means
sigma_sorted = sigma[sI] # Sort uncertainty
youngest, oldest = first(mu_sorted), last(mu_sorted)
# Step sigma for Gaussian proposal distributions
dt = oldest - youngest + first(sigma_sorted) + last(sigma_sorted)
tmin_step = tmax_step = dt / length(mu)
# Use oldest and youngest zircons for initial proposal
tminₚ = tmin = youngest - first(sigma_sorted)
tmaxₚ = tmax = oldest + last(sigma_sorted)
# Log likelihood of initial proposal
llₚ = ll = dist_ll(dist, mu_sorted, sigma_sorted, tmin, tmax)
# Burnin
for i=1:nsteps
# Adjust upper or lower bounds
tminₚ, tmaxₚ = tmin, tmax
r = rand()
(r < 0.5) && (tmaxₚ += tmin_step*randn())
(r > 0.5) && (tminₚ += tmax_step*randn())
# Flip bounds if reversed
(tminₚ > tmaxₚ) && ((tminₚ, tmaxₚ) = (tmaxₚ, tminₚ))
# Calculate log likelihood for new proposal
llₚ = dist_ll(dist, mu_sorted, sigma_sorted, tminₚ, tmaxₚ)
# Decide to accept or reject the proposal
if log(rand()) < (llₚ-ll)
if tminₚ != tmin
tmin_step = abs(tminₚ-tmin)*stepfactor
end
if tmaxₚ != tmax
tmax_step = abs(tmaxₚ-tmax)*stepfactor
end
ll = llₚ
tmin = tminₚ
tmax = tmaxₚ
end
end
# Step through each of the N steps in the Markov chain
@inbounds for i in eachindex(tmindist, tmaxdist, lldist, acceptancedist)
# Adjust upper or lower bounds
tminₚ, tmaxₚ = tmin, tmax
r = rand()
(r < 0.5) && (tmaxₚ += tmin_step*randn())
(r > 0.5) && (tminₚ += tmax_step*randn())
# Flip bounds if reversed
(tminₚ > tmaxₚ) && ((tminₚ, tmaxₚ) = (tmaxₚ, tminₚ))
# Calculate log likelihood for new proposal
llₚ = dist_ll(dist, mu_sorted, sigma_sorted, tminₚ, tmaxₚ)
# Decide to accept or reject the proposal
if log(rand()) < (llₚ-ll)
if tminₚ != tmin
tmin_step = abs(tminₚ-tmin)*stepfactor
end
if tmaxₚ != tmax
tmax_step = abs(tmaxₚ-tmax)*stepfactor
end
ll = llₚ
tmin = tminₚ
tmax = tmaxₚ
acceptancedist[i]=true
end
tmindist[i] = tmin
tmaxdist[i] = tmax
lldist[i] = ll
end
return tmindist, tmaxdist, lldist, acceptancedist
end
function metropolis_minmax!(tmindist::DenseArray{T}, tmaxdist::DenseArray{T}, t0dist::DenseArray{T}, lldist::DenseArray{T}, acceptancedist::BitVector, nsteps::Integer, dist::Collection{T}, analyses::Collection{UPbAnalysis{T}}; burnin::Integer=0) where {T}
# standard deviation of the proposal function is stepfactor * last step; this is tuned to optimize accetance probability at 50%
stepfactor = 2.9
# Sort the dataset from youngest to oldest
# These quantities will be used more than once
t0ₚ = t0 = 0.0
ellipses = Ellipse.(analyses)
ages = similar(ellipses, Measurement{T})
@. ages = upperintercept(t0ₚ, ellipses)
youngest = minimum(ages)
oldest = maximum(ages)
t0step = youngest.val/50
t0prior = Uniform(0, youngest.val)
# Initial step sigma for Gaussian proposal distributions
dt = sqrt((oldest.val - youngest.val)^2 + oldest.err^2 + youngest.err^2)
tmin_step = tmax_step = dt / length(analyses)
# Use oldest and youngest zircons for initial proposal
tminₚ = tmin = val(youngest)
tmaxₚ = tmax = val(oldest)
# Log likelihood of initial proposal
ll = llₚ = dist_ll(dist, ages, tmin, tmax) + logpdf(t0prior, t0)
# Burnin
for i = 1:burnin
tminₚ, tmaxₚ, t0ₚ = tmin, tmax, t0
# Adjust upper or lower bounds, or Pb-loss time
r = rand()
if r < 0.35
tminₚ += tmin_step * randn()
elseif r < 0.70
tmaxₚ += tmax_step * randn()
else
t0ₚ += t0step * randn()
end
# Flip bounds if reversed
(tminₚ > tmaxₚ) && ((tminₚ, tmaxₚ) = (tmaxₚ, tminₚ))
# Calculate log likelihood for new proposal
@. ages = upperintercept(t0ₚ, ellipses)
llₚ = dist_ll(dist, ages, tminₚ, tmaxₚ)
llₚ += logpdf(t0prior, t0ₚ)
# Decide to accept or reject the proposal
if log(rand()) < (llₚ - ll)
if tminₚ != tmin
tmin_step = abs(tminₚ - tmin) * stepfactor
end
if tmaxₚ != tmax
tmax_step = abs(tmaxₚ - tmax) * stepfactor
end
ll = llₚ
tmin = tminₚ
tmax = tmaxₚ
t0 = t0ₚ
end
end
# Step through each of the N steps in the Markov chain
@inbounds for i in eachindex(tmindist, t0dist)
tminₚ, tmaxₚ, t0ₚ = tmin, tmax, t0
# Adjust upper or lower bounds, or Pb-loss time
r = rand()
if r < 0.35
tminₚ += tmin_step * randn()
elseif r < 0.70
tmaxₚ += tmax_step * randn()
else
t0ₚ += t0step * randn()
end
# Flip bounds if reversed
(tminₚ > tmaxₚ) && ((tminₚ, tmaxₚ) = (tmaxₚ, tminₚ))
# Calculate log likelihood for new proposal
@. ages = upperintercept(t0ₚ, ellipses)
llₚ = dist_ll(dist, ages, tminₚ, tmaxₚ)
llₚ += logpdf(t0prior, t0ₚ)
# Decide to accept or reject the proposal
if log(rand()) < (llₚ - ll)
if tminₚ != tmin
tmin_step = abs(tminₚ - tmin) * stepfactor
end
if tmaxₚ != tmax
tmax_step = abs(tmaxₚ - tmax) * stepfactor
end
ll = llₚ
tmin = tminₚ
tmax = tmaxₚ
t0 = t0ₚ
acceptancedist[i]=true
end
tmindist[i] = tmin
tmaxdist[i] = tmax
t0dist[i] = t0
lldist[i] = ll
end
return tmindist, tmaxdist, t0dist, lldist, acceptancedist
end
| Isoplot | https://github.com/JuliaGeochronology/Isoplot.jl.git |
|
[
"MIT"
] | 0.3.6 | b9a419e46fe4516f3c0b52041d84e2bb5be9cb81 | code | 10056 | using SpecialFunctions: erfc
"""
Apply Chauvenet's criterion to a set of data to identify outliers.
The function calculates the z-scores of the data points, and then calculates the probability `p` of observing a value as extreme as the z-score under the assumption of normal distribution.
It then applies Chauvenet's criterion, marking any data point as an outlier if `2 * N * p < 1.0`, where `N` is the total number of data points.
"""
function chauvenet_func(μ::Vector{T}, σ::Vector) where {T}
mean_val = mean(μ)
N = length(μ)
z_scores = abs.(μ .- mean_val) ./ σ
p = 0.5 * erfc.(z_scores ./ sqrt(2.0))
criterion = 2 * N * p
selected_data = criterion .>= 1.0
# add @info about number of outliers
@info "Excluding $(N - sum(selected_data)) outliers based on Chauvenet's criterion."
return selected_data
end
## --- Weighted means
"""
```julia
wμ, wσ, mswd = wmean(μ, σ; corrected=true, chauvenet=false)
wμ ± wσ, mswd = wmean(μ ± σ; corrected=true, chauvenet=false)
```
The weighted mean, with or without the "geochronologist's MSWD correction" to uncertainty.
You may specify your means and standard deviations either as separate vectors `μ` and `σ`,
or as a single vector `x` of `Measurement`s equivalent to `x = μ .± σ`
In all cases, `σ` is assumed to reported as _actual_ sigma (i.e., 1-sigma).
If `corrected=true`, the resulting uncertainty of the weighted mean is expanded by a factor
of `sqrt(mswd)` to attempt to account for dispersion dispersion when the MSWD is greater than `1`
If `chauvenet=true`, outliers will be removed before the computation of the weighted mean
using Chauvenet's criterion.
### Examples
```julia
julia> x = randn(10)
10-element Vector{Float64}:
0.4612989881720301
-0.7255529837975242
-0.18473979056481055
-0.4176427262202118
-0.21975911391551833
-1.6250003193791873
-1.6185557291787287
0.25315988825847513
-0.4979804844182867
1.3565281078086726
julia> y = ones(10);
julia> wmean(x, y)
(-0.321824416323509, 0.31622776601683794, 0.8192171477885678)
julia> wmean(x .± y)
(-0.32 ± 0.32, 0.8192171477885678)
julia> wmean(x .± y./10)
(-0.322 ± 0.032, 81.9217147788568)
julia> wmean(x .± y./10, corrected=true)
(-0.32 ± 0.29, 81.9217147788568)
```
"""
function wmean(μ::Collection1D{T}, σ::Collection1D{T}; corrected::Bool=true, chauvenet::Bool=false) where {T}
if chauvenet
not_outliers = chauvenet_func(μ, σ)
μ = μ[not_outliers]
σ = σ[not_outliers]
end
sum_of_values = sum_of_weights = χ² = zero(float(T))
@inbounds for i in eachindex(μ,σ)
σ² = σ[i]^2
sum_of_values += μ[i] / σ²
sum_of_weights += one(T) / σ²
end
wμ = sum_of_values / sum_of_weights
@inbounds for i in eachindex(μ,σ)
χ² += (μ[i] - wμ)^2 / σ[i]^2
end
mswd = χ² / (length(μ)-1)
wσ = if corrected
sqrt(max(mswd,1) / sum_of_weights)
else
sqrt(1 / sum_of_weights)
end
return wμ, wσ, mswd
end
function wmean(x::AbstractVector{Measurement{T}}; corrected::Bool=true, chauvenet::Bool=false) where {T}
if chauvenet
μ, σ = val.(x), err.(x)
not_outliers = chauvenet_func(μ, σ)
x = x[not_outliers]
end
wμ, wσ, mswd = wmean(val.(x), Measurements.cov(x); corrected)
return wμ ± wσ, mswd
end
# Full covariance matrix method
function wmean(x::AbstractVector{T}, C::AbstractMatrix{T}; corrected::Bool=true) where T
# Weighted mean and variance, full matrix method
J = ones(length(x))
σ²ₓ̄ = 1/(J'/C*J)
x̄ = σ²ₓ̄*(J'/C*x)
# MSWD, full matrix method
r = x .- x̄
χ² = r'/C*r
mswd = χ² / (length(x)-1)
# Optional: expand standard error by sqrt of mswd, if mswd > 1
corrected && (σ²ₓ̄ *= max(mswd,1))
return x̄, sqrt(σ²ₓ̄), mswd
end
# Legacy methods, for backwards compatibility
awmean(args...) = wmean(args...; corrected=false)
gwmean(args...) = wmean(args...; corrected=true)
distwmean(x...; corrected::Bool=true) = distwmean(x; corrected)
function distwmean(x::NTuple{N, <:AbstractVector}; corrected::Bool=true) where {N}
σₓ = vstd.(x)
wₓ = 1 ./ σₓ.^2
wₜ = sum(wₓ)
c = similar(first(x))
@inbounds for i in eachindex(x...)
c[i] = sum(getindex.(x, i) .* wₓ)/wₜ
if corrected
c[i] += sqrt(sum(wₓ.*abs2.(getindex.(x,i).-c[i]))/(wₜ*(N-1))) * randn()
end
end
return c
end
"""
```julia
mswd(μ, σ)
mswd(μ ± σ)
```
Return the Mean Square of Weighted Deviates (AKA the reduced chi-squared
statistic) of a dataset with values `x` and one-sigma uncertainties `σ`
### Examples
```julia
julia> x = randn(10)
10-element Vector{Float64}:
-0.977227094347237
2.605603343967434
-0.6869683962845955
-1.0435377148872693
-1.0171093080088411
0.12776158554629713
-0.7298235147864734
-0.3164914095249262
-1.44052961622873
0.5515207382660242
julia> mswd(x, ones(10))
1.3901517474017941
```
"""
function mswd(μ::Collection{T}, σ::Collection; chauvenet=false) where {T}
if chauvenet
not_outliers = chauvenet_func(μ, σ)
μ = μ[not_outliers]
σ = σ[not_outliers]
end
sum_of_values = sum_of_weights = χ² = zero(float(T))
@inbounds for i in eachindex(μ,σ)
w = 1 / σ[i]^2
sum_of_values += w * μ[i]
sum_of_weights += w
end
wx = sum_of_values / sum_of_weights
@inbounds for i in eachindex(μ,σ)
χ² += (μ[i] - wx)^2 / σ[i]^2
end
return χ² / (length(μ)-1)
end
function mswd(x::AbstractVector{Measurement{T}}; chauvenet=false) where {T}
if chauvenet
not_outliers = chauvenet_func(val.(x), err.(x))
x = x[not_outliers]
end
wμ, wσ, mswd = wmean(val.(x), Measurements.cov(x))
return mswd
end
## --- Simple linear regression
"""
```julia
(a,b) = lsqfit(x::AbstractVector, y::AbstractVector)
```
Returns the coefficients for a simple linear least-squares regression of
the form `y = a + bx`
### Examples
```
julia> a, b = lsqfit(1:10, 1:10)
2-element Vector{Float64}:
-1.19542133983862e-15
1.0
julia> isapprox(a, 0, atol = 1e-12)
true
julia> isapprox(b, 1, atol = 1e-12)
true
```
"""
lsqfit(x::Collection{<:Number}, y::Collection{<:Number}) = lsqfit(x, collect(y))
function lsqfit(x::Collection{T}, y::AbstractVector{<:Number}) where {T<:Number}
A = Array{T}(undef, length(x), 2)
A[:,1] .= one(T)
A[:,2] .= x
return A\y
end
# Identical to the one in StatGeochemBase
## -- The York (1968) two-dimensional linear regression with x and y uncertainties
# as commonly used in isochrons
# Custom type to hold York fit resutls
struct YorkFit{T<:Number}
intercept::Measurement{T}
slope::Measurement{T}
xm::T
ym::Measurement{T}
mswd::T
end
"""
```julia
yorkfit(x, σx, y, σy, [r])
yorkfit(x::Vector{<:Measurement}, y::Vector{<:Measurement}, [r])
yorkfit(d::Vector{<:Analysis})
```
Uses the York (1968) two-dimensional least-squares fit to calculate `a`, `b`,
and uncertanties `σa`, `σb` for the equation `y = a + bx`, given `x`, `y`,
uncertaintes `σx`, and `σy`, and optially covarances `r`.
For further reference, see:
York, Derek (1968) "Least squares fitting of a straight line with correlated errors"
Earth and Planetary Science Letters 5, 320-324. doi: 10.1016/S0012-821X(68)80059-7
### Examples
```julia
julia> x = (1:100) .+ randn.();
julia> y = 2*(1:100) .+ randn.();
julia> yorkfit(x, ones(100), y, ones(100))
YorkFit{Float64}:
Least-squares linear fit of the form y = a + bx where
intercept a : -0.29 ± 0.2 (1σ)
slope b : 2.0072 ± 0.0035 (1σ)
MSWD : 0.8136665223891004
```
"""
yorkfit(x::Vector{Measurement{T}}, y::Vector{Measurement{T}}, r=zero(T); iterations=10) where {T} = yorkfit(val.(x), err.(x), val.(y), err.(y), r; iterations)
function yorkfit(d::Collection{<:Analysis{T}}; iterations=10) where {T}
# Using NTuples instead of Arrays here avoids allocations and should be
# much more efficient for relatively small N, but could be less efficient
# for large N (greater than ~100)
x = ntuple(i->d[i].μ[1], length(d))
y = ntuple(i->d[i].μ[2], length(d))
σx = ntuple(i->d[i].σ[1], length(d))
σy = ntuple(i->d[i].σ[2], length(d))
r = ntuple(i->d[i].Σ[1,2], length(d))
yorkfit(x, σx, y, σy, r; iterations)
end
function yorkfit(x, σx, y, σy, r=vcor(x,y); iterations=10)
## For an initial estimate of slope and intercept, calculate the
# ordinary least-squares fit for the equation y=a+bx
a, b = lsqfit(x, y)
# Prepare for York fit
∅ = zero(float(eltype(x)))
ωx = 1.0 ./ σx.^2 # x weights
ωy = 1.0 ./ σy.^2 # y weights
α = sqrt.(ωx .* ωy)
## Perform the York fit (must iterate)
Z = @. ωx*ωy / (b^2*ωy + ωx - 2*b*r*α)
x̄ = vsum(Z.*x) / vsum(Z)
ȳ = vsum(Z.*y) / vsum(Z)
U = x .- x̄
V = y .- ȳ
if Z isa NTuple
Z = collect(Z)
U = collect(U)
V = collect(V)
end
sV = @. Z^2 * V * (U/ωy + b*V/ωx - r*V/α)
sU = @. Z^2 * U * (U/ωy + b*V/ωx - b*r*U/α)
b = vsum(sV) / vsum(sU)
a = ȳ - b * x̄
for _ in 2:iterations
@. Z = ωx*ωy / (b^2*ωy + ωx - 2*b*r*α)
ΣZ, ΣZx, ΣZy = ∅, ∅, ∅
@inbounds for i in eachindex(Z)
ΣZ += Z[i]
ΣZx += Z[i] * x[i]
ΣZy += Z[i] * y[i]
end
x̄ = ΣZx / ΣZ
ȳ = ΣZy / ΣZ
@. U = x - x̄
@. V = y - ȳ
@. sV = Z^2 * V * (U/ωy + b*V/ωx - r*V/α)
@. sU = Z^2 * U * (U/ωy + b*V/ωx - b*r*U/α)
b = sum(sV) / sum(sU)
a = ȳ - b * x̄
end
## 4. Calculate uncertainties and MSWD
β = @. Z * (U/ωy + b*V/ωx - (b*U+V)*r/α)
u = x̄ .+ β
v = ȳ .+ b.*β
xm = vsum(Z.*u)./vsum(Z)
ym = vsum(Z.*v)./vsum(Z)
σb = sqrt(1.0 ./ vsum(Z .* (u .- xm).^2))
σa = sqrt(1.0 ./ vsum(Z) + xm.^2 .* σb.^2)
σym = sqrt(1.0 ./ vsum(Z))
# MSWD (reduced chi-squared) of the fit
mswd = 1.0 ./ length(x) .* vsum(@. (y - a - b*x)^2 / (σy^2 + b^2 * σx^2) )
## Results
return YorkFit(a ± σa, b ± σb, xm, ym ± σym, mswd)
end
| Isoplot | https://github.com/JuliaGeochronology/Isoplot.jl.git |
|
[
"MIT"
] | 0.3.6 | b9a419e46fe4516f3c0b52041d84e2bb5be9cb81 | code | 894 |
# Custom pretty-printing for York fit results
function Base.show(io::IO, ::MIME"text/plain", x::YorkFit{T}) where T
print(io, """YorkFit{$T}:
Least-squares linear fit of the form y = a + bx with
intercept: $(x.intercept) (1σ)
slope : $(x.slope) (1σ)
MSWD : $(x.mswd)
"""
)
end
function Base.show(io::IO, ::MIME"text/plain", x::CI{T}) where T
print(io, """CI{$T} $x
mean : $(x.mean)
sigma : $(x.sigma)
median: $(x.median)
lower : $(x.lower)
upper : $(x.upper)
"""
)
end
function Base.print(io::IO, x::CI)
l = round(x.mean - x.lower, sigdigits=2)
u = round(x.upper - x.mean, sigdigits=2)
nodata = any(isnan, (x.mean, x.upper, x.lower))
d = nodata ? 0 : floor(Int, log10(abs(x.mean))) - floor(Int, log10(max(abs(l),abs(u))))
m = round(x.mean, sigdigits=3+d)
print(io, "$m +$u/-$l")
end
| Isoplot | https://github.com/JuliaGeochronology/Isoplot.jl.git |
|
[
"MIT"
] | 0.3.6 | b9a419e46fe4516f3c0b52041d84e2bb5be9cb81 | code | 19319 | module BaseTests
using Test, Statistics
using Measurements
using Isoplot
@testset "Show" begin
yf = Isoplot.YorkFit(1±1, 1±1, 0.0, 1±1, 1.0)
@test display(yf) != NaN
ci = CI(1:10)
@test ci == CI{Float64}(5.5, 3.0276503540974917, 5.5, 1.225, 9.775)
@test "$ci" === "5.5 +4.3/-4.3"
@test display(ci) != NaN
ci = CI(randn(100))
@test display(ci) != NaN
end
@testset "General" begin
@test Age(0) isa Age{Float64}
@test Age(0, 1) isa Age{Float64}
@test Interval(0, 1) isa Interval{Float64}
@test Interval(0, 1) === Interval(0,0, 1,0)
@test min(Interval(0, 1)) isa Age{Float64}
@test max(Interval(0, 1)) isa Age{Float64}
@test min(Interval(0, 1)) === Age(0,0) === Age(0)
@test max(Interval(0, 1)) === Age(1,0) === Age(1)
@test Isoplot.val(1) === 1
@test Isoplot.err(1) === 0
@test Isoplot.val(1±1) === 1.0
@test Isoplot.err(1±1) === 1.0
ci = CI(1:10)
@test Isoplot.val(ci) ≈ 5.5
@test Isoplot.err(ci) ≈ 3.0276503540974917
a = Age(ci)
@test Isoplot.val(a) ≈ 5.5
@test Isoplot.err(a) ≈ 3.0276503540974917
end
@testset "U-Pb" begin
r75 = 22.6602
σ75 = 0.017516107998
r68 = 0.408643
σ68 = 0.0001716486532565
corr = 0.831838
d1 = UPbAnalysis(r75, σ75, r68, σ68, corr)
d2 = UPbAnalysis([22.6602, 0.408643], [0.00030681403939759964 2.501017729814154e-6; 2.501017729814154e-6 2.9463260164770177e-8])
d3 = UPbAnalysis([22.6602, 0.408643], [0.017516107998, 0.0001716486532565], [0.00030681403939759964 2.501017729814154e-6; 2.501017729814154e-6 2.9463260164770177e-8])
@test d1 isa UPbAnalysis{Float64}
@test d2 isa UPbAnalysis{Float64}
@test d3 isa UPbAnalysis{Float64}
@test d1.μ ≈ d2.μ ≈ d3.μ
@test d1.σ ≈ d2.σ ≈ d3.σ
@test d1.Σ ≈ d2.Σ ≈ d3.Σ
@test !isnan(d1)
a75, a68 = age(d1)
@test a75.val ≈ 3209.725483265418
@test a75.err ≈ 1.9420875256761048
@test a68.val ≈ 2208.7076248184017
@test a68.err ≈ 1.422824131349332
@test age68(d1) == a68
@test age75(d1) == a75
@test discordance(d1) ≈ 31.187024051310136
@test rand(d1) isa Vector{Float64}
@test rand(d1, 10) isa Matrix{Float64}
@test rand(d1, 5, 5) isa Matrix{Vector{Float64}}
x = [22.70307499779583, 22.681635852743682, 22.63876085494785, 22.61732500220417, 22.638764147256317, 22.68163914505215, 22.70307499779583]
y = [0.4089925091091875, 0.40901969166358015, 0.4086701825543926, 0.40829349089081246, 0.4082663083364198, 0.4086158174456074, 0.4089925091091875]
e1 = Ellipse(d1, npoints=7)
@test e1 isa Isoplot.Ellipse
@test e1.x ≈ x
@test e1.y ≈ y
tₗₗ = 35
ui = upperintercept(tₗₗ ± 10, d1)
@test ui == 3921.343026090256 ± 2.745595368456398
ui = upperintercept(tₗₗ, d1)
@test ui == 3921.343026090256 ± 0.7241111646504936
N = 10000
uis = upperintercept(tₗₗ, d1, N)
@test uis isa Vector{Float64}
@test mean(uis) ≈ ui.val atol=(4*ui.err/sqrt(N))
@test std(uis) ≈ ui.err rtol=0.03
# Test upper and lower intercepts of multiple-sample concordia arrays
d = [UPbAnalysis(22.6602, 0.0175, 0.40864, 0.00017, 0.83183)
UPbAnalysis(33.6602, 0.0175, 0.50864, 0.00017, 0.83183)]
uis = upperintercept(d, N)
@test mean(uis) ≈ 4601.82 atol=0.1
@test std(uis) ≈ 1.53 atol=0.1
lis = lowerintercept(d, N)
@test mean(lis) ≈ 1318.12 atol=0.1
@test std(lis) ≈ 2.04 atol=0.1
uis, lis = intercepts(d, N)
@test mean(uis) ≈ 4601.82 atol=0.1
@test std(uis) ≈ 1.53 atol=0.1
@test mean(lis) ≈ 1318.12 atol=0.1
@test std(lis) ≈ 2.04 atol=0.1
# Stacey-Kramers common Pb model
@test stacey_kramers(0) == (18.7, 15.628)
@test stacey_kramers(3700) == (11.152, 12.998)
@test stacey_kramers(4567) == (9.314476625036953, 12.984667029161916)
@test stacey_kramers(5000) === (NaN, NaN)
end
@testset "Other systems" begin
μ, σ = rand(2), rand(2)
@test UThAnalysis(μ, σ) isa UThAnalysis
@test ReOsAnalysis(μ, σ) isa ReOsAnalysis
@test LuHfAnalysis(μ, σ) isa LuHfAnalysis
@test SmNdAnalysis(μ, σ) isa SmNdAnalysis
@test RbSrAnalysis(μ, σ) isa RbSrAnalysis
end
@testset "Weighted means" begin
# Weighted means
x = [-3.4699, -0.875, -1.4189, 1.2993, 1.1167, 0.8357, 0.9985, 1.2789, 0.5446, 0.5639]
σx = ones(10)/4
@test all(awmean(x, σx) .≈ (0.08737999999999996, 0.07905694150420949, 38.44179426844445))
@test all(gwmean(x, σx) .≈ (0.08737999999999996, 0.49016447665837415, 38.44179426844445))
wm, m = awmean(x .± σx)
@test wm.val ≈ 0.08737999999999996
@test wm.err ≈ 0.07905694150420949
@test m ≈ 38.44179426844445
wm, m = gwmean(x .± σx)
@test wm.val ≈ 0.08737999999999996
@test wm.err ≈ 0.49016447665837415
@test m ≈ 38.44179426844445
@test mswd(x, σx) ≈ 38.44179426844445
@test mswd(x .± σx) ≈ 38.44179426844445
σx .*= 20 # Test underdispersed data
@test gwmean(x, σx) == awmean(x, σx)
N = 10^6
c = randn(N).+50
a,b = randn(N), randn(N).+1
d = distwmean(a,b; corrected=false)
μ,σ,_ = wmean([0,1], [1,1]; corrected=false)
@test mean(d) ≈ μ atol = 0.02
@test std(d) ≈ σ atol = 0.002
d = distwmean(a,b; corrected=true)
@test mean(d) ≈ μ atol = 0.1
@test std(d) ≈ std(vcat(a,b)) atol = 0.005
b .+= 9
d = distwmean(a,b; corrected=false)
μ,σ,_ = wmean([0,10], [1,1]; corrected=false)
@test mean(d) ≈ μ atol = 0.02
@test std(d) ≈ σ atol = 0.002
d = distwmean(a,b; corrected=true)
μ,σ,_ = wmean([0,10], [1,1]; corrected=true)
@test mean(d) ≈ μ atol = 0.2
@test std(d) ≈ σ atol = 0.2
@test std(d) ≈ std(vcat(a,b)) atol = 0.02
b .+= 90
d = distwmean(a,b; corrected=false)
μ,σ,_ = wmean([0,100], [1,1]; corrected=false)
@test mean(d) ≈ μ atol = 0.2
@test std(d) ≈ σ atol = 0.02
d = distwmean(a,b; corrected=true)
μ,σ,_ = wmean([0,100], [1,1]; corrected=true)
@test mean(d) ≈ μ atol = 0.2
@test std(d) ≈ σ atol = 0.2
@test std(d) ≈ std(vcat(a,b)) atol = 0.2
d = distwmean(a,b,c; corrected=false)
μ,σ,_ = wmean([0,50,100], [1,1,1]; corrected=false)
@test mean(d) ≈ μ atol = 0.2
@test std(d) ≈ σ atol = 0.02
d = distwmean(a,b,c; corrected=true)
μ,σ,_ = wmean([0,50,100], [1,1,1]; corrected=true)
@test mean(d) ≈ μ atol = 0.2
@test std(d) ≈ σ atol = 2
a,b = 2randn(N), 3randn(N).+1
d = distwmean(a,b; corrected=false)
μ,σ,_ = wmean([0,1], [2,3]; corrected=false)
@test mean(d) ≈ μ atol = 0.05
@test std(d) ≈ σ atol = 0.005
b .+= 9
d = distwmean(a,b; corrected=false)
μ,σ,_ = wmean([0,10], [2,3]; corrected=false)
@test mean(d) ≈ μ atol = 0.05
@test std(d) ≈ σ atol = 0.005
d = distwmean(a,b; corrected=true)
μ,σ,_ = wmean([0,10], [2,3]; corrected=true)
@test mean(d) ≈ μ atol = 0.1
@test std(d) ≈ σ atol = 1
b .+= 90
d = distwmean(a,b; corrected=false)
μ,σ,_ = wmean([0,100], [2,3]; corrected=false)
@test mean(d) ≈ μ atol = 0.2
@test std(d) ≈ σ atol = 0.02
d = distwmean(a,b; corrected=true)
μ,σ,_ = wmean([0,100], [2,3]; corrected=true)
@test mean(d) ≈ μ atol = 0.2
@test std(d) ≈ σ atol = 2
d = distwmean(a,b,c; corrected=false)
μ,σ,_ = wmean([0,50,100], [2,1,3]; corrected=false)
@test mean(d) ≈ μ atol = 0.2
@test std(d) ≈ σ atol = 0.02
d = distwmean(a,b,c; corrected=true)
μ,σ,_ = wmean([0,50,100], [2,1,3]; corrected=true)
@test mean(d) ≈ μ atol = 0.2
@test std(d) ≈ σ atol = 2
# test chauvenet criterion
x = [1.2, 1.5, 1.3, 2.4, 2.0, 2.1, 1.9, 2.2, 8.0, 2.3]
xσ = [1,1,1,1,1,1,1,1,1,1.]
expected = [true, true, true, true, true, true, true, true, false, true]
@test Isoplot.chauvenet_func(x, xσ) == expected
μ,σ,MSWD = wmean(x, xσ;chauvenet=true)
@test μ ≈ 1.877777777777778
@test MSWD ≈ 0.19444444444444445
μ, MSWD = wmean((x .± xσ);chauvenet=true)
@test Isoplot.val(μ) ≈ 1.877777777777778
@test MSWD ≈ 0.19444444444444445
end
data = [1.1009 0.00093576 0.123906 0.00002849838 0.319
1.1003 0.00077021 0.123901 0.00003531178 0.415
1.0995 0.00049477 0.123829 0.00002538494 0.434
1.0992 0.00060456 0.123813 0.00003652483 0.616
1.1006 0.00071539 0.123813 0.00002228634 0.321
1.0998 0.00076986 0.123802 0.00002537941 0.418
1.0992 0.00065952 0.123764 0.00003589156 0.509
1.0981 0.00109810 0.123727 0.00003959264 0.232
1.0973 0.00052670 0.123612 0.00002966688 0.470
1.0985 0.00087880 0.123588 0.00002842524 0.341
1.0936 0.00054680 0.123193 0.00003264614 0.575
1.0814 0.00051366 0.121838 0.00003045950 0.587 ]
analyses = UPbAnalysis.(eachcol(data)...,)
@testset "Regression" begin
# Simple linear regression
ϕ = lsqfit(1:10, 1:10)
@test ϕ[1] ≈ 0 atol=1e-12
@test ϕ[2] ≈ 1 atol=1e-12
# York (1968) fit
x = [0.9304, 2.2969, 2.8047, 3.7933, 5.3853, 6.1995, 6.7479, 8.1856, 8.7423, 10.2588]
y = [0.8742, 2.1626, 3.042, 3.829, 5.0116, 5.5614, 6.7675, 7.8856, 9.6414, 10.4955]
σx = σy = ones(10)/4
yf = yorkfit(x, σx, y, σy)
@test yf isa Isoplot.YorkFit
@test yf.intercept.val ≈-0.23498964673701916
@test yf.intercept.err ≈ 0.02250863813481163
@test yf.slope.val ≈ 1.041124018512526
@test yf.slope.err ≈ 0.0035683808205783673
@test yf.mswd ≈ 1.1419901440278089
yf = yorkfit(x, σx, y, σy, zeros(length(x)))
@test yf isa Isoplot.YorkFit
@test yf.intercept.val ≈-0.2446693790977319
@test yf.intercept.err ≈ 0.2469541320914601
@test yf.slope.val ≈ 1.0428730084538775
@test yf.slope.err ≈ 0.039561084436542084
@test yf.mswd ≈ 1.1417951538670306
x = ((1:100) .+ randn.()) .± 1
y = (2*(1:100) .+ randn.()) .± 1
yf = yorkfit(x, y)
@test yf isa Isoplot.YorkFit
@test yf.intercept.val ≈ 0 atol = 2
@test yf.slope.val ≈ 2 atol = 0.1
@test yf.mswd ≈ 1 atol = 0.5
yf = yorkfit(analyses)
@test yf isa Isoplot.YorkFit
@test yf.intercept.val ≈ 0.0050701916562521515
@test yf.intercept.err ≈ 0.004099648408656529
@test yf.slope.val ≈ 0.1079872513087868
@test yf.slope.err ≈ 0.0037392146940848233
@test yf.xm ≈ 1.096376584184683
@test yf.ym.val ≈ 0.12346488538167279
@test yf.ym.err ≈ 2.235949353726133e-5
@test yf.mswd ≈ 0.41413597765872123
ui = upperintercept(analyses)
@test ui.val ≈ 752.6744316220871
@test ui.err ≈ 0.5288009504134864
li = lowerintercept(analyses)
@test li.val ≈ 115.83450556482211
@test li.err ≈ 94.4384248140631
ui, li = intercepts(analyses)
@test ui.val ≈ 752.6744316220871
@test ui.err ≈ 0.5288009504134864
@test li.val ≈ 115.83450556482211
@test li.err ≈ 94.4384248140631
wm, m = wmean(age68.(analyses[1:10]))
@test wm.val ≈ 752.2453179272093
@test wm.err ≈ 1.4781473739306696
@test m ≈ 13.15644886325888
m = mswd(age68.(analyses[1:10]))
@test m ≈ 13.15644886325888
end
@testset "Concordia Metropolis" begin
data = upperintercept.(0, analyses)
@test Isoplot.dist_ll(ones(10), data, 751, 755) ≈ -20.09136536048026
@test Isoplot.dist_ll(ones(10), data, 750, 760) ≈ -30.459633175497830
@test Isoplot.dist_ll(ones(10), data, 752, 753) ≈ -15.305463167234748
@test Isoplot.dist_ll(ones(10), data, 751, 752) ≈ -47.386667785224034
tmindist, t0dist = metropolis_min(1000, ones(10), analyses; burnin=200)
@test tmindist isa Vector{Float64}
@test mean(tmindist) ≈ 751.85 atol = 1.5
@test std(tmindist) ≈ 0.40 rtol = 0.6
@test t0dist isa Vector{Float64}
@test mean(t0dist) ≈ 80. atol = 90
@test std(t0dist) ≈ 50. rtol = 0.6
tmindist, tmaxdist, t0dist, lldist, acceptancedist = metropolis_minmax(10000, ones(10), analyses; burnin=200)
@test tmindist isa Vector{Float64}
@test mean(tmindist) ≈ 751.85 atol = 1.5
@test std(tmindist) ≈ 0.40 rtol = 0.6
@test tmaxdist isa Vector{Float64}
@test mean(tmaxdist) ≈ 753.32 atol = 1.5
@test std(tmaxdist) ≈ 0.60 rtol = 0.6
@test t0dist isa Vector{Float64}
@test mean(t0dist) ≈ 80. atol = 90
@test std(t0dist) ≈ 50. rtol = 0.6
@test lldist isa Vector{Float64}
@test acceptancedist isa BitVector
@test mean(acceptancedist) ≈ 0.6 atol=0.2
terupt = CI(tmindist)
@test terupt isa CI{Float64}
@test terupt.mean ≈ 751.85 atol = 1.5
@test terupt.sigma ≈ 0.40 rtol = 0.6
@test terupt.median ≈ 751.83 atol = 1.5
@test terupt.lower ≈ 750.56 atol = 1.5
@test terupt.upper ≈ 752.52 atol = 1.5
end
@testset "General Metropolis" begin
mu, sigma = collect(100:0.1:101), 0.01*ones(11);
@test Isoplot.dist_ll(MeltsVolcanicZirconDistribution, mu, sigma, 100,101) ≈ -3.6933372932657607
tmindist = metropolis_min(2*10^5, MeltsVolcanicZirconDistribution, mu .± sigma, burnin=10^5)
@test mean(tmindist) ≈ 99.9228 atol=0.015
tmindist, tmaxdist, lldist, acceptancedist = metropolis_minmax(2*10^5, MeltsVolcanicZirconDistribution, mu .± sigma, burnin=10^5)
@test mean(tmindist) ≈ 99.9228 atol=0.015
@test mean(tmaxdist) ≈ 101.08 atol=0.015
@test lldist isa Vector{Float64}
@test acceptancedist isa BitVector
@test mean(acceptancedist) ≈ 0.6 atol=0.2
@test mean(UniformDistribution) ≈ 1
@test mean(TriangularDistribution) ≈ 1
@test mean(HalfNormalDistribution) ≈ 1
@test mean(ExponentialDistribution) ≈ 1.03 atol=0.01
@test mean(MeltsZirconDistribution) ≈ 1 atol=0.01
@test mean(MeltsVolcanicZirconDistribution) ≈ 1 atol=0.01
end
end
module PlotsTest
using Test, Statistics
using Measurements
using Isoplot
using ImageIO, FileIO,Plots
import ..BaseTests: analyses
# Base.retry_load_extensions()
@testset "Plotting" begin
# Plot single concordia ellipse
h = plot(analyses[1], color=:blue, alpha=0.3, label="", framestyle=:box)
savefig(h, "concordia.png")
img = load("concordia.png")
@test size(img) == (400,600)
@test sum(img)/length(img) ≈ RGB{Float64}(0.8151617156862782,0.8151617156862782,0.986395212418301) rtol = 0.02
rm("concordia.png")
# Plot many concordia ellipses and concordia curve
h = plot(analyses, color=:blue, alpha=0.3, label="", framestyle=:box)
concordiacurve!(h)
savefig(h, "concordia.png")
img = load("concordia.png")
@test size(img) == (400,600)
@test sum(img)/length(img) ≈ RGB{Float64}(0.9448600653594766,0.9448600653594766,0.9658495915032675) rtol = 0.01
rm("concordia.png")
# Plot single concordia line
h = concordialine(0, 100, label="")
concordiacurve!(h)
savefig(h, "concordia.png")
img = load("concordia.png")
@test size(img) == (400,600)
@test sum(img)/length(img) ≈ RGB{Float64}(0.981812385620915,0.9832414705882352,0.9841176307189541) rtol = 0.01
rm("concordia.png")
h = concordialine(0, 100, label="", truncate=true)
concordiacurve!(h)
savefig(h, "concordia.png")
img = load("concordia.png")
@test size(img) == (400,600)
@test sum(img)/length(img) ≈ RGB{Float64}(0.981812385620915,0.9832414705882352,0.9841176307189541) rtol = 0.01
rm("concordia.png")
# Plot many single concordia lines
h = concordialine(10*randn(100).+10, 100*randn(100).+1000, label="")
concordiacurve!(h)
savefig(h, "concordia.png")
img = load("concordia.png")
@test size(img) == (400,600)
@test sum(img)/length(img) ≈ RGB{Float64}(0.966250588235294,0.966250588235294,0.966250588235294) rtol = 0.01
rm("concordia.png")
h = concordialine(10*randn(100).+10, 100*randn(100).+1000, label="", truncate=true)
concordiacurve!(h)
savefig(h, "concordia.png")
img = load("concordia.png")
@test size(img) == (400,600)
@test sum(img)/length(img) ≈ RGB{Float64}(0.966250588235294,0.966250588235294,0.966250588235294) rtol = 0.01
rm("concordia.png")
# Rank-order plot
h = rankorder(1:10, 2*ones(10), label="")
savefig(h, "rankorder.png")
img = load("rankorder.png")
@test size(img) == (400,600)
@test sum(img)/length(img) ≈ RGB{Float64}(0.9842757843137254,0.9882103758169932,0.9906218464052285) rtol = 0.01
rm("rankorder.png")
end
end
module MakieTest
using Test, Statistics
using Measurements
using Isoplot
using ImageIO, FileIO, CairoMakie
using ColorTypes
import ..BaseTests: analyses
# Base.retry_load_extensions()
@testset "Makie Plotting" begin
f = Figure()
ax = Axis(f[1,1])
plot!(analyses[1], color=(:blue,0.3))
save("concordia.png",f)
img = load("concordia.png")
@test size(img) == (900, 1200)
@test sum(img)/length(img) ≈ RGB{Float64}(0.8524913580246877,0.8524913580246877,0.9885884168482209) rtol = 0.02
rm("concordia.png")
# Plot many concordia ellipses and concordia curve
f2 = Figure()
ax2 = Axis(f2[1,1])
plot!.(analyses, color=(:blue, 0.3))
ages = age.(analyses)
concordiacurve!(minimum(ages)[1].val-5,maximum(ages)[1].val+5)
xmin, xmax, ymin, ymax = datalimits(analyses)
limits!(ax2,xmin,xmax,ymin,ymax)
save("concordia.png",f2)
img = load("concordia.png")
@test size(img) == (900, 1200)
@test sum(img)/length(img) ≈ RGB{Float64}(0.9523360547065816,0.9523360547065816,0.9661779080315414) rtol = 0.01
rm("concordia.png")
# Plot single concordia line
f3 = Figure()
ax3 = Axis(f3[1,1])
concordialine!(0, 100)
concordiacurve!(0,100)
save("concordia.png",f3)
img = load("concordia.png")
@test size(img) == (900, 1200)
@test sum(img)/length(img) ≈ RGB{Float64}(0.9845678970995279,0.9845678970995279,0.9845678970995279) rtol = 0.01
rm("concordia.png")
end
end
| Isoplot | https://github.com/JuliaGeochronology/Isoplot.jl.git |
|
[
"MIT"
] | 0.3.6 | b9a419e46fe4516f3c0b52041d84e2bb5be9cb81 | docs | 4255 | # Isoplot.jl
[![Docs][docs-dev-img]][docs-dev-url]
[![CI][ci-img]][ci-url]
[![codecov.io][codecov-img]][codecov-url]
Well someone needs to write one...
## Installation
```Julia
pkg> add Isoplot
```
## Usage
```julia
using Isoplot, Plots
# Example U-Pb dataset (MacLennan et al. 2020)
# 207/235 1σ abs 206/238 1σ abs correlation
data = [1.1009 0.00093576 0.123906 0.00002849838 0.319
1.1003 0.00077021 0.123901 0.00003531178 0.415
1.0995 0.00049477 0.123829 0.00002538494 0.434
1.0992 0.00060456 0.123813 0.00003652483 0.616
1.1006 0.00071539 0.123813 0.00002228634 0.321
1.0998 0.00076986 0.123802 0.00002537941 0.418
1.0992 0.00065952 0.123764 0.00003589156 0.509
1.0981 0.00109810 0.123727 0.00003959264 0.232
1.0973 0.00052670 0.123612 0.00002966688 0.470
1.0985 0.00087880 0.123588 0.00002842524 0.341
1.0936 0.00054680 0.123193 0.00003264614 0.575
1.0814 0.00051366 0.121838 0.00003045950 0.587 ]
# Turn into UPbAnalysis objects
analyses = UPbAnalysis.(eachcol(data)...,)
# Screen for discordance
analyses = analyses[discordance.(analyses) .< 0.2]
# Plot in Wetherill concordia space
hdl = plot(xlabel="²⁰⁷Pb/²³⁵U", ylabel="²⁰⁶Pb/²³⁸U", framestyle=:box)
plot!(hdl, analyses, color=:darkblue, alpha=0.3, label="")
concordiacurve!(hdl) # Add concordia curve
savefig(hdl, "concordia.svg")
display(hdl)
```

```julia
# Rank-order plot of 6/8 ages
hdl = plot(framestyle=:box, layout=(1,2), size=(800,400), ylims=(748, 754))
rankorder!(hdl[1], age68.(analyses), ylabel="²⁰⁶Pb/²³⁸U Age [Ma]", color=:darkblue, mscolor=:darkblue)
rankorder!(hdl[2], age75.(analyses), ylabel="²⁰⁷Pb/²³⁵U Age [Ma]", color=:darkblue, mscolor=:darkblue)
savefig(hdl, "rankorder.svg")
display(hdl)
```

### Pb-loss-aware Bayesian eruption age estimation
Among other things implemented in this package is an extension of the method of [Keller, Schoene, and Samperton (2018)](https://doi.org/10.7185/geochemlet.1826) to the case where some analyses may have undergone significant Pb-loss:
```julia
nsteps = 10^6
tmindist, t0dist = metropolis_min(nsteps, HalfNormalDistribution, analyses; burnin=10^4)
tpbloss = CI(t0dist)
terupt = CI(tmindist)
display(terupt)
println("Eruption/deposition age: $terupt Ma (95% CI)")
# Add to concordia plot
I = rand(1:length(tmindist), 1000) # Pick 100 random samples from the posterior distribution
concordialine!(hdl, t0dist[I], tmindist[I], color=:darkred, alpha=0.02, label="Model: $terupt Ma") # Add to Concordia plot
display(hdl)
```
> Eruption/deposition age: 751.952 +0.493/-0.757 Ma (95% CI)
```julia
h = histogram(tmindist, xlabel="Age [Ma]", ylabel="Probability Density", normalize=true, label="Eruption age", color=:darkblue, alpha=0.65, linealpha=0.1, framestyle=:box)
ylims!(h, 0, last(ylims()))
savefig(h, "EruptionAge.svg")
display(h)
```

```julia
h = histogram(t0dist, xlabel="Age [Ma]", ylabel="Probability Density", normalize=true, label="Time of Pb-loss", color=:darkblue, alpha=0.65, linealpha=0.1, framestyle=:box)
xlims!(h, 0, last(xlims()))
ylims!(h, 0, last(ylims()))
savefig(h, "PbLoss.svg")
display(h)
```

Notably, In contrast to a weighted mean or a standard Bayesian eruption age, the result appears to be influenced little if at all by any decision to exclude or not exclude discordant grains, for example:
Excluding four analyses with >0.07% discordance:

Excluding nothing:

with in this example perhaps only a slight _increase_ in precision when more data are included, even if those data happen to be highly discordant.
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[docs-dev-url]: https://JuliaGeochronology.github.io/Isoplot.jl/dev/
[ci-img]: https://github.com/JuliaGeochronology/Isoplot.jl/workflows/CI/badge.svg
[ci-url]: https://github.com/JuliaGeochronology/Isoplot.jl/actions/workflows/CI.yml
[codecov-img]: http://codecov.io/github/JuliaGeochronology/Isoplot.jl/coverage.svg?branch=main
[codecov-url]: http://app.codecov.io/github/JuliaGeochronology/Isoplot.jl?branch=main
| Isoplot | https://github.com/JuliaGeochronology/Isoplot.jl.git |
|
[
"MIT"
] | 0.3.6 | b9a419e46fe4516f3c0b52041d84e2bb5be9cb81 | docs | 184 | ```@meta
CurrentModule = Isoplot
```
# Isoplot
Documentation for [Isoplot.jl](https://github.com/JuliaGeochronology/Isoplot.jl).
```@index
```
```@autodocs
Modules = [Isoplot]
```
| Isoplot | https://github.com/JuliaGeochronology/Isoplot.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 1818 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
import Pkg;
Pkg.develop(path = joinpath(@__DIR__, "../../FMIFlux.jl"));
using Documenter, FMIFlux
using Documenter: GitHubActions
makedocs(
sitename = "FMIFlux.jl",
format = Documenter.HTML(
collapselevel = 1,
sidebar_sitename = false,
edit_link = nothing,
size_threshold_ignore = [joinpath("examples", "juliacon_2023.md")],
),
warnonly = true,
pages = Any[
"Introduction" => "index.md"
"Examples" => [
"Overview" => "examples/overview.md"
"Simple CS-NeuralFMU" => "examples/simple_hybrid_CS.md"
"Simple ME-NeuralFMU" => "examples/simple_hybrid_ME.md"
"Growing Horizon ME-NeuralFMU" => "examples/growing_horizon_ME.md"
"JuliaCon 2023" => "examples/juliacon_2023.md"
"MDPI 2022" => "examples/mdpi_2022.md"
"Modelica Conference 2021" => "examples/modelica_conference_2021.md"
"Pluto Workshops" => "examples/workshops.md"
]
"FAQ" => "faq.md"
"Library Functions" => "library.md"
"Related Publication" => "related.md"
"Contents" => "contents.md"
],
)
function deployConfig()
github_repository = get(ENV, "GITHUB_REPOSITORY", "")
github_event_name = get(ENV, "GITHUB_EVENT_NAME", "")
if github_event_name == "workflow_run" || github_event_name == "repository_dispatch"
github_event_name = "push"
end
github_ref = get(ENV, "GITHUB_REF", "")
return GitHubActions(github_repository, github_event_name, github_ref)
end
deploydocs(
repo = "github.com/ThummeTo/FMIFlux.jl.git",
devbranch = "main",
deploy_config = deployConfig(),
)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 2117 | # Copyright (c) 2023 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license.
# See LICENSE (https://github.com/thummeto/FMIFlux.jl/blob/main/LICENSE) file in the project root for details.
# This workshop was held at the JuliaCon2023 @ MIT (Boston)
using Plots
using Distributed
using JLD2
using DistributedHyperOpt # add via `add "https://github.com/ThummeTo/DistributedHyperOpt.jl"`
# if you want to see more messages about Hyperband working ...
# ENV["JULIA_DEBUG"] = "DistributedHyperOpt"
nprocs()
workers = addprocs(5)
@everywhere include(joinpath(@__DIR__, "workshop_module.jl"))
# creating paths for log files (logs), parameter sets (params) and hyperparameter plots (plots)
for dir ∈ ("logs", "params", "plots")
path = joinpath(@__DIR__, dir)
@info "Creating (if not already) path: $(path)"
mkpath(path)
end
beta1 = 1.0 .- exp10.(LinRange(-4, -1, 4))
beta2 = 1.0 .- exp10.(LinRange(-6, -1, 6))
sampler = DistributedHyperOpt.Hyperband(;
R = 81,
η = 3,
ressourceScale = 1.0 / 81.0 * NODE_Training.data.cumconsumption_t[end],
)
optimization = DistributedHyperOpt.Optimization(
NODE_Training.train!,
DistributedHyperOpt.Parameter(
"eta",
(1e-5, 1e-2);
type = :Log,
samples = 7,
round_digits = 5,
),
DistributedHyperOpt.Parameter("beta1", beta1),
DistributedHyperOpt.Parameter("beta2", beta2),
DistributedHyperOpt.Parameter("batchDur", (0.5, 20.0); samples = 40, round_digits = 1),
DistributedHyperOpt.Parameter("lastWeight", (0.1, 1.0); samples = 10, round_digits = 1),
DistributedHyperOpt.Parameter("schedulerID", [:Random, :Sequential, :LossAccumulation]),
DistributedHyperOpt.Parameter("loss", [:MSE, :MAE]),
)
DistributedHyperOpt.optimize(
optimization;
sampler = sampler,
plot = true,
plot_ressources = true,
save_plot = joinpath(@__DIR__, "plots", "hyperoptim.png"),
redirect_worker_io_dir = joinpath(@__DIR__, "logs"),
)
Plots.plot(optimization; size = (1024, 1024), ressources = true)
minimum, minimizer, ressource = DistributedHyperOpt.results(optimization)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 9852 | # Copyright (c) 2023 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license.
# See LICENSE (https://github.com/thummeto/FMIFlux.jl/blob/main/LICENSE) file in the project root for details.
using LaTeXStrings
import FMIFlux: roundToLength
import FMIZoo: movavg
import FMI: FMUSolution
import FMIZoo: VLDM, VLDM_Data
function singleInstanceMode(fmu::FMU2, mode::Bool)
if mode
# switch to a more efficient execution configuration, allocate only a single FMU instance, see:
# https://thummeto.github.io/FMI.jl/dev/features/#Execution-Configuration
fmu.executionConfig = FMI.FMIImport.FMU_EXECUTION_CONFIGURATION_NOTHING
c, _ = FMIFlux.prepareSolveFMU(
fmu,
nothing,
fmu.type;
instantiate = true,
setup = true,
parameters = data.params,
x0 = x0,
)
else
c = FMI.getCurrentInstance(fmu)
# switch back to the default execution configuration, allocate a new FMU instance for every run, see:
# https://thummeto.github.io/FMI.jl/dev/features/#Execution-Configuration
fmu.executionConfig = FMI.FMIImport.FMU_EXECUTION_CONFIGURATION_NO_RESET
FMIFlux.finishSolveFMU(fmu, c; freeInstance = false, terminate = true)
end
return nothing
end
function dataIndexForTime(t::Real)
return 1 + round(Int, t / dt)
end
function plotEnhancements(
neuralFMU::NeuralFMU,
fmu::FMU2,
data::FMIZoo.VLDM_Data;
reductionFactor::Int = 10,
mov_avg::Int = 100,
filename = nothing,
)
colorMin = 0
colorMax = 0
okregion = 0
label = ""
tStart = data.consumption_t[1]
tStop = data.consumption_t[end]
x0 = FMIZoo.getStateVector(data, tStart)
resultNFMU = neuralFMU(
x0,
(tStart, tStop);
parameters = data.params,
showProgress = false,
recordValues = :derivatives,
saveat = data.consumption_t,
)
resultFMU = simulate(
fmu,
(tStart, tStop);
parameters = data.params,
showProgress = false,
recordValues = :derivatives,
saveat = data.consumption_t,
)
# Finite differences for acceleration
dt = data.consumption_t[2] - data.consumption_t[1]
acceleration_val = (data.speed_val[2:end] - data.speed_val[1:end-1]) / dt
acceleration_val = [acceleration_val..., 0.0]
acceleration_dev = (data.speed_dev[2:end] - data.speed_dev[1:end-1]) / dt
acceleration_dev = [acceleration_dev..., 0.0]
ANNInputs = getValue(resultNFMU, :derivatives) # collect([0.0, 0.0, 0.0, data.speed_val[i], acceleration_val[i], data.consumption_val[i]] for i in 1:length(data.consumption_t))
ANNInputs = collect(
[
ANNInputs[1][i],
ANNInputs[2][i],
ANNInputs[3][i],
ANNInputs[4][i],
ANNInputs[5][i],
ANNInputs[6][i],
] for i = 1:length(ANNInputs[1])
)
ANNOutputs = getStateDerivative(resultNFMU, 5:6; isIndex = true)
ANNOutputs =
collect([ANNOutputs[1][i], ANNOutputs[2][i]] for i = 1:length(ANNOutputs[1]))
FMUOutputs = getStateDerivative(resultFMU, 5:6; isIndex = true)
FMUOutputs =
collect([FMUOutputs[1][i], FMUOutputs[2][i]] for i = 1:length(FMUOutputs[1]))
ANN_consumption = collect(o[2] for o in ANNOutputs)
ANN_error = ANN_consumption - data.consumption_val
ANN_error = collect(
ANN_error[i] > 0.0 ? max(0.0, ANN_error[i] - data.consumption_dev[i]) :
min(0.0, ANN_error[i] + data.consumption_dev[i]) for
i = 1:length(data.consumption_t)
)
FMU_consumption = collect(o[2] for o in FMUOutputs)
FMU_error = FMU_consumption - data.consumption_val
FMU_error = collect(
FMU_error[i] > 0.0 ? max(0.0, FMU_error[i] - data.consumption_dev[i]) :
min(0.0, FMU_error[i] + data.consumption_dev[i]) for
i = 1:length(data.consumption_t)
)
colorMin = -231.0
colorMax = 231.0
FMU_error = movavg(FMU_error, mov_avg)
ANN_error = movavg(ANN_error, mov_avg)
ANN_error = ANN_error .- FMU_error
ANNInput_vel = collect(o[4] for o in ANNInputs)
ANNInput_acc = collect(o[5] for o in ANNInputs)
ANNInput_con = collect(o[6] for o in ANNInputs)
_max = max(ANN_error...)
_min = min(ANN_error...)
neutral = 0.5
if _max > colorMax
@warn "max value ($(_max)) is larger than colorMax ($(colorMax)) - values will be cut"
end
if _min < colorMin
@warn "min value ($(_min)) is smaller than colorMin ($(colorMin)) - values will be cut"
end
anim = @animate for ang = 0:5:360
l = Plots.@layout [Plots.grid(3, 1) r{0.85w}]
fig = Plots.plot(
layout = l,
size = (1600, 800),
left_margin = 10Plots.mm,
right_margin = 10Plots.mm,
bottom_margin = 10Plots.mm,
)
colorgrad = cgrad([:green, :white, :red], [0.0, 0.5, 1.0]) # , scale = :log)
scatter!(
fig[1],
ANNInput_vel[1:reductionFactor:end],
ANNInput_acc[1:reductionFactor:end],
xlabel = "velocity [m/s]",
ylabel = "acceleration [m/s^2]",
color = colorgrad,
zcolor = ANN_error[1:reductionFactor:end],
label = :none,
colorbar = :none,
) #
scatter!(
fig[2],
ANNInput_acc[1:reductionFactor:end],
ANNInput_con[1:reductionFactor:end],
xlabel = "acceleration [m/s^2]",
ylabel = "consumption [W]",
color = colorgrad,
zcolor = ANN_error[1:reductionFactor:end],
label = :none,
colorbar = :none,
) #
scatter!(
fig[3],
ANNInput_vel[1:reductionFactor:end],
ANNInput_con[1:reductionFactor:end],
xlabel = "velocity [m/s]",
ylabel = "consumption [W]",
color = colorgrad,
zcolor = ANN_error[1:reductionFactor:end],
label = :none,
colorbar = :none,
) #
scatter!(
fig[4],
ANNInput_vel[1:reductionFactor:end],
ANNInput_acc[1:reductionFactor:end],
ANNInput_con[1:reductionFactor:end],
xlabel = "velocity [m/s]",
ylabel = "acceleration [m/s^2]",
zlabel = "consumption [W]",
color = colorgrad,
zcolor = ANN_error[1:reductionFactor:end],
markersize = 8,
label = :none,
camera = (ang, 20),
colorbar_title = " \n\n\n\n" * L"ΔMAE" * " (smoothed)",
)
# draw invisible dummys to scale colorbar to fixed size
for i = 1:3
scatter!(
fig[i],
[0.0, 0.0],
[0.0, 0.0],
color = colorgrad,
zcolor = [colorMin, colorMax],
markersize = 0,
label = :none,
)
end
for i = 4:4
scatter!(
fig[i],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
color = colorgrad,
zcolor = [colorMin, colorMax],
markersize = 0,
label = :none,
)
end
end
if !isnothing(filename)
return gif(anim, filename; fps = 10)
else
return gif(anim; fps = 10)
end
end
function plotCumulativeConsumption(
solutionNFMU::FMUSolution,
solutionFMU::FMUSolution,
data::FMIZoo.VLDM_Data;
range = (0.0, 1.0),
filename = nothing,
)
len = length(data.consumption_t)
steps = (1+round(Int, range[1] * len)):(round(Int, range[end] * len))
t = data.consumption_t
nfmu_val = getState(solutionNFMU, 6; isIndex = true)
fmu_val = getState(solutionFMU, 6; isIndex = true)
data_val = data.cumconsumption_val
data_dev = data.cumconsumption_dev
mse_nfmu = FMIFlux.Losses.mse_dev(nfmu_val, data_val, data_dev)
mse_fmu = FMIFlux.Losses.mse_dev(fmu_val, data_val, data_dev)
mae_nfmu = FMIFlux.Losses.mae_dev(nfmu_val, data_val, data_dev)
mae_fmu = FMIFlux.Losses.mae_dev(fmu_val, data_val, data_dev)
max_nfmu = FMIFlux.Losses.max_dev(nfmu_val, data_val, data_dev)
max_fmu = FMIFlux.Losses.max_dev(fmu_val, data_val, data_dev)
fig = plot(xlabel = L"t[s]", ylabel = L"x_6 [Ws]", dpi = 600)
plot!(
fig,
t[steps],
data_val[steps];
label = "Data",
ribbon = data_dev,
fillalpha = 0.3,
)
plot!(
fig,
t[steps],
fmu_val[steps];
label = "FMU [ MSE:$(roundToLength(mse_fmu,10)) | MAE:$(roundToLength(mae_fmu,10)) | MAX:$(roundToLength(max_fmu,10)) ]",
)
plot!(
fig,
t[steps],
nfmu_val[steps];
label = "NeuralFMU [ MSE:$(roundToLength(mse_nfmu,10)) | MAE:$(roundToLength(mae_nfmu,10)) | MAX:$(roundToLength(max_nfmu,10)) ]",
)
if !isnothing(filename)
savefig(fig, filename)
end
return fig
end
function simPlotCumulativeConsumption(cycle::Symbol, filename = nothing; kwargs...)
d = FMIZoo.VLDM(cycle)
tStart = d.consumption_t[1]
tStop = d.consumption_t[end]
tSave = d.consumption_t
resultNFMU = neuralFMU(
x0,
(tStart, tStop);
parameters = d.params,
showProgress = false,
saveat = tSave,
maxiters = 1e7,
)
resultFMU = simulate(
fmu,
(tStart, tStop),
parameters = d.params,
showProgress = false,
saveat = tSave,
)
fig = plotCumulativeConsumption(resultNFMU, resultFMU, d, kwargs...)
if !isnothing(filename)
savefig(fig, filename)
end
return fig
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 599 | ### A Pluto.jl notebook ###
# v0.19.43
using Markdown
using InteractiveUtils
# ╔═╡ 1470df0f-40e1-45d5-a4cc-519cc3b28fb8
md"""
# Hands-on: Hybrid Modeling using FMI
Workshop @ MODPROD 2024 (Linköping University, Sweden)
by Tobias Thummerer (University of Augsburg)
*#hybridmodeling, #sciml, #neuralode, #neuralfmu, #penode*
This workshop was refactored and moved to [Scientific Machine Learning using Functional Mock-up Units](https://github.com/ThummeTo/FMIFlux.jl/tree/main/examples/pluto-src/SciMLUsingFMUs/SciMLUsingFMUs.jl).
"""
# ╔═╡ Cell order:
# ╟─1470df0f-40e1-45d5-a4cc-519cc3b28fb8
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 185368 | ### A Pluto.jl notebook ###
# v0.19.46
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try
Base.loaded_modules[Base.PkgId(
Base.UUID("6e696c72-6542-2067-7265-42206c756150"),
"AbstractPlutoDingetjes",
)].Bonds.initial_value
catch
b -> missing
end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ a1ee798d-c57b-4cc3-9e19-fb607f3e1e43
using PlutoUI # Notebook UI
# ╔═╡ 72604eef-5951-4934-844d-d2eb7eb0292c
using FMI # load and simulate FMUs
# ╔═╡ 21104cd1-9fe8-45db-9c21-b733258ff155
using FMIFlux # machine learning with FMUs
# ╔═╡ 9d9e5139-d27e-48c8-a62e-33b2ae5b0086
using FMIZoo # a collection of demo FMUs
# ╔═╡ eaae989a-c9d2-48ca-9ef8-fd0dbff7bcca
using FMIFlux.Flux # default Julia Machine Learning library
# ╔═╡ 98c608d9-c60e-4eb6-b611-69d2ae7054c9
using FMIFlux.DifferentialEquations # the mighty (O)DE solver suite
# ╔═╡ ddc9ce37-5f93-4851-a74f-8739b38ab092
using ProgressLogging: @withprogress, @logprogress, @progressid, uuid4
# ╔═╡ de7a4639-e3b8-4439-924d-7d801b4b3eeb
using BenchmarkTools # default benchmarking library
# ╔═╡ 45c4b9dd-0b04-43ae-a715-cd120c571424
using Plots
# ╔═╡ 1470df0f-40e1-45d5-a4cc-519cc3b28fb8
md"""
# Scientific Machine Learning $br using Functional Mock-Up Units
(former *Hybrid Modeling using FMI*)
Workshop $br
@ JuliaCon 2024 (Eindhoven, Netherlands) $br
@ MODPROD 2024 (Linköping University, Sweden)
by Tobias Thummerer (University of Augsburg)
*#hybridmodeling, #sciml, #neuralode, #neuralfmu, #penode*
# Abstract
If there is something YOU know about a physical system, AI shouldn’t need to learn it. How to integrate YOUR system knowledge into a ML development process is the core topic of this hands-on workshop. The entire workshop evolves around a challenging use case from robotics: Modeling a robot that is able to write arbitrary messages with a pen. After introducing the topic and the considered use case, participants can experiment with their very own hybrid model topology.
# Introduction
This workshop focuses on the integration of Functional Mock-Up Units (FMUs) into a machine learning topology. FMUs are simulation models that can be generated within a variety of modeling tools, see the [FMI homepage](https://fmi-standard.org/). Together with deep neural networks that complement and improve the FMU prediction, so called *neural FMUs* can be created.
The workshop itself evolves around the hybrid modeling of a *Selective Compliance Assembly Robot Arm* (SCARA), that is able to write user defined words on a sheet of paper. A ready to use physical simulation model (FMU) for the SCARA is given and shortly highlighted in this workshop. However, this model – as any simulation model – shows some deviations if compared to measurements from the real system. These deviations results from not modeled slip-stick-friction: The pen sticks to the paper until a force limit is reached, but then moves jerkily. A hard to model physical effect – but not for a neural FMU.
More advanced code snippets are hidden by default and marked with a ghost `👻`. Computations, that are disabled for performance reasons, are marked with `ℹ️`. They offer a hint how to enable the idled computation by activating the corresponding checkbox marked with `🎬`.
## Example Video
If you haven't seen such a SCARA system yet, you can watch the following video. There are many more similar videos out there.
"""
# ╔═╡ 7d694be0-cd3f-46ae-96a3-49d07d7cf65a
html"""
<iframe width="560" height="315" src="https://www.youtube.com/embed/ryIwLLr6yRA?si=ncr1IXlnuNhWPWgl" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
"""
# ╔═╡ 10cb63ad-03d7-47e9-bc33-16c7786b9f6a
md"""
This video is by *Alexandru Babaian* on YouTube.
## Workshop Video
"""
# ╔═╡ 1e0fa041-a592-42fb-bafd-c7272e346e46
html"""
<iframe width="560" height="315" src="https://www.youtube.com/embed/sQ2MXSswrSo?si=XcEoe1Ai7U6hqnp5" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
"""
# ╔═╡ 6fc16c34-c0c8-48ce-87b3-011a9a0f4e7c
md"""
This video is from JuliaCon 2024 (Eindhoven, Netherlands).
## Requirements
To follow this workshop, you should ...
- ... have a rough idea what the *Functional Mock-Up Interface* is and how the standard-conform models - the *Functional Mock-Up Units* - work. If not, a good source is the homepage of the standard, see the [FMI Homepage](https://fmi-standard.org/).
- ... know the *Julia Programming Language* or at least have some programming skills in another high-level programming language like *Python* or *Matlab*. An introduction to Julia can be found on the [Julia Homepage](https://julialang.org/), but there are many more introductions in different formats available on the internet.
- ... have an idea of how modeling (in terms of modeling ODE and DAE systems) and simulation (solving) of such models works.
The technical requirements are:
| | recommended | minimum | your |
| ----- | ---- | ---- | ---- |
| RAM | $\geq$ 16.0GB | 8.0GB | $(round(Sys.total_memory() / 2^30; digits=1))GB |
| OS | Windows | Windows / Linux | $(Sys.islinux() ? "Linux" : (Sys.iswindows() ? "Windows" : "unsupported"))
| Julia | 1.10 | 1.6 | $("" * string(Int(VERSION.major)) * "." * string(Int(VERSION.minor))) |
This said, we can start "programming"! The entire notebook is pre-implemented, so you can use it without writing a single line of code. Users new to Julia can use interactive UI elements to interact, while more advance users can view and manipulate corresponding code. Let's go!
"""
# ╔═╡ 8a82d8c7-b781-4600-8780-0a0a003b676c
md"""
## Loading required Julia libraries
Before starting with the actual coding, we load in the required Julia libraries.
This Pluto-Notebook installs all required packages automatically.
However, this will take some minutes when you start the notebook for the first time... it is recommended to not interact with the UI elements as long as the first compilation runs (orange status light in the bottom right corner).
"""
# ╔═╡ a02f77d1-00d2-46a3-91ba-8a7f5b4bbdc9
md"""
First, we load the Pluto UI elements:
"""
# ╔═╡ 02f0add7-9c4e-4358-8b5e-6863bae3ee75
md"""
Then, the three FMI-libraries we need for FMU loading, machine learning and the FMU itself:
"""
# ╔═╡ 85308992-04c4-4d20-a840-6220cab54680
md"""
Some additional libraries for machine learning and ODE solvers:
"""
# ╔═╡ 3e2579c2-39ce-4249-ad75-228f82e616da
md"""
To visualize a progress bar during training:
"""
# ╔═╡ 93fab704-a8dd-47ec-ac88-13f32be99460
md"""
And to do some benchmarking:
"""
# ╔═╡ 5cb505f7-01bd-4824-8876-3e0f5a922fb7
md"""
Load in the plotting libraries ...
"""
# ╔═╡ 33d648d3-e66e-488f-a18d-e538ebe9c000
import PlotlyJS
# ╔═╡ 1e9541b8-5394-418d-8c27-2831951c538d
md"""
... and use the beautiful `plotly` backend for interactive plots.
"""
# ╔═╡ e6e91a22-7724-46a3-88c1-315c40660290
plotlyjs()
# ╔═╡ 44500f0a-1b89-44af-b135-39ce0fec5810
md"""
Next, we define some helper functions, that are not important to follow the workshop - they are hidden by default. However they are here, if you want to explore what it takes to write fully working code. If you do this workshop for the first time, it is recommended to skip the hidden part and directly go on.
"""
# ╔═╡ 74d23661-751b-4371-bf6b-986149124e81
md"""
Display the table of contents:
"""
# ╔═╡ c88b0627-2e04-40ab-baa2-b4c1edfda0c3
TableOfContents()
# ╔═╡ 915e4601-12cc-4b7e-b2fe-574e116f3a92
md"""
# Loading Model (FMU) and Data
We want to do hybrid modeling, so we need a simulation model and some data to work with. Fortunately, someone already prepared both for us. We start by loading some data from *FMIZoo.jl*, which is a collection of FMUs and corresponding data.
"""
# ╔═╡ f8e40baa-c1c5-424a-9780-718a42fd2b67
md"""
## Training Data
First, we need some data to train our hybrid model on. We can load data for our SCARA (here called `RobotRR`) with the following line:
"""
# ╔═╡ 74289e0b-1292-41eb-b13b-a4a5763c72b0
# load training data for the `RobotRR` from the FMIZoo
data_train = FMIZoo.RobotRR(:train)
# ╔═╡ 33223393-bfb9-4e9a-8ea6-a3ab6e2f22aa
begin
# define the printing messages used at different places in this notebook
LIVE_RESULTS_MESSAGE =
md"""ℹ️ Live plotting is disabled to safe performance. Checkbox `Plot Results`."""
LIVE_TRAIN_MESSAGE =
md"""ℹ️ Live training is disabled to safe performance. Checkbox `Start Training`."""
BENCHMARK_MESSAGE =
md"""ℹ️ Live benchmarks are disabled to safe performance. Checkbox `Start Benchmark`."""
HIDDEN_CODE_MESSAGE =
md"""> 👻 Hidden Code | You probably want to skip this code section on the first run."""
import FMI.FMIImport.FMICore: hasCurrentComponent, getCurrentComponent, FMU2Solution
import Random
function fmiSingleInstanceMode!(
fmu::FMU2,
mode::Bool,
params = FMIZoo.getParameter(data_train, 0.0; friction = false),
x0 = FMIZoo.getState(data_train, 0.0),
)
fmu.executionConfig = deepcopy(FMU2_EXECUTION_CONFIGURATION_NO_RESET)
# for this model, state events are generated but don't need to be handled,
# we can skip that to gain performance
fmu.executionConfig.handleStateEvents = false
fmu.executionConfig.loggingOn = false
#fmu.executionConfig.externalCallbacks = true
if mode
# switch to a more efficient execution configuration, allocate only a single FMU instance, see:
# https://thummeto.github.io/FMI.jl/dev/features/#Execution-Configuration
fmu.executionConfig.terminate = true
fmu.executionConfig.instantiate = false
fmu.executionConfig.reset = true
fmu.executionConfig.setup = true
fmu.executionConfig.freeInstance = false
c, _ = FMIFlux.prepareSolveFMU(
fmu,
nothing,
fmu.type,
true, # instantiate
false, # free
true, # terminate
true, # reset
true, # setup
params;
x0 = x0,
)
else
if !hasCurrentComponent(fmu)
return nothing
end
c = getCurrentComponent(fmu)
# switch back to the default execution configuration, allocate a new FMU instance for every run, see:
# https://thummeto.github.io/FMI.jl/dev/features/#Execution-Configuration
fmu.executionConfig.terminate = true
fmu.executionConfig.instantiate = true
fmu.executionConfig.reset = true
fmu.executionConfig.setup = true
fmu.executionConfig.freeInstance = true
FMIFlux.finishSolveFMU(
fmu,
c,
true, # free
true,
) # terminate
end
return nothing
end
function prepareSolveFMU(fmu, parameters)
FMIFlux.prepareSolveFMU(
fmu,
nothing,
fmu.type,
fmu.executionConfig.instantiate,
fmu.executionConfig.freeInstance,
fmu.executionConfig.terminate,
fmu.executionConfig.reset,
fmu.executionConfig.setup,
parameters,
)
end
function dividePath(values)
last_value = values[1]
paths = []
path = []
for j = 1:length(values)
if values[j] == 1.0
push!(path, j)
end
if values[j] == 0.0 && last_value != 0.0
push!(path, j)
push!(paths, path)
path = []
end
last_value = values[j]
end
if length(path) > 0
push!(paths, path)
end
return paths
end
function plotRobot(solution::FMU2Solution, t::Real)
x = solution.states(t)
a1 = x[5]
a2 = x[3]
dt = 0.01
i = 1 + round(Integer, t / dt)
v = solution.values.saveval[i]
l1 = 0.2
l2 = 0.1
margin = 0.05
scale = 1500
fig = plot(;
title = "Time $(round(t; digits=1))s",
size = (
round(Integer, (2 * margin + l1 + l2) * scale),
round(Integer, (l1 + l2 + 2 * margin) * scale),
),
xlims = (-margin, l1 + l2 + margin),
ylims = (-l1 - margin, l2 + margin),
legend = :bottomleft,
)
p0 = [0.0, 0.0]
p1 = p0 .+ [cos(a1) * l1, sin(a1) * l1]
p2 = p1 .+ [cos(a1 + a2) * l2, sin(a1 + a2) * l2]
f_norm = collect(v[3] for v in solution.values.saveval)
paths = dividePath(f_norm)
drawing = collect(v[1:2] for v in solution.values.saveval)
for path in paths
plot!(
fig,
collect(v[1] for v in drawing[path]),
collect(v[2] for v in drawing[path]),
label = :none,
color = :black,
style = :dot,
)
end
paths = dividePath(f_norm[1:i])
drawing_is = collect(v[4:5] for v in solution.values.saveval)[1:i]
for path in paths
plot!(
fig,
collect(v[1] for v in drawing_is[path]),
collect(v[2] for v in drawing_is[path]),
label = :none,
color = :green,
width = 2,
)
end
plot!(fig, [p0[1], p1[1]], [p0[2], p1[2]], label = :none, width = 3, color = :blue)
plot!(fig, [p1[1], p2[1]], [p1[2], p2[2]], label = :none, width = 3, color = :blue)
scatter!(
fig,
[p0[1]],
[p0[2]],
label = "R1 | α1=$(round(a1; digits=3)) rad",
color = :red,
)
scatter!(
fig,
[p1[1]],
[p1[2]],
label = "R2 | α2=$(round(a2; digits=3)) rad",
color = :purple,
)
scatter!(fig, [v[1]], [v[2]], label = "TCP | F=$(v[3]) N", color = :orange)
end
HIDDEN_CODE_MESSAGE
end # begin
# ╔═╡ 92ad1a99-4ad9-4b69-b6f3-84aab49db54f
@bind t_train_plot Slider(0.0:0.1:data_train.t[end], default = data_train.t[1])
# ╔═╡ f111e772-a340-4217-9b63-e7715f773b2c
md"""
Let's have a look on the data! It's the written word *train*.
You can use the slider to pick a specific point in time to plot the "robot" as recorded as part of the data.
The current picked time is $(round(t_train_plot; digits=1))s.
"""
# ╔═╡ 909de9f1-2aca-4bf0-ba60-d3418964ba4a
plotRobot(data_train.solution, t_train_plot)
# ╔═╡ d8ca5f66-4f55-48ab-a6c9-a0be662811d9
md"""
> 👁️ Interestingly, the first part of the word "trai" is not significantly affected by the slip-stick-effect, the actual TCP trajectory (green) lays quite good on the target position (black dashed). However, the "n" is very jerky. This can be explained by the increasing lever, the motor needs more torque to overcome the static friction the further away the TCP (orange) is from the robot base (red).
Let's extract a start and stop time, as well as saving points for the later solving process:
"""
# ╔═╡ 41b1c7cb-5e3f-4074-a681-36dd2ef94454
tSave = data_train.t # time points to save the solution at
# ╔═╡ 8f45871f-f72a-423f-8101-9ce93e5a885b
tStart = tSave[1] # start time for simulation of FMU and neural FMU
# ╔═╡ 57c039f7-5b24-4d63-b864-d5f808110b91
tStop = tSave[end] # stop time for simulation of FMU and neural FMU
# ╔═╡ 4510022b-ad28-4fc2-836b-e4baf3c14d26
md"""
Finally, also the start state can be grabbed from *FMIZoo.jl*, as well as some default parameters for the simulation model we load in the next section. How to interpret the six states is discussed in the next section where the model is loaded.
"""
# ╔═╡ 9589416a-f9b3-4b17-a381-a4f660a5ee4c
x0 = FMIZoo.getState(data_train, tStart)
# ╔═╡ 326ae469-43ab-4bd7-8dc4-64575f4a4d3e
md"""
The parameter array only contains the path to the training data file, the trajectory writing "train".
"""
# ╔═╡ 8f8f91cc-9a92-4182-8f18-098ae3e2c553
parameters = FMIZoo.getParameter(data_train, tStart; friction = false)
# ╔═╡ 8d93a1ed-28a9-4a77-9ac2-5564be3729a5
md"""
## Validation Data
To check whether the hybrid model was not only able to *imitate*, but *understands* the training data, we need some unknown data for validation. In this case, the written word "validate".
"""
# ╔═╡ 4a8de267-1bf4-42c2-8dfe-5bfa21d74b7e
# load validation data for the `RobotRR` from the FMIZoo
data_validation = FMIZoo.RobotRR(:validate)
# ╔═╡ dbde2da3-e3dc-4b78-8f69-554018533d35
@bind t_validate_plot Slider(0.0:0.1:data_validation.t[end], default = data_validation.t[1])
# ╔═╡ 6a8b98c9-e51a-4f1c-a3ea-cc452b9616b7
md"""
Let's have a look on the validation data!
Again, you can use the slider to pick a specific point in time.
The current time is $(round(t_validate_plot; digits=1))s.
"""
# ╔═╡ d42d0beb-802b-4d30-b5b8-683d76af7c10
plotRobot(data_validation.solution, t_validate_plot)
# ╔═╡ e50d7cc2-7155-42cf-9fef-93afeee6ffa4
md"""
> 👁️ It looks similar to the effect we know from training data, the first part "valida" is not significantly affected by the slip-stick-effect, but the "te" is very jerky. Again, think of the increasing lever ...
"""
# ╔═╡ 3756dd37-03e0-41e9-913e-4b4f183d8b81
md"""
## Simulation Model (FMU)
The SCARA simulation model is called `RobotRR` for `Robot Rotational Rotational`, indicating that this robot consists of two rotational joints, connected by links. It is loaded with the following line of code:
"""
# ╔═╡ 2f83bc62-5a54-472a-87a2-4ddcefd902b6
# load the FMU named `RobotRR` from the FMIZoo
# the FMU was exported from Dymola (version 2023x)
# load the FMU in mode `model-exchange` (ME)
fmu = fmiLoad("RobotRR", "Dymola", "2023x"; type = :ME)
# ╔═╡ c228eb10-d694-46aa-b952-01d824879287
begin
# We activate the single instance mode, so only one FMU instance gets allocated and is reused again an again.
fmiSingleInstanceMode!(fmu, true)
using FMI.FMIImport: fmi2StringToValueReference
# declare some model identifiers (inside of the FMU)
STATE_I1 = fmu.modelDescription.stateValueReferences[2]
STATE_I2 = fmu.modelDescription.stateValueReferences[1]
STATE_A1 = fmi2StringToValueReference(
fmu,
"rRPositionControl_Elasticity.rr1.rotational1.revolute1.phi",
)
STATE_A2 = fmi2StringToValueReference(
fmu,
"rRPositionControl_Elasticity.rr1.rotational2.revolute1.phi",
)
STATE_dA1 = fmi2StringToValueReference(
fmu,
"rRPositionControl_Elasticity.rr1.rotational1.revolute1.w",
)
STATE_dA2 = fmi2StringToValueReference(
fmu,
"rRPositionControl_Elasticity.rr1.rotational2.revolute1.w",
)
DER_ddA2 = fmu.modelDescription.derivativeValueReferences[4]
DER_ddA1 = fmu.modelDescription.derivativeValueReferences[6]
VAR_TCP_PX = fmi2StringToValueReference(fmu, "rRPositionControl_Elasticity.tCP.p_x")
VAR_TCP_PY = fmi2StringToValueReference(fmu, "rRPositionControl_Elasticity.tCP.p_y")
VAR_TCP_VX = fmi2StringToValueReference(fmu, "rRPositionControl_Elasticity.tCP.v_x")
VAR_TCP_VY = fmi2StringToValueReference(fmu, "rRPositionControl_Elasticity.tCP.v_y")
VAR_TCP_F = fmi2StringToValueReference(fmu, "combiTimeTable.y[3]")
HIDDEN_CODE_MESSAGE
end
# ╔═╡ 16ffc610-3c21-40f7-afca-e9da806ea626
md"""
Let's check out some meta data of the FMU with `fmiInfo`:
"""
# ╔═╡ 052f2f19-767b-4ede-b268-fce0aee133ad
fmiInfo(fmu)
# ╔═╡ 746fbf6f-ed7c-43b8-8a6f-0377cd3cf85e
md"""
> 👁️ We can read the model name, tool information for the exporting tool, number of event indicators, states, inputs, outputs and whether the optionally implemented FMI features (like *directional derivatives*) are supported by this FMU.
"""
# ╔═╡ 08e1ff54-d115-4da9-8ea7-5e89289723b3
md"""
All six states are listed with all their alias identifiers, that might look a bit awkward the first time. The six states - human readable - are:
| variable reference | description |
| -------- | ------ |
| 33554432 | motor #2 current |
| 33554433 | motor #1 current |
| 33554434 | joint #2 angle |
| 33554435 | joint #2 angular velocity |
| 33554436 | joint #1 angle |
| 33554437 | joint #1 angular velocity |
"""
# ╔═╡ 70c6b605-54fa-40a3-8bce-a88daf6a2022
md"""
To simulate - or *solve* - the ME-FMU, we need an ODE solver. We use the *Tsit5* (explicit Runge-Kutta) here.
"""
# ╔═╡ 634f923a-5e09-42c8-bac0-bf165ab3d12a
solver = Tsit5()
# ╔═╡ f59b5c84-2eae-4e3f-aaec-116c090d454d
md"""
Let's define an array of values we want to be recorded during the first simulation of our FMU. The variable identifiers (like `DER_ddA2`) were pre-defined in the hidden code section above.
"""
# ╔═╡ 0c9493c4-322e-41a0-9ec7-2e2c54ae1373
recordValues = [
DER_ddA2,
DER_ddA1, # mechanical accelerations
STATE_A2,
STATE_A1, # mechanical angles
VAR_TCP_PX,
VAR_TCP_PY, # tool-center-point x and y
VAR_TCP_VX,
VAR_TCP_VY, # tool-center-point velocity x and y
VAR_TCP_F,
] # normal force pen on paper
# ╔═╡ 325c3032-4c78-4408-b86e-d9aa4cfc3187
md"""
Let's simulate the FMU using `fmiSimulate`. In the solution object, different information can be found, like the number of ODE, jacobian or gradient evaluations:
"""
# ╔═╡ 25e55d1c-388f-469d-99e6-2683c0508693
sol_fmu_train = fmiSimulate(
fmu, # our FMU
(tStart, tStop); # sim. from tStart to tStop
solver = solver, # use the Tsit5 solver
parameters = parameters, # the word "train"
saveat = tSave, # saving points for the sol.
recordValues = recordValues,
) # values to record
# ╔═╡ 74c519c9-0eef-4798-acff-b11044bb4bf1
md"""
Now that we know our model and data a little bit better, it's time to care about our hybrid model topology.
# Experiments: $br Hybrid Model Topology
Today is opposite day! Instead of deriving a topology step by step, the final neural FMU topology is presented in the picture below... however, three experiments are intended to make clear why it looks the way it looks.

The first experiment is on choosing a good interface between FMU and ANN. The second is on online data pre- and post-processing. And the third one on gates, that allow to control the influence of ANN and FMU on the resulting hybrid model dynamics. After you completed all three, you are equipped with the knowledge to cope the final challenge: Build your own neural FMU and train it!
"""
# ╔═╡ 786c4652-583d-43e9-a101-e28c0b6f64e4
md"""
## Choosing interface signals
**between the physical and machine learning domain**
When connecting an FMU with an ANN, technically different signals could be used: States, state derivatives, inputs, outputs, parameters, time itself or other observable variables. Depending on the use case, some signals are more clever to choose than others. In general, every additional signal costs a little bit of computational performance, as you will see. So picking the right subset is the key!

"""
# ╔═╡ 5d688c3d-b5e3-4a3a-9d91-0896cc001000
md"""
We start building our deep model as a `Chain` of layers. For now, there is only a single layer in it: The FMU `fmu` itself. The layer input `x` is interpreted as system state (compare to the figure above) and set in the fmu call via `x=x`. The current solver time `t` is set implicitly. Further, we want all state derivatives as layer outputs by setting `dx_refs=:all` and some additional outputs specified via `y_refs=CHOOSE_y_refs` (you can pick them using the checkboxes).
"""
# ╔═╡ 68719de3-e11e-4909-99a3-5e05734cc8b1
md"""
Which signals are used for `y_refs`, can be selected:
"""
# ╔═╡ b42bf3d8-e70c-485c-89b3-158eb25d8b25
@bind CHOOSE_y_refs MultiCheckBox([
STATE_A1 => "Angle Joint 1",
STATE_A2 => "Angle Joint 2",
STATE_dA1 => "Angular velocity Joint 1",
STATE_dA2 => "Angular velocity Joint 2",
VAR_TCP_PX => "TCP position x",
VAR_TCP_PY => "TCP position y",
VAR_TCP_VX => "TCP velocity x",
VAR_TCP_VY => "TCP velocity y",
VAR_TCP_F => "TCP (normal) force z",
])
# ╔═╡ 2e08df84-a468-4e99-a277-e2813dfeae5c
model = Chain(x -> fmu(; x = x, dx_refs = :all, y_refs = CHOOSE_y_refs))
# ╔═╡ c446ed22-3b23-487d-801e-c23742f81047
md"""
Let's pick a state `x1` one second after simulation start to determine sensitivities for:
"""
# ╔═╡ fc3d7989-ac10-4a82-8777-eeecd354a7d0
x1 = FMIZoo.getState(data_train, tStart + 1.0)
# ╔═╡ f4e66f76-76ff-4e21-b4b5-c1ecfd846329
begin
using FMIFlux.FMISensitivity.ReverseDiff
using FMIFlux.FMISensitivity.ForwardDiff
prepareSolveFMU(fmu, parameters)
jac_rwd = ReverseDiff.jacobian(x -> model(x), x1)
A_rwd = jac_rwd[1:length(x1), :]
end
# ╔═╡ 0a7955e7-7c1a-4396-9613-f8583195c0a8
md"""
Depending on how many signals you select, the output of the FMU-layer is extended. The first six outputs are the state derivatives, the remaining are the $(length(CHOOSE_y_refs)) additional output(s) selected above.
"""
# ╔═╡ 4912d9c9-d68d-4afd-9961-5d8315884f75
begin
dx_y = model(x1)
end
# ╔═╡ 19942162-cd4e-487c-8073-ea6b262d299d
md"""
Derivatives:
"""
# ╔═╡ 73575386-673b-40cc-b3cb-0b8b4f66a604
ẋ = dx_y[1:length(x1)]
# ╔═╡ 24861a50-2319-4c63-a800-a0a03279efe2
md"""
Additional outputs:
"""
# ╔═╡ 93735dca-c9f3-4f1a-b1bd-dfe312a0644a
y = dx_y[length(x1)+1:end]
# ╔═╡ 13ede3cd-99b1-4e65-8a18-9043db544728
md"""
For the later training, we need gradients and Jacobians.
"""
# ╔═╡ f7c119dd-c123-4c43-812e-d0625817d77e
md"""
If we use reverse-mode automatic differentiation via `ReverseDiff.jl`, the determined Jacobian $A = \frac{\partial \dot{x}}{\partial x}$ states:
"""
# ╔═╡ b163115b-393d-4589-842d-03859f05be9a
md"""
Forward-mode automatic differentiation (using *ForwardDiff.jl*)is available, too.
We can determine further Jacobians for FMUs, for example the Jacobian $C = \frac{\partial y}{\partial x}$ states (using *ReverseDiff.jl*):
"""
# ╔═╡ ac0afa6c-b6ec-4577-aeb6-10d1ec63fa41
begin
C_rwd = jac_rwd[length(x1)+1:end, :]
end
# ╔═╡ 5e9cb956-d5ea-4462-a649-b133a77929b0
md"""
Let's check the performance of these calls, because they will have significant influence on the later training performance!
"""
# ╔═╡ 9dc93971-85b6-463b-bd17-43068d57de94
md"""
### Benchmark
The amount of selected signals has influence on the computational performance of the model. The more signals you use, the slower is inference and gradient determination. For now, you have picked $(length(CHOOSE_y_refs)) additional signal(s).
"""
# ╔═╡ 476a1ed7-c865-4878-a948-da73d3c81070
begin
CHOOSE_y_refs
md"""
🎬 **Start Benchmark** $(@bind BENCHMARK CheckBox())
(benchmarking takes around 10 seconds)
"""
end
# ╔═╡ 0b6b4f6d-be09-42f3-bc2c-5f17a8a9ab0e
md"""
The current timing and allocations for inference are:
"""
# ╔═╡ a1aca180-d561-42a3-8d12-88f5a3721aae
begin
if BENCHMARK
@btime model(x1)
else
BENCHMARK_MESSAGE
end
end
# ╔═╡ 3bc2b859-d7b1-4b79-88df-8fb517a6929d
md"""
Gradient and Jacobian computation takes a little longer of course. We use reverse-mode automatic differentiation via `ReverseDiff.jl` here:
"""
# ╔═╡ a501d998-6fd6-496f-9718-3340c42b08a6
begin
if BENCHMARK
prepareSolveFMU(fmu, parameters)
function ben_rwd(x)
return ReverseDiff.jacobian(model, x + rand(6) * 1e-12)
end
@btime ben_rwd(x1)
#nothing
else
BENCHMARK_MESSAGE
end
end
# ╔═╡ 83a2122d-56da-4a80-8c10-615a8f76c4c1
md"""
Further, forward-mode automatic differentiation is available too via `ForwardDiff.jl`, but a little bit slower than reverse-mode:
"""
# ╔═╡ e342be7e-0806-4f72-9e32-6d74ed3ed3f2
begin
if BENCHMARK
prepareSolveFMU(fmu, parameters)
function ben_fwd(x)
return ForwardDiff.jacobian(model, x + rand(6) * 1e-12)
end
@btime ben_fwd(x1) # second run for "benchmarking"
#nothing
else
BENCHMARK_MESSAGE
end
end
# ╔═╡ eaf37128-0377-42b6-aa81-58f0a815276b
md"""
> 💡 Keep in mind that the choice of interface might has a significant impact on your inference and training performance! However, some signals are simply required to be part of the interface, because the effect we want to train for depends on them.
"""
# ╔═╡ c030d85e-af69-49c9-a7c8-e490d4831324
md"""
## Online Data Pre- and Postprocessing
**is required for hybrid models**
Now that we have defined the signals that come *from* the FMU and go *into* the ANN, we need to think about data pre- and post-processing. In ML, this is often done before the actual training starts. In hybrid modeling, we need to do this *online*, because the FMU constantly generates signals that might not be suitable for ANNs. On the other hand, the signals generated by ANNs might not suit the expected FMU input. What *suitable* means gets more clear if we have a look on the used activation functions, like e.g. the *tanh*.

We simplify the ANN to a single nonlinear activation function. Let's see what's happening as soon as we put the derivative *angular velocity of joint 1* (dα1) from the FMU into a `tanh` function:
"""
# ╔═╡ 51c200c9-0de3-4e50-8884-49fe06158560
begin
fig_pre_post1 = plot(
layout = grid(1, 2, widths = (1 / 4, 3 / 4)),
xlabel = "t [s]",
legend = :bottomright,
)
plot!(fig_pre_post1[1], data_train.t, data_train.da1, label = :none, xlims = (0.0, 0.1))
plot!(fig_pre_post1[1], data_train.t, tanh.(data_train.da1), label = :none)
plot!(fig_pre_post1[2], data_train.t, data_train.da1, label = "dα1")
plot!(fig_pre_post1[2], data_train.t, tanh.(data_train.da1), label = "tanh(dα1)")
fig_pre_post1
end
# ╔═╡ 0dadd112-3132-4491-9f02-f43cf00aa1f9
md"""
In general, it looks like the velocity isn't saturated too much by `tanh`. This is a good thing and not always the case! However, the very beginning of the trajectory is saturated too much (the peak value of $\approx -3$ is saturated to $\approx -1$). This is bad, because the hybrid model velocity is *slower* in this time interval and the hybrid system won't reach the same angle over time as the original FMU.
We can add shift (=addition) and scale (=multiplication) operations before and after the ANN to bypass this issue. See how you can influence the output *after* the `tanh` (and the ANN respectively) to match the ranges. The goal is to choose pre- and post-processing parameters so that the signal ranges needed by the FMU are preserved by the hybrid model.
"""
# ╔═╡ bf6bf640-54bc-44ef-bd4d-b98e934d416e
@bind PRE_POST_SHIFT Slider(-1:0.1:1.0, default = 0.0)
# ╔═╡ 5c2308d9-6d04-4b38-af3b-6241da3b6871
md"""
Change the `shift` value $(PRE_POST_SHIFT):
"""
# ╔═╡ 007d6d95-ad85-4804-9651-9ac3703d3b40
@bind PRE_POST_SCALE Slider(0.1:0.1:2.0, default = 1.0)
# ╔═╡ 639889b3-b9f2-4a3c-999d-332851768fd7
md"""
Change the `scale` value $(PRE_POST_SCALE):
"""
# ╔═╡ ed1887df-5079-4367-ab04-9d02a1d6f366
begin
fun_pre = ShiftScale([PRE_POST_SHIFT], [PRE_POST_SCALE])
fun_post = ScaleShift(fun_pre)
fig_pre_post2 = plot(; layout = grid(1, 2, widths = (1 / 4, 3 / 4)), xlabel = "t [s]")
plot!(
fig_pre_post2[2],
data_train.t,
data_train.da1,
label = :none,
title = "Shift: $(round(PRE_POST_SHIFT; digits=1)) | Scale: $(round(PRE_POST_SCALE; digits=1))",
legend = :bottomright,
)
plot!(fig_pre_post2[2], data_train.t, tanh.(data_train.da1), label = :none)
plot!(
fig_pre_post2[2],
data_train.t,
fun_post(tanh.(fun_pre(data_train.da1))),
label = :none,
)
plot!(fig_pre_post2[1], data_train.t, data_train.da1, label = "dα1", xlims = (0.0, 0.1))
plot!(fig_pre_post2[1], data_train.t, tanh.(data_train.da1), label = "tanh(dα1)")
plot!(
fig_pre_post2[1],
data_train.t,
fun_post(tanh.(fun_pre(data_train.da1))),
label = "post(tanh(pre(dα1)))",
)
fig_pre_post2
end
# ╔═╡ 0b0c4650-2ce1-4879-9acd-81c16d06700e
md"""
The left plot shows the negative spike at the very beginning in more detail. In *FMIFlux.jl*, there are ready to use layers for scaling and shifting, that can automatically select appropriate parameters. These parameters are trained together with the ANN parameters by default, so they can adapt to new signal ranges that might occur during training.
"""
# ╔═╡ b864631b-a9f3-40d4-a6a8-0b57a37a476d
md"""
> 💡 In many machine learning applications, pre- and post-processing is done offline. If we combine machine learning and physical models, we need to pre- and post-process online at the interfaces. This does at least improve training performance and is a necessity if the nominal values become very large or very small.
"""
# ╔═╡ 0fb90681-5d04-471a-a7a8-4d0f3ded7bcf
md"""
## Introducing Gates
**to control how physical and machine learning model contribute and interact**

"""
# ╔═╡ 95e14ea5-d82d-4044-8c68-090d74d95a61
md"""
There are two obvious ways of connecting two blocks (the ANN and the FMU):
- In **series**, so one block is getting signals from the other block and is able to *manipulate* or *correct* these signals. This way, e.g. modeling or parameterization errors can be corrected.
- In **parallel**, so both are getting the same signals and calculate own outputs, these outputs must be merged afterwards. This way, additional system parts, like e.g. forces or momentum, can be learned and added to or augment the existing dynamics.
The good news is, you don't have to decide this beforehand. This is something that the optimizer can decide, if we introduce a topology with parameters, that allow for both modes. This structure is referred to as *gates*.
"""
# ╔═╡ cbae6aa4-1338-428c-86aa-61d3304e33ed
@bind GATE_INIT_FMU Slider(0.0:0.1:1.0, default = 1.0)
# ╔═╡ 2fa1821b-aaec-4de4-bfb4-89560790dc39
md"""
Change the opening of the **FMU gate** $(GATE_INIT_FMU) for dα1:
"""
# ╔═╡ 8c56acd6-94d3-4cbc-bc29-d249740268a0
@bind GATE_INIT_ANN Slider(0.0:0.1:1.0, default = 0.0)
# ╔═╡ 9b52a65a-f20c-4387-aaca-5292a92fb639
md"""
Change the opening of the **ANN gate** $(GATE_INIT_ANN) for dα1:
"""
# ╔═╡ 845a95c4-9a35-44ae-854c-57432200da1a
md"""
The FMU gate value for dα1 is $(GATE_INIT_FMU) and the ANN gate value is $(GATE_INIT_ANN). This means the hybrid model dα1 is composed of $(GATE_INIT_FMU*100)% of dα1 from the FMU and of $(GATE_INIT_ANN*100)% of dα1 from the ANN.
"""
# ╔═╡ 5a399a9b-32d9-4f93-a41f-8f16a4b102dc
begin
function build_model_gates()
Random.seed!(123)
cache = CacheLayer() # allocate a cache layer
cacheRetrieve = CacheRetrieveLayer(cache) # allocate a cache retrieve layer, link it to the cache layer
# we have two signals (acceleration, consumption) and two sources (ANN, FMU), so four gates:
# (1) acceleration from FMU (gate=1.0 | open)
# (2) consumption from FMU (gate=1.0 | open)
# (3) acceleration from ANN (gate=0.0 | closed)
# (4) consumption from ANN (gate=0.0 | closed)
# the accelerations [1,3] and consumptions [2,4] are paired
gates = ScaleSum([GATE_INIT_FMU, GATE_INIT_ANN], [[1, 2]]) # gates with sum
# setup the neural FMU topology
model_gates = Flux.f64(
Chain(
dx -> cache(dx), # cache `dx`
Dense(1, 16, tanh),
Dense(16, 1, tanh), # pre-process `dx`
dx -> cacheRetrieve(1, dx), # dynamics FMU | dynamics ANN
gates,
),
) # stack together
model_input = collect([v] for v in data_train.da1)
model_output = collect(model_gates(inp) for inp in model_input)
ANN_output = collect(model_gates[2:3](inp) for inp in model_input)
fig = plot(; ylims = (-3, 1), legend = :bottomright)
plot!(fig, data_train.t, collect(v[1] for v in model_input), label = "dα1 of FMU")
plot!(fig, data_train.t, collect(v[1] for v in ANN_output), label = "dα1 of ANN")
plot!(
fig,
data_train.t,
collect(v[1] for v in model_output),
label = "dα1 of neural FMU",
)
return fig
end
build_model_gates()
end
# ╔═╡ fd1cebf1-5ccc-4bc5-99d4-1eaa30e9762e
md"""
Some observations from the current gate openings are:
This equals the serial topology: $((GATE_INIT_FMU==0 && GATE_INIT_ANN==1) ? "✔️" : "❌") $br
This equals the parallel topology: $((GATE_INIT_FMU==1 && GATE_INIT_ANN==1) ? "✔️" : "❌") $br
The neural FMU dynamics equal the FMU dynamics: $((GATE_INIT_FMU==1 && GATE_INIT_ANN==0) ? "✔️" : "❌")
"""
# ╔═╡ 1cd976fb-db40-4ebe-b40d-b996e16fc213
md"""
> 💡 Gates allow to make parts of the architecture *learnable* while still keeping the training results interpretable.
"""
# ╔═╡ 93771b35-4edd-49e3-bed1-a3ccdb7975e6
md"""
> 💭 **Further reading:** Optimizing the gates together with the ANN parameters seems a useful strategy if we don't know how FMU and ANN need to interact in the later application. Technically, we keep a part of the architecture *parameterizable* and therefore learnable. How far can we push this game?
>
> Actually to the point, that the combination of FMU and ANN is described by a single *connection* equation, that is able to express all possible combinations of both models with each other - so a connection between every pair of inputs and outputs. This is discussed in detail as part of our article [*Learnable & Interpretable Model Combination in Dynamic Systems Modeling*](https://doi.org/10.48550/arXiv.2406.08093).
"""
# ╔═╡ e79badcd-0396-4a44-9318-8c6b0a94c5c8
md"""
Time to take care of the big picture next.
"""
# ╔═╡ 2a5157c5-f5a2-4330-b2a3-0c1ec0b7adff
md"""
# Building the neural FMU
**... putting everything together**

"""
# ╔═╡ 4454c8d2-68ed-44b4-adfa-432297cdc957
md"""
## FMU inputs
In general, you can use arbitrary values as input for the FMU layer, like system inputs, states or parameters. In this example, we want to use only system states as inputs for the FMU layer - to keep it easy - which are:
- currents of both motors
- angles of both joints
- angular velocities of both joints
To preserve the ODE topology (a mapping from state to state derivative), we use all system state derivatives as layer outputs. However, you can choose further outputs if you want to... and you definitely should.
## ANN inputs
As input to the ANN, we choose at least the angular accelerations of both joints - this is fixed:
- angular acceleration Joint 1
- angular acceleration Joint 2
Pick additional ANN layer inputs:
"""
# ╔═╡ d240c95c-5aba-4b47-ab8d-2f9c0eb854cd
@bind y_refs MultiCheckBox([
STATE_A2 => "Angle Joint 2",
STATE_A1 => "Angle Joint 1",
STATE_dA1 => "Angular velocity Joint 1",
STATE_dA2 => "Angular velocity Joint 2",
VAR_TCP_PX => "TCP position x",
VAR_TCP_PY => "TCP position y",
VAR_TCP_VX => "TCP velocity x",
VAR_TCP_VY => "TCP velocity y",
VAR_TCP_F => "TCP (normal) force z",
])
# ╔═╡ 06937575-9ab1-41cd-960c-7eef3e8cae7f
md"""
It might be clever to pick additional inputs, because the effect being learned (slip-stick of the pen) might depend on these additional inputs. However, every additional signal has a little negative impact on the computational performance and a risk of learning from wrong correlations.
"""
# ╔═╡ 356b6029-de66-418f-8273-6db6464f9fbf
md"""
## ANN size
"""
# ╔═╡ 5805a216-2536-44ac-a702-d92e86d435a4
md"""
The ANN shall have $(@bind NUM_LAYERS Select([2, 3, 4])) layers with a width of $(@bind LAYERS_WIDTH Select([8, 16, 32])) each.
"""
# ╔═╡ 53e971d8-bf43-41cc-ac2b-20dceaa78667
@bind GATES_INIT Slider(0.0:0.1:1.0, default = 0.0)
# ╔═╡ 68d57a23-68c3-418c-9c6f-32bdf8cafceb
md"""
The ANN gates shall be initialized with $(GATES_INIT), slide to change:
"""
# ╔═╡ e8b8c63b-2ca4-4e6a-a801-852d6149283e
md"""
ANN gates shall be initialized with $(GATES_INIT), meaning the ANN contributes $(GATES_INIT*100)% to the hybrid model derivatives, while the FMU contributes $(100-GATES_INIT*100)%. These parameters are adapted during training, these are only start values.
"""
# ╔═╡ c0ac7902-0716-4f18-9447-d18ce9081ba5
md"""
## Resulting neural FMU
Our final neural FMU topology looks like this:
"""
# ╔═╡ 84215a73-1ab0-416d-a9db-6b29cd4f5d2a
begin
function build_topology(gates_init, add_y_refs, nl, lw)
ANN_input_Vars = [recordValues[1:2]..., add_y_refs...]
ANN_input_Vals = fmiGetSolutionValue(sol_fmu_train, ANN_input_Vars)
ANN_input_Idcs = [4, 6]
for i = 1:length(add_y_refs)
push!(ANN_input_Idcs, i + 6)
end
# pre- and post-processing
preProcess = ShiftScale(ANN_input_Vals) # we put in the derivatives recorded above, FMIFlux shift and scales so we have a data mean of 0 and a standard deviation of 1
#preProcess.scale[:] *= 0.1 # add some additional "buffer"
postProcess = ScaleShift(preProcess; indices = [1, 2]) # initialize the postProcess as inverse of the preProcess, but only take indices 1 and 2
# cache
cache = CacheLayer() # allocate a cache layer
cacheRetrieve = CacheRetrieveLayer(cache) # allocate a cache retrieve layer, link it to the cache layer
gates = ScaleSum(
[1.0 - gates_init, 1.0 - gates_init, gates_init, gates_init],
[[1, 3], [2, 4]],
) # gates with sum
ANN_layers = []
push!(ANN_layers, Dense(2 + length(add_y_refs), lw, tanh)) # first layer
for i = 3:nl
push!(ANN_layers, Dense(lw, lw, tanh))
end
push!(ANN_layers, Dense(lw, 2, tanh)) # last layer
model = Flux.f64(
Chain(
x -> fmu(; x = x, dx_refs = :all, y_refs = add_y_refs),
dxy -> cache(dxy), # cache `dx`
dxy -> dxy[ANN_input_Idcs],
preProcess,
ANN_layers...,
postProcess,
dx -> cacheRetrieve(4, 6, dx), # dynamics FMU | dynamics ANN
gates, # compute resulting dx from ANN + FMU
dx -> cacheRetrieve(1:3, dx[1], 5, dx[2]),
),
)
return model
end
HIDDEN_CODE_MESSAGE
end
# ╔═╡ bc09bd09-2874-431a-bbbb-3d53c632be39
md"""
We find a `Chain` consisting of multipl layers and the corresponding parameter counts. We can evaluate it, by putting in our start state `x0`. The model computes the resulting state derivative:
"""
# ╔═╡ f02b9118-3fb5-4846-8c08-7e9bbca9d208
md"""
On basis of this `Chain`, we can build a neural FMU very easy:
"""
# ╔═╡ d347d51b-743f-4fec-bed7-6cca2b17bacb
md"""
So let's get that thing trained!
# Training
After setting everything up, we can give it a try and train our created neural FMU. Depending on the chosen optimization hyperparameters, this will be more or less successful. Feel free to play around a bit, but keep in mind that for real application design, you should do hyper parameter optimization instead of playing around by yourself.
"""
# ╔═╡ d60d2561-51a4-4f8a-9819-898d70596e0c
md"""
## Hyperparameters
Besides the already introduced hyperparameters - the depth, width and initial gate opening of the hybrid model - further parameters might have significant impact on the training success.
### Optimizer
For this example, we use the well-known `Adam`-Optimizer with a step size `eta` of $(@bind ETA Select([1e-4 => "1e-4", 1e-3 => "1e-3", 1e-2 => "1e-2"])).
### Batching
Because data has a significant length, gradient computation over the entire simulation trajectory might not be effective. The most common approach is to *cut* data into slices and train on these subsets instead of the entire trajectory at once. In this example, data is cut in pieces with length of $(@bind BATCHDUR Select([0.05, 0.1, 0.15, 0.2])) seconds.
"""
# ╔═╡ c97f2dea-cb18-409d-9ae8-1d03647a6bb3
md"""
This results in a batch with $(round(Integer, data_train.t[end] / BATCHDUR)) elements.
"""
# ╔═╡ 366abd1a-bcb5-480d-b1fb-7c76930dc8fc
md"""
We use a simple `Random` scheduler here, that picks a random batch element for the next training step. Other schedulers are pre-implemented in *FMIFlux.jl*.
"""
# ╔═╡ 7e2ffd6f-19b0-435d-8e3c-df24a591bc55
md"""
### Loss Function
Different loss functions are thinkable here. Two quantities that should be considered are the motor currents and the motor revolution speeds. For this workshop we use the *Mean Average Error* (MAE) over the motor currents. Other loss functions can easily be deployed.
"""
# ╔═╡ caa5e04a-2375-4c56-8072-52c140adcbbb
# goal is to match the motor currents (they can be recorded easily in the real application)
function loss(solution::FMU2Solution, data::FMIZoo.RobotRR_Data)
# determine the start/end indices `ts` and `te` (sampled with 100Hz)
dt = 0.01
ts = 1 + round(Integer, solution.states.t[1] / dt)
te = 1 + round(Integer, solution.states.t[end] / dt)
# retrieve simulation data from neural FMU ("where we are") and data from measurements ("where we want to be")
i1_value = fmiGetSolutionState(solution, STATE_I1)
i2_value = fmiGetSolutionState(solution, STATE_I2)
i1_data = data.i1[ts:te]
i2_data = data.i2[ts:te]
# accumulate our loss value
Δvalue = 0.0
Δvalue += FMIFlux.Losses.mae(i1_value, i1_data)
Δvalue += FMIFlux.Losses.mae(i2_value, i2_data)
return Δvalue
end
# ╔═╡ 69657be6-6315-4655-81e2-8edef7f21e49
md"""
For example, the loss function value of the plain FMU is $(round(loss(sol_fmu_train, data_train); digits=6)).
"""
# ╔═╡ 23ad65c8-5723-4858-9abe-750c3b65c28a
md"""
## Summary
To summarize, your ANN has a **depth of $(NUM_LAYERS) layers** with a **width of $(LAYERS_WIDTH)** each. The **ANN gates are initialized with $(GATES_INIT*100)%**, so all FMU gates are initialized with $(100-GATES_INIT*100)%. You decided to batch your data with a **batch element length of $(BATCHDUR)** seconds. Besides the state derivatives, you **put $(length(y_refs)) additional variables** in the ANN. Adam optimizer will try to find a good minimum with **`eta` is $(ETA)**.
Batching takes a few seconds and training a few minutes (depending on the number of training steps), so this is not triggered automatically. If you are ready to go, choose a number of training steps and check the checkbox `Start Training`. This will start a training of $(@bind STEPS Select([0, 10, 100, 1000, 2500, 5000, 10000])) training steps. Alternatively, you can change the training mode to `demo` which loads parameters from a pre-trained model.
"""
# ╔═╡ abc57328-4de8-42d8-9e79-dd4020769dd9
md"""
Select training mode:
$(@bind MODE Select([:train => "Training", :demo => "Demo (pre-trained)"]))
"""
# ╔═╡ f9d35cfd-4ae5-4dcd-94d9-02aefc99bdfb
begin
using JLD2
if MODE == :train
final_model = build_topology(GATES_INIT, y_refs, NUM_LAYERS, LAYERS_WIDTH)
elseif MODE == :demo
final_model = build_topology(
0.2,
[STATE_A2, STATE_A1, VAR_TCP_VX, VAR_TCP_VY, VAR_TCP_F],
3,
32,
)
end
end
# ╔═╡ f741b213-a20d-423a-a382-75cae1123f2c
final_model(x0)
# ╔═╡ 91473bef-bc23-43ed-9989-34e62166d455
begin
neuralFMU = ME_NeuralFMU(
fmu, # the FMU used in the neural FMU
final_model, # the model we specified above
(tStart, tStop),# start and stop time for solving
solver; # the solver (Tsit5)
saveat = tSave,
) # time points to save the solution at
end
# ╔═╡ 404ca10f-d944-4a9f-addb-05efebb4f159
begin
import Downloads
demo_path = Downloads.download(
"https://github.com/ThummeTo/FMIFlux.jl/blob/main/examples/pluto-src/SciMLUsingFMUs/src/20000.jld2?raw=true",
)
# in demo mode, we load parameters from a pre-trained model
if MODE == :demo
fmiLoadParameters(neuralFMU, demo_path)
end
HIDDEN_CODE_MESSAGE
end
# ╔═╡ e8bae97d-9f90-47d2-9263-dc8fc065c3d0
begin
neuralFMU
y_refs
NUM_LAYERS
LAYERS_WIDTH
GATES_INIT
ETA
BATCHDUR
MODE
if MODE == :train
md"""⚠️ The roughly estimated training time is **$(round(Integer, STEPS*10*BATCHDUR + 0.6/BATCHDUR)) seconds** (Windows, i7 @ 3.6GHz). Training might be faster if the system is less stiff than expected. Once you started training by clicking on `Start Training`, training can't be terminated easily.
🎬 **Start Training** $(@bind LIVE_TRAIN CheckBox())
"""
else
LIVE_TRAIN = false
md"""ℹ️ No training in demo mode. Please continue with plotting results.
"""
end
end
# ╔═╡ 2dce68a7-27ec-4ffc-afba-87af4f1cb630
begin
function train(eta, batchdur, steps)
if steps == 0
return md"""⚠️ Number of training steps is `0`, no training."""
end
prepareSolveFMU(fmu, parameters)
train_t = data_train.t
train_data = collect([data_train.i2[i], data_train.i1[i]] for i = 1:length(train_t))
#@info
@info "Started batching ..."
batch = batchDataSolution(
neuralFMU, # our neural FMU model
t -> FMIZoo.getState(data_train, t), # a function returning a start state for a given time point `t`, to determine start states for batch elements
train_t, # data time points
train_data; # data cumulative consumption
batchDuration = batchdur, # duration of one batch element
indicesModel = [1, 2], # model indices to train on (1 and 2 equal the `electrical current` states)
plot = false, # don't show intermediate plots (try this outside of Pluto)
showProgress = false,
parameters = parameters,
)
@info "... batching finished!"
# a random element scheduler
scheduler = RandomScheduler(neuralFMU, batch; applyStep = 1, plotStep = 0)
lossFct = (solution::FMU2Solution) -> loss(solution, data_train)
maxiters = round(Int, 1e5 * batchdur)
_loss =
p -> FMIFlux.Losses.loss(
neuralFMU, # the neural FMU to simulate
batch; # the batch to take an element from
p = p, # the neural FMU training parameters (given as input)
lossFct = lossFct, # our custom loss function
batchIndex = scheduler.elementIndex, # the index of the batch element to take, determined by the chosen scheduler
logLoss = true, # log losses after every evaluation
showProgress = false,
parameters = parameters,
maxiters = maxiters,
)
params = FMIFlux.params(neuralFMU)
FMIFlux.initialize!(
scheduler;
p = params[1],
showProgress = false,
parameters = parameters,
print = false,
)
BETA1 = 0.9
BETA2 = 0.999
optim = Adam(eta, (BETA1, BETA2))
@info "Started training ..."
@withprogress name = "iterating" begin
iteration = 0
function cb()
iteration += 1
@logprogress iteration / steps
FMIFlux.update!(scheduler; print = false)
nothing
end
FMIFlux.train!(
_loss, # the loss function for training
neuralFMU, # the parameters to train
Iterators.repeated((), steps), # an iterator repeating `steps` times
optim; # the optimizer to train
gradient = :ReverseDiff, # use ReverseDiff, because it's much faster!
cb = cb, # update the scheduler after every step
proceed_on_assert = true,
) # go on if a training steps fails (e.g. because of instability)
end
@info "... training finished!"
end
HIDDEN_CODE_MESSAGE
end
# ╔═╡ c3f5704b-8e98-4c46-be7a-18ab4f139458
let
if MODE == :train
if LIVE_TRAIN
train(ETA, BATCHDUR, STEPS)
else
LIVE_TRAIN_MESSAGE
end
else
md"""ℹ️ No training in demo mode. Please continue with plotting results.
"""
end
end
# ╔═╡ 1a608bc8-7264-4dd3-a4e7-0e39128a8375
md"""
> 💡 Playing around with hyperparameters is fun, but keep in mind that this is not a suitable method for finding good hyperparameters in real world engineering. Do a hyperparameter optimization instead.
"""
# ╔═╡ ff106912-d18c-487f-bcdd-7b7af2112cab
md"""
# Results
Now it's time to find out if it worked! Plotting results makes the notebook slow, so it's deactivated by default. Activate it to plot results of your training.
## Training results
Let's check out the *training* results of the freshly trained neural FMU.
"""
# ╔═╡ 51eeb67f-a984-486a-ab8a-a2541966fa72
begin
neuralFMU
MODE
LIVE_TRAIN
md"""
🎬 **Plot results** $(@bind LIVE_RESULTS CheckBox())
"""
end
# ╔═╡ 27458e32-5891-4afc-af8e-7afdf7e81cc6
begin
function plotPaths!(fig, t, x, N; color = :black, label = :none, kwargs...)
paths = []
path = nothing
lastN = N[1]
for i = 1:length(N)
if N[i] == 0.0
if lastN == 1.0
push!(path, (t[i], x[i]))
push!(paths, path)
end
end
if N[i] == 1.0
if lastN == 0.0
path = []
end
push!(path, (t[i], x[i]))
end
lastN = N[i]
end
if length(path) > 0
push!(paths, path)
end
isfirst = true
for path in paths
plot!(
fig,
collect(v[1] for v in path),
collect(v[2] for v in path);
label = isfirst ? label : :none,
color = color,
kwargs...,
)
isfirst = false
end
return fig
end
HIDDEN_CODE_MESSAGE
end
# ╔═╡ 737e2c50-0858-4205-bef3-f541e33b85c3
md"""
### FMU
Simulating the FMU (training data):
"""
# ╔═╡ 5dd491a4-a8cd-4baf-96f7-7a0b850bb26c
begin
fmu_train = fmiSimulate(
fmu,
(data_train.t[1], data_train.t[end]);
x0 = x0,
parameters = Dict{String,Any}("fileName" => data_train.params["fileName"]),
recordValues = [
"rRPositionControl_Elasticity.tCP.p_x",
"rRPositionControl_Elasticity.tCP.p_y",
"rRPositionControl_Elasticity.tCP.N",
"rRPositionControl_Elasticity.tCP.a_x",
"rRPositionControl_Elasticity.tCP.a_y",
],
showProgress = true,
maxiters = 1e6,
saveat = data_train.t,
solver = Tsit5(),
)
nothing
end
# ╔═╡ 4f27b6c0-21da-4e26-aaad-ff453c8af3da
md"""
### Neural FMU
Simulating the neural FMU (training data):
"""
# ╔═╡ 1195a30c-3b48-4bd2-8a3a-f4f74f3cd864
begin
if LIVE_RESULTS
result_train = neuralFMU(
x0,
(data_train.t[1], data_train.t[end]);
parameters = Dict{String,Any}("fileName" => data_train.params["fileName"]),
recordValues = [
"rRPositionControl_Elasticity.tCP.p_x",
"rRPositionControl_Elasticity.tCP.p_y",
"rRPositionControl_Elasticity.tCP.N",
"rRPositionControl_Elasticity.tCP.v_x",
"rRPositionControl_Elasticity.tCP.v_y",
],
showProgress = true,
maxiters = 1e6,
saveat = data_train.t,
)
nothing
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ b0ce7b92-93e0-4715-8324-3bf4ff42a0b3
let
if LIVE_RESULTS
loss_fmu = loss(fmu_train, data_train)
loss_nfmu = loss(result_train, data_train)
md"""
#### The word `train`
The loss function value of the FMU on training data is $(round(loss_fmu; digits=6)), of the neural FMU it is $(round(loss_nfmu; digits=6)). The neural FMU is about $(round(loss_fmu/loss_nfmu; digits=1)) times more accurate.
"""
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ 919419fe-35de-44bb-89e4-8f8688bee962
let
if LIVE_RESULTS
fig = plot(; dpi = 300, size = (200 * 3, 60 * 3))
plotPaths!(
fig,
data_train.tcp_px,
data_train.tcp_py,
data_train.tcp_norm_f,
label = "Data",
color = :black,
style = :dash,
)
plotPaths!(
fig,
collect(v[1] for v in fmu_train.values.saveval),
collect(v[2] for v in fmu_train.values.saveval),
collect(v[3] for v in fmu_train.values.saveval),
label = "FMU",
color = :orange,
)
plotPaths!(
fig,
collect(v[1] for v in result_train.values.saveval),
collect(v[2] for v in result_train.values.saveval),
collect(v[3] for v in result_train.values.saveval),
label = "Neural FMU",
color = :blue,
)
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ ed25a535-ca2f-4cd2-b0af-188e9699f1c3
md"""
#### The letter `a`
"""
# ╔═╡ 2918daf2-6499-4019-a04b-8c3419ee1ab7
let
if LIVE_RESULTS
fig = plot(;
dpi = 300,
size = (40 * 10, 40 * 10),
xlims = (0.165, 0.205),
ylims = (-0.035, 0.005),
)
plotPaths!(
fig,
data_train.tcp_px,
data_train.tcp_py,
data_train.tcp_norm_f,
label = "Data",
color = :black,
style = :dash,
)
plotPaths!(
fig,
collect(v[1] for v in fmu_train.values.saveval),
collect(v[2] for v in fmu_train.values.saveval),
collect(v[3] for v in fmu_train.values.saveval),
label = "FMU",
color = :orange,
)
plotPaths!(
fig,
collect(v[1] for v in result_train.values.saveval),
collect(v[2] for v in result_train.values.saveval),
collect(v[3] for v in result_train.values.saveval),
label = "Neural FMU",
color = :blue,
)
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ d798a5d0-3017-4eab-9cdf-ee85d63dfc49
md"""
#### The letter `n`
"""
# ╔═╡ 048e39c3-a3d9-4e6b-b050-1fd5a919e4ae
let
if LIVE_RESULTS
fig = plot(;
dpi = 300,
size = (50 * 10, 40 * 10),
xlims = (0.245, 0.295),
ylims = (-0.04, 0.0),
)
plotPaths!(
fig,
data_train.tcp_px,
data_train.tcp_py,
data_train.tcp_norm_f,
label = "Data",
color = :black,
style = :dash,
)
plotPaths!(
fig,
collect(v[1] for v in fmu_train.values.saveval),
collect(v[2] for v in fmu_train.values.saveval),
collect(v[3] for v in fmu_train.values.saveval),
label = "FMU",
color = :orange,
)
plotPaths!(
fig,
collect(v[1] for v in result_train.values.saveval),
collect(v[2] for v in result_train.values.saveval),
collect(v[3] for v in result_train.values.saveval),
label = "Neural FMU",
color = :blue,
)
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ b489f97d-ee90-48c0-af06-93b66a1f6d2e
md"""
## Validation results
Let's check out the *validation* results of the freshly trained neural FMU.
"""
# ╔═╡ 4dad3e55-5bfd-4315-bb5a-2680e5cbd11c
md"""
### FMU
Simulating the FMU (validation data):
"""
# ╔═╡ ea0ede8d-7c2c-4e72-9c96-3260dc8d817d
begin
fmu_validation = fmiSimulate(
fmu,
(data_validation.t[1], data_validation.t[end]);
x0 = x0,
parameters = Dict{String,Any}("fileName" => data_validation.params["fileName"]),
recordValues = [
"rRPositionControl_Elasticity.tCP.p_x",
"rRPositionControl_Elasticity.tCP.p_y",
"rRPositionControl_Elasticity.tCP.N",
],
showProgress = true,
maxiters = 1e6,
saveat = data_validation.t,
solver = Tsit5(),
)
nothing
end
# ╔═╡ 35f52dbc-0c0b-495e-8fd4-6edbc6fa811e
md"""
### Neural FMU
Simulating the neural FMU (validation data):
"""
# ╔═╡ 51aed933-2067-4ea8-9c2f-9d070692ecfc
begin
if LIVE_RESULTS
result_validation = neuralFMU(
x0,
(data_validation.t[1], data_validation.t[end]);
parameters = Dict{String,Any}("fileName" => data_validation.params["fileName"]),
recordValues = [
"rRPositionControl_Elasticity.tCP.p_x",
"rRPositionControl_Elasticity.tCP.p_y",
"rRPositionControl_Elasticity.tCP.N",
],
showProgress = true,
maxiters = 1e6,
saveat = data_validation.t,
)
nothing
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ 8d9dc86e-f38b-41b1-80c6-b2ab6f488a3a
begin
if LIVE_RESULTS
loss_fmu = loss(fmu_validation, data_validation)
loss_nfmu = loss(result_validation, data_validation)
md"""
#### The word `validate`
The loss function value of the FMU on validation data is $(round(loss_fmu; digits=6)), of the neural FMU it is $(round(loss_nfmu; digits=6)). The neural FMU is about $(round(loss_fmu/loss_nfmu; digits=1)) times more accurate.
"""
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ 74ef5a39-1dd7-404a-8baf-caa1021d3054
let
if LIVE_RESULTS
fig = plot(; dpi = 300, size = (200 * 3, 40 * 3))
plotPaths!(
fig,
data_validation.tcp_px,
data_validation.tcp_py,
data_validation.tcp_norm_f,
label = "Data",
color = :black,
style = :dash,
)
plotPaths!(
fig,
collect(v[1] for v in fmu_validation.values.saveval),
collect(v[2] for v in fmu_validation.values.saveval),
collect(v[3] for v in fmu_validation.values.saveval),
label = "FMU",
color = :orange,
)
plotPaths!(
fig,
collect(v[1] for v in result_validation.values.saveval),
collect(v[2] for v in result_validation.values.saveval),
collect(v[3] for v in result_validation.values.saveval),
label = "Neural FMU",
color = :blue,
)
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ 347d209b-9d41-48b0-bee6-0d159caacfa9
md"""
#### The letter `d`
"""
# ╔═╡ 05281c4f-dba8-4070-bce3-dc2f1319902e
let
if LIVE_RESULTS
fig = plot(;
dpi = 300,
size = (35 * 10, 50 * 10),
xlims = (0.188, 0.223),
ylims = (-0.025, 0.025),
)
plotPaths!(
fig,
data_validation.tcp_px,
data_validation.tcp_py,
data_validation.tcp_norm_f,
label = "Data",
color = :black,
style = :dash,
)
plotPaths!(
fig,
collect(v[1] for v in fmu_validation.values.saveval),
collect(v[2] for v in fmu_validation.values.saveval),
collect(v[3] for v in fmu_validation.values.saveval),
label = "FMU",
color = :orange,
)
plotPaths!(
fig,
collect(v[1] for v in result_validation.values.saveval),
collect(v[2] for v in result_validation.values.saveval),
collect(v[3] for v in result_validation.values.saveval),
label = "Neural FMU",
color = :blue,
)
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ 590d7f24-c6b6-4524-b3db-0c93d9963b74
md"""
#### The letter `t`
"""
# ╔═╡ 67cfe7c5-8e62-4bf0-996b-19597d5ad5ef
let
if LIVE_RESULTS
fig = plot(;
dpi = 300,
size = (25 * 10, 50 * 10),
xlims = (0.245, 0.27),
ylims = (-0.025, 0.025),
legend = :topleft,
)
plotPaths!(
fig,
data_validation.tcp_px,
data_validation.tcp_py,
data_validation.tcp_norm_f,
label = "Data",
color = :black,
style = :dash,
)
plotPaths!(
fig,
collect(v[1] for v in fmu_validation.values.saveval),
collect(v[2] for v in fmu_validation.values.saveval),
collect(v[3] for v in fmu_validation.values.saveval),
label = "FMU",
color = :orange,
)
plotPaths!(
fig,
collect(v[1] for v in result_validation.values.saveval),
collect(v[2] for v in result_validation.values.saveval),
collect(v[3] for v in result_validation.values.saveval),
label = "Neural FMU",
color = :blue,
)
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ e6dc8aab-82c1-4dc9-a1c8-4fe9c137a146
md"""
#### The letter `e`
"""
# ╔═╡ dfee214e-bd13-4d4f-af8e-20e0c4e0de9b
let
if LIVE_RESULTS
fig = plot(;
dpi = 300,
size = (25 * 10, 30 * 10),
xlims = (0.265, 0.29),
ylims = (-0.025, 0.005),
legend = :topleft,
)
plotPaths!(
fig,
data_validation.tcp_px,
data_validation.tcp_py,
data_validation.tcp_norm_f,
label = "Data",
color = :black,
style = :dash,
)
plotPaths!(
fig,
collect(v[1] for v in fmu_validation.values.saveval),
collect(v[2] for v in fmu_validation.values.saveval),
collect(v[3] for v in fmu_validation.values.saveval),
label = "FMU",
color = :orange,
)
plotPaths!(
fig,
collect(v[1] for v in result_validation.values.saveval),
collect(v[2] for v in result_validation.values.saveval),
collect(v[3] for v in result_validation.values.saveval),
label = "Neural FMU",
color = :blue,
)
else
LIVE_RESULTS_MESSAGE
end
end
# ╔═╡ 88884204-79e4-4412-b861-ebeb5f6f7396
md"""
# Conclusion
Hopefully you got a good first insight in the topic hybrid modeling using FMI and collected your first sense of achievement. Did you find a nice optimum? In case you don't, some rough hyper parameters are given below.
## Hint
If your results are not *that* promising, here is a set of hyperparameters to check. It is *not* a optimal set of parameters, but a *good* set, so feel free to explore the *best*!
| Parameter | Value |
| ----- | ----- |
| eta | 1e-3 |
| layer count | 3 |
| layer width | 32 |
| initial gate opening | 0.2 |
| batch element length | 0.05s |
| training steps | $\geq$ 10 000 |
| additional variables | Joint 1 Angle $br Joint 2 Angle $br TCP velocity x $br TCP velocity y $br TCP nominal force |
## Citation
If you find this workshop useful for your own work and/or research, please cite our related publication:
Tobias Thummerer, Johannes Stoljar and Lars Mikelsons. 2022. **NeuralFMU: presenting a workflow for integrating hybrid neuralODEs into real-world applications.** Electronics 11, 19, 3202. DOI: 10.3390/electronics11193202
## Acknowlegments
- the FMU was created using the excellent Modelica library *Servomechanisms* $br (https://github.com/afrhu/Servomechanisms)
- the linked YouTube video in the introduction is by *Alexandru Babaian* $br (https://www.youtube.com/watch?v=ryIwLLr6yRA)
"""
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
Downloads = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
FMI = "14a09403-18e3-468f-ad8a-74f8dda2d9ac"
FMIFlux = "fabad875-0d53-4e47-9446-963b74cae21f"
FMIZoo = "724179cf-c260-40a9-bd27-cccc6fe2f195"
JLD2 = "033835bb-8acc-5ee8-8aae-3f567f8a3819"
PlotlyJS = "f0f68f2c-4968-5e81-91da-67840de0976a"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
ProgressLogging = "33c8b6b6-d38a-422a-b730-caa89a2f386c"
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[compat]
BenchmarkTools = "~1.5.0"
FMI = "~0.13.3"
FMIFlux = "~0.12.2"
FMIZoo = "~0.3.3"
JLD2 = "~0.4.49"
PlotlyJS = "~0.18.13"
Plots = "~1.40.5"
PlutoUI = "~0.7.59"
ProgressLogging = "~0.1.4"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.10.3"
manifest_format = "2.0"
project_hash = "79772b37e2cae2421c7159b63f3cbe881b42eaeb"
[[deps.ADTypes]]
git-tree-sha1 = "016833eb52ba2d6bea9fcb50ca295980e728ee24"
uuid = "47edcb42-4c32-4615-8424-f2b9edc5f35b"
version = "0.2.7"
[[deps.AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.5.0"
weakdeps = ["ChainRulesCore", "Test"]
[deps.AbstractFFTs.extensions]
AbstractFFTsChainRulesCoreExt = "ChainRulesCore"
AbstractFFTsTestExt = "Test"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "6e1d2a35f2f90a4bc7c2ed98079b2ba09c35b83a"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.3.2"
[[deps.Accessors]]
deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "LinearAlgebra", "MacroTools", "Markdown", "Test"]
git-tree-sha1 = "c0d491ef0b135fd7d63cbc6404286bc633329425"
uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
version = "0.1.36"
[deps.Accessors.extensions]
AccessorsAxisKeysExt = "AxisKeys"
AccessorsIntervalSetsExt = "IntervalSets"
AccessorsStaticArraysExt = "StaticArrays"
AccessorsStructArraysExt = "StructArrays"
AccessorsUnitfulExt = "Unitful"
[deps.Accessors.weakdeps]
AxisKeys = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5"
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
Requires = "ae029012-a4dd-5104-9daa-d747884805df"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "6a55b747d1812e699320963ffde36f1ebdda4099"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "4.0.4"
weakdeps = ["StaticArrays"]
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[[deps.AliasTables]]
deps = ["PtrArrays", "Random"]
git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff"
uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8"
version = "1.1.3"
[[deps.ArgCheck]]
git-tree-sha1 = "a3a402a35a2f7e0b87828ccabbd5ebfbebe356b4"
uuid = "dce04be8-c92d-5529-be00-80e4d2c0e197"
version = "2.3.0"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.ArnoldiMethod]]
deps = ["LinearAlgebra", "Random", "StaticArrays"]
git-tree-sha1 = "d57bd3762d308bded22c3b82d033bff85f6195c6"
uuid = "ec485272-7323-5ecc-a04f-4719b315124d"
version = "0.4.0"
[[deps.ArrayInterface]]
deps = ["Adapt", "LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "ed2ec3c9b483842ae59cd273834e5b46206d6dda"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "7.11.0"
[deps.ArrayInterface.extensions]
ArrayInterfaceBandedMatricesExt = "BandedMatrices"
ArrayInterfaceBlockBandedMatricesExt = "BlockBandedMatrices"
ArrayInterfaceCUDAExt = "CUDA"
ArrayInterfaceCUDSSExt = "CUDSS"
ArrayInterfaceChainRulesExt = "ChainRules"
ArrayInterfaceGPUArraysCoreExt = "GPUArraysCore"
ArrayInterfaceReverseDiffExt = "ReverseDiff"
ArrayInterfaceStaticArraysCoreExt = "StaticArraysCore"
ArrayInterfaceTrackerExt = "Tracker"
[deps.ArrayInterface.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
CUDSS = "45b445bb-4962-46a0-9369-b4df9d0f772e"
ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2"
GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527"
ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267"
StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
[[deps.ArrayLayouts]]
deps = ["FillArrays", "LinearAlgebra"]
git-tree-sha1 = "600078184f7de14b3e60efe13fc0ba5c59f6dca5"
uuid = "4c555306-a7a7-4459-81d9-ec55ddd5c99a"
version = "1.10.0"
weakdeps = ["SparseArrays"]
[deps.ArrayLayouts.extensions]
ArrayLayoutsSparseArraysExt = "SparseArrays"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.AssetRegistry]]
deps = ["Distributed", "JSON", "Pidfile", "SHA", "Test"]
git-tree-sha1 = "b25e88db7944f98789130d7b503276bc34bc098e"
uuid = "bf4720bc-e11a-5d0c-854e-bdca1663c893"
version = "0.1.0"
[[deps.Atomix]]
deps = ["UnsafeAtomics"]
git-tree-sha1 = "c06a868224ecba914baa6942988e2f2aade419be"
uuid = "a9b6321e-bd34-4604-b9c9-b65b8de01458"
version = "0.1.0"
[[deps.AxisAlgorithms]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"]
git-tree-sha1 = "01b8ccb13d68535d73d2b0c23e39bd23155fb712"
uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950"
version = "1.1.0"
[[deps.BandedMatrices]]
deps = ["ArrayLayouts", "FillArrays", "LinearAlgebra", "PrecompileTools"]
git-tree-sha1 = "71f605effb24081b09cae943ba39ef9ca90c04f4"
uuid = "aae01518-5342-5314-be14-df237901396f"
version = "1.7.2"
weakdeps = ["SparseArrays"]
[deps.BandedMatrices.extensions]
BandedMatricesSparseArraysExt = "SparseArrays"
[[deps.BangBang]]
deps = ["Compat", "ConstructionBase", "InitialValues", "LinearAlgebra", "Requires", "Setfield", "Tables"]
git-tree-sha1 = "7aa7ad1682f3d5754e3491bb59b8103cae28e3a3"
uuid = "198e06fe-97b7-11e9-32a5-e1d131e6ad66"
version = "0.3.40"
[deps.BangBang.extensions]
BangBangChainRulesCoreExt = "ChainRulesCore"
BangBangDataFramesExt = "DataFrames"
BangBangStaticArraysExt = "StaticArrays"
BangBangStructArraysExt = "StructArrays"
BangBangTypedTablesExt = "TypedTables"
[deps.BangBang.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
TypedTables = "9d95f2ec-7b3d-5a63-8d20-e2491e220bb9"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.Baselet]]
git-tree-sha1 = "aebf55e6d7795e02ca500a689d326ac979aaf89e"
uuid = "9718e550-a3fa-408a-8086-8db961cd8217"
version = "0.1.1"
[[deps.BenchmarkTools]]
deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"]
git-tree-sha1 = "f1dff6729bc61f4d49e140da1af55dcd1ac97b2f"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "1.5.0"
[[deps.BitFlags]]
git-tree-sha1 = "0691e34b3bb8be9307330f88d1a3c3f25466c24d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.9"
[[deps.BitTwiddlingConvenienceFunctions]]
deps = ["Static"]
git-tree-sha1 = "f21cfd4950cb9f0587d5067e69405ad2acd27b87"
uuid = "62783981-4cbd-42fc-bca8-16325de8dc4b"
version = "0.1.6"
[[deps.Blink]]
deps = ["Base64", "Distributed", "HTTP", "JSExpr", "JSON", "Lazy", "Logging", "MacroTools", "Mustache", "Mux", "Pkg", "Reexport", "Sockets", "WebIO"]
git-tree-sha1 = "bc93511973d1f949d45b0ea17878e6cb0ad484a1"
uuid = "ad839575-38b3-5650-b840-f874b8c74a25"
version = "0.12.9"
[[deps.BoundaryValueDiffEq]]
deps = ["ADTypes", "Adapt", "ArrayInterface", "BandedMatrices", "ConcreteStructs", "DiffEqBase", "FastAlmostBandedMatrices", "FastClosures", "ForwardDiff", "LinearAlgebra", "LinearSolve", "Logging", "NonlinearSolve", "OrdinaryDiffEq", "PreallocationTools", "PrecompileTools", "Preferences", "RecursiveArrayTools", "Reexport", "SciMLBase", "Setfield", "SparseArrays", "SparseDiffTools"]
git-tree-sha1 = "005b55fa2eebaa4d7bf3cfb8097807f47116175f"
uuid = "764a87c0-6b3e-53db-9096-fe964310641d"
version = "5.7.1"
[deps.BoundaryValueDiffEq.extensions]
BoundaryValueDiffEqODEInterfaceExt = "ODEInterface"
[deps.BoundaryValueDiffEq.weakdeps]
ODEInterface = "54ca160b-1b9f-5127-a996-1867f4bc2a2c"
[[deps.BufferedStreams]]
git-tree-sha1 = "4ae47f9a4b1dc19897d3743ff13685925c5202ec"
uuid = "e1450e63-4bb3-523b-b2a4-4ffa8c0fd77d"
version = "1.2.1"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "9e2a6b69137e6969bab0152632dcb3bc108c8bdd"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+1"
[[deps.CEnum]]
git-tree-sha1 = "389ad5c84de1ae7cf0e28e381131c98ea87d54fc"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.5.0"
[[deps.CPUSummary]]
deps = ["CpuId", "IfElse", "PrecompileTools", "Static"]
git-tree-sha1 = "5a97e67919535d6841172016c9530fd69494e5ec"
uuid = "2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9"
version = "0.2.6"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "a2f1c8c668c8e3cb4cca4e57a8efdb09067bb3fd"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.18.0+2"
[[deps.Calculus]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "f641eb0a4f00c343bbc32346e1217b86f3ce9dad"
uuid = "49dc2e85-a5d0-5ad3-a950-438e2897f1b9"
version = "0.5.1"
[[deps.Cassette]]
git-tree-sha1 = "0970356c3bb9113309c74c27c87083cf9c73880a"
uuid = "7057c7e9-c182-5462-911a-8362d720325c"
version = "0.3.13"
[[deps.ChainRules]]
deps = ["Adapt", "ChainRulesCore", "Compat", "Distributed", "GPUArraysCore", "IrrationalConstants", "LinearAlgebra", "Random", "RealDot", "SparseArrays", "SparseInverseSubset", "Statistics", "StructArrays", "SuiteSparse"]
git-tree-sha1 = "227985d885b4dbce5e18a96f9326ea1e836e5a03"
uuid = "082447d4-558c-5d27-93f4-14fc19e9eca2"
version = "1.69.0"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra"]
git-tree-sha1 = "71acdbf594aab5bbb2cec89b208c41b4c411e49f"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.24.0"
weakdeps = ["SparseArrays"]
[deps.ChainRulesCore.extensions]
ChainRulesCoreSparseArraysExt = "SparseArrays"
[[deps.CloseOpenIntervals]]
deps = ["Static", "StaticArrayInterface"]
git-tree-sha1 = "05ba0d07cd4fd8b7a39541e31a7b0254704ea581"
uuid = "fb6a15b2-703c-40df-9091-08a04967cfa9"
version = "0.1.13"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "59939d8a997469ee05c4b4944560a820f9ba0d73"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.4"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"]
git-tree-sha1 = "4b270d6465eb21ae89b732182c20dc165f8bf9f2"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.25.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "b10d0b65641d57b8b4d5e234446582de5047050d"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.5"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"]
git-tree-sha1 = "a1f44953f2382ebb937d60dafbe2deea4bd23249"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.10.0"
weakdeps = ["SpecialFunctions"]
[deps.ColorVectorSpace.extensions]
SpecialFunctionsExt = "SpecialFunctions"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "362a287c3aa50601b0bc359053d5c2468f0e7ce0"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.11"
[[deps.CommonSolve]]
git-tree-sha1 = "0eee5eb66b1cf62cd6ad1b460238e60e4b09400c"
uuid = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2"
version = "0.2.4"
[[deps.CommonSubexpressions]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.0"
[[deps.Compat]]
deps = ["TOML", "UUIDs"]
git-tree-sha1 = "b1c55339b7c6c350ee89f2c1604299660525b248"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.15.0"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.1.1+0"
[[deps.CompositionsBase]]
git-tree-sha1 = "802bb88cd69dfd1509f6670416bd4434015693ad"
uuid = "a33af91c-f02d-484b-be07-31d278c5ca2b"
version = "0.1.2"
weakdeps = ["InverseFunctions"]
[deps.CompositionsBase.extensions]
CompositionsBaseInverseFunctionsExt = "InverseFunctions"
[[deps.ConcreteStructs]]
git-tree-sha1 = "f749037478283d372048690eb3b5f92a79432b34"
uuid = "2569d6c7-a4a2-43d3-a901-331e8e4be471"
version = "0.2.3"
[[deps.ConcurrentUtilities]]
deps = ["Serialization", "Sockets"]
git-tree-sha1 = "6cbbd4d241d7e6579ab354737f4dd95ca43946e1"
uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb"
version = "2.4.1"
[[deps.ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "260fd2400ed2dab602a7c15cf10c1933c59930a2"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.5.5"
[deps.ConstructionBase.extensions]
ConstructionBaseIntervalSetsExt = "IntervalSets"
ConstructionBaseStaticArraysExt = "StaticArrays"
[deps.ConstructionBase.weakdeps]
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
[[deps.ContextVariablesX]]
deps = ["Compat", "Logging", "UUIDs"]
git-tree-sha1 = "25cc3803f1030ab855e383129dcd3dc294e322cc"
uuid = "6add18c4-b38d-439d-96f6-d6bc489c04c5"
version = "0.1.3"
[[deps.Contour]]
git-tree-sha1 = "439e35b0b36e2e5881738abc8857bd92ad6ff9a8"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.6.3"
[[deps.CpuId]]
deps = ["Markdown"]
git-tree-sha1 = "fcbb72b032692610bfbdb15018ac16a36cf2e406"
uuid = "adafc99b-e345-5852-983c-f28acb93d879"
version = "0.3.1"
[[deps.DataAPI]]
git-tree-sha1 = "abe83f3a2f1b857aac70ef8b269080af17764bbe"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.16.0"
[[deps.DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "1d0a14036acb104d9e89698bd408f63ab58cdc82"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.20"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DefineSingletons]]
git-tree-sha1 = "0fba8b706d0178b4dc7fd44a96a92382c9065c2c"
uuid = "244e2a9f-e319-4986-a169-4d1fe445cd52"
version = "0.1.2"
[[deps.DelayDiffEq]]
deps = ["ArrayInterface", "DataStructures", "DiffEqBase", "LinearAlgebra", "Logging", "OrdinaryDiffEq", "Printf", "RecursiveArrayTools", "Reexport", "SciMLBase", "SimpleNonlinearSolve", "SimpleUnPack"]
git-tree-sha1 = "5959ae76ebd198f70e9af81153644543da0cfaf2"
uuid = "bcd4f6db-9728-5f36-b5f7-82caef46ccdb"
version = "5.47.3"
[[deps.DelimitedFiles]]
deps = ["Mmap"]
git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae"
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
version = "1.9.1"
[[deps.DiffEqBase]]
deps = ["ArrayInterface", "ConcreteStructs", "DataStructures", "DocStringExtensions", "EnumX", "EnzymeCore", "FastBroadcast", "FastClosures", "ForwardDiff", "FunctionWrappers", "FunctionWrappersWrappers", "LinearAlgebra", "Logging", "Markdown", "MuladdMacro", "Parameters", "PreallocationTools", "PrecompileTools", "Printf", "RecursiveArrayTools", "Reexport", "SciMLBase", "SciMLOperators", "Setfield", "SparseArrays", "Static", "StaticArraysCore", "Statistics", "Tricks", "TruncatedStacktraces"]
git-tree-sha1 = "03b9555f4c3a7c2f530bb1ae13e85719c632f74e"
uuid = "2b5f629d-d688-5b77-993f-72d75c75574e"
version = "6.151.1"
[deps.DiffEqBase.extensions]
DiffEqBaseCUDAExt = "CUDA"
DiffEqBaseChainRulesCoreExt = "ChainRulesCore"
DiffEqBaseDistributionsExt = "Distributions"
DiffEqBaseEnzymeExt = ["ChainRulesCore", "Enzyme"]
DiffEqBaseGeneralizedGeneratedExt = "GeneralizedGenerated"
DiffEqBaseMPIExt = "MPI"
DiffEqBaseMeasurementsExt = "Measurements"
DiffEqBaseMonteCarloMeasurementsExt = "MonteCarloMeasurements"
DiffEqBaseReverseDiffExt = "ReverseDiff"
DiffEqBaseTrackerExt = "Tracker"
DiffEqBaseUnitfulExt = "Unitful"
[deps.DiffEqBase.weakdeps]
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9"
GeneralizedGenerated = "6b9d7cbe-bcb9-11e9-073f-15a7a543e2eb"
MPI = "da04e1cc-30fd-572f-bb4f-1f8673147195"
Measurements = "eff96d63-e80a-5855-80a2-b1b0885c5ab7"
MonteCarloMeasurements = "0987c9cc-fe09-11e8-30f0-b96dd679fdca"
ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
[[deps.DiffEqCallbacks]]
deps = ["DataStructures", "DiffEqBase", "ForwardDiff", "Functors", "LinearAlgebra", "Markdown", "NLsolve", "Parameters", "RecipesBase", "RecursiveArrayTools", "SciMLBase", "StaticArraysCore"]
git-tree-sha1 = "ee954c8b9d348b7a8a6aec5f28288bf5adecd4ee"
uuid = "459566f4-90b8-5000-8ac3-15dfb0a30def"
version = "2.37.0"
weakdeps = ["OrdinaryDiffEq", "Sundials"]
[[deps.DiffEqNoiseProcess]]
deps = ["DiffEqBase", "Distributions", "GPUArraysCore", "LinearAlgebra", "Markdown", "Optim", "PoissonRandom", "QuadGK", "Random", "Random123", "RandomNumbers", "RecipesBase", "RecursiveArrayTools", "Requires", "ResettableStacks", "SciMLBase", "StaticArraysCore", "Statistics"]
git-tree-sha1 = "65cbbe1450ced323b4b17228ccd96349d96795a7"
uuid = "77a26b50-5914-5dd7-bc55-306e6241c503"
version = "5.21.0"
weakdeps = ["ReverseDiff"]
[deps.DiffEqNoiseProcess.extensions]
DiffEqNoiseProcessReverseDiffExt = "ReverseDiff"
[[deps.DiffResults]]
deps = ["StaticArraysCore"]
git-tree-sha1 = "782dd5f4561f5d267313f23853baaaa4c52ea621"
uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5"
version = "1.1.0"
[[deps.DiffRules]]
deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"]
git-tree-sha1 = "23163d55f885173722d1e4cf0f6110cdbaf7e272"
uuid = "b552c78f-8df3-52c6-915a-8e097449b14b"
version = "1.15.1"
[[deps.DifferentiableEigen]]
deps = ["ForwardDiffChainRules", "LinearAlgebra", "ReverseDiff"]
git-tree-sha1 = "6370fca72115d68efc500b3f49ecd627b715fda8"
uuid = "73a20539-4e65-4dcb-a56d-dc20f210a01b"
version = "0.2.0"
[[deps.DifferentiableFlatten]]
deps = ["ChainRulesCore", "LinearAlgebra", "NamedTupleTools", "OrderedCollections", "Requires", "SparseArrays"]
git-tree-sha1 = "f4dc2c1d994c7e2e602692a7dadd2ac79212c3a9"
uuid = "c78775a3-ee38-4681-b694-0504db4f5dc7"
version = "0.1.1"
[[deps.DifferentialEquations]]
deps = ["BoundaryValueDiffEq", "DelayDiffEq", "DiffEqBase", "DiffEqCallbacks", "DiffEqNoiseProcess", "JumpProcesses", "LinearAlgebra", "LinearSolve", "NonlinearSolve", "OrdinaryDiffEq", "Random", "RecursiveArrayTools", "Reexport", "SciMLBase", "SteadyStateDiffEq", "StochasticDiffEq", "Sundials"]
git-tree-sha1 = "8864b6a953eeba7890d23258aca468d90ca73fd6"
uuid = "0c46a032-eb83-5123-abaf-570d42b7fbaa"
version = "7.12.0"
[[deps.Distances]]
deps = ["LinearAlgebra", "Statistics", "StatsAPI"]
git-tree-sha1 = "66c4c81f259586e8f002eacebc177e1fb06363b0"
uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7"
version = "0.10.11"
weakdeps = ["ChainRulesCore", "SparseArrays"]
[deps.Distances.extensions]
DistancesChainRulesCoreExt = "ChainRulesCore"
DistancesSparseArraysExt = "SparseArrays"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.Distributions]]
deps = ["AliasTables", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SpecialFunctions", "Statistics", "StatsAPI", "StatsBase", "StatsFuns"]
git-tree-sha1 = "9c405847cc7ecda2dc921ccf18b47ca150d7317e"
uuid = "31c24e10-a181-5473-b8eb-7969acd0382f"
version = "0.25.109"
[deps.Distributions.extensions]
DistributionsChainRulesCoreExt = "ChainRulesCore"
DistributionsDensityInterfaceExt = "DensityInterface"
DistributionsTestExt = "Test"
[deps.Distributions.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
DensityInterface = "b429d917-457f-4dbc-8f4c-0cc954292b1d"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.3"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.DualNumbers]]
deps = ["Calculus", "NaNMath", "SpecialFunctions"]
git-tree-sha1 = "5837a837389fccf076445fce071c8ddaea35a566"
uuid = "fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74"
version = "0.6.8"
[[deps.EllipsisNotation]]
deps = ["StaticArrayInterface"]
git-tree-sha1 = "3507300d4343e8e4ad080ad24e335274c2e297a9"
uuid = "da5c29d0-fa7d-589e-88eb-ea29b0a81949"
version = "1.8.0"
[[deps.EnumX]]
git-tree-sha1 = "bdb1942cd4c45e3c678fd11569d5cccd80976237"
uuid = "4e289a0a-7415-4d19-859d-a7e5c4648b56"
version = "1.0.4"
[[deps.Enzyme]]
deps = ["CEnum", "EnzymeCore", "Enzyme_jll", "GPUCompiler", "LLVM", "Libdl", "LinearAlgebra", "ObjectFile", "Preferences", "Printf", "Random"]
git-tree-sha1 = "3fb48f9c18de1993c477457265b85130756746ae"
uuid = "7da242da-08ed-463a-9acd-ee780be4f1d9"
version = "0.11.20"
weakdeps = ["SpecialFunctions"]
[deps.Enzyme.extensions]
EnzymeSpecialFunctionsExt = "SpecialFunctions"
[[deps.EnzymeCore]]
git-tree-sha1 = "1bc328eec34ffd80357f84a84bb30e4374e9bd60"
uuid = "f151be2c-9106-41f4-ab19-57ee4f262869"
version = "0.6.6"
weakdeps = ["Adapt"]
[deps.EnzymeCore.extensions]
AdaptExt = "Adapt"
[[deps.Enzyme_jll]]
deps = ["Artifacts", "JLLWrappers", "LazyArtifacts", "Libdl", "TOML"]
git-tree-sha1 = "32d418c804279c60dd38ac7868126696f3205a4f"
uuid = "7cc45869-7501-5eee-bdea-0790c847d4ef"
version = "0.0.102+0"
[[deps.EpollShim_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "8e9441ee83492030ace98f9789a654a6d0b1f643"
uuid = "2702e6a9-849d-5ed8-8c21-79e8b8f9ee43"
version = "0.0.20230411+0"
[[deps.ExceptionUnwrapping]]
deps = ["Test"]
git-tree-sha1 = "dcb08a0d93ec0b1cdc4af184b26b591e9695423a"
uuid = "460bff9d-24e4-43bc-9d9f-a8973cb893f4"
version = "0.1.10"
[[deps.Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "1c6317308b9dc757616f0b5cb379db10494443a7"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.6.2+0"
[[deps.ExponentialUtilities]]
deps = ["Adapt", "ArrayInterface", "GPUArraysCore", "GenericSchur", "LinearAlgebra", "PrecompileTools", "Printf", "SparseArrays", "libblastrampoline_jll"]
git-tree-sha1 = "8e18940a5ba7f4ddb41fe2b79b6acaac50880a86"
uuid = "d4d017d3-3776-5f7e-afef-a10c40355c18"
version = "1.26.1"
[[deps.ExprTools]]
git-tree-sha1 = "27415f162e6028e81c72b82ef756bf321213b6ec"
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
version = "0.1.10"
[[deps.EzXML]]
deps = ["Printf", "XML2_jll"]
git-tree-sha1 = "380053d61bb9064d6aa4a9777413b40429c79901"
uuid = "8f5d6c58-4d21-5cfd-889c-e3ad7ee6a615"
version = "1.2.0"
[[deps.FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"
[[deps.FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "PCRE2_jll", "Zlib_jll", "libaom_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "466d45dc38e15794ec7d5d63ec03d776a9aff36e"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.4+1"
[[deps.FLoops]]
deps = ["BangBang", "Compat", "FLoopsBase", "InitialValues", "JuliaVariables", "MLStyle", "Serialization", "Setfield", "Transducers"]
git-tree-sha1 = "ffb97765602e3cbe59a0589d237bf07f245a8576"
uuid = "cc61a311-1640-44b5-9fba-1b764f453329"
version = "0.2.1"
[[deps.FLoopsBase]]
deps = ["ContextVariablesX"]
git-tree-sha1 = "656f7a6859be8673bf1f35da5670246b923964f7"
uuid = "b9860ae5-e623-471e-878b-f6a53c775ea6"
version = "0.1.1"
[[deps.FMI]]
deps = ["DifferentialEquations", "Downloads", "FMIExport", "FMIImport", "LinearAlgebra", "ProgressMeter", "Requires", "ThreadPools"]
git-tree-sha1 = "476e0317e86ecb2702d2ad744eb3a02626674fb1"
uuid = "14a09403-18e3-468f-ad8a-74f8dda2d9ac"
version = "0.13.3"
[[deps.FMICore]]
deps = ["ChainRulesCore", "Dates", "Requires"]
git-tree-sha1 = "ba0fb5ec972d3d2bb7f8c1ebd2f84a58268ab30b"
uuid = "8af89139-c281-408e-bce2-3005eb87462f"
version = "0.20.1"
[[deps.FMIExport]]
deps = ["Dates", "EzXML", "FMICore", "UUIDs"]
git-tree-sha1 = "daf601e31aeb73fb0010fe7ff942367bc75d5088"
uuid = "31b88311-cab6-44ed-ba9c-fe5a9abbd67a"
version = "0.3.2"
[[deps.FMIFlux]]
deps = ["Colors", "DifferentiableEigen", "DifferentialEquations", "FMIImport", "FMISensitivity", "Flux", "Optim", "Printf", "ProgressMeter", "Requires", "Statistics", "ThreadPools"]
git-tree-sha1 = "1315f3bfe3e273eb35ea872d71869814349541cd"
uuid = "fabad875-0d53-4e47-9446-963b74cae21f"
version = "0.12.2"
[[deps.FMIImport]]
deps = ["Downloads", "EzXML", "FMICore", "Libdl", "RelocatableFolders", "ZipFile"]
git-tree-sha1 = "b5b245bf7f1fc044ad16b016c7e2f08a2333a6f1"
uuid = "9fcbc62e-52a0-44e9-a616-1359a0008194"
version = "0.16.4"
[[deps.FMISensitivity]]
deps = ["FMICore", "ForwardDiffChainRules", "SciMLSensitivity"]
git-tree-sha1 = "43b9b68262af5d3602c9f153e978aff00b849569"
uuid = "3e748fe5-cd7f-4615-8419-3159287187d2"
version = "0.1.4"
[[deps.FMIZoo]]
deps = ["Downloads", "EzXML", "FilePaths", "FilePathsBase", "Glob", "Interpolations", "MAT", "Optim", "Requires", "ZipFile"]
git-tree-sha1 = "47f7e240ab988c1a24cc028f668eb70f73af5bd3"
uuid = "724179cf-c260-40a9-bd27-cccc6fe2f195"
version = "0.3.3"
[[deps.FastAlmostBandedMatrices]]
deps = ["ArrayInterface", "ArrayLayouts", "BandedMatrices", "ConcreteStructs", "LazyArrays", "LinearAlgebra", "MatrixFactorizations", "PrecompileTools", "Reexport"]
git-tree-sha1 = "a92b5820ea38da3b50b626cc55eba2b074bb0366"
uuid = "9d29842c-ecb8-4973-b1e9-a27b1157504e"
version = "0.1.3"
[[deps.FastBroadcast]]
deps = ["ArrayInterface", "LinearAlgebra", "Polyester", "Static", "StaticArrayInterface", "StrideArraysCore"]
git-tree-sha1 = "a6e756a880fc419c8b41592010aebe6a5ce09136"
uuid = "7034ab61-46d4-4ed7-9d0f-46aef9175898"
version = "0.2.8"
[[deps.FastClosures]]
git-tree-sha1 = "acebe244d53ee1b461970f8910c235b259e772ef"
uuid = "9aa1b823-49e4-5ca5-8b0f-3971ec8bab6a"
version = "0.3.2"
[[deps.FastLapackInterface]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "cbf5edddb61a43669710cbc2241bc08b36d9e660"
uuid = "29a986be-02c6-4525-aec4-84b980013641"
version = "2.0.4"
[[deps.FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "82d8afa92ecf4b52d78d869f038ebfb881267322"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.16.3"
[[deps.FilePaths]]
deps = ["FilePathsBase", "MacroTools", "Reexport", "Requires"]
git-tree-sha1 = "919d9412dbf53a2e6fe74af62a73ceed0bce0629"
uuid = "8fc22ac5-c921-52a6-82fd-178b2807b824"
version = "0.8.3"
[[deps.FilePathsBase]]
deps = ["Compat", "Dates", "Mmap", "Printf", "Test", "UUIDs"]
git-tree-sha1 = "9f00e42f8d99fdde64d40c8ea5d14269a2e2c1aa"
uuid = "48062228-2e41-5def-b9a4-89aafe57970f"
version = "0.9.21"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
[[deps.FillArrays]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "0653c0a2396a6da5bc4766c43041ef5fd3efbe57"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "1.11.0"
weakdeps = ["PDMats", "SparseArrays", "Statistics"]
[deps.FillArrays.extensions]
FillArraysPDMatsExt = "PDMats"
FillArraysSparseArraysExt = "SparseArrays"
FillArraysStatisticsExt = "Statistics"
[[deps.FiniteDiff]]
deps = ["ArrayInterface", "LinearAlgebra", "Requires", "Setfield", "SparseArrays"]
git-tree-sha1 = "2de436b72c3422940cbe1367611d137008af7ec3"
uuid = "6a86dc24-6348-571c-b903-95158fe2bd41"
version = "2.23.1"
[deps.FiniteDiff.extensions]
FiniteDiffBandedMatricesExt = "BandedMatrices"
FiniteDiffBlockBandedMatricesExt = "BlockBandedMatrices"
FiniteDiffStaticArraysExt = "StaticArrays"
[deps.FiniteDiff.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "05882d6995ae5c12bb5f36dd2ed3f61c98cbb172"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.5"
[[deps.Flux]]
deps = ["Adapt", "ChainRulesCore", "Compat", "Functors", "LinearAlgebra", "MLUtils", "MacroTools", "NNlib", "OneHotArrays", "Optimisers", "Preferences", "ProgressLogging", "Random", "Reexport", "SparseArrays", "SpecialFunctions", "Statistics", "Zygote"]
git-tree-sha1 = "edacf029ed6276301e455e34d7ceeba8cc34078a"
uuid = "587475ba-b771-5e3f-ad9e-33799f191a9c"
version = "0.14.16"
[deps.Flux.extensions]
FluxAMDGPUExt = "AMDGPU"
FluxCUDAExt = "CUDA"
FluxCUDAcuDNNExt = ["CUDA", "cuDNN"]
FluxMetalExt = "Metal"
[deps.Flux.weakdeps]
AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
Metal = "dde4c033-4e86-420c-a63e-0dd931031962"
cuDNN = "02a925ec-e4fe-4b08-9a7e-0d78e3d38ccd"
[[deps.Fontconfig_jll]]
deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Zlib_jll"]
git-tree-sha1 = "db16beca600632c95fc8aca29890d83788dd8b23"
uuid = "a3f928ae-7b40-5064-980b-68af3947d34b"
version = "2.13.96+0"
[[deps.Format]]
git-tree-sha1 = "9c68794ef81b08086aeb32eeaf33531668d5f5fc"
uuid = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8"
version = "1.3.7"
[[deps.ForwardDiff]]
deps = ["CommonSubexpressions", "DiffResults", "DiffRules", "LinearAlgebra", "LogExpFunctions", "NaNMath", "Preferences", "Printf", "Random", "SpecialFunctions"]
git-tree-sha1 = "cf0fe81336da9fb90944683b8c41984b08793dad"
uuid = "f6369f11-7733-5829-9624-2563aa707210"
version = "0.10.36"
weakdeps = ["StaticArrays"]
[deps.ForwardDiff.extensions]
ForwardDiffStaticArraysExt = "StaticArrays"
[[deps.ForwardDiffChainRules]]
deps = ["ChainRulesCore", "DifferentiableFlatten", "ForwardDiff", "MacroTools"]
git-tree-sha1 = "088aae09132ee3a8b351bec6569e83985e5b961e"
uuid = "c9556dd2-1aed-4cfe-8560-1557cf593001"
version = "0.2.1"
[[deps.FreeType2_jll]]
deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Zlib_jll"]
git-tree-sha1 = "5c1d8ae0efc6c2e7b1fc502cbe25def8f661b7bc"
uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7"
version = "2.13.2+0"
[[deps.FriBidi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "1ed150b39aebcc805c26b93a8d0122c940f64ce2"
uuid = "559328eb-81f9-559d-9380-de523a88c83c"
version = "1.0.14+0"
[[deps.FunctionProperties]]
deps = ["Cassette", "DiffRules"]
git-tree-sha1 = "bf7c740307eb0ee80e05d8aafbd0c5a901578398"
uuid = "f62d2435-5019-4c03-9749-2d4c77af0cbc"
version = "0.1.2"
[[deps.FunctionWrappers]]
git-tree-sha1 = "d62485945ce5ae9c0c48f124a84998d755bae00e"
uuid = "069b7b12-0de2-55c6-9aab-29f3d0a68a2e"
version = "1.1.3"
[[deps.FunctionWrappersWrappers]]
deps = ["FunctionWrappers"]
git-tree-sha1 = "b104d487b34566608f8b4e1c39fb0b10aa279ff8"
uuid = "77dc65aa-8811-40c2-897b-53d922fa7daf"
version = "0.1.3"
[[deps.FunctionalCollections]]
deps = ["Test"]
git-tree-sha1 = "04cb9cfaa6ba5311973994fe3496ddec19b6292a"
uuid = "de31a74c-ac4f-5751-b3fd-e18cd04993ca"
version = "0.5.0"
[[deps.Functors]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "8a66c07630d6428eaab3506a0eabfcf4a9edea05"
uuid = "d9f16b24-f501-4c13-a1f2-28368ffc5196"
version = "0.4.11"
[[deps.Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
[[deps.GLFW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll"]
git-tree-sha1 = "ff38ba61beff76b8f4acad8ab0c97ef73bb670cb"
uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89"
version = "3.3.9+0"
[[deps.GPUArrays]]
deps = ["Adapt", "GPUArraysCore", "LLVM", "LinearAlgebra", "Printf", "Random", "Reexport", "Serialization", "Statistics"]
git-tree-sha1 = "5c9de6d5af87acd2cf719e214ed7d51e14017b7a"
uuid = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7"
version = "10.2.2"
[[deps.GPUArraysCore]]
deps = ["Adapt"]
git-tree-sha1 = "ec632f177c0d990e64d955ccc1b8c04c485a0950"
uuid = "46192b85-c4d5-4398-a991-12ede77f4527"
version = "0.1.6"
[[deps.GPUCompiler]]
deps = ["ExprTools", "InteractiveUtils", "LLVM", "Libdl", "Logging", "Scratch", "TimerOutputs", "UUIDs"]
git-tree-sha1 = "a846f297ce9d09ccba02ead0cae70690e072a119"
uuid = "61eb1bfa-7361-4325-ad38-22787b887f55"
version = "0.25.0"
[[deps.GR]]
deps = ["Artifacts", "Base64", "DelimitedFiles", "Downloads", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Preferences", "Printf", "Random", "Serialization", "Sockets", "TOML", "Tar", "Test", "p7zip_jll"]
git-tree-sha1 = "3e527447a45901ea392fe12120783ad6ec222803"
uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71"
version = "0.73.6"
[[deps.GR_jll]]
deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "FreeType2_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Qt6Base_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "182c478a179b267dd7a741b6f8f4c3e0803795d6"
uuid = "d2c73de3-f751-5644-a686-071e5b155ba9"
version = "0.73.6+0"
[[deps.GenericSchur]]
deps = ["LinearAlgebra", "Printf"]
git-tree-sha1 = "af49a0851f8113fcfae2ef5027c6d49d0acec39b"
uuid = "c145ed77-6b09-5dd9-b285-bf645a82121e"
version = "0.5.4"
[[deps.Gettext_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046"
uuid = "78b55507-aeef-58d4-861c-77aaff3498b1"
version = "0.21.0+0"
[[deps.Glib_jll]]
deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE2_jll", "Zlib_jll"]
git-tree-sha1 = "7c82e6a6cd34e9d935e9aa4051b66c6ff3af59ba"
uuid = "7746bdde-850d-59dc-9ae8-88ece973131d"
version = "2.80.2+0"
[[deps.Glob]]
git-tree-sha1 = "97285bbd5230dd766e9ef6749b80fc617126d496"
uuid = "c27321d9-0574-5035-807b-f59d2c89b15c"
version = "1.3.1"
[[deps.Graphite2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "344bf40dcab1073aca04aa0df4fb092f920e4011"
uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472"
version = "1.3.14+0"
[[deps.Graphs]]
deps = ["ArnoldiMethod", "Compat", "DataStructures", "Distributed", "Inflate", "LinearAlgebra", "Random", "SharedArrays", "SimpleTraits", "SparseArrays", "Statistics"]
git-tree-sha1 = "334d300809ae0a68ceee3444c6e99ded412bf0b3"
uuid = "86223c79-3864-5bf0-83f7-82e725a168b6"
version = "1.11.1"
[[deps.Grisu]]
git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2"
uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe"
version = "1.0.2"
[[deps.HDF5]]
deps = ["Compat", "HDF5_jll", "Libdl", "MPIPreferences", "Mmap", "Preferences", "Printf", "Random", "Requires", "UUIDs"]
git-tree-sha1 = "e856eef26cf5bf2b0f95f8f4fc37553c72c8641c"
uuid = "f67ccb44-e63f-5c2f-98bd-6dc0ccc4ba2f"
version = "0.17.2"
[deps.HDF5.extensions]
MPIExt = "MPI"
[deps.HDF5.weakdeps]
MPI = "da04e1cc-30fd-572f-bb4f-1f8673147195"
[[deps.HDF5_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "LLVMOpenMP_jll", "LazyArtifacts", "LibCURL_jll", "Libdl", "MPICH_jll", "MPIPreferences", "MPItrampoline_jll", "MicrosoftMPI_jll", "OpenMPI_jll", "OpenSSL_jll", "TOML", "Zlib_jll", "libaec_jll"]
git-tree-sha1 = "38c8874692d48d5440d5752d6c74b0c6b0b60739"
uuid = "0234f1f7-429e-5d53-9886-15a909be8d59"
version = "1.14.2+1"
[[deps.HTTP]]
deps = ["Base64", "CodecZlib", "ConcurrentUtilities", "Dates", "ExceptionUnwrapping", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"]
git-tree-sha1 = "d1d712be3164d61d1fb98e7ce9bcbc6cc06b45ed"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "1.10.8"
[[deps.HarfBuzz_jll]]
deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg"]
git-tree-sha1 = "129acf094d168394e80ee1dc4bc06ec835e510a3"
uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566"
version = "2.8.1+1"
[[deps.Hiccup]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "6187bb2d5fcbb2007c39e7ac53308b0d371124bd"
uuid = "9fb69e20-1954-56bb-a84f-559cc56a8ff7"
version = "0.2.2"
[[deps.HostCPUFeatures]]
deps = ["BitTwiddlingConvenienceFunctions", "IfElse", "Libdl", "Static"]
git-tree-sha1 = "8e070b599339d622e9a081d17230d74a5c473293"
uuid = "3e5b6fbb-0976-4d2c-9146-d79de83f2fb0"
version = "0.1.17"
[[deps.Hwloc_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "1d334207121865ac8c1c97eb7f42d0339e4635bf"
uuid = "e33a78d0-f292-5ffc-b300-72abe9b543c8"
version = "2.11.0+0"
[[deps.HypergeometricFunctions]]
deps = ["DualNumbers", "LinearAlgebra", "OpenLibm_jll", "SpecialFunctions"]
git-tree-sha1 = "f218fe3736ddf977e0e772bc9a586b2383da2685"
uuid = "34004b35-14d8-5ef3-9330-4cdb6864b03a"
version = "0.3.23"
[[deps.Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "179267cfa5e712760cd43dcae385d7ea90cc25a4"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.5"
[[deps.HypertextLiteral]]
deps = ["Tricks"]
git-tree-sha1 = "7134810b1afce04bbc1045ca1985fbe81ce17653"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.5"
[[deps.IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "b6d6bfdd7ce25b0f9b2f6b3dd56b2673a66c8770"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.5"
[[deps.IRTools]]
deps = ["InteractiveUtils", "MacroTools"]
git-tree-sha1 = "950c3717af761bc3ff906c2e8e52bd83390b6ec2"
uuid = "7869d1d1-7146-5819-86e3-90919afe41df"
version = "0.4.14"
[[deps.IfElse]]
git-tree-sha1 = "debdd00ffef04665ccbb3e150747a77560e8fad1"
uuid = "615f187c-cbe4-4ef1-ba3b-2fcf58d6d173"
version = "0.1.1"
[[deps.Inflate]]
git-tree-sha1 = "d1b1b796e47d94588b3757fe84fbf65a5ec4a80d"
uuid = "d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9"
version = "0.1.5"
[[deps.InitialValues]]
git-tree-sha1 = "4da0f88e9a39111c2fa3add390ab15f3a44f3ca3"
uuid = "22cec73e-a1b8-11e9-2c92-598750a2cf9c"
version = "0.3.1"
[[deps.IntelOpenMP_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "be50fe8df3acbffa0274a744f1a99d29c45a57f4"
uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0"
version = "2024.1.0+0"
[[deps.InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[deps.Interpolations]]
deps = ["Adapt", "AxisAlgorithms", "ChainRulesCore", "LinearAlgebra", "OffsetArrays", "Random", "Ratios", "Requires", "SharedArrays", "SparseArrays", "StaticArrays", "WoodburyMatrices"]
git-tree-sha1 = "88a101217d7cb38a7b481ccd50d21876e1d1b0e0"
uuid = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59"
version = "0.15.1"
weakdeps = ["Unitful"]
[deps.Interpolations.extensions]
InterpolationsUnitfulExt = "Unitful"
[[deps.InverseFunctions]]
deps = ["Test"]
git-tree-sha1 = "e7cbed5032c4c397a6ac23d1493f3289e01231c4"
uuid = "3587e190-3f89-42d0-90ee-14403ec27112"
version = "0.1.14"
weakdeps = ["Dates"]
[deps.InverseFunctions.extensions]
DatesExt = "Dates"
[[deps.IrrationalConstants]]
git-tree-sha1 = "630b497eafcc20001bba38a4651b327dcfc491d2"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.2.2"
[[deps.IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[deps.JLD2]]
deps = ["FileIO", "MacroTools", "Mmap", "OrderedCollections", "Pkg", "PrecompileTools", "Reexport", "Requires", "TranscodingStreams", "UUIDs", "Unicode"]
git-tree-sha1 = "84642bc18a79d715b39d3724b03cbdd2e7d48c62"
uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819"
version = "0.4.49"
[[deps.JLFzf]]
deps = ["Pipe", "REPL", "Random", "fzf_jll"]
git-tree-sha1 = "a53ebe394b71470c7f97c2e7e170d51df21b17af"
uuid = "1019f520-868f-41f5-a6de-eb00f4b6a39c"
version = "0.1.7"
[[deps.JLLWrappers]]
deps = ["Artifacts", "Preferences"]
git-tree-sha1 = "7e5d6779a1e09a36db2a7b6cff50942a0a7d0fca"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.5.0"
[[deps.JSExpr]]
deps = ["JSON", "MacroTools", "Observables", "WebIO"]
git-tree-sha1 = "b413a73785b98474d8af24fd4c8a975e31df3658"
uuid = "97c1335a-c9c5-57fe-bc5d-ec35cebe8660"
version = "0.5.4"
[[deps.JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.4"
[[deps.JpegTurbo_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "c84a835e1a09b289ffcd2271bf2a337bbdda6637"
uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8"
version = "3.0.3+0"
[[deps.JuliaVariables]]
deps = ["MLStyle", "NameResolution"]
git-tree-sha1 = "49fb3cb53362ddadb4415e9b73926d6b40709e70"
uuid = "b14d175d-62b4-44ba-8fb7-3064adc8c3ec"
version = "0.2.4"
[[deps.JumpProcesses]]
deps = ["ArrayInterface", "DataStructures", "DiffEqBase", "DocStringExtensions", "FunctionWrappers", "Graphs", "LinearAlgebra", "Markdown", "PoissonRandom", "Random", "RandomNumbers", "RecursiveArrayTools", "Reexport", "SciMLBase", "StaticArrays", "SymbolicIndexingInterface", "UnPack"]
git-tree-sha1 = "ed08d89318be7d625613f3c435d1f6678fba4850"
uuid = "ccbc3e58-028d-4f4c-8cd5-9ae44345cda5"
version = "9.11.1"
weakdeps = ["FastBroadcast"]
[deps.JumpProcesses.extensions]
JumpProcessFastBroadcastExt = "FastBroadcast"
[[deps.KLU]]
deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse_jll"]
git-tree-sha1 = "07649c499349dad9f08dde4243a4c597064663e9"
uuid = "ef3ab10e-7fda-4108-b977-705223b18434"
version = "0.6.0"
[[deps.Kaleido_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "43032da5832754f58d14a91ffbe86d5f176acda9"
uuid = "f7e6163d-2fa5-5f23-b69c-1db539e41963"
version = "0.2.1+0"
[[deps.KernelAbstractions]]
deps = ["Adapt", "Atomix", "InteractiveUtils", "LinearAlgebra", "MacroTools", "PrecompileTools", "Requires", "SparseArrays", "StaticArrays", "UUIDs", "UnsafeAtomics", "UnsafeAtomicsLLVM"]
git-tree-sha1 = "ed7167240f40e62d97c1f5f7735dea6de3cc5c49"
uuid = "63c18a36-062a-441e-b654-da1e3ab1ce7c"
version = "0.9.18"
weakdeps = ["EnzymeCore"]
[deps.KernelAbstractions.extensions]
EnzymeExt = "EnzymeCore"
[[deps.Krylov]]
deps = ["LinearAlgebra", "Printf", "SparseArrays"]
git-tree-sha1 = "267dad6b4b7b5d529c76d40ff48d33f7e94cb834"
uuid = "ba0b0d4f-ebba-5204-a429-3ac8c609bfb7"
version = "0.9.6"
[[deps.LAME_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "170b660facf5df5de098d866564877e119141cbd"
uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d"
version = "3.100.2+0"
[[deps.LERC_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "bf36f528eec6634efc60d7ec062008f171071434"
uuid = "88015f11-f218-50d7-93a8-a6af411a945d"
version = "3.0.0+1"
[[deps.LLVM]]
deps = ["CEnum", "LLVMExtra_jll", "Libdl", "Preferences", "Printf", "Requires", "Unicode"]
git-tree-sha1 = "839c82932db86740ae729779e610f07a1640be9a"
uuid = "929cbde3-209d-540e-8aea-75f648917ca0"
version = "6.6.3"
[deps.LLVM.extensions]
BFloat16sExt = "BFloat16s"
[deps.LLVM.weakdeps]
BFloat16s = "ab4f0b2a-ad5b-11e8-123f-65d77653426b"
[[deps.LLVMExtra_jll]]
deps = ["Artifacts", "JLLWrappers", "LazyArtifacts", "Libdl", "TOML"]
git-tree-sha1 = "88b916503aac4fb7f701bb625cd84ca5dd1677bc"
uuid = "dad2f222-ce93-54a1-a47d-0025e8a3acab"
version = "0.0.29+0"
[[deps.LLVMOpenMP_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "d986ce2d884d49126836ea94ed5bfb0f12679713"
uuid = "1d63c593-3942-5779-bab2-d838dc0a180e"
version = "15.0.7+0"
[[deps.LZO_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "70c5da094887fd2cae843b8db33920bac4b6f07d"
uuid = "dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac"
version = "2.10.2+0"
[[deps.LaTeXStrings]]
git-tree-sha1 = "50901ebc375ed41dbf8058da26f9de442febbbec"
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
version = "1.3.1"
[[deps.Latexify]]
deps = ["Format", "InteractiveUtils", "LaTeXStrings", "MacroTools", "Markdown", "OrderedCollections", "Requires"]
git-tree-sha1 = "e0b5cd21dc1b44ec6e64f351976f961e6f31d6c4"
uuid = "23fbe1c1-3f47-55db-b15f-69d7ec21a316"
version = "0.16.3"
[deps.Latexify.extensions]
DataFramesExt = "DataFrames"
SymEngineExt = "SymEngine"
[deps.Latexify.weakdeps]
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
SymEngine = "123dc426-2d89-5057-bbad-38513e3affd8"
[[deps.LayoutPointers]]
deps = ["ArrayInterface", "LinearAlgebra", "ManualMemory", "SIMDTypes", "Static", "StaticArrayInterface"]
git-tree-sha1 = "a9eaadb366f5493a5654e843864c13d8b107548c"
uuid = "10f19ff3-798f-405d-979b-55457f8fc047"
version = "0.1.17"
[[deps.Lazy]]
deps = ["MacroTools"]
git-tree-sha1 = "1370f8202dac30758f3c345f9909b97f53d87d3f"
uuid = "50d2b5c4-7a5e-59d5-8109-a42b560f39c0"
version = "0.15.1"
[[deps.LazyArrays]]
deps = ["ArrayLayouts", "FillArrays", "LinearAlgebra", "MacroTools", "MatrixFactorizations", "SparseArrays"]
git-tree-sha1 = "35079a6a869eecace778bcda8641f9a54ca3a828"
uuid = "5078a376-72f3-5289-bfd5-ec5146d43c02"
version = "1.10.0"
weakdeps = ["StaticArrays"]
[deps.LazyArrays.extensions]
LazyArraysStaticArraysExt = "StaticArrays"
[[deps.LazyArtifacts]]
deps = ["Artifacts", "Pkg"]
uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3"
[[deps.LevyArea]]
deps = ["LinearAlgebra", "Random", "SpecialFunctions"]
git-tree-sha1 = "56513a09b8e0ae6485f34401ea9e2f31357958ec"
uuid = "2d8b4e74-eb68-11e8-0fb9-d5eb67b50637"
version = "1.0.0"
[[deps.LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
version = "0.6.4"
[[deps.LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
version = "8.4.0+0"
[[deps.LibGit2]]
deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[deps.LibGit2_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"]
uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5"
version = "1.6.4+0"
[[deps.LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
version = "1.11.0+1"
[[deps.Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[deps.Libffi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "0b4a5d71f3e5200a7dff793393e09dfc2d874290"
uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490"
version = "3.2.2+1"
[[deps.Libgcrypt_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll"]
git-tree-sha1 = "9fd170c4bbfd8b935fdc5f8b7aa33532c991a673"
uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4"
version = "1.8.11+0"
[[deps.Libglvnd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll", "Xorg_libXext_jll"]
git-tree-sha1 = "6f73d1dd803986947b2c750138528a999a6c7733"
uuid = "7e76a0d4-f3c7-5321-8279-8d96eeed0f29"
version = "1.6.0+0"
[[deps.Libgpg_error_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "fbb1f2bef882392312feb1ede3615ddc1e9b99ed"
uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8"
version = "1.49.0+0"
[[deps.Libiconv_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "f9557a255370125b405568f9767d6d195822a175"
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
version = "1.17.0+0"
[[deps.Libmount_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "0c4f9c4f1a50d8f35048fa0532dabbadf702f81e"
uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9"
version = "2.40.1+0"
[[deps.Libtiff_jll]]
deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "LERC_jll", "Libdl", "XZ_jll", "Zlib_jll", "Zstd_jll"]
git-tree-sha1 = "2da088d113af58221c52828a80378e16be7d037a"
uuid = "89763e89-9b03-5906-acba-b20f662cd828"
version = "4.5.1+1"
[[deps.Libuuid_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "5ee6203157c120d79034c748a2acba45b82b8807"
uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700"
version = "2.40.1+0"
[[deps.LineSearches]]
deps = ["LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "Printf"]
git-tree-sha1 = "7bbea35cec17305fc70a0e5b4641477dc0789d9d"
uuid = "d3d80556-e9d4-5f37-9878-2ab0fcc64255"
version = "7.2.0"
[[deps.LinearAlgebra]]
deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[deps.LinearSolve]]
deps = ["ArrayInterface", "ChainRulesCore", "ConcreteStructs", "DocStringExtensions", "EnumX", "FastLapackInterface", "GPUArraysCore", "InteractiveUtils", "KLU", "Krylov", "LazyArrays", "Libdl", "LinearAlgebra", "MKL_jll", "Markdown", "PrecompileTools", "Preferences", "RecursiveFactorization", "Reexport", "SciMLBase", "SciMLOperators", "Setfield", "SparseArrays", "Sparspak", "StaticArraysCore", "UnPack"]
git-tree-sha1 = "b2e2dba60642e07c062eb3143770d7e234316772"
uuid = "7ed4a6bd-45f5-4d41-b270-4a48e9bafcae"
version = "2.30.2"
[deps.LinearSolve.extensions]
LinearSolveBandedMatricesExt = "BandedMatrices"
LinearSolveBlockDiagonalsExt = "BlockDiagonals"
LinearSolveCUDAExt = "CUDA"
LinearSolveCUDSSExt = "CUDSS"
LinearSolveEnzymeExt = ["Enzyme", "EnzymeCore"]
LinearSolveFastAlmostBandedMatricesExt = ["FastAlmostBandedMatrices"]
LinearSolveHYPREExt = "HYPRE"
LinearSolveIterativeSolversExt = "IterativeSolvers"
LinearSolveKernelAbstractionsExt = "KernelAbstractions"
LinearSolveKrylovKitExt = "KrylovKit"
LinearSolveMetalExt = "Metal"
LinearSolvePardisoExt = "Pardiso"
LinearSolveRecursiveArrayToolsExt = "RecursiveArrayTools"
[deps.LinearSolve.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockDiagonals = "0a1fb500-61f7-11e9-3c65-f5ef3456f9f0"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
CUDSS = "45b445bb-4962-46a0-9369-b4df9d0f772e"
Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9"
EnzymeCore = "f151be2c-9106-41f4-ab19-57ee4f262869"
FastAlmostBandedMatrices = "9d29842c-ecb8-4973-b1e9-a27b1157504e"
HYPRE = "b5ffcf37-a2bd-41ab-a3da-4bd9bc8ad771"
IterativeSolvers = "42fd0dbc-a981-5370-80f2-aaf504508153"
KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c"
KrylovKit = "0b1a1467-8014-51b9-945f-bf0ae24f4b77"
Metal = "dde4c033-4e86-420c-a63e-0dd931031962"
Pardiso = "46dd5b70-b6fb-5a00-ae2d-e8fea33afaf2"
RecursiveArrayTools = "731186ca-8d62-57ce-b412-fbd966d074cd"
[[deps.LogExpFunctions]]
deps = ["DocStringExtensions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "a2d09619db4e765091ee5c6ffe8872849de0feea"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.28"
[deps.LogExpFunctions.extensions]
LogExpFunctionsChainRulesCoreExt = "ChainRulesCore"
LogExpFunctionsChangesOfVariablesExt = "ChangesOfVariables"
LogExpFunctionsInverseFunctionsExt = "InverseFunctions"
[deps.LogExpFunctions.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
ChangesOfVariables = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112"
[[deps.Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[deps.LoggingExtras]]
deps = ["Dates", "Logging"]
git-tree-sha1 = "c1dd6d7978c12545b4179fb6153b9250c96b0075"
uuid = "e6f89c97-d47a-5376-807f-9c37f3926c36"
version = "1.0.3"
[[deps.LoopVectorization]]
deps = ["ArrayInterface", "CPUSummary", "CloseOpenIntervals", "DocStringExtensions", "HostCPUFeatures", "IfElse", "LayoutPointers", "LinearAlgebra", "OffsetArrays", "PolyesterWeave", "PrecompileTools", "SIMDTypes", "SLEEFPirates", "Static", "StaticArrayInterface", "ThreadingUtilities", "UnPack", "VectorizationBase"]
git-tree-sha1 = "8084c25a250e00ae427a379a5b607e7aed96a2dd"
uuid = "bdcacae8-1622-11e9-2a5c-532679323890"
version = "0.12.171"
weakdeps = ["ChainRulesCore", "ForwardDiff", "SpecialFunctions"]
[deps.LoopVectorization.extensions]
ForwardDiffExt = ["ChainRulesCore", "ForwardDiff"]
SpecialFunctionsExt = "SpecialFunctions"
[[deps.MAT]]
deps = ["BufferedStreams", "CodecZlib", "HDF5", "SparseArrays"]
git-tree-sha1 = "1d2dd9b186742b0f317f2530ddcbf00eebb18e96"
uuid = "23992714-dd62-5051-b70f-ba57cb901cac"
version = "0.10.7"
[[deps.MIMEs]]
git-tree-sha1 = "65f28ad4b594aebe22157d6fac869786a255b7eb"
uuid = "6c6e2e6c-3030-632d-7369-2d6c69616d65"
version = "0.1.4"
[[deps.MKL_jll]]
deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "oneTBB_jll"]
git-tree-sha1 = "80b2833b56d466b3858d565adcd16a4a05f2089b"
uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7"
version = "2024.1.0+0"
[[deps.MLStyle]]
git-tree-sha1 = "bc38dff0548128765760c79eb7388a4b37fae2c8"
uuid = "d8e11817-5142-5d16-987a-aa16d5891078"
version = "0.4.17"
[[deps.MLUtils]]
deps = ["ChainRulesCore", "Compat", "DataAPI", "DelimitedFiles", "FLoops", "NNlib", "Random", "ShowCases", "SimpleTraits", "Statistics", "StatsBase", "Tables", "Transducers"]
git-tree-sha1 = "b45738c2e3d0d402dffa32b2c1654759a2ac35a4"
uuid = "f1d291b0-491e-4a28-83b9-f70985020b54"
version = "0.4.4"
[[deps.MPICH_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Hwloc_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "MPIPreferences", "TOML"]
git-tree-sha1 = "4099bb6809ac109bfc17d521dad33763bcf026b7"
uuid = "7cb0a576-ebde-5e09-9194-50597f1243b4"
version = "4.2.1+1"
[[deps.MPIPreferences]]
deps = ["Libdl", "Preferences"]
git-tree-sha1 = "c105fe467859e7f6e9a852cb15cb4301126fac07"
uuid = "3da0fdf6-3ccc-4f1b-acd9-58baa6c99267"
version = "0.1.11"
[[deps.MPItrampoline_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "MPIPreferences", "TOML"]
git-tree-sha1 = "8c35d5420193841b2f367e658540e8d9e0601ed0"
uuid = "f1f71cc9-e9ae-5b93-9b94-4fe0e1ad3748"
version = "5.4.0+0"
[[deps.MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "2fa9ee3e63fd3a4f7a9a4f4744a52f4856de82df"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.13"
[[deps.ManualMemory]]
git-tree-sha1 = "bcaef4fc7a0cfe2cba636d84cda54b5e4e4ca3cd"
uuid = "d125e4d3-2237-4719-b19c-fa641b8a4667"
version = "0.1.8"
[[deps.Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[deps.MatrixFactorizations]]
deps = ["ArrayLayouts", "LinearAlgebra", "Printf", "Random"]
git-tree-sha1 = "6731e0574fa5ee21c02733e397beb133df90de35"
uuid = "a3b82374-2e81-5b9e-98ce-41277c0e4c87"
version = "2.2.0"
[[deps.MaybeInplace]]
deps = ["ArrayInterface", "LinearAlgebra", "MacroTools", "SparseArrays"]
git-tree-sha1 = "1b9e613f2ca3b6cdcbfe36381e17ca2b66d4b3a1"
uuid = "bb5d69b7-63fc-4a16-80bd-7e42200c7bdb"
version = "0.1.3"
[[deps.MbedTLS]]
deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "NetworkOptions", "Random", "Sockets"]
git-tree-sha1 = "c067a280ddc25f196b5e7df3877c6b226d390aaf"
uuid = "739be429-bea8-5141-9913-cc70e7f3736d"
version = "1.1.9"
[[deps.MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
version = "2.28.2+1"
[[deps.Measures]]
git-tree-sha1 = "c13304c81eec1ed3af7fc20e75fb6b26092a1102"
uuid = "442fdcdd-2543-5da2-b0f3-8c86c306513e"
version = "0.3.2"
[[deps.MicroCollections]]
deps = ["BangBang", "InitialValues", "Setfield"]
git-tree-sha1 = "629afd7d10dbc6935ec59b32daeb33bc4460a42e"
uuid = "128add7d-3638-4c79-886c-908ea0c25c34"
version = "0.1.4"
[[deps.MicrosoftMPI_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "f12a29c4400ba812841c6ace3f4efbb6dbb3ba01"
uuid = "9237b28f-5490-5468-be7b-bb81f5f5e6cf"
version = "10.1.4+2"
[[deps.Missings]]
deps = ["DataAPI"]
git-tree-sha1 = "ec4f7fbeab05d7747bdf98eb74d130a2a2ed298d"
uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28"
version = "1.2.0"
[[deps.Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[deps.MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
version = "2023.1.10"
[[deps.MuladdMacro]]
git-tree-sha1 = "cac9cc5499c25554cba55cd3c30543cff5ca4fab"
uuid = "46d2c3a1-f734-5fdb-9937-b9b9aeba4221"
version = "0.2.4"
[[deps.Mustache]]
deps = ["Printf", "Tables"]
git-tree-sha1 = "a7cefa21a2ff993bff0456bf7521f46fc077ddf1"
uuid = "ffc61752-8dc7-55ee-8c37-f3e9cdd09e70"
version = "1.0.19"
[[deps.Mux]]
deps = ["AssetRegistry", "Base64", "HTTP", "Hiccup", "MbedTLS", "Pkg", "Sockets"]
git-tree-sha1 = "7295d849103ac4fcbe3b2e439f229c5cc77b9b69"
uuid = "a975b10e-0019-58db-a62f-e48ff68538c9"
version = "1.0.2"
[[deps.NLSolversBase]]
deps = ["DiffResults", "Distributed", "FiniteDiff", "ForwardDiff"]
git-tree-sha1 = "a0b464d183da839699f4c79e7606d9d186ec172c"
uuid = "d41bc354-129a-5804-8e4c-c37616107c6c"
version = "7.8.3"
[[deps.NLsolve]]
deps = ["Distances", "LineSearches", "LinearAlgebra", "NLSolversBase", "Printf", "Reexport"]
git-tree-sha1 = "019f12e9a1a7880459d0173c182e6a99365d7ac1"
uuid = "2774e3e8-f4cf-5e23-947b-6d7e65073b56"
version = "4.5.1"
[[deps.NNlib]]
deps = ["Adapt", "Atomix", "ChainRulesCore", "GPUArraysCore", "KernelAbstractions", "LinearAlgebra", "Pkg", "Random", "Requires", "Statistics"]
git-tree-sha1 = "78de319bce99d1d8c1d4fe5401f7cfc2627df396"
uuid = "872c559c-99b0-510c-b3b7-b6c96a88d5cd"
version = "0.9.18"
[deps.NNlib.extensions]
NNlibAMDGPUExt = "AMDGPU"
NNlibCUDACUDNNExt = ["CUDA", "cuDNN"]
NNlibCUDAExt = "CUDA"
NNlibEnzymeCoreExt = "EnzymeCore"
[deps.NNlib.weakdeps]
AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
EnzymeCore = "f151be2c-9106-41f4-ab19-57ee4f262869"
cuDNN = "02a925ec-e4fe-4b08-9a7e-0d78e3d38ccd"
[[deps.NaNMath]]
deps = ["OpenLibm_jll"]
git-tree-sha1 = "0877504529a3e5c3343c6f8b4c0381e57e4387e4"
uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
version = "1.0.2"
[[deps.NameResolution]]
deps = ["PrettyPrint"]
git-tree-sha1 = "1a0fa0e9613f46c9b8c11eee38ebb4f590013c5e"
uuid = "71a1bf82-56d0-4bbc-8a3c-48b961074391"
version = "0.1.5"
[[deps.NamedTupleTools]]
git-tree-sha1 = "90914795fc59df44120fe3fff6742bb0d7adb1d0"
uuid = "d9ec5142-1e00-5aa0-9d6a-321866360f50"
version = "0.14.3"
[[deps.NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
version = "1.2.0"
[[deps.NonlinearSolve]]
deps = ["ADTypes", "ArrayInterface", "ConcreteStructs", "DiffEqBase", "FastBroadcast", "FastClosures", "FiniteDiff", "ForwardDiff", "LazyArrays", "LineSearches", "LinearAlgebra", "LinearSolve", "MaybeInplace", "PrecompileTools", "Preferences", "Printf", "RecursiveArrayTools", "Reexport", "SciMLBase", "SimpleNonlinearSolve", "SparseArrays", "SparseDiffTools", "StaticArraysCore", "SymbolicIndexingInterface", "TimerOutputs"]
git-tree-sha1 = "dc0d78eeed89323526203b8a11a4fa6cdbe25cd6"
uuid = "8913a72c-1f9b-4ce2-8d82-65094dcecaec"
version = "3.11.0"
[deps.NonlinearSolve.extensions]
NonlinearSolveBandedMatricesExt = "BandedMatrices"
NonlinearSolveFastLevenbergMarquardtExt = "FastLevenbergMarquardt"
NonlinearSolveFixedPointAccelerationExt = "FixedPointAcceleration"
NonlinearSolveLeastSquaresOptimExt = "LeastSquaresOptim"
NonlinearSolveMINPACKExt = "MINPACK"
NonlinearSolveNLSolversExt = "NLSolvers"
NonlinearSolveNLsolveExt = "NLsolve"
NonlinearSolveSIAMFANLEquationsExt = "SIAMFANLEquations"
NonlinearSolveSpeedMappingExt = "SpeedMapping"
NonlinearSolveSymbolicsExt = "Symbolics"
NonlinearSolveZygoteExt = "Zygote"
[deps.NonlinearSolve.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
FastLevenbergMarquardt = "7a0df574-e128-4d35-8cbd-3d84502bf7ce"
FixedPointAcceleration = "817d07cb-a79a-5c30-9a31-890123675176"
LeastSquaresOptim = "0fc2ff8b-aaa3-5acd-a817-1944a5e08891"
MINPACK = "4854310b-de5a-5eb6-a2a5-c1dee2bd17f9"
NLSolvers = "337daf1e-9722-11e9-073e-8b9effe078ba"
NLsolve = "2774e3e8-f4cf-5e23-947b-6d7e65073b56"
SIAMFANLEquations = "084e46ad-d928-497d-ad5e-07fa361a48c4"
SpeedMapping = "f1835b91-879b-4a3f-a438-e4baacf14412"
Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[[deps.ObjectFile]]
deps = ["Reexport", "StructIO"]
git-tree-sha1 = "195e0a19842f678dd3473ceafbe9d82dfacc583c"
uuid = "d8793406-e978-5875-9003-1fc021f44a92"
version = "0.4.1"
[[deps.Observables]]
git-tree-sha1 = "7438a59546cf62428fc9d1bc94729146d37a7225"
uuid = "510215fc-4207-5dde-b226-833fc4488ee2"
version = "0.5.5"
[[deps.OffsetArrays]]
git-tree-sha1 = "e64b4f5ea6b7389f6f046d13d4896a8f9c1ba71e"
uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881"
version = "1.14.0"
weakdeps = ["Adapt"]
[deps.OffsetArrays.extensions]
OffsetArraysAdaptExt = "Adapt"
[[deps.Ogg_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "887579a3eb005446d514ab7aeac5d1d027658b8f"
uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051"
version = "1.3.5+1"
[[deps.OneHotArrays]]
deps = ["Adapt", "ChainRulesCore", "Compat", "GPUArraysCore", "LinearAlgebra", "NNlib"]
git-tree-sha1 = "963a3f28a2e65bb87a68033ea4a616002406037d"
uuid = "0b1bfda6-eb8a-41d2-88d8-f5af5cad476f"
version = "0.2.5"
[[deps.OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"
version = "0.3.23+4"
[[deps.OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"
version = "0.8.1+2"
[[deps.OpenMPI_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Hwloc_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "MPIPreferences", "TOML", "Zlib_jll"]
git-tree-sha1 = "a9de2f1fc98b92f8856c640bf4aec1ac9b2a0d86"
uuid = "fe0851c0-eecd-5654-98d4-656369965a5c"
version = "5.0.3+0"
[[deps.OpenSSL]]
deps = ["BitFlags", "Dates", "MozillaCACerts_jll", "OpenSSL_jll", "Sockets"]
git-tree-sha1 = "38cb508d080d21dc1128f7fb04f20387ed4c0af4"
uuid = "4d8831e6-92b7-49fb-bdf8-b643e874388c"
version = "1.4.3"
[[deps.OpenSSL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "a028ee3cb5641cccc4c24e90c36b0a4f7707bdf5"
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
version = "3.0.14+0"
[[deps.OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"
[[deps.Optim]]
deps = ["Compat", "FillArrays", "ForwardDiff", "LineSearches", "LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "PositiveFactorizations", "Printf", "SparseArrays", "StatsBase"]
git-tree-sha1 = "d9b79c4eed437421ac4285148fcadf42e0700e89"
uuid = "429524aa-4258-5aef-a3af-852621145aeb"
version = "1.9.4"
[deps.Optim.extensions]
OptimMOIExt = "MathOptInterface"
[deps.Optim.weakdeps]
MathOptInterface = "b8f27783-ece8-5eb3-8dc8-9495eed66fee"
[[deps.Optimisers]]
deps = ["ChainRulesCore", "Functors", "LinearAlgebra", "Random", "Statistics"]
git-tree-sha1 = "6572fe0c5b74431aaeb0b18a4aa5ef03c84678be"
uuid = "3bd65402-5787-11e9-1adc-39752487f4e2"
version = "0.3.3"
[[deps.Opus_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "51a08fb14ec28da2ec7a927c4337e4332c2a4720"
uuid = "91d4177d-7536-5919-b921-800302f37372"
version = "1.3.2+0"
[[deps.OrderedCollections]]
git-tree-sha1 = "dfdf5519f235516220579f949664f1bf44e741c5"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.6.3"
[[deps.OrdinaryDiffEq]]
deps = ["ADTypes", "Adapt", "ArrayInterface", "DataStructures", "DiffEqBase", "DocStringExtensions", "EnumX", "ExponentialUtilities", "FastBroadcast", "FastClosures", "FillArrays", "FiniteDiff", "ForwardDiff", "FunctionWrappersWrappers", "IfElse", "InteractiveUtils", "LineSearches", "LinearAlgebra", "LinearSolve", "Logging", "MacroTools", "MuladdMacro", "NonlinearSolve", "Polyester", "PreallocationTools", "PrecompileTools", "Preferences", "RecursiveArrayTools", "Reexport", "SciMLBase", "SciMLOperators", "SciMLStructures", "SimpleNonlinearSolve", "SimpleUnPack", "SparseArrays", "SparseDiffTools", "StaticArrayInterface", "StaticArrays", "TruncatedStacktraces"]
git-tree-sha1 = "75b0d2bf28d0df92931919004a5be5304c38cca2"
uuid = "1dea7af3-3e70-54e6-95c3-0bf5283fa5ed"
version = "6.80.1"
[[deps.PCRE2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "efcefdf7-47ab-520b-bdef-62a2eaa19f15"
version = "10.42.0+1"
[[deps.PDMats]]
deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "949347156c25054de2db3b166c52ac4728cbad65"
uuid = "90014a1f-27ba-587c-ab20-58faa44d9150"
version = "0.11.31"
[[deps.PackageExtensionCompat]]
git-tree-sha1 = "fb28e33b8a95c4cee25ce296c817d89cc2e53518"
uuid = "65ce6f38-6b18-4e1d-a461-8949797d7930"
version = "1.0.2"
weakdeps = ["Requires", "TOML"]
[[deps.Parameters]]
deps = ["OrderedCollections", "UnPack"]
git-tree-sha1 = "34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe"
uuid = "d96e819e-fc66-5662-9728-84c9c7592b0a"
version = "0.12.3"
[[deps.Parsers]]
deps = ["Dates", "PrecompileTools", "UUIDs"]
git-tree-sha1 = "8489905bcdbcfac64d1daa51ca07c0d8f0283821"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.8.1"
[[deps.Pidfile]]
deps = ["FileWatching", "Test"]
git-tree-sha1 = "2d8aaf8ee10df53d0dfb9b8ee44ae7c04ced2b03"
uuid = "fa939f87-e72e-5be4-a000-7fc836dbe307"
version = "1.3.0"
[[deps.Pipe]]
git-tree-sha1 = "6842804e7867b115ca9de748a0cf6b364523c16d"
uuid = "b98c9c47-44ae-5843-9183-064241ee97a0"
version = "1.3.0"
[[deps.Pixman_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "LLVMOpenMP_jll", "Libdl"]
git-tree-sha1 = "35621f10a7531bc8fa58f74610b1bfb70a3cfc6b"
uuid = "30392449-352a-5448-841d-b1acce4e97dc"
version = "0.43.4+0"
[[deps.Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
version = "1.10.0"
[[deps.PlotThemes]]
deps = ["PlotUtils", "Statistics"]
git-tree-sha1 = "6e55c6841ce3411ccb3457ee52fc48cb698d6fb0"
uuid = "ccf2f8ad-2431-5c83-bf29-c5338b663b6a"
version = "3.2.0"
[[deps.PlotUtils]]
deps = ["ColorSchemes", "Colors", "Dates", "PrecompileTools", "Printf", "Random", "Reexport", "Statistics"]
git-tree-sha1 = "7b1a9df27f072ac4c9c7cbe5efb198489258d1f5"
uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043"
version = "1.4.1"
[[deps.PlotlyBase]]
deps = ["ColorSchemes", "Dates", "DelimitedFiles", "DocStringExtensions", "JSON", "LaTeXStrings", "Logging", "Parameters", "Pkg", "REPL", "Requires", "Statistics", "UUIDs"]
git-tree-sha1 = "56baf69781fc5e61607c3e46227ab17f7040ffa2"
uuid = "a03496cd-edff-5a9b-9e67-9cda94a718b5"
version = "0.8.19"
[[deps.PlotlyJS]]
deps = ["Base64", "Blink", "DelimitedFiles", "JSExpr", "JSON", "Kaleido_jll", "Markdown", "Pkg", "PlotlyBase", "PlotlyKaleido", "REPL", "Reexport", "Requires", "WebIO"]
git-tree-sha1 = "e62d886d33b81c371c9d4e2f70663c0637f19459"
uuid = "f0f68f2c-4968-5e81-91da-67840de0976a"
version = "0.18.13"
[deps.PlotlyJS.extensions]
CSVExt = "CSV"
DataFramesExt = ["DataFrames", "CSV"]
IJuliaExt = "IJulia"
JSON3Ext = "JSON3"
[deps.PlotlyJS.weakdeps]
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a"
JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1"
[[deps.PlotlyKaleido]]
deps = ["Base64", "JSON", "Kaleido_jll"]
git-tree-sha1 = "2650cd8fb83f73394996d507b3411a7316f6f184"
uuid = "f2990250-8cf9-495f-b13a-cce12b45703c"
version = "2.2.4"
[[deps.Plots]]
deps = ["Base64", "Contour", "Dates", "Downloads", "FFMPEG", "FixedPointNumbers", "GR", "JLFzf", "JSON", "LaTeXStrings", "Latexify", "LinearAlgebra", "Measures", "NaNMath", "Pkg", "PlotThemes", "PlotUtils", "PrecompileTools", "Printf", "REPL", "Random", "RecipesBase", "RecipesPipeline", "Reexport", "RelocatableFolders", "Requires", "Scratch", "Showoff", "SparseArrays", "Statistics", "StatsBase", "TOML", "UUIDs", "UnicodeFun", "UnitfulLatexify", "Unzip"]
git-tree-sha1 = "082f0c4b70c202c37784ce4bfbc33c9f437685bf"
uuid = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
version = "1.40.5"
[deps.Plots.extensions]
FileIOExt = "FileIO"
GeometryBasicsExt = "GeometryBasics"
IJuliaExt = "IJulia"
ImageInTerminalExt = "ImageInTerminal"
UnitfulExt = "Unitful"
[deps.Plots.weakdeps]
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a"
ImageInTerminal = "d8c32880-2388-543b-8c61-d9f865259254"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
[[deps.PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "FixedPointNumbers", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "MIMEs", "Markdown", "Random", "Reexport", "URIs", "UUIDs"]
git-tree-sha1 = "ab55ee1510ad2af0ff674dbcced5e94921f867a9"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.59"
[[deps.PoissonRandom]]
deps = ["Random"]
git-tree-sha1 = "a0f1159c33f846aa77c3f30ebbc69795e5327152"
uuid = "e409e4f3-bfea-5376-8464-e040bb5c01ab"
version = "0.4.4"
[[deps.Polyester]]
deps = ["ArrayInterface", "BitTwiddlingConvenienceFunctions", "CPUSummary", "IfElse", "ManualMemory", "PolyesterWeave", "Requires", "Static", "StaticArrayInterface", "StrideArraysCore", "ThreadingUtilities"]
git-tree-sha1 = "9ff799e8fb8ed6717710feee3be3bc20645daa97"
uuid = "f517fe37-dbe3-4b94-8317-1923a5111588"
version = "0.7.15"
[[deps.PolyesterWeave]]
deps = ["BitTwiddlingConvenienceFunctions", "CPUSummary", "IfElse", "Static", "ThreadingUtilities"]
git-tree-sha1 = "645bed98cd47f72f67316fd42fc47dee771aefcd"
uuid = "1d0040c9-8b98-4ee7-8388-3f51789ca0ad"
version = "0.2.2"
[[deps.PositiveFactorizations]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "17275485f373e6673f7e7f97051f703ed5b15b20"
uuid = "85a6dd25-e78a-55b7-8502-1745935b8125"
version = "0.2.4"
[[deps.PreallocationTools]]
deps = ["Adapt", "ArrayInterface", "ForwardDiff"]
git-tree-sha1 = "406c29a7f46706d379a3bce45671b4e3a39ddfbc"
uuid = "d236fae5-4411-538c-8e31-a6e3d9e00b46"
version = "0.4.22"
weakdeps = ["ReverseDiff"]
[deps.PreallocationTools.extensions]
PreallocationToolsReverseDiffExt = "ReverseDiff"
[[deps.PrecompileTools]]
deps = ["Preferences"]
git-tree-sha1 = "5aa36f7049a63a1528fe8f7c3f2113413ffd4e1f"
uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a"
version = "1.2.1"
[[deps.Preferences]]
deps = ["TOML"]
git-tree-sha1 = "9306f6085165d270f7e3db02af26a400d580f5c6"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.4.3"
[[deps.PrettyPrint]]
git-tree-sha1 = "632eb4abab3449ab30c5e1afaa874f0b98b586e4"
uuid = "8162dcfd-2161-5ef2-ae6c-7681170c5f98"
version = "0.2.0"
[[deps.Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[deps.Profile]]
deps = ["Printf"]
uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79"
[[deps.ProgressLogging]]
deps = ["Logging", "SHA", "UUIDs"]
git-tree-sha1 = "80d919dee55b9c50e8d9e2da5eeafff3fe58b539"
uuid = "33c8b6b6-d38a-422a-b730-caa89a2f386c"
version = "0.1.4"
[[deps.ProgressMeter]]
deps = ["Distributed", "Printf"]
git-tree-sha1 = "00099623ffee15972c16111bcf84c58a0051257c"
uuid = "92933f4c-e287-5a05-a399-4b506db050ca"
version = "1.9.0"
[[deps.PtrArrays]]
git-tree-sha1 = "f011fbb92c4d401059b2212c05c0601b70f8b759"
uuid = "43287f4e-b6f4-7ad1-bb20-aadabca52c3d"
version = "1.2.0"
[[deps.Qt6Base_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Fontconfig_jll", "Glib_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "OpenSSL_jll", "Vulkan_Loader_jll", "Xorg_libSM_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Xorg_libxcb_jll", "Xorg_xcb_util_cursor_jll", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_keysyms_jll", "Xorg_xcb_util_renderutil_jll", "Xorg_xcb_util_wm_jll", "Zlib_jll", "libinput_jll", "xkbcommon_jll"]
git-tree-sha1 = "492601870742dcd38f233b23c3ec629628c1d724"
uuid = "c0090381-4147-56d7-9ebc-da0b1113ec56"
version = "6.7.1+1"
[[deps.QuadGK]]
deps = ["DataStructures", "LinearAlgebra"]
git-tree-sha1 = "9b23c31e76e333e6fb4c1595ae6afa74966a729e"
uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc"
version = "2.9.4"
[[deps.REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[deps.Random]]
deps = ["SHA"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[deps.Random123]]
deps = ["Random", "RandomNumbers"]
git-tree-sha1 = "4743b43e5a9c4a2ede372de7061eed81795b12e7"
uuid = "74087812-796a-5b5d-8853-05524746bad3"
version = "1.7.0"
[[deps.RandomNumbers]]
deps = ["Random", "Requires"]
git-tree-sha1 = "043da614cc7e95c703498a491e2c21f58a2b8111"
uuid = "e6cf234a-135c-5ec9-84dd-332b85af5143"
version = "1.5.3"
[[deps.Ratios]]
deps = ["Requires"]
git-tree-sha1 = "1342a47bf3260ee108163042310d26f2be5ec90b"
uuid = "c84ed2f1-dad5-54f0-aa8e-dbefe2724439"
version = "0.4.5"
weakdeps = ["FixedPointNumbers"]
[deps.Ratios.extensions]
RatiosFixedPointNumbersExt = "FixedPointNumbers"
[[deps.RealDot]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9"
uuid = "c1ae055f-0cd5-4b69-90a6-9a35b1a98df9"
version = "0.1.0"
[[deps.RecipesBase]]
deps = ["PrecompileTools"]
git-tree-sha1 = "5c3d09cc4f31f5fc6af001c250bf1278733100ff"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.3.4"
[[deps.RecipesPipeline]]
deps = ["Dates", "NaNMath", "PlotUtils", "PrecompileTools", "RecipesBase"]
git-tree-sha1 = "45cf9fd0ca5839d06ef333c8201714e888486342"
uuid = "01d81517-befc-4cb6-b9ec-a95719d0359c"
version = "0.6.12"
[[deps.RecursiveArrayTools]]
deps = ["Adapt", "ArrayInterface", "DocStringExtensions", "GPUArraysCore", "IteratorInterfaceExtensions", "LinearAlgebra", "RecipesBase", "SparseArrays", "StaticArraysCore", "Statistics", "SymbolicIndexingInterface", "Tables"]
git-tree-sha1 = "3400ce27995422fb88ffcd3af9945565aad947f0"
uuid = "731186ca-8d62-57ce-b412-fbd966d074cd"
version = "3.23.1"
[deps.RecursiveArrayTools.extensions]
RecursiveArrayToolsFastBroadcastExt = "FastBroadcast"
RecursiveArrayToolsForwardDiffExt = "ForwardDiff"
RecursiveArrayToolsMeasurementsExt = "Measurements"
RecursiveArrayToolsMonteCarloMeasurementsExt = "MonteCarloMeasurements"
RecursiveArrayToolsReverseDiffExt = ["ReverseDiff", "Zygote"]
RecursiveArrayToolsTrackerExt = "Tracker"
RecursiveArrayToolsZygoteExt = "Zygote"
[deps.RecursiveArrayTools.weakdeps]
FastBroadcast = "7034ab61-46d4-4ed7-9d0f-46aef9175898"
ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210"
Measurements = "eff96d63-e80a-5855-80a2-b1b0885c5ab7"
MonteCarloMeasurements = "0987c9cc-fe09-11e8-30f0-b96dd679fdca"
ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[[deps.RecursiveFactorization]]
deps = ["LinearAlgebra", "LoopVectorization", "Polyester", "PrecompileTools", "StrideArraysCore", "TriangularSolve"]
git-tree-sha1 = "6db1a75507051bc18bfa131fbc7c3f169cc4b2f6"
uuid = "f2c3362d-daeb-58d1-803e-2bc74f2840b4"
version = "0.2.23"
[[deps.Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[deps.RelocatableFolders]]
deps = ["SHA", "Scratch"]
git-tree-sha1 = "ffdaf70d81cf6ff22c2b6e733c900c3321cab864"
uuid = "05181044-ff0b-4ac5-8273-598c1e38db00"
version = "1.0.1"
[[deps.Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.3.0"
[[deps.ResettableStacks]]
deps = ["StaticArrays"]
git-tree-sha1 = "256eeeec186fa7f26f2801732774ccf277f05db9"
uuid = "ae5879a3-cd67-5da8-be7f-38c6eb64a37b"
version = "1.1.1"
[[deps.ReverseDiff]]
deps = ["ChainRulesCore", "DiffResults", "DiffRules", "ForwardDiff", "FunctionWrappers", "LinearAlgebra", "LogExpFunctions", "MacroTools", "NaNMath", "Random", "SpecialFunctions", "StaticArrays", "Statistics"]
git-tree-sha1 = "cc6cd622481ea366bb9067859446a8b01d92b468"
uuid = "37e2e3b7-166d-5795-8a7a-e32c996b4267"
version = "1.15.3"
[[deps.Rmath]]
deps = ["Random", "Rmath_jll"]
git-tree-sha1 = "f65dcb5fa46aee0cf9ed6274ccbd597adc49aa7b"
uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa"
version = "0.7.1"
[[deps.Rmath_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "d483cd324ce5cf5d61b77930f0bbd6cb61927d21"
uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f"
version = "0.4.2+0"
[[deps.RuntimeGeneratedFunctions]]
deps = ["ExprTools", "SHA", "Serialization"]
git-tree-sha1 = "04c968137612c4a5629fa531334bb81ad5680f00"
uuid = "7e49a35a-f44a-4d26-94aa-eba1b4ca6b47"
version = "0.5.13"
[[deps.SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
version = "0.7.0"
[[deps.SIMDTypes]]
git-tree-sha1 = "330289636fb8107c5f32088d2741e9fd7a061a5c"
uuid = "94e857df-77ce-4151-89e5-788b33177be4"
version = "0.1.0"
[[deps.SLEEFPirates]]
deps = ["IfElse", "Static", "VectorizationBase"]
git-tree-sha1 = "456f610ca2fbd1c14f5fcf31c6bfadc55e7d66e0"
uuid = "476501e8-09a2-5ece-8869-fb82de89a1fa"
version = "0.6.43"
[[deps.SciMLBase]]
deps = ["ADTypes", "Accessors", "ArrayInterface", "CommonSolve", "ConstructionBase", "Distributed", "DocStringExtensions", "EnumX", "FunctionWrappersWrappers", "IteratorInterfaceExtensions", "LinearAlgebra", "Logging", "Markdown", "PrecompileTools", "Preferences", "Printf", "RecipesBase", "RecursiveArrayTools", "Reexport", "RuntimeGeneratedFunctions", "SciMLOperators", "SciMLStructures", "StaticArraysCore", "Statistics", "SymbolicIndexingInterface", "Tables"]
git-tree-sha1 = "7a6c5c8c38d2e37f45d4686c3598c20c1aebf48e"
uuid = "0bca4576-84f4-4d90-8ffe-ffa030f20462"
version = "2.41.3"
[deps.SciMLBase.extensions]
SciMLBaseChainRulesCoreExt = "ChainRulesCore"
SciMLBaseMakieExt = "Makie"
SciMLBasePartialFunctionsExt = "PartialFunctions"
SciMLBasePyCallExt = "PyCall"
SciMLBasePythonCallExt = "PythonCall"
SciMLBaseRCallExt = "RCall"
SciMLBaseZygoteExt = "Zygote"
[deps.SciMLBase.weakdeps]
ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2"
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
Makie = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a"
PartialFunctions = "570af359-4316-4cb7-8c74-252c00c2016b"
PyCall = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0"
PythonCall = "6099a3de-0909-46bc-b1f4-468b9a2dfc0d"
RCall = "6f49c342-dc21-5d91-9882-a32aef131414"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[[deps.SciMLOperators]]
deps = ["ArrayInterface", "DocStringExtensions", "LinearAlgebra", "MacroTools", "Setfield", "SparseArrays", "StaticArraysCore"]
git-tree-sha1 = "10499f619ef6e890f3f4a38914481cc868689cd5"
uuid = "c0aeaf25-5076-4817-a8d5-81caf7dfa961"
version = "0.3.8"
[[deps.SciMLSensitivity]]
deps = ["ADTypes", "Adapt", "ArrayInterface", "ChainRulesCore", "DiffEqBase", "DiffEqCallbacks", "DiffEqNoiseProcess", "Distributions", "EllipsisNotation", "Enzyme", "FiniteDiff", "ForwardDiff", "FunctionProperties", "FunctionWrappersWrappers", "Functors", "GPUArraysCore", "LinearAlgebra", "LinearSolve", "Markdown", "OrdinaryDiffEq", "Parameters", "PreallocationTools", "QuadGK", "Random", "RandomNumbers", "RecursiveArrayTools", "Reexport", "ReverseDiff", "SciMLBase", "SciMLOperators", "SparseDiffTools", "StaticArrays", "StaticArraysCore", "Statistics", "StochasticDiffEq", "Tracker", "TruncatedStacktraces", "Zygote"]
git-tree-sha1 = "3b0fde1944502bd736bcdc3d0df577dddb54d189"
uuid = "1ed8b502-d754-442c-8d5d-10ac956f44a1"
version = "7.51.0"
[[deps.SciMLStructures]]
deps = ["ArrayInterface"]
git-tree-sha1 = "cfdd1200d150df1d3c055cc72ee6850742e982d7"
uuid = "53ae85a6-f571-4167-b2af-e1d143709226"
version = "1.4.1"
[[deps.Scratch]]
deps = ["Dates"]
git-tree-sha1 = "3bac05bc7e74a75fd9cba4295cde4045d9fe2386"
uuid = "6c6a2e73-6563-6170-7368-637461726353"
version = "1.2.1"
[[deps.Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[deps.Setfield]]
deps = ["ConstructionBase", "Future", "MacroTools", "StaticArraysCore"]
git-tree-sha1 = "e2cc6d8c88613c05e1defb55170bf5ff211fbeac"
uuid = "efcf1570-3423-57d1-acb7-fd33fddbac46"
version = "1.1.1"
[[deps.SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"
[[deps.ShowCases]]
git-tree-sha1 = "7f534ad62ab2bd48591bdeac81994ea8c445e4a5"
uuid = "605ecd9f-84a6-4c9e-81e2-4798472b76a3"
version = "0.1.0"
[[deps.Showoff]]
deps = ["Dates", "Grisu"]
git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de"
uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f"
version = "1.0.3"
[[deps.SimpleBufferStream]]
git-tree-sha1 = "874e8867b33a00e784c8a7e4b60afe9e037b74e1"
uuid = "777ac1f9-54b0-4bf8-805c-2214025038e7"
version = "1.1.0"
[[deps.SimpleNonlinearSolve]]
deps = ["ADTypes", "ArrayInterface", "ConcreteStructs", "DiffEqBase", "DiffResults", "FastClosures", "FiniteDiff", "ForwardDiff", "LinearAlgebra", "MaybeInplace", "PrecompileTools", "Reexport", "SciMLBase", "StaticArraysCore"]
git-tree-sha1 = "c020028bb22a2f23cbd88cb92cf47cbb8c98513f"
uuid = "727e6d20-b764-4bd8-a329-72de5adea6c7"
version = "1.8.0"
[deps.SimpleNonlinearSolve.extensions]
SimpleNonlinearSolveChainRulesCoreExt = "ChainRulesCore"
SimpleNonlinearSolvePolyesterForwardDiffExt = "PolyesterForwardDiff"
SimpleNonlinearSolveReverseDiffExt = "ReverseDiff"
SimpleNonlinearSolveStaticArraysExt = "StaticArrays"
SimpleNonlinearSolveTrackerExt = "Tracker"
SimpleNonlinearSolveZygoteExt = "Zygote"
[deps.SimpleNonlinearSolve.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
PolyesterForwardDiff = "98d1487c-24ca-40b6-b7ab-df2af84e126b"
ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[[deps.SimpleTraits]]
deps = ["InteractiveUtils", "MacroTools"]
git-tree-sha1 = "5d7e3f4e11935503d3ecaf7186eac40602e7d231"
uuid = "699a6c99-e7fa-54fc-8d76-47d257e15c1d"
version = "0.9.4"
[[deps.SimpleUnPack]]
git-tree-sha1 = "58e6353e72cde29b90a69527e56df1b5c3d8c437"
uuid = "ce78b400-467f-4804-87d8-8f486da07d0a"
version = "1.1.0"
[[deps.Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[deps.SortingAlgorithms]]
deps = ["DataStructures"]
git-tree-sha1 = "66e0a8e672a0bdfca2c3f5937efb8538b9ddc085"
uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c"
version = "1.2.1"
[[deps.SparseArrays]]
deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
version = "1.10.0"
[[deps.SparseDiffTools]]
deps = ["ADTypes", "Adapt", "ArrayInterface", "Compat", "DataStructures", "FiniteDiff", "ForwardDiff", "Graphs", "LinearAlgebra", "PackageExtensionCompat", "Random", "Reexport", "SciMLOperators", "Setfield", "SparseArrays", "StaticArrayInterface", "StaticArrays", "Tricks", "UnPack", "VertexSafeGraphs"]
git-tree-sha1 = "cce98ad7c896e52bb0eded174f02fc2a29c38477"
uuid = "47a9eef4-7e08-11e9-0b38-333d64bd3804"
version = "2.18.0"
[deps.SparseDiffTools.extensions]
SparseDiffToolsEnzymeExt = "Enzyme"
SparseDiffToolsPolyesterExt = "Polyester"
SparseDiffToolsPolyesterForwardDiffExt = "PolyesterForwardDiff"
SparseDiffToolsSymbolicsExt = "Symbolics"
SparseDiffToolsZygoteExt = "Zygote"
[deps.SparseDiffTools.weakdeps]
Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9"
Polyester = "f517fe37-dbe3-4b94-8317-1923a5111588"
PolyesterForwardDiff = "98d1487c-24ca-40b6-b7ab-df2af84e126b"
Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[[deps.SparseInverseSubset]]
deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "52962839426b75b3021296f7df242e40ecfc0852"
uuid = "dc90abb0-5640-4711-901d-7e5b23a2fada"
version = "0.1.2"
[[deps.Sparspak]]
deps = ["Libdl", "LinearAlgebra", "Logging", "OffsetArrays", "Printf", "SparseArrays", "Test"]
git-tree-sha1 = "342cf4b449c299d8d1ceaf00b7a49f4fbc7940e7"
uuid = "e56a9233-b9d6-4f03-8d0f-1825330902ac"
version = "0.3.9"
[[deps.SpecialFunctions]]
deps = ["IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
git-tree-sha1 = "2f5d4697f21388cbe1ff299430dd169ef97d7e14"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "2.4.0"
weakdeps = ["ChainRulesCore"]
[deps.SpecialFunctions.extensions]
SpecialFunctionsChainRulesCoreExt = "ChainRulesCore"
[[deps.SplittablesBase]]
deps = ["Setfield", "Test"]
git-tree-sha1 = "e08a62abc517eb79667d0a29dc08a3b589516bb5"
uuid = "171d559e-b47b-412a-8079-5efa626c420e"
version = "0.1.15"
[[deps.Static]]
deps = ["IfElse"]
git-tree-sha1 = "d2fdac9ff3906e27f7a618d47b676941baa6c80c"
uuid = "aedffcd0-7271-4cad-89d0-dc628f76c6d3"
version = "0.8.10"
[[deps.StaticArrayInterface]]
deps = ["ArrayInterface", "Compat", "IfElse", "LinearAlgebra", "PrecompileTools", "Requires", "SparseArrays", "Static", "SuiteSparse"]
git-tree-sha1 = "8963e5a083c837531298fc41599182a759a87a6d"
uuid = "0d7ed370-da01-4f52-bd93-41d350b8b718"
version = "1.5.1"
weakdeps = ["OffsetArrays", "StaticArrays"]
[deps.StaticArrayInterface.extensions]
StaticArrayInterfaceOffsetArraysExt = "OffsetArrays"
StaticArrayInterfaceStaticArraysExt = "StaticArrays"
[[deps.StaticArrays]]
deps = ["LinearAlgebra", "PrecompileTools", "Random", "StaticArraysCore"]
git-tree-sha1 = "20833c5b7f7edf0e5026f23db7f268e4f23ec577"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.9.6"
weakdeps = ["ChainRulesCore", "Statistics"]
[deps.StaticArrays.extensions]
StaticArraysChainRulesCoreExt = "ChainRulesCore"
StaticArraysStatisticsExt = "Statistics"
[[deps.StaticArraysCore]]
git-tree-sha1 = "192954ef1208c7019899fbf8049e717f92959682"
uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
version = "1.4.3"
[[deps.Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
version = "1.10.0"
[[deps.StatsAPI]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "1ff449ad350c9c4cbc756624d6f8a8c3ef56d3ed"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.7.0"
[[deps.StatsBase]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
git-tree-sha1 = "5cf7606d6cef84b543b483848d4ae08ad9832b21"
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
version = "0.34.3"
[[deps.StatsFuns]]
deps = ["HypergeometricFunctions", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"]
git-tree-sha1 = "cef0472124fab0695b58ca35a77c6fb942fdab8a"
uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c"
version = "1.3.1"
weakdeps = ["ChainRulesCore", "InverseFunctions"]
[deps.StatsFuns.extensions]
StatsFunsChainRulesCoreExt = "ChainRulesCore"
StatsFunsInverseFunctionsExt = "InverseFunctions"
[[deps.SteadyStateDiffEq]]
deps = ["ConcreteStructs", "DiffEqBase", "DiffEqCallbacks", "LinearAlgebra", "Reexport", "SciMLBase"]
git-tree-sha1 = "a735fd5053724cf4de31c81b4e2cc429db844be5"
uuid = "9672c7b4-1e72-59bd-8a11-6ac3964bc41f"
version = "2.0.1"
[[deps.StochasticDiffEq]]
deps = ["Adapt", "ArrayInterface", "DataStructures", "DiffEqBase", "DiffEqNoiseProcess", "DocStringExtensions", "FiniteDiff", "ForwardDiff", "JumpProcesses", "LevyArea", "LinearAlgebra", "Logging", "MuladdMacro", "NLsolve", "OrdinaryDiffEq", "Random", "RandomNumbers", "RecursiveArrayTools", "Reexport", "SciMLBase", "SciMLOperators", "SparseArrays", "SparseDiffTools", "StaticArrays", "UnPack"]
git-tree-sha1 = "97e5d0b7e5ec2e68eec6626af97c59e9f6b6c3d0"
uuid = "789caeaf-c7a9-5a7d-9973-96adeb23e2a0"
version = "6.65.1"
[[deps.StrideArraysCore]]
deps = ["ArrayInterface", "CloseOpenIntervals", "IfElse", "LayoutPointers", "LinearAlgebra", "ManualMemory", "SIMDTypes", "Static", "StaticArrayInterface", "ThreadingUtilities"]
git-tree-sha1 = "f35f6ab602df8413a50c4a25ca14de821e8605fb"
uuid = "7792a7ef-975c-4747-a70f-980b88e8d1da"
version = "0.5.7"
[[deps.StructArrays]]
deps = ["ConstructionBase", "DataAPI", "Tables"]
git-tree-sha1 = "f4dc295e983502292c4c3f951dbb4e985e35b3be"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.18"
weakdeps = ["Adapt", "GPUArraysCore", "SparseArrays", "StaticArrays"]
[deps.StructArrays.extensions]
StructArraysAdaptExt = "Adapt"
StructArraysGPUArraysCoreExt = "GPUArraysCore"
StructArraysSparseArraysExt = "SparseArrays"
StructArraysStaticArraysExt = "StaticArrays"
[[deps.StructIO]]
deps = ["Test"]
git-tree-sha1 = "010dc73c7146869c042b49adcdb6bf528c12e859"
uuid = "53d494c1-5632-5724-8f4c-31dff12d585f"
version = "0.3.0"
[[deps.SuiteSparse]]
deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"]
uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9"
[[deps.SuiteSparse_jll]]
deps = ["Artifacts", "Libdl", "libblastrampoline_jll"]
uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c"
version = "7.2.1+1"
[[deps.Sundials]]
deps = ["CEnum", "DataStructures", "DiffEqBase", "Libdl", "LinearAlgebra", "Logging", "PrecompileTools", "Reexport", "SciMLBase", "SparseArrays", "Sundials_jll"]
git-tree-sha1 = "e15f5a73f0d14b9079b807a9d1dac13e4302e997"
uuid = "c3572dad-4567-51f8-b174-8c6c989267f4"
version = "4.24.0"
[[deps.Sundials_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "SuiteSparse_jll", "libblastrampoline_jll"]
git-tree-sha1 = "ba4d38faeb62de7ef47155ed321dce40a549c305"
uuid = "fb77eaff-e24c-56d4-86b1-d163f2edb164"
version = "5.2.2+0"
[[deps.SymbolicIndexingInterface]]
deps = ["Accessors", "ArrayInterface", "RuntimeGeneratedFunctions", "StaticArraysCore"]
git-tree-sha1 = "a5f6f138b740c9d93d76f0feddd3092e6ef002b7"
uuid = "2efcf032-c050-4f8e-a9bb-153293bab1f5"
version = "0.3.22"
[[deps.TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
version = "1.0.3"
[[deps.TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[deps.Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "OrderedCollections", "TableTraits"]
git-tree-sha1 = "cb76cf677714c095e535e3501ac7954732aeea2d"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.11.1"
[[deps.Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
version = "1.10.0"
[[deps.TensorCore]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6"
uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50"
version = "0.1.1"
[[deps.Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[deps.ThreadPools]]
deps = ["Printf", "RecipesBase", "Statistics"]
git-tree-sha1 = "50cb5f85d5646bc1422aa0238aa5bfca99ca9ae7"
uuid = "b189fb0b-2eb5-4ed4-bc0c-d34c51242431"
version = "2.1.1"
[[deps.ThreadingUtilities]]
deps = ["ManualMemory"]
git-tree-sha1 = "eda08f7e9818eb53661b3deb74e3159460dfbc27"
uuid = "8290d209-cae3-49c0-8002-c8c24d57dab5"
version = "0.5.2"
[[deps.TimerOutputs]]
deps = ["ExprTools", "Printf"]
git-tree-sha1 = "5a13ae8a41237cff5ecf34f73eb1b8f42fff6531"
uuid = "a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f"
version = "0.5.24"
[[deps.Tracker]]
deps = ["Adapt", "ChainRulesCore", "DiffRules", "ForwardDiff", "Functors", "LinearAlgebra", "LogExpFunctions", "MacroTools", "NNlib", "NaNMath", "Optimisers", "Printf", "Random", "Requires", "SpecialFunctions", "Statistics"]
git-tree-sha1 = "5158100ed55411867674576788e710a815a0af02"
uuid = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
version = "0.2.34"
weakdeps = ["PDMats"]
[deps.Tracker.extensions]
TrackerPDMatsExt = "PDMats"
[[deps.TranscodingStreams]]
git-tree-sha1 = "d73336d81cafdc277ff45558bb7eaa2b04a8e472"
uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
version = "0.10.10"
weakdeps = ["Random", "Test"]
[deps.TranscodingStreams.extensions]
TestExt = ["Test", "Random"]
[[deps.Transducers]]
deps = ["Adapt", "ArgCheck", "BangBang", "Baselet", "CompositionsBase", "ConstructionBase", "DefineSingletons", "Distributed", "InitialValues", "Logging", "Markdown", "MicroCollections", "Requires", "Setfield", "SplittablesBase", "Tables"]
git-tree-sha1 = "3064e780dbb8a9296ebb3af8f440f787bb5332af"
uuid = "28d57a85-8fef-5791-bfe6-a80928e7c999"
version = "0.4.80"
[deps.Transducers.extensions]
TransducersBlockArraysExt = "BlockArrays"
TransducersDataFramesExt = "DataFrames"
TransducersLazyArraysExt = "LazyArrays"
TransducersOnlineStatsBaseExt = "OnlineStatsBase"
TransducersReferenceablesExt = "Referenceables"
[deps.Transducers.weakdeps]
BlockArrays = "8e7c35d0-a365-5155-bbbb-fb81a777f24e"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
LazyArrays = "5078a376-72f3-5289-bfd5-ec5146d43c02"
OnlineStatsBase = "925886fa-5bf2-5e8e-b522-a9147a512338"
Referenceables = "42d2dcc6-99eb-4e98-b66c-637b7d73030e"
[[deps.TriangularSolve]]
deps = ["CloseOpenIntervals", "IfElse", "LayoutPointers", "LinearAlgebra", "LoopVectorization", "Polyester", "Static", "VectorizationBase"]
git-tree-sha1 = "be986ad9dac14888ba338c2554dcfec6939e1393"
uuid = "d5829a12-d9aa-46ab-831f-fb7c9ab06edf"
version = "0.2.1"
[[deps.Tricks]]
git-tree-sha1 = "eae1bb484cd63b36999ee58be2de6c178105112f"
uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775"
version = "0.1.8"
[[deps.TruncatedStacktraces]]
deps = ["InteractiveUtils", "MacroTools", "Preferences"]
git-tree-sha1 = "ea3e54c2bdde39062abf5a9758a23735558705e1"
uuid = "781d530d-4396-4725-bb49-402e4bee1e77"
version = "1.4.0"
[[deps.URIs]]
git-tree-sha1 = "67db6cc7b3821e19ebe75791a9dd19c9b1188f2b"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.5.1"
[[deps.UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[deps.UnPack]]
git-tree-sha1 = "387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b"
uuid = "3a884ed6-31ef-47d7-9d2a-63182c4928ed"
version = "1.0.2"
[[deps.Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[deps.UnicodeFun]]
deps = ["REPL"]
git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf"
uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1"
version = "0.4.1"
[[deps.Unitful]]
deps = ["Dates", "LinearAlgebra", "Random"]
git-tree-sha1 = "dd260903fdabea27d9b6021689b3cd5401a57748"
uuid = "1986cc42-f94f-5a68-af5c-568840ba703d"
version = "1.20.0"
weakdeps = ["ConstructionBase", "InverseFunctions"]
[deps.Unitful.extensions]
ConstructionBaseUnitfulExt = "ConstructionBase"
InverseFunctionsUnitfulExt = "InverseFunctions"
[[deps.UnitfulLatexify]]
deps = ["LaTeXStrings", "Latexify", "Unitful"]
git-tree-sha1 = "e2d817cc500e960fdbafcf988ac8436ba3208bfd"
uuid = "45397f5d-5981-4c77-b2b3-fc36d6e9b728"
version = "1.6.3"
[[deps.UnsafeAtomics]]
git-tree-sha1 = "6331ac3440856ea1988316b46045303bef658278"
uuid = "013be700-e6cd-48c3-b4a1-df204f14c38f"
version = "0.2.1"
[[deps.UnsafeAtomicsLLVM]]
deps = ["LLVM", "UnsafeAtomics"]
git-tree-sha1 = "bf2c553f25e954a9b38c9c0593a59bb13113f9e5"
uuid = "d80eeb9a-aca5-4d75-85e5-170c8b632249"
version = "0.1.5"
[[deps.Unzip]]
git-tree-sha1 = "ca0969166a028236229f63514992fc073799bb78"
uuid = "41fe7b60-77ed-43a1-b4f0-825fd5a5650d"
version = "0.2.0"
[[deps.VectorizationBase]]
deps = ["ArrayInterface", "CPUSummary", "HostCPUFeatures", "IfElse", "LayoutPointers", "Libdl", "LinearAlgebra", "SIMDTypes", "Static", "StaticArrayInterface"]
git-tree-sha1 = "e7f5b81c65eb858bed630fe006837b935518aca5"
uuid = "3d5dd08c-fd9d-11e8-17fa-ed2836048c2f"
version = "0.21.70"
[[deps.VertexSafeGraphs]]
deps = ["Graphs"]
git-tree-sha1 = "8351f8d73d7e880bfc042a8b6922684ebeafb35c"
uuid = "19fa3120-7c27-5ec5-8db8-b0b0aa330d6f"
version = "0.2.0"
[[deps.Vulkan_Loader_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Wayland_jll", "Xorg_libX11_jll", "Xorg_libXrandr_jll", "xkbcommon_jll"]
git-tree-sha1 = "2f0486047a07670caad3a81a075d2e518acc5c59"
uuid = "a44049a8-05dd-5a78-86c9-5fde0876e88c"
version = "1.3.243+0"
[[deps.Wayland_jll]]
deps = ["Artifacts", "EpollShim_jll", "Expat_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "7558e29847e99bc3f04d6569e82d0f5c54460703"
uuid = "a2964d1f-97da-50d4-b82a-358c7fce9d89"
version = "1.21.0+1"
[[deps.Wayland_protocols_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "93f43ab61b16ddfb2fd3bb13b3ce241cafb0e6c9"
uuid = "2381bf8a-dfd0-557d-9999-79630e7b1b91"
version = "1.31.0+0"
[[deps.WebIO]]
deps = ["AssetRegistry", "Base64", "Distributed", "FunctionalCollections", "JSON", "Logging", "Observables", "Pkg", "Random", "Requires", "Sockets", "UUIDs", "WebSockets", "Widgets"]
git-tree-sha1 = "0eef0765186f7452e52236fa42ca8c9b3c11c6e3"
uuid = "0f1e0344-ec1d-5b48-a673-e5cf874b6c29"
version = "0.8.21"
[[deps.WebSockets]]
deps = ["Base64", "Dates", "HTTP", "Logging", "Sockets"]
git-tree-sha1 = "4162e95e05e79922e44b9952ccbc262832e4ad07"
uuid = "104b5d7c-a370-577a-8038-80a2059c5097"
version = "1.6.0"
[[deps.Widgets]]
deps = ["Colors", "Dates", "Observables", "OrderedCollections"]
git-tree-sha1 = "fcdae142c1cfc7d89de2d11e08721d0f2f86c98a"
uuid = "cc8bc4a8-27d6-5769-a93b-9d913e69aa62"
version = "0.6.6"
[[deps.WoodburyMatrices]]
deps = ["LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "c1a7aa6219628fcd757dede0ca95e245c5cd9511"
uuid = "efce3f68-66dc-5838-9240-27a6d6f5f9b6"
version = "1.0.0"
[[deps.XML2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Zlib_jll"]
git-tree-sha1 = "d9717ce3518dc68a99e6b96300813760d887a01d"
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
version = "2.13.1+0"
[[deps.XSLT_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "XML2_jll", "Zlib_jll"]
git-tree-sha1 = "a54ee957f4c86b526460a720dbc882fa5edcbefc"
uuid = "aed1982a-8fda-507f-9586-7b0439959a61"
version = "1.1.41+0"
[[deps.XZ_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "ac88fb95ae6447c8dda6a5503f3bafd496ae8632"
uuid = "ffd25f8a-64ca-5728-b0f7-c24cf3aae800"
version = "5.4.6+0"
[[deps.Xorg_libICE_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "326b4fea307b0b39892b3e85fa451692eda8d46c"
uuid = "f67eecfb-183a-506d-b269-f58e52b52d7c"
version = "1.1.1+0"
[[deps.Xorg_libSM_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libICE_jll"]
git-tree-sha1 = "3796722887072218eabafb494a13c963209754ce"
uuid = "c834827a-8449-5923-a945-d239c165b7dd"
version = "1.2.4+0"
[[deps.Xorg_libX11_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxcb_jll", "Xorg_xtrans_jll"]
git-tree-sha1 = "afead5aba5aa507ad5a3bf01f58f82c8d1403495"
uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc"
version = "1.8.6+0"
[[deps.Xorg_libXau_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "6035850dcc70518ca32f012e46015b9beeda49d8"
uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec"
version = "1.0.11+0"
[[deps.Xorg_libXcursor_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "12e0eb3bc634fa2080c1c37fccf56f7c22989afd"
uuid = "935fb764-8cf2-53bf-bb30-45bb1f8bf724"
version = "1.2.0+4"
[[deps.Xorg_libXdmcp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "34d526d318358a859d7de23da945578e8e8727b7"
uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05"
version = "1.1.4+0"
[[deps.Xorg_libXext_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"]
git-tree-sha1 = "d2d1a5c49fae4ba39983f63de6afcbea47194e85"
uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3"
version = "1.3.6+0"
[[deps.Xorg_libXfixes_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "0e0dc7431e7a0587559f9294aeec269471c991a4"
uuid = "d091e8ba-531a-589c-9de9-94069b037ed8"
version = "5.0.3+4"
[[deps.Xorg_libXi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXfixes_jll"]
git-tree-sha1 = "89b52bc2160aadc84d707093930ef0bffa641246"
uuid = "a51aa0fd-4e3c-5386-b890-e753decda492"
version = "1.7.10+4"
[[deps.Xorg_libXinerama_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll"]
git-tree-sha1 = "26be8b1c342929259317d8b9f7b53bf2bb73b123"
uuid = "d1454406-59df-5ea1-beac-c340f2130bc3"
version = "1.1.4+4"
[[deps.Xorg_libXrandr_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "34cea83cb726fb58f325887bf0612c6b3fb17631"
uuid = "ec84b674-ba8e-5d96-8ba1-2a689ba10484"
version = "1.5.2+4"
[[deps.Xorg_libXrender_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"]
git-tree-sha1 = "47e45cd78224c53109495b3e324df0c37bb61fbe"
uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa"
version = "0.9.11+0"
[[deps.Xorg_libpthread_stubs_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "8fdda4c692503d44d04a0603d9ac0982054635f9"
uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74"
version = "0.1.1+0"
[[deps.Xorg_libxcb_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"]
git-tree-sha1 = "bcd466676fef0878338c61e655629fa7bbc69d8e"
uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b"
version = "1.17.0+0"
[[deps.Xorg_libxkbfile_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"]
git-tree-sha1 = "730eeca102434283c50ccf7d1ecdadf521a765a4"
uuid = "cc61e674-0454-545c-8b26-ed2c68acab7a"
version = "1.1.2+0"
[[deps.Xorg_xcb_util_cursor_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_jll", "Xorg_xcb_util_renderutil_jll"]
git-tree-sha1 = "04341cb870f29dcd5e39055f895c39d016e18ccd"
uuid = "e920d4aa-a673-5f3a-b3d7-f755a4d47c43"
version = "0.1.4+0"
[[deps.Xorg_xcb_util_image_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "0fab0a40349ba1cba2c1da699243396ff8e94b97"
uuid = "12413925-8142-5f55-bb0e-6d7ca50bb09b"
version = "0.4.0+1"
[[deps.Xorg_xcb_util_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll"]
git-tree-sha1 = "e7fd7b2881fa2eaa72717420894d3938177862d1"
uuid = "2def613f-5ad1-5310-b15b-b15d46f528f5"
version = "0.4.0+1"
[[deps.Xorg_xcb_util_keysyms_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "d1151e2c45a544f32441a567d1690e701ec89b00"
uuid = "975044d2-76e6-5fbe-bf08-97ce7c6574c7"
version = "0.4.0+1"
[[deps.Xorg_xcb_util_renderutil_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "dfd7a8f38d4613b6a575253b3174dd991ca6183e"
uuid = "0d47668e-0667-5a69-a72c-f761630bfb7e"
version = "0.3.9+1"
[[deps.Xorg_xcb_util_wm_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "e78d10aab01a4a154142c5006ed44fd9e8e31b67"
uuid = "c22f9ab0-d5fe-5066-847c-f4bb1cd4e361"
version = "0.4.1+1"
[[deps.Xorg_xkbcomp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxkbfile_jll"]
git-tree-sha1 = "330f955bc41bb8f5270a369c473fc4a5a4e4d3cb"
uuid = "35661453-b289-5fab-8a00-3d9160c6a3a4"
version = "1.4.6+0"
[[deps.Xorg_xkeyboard_config_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xkbcomp_jll"]
git-tree-sha1 = "691634e5453ad362044e2ad653e79f3ee3bb98c3"
uuid = "33bec58e-1273-512f-9401-5d533626f822"
version = "2.39.0+0"
[[deps.Xorg_xtrans_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "e92a1a012a10506618f10b7047e478403a046c77"
uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10"
version = "1.5.0+0"
[[deps.ZipFile]]
deps = ["Libdl", "Printf", "Zlib_jll"]
git-tree-sha1 = "f492b7fe1698e623024e873244f10d89c95c340a"
uuid = "a5390f91-8eb1-5f08-bee0-b1d1ffed6cea"
version = "0.10.1"
[[deps.Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
version = "1.2.13+1"
[[deps.Zstd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "e678132f07ddb5bfa46857f0d7620fb9be675d3b"
uuid = "3161d3a3-bdf6-5164-811a-617609db77b4"
version = "1.5.6+0"
[[deps.Zygote]]
deps = ["AbstractFFTs", "ChainRules", "ChainRulesCore", "DiffRules", "Distributed", "FillArrays", "ForwardDiff", "GPUArrays", "GPUArraysCore", "IRTools", "InteractiveUtils", "LinearAlgebra", "LogExpFunctions", "MacroTools", "NaNMath", "PrecompileTools", "Random", "Requires", "SparseArrays", "SpecialFunctions", "Statistics", "ZygoteRules"]
git-tree-sha1 = "19c586905e78a26f7e4e97f81716057bd6b1bc54"
uuid = "e88e6eb3-aa80-5325-afca-941959d7151f"
version = "0.6.70"
weakdeps = ["Colors", "Distances", "Tracker"]
[deps.Zygote.extensions]
ZygoteColorsExt = "Colors"
ZygoteDistancesExt = "Distances"
ZygoteTrackerExt = "Tracker"
[[deps.ZygoteRules]]
deps = ["ChainRulesCore", "MacroTools"]
git-tree-sha1 = "27798139afc0a2afa7b1824c206d5e87ea587a00"
uuid = "700de1a5-db45-46bc-99cf-38207098b444"
version = "0.2.5"
[[deps.eudev_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "gperf_jll"]
git-tree-sha1 = "431b678a28ebb559d224c0b6b6d01afce87c51ba"
uuid = "35ca27e7-8b34-5b7f-bca9-bdc33f59eb06"
version = "3.2.9+0"
[[deps.fzf_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "a68c9655fbe6dfcab3d972808f1aafec151ce3f8"
uuid = "214eeab7-80f7-51ab-84ad-2988db7cef09"
version = "0.43.0+0"
[[deps.gperf_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3516a5630f741c9eecb3720b1ec9d8edc3ecc033"
uuid = "1a1c6b14-54f6-533d-8383-74cd7377aa70"
version = "3.1.1+0"
[[deps.libaec_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "46bf7be2917b59b761247be3f317ddf75e50e997"
uuid = "477f73a3-ac25-53e9-8cc3-50b2fa2566f0"
version = "1.1.2+0"
[[deps.libaom_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "1827acba325fdcdf1d2647fc8d5301dd9ba43a9d"
uuid = "a4ae2306-e953-59d6-aa16-d00cac43593b"
version = "3.9.0+0"
[[deps.libass_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "5982a94fcba20f02f42ace44b9894ee2b140fe47"
uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0"
version = "0.15.1+0"
[[deps.libblastrampoline_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"
version = "5.8.0+1"
[[deps.libevdev_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "141fe65dc3efabb0b1d5ba74e91f6ad26f84cc22"
uuid = "2db6ffa8-e38f-5e21-84af-90c45d0032cc"
version = "1.11.0+0"
[[deps.libfdk_aac_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "daacc84a041563f965be61859a36e17c4e4fcd55"
uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280"
version = "2.0.2+0"
[[deps.libinput_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "eudev_jll", "libevdev_jll", "mtdev_jll"]
git-tree-sha1 = "ad50e5b90f222cfe78aa3d5183a20a12de1322ce"
uuid = "36db933b-70db-51c0-b978-0f229ee0e533"
version = "1.18.0+0"
[[deps.libpng_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Zlib_jll"]
git-tree-sha1 = "d7015d2e18a5fd9a4f47de711837e980519781a4"
uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f"
version = "1.6.43+1"
[[deps.libvorbis_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll", "Pkg"]
git-tree-sha1 = "b910cb81ef3fe6e78bf6acee440bda86fd6ae00c"
uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a"
version = "1.3.7+1"
[[deps.mtdev_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "814e154bdb7be91d78b6802843f76b6ece642f11"
uuid = "009596ad-96f7-51b1-9f1b-5ce2d5e8a71e"
version = "1.1.6+0"
[[deps.nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
version = "1.52.0+1"
[[deps.oneTBB_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "7d0ea0f4895ef2f5cb83645fa689e52cb55cf493"
uuid = "1317d2d5-d96f-522e-a858-c73665f53c3e"
version = "2021.12.0+0"
[[deps.p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
version = "17.4.0+2"
[[deps.x264_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fea590b89e6ec504593146bf8b988b2c00922b2"
uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a"
version = "2021.5.5+0"
[[deps.x265_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "ee567a171cce03570d77ad3a43e90218e38937a9"
uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76"
version = "3.5.0+0"
[[deps.xkbcommon_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Wayland_jll", "Wayland_protocols_jll", "Xorg_libxcb_jll", "Xorg_xkeyboard_config_jll"]
git-tree-sha1 = "9c304562909ab2bab0262639bd4f444d7bc2be37"
uuid = "d8fb68d0-12a3-5cfd-a85a-d49703b185fd"
version = "1.4.1+1"
"""
# ╔═╡ Cell order:
# ╟─1470df0f-40e1-45d5-a4cc-519cc3b28fb8
# ╟─7d694be0-cd3f-46ae-96a3-49d07d7cf65a
# ╟─10cb63ad-03d7-47e9-bc33-16c7786b9f6a
# ╟─1e0fa041-a592-42fb-bafd-c7272e346e46
# ╟─6fc16c34-c0c8-48ce-87b3-011a9a0f4e7c
# ╟─8a82d8c7-b781-4600-8780-0a0a003b676c
# ╟─a02f77d1-00d2-46a3-91ba-8a7f5b4bbdc9
# ╠═a1ee798d-c57b-4cc3-9e19-fb607f3e1e43
# ╟─02f0add7-9c4e-4358-8b5e-6863bae3ee75
# ╠═72604eef-5951-4934-844d-d2eb7eb0292c
# ╠═21104cd1-9fe8-45db-9c21-b733258ff155
# ╠═9d9e5139-d27e-48c8-a62e-33b2ae5b0086
# ╟─85308992-04c4-4d20-a840-6220cab54680
# ╠═eaae989a-c9d2-48ca-9ef8-fd0dbff7bcca
# ╠═98c608d9-c60e-4eb6-b611-69d2ae7054c9
# ╟─3e2579c2-39ce-4249-ad75-228f82e616da
# ╠═ddc9ce37-5f93-4851-a74f-8739b38ab092
# ╟─93fab704-a8dd-47ec-ac88-13f32be99460
# ╠═de7a4639-e3b8-4439-924d-7d801b4b3eeb
# ╟─5cb505f7-01bd-4824-8876-3e0f5a922fb7
# ╠═45c4b9dd-0b04-43ae-a715-cd120c571424
# ╠═33d648d3-e66e-488f-a18d-e538ebe9c000
# ╟─1e9541b8-5394-418d-8c27-2831951c538d
# ╠═e6e91a22-7724-46a3-88c1-315c40660290
# ╟─44500f0a-1b89-44af-b135-39ce0fec5810
# ╟─33223393-bfb9-4e9a-8ea6-a3ab6e2f22aa
# ╟─74d23661-751b-4371-bf6b-986149124e81
# ╠═c88b0627-2e04-40ab-baa2-b4c1edfda0c3
# ╟─915e4601-12cc-4b7e-b2fe-574e116f3a92
# ╟─f8e40baa-c1c5-424a-9780-718a42fd2b67
# ╠═74289e0b-1292-41eb-b13b-a4a5763c72b0
# ╟─f111e772-a340-4217-9b63-e7715f773b2c
# ╟─92ad1a99-4ad9-4b69-b6f3-84aab49db54f
# ╟─909de9f1-2aca-4bf0-ba60-d3418964ba4a
# ╟─d8ca5f66-4f55-48ab-a6c9-a0be662811d9
# ╠═41b1c7cb-5e3f-4074-a681-36dd2ef94454
# ╠═8f45871f-f72a-423f-8101-9ce93e5a885b
# ╠═57c039f7-5b24-4d63-b864-d5f808110b91
# ╟─4510022b-ad28-4fc2-836b-e4baf3c14d26
# ╠═9589416a-f9b3-4b17-a381-a4f660a5ee4c
# ╟─326ae469-43ab-4bd7-8dc4-64575f4a4d3e
# ╠═8f8f91cc-9a92-4182-8f18-098ae3e2c553
# ╟─8d93a1ed-28a9-4a77-9ac2-5564be3729a5
# ╠═4a8de267-1bf4-42c2-8dfe-5bfa21d74b7e
# ╟─6a8b98c9-e51a-4f1c-a3ea-cc452b9616b7
# ╟─dbde2da3-e3dc-4b78-8f69-554018533d35
# ╠═d42d0beb-802b-4d30-b5b8-683d76af7c10
# ╟─e50d7cc2-7155-42cf-9fef-93afeee6ffa4
# ╟─3756dd37-03e0-41e9-913e-4b4f183d8b81
# ╠═2f83bc62-5a54-472a-87a2-4ddcefd902b6
# ╟─c228eb10-d694-46aa-b952-01d824879287
# ╟─16ffc610-3c21-40f7-afca-e9da806ea626
# ╠═052f2f19-767b-4ede-b268-fce0aee133ad
# ╟─746fbf6f-ed7c-43b8-8a6f-0377cd3cf85e
# ╟─08e1ff54-d115-4da9-8ea7-5e89289723b3
# ╟─70c6b605-54fa-40a3-8bce-a88daf6a2022
# ╠═634f923a-5e09-42c8-bac0-bf165ab3d12a
# ╟─f59b5c84-2eae-4e3f-aaec-116c090d454d
# ╠═0c9493c4-322e-41a0-9ec7-2e2c54ae1373
# ╟─325c3032-4c78-4408-b86e-d9aa4cfc3187
# ╠═25e55d1c-388f-469d-99e6-2683c0508693
# ╟─74c519c9-0eef-4798-acff-b11044bb4bf1
# ╟─786c4652-583d-43e9-a101-e28c0b6f64e4
# ╟─5d688c3d-b5e3-4a3a-9d91-0896cc001000
# ╠═2e08df84-a468-4e99-a277-e2813dfeae5c
# ╟─68719de3-e11e-4909-99a3-5e05734cc8b1
# ╟─b42bf3d8-e70c-485c-89b3-158eb25d8b25
# ╟─c446ed22-3b23-487d-801e-c23742f81047
# ╠═fc3d7989-ac10-4a82-8777-eeecd354a7d0
# ╟─0a7955e7-7c1a-4396-9613-f8583195c0a8
# ╟─4912d9c9-d68d-4afd-9961-5d8315884f75
# ╟─19942162-cd4e-487c-8073-ea6b262d299d
# ╟─73575386-673b-40cc-b3cb-0b8b4f66a604
# ╟─24861a50-2319-4c63-a800-a0a03279efe2
# ╟─93735dca-c9f3-4f1a-b1bd-dfe312a0644a
# ╟─13ede3cd-99b1-4e65-8a18-9043db544728
# ╟─f7c119dd-c123-4c43-812e-d0625817d77e
# ╟─f4e66f76-76ff-4e21-b4b5-c1ecfd846329
# ╟─b163115b-393d-4589-842d-03859f05be9a
# ╟─ac0afa6c-b6ec-4577-aeb6-10d1ec63fa41
# ╟─5e9cb956-d5ea-4462-a649-b133a77929b0
# ╟─9dc93971-85b6-463b-bd17-43068d57de94
# ╟─476a1ed7-c865-4878-a948-da73d3c81070
# ╟─0b6b4f6d-be09-42f3-bc2c-5f17a8a9ab0e
# ╟─a1aca180-d561-42a3-8d12-88f5a3721aae
# ╟─3bc2b859-d7b1-4b79-88df-8fb517a6929d
# ╟─a501d998-6fd6-496f-9718-3340c42b08a6
# ╟─83a2122d-56da-4a80-8c10-615a8f76c4c1
# ╟─e342be7e-0806-4f72-9e32-6d74ed3ed3f2
# ╟─eaf37128-0377-42b6-aa81-58f0a815276b
# ╟─c030d85e-af69-49c9-a7c8-e490d4831324
# ╟─51c200c9-0de3-4e50-8884-49fe06158560
# ╟─0dadd112-3132-4491-9f02-f43cf00aa1f9
# ╟─5c2308d9-6d04-4b38-af3b-6241da3b6871
# ╟─bf6bf640-54bc-44ef-bd4d-b98e934d416e
# ╟─639889b3-b9f2-4a3c-999d-332851768fd7
# ╟─007d6d95-ad85-4804-9651-9ac3703d3b40
# ╟─ed1887df-5079-4367-ab04-9d02a1d6f366
# ╟─0b0c4650-2ce1-4879-9acd-81c16d06700e
# ╟─b864631b-a9f3-40d4-a6a8-0b57a37a476d
# ╟─0fb90681-5d04-471a-a7a8-4d0f3ded7bcf
# ╟─95e14ea5-d82d-4044-8c68-090d74d95a61
# ╟─2fa1821b-aaec-4de4-bfb4-89560790dc39
# ╟─cbae6aa4-1338-428c-86aa-61d3304e33ed
# ╟─9b52a65a-f20c-4387-aaca-5292a92fb639
# ╟─8c56acd6-94d3-4cbc-bc29-d249740268a0
# ╟─845a95c4-9a35-44ae-854c-57432200da1a
# ╟─5a399a9b-32d9-4f93-a41f-8f16a4b102dc
# ╟─fd1cebf1-5ccc-4bc5-99d4-1eaa30e9762e
# ╟─1cd976fb-db40-4ebe-b40d-b996e16fc213
# ╟─93771b35-4edd-49e3-bed1-a3ccdb7975e6
# ╟─e79badcd-0396-4a44-9318-8c6b0a94c5c8
# ╟─2a5157c5-f5a2-4330-b2a3-0c1ec0b7adff
# ╟─4454c8d2-68ed-44b4-adfa-432297cdc957
# ╟─d240c95c-5aba-4b47-ab8d-2f9c0eb854cd
# ╟─06937575-9ab1-41cd-960c-7eef3e8cae7f
# ╟─356b6029-de66-418f-8273-6db6464f9fbf
# ╟─5805a216-2536-44ac-a702-d92e86d435a4
# ╟─68d57a23-68c3-418c-9c6f-32bdf8cafceb
# ╟─53e971d8-bf43-41cc-ac2b-20dceaa78667
# ╟─e8b8c63b-2ca4-4e6a-a801-852d6149283e
# ╟─c0ac7902-0716-4f18-9447-d18ce9081ba5
# ╟─84215a73-1ab0-416d-a9db-6b29cd4f5d2a
# ╟─f9d35cfd-4ae5-4dcd-94d9-02aefc99bdfb
# ╟─bc09bd09-2874-431a-bbbb-3d53c632be39
# ╠═f741b213-a20d-423a-a382-75cae1123f2c
# ╟─f02b9118-3fb5-4846-8c08-7e9bbca9d208
# ╠═91473bef-bc23-43ed-9989-34e62166d455
# ╟─404ca10f-d944-4a9f-addb-05efebb4f159
# ╟─d347d51b-743f-4fec-bed7-6cca2b17bacb
# ╟─d60d2561-51a4-4f8a-9819-898d70596e0c
# ╟─c97f2dea-cb18-409d-9ae8-1d03647a6bb3
# ╟─366abd1a-bcb5-480d-b1fb-7c76930dc8fc
# ╟─7e2ffd6f-19b0-435d-8e3c-df24a591bc55
# ╠═caa5e04a-2375-4c56-8072-52c140adcbbb
# ╟─69657be6-6315-4655-81e2-8edef7f21e49
# ╟─23ad65c8-5723-4858-9abe-750c3b65c28a
# ╟─abc57328-4de8-42d8-9e79-dd4020769dd9
# ╟─e8bae97d-9f90-47d2-9263-dc8fc065c3d0
# ╟─2dce68a7-27ec-4ffc-afba-87af4f1cb630
# ╟─c3f5704b-8e98-4c46-be7a-18ab4f139458
# ╟─1a608bc8-7264-4dd3-a4e7-0e39128a8375
# ╟─ff106912-d18c-487f-bcdd-7b7af2112cab
# ╟─51eeb67f-a984-486a-ab8a-a2541966fa72
# ╟─27458e32-5891-4afc-af8e-7afdf7e81cc6
# ╟─737e2c50-0858-4205-bef3-f541e33b85c3
# ╟─5dd491a4-a8cd-4baf-96f7-7a0b850bb26c
# ╟─4f27b6c0-21da-4e26-aaad-ff453c8af3da
# ╟─1195a30c-3b48-4bd2-8a3a-f4f74f3cd864
# ╟─b0ce7b92-93e0-4715-8324-3bf4ff42a0b3
# ╟─919419fe-35de-44bb-89e4-8f8688bee962
# ╟─ed25a535-ca2f-4cd2-b0af-188e9699f1c3
# ╟─2918daf2-6499-4019-a04b-8c3419ee1ab7
# ╟─d798a5d0-3017-4eab-9cdf-ee85d63dfc49
# ╟─048e39c3-a3d9-4e6b-b050-1fd5a919e4ae
# ╟─b489f97d-ee90-48c0-af06-93b66a1f6d2e
# ╟─4dad3e55-5bfd-4315-bb5a-2680e5cbd11c
# ╟─ea0ede8d-7c2c-4e72-9c96-3260dc8d817d
# ╟─35f52dbc-0c0b-495e-8fd4-6edbc6fa811e
# ╟─51aed933-2067-4ea8-9c2f-9d070692ecfc
# ╟─8d9dc86e-f38b-41b1-80c6-b2ab6f488a3a
# ╟─74ef5a39-1dd7-404a-8baf-caa1021d3054
# ╟─347d209b-9d41-48b0-bee6-0d159caacfa9
# ╟─05281c4f-dba8-4070-bce3-dc2f1319902e
# ╟─590d7f24-c6b6-4524-b3db-0c93d9963b74
# ╟─67cfe7c5-8e62-4bf0-996b-19597d5ad5ef
# ╟─e6dc8aab-82c1-4dc9-a1c8-4fe9c137a146
# ╟─dfee214e-bd13-4d4f-af8e-20e0c4e0de9b
# ╟─88884204-79e4-4412-b861-ebeb5f6f7396
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 1103 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
module JLD2Ext
using FMIFlux, JLD2
using FMIFlux.Flux
function FMIFlux.saveParameters(nfmu::NeuralFMU, path::String; keyword = "parameters")
params = Flux.params(nfmu)
JLD2.save(path, Dict(keyword => params[1]))
end
function FMIFlux.loadParameters(
nfmu::NeuralFMU,
path::String;
flux_model = nothing,
keyword = "parameters",
)
paramsLoad = JLD2.load(path, keyword)
nfmu_params = Flux.params(nfmu)
flux_model_params = nothing
if flux_model != nothing
flux_model_params = Flux.params(flux_model)
end
numParams = length(nfmu_params[1])
l = 1
p = 1
for i = 1:numParams
nfmu_params[1][i] = paramsLoad[i]
if flux_model != nothing
flux_model_params[l][p] = paramsLoad[i]
p += 1
if p > length(flux_model_params[l])
l += 1
p = 1
end
end
end
return nothing
end
end # JLD2Ext
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 1679 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
module FMIFlux
import FMISensitivity
import FMISensitivity.ForwardDiff
import FMISensitivity.Zygote
import FMISensitivity.ReverseDiff
import FMISensitivity.FiniteDiff
@debug "Debugging messages enabled for FMIFlux ..."
if VERSION < v"1.7.0"
@warn "Training under Julia 1.6 is very slow, please consider using Julia 1.7 or newer." maxlog =
1
end
import FMIImport.FMIBase: hasCurrentInstance, getCurrentInstance, unsense
import FMISensitivity.ChainRulesCore: ignore_derivatives
import FMIImport
import Flux
using FMIImport
include("optimiser.jl")
include("hotfixes.jl")
include("convert.jl")
include("flux_overload.jl")
include("neural.jl")
include("misc.jl")
include("layers.jl")
include("deprecated.jl")
include("batch.jl")
include("losses.jl")
include("scheduler.jl")
include("compatibility_check.jl")
# optional extensions
using FMIImport.FMIBase.Requires
using FMIImport.FMIBase.PackageExtensionCompat
function __init__()
@require_extensions
end
# JLD2.jl
function saveParameters end
function loadParameters end
# FMI_neural.jl
export ME_NeuralFMU, CS_NeuralFMU, NeuralFMU
# misc.jl
export mse_interpolate, transferParams!, transferFlatParams!, lin_interp
# scheduler.jl
export WorstElementScheduler,
WorstGrowScheduler, RandomScheduler, SequentialScheduler, LossAccumulationScheduler
# batch.jl
export batchDataSolution, batchDataEvaluation
# layers.jl
# >>> layers are exported inside the file itself
# deprecated.jl
# >>> deprecated functions are exported inside the file itself
end # module
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 18243 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
import FMIImport.FMIBase: FMUSnapshot
import FMIImport: fmi2Real, fmi2FMUstate, fmi2EventInfo, fmi2ComponentState
using FMIImport.FMIBase.DiffEqCallbacks: FunctionCallingCallback
abstract type FMU2BatchElement end
mutable struct FMULoss{T}
loss::T
step::Integer
time::Real
function FMULoss{T}(loss::T, step::Integer = 0, time::Real = time()) where {T}
inst = new{T}(loss, step, time)
return inst
end
function FMULoss(loss, step::Integer = 0, time::Real = time())
loss = unsense(loss)
T = typeof(loss)
inst = new{T}(loss, step, time)
return inst
end
end
function nominalLoss(l::FMULoss{T}) where {T<:AbstractArray}
return unsense(sum(l.loss))
end
function nominalLoss(l::FMULoss{T}) where {T<:Real}
return unsense(l.loss)
end
function nominalLoss(::Nothing)
return Inf
end
function nominalLoss(b::FMU2BatchElement)
return nominalLoss(b.loss)
end
mutable struct FMU2SolutionBatchElement{D} <: FMU2BatchElement
snapshot::Union{FMUSnapshot,Nothing}
xStart::Union{Vector{fmi2Real},Nothing}
xdStart::Union{Vector{D},Nothing}
tStart::fmi2Real
tStop::fmi2Real
# initialState::Union{fmi2FMUstate, Nothing}
# initialComponentState::fmi2ComponentState
# initialEventInfo::Union{fmi2EventInfo, Nothing}
loss::FMULoss # the current loss
losses::Array{<:FMULoss} # logged losses (if used)
step::Integer
saveat::Union{AbstractVector{<:Real},Nothing}
targets::Union{AbstractArray,Nothing}
indicesModel::Any
solution::FMUSolution
scalarLoss::Bool
# canGetSetState::Bool
function FMU2SolutionBatchElement{D}(; scalarLoss::Bool = true) where {D}
inst = new()
inst.snapshot = nothing
inst.xStart = nothing
inst.xdStart = nothing
inst.tStart = -Inf
inst.tStop = Inf
# inst.initialState = nothing
# inst.initialEventInfo = nothing
inst.loss = FMULoss(Inf)
inst.losses = Array{FMULoss,1}()
inst.step = 0
inst.saveat = nothing
inst.targets = nothing
inst.indicesModel = nothing
inst.scalarLoss = scalarLoss
# inst.canGetSetState = canGetSetState
return inst
end
end
mutable struct FMU2EvaluationBatchElement <: FMU2BatchElement
tStart::fmi2Real
tStop::fmi2Real
loss::FMULoss
losses::Array{<:FMULoss}
step::Integer
saveat::Union{AbstractVector{<:Real},Nothing}
targets::Union{AbstractArray,Nothing}
features::Union{AbstractArray,Nothing}
indicesModel::Any
result::Any
scalarLoss::Bool
function FMU2EvaluationBatchElement(; scalarLoss::Bool = true)
inst = new()
inst.tStart = -Inf
inst.tStop = Inf
inst.loss = FMULoss(Inf)
inst.losses = Array{FMULoss,1}()
inst.step = 0
inst.saveat = nothing
inst.features = nothing
inst.targets = nothing
inst.indicesModel = nothing
inst.result = nothing
inst.scalarLoss = scalarLoss
return inst
end
end
function pasteFMUState!(fmu::FMU2, batchElement::FMU2SolutionBatchElement)
c = getCurrentInstance(fmu)
FMIBase.apply!(c, batchElement.snapshot)
@info "Pasting snapshot @$(batchElement.snapshot.t)"
return nothing
end
function copyFMUState!(fmu::FMU2, batchElement::FMU2SolutionBatchElement)
c = getCurrentInstance(fmu)
if isnothing(batchElement.snapshot)
batchElement.snapshot = FMIBase.snapshot!(c)
#batchElement.snapshot.t = batchElement.tStart
@debug "New snapshot @$(batchElement.snapshot.t)"
else
#tBefore = batchElement.snapshot.t
FMIBase.update!(c, batchElement.snapshot)
#batchElement.snapshot.t = batchElement.tStart
#tAfter = batchElement.snapshot.t
# [Note] for discontinuous batches (time offsets inside batch),
# it might be necessary to correct the new snapshot time to fit the old one.
# if tBefore != tAfter
# batchElement.snapshot.t = max(tBefore, tAfter)
# logInfo(fmu, "Corrected snapshot time from $(tAfter) to $(tBefore)")
# end
@debug "Updated snapshot @$(batchElement.snapshot.t)"
end
return nothing
end
function run!(
neuralFMU::ME_NeuralFMU,
batchElement::FMU2SolutionBatchElement;
nextBatchElement = nothing,
kwargs...,
)
neuralFMU.customCallbacksAfter = []
neuralFMU.customCallbacksBefore = []
# STOP CALLBACK
if !isnothing(nextBatchElement)
stopcb = FunctionCallingCallback(
(u, t, integrator) -> copyFMUState!(neuralFMU.fmu, nextBatchElement);
funcat = [batchElement.tStop],
)
push!(neuralFMU.customCallbacksAfter, stopcb)
end
writeSnapshot = nothing
readSnapshot = nothing
# on first run of the element, there is no snapshot
if isnothing(batchElement.snapshot)
c = getCurrentInstance(neuralFMU.fmu)
batchElement.snapshot = snapshot!(c)
writeSnapshot = batchElement.snapshot # needs to be updated, therefore write
else
readSnapshot = batchElement.snapshot
end
@debug "Running $(batchElement.tStart) with snapshot: $(!isnothing(batchElement.snapshot))..."
batchElement.solution = neuralFMU(
batchElement.xStart,
(batchElement.tStart, batchElement.tStop);
readSnapshot = readSnapshot,
writeSnapshot = writeSnapshot,
saveat = batchElement.saveat,
kwargs...,
)
# @assert batchElement.solution.states.t == batchElement.saveat "Batch element simulation failed, missmatch between `states.t` and `saveat`."
neuralFMU.customCallbacksBefore = []
neuralFMU.customCallbacksAfter = []
batchElement.step += 1
return batchElement.solution
end
function run!(model, batchElement::FMU2EvaluationBatchElement, p = nothing)
if isnothing(p) # implicite parameter model
batchElement.result =
collect(model(f)[batchElement.indicesModel] for f in batchElement.features)
else # explicite parameter model
batchElement.result =
collect(model(p)(f)[batchElement.indicesModel] for f in batchElement.features)
end
end
function plot(batchElement::FMU2SolutionBatchElement; targets::Bool = true, plotkwargs...)
fig = Plots.plot(; xlabel = "t [s]", plotkwargs...) # , title="loss[$(batchElement.step)] = $(nominalLoss(batchElement.losses[end]))")
for i = 1:length(batchElement.indicesModel)
if !isnothing(batchElement.solution)
@assert batchElement.solution.states.t == batchElement.saveat "Batch element plotting failed, missmatch between `states.t` and `saveat`."
Plots.plot!(
fig,
batchElement.solution.states.t,
collect(
unsense(u[batchElement.indicesModel[i]]) for
u in batchElement.solution.states.u
),
label = "Simulation #$(i)",
)
end
if targets
Plots.plot!(
fig,
batchElement.saveat,
collect(d[i] for d in batchElement.targets),
label = "Targets #$(i)",
)
end
end
return fig
end
function plot(
batchElement::FMU2BatchElement;
targets::Bool = true,
features::Bool = true,
plotkwargs...,
)
fig = Plots.plot(; xlabel = "t [s]", plotkwargs...) # , title="loss[$(batchElement.step)] = $(nominalLoss(batchElement.losses[end]))")
if batchElement.features != nothing && features
for i = 1:length(batchElement.features[1])
Plots.plot!(
fig,
batchElement.saveat,
collect(d[i] for d in batchElement.features),
style = :dash,
label = "Features #$(i)",
)
end
end
for i = 1:length(batchElement.indicesModel)
if batchElement.result != nothing
Plots.plot!(
fig,
batchElement.saveat,
collect(ForwardDiff.value(u[i]) for u in batchElement.result),
label = "Evaluation #$(i)",
)
end
if targets
Plots.plot!(
fig,
batchElement.saveat,
collect(d[i] for d in batchElement.targets),
label = "Targets #$(i)",
)
end
end
return fig
end
function plot(
batch::AbstractArray{<:FMU2BatchElement};
plot_mean::Bool = true,
plot_shadow::Bool = true,
plotkwargs...,
)
num = length(batch)
xs = 1:num
ys = collect((nominalLoss(b) != Inf ? nominalLoss(b) : 0.0) for b in batch)
fig = Plots.plot(; xlabel = "Batch ID", ylabel = "Loss", plotkwargs...)
if plot_shadow
ys_shadow = collect(
(length(b.losses) > 1 ? nominalLoss(b.losses[end-1]) : 0.0) for b in batch
)
Plots.bar!(
fig,
xs,
ys_shadow;
label = "Previous loss",
color = :green,
bar_width = 1.0,
)
end
Plots.bar!(fig, xs, ys; label = "Current loss", color = :blue, bar_width = 0.5)
if plot_mean
avgsum = mean(ys)
Plots.plot!(fig, [1, num], [avgsum, avgsum]; label = "mean")
end
return fig
end
function plotLoss(batchElement::FMU2BatchElement; xaxis::Symbol = :steps)
@assert length(batchElement.losses) > 0 "Can't plot, no losses!"
ts = nothing
tlabel = ""
if xaxis == :time
ts = collect(l.time for l in batchElement.losses)
tlabel = "t [s]"
elseif xaxis == :steps
ts = collect(l.step for l in batchElement.losses)
tlabel = "steps [/]"
else
@assert false "unsupported keyword for `xaxis`."
end
ls = collect(l.loss for l in batchElement.losses)
fig = Plots.plot(ts, ls, xlabel = tlabel, ylabel = "Loss")
return fig
end
function loss!(batchElement::FMU2SolutionBatchElement, lossFct; logLoss::Bool = false)
loss = 0.0 # will be incremented
if hasmethod(lossFct, Tuple{FMUSolution})
loss = lossFct(batchElement.solution)
elseif hasmethod(lossFct, Tuple{FMUSolution,Union{}})
loss = lossFct(batchElement.solution, batchElement.targets)
else # hasmethod(lossFct, Tuple{Union{}, Union{}})
if batchElement.solution.success
if batchElement.scalarLoss
for i = 1:length(batchElement.indicesModel)
dataTarget = collect(d[i] for d in batchElement.targets)
modelOutput = collect(
u[batchElement.indicesModel[i]] for
u in batchElement.solution.states.u
)
loss += lossFct(modelOutput, dataTarget)
end
else
dataTarget = batchElement.targets
modelOutput = collect(
u[batchElement.indicesModel] for u in batchElement.solution.states.u
)
loss = lossFct(modelOutput, dataTarget)
end
else
@warn "Can't compute loss for batch element, because solution is invalid (`success=false`) for batch element\n$(batchElement)."
end
end
batchElement.loss.step = batchElement.step
batchElement.loss.time = time()
batchElement.loss.loss = unsense(loss)
ignore_derivatives() do
if logLoss
push!(batchElement.losses, deepcopy(batchElement.loss))
end
end
return loss
end
function loss!(batchElement::FMU2EvaluationBatchElement, lossFct; logLoss::Bool = true)
loss = 0.0 # will be incremented
if batchElement.scalarLoss
for i = 1:length(batchElement.indicesModel)
dataTarget = collect(d[i] for d in batchElement.targets)
modelOutput = collect(u[i] for u in batchElement.result)
loss += lossFct(modelOutput, dataTarget)
end
else
dataTarget = batchElement.targets
modelOutput = batchElement.result
loss = lossFct(modelOutput, dataTarget)
end
batchElement.loss.step = batchElement.step
batchElement.loss.time = time()
batchElement.loss.loss = unsense(loss)
ignore_derivatives() do
if logLoss
push!(batchElement.losses, deepcopy(batchElement.loss))
end
end
return loss
end
function _batchDataSolution!(
batch::AbstractArray{<:FMIFlux.FMU2SolutionBatchElement},
neuralFMU::NeuralFMU,
x0_fun,
train_t::AbstractArray{<:AbstractArray{<:Real}},
targets::AbstractArray;
kwargs...,
)
len = length(train_t)
for i = 1:len
_batchDataSolution!(batch, neuralFMU, x0_fun, train_t[i], targets[i]; kwargs...)
end
return nothing
end
function _batchDataSolution!(
batch::AbstractArray{<:FMIFlux.FMU2SolutionBatchElement},
neuralFMU::NeuralFMU,
x0_fun,
train_t::AbstractArray{<:Real},
targets::AbstractArray;
batchDuration::Real = (train_t[end] - train_t[1]),
indicesModel = 1:length(targets[1]),
plot::Bool = false,
scalarLoss::Bool = true,
)
@assert length(train_t) == length(targets) "Timepoints in `train_t` ($(length(train_t))) must match number of `targets` ($(length(targets)))"
canGetSetState = canGetSetFMUState(neuralFMU.fmu)
if !canGetSetState
logWarning(
neuralFMU.fmu,
"This FMU can't set/get a FMU state. This is suboptimal for batched training.",
)
end
# c, _ = prepareSolveFMU(neuralFMU.fmu, nothing, neuralFMU.fmu.type, nothing, nothing, nothing, nothing, nothing, nothing, neuralFMU.tspan[1], neuralFMU.tspan[end], nothing; handleEvents=FMIFlux.handleEvents)
# indicesData = 1:1
tStart = train_t[1]
# iStart = timeToIndex(train_t, tStart)
# iStop = timeToIndex(train_t, tStart + batchDuration)
# startElement = FMIFlux.FMU2SolutionBatchElement(;scalarLoss=scalarLoss)
# startElement.tStart = train_t[iStart]
# startElement.tStop = train_t[iStop]
# startElement.xStart = x0_fun(tStart)
# startElement.saveat = train_t[iStart:iStop]
# startElement.targets = targets[iStart:iStop]
# startElement.indicesModel = indicesModel
# push!(batch, startElement)
numElements = floor(Integer, (train_t[end] - train_t[1]) / batchDuration)
D = eltype(neuralFMU.fmu.modelDescription.discreteStateValueReferences)
for i = 1:numElements
element = FMIFlux.FMU2SolutionBatchElement{D}(; scalarLoss = scalarLoss)
iStart = FMIFlux.timeToIndex(train_t, tStart + (i - 1) * batchDuration)
iStop = FMIFlux.timeToIndex(train_t, tStart + i * batchDuration)
element.tStart = train_t[iStart]
element.tStop = train_t[iStop]
element.xStart = x0_fun(element.tStart)
element.saveat = train_t[iStart:iStop]
element.targets = targets[iStart:iStop]
element.indicesModel = indicesModel
push!(batch, element)
end
return nothing
end
function batchDataSolution(
neuralFMU::NeuralFMU,
x0_fun,
train_t,
targets;
batchDuration::Real = (train_t[end] - train_t[1]),
indicesModel = 1:length(targets[1]),
plot::Bool = false,
scalarLoss::Bool = true,
restartAtJump::Bool = true,
solverKwargs...,
)
batch = Array{FMIFlux.FMU2SolutionBatchElement,1}()
_batchDataSolution!(
batch,
neuralFMU,
x0_fun,
train_t,
targets;
batchDuration = batchDuration,
indicesModel = indicesModel,
plot = plot,
scalarLoss = scalarLoss,
)
numElements = length(batch)
for i = 1:numElements
nextBatchElement = nothing
if i < numElements && batch[i].tStop == batch[i+1].tStart
nextBatchElement = batch[i+1]
end
FMIFlux.run!(
neuralFMU,
batch[i];
nextBatchElement = nextBatchElement,
solverKwargs...,
)
if plot
fig = FMIFlux.plot(batch[i])
display(fig)
end
end
return batch
end
function batchDataEvaluation(
train_t::AbstractArray{<:Real},
targets::AbstractArray,
features::Union{AbstractArray,Nothing} = nothing;
batchDuration::Real = (train_t[end] - train_t[1]),
indicesModel = 1:length(targets[1]),
plot::Bool = false,
round_digits = 3,
scalarLoss::Bool = true,
)
batch = Array{FMIFlux.FMU2EvaluationBatchElement,1}()
indicesData = 1:1
tStart = train_t[1]
iStart = timeToIndex(train_t, tStart)
iStop = timeToIndex(train_t, tStart + batchDuration)
startElement = FMIFlux.FMU2EvaluationBatchElement(; scalarLoss = scalarLoss)
startElement.tStart = train_t[iStart]
startElement.tStop = train_t[iStop]
startElement.saveat = train_t[iStart:iStop]
startElement.targets = targets[iStart:iStop]
if features != nothing
startElement.features = features[iStart:iStop]
else
startElement.features = startElement.targets
end
startElement.indicesModel = indicesModel
push!(batch, startElement)
for i = 2:floor(Integer, (train_t[end] - train_t[1]) / batchDuration)
push!(batch, FMIFlux.FMU2EvaluationBatchElement(; scalarLoss = scalarLoss))
iStart = timeToIndex(train_t, tStart + (i - 1) * batchDuration)
iStop = timeToIndex(train_t, tStart + i * batchDuration)
batch[i].tStart = train_t[iStart]
batch[i].tStop = train_t[iStop]
batch[i].saveat = train_t[iStart:iStop]
batch[i].targets = targets[iStart:iStop]
if features != nothing
batch[i].features = features[iStart:iStop]
else
batch[i].features = batch[i].targets
end
batch[i].indicesModel = indicesModel
if plot
fig = FMIFlux.plot(batch[i-1])
display(fig)
end
end
return batch
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 9292 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
# checks gradient determination for all available sensitivity configurations, see:
# https://docs.sciml.ai/SciMLSensitivity/stable/manual/differential_equation_sensitivities/
using FMISensitivity.SciMLSensitivity
function checkSensalgs!(
loss,
neuralFMU::Union{ME_NeuralFMU,CS_NeuralFMU};
gradients = (:ReverseDiff, :Zygote, :ForwardDiff), # :FiniteDiff is slow ...
max_msg_len = 192,
chunk_size = DEFAULT_CHUNK_SIZE,
OtD_autojacvecs = (
false,
true,
TrackerVJP(),
ZygoteVJP(),
ReverseDiffVJP(false),
ReverseDiffVJP(true),
), # EnzymeVJP() deadlocks in the current release xD
OtD_sensealgs = (
BacksolveAdjoint,
InterpolatingAdjoint,
QuadratureAdjoint,
GaussAdjoint,
),
OtD_checkpointings = (true, false),
DtO_sensealgs = (ReverseDiffAdjoint, ForwardDiffSensitivity, TrackerAdjoint), # TrackerAdjoint, ZygoteAdjoint freeze the REPL
multiObjective::Bool = false,
bestof::Int = 2,
timeout_seconds::Real = 60.0,
gradient_gt::Symbol = :FiniteDiff,
kwargs...,
)
params = Flux.params(neuralFMU)
initial_sensalg = neuralFMU.fmu.executionConfig.sensealg
best_timing = Inf
best_gradient = nothing
best_sensealg = nothing
printstyled("Mode: Ground-Truth ($(gradient_gt)))\n")
grads, _ = runGrads(loss, params, gradient_gt, chunk_size, multiObjective)
# jac = zeros(length(params[1]))
# FiniteDiff.finite_difference_gradient!(jac, loss, params[1])
# step = 1e-6
# for i in 1:length(params[1])
# params[1][i] -= step/2.0
# neg = loss(params[1])
# params[1][i] += step
# pos = loss(params[1])
# params[1][i] -= step/2.0
# jac[i] = (pos-neg)/step
# end
# @info "Jac: $(jac)"
# grads = [jac]
grad_gt_val = collect(sum(abs.(grad)) for grad in grads)[1]
printstyled("\tGround Truth: $(grad_gt_val)\n", color = :green)
@assert grad_gt_val > 0.0 "Loss gradient is zero, grad_gt_val == 0.0"
printstyled("Mode: Optimize-then-Discretize\n")
for gradient ∈ gradients
printstyled("\tGradient: $(gradient)\n")
for sensealg ∈ OtD_sensealgs
printstyled("\t\tSensealg: $(sensealg)\n")
for checkpointing ∈ OtD_checkpointings
printstyled("\t\t\tCheckpointing: $(checkpointing)\n")
if sensealg ∈ (QuadratureAdjoint, GaussAdjoint) && checkpointing
printstyled(
"\t\t\t\t$(sensealg) doesn't implement checkpointing, skipping ...\n",
)
continue
end
for autojacvec ∈ OtD_autojacvecs
printstyled("\t\t\t\tAutojacvec: $(autojacvec)\n")
if sensealg ∈ (BacksolveAdjoint, InterpolatingAdjoint)
neuralFMU.fmu.executionConfig.sensealg = sensealg(;
autojacvec = autojacvec,
chunk_size = chunk_size,
checkpointing = checkpointing,
)
else
neuralFMU.fmu.executionConfig.sensealg =
sensealg(; autojacvec = autojacvec, chunk_size = chunk_size)
end
call =
() -> _tryrun(
loss,
params,
gradient,
chunk_size,
5,
max_msg_len,
multiObjective;
timeout_seconds = timeout_seconds,
grad_gt_val = grad_gt_val,
)
for i = 1:bestof
timing, valid = call()
if valid && timing < best_timing
best_timing = timing
best_gradient = gradient
best_sensealg = neuralFMU.fmu.executionConfig.sensealg
end
end
end
end
end
end
printstyled("Mode: Discretize-then-Optimize\n")
for gradient ∈ gradients
printstyled("\tGradient: $(gradient)\n")
for sensealg ∈ DtO_sensealgs
printstyled("\t\tSensealg: $(sensealg)\n")
if sensealg == ForwardDiffSensitivity
neuralFMU.fmu.executionConfig.sensealg =
sensealg(; chunk_size = chunk_size, convert_tspan = true)
else
neuralFMU.fmu.executionConfig.sensealg = sensealg()
end
call =
() -> _tryrun(
loss,
params,
gradient,
chunk_size,
3,
max_msg_len,
multiObjective;
timeout_seconds = timeout_seconds,
grad_gt_val = grad_gt_val,
)
for i = 1:bestof
timing, valid = call()
if valid && timing < best_timing
best_timing = timing
best_gradient = gradient
best_sensealg = neuralFMU.fmu.executionConfig.sensealg
end
end
end
end
neuralFMU.fmu.executionConfig.sensealg = initial_sensalg
printstyled(
"------------------------------\nBest time: $(best_timing)\nBest gradient: $(best_gradient)\nBest sensealg: $(best_sensealg)\n",
color = :blue,
)
return best_timing, best_gradient, best_sensealg
end
# Thanks to:
# https://discourse.julialang.org/t/help-writing-a-timeout-macro/16591/11
function timeout(f, arg, seconds, fail)
tsk = @task f(arg...)
schedule(tsk)
Timer(seconds) do timer
istaskdone(tsk) || Base.throwto(tsk, InterruptException())
end
try
fetch(tsk)
catch _
fail
end
end
function runGrads(loss, params, gradient, chunk_size, multiObjective)
tstart = time()
grads = nothing
if multiObjective
dim = loss(params[1])
grads = zeros(Float64, length(params[1]), length(dim))
else
grads = zeros(Float64, length(params[1]))
end
computeGradient!(grads, loss, params[1], gradient, chunk_size, multiObjective)
timing = time() - tstart
if length(grads[1]) == 1
grads = [grads]
end
return grads, timing
end
function _tryrun(
loss,
params,
gradient,
chunk_size,
ts,
max_msg_len,
multiObjective::Bool = false;
print_stdout::Bool = true,
print_stderr::Bool = true,
timeout_seconds::Real = 60.0,
grad_gt_val::Real = 0.0,
reltol = 1e-2,
)
spacing = ""
for t in ts
spacing *= "\t"
end
message = ""
color = :black
timing = Inf
valid = false
original_stdout = stdout
original_stderr = stderr
(rd_stdout, wr_stdout) = redirect_stdout()
(rd_stderr, wr_stderr) = redirect_stderr()
try
#grads, timing = timeout(runGrads, (loss, params, gradient, chunk_size, multiObjective), timeout_seconds, ([Inf], -1.0))
grads, timing = runGrads(loss, params, gradient, chunk_size, multiObjective)
if timing == -1.0
message = spacing * "TIMEOUT\n"
color = :red
else
val = collect(sum(abs.(grad)) for grad in grads)[1]
tol = abs(1.0 - val / grad_gt_val)
if tol > reltol
message =
spacing *
"WRONG $(round(tol*100;digits=2))% > $(round(reltol*100;digits=2))% | $(round(timing; digits=3))s | GradAbsSum: $(round.(val; digits=6))\n"
color = :yellow
valid = false
else
message =
spacing *
"SUCCESS $(round(tol*100;digits=2))% <= $(round(reltol*100;digits=2))% | $(round(timing; digits=3))s | GradAbsSum: $(round.(val; digits=6))\n"
color = :green
valid = true
end
end
catch e
msg = "$(e)"
msg = length(msg) > max_msg_len ? first(msg, max_msg_len) * "..." : msg
message = spacing * "$(msg)\n"
color = :red
end
redirect_stdout(original_stdout)
redirect_stderr(original_stderr)
close(wr_stdout)
close(wr_stderr)
if print_stdout
msg = read(rd_stdout, String)
if length(msg) > 0
msg = length(msg) > max_msg_len ? first(msg, max_msg_len) * "..." : msg
printstyled(spacing * "STDOUT: $(msg)\n", color = :yellow)
end
end
if print_stderr
msg = read(rd_stderr, String)
if length(msg) > 0
msg = length(msg) > max_msg_len ? first(msg, max_msg_len) * "..." : msg
printstyled(spacing * "STDERR: $(msg)\n", color = :yellow)
end
end
printstyled(message, color = color)
return timing, valid
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 477 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
function is64(model::Flux.Chain)
params = Flux.params(model)
for i = 1:length(params)
for j = 1:length(params[i])
if !isa(params[i][j], Float64)
return false
end
end
end
return true
end
function convert64(model::Flux.Chain)
Flux.fmap(Flux.f64, model)
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 4832 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using FMIImport.FMIBase: FMI2Struct
"""
DEPRECATED:
Performs something similar to `fmiDoStep` for ME-FMUs (note, that fmiDoStep is for CS-FMUs only).
Event handling (state- and time-events) is supported. If you don't want events to be handled, you can disable event-handling for the NeuralFMU `nfmu` with the attribute `eventHandling = false`.
Optional, additional FMU-values can be set via keyword arguments `setValueReferences` and `setValues`.
Optional, additional FMU-values can be retrieved by keyword argument `getValueReferences`.
Function takes the current system state array ("x") and returns an array with state derivatives ("x dot") and optionally the FMU-values for `getValueReferences`.
Setting the FMU time via argument `t` is optional, if not set, the current time of the ODE solver around the NeuralFMU is used.
"""
function fmi2EvaluateME(
fmu::FMU2,
x::Array{<:Real},
t,#::Real,
setValueReferences::Union{Array{fmi2ValueReference},Nothing} = nothing,
setValues::Union{Array{<:Real},Nothing} = nothing,
getValueReferences::Union{Array{fmi2ValueReference},Nothing} = nothing,
)
y = nothing
y_refs = getValueReferences
u = setValues
u_refs = setValueReferences
if y_refs != nothing
y = zeros(length(y_refs))
end
dx = zeros(length(x))
c = fmu.components[end]
y, dx = c(dx = dx, y = y, y_refs = y_refs, x = x, u = u, u_refs = u_refs, t = t)
return [(dx == nothing ? [] : dx)..., (y == nothing ? [] : y)...]
end
export fmi2EvaluateME
"""
DEPRECATED:
Wrapper. Call ```fmi2EvaluateME``` for more information.
"""
function fmiEvaluateME(
str::FMI2Struct,
x::Array{<:Real},
t::Real = (typeof(str) == FMU2 ? str.components[end].t : str.t),
setValueReferences::Union{Array{fmi2ValueReference},Nothing} = nothing,
setValues::Union{Array{<:Real},Nothing} = nothing,
getValueReferences::Union{Array{fmi2ValueReference},Nothing} = nothing,
)
fmi2EvaluateME(str, x, t, setValueReferences, setValues, getValueReferences)
end
export fmiEvaluateME
"""
DEPRECATED:
Wrapper. Call ```fmi2DoStepCS``` for more information.
"""
function fmiDoStepCS(
str::FMI2Struct,
dt::Real,
setValueReferences::Array{fmi2ValueReference} = zeros(fmi2ValueReference, 0),
setValues::Array{<:Real} = zeros(Real, 0),
getValueReferences::Array{fmi2ValueReference} = zeros(fmi2ValueReference, 0),
)
fmi2DoStepCS(str, dt, setValueReferences, setValues, getValueReferences)
end
export fmiDoStepCS
"""
DEPRECATED:
Wrapper. Call ```fmi2InputDoStepCSOutput``` for more information.
"""
function fmiInputDoStepCSOutput(str::FMI2Struct, dt::Real, u::Array{<:Real})
fmi2InputDoStepCSOutput(str, dt, u)
end
export fmiInputDoStepCSOutput
"""
DEPRECATED:
fmi2InputDoStepCSOutput(comp::FMU2Component,
dt::Real,
u::Array{<:Real})
Sets all FMU inputs to `u`, performs a ´´´fmi2DoStep´´´ and returns all FMU outputs.
"""
function fmi2InputDoStepCSOutput(fmu::FMU2, dt::Real, u::Array{<:Real})
@assert fmi2IsCoSimulation(fmu) [
"fmi2InputDoStepCSOutput(...): As in the name, this function only supports CS-FMUs.",
]
# fmi2DoStepCS(fmu, dt,
# fmu.modelDescription.inputValueReferences,
# u,
# fmu.modelDescription.outputValueReferences)
y_refs = fmu.modelDescription.outputValueReferences
u_refs = fmu.modelDescription.inputValueReferences
y = zeros(length(y_refs))
c = fmu.components[end]
y, _ = c(y = y, y_refs = y_refs, u = u, u_refs = u_refs)
# ignore_derivatives() do
# fmi2DoStep(c, dt)
# end
return y
end
export fmi2InputDoStepCSOutput
function fmi2DoStepCS(
fmu::FMU2,
dt::Real,
setValueReferences::Array{fmi2ValueReference} = zeros(fmi2ValueReference, 0),
setValues::Array{<:Real} = zeros(Real, 0),
getValueReferences::Array{fmi2ValueReference} = zeros(fmi2ValueReference, 0),
)
y_refs = setValueReferences
u_refs = getValueReferences
y = zeros(length(y_refs))
u = setValues
c = fmu.components[end]
y, _ = c(y = y, y_refs = y_refs, u = u, u_refs = u_refs)
# ignore_derivatives() do
# fmi2DoStep(c, dt)
# end
return y
end
export fmi2DoStepCS
# FMU wrappers
function fmi2EvaluateME(comp::FMU2Component, args...; kwargs...)
fmi2EvaluateME(comp.fmu, args...; kwargs...)
end
function fmi2DoStepCS(comp::FMU2Component, args...; kwargs...)
fmi2DoStepCS(comp.fmu, args...; kwargs...)
end
function fmi2InputDoStepCSOutput(comp::FMU2Component, args...; kwargs...)
fmi2InputDoStepCSOutput(comp.fmu, args...; kwargs...)
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 179 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
# feed through
params = Flux.params
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 4085 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
# ToDo: Quick-fixes until patch release SciMLSensitivity v0.7.XX
import FMISensitivity.SciMLSensitivity: FakeIntegrator, u_modified!
import FMISensitivity.SciMLSensitivity.DiffEqBase: set_u!
function u_modified!(::FakeIntegrator, ::Bool)
return nothing
end
function set_u!(::FakeIntegrator, u)
return nothing
end
# import FMISensitivity.ReverseDiff: increment_deriv!
# function increment_deriv!(t::AbstractArray{<:ReverseDiff.TrackedReal}, x::ReverseDiff.ZeroTangent, args...)
# return nothing
# end
#####
# [ToDo] This allows ITP solving also for ReverseDiff.TrackedReal borders, see:
# https://github.com/SciML/DiffEqBase.jl/blob/c7d949e062d9f382e6ef289d6d28e3c53e7202bc/src/internal_itp.jl#L13
using FMISensitivity.SciMLSensitivity.SciMLBase
using FMISensitivity.SciMLSensitivity.DiffEqBase
using FMISensitivity.SciMLSensitivity.DiffEqBase:
InternalITP, nextfloat_tdir, prevfloat_tdir, ReturnCode
import FMISensitivity.SciMLSensitivity.SciMLBase: solve
function SciMLBase.solve(
prob::IntervalNonlinearProblem{IP,Tuple{T,T2}},
alg::InternalITP,
args...;
maxiters = 1000,
kwargs...,
) where {IP,T,T2}
f = Base.Fix2(prob.f, prob.p)
left, right = prob.tspan # a and b
fl, fr = f(left), f(right)
ϵ = eps(T)
if iszero(fl)
return SciMLBase.build_solution(
prob,
alg,
left,
fl;
retcode = ReturnCode.ExactSolutionLeft,
left = left,
right = right,
)
elseif iszero(fr)
return SciMLBase.build_solution(
prob,
alg,
right,
fr;
retcode = ReturnCode.ExactSolutionRight,
left = left,
right = right,
)
end
#defining variables/cache
k1 = T(alg.k1)
k2 = T(alg.k2)
n0 = T(alg.n0)
n_h = ceil(log2(abs(right - left) / (2 * ϵ)))
mid = (left + right) / 2
x_f = (fr * left - fl * right) / (fr - fl)
xt = left
xp = left
r = zero(left) #minmax radius
δ = zero(left) # truncation error
σ = 1.0
ϵ_s = ϵ * 2^(n_h + n0)
i = 0 #iteration
while i <= maxiters
#mid = (left + right) / 2
span = abs(right - left)
r = ϵ_s - (span / 2)
δ = k1 * (span^k2)
## Interpolation step ##
x_f = left + (right - left) * (fl / (fl - fr))
## Truncation step ##
σ = sign(mid - x_f)
if δ <= abs(mid - x_f)
xt = x_f + (σ * δ)
else
xt = mid
end
## Projection step ##
if abs(xt - mid) <= r
xp = xt
else
xp = mid - (σ * r)
end
## Update ##
tmin, tmax = minmax(left, right)
xp >= tmax && (xp = prevfloat(tmax))
xp <= tmin && (xp = nextfloat(tmin))
yp = f(xp)
yps = yp * sign(fr)
if yps > 0
right = xp
fr = yp
elseif yps < 0
left = xp
fl = yp
else
left = prevfloat_tdir(xp, prob.tspan...)
right = xp
return SciMLBase.build_solution(
prob,
alg,
left,
f(left);
retcode = ReturnCode.Success,
left = left,
right = right,
)
end
i += 1
mid = (left + right) / 2
ϵ_s /= 2
if nextfloat_tdir(left, prob.tspan...) == right
return SciMLBase.build_solution(
prob,
alg,
left,
fl;
retcode = ReturnCode.FloatingPointLimit,
left = left,
right = right,
)
end
end
return SciMLBase.build_solution(
prob,
alg,
left,
fl;
retcode = ReturnCode.MaxIters,
left = left,
right = right,
)
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 8098 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Statistics: mean, std
### FMUParameterRegistrator ###
"""
ToDo.
"""
struct FMUParameterRegistrator{T}
fmu::FMU2
p_refs::AbstractArray{<:fmi2ValueReference}
p::AbstractArray{T}
function FMUParameterRegistrator{T}(
fmu::FMU2,
p_refs::fmi2ValueReferenceFormat,
p::AbstractArray{T},
) where {T}
@assert length(p_refs) == length(p) "`p_refs` and `p` need to be the same length!"
p_refs = prepareValueReference(fmu, p_refs)
fmu.default_p_refs = p_refs
fmu.default_p = p
for c in fmu.instances
c.default_p_refs = p_refs
c.default_p = p
end
return new{T}(fmu, p_refs, p)
end
function FMUParameterRegistrator(
fmu::FMU2,
p_refs::fmi2ValueReferenceFormat,
p::AbstractArray{T},
) where {T}
return FMUParameterRegistrator{T}(fmu, p_refs, p)
end
end
export FMUParameterRegistrator
function (l::FMUParameterRegistrator)(x)
l.fmu.default_p_refs = l.p_refs
l.fmu.default_p = l.p
for c in l.fmu.instances
c.default_p_refs = l.p_refs
c.default_p = l.p
end
return x
end
Flux.@functor FMUParameterRegistrator (p,)
### TimeLayer ###
"""
A neutral layer that calls a function `fct` with current FMU time as input.
"""
struct FMUTimeLayer{F,O}
fmu::FMU2
fct::F
offset::O
function FMUTimeLayer{F,O}(fmu::FMU2, fct::F, offset::O) where {F,O}
return new{F,O}(fmu, fct, offset)
end
function FMUTimeLayer(fmu::FMU2, fct::F, offset::O) where {F,O}
return FMUTimeLayer{F,O}(fmu, fct, offset)
end
end
export FMUTimeLayer
function (l::FMUTimeLayer)(x)
if hasCurrentInstance(l.fmu)
c = getCurrentInstance(l.fmu)
l.fct(c.default_t + l.offset[1])
end
return x
end
Flux.@functor FMUTimeLayer (offset,)
### ParameterRegistrator ###
"""
ToDo.
"""
struct ParameterRegistrator{T}
p::AbstractArray{T}
function ParameterRegistrator{T}(p::AbstractArray{T}) where {T}
return new{T}(p)
end
function ParameterRegistrator(p::AbstractArray{T}) where {T}
return ParameterRegistrator{T}(p)
end
end
export ParameterRegistrator
function (l::ParameterRegistrator)(x)
return x
end
Flux.@functor ParameterRegistrator (p,)
### SimultaniousZeroCrossing ###
"""
Forces a simultaniuos zero crossing together with a given value by function.
"""
struct SimultaniousZeroCrossing{T,F}
m::T # scaling factor
fct::F
function SimultaniousZeroCrossing{T,F}(m::T, fct::F) where {T,F}
return new{T,F}(m, fct)
end
function SimultaniousZeroCrossing(m::T, fct::F) where {T,F}
return SimultaniousZeroCrossing{T,F}(m, fct)
end
end
export SimultaniousZeroCrossing
function (l::SimultaniousZeroCrossing)(x)
return x * l.m * l.fct()
end
Flux.@functor SimultaniousZeroCrossing (m,)
### SHIFTSCALE ###
"""
ToDo.
"""
struct ShiftScale{T}
shift::AbstractArray{T}
scale::AbstractArray{T}
function ShiftScale{T}(shift::AbstractArray{T}, scale::AbstractArray{T}) where {T}
inst = new(shift, scale)
return inst
end
function ShiftScale(shift::AbstractArray{T}, scale::AbstractArray{T}) where {T}
return ShiftScale{T}(shift, scale)
end
# initialize for data array
function ShiftScale(
data::AbstractArray{<:AbstractArray{T}};
range::Union{Symbol,UnitRange{<:Integer}} = -1:1,
) where {T}
shift = -mean.(data)
scale = nothing
if range == :NormalDistribution
scale = 1.0 ./ std.(data)
elseif isa(range, UnitRange{<:Integer})
scale =
1.0 ./
(collect(max(d...) for d in data) - collect(min(d...) for d in data)) .*
(range[end] - range[1])
else
@assert false "Unsupported scaleMode, supported is `:NormalDistribution` or `UnitRange{<:Integer}`"
end
return ShiftScale{T}(shift, scale)
end
end
export ShiftScale
function (l::ShiftScale)(x)
x_proc = (x .+ l.shift) .* l.scale
return x_proc
end
Flux.@functor ShiftScale (shift, scale)
### SCALESHIFT ###
"""
ToDo.
"""
struct ScaleShift{T}
scale::AbstractArray{T}
shift::AbstractArray{T}
function ScaleShift{T}(scale::AbstractArray{T}, shift::AbstractArray{T}) where {T}
inst = new(scale, shift)
return inst
end
function ScaleShift(scale::AbstractArray{T}, shift::AbstractArray{T}) where {T}
return ScaleShift{T}(scale, shift)
end
# init ScaleShift with inverse transformation of a given ShiftScale
function ScaleShift(l::ShiftScale{T}; indices = 1:length(l.scale)) where {T}
return ScaleShift{T}(1.0 ./ l.scale[indices], -1.0 .* l.shift[indices])
end
function ScaleShift(data::AbstractArray{<:AbstractArray{T}}) where {T}
shift = mean.(data)
scale = std.(data)
return ShiftScale{T}(scale, shift)
end
end
export ScaleShift
function (l::ScaleShift)(x)
x_proc = (x .* l.scale) .+ l.shift
return x_proc
end
Flux.@functor ScaleShift (scale, shift)
### ScaleSum ###
struct ScaleSum{T}
scale::AbstractArray{T}
groups::Union{AbstractVector{<:AbstractVector{<:Integer}},Nothing}
function ScaleSum{T}(
scale::AbstractArray{T},
groups::Union{AbstractVector{<:AbstractVector{<:Integer}},Nothing} = nothing,
) where {T}
inst = new(scale, groups)
return inst
end
function ScaleSum(
scale::AbstractArray{T},
groups::Union{AbstractVector{<:AbstractVector{<:Integer}},Nothing} = nothing,
) where {T}
return ScaleSum{T}(scale, groups)
end
end
export ScaleSum
function (l::ScaleSum)(x)
if isnothing(l.groups)
x_proc = sum(x .* l.scale)
return [x_proc]
else
return collect(sum(x[g] .* l.scale[g]) for g in l.groups)
end
end
Flux.@functor ScaleSum (scale,)
### CACHE ###
mutable struct CacheLayer
cache::AbstractArray{<:AbstractArray}
function CacheLayer()
inst = new()
inst.cache = Array{Array,1}(undef, Threads.nthreads())
return inst
end
end
export CacheLayer
function (l::CacheLayer)(x)
tid = Threads.threadid()
l.cache[tid] = x
return x
end
### CACHERetrieve ###
struct CacheRetrieveLayer
cacheLayer::CacheLayer
function CacheRetrieveLayer(cacheLayer::CacheLayer)
inst = new(cacheLayer)
return inst
end
end
export CacheRetrieveLayer
function (l::CacheRetrieveLayer)(args...)
tid = Threads.threadid()
values = zeros(Real, 0)
for arg in args
if isa(arg, Integer)
val = l.cacheLayer.cache[tid][arg]
push!(values, val)
elseif isa(arg, AbstractArray) && length(arg) == 0
@warn "Deploying empty arrays `[]` in CacheRetrieveLayer is not necessary anymore, just remove them.\nThis warning is only printed once." maxlog =
1
# nothing to do here
elseif isa(arg, AbstractArray{<:Integer}) && length(arg) == 1
@warn "Deploying single element arrays `$(arg)` in CacheRetrieveLayer is not necessary anymore, just write `$(arg[1])`.\nThis warning is only printed once." maxlog =
1
val = l.cacheLayer.cache[tid][arg]
push!(values, val...)
elseif isa(arg, UnitRange{<:Integer}) || isa(arg, AbstractArray{<:Integer})
val = l.cacheLayer.cache[tid][arg]
push!(values, val...)
elseif isa(arg, Real)
push!(values, arg)
elseif isa(arg, AbstractArray{<:Real})
push!(values, arg...)
else
@assert false "CacheRetrieveLayer: Unknown argument `$(arg)` with type `$(typeof(arg))`"
end
end
# [Todo] this is only a quick fix!
values = [values...] # promote common data type
return values
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 10240 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
module Losses
using Flux
import ..FMIFlux: FMU2BatchElement, NeuralFMU, loss!, run!, ME_NeuralFMU, FMUSolution
import ..FMIFlux.FMIImport.FMIBase: unsense, logWarning
mse = Flux.Losses.mse
mae = Flux.Losses.mae
function last_element_rel(fun, a::AbstractArray, b::AbstractArray, lastElementRatio::Real)
return (1.0 - lastElementRatio) * fun(a[1:end-1], b[1:end-1]) +
lastElementRatio * fun(a[end], b[end])
end
function mse_last_element_rel(
a::AbstractArray,
b::AbstractArray,
lastElementRatio::Real = 0.25,
)
return last_element_rel(mse, a, b, lastElementRatio)
end
function mae_last_element_rel(
a::AbstractArray,
b::AbstractArray,
lastElementRatio::Real = 0.25,
)
return last_element_rel(mae, a, b, lastElementRatio)
end
function mse_last_element(a::AbstractArray, b::AbstractArray)
return mse(a[end], b[end])
end
function mae_last_element(a::AbstractArray, b::AbstractArray)
return mae(a[end], b[end])
end
function deviation(a::AbstractArray, b::AbstractArray, dev::AbstractArray)
Δ = abs.(a .- b)
Δ -= abs.(dev)
Δ = collect(max(val, 0.0) for val in Δ)
return Δ
end
function mae_dev(a::AbstractArray, b::AbstractArray, dev::AbstractArray)
num = length(a)
Δ = deviation(a, b, dev)
Δ = sum(Δ) / num
return Δ
end
function mse_dev(a::AbstractArray, b::AbstractArray, dev::AbstractArray)
num = length(a)
Δ = deviation(a, b, dev)
Δ = sum(Δ .^ 2) / num
return Δ
end
function max_dev(a::AbstractArray, b::AbstractArray, dev::AbstractArray)
Δ = deviation(a, b, dev)
Δ = max(Δ...)
return Δ
end
function mae_last_element_rel_dev(
a::AbstractArray,
b::AbstractArray,
dev::AbstractArray,
lastElementRatio::Real,
)
num = length(a)
Δ = deviation(a, b, dev)
Δ[1:end-1] .*= (1.0 - lastElementRatio)
Δ[end] *= lastElementRatio
Δ = sum(Δ) / num
return Δ
end
function mse_last_element_rel_dev(
a::AbstractArray,
b::AbstractArray,
dev::AbstractArray,
lastElementRatio::Real,
)
num = length(a)
Δ = deviation(a, b, dev)
Δ = Δ .^ 2
Δ[1:end-1] .*= (1.0 - lastElementRatio)
Δ[end] *= lastElementRatio
Δ = sum(Δ) / num
return Δ
end
function stiffness_corridor(
solution::FMUSolution,
corridor::AbstractArray{<:AbstractArray{<:Tuple{Real,Real}}};
lossFct = Flux.Losses.mse,
)
@assert !isnothing(solution.eigenvalues) "stiffness_corridor: Need eigenvalue information, that is not present in the given `FMUSolution`. Use keyword `recordEigenvalues=true` for FMU or NeuralFMU simulation."
eigs_over_time = solution.eigenvalues.saveval
num_eigs_over_time = length(eigs_over_time)
@assert num_eigs_over_time == length(corridor) "stiffness_corridor: length of time points with eigenvalues $(num_eigs_over_time) doesn't match time points in corridor $(length(corridor))."
l = 0.0
for i = 2:num_eigs_over_time
eigs = eigs_over_time[i]
num_eigs = Int(length(eigs) / 2)
for j = 1:num_eigs
re = eigs[(j-1)*2+1]
im = eigs[j*2]
c_min, c_max = corridor[i][j]
if re > c_max
l += lossFct(re, c_max) / num_eigs / num_eigs_over_time
end
if re < c_min
l += lossFct(c_min, re) / num_eigs / num_eigs_over_time
end
end
end
return l
end
function stiffness_corridor(
solution::FMUSolution,
corridor::AbstractArray{<:Tuple{Real,Real}};
lossFct = Flux.Losses.mse,
)
@assert !isnothing(solution.eigenvalues) "stiffness_corridor: Need eigenvalue information, that is not present in the given `FMUSolution`. Use keyword `recordEigenvalues=true` for FMU or NeuralFMU simulation."
eigs_over_time = solution.eigenvalues.saveval
num_eigs_over_time = length(eigs_over_time)
@assert num_eigs_over_time == length(corridor) "stiffness_corridor: length of time points with eigenvalues $(num_eigs_over_time) doesn't match time points in corridor $(length(corridor))."
l = 0.0
for i = 2:num_eigs_over_time
eigs = eigs_over_time[i]
num_eigs = Int(length(eigs) / 2)
c_min, c_max = corridor[i]
for j = 1:num_eigs
re = eigs[(j-1)*2+1]
im = eigs[j*2]
if re > c_max
l += lossFct(re, c_max) / num_eigs / num_eigs_over_time
end
if re < c_min
l += lossFct(c_min, re) / num_eigs / num_eigs_over_time
end
end
end
return l
end
function stiffness_corridor(
solution::FMUSolution,
corridor::Tuple{Real,Real};
lossFct = Flux.Losses.mse,
)
@assert !isnothing(solution.eigenvalues) "stiffness_corridor: Need eigenvalue information, that is not present in the given `FMUSolution`. Use keyword `recordEigenvalues=true` for FMU or NeuralFMU simulation."
eigs_over_time = solution.eigenvalues.saveval
num_eigs_over_time = length(eigs_over_time)
c_min, c_max = corridor
l = 0.0
for i = 2:num_eigs_over_time
eigs = eigs_over_time[i]
num_eigs = Int(length(eigs) / 2)
for j = 1:num_eigs
re = eigs[(j-1)*2+1]
im = eigs[j*2]
if re > c_max
l += lossFct(re, c_max) / num_eigs / num_eigs_over_time
end
if re < c_min
l += lossFct(re, c_min) / num_eigs / num_eigs_over_time
end
end
end
return l
end
function loss(
model,
batchElement::FMU2BatchElement;
logLoss::Bool = true,
lossFct = Flux.Losses.mse,
p = nothing,
)
model = nfmu.neuralODE.model[layers]
# evaluate model
result = run!(model, batchElement, p = p)
return loss!(batchElement, lossFct; logLoss = logLoss)
end
function loss(
nfmu::NeuralFMU,
batch::AbstractArray{<:FMU2BatchElement};
batchIndex::Integer = rand(1:length(batch)),
lossFct = Flux.Losses.mse,
logLoss::Bool = true,
solvekwargs...,
)
# cut out data batch from data
targets_data = batch[batchIndex].targets
nextBatchElement = nothing
if batchIndex < length(batch) && batch[batchIndex].tStop == batch[batchIndex+1].tStart
nextBatchElement = batch[batchIndex+1]
end
solution = run!(
nfmu,
batch[batchIndex];
nextBatchElement = nextBatchElement,
progressDescr = "Sim. Batch $(batchIndex)/$(length(batch)) |",
solvekwargs...,
)
if !solution.success
logWarning(
nfmu.fmu,
"Solving the NeuralFMU as part of the loss function failed with return code `$(solution.states.retcode)`.\nThis is often because the ODE cannot be solved. Did you initialize the NeuralFMU model?\nOften additional solver errors/warnings are printed before this warning.\nHowever, it is tried to compute a loss on the partial retrieved solution from $(unsense(solution.states.t[1]))s to $(unsense(solution.states.t[end]))s.",
)
return Inf
else
return loss!(batch[batchIndex], lossFct; logLoss = logLoss)
end
end
function loss(
model,
batch::AbstractArray{<:FMU2BatchElement};
batchIndex::Integer = rand(1:length(batch)),
lossFct = Flux.Losses.mse,
logLoss::Bool = true,
p = nothing,
)
run!(model, batch[batchIndex], p)
return loss!(batch[batchIndex], lossFct; logLoss = logLoss)
end
function batch_loss(
neuralFMU::ME_NeuralFMU,
batch::AbstractArray{<:FMU2BatchElement};
update::Bool = false,
logLoss::Bool = false,
lossFct = nothing,
kwargs...,
)
accu = nothing
if update
@assert lossFct != nothing "update=true, but no keyword lossFct provided. Please provide one."
numBatch = length(batch)
for i = 1:numBatch
b = batch[i]
b_next = nothing
if i < numBatch && batch[i].tStop == batch[i+1].tStart
b_next = batch[i+1]
end
if !isnothing(b.xStart)
run!(
neuralFMU,
b;
nextBatchElement = b_next,
progressDescr = "Sim. Batch $(i)/$(numBatch) |",
kwargs...,
)
end
if isnothing(accu)
accu = loss!(b, lossFct; logLoss = logLoss)
else
accu += loss!(b, lossFct; logLoss = logLoss)
end
end
else
for b in batch
@assert length(b.losses) > 0 "batch_loss(): `update=false` but no existing losses for batch element $(b)"
if isnothing(accu)
accu = b.losses[end].loss
else
accu += b.losses[end].loss
end
end
end
return accu
end
function batch_loss(
model,
batch::AbstractArray{<:FMU2BatchElement};
update::Bool = false,
logLoss::Bool = false,
lossFct = nothing,
p = nothing,
)
accu = nothing
if update
@assert lossFct != nothing "update=true, but no keyword lossFct provided. Please provide one."
numBatch = length(batch)
for i = 1:numBatch
b = batch[i]
run!(model, b, p)
if isnothing(accu)
accu = loss!(b, lossFct; logLoss = logLoss)
else
accu += loss!(b, lossFct; logLoss = logLoss)
end
end
else
for b in batch
if isnothing(accu)
accu = nominalLoss(b)
else
accu += nominalLoss(b)
end
end
end
return accu
end
mutable struct ToggleLoss
index::Int
losses::Any
function ToggleLoss(losses...)
@assert length(losses) >= 2 "ToggleLoss needs at least 2 losses, $(length(losses)) given."
return new(1, losses)
end
end
function (t::ToggleLoss)(args...; kwargs...)
ret = t.losses[t.index](args...; kwargs...)
t.index += 1
if t.index > length(t.losses)
t.index = 1
end
return ret
end
end # module
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 4280 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
"""
Compares non-equidistant (or equidistant) datapoints by linear interpolating and comparing at given interpolation points `t_comp`.
(Zygote-friendly: Zygote can differentiate through via AD.)
"""
function mse_interpolate(t1, x1, t2, x2, t_comp)
#lin1 = LinearInterpolation(t1, x1)
#lin2 = LinearInterpolation(t2, x2)
ar1 = collect(lin_interp(t1, x1, t_sample) for t_sample in t_comp) #lin1.(t_comp)
ar2 = collect(lin_interp(t2, x2, t_sample) for t_sample in t_comp) #lin2.(t_comp)
Flux.Losses.mse(ar1, ar2)
end
# Helper: simple linear interpolation
function lin_interp(t, x, t_sample)
if t_sample <= t[1]
return x[1]
end
if t_sample >= t[end]
return x[end]
end
i = 1
while t_sample > t[i]
i += 1
end
x_left = x[i-1]
x_right = x[i]
t_left = t[i-1]
t_right = t[i]
dx = x_right - x_left
dt = t_right - t_left
h = t_sample - t_left
x_left + dx / dt * h
end
"""
Writes/Copies flatted (Flux.destructure) training parameters `p_net` to non-flat model `net` with data offset `c`.
"""
function transferFlatParams!(net, p_net, c = 1; netRange = nothing)
if netRange == nothing
netRange = 1:length(net.layers)
end
for l in netRange
if !isa(net.layers[l], Flux.Dense)
continue
end
ni = size(net.layers[l].weight, 2)
no = size(net.layers[l].weight, 1)
w = zeros(no, ni)
b = zeros(no)
for i = 1:ni
for o = 1:no
w[o, i] = p_net[1][c+(i-1)*no+(o-1)]
end
end
c += ni * no
for o = 1:no
b[o] = p_net[1][c+(o-1)]
end
c += no
copy!(net.layers[l].weight, w)
copy!(net.layers[l].bias, b)
end
end
function transferParams!(net, p_net, c = 1; netRange = nothing)
if netRange == nothing
netRange = 1:length(net.layers)
end
for l in netRange
if !(net.layers[l] isa Flux.Dense)
continue
end
for w = 1:length(net.layers[l].weight)
net.layers[l].weight[w] = p_net[1+(l-1)*2][w]
end
for b = 1:length(net.layers[l].bias)
net.layers[l].bias[b] = p_net[l*2][b]
end
end
end
# this is needed by Zygote, but not defined by default
function Base.ndims(::Tuple{Float64})
return 1
end
# transposes a vector of vectors
function transpose(vec::AbstractVector{<:AbstractVector{<:Real}})
return collect(eachrow(reduce(hcat, vec)))
end
function timeToIndex(ts::AbstractArray{<:Real}, target::Real)
tStart = ts[1]
tStop = ts[end]
tLen = length(ts)
@assert target >= tStart "timeToIndex(...): Time ($(target)) < tStart ($(tStart))"
# because of the event handling condition, `target` can be outside of the simulation interval!
# OLD: @assert target <= tStop "timeToIndex(...): Time ($(target)) > tStop ($(tStop))"
# NEW:
if target > tStop
target = tStop
end
if target == tStart
return 1
elseif target == tStop
return tLen
end
# i = 1
# while ts[i] < target
# i += 1
# end
# return i
# estimate start value
steps = 0
i = min(max(round(Integer, (target - tStart) / (tStop - tStart) * tLen), 1), tLen)
lastStep = Inf
while !(ts[i] <= target && ts[i+1] > target)
dt = target - ts[i]
step = round(Integer, dt / (tStop - tStart) * tLen)
if abs(step) >= lastStep
step = Int(sign(dt)) * (lastStep - 1)
end
if step == 0
step = Int(sign(dt))
end
lastStep = abs(step)
#@info "$i += $step = $(i+step)"
i += step
if i < 1
i = 1
elseif i > tLen
i = tLen
end
steps += 1
@assert steps < tLen "Steps reached max."
end
#@info "$steps"
t = ts[i]
next_t = ts[i+1]
@assert t <= target && next_t >= target "No fitting time found, numerical issue."
if (target - t) < (next_t - target)
return i
else
return i + 1
end
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 67217 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
import FMIImport.FMIBase:
assert_integrator_valid,
isdual,
istracked,
issense,
undual,
unsense,
unsense_copy,
untrack,
FMUSnapshot
import FMIImport:
finishSolveFMU, handleEvents, prepareSolveFMU, snapshot_if_needed!, getSnapshot
import Optim
import FMIImport.FMIBase.ProgressMeter
import FMISensitivity.SciMLSensitivity.SciMLBase:
CallbackSet,
ContinuousCallback,
ODESolution,
ReturnCode,
RightRootFind,
VectorContinuousCallback,
set_u!,
terminate!,
u_modified!,
build_solution
import OrdinaryDiffEq: isimplicit, alg_autodiff
using FMISensitivity.ReverseDiff: TrackedArray
import FMISensitivity.SciMLSensitivity:
InterpolatingAdjoint, ReverseDiffVJP, AutoForwardDiff
import ThreadPools
import FMIImport.FMIBase
using FMIImport.FMIBase.DiffEqCallbacks
using FMIImport.FMIBase.SciMLBase: ODEFunction, ODEProblem, solve
using FMIImport.FMIBase:
fmi2ComponentState,
fmi2ComponentStateContinuousTimeMode,
fmi2ComponentStateError,
fmi2ComponentStateEventMode,
fmi2ComponentStateFatal,
fmi2ComponentStateInitializationMode,
fmi2ComponentStateInstantiated,
fmi2ComponentStateTerminated,
fmi2StatusOK,
fmi2Type,
fmi2TypeCoSimulation,
fmi2TypeModelExchange,
logError,
logInfo,
logWarning,
fast_copy!
using FMISensitivity.SciMLSensitivity:
ForwardDiffSensitivity, InterpolatingAdjoint, ReverseDiffVJP, ZygoteVJP
import DifferentiableEigen
import DifferentiableEigen.LinearAlgebra: I
import FMIImport.FMIBase: EMPTY_fmi2Real, EMPTY_fmi2ValueReference
import FMIImport.FMIBase
import FMISensitivity: NoTangent, ZeroTangent
DEFAULT_PROGRESS_DESCR = "Simulating ME-NeuralFMU ..."
DEFAULT_CHUNK_SIZE = 32
"""
The mutable struct representing an abstract (simulation mode unknown) NeuralFMU.
"""
abstract type NeuralFMU end
"""
Structure definition for a NeuralFMU, that runs in mode `Model Exchange` (ME).
"""
mutable struct ME_NeuralFMU{M,R} <: NeuralFMU
model::M
p::AbstractArray{<:Real}
re::R
solvekwargs::Any
re_model::Any
re_p::Any
fmu::FMU
tspan::Any
saveat::Any
saved_values::Any
recordValues::Any
solver::Any
valueStack::Any
customCallbacksBefore::Array
customCallbacksAfter::Array
x0::Union{Array{Float64},Nothing}
firstRun::Bool
tolerance::Union{Real,Nothing}
parameters::Union{Dict{<:Any,<:Any},Nothing}
modifiedState::Bool
execution_start::Real
condition_buffer::Union{AbstractArray{<:Real},Nothing}
snapshots::Bool
function ME_NeuralFMU{M,R}(model::M, p::AbstractArray{<:Real}, re::R) where {M,R}
inst = new()
inst.model = model
inst.p = p
inst.re = re
inst.x0 = nothing
inst.saveat = nothing
inst.re_model = nothing
inst.re_p = nothing
inst.modifiedState = false
# inst.startState = nothing
# inst.stopState = nothing
# inst.startEventInfo = nothing
# inst.stopEventInfo = nothing
inst.customCallbacksBefore = []
inst.customCallbacksAfter = []
inst.execution_start = 0.0
inst.condition_buffer = nothing
inst.snapshots = false
return inst
end
end
"""
Structure definition for a NeuralFMU, that runs in mode `Co-Simulation` (CS).
"""
mutable struct CS_NeuralFMU{F,C} <: NeuralFMU
model::Any
fmu::F
tspan::Any
p::Union{AbstractArray{<:Real},Nothing}
re::Any # restructure function
snapshots::Bool
function CS_NeuralFMU{F,C}() where {F,C}
inst = new{F,C}()
inst.re = nothing
inst.p = nothing
inst.snapshots = false
return inst
end
end
function evaluateModel(nfmu::ME_NeuralFMU, c::FMU2Component, x; p = nfmu.p, t = c.default_t)
@assert getCurrentInstance(nfmu.fmu) == c "Thread `$(Threads.threadid())` wants to evaluate wrong component!"
# [ToDo]: Skip array check, e.g. by using a flag
#if p !== nfmu.re_p || p != nfmu.re_p # || isnothing(nfmu.re_model)
# nfmu.re_p = p # fast_copy!(nfmu, :re_p, p)
# nfmu.re_model = nfmu.re(p)
#end
#return nfmu.re_model(x)
@debug "evaluateModel(t=$(t)) [out-of-place dx]"
#nfmu.p = p
c.default_t = t
return nfmu.re(p)(x)
end
function evaluateModel(
nfmu::ME_NeuralFMU,
c::FMU2Component,
dx,
x;
p = nfmu.p,
t = c.default_t,
)
@assert getCurrentInstance(nfmu.fmu) == c "Thread `$(Threads.threadid())` wants to evaluate wrong component!"
# [ToDo]: Skip array check, e.g. by using a flag
#if p !== nfmu.re_p || p != nfmu.re_p # || isnothing(nfmu.re_model)
# nfmu.re_p = p # fast_copy!(nfmu, :re_p, p)
# nfmu.re_model = nfmu.re(p)
#end
#dx[:] = nfmu.re_model(x)
@debug "evaluateModel(t=$(t)) [in-place dx]"
#nfmu.p = p
c.default_t = t
dx[:] = nfmu.re(p)(x)
return nothing
end
##### EVENT HANDLING START
function startCallback(
integrator,
nfmu::ME_NeuralFMU,
c::Union{FMU2Component,Nothing},
t,
writeSnapshot,
readSnapshot,
)
ignore_derivatives() do
nfmu.execution_start = time()
t = unsense(t)
@assert t == nfmu.tspan[1] "startCallback(...): Called for non-start-point t=$(t)"
c, x0 = prepareSolveFMU(
nfmu.fmu,
c,
fmi2TypeModelExchange;
parameters = nfmu.parameters,
t_start = nfmu.tspan[1],
t_stop = nfmu.tspan[end],
tolerance = nfmu.tolerance,
x0 = nfmu.x0,
handleEvents = FMIFlux.handleEvents,
cleanup = true,
)
if c.eventInfo.nextEventTime == t && c.eventInfo.nextEventTimeDefined == fmi2True
@debug "Initial time event detected!"
else
@debug "No initial time events ..."
end
if nfmu.snapshots
FMIBase.snapshot!(c.solution)
end
if !isnothing(writeSnapshot)
FMIBase.update!(c, writeSnapshot)
end
if !isnothing(readSnapshot)
@assert c == readSnapshot.instance "Snapshot instance mismatch, snapshot instance is $(readSnapshot.instance.compAddr), current component is $(c.compAddr)"
# c = readSnapshot.instance
if t != readSnapshot.t
logWarning(
c.fmu,
"Snapshot time mismatch, snapshot time = $(readSnapshot.t), but start time is $(t)",
)
end
@debug "ME_NeuralFMU: Applying snapshot..."
FMIBase.apply!(c, readSnapshot; t = t)
@debug "ME_NeuralFMU: Snapshot applied."
end
end
return c
end
function stopCallback(nfmu::ME_NeuralFMU, c::FMU2Component, t)
@assert getCurrentInstance(nfmu.fmu) == c "Thread `$(Threads.threadid())` wants to evaluate wrong component!"
ignore_derivatives() do
t = unsense(t)
@assert t == nfmu.tspan[end] "stopCallback(...): Called for non-start-point t=$(t)"
end
return c
end
# Read next time event from fmu and provide it to the integrator
function time_choice(nfmu::ME_NeuralFMU, c::FMU2Component, integrator, tStart, tStop)
@assert getCurrentInstance(nfmu.fmu) == c "Thread `$(Threads.threadid())` wants to evaluate wrong component!"
@assert c.fmu.executionConfig.handleTimeEvents "time_choice(...) was called, but execution config disables time events.\nPlease open a issue."
# assert_integrator_valid(integrator)
# last call may be after simulation end
if c == nothing
return nothing
end
c.solution.evals_timechoice += 1
if c.eventInfo.nextEventTimeDefined == fmi2True
if c.eventInfo.nextEventTime >= tStart && c.eventInfo.nextEventTime <= tStop
@debug "time_choice(...): At $(integrator.t) next time event announced @$(c.eventInfo.nextEventTime)s"
return c.eventInfo.nextEventTime
else
# the time event is outside the simulation range!
@debug "Next time event @$(c.eventInfo.nextEventTime)s is outside simulation time range ($(tStart), $(tStop)), skipping."
return nothing
end
else
return nothing
end
end
# [ToDo] for now, ReverseDiff (together with the rrule) seems to have a problem with the SubArray here (when `collect` it accesses array elements that are #undef),
# so I added an additional (single allocating) dispatch...
# Type is ReverseDiff.TrackedReal{Float64, Float64, ReverseDiff.TrackedArray{Float64, Float64, 1, Vector{Float64}, Vector{Float64}}}[#undef, #undef, #undef, ...]
function condition!(
nfmu::ME_NeuralFMU,
c::FMU2Component,
out::AbstractArray{<:ReverseDiff.TrackedReal},
x,
t,
integrator,
handleEventIndicators,
)
if !isassigned(out, 1)
if isnothing(nfmu.condition_buffer)
logInfo(
nfmu.fmu,
"There is currently an issue with the condition buffer pre-allocation, the buffer can't be overwritten by the generated rrule.\nBuffer is generated automatically.",
)
@assert length(out) == length(handleEventIndicators) "Number of event indicators to handle ($(handleEventIndicators)) doesn't fit buffer size $(length(out))."
nfmu.condition_buffer = zeros(eltype(out), length(out))
elseif eltype(out) != eltype(nfmu.condition_buffer) ||
length(out) != length(nfmu.condition_buffer)
nfmu.condition_buffer = zeros(eltype(out), length(out))
end
out[:] = nfmu.condition_buffer
end
invoke(
condition!,
Tuple{ME_NeuralFMU,FMU2Component,Any,Any,Any,Any,Any},
nfmu,
c,
out,
x,
t,
integrator,
handleEventIndicators,
)
return nothing
end
function condition!(
nfmu::ME_NeuralFMU,
c::FMU2Component,
out,
x,
t,
integrator,
handleEventIndicators,
)
@assert getCurrentInstance(nfmu.fmu) == c "Thread `$(Threads.threadid())` wants to evaluate wrong component!"
@assert c.state == fmi2ComponentStateContinuousTimeMode "condition!(...):\n" *
FMIBase.ERR_MSG_CONT_TIME_MODE
# [ToDo] Evaluate on light-weight model (sub-model) without fmi2GetXXX or similar and the bottom ANN.
# Basically only the layers from very top to FMU need to be evaluated here.
prev_t = c.default_t
prev_ec = c.default_ec
prev_ec_idcs = c.default_ec_idcs
c.default_t = t
c.default_ec = out
c.default_ec_idcs = handleEventIndicators
evaluateModel(nfmu, c, x)
# write back to condition buffer
if (!isdual(out) && isdual(c.output.ec)) || (!istracked(out) && istracked(c.output.ec))
out[:] = unsense(c.output.ec)
else
out[:] = c.output.ec # [ToDo] This seems not to be necessary, because of `c.default_ec = out`
end
# reset
c.default_t = prev_t
c.default_ec = prev_ec
c.default_ec_idcs = prev_ec_idcs
c.solution.evals_condition += 1
@debug "condition!(...) -> [typeof=$(typeof(out))]\n$(unsense(out))"
return nothing
end
global lastIndicator = nothing
global lastIndicatorX = nothing
global lastIndicatorT = nothing
function conditionSingle(nfmu::ME_NeuralFMU, c::FMU2Component, index, x, t, integrator)
@assert c.state == fmi2ComponentStateContinuousTimeMode "condition(...):\n" *
FMIBase.ERR_MSG_CONT_TIME_MODE
@assert getCurrentInstance(nfmu.fmu) == c "Thread `$(Threads.threadid())` wants to evaluate wrong component!"
if c.fmu.handleEventIndicators != nothing && index ∉ c.fmu.handleEventIndicators
return 1.0
end
global lastIndicator
if lastIndicator == nothing ||
length(lastIndicator) != c.fmu.modelDescription.numberOfEventIndicators
lastIndicator = zeros(c.fmu.modelDescription.numberOfEventIndicators)
end
# [ToDo] Evaluate on light-weight model (sub-model) without fmi2GetXXX or similar and the bottom ANN
c.default_t = t
c.default_ec = lastIndicator
evaluateModel(nfmu, c, x)
c.default_t = -1.0
c.default_ec = EMPTY_fmi2Real
c.solution.evals_condition += 1
return lastIndicator[index]
end
function smoothmax(vec::AbstractVector; alpha = 0.5)
dividend = 0.0
divisor = 0.0
e = Float64(ℯ)
for x in vec
dividend += x * e^(alpha * x)
divisor += e^(alpha * x)
end
return dividend / divisor
end
function smoothmax(a, b; kwargs...)
return smoothmax([a, b]; kwargs...)
end
# [ToDo] Check, that the new determined state is the right root of the event instant!
function f_optim(
x,
nfmu::ME_NeuralFMU,
c::FMU2Component,
right_x_fmu,
idx,
sign::Real,
out,
indicatorValue,
handleEventIndicators;
_unsense::Bool = false,
)
prev_ec = c.default_ec
prev_ec_idcs = c.default_ec_idcs
prev_y_refs = c.default_y_refs
prev_y = c.default_y
#@info "\ndx: $(c.default_dx)\n x: $(x)"
c.default_ec = out
c.default_ec_idcs = handleEventIndicators
c.default_y_refs = c.fmu.modelDescription.stateValueReferences
c.default_y = zeros(typeof(x[1]), length(c.fmu.modelDescription.stateValueReferences))
evaluateModel(nfmu, c, x; p = unsense(nfmu.p))
# write back to condition buffer
# if (!isdual(out) && isdual(c.output.ec)) || (!istracked(out) && istracked(c.output.ec))
# @assert false "Type missmatch! Can't propagate sensitivities!"
# out[:] = unsense(c.output.ec)
# else
# out[:] = c.output.ec # [ToDo] This seems not to be necessary, because of `c.default_ec = out`
# end
# reset
c.default_ec = prev_ec
c.default_ec_idcs = prev_ec_idcs
c.default_y_refs = prev_y_refs
c.default_y = prev_y
# propagete the new state-guess `x` through the NeuralFMU
#condition!(nfmu, c, buffer, x, c.t, nothing, handleEventIndicators)
ec = c.output.ec[idx]
y = c.output.y
#@info "\nec: $(ec)\n-> $(unsense(ec))\ny: $(y)\n-> $(unsense(y))"
errorIndicator =
Flux.Losses.mae(indicatorValue, ec) + smoothmax(-sign * ec * 1000.0, 0.0)
# if errorIndicator > 0.0
# errorIndicator = max(errorIndicator, 1.0)
# end
errorState = Flux.Losses.mae(right_x_fmu, y)
#@info "ErrorState: $(errorState) | ErrorIndicator: $(errorIndicator)"
ret = errorState + errorIndicator
# if _unsense
# ret = unsense(ret)
# end
return ret
end
function sampleStateChangeJacobian(nfmu, c, left_x, right_x, t, idx::Integer; step = 1e-8)
@debug "sampleStateChangeJacobian(x = $(left_x))"
c.solution.evals_∂xr_∂xl += 1
numStates = length(left_x)
jac = zeros(numStates, numStates)
# first, jump to before the event instance
# if length(c.solution.snapshots) > 0 # c.t != t
# sn = getSnapshot(c.solution, t)
# FMIBase.apply!(c, sn; x_c=left_x, t=t)
# #@info "[d] Set snapshot @ t=$(t) (sn.t=$(sn.t))"
# end
# indicator_sign = idx > 0 ? sign(fmi2GetEventIndicators(c)[idx]) : 1.0
# [ToDo] ONLY A TEST
new_left_x = copy(left_x)
if length(c.solution.snapshots) > 0 # c.t != t
sn = getSnapshot(c.solution, t)
FMIBase.apply!(c, sn; x_c = new_left_x, t = t)
#@info "[?] Set snapshot @ t=$(t) (sn.t=$(sn.t))"
end
new_right_x = stateChange!(nfmu, c, new_left_x, t, idx; snapshots = false)
statesChanged = (c.eventInfo.valuesOfContinuousStatesChanged == fmi2True)
# [ToDo: these tests should be included, but will drastically fail on FMUs with no support for get/setState]
# @assert statesChanged "Can't reproduce event (statesChanged)!"
# @assert left_x == new_left_x "Can't reproduce event (left_x)!"
# @assert right_x == new_right_x "Can't reproduce event (right_x)!"
at_least_one_state_change = false
for i = 1:numStates
#new_left_x[:] .= left_x
new_left_x = copy(left_x)
new_left_x[i] += step
# first, jump to before the event instance
if length(c.solution.snapshots) > 0 # c.t != t
sn = getSnapshot(c.solution, t)
FMIBase.apply!(c, sn; x_c = new_left_x, t = t)
#@info "[e] Set snapshot @ t=$(t) (sn.t=$(sn.t))"
end
# [ToDo] Don't check if event was handled via event-indicator, because there is no guarantee that it is reset (like for the bouncing ball)
# to match the sign from before the event! Better check if FMU detects a new event!
# fmi2EnterEventMode(c)
# handleEvents(c)
new_right_x = stateChange!(nfmu, c, new_left_x, t, idx; snapshots = false)
statesChanged = (c.eventInfo.valuesOfContinuousStatesChanged == fmi2True)
at_least_one_state_change = statesChanged || at_least_one_state_change
#new_indicator_sign = idx > 0 ? sign(fmi2GetEventIndicators(c)[idx]) : 1.0
#@info "Sample P: t:$(t) $(new_left_x) -> $(new_right_x)"
grad = (new_right_x .- right_x) ./ step # (left_x .- new_left_x)
# choose other direction
if !statesChanged
#@info "New_indicator sign is $(new_indicator_sign) (should be $(indicator_sign)), retry..."
#new_left_x[:] .= left_x
new_left_x = copy(left_x)
new_left_x[i] -= step
if length(c.solution.snapshots) > 0 # c.t != t
sn = getSnapshot(c.solution, t)
FMIBase.apply!(c, sn; x_c = new_left_x, t = t)
#@info "[e] Set snapshot @ t=$(t) (sn.t=$(sn.t))"
end
#fmi2EnterEventMode(c)
#handleEvents(c)
new_right_x = stateChange!(nfmu, c, new_left_x, t, idx; snapshots = false)
statesChanged = (c.eventInfo.valuesOfContinuousStatesChanged == fmi2True)
at_least_one_state_change = statesChanged || at_least_one_state_change
#new_indicator_sign = idx > 0 ? sign(fmi2GetEventIndicators(c)[idx]) : 1.0
#@info "Sample N: t:$(t) $(new_left_x) -> $(new_right_x)"
if statesChanged
grad = (new_right_x .- right_x) ./ -step # (left_x .- new_left_x)
else
grad = (right_x .- right_x) # ... so zero, this state is not sensitive at all!
end
end
# if length(c.solution.snapshots) > 0 # c.t != t
# sn = getSnapshot(c.solution, t)
# FMIBase.apply!(c, sn; x_c=new_left_x, t=t)
# #@info "[e] Set snapshot @ t=$(t) (sn.t=$(sn.t))"
# end
# new_right_x = stateChange!(nfmu, c, new_left_x, t, idx; snapshots=false)
# [ToDo] check if the SAME event indicator was triggered!
#@info "t=$(t) idx=$(idx)\n left_x: $(left_x) -> right_x: $(right_x) [$(indicator_sign)]\nnew_left_x: $(new_left_x) -> new_right_x: $(new_right_x) [$(new_indicator_sign)]"
jac[i, :] = grad
end
#@assert at_least_one_state_change "Sampling state change jacobian failed, can't find another state that triggers the event!"
if !at_least_one_state_change
@info "Sampling state change jacobian failed, can't find another state that triggers the event!\ncommon reasons for that are:\n(a) The FMU is not able to revisit events (which should be possible with fmiXGet/SetState).\n(b) The state change is not dependent on the previous state (hard reset).\nThis is printed only 3 times." maxlog =
3
end
# finally, jump back to the correct FMU state
# if length(c.solution.snapshots) > 0 # c.t != t
# @info "Reset snapshot @ t = $(t)"
# sn = getSnapshot(c.solution, t)
# FMIBase.apply!(c, sn; x_c=left_x, t=t)
# end
# stateChange!(nfmu, c, left_x, t, idx)
if length(c.solution.snapshots) > 0
#@info "Reset exact snapshot @t=$(t)"
sn = getSnapshot(c.solution, t; exact = true)
if !isnothing(sn)
FMIBase.apply!(c, sn; x_c = left_x, t = t)
end
end
#@info "Jac:\n$(jac)"
#@assert isapprox(jac, [0.0 0.0; 0.0 -0.7]; atol=1e-4) "Jac missmatch, is $(jac)"
return jac
end
function is_integrator_sensitive(integrator)
return istracked(integrator.u) ||
istracked(integrator.t) ||
isdual(integrator.u) ||
isdual(integrator.t)
end
function stateChange!(
nfmu,
c,
left_x::AbstractArray{<:Float64},
t::Float64,
idx;
snapshots = nfmu.snapshots,
)
# unpack references
# if typeof(cRef) != UInt64
# cRef = UInt64(cRef)
# end
# c = unsafe_pointer_to_objref(Ptr{Nothing}(cRef))
# if typeof(nfmuRef) != UInt64
# nfmuRef = UInt64(nfmuRef)
# end
# nfmu = unsafe_pointer_to_objref(Ptr{Nothing}(nfmuRef))
# unpack references done
# if length(c.solution.snapshots) > 0 # c.t != t
# sn = getSnapshot(c.solution, t)
# @info "[x] Set snapshot @ t=$(t) (sn.t=$(sn.t))"
# FMIBase.apply!(c, sn; x_c=left_x, t=t)
# end
# [ToDo]: Debugging, remove this!
#@assert fmi2GetContinuousStates(c) == left_x "$(left_x) != $(fmi2GetContinuousStates(c))"
#@debug "stateChange!, state is $(fmi2GetContinuousStates(c))"
fmi2EnterEventMode(c)
handleEvents(c)
#snapshots = true # nfmu.snapshots || snapshotsNeeded(nfmu, integrator)
# ignore_derivatives() do
# if idx == 0
# time_affect!(integrator)
# else
# #affect_right!(integrator, idx)
# end
# end
right_x = left_x
if c.eventInfo.valuesOfContinuousStatesChanged == fmi2True
ignore_derivatives() do
if idx == 0
@debug "stateChange!($(idx)): NeuralFMU time event with state change.\nt = $(t)\nleft_x = $(left_x)"
else
@debug "stateChange!($(idx)): NeuralFMU state event with state change by indicator $(idx).\nt = $(t)\nleft_x = $(left_x)"
end
end
right_x_fmu = fmi2GetContinuousStates(c) # the new FMU state after handled events
# if there is an ANN above the FMU, propaget FMU state through top ANN by optimization
if nfmu.modifiedState
before = fmi2GetEventIndicators(c)
buffer = copy(before)
handleEventIndicators = Vector{UInt32}(
collect(
i for i = 1:length(nfmu.fmu.modelDescription.numberOfEventIndicators)
),
)
_f(_x) = f_optim(
_x,
nfmu,
c,
right_x_fmu,
idx,
sign(before[idx]),
buffer,
before[idx],
handleEventIndicators;
_unsense = true,
)
_f_g(_x) = f_optim(
_x,
nfmu,
c,
right_x_fmu,
idx,
sign(before[idx]),
buffer,
before[idx],
handleEventIndicators;
_unsense = false,
)
function _g!(G, x)
#if istracked(integrator.u)
# ReverseDiff.gradient!(G, _f_g, x)
#else # if isdual(integrator.u)
ForwardDiff.gradient!(G, _f_g, x)
# else
# @assert false "Unknown AD framework! -> $(typeof(integrator.u[1]))"
#end
#@info "G: $(G)"
end
result = Optim.optimize(_f, _g!, left_x, Optim.BFGS())
right_x = Optim.minimizer(result)
after = fmi2GetEventIndicators(c)
if sign(before[idx]) != sign(after[idx])
logError(
nfmu.fmu,
"Eventhandling failed,\nRight state: $(right_x)\nRight FMU state: $(right_x_fmu)\nIndicator (bef.): $(before[idx])\nIndicator (aft.): $(after[idx])",
)
end
else # if there is no ANN above, then:
right_x = right_x_fmu
end
else
ignore_derivatives() do
if idx == 0
@debug "stateChange!($(idx)): NeuralFMU time event without state change.\nt = $(t)\nx = $(left_x)"
else
@debug "stateChange!($(idx)): NeuralFMU state event without state change by indicator $(idx).\nt = $(t)\nx = $(left_x)"
end
end
# [Note] enabling this causes serious issues with time events! (wrong sensitivities!)
# u_modified!(integrator, false)
end
if snapshots
s = snapshot_if_needed!(c.solution, t)
# if !isnothing(s)
# @info "Add snapshot @t=$(s.t)"
# end
end
# [ToDo] This is only correct, if every state is only depenent on itself.
# This should only be done in the frule/rrule, the actual affect should do a hard "set state"
#logWarning(c.fmu, "Before: integrator.u = $(integrator.u)")
# if nfmu.fmu.executionConfig.isolatedStateDependency
# for i in 1:length(left_x)
# if abs(left_x[i]) > 1e-16 # left_x[i] != 0.0 #
# scale = right_x[i] / left_x[i]
# integrator.u[i] *= scale
# else # integrator state zero can't be scaled, need to add (but no sensitivities in this case!)
# shift = right_x[i] - left_x[i]
# integrator.u[i] += shift
# #integrator.u[i] = right_x[i]
# #logWarning(c.fmu, "Probably wrong sensitivities @t=$(unsense(t)) for ∂x^+ / ∂x^-\nCan't scale zero state #$(i) from $(left_x[i]) to $(right_x[i])\nNew state after transform is: $(integrator.u[i])")
# end
# end
# else
# integrator.u[:] = right_x
# end
return right_x
end
# Handles the upcoming event
function affectFMU!(nfmu::ME_NeuralFMU, c::FMU2Component, integrator, idx)
@debug "affectFMU!"
@assert getCurrentInstance(nfmu.fmu) == c "Thread `$(Threads.threadid())` wants to evaluate wrong component!"
# assert_integrator_valid(integrator)
@assert c.state == fmi2ComponentStateContinuousTimeMode "affectFMU!(...):\n" *
FMIBase.ERR_MSG_CONT_TIME_MODE
# [NOTE] Here unsensing is OK, because we just want to reset the FMU to the correct state!
# The values come directly from the integrator and are NOT function arguments!
t = unsense(integrator.t)
left_x = unsense_copy(integrator.u)
right_x = nothing
ignore_derivatives() do
# if snapshots && length(c.solution.snapshots) > 0
# sn = getSnapshot(c.solution, t)
# FMIBase.apply!(c, sn)
# end
#if c.x != left_x
# capture status of `force`
mode = c.force
c.force = true
# there are fx-evaluations before the event is handled, reset the FMU state to the current integrator step
evaluateModel(nfmu, c, left_x; t = t) # evaluate NeuralFMU (set new states)
# [NOTE] No need to reset time here, because we did pass a event instance!
# c.default_t = -1.0
c.force = mode
#end
end
integ_sens = nfmu.snapshots
right_x = stateChange!(nfmu, c, left_x, t, idx)
# sensitivities needed
if integ_sens
jac = I
if c.eventInfo.valuesOfContinuousStatesChanged == fmi2True
jac = sampleStateChangeJacobian(nfmu, c, left_x, right_x, t, idx)
end
VJP = jac * integrator.u
#tgrad = tvec .* integrator.t
staticOff = right_x .- unsense(VJP) # .- unsense(tgrad)
# [ToDo] add (sampled) time gradient
integrator.u[:] = staticOff + VJP # + tgrad
else
integrator.u[:] = right_x
end
#@info "affect right_x = $(right_x)"
# [Note] enabling this causes serious issues with time events! (wrong sensitivities!)
# u_modified!(integrator, true)
if c.eventInfo.nominalsOfContinuousStatesChanged == fmi2True
# [ToDo] Do something with that information, e.g. use for FiniteDiff sampling step size determination
x_nom = fmi2GetNominalsOfContinuousStates(c)
end
ignore_derivatives() do
if idx != -1
_left_x = left_x
_right_x = isnothing(right_x) ? _left_x : unsense_copy(right_x)
#@assert c.eventInfo.valuesOfContinuousStatesChanged == (_left_x != _right_x) "FMU says valuesOfContinuousStatesChanged $(c.eventInfo.valuesOfContinuousStatesChanged), but states say different!"
e = FMUEvent(unsense(t), UInt64(idx), _left_x, _right_x)
push!(c.solution.events, e)
end
# calculates state events per second
pt = t - nfmu.tspan[1]
ne = 0
for event in c.solution.events
#if t - event.t < pt
if event.indicator > 0 # count only state events
ne += 1
end
#end
end
ratio = ne / pt
if ne >= 100 && ratio > c.fmu.executionConfig.maxStateEventsPerSecond
logError(
c.fmu,
"Event chattering detected $(round(Integer, ratio)) state events/s (allowed are $(c.fmu.executionConfig.maxStateEventsPerSecond)), aborting at t=$(t) (rel. t=$(pt)) at state event $(ne):",
)
for i = 1:c.fmu.modelDescription.numberOfEventIndicators
num = 0
for e in c.solution.events
if e.indicator == i
num += 1
end
end
if num > 0
logError(
c.fmu,
"\tEvent indicator #$(i) triggered $(num) ($(round(num/ne*100.0; digits=1))%)",
)
end
end
terminate!(integrator)
end
end
c.solution.evals_affect += 1
return nothing
end
# Does one step in the simulation.
function stepCompleted(
nfmu::ME_NeuralFMU,
c::FMU2Component,
x,
t,
integrator,
tStart,
tStop,
)
# assert_integrator_valid(integrator)
# [Note] enabling this causes serious issues with time events! (wrong sensitivities!)
# u_modified!(integrator, false)
c.solution.evals_stepcompleted += 1
# if snapshots
# FMIBase.snapshot!(c.solution)
# end
if !isnothing(c.progressMeter)
t = unsense(t)
dt = unsense(integrator.t) - unsense(integrator.tprev)
events = length(c.solution.events)
steps = c.solution.evals_stepcompleted
simLen = tStop - tStart
c.progressMeter.desc = "t=$(roundToLength(t, 10))s | Δt=$(roundToLength(dt, 10))s | STPs=$(steps) | EVTs=$(events) |"
#@info "$(tStart) $(tStop) $(t)"
if simLen > 0.0
ProgressMeter.update!(
c.progressMeter,
floor(Integer, 1000.0 * (t - tStart) / simLen),
)
end
end
if c != nothing
(status, enterEventMode, terminateSimulation) =
fmi2CompletedIntegratorStep(c, fmi2True)
if terminateSimulation == fmi2True
logError(c.fmu, "stepCompleted(...): FMU requested termination!")
end
if enterEventMode == fmi2True
affectFMU!(nfmu, c, integrator, -1)
end
@debug "Step completed at $(unsense(t)) with $(unsense(x))"
end
# assert_integrator_valid(integrator)
end
# [ToDo] (1) This must be in-place
# (2) getReal must be replaced with the inplace getter within c(...)
# (3) remove unsense to determine save value sensitivities
# save FMU values
function saveValues(nfmu::ME_NeuralFMU, c::FMU2Component, recordValues, _x, _t, integrator)
t = unsense(_t)
x = unsense(_x)
c.solution.evals_savevalues += 1
# ToDo: Evaluate on light-weight model (sub-model) without fmi2GetXXX or similar and the bottom ANN
evaluateModel(nfmu, c, x; t = t) # evaluate NeuralFMU (set new states)
values = fmi2GetReal(c, recordValues)
@debug "Save values @t=$(t)\nintegrator.t=$(unsense(integrator.t))\n$(values)"
# Todo set inputs
return (values...,)
end
function saveEigenvalues(
nfmu::ME_NeuralFMU,
c::FMU2Component,
_x,
_t,
integrator,
sensitivity::Symbol,
)
@assert c.state == fmi2ComponentStateContinuousTimeMode "saveEigenvalues(...):\n" *
FMIBase.ERR_MSG_CONT_TIME_MODE
c.solution.evals_saveeigenvalues += 1
A = nothing
if sensitivity == :ForwardDiff
A = ForwardDiff.jacobian(x -> evaluateModel(nfmu, c, x; t = _t), _x) # TODO: chunk_size!
elseif sensitivity == :ReverseDiff
A = ReverseDiff.jacobian(x -> evaluateModel(nfmu, c, x; t = _t), _x)
elseif sensitivity == :Zygote
A = Zygote.jacobian(x -> evaluateModel(nfmu, c, x; t = _t), _x)[1]
elseif sensitivity == :none
A = ForwardDiff.jacobian(x -> evaluateModel(nfmu, c, x; t = _t), unsense(_x))
end
eigs, _ = DifferentiableEigen.eigen(A)
return (eigs...,)
end
function fx(
nfmu::ME_NeuralFMU,
c::FMU2Component,
dx,#::Array{<:Real},
x,#::Array{<:Real},
p,#::Array,
t,
)#::Real)
if isnothing(c)
# this should never happen!
@warn "fx() called without allocated FMU instance!"
return zeros(length(x))
end
############
evaluateModel(nfmu, c, dx, x; p = p, t = t)
ignore_derivatives() do
c.solution.evals_fx_inplace += 1
end
return dx
end
function fx(
nfmu::ME_NeuralFMU,
c::FMU2Component,
x,#::Array{<:Real},
p,#::Array,
t,
)#::Real)
if c === nothing
# this should never happen!
return zeros(length(x))
end
ignore_derivatives() do
c.solution.evals_fx_outofplace += 1
end
return evaluateModel(nfmu, c, x; p = p, t = t)
end
##### EVENT HANDLING END
"""
Constructs a ME-NeuralFMU where the FMU is at an arbitrary location inside of the NN.
# Arguments
- `fmu` the considered FMU inside the NN
- `model` the NN topology (e.g. Flux.chain)
- `tspan` simulation time span
- `solver` an ODE Solver (default=`nothing`, heurisitically determine one)
# Keyword arguments
- `recordValues` additionally records internal FMU variables
"""
function ME_NeuralFMU(
fmu::FMU2,
model,
tspan,
solver = nothing;
recordValues = nothing,
saveat = nothing,
solvekwargs...,
)
if !is64(model)
model = convert64(model)
logInfo(
fmu,
"Model is not Float64, but this is necessary for (Neural)FMUs.\nModel parameters are automatically converted to Float64.",
)
end
p, re = Flux.destructure(model)
nfmu = ME_NeuralFMU{typeof(model),typeof(re)}(model, p, re)
######
nfmu.fmu = fmu
nfmu.saved_values = nothing
nfmu.recordValues = prepareValueReference(fmu, recordValues)
nfmu.tspan = tspan
nfmu.solver = solver
nfmu.saveat = saveat
nfmu.solvekwargs = solvekwargs
nfmu.parameters = nothing
######
nfmu
end
"""
Constructs a CS-NeuralFMU where the FMU is at an arbitrary location inside of the ANN.
# Arguents
- `fmu` the considered FMU inside the ANN
- `model` the ANN topology (e.g. Flux.Chain)
- `tspan` simulation time span
# Keyword arguments
- `recordValues` additionally records FMU variables
"""
function CS_NeuralFMU(fmu::FMU2, model, tspan; recordValues = [])
if !is64(model)
model = convert64(model)
logInfo(
fmu,
"Model is not Float64, but this is necessary for (Neural)FMUs.\nModel parameters are automatically converted to Float64.",
)
end
nfmu = CS_NeuralFMU{FMU2,FMU2Component}()
nfmu.fmu = fmu
nfmu.model = model
nfmu.tspan = tspan
nfmu.p, nfmu.re = Flux.destructure(nfmu.model)
return nfmu
end
function CS_NeuralFMU(fmus::Vector{<:FMU2}, model, tspan; recordValues = [])
if !is64(model)
model = convert64(model)
for fmu in fmus
logInfo(
fmu,
"Model is not Float64, but this is necessary for (Neural)FMUs.\nModel parameters are automatically converted to Float64.",
)
end
end
nfmu = CS_NeuralFMU{Vector{FMU2},Vector{FMU2Component}}()
nfmu.fmu = fmus
nfmu.model = model
nfmu.tspan = tspan
nfmu.p, nfmu.re = Flux.destructure(nfmu.model)
return nfmu
end
function checkExecTime(integrator, nfmu::ME_NeuralFMU, c, max_execution_duration::Real)
dist = max(nfmu.execution_start + max_execution_duration - time(), 0.0)
if dist <= 0.0
logInfo(
nfmu.fmu,
"Reached max execution duration ($(max_execution_duration)), terminating integration ...",
)
terminate!(integrator)
end
return 1.0
end
function getInstance(nfmu::NeuralFMU)
return hasCurrentInstance(nfmu.fmu) ? getCurrentInstance(nfmu.fmu) : nothing
end
# ToDo: Separate this: NeuralFMU creation and solving!
"""
nfmu(x_start, tspan; kwargs)
Evaluates the ME_NeuralFMU `nfmu` in the timespan given during construction or in a custom timespan from `t_start` to `t_stop` for a given start state `x_start`.
# Keyword arguments
[ToDo]
"""
function (nfmu::ME_NeuralFMU)(
x_start::Union{Array{<:Real},Nothing} = nfmu.x0,
tspan::Tuple{Float64,Float64} = nfmu.tspan;
showProgress::Bool = false,
progressDescr::String = DEFAULT_PROGRESS_DESCR,
tolerance::Union{Real,Nothing} = nothing,
parameters::Union{Dict{<:Any,<:Any},Nothing} = nothing,
p = nfmu.p,
solver = nfmu.solver,
saveEventPositions::Bool = false,
max_execution_duration::Real = -1.0,
recordValues::fmi2ValueReferenceFormat = nfmu.recordValues,
recordEigenvaluesSensitivity::Symbol = :none,
recordEigenvalues::Bool = (recordEigenvaluesSensitivity != :none),
saveat = nfmu.saveat, # ToDo: Data type
sensealg = nfmu.fmu.executionConfig.sensealg, # ToDo: AbstractSensitivityAlgorithm
writeSnapshot::Union{FMUSnapshot,Nothing} = nothing,
readSnapshot::Union{FMUSnapshot,Nothing} = nothing,
cleanSnapshots::Bool = true,
solvekwargs...,
)
if !isnothing(saveat)
if saveat[1] != tspan[1] || saveat[end] != tspan[end]
logWarning(
nfmu.fmu,
"NeuralFMU changed time interval, start time is $(tspan[1]) and stop time is $(tspan[end]), but saveat from constructor gives $(saveat[1]) and $(saveat[end]).\nPlease provide correct `saveat` via keyword with matching start/stop time.",
1,
)
saveat = collect(saveat)
while saveat[1] < tspan[1]
popfirst!(saveat)
end
while saveat[end] > tspan[end]
pop!(saveat)
end
end
end
recordValues = prepareValueReference(nfmu.fmu, recordValues)
saving = (length(recordValues) > 0)
t_start = tspan[1]
t_stop = tspan[end]
nfmu.tspan = tspan
nfmu.x0 = x_start
nfmu.p = p
ignore_derivatives() do
@debug "ME_NeuralFMU(showProgress=$(showProgress), tspan=$(tspan), x0=$(nfmu.x0))"
nfmu.firstRun = true
nfmu.tolerance = tolerance
if isnothing(parameters)
if !isnothing(nfmu.fmu.default_p_refs)
nfmu.parameters =
Dict(nfmu.fmu.default_p_refs .=> unsense(nfmu.fmu.default_p))
end
else
nfmu.parameters = parameters
end
end
callbacks = []
c = getInstance(nfmu)
@debug "ME_NeuralFMU: Starting callback..."
c = startCallback(nothing, nfmu, c, t_start, writeSnapshot, readSnapshot)
ignore_derivatives() do
c.solution = FMUSolution(c)
@debug "ME_NeuralFMU: Defining callbacks..."
# custom callbacks
for cb in nfmu.customCallbacksBefore
push!(callbacks, cb)
end
nfmu.fmu.hasStateEvents = (c.fmu.modelDescription.numberOfEventIndicators > 0)
nfmu.fmu.hasTimeEvents = (c.eventInfo.nextEventTimeDefined == fmi2True)
# time event handling
if nfmu.fmu.executionConfig.handleTimeEvents && nfmu.fmu.hasTimeEvents
timeEventCb = IterativeCallback(
(integrator) -> time_choice(nfmu, c, integrator, t_start, t_stop),
(integrator) -> affectFMU!(nfmu, c, integrator, 0),
Float64;
initial_affect = (c.eventInfo.nextEventTime == t_start), # already checked in the outer closure: c.eventInfo.nextEventTimeDefined == fmi2True
save_positions = (saveEventPositions, saveEventPositions),
)
push!(callbacks, timeEventCb)
end
# state event callback
if c.fmu.hasStateEvents && c.fmu.executionConfig.handleStateEvents
handleIndicators = nothing
# if we want a specific subset
if !isnothing(c.fmu.handleEventIndicators)
handleIndicators = c.fmu.handleEventIndicators
else # handle all
handleIndicators = collect(
UInt32(i) for i = 1:c.fmu.modelDescription.numberOfEventIndicators
)
end
numEventInds = length(handleIndicators)
if c.fmu.executionConfig.useVectorCallbacks
eventCb = VectorContinuousCallback(
(out, x, t, integrator) ->
condition!(nfmu, c, out, x, t, integrator, handleIndicators),
(integrator, idx) -> affectFMU!(nfmu, c, integrator, idx),
numEventInds;
rootfind = RightRootFind,
save_positions = (saveEventPositions, saveEventPositions),
interp_points = c.fmu.executionConfig.rootSearchInterpolationPoints,
)
push!(callbacks, eventCb)
else
for idx = 1:c.fmu.modelDescription.numberOfEventIndicators
eventCb = ContinuousCallback(
(x, t, integrator) ->
conditionSingle(nfmu, c, idx, x, t, integrator),
(integrator) -> affectFMU!(nfmu, c, integrator, idx);
rootfind = RightRootFind,
save_positions = (saveEventPositions, saveEventPositions),
interp_points = c.fmu.executionConfig.rootSearchInterpolationPoints,
)
push!(callbacks, eventCb)
end
end
end
if max_execution_duration > 0.0
terminateCb = ContinuousCallback(
(x, t, integrator) ->
checkExecTime(integrator, nfmu, c, max_execution_duration),
(integrator) -> terminate!(integrator);
save_positions = (false, false),
)
push!(callbacks, terminateCb)
logInfo(nfmu.fmu, "Setting max execeution time to $(max_execution_duration)")
end
# custom callbacks
for cb in nfmu.customCallbacksAfter
push!(callbacks, cb)
end
if showProgress
c.progressMeter =
ProgressMeter.Progress(1000; desc = progressDescr, color = :blue, dt = 1.0)
ProgressMeter.update!(c.progressMeter, 0) # show it!
else
c.progressMeter = nothing
end
# integrator step callback
stepCb = FunctionCallingCallback(
(x, t, integrator) ->
stepCompleted(nfmu, c, x, t, integrator, t_start, t_stop);
func_everystep = true,
func_start = true,
)
push!(callbacks, stepCb)
# [ToDo] Allow for AD-primitives for sensitivity analysis of recorded values
if saving
c.solution.values = SavedValues(
Float64,
Tuple{collect(Float64 for i = 1:length(recordValues))...},
)
c.solution.valueReferences = recordValues
if isnothing(saveat)
savingCB = SavingCallback(
(x, t, integrator) ->
saveValues(nfmu, c, recordValues, x, t, integrator),
c.solution.values,
)
else
savingCB = SavingCallback(
(x, t, integrator) ->
saveValues(nfmu, c, recordValues, x, t, integrator),
c.solution.values,
saveat = saveat,
)
end
push!(callbacks, savingCB)
end
if recordEigenvalues
@assert recordEigenvaluesSensitivity ∈
(:none, :ForwardDiff, :ReverseDiff, :Zygote) "Keyword `recordEigenvaluesSensitivity` must be one of (:none, :ForwardDiff, :ReverseDiff, :Zygote)"
recordEigenvaluesType = nothing
if recordEigenvaluesSensitivity == :ForwardDiff
recordEigenvaluesType = FMISensitivity.ForwardDiff.Dual
elseif recordEigenvaluesSensitivity == :ReverseDiff
recordEigenvaluesType = FMISensitivity.ReverseDiff.TrackedReal
elseif recordEigenvaluesSensitivity ∈ (:none, :Zygote)
recordEigenvaluesType = fmi2Real
end
dtypes = collect(
recordEigenvaluesType for
_ = 1:2*length(c.fmu.modelDescription.stateValueReferences)
)
c.solution.eigenvalues = SavedValues(recordEigenvaluesType, Tuple{dtypes...})
savingCB = nothing
if isnothing(saveat)
savingCB = SavingCallback(
(u, t, integrator) -> saveEigenvalues(
nfmu,
c,
u,
t,
integrator,
recordEigenvaluesSensitivity,
),
c.solution.eigenvalues,
)
else
savingCB = SavingCallback(
(u, t, integrator) -> saveEigenvalues(
nfmu,
c,
u,
t,
integrator,
recordEigenvaluesSensitivity,
),
c.solution.eigenvalues,
saveat = saveat,
)
end
push!(callbacks, savingCB)
end
end # ignore_derivatives
prob = nothing
function fx_ip(dx, x, p, t)
fx(nfmu, c, dx, x, p, t)
return nothing
end
# function fx_op(x, p, t)
# return fx(nfmu, c, x, p, t)
# end
# function fx_jac(J, x, p, t)
# J[:] = ReverseDiff.jacobian(_x -> fx_op(_x, p, t), x)
# return nothing
# end
# function jvp(Jv, v, x, p, t)
# n = length(x)
# J = similar(x, (n, n))
# fx_jac(J, x, p, t)
# Jv[:] = J * v
# return nothing
# end
# function vjp(Jv, v, x, p, t)
# n = length(x)
# J = similar(x, (n, n))
# fx_jac(J, x, p, t)
# Jv[:] = v' * J
# return nothing
# end
ff = ODEFunction{true}(fx_ip) # ; jvp=jvp, vjp=vjp, jac=fx_jac) # tgrad=nothing
prob = ODEProblem{true}(ff, nfmu.x0, nfmu.tspan, p)
# [TODO] that (using ReverseDiffAdjoint) should work now with `autodiff=false`
if isnothing(sensealg)
#if isnothing(solver)
# logWarning(nfmu.fmu, "No solver keyword detected for NeuralFMU.\nOnly relevant if you use AD: Continuous adjoint method is applied, which requires solving backward in time.\nThis might be not supported by every FMU.", 1)
# sensealg = InterpolatingAdjoint(; autojacvec=ReverseDiffVJP(true), checkpointing=true)
# elseif isimplicit(solver)
# @assert !(alg_autodiff(solver) isa AutoForwardDiff) "Implicit solver using `autodiff=true` detected for NeuralFMU.\nThis is currently not supported, please use `autodiff=false` as solver keyword.\nExample: `Rosenbrock23(autodiff=false)` instead of `Rosenbrock23()`."
# logWarning(nfmu.fmu, "Implicit solver detected for NeuralFMU.\nOnly relevant if you use AD: Continuous adjoint method is applied, which requires solving backward in time.\nThis might be not supported by every FMU.", 1)
# sensealg = InterpolatingAdjoint(; autojacvec=ReverseDiffVJP(true), checkpointing=true)
# else
sensealg = ReverseDiffAdjoint()
#end
end
args = Vector{Any}()
kwargs = Dict{Symbol,Any}(nfmu.solvekwargs..., solvekwargs...)
if !isnothing(saveat)
kwargs[:saveat] = saveat
end
ignore_derivatives() do
if !isnothing(solver)
push!(args, solver)
end
end
#kwargs[:callback]=CallbackSet(callbacks...)
#kwargs[:sensealg]=sensealg
#kwargs[:u0] = nfmu.x0 # this is because of `IntervalNonlinearProblem has no field u0`
@debug "ME_NeuralFMU: Start solving ..."
c.solution.states = solve(
prob,
args...;
callback = CallbackSet(callbacks...),
sensealg = sensealg,
u0 = nfmu.x0,
kwargs...,
)
@debug "ME_NeuralFMU: ... finished solving!"
ignore_derivatives() do
@assert !isnothing(c.solution.states) "Solving NeuralODE returned `nothing`!"
# ReverseDiff returns an array instead of an ODESolution, this needs to be corrected
# [TODO] doesn`t Array cover the TrackedArray case?
if isa(c.solution.states, TrackedArray) || isa(c.solution.states, Array)
@assert !isnothing(saveat) "Keyword `saveat` is nothing, please provide the keyword when using ReverseDiff."
t = collect(saveat)
while t[1] < tspan[1]
popfirst!(t)
end
while t[end] > tspan[end]
pop!(t)
end
u = c.solution.states
c.solution.success = (size(u) == (length(nfmu.x0), length(t)))
if size(u)[2] > 0 # at least some recorded points
c.solution.states =
build_solution(prob, solver, t, collect(u[:, i] for i = 1:size(u)[2]))
end
else
c.solution.success = (c.solution.states.retcode == ReturnCode.Success)
end
end # ignore_derivatives
@debug "ME_NeuralFMU: Stopping callback..."
# stopCB
stopCallback(nfmu, c, t_stop)
# cleanup snapshots to release memory
if cleanSnapshots
for snapshot in c.solution.snapshots
FMIBase.freeSnapshot!(snapshot)
end
c.solution.snapshots = Vector{FMUSnapshot}(undef, 0)
end
return c.solution
end
function (nfmu::ME_NeuralFMU)(x0::Union{Array{<:Real},Nothing}, t::Real; p = nothing)
c = nothing
return fx(nfmu, c, x0, p, t)
end
"""
ToDo: Docstring for Arguments, Keyword arguments, ...
Evaluates the CS_NeuralFMU in the timespan given during construction or in a custum timespan from `t_start` to `t_stop` with a given time step size `t_step`.
Via optional argument `reset`, the FMU is reset every time evaluation is started (default=`true`).
"""
function (nfmu::CS_NeuralFMU{F,C})(
inputFct,
t_step::Real,
tspan::Tuple{Float64,Float64} = nfmu.tspan;
p = nfmu.p,
tolerance::Union{Real,Nothing} = nothing,
parameters::Union{Dict{<:Any,<:Any},Nothing} = nothing,
) where {F,C}
t_start, t_stop = tspan
c = (hasCurrentInstance(nfmu.fmu) ? getCurrentInstance(nfmu.fmu) : nothing)
c, _ = prepareSolveFMU(
nfmu.fmu,
c,
fmi2TypeCoSimulation;
parameters = parameters,
t_start = t_start,
t_stop = t_stop,
tolerance = tolerance,
cleanup = true,
)
ts = collect(t_start:t_step:t_stop)
model_input = inputFct.(ts)
firstStep = true
function simStep(input)
y = nothing
if !firstStep
ignore_derivatives() do
fmi2DoStep(c, t_step)
end
else
firstStep = false
end
if p == nothing # structured, implicite parameters
y = nfmu.model(input)
else # flattened, explicite parameters
@assert !isnothing(nfmu.re) "Using explicite parameters without destructing the model."
y = nfmu.re(p)(input)
end
return y
end
valueStack = simStep.(model_input)
ignore_derivatives() do
c.solution.success = true
end
c.solution.values = SavedValues{typeof(ts[1]),typeof(valueStack[1])}(ts, valueStack)
# [ToDo] check if this is still the case for current releases of related libraries
# this is not possible in CS (pullbacks are sometimes called after the finished simulation), clean-up happens at the next call
# c = finishSolveFMU(nfmu.fmu, c, freeInstance, terminate)
return c.solution
end
function (nfmu::CS_NeuralFMU{Vector{F},Vector{C}})(
inputFct,
t_step::Real,
tspan::Tuple{Float64,Float64} = nfmu.tspan;
p = nothing,
tolerance::Union{Real,Nothing} = nothing,
parameters::Union{Vector{Union{Dict{<:Any,<:Any},Nothing}},Nothing} = nothing,
) where {F,C}
t_start, t_stop = tspan
numFMU = length(nfmu.fmu)
cs = nothing
ignore_derivatives() do
cs = Vector{Union{FMU2Component,Nothing}}(undef, numFMU)
for i = 1:numFMU
cs[i] = (
hasCurrentInstance(nfmu.fmu[i]) ? getCurrentInstance(nfmu.fmu[i]) : nothing
)
end
end
for i = 1:numFMU
cs[i], _ = prepareSolveFMU(
nfmu.fmu[i],
cs[i],
fmi2TypeCoSimulation;
parameters = parameters,
t_start = t_start,
t_stop = t_stop,
tolerance = tolerance,
cleanup = true,
)
end
solution = FMUSolution(nothing)
ts = collect(t_start:t_step:t_stop)
model_input = inputFct.(ts)
firstStep = true
function simStep(input)
y = nothing
if !firstStep
ignore_derivatives() do
for c in cs
fmi2DoStep(c, t_step)
end
end
else
firstStep = false
end
if p == nothing # structured, implicite parameters
y = nfmu.model(input)
else # flattened, explicite parameters
@assert nfmu.re != nothing "Using explicite parameters without destructing the model."
if length(p) == 1
y = nfmu.re(p[1])(input)
else
y = nfmu.re(p)(input)
end
end
return y
end
valueStack = simStep.(model_input)
ignore_derivatives() do
solution.success = true # ToDo: Check successful simulation!
end
solution.values = SavedValues{typeof(ts[1]),typeof(valueStack[1])}(ts, valueStack)
# [ToDo] check if this is still the case for current releases of related libraries
# this is not possible in CS (pullbacks are sometimes called after the finished simulation), clean-up happens at the next call
# cs = finishSolveFMU(nfmu.fmu, cs, freeInstance, terminate)
return solution
end
# adapting the Flux functions
function Flux.params(nfmu::ME_NeuralFMU; destructure::Bool = false)
if destructure
nfmu.p, nfmu.re = Flux.destructure(nfmu.model)
end
ps = Flux.params(nfmu.p)
if issense(ps)
@warn "Parameters include AD-primitives, this indicates that something did go wrong in before."
end
return ps
end
function Flux.params(nfmu::CS_NeuralFMU; destructure::Bool = false) # true)
if destructure
nfmu.p, nfmu.re = Flux.destructure(nfmu.model)
# else
# return Flux.params(nfmu.model)
end
ps = Flux.params(nfmu.p)
if issense(ps)
@warn "Parameters include AD-primitives, this indicates that something did go wrong in before."
end
return ps
end
function computeGradient!(
jac,
loss,
params,
gradient::Symbol,
chunk_size::Union{Symbol,Int},
multiObjective::Bool,
)
if gradient == :ForwardDiff
if chunk_size == :auto_forwarddiff
if multiObjective
conf = ForwardDiff.JacobianConfig(loss, params)
ForwardDiff.jacobian!(jac, loss, params, conf)
else
conf = ForwardDiff.GradientConfig(loss, params)
ForwardDiff.gradient!(jac, loss, params, conf)
end
elseif chunk_size == :auto_fmiflux
chunk_size = DEFAULT_CHUNK_SIZE
if multiObjective
conf = ForwardDiff.JacobianConfig(
loss,
params,
ForwardDiff.Chunk{min(chunk_size, length(params))}(),
)
ForwardDiff.jacobian!(jac, loss, params, conf)
else
conf = ForwardDiff.GradientConfig(
loss,
params,
ForwardDiff.Chunk{min(chunk_size, length(params))}(),
)
ForwardDiff.gradient!(jac, loss, params, conf)
end
else
if multiObjective
conf = ForwardDiff.JacobianConfig(
loss,
params,
ForwardDiff.Chunk{min(chunk_size, length(params))}(),
)
ForwardDiff.jacobian!(jac, loss, params, conf)
else
conf = ForwardDiff.GradientConfig(
loss,
params,
ForwardDiff.Chunk{min(chunk_size, length(params))}(),
)
ForwardDiff.gradient!(jac, loss, params, conf)
end
end
elseif gradient == :Zygote
if multiObjective
jac[:] = Zygote.jacobian(loss, params)[1]
else
jac[:] = Zygote.gradient(loss, params)[1]
end
elseif gradient == :ReverseDiff
if multiObjective
ReverseDiff.jacobian!(jac, loss, params)
else
ReverseDiff.gradient!(jac, loss, params)
end
elseif gradient == :FiniteDiff
if multiObjective
FiniteDiff.finite_difference_jacobian!(jac, loss, params)
else
FiniteDiff.finite_difference_gradient!(jac, loss, params)
end
else
@assert false "Unknown `gradient=$(gradient)`, supported are `:ForwardDiff`, `:Zygote`, `:FiniteDiff` and `:ReverseDiff`."
end
### check gradient is valid
# [Todo] Better!
grads = nothing
if multiObjective
grads = collect(jac[i, :] for i = 1:size(jac)[1])
else
grads = [jac]
end
all_zero = any(collect(all(iszero.(grad)) for grad in grads))
has_nan = any(collect(any(isnan.(grad)) for grad in grads))
has_nothing =
any(collect(any(isnothing.(grad)) for grad in grads)) || any(isnothing.(grads))
@assert !all_zero "Determined gradient containes only zeros.\nThis might be because the loss function is:\n(a) not sensitive regarding the model parameters or\n(b) sensitivities regarding the model parameters are not traceable via AD."
if gradient != :ForwardDiff && (has_nan || has_nothing)
@warn "Gradient determination with $(gradient) failed, because gradient contains `NaNs` and/or `nothing`.\nThis might be because the FMU is throwing redundant events, which is currently not supported.\nTrying ForwardDiff as back-up.\nIf this message gets printed (almost) every step, consider using keyword `gradient=:ForwardDiff` to fix ForwardDiff as sensitivity system."
gradient = :ForwardDiff
computeGradient!(jac, loss, params, gradient, chunk_size, multiObjective)
if multiObjective
grads = collect(jac[i, :] for i = 1:size(jac)[1])
else
grads = [jac]
end
end
has_nan = any(collect(any(isnan.(grad)) for grad in grads))
has_nothing =
any(collect(any(isnothing.(grad)) for grad in grads)) || any(isnothing.(grads))
@assert !has_nan "Gradient determination with $(gradient) failed, because gradient contains `NaNs`.\nNo back-up options available."
@assert !has_nothing "Gradient determination with $(gradient) failed, because gradient contains `nothing`.\nNo back-up options available."
return nothing
end
lk_TrainApply = ReentrantLock()
function trainStep(
loss,
params,
gradient,
chunk_size,
optim::FMIFlux.AbstractOptimiser,
printStep,
proceed_on_assert,
cb,
multiObjective,
)
global lk_TrainApply
#try
for j = 1:length(params)
step = FMIFlux.apply!(optim, params[j])
lock(lk_TrainApply) do
params[j] .-= step
if printStep
@info "Step: min(abs()) = $(min(abs.(step)...)) max(abs()) = $(max(abs.(step)...))"
end
end
end
# catch e
# if proceed_on_assert
# msg = "$(e)"
# msg = length(msg) > 4096 ? first(msg, 4096) * "..." : msg
# @error "Training asserted, but continuing: $(msg)"
# else
# throw(e)
# end
# end
if cb != nothing
if isa(cb, AbstractArray)
for _cb in cb
_cb()
end
else
cb()
end
end
end
"""
train!(loss, neuralFMU::Union{ME_NeuralFMU, CS_NeuralFMU}, data, optim; gradient::Symbol=:ReverseDiff, kwargs...)
A function analogous to Flux.train! but with additional features and explicit parameters (faster).
# Arguments
- `loss` a loss function in the format `loss(p)`
- `neuralFMU` a object holding the neuralFMU with its parameters
- `data` the training data (or often an iterator)
- `optim` the optimizer used for training
# Keywords
- `gradient` a symbol determining the AD-library for gradient computation, available are `:ForwardDiff`, `:Zygote` and :ReverseDiff (default)
- `cb` a custom callback function that is called after every training step (default `nothing`)
- `chunk_size` the chunk size for AD using ForwardDiff (ignored for other AD-methods) (default `:auto_fmiflux`)
- `printStep` a boolean determining wheater the gradient min/max is printed after every step (for gradient debugging) (default `false`)
- `proceed_on_assert` a boolean that determins wheater to throw an ecxeption on error or proceed training and just print the error (default `false`)
- `multiThreading`: a boolean that determins if multiple gradients are generated in parallel (default `false`)
- `multiObjective`: set this if the loss function returns multiple values (multi objective optimization), currently gradients are fired to the optimizer one after another (default `false`)
"""
function train!(
loss,
neuralFMU::Union{ME_NeuralFMU,CS_NeuralFMU},
data,
optim;
gradient::Symbol = :ReverseDiff,
kwargs...,
)
params = Flux.params(neuralFMU)
snapshots = neuralFMU.snapshots
# [Note] :ReverseDiff, :Zygote need it for state change sampling and the rrule
# :ForwardDiff needs it for state change sampling
neuralFMU.snapshots = true
_train!(loss, params, data, optim; gradient = gradient, kwargs...)
neuralFMU.snapshots = snapshots
neuralFMU.p = unsense(neuralFMU.p)
return nothing
end
# Dispatch for FMIFlux.jl [FMIFlux.AbstractOptimiser]
function _train!(
loss,
params::Union{Flux.Params,Zygote.Params,AbstractVector{<:AbstractVector{<:Real}}},
data,
optim::FMIFlux.AbstractOptimiser;
gradient::Symbol = :ReverseDiff,
cb = nothing,
chunk_size::Union{Integer,Symbol} = :auto_fmiflux,
printStep::Bool = false,
proceed_on_assert::Bool = false,
multiThreading::Bool = false,
multiObjective::Bool = false,
)
if length(params) <= 0 || length(params[1]) <= 0
@warn "train!(...): Empty parameter array, training on an empty parameter array doesn't make sense."
return
end
if multiThreading && Threads.nthreads() == 1
@warn "train!(...): Multi-threading is set via flag `multiThreading=true`, but this Julia process does not have multiple threads. This will not result in a speed-up. Please spawn Julia in multi-thread mode to speed-up training."
end
_trainStep =
(i,) -> trainStep(
loss,
params,
gradient,
chunk_size,
optim,
printStep,
proceed_on_assert,
cb,
multiObjective,
)
if multiThreading
ThreadPools.qforeach(_trainStep, 1:length(data))
else
foreach(_trainStep, 1:length(data))
end
end
# Dispatch for Flux.jl [Flux.Optimise.AbstractOptimiser]
function _train!(
loss,
params::Union{Flux.Params,Zygote.Params,AbstractVector{<:AbstractVector{<:Real}}},
data,
optim::Flux.Optimise.AbstractOptimiser;
gradient::Symbol = :ReverseDiff,
chunk_size::Union{Integer,Symbol} = :auto_fmiflux,
multiObjective::Bool = false,
kwargs...,
)
grad_buffer = nothing
if multiObjective
dim = loss(params[1])
grad_buffer = zeros(Float64, length(params[1]), length(dim))
else
grad_buffer = zeros(Float64, length(params[1]))
end
grad_fun! = (G, p) -> computeGradient!(G, loss, p, gradient, chunk_size, multiObjective)
_optim = FluxOptimiserWrapper(optim, grad_fun!, grad_buffer)
_train!(
loss,
params,
data,
_optim;
gradient = gradient,
chunk_size = chunk_size,
multiObjective = multiObjective,
kwargs...,
)
end
# Dispatch for Optim.jl [Optim.AbstractOptimizer]
function _train!(
loss,
params::Union{Flux.Params,Zygote.Params,AbstractVector{<:AbstractVector{<:Real}}},
data,
optim::Optim.AbstractOptimizer;
gradient::Symbol = :ReverseDiff,
chunk_size::Union{Integer,Symbol} = :auto_fmiflux,
multiObjective::Bool = false,
kwargs...,
)
if length(params) <= 0 || length(params[1]) <= 0
@warn "train!(...): Empty parameter array, training on an empty parameter array doesn't make sense."
return
end
grad_fun! = (G, p) -> computeGradient!(G, loss, p, gradient, chunk_size, multiObjective)
_optim = OptimOptimiserWrapper(optim, grad_fun!, loss, params[1])
_train!(
loss,
params,
data,
_optim;
gradient = gradient,
chunk_size = chunk_size,
multiObjective = multiObjective,
kwargs...,
)
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 2510 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
import Flux
import Optim
abstract type AbstractOptimiser end
### Optim.jl ###
struct OptimOptimiserWrapper{G} <: AbstractOptimiser
optim::Optim.AbstractOptimizer
grad_fun!::G
state::Union{Optim.AbstractOptimizerState,Nothing}
d::Union{Optim.OnceDifferentiable,Nothing}
options::Any
function OptimOptimiserWrapper(
optim::Optim.AbstractOptimizer,
grad_fun!::G,
loss,
params,
) where {G}
options = Optim.Options(
outer_iterations = 1,
iterations = 1,
g_calls_limit = 1,
f_calls_limit = 5,
)
# should be ignored anyway, because function `g!` is given
autodiff = :forward # = ::finite
inplace = true
d = Optim.promote_objtype(optim, params, autodiff, inplace, loss, grad_fun!)
state = Optim.initial_state(optim, options, d, params)
return new{G}(optim, grad_fun!, state, d, options)
end
end
export OptimOptimiserWrapper
function apply!(optim::OptimOptimiserWrapper, params)
res = Optim.optimize(optim.d, params, optim.optim, optim.options, optim.state)
step = params .- Optim.minimizer(res)
return step
end
### Flux.Optimisers ###
struct FluxOptimiserWrapper{G} <: AbstractOptimiser
optim::Flux.Optimise.AbstractOptimiser
grad_fun!::G
grad_buffer::Union{AbstractVector{Float64},AbstractMatrix{Float64}}
multiGrad::Bool
function FluxOptimiserWrapper(
optim::Flux.Optimise.AbstractOptimiser,
grad_fun!::G,
grad_buffer::AbstractVector{Float64},
) where {G}
return new{G}(optim, grad_fun!, grad_buffer, false)
end
function FluxOptimiserWrapper(
optim::Flux.Optimise.AbstractOptimiser,
grad_fun!::G,
grad_buffer::AbstractMatrix{Float64},
) where {G}
return new{G}(optim, grad_fun!, grad_buffer, true)
end
end
export FluxOptimiserWrapper
function apply!(optim::FluxOptimiserWrapper, params)
optim.grad_fun!(optim.grad_buffer, params)
if optim.multiGrad
return collect(
Flux.Optimise.apply!(optim.optim, params, optim.grad_buffer[:, i]) for
i = 1:size(optim.grad_buffer)[2]
)
else
return Flux.Optimise.apply!(optim.optim, params, optim.grad_buffer)
end
end
### generic FMIFlux.AbstractOptimiser ###
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 13760 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
import Printf
using Colors
abstract type BatchScheduler end
# ToDo: DocString update.
"""
Computes all batch element losses. Picks the batch element with the greatest loss as next training element.
"""
mutable struct WorstElementScheduler <: BatchScheduler
### mandatory ###
step::Integer
elementIndex::Integer
applyStep::Integer
plotStep::Integer
batch::Any
neuralFMU::NeuralFMU
losses::Vector{Float64}
logLoss::Bool
### type specific ###
lossFct::Any
runkwargs::Any
printMsg::String
updateStep::Integer
excludeIndices::Any
function WorstElementScheduler(
neuralFMU::NeuralFMU,
batch,
lossFct = Flux.Losses.mse;
applyStep::Integer = 1,
plotStep::Integer = 1,
updateStep::Integer = 1,
excludeIndices = nothing,
)
inst = new()
inst.neuralFMU = neuralFMU
inst.step = 0
inst.elementIndex = 0
inst.batch = batch
inst.lossFct = lossFct
inst.applyStep = applyStep
inst.plotStep = plotStep
inst.losses = []
inst.logLoss = false
inst.printMsg = ""
inst.updateStep = updateStep
inst.excludeIndices = excludeIndices
return inst
end
end
# ToDo: DocString update.
"""
Computes all batch element losses. Picks the batch element with the greatest accumulated loss as next training element. If picked, accumulated loss is resetted.
(Prevents starvation of batch elements with little loss)
"""
mutable struct LossAccumulationScheduler <: BatchScheduler
### mandatory ###
step::Integer
elementIndex::Integer
applyStep::Integer
plotStep::Integer
batch::Any
neuralFMU::NeuralFMU
losses::Vector{Float64}
logLoss::Bool
### type specific ###
lossFct::Any
runkwargs::Any
printMsg::String
lossAccu::Array{<:Real}
updateStep::Integer
function LossAccumulationScheduler(
neuralFMU::NeuralFMU,
batch,
lossFct = Flux.Losses.mse;
applyStep::Integer = 1,
plotStep::Integer = 1,
updateStep::Integer = 1,
)
inst = new()
inst.neuralFMU = neuralFMU
inst.step = 0
inst.elementIndex = 0
inst.batch = batch
inst.lossFct = lossFct
inst.applyStep = applyStep
inst.plotStep = plotStep
inst.updateStep = updateStep
inst.losses = []
inst.logLoss = false
inst.printMsg = ""
inst.lossAccu = zeros(length(batch))
return inst
end
end
# ToDo: DocString update.
"""
Computes all batch element losses. Picks the batch element with the greatest grow in loss (derivative) as next training element.
"""
mutable struct WorstGrowScheduler <: BatchScheduler
### mandatory ###
step::Integer
elementIndex::Integer
applyStep::Integer
plotStep::Integer
batch::Any
neuralFMU::NeuralFMU
losses::Vector{Float64}
logLoss::Bool
### type specific ###
lossFct::Any
runkwargs::Any
printMsg::String
function WorstGrowScheduler(
neuralFMU::NeuralFMU,
batch,
lossFct = Flux.Losses.mse;
applyStep::Integer = 1,
plotStep::Integer = 1,
)
inst = new()
inst.neuralFMU = neuralFMU
inst.step = 0
inst.elementIndex = 0
inst.batch = batch
inst.lossFct = lossFct
inst.applyStep = applyStep
inst.plotStep = plotStep
inst.losses = []
inst.logLoss = true # this is because this scheduler estimates derivatives
inst.printMsg = ""
return inst
end
end
# ToDo: DocString update.
"""
Picks a random batch element as next training element.
"""
mutable struct RandomScheduler <: BatchScheduler
### mandatory ###
step::Integer
elementIndex::Integer
applyStep::Integer
plotStep::Integer
batch::Any
neuralFMU::NeuralFMU
losses::Vector{Float64}
logLoss::Bool
### type specific ###
printMsg::String
function RandomScheduler(
neuralFMU::NeuralFMU,
batch;
applyStep::Integer = 1,
plotStep::Integer = 1,
)
inst = new()
inst.neuralFMU = neuralFMU
inst.step = 0
inst.elementIndex = 0
inst.batch = batch
inst.applyStep = applyStep
inst.plotStep = plotStep
inst.losses = []
inst.logLoss = false
inst.printMsg = ""
return inst
end
end
# ToDo: DocString update.
"""
Sequentially runs over all elements.
"""
mutable struct SequentialScheduler <: BatchScheduler
### mandatory ###
step::Integer
elementIndex::Integer
applyStep::Integer
plotStep::Integer
batch::Any
neuralFMU::NeuralFMU
losses::Vector{Float64}
logLoss::Bool
### type specific ###
printMsg::String
function SequentialScheduler(
neuralFMU::NeuralFMU,
batch;
applyStep::Integer = 1,
plotStep::Integer = 1,
)
inst = new()
inst.neuralFMU = neuralFMU
inst.step = 0
inst.elementIndex = 0
inst.batch = batch
inst.applyStep = applyStep
inst.plotStep = plotStep
inst.losses = []
inst.logLoss = false
inst.printMsg = ""
return inst
end
end
function initialize!(scheduler::BatchScheduler; print::Bool = true, runkwargs...)
lastIndex = 0
scheduler.step = 0
scheduler.elementIndex = 0
if hasfield(typeof(scheduler), :runkwargs)
scheduler.runkwargs = runkwargs
end
scheduler.elementIndex = apply!(scheduler; print = print)
if scheduler.plotStep > 0
plot(scheduler, lastIndex)
end
end
function update!(scheduler::BatchScheduler; print::Bool = true)
lastIndex = scheduler.elementIndex
scheduler.step += 1
if scheduler.applyStep > 0 && scheduler.step % scheduler.applyStep == 0
scheduler.elementIndex = apply!(scheduler; print = print)
end
# max/avg error
num = length(scheduler.batch)
losssum = 0.0
avgsum = 0.0
maxe = 0.0
for i = 1:num
l = nominalLoss(scheduler.batch[i])
l = l == Inf ? 0.0 : l
losssum += l
avgsum += l / num
if l > maxe
maxe = l
end
end
push!(scheduler.losses, losssum)
if print
scheduler.printMsg = "AVG: $(roundToLength(avgsum, 8)) | MAX: $(roundToLength(maxe, 8)) | SUM: $(roundToLength(losssum, 8))"
@info scheduler.printMsg
end
if scheduler.plotStep > 0 && scheduler.step % scheduler.plotStep == 0
plot(scheduler, lastIndex)
end
end
function plot(scheduler::BatchScheduler, lastIndex::Integer)
num = length(scheduler.batch)
xs = 1:num
ys = collect((nominalLoss(b) != Inf ? nominalLoss(b) : 0.0) for b in scheduler.batch)
ys_shadow = collect(
(length(b.losses) > 1 ? nominalLoss(b.losses[end-1]) : 1e-16) for
b in scheduler.batch
)
title = "[$(scheduler.step)]"
if hasfield(typeof(scheduler), :printMsg)
title = title * " " * scheduler.printMsg
end
fig = Plots.plot(;
layout = Plots.grid(2, 1),
size = (480, 960),
xlabel = "Batch ID",
ylabel = "Loss",
background_color_legend = colorant"rgba(255,255,255,0.5)",
title = title,
)
if hasfield(typeof(scheduler), :lossAccu)
normScale = max(ys..., ys_shadow...) / max(scheduler.lossAccu...)
Plots.bar!(
fig[1],
xs,
scheduler.lossAccu .* normScale,
label = "Accum. loss (norm.)",
color = :blue,
bar_width = 1.0,
alpha = 0.2,
)
end
good = []
bad = []
for i = 1:num
if ys[i] > ys_shadow[i]
push!(bad, i)
else
push!(good, i)
end
end
Plots.bar!(
fig[1],
xs[good],
ys[good],
label = "Loss (better)",
color = :green,
bar_width = 1.0,
)
Plots.bar!(
fig[1],
xs[bad],
ys[bad],
label = "Loss (worse)",
color = :orange,
bar_width = 1.0,
)
for i = 1:length(ys_shadow)
Plots.plot!(
fig[1],
[xs[i] - 0.5, xs[i] + 0.5],
[ys_shadow[i], ys_shadow[i]],
label = (i == 1 ? "Last loss" : :none),
linewidth = 2,
color = :black,
)
end
if lastIndex > 0
Plots.plot!(
fig[1],
[lastIndex],
[0.0],
color = :pink,
marker = :circle,
label = "Current ID [$(lastIndex)]",
markersize = 5.0,
) # current batch element
end
Plots.plot!(
fig[1],
[scheduler.elementIndex],
[0.0],
color = :pink,
marker = :circle,
label = "Next ID [$(scheduler.elementIndex)]",
markersize = 3.0,
) # next batch element
Plots.plot!(fig[2], 1:length(scheduler.losses), scheduler.losses; yaxis = :log)
display(fig)
end
"""
Rounds a given `number` to a string with a maximum length of `len`.
Exponentials are used if suitable.
"""
function roundToLength(number::Real, len::Integer)
@assert len >= 5 "`len` must be at least `5`."
if number == 0.0
return "0.0"
end
isneg = false
if number < 0.0
isneg = true
number = -number
len -= 1 # we need one digit for the "-"
end
expLen = 0
if abs(number) <= 1.0
expLen = Integer(floor(log10(1.0 / number))) + 1
else
expLen = Integer(floor(log10(number))) + 1
end
len -= 4 # spaces needed for "+" (or "-"), "e", "." and leading number
if expLen >= 100
len -= 3 # 3 spaces needed for large exponent
else
len -= 2 # 2 spaces needed for regular exponent
end
if isneg
number = -number
end
return Printf.format(Printf.Format("%.$(len)e"), number)
end
function apply!(scheduler::WorstElementScheduler; print::Bool = true)
avgsum = 0.0
losssum = 0.0
maxe = 0.0
maxind = 0
updateAll = (scheduler.step % scheduler.updateStep == 0)
num = length(scheduler.batch)
for i = 1:num
l = (nominalLoss(scheduler.batch[i]) != Inf ? nominalLoss(scheduler.batch[i]) : 0.0)
if updateAll
FMIFlux.run!(scheduler.neuralFMU, scheduler.batch[i]; scheduler.runkwargs...)
FMIFlux.loss!(
scheduler.batch[i],
scheduler.lossFct;
logLoss = scheduler.logLoss,
)
l = nominalLoss(scheduler.batch[i])
end
losssum += l
avgsum += l / num
if isnothing(scheduler.excludeIndices) || i ∉ scheduler.excludeIndices
if l > maxe
maxe = l
maxind = i
end
end
end
return maxind
end
function apply!(scheduler::LossAccumulationScheduler; print::Bool = true)
avgsum = 0.0
losssum = 0.0
maxe = 0.0
nextind = 1
# reset current accu loss
if scheduler.elementIndex > 0
scheduler.lossAccu[scheduler.elementIndex] = 0.0
end
updateAll = (scheduler.step % scheduler.updateStep == 0)
num = length(scheduler.batch)
for i = 1:num
l = (nominalLoss(scheduler.batch[i]) != Inf ? nominalLoss(scheduler.batch[i]) : 0.0)
if updateAll
FMIFlux.run!(scheduler.neuralFMU, scheduler.batch[i]; scheduler.runkwargs...)
FMIFlux.loss!(
scheduler.batch[i],
scheduler.lossFct;
logLoss = scheduler.logLoss,
)
l = nominalLoss(scheduler.batch[i])
end
scheduler.lossAccu[i] += l
losssum += l
avgsum += l / num
if l > maxe
maxe = l
end
end
# find largest accumulated loss
for i = 1:num
if scheduler.lossAccu[i] > scheduler.lossAccu[nextind]
nextind = i
end
end
return nextind
end
function apply!(scheduler::WorstGrowScheduler; print::Bool = true)
avgsum = 0.0
losssum = 0.0
maxe = 0.0
maxe_der = -Inf
maxind = 0
num = length(scheduler.batch)
for i = 1:num
FMIFlux.run!(scheduler.neuralFMU, scheduler.batch[i]; scheduler.runkwargs...)
l = FMIFlux.loss!(
scheduler.batch[i],
scheduler.lossFct;
logLoss = scheduler.logLoss,
)
l_der = l # fallback for first run (greatest error)
if length(scheduler.batch[i].losses) >= 2
l_der = (l - nominalLoss(scheduler.batch[i].losses[end-1]))
end
losssum += l
avgsum += l / num
if l > maxe
maxe = l
end
if l_der > maxe_der
maxe_der = l_der
maxind = i
end
end
return maxind
end
function apply!(scheduler::RandomScheduler; print::Bool = true)
next = rand(1:length(scheduler.batch))
if print
@info "Current step: $(scheduler.step) | Current element=$(scheduler.elementIndex) | Next element=$(next)"
end
return next
end
function apply!(scheduler::SequentialScheduler; print::Bool = true)
next = scheduler.elementIndex + 1
if next > length(scheduler.batch)
next = 1
end
if print
@info "Current step: $(scheduler.step) | Current element=$(scheduler.elementIndex) | Next element=$(next)"
end
return next
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 2203 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using FMIFlux.Flux
import Random
Random.seed!(1234);
t_start = 0.0
t_step = 0.01
t_stop = 50.0
tData = t_start:t_step:t_stop
# generate training data
posData, velData, accData = syntTrainingData(tData)
# load FMU for NeuralFMU
fmu = loadFMU("SpringPendulum1D", EXPORTINGTOOL, EXPORTINGVERSION; type = :ME)
using FMIFlux.FMIImport
using FMIFlux.FMIImport.FMICore
# loss function for training
losssum_single = function (p)
global problem, X0, posData
solution = problem(X0; p = p, showProgress = false, saveat = tData)
if !solution.success
return Inf
end
posNet = getState(solution, 1; isIndex = true)
return Flux.Losses.mse(posNet, posData)
end
losssum_multi = function (p)
global problem, X0, posData
solution = problem(X0; p = p, showProgress = false, saveat = tData)
if !solution.success
return [Inf, Inf]
end
posNet = getState(solution, 1; isIndex = true)
velNet = getState(solution, 2; isIndex = true)
return [Flux.Losses.mse(posNet, posData), Flux.Losses.mse(velNet, velData)]
end
numStates = length(fmu.modelDescription.stateValueReferences)
c1 = CacheLayer()
c2 = CacheRetrieveLayer(c1)
# the "Chain" for training
net = Chain(
x -> fmu(; x = x, dx_refs = :all),
dx -> c1(dx),
Dense(numStates, 12, tanh),
Dense(12, 1, identity),
dx -> c2(1, dx[1]),
)
solver = Tsit5()
problem = ME_NeuralFMU(fmu, net, (t_start, t_stop), solver; saveat = tData)
@test problem != nothing
# before
p_net = Flux.params(problem)
lossBefore = losssum_single(p_net[1])
# single objective
optim = OPTIMISER(ETA)
FMIFlux.train!(
losssum_single,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
gradient = GRADIENT,
)
# multi objective
# lastLoss = sum(losssum_multi(p_net[1]))
# optim = OPTIMISER(ETA)
# FMIFlux.train!(losssum_multi, problem, Iterators.repeated((), NUMSTEPS), optim; gradient=GRADIENT, multiObjective=true)
# after
lossAfter = losssum_single(p_net[1])
@test lossAfter < lossBefore
@test length(fmu.components) <= 1
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 322 | using PkgEval
using FMIFlux
using Test
config = Configuration(; julia = "1.10", time_limit = 120 * 60);
package = Package(; name = "FMIFlux");
@info "PkgEval"
result = evaluate([config], [package])
@info "Result"
println(result)
@info "Log"
println(result[1, :log])
@test result[1, :status] == :ok
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 2526 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
using DifferentialEquations: Tsit5
import Random
Random.seed!(1234);
t_start = 0.0
t_step = 0.01
t_stop = 5.0
tData = t_start:t_step:t_stop
# generate training data
posData, velData, accData = syntTrainingData(tData)
# load FMU for NeuralFMU
# [TODO] Replace by a suitable discontinuous FMU
fmu = loadFMU("SpringPendulum1D", EXPORTINGTOOL, EXPORTINGVERSION; type = :ME)
using FMIFlux.FMIImport
using FMIFlux.FMIImport.FMICore
c = fmi2Instantiate!(fmu)
fmi2SetupExperiment(c, 0.0, 1.0)
fmi2EnterInitializationMode(c)
fmi2ExitInitializationMode(c)
p_refs = fmu.modelDescription.parameterValueReferences
p = fmi2GetReal(c, p_refs)
# loss function for training
losssum = function (p)
#@info "$p"
global problem, X0, posData, solution
solution = problem(X0; p = p, showProgress = true, saveat = tData)
if !solution.success
return Inf
end
posNet = getState(solution, 1; isIndex = true)
return Flux.Losses.mse(posNet, posData)
end
numStates = length(fmu.modelDescription.stateValueReferences)
# the "Chain" for training
net = Chain(FMUParameterRegistrator(fmu, p_refs, p), x -> fmu(x = x, dx_refs = :all)) # , fmuLayer(p))
optim = OPTIMISER(ETA)
solver = Tsit5()
problem = ME_NeuralFMU(fmu, net, (t_start, t_stop), solver)
problem.modifiedState = false
@test problem != nothing
solutionBefore = problem(X0; saveat = tData)
@test solutionBefore.success
@test length(solutionBefore.states.t) == length(tData)
@test solutionBefore.states.t[1] == t_start
@test solutionBefore.states.t[end] == t_stop
# train it ...
p_net = Flux.params(problem)
@test length(p_net) == 1
@test length(p_net[1]) == 7
lossBefore = losssum(p_net[1])
@info "Start-Loss for net: $(lossBefore)"
# [ToDo] Discontinuous system?
# j_fin = FiniteDiff.finite_difference_gradient(losssum, p_net[1])
# j_fwd = ForwardDiff.gradient(losssum, p_net[1])
# j_rwd = ReverseDiff.gradient(losssum, p_net[1])
FMIFlux.train!(
losssum,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
gradient = GRADIENT,
)
# check results
solutionAfter = problem(X0; saveat = tData)
@test solutionAfter.success
@test length(solutionAfter.states.t) == length(tData)
@test solutionAfter.states.t[1] == t_start
@test solutionAfter.states.t[end] == t_stop
lossAfter = losssum(p_net[1])
@test lossAfter < lossBefore
@test length(fmu.components) <= 1
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 1645 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
import Random
Random.seed!(1234);
t_start = 0.0
t_step = 0.01
t_stop = 5.0
tData = t_start:t_step:t_stop
# generate training data
posData, velData, accData = syntTrainingData(tData)
fmu = loadFMU("SpringPendulumExtForce1D", EXPORTINGTOOL, EXPORTINGVERSION; type = :CS)
# sine(t) as external force
extForce = function (t)
return [sin(t)]
end
# loss function for training
losssum = function (p)
solution = problem(extForce, t_step; p = p)
if !solution.success
return Inf
end
accNet = getValue(solution, 1; isIndex = true)
Flux.Losses.mse(accNet, accData)
end
# NeuralFMU setup
numInputs = length(fmu.modelDescription.inputValueReferences)
numOutputs = length(fmu.modelDescription.outputValueReferences)
net = Chain(
u -> fmu(;
u_refs = fmu.modelDescription.inputValueReferences,
u = u,
y_refs = fmu.modelDescription.outputValueReferences,
),
Dense(numOutputs, 16, tanh; init = Flux.identity_init),
Dense(16, 16, tanh; init = Flux.identity_init),
Dense(16, numOutputs; init = Flux.identity_init),
)
problem = CS_NeuralFMU(fmu, net, (t_start, t_stop))
@test problem != nothing
# train it ...
p_net = Flux.params(problem)
lossBefore = losssum(p_net[1])
optim = OPTIMISER(ETA)
FMIFlux.train!(
losssum,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
gradient = GRADIENT,
)
lossAfter = losssum(p_net[1])
@test lossAfter < lossBefore
@test length(fmu.components) <= 1
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 6475 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
using DifferentialEquations
import Random
Random.seed!(1234);
t_start = 0.0
t_step = 0.01
t_stop = 5.0
tData = t_start:t_step:t_stop
# generate training data
posData, velData, accData = syntTrainingData(tData)
# load FMU for NeuralFMU
fmu = loadFMU("SpringPendulum1D", EXPORTINGTOOL, EXPORTINGVERSION; type = :ME)
# loss function for training
losssum = function (p)
global problem, X0, posData
solution = problem(X0; p = p, saveat = tData)
if !solution.success
return Inf
end
posNet = getState(solution, 1; isIndex = true)
velNet = getState(solution, 2; isIndex = true)
return Flux.Losses.mse(posNet, posData) + Flux.Losses.mse(velNet, velData)
end
numStates = length(fmu.modelDescription.stateValueReferences)
# some NeuralFMU setups
nets = []
c1 = CacheLayer()
c2 = CacheRetrieveLayer(c1)
c3 = CacheLayer()
c4 = CacheRetrieveLayer(c3)
init = Flux.glorot_uniform
getVRs = [stringToValueReference(fmu, "mass.s")]
numGetVRs = length(getVRs)
y = zeros(fmi2Real, numGetVRs)
setVRs = [stringToValueReference(fmu, "mass.m")]
numSetVRs = length(setVRs)
setVal = [1.1]
# 1. default ME-NeuralFMU (learn dynamics and states, almost-neutral setup, parameter count << 100)
net = Chain(
x -> c1(x),
Dense(numStates, 1, tanh; init = init),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 2. default ME-NeuralFMU (learn dynamics)
net = Chain(
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 3. default ME-NeuralFMU (learn states)
net = Chain(
x -> c1(x),
Dense(numStates, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
)
push!(nets, net)
# 4. default ME-NeuralFMU (learn dynamics and states)
net = Chain(
x -> c1(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh, init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh, init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 5. NeuralFMU with hard setting time to 0.0
net = Chain(
states -> fmu(; x = states, t = 0.0, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 6. NeuralFMU with additional getter
net = Chain(
x -> fmu(; x = x, y_refs = getVRs, dx_refs = :all),
x -> c3(x),
Dense(numStates + numGetVRs, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 7. NeuralFMU with additional setter
net = Chain(
x -> fmu(; x = x, u_refs = setVRs, u = setVal, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 8. NeuralFMU with additional setter and getter
net = Chain(
x -> fmu(; x = x, u_refs = setVRs, u = setVal, y_refs = getVRs, dx_refs = :all),
x -> c3(x),
Dense(numStates + numGetVRs, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 9. an empty NeuralFMU (this does only make sense for debugging)
net = Chain(x -> fmu(x = x, dx_refs = :all))
push!(nets, net)
solvers = [Tsit5()]#, Rosenbrock23(autodiff=false)]
for solver in solvers
@testset "Solver: $(solver)" begin
for i = 1:length(nets)
@testset "Net setup $(i)/$(length(nets)) (Continuous NeuralFMU)" begin
global nets, problem, iterCB
global LAST_LOSS, FAILED_GRADIENTS
# if i ∈ (1, 3, 4)
# @warn "Currently skipping nets $(i) ∈ (1, 3, 4)"
# continue
# end
optim = OPTIMISER(ETA)
net = nets[i]
problem = ME_NeuralFMU(fmu, net, (t_start, t_stop), solver)
@test problem != nothing
# [Note] this is not needed from a mathematical perspective, because the system is continuous differentiable
if i ∈ (1, 3, 4)
problem.modifiedState = true
end
# train it ...
p_net = Flux.params(problem)
@test length(p_net) == 1
solutionBefore = problem(X0; p = p_net[1], saveat = tData)
if solutionBefore.success
@test length(solutionBefore.states.t) == length(tData)
@test solutionBefore.states.t[1] == t_start
@test solutionBefore.states.t[end] == t_stop
end
LAST_LOSS = losssum(p_net[1])
@info "Start-Loss for net #$i: $(LAST_LOSS)"
if length(p_net[1]) == 0
@info "The following warning is not an issue, because training on zero parameters must throw a warning:"
end
FAILED_GRADIENTS = 0
FMIFlux.train!(
losssum,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
gradient = GRADIENT,
cb = () -> callback(p_net),
)
@info "Failed Gradients: $(FAILED_GRADIENTS) / $(NUMSTEPS)"
@test FAILED_GRADIENTS <= FAILED_GRADIENTS_QUOTA * NUMSTEPS
# check results
solutionAfter = problem(X0; p = p_net[1], saveat = tData)
if solutionAfter.success
@test length(solutionAfter.states.t) == length(tData)
@test solutionAfter.states.t[1] == t_start
@test solutionAfter.states.t[end] == t_stop
end
end
end
end
end
@test length(fmu.components) <= 1
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 7919 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
using DifferentialEquations
import Random
Random.seed!(1234);
t_start = 0.0
t_step = 0.01
t_stop = 5.0
tData = t_start:t_step:t_stop
# generate training data
posData = collect(abs(cos(u .* 1.0)) for u in tData) * 2.0
fmu = loadFMU("BouncingBall1D", "Dymola", "2023x"; type = :ME)
# loss function for training
losssum = function (p)
global problem, X0, posData
solution = problem(X0; p = p, saveat = tData)
if !solution.success
return Inf
end
posNet = getState(solution, 1; isIndex = true)
#velNet = getState(solution, 2; isIndex=true)
return Flux.Losses.mse(posNet, posData) #+ Flux.Losses.mse(velNet, velData)
end
numStates = length(fmu.modelDescription.stateValueReferences)
# some NeuralFMU setups
nets = []
c1 = CacheLayer()
c2 = CacheRetrieveLayer(c1)
c3 = CacheLayer()
c4 = CacheRetrieveLayer(c3)
init = Flux.glorot_uniform
getVRs = [stringToValueReference(fmu, "mass_s")]
numGetVRs = length(getVRs)
y = zeros(fmi2Real, numGetVRs)
setVRs = [stringToValueReference(fmu, "damping")]
numSetVRs = length(setVRs)
setVal = [0.8]
# 1. default ME-NeuralFMU (learn dynamics and states, almost-neutral setup, parameter count << 100)
net1 = function ()
net = Chain(
x -> c1(x),
Dense(numStates, 1, tanh; init = init),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 1, tanh; init = init),
x -> c4(1, x[1]),
)
end
push!(nets, net1)
# 2. default ME-NeuralFMU (learn dynamics)
net2 = function ()
net = Chain(
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
end
push!(nets, net2)
# 3. default ME-NeuralFMU (learn states)
net3 = function ()
net = Chain(
x -> c1(x),
Dense(numStates, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
)
end
push!(nets, net3)
# 4. default ME-NeuralFMU (learn dynamics and states)
net4 = function ()
net = Chain(
x -> c1(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh, init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh, init = init),
x -> c4(1, x[1]),
)
end
push!(nets, net4)
# 5. NeuralFMU with hard setting time to 0.0
net5 = function ()
net = Chain(
states -> fmu(; x = states, t = 0.0, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
end
push!(nets, net5)
# 6. NeuralFMU with additional getter
net6 = function ()
net = Chain(
x -> fmu(; x = x, y_refs = getVRs, dx_refs = :all),
x -> c3(x),
Dense(numStates + numGetVRs, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
end
push!(nets, net6)
# 7. NeuralFMU with additional setter
net7 = function ()
net = Chain(
x -> fmu(; x = x, u_refs = setVRs, u = setVal, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
end
push!(nets, net7)
# 8. NeuralFMU with additional setter and getter
net8 = function ()
net = Chain(
x -> fmu(; x = x, u_refs = setVRs, u = setVal, y_refs = getVRs, dx_refs = :all),
x -> c3(x),
Dense(numStates + numGetVRs, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
end
push!(nets, net8)
# 9. an empty NeuralFMU (this does only make sense for debugging)
net9 = function ()
net = Chain(x -> fmu(x = x, dx_refs = :all))
end
push!(nets, net9)
solvers = [Tsit5()]#, Rosenbrock23(autodiff=false)]
for solver in solvers
@testset "Solver: $(solver)" begin
for i = 1:length(nets)
@testset "Net setup $(i)/$(length(nets)) (Discontinuous NeuralFMU)" begin
global nets, problem, iterCB
global LAST_LOSS, FAILED_GRADIENTS
if i ∈ (1, 3, 4)
@warn "Currently skipping net $(i) ∈ (1, 3, 4) for disc. FMUs (ANN before FMU)"
continue
end
optim = OPTIMISER(ETA)
net_constructor = nets[i]
problem = nothing
p_net = nothing
tries = 0
maxtries = 1000
while true
net = net_constructor()
problem = ME_NeuralFMU(fmu, net, (t_start, t_stop), solver)
if i ∈ (1, 3, 4)
problem.modifiedState = true
end
p_net = Flux.params(problem)
solutionBefore = problem(X0; p = p_net[1], saveat = tData)
ne = length(solutionBefore.events)
if ne > 0 && ne <= 10
break
else
if tries >= maxtries
@warn "Solution before did not trigger an acceptable event count (=$(ne) ∉ [1,10]) for net $(i)! Can't find a valid start configuration ($(maxtries) tries)!"
break
end
tries += 1
end
end
@test !isnothing(problem)
# train it ...
p_net = Flux.params(problem)
@test length(p_net) == 1
solutionBefore = problem(X0; p = p_net[1], saveat = tData)
if solutionBefore.success
@test length(solutionBefore.states.t) == length(tData)
@test solutionBefore.states.t[1] == t_start
@test solutionBefore.states.t[end] == t_stop
end
LAST_LOSS = losssum(p_net[1])
@info "Start-Loss for net #$i: $(LAST_LOSS)"
if length(p_net[1]) == 0
@info "The following warning is not an issue, because training on zero parameters must throw a warning:"
end
FAILED_GRADIENTS = 0
FMIFlux.train!(
losssum,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
gradient = GRADIENT,
cb = () -> callback(p_net),
)
@info "Failed Gradients: $(FAILED_GRADIENTS) / $(NUMSTEPS)"
@test FAILED_GRADIENTS <= FAILED_GRADIENTS_QUOTA * NUMSTEPS
# check results
solutionAfter = problem(X0; p = p_net[1], saveat = tData)
if solutionAfter.success
@test length(solutionAfter.states.t) == length(tData)
@test solutionAfter.states.t[1] == t_start
@test solutionAfter.states.t[end] == t_stop
end
# fig = plot(solutionAfter; title="Net $(i) - $(FAILED_GRADIENTS) / $(FAILED_GRADIENTS_QUOTA * NUMSTEPS)")
# plot!(fig, tData, posData)
# display(fig)
end
end
end
end
@test length(fmu.components) <= 1
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 1315 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Statistics: mean, std
shift = [1.0, 2.0, 3.0]
scale = [4.0, 5.0, 6.0]
input = [0.5, 1.2, 1.0]
inputArray = [[-3.0, -2.0, -1.0], [3.0, 2.0, 1.0], [1.0, 2.0, 3.0]]
# ShiftScale
s = ShiftScale(shift, scale)
@test s(input) == [6.0, 16.0, 24.0]
s = ShiftScale(inputArray)
@test s(input) == [2.5, -0.8, -1.0]
s = ShiftScale(inputArray; range = -1:1)
for i = 1:length(inputArray)
res = s(collect(inputArray[j][i] for j = 1:length(inputArray[i])))
@test max(res...) <= 1
@test min(res...) >= -1
end
s = ShiftScale(inputArray; range = -2:2)
for i = 1:length(inputArray)
res = s(collect(inputArray[j][i] for j = 1:length(inputArray[i])))
@test max(res...) <= 2
@test min(res...) >= -2
end
s = ShiftScale(inputArray; range = :NormalDistribution)
# ToDo: Test for :NormalDistribution
# ScaleShift
s = ScaleShift(scale, shift)
@test s(input) == [3.0, 8.0, 9.0]
s = ScaleShift(inputArray)
@test s(input) == [-3.0, 4.4, 4.0]
p = ShiftScale(inputArray)
s = ScaleShift(p)
for i = 1:length(inputArray)
in = collect(inputArray[j][i] for j = 1:length(inputArray[i]))
@test p(in) != in
@test s(p(in)) == in
end
# ToDo: Add remaining layers
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 2062 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
using DifferentialEquations: Tsit5
import Random
Random.seed!(1234);
t_start = 0.0
t_step = 0.01
t_stop = 5.0
tData = t_start:t_step:t_stop
# generate training data
posData, velData, accData = syntTrainingData(tData)
# setup traing data
extForce = function (t)
return [sin(t), cos(t)]
end
# loss function for training
losssum = function (p)
solution = problem(extForce, t_step; p = p)
if !solution.success
return Inf
end
accNet = getValue(solution, 1; isIndex = true)
FMIFlux.Losses.mse(accNet, accData)
end
# Load FMUs
fmus = Vector{FMU2}()
for i = 1:2 # how many FMUs do you want?
_fmu = loadFMU("SpringPendulumExtForce1D", EXPORTINGTOOL, EXPORTINGVERSION; type = :CS)
push!(fmus, _fmu)
end
# NeuralFMU setup
total_fmu_outdim = sum(map(x -> length(x.modelDescription.outputValueReferences), fmus))
evalFMU = function (i, u)
fmus[i](;
u_refs = fmus[i].modelDescription.inputValueReferences,
u = u,
y_refs = fmus[i].modelDescription.outputValueReferences,
)
end
net = Chain(
Parallel(vcat, inputs -> evalFMU(1, inputs[1:1]), inputs -> evalFMU(2, inputs[2:2])),
Dense(total_fmu_outdim, 16, tanh; init = Flux.identity_init),
Dense(16, 16, tanh; init = Flux.identity_init),
Dense(
16,
length(fmus[1].modelDescription.outputValueReferences);
init = Flux.identity_init,
),
)
problem = CS_NeuralFMU(fmus, net, (t_start, t_stop))
@test problem != nothing
solutionBefore = problem(extForce, t_step)
# train it ...
p_net = Flux.params(problem)
optim = OPTIMISER(ETA)
lossBefore = losssum(p_net[1])
FMIFlux.train!(
losssum,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
gradient = GRADIENT,
)
lossAfter = losssum(p_net[1])
@test lossAfter < lossBefore
# check results
solutionAfter = problem(extForce, t_step)
for i = 1:length(fmus)
unloadFMU(fmus[i])
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 4769 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
using DifferentialEquations: Tsit5, Rosenbrock23
import Random
Random.seed!(5678);
t_start = 0.0
t_step = 0.01
t_stop = 5.0
tData = t_start:t_step:t_stop
# generate training data
posData, velData, accData = syntTrainingData(tData)
# load FMU for training
fmu = loadFMU("SpringFrictionPendulum1D", EXPORTINGTOOL, EXPORTINGVERSION; type = :ME)
# loss function for training
losssum = function (p)
global problem, X0, posData
solution = problem(X0; p = p, showProgress = true, saveat = tData)
if !solution.success
return Inf
end
# posNet = getState(solution, 1; isIndex=true)
velNet = getState(solution, 2; isIndex = true)
return FMIFlux.Losses.mse(velNet, velData) # Flux.Losses.mse(posNet, posData)
end
# callback function for training
global iterCB = 0
global lastLoss = 0.0
callb = function (p)
global iterCB += 1
global lastLoss
if iterCB % 5 == 0
loss = losssum(p[1])
@info "[$(iterCB)] Loss: $loss"
# This test condition is not good, because when the FMU passes an event, the error might increase.
@test (loss < lastLoss) && (loss != lastLoss)
lastLoss = loss
end
end
numStates = length(fmu.modelDescription.stateValueReferences)
# some NeuralFMU setups
nets = []
c1 = CacheLayer()
c2 = CacheRetrieveLayer(c1)
c3 = CacheLayer()
c4 = CacheRetrieveLayer(c3)
# 1. Discontinuous ME-NeuralFMU (learn dynamics and states)
net = Chain(
x -> c1(x),
Dense(numStates, 16, tanh),
Dense(16, 1, identity),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 16, tanh),
Dense(16, 16, tanh),
Dense(16, 1, identity),
x -> c4(1, x[1]),
)
push!(nets, net)
for i = 1:length(nets)
@testset "Net setup $(i)/$(length(nets))" begin
global nets, problem, lastLoss, iterCB
net = nets[i]
solver = Tsit5()
problem = ME_NeuralFMU(fmu, net, (t_start, t_stop), solver; saveat = tData)
@test problem !== nothing
solutionBefore = problem(X0)
if solutionBefore.success
@test length(solutionBefore.states.t) == length(tData)
@test solutionBefore.states.t[1] == t_start
@test solutionBefore.states.t[end] == t_stop
end
# train it ...
p_net = Flux.params(problem)
p_start = copy(p_net[1])
iterCB = 0
lastLoss = losssum(p_net[1])
startLoss = lastLoss
@info "[ $(iterCB)] Loss: $lastLoss"
p_net[1][:] = p_start[:]
lastLoss = startLoss
st = time()
optim = OPTIMISER(ETA)
FMIFlux.train!(
losssum,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
cb = () -> callb(p_net),
multiThreading = false,
gradient = GRADIENT,
)
dt = round(time() - st; digits = 2)
@info "Training time single threaded (not pre-compiled): $(dt)s"
p_net[1][:] = p_start[:]
lastLoss = startLoss
st = time()
optim = OPTIMISER(ETA)
FMIFlux.train!(
losssum,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
cb = () -> callb(p_net),
multiThreading = false,
gradient = GRADIENT,
)
dt = round(time() - st; digits = 2)
@info "Training time single threaded (pre-compiled): $(dt)s"
# [ToDo] currently not implemented
# p_net[1][:] = p_start[:]
# lastLoss = startLoss
# st = time()
# optim = OPTIMISER(ETA)
# FMIFlux.train!(losssum, problem, Iterators.repeated((), NUMSTEPS), optim; cb=()->callb(p_net), multiThreading=true, gradient=GRADIENT)
# dt = round(time()-st; digits=2)
# @info "Training time multi threaded x$(Threads.nthreads()) (not pre-compiled): $(dt)s"
# p_net[1][:] = p_start[:]
# lastLoss = startLoss
# st = time()
# optim = OPTIMISER(ETA)
# FMIFlux.train!(losssum, problem, Iterators.repeated((), NUMSTEPS), optim; cb=()->callb(p_net), multiThreading=true, gradient=GRADIENT)
# dt = round(time()-st; digits=2)
# @info "Training time multi threaded x$(Threads.nthreads()) (pre-compiled): $(dt)s"
# check results
solutionAfter = problem(X0)
if solutionAfter.success
@test length(solutionAfter.states.t) == length(tData)
@test solutionAfter.states.t[1] == t_start
@test solutionAfter.states.t[end] == t_stop
end
end
end
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 6625 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
using DifferentialEquations
using FMIFlux.Optim
import Random
Random.seed!(1234);
t_start = 0.0
t_step = 0.01
t_stop = 5.0
tData = t_start:t_step:t_stop
# generate training data
posData, velData, accData = syntTrainingData(tData)
# load FMU for NeuralFMU
fmu = loadFMU("SpringPendulum1D", EXPORTINGTOOL, EXPORTINGVERSION; type = :ME)
# loss function for training
losssum = function (p)
global problem, X0, posData
solution = problem(X0; p = p, saveat = tData)
if !solution.success
return Inf
end
posNet = getState(solution, 1; isIndex = true)
velNet = getState(solution, 2; isIndex = true)
return Flux.Losses.mse(posNet, posData) + Flux.Losses.mse(velNet, velData)
end
numStates = length(fmu.modelDescription.stateValueReferences)
# some NeuralFMU setups
nets = []
c1 = CacheLayer()
c2 = CacheRetrieveLayer(c1)
c3 = CacheLayer()
c4 = CacheRetrieveLayer(c3)
init = Flux.glorot_uniform
getVRs = [stringToValueReference(fmu, "mass.s")]
numGetVRs = length(getVRs)
y = zeros(fmi2Real, numGetVRs)
setVRs = [stringToValueReference(fmu, "mass.m")]
numSetVRs = length(setVRs)
setVal = [1.1]
# 1. default ME-NeuralFMU (learn dynamics and states, almost-neutral setup, parameter count << 100)
net = Chain(
x -> c1(x),
Dense(numStates, 1, tanh; init = init),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 2. default ME-NeuralFMU (learn dynamics)
net = Chain(
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 3. default ME-NeuralFMU (learn states)
net = Chain(
x -> c1(x),
Dense(numStates, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
)
push!(nets, net)
# 4. default ME-NeuralFMU (learn dynamics and states)
net = Chain(
x -> c1(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c2(x[1], 1),
x -> fmu(; x = x, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh, init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh, init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 5. NeuralFMU with hard setting time to 0.0
net = Chain(
states -> fmu(; x = states, t = 0.0, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 6. NeuralFMU with additional getter
net = Chain(
x -> fmu(; x = x, y_refs = getVRs, dx_refs = :all),
x -> c3(x),
Dense(numStates + numGetVRs, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 7. NeuralFMU with additional setter
net = Chain(
x -> fmu(; x = x, u_refs = setVRs, u = setVal, dx_refs = :all),
x -> c3(x),
Dense(numStates, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 8. NeuralFMU with additional setter and getter
net = Chain(
x -> fmu(; x = x, u_refs = setVRs, u = setVal, y_refs = getVRs, dx_refs = :all),
x -> c3(x),
Dense(numStates + numGetVRs, 8, tanh; init = init),
Dense(8, 16, tanh; init = init),
Dense(16, 1, tanh; init = init),
x -> c4(1, x[1]),
)
push!(nets, net)
# 9. an empty NeuralFMU (this does only make sense for debugging)
net = Chain(x -> fmu(x = x, dx_refs = :all))
push!(nets, net)
solvers = [Tsit5()]#, Rosenbrock23(autodiff=false)]
for solver in solvers
@testset "Solver: $(solver)" begin
for i = 1:length(nets)
@testset "Net setup $(i)/$(length(nets)) (Continuous NeuralFMU)" begin
global nets, problem, iterCB
global LAST_LOSS, FAILED_GRADIENTS
# if i ∈ (1, 3, 4)
# @warn "Currently skipping nets $(i) ∈ (1, 3, 4)"
# continue
# end
optim = GradientDescent(;
alphaguess = ETA,
linesearch = Optim.LineSearches.Static(),
) # BFGS()
net = nets[i]
problem = ME_NeuralFMU(fmu, net, (t_start, t_stop), solver)
@test problem != nothing
# [Note] this is not needed from a mathematical perspective, because the system is continuous differentiable
if i ∈ (1, 3, 4)
problem.modifiedState = true
end
# train it ...
p_net = Flux.params(problem)
@test length(p_net) == 1
solutionBefore = problem(X0; p = p_net[1], saveat = tData)
if solutionBefore.success
@test length(solutionBefore.states.t) == length(tData)
@test solutionBefore.states.t[1] == t_start
@test solutionBefore.states.t[end] == t_stop
end
LAST_LOSS = losssum(p_net[1])
@info "Start-Loss for net #$i: $(LAST_LOSS)"
if length(p_net[1]) == 0
@info "The following warning is not an issue, because training on zero parameters must throw a warning:"
end
FAILED_GRADIENTS = 0
FMIFlux.train!(
losssum,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
gradient = GRADIENT,
cb = () -> callback(p_net),
)
@info "Failed Gradients: $(FAILED_GRADIENTS) / $(NUMSTEPS)"
@test FAILED_GRADIENTS <= FAILED_GRADIENTS_QUOTA * NUMSTEPS
# check results
solutionAfter = problem(X0; p = p_net[1], saveat = tData)
if solutionAfter.success
@test length(solutionAfter.states.t) == length(tData)
@test solutionAfter.states.t[1] == t_start
@test solutionAfter.states.t[end] == t_stop
end
end
end
end
end
@test length(fmu.components) <= 1
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 5184 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using FMIFlux
using Test
using FMIZoo
using FMIFlux.FMIImport
using FMIFlux.FMIImport.FMICore
using FMIFlux.Flux
import FMIFlux.FMISensitivity: FiniteDiff, ForwardDiff, ReverseDiff
using FMIFlux.FMIImport:
stringToValueReference, fmi2ValueReference, prepareSolveFMU, fmi2Real
using FMIFlux.FMIImport: FMU_EXECUTION_CONFIGURATIONS
using FMIFlux.FMIImport: getState, getValue, getTime
exportingToolsWindows = [("Dymola", "2022x")] # [("ModelicaReferenceFMUs", "0.0.25")]
exportingToolsLinux = [("Dymola", "2022x")]
# number of training steps to perform
global NUMSTEPS = 30
global ETA = 1e-5
global GRADIENT = nothing
global EXPORTINGTOOL = nothing
global EXPORTINGVERSION = nothing
global X0 = [2.0, 0.0]
global OPTIMISER = Descent
global FAILED_GRADIENTS_QUOTA = 1/3
# callback for bad optimization steps counter
global FAILED_GRADIENTS = 0
global LAST_LOSS
callback = function (p)
global LAST_LOSS, FAILED_GRADIENTS
loss = losssum(p[1])
if loss >= LAST_LOSS
FAILED_GRADIENTS += 1
end
#@info "$(loss)"
LAST_LOSS = loss
end
# training data for pendulum experiment
function syntTrainingData(tData)
posData = cos.(tData * 3.0) * 2.0
velData = sin.(tData * 3.0) * -6.0
accData = cos.(tData * 3.0) * -18.0
return posData, velData, accData
end
# enable assertions for warnings/errors for all default execution configurations - we want strict tests here
for exec in FMU_EXECUTION_CONFIGURATIONS
exec.assertOnError = true
exec.assertOnWarning = true
end
function runtests(exportingTool)
global EXPORTINGTOOL = exportingTool[1]
global EXPORTINGVERSION = exportingTool[2]
@info "Testing FMUs exported from $(EXPORTINGTOOL) ($(EXPORTINGVERSION))"
@testset "Testing FMUs exported from $(EXPORTINGTOOL) ($(EXPORTINGVERSION))" begin
@info "Solution Gradients (solution_gradients.jl)"
@testset "Solution Gradients" begin
include("solution_gradients.jl")
end
@info "Time Event Solution Gradients (time_solution_gradients.jl)"
@testset "Time Event Solution Gradients" begin
include("time_solution_gradients.jl")
end
for _GRADIENT ∈ (:ReverseDiff, :ForwardDiff) # , :FiniteDiff)
global GRADIENT = _GRADIENT
@info "Gradient: $(GRADIENT)"
@testset "Gradient: $(GRADIENT)" begin
@info "Layers (layers.jl)"
@testset "Layers" begin
include("layers.jl")
end
@info "ME-NeuralFMU (Continuous) (hybrid_ME.jl)"
@testset "ME-NeuralFMU (Continuous)" begin
include("hybrid_ME.jl")
end
@info "ME-NeuralFMU (Discontinuous) (hybrid_ME_dis.jl)"
@testset "ME-NeuralFMU (Discontinuous)" begin
include("hybrid_ME_dis.jl")
end
@info "NeuralFMU with FMU parameter optimization (fmu_params.jl)"
@testset "NeuralFMU with FMU parameter optimization" begin
include("fmu_params.jl")
end
@info "Training modes (train_modes.jl)"
@testset "Training modes" begin
include("train_modes.jl")
end
@warn "Multi-threading Test Skipped"
# @info "Multi-threading (multi_threading.jl)"
# @testset "Multi-threading" begin
# include("multi_threading.jl")
# end
@info "CS-NeuralFMU (hybrid_CS.jl)"
@testset "CS-NeuralFMU" begin
include("hybrid_CS.jl")
end
@info "Multiple FMUs (multi.jl)"
@testset "Multiple FMUs" begin
include("multi.jl")
end
@info "Batching (batching.jl)"
@testset "Batching" begin
include("batching.jl")
end
@info "Optimizers from Optim.jl (optim.jl)"
@testset "Optim" begin
include("optim.jl")
end
end
end
@info "Checking supported sensitivities skipped"
# @info "Benchmark: Supported sensitivities (supported_sensitivities.jl)"
# @testset "Benchmark: Supported sensitivities " begin
# include("supported_sensitivities.jl")
# end
end
end
@testset "FMIFlux.jl" begin
if Sys.iswindows()
@info "Automated testing is supported on Windows."
for exportingTool in exportingToolsWindows
runtests(exportingTool)
end
elseif Sys.islinux()
@info "Automated testing is supported on Linux."
for exportingTool in exportingToolsLinux
runtests(exportingTool)
end
elseif Sys.isapple()
@warn "Test-sets are currrently using Windows- and Linux-FMUs, automated testing for macOS is currently not supported."
end
end
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 15216 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
using Statistics
using DifferentialEquations
using FMIFlux, FMIZoo, Test
import FMIFlux.FMISensitivity.SciMLSensitivity.SciMLBase: RightRootFind, LeftRootFind
import FMIFlux.FMIImport.FMIBase: unsense
using FMIFlux.FMISensitivity.SciMLSensitivity.ForwardDiff,
FMIFlux.FMISensitivity.SciMLSensitivity.ReverseDiff,
FMIFlux.FMISensitivity.SciMLSensitivity.FiniteDiff,
FMIFlux.FMISensitivity.SciMLSensitivity.Zygote
using FMIFlux.FMIImport, FMIFlux.FMIImport.FMICore, FMIZoo
import LinearAlgebra: I
import FMIFlux: isimplicit
import Random
Random.seed!(5678);
global solution = nothing
global events = 0
ENERGY_LOSS = 0.7
RADIUS = 0.0
GRAVITY = 9.81
DBL_MIN = 1e-10 # 2.2250738585072013830902327173324040642192159804623318306e-308
NUMEVENTS = 4
t_start = 0.0
t_step = 0.05
t_stop = 2.0
tData = t_start:t_step:t_stop
posData = ones(Float64, length(tData))
x0_bb = [1.0, 0.0]
solvekwargs =
Dict{Symbol,Any}(:saveat => tData, :abstol => 1e-6, :reltol => 1e-6, :dtmax => 1e-2)
numStates = 2
solvers = [Tsit5(), Rosenbrock23(autodiff = false)]#, FBDF(autodiff=false)]
Wr = rand(2, 2) * 1e-4 # zeros(2,2) #
br = rand(2) * 1e-4 # zeros(2) #
W1 = [1.0 0.0; 0.0 1.0] - Wr
b1 = [0.0, 0.0] - br
W2 = [1.0 0.0; 0.0 1.0] - Wr
b2 = [0.0, 0.0] - br
∂xn_∂xp = [0.0 0.0; 0.0 -ENERGY_LOSS]
# setup BouncingBallODE
fx = function (x)
return [x[2], -GRAVITY]
end
fx_bb = function (dx, x, p, t)
dx[:] = re_bb(p)(x)
return nothing
end
net_bb = Chain(#Dense(W1, b1, identity),
fx,
Dense(W2, b2, identity),
)
p_net_bb, re_bb = Flux.destructure(net_bb)
ff = ODEFunction{true}(fx_bb)
prob_bb = ODEProblem{true}(ff, x0_bb, (t_start, t_stop), p_net_bb)
condition = function (out, x, t, integrator)
#x = re_bb(p_net_bb)[1](x)
out[1] = x[1] - RADIUS
end
time_choice = function (integrator)
ts = [0.451523640985728, 1.083656738365748, 1.5261499065317576, 1.8358951242479626]
i = 1
while ts[i] <= integrator.t
i += 1
if i > length(ts)
return nothing
end
end
return ts[i]
end
affect_right! = function (integrator, idx)
#@info "affect_right! triggered by #$(idx)"
# if idx == 1
# # event #1 is handeled as "dummy" (e.g. discrete state change)
# return
# end
if idx > 0
out = zeros(1)
x = integrator.u
t = integrator.t
condition(out, unsense(x), unsense(t), integrator)
if sign(out[idx]) > 0.0
@info "Event for bouncing ball (white-box) triggered, but not valid!"
return nothing
end
end
s_new = RADIUS + DBL_MIN
v_new = -integrator.u[2] * ENERGY_LOSS
u_new = [s_new, v_new]
global events
events += 1
#@info "[$(events)] New state at $(integrator.t) is $(u_new) triggered by #$(idx)"
integrator.u .= u_new
end
affect_left! = function (integrator, idx)
#@info "affect_left! triggered by #$(idx)"
# if idx == 1
# # event #1 is handeled as "dummy" (e.g. discrete state change)
# return
# end
out = zeros(1)
x = integrator.u
t = integrator.t
condition(out, unsense(x), unsense(t), integrator)
if sign(out[idx]) < 0.0
@warn "Event for bouncing ball triggered, but not valid!"
return nothing
end
s_new = integrator.u[1]
v_new = -integrator.u[2] * ENERGY_LOSS
u_new = [s_new, v_new]
global events
events += 1
#@info "[$(events)] New state at $(integrator.t) is $(u_new)"
integrator.u .= u_new
end
stepCompleted = function (x, t, integrator)
end
NUMEVENTINDICATORS = 1 # 2
rightCb = VectorContinuousCallback(
condition, #_double,
affect_right!,
NUMEVENTINDICATORS;
rootfind = RightRootFind,
save_positions = (false, false),
)
leftCb = VectorContinuousCallback(
condition, #_double,
affect_left!,
NUMEVENTINDICATORS;
rootfind = LeftRootFind,
save_positions = (false, false),
)
timeCb = IterativeCallback(
time_choice,
(indicator) -> affect_right!(indicator, 0),
Float64;
initial_affect = false,
save_positions = (false, false),
)
stepCb = FunctionCallingCallback(stepCompleted; func_everystep = true, func_start = true)
# load FMU for NeuralFMU
#fmu = loadFMU("BouncingBall", "ModelicaReferenceFMUs", "0.0.25"; type=:ME)
#fmu_params = nothing
fmu = loadFMU("BouncingBall1D", "Dymola", "2023x"; type = :ME)
fmu_params = Dict("damping" => 0.7, "mass_radius" => 0.0, "mass_s_min" => DBL_MIN)
fmu.executionConfig.isolatedStateDependency = true
net = Chain(#Dense(W1, b1, identity),
x -> fmu(; x = x, dx_refs = :all),
Dense(W2, b2, identity),
)
prob = ME_NeuralFMU(fmu, net, (t_start, t_stop))
prob.snapshots = true # needed for correct sensitivities
# ANNs
losssum = function (p; sensealg = nothing, solver = nothing)
global posData
posNet = mysolve(p; sensealg = sensealg, solver = solver)
return Flux.Losses.mae(posNet, posData)
end
losssum_bb = function (p; sensealg = nothing, root = :Right, solver = nothing)
global posData
posNet = mysolve_bb(p; sensealg = sensealg, root = root, solver = solver)
return Flux.Losses.mae(posNet, posData)
end
mysolve = function (p; sensealg = nothing, solver = nothing)
global solution, events # write
global prob, x0_bb, posData # read-only
events = 0
solution = prob(
x0_bb;
p = p,
solver = solver,
parameters = fmu_params,
sensealg = sensealg,
cleanSnapshots = false,
solvekwargs...,
)
return collect(u[1] for u in solution.states.u)
end
mysolve_bb = function (p; sensealg = nothing, root = :Right, solver = nothing)
global solution # write
global prob_bb, events # read
events = 0
callback = nothing
if root == :Right
callback = CallbackSet(rightCb, stepCb)
elseif root == :Left
callback = CallbackSet(leftCb, stepCb)
elseif root == :Time
callback = CallbackSet(timeCb, stepCb)
else
@assert false "unknwon root `$(root)`"
end
solution = solve(
prob_bb;
p = p,
alg = solver,
callback = callback,
sensealg = sensealg,
solvekwargs...,
)
if !isa(solution, AbstractArray)
if solution.retcode != FMIFlux.ReturnCode.Success
@error "Solution failed!"
return Inf
end
return collect(u[1] for u in solution.u)
else
return solution[1, :] # collect(solution[:,i] for i in 1:size(solution)[2])
end
end
p_net = Flux.params(prob)[1]
using FMIFlux.FMISensitivity.SciMLSensitivity
sensealg = ReverseDiffAdjoint() # InterpolatingAdjoint(autojacvec=ReverseDiffVJP(false)) #
c = nothing
c, _ = FMIFlux.prepareSolveFMU(
prob.fmu,
c,
fmi2TypeModelExchange;
parameters = prob.parameters,
t_start = prob.tspan[1],
t_stop = prob.tspan[end],
x0 = prob.x0,
handleEvents = FMIFlux.handleEvents,
cleanup = true,
)
### START CHECK CONDITIONS
condition_bb_check = function (x)
buffer = similar(x, 1)
condition(buffer, x, t_start, nothing)
return buffer
end
condition_nfmu_check = function (x)
buffer = similar(x, 1)
FMIFlux.condition!(
prob,
FMIFlux.getInstance(prob),
buffer,
x,
t_start,
nothing,
[UInt32(1)],
)
return buffer
end
jac_fwd1 = ForwardDiff.jacobian(condition_bb_check, x0_bb)
jac_fwd2 = ForwardDiff.jacobian(condition_nfmu_check, x0_bb)
jac_rwd1 = ReverseDiff.jacobian(condition_bb_check, x0_bb)
jac_rwd2 = ReverseDiff.jacobian(condition_nfmu_check, x0_bb)
jac_fin1 = FiniteDiff.finite_difference_jacobian(condition_bb_check, x0_bb)
jac_fin2 = FiniteDiff.finite_difference_jacobian(condition_nfmu_check, x0_bb)
atol = 1e-6
@test isapprox(jac_fin1, jac_fwd1; atol = atol)
@test isapprox(jac_fin1, jac_rwd1; atol = atol)
@test isapprox(jac_fin2, jac_fwd2; atol = atol)
@test isapprox(jac_fin2, jac_rwd2; atol = atol)
### START CHECK AFFECT
affect_bb_check = function (x)
# convert TrackedArrays to Array{<:TrackedReal,1}
if !isa(x, AbstractVector{<:Float64})
x = [x...]
else
x = copy(x)
end
integrator = (t = t_start, u = x)
affect_right!(integrator, 1)
return integrator.u
end
affect_nfmu_check = function (x)
global prob
# convert TrackedArrays to Array{<:TrackedReal,1}
if !isa(x, AbstractVector{<:Float64})
x = [x...]
else
x = copy(x)
end
c, _ = FMIFlux.prepareSolveFMU(
prob.fmu,
nothing,
fmi2TypeModelExchange;
parameters = fmu_params,
t_start = prob.tspan[1],
t_stop = prob.tspan[end],
x0 = unsense(x),
handleEvents = FMIFlux.handleEvents,
cleanup = true,
)
integrator = (t = t_start, u = x, opts = (internalnorm = (a, b) -> 1.0,))
FMIFlux.affectFMU!(prob, c, integrator, 1)
return integrator.u
end
#t_event_time = 0.451523640985728
x_event_left = [-1.0, -1.0] # [-3.808199081191736e-15, -4.429446918069994]
x_event_right = [0.0, 0.7] # [2.2250738585072014e-308, 3.1006128426489954]
x_no_event = [0.1, -1.0]
@test isapprox(affect_bb_check(x_event_left), x_event_right; atol = 1e-4)
@test isapprox(affect_nfmu_check(x_event_left), x_event_right; atol = 1e-4)
jac_con1 = ForwardDiff.jacobian(affect_bb_check, x_event_left)
jac_con2 = ForwardDiff.jacobian(affect_nfmu_check, x_event_left)
@test isapprox(jac_con1, ∂xn_∂xp; atol = 1e-4)
@test isapprox(jac_con2, ∂xn_∂xp; atol = 1e-4)
jac_con1 = ReverseDiff.jacobian(affect_bb_check, x_event_left)
jac_con2 = ReverseDiff.jacobian(affect_nfmu_check, x_event_left)
@test isapprox(jac_con1, ∂xn_∂xp; atol = 1e-4)
@test isapprox(jac_con2, ∂xn_∂xp; atol = 1e-4)
# [Note] checking via FiniteDiff is not possible here, because finite differences offsets might not trigger the events at all
# no-event
@test isapprox(affect_bb_check(x_no_event), x_no_event; atol = 1e-4)
@test isapprox(affect_nfmu_check(x_no_event), x_no_event; atol = 1e-4)
jac_con1 = ForwardDiff.jacobian(affect_bb_check, x_no_event)
jac_con2 = ForwardDiff.jacobian(affect_nfmu_check, x_no_event)
@test isapprox(jac_con1, I; atol = 1e-4)
@test isapprox(jac_con2, I; atol = 1e-4)
jac_con1 = ReverseDiff.jacobian(affect_bb_check, x_no_event)
jac_con2 = ReverseDiff.jacobian(affect_nfmu_check, x_no_event)
@test isapprox(jac_con1, I; atol = 1e-4)
@test isapprox(jac_con2, I; atol = 1e-4)
###
for solver in solvers
@info "Solver: $(solver)"
# Solution (plain)
losssum(p_net; sensealg = sensealg, solver = solver)
@test length(solution.events) == NUMEVENTS
losssum_bb(p_net_bb; sensealg = sensealg, solver = solver)
@test events == NUMEVENTS
# Solution FWD (FMU)
grad_fwd_f =
ForwardDiff.gradient(p -> losssum(p; sensealg = sensealg, solver = solver), p_net)
@test length(solution.events) == NUMEVENTS
# Solution FWD (right)
root = :Right
grad_fwd_r = ForwardDiff.gradient(
p -> losssum_bb(p; sensealg = sensealg, root = root, solver = solver),
p_net_bb,
)
@test events == NUMEVENTS
# Solution FWD (left)
root = :Left
grad_fwd_l = ForwardDiff.gradient(
p -> losssum_bb(p; sensealg = sensealg, root = root, solver = solver),
p_net_bb,
)
@test events == NUMEVENTS
# Solution FWD (time)
root = :Time
grad_fwd_t = ForwardDiff.gradient(
p -> losssum_bb(p; sensealg = sensealg, root = root, solver = solver),
p_net_bb,
)
@test events == NUMEVENTS
# Solution RWD (FMU)
grad_rwd_f =
ReverseDiff.gradient(p -> losssum(p; sensealg = sensealg, solver = solver), p_net)
@test length(solution.events) == NUMEVENTS
# Solution RWD (right)
root = :Right
grad_rwd_r = ReverseDiff.gradient(
p -> losssum_bb(p; sensealg = sensealg, root = root, solver = solver),
p_net_bb,
)
@test events == NUMEVENTS
# Solution RWD (left)
root = :Left
grad_rwd_l = ReverseDiff.gradient(
p -> losssum_bb(p; sensealg = sensealg, root = root, solver = solver),
p_net_bb,
)
@test events == NUMEVENTS
# Solution RWD (time)
root = :Time
grad_rwd_t = ReverseDiff.gradient(
p -> losssum_bb(p; sensealg = sensealg, root = root, solver = solver),
p_net_bb,
)
@test events == NUMEVENTS
# Ground Truth
absstep = 1e-6
grad_fin_r = FiniteDiff.finite_difference_gradient(
p -> losssum_bb(p; sensealg = sensealg, root = :Right, solver = solver),
p_net_bb,
Val{:central};
absstep = absstep,
)
grad_fin_l = FiniteDiff.finite_difference_gradient(
p -> losssum_bb(p; sensealg = sensealg, root = :Left, solver = solver),
p_net_bb,
Val{:central};
absstep = absstep,
)
grad_fin_t = FiniteDiff.finite_difference_gradient(
p -> losssum_bb(p; sensealg = sensealg, root = :Time, solver = solver),
p_net_bb,
Val{:central};
absstep = absstep,
)
grad_fin_f = FiniteDiff.finite_difference_gradient(
p -> losssum(p; sensealg = sensealg, solver = solver),
p_net,
Val{:central};
absstep = absstep,
)
local atol = 1e-3
# check if finite differences match together
@test isapprox(grad_fin_f, grad_fin_r; atol = atol)
@test isapprox(grad_fin_f, grad_fin_l; atol = atol)
@test isapprox(grad_fin_f, grad_fwd_f; atol = 0.2) # [ToDo: this is too much!]
@test isapprox(grad_fin_f, grad_rwd_f; atol = atol)
# Jacobian Test
jac_fwd_r = ForwardDiff.jacobian(
p -> mysolve_bb(p; sensealg = sensealg, solver = solver),
p_net,
)
jac_fwd_f =
ForwardDiff.jacobian(p -> mysolve(p; sensealg = sensealg, solver = solver), p_net)
jac_rwd_r = ReverseDiff.jacobian(
p -> mysolve_bb(p; sensealg = sensealg, solver = solver),
p_net,
)
jac_rwd_f =
ReverseDiff.jacobian(p -> mysolve(p; sensealg = sensealg, solver = solver), p_net)
# [TODO] why this?!
jac_rwd_r[2:end, :] = jac_rwd_r[2:end, :] .- jac_rwd_r[1:end-1, :]
jac_rwd_f[2:end, :] = jac_rwd_f[2:end, :] .- jac_rwd_f[1:end-1, :]
jac_fin_r = FiniteDiff.finite_difference_jacobian(
p -> mysolve_bb(p; sensealg = sensealg, solver = solver),
p_net,
Val{:central};
absstep = absstep,
)
jac_fin_f = FiniteDiff.finite_difference_jacobian(
p -> mysolve(p; sensealg = sensealg, solver = solver),
p_net,
Val{:central};
absstep = absstep,
)
###
local atol = 1e-3
@test isapprox(jac_fin_f, jac_fin_r; atol = atol)
@test isapprox(jac_fin_f, jac_fwd_f; atol = 1e1) # [ToDo] this is too much!
@test mean(abs.(jac_fin_f .- jac_fwd_f)) < 0.15 # added another test for this case...
@test isapprox(jac_fin_f, jac_rwd_f; atol = atol)
@test isapprox(jac_fin_r, jac_fwd_r; atol = atol)
@test isapprox(jac_fin_r, jac_rwd_r; atol = atol)
###
end
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 2204 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
using DifferentialEquations
import Random
Random.seed!(5678);
# boundaries
t_start = 0.0
t_step = 0.1
t_stop = 5.0
tData = t_start:t_step:t_stop
tspan = (t_start, t_stop)
posData = ones(Float64, length(tData))
nfmu = nothing
# load FMU for NeuralFMU
fmus = []
# this is a non-simultaneous event system (one event per time instant)
f = loadFMU("BouncingBall", "ModelicaReferenceFMUs", "0.0.25"; type = :ME)
@assert f.modelDescription.numberOfEventIndicators == 1 "Wrong number of event indicators: $(f.modelDescription.numberOfEventIndicators) != 1"
push!(fmus, f)
# this is a simultaneous event system (two events per time instant)
f = loadFMU("BouncingBall1D", "Dymola", "2023x"; type = :ME)
@assert f.modelDescription.numberOfEventIndicators == 2 "Wrong number of event indicators: $(f.modelDescription.numberOfEventIndicators) != 2"
push!(fmus, f)
x0_bb = [1.0, 0.0]
numStates = length(x0_bb)
function net_const(fmu)
net =
Chain(x -> fmu(; x = x, dx_refs = :all), Dense(2, 16, tanh), Dense(16, 2, identity))
return net
end
# loss function for training
losssum = function (p)
global nfmu, x0_bb, posData
solution = nfmu(x0_bb; p = p, saveat = tData)
if !solution.success
return Inf
end
posNet = getState(solution, 1; isIndex = true)
return FMIFlux.Losses.mse(posNet, posData)
end
for fmu in fmus
@info "##### CHECKING FMU WITH $(fmu.modelDescription.numberOfEventIndicators) SIMULTANEOUS EVENT INDICATOR(S) #####"
solvers = [
Tsit5(),
Rosenbrock23(autodiff = false),
Rodas5(autodiff = false),
FBDF(autodiff = false),
]
for solver in solvers
global nfmu
@info "##### SOLVER: $(solver) #####"
net = net_const(fmu)
nfmu = ME_NeuralFMU(fmu, net, (t_start, t_stop), solver; saveat = tData)
nfmu.modifiedState = false
nfmu.snapshots = true
best_timing, best_gradient, best_sensealg = FMIFlux.checkSensalgs!(losssum, nfmu)
#@test best_timing != Inf
end
end
unloadFMU.(fmus)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 16529 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using FMIFlux.Flux
using DifferentialEquations
using FMIFlux, FMIZoo, Test
import FMIFlux.FMISensitivity.SciMLSensitivity.SciMLBase: RightRootFind, LeftRootFind
using FMIFlux.FMIImport.FMIBase: unsense
using FMIFlux.FMISensitivity.SciMLSensitivity.ForwardDiff,
FMIFlux.FMISensitivity.SciMLSensitivity.ReverseDiff,
FMIFlux.FMISensitivity.SciMLSensitivity.FiniteDiff,
FMIFlux.FMISensitivity.SciMLSensitivity.Zygote
using FMIFlux.FMIImport, FMIFlux.FMIImport.FMICore, FMIZoo
import LinearAlgebra: I
import Random
Random.seed!(5678);
global solution = nothing
global events = 0
ENERGY_LOSS = 0.7
RADIUS = 0.0
GRAVITY = 9.81
GRAVITY_SIGN = -1
DBL_MIN = 1e-10 # 2.2250738585072013830902327173324040642192159804623318306e-308
TIME_FREQ = 1.0
MASS = 1.0
INTERP_POINTS = 10
NUMEVENTS = 4
t_start = 0.0
t_step = 0.05
t_stop = 2.0
tData = t_start:t_step:t_stop
posData = ones(Float64, length(tData))
x0_bb = [0.5, 0.0]
solvekwargs =
Dict{Symbol,Any}(:saveat => tData, :abstol => 1e-6, :reltol => 1e-6, :dtmax => 1e-2)
numStates = 2
solvers = [Tsit5()]#, Rosenbrock23(autodiff=false)]
Wr = rand(2, 2) * 1e-4
br = rand(2) * 1e-4
W1 = [1.0 0.0; 0.0 1.0] - Wr
b1 = [0.0, 0.0] - br
W2 = [1.0 0.0; 0.0 1.0] - Wr
b2 = [0.0, 0.0] - br
∂xn_∂xp = [0.0 0.0; 0.0 -ENERGY_LOSS]
# setup BouncingBallODE
global fx_dx_cache = zeros(Real, 2)
fx = function (x, t; kwargs...)
return _fx(x, t; kwargs...)
end
_fx = function (x, t)
global fx_dx_cache
fx_dx_cache[1] = x[2]
fx_dx_cache[2] = GRAVITY_SIGN * GRAVITY / MASS
return fx_dx_cache
end
fx_bb = function (dx, x, p, t)
dx[:] = re_bb(p)(x)
return nothing
end
net_bb = Chain(#Dense(W1, b1, identity),
x -> fx(x, 0.0),
Dense(W2, b2, identity),
)
p_net_bb, re_bb = Flux.destructure(net_bb)
ff = ODEFunction{true}(fx_bb)
prob_bb = ODEProblem{true}(ff, x0_bb, (t_start, t_stop), p_net_bb)
condition = function (out, x, t, integrator)
#x = re_bb(p_net_bb)[1](x)
out[1] = x[1] - RADIUS
out[2] = x[1] - RADIUS
end
import FMIFlux: unsense
time_choice = function (integrator)
next = (floor(integrator.t / TIME_FREQ) + 1) * TIME_FREQ
if next <= t_stop
#@info "next: $(next)"
return unsense(next)
else
return nothing
end
end
time_affect! = function (integrator)
global GRAVITY_SIGN
GRAVITY_SIGN = -GRAVITY_SIGN
global events
events += 1
#u_modified!(integrator, false)
end
affect_right! = function (integrator, idx)
#@info "affect_right! triggered by #$(idx)"
# if idx == 1
# # event #1 is handeled as "dummy" (e.g. discrete state change)
# return
# end
if idx > 0
out = zeros(NUMEVENTINDICATORS)
x = integrator.u
t = integrator.t
condition(out, unsense(x), unsense(t), integrator)
if sign(out[idx]) > 0.0
@info "Event for bouncing ball (white-box) triggered, but not valid!"
return nothing
end
end
s_new = RADIUS + DBL_MIN
v_new = -1.0 * unsense(integrator.u[2]) * ENERGY_LOSS
left_x = unsense(integrator.u)
right_x = [s_new, v_new]
global events
events += 1
#@info "[$(events)] New state at $(integrator.t) is $(u_new) triggered by #$(idx)"
#integrator.u[:] .= u_new
for i = 1:length(left_x)
if left_x[i] != 0.0 # abs(left_x[i]) > 1e-128
scale = right_x[i] / left_x[i]
integrator.u[i] *= scale
else # integrator state zero can't be scaled, need to add (but no sensitivities in this case!)
shift = right_x[i] - left_x[i]
integrator.u[i] += shift
#integrator.u[i] = right_x[i]
logWarning(
c.fmu,
"Probably wrong sensitivities @t=$(unsense(t)) for ∂x^+ / ∂x^-\nCan't scale zero state #$(i) from $(left_x[i]) to $(right_x[i])\nNew state after transform is: $(integrator.u[i])",
)
end
end
return nothing
end
affect_left! = function (integrator, idx)
#@info "affect_left! triggered by #$(idx)"
# if idx == 1
# # event #1 is handeled as "dummy" (e.g. discrete state change)
# return
# end
out = zeros(NUMEVENTINDICATORS)
x = integrator.u
t = integrator.t
condition(out, unsense(x), unsense(t), integrator)
if sign(out[idx]) < 0.0
@warn "Event for bouncing ball triggered, but not valid!"
return nothing
end
s_new = integrator.u[1]
v_new = -integrator.u[2] * ENERGY_LOSS
u_new = [s_new, v_new]
global events
events += 1
#@info "[$(events)] New state at $(integrator.t) is $(u_new)"
integrator.u .= u_new
end
stepCompleted = function (x, t, integrator)
end
NUMEVENTINDICATORS = 2
rightCb = VectorContinuousCallback(
condition, #_double,
affect_right!,
NUMEVENTINDICATORS;
rootfind = RightRootFind,
save_positions = (false, false),
interp_points = INTERP_POINTS,
)
leftCb = VectorContinuousCallback(
condition, #_double,
affect_left!,
NUMEVENTINDICATORS;
rootfind = LeftRootFind,
save_positions = (false, false),
interp_points = INTERP_POINTS,
)
gravityCb = IterativeCallback(
time_choice,
time_affect!,
Float64;
initial_affect = false,
save_positions = (false, false),
)
stepCb = FunctionCallingCallback(stepCompleted; func_everystep = true, func_start = true)
# load FMU for NeuralFMU
fmu = loadFMU("BouncingBallGravitySwitch1D", "Dymola", "2023x"; type = :ME)
fmu_params = Dict(
"damping" => ENERGY_LOSS,
"mass_radius" => RADIUS,
"gravity" => GRAVITY,
"period" => TIME_FREQ,
"mass_m" => MASS,
"mass_s_min" => DBL_MIN,
)
fmu.executionConfig.isolatedStateDependency = true
net = Chain(#Dense(W1, b1, identity),
x -> fmu(; x = x, dx_refs = :all),
Dense(W2, b2, identity),
)
prob = ME_NeuralFMU(fmu, net, (t_start, t_stop))
prob.snapshots = true # needed for correct sensitivities
# ANNs
losssum = function (p; sensealg = nothing, solver = nothing)
global posData
posNet = mysolve(p; sensealg = sensealg, solver = solver)
return Flux.Losses.mae(posNet, posData)
end
losssum_bb = function (p; sensealg = nothing, root = :Right, solver = nothing)
global posData
posNet = mysolve_bb(p; sensealg = sensealg, root = root, solver = solver)
return Flux.Losses.mae(posNet, posData)
end
mysolve = function (p; sensealg = nothing, solver = nothing)
global solution, events # write
global prob, x0_bb, posData # read-only
events = 0
solution = prob(
x0_bb;
p = p,
solver = solver,
parameters = fmu_params,
sensealg = sensealg,
solvekwargs...,
)
return collect(u[1] for u in solution.states.u)
end
mysolve_bb = function (p; sensealg = nothing, root = :Right, solver = nothing)
global solution, GRAVITY_SIGN
global prob_bb, events # read
events = 0
callback = nothing
if root == :Right
callback = CallbackSet(gravityCb, rightCb, stepCb)
elseif root == :Left
callback = CallbackSet(gravityCb, leftCb, stepCb)
else
@assert false "unknwon root `$(root)`"
end
GRAVITY_SIGN = -1
solution = solve(
prob_bb,
solver;
u0 = x0_bb,
p = p,
callback = callback,
sensealg = sensealg,
solvekwargs...,
)
if !isa(solution, AbstractArray)
if solution.retcode != FMIFlux.ReturnCode.Success
@error "Solution failed!"
return Inf
end
return collect(u[1] for u in solution.u)
else
return solution[1, :] # collect(solution[:,i] for i in 1:size(solution)[2])
end
end
p_net = Flux.params(prob)[1]
using FMIFlux.FMISensitivity.SciMLSensitivity
sensealg = ReverseDiffAdjoint() # InterpolatingAdjoint(autojacvec=ReverseDiffVJP(false)) #
c = nothing
c, _ = FMIFlux.prepareSolveFMU(
prob.fmu,
c,
fmi2TypeModelExchange;
parameters = prob.parameters,
t_start = prob.tspan[1],
t_stop = prob.tspan[end],
x0 = prob.x0,
handleEvents = FMIFlux.handleEvents,
cleanup = true,
)
### START CHECK CONDITIONS
condition_bb_check = function (x)
buffer = similar(x, NUMEVENTINDICATORS)
condition(buffer, x, t_start, nothing)
return buffer
end
condition_nfmu_check = function (x)
buffer = similar(x, fmu.modelDescription.numberOfEventIndicators)
inds = collect(UInt32(i) for i = 1:fmu.modelDescription.numberOfEventIndicators)
FMIFlux.condition!(prob, FMIFlux.getInstance(prob), buffer, x, t_start, nothing, inds)
return buffer
end
jac_fwd1 = ForwardDiff.jacobian(condition_bb_check, x0_bb)
jac_fwd2 = ForwardDiff.jacobian(condition_nfmu_check, x0_bb)
jac_rwd1 = ReverseDiff.jacobian(condition_bb_check, x0_bb)
jac_rwd2 = ReverseDiff.jacobian(condition_nfmu_check, x0_bb)
jac_fin1 = FiniteDiff.finite_difference_jacobian(condition_bb_check, x0_bb)
jac_fin2 = FiniteDiff.finite_difference_jacobian(condition_nfmu_check, x0_bb)
atol = 1e-6
@test isapprox(jac_fin1, jac_fwd1; atol = atol)
@test isapprox(jac_fin1, jac_rwd1; atol = atol)
@test isapprox(jac_fin2, jac_fwd2; atol = atol)
@test isapprox(jac_fin2, jac_rwd2; atol = atol)
### START CHECK AFFECT
affect_bb_check = function (x, t, idx = 1)
# convert TrackedArrays to Array{<:TrackedReal,1}
if !isa(x, AbstractVector{<:Float64})
x = [x...]
else
x = copy(x)
end
integrator = (t = t, u = x)
if idx == 0
time_affect!(integrator)
else
affect_right!(integrator, idx)
end
return integrator.u
end
affect_nfmu_check = function (x, t, idx = 1)
global prob
# convert TrackedArrays to Array{<:TrackedReal,1}
if !isa(x, AbstractVector{<:Float64})
x = [x...]
else
x = copy(x)
end
c, _ = FMIFlux.prepareSolveFMU(
prob.fmu,
nothing,
fmi2TypeModelExchange;
parameters = fmu_params,
t_start = unsense(t),
t_stop = prob.tspan[end],
x0 = unsense(x),
handleEvents = FMIFlux.handleEvents,
cleanup = true,
)
integrator = (t = t, u = x, opts = (internalnorm = (a, b) -> 1.0,))
FMIFlux.affectFMU!(prob, c, integrator, idx)
return integrator.u
end
#t_event_time = 0.451523640985728
x_event_left = [-1.0, -1.0] # [-3.808199081191736e-15, -4.429446918069994]
x_event_right = [0.0, 0.7] # [2.2250738585072014e-308, 3.1006128426489954]
x_no_event = [0.1, -1.0]
t_no_event = t_start
# [ToDo] the following tests fail for some FMUs
# @test isapprox(affect_bb_check(x_event_left, t_no_event), x_event_right; atol=1e-4)
# @test isapprox(affect_nfmu_check(x_event_left, t_no_event), x_event_right; atol=1e-4)
# jac_con1 = ForwardDiff.jacobian(x -> affect_bb_check(x, t_no_event), x_event_left)
# jac_con2 = ForwardDiff.jacobian(x -> affect_nfmu_check(x, t_no_event), x_event_left)
# @test isapprox(jac_con1, ∂xn_∂xp; atol=1e-4)
# @test isapprox(jac_con2, ∂xn_∂xp; atol=1e-4)
# jac_con1 = ReverseDiff.jacobian(x -> affect_bb_check(x, t_no_event), x_event_left)
# jac_con2 = ReverseDiff.jacobian(x -> affect_nfmu_check(x, t_no_event), x_event_left)
# @test isapprox(jac_con1, ∂xn_∂xp; atol=1e-4)
# @test isapprox(jac_con2, ∂xn_∂xp; atol=1e-4)
# [Note] checking via FiniteDiff is not possible here, because finite differences offsets might not trigger the events at all
# no-event
@test isapprox(affect_bb_check(x_no_event, t_no_event), x_no_event; atol = 1e-4)
@test isapprox(affect_nfmu_check(x_no_event, t_no_event), x_no_event; atol = 1e-4)
jac_con1 = ForwardDiff.jacobian(x -> affect_bb_check(x, t_no_event), x_no_event)
jac_con2 = ForwardDiff.jacobian(x -> affect_nfmu_check(x, t_no_event), x_no_event)
@test isapprox(jac_con1, I; atol = 1e-4)
@test isapprox(jac_con2, I; atol = 1e-4)
jac_con1 = ReverseDiff.jacobian(x -> affect_bb_check(x, t_no_event), x_no_event)
jac_con2 = ReverseDiff.jacobian(x -> affect_nfmu_check(x, t_no_event), x_no_event)
@test isapprox(jac_con1, I; atol = 1e-4)
@test isapprox(jac_con2, I; atol = 1e-4)
### TIME-EVENTS
t_event = t_start + 1.1
@test isapprox(affect_bb_check(x_no_event, t_event, 0), x_no_event; atol = 1e-4)
@test isapprox(affect_nfmu_check(x_no_event, t_event, 0), x_no_event; atol = 1e-4)
jac_con1 = ForwardDiff.jacobian(x -> affect_bb_check(x, t_event, 0), x_no_event)
jac_con2 = ForwardDiff.jacobian(x -> affect_nfmu_check(x, t_event, 0), x_no_event)
@test isapprox(jac_con1, I; atol = 1e-4)
@test isapprox(jac_con2, I; atol = 1e-4)
jac_con1 = ReverseDiff.jacobian(x -> affect_bb_check(x, t_event, 0), x_no_event)
jac_con2 = ReverseDiff.jacobian(x -> affect_nfmu_check(x, t_event, 0), x_no_event)
@test isapprox(jac_con1, I; atol = 1e-4)
@test isapprox(jac_con2, I; atol = 1e-4)
jac_con1 = ReverseDiff.jacobian(t -> affect_bb_check(x_event_left, t[1], 0), [t_event])
jac_con2 = ReverseDiff.jacobian(t -> affect_nfmu_check(x_event_left, t[1], 0), [t_event])
###
NUMEVENTS = 4
for solver in solvers
@info "Solver: $(solver)"
global GRAVITY_SIGN
# Solution (plain)
GRAVITY_SIGN = -1
losssum(p_net; sensealg = sensealg, solver = solver)
@test length(solution.events) == NUMEVENTS
GRAVITY_SIGN = -1
losssum_bb(p_net_bb; sensealg = sensealg, solver = solver)
@test events == NUMEVENTS
# Solution FWD (FMU)
GRAVITY_SIGN = -1
grad_fwd_f =
ForwardDiff.gradient(p -> losssum(p; sensealg = sensealg, solver = solver), p_net)
@test length(solution.events) == NUMEVENTS
# Solution FWD (right)
GRAVITY_SIGN = -1
root = :Right
grad_fwd_r = ForwardDiff.gradient(
p -> losssum_bb(p; sensealg = sensealg, root = root, solver = solver),
p_net_bb,
)
@test events == NUMEVENTS
# Solution RWD (FMU)
GRAVITY_SIGN = -1
grad_rwd_f =
ReverseDiff.gradient(p -> losssum(p; sensealg = sensealg, solver = solver), p_net)
@test length(solution.events) == NUMEVENTS
# Solution RWD (right)
GRAVITY_SIGN = -1
root = :Right
grad_rwd_r = ReverseDiff.gradient(
p -> losssum_bb(p; sensealg = sensealg, root = root, solver = solver),
p_net_bb,
)
@test events == NUMEVENTS
# Ground Truth
grad_fin_r = FiniteDiff.finite_difference_gradient(
p -> losssum_bb(p; sensealg = sensealg, root = :Right, solver = solver),
p_net_bb,
Val{:central};
absstep = 1e-6,
)
grad_fin_f = FiniteDiff.finite_difference_gradient(
p -> losssum(p; sensealg = sensealg, solver = solver),
p_net,
Val{:central};
absstep = 1e-6,
)
local atol = 1e-3
# check if finite differences match together
@test isapprox(grad_fin_f, grad_fin_r; atol = atol)
@test isapprox(grad_fin_f, grad_fwd_f; atol = atol)
@test isapprox(grad_fin_f, grad_rwd_f; atol = atol)
@test isapprox(grad_fwd_r, grad_rwd_r; atol = atol)
# Jacobian Test
jac_fwd_r = ForwardDiff.jacobian(
p -> mysolve_bb(p; sensealg = sensealg, solver = solver),
p_net,
)
@test !any(isnan.(jac_fwd_r))
jac_fwd_f =
ForwardDiff.jacobian(p -> mysolve(p; sensealg = sensealg, solver = solver), p_net)
@test !any(isnan.(jac_fwd_f))
jac_rwd_r = ReverseDiff.jacobian(
p -> mysolve_bb(p; sensealg = sensealg, solver = solver),
p_net,
)
@test !any(isnan.(jac_rwd_r))
jac_rwd_f =
ReverseDiff.jacobian(p -> mysolve(p; sensealg = sensealg, solver = solver), p_net)
@test !any(isnan.(jac_rwd_f))
# [TODO] why this?!
jac_rwd_r[2:end, :] = jac_rwd_r[2:end, :] .- jac_rwd_r[1:end-1, :]
jac_rwd_f[2:end, :] = jac_rwd_f[2:end, :] .- jac_rwd_f[1:end-1, :]
jac_fin_r = FiniteDiff.finite_difference_jacobian(
p -> mysolve_bb(p; sensealg = sensealg, solver = solver),
p_net,
)
jac_fin_f = FiniteDiff.finite_difference_jacobian(
p -> mysolve(p; sensealg = sensealg, solver = solver),
p_net,
)
###
local atol = 1e-3
@test isapprox(jac_fin_f, jac_fin_r; atol = atol)
@test isapprox(jac_fin_f, jac_fwd_f; atol = atol)
# [ToDo] whyever... but this is not required to work (but: too much atol here!)
@test isapprox(jac_fin_f, jac_rwd_f; atol = 0.5)
@test isapprox(jac_fin_r, jac_fwd_r; atol = atol)
@test isapprox(jac_fin_r, jac_rwd_r; atol = atol)
###
end
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | code | 4939 | #
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
using Flux
using DifferentialEquations: Tsit5, Rosenbrock23
import FMIFlux.FMIImport: fmi2FreeInstance!
import Random
Random.seed!(5678);
t_start = 0.0
t_step = 0.01
t_stop = 5.0
tData = t_start:t_step:t_stop
# generate training data
posData, velData, accData = syntTrainingData(tData)
# load FMU for NeuralFMU
fmu = loadFMU("SpringFrictionPendulum1D", EXPORTINGTOOL, EXPORTINGVERSION; type = :ME)
# loss function for training
losssum = function (p)
global problem, X0, posData
solution = problem(X0; p = p, saveat = tData)
if !solution.success
return Inf
end
#posNet = getState(solution, 1; isIndex=true)
velNet = getState(solution, 2; isIndex = true)
return Flux.Losses.mse(velNet, velData) # Flux.Losses.mse(posNet, posData)
end
vr = stringToValueReference(fmu, "mass.m")
numStates = length(fmu.modelDescription.stateValueReferences)
# some NeuralFMU setups
nets = []
global comp
comp = nothing
for handleEvents in [true, false]
@testset "handleEvents: $handleEvents" begin
for config in FMU_EXECUTION_CONFIGURATIONS
if config == FMU_EXECUTION_CONFIGURATION_NOTHING
@info "Skipping train modes testing for `FMU_EXECUTION_CONFIGURATION_NOTHING`."
continue
end
configstr = "$(config)"
@testset "config: $(configstr[1:64])..." begin
global problem, lastLoss, iterCB, comp
fmu.executionConfig = config
fmu.executionConfig.handleStateEvents = handleEvents
fmu.executionConfig.handleTimeEvents = handleEvents
fmu.executionConfig.externalCallbacks = true
fmu.executionConfig.loggingOn = true
fmu.executionConfig.assertOnError = true
fmu.executionConfig.assertOnWarning = true
@info "handleEvents: $(handleEvents) | instantiate: $(fmu.executionConfig.instantiate) | reset: $(fmu.executionConfig.reset) | terminate: $(fmu.executionConfig.terminate) | freeInstance: $(fmu.executionConfig.freeInstance)"
# if fmu.executionConfig.instantiate == false
# @info "instantiate = false, instantiating..."
# instantiate = true
# comp, _ = prepareSolveFMU(fmu, comp, :ME, instantiate, nothing, nothing, nothing, nothing, nothing, t_start, t_stop, nothing; x0=X0, handleEvents=FMIFlux.handleEvents, cleanup=true)
# end
c1 = CacheLayer()
c2 = CacheRetrieveLayer(c1)
net = Chain(
states -> fmu(; x = states, dx_refs = :all),
dx -> c1(dx),
Dense(numStates, 16, tanh),
Dense(16, 1, identity),
dx -> c2(1, dx[1]),
)
optim = OPTIMISER(ETA)
solver = Tsit5()
problem = ME_NeuralFMU(fmu, net, (t_start, t_stop), solver)
@test problem != nothing
solutionBefore = problem(X0; saveat = tData)
if solutionBefore.success
@test length(solutionBefore.states.t) == length(tData)
@test solutionBefore.states.t[1] == t_start
@test solutionBefore.states.t[end] == t_stop
end
# train it ...
p_net = Flux.params(problem)
iterCB = 0
lastLoss = losssum(p_net[1])
lastInstCount = length(problem.fmu.components)
@info "Start-Loss for net: $lastLoss"
lossBefore = losssum(p_net[1])
FMIFlux.train!(
losssum,
problem,
Iterators.repeated((), NUMSTEPS),
optim;
gradient = GRADIENT,
)
lossAfter = losssum(p_net[1])
@test lossAfter < lossBefore
# check results
solutionAfter = problem(X0; saveat = tData)
if solutionAfter.success
@test length(solutionAfter.states.t) == length(tData)
@test solutionAfter.states.t[1] == t_start
@test solutionAfter.states.t[end] == t_stop
end
# this is not possible, because some pullbacks are evaluated after simulation end
while length(problem.fmu.components) > 1
fmi2FreeInstance!(problem.fmu.components[end])
end
# if length(problem.fmu.components) == 1
# fmi2Reset(problem.fmu.components[end])
# end
end
end
end
end
unloadFMU(fmu)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 8232 | 
# FMIFlux.jl
## What is FMIFlux.jl?
[*FMIFlux.jl*](https://github.com/ThummeTo/FMIFlux.jl) is a free-to-use software library for the Julia programming language, which offers the ability to simply place your FMU ([fmi-standard.org](http://fmi-standard.org/)) everywhere inside of your ML topologies and still keep the resulting models trainable with a standard (or custom) FluxML training process. This includes for example:
- NeuralODEs including FMUs, so called *Neural Functional Mock-up Units* (NeuralFMUs):
You can place FMUs inside of your ML topology.
- PINNs including FMUs, so called *Functional Mock-Up Unit informed Neural Networks* (FMUINNs):
You can evaluate FMUs inside of your loss function.
[](https://ThummeTo.github.io/FMIFlux.jl/dev)
[](https://github.com/ThummeTo/FMIFlux.jl/actions/workflows/TestLatest.yml)
[](https://github.com/ThummeTo/FMIFlux.jl/actions/workflows/TestLTS.yml)
[](https://github.com/ThummeTo/FMIFlux.jl/actions/workflows/Example.yml)
[](https://github.com/ThummeTo/FMIFlux.jl/actions/workflows/Documentation.yml)
[](https://github.com/ThummeTo/FMIFlux.jl/actions/workflows/Eval.yml)
[](https://codecov.io/gh/ThummeTo/FMIFlux.jl)
[](https://github.com/SciML/ColPrac)
[](https://github.com/SciML/SciMLStyle)
## How can I use FMIFlux.jl?
1\. Open a Julia-REPL, switch to package mode using `]`, activate your preferred environment.
2\. Install [*FMIFlux.jl*](https://github.com/ThummeTo/FMIFlux.jl):
```julia-repl
(@v1) pkg> add FMIFlux
```
3\. If you want to check that everything works correctly, you can run the tests bundled with [*FMIFlux.jl*](https://github.com/ThummeTo/FMIFlux.jl):
```julia-repl
(@v1) pkg> test FMIFlux
```
4\. Have a look inside the [examples folder](https://github.com/ThummeTo/FMIFlux.jl/tree/examples/examples) in the examples branch or the [examples section](https://thummeto.github.io/FMIFlux.jl/dev/examples/overview/) of the documentation. All examples are available as Julia-Script (*.jl*), Jupyter-Notebook (*.ipynb*) and Markdown (*.md*).
## What is currently supported in FMIFlux.jl?
- building and training ME-NeuralFMUs (NeuralODEs) with support for event-handling (*DiffEqCallbacks.jl*) and discontinuous sensitivity analysis (*SciMLSensitivity.jl*)
- building and training CS-NeuralFMUs
- building and training NeuralFMUs consisting of multiple FMUs
- building and training FMUINNs (PINNs)
- different AD-frameworks: ForwardDiff.jl (CI-tested), ReverseDiff.jl (CI-tested, default setting), FiniteDiff.jl (not CI-tested) and Zygote.jl (not CI-tested)
- use `Flux.jl` optimizers as well as the ones from `Optim.jl`
- using the entire *DifferentialEquations.jl* solver suite (`autodiff=false` for implicit solvers, not all are tested, see following section)
- ...
## (Current) Limitations
- Not all implicit solvers work for challenging, hybrid models (stiff FMUs with events), currently tested are: `Rosenbrock23(autodiff=false)`.
- Implicit solvers using `autodiff=true` is not supported (now), but you can use implicit solvers with `autodiff=false`.
- Sensitivity information over state change by event $\partial x^{+} / \partial x^{-}$ can't be accessed in FMI.
These sensitivities are sampled if the FMU supports `fmiXGet/SetState`. If this feature is not available, wrong sensitivities are computed, which my influence your optimization (dependent on the use case).
This issue is also part of the [*OpenScaling*](https://itea4.org/project/openscaling.html) research project.
- If continuous adjoints instead of automatic differentiation through the ODE solver (discrete adjoint) are applied, this might lead to issues, because FMUs are by design not capable of being simulated backwards in time.
On the other hand, many FMUs are capable of doing so.
This issue is also part of the [*OpenScaling*](https://itea4.org/project/openscaling.html) research project.
- For now, only FMI version 2.0 is supported, but FMI 3.0 support is coming with the [*OpenScaling*](https://itea4.org/project/openscaling.html) research project.
## What is under development in FMIFlux.jl?
- performance optimizations
- multi threaded CPU training
- improved documentation
- more examples
- FMI3 integration
- ...
## What Platforms are supported?
[*FMIFlux.jl*](https://github.com/ThummeTo/FMIFlux.jl) is tested (and testing) under Julia versions *v1.6* (LTS) and *v1* (latest) on Windows (latest) and Ubuntu (latest). MacOS should work, but untested.
All shipped examples are automatically tested under Julia version *v1* (latest) on Windows (latest).
## What FMI.jl-Library should I use?

To keep dependencies nice and clean, the original package [*FMI.jl*](https://github.com/ThummeTo/FMI.jl) had been split into new packages:
- [*FMI.jl*](https://github.com/ThummeTo/FMI.jl): High level loading, manipulating, saving or building entire FMUs from scratch
- [*FMIImport.jl*](https://github.com/ThummeTo/FMIImport.jl): Importing FMUs into Julia
- [*FMIExport.jl*](https://github.com/ThummeTo/FMIExport.jl): Exporting stand-alone FMUs from Julia Code
- [*FMIBase.jl*](https://github.com/ThummeTo/FMIBase.jl): Common concepts for import and export of FMUs
- [*FMICore.jl*](https://github.com/ThummeTo/FMICore.jl): C-code wrapper for the FMI-standard
- [*FMISensitivity.jl*](https://github.com/ThummeTo/FMISensitivity.jl): Static and dynamic sensitivities over FMUs
- [*FMIBuild.jl*](https://github.com/ThummeTo/FMIBuild.jl): Compiler/Compilation dependencies for FMIExport.jl
- [*FMIFlux.jl*](https://github.com/ThummeTo/FMIFlux.jl): Machine Learning with FMUs
- [*FMIZoo.jl*](https://github.com/ThummeTo/FMIZoo.jl): A collection of testing and example FMUs
## Video-Workshops
### JuliaCon 2024 (Eindhoven University of Technology, Netherlands)
[](https://www.youtube.com/watch?v=sQ2MXSswrSo)
### JuliaCon 2023 (Massachusetts Institute of Technology, United States)
[](https://www.youtube.com/watch?v=X_u0KlZizD4)
## How to cite?
Tobias Thummerer, Johannes Stoljar and Lars Mikelsons. 2022. **NeuralFMU: presenting a workflow for integrating hybrid NeuralODEs into real-world applications.** Electronics 11, 19, 3202. [DOI: 10.3390/electronics11193202](https://doi.org/10.3390/electronics11193202)
Tobias Thummerer, Lars Mikelsons and Josef Kircher. 2021. **NeuralFMU: towards structural integration of FMUs into neural networks.** Martin Sjölund, Lena Buffoni, Adrian Pop and Lennart Ochel (Ed.). Proceedings of 14th Modelica Conference 2021, Linköping, Sweden, September 20-24, 2021. Linköping University Electronic Press, Linköping (Linköping Electronic Conference Proceedings ; 181), 297-306. [DOI: 10.3384/ecp21181297](https://doi.org/10.3384/ecp21181297)
## Related publications?
Tobias Thummerer, Johannes Tintenherr, Lars Mikelsons 2021. **Hybrid modeling of the human cardiovascular system using NeuralFMUs** Journal of Physics: Conference Series 2090, 1, 012155. [DOI: 10.1088/1742-6596/2090/1/012155](https://doi.org/10.1088/1742-6596/2090/1/012155)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 1538 | # Creation of the SSH deploy key for the CompatHelper
## 1. Create an ssh key pair.
This command is avaible for Windows (`cmd`) and Linux (`bash`).
```
ssh-keygen -N "" -f compathelper_key -t ed25519 -C compathelper
```
## 2. Copy the **private** key.
Copy the output to your clipboard.
1. Windows
```
type compathelper_key
```
1. Linux
```
cat compathelper_key
```
## 3. Create a GitHub secret.
1. Open the repository on the GitHub page.
1. Click on the **Settings** tab.
1. Click on **Secrets**.
1. Click on **Actions**.
1. Click on the **New repository secret** button.
1. Name the secret `COMPATHELPER_PRIV`.
1. Paste the **private** key as content.
## 4. Copy the **public** key.
Copy the output to your clipboard.
1. Windows
```
type compathelper_key.pub
```
1. Linux
```
cat compathelper_key.pub
```
## 5. Create a GitHub deploy key.
1. Open the repository on the GitHub page.
1. Click on the **Settings** tab.
1. Click on **Deploy keys**.
1. Click on the **Add deploy key** button.
1. Name the deploy key `COMPATHELPER_PUB`.
1. Paste the **public** key as content.
1. Enable the write access for the deploy key.
## 6. Delete the ssh key pair.
1. Windows
```
del compathelper_key compathelper_key.pub
```
1. Linux
```
rm -f compathelper_key compathelper_key.pub
```
For more Information click [here](https://docs.juliahub.com/CompatHelper/GCWpz/2.0.1/#Instructions-for-setting-up-the-SSH-deploy-key).
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 28 |
```@contents
Depth = 2
```
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 719 |
# FAQ
This list some common - often numerical - errors, that can be fixed by better understanding the ODE-Problem inside your FMU.
## Double callback crossing
### Description
Error message, a double zero-crossing happened, often during training a NeuralFMU.
### Example
- `Double callback crossing floating pointer reducer errored. Report this issue.`
### Reason
This could be, because the event inside of a NeuralFMU can't be located (often when using Zygote).
### Fix
- Try to increase the root search interpolation points, this is computational expensive for FMUs with many events- and event-indicators. This can be done using `fmu.executionConfig.rootSearchInterpolationPoints = 100` (default value is `10`). | FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 397 | # [Library Functions](@id library)
```@index
```
## FMIFlux functions
```@docs
CS_NeuralFMU
ME_NeuralFMU
NeuralFMU
```
## FMI 2 version dependent functions
```@docs
fmi2DoStepCS
fmi2EvaluateME
fmi2InputDoStepCSOutput
```
## FMI version independent functions
```@docs
fmiDoStepCS
fmiEvaluateME
fmiInputDoStepCSOutput
```
## Additional functions
```@docs
mse_interpolate
transferParams!
``` | FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 497 | # Related Publications
Thummerer T, Kircher J and Mikelsons L: __Neural FMU: Towards structual integration of FMUs into neural networks__ (Preprint, accepted 14th International Modelica Conference) [pdf](https://arxiv.org/abs/2109.04351)|DOI
Thummerer T, Tintenherr J, Mikelsons L: __Hybrid modeling of the human cardiovascular system using NeuralFMUs__ (Preprint, accepted 10th International Conference on Mathematical Modeling in Physical Sciences) [pdf](https://arxiv.org/abs/2109.04880)|DOI
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 2393 | # Examples - Overview
This section discusses the included examples of the FMIFlux.jl library. You can execute them on your machine and get detailed information about all of the steps.
If you require further information about the function calls, see [library functions](https://thummeto.github.io/FMIFlux.jl/dev/library/) section.
For more information related to the setup and simulation of an FMU see [FMI.jl library](https://thummeto.github.io/FMI.jl/dev/).
The examples are intended for users who work in the field of first principle and/or data driven modeling and are further interested in hybrid model building.
The examples show how to combine FMUs with machine learning ("NeuralFMU") and illustrates the advantages of this approach.
## Examples
- [__Simple CS-NeuralFMU__](https://thummeto.github.io/FMIFlux.jl/dev/examples/simple_hybrid_CS/): Showing how to train a NeuralFMU in Co-Simulation-Mode.
- [__Simple ME-NeuralFMU__](https://thummeto.github.io/FMIFlux.jl/dev/examples/simple_hybrid_ME/): Showing how to train a NeuralFMU in Model-Exchange-Mode.
## Advanced examples: Demo applications
- [__JuliaCon 2023: Using NeuralODEs in real life applications__](https://thummeto.github.io/FMIFlux.jl/dev/examples/juliacon_2023/): An example for a NeuralODE in a real world engineering scenario.
- [__Modelica Conference 2021: NeuralFMUs__](https://thummeto.github.io/FMIFlux.jl/dev/examples/modelica_conference_2021/): Showing basics on how to train a NeuralFMU (Contribution for the *Modelica Conference 2021*).
## Workshops
[Pluto](https://plutojl.org/) based notebooks, that can easily be executed on your own Pluto-Setup.
- [__Scientific Machine Learning using Functional Mock-up Units__](../pluto-src/SciMLUsingFMUs/SciMLUsingFMUs.html): Workshop at JuliaCon 2024 (Eindhoven University, Netherlands)
## Archived
- [__MDPI 2022: Physics-enhanced NeuralODEs in real-world applications__](https://thummeto.github.io/FMIFlux.jl/dev/examples/mdpi_2022/): An example for a NeuralODE in a real world modeling scenario (Contribution in *MDPI Electronics 2022*).
- [__Growing Horizon ME-NeuralFMU__](https://thummeto.github.io/FMIFlux.jl/dev/examples/growing_horizon_ME/): Growing horizon training technique for a ME-NeuralFMU.
- [__HybridModelingUsingFMI__](../pluto-src/HybridModelingUsingFMI/HybridModelingUsingFMI.html): Workshop at MODPROD 2024 (Linköping University, Sweden)
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 197 | [Pluto](https://plutojl.org/) based notebooks, that can easyly be executed on your own Pluto-Setup.
```@raw html
<iframe src="../pluto-src/index.html" style="height:500px;width:100%;"></iframe>
``` | FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 1314 | 
# Structure
Examples can be found in the [examples folder in the examples branch](https://github.com/ThummeTo/FMIFlux.jl/tree/examples/examples) or the [examples section of the documentation](https://thummeto.github.io/FMIFlux.jl/dev/examples/overview/). All examples are available as Julia-Script (*.jl*), Jupyter-Notebook (*.ipynb*) and Markdown (*.md*).
# Getting Started
## Install Jupyter in Visual Studio Code
The Jupyter Notebooks extension for Visual Studio Code can be [here](https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter).
## Add Julia Kernel to Jupyter
To run Julia as kernel in a jupyter notebook it is necessary to add the **IJulia** package.
1. Start the Julia REPL.
```
julia
```
2. Select your environment.
```julia
using Pkg
Pkg.activate("Your Env")
```
3. Add and build the IJulia package by typing inside the Julia REPL.
```julia
using Pkg
Pkg.add("IJulia")
Pkg.build("IJulia")
```
4. Now you should be able to choose a Julia kernel in a Jupyter notebook.
More information can be found [here](https://towardsdatascience.com/how-to-best-use-julia-with-jupyter-82678a482677).
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.13.0 | 7fec0fac72076ea32823fb59efcc0e280cd28162 | docs | 208 | 
# Acknowledgement
We thank *Florian Schläffer* for designing the beautiful library logo.
| FMIFlux | https://github.com/ThummeTo/FMIFlux.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 979 | using Documenter
using NATS
using NATS.JetStream
makedocs(
sitename = "NATS",
format = Documenter.HTML(),
modules = [NATS],
pages = [
"index.md",
"Core NATS" => [
"examples.md",
"connect.md",
"pubsub.md",
"reqreply.md",
"custom-data.md",
"scoped_connection.md",
"debugging.md",
],
"JetStream" => [
"jetstream/stream.md"
"jetstream/consumer.md"
"jetstream/keyvalue.md"
"jetstream/jetdict.md"
"jetstream/jetchannel.md"
],
"Internals" => [
"protocol.md",
"interrupt_handling.md",
"benchmarks.md",
]
]
)
# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
deploydocs(
repo = "github.com/jakubwro/NATS.jl"
)
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 23657 | using Markdown
typemap = Dict("string" => :String, "bool" => :Bool, "int" => :Int, "uint64" => :UInt64, "[string]" => :(Vector{String}))
function parse_operations(operations)
parse_row(row) = (name = row[1][1].text[1].code)
ops = map(parse_row, operations.content[1].rows[2:end])
ops = map(op -> strip(op, ['+', '-']), ops)
Expr(:macrocall, Symbol("@enum"), :(), :ProtocolOperation, Symbol.(ops)...)
end
function parse_row(row)
all(isempty, row) && return nothing, nothing
parse_row(row) = (name = row[1][1].code, type = row[3][1], presence = row[4][1], desc = Markdown.plaininline(row[2]))
(name, type, presence, desc) = parse_row(row)
name = replace(name, "-" => "_", " " => "_", "#" => "")
prop_type = typemap[type]
if presence != "always" && presence != "true"
prop_type = Expr(:curly, :Union, prop_type, :Nothing)
end
desc, Expr(:(::), Symbol(name), prop_type)
end
function parse_markdown(md::Markdown.MD, struct_name::Symbol)
expr = quote
struct $struct_name <: ProtocolMessage
$(filter(!isnothing, collect(Iterators.flatten(map(parse_row, md.content[2].rows[2:end]))))...)
end
end
doc = Markdown.plaininline(md.content[1].content)
expr = Base.remove_linenums!(expr)
doc, expr.args[1]
end
operations = md"""
| OP Name | Sent By | Description |
|-------------------------|---------|------------------------------------------------------------------------------------|
| [`INFO`](./#info) | Server | Sent to client after initial TCP/IP connection |
| [`CONNECT`](./#connect) | Client | Sent to server to specify connection information |
| [`PUB`](./#pub) | Client | Publish a message to a subject, with optional reply subject |
| [`HPUB`](./#hpub) | Client | Publish a message to a subject including NATS headers, with optional reply subject |
| [`SUB`](./#sub) | Client | Subscribe to a subject (or subject wildcard) |
| [`UNSUB`](./#unsub) | Client | Unsubscribe (or auto-unsubscribe) from subject |
| [`MSG`](./#msg) | Server | Delivers a message payload to a subscriber |
| [`HMSG`](./#hmsg) | Server | Delivers a message payload to a subscriber with NATS headers |
| [`PING`](./#pingpong) | Both | PING keep-alive message |
| [`PONG`](./#pingpong) | Both | PONG keep-alive response |
| [`+OK`](./#okerr) | Server | Acknowledges well-formed protocol message in `verbose` mode |
| [`-ERR`](./#okerr) | Server | Indicates a protocol error. May cause client disconnect. |
"""
# FIXME: duplicated client_id, report bug to nats docs.
# | `client_id` | The ID of the client. | string | optional |
info = md"""
A client will need to start as a plain TCP connection, then when the server accepts a connection from the client, it will send information about itself, the configuration and security requirements necessary for the client to successfully authenticate with the server and exchange messages.
When using the updated client protocol (see CONNECT below), INFO messages can be sent anytime by the server. This means clients with that protocol level need to be able to asynchronously handle INFO messages.
| name | description | type | presence |
|-------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|----------|
| `server_id` | The unique identifier of the NATS server. | string | always |
| `server_name` | The name of the NATS server. | string | always |
| `version` | The version of NATS. | string | always |
| `go` | The version of golang the NATS server was built with. | string | always |
| `host` | The IP address used to start the NATS server, by default this will be `0.0.0.0` and can be configured with `-client_advertise host:port`. | string | always |
| `port` | The port number the NATS server is configured to listen on. | int | always |
| `headers` | Whether the server supports headers. | bool | always |
| `max_payload` | Maximum payload size, in bytes, that the server will accept from the client. | int | always |
| `proto` | An integer indicating the protocol version of the server. The server version 1.2.0 sets this to `1` to indicate that it supports the "Echo" feature. | int | always |
| `client_id` | The internal client identifier in the server. This can be used to filter client connections in monitoring, correlate with error logs, etc... | uint64 | optional |
| `auth_required` | If this is true, then the client should try to authenticate upon connect. | bool | optional |
| `tls_required` | If this is true, then the client must perform the TLS/1.2 handshake. Note, this used to be `ssl_required` and has been updated along with the protocol from SSL to TLS.| bool | optional |
| `tls_verify` | If this is true, the client must provide a valid certificate during the TLS handshake. | bool | optional |
| `tls_available` | If this is true, the client can provide a valid certificate during the TLS handshake. | bool | optional |
| `connect_urls` | List of server urls that a client can connect to. | [string] | optional |
| `ws_connect_urls` | List of server urls that a websocket client can connect to. | [string] | optional |
| `ldm` | If the server supports _Lame Duck Mode_ notifications, and the current server has transitioned to lame duck, `ldm` will be set to `true`. | bool | optional |
| `git_commit` | The git hash at which the NATS server was built. | string | optional |
| `jetstream` | Whether the server supports JetStream. | bool | optional |
| `ip` | The IP of the server. | string | optional |
| `client_ip` | The IP of the client. | string | optional |
| `nonce` | The nonce for use in CONNECT. | string | optional |
| `cluster` | The name of the cluster. | string | optional |
| `domain` | The configured NATS domain of the server. | string | optional |
"""
connect = md"""
The CONNECT message is the client version of the `INFO` message. Once the client has established a TCP/IP socket connection with the NATS server, and an `INFO` message has been received from the server, the client may send a `CONNECT` message to the NATS server to provide more information about the current connection as well as security information.
| name | description | type | required |
|-----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------|------------------------------|
| `verbose` | Turns on [`+OK`](./#NATS.Ok) protocol acknowledgements. | bool | true |
| `pedantic` | Turns on additional strict format checking, e.g. for properly formed subjects. | bool | true |
| `tls_required` | Indicates whether the client requires SSL connection. | bool | true |
| `auth_token` | Client authorization token. | string | if `auth_required` is `true` |
| `user` | Connection username. | string | if `auth_required` is `true` |
| `pass` | Connection password. | string | if `auth_required` is `true` |
| `name` | Client name. | string | false |
| `lang` | The implementation language of the client. | string | true |
| `version` | The version of the client. | string | true |
| `protocol` | Sending `0` (or absent) indicates client supports original protocol. Sending `1` indicates that the client supports dynamic reconfiguration of cluster topology changes by asynchronously receiving [`INFO`](./#NATS.Info) messages with known servers it can reconnect to. | int | false |
| `echo` | If set to `false`, the server (version 1.2.0+) will not send originating messages from this connection to its own subscriptions. Clients should set this to `false` only for server supporting this feature, which is when `proto` in the `INFO` protocol is set to at least `1`. | bool | false |
| `sig` | In case the server has responded with a `nonce` on `INFO`, then a NATS client must use this field to reply with the signed `nonce`. | string | if `nonce` received |
| `jwt` | The JWT that identifies a user permissions and account. | string | false |
| `no_responders` | Enable quick replies for cases where a request is sent to a topic with no responders. | bool | false |
| `headers` | Whether the client supports headers. | bool | false |
| `nkey` | The public NKey to authenticate the client. This will be used to verify the signature (`sig`) against the `nonce` provided in the `INFO` message. | string | false |
"""
pub = md"""
The PUB message publishes the message payload to the given subject name, optionally supplying a reply subject. If a reply subject is supplied, it will be delivered to eligible subscribers along with the supplied payload. Note that the payload itself is optional. To omit the payload, set the payload size to 0, but the second CRLF is still required.
| name | description | type | required |
|------------|-----------------------------------------------------------------------------------------------|--------|----------|
| `subject` | The destination subject to publish to. | string | true |
| `reply-to` | The reply subject that subscribers can use to send a response back to the publisher/requestor.| string | false |
| `#bytes` | The payload size in bytes. | int | true |
| `payload` | The message payload data. | string | optional |
"""
hpub = md"""
The HPUB message is the same as PUB but extends the message payload to include NATS headers. Note that the payload itself is optional. To omit the payload, set the total message size equal to the size of the headers. Note that the trailing CR+LF is still required.
| name | description | type | required |
|-----------------|-------------------------------------------------------------------------------------------------|--------|----------|
| `subject` | The destination subject to publish to. | string | true |
| `reply-to` | The reply subject that subscribers can use to send a response back to the publisher/requestor. | string | false |
| `#header bytes` | The size of the headers section in bytes including the `␍␊␍␊` delimiter before the payload. | int | true |
| `#total bytes` | The total size of headers and payload sections in bytes. | int | true |
| `headers` | Header version `NATS/1.0␍␊` followed by one or more `name: value` pairs, each separated by `␍␊`.| string | false |
| `payload` | The message payload data. | string | false |
"""
sub = md"""
`SUB` initiates a subscription to a subject, optionally joining a distributed queue group.
| name | description | type | required |
|---------------|----------------------------------------------------------------|--------|----------|
| `subject` | The subject name to subscribe to. | string | true |
| `queue group` | If specified, the subscriber will join this queue group. | string | false |
| `sid` | A unique alphanumeric subscription ID, generated by the client.| string | true |
"""
unsub = md"""
`UNSUB` unsubscribes the connection from the specified subject, or auto-unsubscribes after the specified number of messages has been received.
| name | description | type | required |
|------------|----------------------------------------------------------------------------|--------|----------|
| `sid` | The unique alphanumeric subscription ID of the subject to unsubscribe from.| string | true |
| `max_msgs` | A number of messages to wait for before automatically unsubscribing. | int | false |
"""
msg = md"""
The `MSG` protocol message is used to deliver an application message to the client.
| name | description | type | presence |
|------------|---------------------------------------------------------------|--------|----------|
| `subject` | Subject name this message was received on. | string | always |
| `sid` | The unique alphanumeric subscription ID of the subject. | string | always |
| `reply-to` | The subject on which the publisher is listening for responses.| string | optional |
| `#bytes` | Size of the payload in bytes. | int | always |
| `payload` | The message payload data. | string | optional |
"""
hmsg = md"""
The HMSG message is the same as MSG, but extends the message payload with headers. See also [ADR-4 NATS Message Headers](https://github.com/nats-io/nats-architecture-and-design/blob/main/adr/ADR-4.md).
| name | description | type | presence |
|-----------------|-------------------------------------------------------------------------------------------------|--------|----------|
| `subject` | Subject name this message was received on. | string | always
| `sid` | The unique alphanumeric subscription ID of the subject. | string | always |
| `reply-to` | The subject on which the publisher is listening for responses. | string | optional |
| `#header bytes` | The size of the headers section in bytes including the `␍␊␍␊` delimiter before the payload. | int | always |
| `#total bytes` | The total size of headers and payload sections in bytes. | int | always |
| `headers` | Header version `NATS/1.0␍␊` followed by one or more `name: value` pairs, each separated by `␍␊`.| string | optional |
| `payload` | The message payload data. | string | optional |
"""
ping = md"""
`PING` and `PONG` implement a simple keep-alive mechanism between client and server.
| name | description | type | presence |
|------|--------------|--------|----------|
| | | | |
"""
pong = md"""
`PING` and `PONG` implement a simple keep-alive mechanism between client and server.
| name | description | type | presence |
|------|--------------|--------|----------|
| | | | |
"""
err = md"""
The `-ERR` message is used by the server indicate a protocol, authorization, or other runtime connection error to the client. Most of these errors result in the server closing the connection.
| name | description | type | presence |
|-----------|----------------|--------|----------|
| `message` | Error message. | string | always |
"""
ok = md"""
When the `verbose` connection option is set to `true` (the default value), the server acknowledges each well-formed protocol message from the client with a `+OK` message.
| name | description | type | presence |
|------|--------------|--------|----------|
| | | | |
"""
docs = [info, connect, pub, hpub, sub, unsub, msg, hmsg, ping, pong, err, ok]
structs = [:Info, :Connect, :Pub, :HPub, :Sub, :Unsub, :Msg, :HMsg, :Ping, :Pong, :Err, :Ok]
open("../src/protocol/structs.jl", "w") do f;
println(f, "# This file is autogenerated by `$(relpath(@__FILE__, dirname(@__DIR__)))`. Maunal changes will be lost.")
println(f)
# println(f, parse_operations(operations))
# println(f)
println(f, "abstract type ProtocolMessage end")
for (doc, struct_def) in parse_markdown.(docs, structs)
println(f)
println(f, "\"\"\"")
println(f, doc)
println(f)
println(f, "\$(TYPEDFIELDS)")
println(f, "\"\"\"")
println(f, struct_def)
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2299 | ### NATS.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file aggregates all files of NATS.jl package.
#
### Code:
module NATS
using Random
using Sockets
using StructTypes
using JSON3
using MbedTLS
using DocStringExtensions
using BufferedStreams
using Sodium
using CodecBase
using ScopedValues
using URIs
import Base: show, convert
export NATSError
export connect, reconnect, ping, drain
export payload, header, headers
export publish, subscribe, unsubscribe, next
export request, reply
export with_connection
export JetStream
const DEFAULT_HOST = "localhost"
const DEFAULT_PORT = "4222"
const DEFAULT_CONNECT_URL = "nats://$(DEFAULT_HOST):$(DEFAULT_PORT)"
const CLIENT_VERSION = "0.1.0"
const CLIENT_LANG = "julia"
const MIME_PROTOCOL = MIME"application/nats"
const MIME_PAYLOAD = MIME"application/nats-payload"
const MIME_HEADERS = MIME"application/nats-headers"
# Granular reconnect retries configuration
#TODO: ADR-40 says it should be 3.
const DEFAULT_RECONNECT_RETRIES = 220752000000000000 # 7 bilion years.
const DEFAULT_RECONNECT_FIRST_DELAY = 0.1
const DEFAULT_RECONNECT_MAX_DELAY = 5.0
const DEFAULT_RECONNECT_FACTOR = 5.0
const DEFAULT_RECONNECT_JITTER = 0.1
const DEFAULT_SEND_BUFFER_LIMIT_BYTES = 2 * 2^20 # 2 MB
const DEFAULT_PING_INTERVAL_SECONDS = 2.0 * 60.0
const DEFAULT_MAX_PINGS_OUT = 2
const DEFAULT_RETRY_ON_INIT_FAIL = false
const DEFAULT_IGNORE_ADVERTISED_SERVERS = false
const DEFAULT_RETAIN_SERVERS_ORDER = false
const DEFAULT_ENQUEUE_WHEN_DISCONNECTED = true # If set to true messages will be enqueued when connection lost, otherwise exception will be thrown.
const DEFAULT_SUBSCRIPTION_CHANNEL_SIZE = 512 * 1024
const DEFAULT_SUBSCRIPTION_ERROR_THROTTLING_SECONDS = 5.0
const DEFAULT_REQUEST_TIMEOUT_SECONDS = 5.0
const DEFAULT_DRAIN_TIMEOUT_SECONDS = 5.0
const DEFAULT_DRAIN_POLL_INTERVAL_SECONDS = 0.2
const INVOKE_LATEST_CONVERSIONS = false # TODO: use this in code
include("protocol/protocol.jl")
include("connection/connection.jl")
include("pubsub/pubsub.jl")
include("reqreply/reqreply.jl")
include("experimental/experimental.jl")
include("jetstream/JetStream.jl")
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 19009 | ### connect.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains functions for estabilishing connection and maintaining connectivity when TCP connection fails.
#
### Code:
function default_connect_options()
(
# Options that are defined in the protocol, see Connect struct.
verbose= parse(Bool, get(ENV, "NATS_VERBOSE", "false")),
pedantic = parse(Bool, get(ENV, "NATS_PEDANTIC", "false")),
tls_required = parse(Bool, get(ENV, "NATS_TLS_REQUIRED", "false")),
auth_token = get(ENV, "NATS_AUTH_TOKEN", nothing),
user = get(ENV, "NATS_USER", nothing),
pass = get(ENV, "NATS_PASS", nothing),
name = nothing,
lang = CLIENT_LANG,
version = CLIENT_VERSION,
protocol = 1,
echo = nothing,
sig = nothing,
jwt = get(ENV, "NATS_JWT", nothing),
no_responders = true,
headers = true,
nkey = get(ENV, "NATS_NKEY", nothing),
# Options used only on client side, never sent to server.
nkey_seed = get(ENV, "NATS_NKEY_SEED", nothing),
tls_ca_path = get(ENV, "NATS_TLS_CA_PATH", nothing),
tls_cert_path = get(ENV, "NATS_TLS_CERT_PATH", nothing),
tls_key_path = get(ENV, "NATS_TLS_KEY_PATH", nothing),
ping_interval = parse(Float64, get(ENV, "NATS_PING_INTERVAL", string(DEFAULT_PING_INTERVAL_SECONDS))),
max_pings_out = parse(Int64, get(ENV, "NATS_MAX_PINGS_OUT", string(DEFAULT_MAX_PINGS_OUT))),
retry_on_init_fail = parse(Bool, get(ENV, "NATS_RETRY_ON_INIT_FAIL", string(DEFAULT_RETRY_ON_INIT_FAIL))),
ignore_advertised_servers = parse(Bool, get(ENV, "NATS_IGNORE_ADVERTISED_SERVERS", string(DEFAULT_IGNORE_ADVERTISED_SERVERS))),
retain_servers_order = parse(Bool, get(ENV, "NATS_RETAIN_SERVERS_ORDER", string(DEFAULT_RETAIN_SERVERS_ORDER))),
send_enqueue_when_disconnected = parse(Bool, get(ENV, "NATS_ENQUEUE_WHEN_DISCONNECTED", string(DEFAULT_ENQUEUE_WHEN_DISCONNECTED))),
reconnect_delays = default_reconnect_delays(),
send_buffer_limit = parse(Int, get(ENV, "NATS_SEND_BUFFER_LIMIT_BYTES", string(DEFAULT_SEND_BUFFER_LIMIT_BYTES))),
send_retry_delays = SEND_RETRY_DELAYS,
drain_timeout = parse(Float64, get(ENV, "NATS_DRAIN_TIMEOUT_SECONDS", string(DEFAULT_DRAIN_TIMEOUT_SECONDS))),
drain_poll = parse(Float64, get(ENV, "NATS_DRAIN_POLL_INTERVAL_SECONDS", string(DEFAULT_DRAIN_POLL_INTERVAL_SECONDS))),
)
end
function default_reconnect_delays()
ExponentialBackOff(
n = parse(Int64, get(ENV, "NATS_RECONNECT_RETRIES", string(DEFAULT_RECONNECT_RETRIES))),
first_delay = parse(Float64, get(ENV, "NATS_RECONNECT_FIRST_DELAY", string(DEFAULT_RECONNECT_FIRST_DELAY))),
max_delay = parse(Float64, get(ENV, "NATS_RECONNECT_MAX_DELAY", string(DEFAULT_RECONNECT_MAX_DELAY))),
factor = parse(Float64, get(ENV, "NATS_RECONNECT_FACTOR", string(DEFAULT_RECONNECT_FACTOR))),
jitter = parse(Float64, get(ENV, "NATS_RECONNECT_JITTER", string(DEFAULT_RECONNECT_JITTER))))
end
function validate_connect_options(server_info::Info, options)
# TODO: check if proto is 1 when `echo` flag is set
# TODO: maybe better to rely on server side validation. Grab Err messages and decide if conn should be terminated.
server_info.proto > 0 || error("Server supports too old protocol version.")
server_info.headers || error("Server does not support headers.") # TODO: maybe this can be relaxed.
# Check TLS requirements
if get(options, :tls_required, false)
!isnothing(server_info.tls_available) && server_info.tls_available || error("Client requires TLS but it is not available for the server.")
end
end
function host_port(url::AbstractString)
if !contains(url, "://")
url = "nats://$url"
end
uri = URI(url)
host, port, scheme, userinfo = uri.host, uri.port, uri.scheme, uri.userinfo
if isempty(host)
error("Host not specified in url `$url`.")
end
if isempty(port)
port = DEFAULT_PORT
end
host, parse(Int, port), scheme, userinfo
end
function connect_urls(nc::Connection, url; ignore_advertised_servers::Bool)
info_msg = info(nc)
if ignore_advertised_servers || isnothing(info_msg) || isnothing(info_msg.connect_urls) || isempty(info_msg.connect_urls)
split(url, ",")
else
info_msg.connect_urls
end
end
function init_protocol(nc, url, options)
@atomic nc.connect_init_count += 1
urls = connect_urls(nc, url; options.ignore_advertised_servers)
if options.retain_servers_order
idx = mod((@atomic nc.connect_init_count) - 1, length(urls)) + 1
url = urls[idx]
else
url = rand(urls)
end
host, port, scheme, userinfo = host_port(url)
if scheme == "tls"
# Due to ADR-40 url schema can enforce TLS.
options = merge(options, (tls_required = true,))
end
if !isnothing(userinfo) && !isempty(userinfo)
user, pass = split(userinfo, ":"; limit = 2)
if !haskey(options, :user) || isnothing(options.user)
options = merge(options, (user = user,))
end
if !haskey(options, :pass) || isnothing(options.pass)
options = merge(options, (pass = pass,))
end
end
sock = Sockets.connect(host, port)
try
info_msg = next_protocol_message(sock)
info_msg isa Info || error("Expected INFO, received $info_msg")
validate_connect_options(info_msg, options)
read_stream, write_stream = sock, sock
if !isnothing(info_msg.tls_required) && info_msg.tls_required
tls_options = options[(:tls_ca_path, :tls_cert_path, :tls_key_path)]
(read_stream, write_stream) = upgrade_to_tls(sock, tls_options...)
@debug "Socket upgraded"
end
if !isnothing(info_msg.nonce)
isnothing(options.nkey_seed) && error("Server requires signature but no `nkey_seed` provided.")
isnothing(options.nkey) && error("Missing `nkey` parameter.")
sig = sign(info_msg.nonce, options.nkey_seed)
options = merge(options, (sig = sig,))
end
defaults = default_connect_options()
known_options = keys(defaults)
provided_keys = keys(options)
keys_df = setdiff(provided_keys, known_options)
!isempty(keys_df) && error("Unknown `connect` options: $(join(keys_df, ", "))")
connect_msg = StructTypes.constructfrom(Connect, options)
show(write_stream, MIME_PROTOCOL(), connect_msg)
flush(write_stream)
show(write_stream, MIME_PROTOCOL(), Ping())
flush(write_stream)
msg = next_protocol_message(read_stream)
msg isa Union{Ok, Err, Pong, Ping} || error("Expected +OK, -ERR, PING or PONG , received $msg")
while true
if msg isa Ping
show(write_stream, MIME_PROTOCOL(), Pong())
elseif msg isa Err
error(msg.message)
elseif msg isa Pong
break # This is what we waiting for.
elseif msg isa Ok
# Do nothing, verbose protocol.
else
error("Unexpected message received $msg")
end
msg = next_protocol_message(read_stream)
end
if !isnothing(nc)
nc.url = url
end
sock, read_stream, write_stream, info_msg
catch err
close(sock)
rethrow()
end
end
function receiver(nc::Connection, io::IO)
# @show Threads.threadid()
parser_loop(io) do msg
process(nc, msg)
end
end
function ping_loop(nc::Connection, ping_interval::Float64, max_pings_out::Int64)
pings_out = 0
reconnects = (@atomic nc.reconnect_count)
while status(nc) == CONNECTED && reconnects == (@atomic nc.reconnect_count)
sleep(ping_interval)
if !(status(nc) == CONNECTED && reconnects == (@atomic nc.reconnect_count))
# In case if connection is broken new task will be spawned.
# If another reconnect occured in meanwhile, stop this task cause another was already spawned.
break
end
try
_, tm = @timed ping(nc)
pings_out = 0
@debug "PONG received after $tm seconds"
catch
@debug "No PONG received."
pings_out += 1
end
if pings_out > max_pings_out
@warn "No pong received after $pings_out attempts."
break
end
end
end
#TODO: restore link #NATS.Connect
"""
$(SIGNATURES)
Connect to NATS server. The function is blocking until connection is
initialized. In case of error during initialization process `connect` will
throw exception if `retry_on_init_fail` is set to `false` (what is default).
Otherwise handle will be returned and reconnect will continue in background.
Options are:
- `verbose`: turns on protocol acknowledgements
- `pedantic`: turns on additional strict format checking, e.g. for properly formed subjects
- `tls_required`: indicates whether the client requires SSL connection
- `tls_ca_path`: CA certuficate file path
- `tls_cert_path`: client public certificate file
- `tls_key_path`: client private certificate file
- `auth_token`: client authorization token
- `user`: connection username
- `pass`: connection password
- `name`: client name
- `echo`: if set to `false`, the server will not send originating messages from this connection to its own subscriptions
- `jwt`: the JWT that identifies a user permissions and account.
- `no_responders`: enable quick replies for cases where a request is sent to a topic with no responders.
- `nkey`: the public NKey to authenticate the client
- `nkey_seed`: the private NKey to authenticate the client
- `ping_interval`: interval in seconds how often server should be pinged to check connection health. Default is $DEFAULT_PING_INTERVAL_SECONDS seconds
- `max_pings_out`: how many pings in a row might fail before connection will be restarted. Default is `$DEFAULT_MAX_PINGS_OUT`
- `retry_on_init_fail`: if set connection handle will be returned even if initial connect fails. Otherwise error causing failure will be trown. Default is `$DEFAULT_RETRY_ON_INIT_FAIL`
- `ignore_advertised_servers`: ignores other cluster servers returned by server. Default is `$DEFAULT_IGNORE_ADVERTISED_SERVERS`
- `retain_servers_order`: try to connect server in order specified in `url` or list returned by the server. Defaylt is `$DEFAULT_RETAIN_SERVERS_ORDER`
- `send_enqueue_when_disconnected`: allows buffering outgoing messages during disconnection. Default is `$DEFAULT_ENQUEUE_WHEN_DISCONNECTED`
- `reconnect_delays`: vector of delays that reconnect is performed until connected again, by default it will try to reconnect every second without time limit.
- `send_buffer_limit`: soft limit for buffer of messages pending. Default is `$DEFAULT_SEND_BUFFER_LIMIT_BYTES` bytes, if too small operations that send messages to server (e.g. `publish`) may throw an exception
- `drain_timeout`: Timeout for drain process. After timeout in case of not everyting is processed drain will stop and error will be reported.
- `drain_poll`: Interval for `drain` to check if all messages in buffers are processed.
"""
function connect(
url::String = get(ENV, "NATS_CONNECT_URL", DEFAULT_CONNECT_URL);
options...
)
options = merge(default_connect_options(), options)
nc = Connection(;
url,
info = nothing,
reconnect_count = 0,
connect_init_count = 0,
send_buffer_flushed = true,
options.send_buffer_limit,
options.send_retry_delays,
options.send_enqueue_when_disconnected,
options.drain_timeout,
options.drain_poll)
sock = nothing
read_stream = nothing
write_stream = nothing
info_msg = nothing
try
sock, read_stream, write_stream, info_msg = init_protocol(nc, url, options)
info(nc, info_msg)
status(nc, CONNECTED)
catch
if !options.retry_on_init_fail
rethrow()
end
end
# This task just waits for `drain_even`, to wake up `reconnect_task` that there is cleanup to do.
drain_await_task = Threads.@spawn :interactive disable_sigint() do
wait(nc.drain_event)
end
# This works as controller for connection state. It spawns other task and listens for their completion to do
# reconnect logic.
reconnect_task = Threads.@spawn :interactive disable_sigint() do
# @show Threads.threadid()
while true
if status(nc) == CONNECTING
start_time = time()
# TODO: handle repeating server Err messages.
start_reconnect_time = time()
function check_errors(s, e)
total_retries = length(options.reconnect_delays)
current_retries = total_retries - s[1]
current_time = time() - start_reconnect_time
mod(current_retries, 10) == 0 && @warn "Reconnect to $(clustername(nc)) cluster failed $current_retries times in $current_time seconds." e
(@atomic nc.drain_event.set) == false # Stop on drain
end
retry_init_protocol = retry(init_protocol, delays=options.reconnect_delays, check = check_errors)
try
sock, read_stream, write_stream, info_msg = retry_init_protocol(nc, url, options)
status(nc, CONNECTED)
catch err
time_diff = time() - start_reconnect_time
@error "Connection disconnected after $(nc.connect_init_count) reconnect retries, it took $time_diff seconds." err
if (@atomic nc.drain_event.set) == true
status(nc, DRAINING)
_do_drain(nc, false)
status(nc, DRAINED)
else
status(nc, DISCONNECTED)
end
end
if status(nc) == CONNECTED
@atomic nc.reconnect_count += 1
info(nc, info_msg)
@info "Reconnected to $(clustername(nc)) cluster on `$(nc.url)` after $(time() - start_time) seconds."
elseif status(nc) == DISCONNECTED
wait(nc.reconnect_event)
@debug "Reconnect requested"
if (@atomic nc.drain_event.set) == true
status(nc, DRAINING)
_do_drain(nc, false)
status(nc, DRAINED)
break
else
status(nc, CONNECTING)
continue
end
elseif status(nc) == DRAINED
break
end
end
receiver_task = Threads.@spawn :interactive disable_sigint() do; receiver(nc, read_stream) end
sender_task = Threads.@spawn :interactive disable_sigint() do; sendloop(nc, write_stream) end
ping_task = Threads.@spawn :interactive disable_sigint() do; ping_loop(nc, options.ping_interval, options.max_pings_out) end
reconnect_await_task = Threads.@spawn :interactive disable_sigint() do; wait(nc.reconnect_event) end
tasks = [receiver_task, sender_task, ping_task, reconnect_await_task, drain_await_task]
names = ["receiver", "sender", "ping", "reconnect", "drain"]
err_channel = Channel()
for task in tasks
bind(err_channel, task)
end
try
wait(err_channel)
catch err
if !(err isa InvalidStateException)
@debug "Error caused wake up" err
end
end
cleanup_start = time()
reason = join(names[istaskdone.(tasks)], ", ")
@debug "Controller task woken by: $reason"
if istaskdone(drain_await_task)
status(nc, DRAINING)
# Check if there is a chance for send buffer flush.
is_connected = !(istaskdone(sender_task) || istaskdone(receiver_task))
_do_drain(nc, is_connected)
status(nc, DRAINED)
reopen_send_buffer(nc)
close(sock)
break
end
notify(nc.reconnect_event) # Finish reconnect_await_task.
# TODO: maybe `autoreset` should be used, but special care needs to be taken to not consume it anywhere else.
reset(nc.reconnect_event) # Reset event to prevent forever reconnect.
reopen_send_buffer(nc) # Finish sender_task.
close(sock) # Finish receiver_task.
#TODO: maybe in some case waiting for tasks to finish is not needed, it will shortned reconnect time 10x
try wait(sender_task) catch end
try wait(receiver_task) catch end
try wait(reconnect_await_task) catch end
# `ping_task` will complete eventually seeing `reconnect_count` increased.
@assert istaskdone(receiver_task)
@assert istaskdone(sender_task)
@assert istaskdone(reconnect_await_task)
@warn "Connection to $(clustername(nc)) cluster on `$(nc.url)` lost, trynig to reconnect."
status(nc, CONNECTING)
@atomic nc.connect_init_count = 0
@debug "Cleanup time: $(time() - cleanup_start) seconds"
end
end
errormonitor(reconnect_task)
@lock state.lock push!(state.connections, nc)
nc
end
"""
$(SIGNATURES)
Force a connection reconnect. If connection is `CONNECTED` this will close it
and reopen again resubscribing all existing subscriptions. If connection is
`DISCONNECTED` it will try to connect with all previously existing subscription
restored. In case connection is already `CONNECTING` this method have no effect.
If called on connection that is `DRAINING` or `DRAINED` error will be thrown.
During reconnect period some messages both published and received by the
connection might be lost.
Optional keyword aruguments:
- `should_wait`: If `true` method will block until reconnection process is started, default is `true`.
"""
function reconnect(connection::NATS.Connection; should_wait::Bool = true)
@lock connection.status_change_cond begin
if connection.status == DRAINING || connection.status == DRAINED
error("Cannot reconnect a drained connection.")
end
notify(connection.reconnect_event)
while should_wait && connection.status != CONNECTING
wait(connection.status_change_cond)
end
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 4796 | ### connection.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains data structure definitions and aggregates utilities for handling connection to NATS server.
#
### Code:
@enum ConnectionStatus CONNECTING CONNECTED DISCONNECTED DRAINING DRAINED
include("stats.jl")
struct SubscriptionData
sub::Sub
channel::Channel
stats::Stats
is_async::Bool
lock::ReentrantLock
end
@kwdef mutable struct Connection
url::String
status::ConnectionStatus = CONNECTING
stats::Stats = Stats()
info::Union{Info, Nothing}
sub_data::Dict{Int64, SubscriptionData} = Dict{Int64, SubscriptionData}()
unsubs::Dict{Int64, Int64} = Dict{Int64, Int64}()
lock::ReentrantLock = ReentrantLock()
rng::AbstractRNG = MersenneTwister()
last_sid::Int64 = 0
send_buffer::IO = IOBuffer()
send_buffer_cond::Threads.Condition = Threads.Condition()
send_buffer_limit::Int64 = DEFAULT_SEND_BUFFER_LIMIT_BYTES
send_retry_delays::Any = SEND_RETRY_DELAYS
send_enqueue_when_disconnected::Bool
reconnect_event::Threads.Event = Threads.Event()
drain_event::Threads.Event = Threads.Event()
pong_received_cond::Threads.Condition = Threads.Condition()
status_change_cond::Threads.Condition = Threads.Condition()
@atomic connect_init_count::Int64 # How many tries of protocol init was done on last reconnect.
@atomic reconnect_count::Int64
@atomic send_buffer_flushed::Bool
drain_timeout::Float64
drain_poll::Float64
allow_direct::Dict{String, Bool} = Dict{String, Bool}() # Cache for jetstream for fast lookup of streams that have direct access.
allow_direct_lock = ReentrantLock()
"Handles messages for which handler was not found."
fallback_handlers::Vector{Function} = Function[]
end
info(c::Connection)::Union{Info, Nothing} = @lock c.lock c.info
info(c::Connection, info::Info) = @lock c.lock c.info = info
status(c::Connection)::ConnectionStatus = @lock c.status_change_cond c.status
function status(c::Connection, status::ConnectionStatus)
@lock c.status_change_cond begin
c.status = status
notify(c.status_change_cond)
end
end
function clustername(c::Connection)
info_msg = info(c)
if isnothing(info_msg)
"unknown"
else
@something info(c).cluster "unnamed"
end
end
function new_inbox(connection::Connection, prefix::String = "inbox.")
random_suffix = @lock connection.lock randstring(connection.rng, 10)
"inbox.$random_suffix"
end
function new_sid(connection::Connection)
@lock connection.lock begin
connection.last_sid += 1
connection.last_sid
end
end
include("state.jl")
include("utils.jl")
include("tls.jl")
include("send.jl")
include("handlers.jl")
include("drain.jl")
include("connect.jl")
function status()
println("=== Connection status ====================")
println("connections: $(length(state.connections)) ")
for (i, nc) in enumerate(state.connections)
print(" [#$i]: ")
print(status(nc), ", " , length(nc.sub_data)," subs, ", length(nc.unsubs)," unsubs ")
println()
end
# println("subscriptions: $(length(state.handlers)) ")
println("msgs_handled: $(state.stats.msgs_handled) ")
println("msgs_errored: $(state.stats.msgs_errored) ")
println("==========================================")
end
show(io::IO, nc::Connection) = print(io, typeof(nc), "(",
clustername(nc), " cluster", ", " , status(nc), ", " , length(nc.sub_data)," subs, ", length(nc.unsubs)," unsubs)")
function ping(nc; timer = Timer(1.0))
pong_ch = Channel{Pong}(1)
ping_task = @async begin
@async send(nc, Ping())
@lock nc.pong_received_cond wait(nc.pong_received_cond)
put!(pong_ch, Pong())
end
@async begin
try wait(timer) catch end
close(pong_ch)
end
try
take!(pong_ch)
catch
error("No PONG received.")
end
end
function stats(connection::Connection)
connection.stats
end
function stats(connection::Connection, sid::Int64)
sub_data = @lock connection.lock get(connection.sub_data, sid, nothing)
isnothing(sub_data) && return
sub_data.stats
end
function stats(connection::Connection, sub::Sub)
stats(connection, sub.sid)
end
function status_change(f, nc::Connection)
while true
st = status(nc)
if st == DRAINED
break
end
@lock nc.status_change_cond begin
wait(nc.status_change_cond)
st = nc.status
end
f(st)
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 3112 | ### drain.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementation of connection draining what means
# to close it with processing all messages that are in buffers already.
#
### Code:
# Actual drain logic, for thread safety executed in connection controller task.
function _do_drain(nc::Connection, is_connected; timeout = Timer(nc.drain_timeout))
sids = @lock nc.lock copy(keys(nc.sub_data))
for sid in sids
send(nc, Unsub(sid, 0))
end
sleep(nc.drain_poll)
conn_stats = stats(nc)
while !is_every_message_handled(conn_stats)
if !isopen(timeout)
@error "Timeout for drain exceeded, not all subs might be drained."
# TODO: add log about count of messages not handled.
break
end
sleep(nc.drain_poll)
end
for sid in sids
cleanup_sub_resources(nc, sid)
end
# At this point no more publications can be done. Wait for `send_buffer` flush.
while !is_send_buffer_flushed(nc)
if !isopen(timeout)
@error "Timeout for drain exceeded, some publications might be lost."
# TODO: add log about count of messages undelivered.
break
end
if !is_connected
@error "Cannot flush send buffer as connection is disconnected from server, some publications might be lost."
# TODO: add log about count of messages undelivered.
break
end
sleep(nc.drain_poll)
end
@lock nc.lock empty!(nc.sub_data)
end
"""
$SIGNATURES
Unsubscribe all subscriptions, wait for precessing all messages in buffers,
then close connection. Drained connection is no more usable. This method is
used to gracefuly stop the process.
Underneeth it periodicaly checks for state of all buffers, interval for checks
is configurable per connection with `drain_poll` parameter of `connect` method.
It can also be set globally with `NATS_DRAIN_POLL_INTERVAL_SECONDS` environment
variable. If not set explicitly default polling interval is
`$DEFAULT_DRAIN_POLL_INTERVAL_SECONDS` seconds.
Error will be written to log if drain not finished until timeout expires.
Default timeout value is configurable per connection on `connect` with
`drain_timeout`. Can be also set globally with `NATS_DRAIN_TIMEOUT_SECONDS`
environment variable. If not set explicitly default drain timeout is
`$DEFAULT_DRAIN_TIMEOUT_SECONDS` seconds.
"""
function drain(connection::Connection)
@lock connection.status_change_cond begin
notify(connection.drain_event)
# There is a chance that connection is DISCONNECTED or is in CONNECTING
# state and became DISCONNECTED before drain event is handled. Wake it up
# to force reconnect that will promptly do drain.
notify(connection.reconnect_event)
while connection.status != DRAINED
wait(connection.status_change_cond)
end
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 3238 | ### handlers.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains logic related to processing messages received from NATS server.
#
### Code:
function process(nc::Connection, msg::Info)
@debug "New INFO received: ." msg
info(nc, msg)
if !isnothing(msg.ldm) && msg.ldm
@warn "Server is in Lame Duck Mode, forcing reconnect to other server"
@debug "Connect urls are: $(msg.connect_urls)"
# TODO: do not reconnect if there are no urls provided
reconnect(nc, should_wait = false)
end
end
function process(nc::Connection, ::Ping)
@debug "Sending PONG."
send(nc, Pong())
end
function process(nc::Connection, ::Pong)
@debug "Received pong."
@lock nc.pong_received_cond notify(nc.pong_received_cond)
end
function process(nc::Connection, batch::Vector{ProtocolMessage})
groups = Dict{Int64, Vector{MsgRaw}}()
for msg in batch
if msg isa MsgRaw
arr = get(groups, msg.sid, nothing)
if isnothing(arr)
arr = MsgRaw[]
groups[msg.sid] = arr
end
push!(arr, msg)
else
process(nc, msg)
end
end
fallbacks = nothing
for (sid, msgs) in groups
n_received = length(msgs)
n = n_received
sub_data = @lock nc.lock get(nc.sub_data, sid, nothing)
if !isnothing(sub_data)
sub_stats = sub_data.stats
max_msgs = sub_data.channel.sz_max
n_dropped = max(0, sub_stats.msgs_pending + n_received - max_msgs)
if n_dropped > 0
inc_stats(:msgs_dropped, n_dropped, state.stats, nc.stats, sub_stats)
n -= n_dropped
msgs = first(msgs, n)
# TODO: send NAK for dropped messages
end
if n > 0
try
inc_stats(:msgs_pending, n, state.stats, nc.stats, sub_stats)
put!(sub_data.channel, msgs)
inc_stats(:msgs_received, n, state.stats, nc.stats, sub_stats)
catch
# TODO: if msg needs ack send nak here
# Channel was closed by `unsubscribe`.
dec_stats(:msgs_pending, n, state.stats, nc.stats, sub_stats)
inc_stats(:msgs_dropped, n, state.stats, nc.stats, sub_stats)
end
end
cleanup_sub_resources_if_all_msgs_received(nc, sid, n_received)
else
if isnothing(fallbacks)
fallbacks = lock(nc.lock) do
collect(nc.fallback_handlers)
end
end
for f in fallbacks
for msg in msgs
Base.invokelatest(f, nc, msg)
end
end
inc_stats(:msgs_dropped, n, state.stats, nc.stats)
end
end
end
function process(nc::Connection, ok::Ok)
@debug "Received OK."
end
function process(nc::Connection, err::Err)
@error "NATS protocol error!" err
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 5102 | ### send.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains logic related to sending messages to NATS server.
#
### Code:
const SEND_RETRY_DELAYS = Base.ExponentialBackOff(n=53, first_delay=0.01, max_delay=0.1)
function can_send(nc::Connection, ::ProtocolMessage)
# Drained conection is not usable, otherwise allow ping and pong and unsubs.
status(nc) != DRAINED
end
function can_send(nc::Connection, ::Union{Ping, Pong})
# Do not let PING and PONG polute send buffer during drain.
conn_status = status(nc)
conn_status != DRAINED && conn_status != DRAINING
end
function can_send(nc::Connection, ::Union{Pub, Vector{Pub}})
conn_status = status(nc)
if conn_status == CONNECTED
true
elseif conn_status == CONNECTING
true # TODO: or nc.send_enqueue_when_disconnected?
elseif conn_status == DISCONNECTED
nc.send_enqueue_when_disconnected
elseif conn_status == DRAINING
# Allow handlers to publish results during drain
sub_stats = ScopedValues.get(scoped_subscription_stats)
is_called_from_subscription_handler = !isnothing(sub_stats)
is_called_from_subscription_handler
elseif conn_status == DRAINED
false
end
end
function can_send(nc::Connection, ::Sub)
conn_status = status(nc)
if conn_status == CONNECTED
true
elseif conn_status == CONNECTING
true
elseif conn_status == DISCONNECTED
true
elseif conn_status == DRAINING
# No new subs allowed during drain.
false
elseif conn_status == DRAINED
false
end
end
function try_send(nc::Connection, msgs::Vector{Pub})::Bool
can_send(nc, msgs) || error("Cannot send on connection with status $(status(nc))")
@lock nc.send_buffer_cond begin
if nc.send_buffer.size < nc.send_buffer_limit
for msg in msgs
show(nc.send_buffer, MIME_PROTOCOL(), msg)
end
notify(nc.send_buffer_cond)
true
else
false
end
end
end
function try_send(nc::Connection, msg::ProtocolMessage)
can_send(nc, msg) || error("Cannot send on connection with status $(status(nc))")
@lock nc.send_buffer_cond begin
if msg isa Pub && nc.send_buffer.size > nc.send_buffer_limit
# Apply limits only for publications, to allow unsubs and subs be done with higher priority.
false
else
show(nc.send_buffer, MIME_PROTOCOL(), msg)
notify(nc.send_buffer_cond)
true
end
end
end
function send(nc::Connection, message::Union{ProtocolMessage, Vector{Pub}})
if try_send(nc, message)
return
end
for d in nc.send_retry_delays
sleep(d)
if try_send(nc, message)
return
end
end
error("Cannot send, send buffer too large.")
end
# Calling this function is an easy way to force crash of sender task what will force reconnect.
function reopen_send_buffer(nc::Connection)
@lock nc.send_buffer_cond begin
new_send_buffer = IOBuffer()
data = take!(nc.send_buffer)
for (sid, sub_data) in pairs(nc.sub_data)
show(new_send_buffer, MIME_PROTOCOL(), sub_data.sub)
unsub_max_msgs = get(nc.unsubs, sid, nothing) # TODO: lock on connection may be needed
isnothing(unsub_max_msgs) || show(new_send_buffer, MIME_PROTOCOL(), Unsub(sid, unsub_max_msgs))
end
@debug "Restored subs buffer length $(length(data))"
write(new_send_buffer, data)
@debug "Total restored buffer length $(length(data))"
close(nc.send_buffer)
nc.send_buffer = new_send_buffer
notify(nc.send_buffer_cond)
end
end
# Tells if send buffer if flushed what means no protocol messages are waiting
# to be delivered to the server.
function is_send_buffer_flushed(nc::Connection)
@lock nc.send_buffer_cond begin
nc.send_buffer.size == 0 && (@atomic nc.send_buffer_flushed)
end
end
function sendloop(nc::Connection, io::IO)
# @show Threads.threadid()
send_buffer = nc.send_buffer
while isopen(send_buffer) # @show !eof(io) && !isdrained(nc)
buf = @lock nc.send_buffer_cond begin
# TODO: check for eof on io
taken = take!(send_buffer)
if isempty(taken)
wait(nc.send_buffer_cond)
if !isopen(send_buffer)
break
end
# TODO: check for eof on io
@atomic nc.send_buffer_flushed = false
take!(send_buffer)
else
@atomic nc.send_buffer_flushed = false
taken
end
end
write(io, buf)
flush(io)
@atomic nc.send_buffer_flushed = true
end
@debug "Sender task finished. $(send_buffer.size) bytes in send buffer."
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2218 | ### state.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains utilities for maintaining global state of NATS.jl package.
#
### Code:
@kwdef mutable struct State
connections::Vector{Connection} = Connection[]
lock::ReentrantLock = ReentrantLock()
stats::Stats = Stats()
end
const state = State()
# Allow other packages to handle unexpected messages.
# JetStream might want to `nak` messages that need acknowledgement.
function install_fallback_handler(f, nc::Connection)
@lock nc.lock begin
if !(f in nc.fallback_handlers)
push!(nc.fallback_handlers, f)
end
end
end
function connection(id::Integer)
if id in 1:length(state.connections)
state.connections[id]
else
error("Connection #$id does not exists.")
end
end
# """
# Cleanup subscription data when no more messages are expected.
# """
function cleanup_sub_resources(nc::Connection, sid::Int64)
@lock nc.lock begin
sub_data = get(nc.sub_data, sid, nothing)
if isnothing(sub_data)
# Already cleaned up by other task.
return
end
close(sub_data.channel)
if sub_data.is_async == true || Base.n_avail(sub_data.channel) == 0
# `next` rely on lookup of sub data, in this case let sub data stay and do cleanup
# when `next` gets the last message of a closed channel.
delete!(nc.sub_data, sid)
delete!(nc.unsubs, sid)
end
end
end
# """
# Update state on message received and conditionaly do cleanup.
# Check if previously unsubscribed sub needs cleanup when no more messages are expected.
# """
function cleanup_sub_resources_if_all_msgs_received(nc::Connection, sid::Int64, n::Int64)
lock(nc.lock) do
count = get(nc.unsubs, sid, nothing)
if !isnothing(count)
count -= n
if count <= 0
cleanup_sub_resources(nc, sid)
else
nc.unsubs[sid] = count
end
end
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2513 | ### stats.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains utilities for collecting statistics connections, subscrptions and NATS.jl package.
#
### Code:
const NATS_STATS_MAX_RECENT_ERRORS = 100
mutable struct Stats
"Count of msgs received but maybe not yet handled by subscription."
@atomic msgs_received::Int64
"Count of msgs received that was not pickuped by subscription handler yet."
@atomic msgs_pending::Int64
"Count of msgs handled without error."
@atomic msgs_handled::Int64
"Count of msgs that caused handler function error."
@atomic msgs_errored::Int64
"Msgs that was not put to a subscription channel because it was full or `sid` was not known."
@atomic msgs_dropped::Int64
"Msgs published count."
@atomic msgs_published::Int64
"Subscription handlers running at the moment count."
@atomic handlers_running::Int64
"Recent errors."
errors::Channel{Exception}
function Stats()
new(0, 0, 0, 0, 0, 0, 0, Channel{Exception}(NATS_STATS_MAX_RECENT_ERRORS))
end
end
const scoped_subscription_stats = ScopedValue{Stats}()
function show(io::IO, stats::Stats)
print(io, "published: $(stats.msgs_published) \n")
print(io, " received: $(stats.msgs_received) \n")
print(io, " pending: $(stats.msgs_pending) \n")
print(io, " active: $(stats.handlers_running) \n")
print(io, " handled: $(stats.msgs_handled) \n")
print(io, " errored: $(stats.msgs_errored) \n")
print(io, " dropped: $(stats.msgs_dropped) \n")
end
function inc_stats(field, value, stats...)
for stat in stats
inc_stat(stat, field, value)
end
end
function dec_stats(field, value, stats...)
for stat in stats
dec_stat(stat, field, value)
end
end
function inc_stat(stat, field, value)
Base.modifyproperty!(stat, field, +, value, :sequentially_consistent)
end
function dec_stat(stat, field, value)
Base.modifyproperty!(stat, field, -, value, :sequentially_consistent)
end
# Tell if all received messages are delivered to subscription and handlers finished.
function is_every_message_handled(stats::Stats)
(@atomic stats.msgs_pending) == 0 &&
(@atomic stats.handlers_running) == 0 &&
(@atomic stats.msgs_received) == (@atomic stats.msgs_handled) + (@atomic stats.msgs_errored)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1750 | ### tls.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains utilities for handling TLS handshake.
#
### Code:
function upgrade_to_tls(sock::Sockets.TCPSocket, ca_cert_path::Union{String, Nothing}, client_cert_path::Union{String, Nothing}, client_key_path::Union{String, Nothing})
entropy = MbedTLS.Entropy()
rng = MbedTLS.CtrDrbg()
MbedTLS.seed!(rng, entropy)
ctx = MbedTLS.SSLContext()
conf = MbedTLS.SSLConfig()
MbedTLS.config_defaults!(conf)
MbedTLS.authmode!(conf, MbedTLS.MBEDTLS_SSL_VERIFY_REQUIRED)
MbedTLS.rng!(conf, rng)
# function show_debug(level, filename, number, msg)
# @show level, filename, number, msg
# end
# MbedTLS.dbg!(conf, show_debug)
if !isnothing(ca_cert_path)
MbedTLS.ca_chain!(conf, MbedTLS.crt_parse_file(ca_cert_path))
end
MbedTLS.setup!(ctx, conf)
MbedTLS.set_bio!(ctx, sock)
if !isnothing(client_key_path) && !isnothing(client_key_path)
cert = MbedTLS.crt_parse_file(client_cert_path)
key = MbedTLS.parse_keyfile(client_key_path)
MbedTLS.own_cert!(conf, cert, key)
end
MbedTLS.handshake(ctx)
get_tls_input_buffered(ctx), ctx
end
function get_tls_input_buffered(ssl)
io = Base.BufferStream()
t = Threads.@spawn :interactive disable_sigint() do
try
while !eof(ssl)
av = readavailable(ssl)
write(io, av)
end
finally
close(io)
end
end
errormonitor(t)
BufferedInputStream(io, 1)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2648 | ### utils.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains utilities for managing NATS connection that do not fit anywhere else.
#
### Code:
function argtype(handler)
handler_methods = methods(handler)
if length(handler_methods) > 1
error("Multimethod functions not suported as subscription handler.")
end
signature = first(methods(handler)).sig # TODO: handle multi methods.
if length(signature.parameters) == 1
Nothing
elseif length(signature.parameters) == 2
signature.parameters[2]
else
Tuple{signature.parameters[2:end]...}
end
end
function find_msg_conversion_or_throw(T::Type)
if T != Any && !hasmethod(Base.convert, (Type{T}, Msg))
error("""Conversion of NATS message into type $T is not defined.
Example how to define it:
```
import Base: convert
function convert(::Type{$T}, msg::NATS.Msg)
# Implement conversion logic here.
# For example:
field1, field2 = split(payload(msg), ",")
$T(field1, field2)
end
```
""")
end
end
function find_data_conversion_or_throw(T::Type)
if T != Any && !hasmethod(Base.show, (IO, NATS.MIME_PAYLOAD, T))
error("""Conversion of type $T to NATS payload is not defined.
Example how to define it:
```
import Base: show
function Base.show(io::IO, ::NATS.MIME_PAYLOAD, x::$T)
# Write content to `io` here, it can be UTF-8 string or byte array.
end
```
Optionally you might want to attach headers to a message:
```
function Base.show(io::IO, ::NATS.MIME_HEADERS, x::$T)
# Create vector of pairs of strings
hdrs = ["header_key" => "header_value"]
# Write them to the buffer
show(io, ::NATS.MIME_HEADERS, hdrs)
end
```
""")
end
end
# """
# Return lambda that avoids type conversions for certain types.
# Also allows for use of parameterless handlers for subs that do not need look into msg payload.
# """
function _fast_call(f::Function)
arg_t = argtype(f)
if arg_t === Any || arg_t == NATS.Msg
f
elseif arg_t == Nothing
_ -> f()
else
find_msg_conversion_or_throw(arg_t)
msg -> f(convert(arg_t, msg))
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 353 | ### experimental.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains aggregates experimantal NATS client features.
#
### Code:
include("scoped_connection.jl")
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 4614 | ### scoped_connection.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementation of simplified interface utilizing connection as dynamically scoped variable.
#
### Code:
const sconnection = ScopedValue{Connection}()
function scoped_connection()
conn = ScopedValues.get(sconnection)
if isnothing(conn)
error("""No scoped connection.
To use methods without explicit `connection` parameter you need to wrap your logic into `with_connection` function.
Example:
```
nc = NATS.connect()
with_connection(nc) do
publish("some_subject", "Some payload")
end
```
Or pass `connection` explicitly:
```
nc = NATS.connect()
publish(nc, "some_subject", "Some payload")
```
""")
end
conn.value
end
"""
$(SIGNATURES)
Create scope with ambient context connection, in which connection argument might be skipped during invocation of functions.
Usage:
```
nc = NATS.connect()
with_connection(nc) do
publish("some.subject") # No `connection` argument.
end
```
"""
function with_connection(f, nc::Connection)
with(f, sconnection => nc)
end
function subscribe(
subject::String;
queue_group::Union{String, Nothing} = nothing,
channel_size = parse(Int64, get(ENV, "NATS_SUBSCRIPTION_CHANNEL_SIZE", string(DEFAULT_SUBSCRIPTION_CHANNEL_SIZE))),
monitoring_throttle_seconds = parse(Float64, get(ENV, "NATS_SUBSCRIPTION_ERROR_THROTTLING_SECONDS", string(DEFAULT_SUBSCRIPTION_ERROR_THROTTLING_SECONDS)))
)
subscribe(scoped_connection(), subject; queue_group, channel_size, monitoring_throttle_seconds)
end
function subscribe(
f,
subject::String;
queue_group::Union{String, Nothing} = nothing,
spawn = false,
channel_size = parse(Int64, get(ENV, "NATS_SUBSCRIPTION_CHANNEL_SIZE", string(DEFAULT_SUBSCRIPTION_CHANNEL_SIZE))),
monitoring_throttle_seconds = parse(Float64, get(ENV, "NATS_SUBSCRIPTION_ERROR_THROTTLING_SECONDS", string(DEFAULT_SUBSCRIPTION_ERROR_THROTTLING_SECONDS)))
)
subscribe(f, scoped_connection(), subject; queue_group, spawn, channel_size, monitoring_throttle_seconds)
end
function unsubscribe(
sub::Sub;
max_msgs::Union{Int, Nothing} = nothing
)
unsubscribe(scoped_connection(), sub; max_msgs)
end
function unsubscribe(
sid::Int64;
max_msgs::Union{Int, Nothing} = nothing
)
unsubscribe(scoped_connection(), sid; max_msgs)
end
function drain(sub::Sub)
drain(scoped_connection(), sub)
end
function publish(
subject::String,
data = nothing;
reply_to::Union{String, Nothing} = nothing
)
publish(scoped_connection(), subject, data; reply_to)
end
function reply(
f,
subject::String;
queue_group::Union{Nothing, String} = nothing,
spawn = false
)
reply(f, scoped_connection(), subject; queue_group, spawn)
end
function request(
subject::String,
data = nothing;
timer::Timer = Timer(parse(Float64, get(ENV, "NATS_REQUEST_TIMEOUT_SECONDS", string(DEFAULT_REQUEST_TIMEOUT_SECONDS))))
)
request(scoped_connection(), subject, data; timer)
end
function request(
nreplies::Integer,
subject::String,
data = nothing;
timer::Timer = Timer(parse(Float64, get(ENV, "NATS_REQUEST_TIMEOUT_SECONDS", string(DEFAULT_REQUEST_TIMEOUT_SECONDS))))
)
request(scoped_connection(), nreplies, subject, data; timer)
end
function request(
T::Type,
subject::String,
data = nothing;
timer::Timer = Timer(parse(Float64, get(ENV, "NATS_REQUEST_TIMEOUT_SECONDS", string(DEFAULT_REQUEST_TIMEOUT_SECONDS))))
)
request(T, scoped_connection(), subject, data; timer)
end
function next(sub::Sub; no_wait = false, no_throw = false)::Union{Msg, Nothing}
next(scoped_connection(), sub::Sub; no_wait = false, no_throw = false)
end
function next(T::Type, sub::Sub; no_wait = false, no_throw = false)::Union{T, Nothing}
next(T, scoped_connection(), sub::Sub; no_wait = false, no_throw = false)
end
function next(sub::Sub, batch::Integer; no_wait = false, no_throw = false)::Vector{Msg}
next(scoped_connection(), sub, batch; no_wait = false, no_throw = false)
end
function next(T::Type, sub::Sub, batch::Integer; no_wait = false, no_throw = false)::Vector{T}
next(T, scoped_connection(), sub, batch; no_wait = false, no_throw = false)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1483 | module JetStream
using Dates
using NanoDates
using StructTypes
using Random
using JSON3
using DocStringExtensions
using ScopedValues
using Base64
using CodecBase
import NATS
import Base: show, showerror
import Base: setindex!, getindex, empty!, delete!, iterate, length
import Base: IteratorSize
import Base: put!, take!
export StreamConfiguration, Republish, StreamConsumerLimit, StreamSource
export stream_create, stream_update, stream_update_or_create, stream_purge, stream_delete
export stream_publish, stream_subscribe, stream_unsubscribe
export stream_message_get, stream_message_delete
export ConsumerConfiguration
export consumer_create, consumer_update, consumer_delete
export consumer_next, consumer_ack
export keyvalue_stream_info, keyvalue_buckets
export keyvalue_stream_create, keyvalue_stream_purge, keyvalue_stream_delete
export keyvalue_get, keyvalue_put, keyvalue_delete, keyvalue_watch
export JetDict, watch, with_optimistic_concurrency
export JetChannel, destroy!
const STREAM_RETENTION_OPTIONS = [:limits, :interest, :workqueue]
const STREAM_STORAGE_OPTIONS = [:file, :memory]
const STREAM_COMPRESSION_OPTIONS = [:none, :s2]
const CONSUMER_ACK_POLICY_OPTIONS = [:none, :all, :explicit]
const CONSUMER_REPLAY_POLICY_OPTIONS = [:instant, :original]
include("api/api.jl")
include("stream/stream.jl")
include("consumer/consumer.jl")
include("keyvalue/keyvalue.jl")
include("jetdict/jetdict.jl")
include("jetchannel/jetchannel.jl")
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 622 | abstract type ApiResponse end
@kwdef struct ApiError <: Exception
"HTTP like error code in the 300 to 500 range"
code::Int64
"A human friendly description of the error"
description::Union{String, Nothing} = nothing
"The NATS error code unique to each kind of error"
err_code::Union{Int64, Nothing} = nothing
end
struct ApiResult <: ApiResponse
success::Bool
end
struct IterableResponse
total::Int64
offset::Int64
limit::Int64
end
include("stream.jl")
include("consumer.jl")
include("errors.jl")
include("validate.jl")
include("show.jl")
include("convert.jl")
include("call.jl")
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 439 |
const DEFAULT_API_CALL_DELAYS = ExponentialBackOff(n = 7, first_delay = 0.1, max_delay = 0.5)
function check_api_call_error(s, e)
e isa Union{NATS.NATSError, ApiError} && e.code == 503
end
function jetstream_api_call(T, connection::NATS.Connection, subject, data = nothing; delays = DEFAULT_API_CALL_DELAYS)
call_retry = retry(NATS.request; delays, check = check_api_call_error)
call_retry(T, connection, subject, data)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 5162 |
"""
Configuration options for a consumer.
$(TYPEDFIELDS)
"""
@kwdef struct ConsumerConfiguration
"A unique name for a durable consumer"
durable_name::Union{String, Nothing} = nothing
"A unique name for a consumer"
name::Union{String, Nothing} = nothing
"A short description of the purpose of this consumer"
description::Union{String, Nothing} = nothing
deliver_subject::Union{String, Nothing} = nothing
ack_policy::Symbol = :none
"How long (in nanoseconds) to allow messages to remain un-acknowledged before attempting redelivery"
ack_wait::Union{Int64, Nothing} = 30000000000
"The number of times a message will be redelivered to consumers if not acknowledged in time"
max_deliver::Union{Int64, Nothing} = 1000
# This one is only for NATS 2.9 and older
# "Filter the stream by a single subjects"
# filter_subject::Union{String, Nothing} = nothing
"Filter the stream by multiple subjects"
filter_subjects::Union{Vector{String}, Nothing} = nothing
replay_policy::Symbol = :instant
sample_freq::Union{String, Nothing} = nothing
"The rate at which messages will be delivered to clients, expressed in bit per second"
rate_limit_bps::Union{UInt64, Nothing} = nothing
"The maximum number of messages without acknowledgement that can be outstanding, once this limit is reached message delivery will be suspended"
max_ack_pending::Union{Int64, Nothing} = nothing
"If the Consumer is idle for more than this many nano seconds a empty message with Status header 100 will be sent indicating the consumer is still alive"
idle_heartbeat::Union{Int64, Nothing} = nothing
"For push consumers this will regularly send an empty mess with Status header 100 and a reply subject, consumers must reply to these messages to control the rate of message delivery"
flow_control::Union{Bool, Nothing} = nothing
"The number of pulls that can be outstanding on a pull consumer, pulls received after this is reached are ignored"
max_waiting::Union{Int64, Nothing} = nothing
"Delivers only the headers of messages in the stream and not the bodies. Additionally adds Nats-Msg-Size header to indicate the size of the removed payload"
headers_only::Union{Bool, Nothing} = nothing
"The largest batch property that may be specified when doing a pull on a Pull Consumer"
max_batch::Union{Int64, Nothing} = nothing
"The maximum expires value that may be set when doing a pull on a Pull Consumer"
max_expires::Union{Int64, Nothing} = nothing
"The maximum bytes value that maybe set when dong a pull on a Pull Consumer"
max_bytes::Union{Int64, Nothing} = nothing
"Duration that instructs the server to cleanup ephemeral consumers that are inactive for that long"
inactive_threshold::Union{Int64, Nothing} = nothing
"List of durations in Go format that represents a retry time scale for NaK'd messages"
backoff::Union{Vector{Int64}, Nothing} = nothing
"When set do not inherit the replica count from the stream but specifically set it to this amount"
num_replicas::Union{Int64, Nothing} = nothing
"Force the consumer state to be kept in memory rather than inherit the setting from the stream"
mem_storage::Union{Bool, Nothing} = nothing
# "Additional metadata for the Consumer"
# metadata::Union{Any, Nothing} = nothing
end
@kwdef struct SequenceInfo
"The sequence number of the Consumer"
consumer_seq::UInt64
"The sequence number of the Stream"
stream_seq::UInt64
"The last time a message was delivered or acknowledged (for ack_floor)"
last_active::Union{NanoDate, Nothing} = nothing
end
@kwdef struct ConsumerInfo <: ApiResponse
"The Stream the consumer belongs to"
stream_name::String
"A unique name for the consumer, either machine generated or the durable name"
name::String
"The server time the consumer info was created"
ts::Union{NanoDate, Nothing} = nothing
config::ConsumerConfiguration
"The time the Consumer was created"
created::NanoDate
"The last message delivered from this Consumer"
delivered::SequenceInfo
"The highest contiguous acknowledged message"
ack_floor::SequenceInfo
"The number of messages pending acknowledgement"
num_ack_pending::Int64
"The number of redeliveries that have been performed"
num_redelivered::Int64
"The number of pull consumers waiting for messages"
num_waiting::Int64
"The number of messages left unconsumed in this Consumer"
num_pending::UInt64
cluster::Union{ClusterInfo, Nothing} = nothing
"Indicates if any client is connected and receiving messages from a push consumer"
push_bound::Union{Bool, Nothing} = nothing
end
@kwdef struct StoredMessage
"The subject the message was originally received on"
subject::String
"The sequence number of the message in the Stream"
seq::UInt64
"The base64 encoded payload of the message body"
data::Union{String, Nothing} = nothing
"The time the message was received"
time::String
"Base64 encoded headers for the message"
hdrs::Union{String, Nothing} = nothing
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 945 | import Base.convert
# const api_type_map = Dict(
# "io.nats.jetstream.api.v1.consumer_create_response" => ConsumerInfo,
# "io.nats.jetstream.api.v1.stream_create_response" => StreamInfo,
# "io.nats.jetstream.api.v1.stream_delete_response" => ApiResult,
# "io.nats.jetstream.api.v1.stream_info_response" => StreamInfo
# )
function convert(::Type{T}, msg::NATS.Msg) where { T <: ApiResponse }
# TODO: check headers
response = JSON3.read(@view msg.payload[(begin + msg.headers_length):end])
throw_on_api_error(response)
StructTypes.constructfrom(T, response)
end
function convert(::Type{Union{T, ApiError}}, msg::NATS.Msg) where { T <: ApiResponse }
# TODO: check headers
response = JSON3.read(@view msg.payload[begin+msg.headers_length:end])
if haskey(response, :error)
StructTypes.constructfrom(ApiError, response.error)
else
StructTypes.constructfrom(T, response)
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 540 |
function throw_on_api_error(response::JSON3.Object)
if haskey(response, :error)
throw(StructTypes.constructfrom(ApiError, response.error))
end
end
function throw_on_api_error(response::ApiError)
throw(response)
end
function throw_on_api_error(response::ApiResponse)
# Nothing to do
end
function Base.showerror(io::IO, err::ApiError)
print(io, "JetStream ")
printstyled(io, "$(err.code)"; color=Base.error_color())
if !isnothing(err.description)
print(io, ": $(err.description).")
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 963 |
StructTypes.omitempties(::Type{SubjectTransform}) = true
StructTypes.omitempties(::Type{Placement}) = true
StructTypes.omitempties(::Type{ExternalStreamSource}) = true
StructTypes.omitempties(::Type{StreamSource}) = true
StructTypes.omitempties(::Type{Republish}) = true
StructTypes.omitempties(::Type{StreamConsumerLimit}) = true
StructTypes.omitempties(::Type{StreamConfiguration}) = true
StructTypes.omitempties(::Type{ConsumerConfiguration}) = true
show(io::IO, st::SubjectTransform) = JSON3.pretty(io, st)
show(io::IO, st::Placement) = JSON3.pretty(io, st)
show(io::IO, st::ExternalStreamSource) = JSON3.pretty(io, st)
show(io::IO, st::StreamSource) = JSON3.pretty(io, st)
show(io::IO, st::Republish) = JSON3.pretty(io, st)
show(io::IO, st::StreamConsumerLimit) = JSON3.pretty(io, st)
show(io::IO, st::StreamConfiguration) = JSON3.pretty(io, st)
# function show(io::IO, ::MIME"text/plain", response::ApiResponse)
# JSON3.pretty(io, response)
# end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 9821 |
@kwdef struct SubjectTransform
"The subject transform source"
src::String
"The subject transform destination"
dest::String
end
@kwdef struct Placement
"The desired cluster name to place the stream"
cluster::Union{String, Nothing}
"Tags required on servers hosting this stream"
tags::Union{Vector{String}, Nothing} = nothing
end
@kwdef struct ExternalStreamSource
"The subject prefix that imports the other account/domain $JS.API.CONSUMER.> subjects"
api::String
"The delivery subject to use for the push consumer"
deliver::Union{String, Nothing} = nothing
end
@kwdef struct StreamSource
"Stream name"
name::String
"Sequence to start replicating from"
opt_start_seq::Union{UInt64, Nothing} = nothing
"Time stamp to start replicating from"
opt_start_time::Union{NanoDate, Nothing} = nothing
"Replicate only a subset of messages based on filter"
filter_subject::Union{String, Nothing} = nothing
"The subject filtering sources and associated destination transforms"
subject_transforms::Union{Vector{SubjectTransform}, Nothing} = nothing
external::Union{ExternalStreamSource, Nothing} = nothing
end
@kwdef struct Republish
"The source subject to republish"
src::String
"The destination to publish to"
dest::String
"Only send message headers, no bodies"
headers_only::Union{Bool, Nothing} = nothing
end
@kwdef struct StreamConsumerLimit
"Maximum value for inactive_threshold for consumers of this stream. Acts as a default when consumers do not set this value."
inactive_threshold::Union{Int64, Nothing} = nothing
"Maximum value for max_ack_pending for consumers of this stream. Acts as a default when consumers do not set this value."
max_ack_pending::Union{Int64, Nothing} = nothing
end
"""
Configuration options for a stream.
$(TYPEDFIELDS)
"""
@kwdef struct StreamConfiguration
"A unique name for the Stream."
name::String
"A short description of the purpose of this stream"
description::Union{String, Nothing} = nothing
"A list of subjects to consume, supports wildcards. Must be empty when a mirror is configured. May be empty when sources are configured."
subjects::Union{Vector{String}, Nothing} = nothing
"Subject transform to apply to matching messages"
subject_transform::Union{SubjectTransform, Nothing} = nothing
"How messages are retained in the Stream, once this is exceeded old messages are removed."
retention::Symbol = :limits
"How many Consumers can be defined for a given Stream. -1 for unlimited."
max_consumers::Int64 = -1
"How many messages may be in a Stream, oldest messages will be removed if the Stream exceeds this size. -1 for unlimited."
max_msgs::Int64 = -1
"For wildcard streams ensure that for every unique subject this many messages are kept - a per subject retention limit"
max_msgs_per_subject::Union{Int64, Nothing} = nothing
"How big the Stream may be, when the combined stream size exceeds this old messages are removed. -1 for unlimited."
max_bytes::Int64 = -1
"Maximum age of any message in the stream, expressed in nanoseconds. 0 for unlimited."
max_age::Int64 = 0
"The largest message that will be accepted by the Stream. -1 for unlimited."
max_msg_size::Union{Int32, Nothing} = nothing
"The storage backend to use for the Stream."
storage::Symbol = :file
"Optional compression algorithm used for the Stream."
compression::Symbol = :none
"A custom sequence to use for the first message in the stream"
first_seq::Union{UInt64, Nothing} = nothing
"How many replicas to keep for each message."
num_replicas::Int64 = 1
"Disables acknowledging messages that are received by the Stream."
no_ack::Union{Bool, Nothing} = nothing
"When a Stream reach it's limits either old messages are deleted or new ones are denied"
discard::Union{Symbol, Nothing} = nothing
"The time window to track duplicate messages for, expressed in nanoseconds. 0 for default"
duplicate_window::Union{Int64, Nothing} = nothing
"Placement directives to consider when placing replicas of this stream, random placement when unset"
placement::Union{Placement, Nothing} = nothing
"Maintains a 1:1 mirror of another stream with name matching this property. When a mirror is configured subjects and sources must be empty."
mirror::Union{StreamSource, Nothing} = nothing
"List of Stream names to replicate into this Stream"
sources::Union{Vector{StreamSource}, Nothing} = nothing
"Sealed streams do not allow messages to be deleted via limits or API, sealed streams can not be unsealed via configuration update. Can only be set on already created streams via the Update API"
sealed::Union{Bool, Nothing} = nothing
"Restricts the ability to delete messages from a stream via the API. Cannot be changed once set to true"
deny_delete::Union{Bool, Nothing} = nothing
"Restricts the ability to purge messages from a stream via the API. Cannot be change once set to true"
deny_purge::Union{Bool, Nothing} = nothing
"Allows the use of the Nats-Rollup header to replace all contents of a stream, or subject in a stream, with a single new message"
allow_rollup_hdrs::Union{Bool, Nothing} = nothing
"Allow higher performance, direct access to get individual messages"
allow_direct::Union{Bool, Nothing} = nothing
"Allow higher performance, direct access for mirrors as well"
mirror_direct::Union{Bool, Nothing} = nothing
republish::Union{Republish, Nothing} = nothing
"When discard policy is new and the stream is one with max messages per subject set, this will apply the new behavior to every subject. Essentially turning discard new from maximum number of subjects into maximum number of messages in a subject."
discard_new_per_subject::Union{Bool, Nothing} = nothing
"Additional metadata for the Stream"
metadata::Union{Dict{String, String}, Nothing} = nothing # TODO: what is this for?
"Limits of certain values that consumers can set, defaults for those who don't set these settings"
consumer_limits::Union{StreamConsumerLimit, Nothing} = nothing
end
@kwdef struct StreamState
"Number of messages stored in the Stream"
messages::UInt64
"Combined size of all messages in the Stream"
bytes::UInt64
"Sequence number of the first message in the Stream"
first_seq::UInt64
"The timestamp of the first message in the Stream"
first_ts::Union{NanoDate, Nothing} = nothing
"Sequence number of the last message in the Stream"
last_seq::UInt64
"The timestamp of the last message in the Stream"
last_ts::Union{NanoDate, Nothing} = nothing
"IDs of messages that were deleted using the Message Delete API or Interest based streams removing messages out of order"
deleted::Union{Vector{UInt64}, Nothing} = nothing
# "Subjects and their message counts when a subjects_filter was set"
# subjects::Union{Any, Nothing} = nothing
"The number of unique subjects held in the stream"
num_subjects::Union{Int64, Nothing} = nothing
"The number of deleted messages"
num_deleted::Union{Int64, Nothing} = nothing
# lost::Union{LostStreamData, Nothing} = nothing
"Number of Consumers attached to the Stream"
consumer_count::Int64
end
@kwdef struct PeerInfo
"The server name of the peer"
name::String
"Indicates if the server is up to date and synchronised"
current::Bool = false
"Nanoseconds since this peer was last seen"
active::Int64
"Indicates the node is considered offline by the group"
offline::Union{Bool, Nothing} = nothing
"How many uncommitted operations this peer is behind the leader"
lag::Union{Int64, Nothing} = nothing
end
@kwdef struct ClusterInfo
"The cluster name"
name::Union{String, Nothing} = nothing
"The server name of the RAFT leader"
leader::Union{String, Nothing} = nothing
"The members of the RAFT cluster"
replicas::Union{Vector{PeerInfo}, Nothing} = nothing
end
@kwdef struct StreamSourceInfo
"The name of the Stream being replicated"
name::String
"The subject filter to apply to the messages"
filter_subject::Union{String, Nothing} = nothing
"The subject filtering sources and associated destination transforms"
subject_transforms::Union{Vector{SubjectTransform}, Nothing} = nothing
"How many messages behind the mirror operation is"
lag::UInt64
"When last the mirror had activity, in nanoseconds. Value will be -1 when there has been no activity."
active::Int64
external::Union{ExternalStreamSource, Nothing} = nothing
error::Union{ApiError, Nothing} = nothing
end
@kwdef struct StreamAlternate
"The mirror stream name"
name::String
"The name of the cluster holding the stream"
cluster::String
"The domain holding the string"
domain::Union{String, Nothing} = nothing
end
@kwdef struct StreamInfo <: ApiResponse
"The active configuration for the Stream"
config::StreamConfiguration
"Detail about the current State of the Stream"
state::StreamState
"Timestamp when the stream was created"
created::NanoDate
"The server time the stream info was created"
ts::Union{NanoDate, Nothing} = nothing
cluster::Union{ClusterInfo, Nothing} = nothing
mirror::Union{StreamSourceInfo, Nothing} = nothing
"Streams being sourced into this Stream"
sources::Union{Vector{StreamSourceInfo}, Nothing} = nothing
"List of mirrors sorted by priority"
alternates::Union{Vector{StreamAlternate}, Nothing} = nothing
end
@kwdef struct PubAck <: ApiResponse
stream::String
seq::Union{Int64, Nothing}
duplicate::Union{Bool, Nothing}
domain::Union{String, Nothing}
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 697 | function validate_name(name::String)
# ^[^.*>]+$
# https://github.com/nats-io/jsm.go/blob/30c85c3d2258321d4a2ded882fe8561a83330e5d/schema_source/jetstream/api/v1/definitions.json#L445
isempty(name) && error("Name is empty.")
for c in name
if c == '.' || c == '*' || c == '>'
error("Name \"$name\" contains invalid character '$c'.")
end
end
true
end
function validate(stream_configuration::StreamConfiguration)
validate_name(stream_configuration.name)
stream_configuration.retention in STREAM_RETENTION_OPTIONS || error("Invalid `retention = :$(stream_configuration.retention)`, expected one of $STREAM_RETENTION_OPTIONS")
true
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 737 |
# https://docs.nats.io/using-nats/developer/develop_jetstream/model_deep_dive#acknowledgement-models
const CONSUMER_ACK_OPTIONS = [ "+ACK", "-NAK", "+WPI", "+NXT", "+TERM" ]
"""
$(SIGNATURES)
Confirms message delivery to server.
"""
function consumer_ack(connection::NATS.Connection, msg::NATS.Msg, ack::String = "+ACK"; delays = DEFAULT_API_CALL_DELAYS)
ack in CONSUMER_ACK_OPTIONS || error("Unknown ack type \"$ack\", allowed values: $(join(CONSUMER_ACK_OPTIONS, ", "))")
isnothing(msg.reply_to) && error("No reply subject for msg $msg.")
!startswith(msg.reply_to, "\$JS.ACK") && @warn "`ack` sent for message that doesn't need acknowledgement."
jetstream_api_call(NATS.Msg, connection, msg.reply_to; delays)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 77 |
include("manage.jl")
include("list.jl")
include("next.jl")
include("ack.jl") | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1628 |
function consumer_create_or_update(connection::NATS.Connection, config::ConsumerConfiguration, stream::String)
consumer_name = @something config.name consumer_config.durable_name randstring(20)
subject = "\$JS.API.CONSUMER.CREATE.$stream.$consumer_name"
req_data = Dict(:stream_name => stream, :config => config)
# if !isnothing(action) #TODO: handle action
# req_data[:action] = action
# end
NATS.request(ConsumerInfo, connection, subject, JSON3.write(req_data))
end
function consumer_create_or_update(connection::NATS.Connection, config::ConsumerConfiguration, stream::StreamInfo)
consumer_create_or_update(connection, config, stream.config.name)
end
"""
$(SIGNATURES)
Create a stream consumer.
"""
function consumer_create(connection::NATS.Connection, config::ConsumerConfiguration, stream::Union{String, StreamInfo})
consumer_create_or_update(connection, config, stream)
end
"""
$(SIGNATURES)
Update stream consumer configuration.
"""
function consumer_update(connection::NATS.Connection, consumer::ConsumerConfiguration, stream::Union{StreamInfo, String})
consumer_create_or_update(connection, consumer, stream)
end
"""
$(SIGNATURES)
Delete a consumer.
"""
function consumer_delete(connection::NATS.Connection, stream_name::String, consumer_name::String)
subject = "\$JS.API.CONSUMER.DELETE.$stream_name.$consumer_name"
res = NATS.request(Union{ApiResult, ApiError}, connection, subject)
throw_on_api_error(res)
res
end
function consumer_delete(connection, consumer::ConsumerInfo)
consumer_delete(connection, consumer.stream_name, consumer.name)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1175 | const NEXT_EXPIRES = 500 * 1000 * 1000 # 500 ms, TODO: add to env
"""
$(SIGNATURES)
Get next message for a consumer.
"""
function consumer_next(connection::NATS.Connection, consumer::ConsumerInfo, batch::Int64; no_wait = false, no_throw = false)
req = Dict()
req[:no_wait] = no_wait
req[:batch] = batch
if !no_wait
req[:expires] = NEXT_EXPIRES
end
subject = "\$JS.API.CONSUMER.MSG.NEXT.$(consumer.stream_name).$(consumer.name)"
while true
msgs = NATS.request(connection, batch, subject, JSON3.write(req))
ok = filter(!NATS.has_error_status, msgs)
!isempty(ok) && return ok
err = filter(NATS.has_error_status, msgs)
critical = filter(m -> NATS.statuscode(m) != 408, err)
# 408 indicates timeout
if !isempty(critical)
# TODO warn other errors if any
no_throw || NATS.throw_on_error_status(first(critical))
return critical
end
end
end
function consumer_next(connection::NATS.Connection, consumer::ConsumerInfo; no_wait = false, no_throw = false)
batch = consumer_next(connection, consumer, 1; no_wait, no_throw)
only(batch)
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1462 |
include("manage.jl")
const DEFAULT_JETCHANNEL_DELAYS = ExponentialBackOff(n = typemax(Int64), first_delay = 0.2, max_delay = 0.5)
struct JetChannel{T} <: AbstractChannel{T}
connection::NATS.Connection
name::String
stream::StreamInfo
consumer::ConsumerInfo
end
const DEFAULT_JETCHANNEL_SIZE = 1
function JetChannel{T}(connection::NATS.Connection, name::String, size::Int64 = DEFAULT_JETCHANNEL_SIZE) where T
stream = channel_stream_create(connection, name, size)
consumer = channel_consumer_create(connection, name)
JetChannel{T}(connection, name, stream, consumer)
end
function destroy!(jetchannel::JetChannel)
channel_stream_delete(jetchannel.connection, jetchannel.name)
end
function show(io::IO, jetchannel::JetChannel{T}) where T
sz = jetchannel.stream.config.max_msgs
sz_str = sz == -1 ? "Inf" : string(sz)
print(io, "JetChannel{$T}(\"$(jetchannel.name)\", $sz_str)")
end
function Base.take!(jetchannel::JetChannel{T}) where T
msg = consumer_next(jetchannel.connection, jetchannel.consumer)
ack = consumer_ack(jetchannel.connection, msg; delays = DEFAULT_JETCHANNEL_DELAYS)
@assert ack isa NATS.Msg
convert(T, msg)
end
function Base.put!(jetchannel::JetChannel{T}, v::T) where T
subject = channel_subject(jetchannel.name)
ack = stream_publish(jetchannel.connection, subject, v; delays = DEFAULT_JETCHANNEL_DELAYS)
@assert ack.stream == jetchannel.stream.config.name
v
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1236 |
const CHANNEL_STREAM_PREFIX = "JCH"
channel_stream_name(channel_name::String) = "$(CHANNEL_STREAM_PREFIX)_$(channel_name)"
channel_consumer_name(channel_name::String) = "$(CHANNEL_STREAM_PREFIX)_$(channel_name)_consumer"
channel_subject(channel_name::String) = "$(CHANNEL_STREAM_PREFIX)_$(channel_name)"
const INFINITE_CHANNEL_SIZE = -1
function channel_stream_create(connection::NATS.Connection, name::String, max_msgs = INFINITE_CHANNEL_SIZE)
config = StreamConfiguration(
name = channel_stream_name(name),
subjects = [ channel_subject(name) ],
retention = :workqueue,
max_msgs = max_msgs,
discard = :new,
)
stream_create(connection, config)
end
function channel_stream_delete(connection::NATS.Connection, channel_name::String)
stream_delete(connection, channel_stream_name(channel_name))
end
function channel_consumer_create(connection::NATS.Connection, channel_name::String)
stream_name = channel_stream_name(channel_name)
config = ConsumerConfiguration(
ack_policy = :explicit,
name = channel_consumer_name(channel_name),
durable_name = channel_consumer_name(channel_name)
)
consumer_create(connection, config, stream_name)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 938 |
# Encoding must confirm to `validate_key`, so not url safe base64 is not allowed because of '+'
struct KeyEncoding{encoding} end
const JETDICT_KEY_ENCODING = [:none, :base64url]
encodekey(::KeyEncoding{:none}, key::String) = key
decodekey(::KeyEncoding{:none}, key::String) = key
encodekey(::KeyEncoding{:base64url}, key::String) = String(transcode(Base64Encoder(urlsafe = true), key))
decodekey(::KeyEncoding{:base64url}, key::String) = String(transcode(Base64Decoder(urlsafe = true), key))
function check_encoding_implemented(encoding::Symbol)
hasmethod(encodekey, (KeyEncoding{encoding}, String)) || error("No `encodekey` implemented for $encoding encoding, allowed encodings: $(join(NATS.JetStream.JETDICT_KEY_ENCODING, ", "))")
hasmethod(decodekey, (KeyEncoding{encoding}, String)) || error("No `decodekey` implemented for $encoding encoding, allowed encodings: $(join(NATS.JetStream.JETDICT_KEY_ENCODING, ", "))")
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 5751 |
include("encode.jl")
struct JetDict{T} <: AbstractDict{String, T}
connection::NATS.Connection
bucket::String
stream_info::StreamInfo
T::DataType
revisions::ScopedValue{Dict{String, UInt64}}
encoding::KeyEncoding
end
function get_jetdict_stream_info(connection, bucket, encoding)
res = stream_info(connection, "$KV_STREAM_NAME_PREFIX$bucket"; no_throw = true)
if res isa ApiError
res.code != 404 && throw(res)
keyvalue_stream_create(connection, bucket, encoding, 1)
else
stream_encoding = isnothing(res.config.metadata) ? :none : Symbol(get(res.config.metadata, "encoding", "none"))
if encoding != stream_encoding
error("Encoding do not match, cannot use :$encoding encoding on stream with :$stream_encoding encoding")
end
res
end
end
function JetDict{T}(connection::NATS.Connection, bucket::String, encoding::Symbol = :none) where T
check_encoding_implemented(encoding)
NATS.find_msg_conversion_or_throw(T)
NATS.find_data_conversion_or_throw(T)
stream = get_jetdict_stream_info(connection, bucket, encoding)
JetDict{T}(connection, bucket, stream, T, ScopedValue{Dict{String, UInt64}}(), KeyEncoding{encoding}())
end
function setindex!(jetdict::JetDict{T}, value::T, key::String) where T
escaped = encodekey(jetdict.encoding, key)
validate_key(escaped)
revisions = ScopedValues.get(jetdict.revisions)
if !isnothing(revisions)
revision = get(revisions.value, key, 0)
ack = keyvalue_put(jetdict.connection, jetdict.bucket, escaped, value, revision)
@assert ack isa PubAck
revisions.value[key] = ack.seq
else
ack = keyvalue_put(jetdict.connection, jetdict.bucket, escaped, value)
@assert ack isa PubAck
end
jetdict
end
function getindex(jetdict::JetDict, key::String)
escaped = encodekey(jetdict.encoding, key)
validate_key(escaped)
msg = try
keyvalue_get(jetdict.connection, jetdict.bucket, escaped)
catch err
if err isa NATS.NATSError && err.code == 404
throw(KeyError(key))
else
rethrow()
end
end
if isdeleted(msg)
throw(KeyError(key))
end
revisions = ScopedValues.get(jetdict.revisions)
if !isnothing(revisions)
seq = NATS.header(msg, "Nats-Sequence")
revisions.value[key] = parse(UInt64, seq)
end
convert(jetdict.T, msg)
end
function delete!(jetdict::JetDict, key::String)
escaped = encodekey(jetdict.encoding, key)
ack = keyvalue_delete(jetdict.connection, jetdict.bucket, escaped)
@assert ack isa PubAck
jetdict
end
# No way to get number of not deleted items fast, also kv can change during iteration.
IteratorSize(::JetDict) = Base.SizeUnknown()
IteratorSize(::Base.KeySet{String, JetDict{T}}) where {T} = Base.SizeUnknown()
IteratorSize(::Base.ValueIterator{JetDict{T}}) where {T} = Base.SizeUnknown()
function iterate(jetdict::JetDict)
unique_keys = Set{String}()
consumer_config = ConsumerConfiguration(
name = randstring(20)
)
consumer = consumer_create(jetdict.connection, consumer_config, jetdict.stream_info)
msg = consumer_next(jetdict.connection, consumer, no_wait = true, no_throw = true)
msg_status = NATS.statuscode(msg)
msg_status == 404 && return nothing
NATS.throw_on_error_status(msg)
key = decodekey(jetdict.encoding, replace(msg.subject, "\$KV.$(jetdict.bucket)." => ""))
value = convert(jetdict.T, msg)
push!(unique_keys, key)
(key => value, (consumer, unique_keys))
end
function iterate(jetdict::JetDict, (consumer, unique_keys))
msg = consumer_next(jetdict.connection, consumer, no_wait = true, no_throw = true)
msg_status = NATS.statuscode(msg)
msg_status == 404 && return nothing
NATS.throw_on_error_status(msg)
key = decodekey(jetdict.encoding, replace(msg.subject, "\$KV.$(jetdict.bucket)." => ""))
if key in unique_keys
@warn "Key \"$key\" changed during iteration."
# skip item
iterate(jetdict, (consumer, unique_keys))
elseif isdeleted(msg)
# skip item
iterate(jetdict, (consumer, unique_keys))
else
value = convert(jetdict.T, msg)
push!(unique_keys, key)
(key => value, (consumer, unique_keys))
end
end
function length(jetdict::JetDict)
# TODO: this is not reliable way to check length, it counts deleted items
consumer_config = ConsumerConfiguration(
name = randstring(20)
)
consumer = consumer_create(jetdict.connection, consumer_config, "KV_$(jetdict.bucket)")
msg = consumer_next(jetdict.connection, consumer, no_wait = true, no_throw = true)
msg_status = NATS.statuscode(msg)
msg_status == 404 && return 0
NATS.throw_on_error_status(msg)
remaining = last(split(msg.reply_to, "."))
parse(Int64, remaining) + 1
end
function empty!(jetdict::JetDict)
keyvalue_stream_purge(jetdict.connection, jetdict.bucket)
jetdict
end
function with_optimistic_concurrency(f, kv::JetDict)
with(f, kv.revisions => Dict{String, UInt64}())
end
function isdeleted(msg)
NATS.header(msg, "KV-Operation") in [ "DEL", "PURGE" ]
end
function watch(f, jetdict::JetDict, key = ALL_KEYS; skip_deletes = false)
keyvalue_watch(jetdict.connection, jetdict.bucket, key) do msg
deleted = isdeleted(msg)
if !(skip_deletes && isdeleted(msg))
encoded_key = msg.subject[begin + 1 + length(keyvalue_subject_prefix(jetdict.bucket)):end]
key = decodekey(jetdict.encoding, encoded_key)
value = deleted ? nothing : convert(jetdict.T, msg)
f(key => value)
end
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 418 |
function keyvalue_history(connection::NATS.Connection, bucket::String, key::String)
subject = "$(keyvalue_subject_prefix(bucket)).$(key)"
consumer_config = ConsumerConfiguration(;
name = randstring(10),
filter_subjects = [ subject ]
)
consumer = consumer_create(connection, consumer_config, keyvalue_stream_name(bucket))
consumer_next(connection, consumer, 64; no_wait = true)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 561 |
const KV_STREAM_NAME_PREFIX = "KV_"
function validate_key(key::String)
length(key) <= 3000 || error("Key is too long.")
isempty(key) && error("Key is an empty string.")
first(key) == '.' && error("Key \"$key\" starts with '.'")
last(key) == '.' && error("Key \"$key\" ends with '.'")
for c in key
is_valid = isdigit(c) || isletter(c) || c in [ '-', '/', '_', '=', '.' ]
!is_valid && error("Key \"$key\" contains invalid character '$c'.")
end
true
end
include("manage.jl")
include("watch.jl")
include("history.jl")
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2727 |
function keyvalue_stream_name(bucket::String)
"KV_$bucket"
end
function keyvalue_subject_prefix(bucket::String)
"\$KV.$bucket"
end
const MAX_HISTORY = 64
"""
$(SIGNATURES)
Create a stream for KV bucket.
"""
function keyvalue_stream_create(connection::NATS.Connection, bucket::String, encoding::Symbol, history = MAX_HISTORY)
history in 1:MAX_HISTORY || error("History must be greater than 0 and cannot be greater than $MAX_HISTORY")
stream_config = StreamConfiguration(
name = keyvalue_stream_name(bucket),
subjects = ["$(keyvalue_subject_prefix(bucket)).>"],
allow_rollup_hdrs = true,
deny_delete = true,
allow_direct = true,
max_msgs_per_subject = history,
discard = :new,
metadata = Dict("encoding" => string(encoding))
)
stream_create(connection::NATS.Connection, stream_config)
end
function keyvalue_stream_info(connection::NATS.Connection, bucket::String)
stream_info(connection, keyvalue_stream_name(bucket))
end
"""
$(SIGNATURES)
Delete a KV stream by bucket name.
"""
function keyvalue_stream_delete(connection::NATS.Connection, bucket::String)
stream_delete(connection, keyvalue_stream_name(bucket))
end
"""
$(SIGNATURES)
Purge a KV stream.
"""
function keyvalue_stream_purge(connection::NATS.Connection, bucket::String)
stream_purge(connection, keyvalue_stream_name(bucket))
end
"""
$(SIGNATURES)
Get a value from KV stream.
"""
function keyvalue_get(connection::NATS.Connection, bucket::String, key::String)::NATS.Msg
validate_key(key)
stream = keyvalue_stream_name(bucket)
subject = "$(keyvalue_subject_prefix(bucket)).$key"
stream_message_get(connection, stream, subject; allow_direct = true)
end
"""
$(SIGNATURES)
Put a value to KV stream.
"""
function keyvalue_put(connection::NATS.Connection, bucket::String, key::String, value, revision = 0)::PubAck
validate_key(key)
hdrs = NATS.Headers() #TODO: can preserve original headers?
if revision > 0
push!(hdrs, "Nats-Expected-Last-Subject-Sequence" => string(revision))
end
subject = "$(keyvalue_subject_prefix(bucket)).$key"
stream_publish(connection, subject, (value, hdrs))
end
"""
$(SIGNATURES)
Delete a value from KV stream.
"""
function keyvalue_delete(connection::NATS.Connection, bucket::String, key)::PubAck
validate_key(key)
hdrs = [ "KV-Operation" => "DEL" ]
subject = "$(keyvalue_subject_prefix(bucket)).$key"
stream_publish(connection, subject, (nothing, hdrs))
end
function keyvalue_buckets(connection::NATS.Connection)
map(stream_names(connection::NATS.Connection, "\$KV.>")) do stream_name
stream_name[begin+length(KV_STREAM_NAME_PREFIX):end]
end
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 299 |
const ALL_KEYS = ">"
"""
$(SIGNATURES)
Watch for changes in KV stream.
"""
function keyvalue_watch(f, connection::NATS.Connection, bucket::String, key = ALL_KEYS)
prefix = keyvalue_subject_prefix(bucket)
subject = "$prefix.$key"
JetStream.stream_subscribe(f, connection, subject)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1911 |
function stream_info(connection::NATS.Connection,
stream_name::String;
no_throw = false,
deleted_details = false,
subjects_filter::Union{String, Nothing} = nothing)
validate_name(stream_name)
res = NATS.request(Union{StreamInfo, ApiError}, connection, "\$JS.API.STREAM.INFO.$(stream_name)")
no_throw || throw_on_api_error(res)
res
end
function iterable_request(f)
offset = 0
iterable = f(offset)
offset = iterable.offset + iterable.limit
while iterable.total > offset
iterable = f(offset)
offset = iterable.offset + iterable.limit
end
end
function stream_infos(connection::NATS.Connection, subject = nothing)
result = StreamInfo[]
req = Dict()
if !isnothing(subject)
req[:subject] = subject
end
iterable_request() do offset
req[:offset] = offset
json = NATS.request(JSON3.Object, connection, "\$JS.API.STREAM.LIST", JSON3.write(req))
throw_on_api_error(json)
if !isnothing(json.streams)
for s in json.streams
item = StructTypes.constructfrom(StreamInfo, s)
push!(result, item)
end
end
StructTypes.constructfrom(IterableResponse, json)
end
result
end
function stream_names(connection::NATS.Connection, subject = nothing; timer = Timer(5))
result = String[]
offset = 0
req = Dict()
if !isnothing(subject)
req[:subject] = subject
end
iterable_request() do offset
req[:offset] = offset
json = NATS.request(JSON3.Object, connection, "\$JS.API.STREAM.NAMES", JSON3.write(req); timer)
throw_on_api_error(json)
if !isnothing(json.streams)
append!(result, json.streams)
end
StructTypes.constructfrom(IterableResponse, json)
end
result
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1962 |
"""
$(SIGNATURES)
Create a stream.
"""
function stream_create(connection::NATS.Connection, config::StreamConfiguration; no_throw = false)
validate(config)
response = NATS.request(Union{StreamInfo, ApiError}, connection, "\$JS.API.STREAM.CREATE.$(config.name)", JSON3.write(config))
no_throw || throw_on_api_error(response)
response
end
"""
$(SIGNATURES)
Update a stream.
"""
function stream_update(connection::NATS.Connection, config::StreamConfiguration; no_throw = false)
validate(config)
response = NATS.request(Union{StreamInfo, ApiError}, connection, "\$JS.API.STREAM.UPDATE.$(config.name)", JSON3.write(config))
no_throw || throw_on_api_error(response)
response
end
function stream_update_or_create(connection::NATS.Connection, config::StreamConfiguration)
res = stream_update(connection, config; no_throw = true)
if res isa StreamInfo
res
elseif res isa ApiError
if res.code == 404
stream_create(connection, config)
else
throw(res)
end
end
end
"""
$(SIGNATURES)
Delete a stream.
"""
function stream_delete(connection::NATS.Connection, stream::String; no_throw = false)
res = NATS.request(Union{ApiResult, ApiError}, connection, "\$JS.API.STREAM.DELETE.$(stream)")
no_throw || throw_on_api_error(res)
res
end
function stream_delete(connection::NATS.Connection, stream::StreamInfo; no_throw = false)
stream_delete(connection, stream.config.name; no_throw)
end
"""
$(SIGNATURES)
Purge a stream. It is equivalent of deleting all messages.
"""
function stream_purge(connection::NATS.Connection, stream::String; no_throw = false)
res = NATS.request(Union{ApiResult, ApiError}, connection, "\$JS.API.STREAM.PURGE.$stream")
no_throw || throw_on_api_error(res)
res
end
function stream_purge(connection::NATS.Connection, stream::StreamInfo; no_throw = false)
stream_purge(connection, stream.config.name; no_throw)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2430 |
function check_allow_direct(connection::NATS.Connection, stream_name::String)
@lock connection.allow_direct_lock begin
cached = get(connection.allow_direct, stream_name, nothing)
if !isnothing(cached)
cached
else
stream = stream_info(connection, stream_name)
connection.allow_direct[stream_name] = stream.config.allow_direct
stream.config.allow_direct
end
end
end
"""
$(SIGNATURES)
Get a message from stream.
"""
function stream_message_get(connection::NATS.Connection, stream_name::String, subject::String; allow_direct = nothing)
allow_direct = @something allow_direct check_allow_direct(connection, stream_name)
if allow_direct
msg = NATS.request(connection, "\$JS.API.DIRECT.GET.$(stream_name)", "{\"last_by_subj\": \"$subject\"}")
NATS.throw_on_error_status(msg)
msg
else
res = NATS.request(connection, "\$JS.API.STREAM.MSG.GET.$(stream_name)", "{\"last_by_subj\": \"$subject\"}")
json = JSON3.read(NATS.payload(res))
if haskey(json, :error)
throw(StructTypes.constructfrom(ApiError, json.error))
end
subject = json.message.subject
hdrs = haskey(json.message, :hdrs) ? base64decode(json.message.hdrs) : UInt8[]
append!(hdrs, "Nats-Stream: $(stream_name)\r\n")
append!(hdrs, "Nats-Subject: $(json.message.subject)\r\n")
append!(hdrs, "Nats-Sequence: $(json.message.seq)\r\n")
append!(hdrs, "Nats-Time-Stamp: $(json.message.time)\r\n")
payload = base64decode(json.message.data)
NATS.Msg(res.subject, res.sid, nothing, length(hdrs), vcat(hdrs, payload))
end
end
"""
$(SIGNATURES)
Get a message from stream.
"""
function stream_message_get(connection::NATS.Connection, stream::StreamInfo, subject::String)
stream_message_get(connection, stream.config.name, subject; stream.config.allow_direct)
end
"""
$(SIGNATURES)
Delete a message from stream.
"""
function stream_message_delete(connection::NATS.Connection, stream::StreamInfo, msg::NATS.Msg)
seq = NATS.header(msg, "Nats-Sequence")
isnothing(seq) && error("Message has no `Nats-Sequence` header")
# TODO: validate stream name
req = Dict()
req[:seq] = parse(UInt8, seq)
req[:no_erase] = true
NATS.request(ApiResult, connection, "\$JS.API.STREAM.MSG.DELETE.$(stream.config.name)", JSON3.write(req))
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 331 | const DEFAULT_STREAM_PUBLISH_DELAYS = ExponentialBackOff(n = 7, first_delay = 0.1, max_delay = 0.5)
"""
$(SIGNATURES)
Publish a message to stream.
"""
function stream_publish(connection::NATS.Connection, subject, data; delays = DEFAULT_STREAM_PUBLISH_DELAYS)
jetstream_api_call(PubAck, connection, subject, data; delays)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 327 |
struct StreamSub
subject::String
sub::NATS.Sub
consumer::ConsumerInfo
end
function show(io::IO, stream_sub::StreamSub)
print(io, "StreamSub(\"$(stream_sub.subject)\")")
end
include("manage.jl")
include("info.jl")
include("message.jl")
include("publish.jl")
include("subscribe.jl")
include("unsubscribe.jl")
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1042 |
# Subscribe to a stream by creating a consumer.
# Might be more performant to configure republish subject on steram.
"""
$(SIGNATURES)
Subscribe to a stream.
"""
function stream_subscribe(f, connection::NATS.Connection, subject::String)
subject_streams = stream_infos(connection, subject)
isempty(subject_streams) && error("No stream found for subject \"$subject\"")
length(subject_streams) > 1 && error("Multiple streams found for subject \"$subject\"")
stream = only(subject_streams)
name = randstring(20)
deliver_subject = randstring(8)
idle_heartbeat = 1000 * 1000 * 1000 * 3 # 300 ms
consumer_config = ConsumerConfiguration(;name, deliver_subject) # TODO: filter subject
consumer = consumer_create(connection, consumer_config, stream)
f_typed = NATS._fast_call(f)
sub = NATS.subscribe(connection, deliver_subject) do msg
if NATS.statuscode(msg) == 100
@info "heartbeat"
else
f_typed(msg)
end
end
StreamSub(subject, sub, consumer)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 242 | """
$(SIGNATURES)
Unsubscribe stream subscription.
"""
function stream_unsubscribe(connection::NATS.Connection, stream_sub::StreamSub)
NATS.unsubscribe(connection, stream_sub.sub)
consumer_delete(connection, stream_sub.consumer)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1164 | ### convert.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains deserialization utilities for converting NATS protocol messages into structured data.
#
### Code:
function convert(::Type{Msg}, msgraw::NATS.MsgRaw)
buffer = msgraw.buffer
sid = msgraw.sid
subject = String(buffer[msgraw.subject_range])
reply_to = isempty(msgraw.reply_to_range) ? nothing : String(buffer[msgraw.reply_to_range])
headers_length = msgraw.header_bytes
payload = @view buffer[msgraw.payload_range]
Msg(subject, sid, reply_to, headers_length, payload)
end
function convert(::Type{String}, msg::NATS.Msg)
# Default representation on msg content is payload string.
# This allows to use handlers that take just a payload string and do not use other fields.
payload(msg)
end
function convert(::Type{JSON3.Object}, msg::NATS.Msg)
# TODO: some validation if header has error headers
JSON3.read(@view msg.payload[(begin + msg.headers_length):end])
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2693 | ### crc16.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementations of CRC16 checksum used by NATS nkeys authentication.
#
### Code:
const CRC16 = [
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
]
function crc16(data::Vector{UInt8})::UInt16
crc::UInt16 = 0
for c in data
crc = xor(crc << 8, CRC16[begin + xor(crc>>8, c)])
end
crc
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 738 | ### errors.jl
#
# Copyright (C) 2024 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementations for handling NATS protocol errors.
#
### Code:
struct NATSError <: Exception
code::Int64
message::String
end
function has_error_status(code::Int64)
code in 400:599
end
function has_error_status(msg::NATS.Msg)
has_error_status(statuscode(msg))
end
function throw_on_error_status(msg::Msg)
msg_status, status_message = statusinfo(msg)
if has_error_status(msg_status)
throw(NATSError(msg_status, status_message))
end
msg
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1626 | ### headers.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementations headers parsig and serialization. Headers are represented as vector of paris of strings.
#
### Code:
const Header = Pair{String, String}
const Headers = Vector{Header}
function headers_str(msg::Msg)
String(msg.payload[begin:msg.headers_length])
end
function headers(msg::Msg)
if msg.headers_length == 0
return Headers()
end
hdr = split(headers_str(msg), "\r\n"; keepempty = false)
@assert startswith(first(hdr), "NATS/1.0") "Missing protocol version."
items = hdr[2:end]
items = split.(items, ": "; keepempty = false)
map(x -> string(first(x)) => string(last(x)) , items)
end
function headers(m::Msg, key::String)
last.(filter(h -> first(h) == key, headers(m)))
end
function header(m::Msg, key::String)
hdrs = headers(m, key)
isempty(hdrs) ? nothing : only(hdrs)
end
function statusinfo(header_str::String)
hdr = split(header_str, "\r\n"; keepempty = false, limit = 2)
splitted = split(first(hdr), ' ', limit = 3)
status = length(splitted) >= 2 ? parse(Int, splitted[2]) : 200
message = length(splitted) >= 3 ? splitted[3] : ""
status, message
end
function statusinfo(msg::Msg)::Tuple{Int64, String}
if msg.headers_length == 0
200, ""
else
statusinfo(headers_str(msg))
end
end
function statuscode(msg::Msg)::Int64
first(statusinfo(msg))
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2708 | ### nkeys.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementations nkeys signingature which is one of methods of authentication used by NATS protocol.
#
### Code:
const PUBLIC_KEY_LENGTH = Sodium.LibSodium.crypto_sign_ed25519_PUBLICKEYBYTES
const SECRET_KEY_LENGTH = Sodium.LibSodium.crypto_sign_ed25519_SECRETKEYBYTES
const SIGNATURE_LENGTH = Sodium.LibSodium.crypto_sign_ed25519_BYTES
function sign(nonce::String, nkey_seed::String)
public_key = Vector{Cuchar}(undef, PUBLIC_KEY_LENGTH)
secret_key = Vector{Cuchar}(undef, SECRET_KEY_LENGTH)
raw_seed = _decode_seed(nkey_seed)
errno = Sodium.LibSodium.crypto_sign_ed25519_seed_keypair(public_key, secret_key, raw_seed)
errno == 0 || error("Cannot get key pair from nkey seed.")
signed_message_length = Ref{UInt64}(0)
signed_message = Vector{Cuchar}(undef, SIGNATURE_LENGTH)
errno = Sodium.LibSodium.crypto_sign_ed25519_detached(signed_message, signed_message_length, nonce, sizeof(nonce), secret_key)
errno == 0 || error("Cannot sign nonce.")
@assert signed_message_length[] == SIGNATURE_LENGTH "Unexpected signature length."
signature = transcode(Base64Encoder(urlsafe = true), signed_message)
String(rstrip(==('='), String(signature)))
end
function _decode(encoded::String)
padding_length = mod(8 - mod(length(encoded), 8), 8)
raw = transcode(Base32Decoder(), encoded * repeat("=", padding_length))
length(raw) < 4 && error("Invalid length of decoded nkey.")
crc_bytes = raw[end-1:end]
data_bytes = raw[begin:end-2]
crc = only(reinterpret(UInt16, crc_bytes))
crc == crc16(data_bytes) || error("Invalid nkey CRC16 sum.")
data_bytes
end
const NKEY_SEED_PREFIXES = ['S'] # seed
const NKEY_PUBLIC_PREFIXES = ['N', 'C', 'O', 'A', 'U', 'X'] # server, cluster, operator, account, user, curve
const NKEY_PREFIXES = ['S', 'P', 'N', 'C', 'O', 'A', 'U', 'X'] # seed, private, server, cluster, operator, account, user, curve
function _decode_seed(seed)
# https://github.com/nats-io/nkeys/blob/3e454c8ca12e8e8a15d4c058d380e1ec31399597/strkey.go#L172
seed[1] in NKEY_PUBLIC_PREFIXES && error("Public nkey provided instead of private nkey seed, it should start with character '$(NKEY_SEED_PREFIXES...)'.")
seed[1] in NKEY_SEED_PREFIXES || error("Invalid nkey seed prefix, expected one of: $NKEY_SEED_PREFIXES.")
seed[2] in NKEY_PUBLIC_PREFIXES || error("Invalid public nkey prefix, expected one of: $NKEY_PUBLIC_PREFIXES.")
raw = _decode(seed)
raw[3:end]
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 13867 | ### parser.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementations of NATS protocol parsers.
#
### Code:
@enum ParserState OP_START OP_PLUS OP_PLUS_O OP_PLUS_OK OP_MINUS OP_MINUS_E OP_MINUS_ER OP_MINUS_ERR OP_MINUS_ERR_SPC MINUS_ERR_ARG OP_M OP_MS OP_MSG OP_MSG_SPC MSG_ARG MSG_PAYLOAD MSG_END OP_P OP_H OP_PI OP_PIN OP_PING OP_PO OP_PON OP_PONG OP_I OP_IN OP_INF OP_INFO OP_INFO_SPC INFO_ARG
# Parser state and temporary buffers for parsing subscription messages.
@kwdef mutable struct ParserData
state::ParserState = OP_START
has_header::Bool = false
subject_range::UnitRange{Int64} = 1:0
sid::Int64 = 0
reply_to_range::UnitRange{Int64} = 1:0
payload_start = 0
header_bytes::Int64 = 0
total_bytes::Int64 = 0
arg_begin::Int64 = -1
arg_no::Int64 = 0
args::Vector{UnitRange{Int64}} = UnitRange{Int64}[0:0, 0:0, 0:0, 0:0, 0:0]
payload_buffer::Vector{UInt8} = UInt8[]
results::Vector{ProtocolMessage} = ProtocolMessage[]
end
function parse_error(buffer, pos, data::ParserData)
buf = String(buffer[max(begin, pos-100):min(end,pos+100)])
error("Parser error on position $pos: $buf\nBuffer length: $(length(buffer))")
end
function parser_loop(f, io::IO)
data = ParserData()
# TODO: ensure eof does not block for TLS connection
while !eof(io) # EOF indicates connection is closed, task will be stopped and reconnected.
data_read_start = time()
buffer = readavailable(io) # Sleeps when no data available.
data_ready_time = time()
parse_buffer(io, buffer, data)
batch_ready_time = time()
f(data.results)
handler_call_time = time()
# @info "Read time $(data_ready_time - data_read_start), parser time: $(batch_ready_time - data_ready_time), handler time: $(handler_call_time - batch_ready_time)" length(buffer) length(data.results)
empty!(data.results)
end
end
macro uint8(char::Char)
convert(UInt8, char)
end
@inline function bytes_to_int64(buffer, range)::Int64
ret = Int64(0)
for i in range
ret = (ret << 3) + (ret << 1)
ret += buffer[i] - 0x30
end
ret
end
function parse_buffer(io::IO, buffer::Vector{UInt8}, data::ParserData)
pos = 0
len = length(buffer)
while pos < len
pos += 1
byte = buffer[pos]
if data.state == OP_START
if byte == (@uint8 'M') || byte == (@uint8 'm')
data.state = OP_M
data.has_header = false
elseif byte == (@uint8 'H') || byte == (@uint8 'h')
data.state = OP_H
data.has_header = true
elseif byte == (@uint8 'P') || byte == (@uint8 'p')
data.state = OP_P
elseif byte == (@uint8 '+')
data.state = OP_PLUS
elseif byte == (@uint8 '-')
data.state = OP_MINUS
elseif byte == (@uint8 'I') || byte == (@uint8 'i')
data.state = OP_I
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_PLUS
if byte == (@uint8 'O') || byte == (@uint8 'o')
data.state = OP_PLUS_O
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_PLUS_O
if byte == (@uint8 'K') || byte == (@uint8 'k')
data.state = OP_PLUS_OK
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_PLUS_OK
if byte == (@uint8 '\r')
elseif byte == (@uint8 '\n')
push!(data.results, Ok())
data.state = OP_START
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_MINUS
if byte == (@uint8 'E') || byte == (@uint8 'e')
data.state = OP_MINUS_E
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_MINUS_E
if byte == (@uint8 'R') || byte == (@uint8 'r')
data.state = OP_MINUS_ER
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_MINUS_ER
if byte == (@uint8 'R') || byte == (@uint8 'r')
data.state = OP_MINUS_ERR
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_MINUS_ERR
if byte == (@uint8 ' ') || byte == (@uint8 '\t')
data.state = OP_MINUS_ERR_SPC
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_MINUS_ERR_SPC
if byte == @uint8 ' '
data.state = OP_MINUS_ERR_SPC
elseif byte == @uint8 '\''
data.state = MINUS_ERR_ARG
else
parse_error(buffer, pos, data)
end
elseif data.state == MINUS_ERR_ARG
if byte == (@uint8 '\'')
elseif byte == (@uint8 '\r')
elseif byte == (@uint8 '\n')
push!(data.results, Err(String(data.payload_buffer)))
data.state = OP_START
else
push!(data.payload_buffer, byte)
end
elseif data.state == OP_M
if byte == (@uint8 'S') || byte == (@uint8 's')
data.state = OP_MS
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_MS
if byte == (@uint8 'G') || byte == (@uint8 'g')
data.state = OP_MSG
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_MSG
if byte == (@uint8 ' ') || byte == (@uint8 '\t')
data.state = OP_MSG_SPC
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_MSG_SPC
if byte == (@uint8 ' ') || byte == (@uint8 '\t')
# Skip all spaces.
else
data.arg_begin = pos
data.arg_no += 1
if pos == len
rest = readuntil(io, "\r\n")
append!(buffer, rest, "\r\n")
len += length(rest) + 2
end
data.state = MSG_ARG
end
elseif data.state == MSG_ARG
if pos == len && byte != (@uint8 '\n')
rest = readuntil(io, "\r\n")
len += length(rest) + 2
append!(buffer, rest, "\r\n")
end
if byte == (@uint8 ' ') || byte == (@uint8 '\t')
argrange = range(data.arg_begin, pos-1)
isempty(argrange) || (data.args[data.arg_no] = argrange)
data.arg_begin = pos+1
isempty(argrange) || (data.arg_no += 1)
elseif byte == (@uint8 '\r')
data.args[data.arg_no] = range(data.arg_begin, (pos-1))
elseif byte == (@uint8 '\n')
subject_range = data.args[1]
if data.has_header
if data.arg_no == 4
data.header_bytes = bytes_to_int64(buffer, data.args[3])
data.total_bytes = bytes_to_int64(buffer, data.args[4])
data.reply_to_range = 1:0
elseif data.arg_no == 5
data.header_bytes = bytes_to_int64(buffer, data.args[4])
data.total_bytes = bytes_to_int64(buffer, data.args[5])
data.reply_to_range = data.args[3]
else
parse_error(buffer, pos, data)
end
else
if data.arg_no == 3
data.header_bytes = 0
data.total_bytes = bytes_to_int64(buffer, data.args[3])
data.reply_to_range = 1:0
elseif data.arg_no == 4
data.total_bytes = bytes_to_int64(buffer, data.args[4])
data.header_bytes = 0
data.reply_to_range = data.args[3]
else
parse_error(buffer, pos, data)
end
end
ending = pos + data.total_bytes + 2
if ending > len
rest = read(io, ending - len)
len += length(rest)
append!(buffer, rest)
end
payload_range = range(pos+1, pos + data.total_bytes)
pos = pos + data.total_bytes + 2
msg = MsgRaw(data.sid, buffer, subject_range, data.reply_to_range, data.header_bytes, payload_range)
push!(data.results, msg)
data.arg_no = 0
data.sid = 0
data.state = OP_START
else
if data.arg_no == 2
data.sid = data.sid * 10
data.sid += byte - 0x30
end
end
elseif data.state == OP_P
if byte == (@uint8 'I') || byte == (@uint8 'i')
data.state = OP_PI
elseif byte == (@uint8 'O') || byte == (@uint8 'o')
data.state = OP_PO
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_H
if byte == (@uint8 'M') || byte == (@uint8 'm')
data.state = OP_M
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_PI
if byte == (@uint8 'N') || byte == (@uint8 'n')
data.state = OP_PIN
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_PIN
if byte == (@uint8 'G') || byte == (@uint8 'g')
data.state = OP_PING
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_PING
if byte == (@uint8 '\r')
#Do nothing
elseif byte == (@uint8 '\n')
push!(data.results, Ping())
data.state = OP_START
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_PO
if byte == (@uint8 'N') || byte == (@uint8 'n')
data.state = OP_PON
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_PON
if byte == (@uint8 'G') || byte == (@uint8 'g')
data.state = OP_PONG
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_PONG
if byte == (@uint8 '\r')
#Do nothing
elseif byte == (@uint8 '\n')
push!(data.results, Pong())
data.state = OP_START
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_I
if byte == (@uint8 'N') || byte == (@uint8 'n')
data.state = OP_IN
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_IN
if byte == (@uint8 'F') || byte == (@uint8 'f')
data.state = OP_INF
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_INF
if byte == (@uint8 'O') || byte == (@uint8 'o')
data.state = OP_INFO
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_INFO
if byte == (@uint8 ' ') || byte == (@uint8 '\t')
data.state = OP_INFO_SPC
else
parse_error(buffer, pos, data)
end
elseif data.state == OP_INFO_SPC
if byte == (@uint8 ' ') || byte == (@uint8 '\t')
# skip
else
push!(data.payload_buffer, byte)
data.state = INFO_ARG
end
elseif data.state == INFO_ARG
if byte == (@uint8 '\r')
elseif byte == (@uint8 '\n')
push!(data.results, JSON3.read(data.payload_buffer, Info))
empty!(data.payload_buffer)
data.state = OP_START
else
push!(data.payload_buffer, byte)
end
end
end
end
# Simple interactive parser for protocol initialization.
function next_protocol_message(io::IO)::ProtocolMessage
headline = readuntil(io, "\r\n")
if startswith(uppercase(headline), "+OK") Ok()
elseif startswith(uppercase(headline), "PING") Ping()
elseif startswith(uppercase(headline), "PONG") Pong()
elseif startswith(uppercase(headline), "-ERR") parse_err(headline)
elseif startswith(uppercase(headline), "INFO") parse_info(headline)
elseif startswith(uppercase(headline), "MSG") error("Parsing MSG not supported")
elseif startswith(uppercase(headline), "HMSG") error("Parsing HMSG not supported")
else error("Unexpected protocol message: '$headline'.")
end
end
function parse_info(headline::String)::Info
json = SubString(headline, ncodeunits("INFO "))
JSON3.read(json, Info)
end
function parse_err(headline::String)::Err
left = ncodeunits("-ERR '") + 1
right = ncodeunits(headline) - ncodeunits("'")
Err(headline[left:right])
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 411 | ### payload.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <jakubwro@users.noreply.github.com>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains utilities for NATS messages payload manipulation.
#
### Code:
payload(msg::Msg) = String(msg.payload[begin+msg.headers_length:end]) # TODO: optimize this | NATS | https://github.com/jakubwro/NATS.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.