text:
mutable struct ValidationResults
    gammas::Vector{Float64}
    train_scores::Vector{Float64}
    valid_scores::Vector{Float64}
end
ValidationResults(m::RegressionMethod) = ValidationResults(m, Float64[], Float64[])

function validate_params!(bd::BenchmarkData, m::RegressionMethod)
    error("No validation method for $m.")
end

function settimelimit!(m::Union{ExactPrimalCuttingPlane, PrimalWithHeuristics}, t::Float64)
    old_tl = m.time_limit
    m.time_limit = t
    m.solver = getsolver(typeof(m.solver), t)
    old_tl
end
function settimelimit!(::RelaxDualSubgradient, ::Float64)
    0.0
end
function settimelimit!(::RelaxDualCutting, ::Float64)
    0.0
end

function validate_stepsize!(::RegressionMethod,
                                ::Array{Float64,2},
                                ::YVector,
                                ::Array{Float64,2},
                                ::YVector,
                                ::Int
                            )
    nothing
end

function validate_stepsize!(m::RelaxDualSubgradient{SR},
                                X_train::Array{Float64,2},
                                Y_train::YVector,
                                X_valid::Array{Float64,2},
                                Y_valid::YVector,
                                sparsity::Int
                            ) where {SR <: PolyakStepping}

    best_score = -Inf
    best_if = 0.5
    ifrange = [0.5, 1.0, 2.0]
    for initial_factor in ifrange
        m.sr.initial_factor = initial_factor
        indices, w = solve_problem(m, X_train, Y_train, sparsity)
        pred = predict_sparse(X_valid, indices, w)
        valid_score = oosRsquared(pred, Y_valid, Y_train)
        if valid_score > best_score
            best_score = valid_score
            best_if = initial_factor
        end
    end
    m.sr.initial_factor = best_if
    nothing
end

