text
stringlengths 5
1.02M
|
---|
using Gadfly
using DataFrames
using VML
include("../utility.jl")
function main()
N = [1,2,3,4,5,6,7,8,9,
10,20,30,40,50,60,70,80,90,100,200,300,400,500,750,
1_000,2_500,5_000,7_500,10_000,100_000,1_000_000]
df = DataFrame(N=Int64[],ALLOC=Float64[],VJULIA=Float64[],BJULIA=Float64[],VML=Float64[])
@inbounds for i in 1:length(N)
T = Float64
n = N[i]
a = rand(n)
dest = zeros(n)
sqrt(a)
nrep = 100
ncycle = 10_000 ÷ n + 1
# n < 100 ? gc_enable(false) : gc_enable(true)
# gc()
talloc = 0.0
for j in 1:nrep
talloc += @elapsed for k in 1:ncycle Vector{T}(n) end
end
talloc = talloc / nrep / ncycle / n * 1e9
# gc()
tvjulia = 0.0
for j in 1:nrep
tvjulia += @elapsed for k in 1:ncycle sqrt(a) end
end
tvjulia = tvjulia / nrep / ncycle / n * 1e9
# gc()
tbjulia = 0.0
# for j in 1:nrep
# tbjulia += @elapsed for k in 1:ncycle broadcast!(sqrt,dest,a) end
# end
# tbjulia = tbjulia / nrep / ncycle / n * 1e9
# gc()
tvml = 0.0
# for j in 1:nrep
# tvml += @elapsed for k in 1:ncycle VML.sqrt!(dest,a) end
# end
# tvml = tvml / nrep / ncycle / n * 1e9
# n < 100 ? gc_enable(false) : gc_enable(true)
push!(df,[n,talloc, tvjulia, tbjulia, tvml])
end
df
end
df = main();
df[:diff] = df[:VJULIA]-df[:ALLOC]
println(df)
layers = Layer[]
bench_alloc(),bench_jvect(),bench_jbroadcast!(),bench_mkl(),bench_mkl!(),bench_jvect2()
df = DataFrame() ; df[:N], df[:CPU] = bench_alloc()
push!(layers,layer(df, x="N", y="CPU", Geom.line, Theme(default_color=color("blue")))[1])
df = DataFrame() ; df[:N], df[:CPU] = bench_jvect()
push!(layers,layer(df, x="N", y="CPU", Geom.line, Theme(default_color=color("yellow")))[1])
df = DataFrame() ; df[:N], df[:CPU] = bench_jbroadcast!()
push!(layers,layer(df, x="N", y="CPU", Geom.line, Theme(default_color=color("green")))[1])
df = DataFrame() ; df[:N], df[:CPU] = bench_mkl()
push!(layers,layer(df, x="N", y="CPU", Geom.line, Theme(default_color=color("orange")))[1])
df = DataFrame() ; df[:N], df[:CPU] = bench_mkl!()
push!(layers,layer(df, x="N", y="CPU", Geom.line, Theme(default_color=color("red")))[1])
df = DataFrame() ; df[:N], df[:CPU] = bench_jvect2()
push!(layers,layer(df, x="N", y="CPU", Geom.line, Theme(default_color=color("black")))[1])
println(df)
p = Gadfly.plot(layers,
# Scale.y_log10,
Scale.x_log10,
Guide.xlabel("n-element vector"),
Guide.ylabel("CPU time in nsec/element"),
Guide.title("CPU time with n elements"),
Guide.manual_color_key("",
["ALLOC", "Base.sqrt","broadcast!","VML.sqrt","VML.sqrt!","ibench"],
["blue","yellow","green","orange","red","black"])
)
path = Pkg.dir("MKL") * "/benchmark/sqrt_cpu_regarding_n/"
draw(PNG(path*"sqrt_map!.png", 20cm, 20cm), p)
|
base_dir = string(dirname(@__FILE__))
@testset "read_data" begin
include(joinpath(base_dir,"data_5bus_pu.jl"));
include(joinpath(base_dir,"data_14bus_pu.jl"))
end
|
using LinearAlgebra: norm, transpose
"""
tree_approximation!(newtree::Tree, path::Function, nIterations::Int64, p::Int64=2, r::Int64=2)
Returns a valuated probability scenario tree approximating the input stochastic process.
Args:
- *newtree* - Tree with a certain branching structure,
- *path* - function generating samples from the stochastic process to be approximated,
- *nIterations* - number of iterations for stochastic approximation procedure,
- *p* - choice of norm (default p = 2 (Euclidean distance)), and,
- *r* - transportation distance parameter
"""
function tree_approximation!(newtree::Tree, path::Function, nIterations::Int64, p::Int64=2, r::Int64=2)
leaf, omegas, probaLeaf = leaves(newtree) # leaves, indexes and probabilities of the leaves of the tree
dm = size(newtree.state, 2) # dm = dimension of the states of the nodes of the tree.
T = height(newtree) # height of the tree = number of stages - 1
n = length(leaf) # number of leaves = no of omegas
d = zeros(Float64, dm, length(leaf))
samplepath = zeros(Float64, T+1, dm) # T + 1 = the number of stages in the tree.
probaLeaf = zero(probaLeaf)
probaNode = nodes(newtree) # all nodes of the tree
path_to_leaves = [root(newtree, i) for i in leaf] # all the paths from root to the leaves
path_to_all_nodes = [root(newtree, j) for j in probaNode] # all paths to other nodes
for k = 1 : nIterations
if (rem(k,10)==0)
print("Progress: $(round(k/nIterations*100,digits=2))% \r")
flush(stdout)
end
critical = max(0.0, 0.2 * sqrt(k) - 0.1 * n)
#tmp = findall(xi -> xi <= critical, probaLeaf)
tmp = Int64[inx for (inx, ppf) in enumerate(probaLeaf) if ppf <= critical]
samplepath .= path() # a new trajectory to update the values on the nodes
#The following part addresses the critical probabilities of the tree so that we don't loose the branches
if !isempty(tmp) && !iszero(tmp)
probaNode = zero(probaNode)
probaNode[leaf] = probaLeaf
for i = leaf
while newtree.parent[i] > 0
probaNode[newtree.parent[i]] = probaNode[newtree.parent[i]] + probaNode[i]
i = newtree.parent[i]
end
end
for tmpi = tmp
rt = path_to_leaves[tmpi]
#tmpi = findall(pnt -> pnt <= critical, probaNode[rt])
tmpi = Int64[ind for (ind, pnt) in enumerate(probaNode[rt]) if pnt <= critical]
newtree.state[rt[tmpi],:] .= samplepath[tmpi,:]
end
end
#To the step of STOCHASTIC COMPUTATIONS
endleaf = 0 #start from the root
for t = 1 : T+1
tmpleaves = newtree.children[endleaf + 1]
disttemp = Inf #or fill(Inf,dm)
for i = tmpleaves
dist = norm(view(samplepath, 1 : t) - view(newtree.state, path_to_all_nodes[i]), p)
if dist < disttemp
disttemp = dist
endleaf = i
end
end
end
#istar = findall(lf -> lf == endleaf, leaf)
istar = Int64[idx for (idx, lf) in enumerate(leaf) if lf == endleaf]
probaLeaf[istar] .+= 1.0 #counter of probabilities
StPath = path_to_leaves[endleaf - (leaf[1] - 1)]
delta = newtree.state[StPath,:] - samplepath
d[:,istar] .+= norm(delta, p).^(r)
delta .= r .* norm(delta, p).^(r - p) .* abs.(delta)^(p - 1) .* sign.(delta)
ak = 1.0 ./ (30.0 .+ probaLeaf[istar]) #.^ 0.75 # step size function - sequence for convergence
newtree.state[StPath,:] = newtree.state[StPath,:] - delta .* ak
end
probabilities = map(plf -> plf / sum(probaLeaf), probaLeaf) #divide every element by the sum of all elements
t_dist = (d * hcat(probabilities) / nIterations) .^ (1 / r)
newtree.name = "$(newtree.name) with d=$(t_dist) at $(nIterations) iterations"
newtree.probability .= build_probabilities!(newtree, hcat(probabilities)) #build the probabilities of this tree
return newtree
end
|
# UNION clause.
mutable struct UnionClause <: AbstractSQLClause
over::Union{SQLClause, Nothing}
all::Bool
args::Vector{SQLClause}
UnionClause(;
over = nothing,
all = false,
args) =
new(over, all, args)
end
UnionClause(args...; over = nothing, all = false) =
UnionClause(over = over, all = all, args = SQLClause[args...])
"""
UNION(; over = nothing, all = false, args)
UNION(args...; over = nothing, all = false)
A `UNION` clause.
# Examples
```jldoctest
julia> c = FROM(:measurement) |>
SELECT(:person_id, :date => :measurement_date) |>
UNION(all = true,
FROM(:observation) |>
SELECT(:person_id, :date => :observation_date));
julia> print(render(c))
SELECT
"person_id",
"measurement_date" AS "date"
FROM "measurement"
UNION ALL
SELECT
"person_id",
"observation_date" AS "date"
FROM "observation"
```
"""
UNION(args...; kws...) =
UnionClause(args...; kws...) |> SQLClause
dissect(scr::Symbol, ::typeof(UNION), pats::Vector{Any}) =
dissect(scr, UnionClause, pats)
function PrettyPrinting.quoteof(c::UnionClause, ctx::QuoteContext)
ex = Expr(:call, nameof(UNION))
if c.all !== false
push!(ex.args, Expr(:kw, :all, c.all))
end
if isempty(c.args)
push!(ex.args, Expr(:kw, :args, Expr(:vect)))
else
append!(ex.args, quoteof(c.args, ctx))
end
if c.over !== nothing
ex = Expr(:call, :|>, quoteof(c.over, ctx), ex)
end
ex
end
rebase(c::UnionClause, c′) =
UnionClause(over = rebase(c.over, c′), args = c.args, all = c.all)
|
"""
@do block :while condition
Control flow statement that executes in a **local** scope a `block` of code at least once,
and then repeatedly executes the `block` or not, depending on a given boolean `condition`
after the `:while` symbol at the end of the `block`.`.
# Examples
```julia
julia> Pkg.clone("https://github.com/Ismael-VC/DoWhile.jl.git")
julia> using DoWhile
julia> i = 0
0
julia> @do begin
@show i
i += 1
end :while i < 5
i = 0
i = 1
i = 2
i = 3
i = 4
julia> @do (
@show i;
i += 1
) :while i < 5
i = 5
julia> i
6
julia> @do (@show i; i += 1) :while i ≤ 10
i = 6
i = 7
i = 8
i = 9
i = 10
julia> @do begin @show i; i += 1 end :while i ≤ 10
i = 11
julia> i
12
```
# Help
```julia
help?> DoWhile
?help?> @do
julia> @doc DoWhile
julia> @doc @do
```
"""
module DoWhile
export @do
let
do_while = quote
macro fo(block, sym, cond)
s = sym.args[1]
s != :while && error("@do expected :while symbol, got :$s")
quote
let
$(esc(block))
while $(esc(cond))
$(esc(block))
end
end
end
end
end
do_while.args[2].args[1].args[1] = :do
eval(do_while)
end
@doc (@doc DoWhile) :(@do)
end # module
|
struct HierarchicalPeriodicHMM{F,T} <: AbstractHMM{F}
a::Vector{T}
A::Array{T,3}
B::Array{<:Distribution{F},4}
HierarchicalPeriodicHMM{F,T}(a, A, B) where {F,T} = assert_hierarchicalperiodichmm(a, A, B) && new(a, A, B)
end
HierarchicalPeriodicHMM(
a::AbstractVector{T},
A::AbstractArray{T,3},
B::AbstractArray{<:Distribution{F},4},
) where {F,T} = HierarchicalPeriodicHMM{F,T}(a, A, B)
HierarchicalPeriodicHMM(A::AbstractArray{T,3}, B::AbstractArray{<:Distribution{F},4}) where {F,T} =
HierarchicalPeriodicHMM{F,T}(ones(size(A, 1)) ./ size(A, 1), A, B)
function assert_hierarchicalperiodichmm(a::AbstractVector, A::AbstractArray{T,3} where {T}, B::AbstractArray{<:Distribution,4})
@argcheck isprobvec(a)
@argcheck istransmats(A)
@argcheck size(A, 3) == size(B, 2) ArgumentError("Period length must be the same for transition matrix and distribution")
@argcheck length(a) == size(A, 1) == size(B, 1) ArgumentError("Number of transition rates must match length of chain")
return true
end
function assert_hierarchicalperiodichmm(hmm::HierarchicalPeriodicHMM)
assert_periodichmm(hmm.a, hmm.A, hmm.B)
end
size(hmm::HierarchicalPeriodicHMM, dim = :) = (size(hmm.B, 1), size(hmm.B, 3), size(hmm.B, 2), size(hmm.B, 4))[dim]
# K, D, T, size_memory
copy(hmm::HierarchicalPeriodicHMM) = HierarchicalPeriodicHMM(copy(hmm.a), copy(hmm.A), copy(hmm.B))
function rand_test(
rng::AbstractRNG,
hmm::HierarchicalPeriodicHMM,
n2t::AbstractArray{Int},
useless;
init = rand(rng, Categorical(hmm.a)),
seq = false,
kwargs...
)
T = size(hmm.B, 2)
N = length(n2t)
z = Vector{Int}(undef, N)
(T >= 1) && (z[1] = init)
for n = 2:N
tm1 = n2t[n-1] # periodic t-1
z[n] = rand(rng, Categorical(hmm.A[z[n-1], :, tm1]))
end
y = rand(rng, hmm, n2t, z, useless; kwargs...)
seq ? (z, y) : y
end
function rand_test(
rng::AbstractRNG,
hmm::HierarchicalPeriodicHMM,
n2t::AbstractArray{Int},
z::AbstractVector{<:Integer},
yini;
size_memory = size(hmm, 4)
)
T = size(hmm, 2)
max_size_memory = maximum(size_memory)
y = Matrix{Bool}(undef, length(z), T)
memory = Int.(log.(size_memory) / log(2))
D = size(y, 2)
@argcheck D == size(hmm, 2)
@argcheck length(n2t) == length(z)
p = zeros(D)
for j = 1:D
if memory[j] > 0
# One could do some specialized for each value of memory e.g. for memory = 1, we have simply previous_day_cat = y[n-1,:].+1
N_ini = length(yini[1:memory[j], j])
y[1:N_ini, j] = yini[1:memory[j], j]
for n in eachindex(z)[N_ini+1:end]
t = n2t[n] # periodic t
previous_day_cat = bin2digit([y[n-m, j] for m = 1:memory[j]])
p = succprob(hmm.B[z[n], t, j, previous_day_cat])
y[n, j] = rand(Bernoulli(p))
end
else
for n in eachindex(z)[1:end]
t = n2t[n] # periodic t
p = succprob(hmm.B[z[n], t, j, 1])
y[n, j] = rand(Bernoulli(p))
end
end
end
y
end
function rand(
rng::AbstractRNG,
hmm::HierarchicalPeriodicHMM,
n2t::AbstractArray{Int},
useless;
init = rand(rng, Categorical(hmm.a)),
seq = false
)
T = size(hmm.B, 2)
N = length(n2t)
z = Vector{Int}(undef, N)
(T >= 1) && (z[1] = init)
for n = 2:N
tm1 = n2t[n-1] # periodic t-1
z[n] = rand(rng, Categorical(hmm.A[z[n-1], :, tm1]))
end
y = rand(rng, hmm, n2t, z, useless)
seq ? (z, y) : y
end
function rand(
rng::AbstractRNG,
hmm::HierarchicalPeriodicHMM,
n2t::AbstractArray{Int},
z::AbstractVector{<:Integer},
yini
)
T = size(hmm, 2)
y = Matrix{Bool}(undef, length(z), T)
memory = Int(log(size(hmm, 4)) / log(2))
D = size(y, 2)
@argcheck D == size(hmm, 2)
@argcheck length(n2t) == length(z)
p = zeros(D)
if memory > 0
# One could do some specialized for each value of memory e.g. for memory = 1, we have simply previous_day_cat = y[n-1,:].+1
N_ini = size(yini, 1)
@argcheck N_ini == memory # Did we gave the correct number of initial conditions
size(yini, 1) == D
y[1:N_ini, :] = yini
previous_day_cat = zeros(Int, D)
for n in eachindex(z)[N_ini+1:end]
t = n2t[n] # periodic t
previous_day_cat[:] = bin2digit.(eachcol([y[n-m, j] for m = 1:memory, j = 1:D]))
p[:] = succprob.(hmm.B[CartesianIndex.(z[n], t, 1:D, previous_day_cat)])
y[n, :] = rand(Product(Bernoulli.(p)))
end
else
for n in eachindex(z)[1:end]
t = n2t[n] # periodic t
p[:] = succprob.(hmm.B[CartesianIndex.(z[n], t, 1:D, 1)])
y[n, :] = rand(Product(Bernoulli.(p)))
end
end
y
end
rand(hmm::HierarchicalPeriodicHMM, n2t::AbstractArray{Int}, useless; kwargs...) = rand(GLOBAL_RNG, hmm, n2t, useless; kwargs...)
rand(hmm::HierarchicalPeriodicHMM, n2t::AbstractArray{Int}, z::AbstractVector{<:Integer}, useless; kwargs...) = rand(GLOBAL_RNG, hmm, n2t, z, useless; kwargs...)
rand_test(hmm::HierarchicalPeriodicHMM, n2t::AbstractArray{Int}, useless; kwargs...) = rand(GLOBAL_RNG, hmm, n2t, useless; kwargs...)
rand_test(hmm::HierarchicalPeriodicHMM, n2t::AbstractArray{Int}, z::AbstractVector{<:Integer}, useless; kwargs...) = rand(GLOBAL_RNG, hmm, n2t, z, useless; kwargs...)
function likelihoods!(L::AbstractMatrix, hmm::HierarchicalPeriodicHMM, observations, n2t::AbstractArray{Int}, lag_cat::Matrix{Int})
N, K, T, D = size(observations, 1), size(hmm, 1), size(hmm, 3), size(hmm, 2)
@argcheck size(L) == (N, K)
@inbounds for i in OneTo(K), n in OneTo(N)
t = n2t[n] # periodic t
L[n, i] = pdf(product_distribution(hmm.B[CartesianIndex.(i, t, 1:D, lag_cat[n, :])]), observations[n, :])
end
end
function loglikelihoods!(LL::AbstractMatrix, hmm::HierarchicalPeriodicHMM, observations, n2t::AbstractArray{Int}, lag_cat::Matrix{Int})
N, K, T, D = size(observations, 1), size(hmm, 1), size(hmm, 3), size(hmm, 2)
@argcheck size(LL) == (N, K)
@inbounds for i in OneTo(K), n in OneTo(N)
t = n2t[n] # periodic t
LL[n, i] = logpdf(product_distribution(hmm.B[CartesianIndex.(i, t, 1:D, lag_cat[n, :])]), observations[n, :])
end
end
####
# # In-place update of the observations distributions.
#
# quikest and most generic version -> to use
function update_B!(B::AbstractArray{T,4} where {T}, γ::AbstractMatrix, observations, estimator, idx_tj::Matrix{Vector{Vector{Int}}})
@argcheck size(γ, 1) == size(observations, 1)
@argcheck size(γ, 2) == size(B, 1)
N = size(γ, 1)
K = size(B, 1)
T = size(B, 2)
D = size(B, 3)
size_memory = size(B, 4)
## For periodicHMM only the n observations corresponding to B(t) are used to update B(t)
@inbounds for t in OneTo(T)
for i in OneTo(K)
for j = 1:D
for m = 1:size_memory
if sum(γ[idx_tj[t, j][m], i]) > 0
B[i, t, j, m] = fit_mle(Bernoulli, observations[idx_tj[t, j][m], j], γ[idx_tj[t, j][m], i])
else
B[i, t, j, m] = Bernoulli(eps())
end
end
end
end
end
end
function fit_mle(hmm::HierarchicalPeriodicHMM, observations, n2t::AbstractArray{Int}; init = :none, kwargs...)
hmm = copy(hmm)
if init == :kmeans
kmeans_init!(hmm, observations, display = get(kwargs, :display, :none))
end
history = fit_mle!(hmm, observations, n2t; kwargs...)
hmm, history
end
function fit_mle!(
hmm::HierarchicalPeriodicHMM,
observations,
n2t::AbstractArray{Int}
;
display = :none,
maxiter = 100,
tol = 1e-3,
robust = false,
estimator = fit_mle)
@argcheck display in [:none, :iter, :final]
@argcheck maxiter >= 0
N, K, T, size_memory = size(observations, 1), size(hmm, 1), size(hmm, 3), size(hmm, 4)
@argcheck T == size(hmm.B, 2)
history = EMHistory(false, 0, [])
# n2t = date # dayofyear_Leap.(date)
# Allocate memory for in-place updates
c = zeros(N)
α = zeros(N, K)
β = zeros(N, K)
γ = zeros(N, K)
ξ = zeros(N, K, K)
LL = zeros(N, K)
# assign category for observation depending in the past observations
memory = Int(log(size_memory) / log(2))
lag_cat = conditional_to(observations, memory)
idx_tj = idx_observation_of_past_cat(lag_cat, n2t, T, K, size_memory)
loglikelihoods!(LL, hmm, observations, n2t, lag_cat)
robust && replace!(LL, -Inf => nextfloat(-Inf), Inf => log(prevfloat(Inf)))
forwardlog!(α, c, hmm.a, hmm.A, LL, n2t)
backwardlog!(β, c, hmm.a, hmm.A, LL, n2t)
posteriors!(γ, α, β)
logtot = sum(c)
(display == :iter) && println("Iteration 0: logtot = $logtot")
for it = 1:maxiter
update_a!(hmm.a, α, β)
update_A!(hmm.A, ξ, α, β, LL, n2t)
update_B!(hmm.B, γ, observations, estimator, idx_tj)
# Ensure the "connected-ness" of the states,
# this prevents case where there is no transitions
# between two extremely likely observations.
robust && (hmm.A .+= eps())
@check isprobvec(hmm.a)
@check istransmats(hmm.A)
# loglikelihoods!(LL, hmm, observations, n2t)
loglikelihoods!(LL, hmm, observations, n2t, lag_cat)
robust && replace!(LL, -Inf => nextfloat(-Inf), Inf => log(prevfloat(Inf)))
forwardlog!(α, c, hmm.a, hmm.A, LL, n2t)
backwardlog!(β, c, hmm.a, hmm.A, LL, n2t)
posteriors!(γ, α, β)
logtotp = sum(c)
(display == :iter) && println("Iteration $it: logtot = $logtotp")
push!(history.logtots, logtotp)
history.iterations += 1
if abs(logtotp - logtot) < tol
(display in [:iter, :final]) &&
println("EM converged in $it iterations, logtot = $logtotp")
history.converged = true
break
end
logtot = logtotp
end
if !history.converged
if display in [:iter, :final]
println("EM has not converged after $(history.iterations) iterations, logtot = $logtot")
end
end
history
end
## For AbstractHMM + n2t + lag_cat
function loglikelihoods(hmm::HierarchicalPeriodicHMM, observations, n2t::AbstractArray{Int}; logl = nothing, robust = false,
past = [0 1 0 1 1 0 1 0 0 0
1 1 0 1 1 1 1 1 1 1
1 1 0 1 1 1 0 1 1 1
1 1 0 1 1 0 0 0 1 0
1 1 0 1 1 0 0 1 0 1])
(logl !== nothing) && deprecate_kwargs("logl")
N, K, size_memory = size(observations, 1), size(hmm, 1), size(hmm, 4)
LL = Matrix{Float64}(undef, N, K)
memory = Int(log(size_memory) / log(2))
lag_cat = conditional_to(observations, memory; past = past)
loglikelihoods!(LL, hmm, observations, n2t, lag_cat)
if robust
replace!(LL, -Inf => nextfloat(-Inf), Inf => log(prevfloat(Inf)))
end
LL
end
function forward(hmm::HierarchicalPeriodicHMM, observations, n2t::AbstractArray{Int}; logl = nothing, robust = false,
past = [0 1 0 1 1 0 1 0 0 0
1 1 0 1 1 1 1 1 1 1
1 1 0 1 1 1 0 1 1 1
1 1 0 1 1 0 0 0 1 0
1 1 0 1 1 0 0 1 0 1])
(logl !== nothing) && deprecate_kwargs("logl")
LL = loglikelihoods(hmm, observations, n2t; robust = robust, past = past)
forward(hmm.a, hmm.A, LL, n2t)
end
function backward(hmm::HierarchicalPeriodicHMM, observations, n2t::AbstractArray{Int}; logl = nothing, robust = false,
past = [0 1 0 1 1 0 1 0 0 0
1 1 0 1 1 1 1 1 1 1
1 1 0 1 1 1 0 1 1 1
1 1 0 1 1 0 0 0 1 0
1 1 0 1 1 0 0 1 0 1])
(logl !== nothing) && deprecate_kwargs("logl")
LL = loglikelihoods(hmm, observations; robust = robust, past = past)
backward(hmm.a, hmm.A, LL, n2t)
end
function posteriors(hmm::HierarchicalPeriodicHMM, observations, n2t::AbstractArray{Int}; logl = nothing, robust = false,
past = [0 1 0 1 1 0 1 0 0 0
1 1 0 1 1 1 1 1 1 1
1 1 0 1 1 1 0 1 1 1
1 1 0 1 1 0 0 0 1 0
1 1 0 1 1 0 0 1 0 1])
(logl !== nothing) && deprecate_kwargs("logl")
LL = loglikelihoods(hmm, observations, n2t; robust = robust, past = past)
posteriors(hmm.a, hmm.A, LL, n2t)
end
function viterbi(hmm::HierarchicalPeriodicHMM, observations, n2t::AbstractArray{Int}; logl = nothing, robust = false,
past = [0 1 0 1 1 0 1 0 0 0
1 1 0 1 1 1 1 1 1 1
1 1 0 1 1 1 0 1 1 1
1 1 0 1 1 0 0 0 1 0
1 1 0 1 1 0 0 1 0 1])
(logl !== nothing) && deprecate_kwargs("logl")
LL = loglikelihoods(hmm, observations, n2t; robust = robust, past = past)
viterbi(hmm.a, hmm.A, LL, n2t)
end |
function pilot_sampling(num_PilotSamples)
shift_array_SpinUp = Vector{Float64}()
shift_array_SpinDn = Vector{Float64}()
output_file = open("result","a+")
for N = 1 : num_PilotSamples
eff_spec_SpinUp, eff_spec_SpinDn = matrix_product()
Z_up, Z_dn = recursion_partition_function(eff_spec_SpinUp, eff_spec_SpinDn)
write(output_file, string(Z_up[num_SpinUp] * Z_dn[num_SpinDn]), "\n")
end
close(output_file)
end
"Functions for Importance Sampling"
"function roulette_wheel_generator(γ, num_sites)
roulette_wheel = Vector{Float64}()
cumulative_array = Vector{Float64}()
W = 0 # stands for total weight
for i = 0 : num_sites
selection_length = exp( -2 * i * γ + 2 * (num_sites - i) * γ)
W += selection_length
push!(roulette_wheel, selection_length)
push!(cumulative_array, W)
end
roulette_wheel /= W
cumulative_array /= W
return W, roulette_wheel, cumulative_array
end
function roulette_selection(r, W, cumulative_array) # Binary Search
L = length(cumulative_array)
i_index, f_index = 1, L
p_index = floor(Int64, (i_index + f_index) / 2) # pointer index
while true
if cumulative_array[p_index] <= r <= cumulative_array[p_index + 1]
break
elseif p_index == 1 && r <= cumulative_array[p_index]
return p_index
end
if r < cumulative_array[p_index]
f_index = p_index
p_index = floor(Int64, (i_index + f_index) / 2)
else
i_index = p_index
p_index = floor(Int64, (i_index + f_index) / 2)
end
end
p_index + 1
end"
function σlistGenerator(num_sites)
σlist = Array{Int64,1}[]
for i = 0 : num_sites
σarray = 2 * vcat(zeros(Int16, i), ones(Int16, num_sites - i)) .- 1
push!(σlist, σarray)
end
σlist
end
function σfieldGenerator(k, σlist, num_sites) # i takes value from 0 to num_sites
σfield = Random.shuffle(σlist[k + 1])
WeightPerStep = (num_sites + 1) * binomial(num_sites, k) / 2 ^ num_sites
σfield, WeightPerStep
end
|
@testset "WriteBuffer" begin
buf = BSONWriteBuffer()
@test length(buf) == 0
@test size(buf) == (0,)
@test sizeof(buf) == 0
push!(buf, 0x1)
@test length(buf) == 1
@test size(buf) == (1,)
@test sizeof(buf) == 1
@test GC.@preserve buf unsafe_load(pointer(buf)) == 0x1
resize!(buf, 5)
@test length(buf) == 5
@test buf[1] == 0x1
@test_throws BoundsError buf[6]
empty!(buf)
@test length(buf) == 0
buf = BSONWriteBuffer()
sizehint!(buf, 10)
@test length(buf) == 0
@test length(buf.data) == 10
resize!(buf, 10)
@test length(buf) == 10
@test length(buf.data) == 10
push!(buf, 0x2)
@test length(buf) == 11
@test length(buf.data) > 11
end |
using StaticArrays
const MAT_INFO_KEY = Int
struct MatHist
h::SVector{2,Int}
end
function Base.length(h::MatHist)
l = 0
for a in h.h
iszero(a) && break
l += 1
end
return l
end
struct IIEMatrixGame{T} <: Game{MatHist, MAT_INFO_KEY}
R::Matrix{NTuple{2,T}}
end
IIEMatrixGame(g::MatrixGame) = IIEMatrixGame(g.R)
IIEMatrixGame() = IIEMatrixGame([
(0,0) (-1,1) (1,-1);
(1,-1) (0,0) (-1,1);
(-1,1) (1,-1) (0,0)
])
CounterfactualRegret.initialhist(::IIEMatrixGame) = MatHist(SA[0,0])
CounterfactualRegret.isterminal(::IIEMatrixGame, h::MatHist) = length(h) > 1
function CounterfactualRegret.utility(game::IIEMatrixGame, i::Int, h::MatHist)
length(h) > 1 ? game.R[h.h...][i] : 0
end
CounterfactualRegret.player(::IIEMatrixGame, h::MatHist) = length(h)+1
CounterfactualRegret.player(::IIEMatrixGame, k::MAT_INFO_KEY) = k+1
function CounterfactualRegret.next_hist(::IIEMatrixGame, h::MatHist, a)
l = length(h)
return MatHist(setindex(h.h, a, l+1))
end
CounterfactualRegret.infokey(::IIEMatrixGame, h) = length(h)
function CounterfactualRegret.actions(game::IIEMatrixGame, h::MatHist)
iszero(length(h)) ? (1:size(game.R,1)) : (1:size(game.R,2))
end
## extras
function Base.print(io::IO, solver::AbstractCFRSolver{K,G}) where {K,G<:IIEMatrixGame}
println(io)
for (k,v) in solver.I
σ = copy(v.s)
σ ./= sum(σ)
σ = round.(σ, digits=3)
println(io, "Player: $(k) \t σ: $σ")
end
end
function cumulative_strategies(hist::Vector{Vector{Float64}})
Lσ = length(hist[1])
mat = Matrix{Float64}(undef, length(hist), Lσ)
σ = zeros(Float64, Lσ)
for (i,σ_i) in enumerate(hist)
σ = σ + (σ_i - σ)/i
mat[i,:] .= σ
end
return mat
end
@recipe function f(sol::AbstractCFRSolver{K,G}) where {K,G <: IIEMatrixGame}
layout --> 2
link := :both
framestyle := [:axes :axes]
xlabel := "Training Steps"
L1 = length(sol.I[0].σ)
labels1 = Matrix{String}(undef, 1, L1)
for i in eachindex(labels1); labels1[i] = L"a_{%$(i)}"; end
@series begin
subplot := 1
ylabel := "Strategy"
title := "Player 1"
labels := labels1
reduce(hcat,sol.I[0].hist)'
end
L2 = length(sol.I[1].σ)
labels2 = Matrix{String}(undef, 1, L2)
for i in eachindex(labels2); labels2[i] = L"a_{%$(i)}"; end
@series begin
subplot := 2
title := "Player 2"
labels := labels2
reduce(hcat,sol.I[1].hist)'
end
end
|
function parse_input(dirname::String)
f = open(dirname)
lines = readlines()
@assert lines[1] == "problemData"
chainlength = split(lines[2], ',')
@assert chainlength[1] == "maxChainLength"
if chainlength[2] == "Infinity"
max_chain_length = Inf64
else
max_chain_length = Int64(chainlength[2])
end
close(f)
return max_chain_length
end
|
#include("MCMCplot.jl"); traceplot("MCMC_samples_residual_variance.txt","plotly",4); savefig("plot.png");
using DelimitedFiles,Plots,Plots.PlotMeasures,StatsPlots
function traceplot(file,backend="plotly",nplots=4)
#catch errors when no backends are installed
if backend == "pyplot"
pyplot(size=(300*nplots,200*nplots))
elseif backend == "plotly"
plotly(size=(300*nplots,200*nplots))
end
mychain,mylabel=readdlm(file,',',header=true)
if nplots > length(mylabel)
nplots=length(mylabel)
end
mychain = mychain[:,1:nplots]
mylabel = mylabel[1:nplots]
steps = 1:size(mychain,1)
h1=plot(mychain, layout=(nplots,1),title= reshape(mylabel,1,length(mylabel)),
label="",title_location=:left,titlefont=12,xlabel="iterations",ylabel = "residual variance",ytickfont=font(8))
# add horizontal line
hline!(h1,cumsum(mychain,dims=1)./steps,layout=(nplots,1),label="",color=:red,linewidth=0.1)
#density plot
h2=density(mychain,layout= (nplots,1),label="",orientation = :horizontal,xlim =[0,1.5],ylim = [-10,25])
plot(h1, h2, link = :y, layout = grid(1,2,widths = [0.7,0.3]))
end
|
function minimize(objective, x0, scheme::QuasiNewton, B0=nothing, options=OptOptions())
minimize(objective, x0, (scheme, BackTracking()), B0, options)
end
function minimize(objective::T1, x0, approach::Tuple{<:Any, <:LineSearch}, B0=nothing,
options::OptOptions=OptOptions(),
linesearch::T2 = BackTracking()
) where {T1, T2}
x, fx, ∇fx, z, fz, ∇fz, B = prepare_variables(objective, approach, x0, copy(x0), B0)
# first iteration
z, fz, ∇fz, B, is_converged = iterate(x, fx, ∇fx, z, fz, ∇fz, B, approach, objective, options)
iter = 0
while iter <= options.maxiter && !is_converged
iter += 1
# take a step and update approximation
z, fz, ∇fz, B, is_converged = iterate(x, fx, ∇fx, z, fz, ∇fz, B, approach, objective, options, false)
end
return z, fz, ∇fz, iter
end
function iterate(x, fx, ∇fx, z, fz, ∇fz, B, approach, objective, options, is_first=nothing)
# split up the approach into the hessian approximation scheme and line search
scheme, linesearch = approach
# Move nexts into currs
fx = fz
x = copy(z)
∇fx = copy(∇fz)
# Update current gradient and calculate the search direction
d = find_direction(B, ∇fx, scheme) # solve Bd = -∇f
# # Perform line search along d
α, f_α, ls_success = linesearch(objective, d, x, fx, ∇fx, 1.0)
# # Calculate final step vector and update the state
s = @. α * d
z = @. x + s
# Update approximation
fz, ∇fz, B = update_obj(objective, d, s, ∇fx, z, ∇fz, B, scheme, is_first)
# Check for gradient convergence
is_converged = converged(z, ∇fz, options.g_tol)
return z, fz, ∇fz, B, is_converged
end
|
# parameters
mass_bin_name = ARGS[1]
tslice = "t1"
path_wavelist = "src"
path_to_working_folder = "data"
list_of_files = ARGS[2:end]
println("Starting with ARGS = ", ARGS)
######################################################
using DelimitedFiles
using LinearAlgebra
push!(LOAD_PATH,"src")
using SDMHelper
using FittingPWALikelihood
using amplitudes_compass
using PWAHelper
BmatMC = read_cmatrix(
joinpath(path_to_working_folder,"integrmat_$(mass_bin_name)_$(tslice)_mc.txt"));
# read wavelist throw waves below threshol
wavelist = get_wavelist(joinpath(path_wavelist,"wavelist_formated.txt");
path_to_thresholds=joinpath(path_wavelist,"thresholds_formated.txt"),
M3pi=Meta.parse(mass_bin_name[1:4])/1000)
const noϵ = [1] # flat wave
const posϵ = [i for (i,ϵ) in enumerate(wavelist[:,6]) if ϵ=="+"]
const negϵ = [i for (i,ϵ) in enumerate(wavelist[:,6]) if ϵ=="-"]
# Model description
const ModelBlocks = [noϵ, posϵ, negϵ, negϵ]
# load precalculated data array
const PsiRD = read_precalc_basis(
joinpath(path_to_working_folder,"functions_$(mass_bin_name)_$(tslice)_rd.bin"));
# get functions to calculate LLH, derivative and hessian
LLH, GRAD, LLH_and_GRAD!, HES = createLLHandGRAD(PsiRD, BmatMC, ModelBlocks);
println("---> Start calculating LLHs")
llhs = [LLH(vcat(readdlm(path_and_filename)...)) for path_and_filename in list_of_files]
sorted_list = sort(collect(zip(list_of_files, llhs)), by=x->x[2])
writedlm(joinpath(path_to_working_folder,"llh_attmpts_$(mass_bin_name)_$(tslice).txt"), sorted_list)
###########################################################################
println("---> Trying to improve minimum")
# fit the best minimum again
## normalize B
Bscale = [BmatMC[i,i] for i in 1:size(BmatMC,1)];
for i=1:size(BmatMC,1), j=1:size(BmatMC,2)
BmatMC[i,j] *= 1/sqrt(Bscale[i]*Bscale[j])
end
## normalize Psi
for i in 1:size(PsiRD,2)
PsiRD[:,i] .*= 1.0/sqrt(Bscale[i])
end
## get functions to calculate LLH, derivative and hessian
LLH, GRAD, LLH_and_GRAD!, HES = createLLHandGRAD(PsiRD, BmatMC, ModelBlocks);
## load the best parameters
best_parameters = vcat(readdlm(sorted_list[1][1])...)
parscale = abs.(extnd(sqrt.(Bscale), get_parameter_map(ModelBlocks, size(BmatMC,1))))
best_parameters_scalled = best_parameters .* parscale
## fit
@time minpars = minimize(LLH, LLH_and_GRAD!;
algorithm = :LD_LBFGS, verbose=1, starting_pars=best_parameters_scalled,
llhtolerance = 1e-6)
max_reldiff_of_parameters = max(abs.(1 .- minpars ./ best_parameters_scalled)...)
@show max_reldiff_of_parameters
(max_reldiff_of_parameters > 0.1) && warn("Too big improvement in the fit while fine tuning!")
@time minpars2 = minimize(LLH, LLH_and_GRAD!;
algorithm = :LD_SLSQP, verbose=1, starting_pars=minpars,
llhtolerance = 1e-6)
max_reldiff_of_parameters2 = max(abs.(1 .- minpars2 ./ minpars)...)
@show max_reldiff_of_parameters2
(max_reldiff_of_parameters2 > 0.1) && warn("Too big improvement in the fit while fine tuning!")
###########################################################################
println("---> Calculating Hessian")
# get derivative
hes = HES(minpars2)
singular = (det(hes) ≈ 0.0); singular && warn("Hessian matrix is singular!")
invhes = !(singular) ? inv(hes) : fill(0.0,size(hes)...)
invhes_scaled_back = invhes ./ transpose(parscale) ./ parscale
writedlm(joinpath(path_to_working_folder,"invhes_$(splitdir(sorted_list[1][1])[end])"), invhes_scaled_back)
println("Done")
|
using LightXML
let docstr = """<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>"""
doc = parse_string(docstr)
xroot = root(doc)
for elem in xroot["Student"]
println(attribute(elem, "Name"))
end
end
|
"""
Type representing any object drawable on image
"""
abstract type Drawable end
"""
p = Point(x,y)
p = Point(c)
A `Drawable` point on the image
"""
struct Point <: Drawable
x::Int
y::Int
end
abstract type Line <: Drawable end
abstract type Circle <: Drawable end
"""
line = LineTwoPoints(p1, p2)
A `Drawable` infinite length line passing through the two points
`p1` and `p2`.
"""
struct LineTwoPoints <: Line
p1::Point
p2::Point
end
"""
line = LineNormal(ρ, θ)
A `Drawable` infinte length line having perpendicular length `ρ` from
origin and angle `θ` between the perpendicular and x-axis
"""
struct LineNormal{T<:Real, U<:Real} <: Line
ρ::T
θ::U
end
"""
circle = CircleThreePoints(p1, p2, p3)
A `Drawable` circle passing through points `p1`, `p2` and `p3`
"""
struct CircleThreePoints <: Circle
p1::Point
p2::Point
p3::Point
end
"""
circle = CirclePointRadius(center, ρ)
A `Drawable` circle having center `center` and radius `ρ`
"""
struct CirclePointRadius{T<:Real} <: Circle
center::Point
ρ::T
end
"""
ls = LineSegment(p1, p2)
A `Drawable` finite length line between `p1` and `p2`
"""
struct LineSegment <: Drawable
p1::Point
p2::Point
end
"""
path = Path([point])
A `Drawable` sequence of line segments connecting consecutive pairs
of points in `[point]`.
!!! note
This will create a non-closed path. For a closed path, see `Polygon`
"""
struct Path <: Drawable
vertices::Vector{Point}
end
"""
ellipse = Ellipse(center, ρx, ρy)
A `Drawable` ellipse with center `center` and parameters `ρx` and `ρy`
"""
struct Ellipse{T<:Real, U<:Real} <: Drawable
center::Point
ρx::T
ρy::U
end
"""
polygon = Polygon([vertex])
A `Drawable` polygon i.e. a closed path created by joining the
consecutive points in `[vertex]` along with the first and last point.
!!! note
This will create a closed path. For a non-closed path, see `Path`
"""
struct Polygon <: Drawable
vertices::Vector{Point}
end
"""
rp = RegularPolygon(center, side_count, side_length, θ)
A `Drawable` regular polygon.
#Arguments
* `center::Point` : the center of the polygon
* `side_count::Int` : number of sides of the polygon
* `side_length::Real` : length of each side
* `θ::Real` : orientation of the polygon w.r.t x-axis (in radians)
"""
struct RegularPolygon{T<:Real, U<:Real} <: Drawable
center::Point
side_count::Int
side_length::T
θ::U
end
"""
cross = Cross(c, range::UnitRange{Int})
A `Drawable` cross passing through the point `c` with arms ranging across `range`.
"""
struct Cross <: Drawable
c::Point
range::UnitRange{Int}
end
"""
img = draw!(img, drawable, color)
img = draw!(img, drawable)
Draws `drawable` on `img` using color `color` which
defaults to `oneunit(eltype(img))`
"""
draw!(img::AbstractArray{T,2}, object::Drawable) where {T<:Colorant} = draw!(img, object, oneunit(T))
"""
img = draw!(img, [drawable], [color])
img = draw!(img, [drawable] ,color)
img = draw!(img, [drawable])
Draws all objects in `[drawable]` in the given order on `img` using
corresponding colors from `[color]` which defaults to `oneunit(eltype(img))`
If only a single color `color` is specified then all objects will be
colored with that color.
"""
function draw!(img::AbstractArray{T,2}, objects::AbstractVector{U}, colors::AbstractVector{V}) where {T<:Colorant, U<:Drawable, V<:Colorant}
colors = copy(colors)
while length(colors) < length(objects)
push!(colors, oneunit(T))
end
foreach((object, color) -> draw!(img, object, color), objects, colors)
img
end
draw!(img::AbstractArray{T,2}, objects::AbstractVector{U}, color::T = oneunit(T)) where {T<:Colorant, U<:Drawable} =
draw!(img, objects, [color for i in 1:length(objects)])
"""
img_new = draw(img, drawable, color)
img_new = draw(img, [drawable], [color])
Draws the `drawable` object on a copy of image `img` using color
`color`. Can also draw multiple `Drawable` objects when passed
as a `AbstractVector{Drawable}` with corresponding colors in `[color]`
"""
draw(img::AbstractArray{T,2}, args...) where {T<:Colorant} = draw!(copy(img), args...)
Point(τ::Tuple{Int, Int}) = Point(τ...)
Point(p::CartesianIndex) = Point(p[2], p[1])
function draw!(img::AbstractArray{T,2}, point::Point, color::T) where T<:Colorant
drawifinbounds!(img, point, color)
end
"""
img_new = drawifinbounds!(img, y, x, color)
img_new = drawifinbounds!(img, Point, color)
img_new = drawifinbounds!(img, CartesianIndex, color)
Draws a single point after checkbounds() for coordinate in the image.
Color Defaults to oneunit(T)
"""
drawifinbounds!(img::AbstractArray{T,2}, p::Point, color::T = oneunit(T)) where {T<:Colorant} = drawifinbounds!(img, p.y, p.x, color)
drawifinbounds!(img::AbstractArray{T,2}, p::CartesianIndex{2}, color::T = oneunit(T)) where {T<:Colorant} = drawifinbounds!(img, Point(p), color)
function drawifinbounds!(img::AbstractArray{T,2}, y::Int, x::Int, color::T) where {T<:Colorant}
if checkbounds(Bool, img, y, x) img[y, x] = color end
img
end
|
using MultivariateStats
using PLSRegressor
const defdir = PLSRegressor.dir("datasets")
function gethousingdata(dir, filename)
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data"
mkpath(dir)
path = download(url, "$(defdir)/$filename")
end
function loaddata(test=0.1)
filename = "housing.data"
file = "$(defdir)/$filename"
isfile("$(defdir)/$filename") || gethousingdata(defdir, filename)
data = readdlm(file)
nfeatures = size(data)[2] - 1
target_idx = size(data)[2]
x = data[:, 1:nfeatures]
y = data[:, target_idx:target_idx]
if test == 0
xtrn = xtst = x
ytrn = ytst = y
else
r = randperm(size(x,1)) # trn/tst split
n = round(Int, (1-test) * size(x,1))
xtrn=x[r[1:n], :]
ytrn=y[r[1:n], :]
xtst=x[r[n+1:end], :]
ytst=y[r[n+1:end], :]
end
(xtrn, [ytrn...], xtst, [ytst...])
end
(xtrn, ytrn, xtst, ytst) = loaddata()
model = PLSRegressor.fit(xtrn, ytrn, nfactors = 3)
pred = PLSRegressor.predict(model, xtst)
println("[PLS] mae error :", mean(abs.(ytst .- pred)))
# linear least squares from MultiVariateStats
sol = llsq(xtrn, ytrn)
a, b = sol[1:end-1], sol[end]
yp = xtst * a + b
println("[LLS] mae error :",mean(abs.(ytst .- yp)))
### if you want to save or load model use this
#PLSRegressor.save(model,filename="/tmp/pls_model.jld",modelname="pls_model")
#model = PLSRegressor.load(filename="/tmp/pls_model.jld",modelname="pls_model")
|
# # A model with homeowners and renters
using Revise
using Test, Aiyagari
using QuantEcon, Parameters, Interpolations
using Plots
u(c; γ) = c^(1-γ) / (1-γ)
function u(c,h; ξ=0.8159, ρ=map(s -> (s-1)/s, 0.13), γ=2.0)
C = (ξ * h^ρ + (1-ξ) * c^ρ)^(1/ρ)
u(C, γ=γ)
end
# Exogenous states (incomes)
z_grid = [0.5; 1.0; 1.5]
z_prob = [0.7 0.15 0.15;
0.2 0.6 0.2;
0.15 0.15 0.7]
z_MC = MarkovChain(z_prob, z_grid, :z)
# Moving shocks
move_grid = Symbol[:just_moved, :normal, :move]
move_grid = [1, 2, 3]
move_prob = [0.7 0.3 0.0;
0.0 0.99 0.01;
1.0 0.0 0.0]
#move_prob = ones(3,3)/3
move_MC = MarkovChain(move_prob, move_grid, :move)
# itp_scheme = BSpline(Cubic(Line(OnGrid())))
# a_grid = LinRange(0.0, 0.7, 50)
#
# val = u.(a_grid .+ permutedims([exo.z for exo in exo1.grid]), γ=2.0)
#
# 𝔼V = extrapolated_𝔼V(a_grid, itp_scheme, val, exo1, 3, Aiyagari.Conditional(:move))
#
# 𝔼V([1.0, 2.0, 0.7])
mutable struct HousingAS{T1,T2,T3,T4} <: AggregateState
r::T1
p::T2 # house price
ρ::T3 # rent
dist::T4 # the distribution over idiosynchratic states
end
function HousingAS(r, p, a_grid, exo, param; ρ=p * (param.δ + r))
dist_proto = zeros((length(a_grid), length(exo)))
HousingAS(r, p, ρ, dist_proto)
end
include("housing-simple-nlopt.jl")
include("housing-nlopt.jl")
include("renting-nlopt.jl")
#include("housing-simple-jump.jl")
r = 0.29
exo = ExogenousStateSpace([z_MC])
exo = ExogenousStateSpace([z_MC, move_MC])
# ## Forever home owners
r_own = 0.29
a_grid_own = LinRange(0.0, 0.7, 50)
h_grid_own = LinRange(eps(), 2, 10)
endo = EndogenousStateSpace((w=a_grid_own, h=h_grid_own))
param_own = (β = 0.7, θ = 0.9, δ = 0.1, h_thres = eps())
agg_state_own = HousingAS(r_own, 2.2, a_grid_own, exo, param_own)
out_C = solve_bellman(a_grid_own, exo, agg_state_own, param_own, Owner(Aiyagari.Conditional(:move)), tol=1e-5)
out_UC = solve_bellman(a_grid_own, exo, agg_state_own, param_own, Owner(Aiyagari.Unconditional()), tol=1e-5)
out_U = solve_bellman(endo, exo, agg_state_own, param_own, Owner(Aiyagari.Unconditional()), tol=2e-5)
@testset "conditional vs unconditional" begin
itp_scheme = BSpline(Cubic(Line(OnGrid())))
V_C = extrapolated_𝔼V(a_grid_own, itp_scheme, out_C.val, exo, 1, Aiyagari.Conditional(:move))
V_UC = extrapolated_𝔼V(a_grid_own, itp_scheme, out_C.val, exo, 1, Aiyagari.Unconditional())
V_UC_old = extrapolated_𝔼V(a_grid_own, itp_scheme, out_U.val, exo_old, 1, Aiyagari.Unconditional())
V_C_p(a) = ForwardDiff.derivative(V_C, a)
V_UC_p(a) = ForwardDiff.derivative(V_UC, a)
V_UC_old_p(a) = ForwardDiff.derivative(V_UC_old, a)
@test all(V_C.(a_grid_own) .≈ V_UC.(a_grid_own))
@test all(V_C_p.(a_grid_own) .≈ V_UC_p.(a_grid_own))
@show maximum(abs, V_UC.(a_grid_own) .- V_UC_old.(a_grid_own))
@show maximum(abs, V_UC_p.(a_grid_own) .- V_UC_old_p.(a_grid_own))
using Distributions
a_rand = rand(Uniform(0, 0.7), 500)
a_low = rand(Uniform(-5, 0), 500)
a_high = rand(Uniform(0.7, 5), 500)
@test all(V_C.(a_rand) .≈ V_UC.(a_rand))
@test all(V_C.(a_low) .≈ V_UC.(a_low))
@test all(V_C.(a_high) .≈ V_UC.(a_high))
end
using DelimitedFiles
@testset "regression test simple housing" begin
#writedlm("test/matrices/housing_simple_nlopt_value.txt", val)
value_test = readdlm("test/matrices/housing_simple_nlopt_value.txt")
for i in 1:length(z_grid)
Δ = maximum(abs, value_test[:,i] .- Aiyagari.get_cond_𝔼V(val, exo, i, :z => i))
@test abs(Δ) < 1e-6
end
end
#@show all(value_test .≈ val) || maximum(abs, value_test .- val)
hh = reshape(out_U.policies_full.h, (size(endo)..., length(exo)))
plot(a_grid_own, hh, title="house size", xlab="wealth", legend=:false)
plot(h_grid_own, reshape(permutedims(hh, (2,1,3)), (10,150)), title="house size", xlab="wealth", legend=:false, alpha=0.3)
ylims!(0,2)
#
#plot(a_grid_own, policies_full.m, title="mortgage", xlab="wealth")
dist = stationary_distribution(z_MC, a_grid_own, policies_full.w_next)
#writedlm("test/matrices/housing_simple_nlopt_dist.txt", dist)
dist_test = readdlm("test/matrices/housing_simple_nlopt_dist.txt")
all(dist_test .≈ dist) || maximum(abs, dist_test .- dist)
plot(a_grid_own, dist, xlab="wealth" )
# ## Forever renters
r_rent = 0.15
a_grid_rent = LinRange(-0.05, 1.5, 50)
param_rent = (β = 0.7, θ = 0.9, δ = 0.1, h_thres = Inf)
agg_state_rent = HousingAS(r_rent, 2.2, a_grid_rent, exo, param_rent, ρ=2.2 * (param_rent.δ + r))
@unpack val, policy, policies_full = solve_bellman(a_grid_rent, exo, agg_state_rent, param_rent, Renter(Aiyagari.Unconditional()), maxiter=100)
plot(a_grid_rent, Aiyagari.get_cond_𝔼V(val, exo, 1, :z => 1))
plot!(a_grid_rent, Aiyagari.get_cond_𝔼V(val, exo, 2, :z => 2))
plot!(a_grid_rent, Aiyagari.get_cond_𝔼V(val, exo, 3, :z => 3))
plot(a_grid_rent, val)
plot(a_grid_rent, policies_full.w_next, title="house size", xlab="wealth", legend=:topleft)
# ### Stationary distribution
dist = stationary_distribution(exo.mc, a_grid_rent, policies_full.w_next)
plot(a_grid_rent, dist, xlab="wealth" )
# ## Own big, rent small
r = 0.10
a_grid = LinRange(0.0, 1.0, 40)
param_both = (β = 0.7, θ = 0.9, δ = 0.1, h_thres = 0.75)
param = [param_own, param_rent]
agg_state_both = HousingAS(r, 2.2, a_grid, exo, param_both, ρ= 1.07 * 2.2 * (param_both.δ + r))
@unpack val, policy, policies_full, owner = solve_bellman(a_grid, exo, agg_state_both, param, OwnOrRent(), maxiter=70)
plot(a_grid, owner, title="Who owns?")
# using StructArrays
# move = StructArray(exo.grid).move
# move_long = repeat(permutedims(move), 40, 1)
w_next_all = policies_full[1].w_next .* owner .+ policies_full[2].w_next .* .!owner
h_all = policies_full[1].h .* owner .+ policies_full[2].h .* .!owner
c_all = policies_full[1].c .* owner .+ policies_full[2].c .* .!owner
scatter(a_grid, h_all .* (owner .== 1), color=:blue, legend=:false, title="House size", alpha=0.3, markerstrokewidth=0, xlab="wealth")
scatter!(a_grid, h_all .* (owner .== 0), color=:red, alpha=0.3, markerstrokewidth=0)
ylims!(0.3, 2.25)
title!("no moving costs (blue == own, red == rent)")
savefig("no-moving-costs.png")
hline!([param_both.h_thres], color=:gray, label="", linestyle=:dash)
plot(a_grid, w_next_all, legend=false, title="wealth")
#
#
# plot(a_grid, w_next_all, legend=:left, title="cash-at-hand")
# #plot!(a_grid, a_grid)
# #plot!(a_grid[[1;end]], a_grid[[end;end]], legend=false)
#
# using Plots
# using DelimitedFiles
# #writedlm("test/matrices/housing_simple_nlopt_value.txt", val)
# value_test = readdlm("test/matrices/housing_simple_nlopt_value.txt")
#
# @test all(val .== value_test)
#
# using Plots
# plot(val)
#
# scatter(a_grid, policies_full.w_next)
# scatter(a_grid, policies_full[1].h)
# scatter!(a_grid, policies_full[2].h)
# scatter(a_grid, policies_full[1].m .* owner)
# scatter(a_grid, c_all)
#
# all(policies_full.conv)
# ## Stationary distribution
dist = stationary_distribution(exo.mc, a_grid, w_next_all)
plot(a_grid, dist, xlab="wealth" )
# #writedlm("test/matrices/housing_simple_nlopt_dist.txt", dist)
# dist_test = readdlm("test/matrices/housing_simple_nlopt_dist.txt")
# @test all(dist .== dist_test)
#
# using StatsBase
# mean(vec(policies_full.m), Weights(vec(dist)))
# mean(vec(policies_full.h), Weights(vec(dist)))
# #926 μs
#
|
function test(args::Dict)
is_sorted = args["--sorted"]
is_sorted |= args["-s"]
test(is_sorted)
end
function test(is_sorted=false)
scratch_file = "$(dirname(@__FILE__))"
scratch_file *= "/../../../"
scratch_file *= "tmp/scratch.jl"
open(scratch_file, "w") do f
write(f, "tests_are_sorted = $is_sorted \n")
end
target_name = bump()
Pkg.test(target_name)
open(scratch_file, "w") do f
write(f, "")
end
end
|
# generally, Documenter.jl assumes markdown files ends with `.md`
const markdown_exts = [".md",]
const markdown_footer = raw"""
---
*This page was generated using [DemoCards.jl](https://github.com/johnnychen94/DemoCards.jl).*
"""
"""
struct MarkdownDemoCard <: AbstractDemoCard
MarkdownDemoCard(path::String)
Constructs a markdown-format demo card from existing markdown file `path`.
# Fields
Besides `path`, this struct has some other fields:
* `path`: path to the source markdown file
* `cover`: path to the cover image
* `id`: cross-reference id
* `title`: one-line description of the demo card
* `author`: author(s) of this demo.
* `date`: the update date of this demo.
* `description`: multi-line description of the demo card
* `hidden`: whether this card is shown in the generated index page
# Configuration
You can pass additional information by adding a YAML front matter to the markdown file.
Supported items are:
* `cover`: an URL or a relative path to the cover image. If not specified, it will use the first available image link, or all-white image if there's no image links.
* `description`: a multi-line description to this file, will be displayed when the demo card is hovered. By default it uses `title`.
* `id`: specify the `id` tag for cross-references. By default it's infered from the filename, e.g., `simple_demo` from `simple demo.md`.
* `title`: one-line description to this file, will be displayed under the cover image. By default, it's the name of the file (without extension).
* `author`: author name. If there are multiple authors, split them with semicolon `;`.
* `date`: any string contents that can be passed to `Dates.DateTime`. For example, `2020-09-13`.
* `hidden`: whether this card is shown in the layout of index page. The default value is `false`.
An example of the front matter:
```text
---
title: passing extra information
cover: cover.png
id: non_ambiguious_id
author: Jane Doe; John Roe
date: 2020-01-31
description: this demo shows how you can pass extra demo information to DemoCards package. All these are optional.
hidden: false
---
```
See also: [`JuliaDemoCard`](@ref DemoCards.JuliaDemoCard), [`DemoSection`](@ref DemoCards.DemoSection), [`DemoPage`](@ref DemoCards.DemoPage)
"""
mutable struct MarkdownDemoCard <: AbstractDemoCard
path::String
cover::Union{String, Nothing}
id::String
title::String
description::String
author::String
date::DateTime
hidden::Bool
end
function MarkdownDemoCard(path::String)::MarkdownDemoCard
# first consturct an incomplete democard, and then load the config
card = MarkdownDemoCard(path, "", "", "", "", "", DateTime(0), false)
config = parse(card)
card.cover = load_config(card, "cover"; config=config)
card.title = load_config(card, "title"; config=config)
card.date = load_config(card, "date"; config=config)
card.author = load_config(card, "author"; config=config)
# Unlike JuliaDemoCard, Markdown card doesn't accept `julia` compat field. This is because we
# generally don't know the markdown processing backend. It might be Documenter, but who knows.
# More generally, any badges can just be manually added by demo writter, if they want.
# `date` and `author` fields are added just for convinience.
# default id requires a title
card.id = load_config(card, "id"; config=config)
# default description requires a title
card.description = load_config(card, "description"; config=config)
card.hidden = load_config(card, "hidden"; config=config)
return card
end
"""
save_democards(card_dir::String, card::MarkdownDemoCard)
process the original markdown file and save it.
The processing pipeline is:
1. strip the front matter
2. insert a level-1 title and id
"""
function save_democards(card_dir::String,
card::MarkdownDemoCard;
credit,
kwargs...)
isdir(card_dir) || mkpath(card_dir)
markdown_path = joinpath(card_dir, basename(card))
_, _, body = split_frontmatter(read(card.path, String))
config = parse(Val(:Markdown), body)
need_header = !haskey(config, "title")
# @ref syntax: https://juliadocs.github.io/Documenter.jl/stable/man/syntax/#@ref-link-1
header = need_header ? "# [$(card.title)](@id $(card.id))\n" : "\n"
footer = credit ? markdown_footer : "\n"
write(markdown_path, header, make_badges(card)*"\n\n", body, footer)
end
|
"""
stroboscopicmap(ds::ContinuousDynamicalSystem, T; kwargs...) → smap
Return a map (integrator) that produces iterations over a period `T` of the `ds`,
known as a stroboscopic map. See [Integrator API](@ref) for handling integrators.
See also [`poincaremap`](@ref).
## Keyword Arguments
* `u0`: initial state
* `diffeq` is a `NamedTuple` (or `Dict`) of keyword arguments propagated into
`init` of DifferentialEquations.jl.
## Example
```julia
f = 0.27; ω = 0.1
ds = Systems.duffing(zeros(2); ω, f, d = 0.15, β = -1)
smap = stroboscopicmap(ds, 2π/ω; diffeq = (;reltol = 1e-8))
reinit!(smap, [1.0, 1.0])
u = step!(smap)
u = step!(smap, 4) # step 4 iterations forward
```
"""
function stroboscopicmap(ds::CDS, T; u0 = get_state(ds), diffeq = NamedTuple())
integ = integrator(ds, u0; diffeq)
return StroboscopicMap{typeof(integ), dimension(ds), typeof(T)}(integ, T)
end
struct StroboscopicMap{I, D, F} <: GeneralizedDynamicalSystem
integ::I
T::F
end
isdiscretetime(::StroboscopicMap) = true
DelayEmbeddings.dimension(::StroboscopicMap{I, D}) where {I, D} = D
integrator(p::StroboscopicMap) = p
function step!(smap::StroboscopicMap)
step!(smap.integ, smap.T, true)
return smap.integ.u
end
function step!(smap::StroboscopicMap, n::Int)
for k in 1:n; step!(smap.integ, smap.T, true); end
return smap.integ.u
end
function reinit!(smap::StroboscopicMap, u0)
reinit!(smap.integ, u0)
return
end
function get_state(smap::StroboscopicMap)
return smap.integ.u
end
function Base.show(io::IO, smap::StroboscopicMap)
println(io, "Iterator of the stroboscopic map")
println(io, rpad(" rule f: ", 14), DynamicalSystemsBase.eomstring(smap.integ.f.f))
println(io, rpad(" Period: ", 14), smap.T)
end
current_time(smap::StroboscopicMap) = current_time(smap.integ)
function (smap::StroboscopicMap)(t)
if t == current_time(smap)
return get_state(smap)
else
error("Can't extrapolate discrete systems!")
end
end
integrator(pinteg::StroboscopicMap, args...; kwargs...) = pinteg
|
using JFVM
using Base.Test
# write your own tests here
JFVM_test()
@test 1==1
|
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.
struct FlowcontrolApiserverV1alpha1Api <: SwaggerApi
client::Swagger.Client
end
function _swaggerinternal_createFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "POST", IoK8sApiFlowcontrolV1alpha1FlowSchema, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas", ["BearerToken"], body)
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
create a FlowSchema
Param: body::IoK8sApiFlowcontrolV1alpha1FlowSchema (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiFlowcontrolV1alpha1FlowSchema
"""
function createFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_createFlowcontrolApiserverV1alpha1FlowSchema(_api, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function createFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_createFlowcontrolApiserverV1alpha1FlowSchema(_api, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_createFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "POST", IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations", ["BearerToken"], body)
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
create a PriorityLevelConfiguration
Param: body::IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration
"""
function createFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_createFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function createFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_createFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_deleteFlowcontrolApiserverV1alpha1CollectionFlowSchema(_api::FlowcontrolApiserverV1alpha1Api; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas", ["BearerToken"], body)
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks) # type Bool
Swagger.set_param(_ctx.query, "continue", __continue__) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector) # type String
Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds) # type Int32
Swagger.set_param(_ctx.query, "labelSelector", labelSelector) # type String
Swagger.set_param(_ctx.query, "limit", limit) # type Int32
Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents) # type Bool
Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy) # type String
Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion) # type String
Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds) # type Int32
Swagger.set_param(_ctx.query, "watch", watch) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
delete collection of FlowSchema
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: __continue__::String
Param: dryRun::String
Param: fieldSelector::String
Param: gracePeriodSeconds::Int32
Param: labelSelector::String
Param: limit::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteFlowcontrolApiserverV1alpha1CollectionFlowSchema(_api::FlowcontrolApiserverV1alpha1Api; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_deleteFlowcontrolApiserverV1alpha1CollectionFlowSchema(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function deleteFlowcontrolApiserverV1alpha1CollectionFlowSchema(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_deleteFlowcontrolApiserverV1alpha1CollectionFlowSchema(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_deleteFlowcontrolApiserverV1alpha1CollectionPriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations", ["BearerToken"], body)
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks) # type Bool
Swagger.set_param(_ctx.query, "continue", __continue__) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector) # type String
Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds) # type Int32
Swagger.set_param(_ctx.query, "labelSelector", labelSelector) # type String
Swagger.set_param(_ctx.query, "limit", limit) # type Int32
Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents) # type Bool
Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy) # type String
Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion) # type String
Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds) # type Int32
Swagger.set_param(_ctx.query, "watch", watch) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
delete collection of PriorityLevelConfiguration
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: __continue__::String
Param: dryRun::String
Param: fieldSelector::String
Param: gracePeriodSeconds::Int32
Param: labelSelector::String
Param: limit::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteFlowcontrolApiserverV1alpha1CollectionPriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_deleteFlowcontrolApiserverV1alpha1CollectionPriorityLevelConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function deleteFlowcontrolApiserverV1alpha1CollectionPriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_deleteFlowcontrolApiserverV1alpha1CollectionPriorityLevelConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_deleteFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas/{name}", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds) # type Int32
Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents) # type Bool
Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
delete a FlowSchema
Param: name::String (required)
Param: pretty::String
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: dryRun::String
Param: gracePeriodSeconds::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_deleteFlowcontrolApiserverV1alpha1FlowSchema(_api, name; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function deleteFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_deleteFlowcontrolApiserverV1alpha1FlowSchema(_api, name; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_deleteFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations/{name}", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds) # type Int32
Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents) # type Bool
Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
delete a PriorityLevelConfiguration
Param: name::String (required)
Param: pretty::String
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: dryRun::String
Param: gracePeriodSeconds::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_deleteFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function deleteFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_deleteFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_getFlowcontrolApiserverV1alpha1APIResources(_api::FlowcontrolApiserverV1alpha1Api; _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1APIResourceList, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/", ["BearerToken"])
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"] : [_mediaType])
return _ctx
end
"""
get available resources
Return: IoK8sApimachineryPkgApisMetaV1APIResourceList
"""
function getFlowcontrolApiserverV1alpha1APIResources(_api::FlowcontrolApiserverV1alpha1Api; _mediaType=nothing)
_ctx = _swaggerinternal_getFlowcontrolApiserverV1alpha1APIResources(_api; _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function getFlowcontrolApiserverV1alpha1APIResources(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel; _mediaType=nothing)
_ctx = _swaggerinternal_getFlowcontrolApiserverV1alpha1APIResources(_api; _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_listFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiFlowcontrolV1alpha1FlowSchemaList, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas", ["BearerToken"])
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks) # type Bool
Swagger.set_param(_ctx.query, "continue", __continue__) # type String
Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector) # type String
Swagger.set_param(_ctx.query, "labelSelector", labelSelector) # type String
Swagger.set_param(_ctx.query, "limit", limit) # type Int32
Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion) # type String
Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds) # type Int32
Swagger.set_param(_ctx.query, "watch", watch) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
list or watch objects of kind FlowSchema
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApiFlowcontrolV1alpha1FlowSchemaList
"""
function listFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_listFlowcontrolApiserverV1alpha1FlowSchema(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function listFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_listFlowcontrolApiserverV1alpha1FlowSchema(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_listFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationList, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations", ["BearerToken"])
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks) # type Bool
Swagger.set_param(_ctx.query, "continue", __continue__) # type String
Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector) # type String
Swagger.set_param(_ctx.query, "labelSelector", labelSelector) # type String
Swagger.set_param(_ctx.query, "limit", limit) # type Int32
Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion) # type String
Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds) # type Int32
Swagger.set_param(_ctx.query, "watch", watch) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
list or watch objects of kind PriorityLevelConfiguration
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApiFlowcontrolV1alpha1PriorityLevelConfigurationList
"""
function listFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_listFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function listFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_listFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_patchFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "PATCH", IoK8sApiFlowcontrolV1alpha1FlowSchema, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas/{name}", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_param(_ctx.query, "force", force) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json-patch+json", "application/merge-patch+json", "application/strategic-merge-patch+json", "application/apply-patch+yaml"] : [_mediaType])
return _ctx
end
"""
partially update the specified FlowSchema
Param: name::String (required)
Param: body::IoK8sApimachineryPkgApisMetaV1Patch (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Param: force::Bool
Return: IoK8sApiFlowcontrolV1alpha1FlowSchema
"""
function patchFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_patchFlowcontrolApiserverV1alpha1FlowSchema(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function patchFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_patchFlowcontrolApiserverV1alpha1FlowSchema(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_patchFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "PATCH", IoK8sApiFlowcontrolV1alpha1FlowSchema, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas/{name}/status", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_param(_ctx.query, "force", force) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json-patch+json", "application/merge-patch+json", "application/strategic-merge-patch+json", "application/apply-patch+yaml"] : [_mediaType])
return _ctx
end
"""
partially update status of the specified FlowSchema
Param: name::String (required)
Param: body::IoK8sApimachineryPkgApisMetaV1Patch (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Param: force::Bool
Return: IoK8sApiFlowcontrolV1alpha1FlowSchema
"""
function patchFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_patchFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function patchFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_patchFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_patchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "PATCH", IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations/{name}", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_param(_ctx.query, "force", force) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json-patch+json", "application/merge-patch+json", "application/strategic-merge-patch+json", "application/apply-patch+yaml"] : [_mediaType])
return _ctx
end
"""
partially update the specified PriorityLevelConfiguration
Param: name::String (required)
Param: body::IoK8sApimachineryPkgApisMetaV1Patch (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Param: force::Bool
Return: IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration
"""
function patchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_patchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function patchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_patchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_patchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "PATCH", IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations/{name}/status", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_param(_ctx.query, "force", force) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json-patch+json", "application/merge-patch+json", "application/strategic-merge-patch+json", "application/apply-patch+yaml"] : [_mediaType])
return _ctx
end
"""
partially update status of the specified PriorityLevelConfiguration
Param: name::String (required)
Param: body::IoK8sApimachineryPkgApisMetaV1Patch (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Param: force::Bool
Return: IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration
"""
function patchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_patchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function patchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_patchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_readFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiFlowcontrolV1alpha1FlowSchema, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas/{name}", ["BearerToken"])
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "exact", exact) # type Bool
Swagger.set_param(_ctx.query, "export", __export__) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
read the specified FlowSchema
Param: name::String (required)
Param: pretty::String
Param: exact::Bool
Param: __export__::Bool
Return: IoK8sApiFlowcontrolV1alpha1FlowSchema
"""
function readFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_readFlowcontrolApiserverV1alpha1FlowSchema(_api, name; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function readFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_readFlowcontrolApiserverV1alpha1FlowSchema(_api, name; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_readFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiFlowcontrolV1alpha1FlowSchema, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas/{name}/status", ["BearerToken"])
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
read status of the specified FlowSchema
Param: name::String (required)
Param: pretty::String
Return: IoK8sApiFlowcontrolV1alpha1FlowSchema
"""
function readFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_readFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api, name; pretty=pretty, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function readFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String; pretty=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_readFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api, name; pretty=pretty, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_readFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations/{name}", ["BearerToken"])
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "exact", exact) # type Bool
Swagger.set_param(_ctx.query, "export", __export__) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
read the specified PriorityLevelConfiguration
Param: name::String (required)
Param: pretty::String
Param: exact::Bool
Param: __export__::Bool
Return: IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration
"""
function readFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_readFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function readFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_readFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_readFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations/{name}/status", ["BearerToken"])
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
read status of the specified PriorityLevelConfiguration
Param: name::String (required)
Param: pretty::String
Return: IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration
"""
function readFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String; pretty=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_readFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api, name; pretty=pretty, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function readFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String; pretty=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_readFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api, name; pretty=pretty, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_replaceFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "PUT", IoK8sApiFlowcontrolV1alpha1FlowSchema, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas/{name}", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
replace the specified FlowSchema
Param: name::String (required)
Param: body::IoK8sApiFlowcontrolV1alpha1FlowSchema (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiFlowcontrolV1alpha1FlowSchema
"""
function replaceFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_replaceFlowcontrolApiserverV1alpha1FlowSchema(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function replaceFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_replaceFlowcontrolApiserverV1alpha1FlowSchema(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_replaceFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "PUT", IoK8sApiFlowcontrolV1alpha1FlowSchema, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/flowschemas/{name}/status", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
replace status of the specified FlowSchema
Param: name::String (required)
Param: body::IoK8sApiFlowcontrolV1alpha1FlowSchema (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiFlowcontrolV1alpha1FlowSchema
"""
function replaceFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_replaceFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function replaceFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_replaceFlowcontrolApiserverV1alpha1FlowSchemaStatus(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_replaceFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "PUT", IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations/{name}", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
replace the specified PriorityLevelConfiguration
Param: name::String (required)
Param: body::IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration
"""
function replaceFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_replaceFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function replaceFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_replaceFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_replaceFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "PUT", IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/prioritylevelconfigurations/{name}/status", ["BearerToken"], body)
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "dryRun", dryRun) # type String
Swagger.set_param(_ctx.query, "fieldManager", fieldManager) # type String
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
replace status of the specified PriorityLevelConfiguration
Param: name::String (required)
Param: body::IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiFlowcontrolV1alpha1PriorityLevelConfiguration
"""
function replaceFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api::FlowcontrolApiserverV1alpha1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_replaceFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function replaceFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_replaceFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_watchFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/watch/flowschemas/{name}", ["BearerToken"])
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks) # type Bool
Swagger.set_param(_ctx.query, "continue", __continue__) # type String
Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector) # type String
Swagger.set_param(_ctx.query, "labelSelector", labelSelector) # type String
Swagger.set_param(_ctx.query, "limit", limit) # type Int32
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion) # type String
Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds) # type Int32
Swagger.set_param(_ctx.query, "watch", watch) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
watch changes to an object of kind FlowSchema. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter.
Param: name::String (required)
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_watchFlowcontrolApiserverV1alpha1FlowSchema(_api, name; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function watchFlowcontrolApiserverV1alpha1FlowSchema(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_watchFlowcontrolApiserverV1alpha1FlowSchema(_api, name; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_watchFlowcontrolApiserverV1alpha1FlowSchemaList(_api::FlowcontrolApiserverV1alpha1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/watch/flowschemas", ["BearerToken"])
Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks) # type Bool
Swagger.set_param(_ctx.query, "continue", __continue__) # type String
Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector) # type String
Swagger.set_param(_ctx.query, "labelSelector", labelSelector) # type String
Swagger.set_param(_ctx.query, "limit", limit) # type Int32
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion) # type String
Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds) # type Int32
Swagger.set_param(_ctx.query, "watch", watch) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
watch individual changes to a list of FlowSchema. deprecated: use the 'watch' parameter with a list operation instead.
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchFlowcontrolApiserverV1alpha1FlowSchemaList(_api::FlowcontrolApiserverV1alpha1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_watchFlowcontrolApiserverV1alpha1FlowSchemaList(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function watchFlowcontrolApiserverV1alpha1FlowSchemaList(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_watchFlowcontrolApiserverV1alpha1FlowSchemaList(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_watchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/watch/prioritylevelconfigurations/{name}", ["BearerToken"])
Swagger.set_param(_ctx.path, "name", name) # type String
Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks) # type Bool
Swagger.set_param(_ctx.query, "continue", __continue__) # type String
Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector) # type String
Swagger.set_param(_ctx.query, "labelSelector", labelSelector) # type String
Swagger.set_param(_ctx.query, "limit", limit) # type Int32
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion) # type String
Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds) # type Int32
Swagger.set_param(_ctx.query, "watch", watch) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
watch changes to an object of kind PriorityLevelConfiguration. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter.
Param: name::String (required)
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_watchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function watchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_watchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration(_api, name; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
function _swaggerinternal_watchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationList(_api::FlowcontrolApiserverV1alpha1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/flowcontrol.apiserver.k8s.io/v1alpha1/watch/prioritylevelconfigurations", ["BearerToken"])
Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks) # type Bool
Swagger.set_param(_ctx.query, "continue", __continue__) # type String
Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector) # type String
Swagger.set_param(_ctx.query, "labelSelector", labelSelector) # type String
Swagger.set_param(_ctx.query, "limit", limit) # type Int32
Swagger.set_param(_ctx.query, "pretty", pretty) # type String
Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion) # type String
Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds) # type Int32
Swagger.set_param(_ctx.query, "watch", watch) # type Bool
Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
return _ctx
end
"""
watch individual changes to a list of PriorityLevelConfiguration. deprecated: use the 'watch' parameter with a list operation instead.
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationList(_api::FlowcontrolApiserverV1alpha1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_watchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationList(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx)
end
function watchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationList(_api::FlowcontrolApiserverV1alpha1Api, response_stream::Channel; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
_ctx = _swaggerinternal_watchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationList(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
Swagger.exec(_ctx, response_stream)
end
export createFlowcontrolApiserverV1alpha1FlowSchema, createFlowcontrolApiserverV1alpha1PriorityLevelConfiguration, deleteFlowcontrolApiserverV1alpha1CollectionFlowSchema, deleteFlowcontrolApiserverV1alpha1CollectionPriorityLevelConfiguration, deleteFlowcontrolApiserverV1alpha1FlowSchema, deleteFlowcontrolApiserverV1alpha1PriorityLevelConfiguration, getFlowcontrolApiserverV1alpha1APIResources, listFlowcontrolApiserverV1alpha1FlowSchema, listFlowcontrolApiserverV1alpha1PriorityLevelConfiguration, patchFlowcontrolApiserverV1alpha1FlowSchema, patchFlowcontrolApiserverV1alpha1FlowSchemaStatus, patchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration, patchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus, readFlowcontrolApiserverV1alpha1FlowSchema, readFlowcontrolApiserverV1alpha1FlowSchemaStatus, readFlowcontrolApiserverV1alpha1PriorityLevelConfiguration, readFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus, replaceFlowcontrolApiserverV1alpha1FlowSchema, replaceFlowcontrolApiserverV1alpha1FlowSchemaStatus, replaceFlowcontrolApiserverV1alpha1PriorityLevelConfiguration, replaceFlowcontrolApiserverV1alpha1PriorityLevelConfigurationStatus, watchFlowcontrolApiserverV1alpha1FlowSchema, watchFlowcontrolApiserverV1alpha1FlowSchemaList, watchFlowcontrolApiserverV1alpha1PriorityLevelConfiguration, watchFlowcontrolApiserverV1alpha1PriorityLevelConfigurationList
|
using Documenter
using SExpressions
makedocs(
format = Documenter.HTML(analytics="UA-68884109-1"),
sitename = "SExpressions.jl",
authors = "Fengyang Wang",
pages = [
"index.md"
]
)
deploydocs(
repo = "github.com/TotalVerb/SExpressions.jl.git",
target = "build",
deps = nothing,
make = nothing,
)
|
getindex(g::MetaGraph) = g.gprops
function getindex(g::MetaGraph, label)
_, val = g.vprops[label]
val
end
getindex(g::MetaGraph, label_1, label_2) = g.eprops[arrange(g, label_1, label_2)]
"""
haskey(g, :label)
Determine whether a graph `g` contains the vertex `:label`.
"""
haskey(g::MetaGraph, label) = haskey(g.vprops, label)
"""
haskey(g, :v1, :v2)
Determine whether a graph `g` contains an edge from `:v1` to `:v2`. The order of `:v1` and `:v2` only matters if `g` is a digraph.
"""
function haskey(g::MetaGraph, label_1, label_2)
return (
haskey(g, label_1) &&
haskey(g, label_2) &&
haskey(g.eprops, arrange(g, label_1, label_2))
)
end
function setindex!(g::MetaGraph, val, label)
vprops = g.vprops
v = if haskey(vprops, label)
(v, _) = vprops[label]
v
else
add_vertex!(g.graph)
v = nv(g)
g.metaindex[v] = label
v
end
vprops[label] = (v, val)
return nothing
end
function setindex!(g::MetaGraph, val, label_1, label_2)
vprops = g.vprops
u, _ = vprops[label_1]
v, _ = vprops[label_2]
add_edge!(g.graph, u, v)
g.eprops[arrange(g, label_1, label_2, u, v)] = val
return nothing
end
function delete!(g::MetaGraph, label)
if haskey(g, label)
v, _ = g.vprops[label]
_rem_vertex!(g, label, v)
end
return nothing
end
function delete!(g::MetaGraph, label_1, label_2)
vprops = g.vprops
u, _ = vprops[label_1]
v, _ = vprops[label_2]
rem_edge!(g.graph, u, v)
delete!(g.eprops, arrange(g, label_1, label_2, u, v))
return nothing
end
function _copy_props!(oldg::T, newg::T, vmap) where {T<:MetaGraph}
for (newv, oldv) in enumerate(vmap)
oldl = oldg.metaindex[oldv]
_, meta = oldg.vprops[oldl]
newg.metaindex[newv] = oldl
newg.vprops[oldl] = (newv, meta)
end
for newe in edges(newg.graph)
metaindex = newg.metaindex
u, v = Tuple(newe)
label_1 = metaindex[u]
label_2 = metaindex[v]
newg.eprops[arrange(newg, label_1, label_2, u, v)] =
oldg.eprops[arrange(oldg, label_1, label_2)]
end
return nothing
end
# TODO - would be nice to be able to apply a function to properties. Not sure
# how this might work, but if the property is a vector, a generic way to append to
# it would be a good thing.
"""
code_for(meta::MetaGraph, vertex_label)
Find the code associated with a `vertex_label`. This can be useful to pass to methods inherited from `LightGraphs`. Note, however, that vertex codes could be
reassigned after vertex deletion.
"""
function code_for(meta::MetaGraph, vertex_label)
code, _ = meta.vprops[vertex_label]
code
end
"""
label_for(meta::MetaGraph, vertex_code)
Find the label associated with a `vertex_code`. This can be useful to interpret the results of methods inherited from `LightGraphs`. Note, however, that vertex codes could be reassigned after vertex deletion.
"""
function label_for(meta::MetaGraph, vertex_code)
meta.metaindex[vertex_code]
end
|
export map_to
"""
map_to(value::T) where T
Creates a map operator, which emits the given constant value on the output Observable every time the source Observable emits a value.
# Arguments
- `value::T`: the constant value to map each source value to
# Producing
Stream of type `<: Subscribable{T}`
# Examples
```jldoctest
using Rocket
source = from([ 1, 2, 3 ])
subscribe!(source |> map_to('a'), logger())
;
# output
[LogActor] Data: a
[LogActor] Data: a
[LogActor] Data: a
[LogActor] Completed
```
See also: [`map`](@ref), [`AbstractOperator`](@ref), [`RightTypedOperator`](@ref), [`ProxyObservable`](@ref), [`logger`](@ref)
"""
map_to(value::T) where T = map(T, _ -> value)
|
export Unscented
struct Unscented <: AbstractNonLinearApproximation
L :: Int64
α :: Float64
β :: Float64
κ :: Float64
λ :: Float64
Wm :: Vector{Float64}
Wc :: Vector{Float64}
end
function Unscented(dim::Int64; α::Float64=1e-3, β::Float64=2.0, κ::Float64=0.0)
λ = α^2*(dim + κ) - dim
Wm = ones(2*dim + 1)
Wc = ones(2*dim + 1)
Wm ./= (2*(dim+λ))
Wc ./= (2*(dim+λ))
Wm[1] = λ/(dim+λ)
Wc[1] = λ/(dim+λ) + (1 - α^2 + β)
return Unscented(dim, α, β, κ, λ, Wm, Wc)
end
# get-functions for the Unscented structure
getL(approximation::Unscented) = approximation.L
getα(approximation::Unscented) = approximation.α
getβ(approximation::Unscented) = approximation.β
getκ(approximation::Unscented) = approximation.κ
getλ(approximation::Unscented) = approximation.λ
getWm(approximation::Unscented) = approximation.Wm
getWc(approximation::Unscented) = approximation.Wc |
using Documenter
using DataFrameMacros
makedocs(
sitename = "DataFrameMacros.jl",
format = Documenter.HTML(),
)
# 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/jkrumbiegel/DataFrameMacros.jl.git",
push_preview = true,
)
|
deg(A::AbstractArray{Pol{T}, N}) where {T<:Number, N} = maximum(deg.(A))
deg(A::AbstractArray{T, N}) where {T<:Number, N} = 0
lc(P::AbstractArray{Pol{T}, N}) where {T<:Number, N} = coeff(P, deg(P))
lc(P::AbstractArray{T, N}) where {T<:Number, N} = P
coeff(A::AbstractArray{Pol{T}, N}, k::Int) where {T<:Number, N} = coeff.(A, k)
function rev(P::AbstractArray{Pol{T}, N}) where {T<:Number, N}
res = zero(P)
for i in 0:deg(P)
res += Pol([0, 1])^(deg(P)-i)*coeff(P, i)
end
return res
end
subs(P::AbstractArray{Pol{T}, N}, val::S) where {T,S<:Number, N} = subs.(P, val)
Base.:+(A::AbstractArray{Pol{T}, N}, b::Number) where {T<:Number, N} = A .+ b
Base.:+(b::Number, A::AbstractArray{Pol{T}, N}) where {T<:Number, N} = b .+ A
Base.:-(A::AbstractArray{Pol{T}, N}, b::Number) where {T<:Number, N} = A .- b
Base.:-(b::Number, A::AbstractArray{Pol{T}, N}) where {T<:Number, N} = b .- A
for op in (:+, :-, :*)
@eval Base.$op(A::AbstractArray, b::Pol) = [$op(a, b) for a in A]
@eval Base.$op(b::Pol, A::AbstractArray) = [$op(b, a) for a in A]
end
"""
computes the companion pencil Bx-A of the polynomial matrix P
"""
function toPencil(P::AbstractArray{Pol{T}, N}) where {T<:Number, N}
k = deg(P)
m = size(P, 1)
n = size(P, 2)
# patological case of polynomial of degree zero
if iszero(k)
B = zeros(T, m, n)
A = hcat(-coeff(P, 0)) # ensure array is 2-dimensional
return A, B
end
A = zeros(T, (k-1)*n+m, k*n)
B = zeros(T, (k-1)*n+m, k*n)
B[1:m, 1:n] = lc(P)
B[m+1:end, n+1:end] = Matrix(I, (k-1)*n, (k-1)*n)
A[m+1:end, 1:(k-1)*n] = Matrix(I, (k-1)*n, (k-1)*n)
@inbounds for i in 1:k
A[1:m, (i-1)*n+1:i*n] = -coeff(P, k-i)
end
return A, B
end
function toPencil(P::AbstractArray{T, N}) where {T<:Number, N}
m = size(P, 1)
n = size(P, 2)
B = zeros(T, m, n)
A = hcat(-P)
return A, B
end
function polrank(M::AbstractArray{Pol{T}, N}, tol=0.0) where {T<:Number, N}
rnk = 0
imax = deg(M)*min(size(M)...)
for i=1:imax
rnk = max(rnk, rank(subs(M, i), atol=tol))
end
return rnk
end
|
############################################################
## joAbstractDAparallelLinearOperator - extra functions
# elements(jo)
elements(A::joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = A*jo_eye(DDT,A.n)
# hasinverse(jo)
hasinverse(A::joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = !isnull(A.iop)
# issquare(jo)
issquare(A::joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = (A.m == A.n)
# istall(jo)
istall(A::joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = (A.m > A.n)
# iswide(jo)
iswide(A::joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = (A.m < A.n)
# iscomplex(jo)
iscomplex(A::joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = !(DDT<:Real && RDT<:Real)
# islinear(jo)
#function islinear(A::joAbstractDAparallelLinearOperator{DDT,RDT},samples::Integer=3;tol::Float64=0.,verbose::Bool=false) where {DDT,RDT}
#end
# isadjoint(jo)
#function isadjoint(A::joAbstractDAparallelLinearOperator{DDT,RDT},samples::Integer=3;tol::Float64=0.,normfactor::Real=1.,userange::Bool=false,verbose::Bool=false) where {DDT,RDT}
#end
|
function Base.eps(x::arb)
parent(x)(2)^(-(precision(parent(x)) - 1))
end
function Base.eps(RR::ArbField)
RR(2)^(-(precision(RR) - 1))
end
function isnan(x::arb)
x_mid = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), x)
0 != ccall(("arf_is_nan", Nemo.libarb), Cint, (Ref{Nemo.arf_struct},), x_mid)
end
function inf(x::arb)
y = parent(x)(0)
ccall(("arb_pos_inf", Nemo.libarb), Cvoid, (Ref{arb},), y)
y
end
function posinf(x::arb)
y = parent(x)(0)
ccall(("arb_pos_inf", Nemo.libarb), Cvoid, (Ref{arb},), y)
y
end
function neginf(x::arb)
y = parent(x)(0)
ccall(("arb_neg_inf", Nemo.libarb), Cvoid, (Ref{arb},), y)
y
end
"""
max(x::arb, y::arb)
> Return a ball containing the maximum of x and y.
"""
function Base.max(x::arb, y::arb)
z = parent(x)()
ccall((:arb_max, Nemo.libarb), Nothing,
(Ref{arb}, Ref{arb}, Ref{arb}, Int), z, x, y, precision(parent(x)))
return z
end
"""
min(x::arb, y::arb)
> Return a ball containing the minimum of x and y.
"""
function Base.min(x::arb, y::arb)
z = parent(x)()
ccall((:arb_min, Nemo.libarb), Nothing,
(Ref{arb}, Ref{arb}, Ref{arb}, Int), z, x, y, precision(parent(x)))
return z
end
"""
setinterval(x::arb, y::arb)
> Return a ball containing the interval [x,y].
"""
function setinterval(x::arb, y::arb)
z = parent(x)()
x_lower = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), lbound(x))
y_upper = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), ubound(y))
ccall((:arb_set_interval_arf, Nemo.libarb), Cvoid,
(Ref{arb}, Ptr{Nemo.arf_struct}, Ptr{Nemo.arf_struct}, Int),
z, x_lower, y_upper, precision(parent(x)))
return z
end
"""
getinterval(x::arb)
getinterval(::Type{arb}, x::arb)
> Return an interval [a,b] containing the ball x.
"""
function getinterval(x::arb)
getinterval(arb, x)
end
function getinterval(::Type{arb}, x::arb)
a, b = x.parent(), x.parent()
a_mid = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), a)
b_mid = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), b)
ccall((:arb_get_interval_arf, Nemo.libarb), Cvoid,
(Ptr{Nemo.arf_struct}, Ptr{Nemo.arf_struct}, Ref{arb}, Clong),
a_mid, b_mid, x, precision(parent(x)))
(a, b)
end
"""
getinterval(::Type{BigFloat}, x::arb)
> Return an interval [a,b] containing the ball x.
"""
function getinterval(::Type{BigFloat}, x::arb)
a, b = BigFloat(), BigFloat()
ccall((:arb_get_interval_mpfr, Nemo.libarb), Cvoid,
(Ref{BigFloat}, Ref{BigFloat}, Ref{arb}),
a, b, x)
(a, b)
end
"""
convert(::Type{BigFloat}, x::arb)
> Return the midpoint of x as a BigFloat rounded down to the current
precision of BigFloat.
"""
function BigFloat(x::arb)
GC.@preserve x begin
t = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), x)
# 4 == round to nearest
m = BigFloat()
ccall((:arf_get_mpfr, Nemo.libarb), Float64,
(Ref{BigFloat}, Ptr{Nemo.arf_struct}, Base.MPFR.MPFRRoundingMode),
m, t, Base.MPFR.MPFRRoundNearest)
end
return m
end
"""
convert(::Type{BigFloat}, x::arb)
> Return the midpoint of x as a BigFloat rounded down to the current
precision of BigFloat.
"""
function Base.convert(::Type{BigFloat}, x::arb)
return BigFloat(x)
end
"""
rel_accuracy_bits(x)
> Compute the relatively accuracy of the ball `x` in bits.
"""
function rel_accuracy_bits(x::arb)
ccall(("arb_rel_accuracy_bits", Nemo.libarb), Int,
(Ref{arb},), x)
end
"""
atan(x::arb, y::arb)
> Return atan(x, y) = arg(x + yi).
"""
function atan(x::arb, y::arb)
z = parent(x)()
ccall((:arb_atan2, Nemo.libarb), Nothing,
(Ref{arb}, Ref{arb}, Ref{arb}, Int), z, x, y, precision(parent(x)))
return z
end
function arb_dump(x::arb)
cstr = ccall((:arb_dump_str, Nemo.libarb), Ptr{UInt8}, (Ref{arb},),
x)
unsafe_string(cstr)
end
function arb_load_dump(str::String, r::ArbField)
x = r()
err = ccall((:arb_load_str, Nemo.libarb), Int32, (Ref{arb}, Ptr{UInt8}),
x, str)
err == 0 || Throw(error("Invalid string $str"))
x
end
function format_arb(x::arb, digits::Int)
cstr = ccall((:arb_get_str, Nemo.libarb), Ptr{UInt8}, (Ref{arb}, Int, UInt),
x, digits, UInt(0))
str = unsafe_string(cstr)
ccall((:flint_free, Nemo.libflint), Nothing, (Ptr{UInt8},), cstr)
return str
end
function add_error!(x::arb, error::arb)
ccall((:arb_add_error, Nemo.libarb), Nothing, (Ref{arb}, Ref{arb}), x, error)
return x
end
function abs_ubound(x::arb)
res = parent(x)()
GC.@preserve x begin
t = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), res)
ccall((:arb_get_abs_ubound_arf, Nemo.libarb), Nothing, (Ptr{Nemo.arf_struct}, Ref{arb}, Int),
t, x, precision(parent(x)))
end
return res
end
function abs_lbound(x::arb)
res = parent(x)()
GC.@preserve x begin
t = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), res)
ccall((:arb_get_abs_lbound_arf, Nemo.libarb), Nothing, (Ptr{Nemo.arf_struct}, Ref{arb}, Int),
t, x, precision(parent(x)))
end
return res
end
function ubound(x::arb)
res = parent(x)()
GC.@preserve x begin
t = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), res)
ccall((:arb_get_ubound_arf, Nemo.libarb), Nothing, (Ptr{Nemo.arf_struct}, Ref{arb}, Int),
t, x, precision(parent(x)))
end
return res
end
function lbound(x::arb)
res = parent(x)()
GC.@preserve x begin
t = ccall((:arb_mid_ptr, Nemo.libarb), Ptr{Nemo.arf_struct}, (Ref{arb}, ), res)
ccall((:arb_get_lbound_arf, Nemo.libarb), Nothing, (Ptr{Nemo.arf_struct}, Ref{arb}, Int),
t, x, precision(parent(x)))
end
return res
end
|
# Annotations related to GeneOntology
# http://geneontology.org/page/go-annotation-file-gaf-format-20
# Spec of annotation record (copied from GO Annotation File (GAF) Format 2.0)
#
# Column Content Required? Cardinality Example
# -------------------------------------------------------------------------------------
# 1 DB required 1 UniProtKB
# 2 DB Object ID required 1 P12345
# 3 DB Object Symbol required 1 PHO3
# 4 Qualifier optional 0 or greater NOT
# 5 GO ID required 1 GO:0003993
# 6 DB:Reference (|DB:Reference) required 1 or greater PMID:2676709
# 7 Evidence Code required 1 IMP
# 8 With (or) From optional 0 or greater GO:0000346
# 9 Aspect required 1 F
# 10 DB Object Name optional 0 or 1 Toll-like receptor 4
# 11 DB Object Synonym (|Synonym) optional 0 or greater hToll|Tollbooth
# 12 DB Object Type required 1 protein
# 13 Taxon(|taxon) required 1 or 2 taxon:9606
# 14 Date required 1 20090118
# 15 Assigned By required 1 SGD
# 16 Annotation Extension optional 0 or greater part_of(CL:0000576)
# 17 Gene Product Form ID optional 0 or 1 UniProtKB:P12345-2
type AnnotationRecord
db::ASCIIString
db_object_id::ASCIIString
db_object_symbol::ASCIIString
qualifier::Vector{ASCIIString}
go_id::TermID
db_reference::Vector{ASCIIString}
evidence_code::ASCIIString
with_or_from::Vector{ASCIIString}
aspect::RootOntology
db_object_name::Union(ASCIIString,Nothing)
db_object_synonym::Vector{ASCIIString}
db_object_type::ASCIIString
taxon::Vector{ASCIIString}
date::ASCIIString
assigned_by::ASCIIString
annotation_extension::Vector{String}
gene_product_form::Union(ASCIIString,Nothing)
end
Base.show(io::IO, annot::AnnotationRecord) = @printf io "AnnotationRecord(\"%s\", \"%s\", \"%s\")" annot.db annot.db_object_id annot.go_id
|
"""
ArrayManifold{M <: Manifold} <: Manifold
A manifold to encapsulate manifolds working on array representations of
`MPoints` and `TVectors` in a transparent way, such that for these manifolds its
not necessary to introduce explicit types for the points and tangent vectors,
but they are encapusalted/stripped automatically when needed.
"""
struct ArrayManifold{M <: Manifold} <: Manifold
manifold::M
end
convert(::Type{M},m::ArrayManifold{M}) where M <: Manifold = m.manifold
convert(::Type{ArrayManifold{M}},m::M) where M <: Manifold = ArrayManifold(M)
manifold_dimension(M::ArrayManifold) = manifold_dimension(M.manifold)
@traitimpl IsDecoratorManifold{ArrayManifold}
struct ArrayMPoint{V <: AbstractArray{<:Number}} <: MPoint
value::V
end
convert(::Type{V},x::ArrayMPoint{V}) where V <: AbstractArray{<:Number} = x.value
convert(::Type{ArrayMPoint{V}},x::V) where V <: AbstractArray{<:Number} = ArrayPoint{V}(x)
eltype(::Type{ArrayMPoint{V}}) where V = eltype(V)
similar(x::ArrayMPoint) = ArrayMPoint(similar(x.value))
similar(x::ArrayMPoint, ::Type{T}) where T = ArrayMPoint(similar(x.value, T))
struct ArrayTVector{V <: AbstractArray{<:Number}} <: TVector
value::V
end
convert(::Type{V},v::ArrayTVector{V}) where V <: AbstractArray{<:Number} = v.value
convert(::Type{ArrayTVector{V}},v::V) where V <: AbstractArray{<:Number} = ArrayTVector{V}(v)
eltype(::Type{ArrayTVector{V}}) where V = eltype(V)
similar(x::ArrayTVector) = ArrayTVector(similar(x.value))
similar(x::ArrayTVector, ::Type{T}) where T = ArrayTVector(similar(x.value, T))
array_value(x::AbstractArray) = x
array_value(x::ArrayMPoint) = x.value
array_value(v::ArrayTVector) = v.value
(+)(v1::ArrayTVector, v2::ArrayTVector) = ArrayTVector(v1.value + v2.value)
(-)(v1::ArrayTVector, v2::ArrayTVector) = ArrayTVector(v1.value - v2.value)
(-)(v::ArrayTVector) = ArrayTVector(-v.value)
(*)(a::Number, v::ArrayTVector) = ArrayTVector(a*v.value)
function isapprox(M::ArrayManifold, x, y; kwargs...)
is_manifold_point(M, x; kwargs...)
is_manifold_point(M, y; kwargs...)
return isapprox(M.manifold, array_value(x), array_value(y); kwargs...)
end
function isapprox(M::ArrayManifold, x, v, w; kwargs...)
is_manifold_point(M, x; kwargs...)
is_tangent_vector(M, x, v; kwargs...)
is_tangent_vector(M, x, w; kwargs...)
return isapprox(M.manifold, array_value(x), array_value(v), array_value(w); kwargs...)
end
function project_tangent!(M::ArrayManifold, w, x, v; kwargs...)
is_manifold_point(M, x; kwargs...)
project_tangent!(M.manifold, w.value, array_value(x), array_value(v))
is_tangent_vector(M, x, w; kwargs...)
return w
end
function distance(M::ArrayManifold, x, y; kwargs...)
is_manifold_point(M, x; kwargs...)
is_manifold_point(M, y; kwargs...)
return distance(M.manifold, array_value(x), array_value(y))
end
function inner(M::ArrayManifold, x, v, w; kwargs...)
is_manifold_point(M, x; kwargs...)
is_tangent_vector(M, x, v; kwargs...)
is_tangent_vector(M, x, w; kwargs...)
return inner(M.manifold, array_value(x), array_value(v), array_value(w))
end
function exp!(M::ArrayManifold, y, x, v; kwargs...)
is_manifold_point(M, x; kwargs...)
is_tangent_vector(M, x, v; kwargs...)
exp!(M.manifold, array_value(y), array_value(x), array_value(v))
is_manifold_point(M, y; kwargs...)
return y
end
function log(M::ArrayManifold, x, y; kwargs...)
is_manifold_point(M, x; kwargs...)
is_manifold_point(M, y; kwargs...)
v = ArrayTVector(log(M.manifold, array_value(x), array_value(y)))
is_tangent_vector(M, x, v; kwargs...)
return v
end
function log!(M::ArrayManifold, v, x, y; kwargs...)
is_manifold_point(M, x; kwargs...)
is_manifold_point(M, y; kwargs...)
log!(M.manifold, array_value(v), array_value(x), array_value(y))
is_tangent_vector(M, x, v; kwargs...)
return v
end
function zero_tangent_vector!(M::ArrayManifold, v, x; kwargs...)
is_manifold_point(M, x; kwargs...)
zero_tangent_vector!(M.manifold, array_value(v), array_value(x); kwargs...)
is_tangent_vector(M, x, v; kwargs...)
return v
end
function zero_tangent_vector(M::ArrayManifold, x; kwargs...)
is_manifold_point(M, x; kwargs...)
w = zero_tangent_vector(M.manifold, array_value(x))
is_tangent_vector(M, x, w; kwargs...)
return w
end
function vector_transport(M::ArrayManifold, x, v, y)
return vector_transport(M.manifold,
array_value(x),
array_value(v),
array_value(y))
end
export ArrayManifold,
ArrayMPoint,
ArrayTVector
|
using Compat
using KUnet
using HDF5,JLD
typealias LUP Union(Op,UpdateParam)
import Base.isequal
function isequal(l1::LUP, l2::LUP)
for n in fieldnames(l1)
isdefined(l1,n) || continue
isdefined(l2,n) || return false
end
for n in fieldnames(l2)
isdefined(l2,n) || continue
isdefined(l1,n) || return false
isequal(l1.(n),l2.(n)) || return false
end
return true
end
net=newnet(relu, 1326, 20000,10)
setparam!(net, learningRate=0.02, dropout=0.5)
save("foo.jld", net)
foo=newnet("foo.jld")
isequal(copy(net,:cpu),copy(foo,:cpu))
|
getname(p::Dagger.OSProc) = "OS Process on worker $(p.pid)"
getname(p::Dagger.ThreadProc) = "Thread $(p.tid) on worker $(p.owner)"
getname(p) = sprint(Base.show, p)
function proclt(p1::T, p2::R) where {T,R}
if p1.owner != p2.owner
return p1.owner < p2.owner
else
return repr(T) < repr(R)
end
end
function proclt(p1::T, p2::T) where {T}
if p1.owner != p2.owner
return p1.owner < p2.owner
else
for field in fieldnames(T)
f1 = getfield(p1, field)
f2 = getfield(p2, field)
if f1 != f2
return f1 < f2
end
end
end
false
end
proclt(p1::Dagger.OSProc, p2::Dagger.OSProc) = p1.pid < p2.pid
proclt(p1::Dagger.OSProc, p2) = p1.pid < p2.owner
proclt(p1, p2::Dagger.OSProc) = p1.owner < p2.pid
function update_window_logs!(window_logs, logs; root_time, window_start)
if !isempty(logs)
for id in keys(logs)
append!(window_logs, map(x->(x,), filter(x->x.category==:compute||x.category==:scheduler_init, logs[id])))
end
end
for idx in length(window_logs):-1:1
log = window_logs[idx]
if length(log) == 2
# Clear out finished events older than window start
log_finish_s = (log[2].timestamp-root_time)/(1000^3)
if log_finish_s < window_start
@debug "Gantt: Deleted event"
deleteat!(window_logs, idx)
end
elseif log[1] isa Dagger.Event{:finish}
# Pair finish events with start events
sidx = findfirst(x->length(x) == 1 &&
x[1] isa Dagger.Event{:start} &&
x[1].id==log[1].id, window_logs)
if sidx === nothing
@debug "Gantt: Removed unpaired finish"
deleteat!(window_logs, idx)
continue
end
window_logs[sidx] = (window_logs[sidx][1], log[1])
@debug "Gantt: Paired event"
deleteat!(window_logs, idx)
end
end
end
function logs_to_stackframes(logs)
data = UInt64[]
lidict = Dict{UInt64, Vector{Base.StackTraces.StackFrame}}()
for log in filter(x->length(x)==2, logs)
append!(data, log[2].profiler_samples.samples)
merge!(lidict, log[2].profiler_samples.lineinfo)
end
return data, lidict
end
const continue_rendering = Ref{Bool}(true)
const render_results = Channel()
|
# Copyright 2019 Tobias Frilling
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This is basically Base.findmin, but first applies f to the elements.
# faster than findmin(map(f, a))
function _findmin(f, a)
p = pairs(a)
(mi, mv), _ = iterate(p)
i = mi
f_mv = f(mv)
for (i, v) in p
f_v = f(v)
if f_v < f_mv
f_mv = f_v
mi = i
end
end
return (f_mv, mi)
end
|
# Wolff single-cluster flip code
# Stefan Countryman
# stc2117@columbia.edu
type SpinArray
Nx::Int64
Ny::Int64
N ::Int64
σ ::Array{Int64,2}
Eold::Float64
end
# Initialize a spin-up spin array with specified dimensions
SpinArray(Nx::Int64, Ny::Int64) = SpinArray(Nx, Ny, Nx*Ny, ones(Int64, Ny, Nx), 0.0)
function magnetization(A::SpinArray)
return sum(A.σ)/A.N
end
function flip!(x::Int64, y::Int64, A::SpinArray, Δσ::Array{Int64,2}, flips::Int64, p::Float64)
s0 = Δσ[x,y] # current spin
Δσ[x,y] = -s0 # flip this spot
flips += 1 # add a flip
nei = [
(x, mod1(y+1, A.Ny))
(x, mod1(y-1, A.Ny))
(mod1(x+1, A.Nx), y)
(mod1(x-1, A.Nx), y)
]
for (xx, yy) in nei
if (s0 == Δσ[xx,yy] && rand() < p)
flips = flip!(xx, yy, A, Δσ, flips, p)
end
end
return flips
end
function spatialcorelator(spins::Array{Int64,2}, Δx::Int64, Δy::Int64)
Δx >= 0 || error("Δx must be nonnegative")
Δy >= 0 || error("Δy must be nonnegative")
shifted = spins
shifted = [shifted[:,(Δx+1):end] shifted[:,(1:Δx)]] # x shift
shifted = [shifted[(end-Δy+1):end,:]; shifted[1:(end-Δy),:]] # y shift
shifted .*= spins # spatial correlations
return mean(shifted) # ⟨σ(x⃗)σ(y⃗)⟩
end
# energies are -2J*∑s1*s2/T; sum them all up
function interactionenergy(spins::Array{Int64,2}, J::Float64)
interactions = 0
horshift = [spins[:,2:end] spins[:,1]]
horshift .*= spins
vershift = [spins[2:end,:]; spins[1,:]]
vershift .*= spins
interactions += sum(horshift)
interactions += sum(vershift)
interactions *= -2
return J * float64(interactions)
end
function magneticenergy(spins::Array{Int64,2}, B::Float64)
spin = sum(spins)
spin *= -1
return B * float(spin)
end
function cluster(Nx::Int64, Ny::Int64, steps::Int64, J::Float64, B::Float64, T::Float64, mcd::Int64)
print("Finding normalized magnetization for J=$J, B=$B, T=$T... ")
p = 1-exp(-2J/T)
A = SpinArray(Nx, Ny)
A.Eold = magneticenergy(A.σ, B) # + interactionenergy(A.σ, J)
Δσ = zeros(A.σ) # proposed spins
magnetizations = zeros(steps)
accepts = 0
Enew = 0.0
ΔE = 0.0
Pacc = 0.0
mcd == 0 ? (cor = false) : (cor = true)
if cor == true
naivecorrelators = zeros(Float64, mcd, steps)
### correlators = zeros(Float64, steps)
end
for n in 1:steps
# randomly pick a spot to flip
x = int(ceil(rand() * Nx))
y = int(ceil(rand() * Ny))
# reset variables
Δσ[:] = A.σ[:]
s0 = Δσ[x,y]
flips = 0
# propose flip
flips = flip!(x, y, A, Δσ, flips, p)
# showspins(Δσ)
# calculate energies; ΔE = (Eint + Emag) - Eold
# Enew = interactionenergy(Δσ, J) # apparently shouldn't have this...
Enew = magneticenergy(Δσ, B)
ΔE = Enew - A.Eold
Pacc = exp(-ΔE/T)
# accept/reject
if rand() < Pacc
A.σ[:] = Δσ[:]
A.Eold = Enew
# println("Accepted step $n")
accepts += 1
end
# find naive correlator
for d in 1:mcd
naivecorrelators[d,n] += spatialcorelator(A.σ, d, 0)
naivecorrelators[d,n] += spatialcorelator(A.σ, 0, d)
end
# get magnetization
magnetizations[n] = magnetization(A)
# n%100 == 0 && println("\tMagnetization for step $n: ",magnetizations[n])
end
println("done with ",(accepts/steps)," accept ratio.")
if cor == false
return magnetizations, accepts/steps
else
return magnetizations, accepts/steps, naivecorrelators ###, correlators
end
end
# for when you don't want the correlator
cluster(Nx, Ny, steps, J, B, T) = cluster(Nx, Ny, steps, J, B, T, 0)
function M(T,J)
return (1 - (sinh(2J./T)).^-4).^(1/8)
end
function showspins(spins::Array{Int64,2})
up = "██"
down = " "
println("Spins (\"$up\" is ↑, \"$down\" is ↓):")
for nrow in 1:size(spins)[2]
for spin in spins[:,nrow]
if spin == 1
print(up)
elseif spin == -1
print(down)
else
error("Spin array must have values of 1 or -1.")
end
end
println()
end
end
function aoft(correlators::Array{Float64, 2})
l = size(correlators)[1] # number of distance values used
D = [1:l] # distances between lattice points
return -D ./ log(abs(correlators))
end
|
const attributes_setters = Dict(
:output_style => sass_option_set_output_style,
:source_comments => sass_option_set_source_comments,
:source_map_file => sass_option_set_source_map_file,
:omit_source_map_url => sass_option_set_omit_source_map_url,
:source_map_embed => sass_option_set_source_map_embed,
:source_map_contents => sass_option_set_source_map_contents,
:source_map_file_urls => sass_option_set_source_map_file_urls,
:source_map_root => sass_option_set_source_map_root,
:is_indented_syntax_src => sass_option_set_is_indented_syntax_src,
:include_path => sass_option_set_include_path,
:plugin_path => sass_option_set_plugin_path,
:indent => sass_option_set_indent,
:linefeed => sass_option_set_linefeed,
:input_path => sass_option_set_input_path,
:output_path => sass_option_set_output_path,
:precision => sass_option_set_precision,
)
"""
`compile_file(filename; kwargs...)`
Compile `filename` from sass or scss to a css string. Possible options, given by keyword
arguments, are:
- `output_style`: output style for the generated css code. See `Sass.Style` for options. For example `output_style = Sass.nested`
- `source_comments`: a boolean to specify whether to insert inline source comments
- `source_map_file`: path to source map file, enables the source map generating used to create sourceMappingUrl
- `omit_source_map_url`: disable sourceMappingUrl in css output
- `source_map_embed`: embed sourceMappingUrl as data uri
- `source_map_contents`: embed include contents in maps
- `source_map_file_urls`: create file urls for sources
- `source_map_root`: pass-through as sourceRoot property
- `is_indented_syntax_src`: treat source_string as sass (as opposed to scss)
- `include_paths` (`AbstractString` or `AbstractArray{<:AbstractString}`)
- `plugin_paths` (`AbstractString` or `AbstractArray{<:AbstractString}`)
- `indent`: string to be used for indentation
- `linefeed`: string to be used to for line feeds
- `input_path`: the input path is used for source map generating. It can be used to define something with string compilation or to overload the input file path. It is set to `stdin` for data contexts and to the input file on file contexts.
- `output_path`: the output path is used for source map generating. LibSass will not write to this file, it is just used to create information in source-maps etc.
- `precision`: precision for outputting fractional numbers
## Examples
```julia
julia> filename = joinpath(Sass.examplefolder, "test.sass");
julia> Sass.compile_file(filename; output_style = Sass.compressed)
"body{font:100% Helvetica,sans-serif;color:#333}\n"
```
"""
function compile_file(filename; input_path = filename, source_map_file = nothing, kwargs...)
ctx = sass_make_file_context(filename)
ctx_out = sass_file_context_get_context(ctx)
options = sass_context_get_options(ctx)
for (key, val) in kwargs
setter = get(attributes_setters, key, nothing)
setter === nothing || setter(options, val)
end
sass_option_set_input_path(options, input_path)
source_map_file === nothing || sass_option_set_source_map_file(options, source_map_file)
sass_file_context_set_options(ctx, options)
sass_compile_file_context(ctx)
status = sass_context_get_error_status(ctx_out)
status == 0 || error(sass_context_get_error_text(ctx_out))
css = sass_context_get_output_string(ctx_out)
ret = source_map_file === nothing ? css : (css, sass_context_get_source_map_string(ctx_out))
sass_delete_file_context(ctx)
ret
end
"""
`compile_file(filename, dest; kwargs...)`
Same as `compile_file(filename; kwargs)` but writes the resulting string in file `dest`.
"""
function compile_file(filename, dest; output_path = dest, source_map_file = nothing, kwargs...)
if source_map_file === nothing
css = compile_file(filename; output_path = output_path, kwargs...)
open(dest, "w") do io
write(io, css)
end
else
css, src_map = compile_file(filename; output_path = output_path, source_map_file = source_map_file, kwargs...)
open(dest, "w") do io
write(io, css)
end
open(source_map_file, "w") do io
write(io, src_map)
end
end
end
|
using BenchmarkTools
using Piecewise
function piecewise_hardcoded(x)
if x < -1
return 0.0
elseif x < 0
return 1.0 - x^2
elseif x < 1
return x^2 -1.0
else
return 0.0
end
end
polynomials = [
StaticPolynomial(0.0, 0.0, 0.0),
p"1.0-x^2",
p"x^2 - 1.0",
StaticPolynomial(0.0, 0.0, 0.0),
]
breakpoints = [-1.0, 0.0, 1.0]
mypiecewise = PiecewisePolynomial{3}(polynomials, breakpoints)
println("Hardcoded piecewise polynomial")
@btime piecewise_hardcoded(x) setup=(x=4*rand()-2)
println("Generated piecewise polynomial")
@btime $mypiecewise(x) setup=(x=4*rand()-2)
myderivative = differentiate(mypiecewise)
println("Generated derivative")
@btime $myderivative(x) setup=(x=4*rand()-2)
functions = [
x -> 0.0,
x -> 1.0 - x^2,
x -> x^2 - 1.0,
x -> 0.0
]
mypiecewisefunction = Piecewise.OrderedPiecewiseFunction{3}(functions, breakpoints)
println("Generated piecewise function")
@btime $mypiecewisefunction(x) setup=(x=4*rand()-2)
op_macro = Piecewise.@ordered_piecewise begin
-1.0 => x -> 0.0
0.0 => x -> 1.0 - x^2
1.0 => x -> x^2- 1.0
_ => x -> 0.0
end
pp_macro = Piecewise.@piecewise_polynomial begin
-1.0 => zero(StaticPolynomial{Float64, 3})
0.0 => p"1.0 - x^2"
1.0 => p"x^2 - 1.0"
_ => zero(StaticPolynomial{Float64, 3})
end
pp_deriv = differentiate(pp_macro)
pp_integ = integrate(pp_macro)
println("Macro ordered piecewise")
@btime $op_macro(x) setup=(x=4*rand()-2)
println("Macro piecewise polynomial")
@btime $pp_macro(x) setup=(x=4*rand()-2)
println("Derivative of macro piecewise polynomial")
@btime $pp_deriv(x) setup=(x=4*rand()-2)
println("Integral of macro piecewise polynomial")
@btime $pp_integ(x) setup=(x=4*rand()-2) |
#=
Proposal functions for joint
Biogeographic competition model
Ignacio Quintero Mächler
t(-_-t)
May 16 2017
=#
#=
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
`Y` IID proposal functions
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=#
"""
upnode!(λ1 ::Float64,
λ0 ::Float64,
triad ::Array{Int64,1},
Y ::Array{Int64,3},
stemevs::Array{Array{Float64,1},1},
bridx_a::Array{Array{UnitRange{Int64},1},1},
brδt ::Vector{Vector{Float64}},
brl ::Vector{Float64},
brs ::Array{Int64,3},
narea ::Int64,
nedge ::Int64)
Update node and incident branches using discrete
Data Augmentation for all areas using a non-competitive
mutual-independence Markov model.
"""
function upnode!(λ1 ::Float64,
λ0 ::Float64,
triad ::Array{Int64,1},
Y ::Array{Int64,3},
stemevs::Array{Array{Float64,1},1},
bridx_a::Array{Array{UnitRange{Int64},1},1},
brδt ::Vector{Vector{Float64}},
brl ::Vector{Float64},
brs ::Array{Int64,3},
narea ::Int64,
nedge ::Int64)
@inbounds begin
# define branch triad
pr, d1, d2 = triad
# sample
samplenode!(λ1, λ0, pr, d1, d2, brs, brl, narea)
# save extinct
ntries = 1
while iszero(sum(view(brs,pr,2,:)))
samplenode!(λ1, λ0, pr, d1, d2, brs, brl, narea)
ntries += 1
if ntries == 500
return false
end
end
# set new node in Y
@simd for k in Base.OneTo(narea)
Y[bridx_a[k][d1][1]] = Y[bridx_a[k][d2][1]] = brs[pr,2,k]
end
# sample a consistent history
createhists!(λ1, λ0, Y, pr, d1, d2, brs, brδt, bridx_a, narea, nedge,
stemevs, brl[nedge])
ntries = 1
while ifextY(Y, stemevs, triad, brs, brl[nedge], narea, bridx_a, nedge)
createhists!(λ1, λ0, Y, pr, d1, d2, brs, brδt, bridx_a, narea, nedge,
stemevs, brl[nedge])
ntries += 1
if ntries == 500
return false
end
end
end
return true
end
"""
samplenode!(λ1 ::Float64,
λ0 ::Float64,
pr ::Int64,
d1 ::Int64,
d2 ::Int64,
brs ::Array{Int64,3},
brl ::Array{Float64,1},
narea::Int64)
Sample one internal node according to
mutual-independence model transition probabilities.
"""
function samplenode!(λ1 ::Float64,
λ0 ::Float64,
pr ::Int64,
d1 ::Int64,
d2 ::Int64,
brs ::Array{Int64,3},
brl ::Array{Float64,1},
narea::Int64)
@inbounds begin
# estimate transition probabilities
pr0_1, pr0_2 = Ptrfast_start(λ1, λ0, brl[pr], Val{0})
pr1_1, pr1_2 = Ptrfast_start(λ1, λ0, brl[pr], Val{1})
d10_1, d10_2 = Ptrfast_end( λ1, λ0, brl[d1], Val{0})
d11_1, d11_2 = Ptrfast_end( λ1, λ0, brl[d1], Val{1})
d20_1, d20_2 = Ptrfast_end( λ1, λ0, brl[d2], Val{0})
d21_1, d21_2 = Ptrfast_end( λ1, λ0, brl[d2], Val{1})
for k = Base.OneTo(narea)
if iszero(brs[pr,1,k])
ppr_1, ppr_2 = pr0_1, pr0_2
else
ppr_1, ppr_2 = pr1_1, pr1_2
end
if iszero(brs[d1,2,k])
pd1_1, pd1_2 = d10_1, d10_2
else
pd1_1, pd1_2 = d11_1, d11_2
end
if iszero(brs[d2,2,k])
pd2_1, pd2_2 = d20_1, d20_2
else
pd2_1, pd2_2 = d21_1, d21_2
end
tp = normlize(*(ppr_1, pd1_1, pd2_1),
*(ppr_2, pd1_2, pd2_2))::Float64
# sample the node's character
brs[pr,2,k] = brs[d1,1,k] = brs[d2,1,k] = coinsamp(tp)::Int64
end
end
return nothing
end
"""
createhists!(λ::Array{Float64,1}, Y::Array{Int64,3}, pr::Int64, d1::Int64, d2::Int64, brs::Array{Int64,3}, brδt::Array{Array{Float64,1},1}, bridx_a::Array{Array{Array{Int64,1},1},1}, narea::Int64)
Create bit histories for all areas for the branch trio.
"""
function createhists!(λ1 ::Float64,
λ0 ::Float64,
Y ::Array{Int64,3},
pr ::Int64,
d1 ::Int64,
d2 ::Int64,
brs ::Array{Int64,3},
brδt ::Array{Array{Float64,1},1},
bridx_a::Array{Array{UnitRange{Int64},1},1},
narea ::Int64,
nedge ::Int64,
stemevs::Array{Array{Float64,1},1},
stbrl ::Float64)
@inbounds begin
if pr == nedge
# if stem branch do continuous DA
mult_rejsam!(stemevs, brs, λ1, λ0, stbrl, narea, nedge)
for j = Base.OneTo(narea), idx = (d1,d2)
bit_rejsam!(Y, bridx_a[j][idx], brs[idx,2,j],
λ1, λ0, brδt[idx])
end
else
for j = Base.OneTo(narea), idx = (pr,d1,d2)
bit_rejsam!(Y, bridx_a[j][idx], brs[idx,2,j],
λ1, λ0, brδt[idx])
end
end
end
return nothing
end
"""
mult_rejsam!(evs ::Array{Array{Float64,1},1},
brs ::Array{Int64,3},
λ1 ::Float64,
λ0 ::Float64,
t ::Float64,
narea::Int64,
nedge::Int64)
Multi-area branch rejection independent model sampling.
"""
function mult_rejsam!(evs ::Array{Array{Float64,1},1},
brs ::Array{Int64,3},
λ1 ::Float64,
λ0 ::Float64,
t ::Float64,
narea::Int64,
nedge::Int64)
@simd for k = Base.OneTo(narea)
rejsam!(evs[k], brs[nedge,1,k], brs[nedge,2,k], λ1, λ0, t)
end
return nothing
end
"""
ifextY(Y ::Array{Int64,3},
triad ::Array{Int64,1},
narea ::Int64,
bridx_a::Array{Array{UnitRange{Int64},1},1})
Return `true` if at some point the species
goes extinct and/or more than one change is
observed after some **δt**, otherwise returns `false`.
"""
function ifextY(Y ::Array{Int64,3},
stemevs::Array{Array{Float64,1},1},
triad ::Array{Int64,1},
brs ::Array{Int64,3},
stbrl ::Float64,
narea ::Int64,
bridx_a::Array{Array{UnitRange{Int64},1},1},
nedge ::Int64)
@inbounds begin
if triad[1] == nedge
ifext_cont(stemevs, brs, stbrl, narea, nedge) && return true::Bool
for k in (triad[2],triad[3])
ifext_disc(Y, k, narea, bridx_a) && return true::Bool
end
else
for k in triad
ifext_disc(Y, k, narea, bridx_a) && return true::Bool
end
end
end
return false::Bool
end
"""
ifext_cont(t_hist::Array{Array{Float64,1},1},
brs ::Array{Int64,3},
t ::Float64,
narea ::Int64,
nedge ::Int64)
Return true if lineage goes extinct.
"""
function ifext_cont(t_hist::Array{Array{Float64,1},1},
brs ::Array{Int64,3},
t ::Float64,
narea ::Int64,
nedge ::Int64)
@inbounds begin
ioc = 0
# initial occupancy time
for k in Base.OneTo(narea)
if brs[nedge,1,k] == 1
ioc = k
break
end
end
ioct = t_hist[ioc][1]
ntries = 0
while !isapprox(ioct, t, atol = 1.0e-12)
if ioc == narea
ioc = 1
else
ioc += 1
end
tc = 0.0
cs = brs[nedge,1,ioc]
for ts in t_hist[ioc]
tc += ts
if ioct < tc
if cs == 1
ioct = tc
ntries = 0
break
else
ntries += 1
if ntries > narea
return true
end
break
end
end
cs = 1 - cs
end
end
end
return false::Bool
end
"""
ifext_disc(Y ::Array{Int64,3},
br ::Int64,
narea ::Int64,
bridx_a::Array{Array{UnitRange{Int64},1},1})
Return `true` if at some point the species
goes extinct and/or more than one change is
observed after some **δt**, otherwise returns `false`.
This specific method is for single branch updates.
"""
function ifext_disc(Y ::Array{Int64,3},
br ::Int64,
narea ::Int64,
bridx_a::Array{Array{UnitRange{Int64},1},1})
@inbounds begin
for i = Base.OneTo(length(bridx_a[1][br]::UnitRange{Int64})-1)
s_e::Int64 = 0 # count current areas
s_c::Int64 = 0 # count area changes
for k = Base.OneTo(narea)
s_e += Y[bridx_a[k][br][i]]::Int64
if Y[bridx_a[k][br][i]]::Int64 != Y[bridx_a[k][br][i+1]]::Int64
s_c += 1
end
end
if s_e == 0 || s_c > 1
return true::Bool
end
end
end
return false::Bool
end
#=
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Y stem node proposal function (continuous DA)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=#
"""
upstemnode!(λ1 ::Float64,
λ0 ::Float64,
nedge::Int64,
stemevs::Array{Array{Float64,1},1},
brs ::Array{Int64,3},
brl ::Array{Float64,1},
narea::Int64)
Update stem node.
"""
function upstemnode!(λ1 ::Float64,
λ0 ::Float64,
nedge ::Int64,
stemevs::Array{Array{Float64,1},1},
brs ::Array{Int64,3},
stbrl ::Float64,
narea ::Int64)
@inbounds begin
# sample
samplestem!(λ1, λ0, nedge, brs, stbrl, narea)
# save extinct
ntries = 1
while sum(view(brs,nedge,1,:)) < 1
samplestem!(λ1, λ0, nedge, brs, stbrl, narea)
ntries += 1
if ntries == 500
return false::Bool
end
end
# sample a congruent history
mult_rejsam!(stemevs, brs, λ1, λ0, stbrl, narea, nedge)
ntries = 1
# check if extinct
while ifext_cont(stemevs, brs, stbrl, narea, nedge)
mult_rejsam!(stemevs, brs, λ1, λ0, stbrl, narea, nedge)
ntries += 1
if ntries == 500
return false::Bool
end
end
end
return true::Bool
end
"""
samplestem!(λ1 ::Float64,
λ0 ::Float64,
nedge::Int64,
brs ::Array{Int64,3},
brl ::Array{Float64,1},
narea::Int64)
Sample stem node.
"""
function samplestem!(λ1 ::Float64,
λ0 ::Float64,
nedge::Int64,
brs ::Array{Int64,3},
stbrl::Float64,
narea::Int64)
@inbounds begin
# estimate transition probabilities
p0 = normlize(Ptrfast_end(λ1, λ0, stbrl, Val{0}))::Float64
p1 = normlize(Ptrfast_end(λ1, λ0, stbrl, Val{1}))::Float64
for k = Base.OneTo(narea)
# sample the node's character
if iszero(brs[nedge,2,k])
brs[nedge,1,k] = coinsamp(p0)::Int64
else
brs[nedge,1,k] = coinsamp(p1)::Int64
end
end
end
return nothing
end
#=
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Y branch proposal functions
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=#
"""
upbranchY!(λ1 ::Float64,
λ0 ::Float64,
ω1 ::Float64,
ω0 ::Float64,
avg_Δx ::Array{Float64,2},
br ::Int64,
Y ::Array{Int64,3},
stemevc::Array{Array{Float64,1},1},
wareas ::Array{Int64,1},
bridx_a::Array{Array{UnitRange{Int64},1},1},
brδt ::Vector{Vector{Float64}},
brl ::Vector{Float64},
brs ::Array{Int64,3},
narea ::Int64,
nedge ::Int64)
Update one branch using discrete Data Augmentation
for all areas with independent
proposals taking into account `Δx` and `ω1` & `ω0`.
"""
function upbranchY!(λ1 ::Float64,
λ0 ::Float64,
br ::Int64,
Y ::Array{Int64,3},
stemevs::Array{Array{Float64,1},1},
bridx_a::Array{Array{UnitRange{Int64},1},1},
brδt ::Vector{Vector{Float64}},
stbrl ::Float64,
brs ::Array{Int64,3},
narea ::Int64,
nedge ::Int64)
ntries = 1
# if stem branch
if br == nedge
mult_rejsam!(stemevs, brs, λ1, λ0, stbrl, narea, nedge)
# check if extinct
while ifext_cont(stemevs, brs, stbrl, narea, nedge)
mult_rejsam!(stemevs, brs, λ1, λ0, stbrl, narea, nedge)
ntries += 1
if ntries == 500
return false
end
end
else
createhists!(λ1, λ0, Y, br, brs, brδt, bridx_a, narea)
# check if extinct
while ifext_disc(Y, br, narea, bridx_a)
createhists!(λ1, λ0, Y, br, brs, brδt, bridx_a, narea)
ntries += 1
if ntries == 500
return false
end
end
end
return true
end
"""
createhists!(λ1 ::Float64,
λ0 ::Float64,
ω1 ::Float64,
ω0 ::Float64,
avg_Δx ::Array{Float64,2},
Y ::Array{Int64,3},
br ::Int64,
brs ::Array{Int64,3},
brδt ::Array{Array{Float64,1},1},
bridx_a::Array{Array{UnitRange{Int64},1},1},
narea ::Int64)
Create bit histories for all areas for one single branch
taking into account `Δx` and `ω1` & `ω0` for all areas.
"""
function createhists!(λ1 ::Float64,
λ0 ::Float64,
Y ::Array{Int64,3},
br ::Int64,
brs ::Array{Int64,3},
brδt ::Array{Array{Float64,1},1},
bridx_a::Array{Array{UnitRange{Int64},1},1},
narea ::Int64)
@inbounds begin
for j = Base.OneTo(narea)
bit_rejsam!(Y, bridx_a[j][br], brs[br,2,j], λ1, λ0, brδt[br])
end
end
return nothing
end
#=
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
X proposal functions
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=#
"""
uptrioX!(pr ::Int64,
d1 ::Int64,
d2 ::Int64,
X ::Array{Float64,2},
bridx::Array{UnitRange{Int64},1},
brδt ::Array{Array{Float64,1},1},
σ²c ::Float64)
Update the node and adjoining branhces of `trio` using Brownian bridges.
"""
function uptrioX!(pr ::Int64,
d1 ::Int64,
d2 ::Int64,
X ::Array{Float64,2},
bridx::Array{UnitRange{Int64},1},
brδt ::Array{Array{Float64,1},1},
brl ::Array{Float64,1},
σ²ϕ ::Float64,
nedge::Int64)
@inbounds begin
# if not root
if pr != nedge
ipr = bridx[pr]
id1 = bridx[d1]
id2 = bridx[d2]
# update node
X[id1[1]] =
X[id2[1]] = trioupd(X[ipr[1]],
X[id1[end]],
X[id2[end]],
brl[pr], brl[d1], brl[d2], σ²ϕ)
#update branches
bbX!(X, ipr, brδt[pr], σ²ϕ)
bbX!(X, id1, brδt[d1], σ²ϕ)
bbX!(X, id2, brδt[d2], σ²ϕ)
else
id1 = bridx[d1]
id2 = bridx[d2]
# update node
X[id1[1]] =
X[id2[1]] = duoupd(X[id1[end]],
X[id2[end]],
brl[d1], brl[d2], σ²ϕ)
# update branches
bbX!(X, id1, brδt[d1], σ²ϕ)
bbX!(X, id2, brδt[d2], σ²ϕ)
end
end
return nothing
end
"""
upbranchX!(j ::Int64,
X ::Array{Float64,2},
bridx::Array{UnitRange{Int64},1},
brδt ::Array{Array{Float64,1},1},
σ²c ::Float64)
Update a branch j in X using a Brownian bridge.
"""
function upbranchX!(j ::Int64,
X ::Array{Float64,2},
bridx::Array{UnitRange{Int64},1},
brδt ::Array{Array{Float64,1},1},
σ²ϕ ::Float64)
@inbounds bbX!(X, bridx[j], brδt[j], σ²ϕ)
return nothing
end
"""
bbX!(X::Array{Float64,2}, idx::UnitRange, t::Array{Float64,1}, σ::Float64)
Brownian bridge simulation function for updating a branch in X in place.
"""
function bbX!(X ::Array{Float64,2},
idx::UnitRange,
t ::Array{Float64,1},
σ²ϕ::Float64)
@inbounds begin
xf::Float64 = X[idx[end]]
for i = Base.OneTo(lastindex(t)-1)
X[idx[i+1]] = (X[idx[i]] + randn()*sqrt((t[i+1] - t[i])*σ²ϕ))::Float64
end
invte::Float64 = 1.0/t[end]
xdif ::Float64 = (X[idx[end]] - xf)
@simd for i = Base.OneTo(lastindex(t))
X[idx[i]] = (X[idx[i]] - t[i] * invte * xdif)::Float64
end
end
return nothing
end
|
using JuLIP, ASE, StaticArrays, NeighbourLists
using Test
X_Ti = vecs([0.0 5.19374 2.59687 3.8953 1.29843 6.49217 7.7906 12.9843 10.3875 11.6859 9.08904 14.2828; 0.0 0.918131 1.83626 -1.11022e-16 0.918131 1.83626 -2.22045e-16 0.918131 1.83626 0.0 0.918131 1.83626; 0.0 0.0 0.0 2.24895 2.24895 2.24895 0.0 0.0 0.0 2.24895 2.24895 2.24895])
C_Ti = (@SMatrix [15.5812 2.47895 0.0; 0.0 2.75439 0.0; 0.0 0.0 4.49791])
# -------------- MatSciPy NeighbourList Patch -------------
using PyCall
import NeighbourLists
matscipy_neighbours = pyimport("matscipy.neighbours")
function asenlist(at::Atoms, rcut)
pyat = ASEAtoms(at).po
return matscipy_neighbours[:neighbour_list]("ijdD", pyat, rcut)
end
function matscipy_nlist(at::Atoms{T}, rcut::T; recompute=false, kwargs...) where T <: AbstractFloat
i, j, r, R = asenlist(at, rcut)
i = copy(i) .+ 1
j = copy(j) .+ 1
r = copy(r)
R = collect(vecs(copy(R')))
first = NeighbourLists.get_first(i, length(at))
NeighbourLists.sort_neigs!(j, r, R, first)
return NeighbourLists.PairList(positions(at), rcut, i, j, r, R, first)
end
# --------------------------------------------------------
pynlist(at, cutoff) = matscipy_nlist(at, cutoff)
jnlist(at, cutoff) = PairList(positions(at), cutoff, cell(at), pbc(at))
function test_nlist_julip(at, cutoff)
nlist = jnlist(at, cutoff)
py_nlist = pynlist(at, cutoff)
return ( (nlist.i == py_nlist.i) &&
(nlist.j == py_nlist.j) &&
(nlist.r ≈ py_nlist.r) &&
(nlist.R ≈ py_nlist.R) )
end
test_configs = [
#
( "si, cubic, cluster, short",
set_pbc!(bulk(:Si, cubic=true) * 3, false),
1.1 * rnn(:Si) ),
#
( "si, cubic, cluster, med",
set_pbc!(bulk(:Si, cubic=true) * 3, false),
2.1 * rnn(:Si) ),
#
( "si, non-cubic cell, cluster, med",
set_pbc!(bulk(:Si) * 5, false),
2.1 * rnn(:Si) ),
#
( "si, non-cubic cell, pbc",
set_pbc!(bulk(:Si) * 5, false),
2.1 * rnn(:Si) ),
#
( "si, non-cubic cell, mixed bc",
set_pbc!(bulk(:Si) * 5, false),
2.1 * rnn(:Si) ),
#
("Ti, non-symmetric elongated cell, pbc",
set_pbc!( set_cell!( Atoms(:Ti, X_Ti), C_Ti ), true ),
1.45 * rnn(:Ti) ),
#
("Ti (hcp?) canonical cell, pbc",
set_pbc!( bulk(:Ti) * 4, true ),
2.3 * rnn(:Ti) ),
]
# ----------- A FEW MORE COMPLEX TESTS THAT FAILED AT SOME POINT ---------------
# [1] a left-handed cell orientation
# the test that failed during Cas' experiments
X = [ 0.00000000e+00 0.00000000e+00 0.00000000e+00
1.92333044e+00 6.63816518e-17 -1.36000000e+00
1.92333044e+00 1.92333044e+00 -2.72000000e+00
3.84666089e+00 1.92333044e+00 -4.08000000e+00 ]'
C = [ 3.84666089 0. 0.
0. 3.84666089 0.
0. 0. -5.44 ]'
# X = [ 0.00000000e+00 0.00000000e+00 0.00000000e+00
# 1.92333044e+00 6.63816518e-17 1.36000000e+00
# 1.92333044e+00 1.92333044e+00 2.72000000e+00
# 3.84666089e+00 1.92333044e+00 4.08000000e+00 ]'
# C = [ 3.84666089 0. 0.
# 0. 3.84666089 0.
# 0. 0. 5.44 ]'
at = Atoms(:Si, collect(vecs(X)))
set_cell!(at, C)
set_pbc!(at, (true,true,true))
atlge = at * (1,1,10)
rcut = 2.3*rnn(:Si)
push!(test_configs, ("Si left-oriented", at, rcut))
push!(test_configs, ("Si left-oriented, large", atlge, rcut))
test_nlist_julip(at, rcut)
test_nlist_julip(atlge, rcut)
# # [2] vacancy in bulk Si
#
# using PyCall
# at = bulk(:Si, cubic=true)
# @pyimport ase.lattice.cubic as cubic
# at2py = cubic.Diamond(symbol = "Si", latticeconstant = 5.43)
# at2py[:get_positions]()
# @test at2py[:get_cell]() ≈ cell(at1)
# @test mat(positions(at1))' ≈ at2py[:get_positions]()[:,[3,2,1]]
#
# at = bulk(:Si, cubic=true)
# at1 = at * 3
# X = mat(positions(at1))
# at1 = deleteat!(at1, 1)
# at2 = deleteat!(set_positions!(at * 3, X[[3,2,1],:]), 1)
# rcut = 2.3 * rnn(:Si)
# test_nlist_julip(at1, rcut)
# test_nlist_julip(at2, rcut)
# [3] Two Ti configuration that seems to be causing problems
C1 = @SMatrix [5.71757 -1.81834e-15 9.74255e-41; -2.85879 4.95156 4.93924e-25; 4.56368e-40 9.05692e-25 9.05629]
X1 = vecs([0.00533847 2.85879 -1.42939 1.42939 0.0 2.85879 -1.42939 1.42939 -1.43e-6 2.85878 -1.42939 1.42939 -1.43e-6 2.85878 -1.42939 1.42939;
-0.0 -0.0 2.47578 2.47578 0.0 -0.0 2.47578 2.47578 1.65052 1.65052 4.1263 4.1263 1.65052 1.65052 4.1263 4.1263;
0.00845581 0.0 0.0 0.0 4.52815 4.52815 4.52815 4.52815 2.26407 2.26407 2.26407 2.26407 6.79222 6.79222 6.79222 6.79222]) |> collect
C2 = @SMatrix [5.71757 0.0 0.0; -2.85879 4.95156 0.0; 0.0 0.0 9.05629]
X2 = vecs([0.00534021 2.85879 -1.42939 1.42939 0.0 2.85879 -1.42939 1.42939 0.0 2.85879 -1.4294 1.4294 0.0 2.85879 -1.4294 1.4294;
0.0 0.0 2.47578 2.47578 0.0 0.0 2.47578 2.47578 1.65052 1.65052 4.1263 4.1263 1.65052 1.65052 4.1263 4.1263;
0.00845858 0.0 0.0 0.0 4.52815 4.52815 4.52815 4.52815 2.26407 2.26407 2.26407 2.26407 6.79222 6.79222 6.79222 6.79222]) |> collect
at1 = set_cell!(Atoms(:Ti, X1), C1)
at2 = set_cell!(Atoms(:Ti, X2), C2)
rcut = 2.5 * rnn(:Ti)
test_nlist_julip(at1, rcut)
test_nlist_julip(at2, rcut)
# --------------- ACTUALLY RUNNING THE TESTS ------------------
println("JuLIP Configuration tests:")
for (i, (descr, at, cutoff)) in enumerate(test_configs)
print("TEST $i: $descr => ")
println(@test test_nlist_julip(at, cutoff))
end
|
using .VectorizationBase: AbstractSIMD
import .ForwardDiff
import .ChainRulesCore
@generated function SLEEFPirates.tanh_fast(x::ForwardDiff.Dual{T,S,N}) where {T,S,N}
quote
$(Expr(:meta,:inline))
t = tanh_fast(x.value)
∂t = vfnmadd_fast(t, t, one(S))
p = x.partials
ForwardDiff.Dual(t, ForwardDiff.Partials(Base.Cartesian.@ntuple $N n -> mul_fast(∂t, p[n])))
end
end
function ChainRulesCore.rrule(::typeof(tanh_fast), x)
t = tanh_fast(x)
∂ = let t = t
y -> (ChainRulesCore.Zero(), mul_fast(vfnmadd_fast(t, t, one(t)), y))
end
t, ∂
end
@generated function SLEEFPirates.sigmoid_fast(x::ForwardDiff.Dual{T,S,N}) where {T,S,N}
quote
$(Expr(:meta,:inline))
s = sigmoid_fast(x.value)
∂s = vfnmadd_fast(s,s,s)
p = x.partials
ForwardDiff.Dual(s, ForwardDiff.Partials(Base.Cartesian.@ntuple $N n -> mul_fast(∂s, p[n])))
end
end
function ChainRulesCore.rrule(::typeof(sigmoid_fast), x)
s = sigmoid_fast(x)
∂ = let s = s
y -> (ChainRulesCore.Zero(), mul_fast(vfnmadd_fast(s, s, s), y))
end
s, ∂
end
@generated function VectorizationBase.relu(x::ForwardDiff.Dual{T,S,N}) where {T,S,N}
quote
$(Expr(:meta,:inline))
v = x.value
z = zero(v)
cmp = v < z
r = ifelse(cmp, z, v)
p = x.partials
ForwardDiff.Dual(r, ForwardDiff.Partials(Base.Cartesian.@ntuple $N n -> ifelse(cmp, z, p[n])))
end
end
function ChainRulesCore.rrule(::typeof(relu), v)
z = zero(v)
cmp = v < z
r = ifelse(cmp, z, v)
∂ = let cmp = cmp
y -> (ChainRulesCore.Zero(), ifelse(cmp, zero(y), y))
end
r, ∂
end
@generated function init_dual(v::Tuple{Vararg{AbstractSIMD,A}}) where {A}
res = Expr(:tuple)
q = Expr(:block, Expr(:meta,:inline))
for a ∈ 1:A
v_a = Symbol(:v_,a)
push!(q.args, Expr(:(=), v_a, Expr(:ref, :v, a)))
partials = Expr(:tuple)
for i ∈ 1:A
push!(partials.args, Expr(:call, i == a ? :one : :zero, v_a))
end
push!(res.args, :(ForwardDiff.Dual($v_a, ForwardDiff.Partials($partials))))
end
push!(q.args, res)
q
end
@generated function dual_store!(∂p::Tuple{Vararg{AbstractStridedPointer,A}}, p::AbstractStridedPointer, ∂v, im::Vararg{Any,N}) where {A,N}
quote
$(Expr(:meta,:inline))
v = ∂v.value
∂ = ∂v.partials
Base.Cartesian.@nextract $N im im
Base.Cartesian.@ncall $N VectorizationBase.vnoaliasstore! p v im # store
Base.Cartesian.@nexprs $A a -> begin # for each of `A` partials
∂p_a = ∂p[a]
∂_a = ∂[a]
Base.Cartesian.@ncall $N VectorizationBase.vnoaliasstore! ∂p_a ∂_a im # store
end
nothing
end
end
function ∂vmap_singlethread!(
f::F, ∂y::Tuple{Vararg{DenseArray{T},A}}, y::DenseArray{T},
args::Vararg{<:DenseArray{<:Base.HWReal},A}
) where {F,T <: Base.HWReal, A}
N = length(y)
ptry = VectorizationBase.zero_offsets(stridedpointer(y))
ptrargs = VectorizationBase.zero_offsets.(stridedpointer.(args))
ptr∂y = VectorizationBase.zero_offsets.(stridedpointer.(∂y))
i = 0
V = VectorizationBase.pick_vector_width(T)
W = Int(V)
st = VectorizationBase.static_sizeof(T)
zero_index = MM{W}(StaticInt(0), st)
while i < N - ((W << 2) - 1)
index = VectorizationBase.Unroll{1,W,4,1,W,0x0000000000000000}((i,))
v = f(init_dual(vload.(ptrargs, index))...)
dual_store!(ptr∂y, ptry, v, index)
i = vadd_fast(i, 4W)
end
while i < N - (W - 1)
vᵣ = f(init_dual(vload.(ptrargs, ((MM{W}(i),),)))...)
dual_store!(ptr∂y, ptry, vᵣ, (MM{W}(i),))
i = vadd_fast(i, W)
end
if i < N
m = mask(T, N & (W - 1))
dual_store!(ptr∂y, ptry, f(init_dual(vload.(ptrargs, ((MM{W}(i),),), m))...), (MM{W}(i,),), m)
end
nothing
end
struct SIMDMapBack{K,T<:Tuple{Vararg{Any,K}}}
jacs::T
end
@generated function (b::SIMDMapBack{K,T})(Δ::A) where {K,T,A}
preloop = Expr(:block, :(jacs = b.jacs))
loop_body = Expr(:block, :(Δᵢ = Δ[i]))
ret = Expr(:tuple, ChainRulesCore.Zero(), ChainRulesCore.Zero())
for k ∈1:K
jₖ = Symbol(:j_, k)
push!(preloop.args, :($jₖ = jacs[$k]))
push!(loop_body.args, :($jₖ[i] *= Δᵢ))
push!(ret.args, jₖ)
end
quote
$preloop
@avx for i ∈ eachindex(Δ)
$loop_body
end
$ret
end
end
function ChainRulesCore.rrule(::typeof(vmap), f::F, args::Vararg{Any,K}) where {F,K}
out = similar(first(args))
jacs = map(similar, args)
∂vmap_singlethread!(f, jacs, out, args...)
out, SIMDMapBack(jacs)
end
|
""" Data structure for undirected wiring diagrams.
"""
module UndirectedWiringDiagrams
export AbstractUndirectedWiringDiagram, UndirectedWiringDiagram,
outer_box, box, junction, nboxes, njunctions, boxes, junctions, ports,
ports_with_junction, junction_type, port_type, add_box!, add_junction!,
add_junctions!, set_junction!, add_wire!, add_wires!, ocompose
using ...CategoricalAlgebra.CSets, ...Present
using ...CategoricalAlgebra.ShapeDiagrams: Span
using ...CategoricalAlgebra.FinSets: FinOrdFunction, pushout
using ...Theories: FreeCategory, dom, codom, compose, ⋅, id
import ..DirectedWiringDiagrams: box, boxes, nboxes, add_box!, add_wire!,
add_wires!
import ..AlgebraicWiringDiagrams: add_junctions!, ocompose
# Data types
############
@present TheoryUWD(FreeCategory) begin
Box::Ob
Port::Ob
OuterPort::Ob
Junction::Ob
box::Hom(Port,Box)
junction::Hom(Port,Junction)
outer_junction::Hom(OuterPort,Junction)
end
const AbstractUndirectedWiringDiagram = const AbstractUWD =
AbstractCSetType(TheoryUWD)
const UntypedUndirectedWiringDiagram = const UntypedUWD =
CSetType(TheoryUWD, index=[:box, :junction, :outer_junction])
@present TheoryTypedUWD <: TheoryUWD begin
Type::Ob
port_type::Hom(Port,Type)
outer_port_type::Hom(OuterPort,Type)
junction_type::Hom(Junction,Type)
compose(junction, junction_type) == port_type
compose(outer_junction, junction_type) == outer_port_type
end
const TypedUndirectedWiringDiagram = const TypedUWD =
CSetType(TheoryTypedUWD, data=[:Type],
index=[:box, :junction, :outer_junction])
# Imperative interface
######################
function UndirectedWiringDiagram(::Type{UWD},
nports::Int; data_types...) where UWD <: AbstractUWD
d = UWD(; data_types...)
add_parts!(d, :OuterPort, nports)
return d
end
UndirectedWiringDiagram(nports::Int; data_types...) =
UndirectedWiringDiagram(UntypedUWD, nports; data_types...)
function UndirectedWiringDiagram(::Type{UWD},
port_types::AbstractVector{T}; data_types...) where {UWD <: AbstractUWD, T}
d = UWD(; port_type=T, outer_port_type=T, junction_type=T, data_types...)
nports = length(port_types)
add_parts!(d, :OuterPort, nports, outer_port_type=port_types)
return d
end
UndirectedWiringDiagram(port_types::AbstractVector; data_types...) =
UndirectedWiringDiagram(TypedUWD, port_types; data_types...)
outer_box(::AbstractUWD) = 0
box(d::AbstractUWD, args...) = subpart(d, args..., :box)
junction(d::AbstractUWD, args...; outer::Bool=false) =
subpart(d, args..., outer ? :outer_junction : :junction)
function junction(d::AbstractUWD, port::Tuple{Int,Int})
box, nport = port
box == outer_box(d) ?
junction(d, nport, outer=true) : junction(d, ports(d, box)[nport])
end
nboxes(d::AbstractUWD) = nparts(d, :Box)
njunctions(d::AbstractUWD) = nparts(d, :Junction)
boxes(d::AbstractUWD) = 1:nboxes(d)
junctions(d::AbstractUWD) = 1:njunctions(d)
ports(d::AbstractUWD; outer::Bool=false) =
1:nparts(d, outer ? :OuterPort : :Port)
ports(d::AbstractUWD, box) =
box == outer_box(d) ? (1:nparts(d, :OuterPort)) : incident(d, box, :box)
ports_with_junction(d::AbstractUWD, junction; outer::Bool=false) =
incident(d, junction, outer ? :outer_junction : :junction)
junction_type(d::AbstractUWD, args...) = subpart(d, args..., :junction_type)
port_type(d::AbstractUWD, args...; outer::Bool=false) =
subpart(d, args..., outer ? :outer_port_type : :port_type)
function port_type(d::AbstractUWD, port::Tuple{Int,Int})
box, nport = port
box == outer_box(d) ?
port_type(d, nport, outer=true) : port_type(d, ports(d, box)[nport])
end
add_box!(d::AbstractUWD; data...) = add_part!(d, :Box; data...)
function add_box!(d::AbstractUWD, nports::Int; data...)
box = add_box!(d; data...)
ports = add_parts!(d, :Port, nports, box=box)
box
end
function add_box!(d::AbstractUWD, port_types::AbstractVector; data...)
box = add_box!(d; data...)
nports = length(port_types)
ports = add_parts!(d, :Port, nports, box=box, port_type=port_types)
box
end
add_junction!(d::AbstractUWD; data...) = add_part!(d, :Junction; data...)
add_junction!(d::AbstractUWD, type; data...) =
add_part!(d, :Junction; junction_type=type, data...)
add_junctions!(d::AbstractUWD, njunctions::Int; data...) =
add_parts!(d, :Junction, njunctions; data...)
add_junctions!(d::AbstractUWD, types::AbstractVector; data...) =
add_parts!(d, :Junction, length(types); junction_type=types, data...)
function set_junction!(d::AbstractUWD, port, junction; outer::Bool=false)
if has_subpart(d, :junction_type)
ptype, jtype = port_type(d, port, outer=outer), junction_type(d, junction)
all(ptype .== jtype) || error(
"Domain error: port type $ptype and junction type $jtype do not match")
end
set_subpart!(d, port, outer ? :outer_junction : :junction, junction)
end
set_junction!(d::AbstractUWD, junction; kw...) =
set_junction!(d, :, junction; kw...)
function set_junction!(d::AbstractUWD, port::Tuple{Int,Int}, junction)
box, nport = port
if box == outer_box(d)
set_junction!(d, nport, junction, outer=true)
else
set_junction!(d, ports(d, box)[nport], junction)
end
end
""" Wire together two ports in an undirected wiring diagram.
A convenience method that creates and sets junctions as needed. Ports are only
allowed to have one junction, so if both ports already have junctions, then the
second port is assigned the junction of the first. The handling of the two
arguments is otherwise symmetric.
FIXME: When both ports already have junctions, the two junctions should be
*merged*. To do this, we must implement `merge_junctions!` and thus also
`rem_part!`.
"""
function add_wire!(d::AbstractUWD, port1::Tuple{Int,Int}, port2::Tuple{Int,Int})
j1, j2 = junction(d, port1), junction(d, port2)
if j1 > 0
set_junction!(d, port2, j1)
elseif j2 > 0
set_junction!(d, port1, j2)
else
j = has_subpart(d, :junction_type) ?
add_junction!(d, port_type(d, port1)) : add_junction!(d)
set_junction!(d, port1, j)
set_junction!(d, port2, j)
end
end
add_wire!(d, wire::Pair) = add_wire!(d, first(wire), last(wire))
function add_wires!(d::AbstractUWD, wires)
for wire in wires
add_wire!(d, wire)
end
end
# Operadic interface
####################
function ocompose(f::AbstractUWD, gs::AbstractVector{<:AbstractUWD})
@assert length(gs) == nboxes(f)
h = empty(f)
copy_parts!(h, f, OuterPort=ports(f, outer=true))
for g in gs
copy_boxes!(h, g, boxes(g))
end
f_junction = FinOrdFunction(
flat(junction(f, ports(f, i)) for i in boxes(f)), njunctions(f))
# FIXME: Should use coproduct as monoidal product.
gs_offset = [0; cumsum(njunctions.(gs))]
gs_outer = FinOrdFunction(
flat(junction(g, outer=true) .+ n for (g,n) in zip(gs, gs_offset[1:end-1])),
gs_offset[end])
cospan = pushout(Span(f_junction, gs_outer))
f_inc, g_inc = cospan.left, cospan.right
junctions = add_junctions!(h, codom(f_inc).n)
if has_subpart(h, :junction_type)
set_subpart!(h, [collect(f_inc); collect(g_inc)], :junction_type,
[junction_type(f); flat(junction_type(g) for g in gs)])
end
f_outer = FinOrdFunction(junction(f, outer=true), njunctions(f))
# FIXME: Again, should use coproduct.
gs_junction = FinOrdFunction(
flat(junction(g) .+ n for (g,n) in zip(gs, gs_offset[1:end-1])),
gs_offset[end])
set_junction!(h, collect(f_outer ⋅ f_inc), outer=true)
set_junction!(h, collect(gs_junction ⋅ g_inc))
return h
end
function ocompose(f::AbstractUWD, i::Int, g::AbstractUWD)
@assert 1 <= i <= nboxes(f)
h = empty(f)
copy_parts!(h, f, OuterPort=ports(f, outer=true))
copy_boxes!(h, f, 1:(i-1))
copy_boxes!(h, g, boxes(g))
copy_boxes!(h, f, (i+1):nboxes(f))
f_i = FinOrdFunction(junction(f, ports(f, i)), njunctions(f))
g_outer = FinOrdFunction(junction(g, outer=true), njunctions(g))
cospan = pushout(Span(f_i, g_outer))
f_inc, g_inc = cospan.left, cospan.right
junctions = add_junctions!(h, codom(f_inc).n)
if has_subpart(h, :junction_type)
set_subpart!(h, [collect(f_inc); collect(g_inc)], :junction_type,
[junction_type(f); junction_type(g)])
end
f_outer = FinOrdFunction(junction(f, outer=true), njunctions(f))
f_start = FinOrdFunction(junction(f, flat(ports(f, 1:(i-1)))), njunctions(f))
g_junction = FinOrdFunction(junction(g), njunctions(g))
f_end = FinOrdFunction(
junction(f, flat(ports(f, (i+1):nboxes(f)))), njunctions(f))
set_junction!(h, collect(f_outer ⋅ f_inc), outer=true)
set_junction!(h, [
collect(f_start ⋅ f_inc);
collect(g_junction ⋅ g_inc);
collect(f_end ⋅ f_inc);
])
return h
end
copy_boxes!(d::AbstractUWD, from::AbstractUWD, boxes) =
copy_parts!(d, from, Box=boxes, Port=flat(ports(from, boxes)))
flat(vs) = reduce(vcat, vs, init=Int[])
end
|
function readdata(paths::Array{String, 1}; columns_to_get=[], add_tag::Bool = true, samplestocut::Int = 3)
formated_data = DataFrame(reshape([], 0, length(columns_to_get)), :auto)
rename!(formated_data, columns_to_get)
for file in paths
formated_data =
vcat(formated_data, readdata(file, columns_to_get=columns_to_get, add_tag=add_tag, samplestocut=samplestocut))
end
return formated_data
end
function readdata(path::String; columns_to_get::Array=[], add_tag::Bool = true, samplestocut::Int = 3)
df = readdatafromcsv(path)
meta = getmetadata(df)
data = getdatawithoutmeta(df)
lonlat = calculatelonlat(meta)
data = hcat(data, lonlat)
if add_tag
tag_columns = createtagcolumns(path, data)
data = hcat(data, tag_columns)
end
data = cutoutliners(data, samplestocut)
data[!, :timestep] = 0:nrow(data)-1
data[!, :timestep] = data[!, :timestep] .* 0.1
data = data[:, columns_to_get]
end
function readdatafromcsv(path)
AXIS = ["_x" "_y" "_z"]
NAMES = [:timestep]
NAMES = vcat(NAMES, vec(Symbol.(["magnetometr"], AXIS)))
NAMES = vcat(NAMES, vec(Symbol.(["acceleromter"], AXIS)))
NAMES = vcat(NAMES, vec(Symbol.(["orientation"], AXIS)))
df =
CSV.read(path, DataFrame, header = NAMES, silencewarnings = true, threaded = false)
end
function getmetadata(df)
METADATA_COLNAMES = [
"latitude_start",
"longitude_start",
"latitude_end",
"longitude_end",
"first_sample",
"last_sample",
]
gapidx = findfirst(occursin.(r"<\d+>", df[!, "timestep"]))
meta = df[gapidx+1:end, :][:, 1:6]
rename!(meta, Symbol.(METADATA_COLNAMES))
meta[!, "latitude_start"] = parse.(Float64, meta[!, "latitude_start"])
meta[!, "first_sample"] = trunc.(Int, meta[!, "first_sample"])
meta[!, "last_sample"] = trunc.(Int, meta[!, "last_sample"])
meta = DataFrame(meta)
end
function getdatawithoutmeta(df)
gapidx = findfirst(occursin.(r"<\d+>", df[!, "timestep"]))
data = df[1:gapidx-1, :]
end
function calculatelonlat(meta)
samples_num = last(meta, 1)[!, "last_sample"][1] + 1
result = DataFrame(lat = 1:samples_num, lon = 1:samples_num)
result[!, "lat"] = convert.(Float64, result[!, "lat"])
result[!, "lon"] = convert.(Float64, result[!, "lon"])
for corridor in eachrow(meta)
first_sample_idx = corridor["first_sample"] + 1 # This dataset is 0-index-based
last_sample_idx = corridor["last_sample"] + 1
corridor_idxs = first_sample_idx:last_sample_idx
corridor_samples_num = last_sample_idx - first_sample_idx + 1
lat_diff = corridor["latitude_end"] - corridor["latitude_start"]
lon_diff = corridor["longitude_end"] - corridor["longitude_start"]
lat_step = lat_diff / corridor_samples_num
lon_step = lon_diff / corridor_samples_num
result[corridor_idxs, :lon] =
(result[corridor_idxs, :lon] .- first_sample_idx) * lon_step .+
corridor["longitude_start"]
result[corridor_idxs, :lat] =
(result[corridor_idxs, :lat] .- first_sample_idx) * lat_step .+
corridor["latitude_start"]
end
return result
end
function createtagcolumns(path, data)
n_rows = nrow(data)
tag = match(r"(.*[/\\])*(?<id>.*)_(?<sample>.*)\.txt", path)
if !isnothing(tag)
return DataFrame(
path_id = repeat([tag[:id]], n_rows),
path_sample = repeat([tag[:sample]], n_rows)
)
else
tag = match(r"(.*[/\\])*(?<pathid>.*)\.txt", path)
return DataFrame(
path_id = repeat([tag[:pathid]], n_rows)
)
end
end
function cutoutliners(data, samplestocut)
data = data[setdiff(1:end, 1:samplestocut), :]
data = data[setdiff(1:end, end-samplestocut:end), :]
end
|
function check_tolerance(::Type{Sphere2D}, arg0::jdouble)
return jcall(Sphere2D, "checkTolerance", void, (jdouble,), arg0)
end
function get_dimension(obj::Sphere2D)
return jcall(obj, "getDimension", jint, ())
end
function get_instance(::Type{Sphere2D})
return jcall(Sphere2D, "getInstance", Sphere2D, ())
end
function get_sub_space(obj::Sphere2D)
return jcall(obj, "getSubSpace", Sphere1D, ())
end
|
@testset "Perfect bipartite matching" begin
@testset "Uncorrelated" begin
@testset "Constructor with $i nodes on each side" for i in [2, 5, 10]
n = i
ε = (i - 2) / 16
reward = Distribution[Bernoulli(.5 + ((i == j) ? ε : 0.)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
@test instance.n_arms == n ^ 2
@test instance.reward == reward
# Error: non bipartite.
reward = Distribution[Bernoulli(.5 + ((i == j) ? ε : 0.)) for i in 1:n, j in 1:(n + 2)]
@test_throws ErrorException UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
reward = Distribution[Bernoulli(.5 + ((i == j) ? ε : 0.)) for i in 1:(n + 2), j in 1:n]
@test_throws ErrorException UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
end
@testset "State with $i nodes on each side" for i in [2, 5, 10]
n = i
ε = (i - 2) / 16
reward = Distribution[Bernoulli(.5 + ((i == j) ? ε : .0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
state = initial_state(instance)
@test state.round == 0
@test state.regret == 0.0
@test state.reward == 0.0
@test length(state.arm_counts) == n * n
@test length(state.arm_reward) == n * n
@test length(state.arm_average_reward) == n * n
for i in 1:n
for j in 1:n
@test state.arm_counts[(i, j)] == 0
@test state.arm_reward[(i, j)] == 0.0
@test state.arm_average_reward[(i, j)] == 0.0
end
end
end
@testset "Trace with $i nodes on each side" for i in [2, 5, 10]
n = i
ε = (i - 2) / 16
reward = Distribution[Bernoulli(.5 + ((i == j) ? ε : .0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
trace = initial_trace(instance)
@test length(trace.states) == 0
@test length(trace.arms) == 0
@test length(trace.reward) == 0
@test length(trace.policy_details) == 0
@test length(trace.time_choose_action) == 0
@test eltype(trace.states) == State{Tuple{Int, Int}}
@test eltype(trace.arms) == Vector{Tuple{Int, Int}}
@test eltype(trace.reward) == Vector{Float64}
@test eltype(trace.time_choose_action) == Int
end
@testset "Pull with $i nodes on each side" for i in [2, 5, 10]
n = i
reward = Distribution[Bernoulli(((i == j) ? 0.0 : 1.0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
Random.seed!(1)
@test pull(instance, [(1, 2), (i, i)]) == ([1.0, 0.0], -1) # Reward and regret
end
@testset "Check feasibility with 3 nodes on each side" begin
n = 3
reward = Distribution[Bernoulli(((i == j) ? 0.0 : 1.0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
@test is_feasible(instance, [(1, 2), (2, 3), (3, 1)])
@test ! is_feasible(instance, [(2, 3), (3, 2), (1, 2)])
@test ! is_feasible(instance, [(2, 3), (3, 2), (2, 1), (1, 2)])
end
if ! is_travis
@testset "LP solver" begin
@testset "Constructor" for i in [2, 5, 10]
n = i
reward = Distribution[Bernoulli(((i == j) ? 0.0 : 1.0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingLPSolver(Gurobi.Optimizer))
@test instance.solver != nothing
@test instance.solver.model != nothing
@test size(instance.solver.x, 1) == n * n
end
@testset "Solve with $i nodes on each side" for i in [2, 5, 10]
n = i
reward = Distribution[Bernoulli(((i == j) ? 0.0 : 1.0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingLPSolver(Gurobi.Optimizer))
Random.seed!(i)
drawn = Dict((i, j) => rand() for i in 1:n, j in 1:n)
solution = solve_linear(instance, drawn)
@test is_feasible(instance, solution)
end
end
end
@testset "Munkres solver" begin
@testset "Constructor" for i in [2, 5, 10]
n = i
reward = Distribution[Bernoulli(((i == j) ? 0.0 : 1.0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingMunkresSolver())
@test instance.solver != nothing
end
@testset "Solve with $i nodes on each side" for i in [2, 5, 10]
n = i
reward = Distribution[Bernoulli(((i == j) ? 0.0 : 1.0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingMunkresSolver())
Random.seed!(i)
drawn = Dict((i, j) => rand() for i in 1:n, j in 1:n)
solution = solve_linear(instance, drawn)
@test is_feasible(instance, solution)
end
end
@testset "Hungarian solver" begin
@testset "Constructor" for i in [2, 5, 10]
n = i
reward = Distribution[Bernoulli(((i == j) ? 0.0 : 1.0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingHungarianSolver())
@test instance.solver != nothing
end
@testset "Solve with $i nodes on each side" for i in [2, 5, 10]
n = i
reward = Distribution[Bernoulli(((i == j) ? 0.0 : 1.0)) for i in 1:n, j in 1:n]
instance = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingHungarianSolver())
Random.seed!(i)
drawn = Dict((i, j) => rand() for i in 1:n, j in 1:n)
solution = solve_linear(instance, drawn)
@test is_feasible(instance, solution)
end
end
@testset "Solver equivalence (size: $i nodes on each side)" for i in [2, 5, 10]
n = i
reward = Distribution[Bernoulli(((i == j) ? 0.0 : 1.0)) for i in 1:n, j in 1:n]
instance_lp = ! is_travis && UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingLPSolver(Gurobi.Optimizer))
instance_munkres = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingMunkresSolver())
instance_hungarian = UncorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingHungarianSolver())
Random.seed!(i)
drawn = Dict((i, j) => rand() for i in 1:n, j in 1:n)
if ! is_travis
solution_lp = solve_linear(instance_lp, drawn)
@test is_feasible(instance_lp, solution_lp)
end
solution_munkres = solve_linear(instance_munkres, drawn)
@test is_feasible(instance_munkres, solution_munkres)
solution_hungarian = solve_linear(instance_hungarian, drawn)
@test is_feasible(instance_hungarian, solution_hungarian)
# All solutions must have the same length, as these are perfect matchings.
@test length(solution_hungarian) == length(solution_munkres)
cost_munkres = sum(drawn[o] for o in solution_munkres)
cost_hungarian = sum(drawn[o] for o in solution_hungarian)
@test cost_hungarian ≈ cost_munkres
if ! is_travis
@test length(solution_lp) == length(solution_hungarian)
cost_lp = sum(drawn[o] for o in solution_lp)
@test cost_lp ≈ cost_hungarian
end
end
end
@testset "Correlated" begin
@testset "Constructor with $i nodes on each side" for i in [2, 5, 10]
n = i
ε = (i - 2) / 16
μ = vec(Float64[.5 + ((i == j) ? ε : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
@test instance.n_arms == n ^ 2
@test instance.reward == reward
end
@testset "State with $i nodes on each side" for i in [2, 5, 10]
n = i
ε = (i - 2) / 16
μ = vec(Float64[.5 + ((i == j) ? ε : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
state = initial_state(instance)
@test state.round == 0
@test state.regret == 0.0
@test state.reward == 0.0
@test length(state.arm_counts) == n * n
@test length(state.arm_reward) == n * n
@test length(state.arm_average_reward) == n * n
for i in 1:n
for j in 1:n
@test state.arm_counts[(i, j)] == 0
@test state.arm_reward[(i, j)] == 0.0
@test state.arm_average_reward[(i, j)] == 0.0
end
end
end
@testset "Trace with $i nodes on each side" for i in [2, 5, 10]
n = i
ε = (i - 2) / 16
μ = vec(Float64[.5 + ((i == j) ? ε : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
trace = initial_trace(instance)
@test length(trace.states) == 0
@test length(trace.arms) == 0
@test length(trace.reward) == 0
@test length(trace.policy_details) == 0
@test length(trace.time_choose_action) == 0
@test eltype(trace.states) == State{Tuple{Int, Int}}
@test eltype(trace.arms) == Vector{Tuple{Int, Int}}
@test eltype(trace.reward) == Vector{Float64}
@test eltype(trace.time_choose_action) == Int
end
@testset "Pull with $i nodes on each side" for i in [2]#, 5, 10]
n = i
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
Random.seed!(1)
rewards, regret = pull(instance, [(1, 2), (i, i)])
@test rewards ≈ [0.5, 1.5] atol=1.e-6
@test regret ≈ -0.5 atol=1.e-6
end
@testset "Check feasibility with 3 nodes on each side" begin
n = 3
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
@test is_feasible(instance, [(1, 2), (2, 3), (3, 1)])
@test ! is_feasible(instance, [(2, 3), (3, 2), (1, 2)])
@test ! is_feasible(instance, [(2, 3), (3, 2), (2, 1), (1, 2)])
end
@testset "Check partial acceptability with 3 nodes on each side" begin
n = 3
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingNoSolver())
@test is_partially_acceptable(instance, [(1, 2)])
@test is_partially_acceptable(instance, [(1, 2), (2, 3)])
@test is_partially_acceptable(instance, [(1, 2), (2, 3), (3, 1)])
@test ! is_partially_acceptable(instance, [(2, 3), (3, 2), (1, 2)])
@test ! is_partially_acceptable(instance, [(2, 3), (3, 2), (2, 1), (1, 2)])
end
if ! is_travis
@testset "LP solver" begin
@testset "Constructor" for i in [2, 5, 10]
n = i
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingLPSolver(Gurobi.Optimizer))
@test instance.solver != nothing
@test instance.solver.model != nothing
@test size(instance.solver.x, 1) == n * n
end
@testset "Solve with $i nodes on each side" for i in [2, 5, 10]
n = i
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingLPSolver(Gurobi.Optimizer))
Random.seed!(i)
drawn = Dict((i, j) => rand() for i in 1:n, j in 1:n)
solution = solve_linear(instance, drawn)
@test is_feasible(instance, solution)
end
end
end
@testset "Munkres solver" begin
@testset "Constructor" for i in [2, 5, 10]
n = i
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingMunkresSolver())
@test instance.solver != nothing
end
@testset "Solve with $i nodes on each side" for i in [2, 5, 10]
n = i
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingMunkresSolver())
Random.seed!(i)
drawn = Dict((i, j) => rand() for i in 1:n, j in 1:n)
solution = solve_linear(instance, drawn)
@test is_feasible(instance, solution)
end
end
@testset "Hungarian solver" begin
@testset "Constructor" for i in [2, 5, 10]
n = i
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingHungarianSolver())
@test instance.solver != nothing
end
@testset "Solve with $i nodes on each side" for i in [2, 5, 10]
n = i
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingHungarianSolver())
Random.seed!(i)
drawn = Dict((i, j) => rand() for i in 1:n, j in 1:n)
solution = solve_linear(instance, drawn)
@test is_feasible(instance, solution)
end
end
@testset "Solver equivalence (size: $i nodes on each side)" for i in [2, 5, 10]
n = i
μ = vec(Float64[.5 + ((i == j) ? 1. : 0.) for i in 1:n, j in 1:n])
Σ = vec(Float64[((abs(i - j) <= 1) ? sign(i - j) : 0.) for i in 1:n, j in 1:n])
reward = MvNormal(μ, Σ)
instance_lp = ! is_travis && CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingLPSolver(Gurobi.Optimizer))
instance_munkres = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingMunkresSolver())
instance_hungarian = CorrelatedPerfectBipartiteMatching(reward, PerfectBipartiteMatchingHungarianSolver())
Random.seed!(i)
drawn = Dict((i, j) => rand() for i in 1:n, j in 1:n)
if ! is_travis
solution_lp = solve_linear(instance_lp, drawn)
@test is_feasible(instance_lp, solution_lp)
end
solution_munkres = solve_linear(instance_munkres, drawn)
@test is_feasible(instance_munkres, solution_munkres)
solution_hungarian = solve_linear(instance_hungarian, drawn)
@test is_feasible(instance_hungarian, solution_hungarian)
# All solutions must have the same length, as these are perfect matchings.
@test length(solution_hungarian) == length(solution_munkres)
cost_munkres = sum(drawn[o] for o in solution_munkres)
cost_hungarian = sum(drawn[o] for o in solution_hungarian)
@test cost_hungarian ≈ cost_munkres
if ! is_travis
@test length(solution_lp) == length(solution_hungarian)
cost_lp = sum(drawn[o] for o in solution_lp)
@test cost_lp ≈ cost_hungarian
end
end
end
end
|
function uniformMutation(genotype::IntegerGenotype, rng::Random.AbstractRNG,
min::Integer, max::Integer, nGens::Integer=1)
if min > max
min, max = max, min
end
indRep = genotype._representation
genLen = length(indRep)
mutatedIndRep = Array{Integer}(undef, genLen)
if nGens > genLen
nGens = genLen
end
indexes = randomIndexSelection(genLen, nGens, rng)
mutatedIndRep = copy(indRep)
range = max-min
for i=1:nGens
mutatedIndRep[indexes[i]] = (rand(rng, UInt64)%range)+1+min
end
return IntegerGenotype(mutatedIndRep)
end
|
md"""
# Model Pruning Example
While NaiveNASflux does not come with any built in search policies, it is still possible to do some cool stuff with it.
Below is a very simple example of parameter pruning.
First we need some boilerplate to create the model and do the training:
"""
@testset "Pruning xor example" begin #src
using NaiveNASflux, Flux, Test
using Flux: train!, mse
import Random
Random.seed!(0)
niters = 50
# To cut down on the verbosity, start by making a helper function for creating a Dense layer as a graph vertex.
# The keyword argument `layerfun=`[`ActivationContribution`](@ref) will wrap the layer and compute an activity
# based neuron utility metric for it while the model trains.
densevertex(in, outsize, act) = fluxvertex(Dense(nout(in),outsize, act), in, layerfun=ActivationContribution)
# Ok, lets create the model and train it. We overparameterize quite heavily to avoid sporadic test failures :)
invertex = denseinputvertex("input", 2)
layer1 = densevertex(invertex, 32, relu)
layer2 = densevertex(layer1, 1, sigmoid)
original = CompGraph(invertex, layer2)
## Training params, nothing to see here
opt = ADAM(0.1)
loss(g) = (x, y) -> mse(g(x), y)
## Training data: xor truth table: y = xor(x) just so we don't need to download a dataset.
x = Float32[0 0 1 1;
0 1 0 1]
y = Float32[0 1 1 0]
## Train the model
train!(loss(original), params(original), Iterators.repeated((x,y), niters), opt)
@test loss(original)(x, y) < 0.001
# With that out of the way, lets try three different ways to prune the hidden layer (vertex nr 2 in the graph).
# To make examples easier to compare, lets decide up front that we want to remove half of the hidden layer neurons
# and try out three different ways of how to select which ones to remove.
nprune = 16
# Prune the neurons with lowest utility according to the metric in [`ActivationContribution`](@ref).
# This is the default if no utility function is provided.
pruned_least = deepcopy(original)
Δnout!(pruned_least[2] => -nprune)
# Prune the neurons with higest utility according to the metric in [`ActivationContribution`](@ref).
# This is obviously not a good idea if you want to preserve the accuracy.
pruned_most = deepcopy(original)
Δnout!(pruned_most[2] => -nprune) do v
vals = NaiveNASlib.defaultutility(v)
return 2*sum(vals) .- vals # Ensure all values are still > 0, even for last vertex
end
# Prune randomly selected neurons by giving random utility.
pruned_random = deepcopy(original)
Δnout!(v -> rand(nout(v)), pruned_random[2] => -nprune)
# Free lunch anyone?
@test loss(pruned_most)(x, y) >
loss(pruned_random)(x, y) >
loss(pruned_least)(x, y) >=
loss(original)(x, y)
# The metric calculated by [`ActivationContribution`](@ref) is actually quite good in this case.
@test loss(pruned_least)(x, y) ≈ loss(original)(x, y) atol = 1e-5
end #src
|
# x(t+1) = A*x(t) + B*u(t)
struct Dynamics
A
B
vx_range
vy_range
d
end
# ϕ₁*x + ϕ₂*y + ϕ₃*z ≥ -þ
# ϕ₁*x + ϕ₂*y + ϕ₃*z ≥ -þ == -ϕ₁*x - ϕ₂*y - ϕ₃*z ≤ þ
struct Ineq
ϕ₁::Float64
ϕ₂::Float64
ϕ₃::Float64
þ::Float64
end
struct Region
name
r::Vector{Ineq}
θ::Float64
end
mutable struct Funnel
name
params
pos_prec
neg_prec
continuous_prec
dynamics
pos_eff
neg_eff
end_region
is_continuous
cont_ind
function Funnel(name)
new(name, [],[],[],[],[],[],[],Dict(),true, 1)
end
end
mutable struct Graph
num_levels::Int64
acts
μacts
props
μprops
leveled
initprops
goalprops
indexes #[object_index, place_pose_index]
safe_poses
has_placement_constraint
function Graph()
new(0, Dict(1=>[]), Dict(1=>[]), Dict(1=>Dict()), Dict(1=>[]), false, Dict(), Dict(), [1,1],[],true)
end
end |
@testset "SVector" begin
@testset "Inner Constructors" begin
@test SVector{1,Int}((1,)).data === (1,)
@test SVector{1,Float64}((1,)).data === (1.0,)
@test SVector{2,Float64}((1, 1.0)).data === (1.0, 1.0)
@test_throws Exception SVector{1,Int}()
@test_throws Exception SVector{2,Int}((1,))
@test_throws Exception SVector{1,Int}(())
@test_throws Exception SVector{Int,1}((1,))
end
@testset "Outer constructors and macro" begin
@test SVector{1}((1,)).data === (1,)
@test SVector{1}((1.0,)).data === (1.0,)
@test SVector((1,)).data === (1,)
@test SVector((1.0,)).data === (1.0,)
@test ((@SVector [1.0])::SVector{1}).data === (1.0,)
@test ((@SVector [1, 2, 3])::SVector{3}).data === (1, 2, 3)
@test ((@SVector Float64[1,2,3])::SVector{3}).data === (1.0, 2.0, 3.0)
@test ((@SVector [i for i = 1:3])::SVector{3}).data === (1, 2, 3)
@test ((@SVector Float64[i for i = 1:3])::SVector{3}).data === (1.0, 2.0, 3.0)
@test ((@SVector zeros(2))::SVector{2, Float64}).data === (0.0, 0.0)
@test ((@SVector ones(2))::SVector{2, Float64}).data === (1.0, 1.0)
@test isa(@SVector(rand(2)), SVector{2, Float64})
@test isa(@SVector(randn(2)), SVector{2, Float64})
@test ((@SVector zeros(Float32, 2))::SVector{2,Float32}).data === (0.0f0, 0.0f0)
@test ((@SVector ones(Float32, 2))::SVector{2,Float32}).data === (1.0f0, 1.0f0)
@test isa(@SVector(rand(Float32, 2)), SVector{2, Float32})
@test isa(@SVector(randn(Float32, 2)), SVector{2, Float32})
end
@testset "Methods" begin
v = @SVector [11, 12, 13]
@test isimmutable(v) == true
@test v[1] === 11
@test v[2] === 12
@test v[3] === 13
@test Tuple(v) === (11, 12, 13)
@test size(v) === (3,)
@test size(typeof(v)) === (3,)
@test size(SVector{3}) === (3,)
@test size(v, 1) === 3
@test size(v, 2) === 1
@test size(typeof(v), 1) === 3
@test size(typeof(v), 2) === 1
@test length(v) === 3
@test_throws Exception v[1] = 1
end
end
|
using DashBootstrapComponents
form = dbc_row(
[
dbc_col(
[
dbc_label("Email", html_for = "example-email-grid"),
dbc_input(
type = "email",
id = "example-email-grid",
placeholder = "Enter email",
),
],
width = 6,
),
dbc_col(
[
dbc_label("Password", html_for = "example-password-grid"),
dbc_input(
type = "password",
id = "example-password-grid",
placeholder = "Enter password",
),
],
width = 6,
),
],
className = "g-3",
)
|
"""
$(TYPEDEF)
Hierachy of AbstractSoilVC:
- [`BrooksCorey`](@ref)
- [`VanGenuchten`](@ref)
"""
abstract type AbstractSoilVC{FT<:AbstractFloat} end
#######################################################################################################################################################################################################
#
# Changes to this structure
# General
# 2021-Sep-30: define this structure with no default constructor
# 2021-Sep-30: define a constructor to fil the value from VanGenuchten parameters
#
#######################################################################################################################################################################################################
"""
$(TYPEDEF)
Brooks Corey soil parameters
# Fields
$(TYPEDFIELDS)
# Examples
```julia
bc = BrooksCorey{FT}("Test", FT(5), FT(2), FT(0.5), FT(0.1));
bc = BrooksCorey{FT}(VanGenuchten{FT}("Loam"));
```
"""
struct BrooksCorey{FT<:AbstractFloat} <:AbstractSoilVC{FT}
"Soil type"
TYPE::String
"Soil b"
B::FT
"Potential at saturation `[MPa]`"
Ψ_SAT::FT
"Saturated soil volumetric water content"
Θ_SAT::FT
"Residual soil volumetric water content"
Θ_RES::FT
end
#######################################################################################################################################################################################################
#
# Changes to this structure
# General
# 2021-Sep-30: define this structure with two default constructors from an incomplete parameter set
#
#######################################################################################################################################################################################################
"""
$(TYPEDEF)
van Genuchten soil parameters
# Fields
$(TYPEDFIELDS)
# Examples
```julia
vg = VanGenuchten{FT}("Loam");
vg = VanGenuchten{FT}("Silt");
vg = VanGenuchten{FT}("Test", FT(100), FT(2), FT(0.5), FT(0.1));
```
"""
struct VanGenuchten{FT<:AbstractFloat} <:AbstractSoilVC{FT}
"Soil type"
TYPE::String
"Soil α is related to the inverse of the air entry suction, α > 0"
Α::FT
"Soil n is Measure of the pore-size distribution"
N::FT
"Soil m = 1 - 1/n"
M::FT
"Saturated soil volumetric water content"
Θ_SAT::FT
"Residual soil volumetric water content"
Θ_RES::FT
# constructors
VanGenuchten{FT}(name::String, α::FT, n::FT, θ_sat::FT, θ_res::FT) where {FT<:AbstractFloat} = new{FT}(name, α, n, 1-1/n, θ_sat, θ_res)
VanGenuchten{FT}(name::String) where {FT<:AbstractFloat} = (
# Parameters from Silt soil
_p = [ 163.2656, 1.37, 0.46, 0.034];
# switch name
if name=="Sand"
_p = [1479.5945, 2.68, 0.43, 0.045];
elseif name=="Loamy Sand"
_p = [1265.3084, 2.28, 0.41, 0.057];
elseif name=="Sandy Loam"
_p = [ 765.3075, 1.89, 0.41, 0.065];
elseif name=="Loam"
_p = [ 367.3476, 1.56, 0.43, 0.078];
elseif name=="Sandy Clay Loam"
_p = [ 602.0419, 1.48, 0.39, 0.100];
elseif name=="Silt Loam"
_p = [ 204.0820, 1.41, 0.45, 0.067];
elseif name=="Silt"
_p = [ 163.2656, 1.37, 0.46, 0.034];
elseif name=="Clay Loam"
_p = [ 193.8779, 1.31, 0.41, 0.095];
elseif name=="Silty Clay Loam"
_p = [ 102.0410, 1.23, 0.43, 0.089];
elseif name== "Sandy Clay"
_p = [ 275.5107, 1.23, 0.38, 0.100];
elseif name=="Silty Clay"
_p = [ 51.0205, 1.09, 0.36, 0.070];
elseif name=="Clay"
_p = [ 81.6328, 1.09, 0.38, 0.068];
else
@warn "Soil type $(name) not recognized, use Silt instead.";
name = "Silt";
end;
# return a new struct
return new{FT}(name, _p[1], _p[2], 1-1/_p[2], _p[3], _p[4])
);
end
#######################################################################################################################################################################################################
#
# Changes to this structure
# General
# 2021-Sep-30: define this structure with no constructors
# 2021-Oct-19: add soil and air variables
# 2021-Oct-19: sort variable to prognostic and dignostic catergories
#
#######################################################################################################################################################################################################
"""
$(TYPEDEF)
Struct that contains environmental conditions, such as soil moisture and atmospheric vapor pressure. Note that this structure is designed to be containers to interact with other CliMA modules and to
prescribe values.
# Fields
$(TYPEDFIELDS)
# Examples
```julia
;
```
"""
mutable struct SoilAir{FT<:AbstractFloat}
# parameters that do not change with time
"Total area of the soil/air interface `[m²]`"
AREA::FT
"Soil color class used for soil albedo calculations"
COLOR::Int
"Number of air layers"
N_AIR::Int
"Number of soil layers"
N_SOIL::Int
"Soil moisture retention curve"
VC::Union{Vector{BrooksCorey{FT}}, Vector{VanGenuchten{FT}}}
"Z profile for air `[m]`"
Z_AIR::Vector{FT}
"Z profile for soil `[m]`"
Z_SOIL::Vector{FT}
"ΔZ profile for air `[m]`"
ΔZ_AIR::Vector{FT}
"ΔZ profile for soil `[m]`"
ΔZ_SOIL::Vector{FT}
# prognostic variables that change with time
"CO₂ partial pressure at different air layers `[Pa]`"
p_CO₂::Vector{FT}
"H₂O partial pressure at different air layers `[Pa]`"
p_H₂O::Vector{FT}
"Temperature at different air layers `[K]`"
t_air::Vector{FT}
"Temperature at different soil layers `[K]`"
t_soil::Vector{FT}
"Wind speed (total) `[m s⁻¹]`"
wind::Vector{FT}
"Wind speed (vertical) `[m s⁻¹]`"
wind_z::Vector{FT}
"Soil water content at different soil layers `[m³ m⁻³]`"
θ::Vector{FT}
# dignostic variables that change with time
"Saturated vapor pressure at different air layers `[Pa]`"
p_H₂O_sat::Vector{FT}
"Vapor pressure deficit at different air layers `[Pa]`"
vpd::Vector{FT}
"Soil water potential at different soil layers `[MPa]`"
ψ::Vector{FT}
# caches to speed up calculations
# constructors
SoilAir{FT}(z_soil::Vector{FT}, z_air::Vector{FT}, area::FT=FT(1)) where {FT<:AbstractFloat} = (
_n_air = length(z_air) - 1;
_n_soil = length(z_soil) - 1;
_p_sats = saturation_vapor_pressure(T_25()) * ones(_n_air);
_vcs = [VanGenuchten{FT}("Silt") for _i in 1:_n_soil];
return new{FT}(area, 1, _n_air, _n_soil, _vcs, z_air, z_soil, diff(z_air), diff(z_soil), 41 * ones(_n_air), 0.5 * _p_sats, T_25() * ones(_n_air), T_25() * ones(_n_soil), 2 * ones(_n_air),
1 * ones(_n_air), [_vc.Θ_SAT for _vc in _vcs], _p_sats, 0.5 * _p_sats, zeros(_n_soil))
);
end
|
### A Pluto.jl notebook ###
# v0.15.1
using Markdown
using InteractiveUtils
# ╔═╡ 78090450-7373-4824-bfe9-1283e971dda0
begin
using InteractiveUtils
using Pkg
with_terminal() do
versioninfo()
Pkg.status()
end
end
# ╔═╡ 5d7dc2d4-1008-11ec-2ea6-ffc13cf6dbf7
begin
using CategoricalArrays
using CSV
using DataFrames
using CairoMakie
CairoMakie.activate!(type="svg")
using AlgebraOfGraphics
using MixedModels
using MixedModelsExtras
using MixedModelsMakie
using Effects
using PlutoUI
using Random
TableOfContents()
end
# ╔═╡ 16199f57-4b1a-4f75-a247-a3d153d01e5c
md"""
# Analysis of data contributed by Sinika Timme
-- *Phillip Alday*
"""
# ╔═╡ df9273de-28e0-42ca-8e7d-8d2fe1b9be2d
md"""
## Data loading
Including a bunch of keyword-arguments for CSV.
"""
# ╔═╡ 99546f56-7c64-4cf5-98ce-0ed48896b82c
begin
dat = DataFrame(CSV.File("data/hexaff_all.csv";
comment="#",
delim=';',
missingstring=["NA",""],
downcast=true,
drop=[1,2],
ntasks=1, # this is due to a bug in CSV.jl-0.9 -- I'll try to get it fixed later
decimal=','
))
dropmissing!(dat, [:FS, :timepoint, :date])
end
# ╔═╡ 11cb62b7-6736-47de-8c91-67b858747004
# select(dat, Not([:FS, :HR]))
# ╔═╡ 5aa0776d-3b03-4910-a2b7-e51c7404e1ee
describe(dat)
# ╔═╡ d8d7d67a-d2aa-4fb7-8cea-f69c60de2326
md"""
## `fm1`: `timepoint` is numeric, `ID` as grouping
"""
# ╔═╡ c4a027a1-902f-48bc-8009-71653f766e8d
# fm1 = fit(MixedModel,
# @formula(FS ~ 1 + timepoint + (1 + timepoint|ID)),
# dat;
# contrasts=Dict(:ID => Grouping()))
# ╔═╡ 88c9b542-448e-4a91-a985-24e4e8b863f5
# fm1.rePCA
# ╔═╡ 09a4adef-0d8b-4242-885b-e8dfb6d5b756
# shrinkageplot(fm1)
# ╔═╡ fab68835-d889-4bde-ad2a-80e5dc6b1983
# caterpillar(fm1)
# ╔═╡ 092c77a2-37aa-4c78-906a-322b61308b34
# VarCorr(fm1)
# ╔═╡ 9fd0c2d7-109d-4fe3-a0c6-a75839799cb7
md"""
## `fm2`: `timepoint` is numeric, `date` is categorical `ID` as grouping
"""
# ╔═╡ fd153bbb-5273-4b36-a111-2d34137b10bd
# fm2 = fit(MixedModel,
# @formula(FS ~ 1 + timepoint * date + (1 + timepoint + date|ID)),
# dat;
# contrasts=Dict(:ID => Grouping(),
# :date => HelmertCoding()))
# ╔═╡ 06703b73-e491-4112-a59d-28d2e477d0a6
# fm2.rePCA
# ╔═╡ 22e90698-2dd6-4cf3-a694-a0fabd2a0302
md"""
!!! warning
Some planels in the shrinkage plot actually show "anti-shrinkage".
In my experience, this is often symptomatic of a misspecified model.
"""
# ╔═╡ 60fed847-bd2c-4896-a43a-d5cca63786d3
# shrinkageplot(fm2)
# ╔═╡ d98f7985-2c65-46e4-a356-d9cb57c2b829
# qqcaterpillar(fm2)
# ╔═╡ 34151154-5ecb-4651-b519-0cb006de1d15
# VarCorr(fm2)
# ╔═╡ ea9a452a-086d-437d-9ada-47f7cbd5398c
md"""
## `fm3`: `timepoint` is numeric, `ID&date` as grouping
"""
# ╔═╡ d6887601-3f49-48b1-b527-59849fc59908
fm3 = fit(MixedModel,
@formula(FS ~ 1 + timepoint + (1 + timepoint|ID & date)),
dat;
contrasts=Dict(:ID => Grouping(),
:date => Grouping()))
# ╔═╡ 79152bfc-b75b-4aaf-bbf6-2fe14a24d315
fm3.rePCA
# ╔═╡ 5299c521-e359-4e5d-ace3-73766a323b1d
# shrinkageplot(fm3)
# ╔═╡ 2891251e-e32f-4654-9243-296f6206429c
# qqcaterpillar(fm3)
# ╔═╡ f77aa540-579e-4367-a1ab-b863a8d015d9
# VarCorr(fm3)
# ╔═╡ 0d204adc-5a4c-4276-ba83-690178bc570c
md"""
## `fm4`: `timepoint` is categorical, `ID&date` as grouping
!!! warning
This model is probably overfit.
"""
# ╔═╡ 14b559e6-4e2a-43e3-ad92-4d90342c8835
# fm4 = fit(MixedModel,
# @formula(FS ~ 1 + timepoint + zerocorr(1 + timepoint|ID & date)),
# dat;
# contrasts=Dict(:ID => Grouping(),
# :date => Grouping(),
# :timepoint => SeqDiffCoding()))
# ╔═╡ 02de86be-40ea-4b62-8e54-c7529e57fa31
# MixedModels.likelihoodratiotest(fm3, fm4)
# ╔═╡ 54e69118-d930-49ba-9bd7-afbf614dda75
# begin
# with_terminal() do
# show(fm4)
# end
# end
# ╔═╡ 18a6b29b-94b4-46e6-8242-45dbea143700
# aicc.([fm3, fm4])
# ╔═╡ d223139b-f209-4495-ad6a-69e91f524690
# fm4.rePCA
# ╔═╡ 2c2c3b51-426d-41ec-acad-7e6c1e6fae48
md"""
## Model Diagnostics (of `fm3`)
"""
# ╔═╡ 3198e0c5-588e-4bcd-bb62-ecba0ca129a2
fm3.optsum
# ╔═╡ 4d14f8a6-17b1-406d-8f4c-1199ee0f9966
# begin
# fm5 = LinearMixedModel(@formula(FS ~ 1 + timepoint + (1 + timepoint|ID & date)), dat;
# contrasts=Dict(:ID => Grouping(),
# :date => Grouping()))
# fm5.optsum.optimizer = :LN_COBYLA
# fit!(fm5)
# fm5.optsum
# end
# ╔═╡ f2a1b2d0-7bae-4ab6-a287-e42d02e01383
# scatter(fitted(fm3), response(fm3))
# ╔═╡ b16e6a8d-db29-4cc6-911b-3ebb3c8f71c0
# scatter(residuals(fm3), fitted(fm3))
# ╔═╡ ee60825b-808f-49da-9dd8-824aa85d2c76
# qqnorm(fm3)
# ╔═╡ 9f4c72f1-aa01-4666-b07b-e2fb1f0cacb3
md"""
## Things I don't really recommend but reviewers ask for
"""
# ╔═╡ fce2e257-897f-487b-b0e3-fb5942820ed2
# icc(fm3)
# ╔═╡ e4d72691-6d31-47e5-b1e0-630571988330
md"""
## Estimates and Effects (of `fm3`)
"""
# ╔═╡ e062623c-9dee-49f3-8f8a-362d0073eb60
# coefplot(fm3)
# ╔═╡ 9533ef07-6e79-4f17-8626-cc85413957b9
# boot = parametricbootstrap(MersenneTwister(42), 1000, fm3)
# ╔═╡ cb5aafb6-a724-428f-aa15-22ed30b42b08
# coefplot(boot)
# ╔═╡ 12ce0e46-fb15-4396-84d7-212c5d850423
# ridgeplot(boot)
# ╔═╡ 8f073561-8b51-4a6d-b08d-225821bf7d56
# design = Dict(:timepoint => unique(skipmissing(dat.timepoint)))
# ╔═╡ 23d494fd-52cb-4679-a186-c6d795299a97
# eff = effects(design, fm3)
# ╔═╡ fd193833-b163-4182-a85b-84085c747f71
# begin
# # convert to 95% CIs instead of standard errors
# @. eff.lower = eff.FS - 1.96 * eff.err
# @. eff.upper = eff.FS + 1.96 * eff.err
# end
# ╔═╡ 1a36289a-4b08-4aed-adbb-de4dea5e504f
# begin
# plt = data(eff) * mapping(:timepoint, :FS; lower=:lower, upper=:upper) *
# (visual(Lines) + visual(LinesFill; color=:black))
# draw(plt)
# end
# ╔═╡ cf4d7b94-abf0-4338-b72a-f60aaefe9a90
# begin
# data(dat) * mapping(:timepoint, :FS; layout=:ID) * visual(Scatter) |> draw
# end
# ╔═╡ 0aef95c5-0e48-4ff7-b8a3-58d4e8c94c0b
# begin
# dat2 = transform(dat, :ID => categorical; renamecols=false)
# dat2.fitted = fitted(fm3)
# # important for connecting the dots in plotting later
# sort!(dat2, [:date, :ID, :timepoint])
# describe(dat2)
# end
# ╔═╡ 6acc4e05-d650-40ca-abf9-9cccd401ed45
# begin
# plt2 = plt + data(dat2) * mapping(:timepoint, :FS; layout=:ID) * visual(Scatter; color=:black)
# # note that it's "axis" and "figure" -- each panel/facet is an axis
# # so each of those is width x height which means the entire figure is much bigger
# # but pluto has scaled it for display purposes here
# draw(plt2; axis=(width=150, height=150))
# end
# ╔═╡ 32d56757-1e1b-43dd-a9aa-83b5177172e9
# begin
# plt3 = plt2 + data(dat2) * mapping(:timepoint, :fitted; layout=:ID, color=:date) * visual(Lines)
# draw(plt3; axis=(width=150, height=150))
# end
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
AlgebraOfGraphics = "cbdf2221-f076-402e-a563-3d30da359d67"
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0"
CategoricalArrays = "324d7699-5711-5eae-9e2f-1d82baa6b597"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
Effects = "8f03c58b-bd97-4933-a826-f71b64d2cca2"
InteractiveUtils = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
MixedModels = "ff71e718-51f3-5ec2-a782-8ffcbfa3c316"
MixedModelsExtras = "781a26e1-49f4-409a-8f4c-c3159d78c17e"
MixedModelsMakie = "b12ae82c-6730-437f-aff9-d2c38332a376"
Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[compat]
AlgebraOfGraphics = "~0.5.3"
CSV = "~0.9.0"
CairoMakie = "~0.6.5"
CategoricalArrays = "~0.10.0"
DataFrames = "~1.2.2"
Effects = "~0.1.2"
MixedModels = "~4.1.1"
MixedModelsExtras = "~0.1.2"
MixedModelsMakie = "~0.3.8"
PlutoUI = "~0.7.9"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
[[AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "485ee0867925449198280d4af84bdb46a2a404d0"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.0.1"
[[AbstractTrees]]
git-tree-sha1 = "03e0550477d86222521d254b741d470ba17ea0b5"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.3.4"
[[Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "84918055d15b3114ede17ac6a7182f68870c16f7"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.3.1"
[[AlgebraOfGraphics]]
deps = ["Colors", "Dates", "FileIO", "GLM", "GeoInterface", "GeometryBasics", "GridLayoutBase", "KernelDensity", "Loess", "Makie", "PlotUtils", "PooledArrays", "RelocatableFolders", "StatsBase", "StructArrays", "Tables"]
git-tree-sha1 = "40446e661ffe7a33c31980ec6438181daa41deff"
uuid = "cbdf2221-f076-402e-a563-3d30da359d67"
version = "0.5.3"
[[Animations]]
deps = ["Colors"]
git-tree-sha1 = "e81c509d2c8e49592413bfb0bb3b08150056c79d"
uuid = "27a7e980-b3e6-11e9-2bcd-0b925532e340"
version = "0.4.1"
[[ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
[[ArrayInterface]]
deps = ["IfElse", "LinearAlgebra", "Requires", "SparseArrays", "Static"]
git-tree-sha1 = "019303a0f26d6012f35ecdfa4618551d145fb9f2"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "3.1.31"
[[Arrow]]
deps = ["ArrowTypes", "BitIntegers", "CodecLz4", "CodecZstd", "DataAPI", "Dates", "Mmap", "PooledArrays", "SentinelArrays", "Tables", "TimeZones", "UUIDs"]
git-tree-sha1 = "b00e6eaba895683867728e73af78a00218f0db10"
uuid = "69666777-d1a9-59fb-9406-91d4454c9d45"
version = "1.6.2"
[[ArrowTypes]]
deps = ["UUIDs"]
git-tree-sha1 = "a0633b6d6efabf3f76dacd6eb1b3ec6c42ab0552"
uuid = "31f734f8-188a-4ce0-8406-c8a06bd891cd"
version = "1.2.1"
[[Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[Automa]]
deps = ["Printf", "ScanByte", "TranscodingStreams"]
git-tree-sha1 = "d50976f217489ce799e366d9561d56a98a30d7fe"
uuid = "67c07d97-cdcb-5c2c-af73-a7f9c32a568b"
version = "0.8.2"
[[AxisAlgorithms]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"]
git-tree-sha1 = "a4d07a1c313392a77042855df46c5f534076fab9"
uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950"
version = "1.0.0"
[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[BenchmarkTools]]
deps = ["JSON", "Logging", "Printf", "Statistics", "UUIDs"]
git-tree-sha1 = "42ac5e523869a84eac9669eaceed9e4aa0e1587b"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "1.1.4"
[[BitIntegers]]
deps = ["Random"]
git-tree-sha1 = "f50b5a99aa6ff9db7bf51255b5c21c8bc871ad54"
uuid = "c3b6d118-76ef-56ca-8cc7-ebb389d030a1"
version = "0.2.5"
[[Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[CEnum]]
git-tree-sha1 = "215a9aa4a1f23fbd05b92769fdd62559488d70e9"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.4.1"
[[CSV]]
deps = ["CodecZlib", "Dates", "FilePathsBase", "Mmap", "Parsers", "PooledArrays", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings"]
git-tree-sha1 = "24e8646b28d573b10be1c6dab18fb336846a955c"
uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
version = "0.9.0"
[[Cairo]]
deps = ["Cairo_jll", "Colors", "Glib_jll", "Graphics", "Libdl", "Pango_jll"]
git-tree-sha1 = "d0b3f8b4ad16cb0a2988c6788646a5e6a17b6b1b"
uuid = "159f3aea-2a34-519c-b102-8c37f9878175"
version = "1.0.5"
[[CairoMakie]]
deps = ["Base64", "Cairo", "Colors", "FFTW", "FileIO", "FreeType", "GeometryBasics", "LinearAlgebra", "Makie", "SHA", "StaticArrays"]
git-tree-sha1 = "8664989955daccc90002629aa80193e44893bb45"
uuid = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0"
version = "0.6.5"
[[Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "f2202b55d816427cd385a9a4f3ffb226bee80f99"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.1+0"
[[CategoricalArrays]]
deps = ["DataAPI", "Future", "JSON", "Missings", "Printf", "RecipesBase", "Statistics", "StructTypes", "Unicode"]
git-tree-sha1 = "1562002780515d2573a4fb0c3715e4e57481075e"
uuid = "324d7699-5711-5eae-9e2f-1d82baa6b597"
version = "0.10.0"
[[ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "30ee06de5ff870b45c78f529a6b093b3323256a3"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.3.1"
[[CodecBzip2]]
deps = ["Bzip2_jll", "Libdl", "TranscodingStreams"]
git-tree-sha1 = "2e62a725210ce3c3c2e1a3080190e7ca491f18d7"
uuid = "523fee87-0ab8-5b00-afb7-3ecf72e48cfd"
version = "0.7.2"
[[CodecLz4]]
deps = ["Lz4_jll", "TranscodingStreams"]
git-tree-sha1 = "59fe0cb37784288d6b9f1baebddbf75457395d40"
uuid = "5ba52731-8f18-5e0d-9241-30f10d1ec561"
version = "0.4.0"
[[CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "ded953804d019afa9a3f98981d99b33e3db7b6da"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.0"
[[CodecZstd]]
deps = ["TranscodingStreams", "Zstd_jll"]
git-tree-sha1 = "d19cd9ae79ef31774151637492291d75194fc5fa"
uuid = "6b39b394-51ab-5f42-8807-6242bab2b4c2"
version = "0.7.0"
[[ColorBrewer]]
deps = ["Colors", "JSON", "Test"]
git-tree-sha1 = "61c5334f33d91e570e1d0c3eb5465835242582c4"
uuid = "a2cac450-b92f-5266-8821-25eda20663c8"
version = "0.4.0"
[[ColorSchemes]]
deps = ["ColorTypes", "Colors", "FixedPointNumbers", "Random"]
git-tree-sha1 = "9995eb3977fbf67b86d0a0a0508e83017ded03f2"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.14.0"
[[ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "32a2b8af383f11cbb65803883837a149d10dfe8a"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.10.12"
[[ColorVectorSpace]]
deps = ["ColorTypes", "Colors", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "StatsBase"]
git-tree-sha1 = "4d17724e99f357bfd32afa0a9e2dda2af31a9aea"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.8.7"
[[Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.8"
[[Compat]]
deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"]
git-tree-sha1 = "727e463cfebd0c7b999bbf3e9e7e16f254b94193"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "3.34.0"
[[CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
[[Contour]]
deps = ["StaticArrays"]
git-tree-sha1 = "9f02045d934dc030edad45944ea80dbd1f0ebea7"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.5.7"
[[Crayons]]
git-tree-sha1 = "3f71217b538d7aaee0b69ab47d9b7724ca8afa0d"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.0.4"
[[DataAPI]]
git-tree-sha1 = "bec2532f8adb82005476c141ec23e921fc20971b"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.8.0"
[[DataFrames]]
deps = ["Compat", "DataAPI", "Future", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrettyTables", "Printf", "REPL", "Reexport", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"]
git-tree-sha1 = "d785f42445b63fc86caa08bb9a9351008be9b765"
uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
version = "1.2.2"
[[DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "7d9d316f04214f7efdbb6398d545446e246eff02"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.10"
[[DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
[[Distances]]
deps = ["LinearAlgebra", "Statistics", "StatsAPI"]
git-tree-sha1 = "9f46deb4d4ee4494ffb5a40a27a2aced67bdd838"
uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7"
version = "0.10.4"
[[Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[Distributions]]
deps = ["ChainRulesCore", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns"]
git-tree-sha1 = "f4efaa4b5157e0cdb8283ae0b5428bc9208436ed"
uuid = "31c24e10-a181-5473-b8eb-7969acd0382f"
version = "0.25.16"
[[DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "a32185f5428d3986f47c2ab78b1f216d5e6cc96f"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.8.5"
[[Downloads]]
deps = ["ArgTools", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
[[EarCut_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3f3a2501fa7236e9b911e0f7a588c657e822bb6d"
uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5"
version = "2.2.3+0"
[[Effects]]
deps = ["DataFrames", "LinearAlgebra", "Statistics", "StatsBase", "StatsModels", "Tables"]
git-tree-sha1 = "989a9cb80952d2d3d36bccbe7c0001fd9ef5dfa2"
uuid = "8f03c58b-bd97-4933-a826-f71b64d2cca2"
version = "0.1.2"
[[EllipsisNotation]]
deps = ["ArrayInterface"]
git-tree-sha1 = "8041575f021cba5a099a456b4163c9a08b566a02"
uuid = "da5c29d0-fa7d-589e-88eb-ea29b0a81949"
version = "1.1.0"
[[Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b3bfd02e98aedfa5cf885665493c5598c350cd2f"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.2.10+0"
[[ExprTools]]
git-tree-sha1 = "b7e3d17636b348f005f11040025ae8c6f645fe92"
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
version = "0.1.6"
[[FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"
[[FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "Pkg", "Zlib_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "d8a578692e3077ac998b50c0217dfd67f21d1e5f"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.0+0"
[[FFTW]]
deps = ["AbstractFFTs", "FFTW_jll", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"]
git-tree-sha1 = "f985af3b9f4e278b1d24434cbb546d6092fca661"
uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341"
version = "1.4.3"
[[FFTW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3676abafff7e4ff07bbd2c42b3d8201f31653dcc"
uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a"
version = "3.3.9+8"
[[FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "937c29268e405b6808d958a9ac41bfe1a31b08e7"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.11.0"
[[FilePathsBase]]
deps = ["Dates", "Mmap", "Printf", "Test", "UUIDs"]
git-tree-sha1 = "0f5e8d0cb91a6386ba47bd1527b240bd5725fbae"
uuid = "48062228-2e41-5def-b9a4-89aafe57970f"
version = "0.9.10"
[[FillArrays]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "Statistics"]
git-tree-sha1 = "a3b7b041753094f3b17ffa9d2e2e07d8cace09cd"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "0.12.3"
[[FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[Fontconfig_jll]]
deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "21efd19106a55620a188615da6d3d06cd7f6ee03"
uuid = "a3f928ae-7b40-5064-980b-68af3947d34b"
version = "2.13.93+0"
[[Formatting]]
deps = ["Printf"]
git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8"
uuid = "59287772-0a20-5a39-b81b-1366585eb4c0"
version = "0.4.2"
[[FreeType]]
deps = ["CEnum", "FreeType2_jll"]
git-tree-sha1 = "cabd77ab6a6fdff49bfd24af2ebe76e6e018a2b4"
uuid = "b38be410-82b0-50bf-ab77-7b57e271db43"
version = "4.0.0"
[[FreeType2_jll]]
deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "87eb71354d8ec1a96d4a7636bd57a7347dde3ef9"
uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7"
version = "2.10.4+0"
[[FreeTypeAbstraction]]
deps = ["ColorVectorSpace", "Colors", "FreeType", "GeometryBasics", "StaticArrays"]
git-tree-sha1 = "19d0f1e234c13bbfd75258e55c52aa1d876115f5"
uuid = "663a7486-cb36-511b-a19d-713bb74d65c9"
version = "0.9.2"
[[FriBidi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91"
uuid = "559328eb-81f9-559d-9380-de523a88c83c"
version = "1.0.10+0"
[[Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
[[GLM]]
deps = ["Distributions", "LinearAlgebra", "Printf", "Reexport", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns", "StatsModels"]
git-tree-sha1 = "f564ce4af5e79bb88ff1f4488e64363487674278"
uuid = "38e38edf-8417-5370-95a0-9cbb8c7f171a"
version = "1.5.1"
[[GeoInterface]]
deps = ["RecipesBase"]
git-tree-sha1 = "38a649e6a52d1bea9844b382343630ac754c931c"
uuid = "cf35fbd7-0cd7-5166-be24-54bfbe79505f"
version = "0.5.5"
[[GeometryBasics]]
deps = ["EarCut_jll", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"]
git-tree-sha1 = "58bcdf5ebc057b085e58d95c138725628dd7453c"
uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
version = "0.4.1"
[[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"
[[Glib_jll]]
deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "7bf67e9a481712b3dbe9cb3dac852dc4b1162e02"
uuid = "7746bdde-850d-59dc-9ae8-88ece973131d"
version = "2.68.3+0"
[[Graphics]]
deps = ["Colors", "LinearAlgebra", "NaNMath"]
git-tree-sha1 = "2c1cf4df419938ece72de17f368a021ee162762e"
uuid = "a2bd30eb-e257-5431-a919-1863eab51364"
version = "1.1.0"
[[Graphite2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "344bf40dcab1073aca04aa0df4fb092f920e4011"
uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472"
version = "1.3.14+0"
[[GridLayoutBase]]
deps = ["GeometryBasics", "InteractiveUtils", "Match", "Observables"]
git-tree-sha1 = "e2f606c87d09d5187bb6069dab8cee0af7c77bdb"
uuid = "3955a311-db13-416c-9275-1d80ed98e5e9"
version = "0.6.1"
[[Grisu]]
git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2"
uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe"
version = "1.0.2"
[[HarfBuzz_jll]]
deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg"]
git-tree-sha1 = "8a954fed8ac097d5be04921d595f741115c1b2ad"
uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566"
version = "2.8.1+0"
[[IfElse]]
git-tree-sha1 = "28e837ff3e7a6c3cdb252ce49fb412c8eb3caeef"
uuid = "615f187c-cbe4-4ef1-ba3b-2fcf58d6d173"
version = "0.1.0"
[[ImageCore]]
deps = ["AbstractFFTs", "Colors", "FixedPointNumbers", "Graphics", "MappedArrays", "MosaicViews", "OffsetArrays", "PaddedViews", "Reexport"]
git-tree-sha1 = "db645f20b59f060d8cfae696bc9538d13fd86416"
uuid = "a09fc81d-aa75-5fe9-8630-4744c3626534"
version = "0.8.22"
[[ImageIO]]
deps = ["FileIO", "Netpbm", "PNGFiles"]
git-tree-sha1 = "0d6d09c28d67611c68e25af0c2df7269c82b73c7"
uuid = "82e4d734-157c-48bb-816b-45c225c6df19"
version = "0.4.1"
[[IndirectArrays]]
git-tree-sha1 = "012e604e1c7458645cb8b436f8fba789a51b257f"
uuid = "9b13fd28-a010-5f03-acff-a1bbcff69959"
version = "1.0.0"
[[IntelOpenMP_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "d979e54b71da82f3a65b62553da4fc3d18c9004c"
uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0"
version = "2018.0.3+2"
[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[Interpolations]]
deps = ["AxisAlgorithms", "ChainRulesCore", "LinearAlgebra", "OffsetArrays", "Random", "Ratios", "Requires", "SharedArrays", "SparseArrays", "StaticArrays", "WoodburyMatrices"]
git-tree-sha1 = "61aa005707ea2cebf47c8d780da8dc9bc4e0c512"
uuid = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59"
version = "0.13.4"
[[IntervalSets]]
deps = ["Dates", "EllipsisNotation", "Statistics"]
git-tree-sha1 = "3cc368af3f110a767ac786560045dceddfc16758"
uuid = "8197267c-284f-5f27-9208-e0e47529a953"
version = "0.5.3"
[[InvertedIndices]]
git-tree-sha1 = "bee5f1ef5bf65df56bdd2e40447590b272a5471f"
uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f"
version = "1.1.0"
[[IrrationalConstants]]
git-tree-sha1 = "f76424439413893a832026ca355fe273e93bce94"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.1.0"
[[Isoband]]
deps = ["isoband_jll"]
git-tree-sha1 = "f9b6d97355599074dc867318950adaa6f9946137"
uuid = "f1662d9f-8043-43de-a69a-05efc1cc6ff4"
version = "0.1.1"
[[IterTools]]
git-tree-sha1 = "05110a2ab1fc5f932622ffea2a003221f4782c18"
uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
version = "1.3.0"
[[IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "642a199af8b68253517b80bd3bfd17eb4e84df6e"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.3.0"
[[JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.2"
[[JSON3]]
deps = ["Dates", "Mmap", "Parsers", "StructTypes", "UUIDs"]
git-tree-sha1 = "b3e5984da3c6c95bcf6931760387ff2e64f508f3"
uuid = "0f8b85d8-7281-11e9-16c2-39a750bddbf1"
version = "1.9.1"
[[KernelDensity]]
deps = ["Distributions", "DocStringExtensions", "FFTW", "Interpolations", "StatsBase"]
git-tree-sha1 = "591e8dc09ad18386189610acafb970032c519707"
uuid = "5ab0869b-81aa-558d-bb23-cbf5423bbe9b"
version = "0.6.3"
[[LAME_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "f6250b16881adf048549549fba48b1161acdac8c"
uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d"
version = "3.100.1+0"
[[LZO_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e5b909bcf985c5e2605737d2ce278ed791b89be6"
uuid = "dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac"
version = "2.10.1+0"
[[LaTeXStrings]]
git-tree-sha1 = "c7f1c695e06c01b95a67f0cd1d34994f3e7db104"
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
version = "1.2.1"
[[LazyArtifacts]]
deps = ["Artifacts", "Pkg"]
uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3"
[[LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
[[LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
[[LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
[[Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[Libffi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "761a393aeccd6aa92ec3515e428c26bf99575b3b"
uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490"
version = "3.2.2+0"
[[Libgcrypt_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll", "Pkg"]
git-tree-sha1 = "64613c82a59c120435c067c2b809fc61cf5166ae"
uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4"
version = "1.8.7+0"
[[Libgpg_error_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c333716e46366857753e273ce6a69ee0945a6db9"
uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8"
version = "1.42.0+0"
[[Libiconv_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "42b62845d70a619f063a7da093d995ec8e15e778"
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
version = "1.16.1+1"
[[Libmount_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "9c30530bf0effd46e15e0fdcf2b8636e78cbbd73"
uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9"
version = "2.35.0+0"
[[Libuuid_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7f3efec06033682db852f8b3bc3c1d2b0a0ab066"
uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700"
version = "2.36.0+0"
[[LinearAlgebra]]
deps = ["Libdl"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[Loess]]
deps = ["Distances", "LinearAlgebra", "Statistics"]
git-tree-sha1 = "b5254a86cf65944c68ed938e575f5c81d5dfe4cb"
uuid = "4345ca2d-374a-55d4-8d30-97f9976e7612"
version = "0.5.3"
[[LogExpFunctions]]
deps = ["ChainRulesCore", "DocStringExtensions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "86197a8ecb06e222d66797b0c2d2f0cc7b69e42b"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.2"
[[Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[Lz4_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "5d494bc6e85c4c9b626ee0cab05daa4085486ab1"
uuid = "5ced341a-0733-55b8-9ab6-a4889d929147"
version = "1.9.3+0"
[[MKL_jll]]
deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "Pkg"]
git-tree-sha1 = "c253236b0ed414624b083e6b72bfe891fbd2c7af"
uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7"
version = "2021.1.1+1"
[[Makie]]
deps = ["Animations", "Base64", "ColorBrewer", "ColorSchemes", "ColorTypes", "Colors", "Contour", "Distributions", "DocStringExtensions", "FFMPEG", "FileIO", "FixedPointNumbers", "Formatting", "FreeType", "FreeTypeAbstraction", "GeometryBasics", "GridLayoutBase", "ImageIO", "IntervalSets", "Isoband", "KernelDensity", "LaTeXStrings", "LinearAlgebra", "MakieCore", "Markdown", "Match", "MathTeXEngine", "Observables", "Packing", "PlotUtils", "PolygonOps", "Printf", "Random", "RelocatableFolders", "Serialization", "Showoff", "SignedDistanceFields", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "StatsFuns", "StructArrays", "UnicodeFun"]
git-tree-sha1 = "7e49f989e7c7f50fe55bd92d45329c9cf3f2583d"
uuid = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a"
version = "0.15.2"
[[MakieCore]]
deps = ["Observables"]
git-tree-sha1 = "7bcc8323fb37523a6a51ade2234eee27a11114c8"
uuid = "20f20a25-4f0e-4fdf-b5d1-57303727442b"
version = "0.1.3"
[[MappedArrays]]
git-tree-sha1 = "e8b359ef06ec72e8c030463fe02efe5527ee5142"
uuid = "dbb5928d-eab1-5f90-85c2-b9b0edb7c900"
version = "0.4.1"
[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[Match]]
git-tree-sha1 = "5cf525d97caf86d29307150fcba763a64eaa9cbe"
uuid = "7eb4fadd-790c-5f42-8a69-bfa0b872bfbf"
version = "1.1.0"
[[MathOptInterface]]
deps = ["BenchmarkTools", "CodecBzip2", "CodecZlib", "JSON", "LinearAlgebra", "MutableArithmetics", "OrderedCollections", "Printf", "SparseArrays", "Test", "Unicode"]
git-tree-sha1 = "debba84c7060716b0737504b59aabe976c9b91cb"
uuid = "b8f27783-ece8-5eb3-8dc8-9495eed66fee"
version = "0.10.0"
[[MathProgBase]]
deps = ["LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "9abbe463a1e9fc507f12a69e7f29346c2cdc472c"
uuid = "fdba3010-5040-5b88-9595-932c9decdf73"
version = "0.7.8"
[[MathTeXEngine]]
deps = ["AbstractTrees", "Automa", "DataStructures", "FreeTypeAbstraction", "GeometryBasics", "LaTeXStrings", "REPL", "RelocatableFolders", "Test"]
git-tree-sha1 = "f5c8789464aed7058107463e5cef53e6ad3f1f3e"
uuid = "0a4f8689-d25c-4efe-a92b-7142dfc1aa53"
version = "0.2.0"
[[MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
[[Missings]]
deps = ["DataAPI"]
git-tree-sha1 = "2ca267b08821e86c5ef4376cffed98a46c2cb205"
uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28"
version = "1.0.1"
[[MixedModels]]
deps = ["Arrow", "DataAPI", "Distributions", "GLM", "JSON3", "LazyArtifacts", "LinearAlgebra", "Markdown", "NLopt", "PooledArrays", "ProgressMeter", "Random", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "StatsFuns", "StatsModels", "StructTypes", "Tables"]
git-tree-sha1 = "f318e42a48ec0a856292bafeec6b07aed3f6d600"
uuid = "ff71e718-51f3-5ec2-a782-8ffcbfa3c316"
version = "4.1.1"
[[MixedModelsExtras]]
deps = ["MixedModels", "Statistics", "StatsBase"]
git-tree-sha1 = "3b01c97c288924fd67958ab12b8a5ea541edc5e5"
uuid = "781a26e1-49f4-409a-8f4c-c3159d78c17e"
version = "0.1.2"
[[MixedModelsMakie]]
deps = ["DataFrames", "Distributions", "KernelDensity", "LinearAlgebra", "Makie", "MixedModels", "Printf", "SpecialFunctions", "StatsBase"]
git-tree-sha1 = "e2ae99b3b4675ddc91e9c421a775eff52a784696"
uuid = "b12ae82c-6730-437f-aff9-d2c38332a376"
version = "0.3.8"
[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[Mocking]]
deps = ["ExprTools"]
git-tree-sha1 = "748f6e1e4de814b101911e64cc12d83a6af66782"
uuid = "78c3b35d-d492-501b-9361-3d52fe80e533"
version = "0.7.2"
[[MosaicViews]]
deps = ["MappedArrays", "OffsetArrays", "PaddedViews", "StackViews"]
git-tree-sha1 = "b34e3bc3ca7c94914418637cb10cc4d1d80d877d"
uuid = "e94cdb99-869f-56ef-bcf0-1ae2bcbe0389"
version = "0.3.3"
[[MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
[[MutableArithmetics]]
deps = ["LinearAlgebra", "SparseArrays", "Test"]
git-tree-sha1 = "3927848ccebcc165952dc0d9ac9aa274a87bfe01"
uuid = "d8a4904e-b15c-11e9-3269-09a3773c0cb0"
version = "0.2.20"
[[NLopt]]
deps = ["MathOptInterface", "MathProgBase", "NLopt_jll"]
git-tree-sha1 = "f115030b9325ca09ef1619ba0617b2a64101ce84"
uuid = "76087f3c-5699-56af-9a33-bf431cd00edd"
version = "0.6.4"
[[NLopt_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "2b597c46900f5f811bec31f0dcc88b45744a2a09"
uuid = "079eb43e-fd8e-5478-9966-2cf3e3edb778"
version = "2.7.0+0"
[[NaNMath]]
git-tree-sha1 = "bfe47e760d60b82b66b61d2d44128b62e3a369fb"
uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
version = "0.3.5"
[[Netpbm]]
deps = ["ColorVectorSpace", "FileIO", "ImageCore"]
git-tree-sha1 = "09589171688f0039f13ebe0fdcc7288f50228b52"
uuid = "f09324ee-3d7c-5217-9330-fc30815ba969"
version = "1.0.1"
[[NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
[[Observables]]
git-tree-sha1 = "fe29afdef3d0c4a8286128d4e45cc50621b1e43d"
uuid = "510215fc-4207-5dde-b226-833fc4488ee2"
version = "0.4.0"
[[OffsetArrays]]
deps = ["Adapt"]
git-tree-sha1 = "c870a0d713b51e4b49be6432eff0e26a4325afee"
uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881"
version = "1.10.6"
[[Ogg_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f"
uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051"
version = "1.3.5+0"
[[OpenSSL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "15003dcb7d8db3c6c857fda14891a539a8f2705a"
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
version = "1.1.10+0"
[[OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"
[[Opus_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "51a08fb14ec28da2ec7a927c4337e4332c2a4720"
uuid = "91d4177d-7536-5919-b921-800302f37372"
version = "1.3.2+0"
[[OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"
[[PCRE_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b2a7af664e098055a7529ad1a900ded962bca488"
uuid = "2f80f16e-611a-54ab-bc61-aa92de5b98fc"
version = "8.44.0+0"
[[PDMats]]
deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "4dd403333bcf0909341cfe57ec115152f937d7d8"
uuid = "90014a1f-27ba-587c-ab20-58faa44d9150"
version = "0.11.1"
[[PNGFiles]]
deps = ["Base64", "CEnum", "ImageCore", "IndirectArrays", "OffsetArrays", "libpng_jll"]
git-tree-sha1 = "e14c485f6beee0c7a8dcf6128bf70b85f1fe201e"
uuid = "f57f5aa1-a3ce-4bc8-8ab9-96f992907883"
version = "0.3.9"
[[Packing]]
deps = ["GeometryBasics"]
git-tree-sha1 = "1155f6f937fa2b94104162f01fa400e192e4272f"
uuid = "19eb6ba3-879d-56ad-ad62-d5c202156566"
version = "0.4.2"
[[PaddedViews]]
deps = ["OffsetArrays"]
git-tree-sha1 = "646eed6f6a5d8df6708f15ea7e02a7a2c4fe4800"
uuid = "5432bcbf-9aad-5242-b902-cca2824c8663"
version = "0.5.10"
[[Pango_jll]]
deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "9bc1871464b12ed19297fbc56c4fb4ba84988b0d"
uuid = "36c8627f-9965-5494-a995-c6b170f724f3"
version = "1.47.0+0"
[[Parsers]]
deps = ["Dates"]
git-tree-sha1 = "438d35d2d95ae2c5e8780b330592b6de8494e779"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.0.3"
[[Pixman_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b4f5d02549a10e20780a24fce72bea96b6329e29"
uuid = "30392449-352a-5448-841d-b1acce4e97dc"
version = "0.40.1+0"
[[Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
[[PlotUtils]]
deps = ["ColorSchemes", "Colors", "Dates", "Printf", "Random", "Reexport", "Statistics"]
git-tree-sha1 = "9ff1c70190c1c30aebca35dc489f7411b256cd23"
uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043"
version = "1.0.13"
[[PlutoUI]]
deps = ["Base64", "Dates", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "Suppressor"]
git-tree-sha1 = "44e225d5837e2a2345e69a1d1e01ac2443ff9fcb"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.9"
[[PolygonOps]]
git-tree-sha1 = "c031d2332c9a8e1c90eca239385815dc271abb22"
uuid = "647866c9-e3ac-4575-94e7-e3d426903924"
version = "0.1.1"
[[PooledArrays]]
deps = ["DataAPI", "Future"]
git-tree-sha1 = "a193d6ad9c45ada72c14b731a318bedd3c2f00cf"
uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720"
version = "1.3.0"
[[Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00cfd92944ca9c760982747e9a1d0d5d86ab1e5a"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.2.2"
[[PrettyTables]]
deps = ["Crayons", "Formatting", "Markdown", "Reexport", "Tables"]
git-tree-sha1 = "0d1245a357cc61c8cd61934c07447aa569ff22e6"
uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d"
version = "1.1.0"
[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[ProgressMeter]]
deps = ["Distributed", "Printf"]
git-tree-sha1 = "afadeba63d90ff223a6a48d2009434ecee2ec9e8"
uuid = "92933f4c-e287-5a05-a399-4b506db050ca"
version = "1.7.1"
[[QuadGK]]
deps = ["DataStructures", "LinearAlgebra"]
git-tree-sha1 = "12fbe86da16df6679be7521dfb39fbc861e1dc7b"
uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc"
version = "2.4.1"
[[REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[Random]]
deps = ["Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[Ratios]]
deps = ["Requires"]
git-tree-sha1 = "7dff99fbc740e2f8228c6878e2aad6d7c2678098"
uuid = "c84ed2f1-dad5-54f0-aa8e-dbefe2724439"
version = "0.4.1"
[[RecipesBase]]
git-tree-sha1 = "44a75aa7a527910ee3d1751d1f0e4148698add9e"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.1.2"
[[Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[RelocatableFolders]]
deps = ["SHA", "Scratch"]
git-tree-sha1 = "0529f4188bc8efee85a7e580aca1c7dff6b103f8"
uuid = "05181044-ff0b-4ac5-8273-598c1e38db00"
version = "0.1.0"
[[Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.1.3"
[[Rmath]]
deps = ["Random", "Rmath_jll"]
git-tree-sha1 = "bf3188feca147ce108c76ad82c2792c57abe7b1f"
uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa"
version = "0.7.0"
[[Rmath_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "68db32dff12bb6127bac73c209881191bf0efbb7"
uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f"
version = "0.3.0+0"
[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
[[SIMD]]
git-tree-sha1 = "9ba33637b24341aba594a2783a502760aa0bff04"
uuid = "fdea26ae-647d-5447-a871-4b548cad5224"
version = "3.3.1"
[[ScanByte]]
deps = ["Libdl", "SIMD"]
git-tree-sha1 = "9cc2955f2a254b18be655a4ee70bc4031b2b189e"
uuid = "7b38b023-a4d7-4c5e-8d43-3f3097f304eb"
version = "0.3.0"
[[Scratch]]
deps = ["Dates"]
git-tree-sha1 = "0b4b7f1393cff97c33891da2a0bf69c6ed241fda"
uuid = "6c6a2e73-6563-6170-7368-637461726353"
version = "1.1.0"
[[SentinelArrays]]
deps = ["Dates", "Random"]
git-tree-sha1 = "54f37736d8934a12a200edea2f9206b03bdf3159"
uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c"
version = "1.3.7"
[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"
[[ShiftedArrays]]
git-tree-sha1 = "22395afdcf37d6709a5a0766cc4a5ca52cb85ea0"
uuid = "1277b4bf-5013-50f5-be3d-901d8477a67a"
version = "1.0.0"
[[Showoff]]
deps = ["Dates", "Grisu"]
git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de"
uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f"
version = "1.0.3"
[[SignedDistanceFields]]
deps = ["Random", "Statistics", "Test"]
git-tree-sha1 = "d263a08ec505853a5ff1c1ebde2070419e3f28e9"
uuid = "73760f76-fbc4-59ce-8f25-708e95d2df96"
version = "0.4.0"
[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[SortingAlgorithms]]
deps = ["DataStructures"]
git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508"
uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c"
version = "1.0.1"
[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[SpecialFunctions]]
deps = ["ChainRulesCore", "LogExpFunctions", "OpenSpecFun_jll"]
git-tree-sha1 = "a322a9493e49c5f3a10b50df3aedaf1cdb3244b7"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "1.6.1"
[[StackViews]]
deps = ["OffsetArrays"]
git-tree-sha1 = "46e589465204cd0c08b4bd97385e4fa79a0c770c"
uuid = "cae243ae-269e-4f55-b966-ac2d0dc13c15"
version = "0.1.1"
[[Static]]
deps = ["IfElse"]
git-tree-sha1 = "854b024a4a81b05c0792a4b45293b85db228bd27"
uuid = "aedffcd0-7271-4cad-89d0-dc628f76c6d3"
version = "0.3.1"
[[StaticArrays]]
deps = ["LinearAlgebra", "Random", "Statistics"]
git-tree-sha1 = "3240808c6d463ac46f1c1cd7638375cd22abbccb"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.2.12"
[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[StatsAPI]]
git-tree-sha1 = "1958272568dc176a1d881acb797beb909c785510"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.0.0"
[[StatsBase]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
git-tree-sha1 = "8cbbc098554648c84f79a463c9ff0fd277144b6c"
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
version = "0.33.10"
[[StatsFuns]]
deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"]
git-tree-sha1 = "46d7ccc7104860c38b11966dd1f72ff042f382e4"
uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c"
version = "0.9.10"
[[StatsModels]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "Printf", "ShiftedArrays", "SparseArrays", "StatsBase", "StatsFuns", "Tables"]
git-tree-sha1 = "3fa15c1f8be168e76d59097f66970adc86bfeb95"
uuid = "3eaba693-59b7-5ba5-a881-562e759f1c8d"
version = "0.6.25"
[[StructArrays]]
deps = ["Adapt", "DataAPI", "StaticArrays", "Tables"]
git-tree-sha1 = "1700b86ad59348c0f9f68ddc95117071f947072d"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.1"
[[StructTypes]]
deps = ["Dates", "UUIDs"]
git-tree-sha1 = "8445bf99a36d703a09c601f9a57e2f83000ef2ae"
uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4"
version = "1.7.3"
[[SuiteSparse]]
deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"]
uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9"
[[Suppressor]]
git-tree-sha1 = "a819d77f31f83e5792a76081eee1ea6342ab8787"
uuid = "fd094767-a336-5f1f-9728-57cf17d0bbfb"
version = "0.2.0"
[[TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
[[TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"]
git-tree-sha1 = "368d04a820fe069f9080ff1b432147a6203c3c89"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.5.1"
[[Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
[[Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[TimeZones]]
deps = ["Dates", "Future", "LazyArtifacts", "Mocking", "Pkg", "Printf", "RecipesBase", "Serialization", "Unicode"]
git-tree-sha1 = "6c9040665b2da00d30143261aea22c7427aada1c"
uuid = "f269a46b-ccf7-5d73-abea-4c690281aa53"
version = "1.5.7"
[[TranscodingStreams]]
deps = ["Random", "Test"]
git-tree-sha1 = "216b95ea110b5972db65aa90f88d8d89dcb8851c"
uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
version = "0.9.6"
[[UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[UnicodeFun]]
deps = ["REPL"]
git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf"
uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1"
version = "0.4.1"
[[WeakRefStrings]]
deps = ["DataAPI", "Parsers", "Random", "Serialization", "Test"]
git-tree-sha1 = "4cd606838f91a9c3c7404df41173e132bdb09e82"
uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5"
version = "1.2.2"
[[WoodburyMatrices]]
deps = ["LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "59e2ad8fd1591ea019a5259bd012d7aee15f995c"
uuid = "efce3f68-66dc-5838-9240-27a6d6f5f9b6"
version = "0.5.3"
[[XML2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "1acf5bdf07aa0907e0a37d3718bb88d4b687b74a"
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
version = "2.9.12+0"
[[XSLT_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "Pkg", "XML2_jll", "Zlib_jll"]
git-tree-sha1 = "91844873c4085240b95e795f692c4cec4d805f8a"
uuid = "aed1982a-8fda-507f-9586-7b0439959a61"
version = "1.1.34+0"
[[Xorg_libX11_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll", "Xorg_xtrans_jll"]
git-tree-sha1 = "5be649d550f3f4b95308bf0183b82e2582876527"
uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc"
version = "1.6.9+4"
[[Xorg_libXau_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4e490d5c960c314f33885790ed410ff3a94ce67e"
uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec"
version = "1.0.9+4"
[[Xorg_libXdmcp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fe47bd2247248125c428978740e18a681372dd4"
uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05"
version = "1.1.3+4"
[[Xorg_libXext_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "b7c0aa8c376b31e4852b360222848637f481f8c3"
uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3"
version = "1.3.4+4"
[[Xorg_libXrender_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "19560f30fd49f4d4efbe7002a1037f8c43d43b96"
uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa"
version = "0.9.10+4"
[[Xorg_libpthread_stubs_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "6783737e45d3c59a4a4c4091f5f88cdcf0908cbb"
uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74"
version = "0.1.0+3"
[[Xorg_libxcb_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"]
git-tree-sha1 = "daf17f441228e7a3833846cd048892861cff16d6"
uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b"
version = "1.13.0+3"
[[Xorg_xtrans_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "79c31e7844f6ecf779705fbc12146eb190b7d845"
uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10"
version = "1.4.0+3"
[[Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
[[Zstd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6"
uuid = "3161d3a3-bdf6-5164-811a-617609db77b4"
version = "1.5.0+0"
[[isoband_jll]]
deps = ["Libdl", "Pkg"]
git-tree-sha1 = "a1ac99674715995a536bbce674b068ec1b7d893d"
uuid = "9a68df92-36a6-505f-a73e-abb412b6bfb4"
version = "0.2.2+0"
[[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"
[[libfdk_aac_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "daacc84a041563f965be61859a36e17c4e4fcd55"
uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280"
version = "2.0.2+0"
[[libpng_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "94d180a6d2b5e55e447e2d27a29ed04fe79eb30c"
uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f"
version = "1.6.38+0"
[[libvorbis_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll", "Pkg"]
git-tree-sha1 = "c45f4e40e7aafe9d086379e5578947ec8b95a8fb"
uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a"
version = "1.3.7+0"
[[nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
[[p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
[[x264_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fea590b89e6ec504593146bf8b988b2c00922b2"
uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a"
version = "2021.5.5+0"
[[x265_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "ee567a171cce03570d77ad3a43e90218e38937a9"
uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76"
version = "3.5.0+0"
"""
# ╔═╡ Cell order:
# ╟─16199f57-4b1a-4f75-a247-a3d153d01e5c
# ╠═5d7dc2d4-1008-11ec-2ea6-ffc13cf6dbf7
# ╟─df9273de-28e0-42ca-8e7d-8d2fe1b9be2d
# ╠═99546f56-7c64-4cf5-98ce-0ed48896b82c
# ╠═11cb62b7-6736-47de-8c91-67b858747004
# ╠═5aa0776d-3b03-4910-a2b7-e51c7404e1ee
# ╟─d8d7d67a-d2aa-4fb7-8cea-f69c60de2326
# ╠═c4a027a1-902f-48bc-8009-71653f766e8d
# ╠═88c9b542-448e-4a91-a985-24e4e8b863f5
# ╠═09a4adef-0d8b-4242-885b-e8dfb6d5b756
# ╠═fab68835-d889-4bde-ad2a-80e5dc6b1983
# ╠═092c77a2-37aa-4c78-906a-322b61308b34
# ╟─9fd0c2d7-109d-4fe3-a0c6-a75839799cb7
# ╠═fd153bbb-5273-4b36-a111-2d34137b10bd
# ╠═06703b73-e491-4112-a59d-28d2e477d0a6
# ╟─22e90698-2dd6-4cf3-a694-a0fabd2a0302
# ╠═60fed847-bd2c-4896-a43a-d5cca63786d3
# ╠═d98f7985-2c65-46e4-a356-d9cb57c2b829
# ╠═34151154-5ecb-4651-b519-0cb006de1d15
# ╟─ea9a452a-086d-437d-9ada-47f7cbd5398c
# ╠═d6887601-3f49-48b1-b527-59849fc59908
# ╠═79152bfc-b75b-4aaf-bbf6-2fe14a24d315
# ╠═5299c521-e359-4e5d-ace3-73766a323b1d
# ╠═2891251e-e32f-4654-9243-296f6206429c
# ╠═f77aa540-579e-4367-a1ab-b863a8d015d9
# ╟─0d204adc-5a4c-4276-ba83-690178bc570c
# ╠═14b559e6-4e2a-43e3-ad92-4d90342c8835
# ╠═02de86be-40ea-4b62-8e54-c7529e57fa31
# ╠═54e69118-d930-49ba-9bd7-afbf614dda75
# ╠═18a6b29b-94b4-46e6-8242-45dbea143700
# ╠═d223139b-f209-4495-ad6a-69e91f524690
# ╟─2c2c3b51-426d-41ec-acad-7e6c1e6fae48
# ╠═3198e0c5-588e-4bcd-bb62-ecba0ca129a2
# ╠═4d14f8a6-17b1-406d-8f4c-1199ee0f9966
# ╠═f2a1b2d0-7bae-4ab6-a287-e42d02e01383
# ╠═b16e6a8d-db29-4cc6-911b-3ebb3c8f71c0
# ╠═ee60825b-808f-49da-9dd8-824aa85d2c76
# ╟─9f4c72f1-aa01-4666-b07b-e2fb1f0cacb3
# ╠═fce2e257-897f-487b-b0e3-fb5942820ed2
# ╟─e4d72691-6d31-47e5-b1e0-630571988330
# ╠═e062623c-9dee-49f3-8f8a-362d0073eb60
# ╠═9533ef07-6e79-4f17-8626-cc85413957b9
# ╠═cb5aafb6-a724-428f-aa15-22ed30b42b08
# ╠═12ce0e46-fb15-4396-84d7-212c5d850423
# ╠═8f073561-8b51-4a6d-b08d-225821bf7d56
# ╠═23d494fd-52cb-4679-a186-c6d795299a97
# ╠═fd193833-b163-4182-a85b-84085c747f71
# ╠═1a36289a-4b08-4aed-adbb-de4dea5e504f
# ╠═cf4d7b94-abf0-4338-b72a-f60aaefe9a90
# ╠═0aef95c5-0e48-4ff7-b8a3-58d4e8c94c0b
# ╠═6acc4e05-d650-40ca-abf9-9cccd401ed45
# ╠═32d56757-1e1b-43dd-a9aa-83b5177172e9
# ╠═78090450-7373-4824-bfe9-1283e971dda0
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
|
"""
F = JopNormalize(spc, c)
where `F` is the 'normalize by maximuam value of integral' operator F(t) = x(t) / int_0^T [ x(t) dt ]
Note the integration is along the 1st (fastest) dimension.
"""
function JopNormalize(spc::JetSpace{T}; α=1.0) where {T}
tmp1 = zeros(spc)
tmp2 = zeros(spc)
A = JopLeakyIntegration(spc, α=α)
JopNl(dom = spc, rng = spc, f! = JopNormalize_f!, df! = JopNormalize_df!, df′! = JopNormalize_df′!, s = (tmp1=tmp1, tmp2=tmp2, A=A))
end
export JopNormalize
function JopNormalize_f!(d::AbstractArray, m::AbstractArray; tmp1, tmp2, A)
d .= m ./ sum(m, dims=1)
end
# For normalized integral method:
# f = I[m] / I_t[m]
# df = [ I[m]' I_t[m] - I[m] I_t[m]' ] / I_t[m]^2
# df = (I_t[m] I[dm] - I_t[dm] I[m]) / (I_t[m])^2
# dfᵀ = (I_t[m] Iᵀ[δd] - I_tᵀ[mᵀ Iᵀ δd]) / (I_t[m])^2
#
# For normalization only:
# f = m / I_t[m]
# df = [ m' I_t[m] - m I_t[m]' ] / I_t[m]^2
# df = ( I_t[m] dm - I_t[dm] m) / (I_t[m])^2
# dfᵀ = (I_t[m] δd - I_tᵀ[mᵀ δd]) / (I_t[m])^2
function JopNormalize_df!(δd::AbstractArray{T}, δm::AbstractArray{T}; mₒ, tmp1, tmp2, A) where {T}
δd .= (sum(mₒ,dims=1) .* δm .- sum(δm,dims=1) .* mₒ) ./ sum(mₒ,dims=1).^2
end
function JopNormalize_df′!(δm::AbstractArray{T}, δd::AbstractArray{T}; mₒ, tmp1, tmp2, A) where {T}
δm .= conj.((sum(mₒ,dims=1) .* conj.(δd) .- sum(mₒ .* conj.(δd),dims=1)) ./ sum(mₒ,dims=1).^2)
end
|
module GLMPriors
using SparseArrays, LinearAlgebra
export ridge_prior, smoothing_prior, null_prior, get_prior!, get_lambda, nlambda
export allocate_prior, AbstractPrior
const SPMat = SparseMatrixCSC{Float64,Int}
# ============================================================================ #
abstract type AbstractPrior{N,T} end
struct GLMPrior{N,T} <: AbstractPrior{N,T}
d::SPMat
filter_len::NTuple{N,Int}
lambda::NTuple{T,Vector{Float64}}
lambda_len::NTuple{T,Int}
end
function GLMPrior{N,T}(d::SPMat, x::NTuple{N,<:Integer},
lm::NTuple{T,AbstractVector{<:Real}}) where {N,T}
if ((T < N) && T != 1)
error("Invalid number of lambda parameters")
elseif T >= N
T2 = N
else
T2 = T
end
return GLMPrior{N,T2}(d, x, lm[1:T2], map(length, lm[1:T2]))
end
# ============================================================================ #
struct NullPrior{N} <: AbstractPrior{N, 0}
filter_len::NTuple{N,Int}
end
# ============================================================================ #
struct LassoPrior{N,T} <: AbstractPrior{N,T}
filter_len::NTuple{N,Int}
lambda::NTuple{T,Vector{Float64}}
lambda_len::NTuple{T,Int}
end
struct Lasso{T<:Real}
x::Vector{T}
end
Base.:*(v::AbstractArray{<:Number}, l::Lasso) = sign.(v) .* reshape(l.x, size(v))
Base.:*(l::Lasso, v::AbstractArray{<:Number}) = sign.(v) .* reshape(l.x, size(v))
# ============================================================================ #
@inline nlambda(gp::GLMPrior{N,T}) where {N,T} = T
@inline nlambda(gp::NullPrior) = 0
@inline nlambda(gp::LassoPrior{N,T}) where {N,T} = T
# ---------------------------------------------------------------------------- #
@inline Base.length(gp::AbstractPrior) = prod(gp.lambda_len)
@inline Base.length(gp::NullPrior) = 1
# ---------------------------------------------------------------------------- #
function get_prior!(x::SPMat, gp::NullPrior, k::Integer)
knz = findall(!iszero, x)
x[knz] .= 0.0
return x
end
# ---------------------------------------------------------------------------- #
function get_prior!(x::SPMat, gp::GLMPrior{N,T}, k::Integer) where {N,T}
kstart = 0
kend = 1
kp = CartesianIndices(gp.lambda_len)[k]
inc = 1
for kl in (T < N ? fill(1, N) : 1:N)
kstart = kend + 1
kend = kstart + gp.filter_len[inc] - 1
slice = kstart:kend
x[:, slice] .= gp.d[:, slice] .* gp.lambda[kl][kp[kl]]
inc += 1
end
return x
end
# ---------------------------------------------------------------------------- #
function get_prior!(l::Lasso, gp::LassoPrior{N,T}, k::Integer) where {N,T}
kstart = 0
kend = 1
kp = CartesianIndices(gp.lambda_len)[k]
inc = 1
for kl in (T < N ? fill(1, N) : 1:N)
kstart = kend + 1
kend = kstart + gp.filter_len[inc] - 1
slice = kstart:kend
l.x[slice] .= gp.lambda[kl][kp[kl]]
inc += 1
end
return l
end
# ---------------------------------------------------------------------------- #
function allocate_prior(gp::AbstractPrior)
n = sum(gp.filter_len)+1
return spzeros(n, n)
end
# ---------------------------------------------------------------------------- #
function allocate_prior(gp::LassoPrior)
n = sum(gp.filter_len)+1
return Lasso(zeros(n))
end
# ---------------------------------------------------------------------------- #
function get_lambda(gp::AbstractPrior, k::Integer)
kp = CartesianIndices(gp.lambda_len)[k]
out = Vector{Float64}(undef, length(gp.lambda))
for k in eachindex(out)
out[k] = gp.lambda[k][kp[k]]
end
return out
end
get_lambda(gp::NullPrior, k::Integer) = [0.0]
# ============================================================================ #
@inline null_prior(x::NTuple{N,<:Integer}) where N = NullPrior(x)
# ---------------------------------------------------------------------------- #
function ridge_prior(x::NTuple{N,<:Integer},
lm::NTuple{T,AbstractVector{<:Real}}) where {N,T}
n = sum(x)
return GLMPrior{N,T}(blockdiag(spzeros(1,1), sparse(I, n, n)), x, lm)
end
# ---------------------------------------------------------------------------- #
function smoothing_prior(x::NTuple{N,<:Integer},
lm::NTuple{T,AbstractVector{<:Real}}) where {N,T}
tmp = Vector{SparseMatrixCSC}(undef, length(x))
for k in eachindex(x)
d = spdiagm(0 => fill(-1.0, x[k]), 1 => fill(1.0, x[k]-1))
tmp[k] = d'*d
tmp[k][end,end] = 1.0
end
bd = blockdiag(spzeros(1,1), tmp...)
return GLMPrior{N,T}(blockdiag(spzeros(1,1), tmp...), x, lm)
end
# ---------------------------------------------------------------------------- #
function lasso_prior(x::NTuple{N,<:Integer},
lm::NTuple{T,AbstractVector{<:Real}}) where {N,T}
return LassoPrior(x, map(collect, lm), map(length, lm))
end
# ============================================================================ #
end
|
"""
Pkg NSG
---
# Objectives
This package is to organize genotypes of NSG sheep on various platforms.
The functions include:
1. Management of raw genotypes
2. Data QC to filter out low quality ID and/or loci
3. Imputation of sparser platforms to denser ones.
4. Calculation of a **G** matrix with imputed genotypes
This package was written only for Linux OS
"""
module NSG
work_dir = pwd() # all data and results are relative to work_dir
bin_dir, cpp_dir = begin
t = splitdir(pathof(NSG))[1]
l = findlast('/', t) - 1
joinpath(t[1:l], "bin"), joinpath(t[1:l], "src")
end
beagle = joinpath(bin_dir, "beagle.jar")
plink = joinpath(bin_dir, "plink")
global nsNe = 100
set_ne(ne) = (global nsNe=ne)
global _nthreads = 8
set_nthreads(n) = (global _nthreads=n)
include("styled-messages.jl")
include("update.jl")
include("raw.jl")
include("misc.jl")
include("QC.jl")
include("imputation.jl")
include("gmatrix.jl")
include("genotypes.jl")
include("comp-refs.jl")
NSG.title("Updating binaries")
NSG.Update()
end # module
|
module FinancialModels
using Random, Distributions, ProgressMeter, Printf
include("common.jl")
include("JacobLeal/JacobLeal.jl")
include("api.jl")
export SimulationResults, Options, JacobLealParameters, Simulate, prices, trace
end |
using ZMQ
using ProtoBuf
include("./proto/matrix_io.jl")
"""
Base type for Matrix Core drivers
# Fields
- baseport : base port for the driver
- host : host
- configsocket : ZMQ socket to send config data
- errsocket : ZMQ socket for receiving errors
- datasocket : ZMQ socket for receiving data
- keepalivesocket : ZMQ socket for sending keep alive pings
- datachannel : channel for receiving data as protobuf messages
- errchannel : channel for receiving error messages
"""
abstract type Driver end
"""
Print the content of a message
"""
function printmessage(m)
j = typeof(m)
if typeof(m) == matrix_io.malos.v1.sense.Humidity
println("Humidity $(m.humidity)% $(m.temperature)°C $(m.temperature_is_calibrated) $(m.temperature_raw)")
elseif typeof(m) == matrix_io.malos.v1.sense.Pressure
println("Pressure $(m.pressure) Pa $(m.altitude) m $(m.temperature) °C")
elseif typeof(m) == matrix_io.malos.v1.sense.UV
println("UV $(m.uv_index), $(m.oms_risk)")
elseif typeof(m) == matrix_io.malos.v1.sense.Imu
println("Imu $(m.yaw) ° $(m.pitch) ° $(m.roll) ° $(m.accel_x) m/s^2 $(m.accel_y) m/s^2 $(m.accel_z) m/s^2")
elseif typeof(m) == matrix_io.malos.v1.io.EverloopImage
println("Everloop $(m.everloop_length)")
elseif typeof(m) == matrix_io.malos.v1.io.GpioParams
println("GPIO $(m.values)")
end
end
"""
close(::<Driver)
Close all the sockets and channels of the driver
"""
function Base.close(d::T) where {T<:Driver}
close(d.errsocket)
close(d.datasocket)
close(d.keepalivesocket)
close(d.configsocket)
close(d.datachannel)
close(d.errchannel)
end
"""
connecterror(::<Driver)
Connect to the error port for the driver and start a task to put the received messages in the
error channel of the driver.
Used in the [`start`](@ref) function.
# Returns
The started task
"""
function connecterror(d::T) where {T<:Driver}
port = d.baseport+2
connect(d.errsocket,"tcp://$(d.host):$port")
subscribe(d.errsocket,"")
@async while isopen(d.errsocket)
try
m = recv(d.errsocket, String)
put!(d.errchannel, m)
catch e
if typeof(e)!=ZMQ.StateError &&
typeof(e)!=EODError
println("caught exception $e")
end
end
end
end # function
"""
connectdata(::<Driver)
Open the data socket and start a task to receive data messages and put them in the data channel.
Used in the [`start`](@ref) function
# Returns
The started task
"""
function connectdata(d::T) where {T<:Driver}
port = d.baseport+3
connect(d.datasocket,"tcp://$(d.host):$port")
subscribe(d.datasocket,"")
@async while isopen(d.datasocket)
try
m = recv(d.datasocket, String)
put!(d.datachannel, decodedata(d,m))
catch e
if typeof(e)!=ZMQ.StateError &&
typeof(e)!=EODError
println("caught exception $e")
end
end
end
end # function
"""
connectkeepalive(::<Driver)
Open the keep alive socket and start a task to send empty messages to the driver.
Used in the [`start`](@ref) function
# Arguments
- d : driver
# Returns
The started task
# Named arguments
- time : time interval in seconds between messages
"""
function connectkeepalive(d::T; time::Number = 2) where {T<:Driver}
port = d.baseport+1
connect(d.keepalivesocket,"tcp://$(d.host):$port")
@async while isopen(d.keepalivesocket)
send(d.keepalivesocket,"")
sleep(time)
end
end # function
"""
start(<:Driver, datafunc::Function, errfunc::Function, katime::Number)
Start tasks to receive and process messages from the driver
# Arguments
- `driver` : The driver to use
- `datafunc` : The function to process the incoming data messages.
Must take a ProtoBuf message as unique parameter. Default behavior is to print the
received message
- `errfunc` : The function to process the incoming error messages.
Must take a unique parameter. Default behavior is to print the error message
- `katime` : Time interval in seconds for the keep alive messages
# Returns
tuple of started tasks (t1, t2, t3, t4, t5), with
- t1 : data reception task
- t2 : error reception task
- t3 : keep alive send task
- t4 : data processing task
- t5 : error processing task
# Example
```julia
h = HumidityDriver("192.168.42.1")
configure(h; delay=2)
(t1, t2, t3, t4, t5) = start(h)
```
```julia
h = EverloopDriver("192.168.42.1")
for i=1:200
n::UInt32=256
red=rand(UInt32,35).%n
green=rand(UInt32,35).%n
blue=rand(UInt32,35).%n
configure(h,red,green,blue)
sleep(0.1)
end
red=zeros(UInt32,35)
configure(h,red,red,red)
closedriver(h)
```
"""
function start(driver::T, datafunc::Function=printmessage, errfunc::Function=println, katime::Number=2) where {T<:Driver}
t1=connectdata(driver)
t2=connecterror(driver)
t3=connectkeepalive(driver; time=katime)
t4=Task( () -> begin
while true
m = take!(driver.datachannel)
datafunc(m)
end
end )
schedule(t4)
t5=Task( () -> begin
while true
m = take!(driver.errchannel)
errfunc(m)
end
end )
schedule(t5)
(t1, t2, t3, t4, t5)
end
"""
configure(<:Driver)
Send configuration data to the driver. Each driver has its own method using a specific set of arguments.
# Methods
```julia
configure(d::HumidityDriver; delay=2, timeout= 6, temp=21)
configure(d::IMUDriver; delay=2, timeout=6)
configure(d::UVDriver; delay=2, timeout=6)
configure(d::PressureDriver; delay=2, timeout=6)
configure(d::EverloopDriver,red::Array{UInt32},green::Array{UInt32},blue::Array{UInt32};nbleds=35)
configure(d::GPIODriver; delay=2, timeout=6, pin=1, isinput=false, value=0)
```
# Arguments
- `d` : driver
# Named arguments
- `delay` : period in seconds for data refresh
- `timeout` : delay in seconds to stop sending data messages after last keep alive message
- `temp` : calibration temperature for the humidity sensor
- `red`,`green`,`blue` : color arrays for the everloop driver
- `nbleds` : number of leds for the everloop driver
"""
function configure(::T) where {T<:Driver}
error("abstract method")
end
function decodedata(::T, ::AbstractString) where {T<:Driver}
error("abstract method")
end
"""
HumidityDriver <: Driver
Driver for the humidity sensor
"""
struct HumidityDriver <: Driver
baseport
host::String
configsocket::Socket
errsocket::Socket
keepalivesocket::Socket
datasocket::Socket
datachannel::Channel{ProtoType}
errchannel::Channel
function HumidityDriver(h)
d=new(20017, h, Socket(PUSH), Socket(SUB), Socket(PUSH), Socket(SUB), Channel{ProtoType}(typemax(Int)), Channel(Inf))
connect(d.configsocket, "tcp://$(d.host):$(d.baseport)")
d
end
end
function configure(d::HumidityDriver; delay=2, timeout= 6, temp=21)
config = matrix_io.malos.v1.driver.DriverConfig(
delay_between_updates=delay,
timeout_after_last_ping=timeout,
humidity=matrix_io.malos.v1.sense.HumidityParams(current_temperature=temp)
)
io = IOBuffer()
writeproto(io, config)
msg = String(take!(io))
send(d.configsocket,msg)
end
function decodedata(d::HumidityDriver, buffer::AbstractString)
io = IOBuffer(buffer)
readproto(io, matrix_io.malos.v1.sense.Humidity())
end
"""
IMUDriver <: Driver
Driver for the IMU sensor
"""
struct IMUDriver <: Driver
baseport
host::String
configsocket::Socket
errsocket::Socket
keepalivesocket::Socket
datasocket::Socket
datachannel::Channel{ProtoType}
errchannel::Channel
function IMUDriver(h)
d=new(20013, h, Socket(PUSH), Socket(SUB), Socket(PUSH), Socket(SUB), Channel{ProtoType}(typemax(Int)), Channel(Inf))
connect(d.configsocket, "tcp://$(d.host):$(d.baseport)")
d
end
end
function configure(d::IMUDriver; delay=2, timeout=6)
config = matrix_io.malos.v1.driver.DriverConfig(
delay_between_updates=delay,
timeout_after_last_ping=timeout
)
io = IOBuffer()
writeproto(io, config)
m = String(take!(io))
send(d.configsocket,msg)
end
function decodedata(d::IMUDriver, buffer::AbstractString)
io = IOBuffer(buffer)
readproto(io, matrix_io.malos.v1.sense.Imu())
end
"""
UVDriver <: Driver
Driver for the UV sensor
"""
struct UVDriver <: Driver
baseport
host::String
configsocket::Socket
errsocket::Socket
keepalivesocket::Socket
datasocket::Socket
datachannel::Channel{ProtoType}
errchannel::Channel
function UVDriver(h)
d=new(20029, h, Socket(PUSH), Socket(SUB), Socket(PUSH), Socket(SUB), Channel{ProtoType}(typemax(Int)), Channel(Inf))
connect(d.configsocket, "tcp://$(d.host):$(d.baseport)")
d
end
end
function configure(d::UVDriver; delay=2, timeout=6)
config = matrix_io.malos.v1.driver.DriverConfig(
delay_between_updates=delay,
timeout_after_last_ping=timeout
)
io = IOBuffer()
writeproto(io, config)
msg = String(take!(io))
send(d.configsocket,msg)
end
function decodedata(d::UVDriver, buffer::AbstractString)
io = IOBuffer(buffer)
readproto(io, matrix_io.malos.v1.sense.UV())
end
"""
PressureDriver <: Driver
Driver for the Pressure sensor
"""
struct PressureDriver <: Driver
baseport
host::String
configsocket::Socket
errsocket::Socket
keepalivesocket::Socket
datasocket::Socket
datachannel::Channel{ProtoType}
errchannel::Channel
function PressureDriver(h)
d=new(20025, h, Socket(PUSH), Socket(SUB), Socket(PUSH), Socket(SUB), Channel{ProtoType}(typemax(Int)), Channel(Inf))
connect(d.configsocket, "tcp://$(d.host):$(d.baseport)")
d
end
end
function configure(d::PressureDriver; delay=2, timeout=6)
config = matrix_io.malos.v1.driver.DriverConfig(
delay_between_updates=delay,
timeout_after_last_ping=timeout
)
io = IOBuffer()
writeproto(io, config)
msg = String(take!(io))
send(d.configsocket,msg)
end
function decodedata(d::PressureDriver, buffer::String)
io = IOBuffer(buffer)
readproto(io, matrix_io.malos.v1.sense.Pressure())
end
"""
EverloopDriver <: Driver
Driver for the Everloop
"""
struct EverloopDriver <: Driver
baseport
host::String
configsocket::Socket
errsocket::Socket
keepalivesocket::Socket
datasocket::Socket
datachannel::Channel{ProtoType}
errchannel::Channel
function EverloopDriver(h)
d=new(20021, h, Socket(PUSH), Socket(SUB), Socket(PUSH), Socket(SUB), Channel{ProtoType}(typemax(Int)), Channel(Inf))
connect(d.configsocket, "tcp://$(d.host):$(d.baseport)")
d
end
end
function configure(d::EverloopDriver,r::Array{UInt32},g::Array{UInt32},b::Array{UInt32};nbleds=35)
config = matrix_io.malos.v1.driver.DriverConfig(
image=matrix_io.malos.v1.io.EverloopImage()
)
nb=min(size(r,1),size(g,1),size(b,1),nbleds)
config.image.led=Vector{matrix_io.malos.v1.io.LedValue}(undef,nbleds)
z::UInt32=0
for i=1:nb
config.image.led[i]=matrix_io.malos.v1.io.LedValue(red=r[i],green=g[i],blue=b[i],white=z)
end
for i=nb+1:nbleds
config.image.led[i]=matrix_io.malos.v1.io.LedValue(red=z,green=z,blue=z,white=z)
end
io = IOBuffer()
writeproto(io, config)
msg = String(take!(io))
send(d.configsocket,msg)
end
function decodedata(d::EverloopDriver, buffer::String)
io = IOBuffer(buffer)
readproto(io, matrix_io.malos.v1.io.EverloopImage())
end
"""
GPIODriver <: Driver
Driver for the GPIO
"""
struct GPIODriver <: Driver
baseport
host::String
configsocket::Socket
errsocket::Socket
keepalivesocket::Socket
datasocket::Socket
datachannel::Channel{ProtoType}
errchannel::Channel
function GPIODriver(h)
d=new(20049, h, Socket(PUSH), Socket(SUB), Socket(PUSH), Socket(SUB), Channel{ProtoType}(typemax(Int)), Channel(Inf))
connect(d.configsocket, "tcp://$(d.host):$(d.baseport)")
d
end
end
function configure(d::GPIODriver; delay=2, timeout=6, pin=1, isinput=false, value=0)
config = matrix_io.malos.v1.driver.DriverConfig(
delay_between_updates=delay,
timeout_after_last_ping=timeout,
gpio=matrix_io.malos.v1.io.GpioParams(
pin=pin,
mode=isinput ? 0 : 1,
value=value
)
)
io = IOBuffer()
writeproto(io, config)
msg = String(take!(io))
send(d.configsocket,msg)
end
function decodedata(d::GPIODriver, buffer::String)
io = IOBuffer(buffer)
readproto(io, matrix_io.malos.v1.io.GpioParams())
end
|
# LazyArrays._copyto!(::LazyArrays.DiagonalLayout, dest::Diagonal, M::LazyArrays.MatMulMat{<:LazyArrays.DiagonalLayout}) =
# copyto!(dest, M.factors[1]*M.factors[2])
# Base.similar(M::LazyArrays.MatMulMat{<:LazyArrays.DiagonalLayout}) = Diagonal(Vector{eltype(M)}(undef,size(M,1)))
# LazyArrays._materialize(M:: LazyArrays.ArrayMuls, ::Tuple{Base.OneTo}) = LazyArrays.rmaterialize(M)
# LazyArrays._materialize(M:: LazyArrays.Mul, ::Tuple{Base.OneTo}) = LazyArrays.rmaterialize(M)
# LazyArrays._materialize(M:: LazyArrays.ArrayMulArray, ::Tuple{Base.OneTo}) = copyto!(similar(M), M)
|
# on-device functionality
export AbstractDeviceArray, @LocalMemory
## device array
"""
AbstractDeviceArray{T, N} <: DenseArray{T, N}
Supertype for `N`-dimensional GPU arrays (or array-like types) with elements of type `T`.
Instances of this type are expected to live on the device, see [`AbstractGPUArray`](@ref)
for device-side objects.
"""
abstract type AbstractDeviceArray{T, N} <: DenseArray{T, N} end
Base.IndexStyle(::AbstractDeviceArray) = IndexLinear()
@inline function Base.iterate(A::AbstractDeviceArray, i=1)
if (i % UInt) - 1 < length(A)
(@inbounds A[i], i + 1)
else
nothing
end
end
function Base.sum(A::AbstractDeviceArray{T}) where T
acc = zero(T)
for elem in A
acc += elem
end
acc
end
## thread-local array
const shmem_counter = Ref{Int}(0)
"""
Creates a local static memory shared inside one block.
Equivalent to `__local` of OpenCL or `__shared__ (<variable>)` of CUDA.
"""
macro LocalMemory(state, T, N)
id = (shmem_counter[] += 1)
quote
LocalMemory($(esc(state)), $(esc(T)), Val($(esc(N))), Val($id))
end
end
"""
Creates a block local array pointer with `T` being the element type
and `N` the length. Both T and N need to be static! C is a counter for
approriately get the correct Local mem id in CUDAnative.
This is an internal method which needs to be overloaded by the GPU Array backends
"""
function LocalMemory(state, ::Type{T}, ::Val{dims}, ::Val{id}) where {T, dims, id}
error("Not implemented") # COV_EXCL_LINE
end
|
# GA
#=
LeetCode 198. House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
=#
# Import Packages
# GA Parameters
NP = 20
L = 10
Pc = 0.8
Pv = 0.2
G = 100
# Example
house = Int64.(floor.(rand(1, L) * 10) .+ 1)
# Initalization
f = Int64.(zeros(NP, L))
money = zeros(NP, 1)
moneyFit = zeros(NP, 1)
fBest = Int64.(zeros(1, L))
for ii = 1: NP
f[ii, :] = Int64.(floor.(rand(1, L) .+ 0.5))
end
# Start
nf = Int64.(zeros(NP, L))
for ii = 1: G
for jj = 1: NP
global moneyFit, fBest, f, nf
# Fitness (money)
for kk = 1: (L - 1)
if f[jj, kk] & f[jj, kk + 1] == 1
money[jj, 1] = 0
break
else
money[jj, 1] = sum(f[jj, :] .* house[1, :])
end
end
moneyMin = minimum(money[:, 1]) # Max
moneyMax = maximum(money[:, 1]) # Min
if money[jj, 1] == moneyMax
fBest[1, :] = f[jj, :] # Best
end
moneyFit[jj, 1] = (money[jj, 1] - moneyMin) / (moneyMax - moneyMin) # Normalization
# Roulette
sumFit = sum(moneyFit)
fitValue = moneyFit ./ sumFit
cumFitValue = cumsum(fitValue[:, 1])
for mm = 1: NP
roll = rand()
for nn = 1: (length(cumFitValue) - 1)
if cumFitValue[mm] < roll < cumFitValue[mm + 1]
nf[mm, :] = f[nn, :]
else
nf[mm, :] = f[1, :]
end
end
end
# Crossing
for kk = 1: 2: NP
c = rand()
if c < Pc
selection = Int64.(floor.(rand(1, L) .+ 0.5))
new1 = nf[kk, :] .* selection[1, :] .+ nf[kk + 1, :] .* (1 .- selection[1, :])
new2 = nf[kk, :] .* (1 .- selection[1, :]) .+ nf[kk + 1, :] .* selection[1, :]
nf[kk, :] = new1
nf[kk + 1, :] = new2
end
end
# Variation
for pp = 1: NP
for qq = 1: L
v = rand()
if v < Pv
nf[pp, qq] = 1 - nf[pp, qq]
end
end
end
# Replacing
f = nf
nf[1, :] = fBest[1, :]
end
end
moneyBest = sum(fBest[1, :] .* house[1, :])
println("Best Selection is $(fBest), money is $(moneyBest).")
|
using Pkg;
Pkg.activate(".");
using JLD2, Plots, SolverBenchmark
name = "2022-04-02_ARCqKOp10204_ARCqKOp10201_ARCqKOp102005_ARCqKOp10203_ARCqKOp10202_cutest_277_1000000"
@load "$name.jld2" stats
#=
stats1 = copy(stats)
name = "2022-03-21_trunk_tron_ipopt_lbfgs_cutest_277_1000000"
@load "$name.jld2" stats
stats = merge(stats, stats1)
=#
solved(df) = (df.status .== :first_order) .| (df.status .== :unbounded)
open("$name.dat", "w") do io
for solver in keys(stats)
# Number of problems solved
println(io, solver)
println(io, size(stats[solver][solved(stats[solver]), [:name]], 1))
println(
io,
stats[solver][
.!solved(stats[solver]),
[:name, :nvar, :status, :elapsed_time, :dual_feas],
],
)
end
end
costs =
[df -> .!solved(df) * Inf + df.elapsed_time, df -> .!solved(df) * Inf + df.neval_obj]
costnames = ["Time", "Evaluations of f"]
p = profile_solvers(stats, costs, costnames)
png(p, "$name")
for solver in keys(stats)
open("$(name)_result_$(solver).dat", "w") do io
print(
io,
stats[solver][
!,
[
:name,
:nvar,
:ncon,
:status,
:objective,
:elapsed_time,
:iter,
:primal_feas,
:dual_feas,
:neval_obj,
:neval_grad,
:neval_hprod,
:neval_hess,
],
],
)
end
end
nmins = [0, 100, 1000, 10000]
for nmin in nmins
# Same figure with minimum number of variables
stats2 = copy(stats)
for solver in keys(stats)
stats2[solver] = stats[solver][stats[solver].nvar.>=nmin, :]
end
nb_problems = length(stats2[first(keys(stats))][!, :name])
# Figures comparing two results:
costs_all = [
df -> .!solved(df) * Inf + df.elapsed_time,
df -> .!solved(df) * Inf + df.neval_obj,
df -> .!solved(df) * Inf + df.neval_grad,
df -> .!solved(df) * Inf + df.neval_hprod,
df -> .!solved(df) * Inf + df.neval_obj + df.neval_grad + df.neval_hprod,
]
costnames_all = [
"time",
"objective evals",
"gradient evals",
"hessian-vector products",
"obj + grad + hprod",
]
p = profile_solvers(stats2, costs_all, costnames_all)
png(p, "$(name)_all($(nb_problems))_min_$(nmin)")
end
|
"""
```
function metropolis_hastings(propdist::Distribution,
loglikelihood::Function,
parameters::ParameterVector{S},
data::Matrix{T},
cc0::T,
cc::T;
n_blocks::Int = 1,
n_sim::Int = 100,
n_burn::Int = 0,
mhthin::Int = 1,
verbose::Symbol=:low,
savepath::String = "mhsave.h5",
rng::MersenneTwister = MersenneTwister(0),
testing::Bool = false) where {S<:Number, T<:AbstractFloat}
```
Implements the Metropolis-Hastings MCMC algorithm for sampling from the posterior
distribution of the parameters.
### Arguments
- `propdist`: The proposal distribution that Metropolis-Hastings begins sampling from.
- `m`: The model object
- `data`: Data matrix for observables
- `cc0`: Jump size for initializing Metropolis-Hastings.
- `cc`: Jump size for the rest of Metropolis-Hastings.
### Optional Arguments
- `n_blocks::Int = 1`: Number of blocks (for memory-management purposes)
- `n_param_blocks::Int = 1`: Number of parameter blocks
- `n_sim::Int = 100`: Number of simulations. Note: # saved observations will be
n_sim * n_param_blocks * (n_blocks - b_burn).
- `n_burn::Int = 0`: Length of burn-in period
- `mhthin::Int = 1`: Thinning parameter (for mhthin = d, keep only every dth draw)
- `adaptive_accpt::Bool = false`: Whether or not to adaptively adjust acceptance prob.
- `α::T = 1.0`: Tuning parameter for proposal density computation in adaptive case
- `c::T = 1.0`: Tuning parameter for proposal density computation in adaptive case
- `verbose::Bool`: The desired frequency of function progress messages printed to
standard out. One of:
```
- `:none`: No status updates will be reported.
- `:low`: Status updates provided at each block.
- `:high`: Status updates provided at each draw.
```
- `savepath::String = "mhsave.h5"`: String specifying path to output file
- `rng::MersenneTwister = MersenneTwister(0)`: Chosen seed (overridden if testing = true)
- `testing::Bool = false`: Conditional for use when testing (determines fixed seeding)
"""
function metropolis_hastings(propdist::Distribution,
loglikelihood::Function,
parameters::ParameterVector{S},
data::Matrix{T},
cc0::T,
cc::T;
n_blocks::Int64 = 1,
n_param_blocks::Int64 = 1, # TODO: give these kwargs better names
n_sim::Int64 = 100,
n_burn::Int64 = 0,
mhthin::Int64 = 1,
adaptive_accpt::Bool = false,
α::T = 1.0, c::T = 1.0,
verbose::Symbol = :low,
savepath::String = "mhsave.h5",
rng::MersenneTwister = MersenneTwister(0),
testing::Bool = false) where {S<:Number, T<:AbstractFloat}
# If testing, set the random seeds at fixed numbers
if testing
Random.seed!(rng, 654)
end
# Initialize algorithm by drawing para_old from normal distribution centered at the
# posterior mode, until parameters within bounds (indicated by posterior value > -∞)
para_old = rand(propdist, rng; cc = cc0)
post_old = -Inf
initialized = false
while !initialized
post_old = posterior!(loglikelihood, parameters, para_old, data; sampler = true)
if post_old > -Inf
propdist.μ = para_old
initialized = true
else
para_old = rand(propdist, rng; cc=cc0)
end
end
# New feature: Parameter Blocking
free_para_inds = findall([!θ.fixed for θ in parameters])
n_free_para = length(free_para_inds)
n_params = length(parameters)
param_blocks = SMC.generate_param_blocks(n_params, n_param_blocks)
# Report number of blocks that will be used
println(verbose, :low, "Blocks: $n_blocks")
println(verbose, :low, "Draws per block: $n_sim")
println(verbose, :low, "Parameter blocks: $n_param_blocks")
# For n_sim*mhthin iterations within each block, generate a new parameter draw.
# Decide to accept or reject, and save every (mhthin)th draw that is accepted.
all_rejections = 0
# Initialize matrices for parameter draws and transition matrices
mhparams = zeros(n_sim * n_param_blocks, n_params)
# Open HDF5 file for saving parameter draws
simfile = h5open(savepath, "w")
n_saved_obs = n_sim * n_param_blocks * (n_blocks - n_burn)
parasim = d_create(simfile, "mhparams", datatype(Float64),
dataspace(n_saved_obs, n_params),
"chunk", (n_sim * n_param_blocks, n_params))
# Keep track of how long metropolis_hastings has been sampling
total_sampling_time = 0.
for block = 1:n_blocks
begin_time = time_ns()
block_rejections = 0
for j = 1:(n_sim * mhthin)
for (k, p_block) in enumerate(param_blocks)
# Draw para_new from the proposal distribution
para_subset = para_old[p_block]
d_subset = DegenerateMvNormal(propdist.μ[p_block],
propdist.σ[p_block, p_block])
para_draw = rand(d_subset, rng; cc = cc)
para_new = deepcopy(para_old)
para_new[p_block] = para_draw
q0, q1 = if adaptive_accpt
SMC.compute_proposal_densities(para_draw, para_subset, d_subset;
α = α, c = c)
else
0.0, 0.0
end
# Solve the model (checking that parameters are within bounds and
# gensys returns a meaningful system) and evaluate the posterior
post_new = posterior!(loglikelihood, parameters, para_new, data;
sampler = true)
println(verbose, :high, "Block $block, Iteration $j, Parameter Block " *
"$k/$(n_param_blocks): posterior = $post_new")
# Choose to accept or reject the new parameter by calculating the
# ratio (r) of the new posterior value relative to the old one We
# compare min(1, r) to a number drawn randomly from a uniform (0, 1)
# distribution. This allows us to always accept the new draw if its
# posterior value is greater than the previous draw's, but it gives
# some probability to accepting a draw with a smaller posterior
# value, so that we may explore tails and other local modes.
r = exp((post_new - post_old) + (q0 - q1))
x = rand(rng)
if x < min(1.0, r)
# Accept proposed jump
para_old = para_new
post_old = post_new
propdist.μ = para_new
println(verbose, :high, "Block $block, Iteration $j, Parameter Block " *
"$k/$(n_param_blocks): accept proposed jump")
else
# Reject proposed jump
block_rejections += 1
println(verbose, :high, "Block $block, Iteration $j, Parameter Block " *
"$k/$(n_param_blocks): reject proposed jump")
end
# Save every (mhthin)th draw
if j % mhthin == 0
draw_index = convert(Int, j / mhthin)
mhparams[draw_index, :] = para_old'
end
end # of block
all_rejections += block_rejections
block_rejection_rate = block_rejections / (n_sim * mhthin * n_param_blocks)
## Once every iblock times, write parameters to a file
# Calculate starting, ending indices for this block (corresponds to new chunk in memory)
block_start = n_sim * n_param_blocks * (block - n_burn - 1)+1
block_end = block_start + (n_sim * n_param_blocks) - 1
# Write parameters to file if we're past n_burn blocks
if block > n_burn
parasim[block_start:block_end, :] = map(Float64, mhparams)
end
# Calculate time to complete this block, average block time, and
# expected time to completion
block_time = (time_ns() - begin_time) / 1e9
total_sampling_time += block_time
total_sampling_time_minutes = total_sampling_time / 60
expected_time_remaining_sec = (total_sampling_time / block) * (n_blocks - block)
expected_time_remaining_minutes = expected_time_remaining_sec / 60
println(verbose, :low, "Completed $block of $n_blocks blocks.")
println(verbose, :low, "Total time to compute $block blocks: " *
"$total_sampling_time_minutes minutes")
println(verbose, :low, "Expected time remaining for Metropolis-Hastings: " *
"$expected_time_remaining_minutes minutes")
println(verbose, :low, "Block $block rejection rate: $block_rejection_rate \n")
end # of loop over parameter blocks
end # of loop over blocks
close(simfile)
rejection_rate = all_rejections / (n_blocks * n_sim * mhthin * n_param_blocks)
println(verbose, :low, "Overall rejection rate: $rejection_rate")
end
"""
```
metropolis_hastings(propdist::Distribution, m::AbstractDSGEModel,
data::Matrix{T}, cc0::T, cc::T; verbose::Symbol = :low) where {T<:AbstractFloat}
```
Wrapper function for DSGE models which calls Metropolis-Hastings MCMC algorithm for
sampling from the posterior distribution of the parameters.
### Arguments
- `propdist`: The proposal distribution that Metropolis-Hastings begins sampling from.
- `m`: The model object
- `data`: Data matrix for observables
- `cc0`: Jump size for initializing Metropolis-Hastings.
- `cc`: Jump size for the rest of Metropolis-Hastings.
### Optional Arguments
- `verbose`: The desired frequency of function progress messages printed to
standard out. One of:
```
- `:none`: No status updates will be reported.
- `:low`: Status updates provided at each block.
- `:high`: Status updates provided at each draw.
```
"""
function metropolis_hastings(propdist::Distribution,
m::AbstractDSGEModel,
data::Matrix{T},
cc0::T,
cc::T;
verbose::Symbol=:low,
filestring_addl::Vector{String} = Vector{String}(undef, 0)) where {T<:AbstractFloat}
n_blocks = n_mh_blocks(m)
n_sim = n_mh_simulations(m)
n_burn = n_mh_burn(m)
mhthin = mh_thin(m)
rng = m.rng
testing = m.testing
savepath = rawpath(m, "estimate", "mhsave.h5", filestring_addl)
# To check: Defaulting to using Chandrasekhar recursions if no missing data
use_chand_recursion = !any(isnan.(data))
function loglikelihood(p::ParameterVector, data::Matrix{Float64})::Float64
update!(m, p)
likelihood(m, data; sampler = true, catch_errors = false,
use_chand_recursion = use_chand_recursion)
end
return metropolis_hastings(propdist, loglikelihood, m.parameters, data, cc0, cc;
n_blocks = n_blocks, n_sim = n_sim, n_burn = n_burn,
mhthin = mhthin, verbose = verbose, savepath = savepath,
rng = rng, testing = testing)
end
|
@testset "Constraints" begin
#TODO needs to be updated for the new constraint design and interaction with Core
T = Float64
N = 3
# Test extreme constraints
c1(x) = x[1] < 1
c2(x) = x[1] + x[3] > 1
c3(x) = x[2] > 0
p1(x) = x[1] < 1 ? 0 : x[1] - 1
p2(x) = x[1] + x[3] > 1 ? 0 : 1 - x[1] + x[3]
p3(x) = x[2] > 0 ? 0 : -x[2]
C = DS.Constraints{T}()
@testset "Constraints" begin
@test C.count == length(C.collections) == 2
@test typeof(C.collections[1]) == DS.ConstraintCollection{T, DS.ExtremeConstraint}
@test typeof(C.collections[2]) == DS.ConstraintCollection{T, DS.ProgressiveConstraint}
end
@testset "DefaultConstraintCollection" begin
ex = C.collections[1]
pr = C.collections[2]
# Extreme barrier constraint default collection
@test length(ex.constraints) == ex.count == 0
@test typeof(ex.constraints) == Vector{DS.ExtremeConstraint}
@test ex.h_max == 0.0
# Extreme barrier constraint default collection
@test length(pr.constraints) == pr.count == 0
@test typeof(pr.constraints) == Vector{DS.ProgressiveConstraint}
@test pr.h_max == Inf
# TODO: Test default update functions
end
C = DS.Constraints{T}()
@testset "AddExtremeConstraint" begin
c1_ref = DS.AddExtremeConstraint(C, c1)
@test c1_ref.value == 1
@test typeof(c1_ref) == DS.ConstraintIndex
# Can't push an extreme constraint to a progressive collection
@test_throws MethodError DS.AddExtremeConstraint(C, c1, index=DS.CollectionIndex(2))
@test_throws ErrorException DS.AddExtremeConstraint(C, c1, index=DS.CollectionIndex(3))
vec_ref = DS.AddExtremeConstraint(C, [c2, c3])
@test length(vec_ref) == 2
@test vec_ref[1].value == 2
@test vec_ref[2].value == 3
end
@testset "AddProgressiveConstraint" begin
p1_ref = DS.AddProgressiveConstraint(C, p1)
@test p1_ref.value == 1
@test typeof(p1_ref) == DS.ConstraintIndex
# Can't push an extreme constraint to a progressive collection
@test_throws MethodError DS.AddProgressiveConstraint(C, p1, index=DS.CollectionIndex(1))
@test_throws ErrorException DS.AddProgressiveConstraint(C, p1, index=DS.CollectionIndex(3))
vec_ref = DS.AddProgressiveConstraint(C, [c2, c3])
@test length(vec_ref) == 2
@test vec_ref[1].value == 2
@test vec_ref[2].value == 3
end
C = DS.Constraints{T}()
@testset "AddProgressiveCollection" begin
c_ref = DS.AddProgressiveCollection(C)
@test typeof(c_ref) == DS.CollectionIndex
@test c_ref.value == 3
@test typeof(C.collections[3]) == DS.ConstraintCollection{T, DS.ProgressiveConstraint}
@test length(C.collections[3].constraints) == C.collections[3].count == 0
p_ref = DS.AddProgressiveConstraint(C, p2, index=c_ref)
@test length(C.collections[3].constraints) == C.collections[3].count == 1
end
#TODO constraint evaluation
end
|
using DReal
a = Var(Float64,"aexpop2",0.,1.)
b2 = (a < 0.1) | (a > 0.9)
push_ctx!()
add!(b2)
is_satisfiable()
pop_ctx!()
push_ctx!()
b3 = !b2
#b3 = (a >= 0.1) & (a <= 0.9)
add!(b3)
is_satisfiable()
|
using BranchTests
using Test
Code = quote
@testbranch "Vector" begin
println("in 'Vector'")
v = Vector{Int}()
@test isempty(v)
@testbranch "adds one element" begin
println("in 'adds one element'")
push!(v, 1)
@test length(v) == 1
@testbranch "adds another element" begin
println("in 'adds another element'")
push!(v, 2)
@test length(v) == 2
end
@testbranch DefaultTestSet "removes one" begin # test set type
println("in 'removes one'")
pop!(v)
@test isempty(v)
end
end
@testbranch begin # no name
println("in 'equality'")
@test v == v
end
end
end
eval(Code)
#@testset "vector" begin
# v = Vector{Int}()
#
# @testset "adds one element" begin
# push!(v, 1)
# @test length(v) == 1
#
# @testset "adds another element" begin
# push!(v, 1)
# @test length(v) == 2
# end
#
# @testset "removes - empty" begin
# pop!(v)
# @test isempty(v)
# end
# end
#end
|
using BCTRNN
using DiffEqSensitivity
using OrdinaryDiffEq
import DiffEqFlux: FastChain, FastDense
import Flux: ClipValue, ADAM
# Not in Project.toml
using Plots
gr()
include("sine_wave_dataloader.jl")
function train_sine_ss_fc(epochs, solver=Tsit5();
sensealg=InterpolatingAdjoint(autojacvec=ReverseDiffVJP(true)),
T=Float32, model_size=5,
mtkize=false, gen_jac=false, lr=0.02, kwargs...)
train_dl = generate_2d_data(T)
f_in = 2
f_out = 1
im = BCTRNN.InputAllToAll()
sm = BCTRNN.SynsFullyConnected()
#om = BCTRNN.OutputAll()
om = BCTRNN.OutputIdxs(collect(1:model_size))
wiring = BCTRNN.WiringConfig(f_in, model_size, im,sm,om)
model = FastChain(BCTRNN.Mapper(f_in),
BCTRNN.LTCSynStateMTK(wiring, solver, sensealg; T, mtkize, gen_jac, kwargs...),
FastDense(wiring.n_out, f_out))
hs = []
for (k,v) in wiring.matrices
push!(hs, heatmap(v, title=k))
end
display(plot(hs..., layout=length(hs)))
cb = BCTRNN.MyCallback(T; ecb=mycb, nepochs=epochs, nsamples=length(train_dl))
#opt = GalacticOptim.Flux.Optimiser(ClipValue(0.5), ADAM(0.02))
opt = BCTRNN.ClampBoundOptim(BCTRNN.get_bounds(model,T)..., ClipValue(T(1.0)), ADAM(T(lr)))
BCTRNN.optimize(model, BCTRNN.loss_seq, cb, opt, train_dl, epochs, T), model
end
@time train_sine_ss_fc(100, Vern7(); model_size=8, mtkize=false, lr=0.01,
)
function train_sine_ss_ncp(epochs, solver=Tsit5();
sensealg=InterpolatingAdjoint(autojacvec=ReverseDiffVJP(true)),
T=Float32,
n_sensory=2, n_inter=5, n_command=5, n_motor=2,
sensory_inter=2, inter_command=3, command_command=2, command_motor=2,
mtkize=false, gen_jac=false, lr=0.02, kwargs...)
train_dl = generate_2d_data(T)
f_in = 2
f_out = 1
im = BCTRNN.InputAllToFirstN(n_sensory)
sm = BCTRNN.SynsNCP(; n_sensory, n_inter, n_command, n_motor,
sensory_inter, inter_command, command_command, command_motor
)
om = BCTRNN.OutputAll()
om = BCTRNN.OutputIdxs(collect(1:n_sensory+n_inter+n_command+n_motor))
wiring = BCTRNN.WiringConfig(f_in, im,sm,om)
model = FastChain(BCTRNN.Mapper(f_in),
BCTRNN.LTCSynStateMTK(wiring, solver, sensealg; T, mtkize, gen_jac, kwargs...),
FastDense(wiring.n_out, f_out))
hs = []
for (k,v) in wiring.matrices
push!(hs, heatmap(v, title=k))
end
display(plot(hs..., layout=length(hs)))
cb = BCTRNN.MyCallback(T; ecb=mycb, nepochs=epochs, nsamples=length(train_dl))
#opt = GalacticOptim.Flux.Optimiser(ClipValue(0.5), ADAM(0.02))
opt = BCTRNN.ClampBoundOptim(BCTRNN.get_bounds(model,T)..., ClipValue(T(1.0)), ADAM(T(lr)))
BCTRNN.optimize(model, BCTRNN.loss_seq, cb, opt, train_dl, epochs, T), model
end
@time train_sine_ss_ncp(100, ROCK4(), n_sensory=5, n_inter=10, n_command=10, mtkize=false, lr=0.01,
)
@time train_sine_ss_ncp(100, TRBDF2(linsolve=LinSolveGMRES()), n_sensory=3, n_inter=5, n_command=5, mtkize=false, lr=0.01,
) |
# test/runtests.jl
# Test UnitfulCurrency
using UnitfulCurrency
|
function find_package(f, registry::String="")
for reg in Pkg.Registry.reachable_registries()
if isempty(registry) || registry == reg.name
data = get_registry_file(reg, "Registry.toml")
for (uuid, pkginfo) in data["packages"]
f(uuid, pkginfo) && return (;uuid, reg, name=pkginfo["name"], path=pkginfo["path"])
end
end
end
return
end
function find_package(package::String, registry::String="")
find_package(registry) do uuid, pkginfo
pkginfo["name"] == package
end
end
function find_max_version(package::String, registry::String="")
info = find_package(package, registry)
info === nothing && return
versions = get_registry_file(info.reg, joinpath(info.path, "Versions.toml"))
max_version = findmax(VersionNumber.(keys(versions)))[1]
return max_version
end
function get_registry_file(reg, path::String)
return if isnothing(reg.in_memory_registry)
TOML.parsefile(joinpath(reg.path, path))
else
TOML.parse(reg.in_memory_registry[path])
end
end
|
### A Pluto.jl notebook ###
# v0.12.10
using Markdown
using InteractiveUtils
# ╔═╡ 680fdae0-1b3c-11ec-0de6-eb64d535f45f
# ╔═╡ 67f96cb0-1b3c-11ec-2f27-3bf1bcfaca4b
# ╔═╡ 67f945a0-1b3c-11ec-0b73-6bf3aba70083
# ╔═╡ 67cdefde-1b3c-11ec-218e-17e0fe9beb7c
# ╔═╡ Cell order:
# ╠═680fdae0-1b3c-11ec-0de6-eb64d535f45f
# ╠═67f96cb0-1b3c-11ec-2f27-3bf1bcfaca4b
# ╠═67f945a0-1b3c-11ec-0b73-6bf3aba70083
# ╠═67cdefde-1b3c-11ec-218e-17e0fe9beb7c
|
#=
Copyright (c) 2018-2022 Chris Coey, Lea Kapelevich, and contributors
This Julia package Hypatia.jl is released under the MIT license; see LICENSE
file in the root directory or at https://github.com/chriscoey/Hypatia.jl
helpers for dense factorizations and linear solves
=#
import LinearAlgebra.BlasReal
import LinearAlgebra.BlasFloat
import LinearAlgebra.BlasInt
import LinearAlgebra.BLAS.@blasfunc
import LinearAlgebra.LAPACK.liblapack
import LinearAlgebra.copytri!
# helpers for in-place matrix inverses (updates upper triangle only in some cases)
# Cholesky, BlasFloat
function inv_fact!(
mat::Matrix{R},
fact::Cholesky{R, Matrix{R}},
) where {R <: BlasFloat}
copyto!(mat, fact.factors)
LAPACK.potri!(fact.uplo, mat)
return mat
end
# Cholesky, generic
function inv_fact!(
mat::Matrix{R},
fact::Cholesky{R, Matrix{R}},
) where {R <: RealOrComplex{<:Real}}
# this is how Julia computes the inverse, but it could be implemented better
copyto!(mat, I)
ldiv!(fact, mat)
return mat
end
# BunchKaufman, BlasReal
function inv_fact!(
mat::Matrix{T},
fact::BunchKaufman{T, Matrix{T}},
) where {T <: BlasReal}
@assert fact.rook
copyto!(mat, fact.LD)
LAPACK.sytri_rook!(fact.uplo, mat, fact.ipiv),
return mat
end
# LU, BlasReal
function inv_fact!(
mat::Matrix{T},
fact::LU{T, Matrix{T}},
) where {T <: BlasReal}
copyto!(mat, fact.factors)
LAPACK.getri!(mat, fact.ipiv)
return mat
end
# LU, generic
function inv_fact!(
mat::Matrix{T},
fact::LU{T, Matrix{T}},
) where {T <: Real}
# this is how Julia computes the inverse, but it could be implemented better
copyto!(mat, I)
ldiv!(fact, mat)
return mat
end
# helpers for updating symmetric/Hermitian eigendecomposition
update_eigen!(X::Matrix{<:BlasFloat}) = LAPACK.syev!('V', 'U', X)[1]
function update_eigen!(X::Matrix{<:RealOrComplex{<:Real}})
F = eigen(Hermitian(X, :U))
copyto!(X, F.vectors)
return F.values
end
# helpers for symmetric outer product (upper triangle only)
# B = alpha * A' * A + beta * B
outer_prod!(
A::Matrix{T},
B::Matrix{T},
alpha::Real,
beta::Real,
) where {T <: LinearAlgebra.BlasReal} =
BLAS.syrk!('U', 'T', alpha, A, beta, B)
outer_prod!(
A::AbstractMatrix{Complex{T}},
B::AbstractMatrix{Complex{T}},
alpha::Real,
beta::Real,
) where {T <: LinearAlgebra.BlasReal} =
BLAS.herk!('U', 'C', alpha, A, beta, B)
outer_prod!(
A::AbstractMatrix{R},
B::AbstractMatrix{R},
alpha::Real,
beta::Real,
) where {R <: RealOrComplex} =
mul!(B, A', A, alpha, beta)
# ensure diagonal terms in square matrix are not too small
function increase_diag!(A::Matrix{T}) where {T <: Real}
diag_pert = 1 + T(1e-5)
diag_min = 1000 * eps(T)
@inbounds for j in 1:size(A, 1)
A[j, j] = diag_pert * max(A[j, j], diag_min)
end
return A
end
# helpers for spectral outer products
function spectral_outer!(
mat::AbstractMatrix{T},
vecs::Union{Matrix{T}, Adjoint{T, Matrix{T}}},
diag::AbstractVector{T},
temp::Matrix{T},
) where {T <: Real}
mul!(temp, vecs, Diagonal(diag))
mul!(mat, temp, vecs')
return mat
end
function spectral_outer!(
mat::AbstractMatrix{T},
vecs::Union{Matrix{T}, Adjoint{T, Matrix{T}}},
symm::Symmetric{T},
temp::Matrix{T},
) where {T <: Real}
mul!(temp, vecs, symm)
mul!(mat, temp, vecs')
return mat
end
#=
nonsymmetric square: LU
=#
function nonsymm_fact_copy!(
mat2::Matrix{T},
mat::Matrix{T},
) where {T <: Real}
copyto!(mat2, mat)
fact = lu!(mat2, check = false)
if !issuccess(fact)
copyto!(mat2, mat)
increase_diag!(mat2)
fact = lu!(mat2, check = false)
end
return fact
end
#=
symmetric indefinite: BunchKaufman (rook pivoting) and LU for generic fallback
NOTE if better fallback becomes available (eg dense LDL), use that
=#
symm_fact!(A::Symmetric{T, Matrix{T}}) where {T <: BlasReal} =
bunchkaufman!(A, true, check = false)
symm_fact!(A::Symmetric{T, Matrix{T}}) where {T <: Real} =
lu!(A, check = false)
function symm_fact_copy!(
mat2::Symmetric{T, Matrix{T}},
mat::Symmetric{T, Matrix{T}},
) where {T <: Real}
copyto!(mat2, mat)
fact = symm_fact!(mat2)
if !issuccess(fact)
copyto!(mat2, mat)
increase_diag!(mat2.data)
fact = symm_fact!(mat2)
end
return fact
end
#=
symmetric positive definite: unpivoted Cholesky
NOTE pivoted seems slower than BunchKaufman
=#
posdef_fact!(A::Symmetric{T, Matrix{T}}) where {T <: Real} =
cholesky!(A, check = false)
function posdef_fact_copy!(
mat2::Symmetric{T, Matrix{T}},
mat::Symmetric{T, Matrix{T}},
try_shift::Bool = true,
) where {T <: Real}
copyto!(mat2, mat)
fact = posdef_fact!(mat2)
if !issuccess(fact)
# try using symmetric factorization instead
copyto!(mat2, mat)
fact = symm_fact!(mat2)
if try_shift && !issuccess(fact)
copyto!(mat2, mat)
increase_diag!(mat2.data)
fact = symm_fact!(mat2)
end
end
return fact
end
|
# We probably won't use this. Prefer Distances.jl
function hellinger_distance!(p_counts::AbstractDict{T,V}, q_counts::AbstractDict{T,V}) where {T, V}
p_sum = sum(values(p_counts))
q_sum = sum(values(q_counts))
total = float(zero(V))
for (key, val) in p_counts
if haskey(q_counts, key)
total += (sqrt(val / p_sum) - sqrt(q_counts[key] / q_sum))^2
delete!(q_counts, key)
else
total += val / p_sum
end
end
total += sum(x -> x / q_sum, values(q_counts))
dist = sqrt(total / 2)
return dist
end
hellinger_distance(p_counts::AbstractDict, q_counts::AbstractDict) =
hellinger_distance!(copy(p_counts), copy(q_counts))
|
const hash_mask = typemax(UInt) >>> 0x01
const deletion_mask = hash_mask + 0x01
mutable struct Indices{I} <: AbstractIndices{I}
# The hash table
slots::Vector{Int}
# Hashes and values
hashes::Vector{UInt} # Deletion marker stored in high bit
values::Vector{I}
holes::Int # Number of "vacant" slots in hashes and values
end
_slots(inds::Indices) = getfield(inds, :slots)
_hashes(inds::Indices) = getfield(inds, :hashes)
_values(inds::Indices) = getfield(inds, :values)
_holes(inds::Indices) = getfield(inds, :holes)
Indices(; sizehint = 8) = Indices{Any}(; sizehint = sizehint)
function Indices{I}(; sizehint = 8) where {I}
newsize = Base._tablesz((3 * sizehint) >> 0x01);
Indices{I}(fill(0, newsize), Vector{UInt}(), Vector{I}(), 0)
end
"""
Indices(iter)
Indices{I}(iter)
Construct a `Indices` with indices from iterable container `iter`.
Note that the elements of `iter` must be distinct/unique. Instead, the `distinct` function
can be used for finding the unique elements.
# Examples
```julia
julia> Indices([1,2,3])
3-element Indices{Int64}
1
2
3
julia> Indices([1,2,3,3])
ERROR: IndexError("Indices are not unique (inputs at positions 3 and 4) - consider using the distinct function")
Stacktrace:
[1] Indices{Int64}(::Array{Int64,1}) at /home/ferris/.julia/dev/Dictionaries/src/Indices.jl:92
[2] Indices(::Array{Int64,1}) at /home/ferris/.julia/dev/Dictionaries/src/Indices.jl:53
[3] top-level scope at REPL[12]:1
julia> distinct([1,2,3,3])
3-element Indices{Int64}
1
2
3
```
"""
function Indices(iter)
if Base.IteratorEltype(iter) === Base.EltypeUnknown()
iter = collect(iter)
end
return Indices{eltype(iter)}(iter)
end
function Indices{I}(iter) where {I}
iter_size = Base.IteratorSize(iter)
if iter_size isa Union{Base.HasLength, Base.HasShape}
values = Vector{I}(undef, length(iter))
@inbounds for (i, value) in enumerate(iter)
values[i] = value
end
else
values = Vector{I}()
@inbounds for value in iter
push!(values, value)
end
end
return Indices{I}(values)
end
function Indices{I}(values::Vector{I}) where {I}
# The input must have unique elements (the constructor is not to be used in place of `distinct`)
hashes = map(v -> hash(v) & hash_mask, values)
# Incrementally build the hashmap and throw if duplicates detected
newsize = Base._tablesz(3*length(values) >> 0x01)
bit_mask = newsize - 1 # newsize is a power of two
slots = zeros(Int, newsize)
@inbounds for index in keys(hashes)
full_hash = hashes[index]
trial_slot = reinterpret(Int, full_hash) & bit_mask
@inbounds while true
trial_slot = (trial_slot + 1)
if slots[trial_slot] == 0
slots[trial_slot] = index
break
else
# TODO make this check optional
if isequal(values[index], values[slots[trial_slot]])
throw(IndexError("Indices are not unique (inputs at positions $(slots[trial_slot]) and $index) - consider using the distinct function"))
end
end
trial_slot = trial_slot & bit_mask
# This is potentially an infinte loop and care must be taken not to overfill the container
end
end
return Indices{I}(slots, hashes, values, 0)
end
Base.convert(::Type{AbstractIndices{I}}, inds::AbstractIndices) where {I} = convert(Indices{I}, inds) # the default AbstractIndices type
Base.convert(::Type{AbstractIndices{I}}, inds::AbstractIndices{I}) where {I} = inds
Base.convert(::Type{AbstractIndices{I}}, inds::Indices) where {I} = convert(Indices{I}, inds)
Base.convert(::Type{Indices}, inds::AbstractIndices{I}) where {I} = convert(Indices{I}, inds)
Base.convert(::Type{Indices{I}}, inds::Indices{I}) where {I} = inds
function Base.convert(::Type{Indices{I}}, inds::AbstractIndices) where {I}
# Fast path
if inds isa Indices && _holes(inds) == 0
# Note: `convert` doesn't have copy semantics
return Indices{I}(_slots(inds), _hashes(inds), convert(Vector{I}, _values(inds)), 0)
end
# The input is already unique
values = collect(I, inds)
hashes = map(v -> hash(v) & hash_mask, values)
# Incrementally build the hashmap
newsize = Base._tablesz(3*length(values) >> 0x01)
bit_mask = newsize - 1 # newsize is a power of two
slots = zeros(Int, newsize)
@inbounds for index in keys(hashes)
full_hash = hashes[index]
trial_slot = reinterpret(Int, full_hash) & bit_mask
@inbounds while true
trial_slot = (trial_slot + 1)
if slots[trial_slot] == 0
slots[trial_slot] = index
break
else
# TODO make this check optional
if isequal(values[index], values[slots[trial_slot]])
throw(IndexError("Indices are not unique (inputs at positions $(slots[trial_slot]) and $index)"))
end
end
trial_slot = trial_slot & bit_mask
# This is potentially an infinte loop and care must be taken not to overfill the container
end
end
return Indices{I}(slots, hashes, values, 0)
end
"""
copy(inds::AbstractIndices)
copy(inds::AbstractIndices, ::Type{I})
Create a shallow copy of the indices, optionally changing the element type.
(Note that `copy` on a dictionary does not copy its indices).
"""
function Base.copy(indices::Indices{I}, ::Type{I2}) where {I, I2}
return Indices{I}(copy(_slots(indices)), copy(_hashes(indices)), collect(I2, _values(indices)), _holes(indices))
end
function Base.copy(indices::ReverseIndices{I,Indices{I}}, ::Type{I2}) where {I, I2}
p = parent(indices)
l = length(_values(p)) + 1
old_slots = _slots(p)
new_slots = similar(old_slots)
@inbounds for i in keys(_slots(p))
index = old_slots[i]
if index > 0
new_slots[i] = l - index
else
new_slots[i] = index
end
end
return Indices{I2}(new_slots, reverse(_hashes(p)), collect(I2, Iterators.reverse(_values(p))), _holes(p))
end
# private (note that newsize must be power of two)
function rehash!(indices::Indices{I}, newsize::Int, values = (), include_last_values::Bool = true) where {I}
slots = resize!(_slots(indices), newsize)
fill!(slots, 0)
bit_mask = newsize - 1 # newsize is a power of two
if _holes(indices) == 0
for (index, full_hash) in enumerate(_hashes(indices))
trial_slot = reinterpret(Int, full_hash) & bit_mask
@inbounds while true
trial_slot = (trial_slot + 1)
if slots[trial_slot] == 0
slots[trial_slot] = index
break
else
trial_slot = trial_slot & bit_mask
end
# This is potentially an infinte loop and care must be taken not to overfill the container
end
end
else
# Compactify _values(indices), _hashes(indices) and the values while we are at it
to_index = Ref(1) # Reassigning to to_index/from_index gives the closure capture boxing issue, so mutate a reference instead
from_index = Ref(1)
n_values = length(_values(indices))
@inbounds while from_index[] <= n_values
full_hash = _hashes(indices)[from_index[]]
if full_hash & deletion_mask === zero(UInt)
trial_slot = reinterpret(Int, full_hash) & bit_mask
@inbounds while true
trial_slot = trial_slot + 1
if slots[trial_slot] == 0
slots[trial_slot] = to_index[]
_hashes(indices)[to_index[]] = _hashes(indices)[from_index[]]
_values(indices)[to_index[]] = _values(indices)[from_index[]]
if include_last_values || from_index[] < n_values
# Note - the last slot might end up with a random value (or
# GC'd reference). It's the callers responsibility to ensure the
# last slot is written to after this operation.
map(values) do (vals)
@inbounds vals[to_index[]] = vals[from_index[]]
end
end
to_index[] += 1
break
else
trial_slot = trial_slot & bit_mask
end
end
end
from_index[] += 1
end
new_size = n_values - _holes(indices)
resize!(_values(indices), new_size)
resize!(_hashes(indices), new_size)
map(values) do (vals)
resize!(vals, new_size)
end
setfield!(indices, :holes, 0)
end
return indices
end
Base.length(indices::Indices) = length(_values(indices)) - _holes(indices)
# Token interface
istokenizable(::Indices) = true
tokentype(::Indices) = Int
# Duration iteration the token cannot be used for deletion - we do not worry about the slots
@propagate_inbounds function iteratetoken(indices::Indices)
if _holes(indices) == 0
return length(indices) > 0 ? ((0, 1), 1) : nothing
end
index = 1
@inbounds while index <= length(_hashes(indices))
if _hashes(indices)[index] & deletion_mask === zero(UInt)
return ((0, index), index)
end
index += 1
end
return nothing
end
@propagate_inbounds function iteratetoken(indices::Indices, index::Int)
index += 1
if _holes(indices) == 0 # apparently this is enough to make it iterate as fast as `Vector`
return index <= length(_values(indices)) ? ((0, index), index) : nothing
end
@inbounds while index <= length(_hashes(indices))
if _hashes(indices)[index] & deletion_mask === zero(UInt)
return ((0, index), index)
end
index += 1
end
return nothing
end
@propagate_inbounds function iteratetoken_reverse(indices::Indices)
index = length(indices)
if _holes(indices) == 0
return index > 0 ? ((0, index), index) : nothing
end
@inbounds while index > 0
if _hashes(indices)[index] & deletion_mask === zero(UInt)
return ((0, index), index)
end
index -= 1
end
return nothing
end
@propagate_inbounds function iteratetoken_reverse(indices::Indices, index::Int)
index -= 1
if _holes(indices) == 0 # apparently this is enough to make it iterate as fast as `Vector`
return index > 0 ? ((0, index), index) : nothing
end
@inbounds while index > 0
if _hashes(indices)[index] & deletion_mask === zero(UInt)
return ((0, index), index)
end
index -= 1
end
return nothing
end
function gettoken(indices::Indices{I}, i::I) where {I}
full_hash = hash(i) & hash_mask
n_slots = length(_slots(indices))
bit_mask = n_slots - 1 # n_slots is always a power of two
trial_slot = reinterpret(Int, full_hash) & bit_mask
@inbounds while true
trial_slot = (trial_slot + 1)
trial_index = _slots(indices)[trial_slot]
if trial_index > 0
value = _values(indices)[trial_index]
if i === value || isequal(i, value)
return (true, (trial_slot, trial_index))
end
elseif trial_index === 0
return (false, (0, 0))
end
trial_slot = trial_slot & bit_mask
# This is potentially an infinte loop and care must be taken upon insertion not
# to completely fill the container
end
end
@propagate_inbounds function gettokenvalue(indices::Indices, (_slot, index))
return _values(indices)[index]
end
@propagate_inbounds function gettokenvalue(indices::Indices, index::Int)
return _values(indices)[index]
end
# Insertion interface
isinsertable(::Indices) = true
function gettoken!(indices::Indices{I}, i::I, values = ()) where {I}
full_hash = hash(i) & hash_mask
n_slots = length(_slots(indices))
bit_mask = n_slots - 1 # n_slots is always a power of two
n_values = length(_values(indices))
trial_slot = reinterpret(Int, full_hash) & bit_mask
trial_index = 0
deleted_slot = 0
@inbounds while true
trial_slot = (trial_slot + 1)
trial_index = _slots(indices)[trial_slot]
if trial_index == 0
break
elseif trial_index < 0
if deleted_slot == 0
deleted_slot = trial_slot
end
else
value = _values(indices)[trial_index]
if i === value || isequal(i, value)
return (true, (trial_slot, trial_index))
end
end
trial_slot = trial_slot & bit_mask
# This is potentially an infinte loop and care must be taken upon insertion not
# to completely fill the container
end
new_index = n_values + 1
if deleted_slot == 0
# Use the trail slot
_slots(indices)[trial_slot] = new_index
else
# Use the deleted slot
_slots(indices)[deleted_slot] = new_index
end
push!(_hashes(indices), full_hash)
push!(_values(indices), i)
map(values) do (vals)
resize!(vals, length(vals) + 1)
end
# Expand the hash map when it reaches 2/3rd full
if 3 * new_index > 2 * n_slots
# Grow faster for small hash maps than for large ones
newsize = n_slots > 16000 ? 2 * n_slots : 4 * n_slots
rehash!(indices, newsize, values, false)
# The index has changed
new_index = length(_values(indices))
# The slot also has changed
bit_mask = newsize - 1
trial_slot = reinterpret(Int, full_hash) & bit_mask
@inbounds while true
trial_slot = (trial_slot + 1)
if _slots(indices)[trial_slot] == new_index
break
end
trial_slot = trial_slot & bit_mask
end
end
return (false, (trial_slot, new_index))
end
@propagate_inbounds function deletetoken!(indices::Indices{I}, (slot, index), values = ()) where {I}
@boundscheck if slot == 0
error("Cannot use iteration token for deletion")
end
_slots(indices)[slot] = -index
_hashes(indices)[index] = deletion_mask
isbitstype(I) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), _values(indices), index-1)
setfield!(indices, :holes, _holes(indices) + 1)
# Recreate the hash map when 1/3rd of the values are deletions
n_values = length(_values(indices)) - _holes(indices)
if 3 * _holes(indices) > n_values
# Halve if necessary
n_slots = length(_slots(indices))
halve = 4 * n_values < n_slots && n_slots > 8
rehash!(indices, halve ? n_slots >> 0x01 : n_slots, values)
end
return indices
end
function Base.empty!(indices::Indices{I}, values = ()) where {I}
setfield!(indices, :hashes, Vector{UInt}())
setfield!(indices, :values, Vector{I}())
setfield!(indices, :slots, fill(0, 8))
setfield!(indices, :holes, 0)
foreach(empty!, values)
return indices
end
# Accelerated filtering
function Base.filter!(pred, indices::Indices)
_filter!(token -> pred(@inbounds gettokenvalue(indices, token)), indices, ())
end
@inline function _filter!(pred, indices::Indices, values = ())
indices_values = _values(indices)
hashes = _hashes(indices)
n = length(indices_values)
i = Ref(0)
j = Ref(0)
@inbounds while i[] < n
i[] += 1
if hashes[i[]] & deletion_mask === zero(UInt) && pred(i[])
j[] += 1
indices_values[j[]] = indices_values[i[]]
hashes[j[]] = hashes[i[]]
map(vec -> @inbounds(vec[j[]] = vec[i[]]), values)
end
end
newsize = j[]
resize!(indices_values, newsize)
resize!(hashes, newsize)
map(vec -> resize!(vec, newsize), values)
setfield!(indices, :holes, 0)
newsize = Base._tablesz(3*length(_values(indices)) >> 0x01)
rehash!(indices, newsize, values)
end
# Factories
# TODO make this generic... maybe a type-based `empty`?
function _distinct(::Type{Indices}, itr)
if Base.IteratorEltype(itr) === Base.HasEltype()
return _distinct(Indices{eltype(itr)}, itr)
end
tmp = iterate(itr)
if tmp === nothing
return Indices{Base.@default_eltype(itr)}()
end
(x, s) = tmp
indices = Indices{typeof(x)}()
insert!(indices, x)
return __distinct!(indices, itr, s, x)
end
# An auto-widening constructor for insertable AbstractIndices
function __distinct!(indices::AbstractIndices, itr, s, x_old)
T = eltype(indices)
tmp = iterate(itr, s)
while tmp !== nothing
(x, s) = tmp
if !isequal(x, x_old) # Optimized for repeating elements of `itr`, e.g. if `itr` is sorted
if !(x isa T) && promote_type(typeof(x), T) != T
new_indices = copy(indices, promote_type(T, typeof(x)))
set!(new_indices, x)
return __distinct!(new_indices, itr, s, x)
end
set!(indices, x)
x_old = x
end
tmp = iterate(itr, s)
end
return indices
end
function randtoken(rng::Random.AbstractRNG, inds::Indices)
if inds.holes === 0
return (0, rand(rng, Base.OneTo(length(inds))))
end
# Rejection sampling to handle deleted tokens (which are sparse)
range = Base.OneTo(length(_hashes(inds)))
while true
i = rand(rng, range)
if inds.hashes[i] !== deletion_mask
return (0, i)
end
end
end |
using FileIO
using JLD2
using Pkg.Artifacts
using ClimateMachine.ArtifactWrappers
# Get bomex_edmf dataset folder:
bomex_edmf_dataset = ArtifactWrapper(
joinpath(@__DIR__, "Artifacts.toml"),
"bomex_edmf",
ArtifactFile[ArtifactFile(
url = "https://caltech.box.com/shared/static/jbhcy6ncc5wh1hg9hcea5f45w6t22kk2.jld2",
filename = "bomex_edmf.jld2",
),],
)
bomex_edmf_dataset_path = get_data_folder(bomex_edmf_dataset)
data_file = joinpath(bomex_edmf_dataset_path, "bomex_edmf.jld2")
updraft_vars(N_up, st, tol, sym...) = Dict(ntuple(N_up) do i
"turbconv.updraft[$i]." * join(string.(sym), ".") => (st, tol)
end)
vars_to_compare(N_up) = Dict(
"ρ" => (Prognostic(), 1),
"ρu[1]" => (Prognostic(), 1),
"ρu[2]" => (Prognostic(), 1),
"ρu[3]" => (Prognostic(), 1),
"ρe" => (Prognostic(), 1e5),
"moisture.ρq_tot" => (Prognostic(), 1e-2),
"turbconv.environment.ρatke" => (Prognostic(), 5e-1),
"turbconv.environment.T" => (Auxiliary(), 300),
"turbconv.environment.cld_frac" => (Auxiliary(), 1),
"turbconv.environment.buoyancy" => (Auxiliary(), 1e-2),
updraft_vars(N_up, Prognostic(), 1 * 0.1, :ρa)...,
updraft_vars(N_up, Prognostic(), 1 * 0.1, :ρaw)...,
updraft_vars(N_up, Prognostic(), 300 * 0.1, :ρaθ_liq)...,
updraft_vars(N_up, Prognostic(), 1e-2 * 0.1, :ρaq_tot)...,
updraft_vars(N_up, Auxiliary(), 1e-2, :buoyancy)...,
)
compare = Dict()
@testset "Regression Test" begin
N_up = n_updrafts(solver_config.dg.balance_law.turbconv)
numerical_data =
dict_of_nodal_states(solver_config, ["z"], (Prognostic(), Auxiliary()))
data_to_compare = Dict()
for (ftc, v) in vars_to_compare(N_up)
data_to_compare[ftc] = numerical_data[ftc]
end
export_new_solution_jld2 = false
if export_new_solution_jld2
save("bomex_edmf.jld2", data_to_compare)
end
all_data_ref = load(data_file)
@test all(k in keys(all_data_ref) for k in keys(data_to_compare))
N_up = n_updrafts(solver_config.dg.balance_law.turbconv)
comparison_vars = vars_to_compare(N_up)
for k in keys(all_data_ref)
data = data_to_compare[k]
ref_data = all_data_ref[k]
tol = comparison_vars[k][2]
s = length(data) / 100
@test !any(isnan.(ref_data))
@test !any(isnan.(data))
absΔdata = abs.(data .- ref_data)
T1 = isapprox(norm(absΔdata), 0, atol = tol * 0.01 * s) # norm
T2 = isapprox(maximum(absΔdata), 0, atol = tol * 0.01) # max of local
compare[k] = (norm(absΔdata), maximum(absΔdata), tol)
(!T1 || !T2) && @show k, norm(absΔdata), maximum(absΔdata), tol
@test isapprox(norm(absΔdata), 0, atol = tol * 0.01 * s) # norm
@test isapprox(maximum(absΔdata), 0, atol = tol * 0.01) # max of local
end
end
|
struct Subsequence{VT<:AbstractVector,T}
c::VT
fillvalue::T
winlen::Int
noverlap::Int
step::Int
lpadlen::Int
rpadlen::Int
end
function getpadlen(winlen)
if mod(winlen, 2) == 0
lpadlen = (winlen-1)÷2
rpadlen = winlen÷2
else
lpadlen = rpadlen = winlen÷2
end
lpadlen, rpadlen
end
function Subsequence(c::AbstractVector{T}, winlen, noverlap; fillvalue=zero(T)) where T
winlen > length(c) && throw(ArgumentError("`winlen` has to be smaller than the signal length."))
step = winlen-noverlap
lpadlen, rpadlen = getpadlen(winlen)
Subsequence(c,
fillvalue,
winlen,
noverlap,
step,
lpadlen,
rpadlen)
# Subsequence(PaddedView(fill, c, (1-lpadlen:length(c)+rpadlen,)), winlen, noverlap, step, lpadlen, rpadlen)
end
function Base.iterate(subseq::Subsequence, state=1)
lenc = length(subseq.c)
state > lenc && return nothing
# return @view(subseq.c[state-subseq.lpadlen:state+subseq.rpadlen]), state+subseq.step
if state <= subseq.lpadlen
return vcat(fill(subseq.fillvalue, subseq.lpadlen-(state-1)), @view(subseq.c[1:state+subseq.rpadlen])), state+subseq.step
elseif state >= lenc-subseq.rpadlen
return vcat(@view(subseq.c[state-subseq.lpadlen:end]), fill(subseq.fillvalue, subseq.rpadlen-(lenc-state))), state+subseq.step
else
return @view(subseq.c[state-subseq.lpadlen:state+subseq.rpadlen]), state+subseq.step
end
end
Base.length(subseq::Subsequence) = ceil(Int64, length(subseq.c)/subseq.step)
Base.getindex(subseq::Subsequence, i::Number) = iterate(subseq, (1:subseq.step:length(subseq.c))[i])[1]
|
module QJuliaGaugeUtils
import QJuliaInterface
import QJuliaEnums
import QUDARoutines
debug_constructGaugeField = false
@inline function accumulateConjugateProduct(a::Complex{T}, b::Complex{T}, c::Complex{T}, sign::Float64) where T <: AbstractFloat
local tmp::Complex{T} = b*c
a += Complex{T}(sign*real(tmp), -sign*imag(tmp))
return a
end
# normalize the vector a
function normalize(a::AbstractArray, len::Int)
local sum::Float64 = 0.0;
for i in 1:len; sum += abs2(a[i]); end
a[:] /= sqrt(sum)
end
# orthogonalize vector b to vector a
function orthogonalize(a::AbstractArray, b::AbstractArray, len::Int)
local dot::Complex{Float64} = 0.0;
for i in 1:len; dot += conj(a[i])*b[i]; end
b[:] -= (dot*a[:])
end
#Main methods:
function applyGaugeFieldScaling!(gauge::Matrix{Complex{T}}, param::QJuliaInterface.QJuliaGaugeParam_qj) where T <: AbstractFloat
vol = param.X[1]*param.X[2]*param.X[3]*param.X[4]
volh = Int(vol / 2)
volh_t = Int(param.X[1] / 2)*param.X[2]*param.X[3]*(param.X[4]-1)
# Apply spatial scaling factor (u0) to spatial links
gauge[:, 1:3] /= param.anisotropy;
# only apply T-boundary at edge nodes (always true for the single device)
local last_node_in_t = (QUDARoutines.commCoords_qj(3) == QUDARoutines.commDim_qj(3)-1) ? true : false
# create time direction views:
even_tlinks = view(gauge, (9volh_t+1):9volh, 4)
odd_tlinks = view(gauge, 9(volh+volh_t)+1:9vol, 4)
# Apply boundary conditions to temporal links
if param.t_boundary == QJuliaEnums.QJULIA_ANTI_PERIODIC_T && last_node_in_t
println("Applying antiperiodic BC.")
even_tlinks[:] *= -1.0
odd_tlinks[:] *= -1.0
end
if param.gauge_fix == QJuliaEnums.QJULIA_GAUGE_FIXED_YES
println("Applying gauge fixing.")
# set all gauge links (except for the last X[1]*X[2]*X[3]/2) to the identity,
# to simulate fixing to the temporal gauge.
local iMax = last_node_in_t ? volh_t : volh
even_gauge = view(gauge, 1:9iMax, 4)
odd_gauge = view(gauge, 9volh+1:9(volh+iMax), 4)
for i in 0:(iMax-1)
for m in 0:2
for n in 0:2
even_gauge[9i + 3m + n + 1] = (m==n) ? 1.0 : 0.0;
odd_gauge[ 9i + 3m + n + 1] = (m==n) ? 1.0 : 0.0;
end # for n
end # for m
end #for i
end # param.gauge_fix
end #applyGaugeFieldScaling!
function constructUnitGaugeField!(gauge::Matrix{Complex{T}}, param::QJuliaInterface.QJuliaGaugeParam_qj) where T <: AbstractFloat
vol = param.X[1]*param.X[2]*param.X[3]*param.X[4]
volh = Int(vol / 2)
even_gauge = view(gauge, 1:9volh, :)
odd_gauge = view(gauge, 9volh+1:9vol, :)
for d in 1:4
for i in 0:(volh-1)
for m in 0:2
for n in 0:2
even_gauge[9i + 3m + n + 1, d] = (m==n) ? 1.0 : 0.0;
odd_gauge[9i + 3m + n + 1 , d] = (m==n) ? 1.0 : 0.0;
end # for n
end # for m
end # for i
end # for d
applyGaugeFieldScaling!(gauge, param)
end # constructUnitGaugeField!
function constructGaugeField!(gauge::Matrix{Complex{T}}, param::QJuliaInterface.QJuliaGaugeParam_qj) where T <: AbstractFloat
vol = param.X[1]*param.X[2]*param.X[3]*param.X[4]
volh = Int(vol / 2)
println("Gauge field volume: ", vol)
even_gauge = view(gauge, 1:9volh, :)
odd_gauge = view(gauge, 9volh+1:9vol, :)
#println(typeof(even_gauge))
#println(typeof(odd_gauge) )
#we do always need offset = 1
for d in 1:4
for i in 0:(volh-1)
for m in 0:2
for n in 0:2
even_gauge[9i + 3m + n + 1, d] = Complex{T}(rand(), rand())
odd_gauge[9i + 3m + n + 1 , d] = Complex{T}(rand(), rand())
end
end
#create a view for a given link
local c = 1;
gauge_link_col0 = view(even_gauge, (9i +1):(9i+3c ), d)
gauge_link_col1 = view(even_gauge, (9i+3c +1):(9i+3(c+1)), d)
gauge_link_col2 = view(even_gauge, (9i+3(c+1)+1):(9i+3(c+2)), d)
normalize(gauge_link_col1, 3)
orthogonalize(gauge_link_col1, gauge_link_col2, 3)
normalize(gauge_link_col2, 3)
for i in 1:3; gauge_link_col0[i] = 0.0; end
gauge_link_col0[1] = accumulateConjugateProduct(gauge_link_col0[1], gauge_link_col1[2], gauge_link_col2[3], +1.0)
gauge_link_col0[1] = accumulateConjugateProduct(gauge_link_col0[1], gauge_link_col1[3], gauge_link_col2[2], -1.0)
gauge_link_col0[2] = accumulateConjugateProduct(gauge_link_col0[2], gauge_link_col1[3], gauge_link_col2[1], +1.0)
gauge_link_col0[2] = accumulateConjugateProduct(gauge_link_col0[2], gauge_link_col1[1], gauge_link_col2[3], -1.0)
gauge_link_col0[3] = accumulateConjugateProduct(gauge_link_col0[3], gauge_link_col1[1], gauge_link_col2[2], +1.0)
gauge_link_col0[3] = accumulateConjugateProduct(gauge_link_col0[3], gauge_link_col1[2], gauge_link_col2[1], -1.0)
gauge_link_col0 = view(odd_gauge, (9i +1):(9i+3c ), d)
gauge_link_col1 = view(odd_gauge, (9i+3c+1):(9i+3(c+1)), d)
gauge_link_col2 = view(odd_gauge, (9i+3(c+1)+1):(9i+3(c+2)), d)
normalize(gauge_link_col1, 3)
orthogonalize(gauge_link_col1, gauge_link_col2, 3)
normalize(gauge_link_col2, 3)
for i in 1:3; gauge_link_col0[i] = 0.0; end
gauge_link_col0[1] = accumulateConjugateProduct(gauge_link_col0[1], gauge_link_col1[2], gauge_link_col2[3], +1.0)
gauge_link_col0[1] = accumulateConjugateProduct(gauge_link_col0[1], gauge_link_col1[3], gauge_link_col2[2], -1.0)
gauge_link_col0[2] = accumulateConjugateProduct(gauge_link_col0[2], gauge_link_col1[3], gauge_link_col2[1], +1.0)
gauge_link_col0[2] = accumulateConjugateProduct(gauge_link_col0[2], gauge_link_col1[1], gauge_link_col2[3], -1.0)
gauge_link_col0[3] = accumulateConjugateProduct(gauge_link_col0[3], gauge_link_col1[1], gauge_link_col2[2], +1.0)
gauge_link_col0[3] = accumulateConjugateProduct(gauge_link_col0[3], gauge_link_col1[2], gauge_link_col2[1], -1.0)
end # for i
end # for d
if param.gtype == QJuliaEnums.QJULIA_WILSON_LINKS
println("Applying scaling/BC on the gauge links")
applyGaugeFieldScaling!(gauge, param)
end
if debug_constructGaugeField == true
println("::> Begin debug info for function constructGaugeField...")
dir = 1
for i in 1:16
println("Cehck value for index ", i, ",dir " , dir, " complex value is = ", gauge[i, dir])
end
println("<:: End debug info.")
end
end #constructGaugeField!
function construct_gauge_field!(gauge::Matrix{Complex{T}}, gtype, param::QJuliaInterface.QJuliaGaugeParam_qj) where T <: AbstractFloat
println("Working with gauge field type:", typeof(gauge), " : ", length(gauge))
if gtype == 0
println("Construct unit gauge field")
constructUnitGaugeField!(gauge, param)
elseif gtype == 1
println("Construct random gauge field")
constructGaugeField!(gauge, param)
else
println("Apply scaling...")
applyGaugeFieldScaling!(gauge, param)
end
end #construct_gauge_field!
end #QJuliaGaugeUtils
|
# Methods that deal with interpolating the adaptive kernel's kernel parameters
# or the warp map from samples.
# # One single interpolator for the size of the entire image.
# function getθset{KT}(itp, itp_set, θ::KT, scale_factor::Float64,
# ratio::Vector{Float64},
# offset::Vector{Float64})::Matrix{AdaptiveKernelType{KT}}
#
# θ_set = Array{AdaptiveKernelType{KT}}(size(itp_set))
#
# for i = 1:length(θ_set)
# θ_set[i] = AdaptiveKernelType(θ, x->scale_factor*itp[(x./ratio+offset)...] )
# end
#
# return θ_set
# end
#
# # The version that uses an array of smaller interpolators, with oversized phi patches.
# function getθsetlocalinterpolators2{KT}(itp_sets::Vector,
# θ::KT, scale_factor::Float64,
# ratio::Vector{Float64},
# X_set::Matrix{Matrix{Vector{Float64}}},
# overlap::Int)::Matrix{AdaptiveKernelType{KT}}
#
# N_rows, N_cols = size(itp_sets[1])
# θ_set = Array{AdaptiveKernelType{KT}}(N_rows,N_cols)
#
# M = length(itp_sets)
#
# # Top left. Put into for-loop block so anchor and offset gets its own scope.
# for i = 1:1
# anchor = [1; 1]
# offset = -X_set[1,1][1]./ratio + anchor
#
# warpfunc_set = Vector{Function}(M)
# for m = 1:M
# itp_set = itp_sets[m]
# warpfunc_set[m] = x->scale_factor*itp_set[1,1][(x./ratio+offset)...]
# end
#
# θ_set[1,1] = AdaptiveKernelType(θ,warpfunc_set)
# end
#
# # Left column, second row until end.
# for i = 2:N_rows
# anchor = [overlap+1; 1]
# offset = -X_set[i,1][1]./ratio + anchor
#
# warpfunc_set = Vector{Function}(M)
# for m = 1:M
# itp_set = itp_sets[m]
# warpfunc_set[m] = x->scale_factor*itp_set[i,1][(x./ratio+offset)...]
# end
#
# θ_set[i,1] = AdaptiveKernelType(θ,warpfunc_set)
# end
#
# # Top row, second column until end.
# for j = 2:N_cols
# anchor = [1; overlap+1]
# offset = -X_set[1,j][1]./ratio + anchor
#
# warpfunc_set = Vector{Function}(M)
# for m = 1:M
# itp_set = itp_sets[m]
# warpfunc_set[m] = x->scale_factor*itp_set[1,j][(x./ratio+offset)...]
# end
#
# θ_set[1,j] = AdaptiveKernelType(θ,warpfunc_set)
# end
#
# # Central regions, second row ⊗ second column until end.
# for i = 2:N_rows
# for j = 2:N_cols
# anchor = [overlap+1; overlap+1]
# offset = -X_set[i,j][1]./ratio + anchor
#
# warpfunc_set = Vector{Function}(M)
# for m = 1:M
# itp_set = itp_sets[m]
# warpfunc_set[m] = x->scale_factor*itp_set[i,j][(x./ratio+offset)...]
# end
#
# θ_set[i,j] = AdaptiveKernelType(θ,warpfunc_set)
# end
# end
#
# return θ_set
# end
# options for warp map samples.
# this is the case when the target density is unknown, but realizations are available.
function getwarpmapsamplecustom( y::Array{T,D},
ω_set,
pass_band_factor) where {T,D}
#
N_bands = length(ω_set)
Y = y
#### Split-band analysis.
ϕY, ψY = SignalTools.runsplitbandanalysis(Y, ω_set, SignalTools.getGaussianfilters)
ηY = SignalTools.runbandpassanalysis(Y, ω_set, pass_band_factor, SignalTools.getGaussianfilters)
# #### Riesz transform on the different filtered signals.
# H, ordering = gethigherorderRTfilters(Y,order)
#
# 𝓡ϕY = collect( RieszAnalysisLimited(ϕY[s],H) for s = 1:N_bands)
# 𝓡ψY = collect( RieszAnalysisLimited(ψY[s],H) for s = 1:N_bands)
# 𝓡ηY = collect( RieszAnalysisLimited(ηY[s],H) for s = 1:N_bands)
ϕ_set = ηY
ϕ = reduce(+,ϕ_set)./N_bands
return ϕY, ψY, ηY
end
function getwarpmaplinear(ϕ::Array{T,D}) where {T,D}
itp_ϕ = Interpolations.interpolate(ϕ,
Interpolations.BSpline(Interpolations.Linear()))
etp_ϕ = Interpolations.extrapolate(itp_ϕ, Interpolations.Line())
return etp_ϕ
end
function getwarpmap(ϕ::Array{T,D}) where {T,D}
itp_ϕ = Interpolations.interpolate(ϕ,
Interpolations.BSpline(Interpolations.Cubic(
Interpolations.Flat(Interpolations.OnGrid()))))
etp_ϕ = Interpolations.extrapolate(itp_ϕ, Interpolations.Line())
#etp_ϕ = Interpolations.extrapolate(itp_ϕ, 0)
return etp_ϕ
end
function getwarpmap(ϕ::Array{T,D}, x_ranges::Vector, amplification_factor::T) where {T,D}
@assert D == length(x_ranges)
N_array = collect( length(x_ranges[d]) for d = 1:D )
itp_ϕ = Interpolations.interpolate(ϕ,
Interpolations.BSpline(Interpolations.Cubic(
Interpolations.Flat(Interpolations.OnGrid()))))
etp_ϕ = Interpolations.extrapolate(itp_ϕ, Interpolations.Line())
#etp_ϕ = Interpolations.extrapolate(itp_ϕ, 0)
st = collect( x_ranges[d][1] for d = 1:D )
fin = collect( x_ranges[d][end] for d = 1:D )
f = xx->etp_ϕ(interval2itpindex(xx,
st,
fin,
N_array)...)*amplification_factor
# chain rule for first derivatives.
df = xx->( Interpolations.gradient(etp_ϕ,interval2itpindex(xx,
st,
fin,
N_array)...) .* derivativeinterval2itpindex(st,fin,N_array) .*amplification_factor )
# chain rule for second derivatives.
d2f = xx->( Interpolations.hessian(etp_ϕ,interval2itpindex(xx,
st,
fin,
N_array)...) .* (derivativeinterval2itpindex(st,fin,N_array).^2) .*amplification_factor )
return f, df, d2f
end
# # test code.
#
# A = randn(N,N)
# itp_ϕ = Interpolations.interpolate(A,
# Interpolations.BSpline(Interpolations.Cubic(
# Interpolations.Flat(Interpolations.OnGrid()))))
#
# P = [1.1; 2.3]
# ϕ_map_func, d_ϕ_map_func = getwarpmap(A, x_ranges[1:2], amplification_factor)
#
#
# dϕ_ND = xx->Calculus.gradient(ϕ_map_func, xx)
# dϕ_ND(P)
#
# d_ϕ_map_func(P) ./ dϕ_ND(P)
|
function get_combined_provider(::Type{TransformProviderUtils}, arg0::TransformProvider, arg1::TransformProvider)
return jcall(TransformProviderUtils, "getCombinedProvider", TransformProvider, (TransformProvider, TransformProvider), arg0, arg1)
end
function get_reversed_provider(::Type{TransformProviderUtils}, arg0::TransformProvider)
return jcall(TransformProviderUtils, "getReversedProvider", TransformProvider, (TransformProvider,), arg0)
end
|
#///////////////////////////////////////
#// File Name: rs_sac_controller_test.jl
#// Author: Haruki Nishimura (hnishimura@stanford.edu)
#// Date Created: 2021/02/26
#// Description: Test code for src/rs_sac_controller.jl
#///////////////////////////////////////
using DataStructures
using LinearAlgebra
using Random
using RobotOS
@testset "RSSAC Controller Test" begin
# Cost parameters
Cep = Matrix(1.0I, 2, 2);
Cu = Matrix(1.0I, 2, 2);
β_pos = 0.6;
β_col = 0.4;
α_col = 100.0;
λ_col = 1.0;
σ_risk = 1.0;
cost_param = CostParameter(Cep, Cu, β_pos, α_col, β_col, λ_col, σ_risk);
# Simulation parameters
conf_file_name = "config.json";
test_data_name = "eth_test.pkl";
test_scene_id = 0;
start_time_idx = 50;
device = py"torch".device("cpu");
incl_robot_name = false;
scene_param = TrajectronSceneParameter(conf_file_name, test_data_name,
test_scene_id, start_time_idx,
incl_robot_name);
scene_loader = TrajectronSceneLoader(scene_param, verbose=false);
num_samples = 50;
prediction_steps = 12;
use_robot_future = false;
deterministic = false;
rng_seed_py = 1;
predictor_param = TrajectronPredictorParameter(prediction_steps, num_samples,
use_robot_future, deterministic,
rng_seed_py);
traj_predictor = TrajectronPredictor(predictor_param,
scene_loader.model_dir,
scene_loader.param.conf_file_name,
device, verbose=false);
initialize_scene_graph!(traj_predictor, scene_loader);
ado_states = fetch_ado_positions!(scene_loader, return_full_state=true);
ado_positions = reduce_to_positions(ado_states);
dtc = 0.01;
sim_param = SimulationParameter(scene_loader, traj_predictor, dtc, cost_param);
# Initial conditions
ep = [-1., 3.5];
ev = [1., 1.];
t_init = Time(1.0);
e_init = RobotState([ep; ev], t_init);
ap_dict_init = convert_nodes_to_str(ado_positions);
t_last_m = Time(0.8);
w_init = WorldState(e_init, ap_dict_init, t_last_m);
# Target Trajectory
u_nominal_base = [0.0, 0.0];
u_array_base = [u_nominal_base for ii = 1:480];
wp1 = WayPoint2D([0.0, 0.0], Time(1.0));
wp2 = WayPoint2D([0.0, 0.0], Time(5, 8e8));
target_trajectory = Trajectory2D([wp1, wp2]);
# ControlParameter
eamax = 5.0;
tcalc = 0.1;
dtexec = [0.05, 0.01, 0.02];
dtr = 0.1;
nominal_search_depth = 2;
constraint_time = nothing;
u_nominal_cand = append!([[0.0, 0.0]],
[round.([a*cos(deg2rad(θ)), a*sin(deg2rad(θ))], digits=5)
for a = [2., 4.] for θ = 0.:45.:(360. - 45.)]) # nominal control candidate value [ax, ay] [m/s^2]
cnt_param = ControlParameter(eamax, tcalc, dtexec, dtr, u_nominal_base,
u_nominal_cand, nominal_search_depth,
constraint_time=constraint_time);
# Prediction Dict
prediction_dict = sample_future_ado_positions!(traj_predictor,
ado_states);
num_controls = length(cnt_param.u_nominal_cand)^nominal_search_depth;
for key in keys(prediction_dict)
prediction_dict[key] = repeat(prediction_dict[key], outer=(num_controls, 1, 1));
end
@test prediction_dict["PEDESTRIAN/25"][1:50, :, :] == prediction_dict["PEDESTRIAN/25"][51:100, :, :]
# # Helper functions test
# convert_to_schedule test
u_schedule = convert_to_schedule(w_init.t, u_array_base, sim_param);
@test length(u_schedule) == 480
@test all(collect(values(u_schedule)) .== [[0.0, 0.0]])
@test haskey(u_schedule, Time(1.0))
@test haskey(u_schedule, Time(1.01))
@test haskey(u_schedule, Time(5.79))
# get_nominal_u_arrays test: get nominal u_arrays from u_schedule and nominal control candidates
#u_nominal_mod_init_time = w_init.t + Duration(cnt_param.tcalc);
#u_nominal_mod_final_time = u_nominal_mod_init_time +
# Duration(sim_param.dto) -
# Duration(sim_param.dtc);
schedule_before = u_schedule;
u_arrays = get_nominal_u_arrays(u_schedule, sim_param, cnt_param);
@test all(u_arrays[1][1:end] .== [[0.0, 0.0]])
@test all([all(u_arrays[ii][1:10] .== [[0.0, 0.0]]) &&
all(u_arrays[ii][11:50] .== [u_nominal_cand[div(ii - 1, length(cnt_param.u_nominal_cand)) + 1]]) &&
all(u_arrays[ii][51:90] .== [u_nominal_cand[mod(ii - 1, length(cnt_param.u_nominal_cand)) + 1]]) &&
all(u_arrays[ii][91:end] .== [[0.0, 0.0]])
for ii = 2:length(cnt_param.u_nominal_cand)])
@test u_schedule == schedule_before
# get_robot_present_and_future_test
begin
e_state = RobotState([-5.0, 0.0, 0.0, 1.0]);
u_nominal = [[0.0, 0.0] for ii = 1:Int64(round(prediction_steps*sim_param.dto/dtc))];
u_s = convert_to_schedule(e_state.t, u_nominal, sim_param);
rpf = get_robot_present_and_future(e_state, u_s, sim_param, cnt_param);
@test size(rpf) == (17^nominal_search_depth, 13, 6)
@test all(isapprox.(cumsum(rpf[:, 1:end-1, 5:6], dims=2).*sim_param.dto .+ rpf[:, 1:1, 3:4], rpf[:, 2:end, 3:4], atol=1e-6))
end
# Get simulation result and best nominal u_array
sim_result, u_nominal_array = simulate(w_init, u_arrays, target_trajectory,
prediction_dict, sim_param, cnt_param.constraint_time);
# get_control_coeffs_test
coeff_matrix, coeff_matrix_constraint = get_control_coeffs(sim_result, sim_param, cnt_param);
#@test size(coeff_matrix) == (2, 20);
@test size(coeff_matrix) == (2, 480);
@test isnothing(coeff_matrix_constraint)
test_time_id = 11;
den_test = sum(exp.(σ_risk.*sim_result.sampled_total_costs));
num_test = sum(exp.(σ_risk.*sim_result.sampled_total_costs).*
[sim_result.e_costate_array[:, test_time_id, jj] for jj = 1:sim_param.num_samples]);
@test transition_control_coeff(sim_result.e_state_array[test_time_id])'*
(num_test./den_test) ≈ coeff_matrix[:, test_time_id];
# get_control_schedule test
control_schedule_array = get_control_schedule(sim_result, u_nominal_array, coeff_matrix,
sim_param, cnt_param);
#@test length(control_schedule_array) == Int64((tcalc+dtr)/dtc);
@test length(control_schedule_array) == Int64(round(sim_param.dto*sim_param.prediction_steps/dtc, digits=5));
@test maximum(map(s -> norm(vec(s.u)), control_schedule_array)) < eamax ||
maximum(map(s -> norm(vec(s.u)), control_schedule_array)) ≈ eamax;
@test !any(isnan.(map(s -> s.cost, control_schedule_array)));
# determine_control_time test
control_chosen = determine_control_time(sim_result,
control_schedule_array, sim_param,
cnt_param);
@test t_init + Duration(cnt_param.tcalc) + Duration(maximum(cnt_param.dtexec)) <= control_chosen.t;
#@test control_chosen.t <= t_init + Duration(cnt_param.tcalc) + Duration(cnt_param.dtr)
@test control_chosen.t <= t_init + Duration(sim_param.dto*sim_param.prediction_steps);
@test norm(control_chosen.u) < eamax || norm(control_chosen.u) ≈ eamax;
# sac_control_update_test
tcalc_actual, best_schedule, sim_result =
sac_control_update(w_init, u_schedule, target_trajectory, prediction_dict,
sim_param, cnt_param);
perturbation_times = [k for (k,v) in best_schedule if v==control_chosen.u];
if length(perturbation_times) > 1
@test best_schedule[control_chosen.t - Duration(dtc)] == control_chosen.u
@test best_schedule[control_chosen.t] != control_chosen.u
@test in(to_sec(perturbation_times[end] - perturbation_times[1]) + sim_param.dtc, cnt_param.dtexec)
end
# # Main functions test
u_schedule = convert_to_schedule(w_init.t, u_array_base, sim_param);
controller = RSSACController(traj_predictor, u_schedule, sim_param, cnt_param);
scene_loader = TrajectronSceneLoader(scene_param, verbose=false);
traj_predictor = TrajectronPredictor(predictor_param,
scene_loader.model_dir,
scene_loader.param.conf_file_name,
device, verbose=false);
initialize_scene_graph!(traj_predictor, scene_loader);
ado_states = fetch_ado_positions!(scene_loader, return_full_state=true);
ado_positions = reduce_to_positions(ado_states);
schedule_prediction!(controller, ado_states);
wait(controller.prediction_task);
@test istaskdone(controller.prediction_task);
@test controller.prediction_dict_tmp["PEDESTRIAN/25"][1:50, :, :] ==
controller.prediction_dict_tmp["PEDESTRIAN/25"][51:100, :, :]
schedule_control_update!(controller, w_init, target_trajectory);
@test !isnothing(controller.prediction_dict);
@test isnothing(controller.prediction_task);
wait(controller.control_update_task);
@test istaskdone(controller.control_update_task);
ado_positions_str = convert_nodes_to_str(ado_positions);
latest_ado_pos_dict = deepcopy(ado_positions_str);
ado_1 = collect(keys(latest_ado_pos_dict))[1];
ado_2 = collect(keys(latest_ado_pos_dict))[2];
prediction_array_ado_2 = copy(controller.prediction_dict[ado_2]);
latest_ado_pos_dict[ado_2] += [0.5, 0.5];
pop!(latest_ado_pos_dict, ado_1);
latest_ado_pos_dict["PEDESTRIAN/999"] = [1.0, 1.0];
adjust_old_prediction!(controller, ado_positions_str, latest_ado_pos_dict);
@test all(controller.prediction_dict[ado_2][:, :, 1] .- prediction_array_ado_2[:, :, 1] .≈ 0.5);
@test all(controller.prediction_dict[ado_2][:, :, 2] .- prediction_array_ado_2[:, :, 2] .≈ 0.5);
@test !in(controller.prediction_dict, ado_1);
@test size(controller.prediction_dict["PEDESTRIAN/999"]) == (num_samples*num_controls, sim_param.prediction_steps, 2);
@test all(controller.prediction_dict["PEDESTRIAN/999"][:, :, 1] .== 1.0)
@test all(controller.prediction_dict["PEDESTRIAN/999"][:, :, 2] .== 1.0)
u_1 = control!(controller, Time(1.0));
@test u_1 == [0.0, 0.0];
@test !isnothing(controller.sim_result);
@test !isnothing(controller.tcalc_actual);
#@test !isnothing(controller.u_init_time);
#@test !isnothing(controller.u_last_time);
#@test !isnothing(controller.u_value);
@test isnothing(controller.control_update_task);
# # constraint_time tests
constraint_time = 0.1;
cnt_param = ControlParameter(eamax, tcalc, dtexec, dtr, u_nominal_base,
u_nominal_cand, nominal_search_depth,
constraint_time=constraint_time);
# Get simulation result and best nominal u_array
sim_result, u_nominal_array = simulate(w_init, u_arrays, target_trajectory,
prediction_dict, sim_param, cnt_param.constraint_time);
# get_control_coeffs_test
coeff_matrix, coeff_matrix_constraint = get_control_coeffs(sim_result, sim_param, cnt_param);
#@test size(coeff_matrix) == (2, 20);
@test size(coeff_matrix) == (2, 480);
@test !isnothing(coeff_matrix_constraint)
@test size(coeff_matrix_constraint) == (2, 10);
u_array_constraint, cost_array_constraint = solve_multi_qcqp(u_nominal_array,
coeff_matrix,
coeff_matrix_constraint,
sim_param, cnt_param);
@test all([norm(u) <= cnt_param.eamax for u in u_array_constraint])
control_schedule_array_constraint =
get_control_schedule(sim_result, u_nominal_array, coeff_matrix,
sim_param, cnt_param, coeff_matrix_constraint);
@test all([s.u == u for (s, u) in zip(control_schedule_array_constraint[1:10], u_array_constraint)])
@test all([s.cost == cost for (s, cost) in zip(control_schedule_array_constraint[1:10], cost_array_constraint)])
@test all([s.t == s_constraint.t for (s, s_constraint) in zip(control_schedule_array[1:10], control_schedule_array_constraint[1:10])])
@test all([s.u == s_constraint.u for (s, s_constraint) in zip(control_schedule_array[11:20], control_schedule_array_constraint[11:20])])
@test all([s.cost == s_constraint.cost for (s, s_constraint) in zip(control_schedule_array[11:20], control_schedule_array_constraint[11:20])])
@test all([s.t == s_constraint.t for (s, s_constraint) in zip(control_schedule_array[11:20], control_schedule_array_constraint[11:20])])
# sac_control_update_test
tcalc_actual, best_schedule, sim_result =
sac_control_update(w_init, u_schedule, target_trajectory, prediction_dict,
sim_param, cnt_param);
end
|
#not currently used
#=
function get_data_info_oldversion(at_set, dim)
# very minor changes, see differs. This is soley for format conversion from old coefs to new format, which has extra 3body terms.
n_2body = 5
n_2body_onsite = 4
n_2body_S = 7
n_3body = 5 #differs. is 7 in the main version
n_3body_same = 5
n_3body_onsite = 4
n_3body_onsite_same = 2
data_info = Dict{Tuple, Array{Int64,1}}()
orbs = []
if dim == 2 #2body
at_list = [i for i in at_set]
# println(at_list)
if length(at_list) == 1
at_list = [at_list[1], at_list[1]]
end
sort!(at_list)
# println(at_list)
orbs1 = atoms[at_list[1]].orbitals
orbs2 = atoms[at_list[2]].orbitals
at1 = at_list[1]
at2 = at_list[2]
if at1 == at2
same_at = true
else
same_at = false
end
# orbs = []
#2body part
function get2bdy(n, symb)
tot=0
for o1 in orbs1
for o2 in orbs2
if same_at && ((o2 == :s && o1 == :p) || (o2 == :s && o1 == :d) || (o2 == :p && o1 == :d))
continue
end
# push!(orbs, (o1, o2, symb))
if o1 == :s && o2 == :s
data_info[(at1, o1, at2, o2, symb)] = tot+1:tot+n
data_info[(at2, o2, at1, o1, symb)] = tot+1:tot+n
tot += n
elseif (o1 == :s && o2 == :p ) || (o1 == :p && o2 == :s )
data_info[(at1, o1, at2, o2, symb)] = tot+1:tot+n
data_info[(at2, o2, at1, o1, symb)] = tot+1:tot+n
tot += n
# if same_at
# data_info[(o2, o1, symb)] = data_info[(o1, o2, symb)]
# end
elseif (o1 == :p && o2 == :p )
data_info[(at1, o1, at2, o2, symb)] = tot+1:tot+n*2
data_info[(at2, o2, at1, o1, symb)] = tot+1:tot+n*2
tot += n*2
# elseif (o1 == :p && o2 == :p )
# data_info[(at1, o1, at2, o2, symb)] = tot+1:tot+n*2
# data_info[(at2, o2, at1, o1, symb)] = tot+1:tot+n*2
# tot += n*2
elseif (o1 == :s && o2 == :d ) || (o1 == :d && o2 == :s )
data_info[(at1, o1, at2, o2, symb)] = tot+1:tot+n
data_info[(at2, o2, at1, o1, symb)] = tot+1:tot+n
tot += n
elseif (o1 == :p && o2 == :d ) || (o1 == :d && o2 == :p )
data_info[(at1, o1, at2, o2, symb)] = tot+1:tot+n*2
data_info[(at2, o2, at1, o1, symb)] = tot+1:tot+n*2
tot += n*2
elseif (o1 == :d && o2 == :d )
data_info[(at1, o1, at2, o2, symb)] = tot+1:tot+n*3
data_info[(at2, o2, at1, o1, symb)] = tot+1:tot+n*3
tot += n*3
end
end
end
return tot
end
totH = get2bdy(n_2body, :H)
totS = get2bdy(n_2body_S, :S)
# println("totH $totH totS $totS")
#onsite part
function getonsite(atX,orbsX, tot, n)
for o1 in orbsX
for o2 in orbsX
if (o2 == :s && o1 == :p) || (o2 == :s && o1 == :d) || (o2 == :p && o1 == :d)
continue
end
# push!(orbs, (o1, o2, :O))
if o1 == :s && o2 == :s
data_info[(atX, o1, o2, :O)] = tot+1:tot+n
# println("data_info" , (atX, o1, o2, :O), tot+1:tot+n)
tot += n
elseif (o1 == :s && o2 == :p )
data_info[(atX, o1, o2, :O)] = tot+1:tot+n
data_info[(atX, o2, o1, :O)] = data_info[(atX, o1, o2, :O)]
tot += n
elseif (o1 == :p && o2 == :p )
data_info[(atX, o1, o2, :O)] = tot+1:tot+n*2
tot += n*2
elseif o1 == :s && o2 == :d
data_info[(atX, o1, o2, :O)] = tot+1:tot+n
data_info[(atX, o2, o1, :O)] = data_info[(atX, o1, o2, :O)]
tot += n
elseif o1 == :p && o2 == :d
data_info[(atX, o1, o2, :O)] = tot+1:tot+n
data_info[(atX, o2, o1, :O)] = data_info[(atX, o1, o2, :O)]
tot += n
elseif o1 == :d && o2 == :d
data_info[(atX, o1, o2, :O)] = tot+1:tot+n*2
data_info[(atX, o2, o1, :O)] = data_info[(atX, o1, o2, :O)]
tot += n*2
end
end
end
return tot
end
if same_at #true onsite terms
for o in orbs1
# println("true onsite ", o)
data_info[(at1, o, :A)] = [totH+1]
totH += 1
end
end
totHO = getonsite(at1, orbs1, totH, n_2body_onsite)
if !(same_at) #need reverse if not same atom
totHO = getonsite(at2, orbs2, totHO, n_2body_onsite)
end
elseif dim == 3 #3body
totS = 0 #no 3body overlap terms
at_list = [i for i in at_set]
sort!(at_list)
if length(at_list) == 1
#permutations are trivial
perm_ij = [[at_list[1], at_list[1], at_list[1]]]
perm_on = [[at_list[1], at_list[1], at_list[1]]]
elseif length(at_list) == 2
#unique permutations
perm_ij = [[at_list[1], at_list[1], at_list[2]] ,
[at_list[2], at_list[2], at_list[1]] ,
[at_list[1], at_list[2], at_list[1]] ,
[at_list[1], at_list[2], at_list[2]] ]
perm_on = [[at_list[1], at_list[2], at_list[2]] ,
[at_list[1], at_list[1], at_list[2]] ,
[at_list[2], at_list[1], at_list[1]] ,
[at_list[2], at_list[1], at_list[2]] ]
elseif length(at_list) == 3
#all permutations exist hij
perm_ij = [[at_list[1], at_list[2], at_list[3]] ,
[at_list[1], at_list[3], at_list[2]] ,
[at_list[2], at_list[1], at_list[3]] ,
[at_list[2], at_list[3], at_list[1]] ,
[at_list[3], at_list[1], at_list[2]] ,
[at_list[3], at_list[2], at_list[1]] ]
#onsite can flip last 2 atoms
perm_on = [[at_list[1], at_list[2], at_list[3]] ,
[at_list[2], at_list[1], at_list[3]] ,
[at_list[3], at_list[1], at_list[2]]]
else
println("ERROR get_data_info $dim $at_set $at_list")
end
function get3bdy(n, symb, start, at1, at2, at3)
tot=start
orbs1 = atoms[at1].orbitals
orbs2 = atoms[at2].orbitals
if at1 == at2
same_at = true
else
same_at = false
end
for o1 in orbs1
for o2 in orbs2
if same_at && ((o2 == :s && o1 == :p) || (o2 == :s && o1 == :d) || (o2 == :p && o1 == :d))
continue
end
# push!(orbs, (o1, o2, symb))
if same_at
data_info[(at1, o1, at2, o2, at3, symb)] = collect(tot+1:tot+n)
data_info[(at2, o2, at1, o1, at3, symb)] = collect(tot+1:tot+n)
else #[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18]
data_info[(at1, o1, at2, o2, at3, symb)] = collect(tot+1:tot+n)
# data_info[(at2, o2, at1, o1, at3, symb)] = tot .+ [1 4 6 2 5 3 7 10 12 8 11 9 13 16 18 14 17 15]' #switch 2 4 and 3 6
# data_info[(at2, o2, at1, o1, at3, symb)] = tot .+ [1 4 6 2 5 3 7 10 12 8 11 9 ]' #switch 2 4 and 3 6
# data_info[(at2, o2, at1, o1, at3, symb)] = tot .+ [1 3 2 4 5 7 6 8 9]' #switch 2 4 and 3 6
# data_info[(at2, o2, at1, o1, at3, symb)] = tot .+ [1 3 2 4 5 7 6]' #switch 2 4 and 3 6
# data_info[(at2, o2, at1, o1, at3, symb)] = tot .+ [1 3 2 4 6 5]' #switch 2 4 and 3 6
# data_info[(at2, o2, at1, o1, at3, symb)] = tot .+ [1 3 2 4 6 5 7 9 8 ]' #switch 2 4 and 3 6
# data_info[(at2, o2, at1, o1, at3, symb)] = tot .+ [1, 3, 2, 4, 5, 7, 6 ] #switch 2 4 and 3 6
data_info[(at2, o2, at1, o1, at3, symb)] = tot .+ [1, 3, 2, 4, 5 ] #differs
end
tot += n
# if same_at
# data_info[(o2, o1, symb)] = data_info[(o1, o2, symb)]
# end
end
end
return tot
end
# if at_list[2] == at_list[3]
# same_at_on = true
# else
# same_at_on = false
# end
function get3bdy_onsite(n, same_at,symb, start, at1, at2, at3)
# if at2 == at3 #|| at1 == at2 || at1 == at3
# same_at = true
# else
# same_at = false
# end
orbs1 = atoms[at1].orbitals
# println("get3bdy_onsite $at1 $at2 $at3 $n")
tot=start
for o1 in orbs1
# data_info[(at1, o1,at2, at3, symb)] = collect(tot+1:tot+n)
# data_info[(at1, o1,at3, at2, symb)] = collect(tot+1:tot+n)
# push!(orbs, (at1, o1,at2, at3, symb))
# push!(orbs, (at1, o1,at3, at2, symb))
if same_at
data_info[(at1, o1,at2, at3, symb)] = collect(tot+1:tot+n)
data_info[(at1, o1,at3, at2, symb)] = collect(tot+1:tot+n)
else
data_info[(at1, o1,at2, at3, symb)] = collect(tot+1:tot+n)
# data_info[(at1, o1,at3, at2, symb)] = collect(tot+1:tot+n)
data_info[(at1, o1,at3, at2, symb)] = tot .+ [1, 3, 2, 4]
# data_info[(at1, o1,at2, at3, symb)] = collect(tot+1:tot+n)
# data_info[(at1, o1,at3, at2, symb)] = tot .+ [1 3 2 4]'
end
tot += n # 1 2 3 4 5 6 7 8
end
return tot
end
tot_size = 0
for p in perm_ij
if p[1] == p[2]
tot_size = get3bdy(n_3body_same, :H, tot_size, p[1], p[2], p[3])
else
tot_size = get3bdy(n_3body, :H, tot_size, p[1], p[2], p[3])
end
end
for p in perm_on
if (p[1] == p[2] || p[2] == p[3] || p[1] == p[3])
tot_size = get3bdy_onsite(n_3body_onsite_same,true, :O, tot_size, p[1], p[2], p[3]) #all diff
else
tot_size = get3bdy_onsite(n_3body_onsite,false, :O, tot_size, p[1], p[2], p[3]) #
end
end
totHO = tot_size
else
println("error, only 2 or 3 body terms, you gave me : ", at_list)
end
return totHO ,totS, data_info, orbs
end
function fix_format_change(datH, totHnew, dim, at_list, data_info)
#this converts from old data_info to new data_info, setting the extra terms to zero.
totH,totS, data_info_old, orbs = get_data_info_oldversion(at_list, dim)
datHnew = zeros(totHnew)
for k in keys(data_info)
dnew = data_info[k]
dold = data_info_old[k]
n=length(dold)
datHnew[dnew[1:n] ] = datH[dold] #the extra terms are left as zero
end
return datHnew
end
=#
|
using NonlinearEigenproblems
using SparseArrays
export RKNEP
export MatrixAndFunction
export LowRankMatrixAndFunction
export get_rk_nep
import Base.size
import ..NEPCore.compute_Mder
import ..NEPCore.compute_Mlincomb
import ..NEPTypes.get_Av
import ..NEPTypes.get_fv
import ..NEPTypes.LowRankFactorizedNEP
"NEP instance supplemented with various structures used for rational Krylov problems."
struct RKNEP{S<:AbstractMatrix{<:Number}, T<:Number}
nep::NEP # Original NEP problem
spmf::Bool # Whether this NEP is a sum a products of matrices and functions
p::Int # Order of polynomial part
q::Int # Number of nonlinear matrices and functions
BBCC::S # The polynomial and nonlinear matrices concatenated vertically
is_low_rank::Bool # Whether the nonlinear matrices of this NEP have an attached low rank LU factorization
r::Int # Sum of ranks of low rank nonlinear matrices
iL::Vector{Int} # Vector with indices of L-factors
iLr::Vector{Int} # Vector with row indices of L-factors that have any entries present
L::Vector{S} # Vector of L factors of low rank LU factorization of nonlinear part
LL::Vector{SparseVector{T,Int}} # Rows of L factors concatenated into vectors (only rows with nnz > 0 are stored)
UU::S # The U factors concatenated vertically
end
RKNEP(::Type{T}, nep::NEP) where T<:Number =
RKNEP(nep, false, 0, 0, Matrix{T}(undef, 0, 0), false, 0, Vector{Int}(), Vector{Int}(), Vector{Matrix{T}}(), Vector{SparseVector{T,Int}}(), Matrix{T}(undef, 0, 0))
RKNEP(nep::NEP, p, q, BBCC::AbstractMatrix{T}) where T<:Number =
RKNEP(nep, true, p, q, BBCC, false, 0, Vector{Int}(), Vector{Int}(), Vector{typeof(BBCC)}(), Vector{SparseVector{T,Int}}(), similar(BBCC, 0, 0))
RKNEP(nep::NEP, p, q, BBCC, r, iL, iLr, L, LL, UU) =
RKNEP(nep, true, p, q, BBCC, true, r, iL, iLr, L, LL, UU)
struct LowRankMatrixAndFunction{S<:AbstractMatrix{<:Number}}
A::S
L::S # L factor of LU-factorized A
U::S # U factor of LU-factorized A
f::Function
end
"Create low rank LU factorization of A."
function LowRankMatrixAndFunction(A::AbstractMatrix{<:Number}, f::Function)
L, U = low_rank_lu_factors(A)
LowRankMatrixAndFunction(A, L, U, f)
end
export LowRankFactorizedNEP
# Additional constructor for particle example
function LowRankFactorizedNEP(Amf::AbstractVector{LowRankMatrixAndFunction{S}}) where {T<:Number, S<:AbstractMatrix{T}}
# if A is not specified, create it from LU factors
A = [isempty(M.A) ? M.L * M.U' : M.A for M in Amf]
L = getfield.(Amf, :L)
U = getfield.(Amf, :U)
f = getfield.(Amf, :f)
rank = mapreduce(M -> size(M.U, 2), +, Amf)
return LowRankFactorizedNEP(SPMF_NEP(A, f, align_sparsity_patterns=true), rank, L, U)
end
function low_rank_lu_factors(A::SparseMatrixCSC{<:Number,Int})
n = size(A, 1)
idx = findall(!iszero, A)
r = extrema(getindex.(idx, 1))
c = extrema(getindex.(idx, 2))
B = A[r[1]:r[2], c[1]:c[2]]
L, U = lu(Matrix(B); check = false)
Lc, Uc = compactlu(sparse(L), sparse(U))
Lca = spzeros(n, size(Lc, 2))
Lca[r[1]:r[2], :] = Lc
Uca = spzeros(size(Uc, 1), n)
Uca[:, c[1]:c[2]] = Uc
return Lca, sparse(Uca')
# TODO use this; however we then need to support permutation and scaling
#F = lu(B)
#Lcf,Ucf = compactlu(sparse(F.L),sparse(F.U))
#Lcaf = spzeros(n, size(Lcf, 2))
#Lcaf[r[1]:r[2], :] = Lcf
#Ucaf = spzeros(size(Ucf, 1), n)
#Ucaf[:, c[1]:c[2]] = Ucf
#Ucaf = Ucaf'
end
function compactlu(L, U)
n = size(L, 1)
select = map(i -> nnz(L[i:n, i]) > 1 || nnz(U[i, i:n]) > 0, 1:n)
return L[:,select], U[select,:]
end
"Create RKNEP instance, exploiting the type of the input NEP as much as possible"
function get_rk_nep(::Type{T}, nep::NEP) where T<:Real
# Most generic case: No coefficient matrices, all we have is M(λ)
if !isa(nep, AbstractSPMF)
return RKNEP(T, nep)
end
Av = get_Av(nep)
BBCC = vcat(Av...)::eltype(Av)
# Polynomial eigenvalue problem
if isa(nep, PEP)
return RKNEP(nep, length(Av) - 1, 0, BBCC)
end
# If we can't separate the problem into a PEP + SPMF, consider it purely SPMF
if !isa(nep, SPMFSumNEP{PEP,S} where S<:AbstractSPMF)
return RKNEP(nep, -1, length(Av), BBCC)
end
p = length(get_Av(nep.nep1)) - 1
q = length(get_Av(nep.nep2))
# Case when there is no low rank structure to exploit
if q == 0 || !isa(nep.nep2, LowRankFactorizedNEP{S} where S<:Any)
return RKNEP(nep, p, q, BBCC)
end
# L and U factors of the low rank nonlinear part
L = nep.nep2.L
UU = hcat(nep.nep2.U...)::eltype(nep.nep2.U)
r = nep.nep2.r
iL = zeros(Int, r)
c = 0
for ii = 1:q
ri = size(L[ii], 2)
iL[c+1:c+ri] .= ii
c += ri
end
# Store L factors in a compact format to speed up system solves later on
LL = Vector{SparseVector{eltype(L[1]),Int}}()
iLr = Vector{Int}()
for ri = 1:size(nep, 1)
row = reduce(vcat, [L[i][ri,:] for i=1:length(L)])
if nnz(row) > 0
push!(LL, row)
push!(iLr, ri)
end
end
return RKNEP(nep, p, q, BBCC, r, iL, iLr, L, LL, UU)
end
|
using GLMakie, GeometryBasics, RPRMakie, RadeonProRender
using Colors, FileIO
using Colors: N0f8
RPR = RadeonProRender
context = RPR.Context()
matsys = RPR.MaterialSystem(context, 0)
materials = [
RPR.DiffuseMaterial(matsys) RPR.MicrofacetMaterial(matsys);
RPR.ReflectionMaterial(matsys) RPR.RefractionMaterial(matsys);
RPR.EmissiveMaterial(matsys) RPR.UberMaterial(matsys);
]
cat = load(GLMakie.assetpath("cat.obj"))
fig = Figure(resolution=(1000, 1000))
ax = LScene(fig[1, 1], scenekw=(show_axis=false,))
palette = reshape(Makie.default_palettes.color[][1:6], size(materials))
for i in CartesianIndices(materials)
x, y = Tuple(i)
catmesh = mesh!(ax, cat, material=materials[i], color=palette[i])
translate!(catmesh, x, y, 0)
end
# materials[3, 1].color = Vec4(200)
display(fig)
context, task = RPRMakie.replace_scene_rpr!(ax.scene, context, matsys)
# fetch(task)
volmat = materials[end, end]
volmat.scattering = Vec3(0, 0, 0)
volmat.absorption = RGB(0.01, 0.01, 0.01)
volmat.multiscatter = true
# volmat.emission = RPR.RPR_MATERIAL_INPUT_EMISSION,
# volmat.scatter_direction = RPR.RPR_MATERIAL_INPUT_G,
|
module DF
using Base.Iterators
import IterTools: nth
import Base: show, first, last, iterate, size, length, ndims,
summary, getindex, setindex!, ∘, iszero, isone,
isless
#import Base.∘
export Segment, DirectProduct, BooleanCube
export DiscreteFunction, ResidueFunction, ExtendedResidueFunction, BooleanFunction
export FunProduct, FunTupling
export tablegen
export domain, codomain
export BooleanGenerator, ResidueGenerator, ExtendedResidueGenerator
export FunProductGenerator, FunTuplingGenerator
# short names
export DProd, BCube
export DFun, ResFun, ExtFun, BoolFun, FProd, FTuple
export BoolGen, ResGen, ExtGen, FTGen, FPGen
include("finite_sets.jl")
include("types.jl")
include("helper_utils.jl")
include("generators.jl")
include("boolean/boolean.jl")
include("compositions.jl")
end # module
|
using StatsFuns: logistic
using Base: setindex!, getindex
"""
Nonparametric discrete distribution with parameters in logit space.
This represents a discrete distribution with p.m.f of
```math
P(K = k) = (1 - \\rho_k) \\prod_{i = 1}^{k - 1} \\rho_i.
```
"""
struct LogitNPD{T<:Real,A<:AbstractVector{T}} <: Distributions.DiscreteUnivariateDistribution
logitρ :: A
l_init :: T # initial value for each logitρᵢ
end
LogitNPD(; l_init=zero(Double)) = LogitNPD(0; l_init=l_init)
LogitNPD(alpha::AbstractFloat; l_init=zero(Double)) = LogitNPD(ceil(Int, alpha); l_init=l_init)
LogitNPD(k_init::Int; l_init=zero(Double)) = LogitNPD(ones(Double, k_init) * l_init, l_init)
function getlogitρ(lnpd::LogitNPD{T,A}, k::Int) where {T<:Real,A<:AbstractVector{T}}
l = length(lnpd.logitρ)
if k > l
append!(lnpd.logitρ, ones(T, k - l) * lnpd.l_init...)
end
return lnpd.logitρ[k]
end
function getlogitρ(lnpd::LogitNPD{T,A}, k1::Int, k2::Int) where {T<:Real,A<:AbstractVector{T}}
l = length(lnpd.logitρ)
if k2 > l
append!(lnpd.logitρ, ones(T, k2 - l) * lnpd.l_init...)
end
return lnpd.logitρ[k1:k2]
end
getρ(lnpd::LogitNPD, k...) = logistic.(getlogitρ(lnpd, k...))
function getlogρ(lnpd::LogitNPD, k...)
l = getlogitρ(lnpd, k...)
return l .- log1pexp.(l)
end
function pdf(lnpd::LogitNPD, k::Int)
if k <= 0
return 0
elseif k == 1
return 1 - getρ(lnpd, 1)
else
return prod(getρ(lnpd, 1, k - 1)) * (1 - getρ(lnpd, k))
end
end
function logpdf(lnpd::LogitNPD, k::Int)
if k <= 0
return -Inf
elseif k == 1
return log(1 - getρ(lnpd, 1))
else
return sum(getlogrho(lnpd, 1, k - 1)) + log(1 - getρ(lnpd, k))
end
end
function ccdf(lnpd::LogitNPD{T,A}, k::Int) where {T<:Real,A<:AbstractVector{T}}
if k <= 0
return one(T)
else
return prod(getρ(lnpd, 1, k))
end
end
function cdf(lnpd::LogitNPD, k::Int)
return 1 - ccdf(lnpd, k)
end
function rand(lnpd::LogitNPD{T,A}) where {T<:Real,A<:AbstractVector{T}}
i = 1
while true
u = rand(T)
if u > getρ(lnpd, i)
return i
end
i = i + 1
end
end
function rand(lnpd::LogitNPD{T,A}, n::Int) where {T<:Real,A<:AbstractVector{T}}
return Int[rand(lnpd) for _ = 1:n]
end
function mode(lnpd::LogitNPD)
p = pdf(lnpd, 1)
p_acc = p_max = p
k = k_max = 1
while p_max < 1 - p_acc
p_next = pdf(lnpd, k + 1)
p_acc += p_next
if p_next > p_max
p_max = p_next
k_max = k
end
k = k + 1
end
return k_max
end
function invlogcdf(lnpd::LogitNPD, lc::AbstractFloat)
p_target = exp(lc)
k = 1
p = pdf(lnpd, 1)
p_acc = p
while p_acc < p_target
k += 1
p_acc += pdf(lnpd, k)
end
return k
end
|
abstract type Event end
abstract type ObjEvent <: Event end
abstract type BaseEvent <: ObjEvent end # Basic || influencial
abstract type HighLvlEvent <: ObjEvent end #
abstract type UniverseEvent <: Event end
# Obj Events
#- Base
#-- Disappear
struct Disappear <: BaseEvent
end
#-- Appear
struct Appear <: BaseEvent
end
#-- Move
struct Move <: BaseEvent
dr::Vector{Int64}
end
#-- ReSize
struct ReSize <: BaseEvent
newSize::Int64
end
#- High level
struct ReDirection <: HighLvlEvent
newDirection::Vector{Int64}
end
#-- Swallow
struct Swallow <: HighLvlEvent
end
#-- Slip
struct Slip <: HighLvlEvent
upAndDown::Int64
end
#-- ReFre
struct ReFres <: HighLvlEvent
newFres::Vector{Float64}
end
# Universe Event
struct IntroduceRandomDefects <: UniverseEvent
numDefects::Int64
maxSize::Int64
end
# Event Container
mutable struct EventContainer{T<:Event}
fre::Float64
fres::Vector{Float64}
events::Vector{T}
end |
"""
Constant that represents document term vector (DTV) models used in text embedding.
"""
const DTVModel{T,S} = Union{
StringAnalysis.RPModel{S,T,<:AbstractMatrix{T},<:Integer},
StringAnalysis.LSAModel{S,T,<:AbstractMatrix{T},<:Integer}
}
"""
Structure for document embedding using DTV's.
"""
struct DTVEmbedder{T,S} <: AbstractEmbedder{T,S}
model::DTVModel{T,S}
config::NamedTuple
end
DTVEmbedder(mtype::Type{<:DTVModel}, dtm, config; kwargs...) = DTVEmbedder(mtype(dtm; kwargs...), config)
# Document to vector embedding function
function __document2vec(embedder::DTVEmbedder{T,S},
document::Vector{String}; # a vector of sentences
isregex::Bool=false,
kwargs... # for the unused arguments
)::SparseVector{T, Int} where {T,S}
dtv_function = ifelse(isregex, dtv_regex, dtv)
words = Vector{String}()
for sentence in document
for word in tokenize(sentence, method=:stringanalysis)
push!(words, word)
end
end
vocab_hash = embedder.model.vocab_hash
model = embedder.model
v = dtv_function(words, vocab_hash, T;
ngram_complexity=embedder.config.ngram_complexity,
tokenizer=DEFAULT_TOKENIZER,
lex_is_row_indices=true)
embedded_document = StringAnalysis.embed_document(model, v)
return embedded_document
end
function document2vec(embedder::DTVEmbedder{T,S},
document::Vector{String}; # a vector of sentences
isregex::Bool=false,
kwargs... # for the unused arguments
)::Tuple{SparseVector{T, Int}, Bool} where {T,S}
embedded_document = __document2vec(embedder,
document;
isregex=isregex,
kwargs...)
is_embedded = !iszero(embedded_document)
# Check for OOV (out-of-vocabulary) policy
if embedder.config.oov_policy == :large_vector && !is_embedded
embedded_document .= T(DEFAULT_OOV_VAL)
end
return embedded_document, is_embedded
end
# Dimensionality function
function dimensionality(embedder::DTVEmbedder)
# Return output dimensionality (second dim)
return size(embedder.model)[2]
end
|
# 1.1 UE-BMI under benchmark scenario
# NOTE: it is a 4-subfigure figure
# 1.1.1 second, define a temp expr to save code lines
tmpexpr = :(
xlabel("Year"); ylabel("Percentage (%)"); grid(true);
xlim([ idx_year2plot[1] - 1, idx_year2plot[end] + 1 ]);
plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* dict_Demog_base["AgingPopuRatio"][idx_plot], "--b" );
plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* (1.0 .- dict_Demog_base["WorkPopuRatio"] )[idx_plot], "-.r" );
)
# 1.1.2 then, do plotting
figure( figsize = (13,8) )
subplot(2,2,1) # gap / pooling account's expenditure
plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* (DatPkg_base.Dt[:LI]./DatPkg_base.Dt[:AggPoolExp])[idx_plot] )
eval(tmpexpr)
legend( ("Pool Gap/Pool Benefits","Aging Population Share (65+)",L"\rho"), loc = "best")
subplot(2,2,2) # gap / pooling account's income
plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* (DatPkg_base.Dt[:LI]./DatPkg_base.Dt[:AggPoolIn])[idx_plot] )
eval(tmpexpr)
legend( ("Pool Gap/Pool Incomes","Aging Population Share (65+)",L"\rho"), loc = "best")
subplot(2,2,3) # gap / GDP
plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* (DatPkg_base.Dt[:LI]./DatPkg_base.Dt[:Y])[idx_plot] )
eval(tmpexpr)
legend( ("Pool Gap/GDP","Aging Population Share (65+)",L"\rho"), loc = "best")
subplot(2,2,4) # gap / fiscal incomes
plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* (DatPkg_base.Dt[:LI]./(DatPkg_base.Dt[:TRw] .+ DatPkg_base.Dt[:TRc]))[idx_plot] )
eval(tmpexpr)
legend( ("Pool Gap/Tax Revenues","Aging Population Share (65+)",L"\rho"), loc = "best")
tight_layout() # tight layout of the figure
# 1.1.3 finally, save the figure as a pdf file
savefig( "./output/BenchProfile.pdf", format = "pdf" )
# -----------------------------------------
# 1.2 simulation v.s. accounting
# 1.2.1 do underlying plotting & read in accounting data
EasyPlot.Plot_Calibrate( DatPkg_base.Dt, DatPkg_base.Dst, DatPkg_base.Pt, DatPkg_base.Ps, DatPkg_base.Pc, env,
YearRange = ( 2010, 2050 ), LineWidth = 1.0, outpdf = nothing, picsize = (12,9),
tmpLayout = (2,1)
)
tmpDat = EasyIO.readcsv("./data/Calib_统筹账户收支核算结果v3_190403.csv")
tmpEndTime = 40 + 2
# 1.2.2 decoration (NOTE: do not new a figure GUI, just decorate the current one)
subplot(2,1,1)
plot( tmpDat[2:tmpEndTime,1] , 100.0 .* tmpDat[2:tmpEndTime,4] ./ tmpDat[2:tmpEndTime,2] , "-.r" )
legend(["Baseline simulation","Pooling gap / Pooling account expenditure"],
fontsize = 14)
subplot(2,1,2)
plot( tmpDat[2:tmpEndTime,1] , 100.0 .* tmpDat[2:tmpEndTime,4] ./ tmpDat[2:tmpEndTime,3] , "-.r" )
legend(["Baseline simulation","Pooling gap / Pooling account revenues"],
fontsize = 14)
tight_layout()
# 1.2.3 save figure
savefig( "./output/BenchmarkCpAccount.pdf", format = "pdf" )
#
|
using Caesar, Caesar.ZmqCaesar
using Distributions
using LinearAlgebra
# Distribution: AliasingScalarSampler
packed = Packed_AliasingScalarSampler(collect(1:10), collect(11:20), 0, "AliasingScalarSampler")
json = JSON.json(packed)
sampler = convert(IncrementalInference.AliasingScalarSampler, JSON.parse(json))
packedCompare = convert(Packed_AliasingScalarSampler, sampler)
jsonCompare = JSON.json(packedCompare)
# Distribution: Normal
normal = Normal(5.0, 10.0)
packed = convert(Dict{String, Any}, normal)
back = convert(Normal, JSON.parse(JSON.json(packed)))
# Factor: PartialPriorRollPitchZ
a = MvNormal([0, 0, 0, 0], Matrix(LinearAlgebra.I, 4, 4))
b = Normal(0, 1)
partPrior = PartialPriorRollPitchZ(a, b)
j = JSON.json(convert(Dict{String, Any}, partPrior))
# Test the deserializer
back = convert(PartialPriorRollPitchZ, JSON.parse(j))
jback = JSON.json(convert(Dict{String, Any}, back))
jback = j
|
# This file is a part of Julia. License is MIT: https://julialang.org/license
const Chars = Union{AbstractChar,Tuple{Vararg{<:AbstractChar}},AbstractVector{<:AbstractChar},Set{<:AbstractChar}}
# starts with and ends with predicates
"""
startswith(s::AbstractString, prefix::AbstractString)
Return `true` if `s` starts with `prefix`. If `prefix` is a vector or set
of characters, test whether the first character of `s` belongs to that set.
See also [`endswith`](@ref).
# Examples
```jldoctest
julia> startswith("JuliaLang", "Julia")
true
```
"""
function startswith(a::AbstractString, b::AbstractString)
a, b = Iterators.Stateful(a), Iterators.Stateful(b)
all(splat(==), zip(a, b)) && isempty(b)
end
startswith(str::AbstractString, chars::Chars) = !isempty(str) && first(str)::AbstractChar in chars
"""
endswith(s::AbstractString, suffix::AbstractString)
Return `true` if `s` ends with `suffix`. If `suffix` is a vector or set of
characters, test whether the last character of `s` belongs to that set.
See also [`startswith`](@ref).
# Examples
```jldoctest
julia> endswith("Sunday", "day")
true
```
"""
function endswith(a::AbstractString, b::AbstractString)
a = Iterators.Stateful(Iterators.reverse(a))
b = Iterators.Stateful(Iterators.reverse(b))
all(splat(==), zip(a, b)) && isempty(b)
end
endswith(str::AbstractString, chars::Chars) = !isempty(str) && last(str) in chars
function startswith(a::Union{String, SubString{String}},
b::Union{String, SubString{String}})
cub = ncodeunits(b)
if ncodeunits(a) < cub
false
elseif _memcmp(a, b, sizeof(b)) == 0
nextind(a, cub) == cub + 1
else
false
end
end
function endswith(a::Union{String, SubString{String}},
b::Union{String, SubString{String}})
cub = ncodeunits(b)
astart = ncodeunits(a) - ncodeunits(b) + 1
if astart < 1
false
elseif GC.@preserve(a, _memcmp(pointer(a, astart), b, sizeof(b))) == 0
thisind(a, astart) == astart
else
false
end
end
"""
contains(haystack::AbstractString, needle)
Return `true` if `haystack` contains `needle`.
This is the same as `occursin(needle, haystack)`, but is provided for consistency with
`startswith(haystack, needle)` and `endswith(haystack, needle)`.
# Examples
```jldoctest
julia> contains("JuliaLang is pretty cool!", "Julia")
true
julia> contains("JuliaLang is pretty cool!", 'a')
true
julia> contains("aba", r"a.a")
true
julia> contains("abba", r"a.a")
false
```
!!! compat "Julia 1.5"
The `contains` function requires at least Julia 1.5.
"""
contains(haystack::AbstractString, needle) = occursin(needle, haystack)
"""
endswith(suffix)
Create a function that checks whether its argument ends with `suffix`, i.e.
a function equivalent to `y -> endswith(y, suffix)`.
The returned function is of type `Base.Fix2{typeof(endswith)}`, which can be
used to implement specialized methods.
!!! compat "Julia 1.5"
The single argument `endswith(suffix)` requires at least Julia 1.5.
# Examples
```jldoctest
julia> endswith_julia = endswith("Julia");
julia> endswith_julia("Julia")
true
julia> endswith_julia("JuliaLang")
false
```
"""
endswith(s) = Base.Fix2(endswith, s)
"""
startswith(prefix)
Create a function that checks whether its argument starts with `prefix`, i.e.
a function equivalent to `y -> startswith(y, prefix)`.
The returned function is of type `Base.Fix2{typeof(startswith)}`, which can be
used to implement specialized methods.
!!! compat "Julia 1.5"
The single argument `startswith(prefix)` requires at least Julia 1.5.
# Examples
```jldoctest
julia> startswith_julia = startswith("Julia");
julia> startswith_julia("Julia")
true
julia> startswith_julia("NotJulia")
false
```
"""
startswith(s) = Base.Fix2(startswith, s)
"""
contains(needle)
Create a function that checks whether its argument contains `needle`, i.e.
a function equivalent to `haystack -> contains(haystack, needle)`.
The returned function is of type `Base.Fix2{typeof(contains)}`, which can be
used to implement specialized methods.
"""
contains(needle) = Base.Fix2(contains, needle)
"""
chop(s::AbstractString; head::Integer = 0, tail::Integer = 1)
Remove the first `head` and the last `tail` characters from `s`.
The call `chop(s)` removes the last character from `s`.
If it is requested to remove more characters than `length(s)`
then an empty string is returned.
# Examples
```jldoctest
julia> a = "March"
"March"
julia> chop(a)
"Marc"
julia> chop(a, head = 1, tail = 2)
"ar"
julia> chop(a, head = 5, tail = 5)
""
```
"""
function chop(s::AbstractString; head::Integer = 0, tail::Integer = 1)
if isempty(s)
return SubString(s)
end
SubString(s, nextind(s, firstindex(s), head), prevind(s, lastindex(s), tail))
end
# TODO: optimization for the default case based on
# chop(s::AbstractString) = SubString(s, firstindex(s), prevind(s, lastindex(s)))
"""
chomp(s::AbstractString) -> SubString
Remove a single trailing newline from a string.
# Examples
```jldoctest
julia> chomp("Hello\\n")
"Hello"
```
"""
function chomp(s::AbstractString)
i = lastindex(s)
(i < 1 || s[i] != '\n') && (return SubString(s, 1, i))
j = prevind(s,i)
(j < 1 || s[j] != '\r') && (return SubString(s, 1, j))
return SubString(s, 1, prevind(s,j))
end
function chomp(s::String)
i = lastindex(s)
if i < 1 || codeunit(s,i) != 0x0a
return @inbounds SubString(s, 1, i)
elseif i < 2 || codeunit(s,i-1) != 0x0d
return @inbounds SubString(s, 1, prevind(s, i))
else
return @inbounds SubString(s, 1, prevind(s, i-1))
end
end
"""
lstrip([pred=isspace,] str::AbstractString) -> SubString
lstrip(str::AbstractString, chars) -> SubString
Remove leading characters from `str`, either those specified by `chars` or those for
which the function `pred` returns `true`.
The default behaviour is to remove leading whitespace and delimiters: see
[`isspace`](@ref) for precise details.
The optional `chars` argument specifies which characters to remove: it can be a single
character, or a vector or set of characters.
# Examples
```jldoctest
julia> a = lpad("March", 20)
" March"
julia> lstrip(a)
"March"
```
"""
function lstrip(f, s::AbstractString)
e = lastindex(s)
for (i::Int, c::AbstractChar) in pairs(s)
!f(c) && return @inbounds SubString(s, i, e)
end
SubString(s, e+1, e)
end
lstrip(s::AbstractString) = lstrip(isspace, s)
lstrip(s::AbstractString, chars::Chars) = lstrip(in(chars), s)
"""
rstrip([pred=isspace,] str::AbstractString) -> SubString
rstrip(str::AbstractString, chars) -> SubString
Remove trailing characters from `str`, either those specified by `chars` or those for
which the function `pred` returns `true`.
The default behaviour is to remove trailing whitespace and delimiters: see
[`isspace`](@ref) for precise details.
The optional `chars` argument specifies which characters to remove: it can be a single
character, or a vector or set of characters.
# Examples
```jldoctest
julia> a = rpad("March", 20)
"March "
julia> rstrip(a)
"March"
```
"""
function rstrip(f, s::AbstractString)
for (i, c) in Iterators.reverse(pairs(s))
f(c::AbstractChar) || return @inbounds SubString(s, 1, i::Int)
end
SubString(s, 1, 0)
end
rstrip(s::AbstractString) = rstrip(isspace, s)
rstrip(s::AbstractString, chars::Chars) = rstrip(in(chars), s)
"""
strip([pred=isspace,] str::AbstractString) -> SubString
strip(str::AbstractString, chars) -> SubString
Remove leading and trailing characters from `str`, either those specified by `chars` or
those for which the function `pred` returns `true`.
The default behaviour is to remove leading whitespace and delimiters: see
[`isspace`](@ref) for precise details.
The optional `chars` argument specifies which characters to remove: it can be a single
character, vector or set of characters.
!!! compat "Julia 1.2"
The method which accepts a predicate function requires Julia 1.2 or later.
# Examples
```jldoctest
julia> strip("{3, 5}\\n", ['{', '}', '\\n'])
"3, 5"
```
"""
strip(s::AbstractString) = lstrip(rstrip(s))
strip(s::AbstractString, chars::Chars) = lstrip(rstrip(s, chars), chars)
strip(f, s::AbstractString) = lstrip(f, rstrip(f, s))
## string padding functions ##
"""
lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> String
Stringify `s` and pad the resulting string on the left with `p` to make it `n`
characters (code points) long. If `s` is already `n` characters long, an equal
string is returned. Pad with spaces by default.
# Examples
```jldoctest
julia> lpad("March", 10)
" March"
```
"""
lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') = lpad(string(s)::AbstractString, n, string(p))
function lpad(
s::Union{AbstractChar,AbstractString},
n::Integer,
p::Union{AbstractChar,AbstractString}=' ',
) :: String
n = Int(n)::Int
m = signed(n) - Int(length(s))::Int
m ≤ 0 && return string(s)
l = length(p)
q, r = divrem(m, l)
r == 0 ? string(p^q, s) : string(p^q, first(p, r), s)
end
"""
rpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> String
Stringify `s` and pad the resulting string on the right with `p` to make it `n`
characters (code points) long. If `s` is already `n` characters long, an equal
string is returned. Pad with spaces by default.
# Examples
```jldoctest
julia> rpad("March", 20)
"March "
```
"""
rpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') = rpad(string(s)::AbstractString, n, string(p))
function rpad(
s::Union{AbstractChar,AbstractString},
n::Integer,
p::Union{AbstractChar,AbstractString}=' ',
) :: String
n = Int(n)::Int
m = signed(n) - Int(length(s))::Int
m ≤ 0 && return string(s)
l = length(p)
q, r = divrem(m, l)
r == 0 ? string(s, p^q) : string(s, p^q, first(p, r))
end
"""
split(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
split(str::AbstractString; limit::Integer=0, keepempty::Bool=false)
Split `str` into an array of substrings on occurrences of the delimiter(s) `dlm`. `dlm`
can be any of the formats allowed by [`findnext`](@ref)'s first argument (i.e. as a
string, regular expression or a function), or as a single character or collection of
characters.
If `dlm` is omitted, it defaults to [`isspace`](@ref).
The optional keyword arguments are:
- `limit`: the maximum size of the result. `limit=0` implies no maximum (default)
- `keepempty`: whether empty fields should be kept in the result. Default is `false` without
a `dlm` argument, `true` with a `dlm` argument.
See also [`rsplit`](@ref).
# Examples
```jldoctest
julia> a = "Ma.rch"
"Ma.rch"
julia> split(a, ".")
2-element Vector{SubString{String}}:
"Ma"
"rch"
```
"""
function split end
function split(str::T, splitter;
limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString}
_split(str, splitter, limit, keepempty, T <: SubString ? T[] : SubString{T}[])
end
function split(str::T, splitter::Union{Tuple{Vararg{<:AbstractChar}},AbstractVector{<:AbstractChar},Set{<:AbstractChar}};
limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString}
_split(str, in(splitter), limit, keepempty, T <: SubString ? T[] : SubString{T}[])
end
function split(str::T, splitter::AbstractChar;
limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString}
_split(str, isequal(splitter), limit, keepempty, T <: SubString ? T[] : SubString{T}[])
end
function _split(str::AbstractString, splitter::F, limit::Integer, keepempty::Bool, strs::Vector) where F
# Forcing specialization on `splitter` improves performance (roughly 30% decrease in runtime)
# and prevents a major invalidation risk (1550 MethodInstances)
i = 1 # firstindex(str)
n = lastindex(str)::Int
r = findfirst(splitter,str)::Union{Nothing,Int,UnitRange{Int}}
if !isnothing(r)
j, k = first(r), nextind(str,last(r))::Int
while 0 < j <= n && length(strs) != limit-1
if i < k
if keepempty || i < j
push!(strs, @inbounds SubString(str,i,prevind(str,j)::Int))
end
i = k
end
(k <= j) && (k = nextind(str,j)::Int)
r = findnext(splitter,str,k)::Union{Nothing,Int,UnitRange{Int}}
isnothing(r) && break
j, k = first(r), nextind(str,last(r))::Int
end
end
if keepempty || i <= ncodeunits(str)::Int
push!(strs, @inbounds SubString(str,i))
end
return strs
end
# a bit oddball, but standard behavior in Perl, Ruby & Python:
split(str::AbstractString;
limit::Integer=0, keepempty::Bool=false) =
split(str, isspace; limit=limit, keepempty=keepempty)
"""
rsplit(s::AbstractString; limit::Integer=0, keepempty::Bool=false)
rsplit(s::AbstractString, chars; limit::Integer=0, keepempty::Bool=true)
Similar to [`split`](@ref), but starting from the end of the string.
# Examples
```jldoctest
julia> a = "M.a.r.c.h"
"M.a.r.c.h"
julia> rsplit(a, ".")
5-element Vector{SubString{String}}:
"M"
"a"
"r"
"c"
"h"
julia> rsplit(a, "."; limit=1)
1-element Vector{SubString{String}}:
"M.a.r.c.h"
julia> rsplit(a, "."; limit=2)
2-element Vector{SubString{String}}:
"M.a.r.c"
"h"
```
"""
function rsplit end
function rsplit(str::T, splitter;
limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString}
_rsplit(str, splitter, limit, keepempty, T <: SubString ? T[] : SubString{T}[])
end
function rsplit(str::T, splitter::Union{Tuple{Vararg{<:AbstractChar}},AbstractVector{<:AbstractChar},Set{<:AbstractChar}};
limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString}
_rsplit(str, in(splitter), limit, keepempty, T <: SubString ? T[] : SubString{T}[])
end
function rsplit(str::T, splitter::AbstractChar;
limit::Integer=0, keepempty::Bool=true) where {T<:AbstractString}
_rsplit(str, isequal(splitter), limit, keepempty, T <: SubString ? T[] : SubString{T}[])
end
function _rsplit(str::AbstractString, splitter, limit::Integer, keepempty::Bool, strs::Array)
n = lastindex(str)::Int
r = something(findlast(splitter, str)::Union{Nothing,Int,UnitRange{Int}}, 0)
j, k = first(r), last(r)
while j > 0 && k > 0 && length(strs) != limit-1
(keepempty || k < n) && pushfirst!(strs, @inbounds SubString(str,nextind(str,k)::Int,n))
n = prevind(str, j)::Int
r = something(findprev(splitter,str,n)::Union{Nothing,Int,UnitRange{Int}}, 0)
j, k = first(r), last(r)
end
(keepempty || n > 0) && pushfirst!(strs, SubString(str,1,n))
return strs
end
rsplit(str::AbstractString;
limit::Integer=0, keepempty::Bool=false) =
rsplit(str, isspace; limit=limit, keepempty=keepempty)
_replace(io, repl, str, r, pattern) = print(io, repl)
_replace(io, repl::Function, str, r, pattern) =
print(io, repl(SubString(str, first(r), last(r))))
_replace(io, repl::Function, str, r, pattern::Function) =
print(io, repl(str[first(r)]))
replace(str::String, pat_repl::Pair{<:AbstractChar}; count::Integer=typemax(Int)) =
replace(str, isequal(first(pat_repl)) => last(pat_repl); count=count)
replace(str::String, pat_repl::Pair{<:Union{Tuple{Vararg{<:AbstractChar}},
AbstractVector{<:AbstractChar},Set{<:AbstractChar}}};
count::Integer=typemax(Int)) =
replace(str, in(first(pat_repl)) => last(pat_repl), count=count)
_pat_replacer(x) = x
_free_pat_replacer(x) = nothing
function replace(str::String, pat_repl::Pair; count::Integer=typemax(Int))
pattern, repl = pat_repl
count == 0 && return str
count < 0 && throw(DomainError(count, "`count` must be non-negative."))
n = 1
e = lastindex(str)
i = a = firstindex(str)
pattern = _pat_replacer(pattern)
r = something(findnext(pattern,str,i), 0)
j, k = first(r), last(r)
if j == 0
_free_pat_replacer(pattern)
return str
end
out = IOBuffer(sizehint=floor(Int, 1.2sizeof(str)))
while j != 0
if i == a || i <= k
GC.@preserve str unsafe_write(out, pointer(str, i), UInt(j-i))
_replace(out, repl, str, r, pattern)
end
if k < j
i = j
j > e && break
k = nextind(str, j)
else
i = k = nextind(str, k)
end
r = something(findnext(pattern,str,k), 0)
r === 0:-1 || n == count && break
j, k = first(r), last(r)
n += 1
end
_free_pat_replacer(pattern)
write(out, SubString(str,i))
String(take!(out))
end
"""
replace(s::AbstractString, pat=>r; [count::Integer])
Search for the given pattern `pat` in `s`, and replace each occurrence with `r`.
If `count` is provided, replace at most `count` occurrences.
`pat` may be a single character, a vector or a set of characters, a string,
or a regular expression.
If `r` is a function, each occurrence is replaced with `r(s)`
where `s` is the matched substring (when `pat` is a `AbstractPattern` or `AbstractString`) or
character (when `pat` is an `AbstractChar` or a collection of `AbstractChar`).
If `pat` is a regular expression and `r` is a [`SubstitutionString`](@ref), then capture group
references in `r` are replaced with the corresponding matched text.
To remove instances of `pat` from `string`, set `r` to the empty `String` (`""`).
# Examples
```jldoctest
julia> replace("Python is a programming language.", "Python" => "Julia")
"Julia is a programming language."
julia> replace("The quick foxes run quickly.", "quick" => "slow", count=1)
"The slow foxes run quickly."
julia> replace("The quick foxes run quickly.", "quick" => "", count=1)
"The foxes run quickly."
julia> replace("The quick foxes run quickly.", r"fox(es)?" => s"bus\\1")
"The quick buses run quickly."
```
"""
replace(s::AbstractString, pat_f::Pair; count=typemax(Int)) =
replace(String(s), pat_f, count=count)
# TODO: allow transform as the first argument to replace?
# hex <-> bytes conversion
"""
hex2bytes(s::Union{AbstractString,AbstractVector{UInt8}})
Given a string or array `s` of ASCII codes for a sequence of hexadecimal digits, returns a
`Vector{UInt8}` of bytes corresponding to the binary representation: each successive pair
of hexadecimal digits in `s` gives the value of one byte in the return vector.
The length of `s` must be even, and the returned array has half of the length of `s`.
See also [`hex2bytes!`](@ref) for an in-place version, and [`bytes2hex`](@ref) for the inverse.
# Examples
```jldoctest
julia> s = string(12345, base = 16)
"3039"
julia> hex2bytes(s)
2-element Vector{UInt8}:
0x30
0x39
julia> a = b"01abEF"
6-element Base.CodeUnits{UInt8, String}:
0x30
0x31
0x61
0x62
0x45
0x46
julia> hex2bytes(a)
3-element Vector{UInt8}:
0x01
0xab
0xef
```
"""
function hex2bytes end
hex2bytes(s::AbstractString) = hex2bytes(String(s))
hex2bytes(s::Union{String,AbstractVector{UInt8}}) = hex2bytes!(Vector{UInt8}(undef, length(s) >> 1), s)
_firstbyteidx(s::String) = 1
_firstbyteidx(s::AbstractVector{UInt8}) = first(eachindex(s))
_lastbyteidx(s::String) = sizeof(s)
_lastbyteidx(s::AbstractVector{UInt8}) = lastindex(s)
"""
hex2bytes!(d::AbstractVector{UInt8}, s::Union{String,AbstractVector{UInt8}})
Convert an array `s` of bytes representing a hexadecimal string to its binary
representation, similar to [`hex2bytes`](@ref) except that the output is written in-place
in `d`. The length of `s` must be exactly twice the length of `d`.
"""
function hex2bytes!(d::AbstractVector{UInt8}, s::Union{String,AbstractVector{UInt8}})
if 2length(d) != sizeof(s)
isodd(sizeof(s)) && throw(ArgumentError("input hex array must have even length"))
throw(ArgumentError("output array must be half length of input array"))
end
j = first(eachindex(d)) - 1
for i = _firstbyteidx(s):2:_lastbyteidx(s)
@inbounds d[j += 1] = number_from_hex(_nthbyte(s,i)) << 4 + number_from_hex(_nthbyte(s,i+1))
end
return d
end
@inline number_from_hex(c) =
(UInt8('0') <= c <= UInt8('9')) ? c - UInt8('0') :
(UInt8('A') <= c <= UInt8('F')) ? c - (UInt8('A') - 0x0a) :
(UInt8('a') <= c <= UInt8('f')) ? c - (UInt8('a') - 0x0a) :
throw(ArgumentError("byte is not an ASCII hexadecimal digit"))
"""
bytes2hex(a::AbstractArray{UInt8}) -> String
bytes2hex(io::IO, a::AbstractArray{UInt8})
Convert an array `a` of bytes to its hexadecimal string representation, either
returning a `String` via `bytes2hex(a)` or writing the string to an `io` stream
via `bytes2hex(io, a)`. The hexadecimal characters are all lowercase.
# Examples
```jldoctest
julia> a = string(12345, base = 16)
"3039"
julia> b = hex2bytes(a)
2-element Vector{UInt8}:
0x30
0x39
julia> bytes2hex(b)
"3039"
```
"""
function bytes2hex end
function bytes2hex(a::Union{NTuple{<:Any, UInt8}, AbstractArray{UInt8}})
b = Base.StringVector(2*length(a))
@inbounds for (i, x) in enumerate(a)
b[2i - 1] = hex_chars[1 + x >> 4]
b[2i ] = hex_chars[1 + x & 0xf]
end
return String(b)
end
function bytes2hex(io::IO, a::Union{NTuple{<:Any, UInt8}, AbstractArray{UInt8}})
for x in a
print(io, Char(hex_chars[1 + x >> 4]), Char(hex_chars[1 + x & 0xf]))
end
end
# check for pure ASCII-ness
function ascii(s::String)
for i in 1:sizeof(s)
@inbounds codeunit(s, i) < 0x80 || __throw_invalid_ascii(s, i)
end
return s
end
@noinline __throw_invalid_ascii(s::String, i::Int) = throw(ArgumentError("invalid ASCII at index $i in $(repr(s))"))
"""
ascii(s::AbstractString)
Convert a string to `String` type and check that it contains only ASCII data, otherwise
throwing an `ArgumentError` indicating the position of the first non-ASCII byte.
# Examples
```jldoctest
julia> ascii("abcdeγfgh")
ERROR: ArgumentError: invalid ASCII at index 6 in "abcdeγfgh"
Stacktrace:
[...]
julia> ascii("abcdefgh")
"abcdefgh"
```
"""
ascii(x::AbstractString) = ascii(String(x))
Base.rest(s::Union{String,SubString{String}}, i=1) = SubString(s, i)
function Base.rest(s::AbstractString, st...)
io = IOBuffer()
for c in Iterators.rest(s, st...)
print(io, c)
end
return String(take!(io))
end
|
int_rules_1_1_1_7 = @theory begin
#= ::Subsection::Closed:: =#
#= 1.1.1.7*P(x)*(a+b*x)^m*(c+d*x)^n*(e+f*x)^p*(g+h*x)^q =#
@apply_utils Antiderivative(~Px * (~a + ~(b') * (~x) ^ ~n) ^ ~p, ~x) => (Coeff(~Px, ~x, ~n - 1) * (~a + ~b * (~x) ^ ~n) ^ (~p + 1)) / (~b * ~n * (~p + 1)) + Antiderivative((~Px - Coeff(~Px, ~x, ~n - 1) * (~x) ^ (~n - 1)) * (~a + ~b * (~x) ^ ~n) ^ ~p, ~x) <-- FreeQ([~a, ~b], ~x) && (PolyQ(~Px, ~x) && (IGtQ(~p, 1) && (IGtQ(~n, 1) && (NeQ(Coeff(~Px, ~x, ~n - 1), 0) && (NeQ(~Px, Coeff(~Px, ~x, ~n - 1) * (~x) ^ (~n - 1)) && Not(MatchQ(~Px, ~(Qx') * (~c + ~(d') * (~x) ^ ~m) ^ ~q <-- FreeQ([c, d], ~x) && (PolyQ(Qx, ~x) && (IGtQ(q, 1) && (IGtQ(m, 1) && (NeQ(Coeff(Qx * (~a + ~b * (~x) ^ ~n) ^ ~p, ~x, m - 1), 0) && GtQ(m * q, ~n * ~p))))))))))))
@apply_utils Antiderivative(~Px * (~x) ^ ~(m') * (~a + ~(b') * (~x) ^ ~(n')) ^ ~p, ~x) => (Coeff(~Px, ~x, (~n - ~m) - 1) * (~a + ~b * (~x) ^ ~n) ^ (~p + 1)) / (~b * ~n * (~p + 1)) + Antiderivative((~Px - Coeff(~Px, ~x, (~n - ~m) - 1) * (~x) ^ ((~n - ~m) - 1)) * (~x) ^ ~m * (~a + ~b * (~x) ^ ~n) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~m, ~n], ~x) && (PolyQ(~Px, ~x) && (IGtQ(~p, 1) && (IGtQ(~n - ~m, 0) && NeQ(Coeff(~Px, ~x, (~n - ~m) - 1), 0))))
@apply_utils Antiderivative(~(u') * (~x) ^ ~(m') * (~(a') * (~x) ^ ~(p') + ~(b') * (~x) ^ ~(q')) ^ ~(n'), ~x) => Antiderivative(~u * (~x) ^ (~m + ~n * ~p) * (~a + ~b * (~x) ^ (~q - ~p)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~m, ~p, ~q], ~x) && (IntegerQ(~n) && PosQ(~q - ~p))
@apply_utils Antiderivative(~(u') * (~x) ^ ~(m') * (~(a') * (~x) ^ ~(p') + ~(b') * (~x) ^ ~(q') + ~(c') * (~x) ^ ~(r')) ^ ~(n'), ~x) => Antiderivative(~u * (~x) ^ (~m + ~n * ~p) * (~a + ~b * (~x) ^ (~q - ~p) + ~c * (~x) ^ (~r - ~p)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~c, ~m, ~p, ~q, ~r], ~x) && (IntegerQ(~n) && (PosQ(~q - ~p) && PosQ(~r - ~p)))
@apply_utils Antiderivative(~(u') * (~Px) ^ ~(p') * (~Qx) ^ ~(q'), ~x) => Antiderivative(~u * PolynomialQuotient(~Px, ~Qx, ~x) ^ ~p * (~Qx) ^ (~p + ~q), ~x) <-- FreeQ(~q, ~x) && (PolyQ(~Px, ~x) && (PolyQ(~Qx, ~x) && (EqQ(PolynomialRemainder(~Px, ~Qx, ~x), 0) && (IntegerQ(~p) && LtQ(~p * ~q, 0)))))
@apply_utils Antiderivative(~Pp / ~Qq, ~x) => With([p = Expon(~Pp, ~x), q = Expon(~Qq, ~x)], (Coeff(~Pp, ~x, p) * log(RemoveContent(~Qq, ~x))) / (q * Coeff(~Qq, ~x, q)) <-- EqQ(p, q - 1) && EqQ(~Pp, Simplify((Coeff(~Pp, ~x, p) / (q * Coeff(~Qq, ~x, q))) * D(~Qq, ~x)))) <-- PolyQ(~Pp, ~x) && PolyQ(~Qq, ~x)
@apply_utils Antiderivative(~Pp * (~Qq) ^ ~(m'), ~x) => With([p = Expon(~Pp, ~x), q = Expon(~Qq, ~x)], (Coeff(~Pp, ~x, p) * (~x) ^ ((p - q) + 1) * (~Qq) ^ (~m + 1)) / ((p + ~m * q + 1) * Coeff(~Qq, ~x, q)) <-- NeQ(p + ~m * q + 1, 0) && EqQ((p + ~m * q + 1) * Coeff(~Qq, ~x, q) * ~Pp, Coeff(~Pp, ~x, p) * (~x) ^ (p - q) * (((p - q) + 1) * ~Qq + (~m + 1) * ~x * D(~Qq, ~x)))) <-- FreeQ(~m, ~x) && (PolyQ(~Pp, ~x) && (PolyQ(~Qq, ~x) && NeQ(~m, -1)))
@apply_utils Antiderivative((~x) ^ ~(m') * (~a1 + ~(b1') * (~x) ^ ~(n')) ^ ~p * (~a2 + ~(b2') * (~x) ^ ~(n')) ^ ~p, ~x) => ((~a1 + ~b1 * (~x) ^ ~n) ^ (~p + 1) * (~a2 + ~b2 * (~x) ^ ~n) ^ (~p + 1)) / (2 * ~b1 * ~b2 * ~n * (~p + 1)) <-- FreeQ([~a1, ~b1, ~a2, ~b2, ~m, ~n, ~p], ~x) && (EqQ(~a2 * ~b1 + ~a1 * ~b2, 0) && (EqQ((~m - 2 * ~n) + 1, 0) && NeQ(~p, -1)))
@apply_utils Antiderivative(~Pp * (~Qq) ^ ~(m') * (~Rr) ^ ~(n'), ~x) => With([p = Expon(~Pp, ~x), q = Expon(~Qq, ~x), r = Expon(~Rr, ~x)], (Coeff(~Pp, ~x, p) * (~x) ^ (((p - q) - r) + 1) * (~Qq) ^ (~m + 1) * (~Rr) ^ (~n + 1)) / ((p + ~m * q + ~n * r + 1) * Coeff(~Qq, ~x, q) * Coeff(~Rr, ~x, r)) <-- NeQ(p + ~m * q + ~n * r + 1, 0) && EqQ((p + ~m * q + ~n * r + 1) * Coeff(~Qq, ~x, q) * Coeff(~Rr, ~x, r) * ~Pp, Coeff(~Pp, ~x, p) * (~x) ^ ((p - q) - r) * ((((p - q) - r) + 1) * ~Qq * ~Rr + (~m + 1) * ~x * ~Rr * D(~Qq, ~x) + (~n + 1) * ~x * ~Qq * D(~Rr, ~x)))) <-- FreeQ([~m, ~n], ~x) && (PolyQ(~Pp, ~x) && (PolyQ(~Qq, ~x) && (PolyQ(~Rr, ~x) && (NeQ(~m, -1) && NeQ(~n, -1)))))
@apply_utils Antiderivative(~Qr * (~(a') + ~(b') * (~Pq) ^ ~(n')) ^ ~(p'), ~x) => With([q = Expon(~Pq, ~x), r = Expon(~Qr, ~x)], (Coeff(~Qr, ~x, r) / (q * Coeff(~Pq, ~x, q))) * Subst(Antiderivative((~a + ~b * (~x) ^ ~n) ^ ~p, ~x), ~x, ~Pq) <-- EqQ(r, q - 1) && EqQ(Coeff(~Qr, ~x, r) * D(~Pq, ~x), q * Coeff(~Pq, ~x, q) * ~Qr)) <-- FreeQ([~a, ~b, ~n, ~p], ~x) && (PolyQ(~Pq, ~x) && PolyQ(~Qr, ~x))
@apply_utils Antiderivative(~Qr * (~(a') + ~(b') * (~Pq) ^ ~(n') + ~(c') * (~Pq) ^ ~(n2')) ^ ~(p'), ~x) => Module([q = Expon(~Pq, ~x), r = Expon(~Qr, ~x)], (Coeff(~Qr, ~x, r) / (q * Coeff(~Pq, ~x, q))) * Subst(Antiderivative((~a + ~b * (~x) ^ ~n + ~c * (~x) ^ (2 * ~n)) ^ ~p, ~x), ~x, ~Pq) <-- EqQ(r, q - 1) && EqQ(Coeff(~Qr, ~x, r) * D(~Pq, ~x), q * Coeff(~Pq, ~x, q) * ~Qr)) <-- FreeQ([~a, ~b, ~c, ~n, ~p], ~x) && (EqQ(~n2, 2 * ~n) && (PolyQ(~Pq, ~x) && PolyQ(~Qr, ~x)))
@apply_utils Antiderivative(~(u') * (~(a') * (~x) ^ ~(p') + ~(b') * (~x) ^ ~(q')) ^ ~(n'), ~x) => Antiderivative(~u * (~x) ^ (~n * ~p) * (~a + ~b * (~x) ^ (~q - ~p)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~p, ~q], ~x) && (IntegerQ(~n) && PosQ(~q - ~p))
@apply_utils Antiderivative(~(u') * (~(a') * (~x) ^ ~(p') + ~(b') * (~x) ^ ~(q') + ~(c') * (~x) ^ ~(r')) ^ ~(n'), ~x) => Antiderivative(~u * (~x) ^ (~n * ~p) * (~a + ~b * (~x) ^ (~q - ~p) + ~c * (~x) ^ (~r - ~p)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~c, ~p, ~q, ~r], ~x) && (IntegerQ(~n) && (PosQ(~q - ~p) && PosQ(~r - ~p)))
#= Antiderivative(sqrt((~a')+(~b')*(~x))*((~A')+(~B')*(~x))/(sqrt((~c')+(~d')*(~x))*sqrt((~e')+(~f')*(~x) )*sqrt((~g')+(~h')*(~x))),~x) := B*sqrt(a+b*x)*sqrt(e+f*x)*sqrt(g+h*x)/(f*h*sqrt(c+d*x)) - B*(b*g-a*h)/(2*f*h)*Antiderivative(sqrt(e+f*x)/(sqrt(a+b*x)*sqrt(c+d*x)*sqrt(g+ h*x)),x) + B*(d*e-c*f)*(d*g-c*h)/(2*d*f*h)*Antiderivative(sqrt(a+b*x)/((c+d*x)^(3/2)*sqrt( e+f*x)*sqrt(g+h*x)),x) <-- FreeQ([a,b,c,d,e,f,g,h,A,B],x) && EqQ(2*A*d*f-B*(d*e+c*f),0) =#
@apply_utils Antiderivative((sqrt(~(a') + ~(b') * ~x) * (~(A') + ~(B') * ~x)) / (sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => ((~b * ~B * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)) / (~d * ~f * ~h * sqrt(~a + ~b * ~x)) - ((~B * (~b * ~g - ~a * ~h)) / (2 * ~f * ~h)) * Antiderivative(sqrt(~e + ~f * ~x) / (sqrt(~a + ~b * ~x) * sqrt(~c + ~d * ~x) * sqrt(~g + ~h * ~x)), ~x)) + ((~B * (~b * ~e - ~a * ~f) * (~b * ~g - ~a * ~h)) / (2 * ~d * ~f * ~h)) * Antiderivative(sqrt(~c + ~d * ~x) / ((~a + ~b * ~x) ^ (3 / 2) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~B], ~x) && EqQ(2 * ~A * ~d * ~f - ~B * (~d * ~e + ~c * ~f), 0)
#= Antiderivative(sqrt((~a')+(~b')*(~x))*((~A')+(~B')*(~x))/(sqrt((~c')+(~d')*(~x))*sqrt((~e')+(~f')*(~x) )*sqrt((~g')+(~h')*(~x))),~x) := (2*A*d*f-B*(d*e+c*f))/(2*d*f)*Antiderivative(sqrt(a+b*x)/(sqrt(c+d*x)*sqrt(e+f*x) *sqrt(g+h*x)),x) + B/(2*d*f)*Antiderivative((sqrt(a+b*x)*(d*e+c*f+2*d*f*x))/(sqrt(c+d*x)*sqrt(e+f* x)*sqrt(g+h*x)),x) <-- FreeQ([a,b,c,d,e,f,g,h,A,B],x) && NeQ(2*A*d*f-B*(d*e+c*f),0) =#
@apply_utils Antiderivative((sqrt(~(a') + ~(b') * ~x) * (~(A') + ~(B') * ~x)) / (sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => (((~B * sqrt(~a + ~b * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)) / (~f * ~h * sqrt(~c + ~d * ~x)) + ((~B * (~d * ~e - ~c * ~f) * (~d * ~g - ~c * ~h)) / (2 * ~d * ~f * ~h)) * Antiderivative(sqrt(~a + ~b * ~x) / ((~c + ~d * ~x) ^ (3 / 2) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)), ~x)) - ((~B * (~b * ~e - ~a * ~f) * (~b * ~g - ~a * ~h)) / (2 * ~b * ~f * ~h)) * Antiderivative(1 / (sqrt(~a + ~b * ~x) * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)), ~x)) + ((2 * ~A * ~b * ~d * ~f * ~h + ~B * (~a * ~d * ~f * ~h - ~b * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h))) / (2 * ~b * ~d * ~f * ~h)) * Antiderivative(sqrt(~a + ~b * ~x) / (sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~B], ~x) && NeQ(2 * ~A * ~d * ~f - ~B * (~d * ~e + ~c * ~f), 0)
@apply_utils Antiderivative(((~(a') + ~(b') * ~x) ^ ~(m') * (~(A') + ~(B') * ~x)) / (sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => (1 / (~d * ~f * ~h * (2 * ~m + 3))) * Antiderivative(((~a + ~b * ~x) ^ (~m - 1) / (sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x))) * Simp(~a * ~A * ~d * ~f * ~h * (2 * ~m + 3) + (~A * ~b + ~a * ~B) * ~d * ~f * ~h * (2 * ~m + 3) * ~x + ~b * ~B * ~d * ~f * ~h * (2 * ~m + 3) * (~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~B], ~x) && (IntegerQ(2 * ~m) && GtQ(~m, 0))
@apply_utils Antiderivative((~(A') + ~(B') * ~x) / (sqrt(~(a') + ~(b') * ~x) * sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => ((~A * ~b - ~a * ~B) / ~b) * Antiderivative(1 / (sqrt(~a + ~b * ~x) * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)), ~x) + (~B / ~b) * Antiderivative(sqrt(~a + ~b * ~x) / (sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~B], ~x)
@apply_utils Antiderivative(((~(a') + ~(b') * ~x) ^ ~m * (~(A') + ~(B') * ~x)) / (sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => ((~A * (~b) ^ 2 - ~a * ~b * ~B) * (~a + ~b * ~x) ^ (~m + 1) * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)) / ((~m + 1) * (~b * ~c - ~a * ~d) * (~b * ~e - ~a * ~f) * (~b * ~g - ~a * ~h)) - (1 / (2 * (~m + 1) * (~b * ~c - ~a * ~d) * (~b * ~e - ~a * ~f) * (~b * ~g - ~a * ~h))) * Antiderivative(((~a + ~b * ~x) ^ (~m + 1) / (sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x))) * Simp(((~A * ((2 * (~a) ^ 2 * ~d * ~f * ~h * (~m + 1) - 2 * ~a * ~b * (~m + 1) * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h)) + (~b) ^ 2 * (2 * ~m + 3) * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h)) - ~b * ~B * (~a * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h) + 2 * ~b * ~c * ~e * ~g * (~m + 1))) - 2 * ((~A * ~b - ~a * ~B) * (~a * ~d * ~f * ~h * (~m + 1) - ~b * (~m + 2) * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h))) * ~x) + ~d * ~f * ~h * (2 * ~m + 5) * (~A * (~b) ^ 2 - ~a * ~b * ~B) * (~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~B], ~x) && (IntegerQ(2 * ~m) && LtQ(~m, -1))
@apply_utils Antiderivative(((~(a') + ~(b') * ~x) ^ ~(m') * (~(A') + ~(B') * ~x + ~(C') * (~x) ^ 2)) / (sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => (2 * ~C * (~a + ~b * ~x) ^ ~m * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)) / (~d * ~f * ~h * (2 * ~m + 3)) + (1 / (~d * ~f * ~h * (2 * ~m + 3))) * Antiderivative(((~a + ~b * ~x) ^ (~m - 1) / (sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x))) * Simp((~a * ~A * ~d * ~f * ~h * (2 * ~m + 3) - ~C * (~a * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h) + 2 * ~b * ~c * ~e * ~g * ~m)) + ((~A * ~b + ~a * ~B) * ~d * ~f * ~h * (2 * ~m + 3) - ~C * (2 * ~a * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h) + ~b * (2 * ~m + 1) * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h))) * ~x + (~b * ~B * ~d * ~f * ~h * (2 * ~m + 3) + 2 * ~C * (~a * ~d * ~f * ~h * ~m - ~b * (~m + 1) * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h))) * (~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~B, ~C], ~x) && (IntegerQ(2 * ~m) && GtQ(~m, 0))
@apply_utils Antiderivative(((~(a') + ~(b') * ~x) ^ ~(m') * (~(A') + ~(C') * (~x) ^ 2)) / (sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => (2 * ~C * (~a + ~b * ~x) ^ ~m * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)) / (~d * ~f * ~h * (2 * ~m + 3)) + (1 / (~d * ~f * ~h * (2 * ~m + 3))) * Antiderivative(((~a + ~b * ~x) ^ (~m - 1) / (sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x))) * Simp((~a * ~A * ~d * ~f * ~h * (2 * ~m + 3) - ~C * (~a * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h) + 2 * ~b * ~c * ~e * ~g * ~m)) + (~A * ~b * ~d * ~f * ~h * (2 * ~m + 3) - ~C * (2 * ~a * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h) + ~b * (2 * ~m + 1) * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h))) * ~x + 2 * ~C * (~a * ~d * ~f * ~h * ~m - ~b * (~m + 1) * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h)) * (~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~C], ~x) && (IntegerQ(2 * ~m) && GtQ(~m, 0))
@apply_utils Antiderivative((~(A') + ~(B') * ~x + ~(C') * (~x) ^ 2) / (sqrt(~(a') + ~(b') * ~x) * sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => (~C * sqrt(~a + ~b * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)) / (~b * ~f * ~h * sqrt(~c + ~d * ~x)) + ((~C * (~d * ~e - ~c * ~f) * (~d * ~g - ~c * ~h)) / (2 * ~b * ~d * ~f * ~h)) * Antiderivative(sqrt(~a + ~b * ~x) / ((~c + ~d * ~x) ^ (3 / 2) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)), ~x) + (1 / (2 * ~b * ~d * ~f * ~h)) * Antiderivative((1 / (sqrt(~a + ~b * ~x) * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x))) * Simp((2 * ~A * ~b * ~d * ~f * ~h - ~C * (~b * ~d * ~e * ~g + ~a * ~c * ~f * ~h)) + (2 * ~b * ~B * ~d * ~f * ~h - ~C * (~a * ~d * ~f * ~h + ~b * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h))) * ~x, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~B, ~C], ~x)
@apply_utils Antiderivative((~(A') + ~(C') * (~x) ^ 2) / (sqrt(~(a') + ~(b') * ~x) * sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => (~C * sqrt(~a + ~b * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)) / (~b * ~f * ~h * sqrt(~c + ~d * ~x)) + ((~C * (~d * ~e - ~c * ~f) * (~d * ~g - ~c * ~h)) / (2 * ~b * ~d * ~f * ~h)) * Antiderivative(sqrt(~a + ~b * ~x) / ((~c + ~d * ~x) ^ (3 / 2) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)), ~x) + (1 / (2 * ~b * ~d * ~f * ~h)) * Antiderivative((1 / (sqrt(~a + ~b * ~x) * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x))) * Simp((2 * ~A * ~b * ~d * ~f * ~h - ~C * (~b * ~d * ~e * ~g + ~a * ~c * ~f * ~h)) - ~C * (~a * ~d * ~f * ~h + ~b * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h)) * ~x, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~C], ~x)
@apply_utils Antiderivative(((~(a') + ~(b') * ~x) ^ ~m * (~(A') + ~(B') * ~x + ~(C') * (~x) ^ 2)) / (sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => (((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C) * (~a + ~b * ~x) ^ (~m + 1) * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)) / ((~m + 1) * (~b * ~c - ~a * ~d) * (~b * ~e - ~a * ~f) * (~b * ~g - ~a * ~h)) - (1 / (2 * (~m + 1) * (~b * ~c - ~a * ~d) * (~b * ~e - ~a * ~f) * (~b * ~g - ~a * ~h))) * Antiderivative(((~a + ~b * ~x) ^ (~m + 1) / (sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x))) * Simp(((~A * ((2 * (~a) ^ 2 * ~d * ~f * ~h * (~m + 1) - 2 * ~a * ~b * (~m + 1) * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h)) + (~b) ^ 2 * (2 * ~m + 3) * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h)) - (~b * ~B - ~a * ~C) * (~a * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h) + 2 * ~b * ~c * ~e * ~g * (~m + 1))) - 2 * ((~A * ~b - ~a * ~B) * (~a * ~d * ~f * ~h * (~m + 1) - ~b * (~m + 2) * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h)) - ~C * (((~a) ^ 2 * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h) - (~b) ^ 2 * ~c * ~e * ~g * (~m + 1)) + ~a * ~b * (~m + 1) * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h))) * ~x) + ~d * ~f * ~h * (2 * ~m + 5) * ((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C) * (~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~B, ~C], ~x) && (IntegerQ(2 * ~m) && LtQ(~m, -1))
@apply_utils Antiderivative(((~(a') + ~(b') * ~x) ^ ~m * (~(A') + ~(C') * (~x) ^ 2)) / (sqrt(~(c') + ~(d') * ~x) * sqrt(~(e') + ~(f') * ~x) * sqrt(~(g') + ~(h') * ~x)), ~x) => ((~A * (~b) ^ 2 + (~a) ^ 2 * ~C) * (~a + ~b * ~x) ^ (~m + 1) * sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x)) / ((~m + 1) * (~b * ~c - ~a * ~d) * (~b * ~e - ~a * ~f) * (~b * ~g - ~a * ~h)) - (1 / (2 * (~m + 1) * (~b * ~c - ~a * ~d) * (~b * ~e - ~a * ~f) * (~b * ~g - ~a * ~h))) * Antiderivative(((~a + ~b * ~x) ^ (~m + 1) / (sqrt(~c + ~d * ~x) * sqrt(~e + ~f * ~x) * sqrt(~g + ~h * ~x))) * Simp(((~A * ((2 * (~a) ^ 2 * ~d * ~f * ~h * (~m + 1) - 2 * ~a * ~b * (~m + 1) * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h)) + (~b) ^ 2 * (2 * ~m + 3) * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h)) + ~a * ~C * (~a * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h) + 2 * ~b * ~c * ~e * ~g * (~m + 1))) - 2 * (~A * ~b * (~a * ~d * ~f * ~h * (~m + 1) - ~b * (~m + 2) * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h)) - ~C * (((~a) ^ 2 * (~d * ~f * ~g + ~d * ~e * ~h + ~c * ~f * ~h) - (~b) ^ 2 * ~c * ~e * ~g * (~m + 1)) + ~a * ~b * (~m + 1) * (~d * ~e * ~g + ~c * ~f * ~g + ~c * ~e * ~h))) * ~x) + ~d * ~f * ~h * (2 * ~m + 5) * (~A * (~b) ^ 2 + (~a) ^ 2 * ~C) * (~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~A, ~C], ~x) && (IntegerQ(2 * ~m) && LtQ(~m, -1))
@apply_utils Antiderivative(~Px * (~(a') + ~(b') * ~x) ^ ~(m') * (~(c') + ~(d') * ~x) ^ ~(n') * (~(e') + ~(f') * ~x) ^ ~(p') * (~(g') + ~(h') * ~x) ^ ~(q'), ~x) => Antiderivative(ExpandIntegrand(~Px * (~a + ~b * ~x) ^ ~m * (~c + ~d * ~x) ^ ~n * (~e + ~f * ~x) ^ ~p * (~g + ~h * ~x) ^ ~q, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~m, ~n, ~p, ~q], ~x) && (PolyQ(~Px, ~x) && IntegersQ(~m, ~n))
@apply_utils Antiderivative(~Px * (~(a') + ~(b') * ~x) ^ ~(m') * (~(c') + ~(d') * ~x) ^ ~(n') * (~(e') + ~(f') * ~x) ^ ~(p') * (~(g') + ~(h') * ~x) ^ ~(q'), ~x) => PolynomialRemainder(~Px, ~a + ~b * ~x, ~x) * Antiderivative((~a + ~b * ~x) ^ ~m * (~c + ~d * ~x) ^ ~n * (~e + ~f * ~x) ^ ~p * (~g + ~h * ~x) ^ ~q, ~x) + Antiderivative(PolynomialQuotient(~Px, ~a + ~b * ~x, ~x) * (~a + ~b * ~x) ^ (~m + 1) * (~c + ~d * ~x) ^ ~n * (~e + ~f * ~x) ^ ~p * (~g + ~h * ~x) ^ ~q, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~m, ~n, ~p, ~q], ~x) && (PolyQ(~Px, ~x) && EqQ(~m, -1))
@apply_utils Antiderivative(~Px * (~(a') + ~(b') * ~x) ^ ~(m') * (~(c') + ~(d') * ~x) ^ ~(n') * (~(e') + ~(f') * ~x) ^ ~(p') * (~(g') + ~(h') * ~x) ^ ~(q'), ~x) => PolynomialRemainder(~Px, ~a + ~b * ~x, ~x) * Antiderivative((~a + ~b * ~x) ^ ~m * (~c + ~d * ~x) ^ ~n * (~e + ~f * ~x) ^ ~p * (~g + ~h * ~x) ^ ~q, ~x) + Antiderivative(PolynomialQuotient(~Px, ~a + ~b * ~x, ~x) * (~a + ~b * ~x) ^ (~m + 1) * (~c + ~d * ~x) ^ ~n * (~e + ~f * ~x) ^ ~p * (~g + ~h * ~x) ^ ~q, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h, ~m, ~n, ~p, ~q], ~x) && PolyQ(~Px, ~x)
end
|
module TestDBI
using DBI
using DBDSQLite
# User database
path = Pkg.dir("DBDSQLite", "test", "db", "users.sqlite3")
run(`touch $path`)
db = connect(SQLite3, path)
stmt = prepare(
db,
"CREATE TABLE users (id INT NOT NULL, name VARCHAR(255))"
)
@assert executed(stmt) == 0
execute(stmt)
@assert executed(stmt) == 1
finish(stmt)
try
stmt = prepare(
db,
"CREATE TABLE users (id INT NOT NULL, name VARCHAR(255))"
)
end
errcode(db)
errstring(db)
stmt = prepare(db, "INSERT INTO users VALUES (1, 'Jeff Bezanson')")
execute(stmt)
finish(stmt)
stmt = prepare(db, "INSERT INTO users VALUES (2, 'Viral Shah')")
execute(stmt)
finish(stmt)
run(db, "INSERT INTO users VALUES (3, 'Stefan Karpinski')")
stmt = prepare(db, "INSERT INTO users VALUES (?, ?)")
execute(stmt, {4, "Jameson Nash"})
execute(stmt, {5, "Keno Fisher"})
finish(stmt)
stmt = prepare(db, "SELECT * FROM users")
execute(stmt)
row = fetchrow(stmt)
row = fetchrow(stmt)
row = fetchrow(stmt)
row = fetchrow(stmt)
row = fetchrow(stmt)
row = fetchrow(stmt)
finish(stmt)
stmt = prepare(db, "SELECT * FROM users")
execute(stmt)
rows = fetchall(stmt)
finish(stmt)
stmt = prepare(db, "SELECT * FROM users")
execute(stmt)
rows = fetchdf(stmt)
finish(stmt)
rows = select(db, "SELECT * FROM users")
tabledata = tableinfo(db, "users")
columndata = columninfo(db, "users", "id")
columndata = columninfo(db, "users", "name")
stmt = prepare(db, "DROP TABLE users")
execute(stmt)
finish(stmt)
disconnect(db)
rm(path)
# China OK database
path = Pkg.dir("DBDSQLite", "test", "db", "chinook.sqlite3")
db = connect(SQLite3, path)
stmt = prepare(db, "SELECT * FROM Employee")
execute(stmt)
df = fetchdf(stmt)
finish(stmt)
df = select(
db,
"SELECT * FROM sqlite_master WHERE type = 'table' ORDER BY name"
)
df = select(db, "SELECT * FROM Album")
df = select(
db,
"""
SELECT a.*, b.AlbumId
FROM Artist a
LEFT OUTER JOIN Album b ON b.ArtistId = a.ArtistId
ORDER BY name
"""
)
disconnect(db)
end
|
using Church
dp(concentration::Real, base_measure::Function) = begin
sticks = Mem(i::Int -> beta(1., concentration))
atoms = Mem(i::Int -> base_measure())
loop(i::Int) =
@If(bernoulli(sticks[i]), atoms[i], loop(i+1))
d = () -> loop(1)
end
dp_mixture(concentration::Real, base_measure::Function, parameter::Function) = begin
dp_ = dp(concentration, base_measure)
() -> parameter(dp_())
end
d = dp(1., normal)
ds = [d() for i = 1:20]
f = dp_mixture(1., normal, x -> normal(x, 0.1))
fs = [f() for i = 1:20]
n_data = 10
n_components = 20
indicies = [categorical(n_components) for i = 1:n_data]
components = Mem((i::Int) -> normal())
data = [components[indicies[i]] for i = 1:n_data]
|
module Core
const API_SIGN = "API\0"
const HEADTYPE = UInt32 # sizeof(HEADTYPE) == 4 bytes
const MAX_LEN = 0xffffff
isascii(m) = all(x -> x < 0x80, m) # ASCII
function write_one(socket, buf, api_sign=false)
msg = take!(buf)
len = length(msg)
@assert isascii(msg)
@assert len ≤ MAX_LEN
api_sign ? write(socket, API_SIGN, hton(HEADTYPE(len)), msg) :
write(socket, hton(HEADTYPE(len)), msg)
end
function read_one(socket)
len = ntoh(read(socket, HEADTYPE))
@assert len ≤ MAX_LEN
read(socket, len)
end
end
|
mutable struct DoubleMacaulayMatrix{C}
# pivot -> row
leftpivs::Vector{Vector{Int}}
leftcoeffs::Vector{Vector{C}}
# idx -> row
rightrows::Vector{Vector{Int}}
rightcoeffs::Vector{Vector{C}}
# pivot -> idx
pivot2idx::Vector{Int}
#
lefthash2col::Dict{Int, Int}
leftcol2hash::Vector{Int}
righthash2col::Dict{Int, Int}
rightcol2hash::Vector{Int}
# size of leftpivs
nlsize::Int
# load of rightrows
nrrows::Int
# size of rightrows
nrsize::Int
# left cols filled
nlcols::Int
# right cols filled
nrcols::Int
end
function initialize_double_matrix(basis::Basis{C}) where {C<:Coeff}
n = length(basis.gens)
leftrows = Vector{Vector{Int}}(undef, n)
leftcoeffs = Vector{Vector{C}}(undef, n)
pivot2idx = Vector{Int}(undef, n)
m = length(basis.gens)
rightrows = Vector{Vector{Int}}(undef, m)
rightcoeffs= Vector{Vector{C}}(undef, m)
lsz = n
lefthash2col = Dict{Int, Int}()
leftcol2hash = Vector{Int}(undef, lsz)
rsz = m
righthash2col = Dict{Int, Int}()
rightcol2hash = Vector{Int}(undef, rsz)
DoubleMacaulayMatrix(leftrows, leftcoeffs, rightrows,
rightcoeffs, pivot2idx, lefthash2col, leftcol2hash,
righthash2col, rightcol2hash, n, 0, m, 0, 0)
end
function convert_to_double_dense_row(matrix, monom, vector::Basis{C}, ht) where {C<:Coeff}
if matrix.nrcols >= length(matrix.rightcol2hash)
resize!(matrix.rightcol2hash, 2*length(matrix.rightcol2hash))
end
matrix.nrcols += 1
matrix.rightcol2hash[matrix.nrcols] = monom
matrix.righthash2col[monom] = matrix.nrcols
rightrow = zeros(C, matrix.nrcols)
rightrow[end] = one(C)
exps, coeffs = vector.gens[1], vector.coeffs[1]
for i in 1:length(exps)
if !haskey(matrix.lefthash2col, exps[i])
if matrix.nlcols >= length(matrix.leftcol2hash)
resize!(matrix.leftcol2hash, 2*length(matrix.leftcol2hash))
end
matrix.nlcols += 1
matrix.lefthash2col[exps[i]] = matrix.nlcols
matrix.leftcol2hash[matrix.nlcols] = exps[i]
end
end
leftrow = zeros(C, matrix.nlcols)
for i in 1:length(exps)
leftrow[matrix.lefthash2col[exps[i]]] = coeffs[i]
end
leftrow, rightrow
end
# reduces row by mul*cfs modulo ch at indices positions
#
# Finite field magic specialization
function reduce_by_pivot_simultaneous!(leftrow, leftexps, leftcfs::Vector{CoeffFF},
rightrow, rightexps, rightcfs, magic)
# mul = -densecoeffs[i]
# actually.. not bad!
mul = (magic.divisor - leftrow[leftexps[1]]) % magic
@inbounds for j in 1:length(leftexps)
idx = leftexps[j]
leftrow[idx] = (leftrow[idx] + mul*leftcfs[j]) % magic
end
@inbounds for j in 1:length(rightexps)
idx = rightexps[j]
rightrow[idx] = (rightrow[idx] + mul*rightcfs[j]) % magic
end
mul
end
#
# Finite field magic specialization
function normalize_double_row_sparse!(leftcfs::Vector{CoeffFF}, rightcfs, magic)
pinv = invmod(leftcfs[1], magic.divisor) % magic
@inbounds for i in 2:length(leftcfs)
# row[i] *= pinv
leftcfs[i] = (leftcfs[i] * pinv) % magic
end
@inbounds leftcfs[1] = one(leftcfs[1])
@inbounds for i in 1:length(rightcfs)
# row[i] *= pinv
rightcfs[i] = (rightcfs[i] * pinv) % magic
end
end
#
# Finite field magic specialization
function normalize_double_row_sparse!(leftcfs::Vector{CoeffQQ}, rightcfs, magic)
pinv = inv(leftcfs[1])
@inbounds for i in 2:length(leftcfs)
# row[i] *= pinv
leftcfs[i] = leftcfs[i] * pinv
end
@inbounds leftcfs[1] = one(leftcfs[1])
@inbounds for i in 1:length(rightcfs)
rightcfs[i] = rightcfs[i] * pinv
end
end
# reduces row by mul*cfs modulo ch at indices positions
#
# Rational field specialization
function reduce_by_pivot_simultaneous!(leftrow, leftexps, leftcfs::Vector{CoeffQQ},
rightrow, rightexps, rightcfs, magic)
# mul = -densecoeffs[i]
# actually.. not bad!
mul = -leftrow[leftexps[1]]
@inbounds for j in 1:length(leftexps)
idx = leftexps[j]
leftrow[idx] = leftrow[idx] + mul*leftcfs[j]
end
@inbounds for j in 1:length(rightexps)
idx = rightexps[j]
rightrow[idx] = rightrow[idx] + mul*rightcfs[j]
end
mul
end
function reduce_double_dense_row_by_known_pivots_sparse!(
matrix::DoubleMacaulayMatrix{C},
leftrow, rightrow, magic) where {C}
leftrows = matrix.leftpivs
rightrows = matrix.rightrows
pivot2idx = matrix.pivot2idx
# new row nonzero elements count
k = 0
uzero = C(0)
# new pivot index
np = -1
if debug()
@warn "in reduce" matrix.nlcols matrix.nrcols matrix.leftpivs
@warn "hmm" leftrow
end
for i in 1:matrix.nlcols
# if row element zero - no reduction
@inbounds if leftrow[i] == uzero
continue
end
# TODO: check this first?
if !isassigned(leftrows, i)
if np == -1
np = i
end
k += 1
continue
end
# exponents of reducer row at column i
leftexps = leftrows[i]
leftcfs = matrix.leftcoeffs[i]
# here map pivot --> when added
rightexps = rightrows[pivot2idx[i]]
rightcfs = matrix.rightcoeffs[pivot2idx[i]]
mul = reduce_by_pivot_simultaneous!(leftrow, leftexps, leftcfs,
rightrow, rightexps, rightcfs, magic)
end
return k == 0, np, k
end
function extract_sparse_row(row)
newrow, newcfs, k = extract_sparse_row(row, 1, length(row))
resize!(newrow, k)
resize!(newcfs, k)
newrow, newcfs, k
end
function extract_sparse_row(row::Vector{C}, np, k) where {C}
newrow = Vector{Int}(undef, k)
newcfs = Vector{C}(undef, k)
# store new row in sparse format
# where k - number of structural nonzeros in new reduced row, k > 0
j = 1
@inbounds for i in np:length(row) # from new pivot
@inbounds if row[i] != 0
newrow[j] = i
newcfs[j] = row[i]
j += 1
end
end
newrow, newcfs, j - 1
end
function linear_relation!(
matrix::DoubleMacaulayMatrix,
monom::Int, vector::Basis{C},
ht) where {C<:Coeff}
magic = select_divisor(vector.coeffs, vector.ch)
leftrow, rightrow = convert_to_double_dense_row(matrix, monom, vector, ht)
if debug()
@warn "start"
println(monom)
println(vector.gens, " ", vector.coeffs)
println(leftrow)
println(rightrow)
println(matrix)
end
reduced, np, k = reduce_double_dense_row_by_known_pivots_sparse!(matrix, leftrow, rightrow, magic)
if debug()
@warn "reduced"
println(reduced, " ", np, " ", k)
println(leftrow)
println(rightrow)
end
if reduced
# pass
else
lexps, lcoeffs, _ = extract_sparse_row(leftrow, np, k)
rexps, rcoeffs, _ = extract_sparse_row(rightrow)
normalize_double_row_sparse!(lcoeffs, rcoeffs, magic)
if debug()
@warn "extracted"
println(lexps, " ", lcoeffs)
println(rexps, " ", rcoeffs)
end
while np >= matrix.nlsize
matrix.nlsize *= 2
resize!(matrix.leftpivs, matrix.nlsize)
resize!(matrix.leftcoeffs, matrix.nlsize)
resize!(matrix.pivot2idx, matrix.nlsize)
end
matrix.leftpivs[np] = lexps
matrix.leftcoeffs[np] = lcoeffs
matrix.nrrows += 1
matrix.pivot2idx[np] = matrix.nrrows
if matrix.nrrows >= matrix.nrsize
matrix.nrsize *= 2
resize!(matrix.rightrows, matrix.nrsize)
resize!(matrix.rightcoeffs, matrix.nrsize)
end
matrix.rightrows[matrix.nrrows] = rexps
matrix.rightcoeffs[matrix.nrrows] = rcoeffs
end
return reduced, rightrow
end
|
using WAVI, Plots
"""
Produce a plot of the melt rate in MISMIP for specified melt rate parametrization (c.f. figure 4 in Favier 2019 10.5194/gmd-12-2255-2019)
***Options***
- PICO_nboxP_zQ : PICO with P boxes, ambient temperature taken at Qm depth for P = 10, 8, 5, 2 and Q = 500, 700
(e.g. "PICO_nbox2_z700")
- PME : Plume model emulator (using Lazeroms 2018 algorithm for grounding line and basal slope -- doi:10.5194/tc-12-49-2018)
- MISMIP_1r : Melt rate according to the MISMIP+ ice 1r experiment (doi: 10.5194/tc-14-2283-2020) scaled to match the mean melt rate
- QuadL : Quadratic formulation of melting with local dependency on thermal driving
- QuadNL : Quadratic formulation of melting with non-local dependency on thermal driving
"""
melt_rate_model = "QuadL"
function Favier2019_4km_init(melt_model)
# Grid and boundary conditions
nx = 160
ny = 20
nσ = 4
x0 = 0.0
y0 = -40000.0
dx = 4000.0
dy = 4000.0
h_mask = trues(nx, ny)
u_iszero = falses(nx + 1, ny); u_iszero[1,:] .= true
v_iszero = falses(nx, ny + 1); v_iszero[:,1] .= true; v_iszero[:,end] .= true
grid = Grid(nx=nx,
ny=ny,
nσ=nσ,
x0=x0,
y0=y0,
dx=dx,
dy=dy,
h_mask=h_mask,
u_iszero=u_iszero,
v_iszero=v_iszero)
# Bed
bed = WAVI.mismip_plus_bed # function definition
# Inputing thickness profile, reading from binary file
#fname = "examples\\Favier2019_melt_params\\data\\MISMIP_ice0_2km_SteadyThickness.bin";
#fname = joinpath(dirname(@__FILE__), "data", "WAVI_ice0_4km_thick_interpolated.bin")
fname = joinpath(dirname(@__FILE__), "data", "WAVI_ice0_4km_thickness.bin")
h = Array{Float64,2}(undef, nx, ny)
read!(fname, h)
h = ntoh.(h)
# make the model
initial_conditions = InitialConditions(initial_thickness=h) # set thickness
model = Model(grid=grid,
bed_elevation=bed,
melt_rate = melt_model,
initial_conditions=initial_conditions,
solver_params=SolverParams(maxiter_picard=1)
) ;
# update the configuration
update_state!(model)
#contour plot melt rate
m = deepcopy(model.fields.gh.basal_melt)
m[model.fields.gh.grounded_fraction .== 1.] .= NaN
msat = deepcopy(m)
msat[msat .> 50] .= 50
#msat[zb .> -300] .= NaN;
x = model.grid.xxh[:,1]; y = model.grid.yyh[1,:];
plt = heatmap(x ./ 1e3,y / 1e3, msat',
fill=true,
linewidth=0,
colorbar=true,
colorbar_title="melt rate (m/yr)",
framestyle=:box)
xlims!((420, 640))
xlabel!("x (km)")
ylabel!("y (km)")
return model, plt
end
#Need these for PICO
nx = 160; ny = 20;
ice_front_mask = zeros(nx,ny);
ice_front_mask[end,:] .= 1;
if melt_rate_model == "PICO_nbox10_z700"
melt_model = PICO(ice_front_mask = ice_front_mask,
T0 =1.2,
S0 = 34.6,
use_box_mean_depth = true,
γT = 0.94e-5,
nbox = 10);
elseif melt_rate_model == "PICO_nbox8_z700"
melt_model = PICO(ice_front_mask = ice_front_mask,
T0 =1.2,
S0 = 34.6,
use_box_mean_depth = true,
γT = 0.91e-5,
nbox = 8);
elseif melt_rate_model == "PICO_nbox5_z700"
melt_model = PICO(ice_front_mask = ice_front_mask,
T0 = 1.2,
S0 = 34.6,
use_box_mean_depth = true,
γT = 0.87e-5,
nbox = 5);
elseif melt_rate_model == "PICO_nbox2_z700"
melt_model = PICO(ice_front_mask = ice_front_mask,
T0 = 1.2,
S0 = 34.6,
use_box_mean_depth = true,
γT = 0.85e-5,
nbox = 2);
elseif melt_rate_model == "PME"
melt_model = PlumeEmulator(α=1.49)
elseif melt_rate_model == "MISMIP_1r"
melt_model = MISMIPMeltRateOne(α = 0.184)
elseif melt_rate_model == "QuadL"
melt_model = QuadraticMeltRate(γT = 0.745*1e-3)
#melt_model = QuadraticMeltRate(γT = 0.745*1e-3, melt_partial_cell = true)
elseif melt_rate_model == "QuadNL"
melt_model = QuadraticMeltRate(γT = 0.85*1e-3, flocal = false)
#melt_model = QuadraticMeltRate(γT = 0.85*1e-3, flocal = false, melt_partial_cell = true)
else
throw(ArgumentError("Specified melt rate model not found"))
end
model, plt = Favier2019_4km_init(melt_model);
m = deepcopy(model.fields.gh.basal_melt);
zb = model.fields.gh.b .* (model.fields.gh.grounded_fraction .== 1) + - 918.0 / 1028.0 .* model.fields.gh.h .* (model.fields.gh.grounded_fraction .< 1)
idx = (model.fields.gh.grounded_fraction .== 0)
mean_melt = sum(m[idx])./length(m[idx])
println("mean melt rate for shelf points is $mean_melt") |
fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)
|
using Test
using Distributed
using Dates
import REPL
using Printf: @sprintf
if isdefined(Base, :Experimental)
Stub = Base.Experimental
else
Stub = Base
end
# The following is taken from https://github.com/JuliaLang/julia/blob/master/test/runtests.jl\
# Part of Julia. License is MIT: https://julialang.org/license
addprocs(n_procs)
const max_worker_rss = if haskey(ENV, "JULIA_TEST_MAXRSS_MB")
parse(Int, ENV["JULIA_TEST_MAXRSS_MB"]) * 2^20
else
typemax(Csize_t)
end
limited_worker_rss = max_worker_rss != typemax(Csize_t)
exit_on_error = true
n = 1
skipped = 0
seed = rand(UInt128)
running_under_rr() = false
@everywhere include("testdefs.jl")
@everywhere using Hecke
@everywhere using RandomExtensions
if short_test
@everywhere short_test = true
else
@everywhere short_test = false
end
if long_test
@everywhere long_test = true
else
@everywhere long_test = false
end
@everywhere include("setup.jl")
if with_gap
@everywhere push!(Base.LOAD_PATH, "@v#.#")
@everywhere using GAP
end
testgroupheader = "Test"
workerheader = "(Worker)"
name_align = maximum([textwidth(testgroupheader) + textwidth(" ") + textwidth(workerheader); map(x -> textwidth(x) + 3 + ndigits(nworkers()), tests)])
elapsed_align = textwidth("Time (s)")
gc_align = textwidth("GC (s)")
percent_align = textwidth("GC %")
alloc_align = textwidth("Alloc (MB)")
rss_align = textwidth("RSS (MB)")
printstyled(testgroupheader, color=:white)
printstyled(lpad(workerheader, name_align - textwidth(testgroupheader) + 1), " | ", color=:white)
printstyled("Time (s) | GC (s) | GC % | Alloc (MB) | RSS (MB)\n", color=:white)
results = []
print_lock = stdout isa Base.LibuvStream ? stdout.lock : ReentrantLock()
if stderr isa Base.LibuvStream
stderr.lock = print_lock
end
function print_testworker_stats(test, wrkr, resp)
@nospecialize resp
lock(print_lock)
try
printstyled(test, color=:white)
printstyled(lpad("($wrkr)", name_align - textwidth(test) + 1, " "), " | ", color=:white)
time_str = @sprintf("%7.2f",resp[2])
printstyled(lpad(time_str, elapsed_align, " "), " | ", color=:white)
gc_str = @sprintf("%5.2f", resp[5].total_time / 10^9)
printstyled(lpad(gc_str, gc_align, " "), " | ", color=:white)
# since there may be quite a few digits in the percentage,
# the left-padding here is less to make sure everything fits
percent_str = @sprintf("%4.1f", 100 * resp[5].total_time / (10^9 * resp[2]))
printstyled(lpad(percent_str, percent_align, " "), " | ", color=:white)
alloc_str = @sprintf("%5.2f", resp[3] / 2^20)
printstyled(lpad(alloc_str, alloc_align, " "), " | ", color=:white)
rss_str = @sprintf("%5.2f", resp[6] / 2^20)
printstyled(lpad(rss_str, rss_align, " "), "\n", color=:white)
finally
unlock(print_lock)
end
nothing
end
global print_testworker_started = (name, wrkr)->begin
pid = running_under_rr() ? remotecall_fetch(getpid, wrkr) : 0
at = lpad("($wrkr)", name_align - textwidth(name) + 1, " ")
lock(print_lock)
try
printstyled(name, at, " |", " "^elapsed_align,
"started at $(now())",
(pid > 0 ? " on pid $pid" : ""),
"\n", color=:white)
finally
unlock(print_lock)
end
nothing
end
function print_testworker_errored(name, wrkr, @nospecialize(e))
lock(print_lock)
try
printstyled(name, color=:red)
printstyled(lpad("($wrkr)", name_align - textwidth(name) + 1, " "), " |",
" "^elapsed_align, " failed at $(now())\n", color=:red)
if isa(e, Test.TestSetException)
for t in e.errors_and_fails
show(t)
println()
end
elseif e !== nothing
Base.showerror(stdout, e)
end
println()
finally
unlock(print_lock)
end
end
all_tests = tests
local stdin_monitor
all_tasks = Task[]
try
# Monitor stdin and kill this task on ^C
# but don't do this on Windows, because it may deadlock in the kernel
running_tests = Dict{String, DateTime}()
if !Sys.iswindows() && isa(stdin, Base.TTY)
t = current_task()
stdin_monitor = @async begin
term = REPL.Terminals.TTYTerminal("xterm", stdin, stdout, stderr)
try
REPL.Terminals.raw!(term, true)
while true
c = read(term, Char)
if c == '\x3'
Base.throwto(t, InterruptException())
break
elseif c == '?'
println("Currently running: ")
tests = sort(collect(running_tests), by=x->x[2])
foreach(tests) do (test, date)
println(test, " (running for ", round(now()-date, Minute), ")")
end
end
end
catch e
isa(e, InterruptException) || rethrow()
finally
REPL.Terminals.raw!(term, false)
end
end
end
@Stub.sync begin
for p in workers()
@async begin
push!(all_tasks, current_task())
while length(tests) > 0
test = popfirst!(tests)
running_tests[test] = now()
wrkr = p
resp = try
remotecall_fetch(runtests, wrkr, test, test_path(test); seed=seed, isolate = false)
catch e
isa(e, InterruptException) && return
Any[CapturedException(e, catch_backtrace())]
end
delete!(running_tests, test)
push!(results, (test, resp))
if length(resp) == 1
print_testworker_errored(test, wrkr, exit_on_error ? nothing : resp[1])
if exit_on_error
skipped = length(tests)
empty!(tests)
elseif n > 1
# the worker encountered some failure, recycle it
# so future tests get a fresh environment
rmprocs(wrkr, waitfor=30)
p = addprocs_with_testenv(1)[1]
remotecall_fetch(include, p, "testdefs.jl")
if use_revise
Distributed.remotecall_eval(Main, p, revise_init_expr)
end
end
else
print_testworker_stats(test, wrkr, resp)
if resp[end] > max_worker_rss
# the worker has reached the max-rss limit, recycle it
# so future tests start with a smaller working set
if n > 1
rmprocs(wrkr, waitfor=30)
p = addprocs_with_testenv(1)[1]
remotecall_fetch(include, p, "testdefs.jl")
if use_revise
Distributed.remotecall_eval(Main, p, revise_init_expr)
end
else # single process testing
error("Halting tests. Memory limit reached : $resp > $max_worker_rss")
end
end
end
end
if p != 1
# Free up memory =)
rmprocs(p, waitfor=30)
end
end
end
end
catch e
isa(e, InterruptException) || rethrow()
# If the test suite was merely interrupted, still print the
# summary, which can be useful to diagnose what's going on
foreach(task -> begin
istaskstarted(task) || return
istaskdone(task) && return
try
schedule(task, InterruptException(); error=true)
catch ex
@error "InterruptException" exception=ex,catch_backtrace()
end
end, all_tasks)
foreach(wait, all_tasks)
finally
if @isdefined stdin_monitor
schedule(stdin_monitor, InterruptException(); error=true)
end
end
#=
` Construct a testset on the master node which will hold results from all the
test files run on workers and on node1. The loop goes through the results,
inserting them as children of the overall testset if they are testsets,
handling errors otherwise.
Since the workers don't return information about passing/broken tests, only
errors or failures, those Result types get passed `nothing` for their test
expressions (and expected/received result in the case of Broken).
If a test failed, returning a `RemoteException`, the error is displayed and
the overall testset has a child testset inserted, with the (empty) Passes
and Brokens from the worker and the full information about all errors and
failures encountered running the tests. This information will be displayed
as a summary at the end of the test run.
If a test failed, returning an `Exception` that is not a `RemoteException`,
it is likely the julia process running the test has encountered some kind
of internal error, such as a segfault. The entire testset is marked as
Errored, and execution continues until the summary at the end of the test
run, where the test file is printed out as the "failed expression".
=#
Test.TESTSET_PRINT_ENABLE[] = false
o_ts = Test.DefaultTestSet("Overall")
Test.push_testset(o_ts)
completed_tests = Set{String}()
for (testname, (resp,)) in results
push!(completed_tests, testname)
if isa(resp, Test.DefaultTestSet)
Test.push_testset(resp)
Test.record(o_ts, resp)
Test.pop_testset()
elseif isa(resp, Test.TestSetException)
fake = Test.DefaultTestSet(testname)
for i in 1:resp.pass
Test.record(fake, VERSION < v"1.7.0-DEV.1196" ? Test.Pass(:test, nothing, nothing, nothing) : Test.Pass(:test, nothing, nothing, nothing, LineNumberNode(@__LINE__, @__FILE__)))
end
for i in 1:resp.broken
Test.record(fake, Test.Broken(:test, nothing))
end
for t in resp.errors_and_fails
Test.record(fake, t)
end
Test.push_testset(fake)
Test.record(o_ts, fake)
Test.pop_testset()
else
if !isa(resp, Exception)
resp = ErrorException(string("Unknown result type : ", typeof(resp)))
end
# If this test raised an exception that is not a remote testset exception,
# i.e. not a RemoteException capturing a TestSetException that means
# the test runner itself had some problem, so we may have hit a segfault,
# deserialization errors or something similar. Record this testset as Errored.
fake = Test.DefaultTestSet(testname)
Test.record(fake, Test.Error(:nontest_error, testname, nothing, Any[(resp, [])], LineNumberNode(1)))
Test.push_testset(fake)
Test.record(o_ts, fake)
Test.pop_testset()
end
end
for test in all_tests
(test in completed_tests) && continue
fake = Test.DefaultTestSet(test)
Test.record(fake, Test.Error(:test_interrupted, test, nothing, [("skipped", [])], LineNumberNode(1)))
Test.push_testset(fake)
Test.record(o_ts, fake)
Test.pop_testset()
end
Test.TESTSET_PRINT_ENABLE[] = true
println()
Test.print_test_results(o_ts, 1)
if !o_ts.anynonpass
println(" \033[32;1mSUCCESS\033[0m")
else
println(" \033[31;1mFAILURE\033[0m\n")
skipped > 0 &&
println("$skipped test", skipped > 1 ? "s were" : " was", " skipped due to failure.")
println("The global RNG seed was 0x$(string(seed, base = 16)).\n")
Test.print_test_errors(o_ts)
throw(Test.FallbackTestSetException("Test run finished with errors"))
end
|
#######################################################
### ------------------ DEFINITIONS -------------------
#######################################################
abstract type Dimension end
abstract type TwoD <: Dimension end
abstract type ThreeD <: Dimension end
struct Square <: TwoD end
struct Circle <: TwoD end
struct Cube <: ThreeD end
struct Sphere <: ThreeD end
struct Atom{T <: Dimension}
shape::T
r::Matrix
N::Int64
sizes::Any
end
get_dimension(atom::Atom{T}) where T <: TwoD = 2
get_dimension(atom::Atom{T}) where T <: ThreeD = 3
abstract type Pump end
abstract type PlaneWave <: Pump end
abstract type Gaussian <: Pump end
struct PlaneWave2D <: PlaneWave
direction::Vector
end
struct PlaneWave3D <: PlaneWave
direction::Vector
end
struct Gaussian2D <: Gaussian
w₀::Float64
end
struct Gaussian3D <: Gaussian
w₀::Float64
end
struct Laser{T <: Pump}
pump::T
s::Float64
Δ::Float64
end
struct Lasers{T <: Pump}
pump::Vector{T}
s::Vector{Float64}
Δ::Vector{Float64}
end
abstract type Physics end
abstract type Linear <: Physics end
abstract type NonLinear <: Physics end
struct Scalar <: Linear end
struct Vectorial <: Linear end
struct MeanField <: NonLinear end
struct BBGKY <: NonLinear end
struct LinearOptics{T <: Linear}
physic::T
atoms::Atom
laser::Laser
kernelFunction::Function
spectrum::Dict
data::Dict
end
struct NonLinearOptics{T <: NonLinear}
physic::T
atoms::Atom
laser::Laser
excitations::Dict
data::Dict
end
#######################################################
### ------------------ CONSTRUCTORS -------------------
#######################################################
# """
# b₀_of(atoms::Cube)
# Formula : `ρ^2*N/( (4π/3 * (3/(16π))^3))^(1/3) )`
# """
# b₀_of(atoms::Cube) = (ρ_of(atoms) .^ 2 * atoms.N / ((4π / 3) * (3 / (16π))^3))^(1 / 3)
# """
# ρ_of(atoms::Cube)
# Formula : `N/( kL^3 )`
# """
# ρ_of(atoms::Cube) = atoms.N / atoms.kL^3
# """
# b₀_of(atoms::Cube)
# Formula : `ρ^2*N/( (4π/3 * (3/(16π))^3))^(1/3) )`
# """
# b₀_of(atoms::Sphere) = (ρ_of(atoms) .^ 2 * atoms.N / ((4π / 3) * (3 / (16π))^3))^(1 / 3)
# ρ_of(atoms::Sphere) = atoms.N / VolumeSphere(atoms.kR)
# ### --------------- LASER ---------------
# """
# PlaneWave_3D(direction=:z, s=1e-6, Δ=0)
# `direction` can be [:x, :y, :z]
# """
# function PlaneWave_3D(direction=:z, s=1e-6, Δ=0)
# if direction == :x
# matrix_slace = 1
# elseif direction == :y
# matrix_slace = 2
# elseif direction == :z
# matrix_slace = 3
# else
# @error("No support for this direction yet")
# end
# return PlaneWave(matrix_slace, s, Δ)
# end
# """
# PlaneWave_2D(direction=:z, s=1e-6, Δ=0)
# `direction` can be [:x, :y]
# """
# function PlaneWave_2D(direction=:x, s=1e-6, Δ=0)
# if direction == :x
# matrix_slace = 1
# elseif direction == :y
# matrix_slace = 2
# else
# @error("No support for this direction yet")
# end
# return PlaneWave(matrix_slace, s, Δ)
# end
# """
|
#jl
"""
Struct Material
Used for solid Materials in Pipes. So far includes just name, thermal
conductivity, and surface roughness.
"""
struct Material
name::String
thermal_conductivity::Function
roughness::Real
end
struct Pipe{T<:Real}
length::T
diameter::T
radius::T
flowarea::T
thickness::T
outer_diameter::T
outer_radius::T
totalarea::T
roughness::T
elevation_change::T
therm_cond::Function
end
const valid_Pipe_diams = [0.125, 0.25, 0.375, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5,
3.0, 3.5, 4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 16.0]
function Pipe(l, d, t, ϵ, z, kfunc)
# Assumes a circular Pipe of diameter d
return Pipe(l,d,d/2,pi*(d/2)^2,t,d+2t,(d+2t)/2,pi*((d+2t)/2)^2,ϵ,z,kfunc)
end
mutable struct PipeProps{T<:Real}
dᵢ::T
dₒ::T
thickness::T
rᵢ::T
rₒ::T
units::String
end
function PipeProps(d, t, units="in")
di = d - 2t
ro = d/2
ri = di/2
return PipeProps(di, d, t, ri, ro, units)
end
const conversions = Dict(["cm","m"] => 1e-2,
["m","cm"] => 100,
["in","cm"] => 2.54,
["cm","in"] => 1/2.54,
["in","m"] => 2.54e-2,
["m","in"] => 1/2.54e-2,
["m","m"] => 1.0,
["cm","cm"] => 1.0,
["in","in"] => 1.0)
function convert(p::PipeProps, newUnits::String)
key_ = [p.units, newUnits]
conversion_factor = conversions[key_]
p.dᵢ *= conversion_factor
p.dₒ *= conversion_factor
p.rᵢ *= conversion_factor
p.rₒ *= conversion_factor
p.units = newUnits
end
const schedule40_props = [PipeProps(0.405, 0.068), PipeProps(0.540, 0.088),
PipeProps(0.675, 0.091), PipeProps(0.840, 0.109),
PipeProps(1.050, 0.113), PipeProps(1.315, 0.133),
PipeProps(1.660, 0.140), PipeProps(1.900, 0.145),
PipeProps(2.375, 0.154), PipeProps(2.875, 0.203),
PipeProps(3.500, 0.216), PipeProps(4.000, 0.226),
PipeProps(4.500, 0.237), PipeProps(5.563, 0.258),
PipeProps(6.625, 0.280), PipeProps(8.625, 0.322),
PipeProps(10.750, 0.365), PipeProps(12.750, 0.406),
PipeProps(16.000, 0.500)]
# Note: These outer diameters and wall thicknesses were obtained at this web
# site: http://www.engineeringtoolbox.com/steel-dimensions-d_43.html
for props in schedule40_props
convert(props, "m")
end
const props40_by_nominal_diameter = Dict(zip(valid_Pipe_diams, schedule40_props))
const schedule_props = Dict("40" => props40_by_nominal_diameter,
40 => props40_by_nominal_diameter)
function Pipe(schedule_info::Tuple, mat::Material, l, Δz)
# schedule_info is a Tuple: the schedule number comes first and the nominal
# diameter comes second
props = schedule_props[schedule_info[1]][schedule_info[2]]
return Pipe(l,props.dᵢ,props.dᵢ/2,pi*(props.rᵢ)^2,props.thickness,props.dₒ,
props.rₒ,pi*(props.rₒ)^2,mat.roughness,Δz,mat.thermal_conductivity)
end
function Pipe(schedule_info::Tuple, mat::String, l, Δz)
return Pipe(schedule_info, Pipe_Materials[mat], l, Δz)
end
function colebrook(Re, p::Pipe, f_g)
if f_g < 0
return f_g * 1e5
else
return 10^(-1 / (2 * √(f_g))) - (p.roughness / (3.7 * p.diameter) + 2.51 / (Re * √(f_g)))
end
end
function getf(Re, p::Pipe)
print("Sanity check: Re = ",Re)
function dummysolve!(f_guess, fvec)
fvec[1] = colebrook(Re, p, f_guess[1])
end
return NLsolve.nlsolve(dummysolve!, [0.001]).zero[1]
end
laminarf(Re, p::Pipe) = 64.0/Re
function swameejain(Re, p::Pipe)
return 0.25/(log10(p.roughness/(3.7*p.diameter)+ 5.74/(Re^ 0.9)))^2
end
function getf2(Re, p::Pipe)
if Re > 2000
return swameejain(Re, p)
else
return laminarf(Re, p)
end
end
function stainless_steel_thermal_conductivity(T)
# Source: http://www.mace.manchester.ac.uk/project/research/structures/strucfire/MaterialInFire/Steel/StainlessSteel/thermalProperties.htm
return 14.6 + 1.27e-2 *(T-273.15)
end
function copper_thermal_conductivity(T)
# Source: http://www-ferp.ucsd.edu/LIB/PROPS/PANOS/cu.html
return 14.6 + 1.27e-2 *(T-273.15)
end
const ss_roughness_by_finish = Dict("2D" => 1E-6,
"2B" => 0.5E-6,
"2R" => 0.2E-6,
"BA" => 0.2E-6,
"2BB" => 0.1E-6)
# These surface roughness values are in m and were obtained from the following
# corporate site: http://www.outokumpu.com/en/products-properties/
# more-stainless/stainless-steel-surface-finishes/cold-rolled-finishes/Pages/default.aspx
# Note that the given values are the maximum roughness values in the range on
# the website, except for finish 2BB, which didn't have a roughness value
# so I took the lowest value for finish 2B since the compnay says this:
# "Due to the fact that surface roughness of the finish 2BB is lower than that
# of 2B, some modifications on lubrication during forming might be needed."
const ss_mat = Material("Stainless Steel", stainless_steel_thermal_conductivity,
ss_roughness_by_finish["2B"])
const cu_roughness = 0.03e-3
# Copper roughness.
# Source: http://www.pressure-drop.com/Online-Calculator/rauh.html
const cu_mat = Material("Copper", copper_thermal_conductivity, cu_roughness)
const pipematerials = Dict("Copper" => cu_mat, "Stainless Steel"=>ss_mat)
|
"""
This file contains all the functions that required to extract region information
from a given textfile repository, and from there extraction of relevant regional
data from given datasets.
There are three major types of functions contained in this .jl module:
1) extraction of region information and attributes
2) extraction of data from a given dataset based upon the given region
information and list of attributes
3) transformation of longitude coordinate systems [-180,180] <=> [0,360]
"""
# Region Information and Attributes
function regionload()
@debug "$(Dates.now()) - Loading information on possible regions ..."
return readdlm(joinpath(@__DIR__,"regions.txt"),',',comments=true);
end
function regioninfodisplay(regioninfo)
@info "$(Dates.now()) - The following regions are offered in the ClimateEasy.jl"
for ii = 1 : size(regioninfo,1); @info "$(Dates.now()) - $(ii)) $(regioninfo[ii,7])" end
end
# Find Regions Bounds
function regionbounds(reg::AbstractString)
reginfo = regionload(); regions = reginfo[:,1]; regid = (regions .== reg);
N,S,E,W = reginfo[regid,[3,5,6,4]];
@debug "$(Dates.now()) - The bounds of the region are, in [N,S,E,W] format, [$(N),$(S),$(E),$(W)]."
return [N,S,E,W]
end
function regionbounds(reg::AbstractString,reginfo::AbstractArray)
regions = reginfo[:,1]; regid = (regions .== reg)[1];
N,S,E,W = reginfo[regid,[3,5,6,4]];
@debug "$(Dates.now()) - The bounds of the region are, in [N,S,E,W] format, [$(N),$(S),$(E),$(W)]."
return [N,S,E,W]
end
function regionbounds(regID::Int64)
reginfo = regionload();
N,S,E,W = reginfo[regID,[3,5,6,4]];
@debug "$(Dates.now()) - The bounds of the region are, in [N,S,E,W] format, [$(N),$(S),$(E),$(W)]."
return [N,S,E,W]
end
function regionbounds(regID::Int64,reginfo::AbstractArray)
N,S,E,W = reginfo[regID,[3,5,6,4]];
@debug "$(Dates.now()) - The bounds of the region are, in [N,S,E,W] format, [$(N),$(S),$(E),$(W)]."
return [N,S,E,W]
end
# Find Short Region Name
function regionshortname(regID::Int64)
reginfo = regionload(); return reginfo[regID,1];
end
function regionshortname(regID::Int64,reginfo::AbstractArray)
return reginfo[regID,1];
end
# Find Full Region Name
function regionfullname(reg::AbstractString)
reginfo = regionload(); regions = reginfo[:,1]; regid = (regions .== reg);
return reginfo[regid,7][1];
end
function regionfullname(reg::AbstractString,reginfo::AbstractArray)
regions = reginfo[:,1]; regid = (regions .== reg);
return reginfo[regid,7][1];
end
function regionfullname(regID::Int64)
reginfo = regionload(); return reginfo[regID,7];
end
function regionfullname(regID::Int64,reginfo::AbstractArray)
return reginfo[regID,7];
end
# Find Region Parent
function regionparent(reg::AbstractString)
reginfo = regionload(); regions = reginfo[:,1]; regid = (regions .== reg);
return reginfo[regid,2][1];
end
function regionparent(reg::AbstractString,reginfo::AbstractArray)
regions = reginfo[:,1]; regid = (regions .== reg);
return reginfo[regid,2][1];
end
function regionparent(regID::Int64)
reginfo = regionload(); return reginfo[regID,2];
end
function regionparent(regID::Int64,reginfo::AbstractArray)
return reginfo[regID,2];
end
# Find if the Region is Global
function regionisglobe(reg::AbstractString)
reginfo = regionload(); regions = reginfo[:,1]; regid = (regions .== reg);
if regid == 1; return true; else; return false end
end
function regionisglobe(reg::AbstractString,reginfo::AbstractArray)
regions = reginfo[:,1]; regid = (regions .== reg);
if regid == 1; return true; else; return false end
end
function regionisglobe(regID::Int64)
if regID == 1; return true; else; return false end
end
# Find if Point / Grid is in specified Regions
function ispointinregion(plon::AbstractFloat,plat::AbstractFloat,lon::Array,lat::Array)
minlon = minimum(lon); maxlon = maximum(lon);
minlat = minimum(lat); maxlat = maximum(lat);
if plon > maxlon; plon = plon - 360;
elseif plon < minlon; plon = plon + 360;
end
if (plon > minlon) && (plon < maxlon) &&
(plat > minlat) && (plat < maxlat)
return true
else; return false
end
end
function ispointinregion(plon::AbstractFloat,plat::AbstractFloat,reg)
N,S,E,W = regionbounds(reg); lon = [E,W]; lat = [N,S];
minlon = minimum(lon); maxlon = maximum(lon);
minlat = minimum(lat); maxlat = maximum(lat);
if plon > maxlon; plon = plon - 360;
elseif plon < minlon; plon = plon + 360;
end
if (plon > minlon) && (plon < maxlon) &&
(plat > minlat) && (plat < maxlat)
return true
else; return false
end
end
function ispointinregion(pcoord::AbstractArray,lon::Array,lat::Array)
plon,plat = pcoord;
minlon = minimum(lon); maxlon = maximum(lon);
minlat = minimum(lat); maxlat = maximum(lat);
if plon > maxlon; plon = plon - 360;
elseif plon < minlon; plon = plon + 360;
end
if (plon > minlon) && (plon < maxlon) &&
(plat > minlat) && (plat < maxlat)
return true
else; return false
end
end
function ispointinregion(pcoord::Array{Any,2},reg)
plon,plat = pcoord; N,S,E,W = regionbounds(reg); lon = [E,W]; lat = [N,S];
minlon = minimum(lon); maxlon = maximum(lon);
minlat = minimum(lat); maxlat = maximum(lat);
if plon > maxlon; plon = plon - 360;
elseif plon < minlon; plon = plon + 360;
end
if (plon > minlon) && (plon < maxlon) &&
(plat > minlat) && (plat < maxlat)
return true
else; return false
end
end
function isgridinregion(bounds::Array,reg)
N,S,E,W = bounds;
rN,rS,rE,rW = regionbounds(reg); lon = [rE,rW]; lat = [rN,rS];
minlon = minimum(lon); maxlon = maximum(lon);
minlat = minimum(lat); maxlat = maximum(lat);
if E > maxlon; E = from0360to180(E);
elseif E < minlon; E = from180to0360(E);
end
if W > maxlon; W = from0360to180(W);
elseif W < minlon; W = from180to0360(W);
end
if all([W,E] > minlon) && all([W,E] < maxlon) &&
all([N,S] > minlat) && all([N,S] < maxlat)
return true
else; return false
end
end
function isgridinregion(bounds::Array{Any,2},lon::Array,lat::Array)
N,S,E,W = bounds;
minlon = minimum(lon); maxlon = maximum(lon);
if E > maxlon; E = from0360to180(E);
elseif E < minlon; E = from180to0360(E);
end
if W > maxlon; W = from0360to180(W);
elseif W < minlon; W = from180to0360(W);
end
if all([W,E] > minlon) && all([W,E] < maxlon) &&
all([N,S] > minlat) && all([N,S] < maxlat)
return true
else; return false
end
end
# Find Index of given position in Region
# Assumes that we points/grid are definitely in the region.
function regionpoint(plon::AbstractFloat,plat::AbstractFloat,lon::Array,lat::Array)
minlon = minimum(lon); maxlon = maximum(lon);
if plon > maxlon; plon = from0360to180(plon);
elseif plon < minlon; plon = from180to0360(plon);
end
@info "$(Dates.now()) - Finding grid points in data closest to requested location ..."
ilon = argmin(abs.(lon.-plon)); ilat = argmin(abs.(lat.-plat));
return [ilon,ilat]
end
function regionpoint(pcoord::Array{Any,2},lon::Array,lat::Array)
plon,plat = pcoord; minlon = minimum(lon); maxlon = maximum(lon);
if plon > maxlon; plon = from0360to180(plon);
elseif plon < minlon; plon = from180to0360(plon);
end
@info "$(Dates.now()) - Finding grid points in data closest to requested location ..."
ilon = argmin(abs.(lon.-plon)); ilat = argmin(abs.(lat.-plat));
return [ilon,ilat]
end
function regiongrid(bounds::Array,lon::Array,lat::Array)
N,S,E,W = bounds;
minlon = minimum(lon); maxlon = maximum(lon);
if E > maxlon; E = from0360to180(E);
elseif E < minlon; E = from180to0360(E);
end
if W > maxlon; W = from0360to180(W);
elseif W < minlon; W = from180to0360(W);
end
@info "$(Dates.now()) - Finding indices of data matching given boundaries ..."
iE = argmin(abs.(lon.-E)); iW = argmin(abs.(lon.-W));
iN = argmin(abs.(lat.-N)); iS = argmin(abs.(lat.-S));
return [iN,iS,iE,iW]
end
# Tranformation of Coordinates
function from180to0360(lon)
@info "$(Dates.now()) - Longitude of point given in [-180,180] but data range is [0,360]. Adjusting coordinates of point to match."
lon = lon + 360;
end
function from0360to180(lon)
@info "$(Dates.now()) - Longitude of point given in [0,360] but data range is [-180,180]. Adjusting coordinates of point to match."
lon = lon - 360;
end
# Data Extraction
function regionpermute(data)
irow = size(data,1); icol = size(data,2); nd = ndims(data)
if irow < icol
@info "$(Dates.now()) - Number of rows smaller than number of columns, indicating that data is in (lat,lon) rather than (lon,lat) format. Permuting to (lon,lat) formatting."
if nd == 2; data = transpose(data)
elseif nd > 2; data = permutedims(data,vcat(2,1,convert(Array,3:nd)))
end
end
return data
end
function regionextract(data,coord,ndim)
if ndim == 2; data = data[coord[1],coord[2]];
elseif ndim == 3; data = data[coord[1],coord[2],:];
elseif ndim == 4; data = data[coord[1],coord[2],:,:];
end
end
function regionextractpoint(data,plon,plat,lon::Array,lat::Array)
icoord = regionpoint(plon,plat,lon,lat); ndim = ndims(data)
@info "$(Dates.now()) - Extracting data from coordinates (lon=$(plon),lat=$(plat)) from global datasets ..."
pdata = regionextract(data,icoord,ndim)
return pdata
end
function regionextractgrid(data,reg,lon::Array,lat::Array)
data = regionpermute(data);
@info "$(Dates.now()) - Determining indices of longitude and latitude boundaries in parent dataset ..."
bounds = regionbounds(reg); nlon = length(lon); ndim = ndims(data);
igrid = regiongrid(bounds,lon,lat);
iN = igrid[1]; iS = igrid[2]; iE = igrid[3]; iW = igrid[4];
@debug "$(Dates.now()) - Creating vector of latitude indices to extract ..."
if iN < iS; iNS = iN : iS
elseif iS < iN; iNS = iS : iN
end
@debug "$(Dates.now()) - Creating vector of longitude indices to extract ..."
if iW < iE; iWE = iW : iE
elseif iW > iE; iWE = 1 : (iE + nlon - iW); ilon = vcat(iW:nlon,1:(iW-1));
@info "$(Dates.now()) - West indice larger than East indice. Reshaping of longitude vector required."
lon[1:(iW-1)] = lon[1:(iW-1)] .+ 360; lon = lon[ilon];
@info "$(Dates.now()) - Reshaping data matrix to match longitude vector ..."
if ndim == 2; data = data[ilon,:];
elseif ndim == 3; data = data[ilon,:,:];
elseif ndim == 4; data = data[ilon,:,:,:];
end
end
@info "$(Dates.now()) - Extracting data for the $(regionfullname(reg)) region from global datasets ..."
rdata = regionextract(data,[iWE,iNS],ndim)
rgrid = [lon[iWE],lat[iNS]]
return rdata,rgrid
end
|
import Base.+
import Base.-
import Base.*
import Base./
import Base.zero
import Base.iszero
import Base.one
import Base.inv
import Base.isnan
using Images
using ColorTypes
function zero(a::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return (0.0,0.0,0.0,0.0)
end
function iszero((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64}
)::Bool
return x1==0.0 && x2==0.0 && x3==0.0 && x4==0.0
end
function one((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return (1.0,0.0,0.0,0.0)
end
function +((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64},
(y1,y2,y3,y4)::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return (x1+y1,x2+y2,x3+y3,x4+y4)
end
function -((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64},
(y1,y2,y3,y4)::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return (x1-y1,x2-y2,x3-y3, x4-y4)
end
function -((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return (-x1,-x2,-x3,-x4)
end
function *((x1,x2,x3, x4)::Tuple{Float64, Float64, Float64, Float64}, y::Float64
)::Tuple{Float64, Float64, Float64, Float64}
return (x1*y,x2*y,x3*y,x4*y)
end
function *(y::Float64, (x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return (x1*y,x2*y,x3*y,x4*y)
end
# \cdot tab
function ⋅((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64},
(y1,y2,y3,y4)::Tuple{Float64, Float64, Float64, Float64})::Float64
return x1*y1+x2*y2+x3*y3+x4*y4
end
function norm(x::Tuple{Float64, Float64, Float64, Float64})::Float64
return sqrt(x ⋅ x)
end
function normalize(a::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
n=norm(a)
if n==0.0
return a
end
return (1.0/n)*a
end
function conj((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return (x1,-x2,-x3,-x4)
end
function inv((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return (1.0/(x1*x1+x2*x2+x3*x3+x4*x4))*(x1,-x2,-x3,-x4)
end
function isnan((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64}
)::Bool
return isnan(x1) || isnan(x2) || isnan(x3) || isnan(x4)
end
function *((x1,x2,x3,x4)::Tuple{Float64, Float64, Float64, Float64},
(y1,y2,y3,y4)::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return (x1*y1-x2*y2-x3*y3-x4*y4,
x2*y1+x1*y2+x3*y4-x4*y3,
x3*y1+x1*y3-x2*y4+x4*y2,
x1*y4+x4*y1+x2*y3-x3*y2)
end
function /(a::Tuple{Float64, Float64, Float64, Float64},
b::Tuple{Float64, Float64, Float64, Float64}
)::Tuple{Float64, Float64, Float64, Float64}
return a*inv(b)
end
function initPalette(;colorScheme::Int64=0,
colorRepetitions::Int64=1)::Tuple{Vector{RGB},Int64}
colorstepsOneColor=256
colorsteps=6*colorRepetitions*colorstepsOneColor
gray = 1.0/convert(Float64,colorstepsOneColor)
colors=Array{RGB}(UndefInitializer(),colorsteps)
for ii in 1:colorstepsOneColor
scaledgray=gray*ii
red=RGB(scaledgray,0.0,0.7*scaledgray)
green=RGB(0.0,scaledgray,0.8*scaledgray)
blue=RGB(0.4*scaledgray,0.0,scaledgray)
if colorScheme == 1
color1=blue
color2=red
color3=green
elseif colorScheme == 2
color1=green
color2=blue
color3=red
elseif colorScheme == 3
color1=blue
color2=green
color3=red
elseif colorScheme == 4
color1=green
color2=red
color3=blue
elseif colorScheme == 5
color1=red
color2=blue
color3=green
else
color1=red
color2=green
color3=blue
end
for jj in 0:colorRepetitions-1
colors[jj*6*colorstepsOneColor+ii]=color2
colors[(jj*6+2)*colorstepsOneColor-(ii-1)]=color2
colors[(jj*6+2)*colorstepsOneColor+ii]=color1
colors[(jj*6+4)*colorstepsOneColor-(ii-1)]=color1
colors[(jj*6+4)*colorstepsOneColor+ii]=color3
colors[(jj*6+6)*colorstepsOneColor-(ii-1)]=color3
end
end
return (colors,colorsteps)
end
function myimage((x,y,z,u)::Tuple{Float64, Float64, Float64, Float64},
radius::Float64,limit::Float64,size::Int64;
turnIt::Tuple{Float64, Float64, Float64, Float64}=(1.0,0.0,0.0,0.0),
colorScheme::Int64=0,
colorFactor::Int64=1,
colorOffset::Int64=0,
colorRepetitions::Int64=1)::Matrix{RGB}
image=Matrix{RGB}(UndefInitializer(),size,size)
step = radius*2.0/convert(Float64,size)
(colors,colorsteps) = initPalette(colorScheme=colorScheme,colorRepetitions=colorRepetitions)
black=RGB(0.0,0.0,0.0)
turnItNorm=normalize(turnIt)
xpos = x-radius
colorLimit=div(colorsteps-colorOffset,colorFactor)
for i in 1:size
ypos = y-radius
for j in 1:size
n=1
c=(xpos,ypos,z,u)*turnItNorm
v=zero(c)
w=zero(c)
while true
if norm(v)+norm(w)>=limit
image[i,j] = colors[colorOffset+n*colorFactor]
break
end
if n>colorLimit-1
image[i,j] = black
break
end
n += 1
vtemp = v
vinv = inv(v)
if isnan(vinv)
vinv = zero(vinv)
end
winv = inv(w)
if isnan(winv)
winv = zero(winv)
end
s=v*v+winv
t=w*w-vinv
v = s * s * (1.0/2273.0) + w + c
w = t * t * t * (1.0/3709.0) + vtemp + c
end
ypos += step
end
xpos += step
end
return image
end
function mydraw(fn::String,
a::Tuple{Float64, Float64, Float64, Float64},
radius::Float64,limit::Float64,size::Int64;
turnIt::Tuple{Float64, Float64, Float64, Float64}=(1.0,0.0,0.0,0.0),
colorScheme::Int64=0,
colorFactor::Int64=1,
colorOffset::Int64=0,
colorRepetitions::Int64=1)
image=myimage(a,radius,limit,size,
turnIt=turnIt,
colorScheme=colorScheme,
colorFactor=colorFactor,
colorOffset=colorOffset,
colorRepetitions=colorRepetitions)
save(fn,image)
end
|