"""
    validate_params!(X::Array{Float64,2},
                    Y::YVector,
                    sparsity::Int,
                    m::RegressionMethod)

Just need to validate gamma.
"""
function validate_params!(X::Array{Float64,2},
                        Y::YVector,
                        sparsity::Int,
                        m::RegressionMethod)

    nfolds = 10
    folds = kfolds(shuffleobs((X', Y)), k = nfolds)

    # Range of gammas we are going to validate # TODO make input
    n = size(X, 1)
    gamma_range = 1 / sqrt(n) .* 2.^collect(0:10)
    nvals = length(gamma_range)

    # Cache results from each gamma in case it is of interest
    v_results = ValidationResults(gamma_range, zeros(nvals), zeros(nvals))

    # Gammas giving highest validation score in each fold
    best_gammas = zeros(nfolds)

    old_tl = settimelimit!(m, 60.0)

    # train_scores = SharedArray{Float64}(length(gamma_range))
    # train_scores .= 0.0
    # valid_scores = SharedArray{Float64}(length(gamma_range))
    # valid_scores .= 0.0

    # Validate over all folds in the data
    fold = 1
    for ((X_train, Y_train), (X_valid, Y_valid)) in folds
        X_train, X_valid = X_train', X_valid'
        best_score = -Inf
        for (i, f) in enumerate(gamma_range)
            m.gamma = f
            # If relevant, find the best scaling factor for varying stepsizes
            validate_stepsize!(m, X_train, Y_train, X_valid, Y_valid, sparsity)
            # Solve the problem
            indices, w = solve_problem(m, X_train, Y_train, sparsity)
            # Make in sample and out of sample predictions
            pred = predict_sparse(X_valid, indices, w)
            pred_train = predict_sparse(X_train, indices, w)
            # Get scores
            train_score = isRsquared(pred_train, Y_train)
            valid_score = oosRsquared(pred, Y_valid, Y_train)
            # Cache scores in case they are of interest
            v_results.train_scores[i] += train_score
            v_results.valid_scores[i] += valid_score
            # Update best gamma and score if relevant
            if valid_score > best_score
                best_score = valid_score
                best_gammas[fold] = m.gamma
            end
        end
        fold += 1
    end
    # v_results.train_scores = train_scores
    # v_results.valid_scores = valid_scores
    settimelimit!(m, old_tl)
    v_results.train_scores ./= nfolds
    v_results.valid_scores ./= nfolds
    m.gamma = mean(best_gammas)
    v_results
end

function valid2io(io::IO, vresults::Array{ValidationResults,2}, nrange::Vector{Int})
    @assert length(nrange) == size(vresults, 1)
    write(io, "test_fold, n, gamma, mean_train_score, mean_valid_score \n")
    for j = 1:size(vresults, 2)
        for i = 1:length(nrange)
            for k = 1:length(vresults[i, j].gammas)
              write(io, "$j, $(nrange[i]), $(vresults[i, j].gammas[k]), $(vresults[i, j].train_scores[k]), $(vresults[i, j].valid_scores[k]) \n")
            end
        end
    end
end


text:
function cue()
    # example of CUE GMM: draws from N(0,1)
    y = randn(100,1)
    # 3 moment conditions
    moments = theta -> [y-theta[1] (y.^2.0).-theta[2] (y.-theta[1]).^3.0]
    weight = theta -> inv(NeweyWest(moments(theta)))
    obj = theta -> vec(mean(moments(theta),1))'*weight(theta)*vec(mean(moments(theta),1))
    theta = [0.0, 1.0]
    results = fminunc(obj, theta)
end

ext: jl

max_stars_repo_name: nilshg/Econometrics

max_issues_repo_name: nilshg/Econometrics

max_forks_repo_name: nilshg/Econometrics


text:
struct PrimalData{T, TV1<:AbstractVector{T}, TV2, TM<:AbstractMatrix{T}}
    σ::TV1
    α::TV1 # Lower move limit
    β::TV1 # Upper move limit
    p0::TV1
    q0::TV1
    p::TM
    q::TM
    ρ::TV2
    r::TV2
    r0::Base.RefValue{T}
    x::TV1 # Optimal value for x in dual iteration
    x1::TV1 # Optimal value for x in previous outer iteration
    f_val::Base.RefValue{T} # Function value at current iteration
    g_val::TV2 # Inequality values at current iteration
    ∇f::TV1 # Function gradient at current iteration
    ∇g::TM # Inequality gradients [var, ineq] at current iteration
end

struct XUpdater{TPD<:PrimalData}
    pd::TPD
end
function (xu::XUpdater)(λ)
    @unpack x = xu.pd
    #@show sum(x)
    #@show mean(xu.pd.p0), mean(xu.pd.q0)
    map!((j)->xu(λ, j), x, 1:length(x))
end
function (xu::XUpdater)(λ, j)
    @unpack p0, p, q0, ρ, q, σ, x1, α, β = xu.pd
    lj1 = p0[j] + matdot(λ, p, j) + dot(λ, ρ)*σ[j]/4
    lj2 = q0[j] + matdot(λ, q, j) + dot(λ, ρ)*σ[j]/4

    αj, βj = α[j], β[j]
    Lj, Uj = minus_plus(x1[j], σ[j])

    Ujαj = Uj - αj
    αjLj = αj - Lj
    ljαj = lj1/Ujαj^2 - lj2/αjLj^2

    Ujβj = Uj - βj
    βjLj = βj - Lj
    ljβj = lj1/Ujβj^2 - lj2/βjLj^2

    (lj1 < 0 || lj2 < 0) && @show lj1, lj2
    fpj = sqrt(lj1)
    fqj = sqrt(lj2)
    xj = (fpj * Lj + fqj * Uj) / (fpj + fqj)
    xj = ifelse(ljαj >= 0, αj, ifelse(ljβj <= 0, βj, xj))

    return xj
end

# Primal problem functions
struct ConvexApproxGradUpdater{T, TPD<:PrimalData{T}, TM<:MMAModel{T}}
    pd::TPD
    m::TM
end

function (gu::ConvexApproxGradUpdater{T})() where T
    @unpack pd, m = gu
    @unpack f_val, g_val, r = pd
    n = dim(m)
    r0 = f_val[] - mapreduce(gu, +, 1:n, init=T(0))
    map!((i)->(g_val[i] - mapreduce(gu, +, Base.Iterators.product(1:n, i:i), init=T(0))),
        r, 1:length(constraints(m)))
    pd.r0[] = r0
end
function (gu::ConvexApproxGradUpdater{T})(j::Int) where T
    pd = gu.pd
    @unpack x, σ, x1, p0, q0, ∇f = pd
    xj = x[j]
    σj = σ[j]
    Lj, Uj = minus_plus(xj, σj) # x == x1
    ∇fj = ∇f[j]
    abs2σj∇fj = abs2(σj)*∇fj
    (p0j, q0j) = ifelse(∇fj > 0, (abs2σj∇fj, zero(T)), (zero(T), -abs2σj∇fj))
    p0[j], q0[j] = p0j, q0j
    return (p0[j] + q0[j])/σj
end
function (gu::ConvexApproxGradUpdater{T})(ji::Tuple) where T
    j, i = ji
    pd = gu.pd
    @unpack x, σ, p, q, ρ, ∇g = pd
    σj = σ[j]
    xj = x[j]
    Lj, Uj = minus_plus(xj, σj) # x == x1
    ∇gj = ∇g[j,i]
    abs2σj∇gj = abs2(σj)*∇gj
    (pji, qji) = ifelse(∇gj > 0, (abs2σj∇gj, zero(T)), (zero(T), -abs2σj∇gj))
    p[j,i], q[j,i] = pji, qji
    Δ = ρ[i]*σj/4
    return (pji + qji + 2Δ)/σj
end

struct VariableBoundsUpdater{T, TPD<:PrimalData{T}, TModel<:MMAModel{T}}
    pd::TPD
    m::TModel
    μ::T
end

function (bu::VariableBoundsUpdater{T})() where {T}
    @unpack pd, m = bu
    @unpack α, β = pd
    n = dim(m)
    s = StructArray{NTuple{2,T}}(α, β)
    map!(s, 1:n) do i
        t = bu(i)
        (x1 = t[1], x2 = t[2])
    end
end
function (bu::VariableBoundsUpdater{T})(j) where T
    @unpack m, pd, μ = bu
    @unpack x, σ = pd
    xj = x[j]
    Lj, Uj = minus_plus(xj, σ[j]) # x == x1 here
    αj = max(Lj + μ * (xj - Lj), min(m, j))
    βj = min(Uj - μ * (Uj - xj), max(m, j))
    return (αj, βj)
end

struct AsymptotesUpdater{T, TV<:AbstractVector{T}, TModel<:MMAModel{T}}
    m::TModel
    σ::TV
    x::TV
    x1::TV
    x2::TV
    s_init::T
    s_incr::T
    s_decr::T
end

struct InitialAsymptotesUpdater{T, TModel<:MMAModel{T}}
    m::TModel
    s_init::T
end
Initial(au::AsymptotesUpdater) = InitialAsymptotesUpdater(au.m, au.s_init)

function (au::AsymptotesUpdater{T, TV})(k::Iteration) where {T, TV}
    @unpack σ, m = au
    if k.i == 1 || k.i == 2
        map!(Initial(au), σ, 1:dim(m))
    else
        map!(au, σ, 1:dim(m))
    end
end
# Update move limits
function (au::InitialAsymptotesUpdater)(j::Int)
    @unpack m, s_init = au
    return s_init * (max(m, j) - min(m, j))
end
function (au::AsymptotesUpdater{T})(j::Int) where T
    @unpack x, x1, x2, s_incr, s_decr, σ, m = au
    σj = σ[j]
    xj = x[j]
    x1j = x1[j]
    x2j = x2[j]
    d = ifelse((xj == x1j || x1j == x2j),
        σj, ifelse(xor(xj > x1j, x1j > x2j),
        σj * s_decr, σj * s_incr))
    diff = max(m, j) - min(m, j)
    _min = T(0.01)*diff
    _max = 10diff
    return ifelse(d <= _min, _min, ifelse(d >= _max, _max, d))
end


text:
export instantaneous_zenith_angle, daily_zenith_angle

# mean anomaly at vernal equinox, radians (eq 3.11)
function mean_anomaly_vernal_equinox(ϖ::FT, e::FT) where {FT <: Real}
    β = (FT(1)-e^FT(2))^FT(0.5)
    M_v = -ϖ + (e+FT(0.25)*e^FT(3))*(FT(1)+β)*sin(ϖ)
            - FT(0.5)*e^FT(2)*(FT(0.5)+β)*sin(FT(2)*ϖ)
            + FT(0.25)*e^FT(3)*(FT(1)/FT(3)+β)*sin(FT(3)*ϖ)
    M_v = mod(M_v, FT(2)*FT(π))
    return M_v
end

# true anomaly, radians (eq 3.8)
function true_anomaly(MA::FT, e::FT) where {FT <: Real}
    TA = MA + (FT(2)*e - FT(0.25)*e^FT(3))*sin(MA)
            + FT(1.25)*e^FT(2)*sin(FT(2)*MA)
            + FT(13)/FT(12)*e^FT(3)*sin(FT(3)*MA)
    TA = mod(TA, FT(2)*FT(π))
    return TA
end

# equation of time, radians
function equation_of_time(e::FT, MA::FT, γ::FT, ϖ::FT) where {FT <: Real}
    Δt = -FT(2)*e*sin(MA) + tan(γ/FT(2))^FT(2)*sin(FT(2)*(MA + ϖ))
    Δt = mod(Δt+π, FT(2)*FT(π))-π
end

# calculate the distance, declination, and hour angle (at lon=0)
function distance_declination_hourangle(::Type{FT}, date::DateTime, param_set::APS, eot_correction::Bool) where {FT <: Real}
    Ya::FT = year_anom(param_set)
    day_length::FT = Planet.day(param_set)
    AU::FT = astro_unit()

    _epoch::FT = epoch(param_set)
    M0::FT = mean_anom_epoch(param_set)
    ϖ0::FT = lon_perihelion_epoch(param_set)

    γ::FT = obliq_epoch(param_set)
    ϖ::FT = lon_perihelion(param_set)
    e::FT = eccentricity_epoch(param_set)

    # time of vernal equinox in the epoch (rearrangement of 3.6 and 3.10)
    M_v0 = mean_anomaly_vernal_equinox(ϖ0, e)
    time_v = Ya * (M_v0 - M0) / (FT(2)*FT(π)) + _epoch

    # mean anomaly given mean anomaly at vernal equinox (3.10)
    time = datetime2julian(date) * day_length # in seconds
    M_v = mean_anomaly_vernal_equinox(ϖ, e)
    MA = mod(FT(2)*FT(π) * FT(time - time_v) / Ya + M_v, FT(2)*FT(π))

    # true anomaly, radians (3.8)
    TA = true_anomaly(MA, e)

    # true longitude, radians (3.9)
    TL = mod(TA + ϖ, FT(2)*FT(π))

    # declination, radians (3.16)
    δ = mod(asin(sin(γ) * sin(TL)), FT(2)*FT(π))

    # earth-sun distance, (3.1)
    d = AU * (FT(1) - e^FT(2)) / (FT(1) + e*cos(TA))

    # hour angle, zero at local solar noon, radians (3.17)
    if eot_correction
        Δt = equation_of_time(e, MA, γ, ϖ) / 2π * day_length # radians to seconds
    else
        Δt = FT(0)
    end
    η_UTC = mod(FT(2)*FT(π) * FT(time + Δt) / day_length, FT(2)*FT(π))

    return d, δ, η_UTC
end

"""
    instantaneous_zenith_angle(date::DateTime,
                               longitude::FT,
                               latitude::FT,
                               param_set::APS;
                               eot_correction::Bool=true) where {FT <: Real}

Returns the zenith angle and earth-sun distance
at a particular longitude and latitude on the given date (and time UTC)
given orbital parameters: obliquity, longitude of perihelion, and eccentricity
param_set is an AbstractParameterSet from CLIMAParameters.jl.

eot_correction is an optional Boolean keyword argument that defaults to true
when set to true the equation of time correction is turned on.
This switch functionality is implemented for easy comparisons with reanalyses.
"""
function instantaneous_zenith_angle(date::DateTime,
                                    longitude::FT,
                                    latitude::FT,
                                    param_set::APS;
                                    eot_correction::Bool=true) where {FT <: Real}
    λ = deg2rad(longitude)
    ϕ = deg2rad(latitude)

    d, δ, η_UTC = distance_declination_hourangle(FT, date, param_set, eot_correction)

    # hour angle
    η = mod(η_UTC + λ, FT(2)*FT(π))

    # zenith angle, radians (3.18)
    θ = mod(acos(cos(ϕ)*cos(δ)*cos(η) + sin(ϕ)*sin(δ)), FT(2)*FT(π))

    # solar azimuth angle, ζ = 0 when due E and increasing CCW
    # ζ = 3π/2 (due S) when η=0 at local solar noon
    ζ = mod(FT(1.5)*FT(π) - atan(sin(η), cos(η)*sin(ϕ) - tan(δ)*cos(ϕ)), FT(2)*FT(π))

    return θ, ζ, d
end

"""
    daily_zenith_angle(date::DateTime,
                       latitude::FT,
                       param_set::APS;
                       eot_correction::Bool=true) where {FT <: Real}
Returns the daily averaged zenith angle and earth-sun distance
at a particular latitude given the date and orbital parameters
obliquity, longitude of perihelion, and eccentricity
param_set is an AbstractParameterSet from CLIMAParameters.jl.

eot_correction is an optional Boolean keyword argument that defaults to true
when set to true the equation of time correction is turned on.
This switch functionality is implemented for easy comparisons with reanalyses.
"""
function daily_zenith_angle(date::DateTime,
                            latitude::FT,
                            param_set::APS;
                            eot_correction::Bool=true) where {FT <: Real}
    ϕ = deg2rad(latitude)

    d, δ, _ = distance_declination_hourangle(FT, date, param_set, eot_correction)

    # sunrise/sunset angle (3.19)
    T = tan(ϕ) * tan(δ)
    if T >= FT(1)
        ηd = FT(π)
    elseif T <= FT(-1)
        ηd = FT(0.0)
    else
        ηd = acos(FT(-1)*T)
    end

    # daily averaged zenith angle (3.20)
    daily_θ = mod(acos(FT(1)/FT(π)*(ηd*sin(ϕ)*sin(δ) + cos(ϕ)*cos(δ)*sin(ηd))), FT(2)*FT(π))

    return daily_θ, d
end


text:
type UCFH<:FiniteHorizonAgent
    policy::Matrix{UInt64}
    ns::Array{UInt64, 4}
    phat::Array{Float64, 4}
    n::Array{UInt64, 3}
    nstemp::Array{UInt64, 4}
    ntemp::Array{UInt64, 3}
    rewards::Array{Float64, 3}
    Vopt::Matrix{Float64}
    δ::Float64
    ϵ::Float64
    rewards_known::Bool
    update_schedule::Bool
    ln1d::Float64
    mval::Float64
    mfactor::Float64
    update_necessary::Bool
end

function UCFH(S, A, H, rewards, δ, ϵ, update_schedule=false, mfactor=1.)
    policy = zeros(UInt64, S, H)
    ns = zeros(UInt64, S, S, A, H)
    phat = zeros(S, S, A, H)
    phat[1, :, :, :] = 1.
    n = zeros(UInt64, S, A, H)

    δ1 = δ / (2 * S^2 * A * H * log2( S^2 * H^2 * 4 / ϵ))
    ln1d = log(6 / δ1)
    mval = 512 * (log2(log2(H)))^2 * S * H^3 * log(8 * H^2 * S^2 / ϵ)^2 * log(3 / δ1)

    m = UCFH(policy, ns, phat, n, copy(ns), copy(n), rewards, zeros(S, H+1), δ, ϵ, true, update_schedule, ln1d, mval, mfactor, false)
    rand!(m.policy, 1:A) # Initialize with uniformly random policy
    m
end
function observe!(m::UCFH, s, a, t, r, sn)
    if !m.update_schedule
        m.ns[sn, s, a, t] += 1
        m.n[s, a, t] +=  1
        if !m.rewards_known
            m.rewards[s, a, t] += r
        end
    else
        if m.ntemp[s,a,t] >= nS(m) * m.mval * m.mfactor * horizon(m)
            return
        end
        m.nstemp[sn, s, a, t] += 1
        m.ntemp[s, a, t] +=  1
        if m.ntemp[s,a,t] >= max(m.mval * m.mfactor, m.n[s,a,t])
            m.update_necessary = true
            m.n[s,a,t] = m.ntemp[s,a,t]
            m.ns[:,s,a,t] = m.nstemp[:, s, a, t]
        end
    end
end

"""computes the convex hull of the confidence set stated in the paper
the convex hull is sufficient for the theoretical results to hold"""
function confidence_set(m::UCFH, p, n)

    ln1d = m.ln1d
    if n <= 1
        return (0., 1.)
    end
    empstd = √(p * (1 - p))
    hoeff = √(ln1d / 2 / n)
    bern = empstd * √(ln1d * 2 / n) + 7 / 3 / (n - 1) * ln1d

    pmax = min(1, p + hoeff, p + bern)
    pmin = max(0, p - hoeff, p - bern)

    stdC =√(2 * ln1d / (n - 1))
    # confidence interval induced by empricial stddev bound
    if empstd >= stdC && empstd <= 0.5
        v =  √(0.25 - (empstd - stdC)^2)
        pmin = max(pmin, .5 - v)
        pmax = min(pmax, .5 + v)
    end

    ## potentially nonconvex confidence set induced by empiricla stddev bound
    #if empstd <= 0.5 - stdC
    #    p1 = 0.5 - √(0.25 - (empstd + stdC)^2)
    #    p2 = 0.5 + √(0.25 - (empstd + stdC)^2)
    #    if p1 <= pmin
    #        pmin = max(pmin, p2)
    #    elseif p2 >= pmax
    #        pmax = min(pmax, p1)
    #    end
    #end
    (pmin, pmax)
end

function update_policy!(m::UCFH)
    if m.update_schedule && !m.update_necessary
        return
    end
    S = nS(m)
    H = horizon(m)
    A = nA(m)
    Q = zeros(A)
    m.rewards_known || error("UCFH assumes known rewards")

    pcur = zeros(S)
    pmax = ones(S)

    m.phat .= m.ns ./ reshape(m.n, 1, S, A, H)
    for t=H:-1:1
        V = m.Vopt[:, t+1]
        ind = sortperm(V)

        for s ∈ 1:S
            for a ∈ 1:A
                mass_left = 1.
                EV = 0.
                for i ∈ 1:S
                    pcur[i], pmax[i] = confidence_set(m, m.phat[i, s, a, t], m.n[s,a,t])
                    mass_left -= pcur[i]
                    EV += pcur[i] * V[i]
                end
                if mass_left < 0
                    error("Inadmissible interval with total mass $(1 - mass_left)")
                end
                for i ∈ S:-1:1
                    ii = ind[i]
                    pcmax = min(mass_left+pcur[ii], pmax[ii])
                    mass_left -= pcmax - pcur[ii]
                    EV += (pcmax - pcur[ii]) * V[ii]
                    pcur[ii] = pcmax
                    if mass_left < 3 * eps(typeof(mass_left))
                        break
                    end
                end

                r = m.rewards[s, a, t]

                Q[a] = r + EV
            end
            bestA = indmax(Q)
            m.policy[s, t] = bestA
            m.Vopt[s, t] = Q[bestA]
        end
    end
    m.update_necessary = false
end


text:
module Grids

export PhysicalGrid, FourierGrid
export LocalGridIterator, PhysicalGridIterator, FourierGridIterator
import Base: @propagate_inbounds

using PencilFFTs.PencilArrays
const PA = PencilArrays

using AbstractFFTs: Frequencies, fftfreq, rfftfreq

# N-dimensional grid.
abstract type AbstractGrid{T, N, Perm} end

# Note: the PhysicalGrid is accessed with non-permuted indices.
struct PhysicalGrid{T, N, LocalRange <: AbstractRange{T}, Perm} <: AbstractGrid{T, N, Perm}
    dims  :: Dims{N}                # permuted dimensions (N1, N2, N3)
    r     :: NTuple{N, LocalRange}  # non-permuted coordinates (x, y, z)
    iperm :: Perm  # inverse permutation (i_2, i_3, i_1) -> (i_1, i_2, i_3)

    # limits: non-permuted geometry limits ((xbegin_1, xend_1), (xbegin_2, xend_2), ...)
    # dims_in: non-permuted global dimensions
    # perm: index permutation
    function PhysicalGrid(limits::NTuple{N, NTuple{2}}, dims_in::Dims{N},
                          perm, ::Type{T}=Float64) where {T, N}
        r = map(limits, dims_in) do l, d
            # Note: we store one extra value at the end (not included in
            # `dims`), to include the right limit.
            LinRange{T}(first(l), last(l), d + 1)
        end
        dims = dims_in
        iperm = inv(perm)
        Perm = typeof(iperm)
        new{T, N, typeof(first(r)), Perm}(dims, r, iperm)
    end
end

# Grid of Fourier wavenumbers for N-dimensional r2c FFTs.
struct FourierGrid{T, N, Perm} <: AbstractGrid{T, N, Perm}
    dims  :: Dims{N}
    r     :: NTuple{N, Frequencies{T}}
    iperm :: Perm

    function FourierGrid(limits::NTuple{N, NTuple{2}}, dims_in::Dims{N},
                         perm, ::Type{T}=Float64) where {T, N}
        F = Frequencies{T}
        r = ntuple(Val(N)) do n
            l = limits[n]
            L = last(l) - first(l)  # box size
            M = dims_in[n]
            fs::T = 2pi * M / L
            n == 1 ? rfftfreq(M, fs)::F : fftfreq(M, fs)::F
        end
        dims = dims_in
        iperm = inv(perm)
        Perm = typeof(iperm)
        new{T,N,Perm}(dims, r, iperm)
    end
end

Base.eltype(::Type{<:AbstractGrid{T}}) where {T} = T
Base.ndims(g::AbstractGrid{T, N}) where {T, N} = N
Base.size(g::AbstractGrid) = g.dims
Base.size(g::AbstractGrid, i) = size(g)[i]
Base.axes(g::AbstractGrid) = Base.OneTo.(size(g))
Base.CartesianIndices(g::AbstractGrid) = CartesianIndices(axes(g))

function Base.iterate(g::AbstractGrid, state::Int=1)
    state_new = state == ndims(g) ? nothing : state + 1
    g[state], state_new
end
Base.iterate(::AbstractGrid, ::Nothing) = nothing

@propagate_inbounds Base.getindex(g::AbstractGrid, i::Integer) = g.r[i]

@propagate_inbounds function Base.getindex(g::AbstractGrid{T, N} where T,
                                           I::CartesianIndex{N}) where N
    # Assume input indices are not permuted.
    ntuple(n -> g[n][I[n]], Val(N))
end

@propagate_inbounds function Base.getindex(g::AbstractGrid{T, N} where T,
                                           ranges::NTuple{N, AbstractRange}) where N
    ntuple(n -> g[n][ranges[n]], Val(N))
end

# Get range of geometry associated to a given pencil.
@propagate_inbounds Base.getindex(g::AbstractGrid{T, N} where T,
                                  p::Pencil{N}) where N =
    g[range_local(p, LogicalOrder())]

"""
    LocalGridIterator{T, N, G<:AbstractGrid}

Iterator for efficient access to a subregion of a global grid defined by an
`AbstractGrid` object.
"""
struct LocalGridIterator{
                T,
                N,
                G <: AbstractGrid{T, N},
                It <: Iterators.ProductIterator{<:Tuple{Vararg{AbstractVector,N}}},
                Perm,
            }
    grid  :: G
    range :: NTuple{N, UnitRange{Int}}
    iter  :: It    # iterator with permuted indices and values
    iperm :: Perm  # inverse permutation

    # Note: the range is expected to be unpermuted.
    function LocalGridIterator(grid::AbstractGrid{T,N},
                               range::NTuple{N,UnitRange{Int}}) where {T, N}
        if !(CartesianIndices(range) ⊆ CartesianIndices(grid))
            throw(ArgumentError("given range $range is not a subrange " *
                                "of grid with unpermuted axes = $(axes(grid))"))
        end

        iperm = grid.iperm
        perm = inv(iperm)

        # Note: grid[range] returns non-permuted coordinates from a non-permuted
        # `range`.
        # We want the coordinates permuted. This way we can iterate in the
        # right memory order, according to the current dimension permutation.
        # Then, we unpermute the coordinates at each call to `iterate`.
        grid_perm = perm * grid[range]
        iter = Iterators.product(grid_perm...)

        G = typeof(grid)
        It = typeof(iter)
        Perm = typeof(iperm)

        new{T, N, G, It, Perm}(grid, range, iter, iperm)
    end
end

LocalGridIterator(grid::AbstractGrid, u::PA.MaybePencilArrayCollection) =
    LocalGridIterator(grid, pencil(u))

LocalGridIterator(grid::AbstractGrid, p::Pencil) =
    LocalGridIterator(grid, range_local(p, LogicalOrder()))

Base.parent(g::LocalGridIterator) = g.grid
Base.size(g::LocalGridIterator) = size(g.iter)
Base.eltype(::Type{G} where G <: LocalGridIterator{T}) where {T} = T

@inline function Base.iterate(g::LocalGridIterator, state...)
    next = iterate(g.iter, state...)
    next === nothing && return nothing
    coords_perm, state_new = next  # `coords_perm` is permuted, e.g. (z, y, x)
    # We return unpermuted coordinates, e.g. (x, y, z)
    g.iperm * coords_perm, state_new
end

const FourierGridIterator{T, N} =
    LocalGridIterator{T, N, G} where {T, N, G <: FourierGrid}

const PhysicalGridIterator{T, N} =
    LocalGridIterator{T, N, G} where {T, N, G <: PhysicalGrid}

end


text:
using LinearAlgebra
using SparseArrays
using PartitionedArrays
using Test
using IterativeSolvers

function test_fdm(parts)

  u(x) = x[1]+x[2]
  f(x) = zero(x[1])

  lx = 2.0
  ls = (lx,lx,lx)
  nx = 10
  ns = (nx,nx,nx)
  n = prod(ns)
  h = lx/(nx-1)
  points = [(0,0,0),(-1,0,0),(1,0,0),(0,-1,0),(0,1,0),(0,0,-1),(0,0,1)]
  coeffs = [-6,1,1,1,1,1,1]/(h^2)
  stencil = [ (coeff,CartesianIndex(point)) for (coeff,point) in zip(coeffs,points) ]

  #lx = 2.0
  #ls = (lx,lx)
  #nx = 4
  #ns = (nx,nx)
  #n = prod(ns)
  #h = lx/(nx-1)
  #points = [(0,0),(-1,0),(1,0),(0,-1),(0,1)]
  #coeffs = [-4,1,1,1,1]/(h^2)
  #stencil = [ (coeff,CartesianIndex(point)) for (coeff,point) in zip(coeffs,points) ]

  # Use a Cartesian partition if possible
  if ndims(parts) == length(ns)
    rows = PRange(parts,ns)
  else
    rows = PRange(parts,n)
  end

  # We don't need the ghost layer for the rhs
  # So, it can be allocated right now.
  b = PVector{Float64}(undef,rows)

  # We don't need the ghost layer for the exact solution
  # So, it can be allocated right now.
  x̂ = similar(b)

  # Loop over (owned) rows, fill the coo-vectors, rhs, and the exact solution
  # In this case, we always touch local rows, but arbitrary cols.
  # Thus, row ids can be readily stored in local numbering so that we do not need to convert
  # them later.
  I,J,V = map_parts(rows.partition,b.values,x̂.values) do rows,b,x̂
    cis = CartesianIndices(ns)
    lis = LinearIndices(cis)
    I = Int[]
    J = Int[]
    V = Float64[]
    for lid in rows.oid_to_lid
      i = rows.lid_to_gid[lid]
      ci = cis[i]
      xi = (Tuple(ci) .- 1) .* h
      x̂[lid] = u(xi)
      boundary = any(s->(1==s||s==nx),Tuple(ci))
      if boundary
        push!(I,lid)
        push!(J,i)
        push!(V,one(eltype(V)))
        b[lid] = u(xi)
      else
        for (v,dcj) in stencil
          cj = ci + dcj
          j = lis[cj]
          push!(I,lid)
          push!(J,j)
          push!(V,-v)
        end
        b[lid] = f(xi)
      end
    end
    I,J,V
  end

  # TODO fill b and x̂ while add_gids is communicating values.

  # Build a PRange taking the owned ids in rows plus ghost ids from the touched cols
  cols = add_gids(rows,J)

  # Now we can convert J to local numbering, I is already in local numbering.
  to_lids!(J,cols)

  # Build the PSparseMatrix from the coo-vectors (in local numbering)
  # and the data distribution described by rows and cols.
  A = PSparseMatrix(I,J,V,rows,cols;ids=:local)

  # The initial guess needs the ghost layer (that why we take cols)
  # in other to perform the product A*x in the cg solver.
  # We also need to set the boundary values
  x0 = PVector(0.0,cols)
  map_parts(x0.values,x0.rows.partition) do x,rows
    for lid in rows.oid_to_lid
      cis = CartesianIndices(ns)
      i = rows.lid_to_gid[lid]
      ci = cis[i]
      xi = (Tuple(ci) .- 1) .* h
      boundary = any(s->(1==s||s==nx),Tuple(ci))
      if boundary
        x[lid] = u(xi)
      end
    end
  end

  # When this call returns, x has the correct answer only in the owned values.
  # The values at ghost ids can be recovered with exchange!(x)
  x = copy(x0)
  IterativeSolvers.cg!(x,A,b,verbose=i_am_main(parts))

  # This compares owned values, so we don't need to exchange!
  @test norm(x-x̂) < 1.0e-5

end


text:
module spiavalonfpga

#  Derived from spiavagif4 July 22, 2019.
#  By Gregory Raven, Plantation Florida
#  KF5N

#include("command_line.jl")
include("SPIManager.jl")

export send

# For opening and working with images
using Images
using Printf

# For progress information on the command line
using ProgressMeter

# Address of the max_frame_count register.
# System counts to this value before moving to the next frame.
framecount_reg_address() = 0x0400_0000

# Address of the max_image_count register.
# Number of images in the GIF.
imagecount_reg_address() = 0x0400_0010

dram_base_address() = zero(UInt)

#  Modify this function to work with SPI.
function send(image::String)  # image is a string path.
    @info "Loading Image"
    img = load(image)

    # Configure frame count register.
    #  This writes the number of frames in the GIF -1 (zero based).
    gif_frames = zeros(UInt8,1)  #  view will not take array size of 1.
    gif_frames[1] = size(img, 3) - 1
    Printf.@printf("The number of frames in the GIF is %d\n", gif_frames[1] + 1)
    SPIManager.write(imagecount_reg_address(), gif_frames)

    @info "Packing Image"
    # By default, use 4 bits per color and 16 bits per pixel.
    data = pack(flatten(img), 4, 16)

    @info "Sending Image"
    #  write function for SPI:
    #  write(address, data)
    SPIManager.write(dram_base_address(), data)
end

# Orient images correctly so standard iteration ends up in the correct format
# for the display unit.
#
# Display unit expects images to be row major.
flatten(img::AbstractArray{T,2}) where T = reshape(img', :)
flatten(img::AbstractArray{T,3}) where T = permutedims(img, (2,1,3))

function pack(img::Array, bits_per_color, bits_per_pixel)
    # Make sure numbers match.
    num_colors = 3
    if num_colors * bits_per_color > bits_per_pixel
        throw(Error())
    end
    # Final return type, just a collection of bytes.
    packed_data = UInt8[]

    # Basic Idea:
    #
    # Go through each item in the flattened image. Pull out the red, green, and
    # blue channels, taking the requested number of bits from the top of each
    # value. As these are decoded, they will be appended to a vector.
    #
    # Each time the vector exceeds 8 bits, we will convert the leading 8 bits
    # to a UInt8 and remove them from the vector.
    #
    # Pad zeros to the desired "bits_per_pixel".
    #
    # Note that this is not super efficient.
    bit_buffer = UInt8[]
    colors = (red, green, blue)

    @showprogress 1 for pixel in img
        newbits = upperbits.(bits.(colors, pixel), bits_per_color)
        for vec in newbits
            append!(bit_buffer, vec)
        end

        # Zero pad if necessary
        pad = zeros(UInt8, bits_per_pixel - 3 * bits_per_color)
        append!(bit_buffer, pad)

        # Pull out groups of 8 bits and put them in the return data.
        groupbits!(packed_data, bit_buffer)
    end

    return packed_data
end

bits(f, x) = f(x).i
upperbits(x::Unsigned, n) = digits(UInt8, x; base = 2, pad = 8 * sizeof(UInt8))[end+1-n:end]

function groupbits!(target, buffer)
    while length(buffer) >= 8
        result = zero(UInt8)
        for i in 0:7
            b = popfirst!(buffer)
            result |= UInt8(b * 2^(i))
        end
        push!(target, result)
    end
end

end # module

max_stars_repo_name: Greg-R/spiavalonfpga

max_issues_repo_name: Greg-R/spiavalonfpga

max_forks_repo_name: Greg-R/spiavalonfpga


text:
function partition(
    rscriptPath::AbstractString,
    plinkfile::AbstractString,
    mapfile::AbstractString,
    qc_variants::AbstractString,
    outfile::AbstractString
    )
    bimfile = plinkfile * ".bim"
    run(`Rscript --vanilla $rscriptPath $mapfile $bimfile $qc_variants $outfile`)
end

"""
    rapid(rapid_exe, vcffile, mapfile, d, outfolder, w, r, s, [a])

Wrapper for the RaPID program.

# Inputs
- `rapid_exe`: Full path to the `RaPID_v.1.7` executable file
- `vcffile`: Phased VCF file name
- `mapfile`: Map file name
- `d`: Actual Minimum IBD length in cM
- `outfolder`: Output folder name
- `w`: Number of SNPs in a window for sub-sampling
- `r`: Number of runs
- `s`: Minimum number of successes to consider a hit

# Optional Inputs
- `a`: If `true`, ignore MAFs. By default (`a=false`) the sites are selected at random weighted
    by their MAFs.
"""
function rapid(
    rapid_exe::AbstractString,
    vcffile::AbstractString,
    mapfile::AbstractString,
    d::Number,
    outfolder::AbstractString,
    w::Int,
    r::Int,
    s::Int;
    a::Bool = false
    )
    d ≥ 0 || error("d must be ≥ 0 but was $d.")
    s ≥ 0 || error("s must be ≥ 1 but was $s.")
    isdir(outfolder) || mkdir(outfolder)
    args = String[]
    push!(args, "-i", vcffile)
    push!(args, "-g", mapfile)
    push!(args, "-d", string(d))
    push!(args, "-o", outfolder)
    push!(args, "-w", string(w))
    push!(args, "-r", string(r))
    push!(args, "-s", string(s))
    a && push!(args, "-a")
    cmd = `$rapid_exe $args`
    @info "RaPID command:\n$cmd\n"
    @info "Output directory: $outfolder\n"
    run(cmd)
end

function snpknock2(
    snpknock2_exe::AbstractString,
    bgenfile::AbstractString,
    sample_qc::AbstractString,
    variant_qc::AbstractString,
    mapfile::AbstractString,
    partfile::AbstractString,
    ibdfile::AbstractString,
    K::Int,
    cluster_size_min::Int,
    cluster_size_max::Int,
    hmm_rho::Number, # recombination scale
    hmm_lambda::AbstractFloat,
    windows::Int,
    n_threads::Int,
    seed::Int,
    compute_references::Bool,
    generate_knockoffs::Bool,
    outfile::AbstractString
    )
    args = String[]
    isdir("knockoffs") || mkdir("knockoffs")
    push!(args, "--bgen", bgenfile)
    push!(args, "--keep", sample_qc)
    push!(args, "--extract", variant_qc)
    push!(args, "--map", mapfile)
    push!(args, "--part", partfile)
    push!(args, "--ibd", ibdfile)
    push!(args, "--K", string(K))
    push!(args, "--cluster_size_min", string(cluster_size_min))
    push!(args, "--cluster_size_max", string(cluster_size_max))
    push!(args, "--hmm-rho", string(hmm_rho))
    push!(args, "--hmm-lambda", string(hmm_lambda))
    push!(args, "--windows", string(windows))
    push!(args, "--n_threads", string(n_threads))
    push!(args, "--seed", string(seed))
    compute_references && push!(args, "--compute-references")
    generate_knockoffs && push!(args, "--generate-knockoffs")
    push!(args, "--out", "./knockoffs/$outfile")
    cmd = `$snpknock2_exe $args`
    @info "snpknock2 command:\n$cmd\n"
    @info "Output directory: $(pwd() * "/knockoffs")\n"
    run(cmd)
end

"""
    decorrelate_knockoffs(plinkfile, original, knockoff)

If a SNP and its knockoffs has correlation > `r2_threshold`, this function is randomly
change some entries in the knockoff variable, i.e. decorrelate the knockoff.
"""
function decorrelate_knockoffs(
    plinkfile::AbstractString,
    original::Vector{Int},
    knockoff::Vector{Int};
    outfile = "decorrelated_knockoffs",
    outdir = pwd(),
    r2_threshold = 0.95
    )
    x = SnpArray(plinkfile * ".bed")
    n, p = size(x)
    p >> 1 == length(original) == length(knockoff) || error("Number of SNPs should be the same")
    xnew = SnpArray(joinpath(outdir, outfile * ".bed"), n, p)
    swap_probability = 1 - r2_threshold
    # calculate correlation of knockoffs with their original snps
    r2, snp1, snp2 = sizehint!(Float64[], p >> 1), zeros(n), zeros(n)
    for i in 1:p>>1
        copyto!(snp1, @view(x[:, original[i]]), center=true, scale=true)
        copyto!(snp2, @view(x[:, knockoff[i]]), center=true, scale=true)
        push!(r2, abs(cor(snp1, snp2)))
    end
    # loop over snps
    for j in 1:p>>1
        # copy original snp
        copyto!(@view(xnew[:, original[j]]), @view(x[:, original[j]]))
        # copy knockoffs
        jj = knockoff[j]
        if r2[j] ≤ r2_threshold
            copyto!(@view(xnew[:, jj]), @view(x[:, jj]))
        else
            # loop over each sample
            for i in 1:n
                # We change the an entry of knockoff with probability `swap_probability`
                # if xij is 0 or 2, set it equal to 1. If xij is 1, let it equal 0 or 2 randomly
                if rand() < swap_probability
                    if x[i, jj] == 0x01 || x[i, jj] == 0x03
                        xnew[i, jj] = 0x02
                    else
                        xnew[i, jj] = (rand() < 0.5 ? 0x02 : 0x03)
                    end
                else
                    xnew[i, jj] = x[i, jj]
                end
            end
        end
    end
    # copy bim and fam files
    cp(plinkfile * ".bim", joinpath(outdir, outfile * ".bim"), force=true)
    cp(plinkfile * ".fam", joinpath(outdir, outfile * ".fam"), force=true)
    return xnew
end


text:
"""
    StaticRange{T,L}

Abstract super type for mutable and static ranges that mirror those found in `Base`.
"""
abstract type StaticRange{T,L} <: AbstractRange{T} end

@pure length(::StaticRange{T,L}) where {T,L<:SInteger} = L()
@pure length(::Type{<:StaticRange{T,L}}) where {T,L<:SInteger} = L()

# this will facilitate indirect indexing through custom indices
firstindex(r::StaticRange) = _firstindex(IndexStyle(r), r)
firstindex(r::Type{<:StaticRange}) = _firstindex(IndexStyle(r), r)

@pure _firstindex(::IndexLinear, ::StaticRange) = SOne
@pure _firstindex(indstyle::IndexLinear, ::Type{<:StaticRange}) = SOne

@inline _firstindex(indstyle::StaticRange, ::StaticRange) = first(indstyle)

lastindex(r::StaticRange) = _lastindex(IndexStyle(r), r)

@inline _lastindex(::IndexLinear, r::StaticRange) = length(r)
@inline _lastindex(::IndexLinear, r::Type{<:StaticRange}) = length(r)

@inline _lastindex(indstyle::StaticRange, ::StaticRange) = length(indstyle)

Base.checkindex(::Type{Bool}, r::StaticRange, i::Real) =
    firstindex(r) <= i && i <= lastindex(r)

Base.checkindex(::Type{Bool}, r::StaticRange, i::AbstractRange) =
    checkindex(Bool, r, first(i)) && checkindex(Bool, r, last(i))

function _in_range(x, r::StaticRange)
    if step(r) == 0
        return !isempty(r) && first(r) == x
    else
        n = round(Integer, (x - first(r)) / step(r)) + SOne
        return n >= 1 && n <= length(r) && r[n] == x
    end
end

Base.checkindex(::Type{Bool}, inds::StaticRange, ::Base.Colon) = true
Base.checkindex(::Type{Bool}, inds::StaticRange, ::Base.Slice) = true

# TODO: is this redundant with Base./range/line#716
==(r::StaticRange, s::StaticRange) = (first(r) == first(s)) & (step(r) == step(s)) & (last(r) == last(s))
==(r::StaticRange, s::AbstractRange) = (first(r) == first(s)) & (step(r) == step(s)) & (last(r) == last(s))
==(r::AbstractRange, s::StaticRange) = (first(r) == first(s)) & (step(r) == step(s)) & (last(r) == last(s))

Base.show(io::IO, r::StaticRange) = showrange(io, r)
Base.show(io::IO, ::MIME"text/plain", r::StaticRange) = showrange(io, r)


text:
using Documenter, BasicLU

makedocs(
  modules = [BasicLU],
  doctest = true,
  linkcheck = true,
  strict = true,
  format = Documenter.HTML(
    assets = ["assets/style.css"],
    prettyurls = get(ENV, "CI", nothing) == "true",
  ),
  sitename = "BasicLU.jl",
  pages = ["Home" => "index.md"],
)

deploydocs(repo = "github.com/JuliaSmoothOptimizers/BasicLU.jl.git", devbranch = "main")


text:
using ConservationLawsParticles
using RecursiveArrayTools, DifferentialEquations, Plots

# model
V(t, x) = 2 + 0.5sin(2x) + 0.3sin(2sqrt(2)*x) + 0.2cos(2sqrt(7)*x)
W(t, x) = x^2/2 - abs(x)
W′(t, x) = x - sign(x)
mob(ρ) = max((ρ-1)^2 * (2ρ+1), 0)
smodel = SampledModel((V,), ((W′,),), (mob,))
imodel = IntegratedModel((V,), ((W,),), (mob,))

# initial condition
x0 = ArrayPartition(gaussian_particles(3, 201))

# time span
tspan = (0., 15.)

# ODE system for the particles
sprob = ODEProblem(velocities_diff!, x0, tspan, smodel)
iprob = ODEProblem(velocities_diff!, x0, tspan, imodel)

abstol = reltol = 2e-8

@time ssol = solve(sprob, BS5(); abstol=abstol, reltol=reltol);
@time isol = solve(iprob, BS5(); abstol=abstol, reltol=reltol);

# plot the particle trajectories
plot(legend=false, title="Trajectories", xlabel="time", ylabel="position")
plot!(ssol, vars=1:5:201; color=:blue)
plot!(isol, vars=1:5:201; color=:red)
savefig("traffic-diffusion.png")

# plot an animation of the density
anim = @animate for t in range(tspan...; step=1/24)
    p = plot(legend=false, xlims=(-2,20), ylims=(0,1),
        title="Density", xlabel="position", ylabel="density")
    x = ssol(t).x[1]
    min_dens = minimum(pwc_densities(x)[1][1,:,:], dims=1)[:];
    plot!(p, repeat(x, inner=(1,2))[1:20:201,:]',
        hcat(zero(min_dens), min_dens)[1:20:201,:]',
        color=:gray, opacity=.25)
    plot_density!(p, ssol(t); color=:blue)
    plot_density!(p, isol(t); color=:red)
end
gif(anim, "traffic-diffusion.gif")


text:
function ElevationMask(arg0::Vector{Vector{jdouble}})
    return ElevationMask((Vector{Vector{jdouble}},), arg0)
end

function get_elevation(obj::ElevationMask, arg0::jdouble)
    return jcall(obj, "getElevation", jdouble, (jdouble,), arg0)
end


text:
using JuMP

model = Model()
@variable(model, x);

set_lower_bound(x, 3)
lower_bound(x)

set_lower_bound(x, 2)
lower_bound(x)

delete_lower_bound(x)
has_lower_bound(x)

fix(x, 5)
fix_value(x)

@variable(model, y >= 0);

fix(y, 2; force = true)
fix_value(y)

unfix(x)
is_fixed(x)

all_variables(model)

delete(model, x)
all_variables(model)

is_valid(model, x)

model = Model()
@variable(model, x);

@constraint(model, con, 2x <= 1);

set_normalized_coefficient(con, x, 3)
con

delete(model, con)
is_valid(model, con)

model = Model()
@variable(model, x)
@objective(model, Min, 7x + 4);

objective_function(model)

objective_sense(model)

@objective(model, Max, 8x + 3)
objective_function(model)

objective_sense(model)

set_objective_function(model, 5x + 11)
objective_function(model)

set_objective_sense(model, MOI.MIN_SENSE)
objective_sense(model)


text:
using NaiveNASflux
using Test

function assertlayer(l, Wexp, bexp)
    @test size(Wexp) == size(weights(l))
    @test size(bexp) == size(bias(l))
    @test Wexp == weights(l)
    @test bexp == bias(l)
end

@testset "NaiveNASflux.jl" begin

    @info "Testing util"
    include("util.jl")

    @info "Testing select"
    include("select.jl")

    @info "Testing mutable"
    include("mutable.jl")

    @info "Testing vertex"
    include("vertex.jl")

    @info "Testing pruning"
    include("pruning.jl")

    @info "Testing examples"
    include("examples.jl")
end


text:
# ------------ Factor ------------ #

@inline function (ctx::RegenerateContext)(fn::typeof(factor), arg::A) where A <: Number
    ctx.score += arg
    ctx.weight += arg
    return arg
end


text:
using Dates
import Base.convert

convert(::Type{Int}, v::SubString{String}) = parse(Int, v)
convert(::Type{Float64}, v::SubString{String}) = parse(Float64, v)
convert(::Type{Date}, s::String) = parse(Date, s)
convert(::Type{Int}, s::String) = parse(Int, s)

max_stars_repo_name: jaantollander/genie-webapp-db

max_issues_repo_name: jaantollander/genie-webapp-db

max_forks_repo_name: jaantollander/genie-webapp-db


text:
# Methods that add perturbations

# Scales the standard deviation according to the passed schedule
function apply_schedule(
  stdev::Vector{T},      # Standard deviation
  iter::Integer,              # Iteration number
  niter::Integer,             # Total number of iterations
  schedule::Integer=1,          # Schedule to use
  p::AbstractFloat=0.5) where T <: AbstractFloat

  # stdev = stdev * (1 - (iter/niter)).^p

  if schedule == 1 # Schedule 1
    stdev = stdev .* (1 - (iter/niter)).^p
  elseif schedule == 2 # Schedule 2
    stdev = stdev ./ ((1 + iter).^p)
  elseif schedule == 3 # Schedule 3
    stdev = stdev .* p^(iter/2)
  else
    error("Schedule unknown: ", schedule )
  end

  return stdev
end

# Perturb the codebooks according to the SR-D algorithm. Assumes d-dim codebooks
function SR_D_perturb(
  C::Vector{Matrix{Float32}}, # The codebooks
  iter::Integer,              # Iteration number
  niter::Integer,             # Total number of iterations
  schedule::Integer=1,        # Schedule to use
  p::AbstractFloat=0.5)             # Power parameter in equation (18)

  m = length(C)
  d, h = size(C[1])

  # Compute the standard deviation
  stdc = Statistics.std(cat(C..., dims=2), dims=2) ./ m
  stdc = apply_schedule(stdc[:], iter, niter, schedule, p)

  for i = 1:m # Loop through each codebook
    for j = 1:d # Loop through each dimension
      noise = randn(h, 1) .* stdc[j]
      C[i][j,:] = C[i][j,:] .+ noise
    end
  end

  return C
end

# Perturb the data according to the SR-C algorithm
function SR_C_perturb(
  X::Matrix{Float32},         # d-by-n matrix of data points to train on.
  iter::Integer,              # Iteration number
  niter::Integer,             # Total number of iterations
  schedule::Integer=1,        # Schedule to use
  p::AbstractFloat=0.5)             # Power parameter in equation (18)

  d, n = size(X)

  # Compute the standard deviation
  stdx = Statistics.std(X, dims=2)
  stdx = apply_schedule(stdx[:], iter, niter, schedule, p)

  Y = zeros(Float32,size(X))

  for i = 1:d # Loop through each dimension
    noise = randn(n, 1) .* stdx[i]
    Y[i,:] = X[i,:] .+ noise
  end

  return Y
end


text:
type DispersionFormula
  ncoef::Integer
end

type SellmeierFormula <: DispersionFormula
  SellmeierFormula() = super(17)
end

type Sellmeier2Formula <: DispersionFormula
  Sellmeier2Formula() = super(17)
end

type PolynomialFormula <: DispersionFormula
  PolynomialFormula() = super(17)
end

type CauchyFormula <: DispersionFormula
  CauchyFormula() = super(11)
end


text:
@testset "Basic Arrays" begin

    let og_array = RData.load("data/Example_Log_Likelihood_Array.RData")["x"]
        global log_lik_arr = copy(permutedims(og_array, [3, 1, 2]))
    end
    let og_weights = RData.load("data/Weight_Matrix.RData")["weightMatrix"]
        global r_weights = exp.(permutedims(reshape(og_weights, 500, 2, 32), [3, 1, 2]))
    end
    r_eff = RData.load("data/Rel_Eff.RData")["rel_eff"]
    r_psis = RData.load("data/Psis_Object.RData")["x"]
    r_tail_len = Int.(RData.load("data/Tail_Vector.RData")["tail"])
    pareto_k = RData.load("data/Pareto_K.RData")["pareto_k"]
    r_loo = RData.load("data/Example_Loo.RData")["example_loo"]

    # Add labels, reformat
    r_pointwise = KeyedArray(
        r_loo["pointwise"][:, Not(4)];
        data=1:size(r_loo["pointwise"], 1),
        statistic=[:cv_est, :mcse, :overfit, :pareto_k],
    )

    r_loo["estimates"] = hcat(r_loo["estimates"], r_loo["estimates"] / size(r_pointwise, 1))
    r_ests = KeyedArray(
        r_loo["estimates"][Not(3), :];
        criterion=[:cv_est, :overfit],
        statistic=[:total, :se_total, :mean, :se_mean],
    )

    # All of these should run
    with_r_eff = psis(log_lik_arr; r_eff=r_eff)
    jul_psis = psis(log_lik_arr)
    log_lik_mat = reshape(log_lik_arr, 32, 1000)
    chain_index = vcat(fill(1, 500), fill(2, 500))
    matrix_psis = psis(log_lik_mat; chain_index=chain_index)
    log_psis = psis(log_lik_arr; log_weights=true)

    jul_loo = loo(log_lik_arr)
    r_eff_loo = psis_loo(log_lik_arr; r_eff=r_eff)

    @test display(jul_psis) === nothing
    @test display(jul_loo) === nothing

    # max 20% difference in tail length calc between Julia and R
    @test maximum(abs.(log.(jul_psis.tail_len ./ r_tail_len))) ≤ 0.2
    @test maximum(abs.(jul_psis.tail_len .- r_tail_len)) ≤ 10
    @test maximum(abs.(with_r_eff.tail_len .- r_tail_len)) ≤ 2

    # RMSE from R version is less than .1%
    @test sqrt(mean((with_r_eff.weights ./ r_weights .- 1) .^ 2)) ≤ 0.001
    # RMSE less than .2% when using InferenceDiagnostics' ESS
    @test sqrt(mean((jul_psis.weights ./ r_weights .- 1) .^ 2)) ≤ 0.002
    # Max difference is 1%
    @test maximum(log_psis.weights .- log.(r_weights)) ≤ 0.01

    ## Test difference in loo pointwise results

    # Different r_eff
    jul_pointwise = jul_loo.pointwise([:cv_est, :mcse, :overfit, :pareto_k])
    errs = (r_pointwise - jul_pointwise) .^ 2
    @test sqrt(mean(errs(:cv_est))) ≤ 0.01
    @test sqrt(mean(errs(:overfit))) ≤ 0.01
    @test sqrt(mean(errs(:pareto_k))) ≤ 0.025
    errs_mcse = log.(r_pointwise(:mcse) ./ jul_loo.pointwise(:mcse)) .^ 2
    @test_broken sqrt(mean(errs_mcse)) ≤ 0.1

    # Same r_eff
    r_eff_pointwise = r_eff_loo.pointwise([:cv_est, :mcse, :overfit, :pareto_k])
    errs = (r_pointwise - r_eff_pointwise) .^ 2
    @test sqrt(mean(errs(:cv_est))) ≤ 0.01
    @test sqrt(mean(errs(:overfit))) ≤ 0.01
    @test sqrt(mean(errs(:pareto_k))) ≤ 0.025
    errs_mcse = log.(r_pointwise(:mcse) ./ r_eff_loo.pointwise(:mcse)) .^ 2
    @test_broken sqrt(mean(errs_mcse)) ≤ 0.1

    # Test estimates
    errs = r_ests - jul_loo.estimates(; criterion=[:cv_est, :overfit])
    display(r_ests)
    display(jul_loo.estimates(; criterion=[:cv_est, :overfit]))
    display(errs)
    @test maximum(abs.(errs)) ≤ 0.01

    errs = r_ests - r_eff_loo.estimates(; criterion=[:cv_est, :overfit])
    display(errs)
    @test maximum(abs.(errs)) ≤ 0.01

    # Test for calling correct method
    @test jul_loo.psis_object.weights ≈ psis(-log_lik_arr).weights
    @test r_eff_loo.psis_object.weights ≈ psis(-log_lik_arr; r_eff=r_eff).weights
end


text:
using TreeReducer
using Base.Test

using DistributedArrays

# TreeMapReduce
f = (x -> 2 * x)
op = +
array = [i for i=1:10^3]
darray = distribute(array)

f_clojure = (() -> mapreduce(f, op, localpart(darray)))
@test mapreduce(f, op, array) == tmapreduce(f_clojure, op)

## TreeMapReduce on distributed arrays

max_stars_repo_name: gueltro/TreeReducer

max_issues_repo_name: gueltro/TreeReducer

max_forks_repo_name: gueltro/TreeReducer


text:
module BetaTest

using Test
using ReactiveMP
using Distributions
using Random

@testset "Beta" begin

    # Beta comes from Distributions.jl and most of the things should be covered there
    # Here we test some extra ReactiveMP.jl specific functionality

    @testset "vague" begin
        d = vague(Beta)

        @test typeof(d) <: Beta
        @test mean(d) === 0.5
        @test params(d) === (1.0, 1.0)
    end

    @testset "prod" begin
        @test prod(ProdAnalytical(), Beta(3.0, 2.0), Beta(2.0, 1.0)) ≈ Beta(4.0, 2.0)
        @test prod(ProdAnalytical(), Beta(7.0, 1.0), Beta(0.1, 4.5)) ≈ Beta(6.1, 4.5)
        @test prod(ProdAnalytical(), Beta(1.0, 3.0), Beta(0.2, 0.4)) ≈ Beta(0.19999999999999996, 2.4)
    end

    @testset "logmean" begin
        @test logmean(Beta(1.0, 3.0)) ≈ -1.8333333333333335
        @test logmean(Beta(0.1, 0.3)) ≈ -7.862370395825961
        @test logmean(Beta(4.5, 0.3)) ≈ -0.07197681436958758
    end

    @testset "mirroredlogmean" begin
        @test mirroredlogmean(Beta(1.0, 3.0)) ≈ -0.33333333333333337
        @test mirroredlogmean(Beta(0.1, 0.3)) ≈ -0.9411396776150167
        @test mirroredlogmean(Beta(4.5, 0.3)) ≈ -4.963371962929249
    end

end

end


text:
function num_integrate(f,a,b;order=5, method = FastGaussQuadrature.gausslegendre)
    nodes, weights = method(order);
    t_nodes = 0.5*(b-a)*nodes .+ 0.5*(b+a)
    M = length(f(a))
    if M == 1
        tmp = 0.5*(b-a)*dot(f.(t_nodes),weights)
    else
        tmp = fill(0.0,M)
        for i in 1:M
            g(x) = f(x)[i]
            tmp[i] = 0.5*(b-a)*dot(g.(t_nodes),weights)
        end
    end
    return tmp
end

"build a block diagonal matrix by repeating a matrix N times"
function myblock(A::AbstractArray{T,2},N::Int) where {T}
  M = size(A,1)
  Q = size(A,2)
  B = fill(zero(T),M*N,Q*N)
  for i = 1:N
    B[(i-1)*M+1:i*M,(i-1)*Q+1:i*Q] = A
  end
  B
end

#Flux Splittings
function glf_splt_inner_loop!(fminus, fplus, j, u, α, Flux, nonscalar::Bool)
    if nonscalar
        fminus[:,j] = 0.5*(Flux(u[:,j])-α*u[:,j])
        fplus[:,j] = 0.5*(Flux(u[:,j])+α*u[:,j])
    else
        fminus[j] = 0.5*(Flux(u[j])-α*u[j])
        fplus[j] = 0.5*(Flux(u[j])+α*u[j])
    end
end

function glf_splitting(u, α, Flux, nonscalar, ::Type{Val{true}})
  # Lax Friedrichs flux splitting
  fminus = similar(u); fplus = similar(u)
  N = nonscalar ? size(u,2) : size(u,1)
  Threads.@threads for j = 1:N
      glf_splt_inner_loop!(fminus, fplus, j, u, α, Flux, nonscalar)
  end
  fminus, fplus
end

function glf_splitting(u, α, Flux, nonscalar, ::Type{Val{false}})
  # Lax Friedrichs flux splitting
  fminus = similar(u); fplus = similar(u)
  N = nonscalar ? size(u,2) : size(u,1)
  for j = 1:N
      glf_splt_inner_loop!(fminus, fplus, j, u, α, Flux, nonscalar)
  end
  fminus, fplus
end

function llf_splitting(u, mesh, Flux, nonscalar)
  # Lax Friedrichs flux splitting
  fminus = similar(u); fplus = similar(u)
  ul=cellval_at_left(1,u,mesh)
  αl = fluxρ(ul, Flux)
  αr = zero(αl)
  for j = 1:getncells(mesh)
    ur=cellval_at_right(j,u,mesh)
    αr = fluxρ(ur, Flux)
    αk = max(αl, αr)
    if nonscalar
        fminus[:,j] = 0.5*(Flux(u[:,j])-αk*u[:,j])
        fplus[:,j] = 0.5*(Flux(u[:,j])+αk*u[:,j])
    else
        fminus[j] = 0.5*(Flux(u[j])-αk*u[j])
        fplus[j] = 0.5*(Flux(u[j])+αk*u[j])
    end
    αl = αr
  end
  fminus,fplus
end


text:
module StatStuff

# package code goes here

export

    meanSD,
    medianSD,
    varianceSD,
    standardDeviationSD,
    Poisson,
    cdfPoisson,
    BernoulliTrial

include("meanSD.jl")
include("medianSD.jl")
include("varianceSD.jl")
include("pdf.jl")
include("standardDeviationSD.jl")
include("randomWalk.jl")

end # module


text:
abstract type AbstractSymmetricEdgeCutModel end

@inline (mdl::AbstractSymmetricEdgeCutModel)(n_vertices, n_self_pins, n_cut_pins, k) = mdl(n_vertices, n_self_pins, n_cut_pins)

struct AffineSymmetricEdgeCutModel{Tv} <: AbstractSymmetricEdgeCutModel
    α::Tv
    β_vertex::Tv
    β_self_pin::Tv
    β_cut_pin::Tv
end

function AffineSymmetricEdgeCutModel(; α = false, β_vertex = false, β_self_pin = false, β_cut_pin = false)
    AffineSymmetricEdgeCutModel(promote(α, β_vertex, β_self_pin, β_cut_pin)...)
end

@inline cost_type(::Type{AffineSymmetricEdgeCutModel{Tv}}) where {Tv} = Tv

(mdl::AffineSymmetricEdgeCutModel)(n_vertices, n_self_pins, n_cut_pins) = mdl.α + n_vertices * mdl.β_vertex + n_self_pins * mdl.β_self_pin + n_cut_pins * mdl.β_cut_pin

struct SymmetricEdgeCutOracle{Ti, SelfPin, Mdl} <: AbstractOracleCost{Mdl}
    pos::Vector{Ti}
    selfpin::SelfPin
    mdl::Mdl
end

oracle_model(ocl::SymmetricEdgeCutOracle) = ocl.mdl

function oracle_stripe(hint::AbstractHint, mdl::AbstractSymmetricEdgeCutModel, A::SparseMatrixCSC; net=nothing, adj_A=nothing, kwargs...)
    @inbounds begin
        m, n = size(A)
        pos = A.colptr
        selfpin = selfpincount(hint, A; kwargs...)
        return SymmetricEdgeCutOracle(pos, selfpin, mdl)
    end
end

@inline function (cst::SymmetricEdgeCutOracle{Ti, Mdl})(j, j′, k...) where {Ti, Mdl}
    @inbounds begin
        w = cst.pos[j′] - cst.pos[j]
        l = cst.selfpin(j, j′)
        return cst.mdl(j′ - j, l, w - l, k...)
    end
end

@inline function (stp::Step{Ocl})(_j, _j′, _k...) where {Ti, Mdl, Ocl <: SymmetricEdgeCutOracle{Ti, Mdl}}
    @inbounds begin
        cst = stp.ocl
        j = destep(_j)
        j′ = destep(_j′)
        k = maptuple(destep, _k...)
        w = cst.pos[j′] - cst.pos[j]
        l = Step(cst.selfpin)(_j, _j′)
        return cst.mdl(j′ - j, l, w - l, k...)
    end
end


text:
using Bibliography
using Test
using ReferenceTests

for file in ["test.bib"] #, "xampl.bib"] #, "ignace_ref.bib"]
    test_import = Bibliography.import_bibtex("../examples/$file")
    result = Bibliography.export_web(test_import)

    # test re-exporting to bib file
    result = Bibliography.export_bibtex("result.bib", test_import)
    Sys.WORD_SIZE == 64 && @test_reference "$file" result

    if file == "test.bib"
        # test re-exporting a selection to bib file
        selection = ["CitekeyArticle", "CitekeyBook"]
        test_select = Bibliography.select(test_import, selection)
        result = Bibliography.export_bibtex("result.bib", test_select)
        Sys.WORD_SIZE == 64 && @test_reference "test-selection.bib" result
    end

    rm("result.bib")
end

testdata = """@inproceedings{demo2020proceedings,
 organization  = {DemoOrg},
 pages         = {1--10},
 doi           = {10.1000/001-1-001-00001-1_001},
 author        = {Demo, D},
 note          = {cited by 0},
 year          = {2020},
 booktitle     = {Demo Booktitle},
 title         = {Demo Title}
}"""

write("demo.bib", testdata)
Bibliography.import_bibtex(testdata)
mybib = Bibliography.import_bibtex("demo.bib")
Bibliography.export_bibtex("demo_export.bib", mybib)
mybib2 = Bibliography.import_bibtex("demo_export.bib")

rm("demo.bib")
rm("demo_export.bib")

include("sort_bibliography.jl")
include("staticweb.jl")
include("cff.jl")


text:
#==============================================================================#
# Reversible-jump Neural Networks
#==============================================================================#

module RJNN

include("net.jl")
include("propagation.jl")
include("random.jl")

end # module

max_stars_repo_name: kevdur/rjnn

max_issues_repo_name: kevdur/rjnn

max_forks_repo_name: kevdur/rjnn


text:
using Documenter, MLGoodies

DocMeta.setdocmeta!(MLGoodies, :DocTestSetup, quote
    using MLGoodies
end; recursive=true)

makedocs(;
    modules=[MLGoodies],
    format=Documenter.HTML(assets=String[], prettyurls = false),
    pages=[
        "Home" => "index.md",
        "API" => [
            "Datasets" => "datasets.md",
            "Evaluation" => "evaluation.md",
            "Transforms" => "transforms.md",
            "Utils" => "utils.md",
        ]
    ],
    repo="https://github.com/dhonza/MLGoodies.jl/blob/{commit}{path}#L{line}",
    sitename="MLGoodies.jl",
    authors="Jan Drchal"
)

deploydocs(;
    repo="github.com/dhonza/MLGoodies.jl"
)

max_stars_repo_name: dhonza/MLGoodies


text:
export ultraconversion!,ultraint!

## Start of support for UFun

# diff from T -> U
function ultradiff{T<:Number}(v::Vector{T})
    #polynomial is p(x) = sum ( v[i] * x^(i-1) )
    if length(v)≤1
        w = zeros(T,1)
    else
        w = Array{T}(length(v)-1)
        for k=1:length(v)-1
            @inbounds w[k] = k*v[k+1]
        end
    end

    w
end

#int from U ->T

#TODO: what about missing truncation?
function ultraint!{T<:Number}(v::Array{T,2})
    for k=size(v,1):-1:2
        for j=1:size(v,2)
            @inbounds v[k,j] = v[k-1,j]/(k-1)
        end
    end

    @simd for j=1:size(v)[2]
        @inbounds v[1,j] = zero(T)
    end

    v
end

function ultraint!{T<:Number}(v::Vector{T})
    resize!(v,length(v)+1)
    @simd for k=length(v):-1:2
        @inbounds v[k] = v[k-1]/(k-1)
    end

    @inbounds v[1] = zero(T)

    v
end

# Convert from U -> T
function ultraiconversion{T<:Number}(v::Vector{T})
    n = length(v)
    w = Array(T,n)

    if n == 1
        w[1] = v[1]
    elseif n == 2
        w[1] = v[1]
        w[2] = 2v[2]
    elseif n ≥ 3
        @inbounds w[end] = 2v[end]
        @inbounds w[end-1] = 2v[end-1]

        for k = n-2:-1:2
            @inbounds w[k] = 2*(v[k] + .5w[k+2])
        end

        @inbounds w[1] = v[1] + .5w[3]
    end

    w
end

# Convert T -> U
function ultraconversion{T<:Number}(v::Vector{T})
    n = length(v)
    w = Array(T,n)

    if n == 1
        w[1] = v[1]
    elseif n == 2
        w[1] = v[1]
        w[2] = .5v[2]
    elseif n ≥ 3
        w[1] = v[1] - .5v[3]

        @simd for j=2:n-2
            @inbounds w[j] = .5*(v[j] - v[j+2])
        end

        w[n-1] = .5v[n-1]
        w[n] = .5v[n]
    end

    w
end

function ultraconversion!{T<:Number}(v::Vector{T})
    n = length(v) #number of coefficients

    if n ≤ 1
        #do nothing
    elseif n == 2
        @inbounds v[2] /= 2
    else
        @inbounds v[1] -= v[3]/2

        for j=2:n-2
            @inbounds v[j] = (v[j] - v[j+2])/2
        end
        @inbounds v[n-1] /= 2
        @inbounds v[n] /= 2
    end

    v
end

function ultraconversion!{T<:Number}(v::Array{T,2})
    n = size(v)[1] #number of coefficients
    m = size(v)[2] #number of funs

    if n ≤ 1
        #do nothing
    elseif n == 2
        @simd for k=1:m
            @inbounds v[2,k] /= 2
        end
    else
        for k=1:m
            @inbounds v[1,k] -= v[3,k]/2

            for j=2:n-2
                @inbounds v[j,k] = (v[j,k] - v[j+2,k])/2
            end
            @inbounds v[n-1,k] /= 2
            v[n,k] /= 2
        end
    end

    v
end

#ultraiconversion and ultraconversion are linear, so it is possible to define them on Complex numbers as so
#ultraiconversion(v::Vector{Complex{Float64}})=ultraiconversion(real(v)) + ultraiconversion(imag(v))*1.0im
#ultraconversion(v::Vector{Complex{Float64}})=ultraconversion(real(v)) + ultraconversion(imag(v))*1.0im

#using DualNumbers
#ultraconversion{T<:Number}(v::Vector{Dual{T}})=dual(ultraconversion(real(v)), ultraconversion(epsilon(v)) )


text:
using Test, TransferEntropy

x, y = rand(100), rand(100)

###########################################
# Set `dim` and infer `k`, `l` and `m`.
###########################################
tol = 1e-12

# Only with time series
@test all(transferentropy(x, y) .>= 0 - tol)
@test all(transferentropy(x, y, dim = 3) .>= 0 - tol)
@test all(transferentropy(x, y, dim = 4) .>= 0 - tol)
@test_throws ArgumentError transferentropy(x, y, dim = 2)

# Only with time series
@test transferentropy(x, y, RectangularBinning(10)) >= 0 - tol
@test all(transferentropy(x, y, [RectangularBinning(x) for x in 2:4]) .>= 0 - tol)
@test all(transferentropy(x, y, [RectangularBinning(x) for x in 2:4],  dim = 3) .>= 0 - tol)
@test all(transferentropy(x, y, [RectangularBinning(x) for x in 2:4], dim = 4) .>= 0 - tol)
@test_throws ArgumentError transferentropy(x, y, [RectangularBinning(x) for x in 2:4], dim = 2)

###########################################
# Infer `dim` from `k`, `l` and `m`.
###########################################

# Only with time series
@test all(transferentropy(x, y, 1, 1, 1) .>= 0 - tol)
@test all(transferentropy(x, y, 1, 2, 1) .>= 0 - tol)
@test_throws ArgumentError transferentropy(x, y, 1, 1, 0)

# Only with time series
@test transferentropy(x, y, RectangularBinning(10), 1, 1, 1) >= 0 - tol
@test all(transferentropy(x, y, [RectangularBinning(x) for x in 2:4], 1, 1, 1) .>= 0 - tol)
@test all(transferentropy(x, y, [RectangularBinning(x) for x in 2:4], 1, 2, 1) .>= 0 - tol)

@test_throws ArgumentError transferentropy(x, y, [RectangularBinning(x) for x in 2:4], 1, 0, 1)


text:
### A Pluto.jl notebook ###
# v0.12.20

using Markdown
using InteractiveUtils

# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
    quote
        local el = $(esc(element))
        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
        el
    end
end

# ╔═╡ a3c276fe-30e3-11eb-3e4c-fb31d63eabf6
using ModelingToolkit, OrdinaryDiffEq, Plots, PlutoUI

# ╔═╡ dc926c2c-30e4-11eb-0b88-05fc45844731
import Pkg; Pkg.add("OrdinaryDiffEq")

# ╔═╡ e0f36006-3ba1-11eb-3a47-193462d57302
md"Enter a value for α - natural exponential growth of the prey
$(@bind α Slider(1.0 : 1 : 10; default=1.0, show_value=true))

Enter a value for β - rate of decrease in prey from predators
$(@bind β Slider(1.0 : 1 : 10; default=2.0, show_value=true))

Enter a value for δ - rate of predators growth by eating prey
$(@bind δ Slider(0.5 : .05 : 5; default=1.5, show_value=true))

Enter a value for γ - natural exponential decline of the predator
$(@bind γ Slider(0.5 : .05 : 2; default=1.25, show_value=true))

Enter a value for x0 - Initial Prey count
$(@bind x0 Slider(1 : .1 : 10; default=1, show_value=true))

Enter a value for y0 - Initial Predator count
$(@bind y0 Slider(1 : .1 : 10; default=1, show_value=true))
"

# ╔═╡ 7ebba51a-30e3-11eb-364e-f1255f41a963
function fn_Lotka_Volterra(a,b,c,d,x0,y0)
	@parameters t α β δ γ
	@variables x(t) y(t)
	@derivatives D'~t

	eqs = [D(x) ~ α*x-β*x*y,
		   D(y) ~ δ*x*y-γ*y]

	Lotka_Volterra = ODESystem(eqs,name=:Lotka_Volterra)

	sys = ODESystem(eqs)

	u0 = [x => x0,
		  y => y0]

    p = [α=>a, β=>b, δ=>c, γ=>d];

	tspan = (0.0,10.0)
	prob = ODEProblem(sys,u0,tspan,p)
	sol = solve(prob, Tsit5())
end

# ╔═╡ cb68360a-3b2f-11eb-3bef-b5e530f74f2e
begin
	sol1=fn_Lotka_Volterra(α,β,δ,γ,x0,y0)
    plot(sol1)
end

# ╔═╡ 5edf7256-3bbc-11eb-027d-a990de629754
md"### Here are some specific scenarios.
##### α=2.2,β=3.2,δ=1.6,γ=1.45  x0=2,y0=3 "

# ╔═╡ c9c12e30-3bbb-11eb-308c-b5bc17e4706e
begin
	sol2=fn_Lotka_Volterra(2.2,3.2,1.6,1.45,2,3)
    plot(sol2)
end

# ╔═╡ Cell order:
# ╠═dc926c2c-30e4-11eb-0b88-05fc45844731
# ╠═a3c276fe-30e3-11eb-3e4c-fb31d63eabf6
# ╠═7ebba51a-30e3-11eb-364e-f1255f41a963
# ╟─e0f36006-3ba1-11eb-3a47-193462d57302
# ╠═cb68360a-3b2f-11eb-3bef-b5e530f74f2e
# ╟─5edf7256-3bbc-11eb-027d-a990de629754
# ╠═c9c12e30-3bbb-11eb-308c-b5bc17e4706e


text:
# custom extension of CuArray in CUDArt for sparse vectors/matrices
# using CSC format for interop with Julia's native sparse functionality

export CuSparseMatrixCSC, CuSparseMatrixCSR,
       CuSparseMatrixHYB, CuSparseMatrixBSR,
       CuSparseMatrix, AbstractCuSparseMatrix,
       CuSparseVector

import Base: length, size, ndims, eltype, similar, pointer, stride,
    copy, convert, reinterpret, show, summary, copyto!, getindex, get!, fill!, collect

using LinearAlgebra
import LinearAlgebra: BlasFloat, Hermitian, HermOrSym, issymmetric, Transpose, Adjoint,
    ishermitian, istriu, istril, Symmetric, UpperTriangular, LowerTriangular

using SparseArrays
import SparseArrays: sparse, SparseMatrixCSC, nnz, nonzeros, nonzeroinds,
    _spgetindex

abstract type AbstractCuSparseArray{Tv, N} <: AbstractSparseArray{Tv, Cint, N} end
const AbstractCuSparseVector{Tv} = AbstractCuSparseArray{Tv,1}
const AbstractCuSparseMatrix{Tv} = AbstractCuSparseArray{Tv,2}

mutable struct CuSparseVector{Tv} <: AbstractCuSparseVector{Tv}
    iPtr::CuVector{Cint}
    nzVal::CuVector{Tv}
    dims::NTuple{2,Int}
    nnz::Cint

    function CuSparseVector{Tv}(iPtr::CuVector{Cint}, nzVal::CuVector{Tv}, dims::Int, nnz::Cint) where Tv
        new(iPtr,nzVal,(dims,1),nnz)
    end
end

function CuArrays.unsafe_free!(xs::CuSparseVector)
    unsafe_free!(xs.iPtr)
    unsafe_free!(xs.nzVal)
    return
end

mutable struct CuSparseMatrixCSC{Tv} <: AbstractCuSparseMatrix{Tv}
    colPtr::CuVector{Cint}
    rowVal::CuVector{Cint}
    nzVal::CuVector{Tv}
    dims::NTuple{2,Int}
    nnz::Cint

    function CuSparseMatrixCSC{Tv}(colPtr::CuVector{Cint}, rowVal::CuVector{Cint}, nzVal::CuVector{Tv}, dims::NTuple{2,Int}, nnz::Cint) where Tv
        new(colPtr,rowVal,nzVal,dims,nnz)
    end
end

function CuSparseMatrixCSC!(xs::CuSparseVector)
    unsafe_free!(xs.colPtr)
    unsafe_free!(xs.rowVal)
    unsafe_free!(xs.nzVal)
    return
end

"""
Container to hold sparse matrices in compressed sparse row (CSR) format on the
GPU.

**Note**: Most CUSPARSE operations work with CSR formatted matrices, rather
than CSC.
"""
mutable struct CuSparseMatrixCSR{Tv} <: AbstractCuSparseMatrix{Tv}
    rowPtr::CuVector{Cint}
    colVal::CuVector{Cint}
    nzVal::CuVector{Tv}
    dims::NTuple{2,Int}
    nnz::Cint

    function CuSparseMatrixCSR{Tv}(rowPtr::CuVector{Cint}, colVal::CuVector{Cint}, nzVal::CuVector{Tv}, dims::NTuple{2,Int}, nnz::Cint) where Tv
        new(rowPtr,colVal,nzVal,dims,nnz)
    end
end

function CuSparseMatrixCSR!(xs::CuSparseVector)
    unsafe_free!(xs.rowPtr)
    unsafe_free!(xs.colVal)
    unsafe_free!(xs.nzVal)
    return
end

"""
Container to hold sparse matrices in block compressed sparse row (BSR) format on
the GPU. BSR format is also used in Intel MKL, and is suited to matrices that are
"block" sparse - rare blocks of non-sparse regions.
"""
mutable struct CuSparseMatrixBSR{Tv} <: AbstractCuSparseMatrix{Tv}
    rowPtr::CuVector{Cint}
    colVal::CuVector{Cint}
    nzVal::CuVector{Tv}
    dims::NTuple{2,Int}
    blockDim::Cint
    dir::SparseChar
    nnz::Cint

    function CuSparseMatrixBSR{Tv}(rowPtr::CuVector{Cint}, colVal::CuVector{Cint}, nzVal::CuVector{Tv}, dims::NTuple{2,Int},blockDim::Cint, dir::SparseChar, nnz::Cint) where Tv
        new(rowPtr,colVal,nzVal,dims,blockDim,dir,nnz)
    end
end

function CuSparseMatrixBSR!(xs::CuSparseVector)
    unsafe_free!(xs.rowPtr)
    unsafe_free!(xs.colVal)
    unsafe_free!(xs.nzVal)
    return
end

"""
Container to hold sparse matrices in NVIDIA's hybrid (HYB) format on the GPU.
HYB format is an opaque struct, which can be converted to/from using
CUSPARSE routines.
"""
mutable struct CuSparseMatrixHYB{Tv} <: AbstractCuSparseMatrix{Tv}
    Mat::cusparseHybMat_t
    dims::NTuple{2,Int}
    nnz::Cint

    function CuSparseMatrixHYB{Tv}(Mat::cusparseHybMat_t, dims::NTuple{2,Int}, nnz::Cint) where Tv
        new(Mat,dims,nnz)
    end
end

"""
Utility union type of [`CuSparseMatrixCSC`](@ref), [`CuSparseMatrixCSR`](@ref),
and `Hermitian` and `Symmetric` versions of these two containers. A function accepting
this type can make use of performance improvements by only indexing one triangle of the
matrix if it is guaranteed to be hermitian/symmetric.
"""
const CompressedSparse{T} = Union{CuSparseMatrixCSC{T},CuSparseMatrixCSR{T},HermOrSym{T,CuSparseMatrixCSC{T}},HermOrSym{T,CuSparseMatrixCSR{T}}}

"""
Utility union type of [`CuSparseMatrixCSC`](@ref), [`CuSparseMatrixCSR`](@ref),
[`CuSparseMatrixBSR`](@ref), and [`CuSparseMatrixHYB`](@ref).
"""
const CuSparseMatrix{T} = Union{CuSparseMatrixCSC{T},CuSparseMatrixCSR{T}, CuSparseMatrixBSR{T}, CuSparseMatrixHYB{T}}

Hermitian{T}(Mat::CuSparseMatrix{T}) where T = Hermitian{T,typeof(Mat)}(Mat,'U')

length(g::CuSparseVector) = prod(g.dims)
size(g::CuSparseVector) = g.dims
ndims(g::CuSparseVector) = 1
length(g::CuSparseMatrix) = prod(g.dims)
size(g::CuSparseMatrix) = g.dims
ndims(g::CuSparseMatrix) = 2

function size(g::CuSparseVector, d::Integer)
    if d == 1
        return g.dims[d]
    elseif d > 1
        return 1
    else
        throw(ArgumentError("dimension must be ≥ 1, got $d"))
    end
end

function size(g::CuSparseMatrix, d::Integer)
    if d in [1, 2]
        return g.dims[d]
    elseif d > 1
        return 1
    else
        throw(ArgumentError("dimension must be ≥ 1, got $d"))
    end
end

nnz(g::AbstractCuSparseArray) = g.nnz
nonzeros(g::AbstractCuSparseArray) = g.nzVal

nonzeroinds(g::AbstractCuSparseVector) = g.iPtr

issymmetric(M::Union{CuSparseMatrixCSC,CuSparseMatrixCSR}) = false
ishermitian(M::Union{CuSparseMatrixCSC,CuSparseMatrixCSR}) = false
issymmetric(M::Symmetric{CuSparseMatrixCSC}) = true
ishermitian(M::Hermitian{CuSparseMatrixCSC}) = true

istriu(M::UpperTriangular{T,S}) where {T<:BlasFloat, S<:AbstractCuSparseMatrix} = true
istril(M::UpperTriangular{T,S}) where {T<:BlasFloat, S<:AbstractCuSparseMatrix} = false
istriu(M::LowerTriangular{T,S}) where {T<:BlasFloat, S<:AbstractCuSparseMatrix} = false
istril(M::LowerTriangular{T,S}) where {T<:BlasFloat, S<:AbstractCuSparseMatrix} = true
eltype(g::CuSparseMatrix{T}) where T = T

# getindex (mostly adapted from stdlib/SparseArrays)

# Translations
getindex(A::AbstractCuSparseVector, ::Colon)          = copy(A)
getindex(A::AbstractCuSparseMatrix, ::Colon, ::Colon) = copy(A)
getindex(A::AbstractCuSparseMatrix, i, ::Colon)       = getindex(A, i, 1:size(A, 2))
getindex(A::AbstractCuSparseMatrix, ::Colon, i)       = getindex(A, 1:size(A, 1), i)
getindex(A::AbstractCuSparseMatrix, I::Tuple{Integer,Integer}) = getindex(A, I[1], I[2])

# Column slices
function getindex(x::CuSparseMatrixCSC, ::Colon, j::Integer)
    checkbounds(x, :, j)
    r1 = convert(Int, x.colPtr[j])
    r2 = convert(Int, x.colPtr[j+1]) - 1
    CuSparseVector(x.rowVal[r1:r2], x.nzVal[r1:r2], size(x, 1))
end

function getindex(x::CuSparseMatrixCSR, i::Integer, ::Colon)
    checkbounds(x, :, i)
    c1 = convert(Int, x.rowPtr[i])
    c2 = convert(Int, x.rowPtr[i+1]) - 1
    CuSparseVector(x.colVal[c1:c2], x.nzVal[c1:c2], size(x, 2))
end

# Row slices
# TODO optimize
getindex(A::CuSparseMatrixCSC, i::Integer, ::Colon) = CuSparseVector(sparse(A[i, 1:end]))
# TODO optimize
getindex(A::CuSparseMatrixCSR, ::Colon, j::Integer) = CuSparseVector(sparse(A[1:end, j]))

function getindex(A::CuSparseMatrixCSC{T}, i0::Integer, i1::Integer) where T
    m, n = size(A)
    if !(1 <= i0 <= m && 1 <= i1 <= n)
        throw(BoundsError())
    end
    r1 = Int(A.colPtr[i1])
    r2 = Int(A.colPtr[i1+1]-1)
    (r1 > r2) && return zero(T)
    r1 = searchsortedfirst(A.rowVal, i0, r1, r2, Base.Order.Forward)
    ((r1 > r2) || (A.rowVal[r1] != i0)) ? zero(T) : A.nzVal[r1]
end

function getindex(A::CuSparseMatrixCSR{T}, i0::Integer, i1::Integer) where T
    m, n = size(A)
    if !(1 <= i0 <= m && 1 <= i1 <= n)
        throw(BoundsError())
    end
    c1 = Int(A.rowPtr[i0])
    c2 = Int(A.rowPtr[i0+1]-1)
    (c1 > c2) && return zero(T)
    c1 = searchsortedfirst(A.colVal, i1, c1, c2, Base.Order.Forward)
    ((c1 > c2) || (A.colVal[c1] != i1)) ? zero(T) : A.nzVal[c1]
end

# Called for indexing into `CuSparseVector`s
function _spgetindex(m::Integer, nzind::CuVector{Ti}, nzval::CuVector{Tv},
                     i::Integer) where {Tv,Ti}
    ii = searchsortedfirst(nzind, convert(Ti, i))
    (ii <= m && nzind[ii] == i) ? nzval[ii] : zero(Tv)
end

function collect(Vec::CuSparseVector)
    SparseVector(Vec.dims[1], collect(Vec.iPtr), collect(Vec.nzVal))
end

function collect(Mat::CuSparseMatrixCSC)
    SparseMatrixCSC(Mat.dims[1], Mat.dims[2], collect(Mat.colPtr), collect(Mat.rowVal), collect(Mat.nzVal))
end
function collect(Mat::CuSparseMatrixCSR)
    rowPtr = collect(Mat.rowPtr)
    colVal = collect(Mat.colVal)
    nzVal = collect(Mat.nzVal)
    #construct Is
    I = similar(colVal)
    counter = 1
    for row = 1 : size(Mat)[1], k = rowPtr[row] : (rowPtr[row+1]-1)
        I[counter] = row
        counter += 1
    end
    return sparse(I,colVal,nzVal,Mat.dims[1],Mat.dims[2])
end

summary(g::CuSparseMatrix) = string(g)
summary(g::CuSparseVector) = string(g)

CuSparseVector(iPtr::Vector{Ti}, nzVal::Vector{T}, dims::Int) where {T<:BlasFloat, Ti<:Integer} = CuSparseVector{T}(CuArray(convert(Vector{Cint},iPtr)), CuArray(nzVal), dims, convert(Cint,length(nzVal)))
CuSparseVector(iPtr::CuArray{Ti}, nzVal::CuArray{T}, dims::Int) where {T<:BlasFloat, Ti<:Integer} = CuSparseVector{T}(iPtr, nzVal, dims, convert(Cint,length(nzVal)))

CuSparseMatrixCSC(colPtr::Vector{Ti}, rowVal::Vector{Ti}, nzVal::Vector{T}, dims::NTuple{2,Int}) where {T<:BlasFloat,Ti<:Integer} = CuSparseMatrixCSC{T}(CuArray(convert(Vector{Cint},colPtr)), CuArray(convert(Vector{Cint},rowVal)), CuArray(nzVal), dims, convert(Cint,length(nzVal)))
CuSparseMatrixCSC(colPtr::CuArray{Ti}, rowVal::CuArray{Ti}, nzVal::CuArray{T}, dims::NTuple{2,Int}) where {T<:BlasFloat,Ti<:Integer} = CuSparseMatrixCSC{T}(colPtr, rowVal, nzVal, dims, convert(Cint,length(nzVal)))
CuSparseMatrixCSC(colPtr::CuArray{Ti}, rowVal::CuArray{Ti}, nzVal::CuArray{T}, nnz, dims::NTuple{2,Int}) where {T<:BlasFloat,Ti<:Integer} = CuSparseMatrixCSC{T}(colPtr, rowVal, nzVal, dims, nnz)

CuSparseMatrixCSR(rowPtr::CuArray, colVal::CuArray, nzVal::CuArray{T}, dims::NTuple{2,Int}) where T = CuSparseMatrixCSR{T}(rowPtr, colVal, nzVal, dims, convert(Cint,length(nzVal)))
CuSparseMatrixCSR(rowPtr::CuArray, colVal::CuArray, nzVal::CuArray{T}, nnz, dims::NTuple{2,Int}) where T = CuSparseMatrixCSR{T}(rowPtr, colVal, nzVal, dims, nnz)

CuSparseMatrixBSR(rowPtr::CuArray, colVal::CuArray, nzVal::CuArray{T}, blockDim, dir, nnz, dims::NTuple{2,Int}) where T = CuSparseMatrixBSR{T}(rowPtr, colVal, nzVal, dims, blockDim, dir, nnz)

CuSparseVector(Vec::SparseVector)    = CuSparseVector(Vec.nzind, Vec.nzval, size(Vec)[1])
CuSparseMatrixCSC(Vec::SparseVector)    = CuSparseMatrixCSC([1], Vec.nzind, Vec.nzval, size(Vec))
CuSparseVector(Mat::SparseMatrixCSC) = size(Mat,2) == 1 ? CuSparseVector(Mat.rowval, Mat.nzval, size(Mat)[1]) : throw(ArgumentError("The input argument must have a single column"))
CuSparseMatrixCSC(Mat::SparseMatrixCSC) = CuSparseMatrixCSC(Mat.colptr, Mat.rowval, Mat.nzval, size(Mat))
CuSparseMatrixCSR(Mat::SparseMatrixCSC) = switch2csr(CuSparseMatrixCSC(Mat))

similar(Vec::CuSparseVector) = CuSparseVector(copy(Vec.iPtr), similar(Vec.nzVal), Vec.dims[1])
similar(Mat::CuSparseMatrixCSC) = CuSparseMatrixCSC(copy(Mat.colPtr), copy(Mat.rowVal), similar(Mat.nzVal), Mat.nnz, Mat.dims)
similar(Mat::CuSparseMatrixCSR) = CuSparseMatrixCSR(copy(Mat.rowPtr), copy(Mat.colVal), similar(Mat.nzVal), Mat.nnz, Mat.dims)
similar(Mat::CuSparseMatrixBSR) = CuSparseMatrixBSR(copy(Mat.rowPtr), copy(Mat.colVal), similar(Mat.nzVal), Mat.blockDim, Mat.dir, Mat.nnz, Mat.dims)

function copyto!(dst::CuSparseVector, src::CuSparseVector)
    if dst.dims != src.dims
        throw(ArgumentError("Inconsistent Sparse Vector size"))
    end
    copyto!(dst.iPtr, src.iPtr)
    copyto!(dst.nzVal, src.nzVal)
    dst.nnz = src.nnz
    dst
end

function copyto!(dst::CuSparseMatrixCSC, src::CuSparseMatrixCSC)
    if dst.dims != src.dims
        throw(ArgumentError("Inconsistent Sparse Matrix size"))
    end
    copyto!(dst.colPtr, src.colPtr)
    copyto!(dst.rowVal, src.rowVal)
    copyto!(dst.nzVal, src.nzVal)
    dst.nnz = src.nnz
    dst
end

function copyto!(dst::CuSparseMatrixCSR, src::CuSparseMatrixCSR)
    if dst.dims != src.dims
        throw(ArgumentError("Inconsistent Sparse Matrix size"))
    end
    copyto!(dst.rowPtr, src.rowPtr)
    copyto!(dst.colVal, src.colVal)
    copyto!(dst.nzVal, src.nzVal)
    dst.nnz = src.nnz
    dst
end

function copyto!(dst::CuSparseMatrixBSR, src::CuSparseMatrixBSR)
    if dst.dims != src.dims
        throw(ArgumentError("Inconsistent Sparse Matrix size"))
    end
    copyto!(dst.rowPtr, src.rowPtr)
    copyto!(dst.colVal, src.colVal)
    copyto!(dst.nzVal, src.nzVal)
    dst.dir = src.dir
    dst.nnz = src.nnz
    dst
end

function copyto!(dst::CuSparseMatrixHYB, src::CuSparseMatrixHYB)
    if dst.dims != src.dims
        throw(ArgumentError("Inconsistent Sparse Matrix size"))
    end
    dst.Mat = src.Mat
    dst.nnz = src.nnz
    dst
end

copy(Vec::CuSparseVector) = copyto!(similar(Vec),Vec)
copy(Mat::CuSparseMatrixCSC) = copyto!(similar(Mat),Mat)
copy(Mat::CuSparseMatrixCSR) = copyto!(similar(Mat),Mat)
copy(Mat::CuSparseMatrixBSR) = copyto!(similar(Mat),Mat)


text:
dp, lookup = Dict(), Dict()
function search_dp(key)
    key in keys(dp) && return dp[key]
    return dp[key] = sum(search_dp((key[1] - 1, letters)) for letters in lookup[key[2]])
end
template = readline(); readline()
for (from, to) in readlines() .|>  line -> split(line, " -> ")
    dp[(1, from)] = [count(==(c), from[1] * to) for c in 'A':'Z']
    lookup[from] = (from[1] * to, to * from[2])
end
function solve(for_step)
    occ = sum(search_dp((for_step, a * b)) for (a, b) in zip(template, template[2:end]))
    occ[template[end] - 'A' + 1] += 1
    return maximum(occ) - minimum(filter(!=(0), occ))
end
println(solve(10))
println(solve(40))

max_stars_repo_name: LiquidFun/adventofcode

max_issues_repo_name: LiquidFun/adventofcode

max_forks_repo_name: LiquidFun/adventofcode


text:
# ---
# title: 1237. Find Positive Integer Solution for a Given Equation
# id: problem1237
# author: Tian Jun
# date: 2020-10-31
# difficulty: Easy
# categories: Math, Binary Search
# link: <https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/description/>
# hidden: true
# ---
#
# Given a function  `f(x, y)` and a value `z`, return all positive integer pairs
# `x` and `y` where `f(x,y) == z`.
#
# The function is constantly increasing, i.e.:
#
#   * `f(x, y) < f(x + 1, y)`
#   * `f(x, y) < f(x, y + 1)`
#
# The function interface is defined like this:
#
#
#
#     interface CustomFunction {
#     public:
#       // Returns positive integer f(x, y) for any given positive integer x and y.
#       int f(int x, int y);
#     };
#
#
# For custom testing purposes you're given an integer `function_id` and a target
# `z` as input, where `function_id` represent one function from an secret
# internal list, on the examples you'll know only two functions from the list.
#
# You may return the solutions in any order.
#
#
#
# **Example 1:**
#
#
#
#     Input: function_id = 1, z = 5
#     Output: [[1,4],[2,3],[3,2],[4,1]]
#     Explanation:  function_id = 1 means that f(x, y) = x + y
#
# **Example 2:**
#
#
#
#     Input: function_id = 2, z = 5
#     Output: [[1,5],[5,1]]
#     Explanation:  function_id = 2 means that f(x, y) = x * y
#
#
#
#
# **Constraints:**
#
#   * `1 <= function_id <= 9`
#   * `1 <= z <= 100`
#   * It's guaranteed that the solutions of `f(x, y) == z` will be on the range `1 <= x, y <= 1000`
#   * It's also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
using QuantLib

generate_flatforward_ts{C <: QuantLib.Time.BusinessCalendar}(cal::C, settlementDate::Date, flatRate::Quote) =
                        FlatForwardTermStructure(settlementDate, cal, flatRate, QuantLib.Time.Actual365())

function main()
  cal = QuantLib.Time.TargetCalendar()
  todays_date = Date(2007, 5, 15)
  settlementDate = todays_date
  set_eval_date!(settings, todays_date)

  flatRate = Quote(0.01)

  tsCurve = generate_flatforward_ts(cal, settlementDate, flatRate)

  recoveryRate = 0.5
  quoteSpreads = [0.0150, 0.0150, 0.0150, 0.0150]
  tenors = [Dates.Month(3), Dates.Month(6), Dates.Year(1), Dates.Year(2)]

  maturities = [QuantLib.Time.adjust(cal, QuantLib.Following(), todays_date + ten) for ten in tenors]

  insts = SpreadCDSHelper[SpreadCDSHelper(Quote(quoteSpreads[i]), tenors[i], 0, cal, QuantLib.Time.Quarterly(), QuantLib.Time.Following(), QuantLib.Time.DateGenerationTwentieth(),
            QuantLib.Time.Actual365(), recoveryRate, tsCurve) for i in eachindex(tenors)]

  hazardRateStructure = PiecewiseDefaultCurve(todays_date, insts, QuantLib.Time.Actual365(), QuantLib.Math.BackwardFlatInterpolation(), HazardRate(), 1.0e-12)

  hr_curve_data = nodes(hazardRateStructure)

  println(@sprintf("1Y Survival Probability: %.6f %%", survival_probability(hazardRateStructure, todays_date + Dates.Year(1)) * 100.0))
  println(@sprintf("2Y Survival Probability: %.6f %%", survival_probability(hazardRateStructure, todays_date + Dates.Year(2)) * 100.0))
end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

module RouteFilterClient

using Random
using Dates
using HTTP
using Swagger
import Swagger: field_name, property_type, hasproperty, validate_property, SwaggerApi, SwaggerModel
import Base: convert, propertynames

include("modelincludes.jl")

include("api_RouteFilterRulesApi.jl")
include("api_RouteFiltersApi.jl")

# export models
export convert, Resource
export convert, RouteFilterListResult
export convert, RouteFilterPropertiesFormat
export convert, RouteFilterRuleListResult
export convert, RouteFilterRulePropertiesFormat
export convert, SubResource
export convert, ExpressRouteCircuitPeering
export convert, PatchRouteFilter
export convert, PatchRouteFilterRule
export convert, RouteFilter
export convert, RouteFilterRule

# export operations
export convert, RouteFilterRulesApi, RouteFiltersApi

export check_required, field_name, property_type, hasproperty, propertynames, validate_property, convert

end


text:
println("Dn) Test of the ImpactExcitation module with ASF from an internally generated initial- and final-state multiplet.")

@warn("\n\n !!! This example does not work properly at present !!! \n\n")
#
setDefaults("print summary: open", "zzz-ImpactExcitation.sum")
wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=JAC.Radial.Grid(true), nuclearModel=Nuclear.Model(36.),
                        initialConfigs=[Configuration("1s^2 2s^2 2p^6")],
                        finalConfigs  =[Configuration("1s^2 2s^2 2p^5"), Configuration("1s^2 2s 2p^6") ],
                        process = Eimex(),
                        processSettings=ImpactExcitation.Settings([100., 200.], false, true, LineSelection(), 2, 0.) )

wb = perform(wa)


text:
using JETTest, Documenter

const DOC_SRC_DIR    = normpath(@__DIR__, "src")
const INDEX_FILENAME = normpath(DOC_SRC_DIR, "index.md")

function generate_index!()
    isfile(INDEX_FILENAME) && rm(INDEX_FILENAME)
    open(INDEX_FILENAME, write=true) do io
        s = string(@doc JETTest)
        write(io, s)
    end

    return relpath(INDEX_FILENAME, DOC_SRC_DIR)
end

makedocs(; modules=[JETTest],
           pages=[
               "README" => generate_index!(),
               "Toolset" => let
                    files = readdir(normpath(DOC_SRC_DIR, "toolset"), join=true)
                    relpath.(files, DOC_SRC_DIR)
               end,
           ],
           sitename="JETTest.jl",
           repo="https://github.com/aviatesk/JETTest.jl/blob/{commit}{path}#{line}",
           format=Documenter.HTML(;
               prettyurls=get(ENV, "CI", "false") == "true",
               canonical="https://aviatesk.github.io/JETTest.jl",
               assets=String[],
           ),
)

deploydocs(; repo="github.com/aviatesk/JETTest.jl",
             push_preview = true,
             )


text:
### A Pluto.jl notebook ###
# v0.16.1

using Markdown
using InteractiveUtils

# ╔═╡ 912254bc-2532-11ec-3a0e-bb48e4656479
begin
	using MarkovModels
	using HDF5
	using JLD2
	using SparseArrays
	using PlutoUI
end

# ╔═╡ d130ae9e-f21b-436e-81d5-19913c29b896
den_fsm = jldopen("/people/ondel/Repositories/SpeechLab/recipes/lfmmi/graphs//wsj/train_alignments_fsms.jld2", "r") do f
	 f["48ic030f"]
end;

# ╔═╡ 74ab1c58-1b5b-48e8-a3bc-23db2585a195
"$den_fsm"

# ╔═╡ 74934d7e-b3b2-44c0-a59f-0c8d22ee2c7a
ω = den_fsm.T[1:end-1, end]

# ╔═╡ 510098ba-5632-4b16-84a6-ac805ff2354a
findnz(den_fsm.T[1:end-1, 1:end-1])

# ╔═╡ cea70023-79c2-4139-bc59-d6cf59c5ddf0
den_fsm.T[1,1]

# ╔═╡ 455b3530-3f02-40df-b890-bc7aabb056e1
@__DIR__

# ╔═╡ 42b894cc-7e28-48b6-8304-13f4b8b166e7
open("num_fsm_wsj.txt", "w") do f
	for (i, v) in zip(findnz(den_fsm.π[1:end-1])...)
		println(f, "0 $i $i $i $(-v.val)")
	end

	for (i, j, v) in zip(findnz(den_fsm.T[1:end-1,1:end-1])...)
		println(f, "$i $j $i $j $(-v.val)")
	end

	for (i, v) in zip(findnz(ω)...)
		println(f, "$i $(-v.val)")
	end
end

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
HDF5 = "f67ccb44-e63f-5c2f-98bd-6dc0ccc4ba2f"
JLD2 = "033835bb-8acc-5ee8-8aae-3f567f8a3819"
MarkovModels = "c2ae6250-d0a1-11ea-0991-234599ce5244"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"

[compat]
HDF5 = "~0.15.6"
JLD2 = "~0.4.14"
MarkovModels = "~0.7.0"
PlutoUI = "~0.7.14"
"""

# ╔═╡ 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"

[[Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "84918055d15b3114ede17ac6a7182f68870c16f7"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.3.1"

[[ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"

[[Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"

[[BFloat16s]]
deps = ["LinearAlgebra", "Test"]
git-tree-sha1 = "4af69e205efc343068dc8722b8dfec1ade89254a"
uuid = "ab4f0b2a-ad5b-11e8-123f-65d77653426b"
version = "0.1.0"

[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"

[[Blosc]]
deps = ["Blosc_jll"]
git-tree-sha1 = "84cf7d0f8fd46ca6f1b3e0305b4b4a37afe50fd6"
uuid = "a74b3585-a348-5f62-a45c-50e91977d574"
version = "0.7.0"

[[Blosc_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Lz4_jll", "Pkg", "Zlib_jll", "Zstd_jll"]
git-tree-sha1 = "e747dac84f39c62aff6956651ec359686490134e"
uuid = "0b7ba130-8d10-5ba8-a3d6-c5182647fed9"
version = "1.21.0+0"

[[CEnum]]
git-tree-sha1 = "215a9aa4a1f23fbd05b92769fdd62559488d70e9"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.4.1"

[[CUDA]]
deps = ["AbstractFFTs", "Adapt", "BFloat16s", "CEnum", "CompilerSupportLibraries_jll", "ExprTools", "GPUArrays", "GPUCompiler", "LLVM", "LazyArtifacts", "Libdl", "LinearAlgebra", "Logging", "Printf", "Random", "Random123", "RandomNumbers", "Reexport", "Requires", "SparseArrays", "SpecialFunctions", "TimerOutputs"]
git-tree-sha1 = "335b3d2373733919b4972a51215a6840c7a33828"
uuid = "052768ef-5323-5732-b1bb-66c8b64840ba"
version = "3.4.2"

[[ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "a325370b9dd0e6bf5656a6f1a7ae80755f8ccc46"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.7.2"

[[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 = "31d0151f5716b655421d9d75b7fa74cc4e744df2"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "3.39.0"

[[CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"

[[DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "7d9d316f04214f7efdbb6398d545446e246eff02"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.10"

[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"

[[DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"

[[Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"

[[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"

[[ExprTools]]
git-tree-sha1 = "b7e3d17636b348f005f11040025ae8c6f645fe92"
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
version = "0.1.6"

[[FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "3c041d2ac0a52a12a27af2782b34900d9c3ee68c"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.11.1"

[[GPUArrays]]
deps = ["Adapt", "LinearAlgebra", "Printf", "Random", "Serialization", "Statistics"]
git-tree-sha1 = "69faa5f1c5706ca9ca067604acf797ee3a8ec6f6"
uuid = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7"
version = "8.1.1"

[[GPUCompiler]]
deps = ["ExprTools", "InteractiveUtils", "LLVM", "Libdl", "Logging", "TimerOutputs", "UUIDs"]
git-tree-sha1 = "4ed2616d5e656c8716736b64da86755467f26cf5"
uuid = "61eb1bfa-7361-4325-ad38-22787b887f55"
version = "0.12.9"

[[HDF5]]
deps = ["Blosc", "Compat", "HDF5_jll", "Libdl", "Mmap", "Random", "Requires"]
git-tree-sha1 = "83173193dc242ce4b037f0263a7cc45afb5a0b85"
uuid = "f67ccb44-e63f-5c2f-98bd-6dc0ccc4ba2f"
version = "0.15.6"

[[HDF5_jll]]
deps = ["Artifacts", "JLLWrappers", "LibCURL_jll", "Libdl", "OpenSSL_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "fd83fa0bde42e01952757f01149dd968c06c4dba"
uuid = "0234f1f7-429e-5d53-9886-15a909be8d59"
version = "1.12.0+1"

[[HypertextLiteral]]
git-tree-sha1 = "72053798e1be56026b81d4e2682dbe58922e5ec9"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.0"

[[IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.2"

[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"

[[IrrationalConstants]]
git-tree-sha1 = "f76424439413893a832026ca355fe273e93bce94"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.1.0"

[[JLD2]]
deps = ["DataStructures", "FileIO", "MacroTools", "Mmap", "Pkg", "Printf", "Reexport", "TranscodingStreams", "UUIDs"]
git-tree-sha1 = "192934b3e2a94e897ce177423fd6cf7bdf464bce"
uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819"
version = "0.4.14"

[[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"

[[LLVM]]
deps = ["CEnum", "LLVMExtra_jll", "Libdl", "Printf", "Unicode"]
git-tree-sha1 = "46092047ca4edc10720ecab437c42283cd7c44f3"
uuid = "929cbde3-209d-540e-8aea-75f648917ca0"
version = "4.6.0"

[[LLVMExtra_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "6a2af408fe809c4f1a54d2b3f188fdd3698549d6"
uuid = "dad2f222-ce93-54a1-a47d-0025e8a3acab"
version = "0.0.11+0"

[[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"

[[LinearAlgebra]]
deps = ["Libdl"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"

[[LogExpFunctions]]
deps = ["ChainRulesCore", "DocStringExtensions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "34dc30f868e368f8a17b728a1238f3fcda43931a"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.3"

[[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"

[[MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.8"

[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"

[[MarkovModels]]
deps = ["CUDA", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "4f01fbb60caea1c9f83770dda7d4d8cc7d63db65"
uuid = "c2ae6250-d0a1-11ea-0991-234599ce5244"
version = "0.7.0"

[[MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"

[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"

[[MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"

[[NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"

[[OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"

[[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"

[[OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"

[[Parsers]]
deps = ["Dates"]
git-tree-sha1 = "a8709b968a1ea6abc2dc1967cb1db6ac9a00dfb6"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.0.5"

[[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"

[[PlutoUI]]
deps = ["Base64", "Dates", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "UUIDs"]
git-tree-sha1 = "d1fb76655a95bf6ea4348d7197b22e889a4375f4"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.14"

[[Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00cfd92944ca9c760982747e9a1d0d5d86ab1e5a"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.2.2"

[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"

[[REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"

[[Random]]
deps = ["Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"

[[Random123]]
deps = ["Libdl", "Random", "RandomNumbers"]
git-tree-sha1 = "0e8b146557ad1c6deb1367655e052276690e71a3"
uuid = "74087812-796a-5b5d-8853-05524746bad3"
version = "1.4.2"

[[RandomNumbers]]
deps = ["Random", "Requires"]
git-tree-sha1 = "043da614cc7e95c703498a491e2c21f58a2b8111"
uuid = "e6cf234a-135c-5ec9-84dd-332b85af5143"
version = "1.5.3"

[[Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"

[[Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.1.3"

[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"

[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"

[[SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"

[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"

[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"

[[SpecialFunctions]]
deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
git-tree-sha1 = "793793f1df98e3d7d554b65a107e9c9a6399a6ed"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "1.7.0"

[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"

[[TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"

[[Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"

[[Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"

[[TimerOutputs]]
deps = ["ExprTools", "Printf"]
git-tree-sha1 = "7cb456f358e8f9d102a8b25e8dfedf58fa5689bc"
uuid = "a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f"
version = "0.5.13"

[[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"

[[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"

[[nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"

[[p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
"""

# ╔═╡ Cell order:
# ╠═912254bc-2532-11ec-3a0e-bb48e4656479
# ╠═d130ae9e-f21b-436e-81d5-19913c29b896
# ╠═74ab1c58-1b5b-48e8-a3bc-23db2585a195
# ╠═74934d7e-b3b2-44c0-a59f-0c8d22ee2c7a
# ╠═510098ba-5632-4b16-84a6-ac805ff2354a
# ╠═cea70023-79c2-4139-bc59-d6cf59c5ddf0
# ╠═455b3530-3f02-40df-b890-bc7aabb056e1
# ╠═42b894cc-7e28-48b6-8304-13f4b8b166e7
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002