text
stringlengths
5
1.02M
# This file include the utils for starting an experiment # Use ```include("utils.jl")``` in your experiments import Base: run using Requires @require Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" using Plots include("BanditExpBase.jl") using ...Algorithms using ...Arms using ...Algorithms: make_agents_with_k # using ..BanditExpBase: run
module LLVM using Unicode using Printf using Libdl ## source code includes include("base.jl") include("version.jl") const libllvm = Base.libllvm_path() if libllvm === nothing error("""Cannot find the LLVM library loaded by Julia. Please use a version of Julia that has been built with USE_LLVM_SHLIB=1 (like the official binaries). If you are, please file an issue and attach the output of `Libdl.dllist()`.""") end module API using CEnum using ..LLVM using ..LLVM: libllvm llvm_version = if version() < v"12" "11" elseif version().major == 12 "12" else "13" end libdir = joinpath(@__DIR__, "..", "lib") if !isdir(libdir) error(""" The LLVM API bindings for v$llvm_version do not exist. You might need a newer version of LLVM.jl for this version of Julia.""") end import LLVMExtra_jll: libLLVMExtra include(joinpath(libdir, llvm_version, "libLLVM_h.jl")) include(joinpath(libdir, "libLLVM_extra.jl")) include(joinpath(libdir, "libLLVM_julia.jl")) end # module API # LLVM API wrappers include("support.jl") include("types.jl") include("passregistry.jl") include("init.jl") include("core.jl") include("linker.jl") include("irbuilder.jl") include("analysis.jl") include("moduleprovider.jl") include("pass.jl") include("passmanager.jl") include("execution.jl") include("buffer.jl") include("target.jl") include("targetmachine.jl") include("datalayout.jl") include("ir.jl") include("bitcode.jl") include("transform.jl") include("debuginfo.jl") include("dibuilder.jl") include("jitevents.jl") include("utils.jl") has_orc_v1() = v"8" <= LLVM.version() < v"12" if has_orc_v1() include("orc.jl") end has_orc_v2() = v"12" <= LLVM.version() if has_orc_v2() include("orcv2.jl") end include("interop.jl") include("deprecated.jl") ## initialization function __init__() # sanity checks @debug "Using LLVM $(version()) at $libllvm" if libllvm != Base.libllvm_path() @error "Mismatch between LLVM library used during precompilation ($libllvm) and the current run-time situation ($(Base.libllvm_path())). Please recompile the package." end if version() !== runtime_version() @error "Using a different version of LLVM ($(runtime_version())) than the one shipped with Julia ($(version())); this is unsupported" end _install_handlers() _install_handlers(GlobalContext()) end end
import Markdown const _unexported_public_api = Any[ ## ../docs/src/manual.md # Experimental channel_unordered, append_unordered!, ZipSource, GetIndex, SetIndex, Inject, ## ../docs/src/interface.md # Core interface for transducers Transducer, AbstractFilter, R_, inner, xform, start, next, complete, # Helpers for stateful transducers wrap, unwrap, wrapping, # Interface for reducibles __foldl__, getproperty(@__MODULE__, Symbol("@return_if_reduced")), getproperty(@__MODULE__, Symbol("@next")), ] const _explicit_internal_list = Any[ # Manually list some internal objects to avoid Documenter.jl's # "docstring potentially missing" warning: DefaultInit, ] is_internal(@nospecialize(t)) = t ∈ _explicit_internal_list || (parentmodule(t) === @__MODULE__) && t ∉ _unexported_public_api is_transducer_type(t) = t isa Type && t <: Transducer && t !== Transducer is_transducer_type(::typeof(Zip)) = true struct TransducerLister m::Module end TransducerLister() = TransducerLister(@__MODULE__) Transducer(tl::TransducerLister) = opcompose( Filter() do x t = getproperty(tl.m, x) is_transducer_type(t) end, Map(x -> Docs.Binding(tl.m, x)), ) (tl::TransducerLister)() = eduction(Transducer(tl), names(tl.m)) header_code(m::Markdown.MD) = if !isempty(m.content) header_code(m.content[1]) end header_code(c::Markdown.Code) = c header_code(::Any) = nothing first_paragraph(m::Markdown.MD) = if length(m.content) == 1 first_paragraph(m.content[1]) elseif length(m.content) > 1 first_paragraph(m.content[2]) end first_paragraph(p::Markdown.Paragraph) = p first_paragraph(::Any) = nothing hasdoc(m::Module, b::Docs.Binding) = haskey(Docs.meta(m), b) function Base.show(io::IO, ::MIME"text/markdown", tl::TransducerLister) println(io, "| **Transducer** | **Summary** |") println(io, "|:-- |:-- |") foreach(tl()) do binding hasdoc(tl.m, binding) || return d = Docs.doc(binding) h = header_code(d) if h === nothing shown = binding.var else shown, = split(h.code, "\n", limit=2) end p = first_paragraph(d) if p === nothing gist = "" else gist, = split(sprint(show, "text/markdown", Markdown.MD(p)), "\n", limit=2) end println(io, "| [`", shown, "`](@ref ", binding, ")", " | ", gist, " |") end end function Markdown.MD(tl::TransducerLister) io = IOBuffer() show(io, "text/markdown", tl) seek(io, 0) return Markdown.parse(io) end Base.show(io::IO, mime::MIME"text/plain", tl::TransducerLister) = _show(io, mime, tl) Base.show(io::IO, mime::MIME"text/html", tl::TransducerLister) = _show(io, mime, tl) _show(io, mime, tl) = show(io, mime, Markdown.MD(tl))
function get_bdt(obj::PreloadedTimeScales) return jcall(obj, "getBDT", BDTScale, ()) end function get_glonass(obj::PreloadedTimeScales) return jcall(obj, "getGLONASS", GLONASSScale, ()) end function get_gps(obj::PreloadedTimeScales) return jcall(obj, "getGPS", GPSScale, ()) end function get_gst(obj::PreloadedTimeScales) return jcall(obj, "getGST", GalileoScale, ()) end function get_irnss(obj::PreloadedTimeScales) return jcall(obj, "getIRNSS", IRNSSScale, ()) end function get_qzss(obj::PreloadedTimeScales) return jcall(obj, "getQZSS", QZSSScale, ()) end function get_tai(obj::PreloadedTimeScales) return jcall(obj, "getTAI", TAIScale, ()) end function get_tcb(obj::PreloadedTimeScales) return jcall(obj, "getTCB", TCBScale, ()) end function get_tcg(obj::PreloadedTimeScales) return jcall(obj, "getTCG", TCGScale, ()) end function get_tdb(obj::PreloadedTimeScales) return jcall(obj, "getTDB", TDBScale, ()) end function get_tt(obj::PreloadedTimeScales) return jcall(obj, "getTT", TTScale, ()) end function get_utc(obj::PreloadedTimeScales) return jcall(obj, "getUTC", UTCScale, ()) end
using BinaryBuilder, Pkg julia_version = v"1.6.0" name = "RDKit" version = v"2021.09.1pre" sources = [ GitSource("https://github.com/rdkit/rdkit.git", "d859a23c9e514e3266adeb7119ef337f87e7214b"), ] script = raw""" cd ${WORKSPACE}/srcdir/rdkit mkdir build cd build cmake \ -DCMAKE_BUILD_TYPE=Release \ -DRDK_INSTALL_INTREE=OFF \ -DRDK_BUILD_INCHI_SUPPORT=ON \ -DRDK_BUILD_PYTHON_WRAPPERS=OFF \ -DRDK_BUILD_CFFI_LIB=ON \ -DRDK_BUILD_FREETYPE_SUPPORT=ON \ -DRDK_BUILD_CPP_TESTS=OFF \ -RDK_BUILD_SLN_SUPPORT=OFF \ -DCMAKE_INSTALL_PREFIX=${prefix} \ -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \ -DCMAKE_PREFIX_PATH=${prefix} \ .. make -j${nproc} make install """ platforms = [ Platform("x86_64", "linux"), Platform("i686", "linux"), Platform("aarch64", "linux"), Platform("x86_64", "macos"), # Platform("aarch64", "macos"), ] platforms = expand_cxxstring_abis(platforms) products = [ LibraryProduct("librdkitcffi", :librdkitcffi), ] dependencies = [ Dependency("FreeType2_jll"), Dependency("boost_jll"), BuildDependency("Eigen_jll"), Dependency("Zlib_jll"), ] build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; preferred_gcc_version=v"5", julia_compat="^$(julia_version.major).$(julia_version.minor)")
const KeyMap = ( UP = ["W", "UP"], DOWN = ["S", "DOWN"], LEFT = ["A", "LEFT"], RIGHT = ["D", "RIGHT"], ) const Settings = ( framerate = 10, resolution = 20, colors = ( bg = "#111", snake = "#eee", gameover = "red" ) ) const Dir = ( UP = [ 0, -1], DOWN = [ 0, 1], LEFT = [-1, 0], RIGHT = [ 1, 0] )
using Flux using BSON using LinearAlgebra using Statistics using Random using Zygote: @adjoint using Zygote: @nograd using Zygote using ProgressBars using Distributions using Flux.Losses: ctc_loss Random.seed!(1) const TRAINDIR = "train" const EPOCHS = 100 const BATCH_SIZE = 1 const VAL_SIZE = 500 losses = [] forward = LSTM(39, 100) backward = LSTM(39, 100) output = Dense(200, 62) const NOISE = Normal(0, 0.6) function m(x) h0f = forward.(x) h0b = Flux.flip(backward, x) h0 = vcat.(h0f, h0b) o = output.(h0) return o end function loss(x, y) x = addNoise(x) Flux.reset!((forward, backward)) yhat = m(x) yhat = reduce(hcat, yhat) l = ctc_loss(yhat, y) addToGlobalLoss(l) return l end @nograd function addNoise(x) return [xI .+ Float32.(rand(NOISE, 39)) for xI in x] end function readData(dataDir) fnames = readdir(dataDir) shuffle!(MersenneTwister(4), fnames) Xs = [] Ys = [] for fname in fnames BSON.@load joinpath(dataDir, fname) x y x = [Float32.(x[i,:]) for i in 1:size(x,1)] push!(Xs, x) push!(Ys, collapse(argmax.(eachcol(y)))) end m = mean(reduce(vcat, Xs)) st = std(reduce(vcat, Xs)) for (i, x) in enumerate(Xs) Xs[i] = [(xI .- m) ./ st for xI in x] end return (Xs, Ys) end function lev(s, t) m = length(s) n = length(t) d = Array{Int}(zeros(m+1, n+1)) for i=2:(m+1) @inbounds d[i, 1] = i-1 end for j=2:(n+1) @inbounds d[1, j] = j-1 end for j=2:(n+1) for i=2:(m+1) @inbounds if s[i-1] == t[j-1] substitutionCost = 0 else substitutionCost = 1 end @inbounds d[i, j] = min(d[i-1, j] + 1, # Deletion d[i, j-1] + 1, # Insertion d[i-1, j-1] + substitutionCost) # Substitution end end @inbounds return d[m+1, n+1] end function collapse(seq) if isempty(seq) return seq end s = [seq[1]] for ch in seq[2:end] if ch != s[end] push!(s, ch) end end filter!(x -> x != 62, s) return s end # collapses all repetitions into a single item and # removes blanks; used because data set in its current # form has one-hot encoded phones for every time step # instead of just the phones contained in the sequence. # With a proper re-extraction of the data, this would not # be necessary. function alt_collapse(seq) if isempty(seq) return seq end s = [seq[1]] for ch in seq[2:end] if ch != s[end] push!(s, ch) end end filter!(!=(62), s) return s end """ per(x, y) Compute the phoneme error rate of the model for input `x` and target `y`. The phoneme error rate is defined as the Levenshtein distance between the labeling produced by running `x` through the model and the target labeling in `y`, all divided by the length of the target labeling in `y` """ function per(x, y) Flux.reset!((forward, backward)) yhat = m(x) yhat = reduce(hcat, yhat) yhat = mapslices(argmax, yhat, dims=1) |> vec |> alt_collapse # y = mapslices(argmax, y, dims=1) |> vec |> collapse return lev(yhat, y) / length(y) end function addToGlobalLoss(x) global losses push!(losses, x) end @adjoint function addToGlobalLoss(x) addToGlobalLoss(x) return nothing, () -> nothing end function main() println("Loading files") Xs, Ys = readData(TRAINDIR) data = collect(zip(Xs, Ys)) Xs = [d[1] for d in data] Ys = [d[2] for d in data] println("Beginning training") data = zip(Xs, Ys) |> collect valData = data[1:VAL_SIZE] data = data[VAL_SIZE+1:end] opt = Momentum(1e-4) for i in 1:EPOCHS global losses losses = [] println("Beginning epoch $i/$EPOCHS") Flux.train!(loss, Flux.params((forward, backward, output)), ProgressBar(data), opt) println("Calculating PER...") p = mean(map(x -> per(x...), valData)) println("PER: $(p*100)") println("Mean loss: ", mean(losses)) end end main()
export blasso, sfwsolver, momsossolver, solve! mutable struct BLASSO{T, FT, DT} y::Array{T, 1} φ::FT λ::Real domain::DT μ::Union{AbstractMeasureLike, Nothing} objvalue::Union{Real, Nothing} dualsol::Union{Vector{Real}, Nothing} mommat::Union{MomentMatrix, Nothing} end function blasso(y::Array{T, 1}, φ::Array{PT, 1}, λ::Real, domain::AbstractSemialgebraicSet) where {T, PT<:AbstractPolynomialLike} BLASSO(y, φ, λ, domain, nothing, nothing, nothing, nothing) end function blasso(y::Array{T, 1}, φ::Function, λ::Real, domain::Array{BT, 2}) where {T, BT} BLASSO(y, φ, λ, domain, nothing, nothing, nothing, nothing) end struct Solver name::String options::Dict end function sfwsolver(niter::Integer, gridsize::Integer) Solver("sfw", Dict("niter" => niter, "gridsize" => gridsize)) end function momsossolver(ϵ::Real, maxdeg::Union{Int, String}="defaut") Solver("momsos", Dict("ϵ" => ϵ, "maxdeg" => maxdeg)) end function solve!(blasso::BLASSO, solver::Solver) if solver.name == "momsos" momsos!(blasso, solver.options["ϵ"], solver.options["maxdeg"]) elseif solver.name == "sfw" sfw!(blasso, solver.options["niter"], solver.options["gridsize"]) else throw(ArgumentError(solver.name, "solver name must be either 'momsos' or 'sfw'")) end end
# Generic. include("compiler/utils.jl") include("compiler/loop_detection.jl") include("compiler/reaching.jl") include("compiler/address_blanket.jl") include("compiler/absint/absint.jl") # Kernel detection and dynamic addressing hints. include("compiler/hints.jl") # Trace types system include("compiler/absint/trace_types.jl") # Support error checker. include("compiler/static/support_checker.jl") # Partial evaluation/specialization include("compiler/specializer/diffs.jl") include("compiler/specializer/transforms.jl") include("compiler/specializer/interface.jl") # Automatic addressing converts stochastic functions into PPs include("compiler/automatic_addressing/automatic_addressing_transform.jl") # ------------ Documentation ------------ #
using Test using OrdinaryDiffEq, Calculus, ForwardDiff, FiniteDiff function f(du,u,p,t) du[1] = -p[1] du[2] = p[2] end for x in 0:0.001:5 called = false if x in [1.0, 2.0, 3.0, 4.0, 5.0] print("AD Ping $x") end function test_f(p) cb = ContinuousCallback((u,t,i) -> u[1], (integrator)->(called=true;integrator.p[2]=zero(integrator.p[2]))) prob = ODEProblem(f,eltype(p).([1.0,0.0]),eltype(p).((0.0,1.0)),copy(p)) integrator = init(prob,Tsit5(),abstol=1e-14,reltol=1e-14,callback=cb) step!(integrator) solve!(integrator).u[end] end p = [2.0, x] called = false findiff = Calculus.finite_difference_jacobian(test_f,p) @test called called = false fordiff = ForwardDiff.jacobian(test_f,p) @test called @test findiff ≈ fordiff end function f2(du,u,p,t) du[1] = -u[2] du[2] = p[2] end for x in 2.1:0.001:5 called = false if x in [3.0, 4.0, 5.0] print("AD Ping $x") end function test_f2(p) cb = ContinuousCallback((u,t,i) -> u[1], (integrator)->(called=true;integrator.p[2]=zero(integrator.p[2]))) prob = ODEProblem(f2,eltype(p).([1.0,0.0]),eltype(p).((0.0,1.0)),copy(p)) integrator = init(prob,Tsit5(),abstol=1e-12,reltol=1e-12,callback=cb) step!(integrator) solve!(integrator).u[end] end p = [2.0, x] findiff = Calculus.finite_difference_jacobian(test_f2,p) @test called called = false fordiff = ForwardDiff.jacobian(test_f2,p) @test called @test findiff ≈ fordiff end #= #x = 2.0 is an interesting case x = 2.0 function test_f2(p) cb = ContinuousCallback((u,t,i) -> u[1], (integrator)->(@show(x,integrator.t);called=true;integrator.p[2]=zero(integrator.p[2]))) prob = ODEProblem(f2,eltype(p).([1.0,0.0]),eltype(p).((0.0,1.0)),copy(p)) integrator = init(prob,Tsit5(),abstol=1e-12,reltol=1e-12,callback=cb) step!(integrator) solve!(integrator).u[end] end p = [2.0, x] findiff = Calculus.finite_difference_jacobian(test_f2,p) @test called called = false fordiff = ForwardDiff.jacobian(test_f2,p) @test called # At that value, it shouldn't be called, but a small perturbation will make it called, so finite difference is wrong! =# for x in 1.0:0.001:2.5 if x in [1.5, 2.0, 2.5] print("AD Ping $x") end function lotka_volterra(du,u,p,t) x, y = u α, β, δ, γ = p du[1] = dx = α*x - β*x*y du[2] = dy = -δ*y + γ*x*y end u0 = [1.0,1.0] tspan = (0.0,10.0) p = [x,1.0,3.0,1.0] prob = ODEProblem(lotka_volterra,u0,tspan,p) sol = solve(prob,Tsit5()) called=false function test_lotka(p) cb = ContinuousCallback((u,t,i) -> u[1]-2.5, (integrator)->(called=true;integrator.p[4]=1.5)) prob = ODEProblem(lotka_volterra,eltype(p).([1.0,1.0]),eltype(p).((0.0,10.0)),copy(p)) integrator = init(prob,Tsit5(),abstol=1e-12,reltol=1e-12,callback=cb) step!(integrator) solve!(integrator).u[end] end findiff = Calculus.finite_difference_jacobian(test_lotka,p) @test called called = false fordiff = ForwardDiff.jacobian(test_lotka,p) @test called @test findiff ≈ fordiff end # Gradients and Hessians function myobj(θ) f(u,p,t) = -θ[1]*u u0, _ = promote(10.0, θ[1]) prob = ODEProblem(f, u0, (0.0, 1.0)) sol = solve(prob, Tsit5()) diff = sol.u - 10*exp.(-sol.t) return diff'diff end ForwardDiff.gradient(myobj, [1.0]) ForwardDiff.hessian(myobj, [1.0]) function myobj2(θ) f(du,u,p,t) = (du[1]=-θ[1]*u[1]) u0, _ = promote(10.0, θ[1]) prob = ODEProblem(f, [u0], (0.0, 1.0)) sol = solve(prob, Tsit5()) diff = sol[:,1] .- 10 .*exp.(-sol.t) return diff'diff end ForwardDiff.gradient(myobj2, [1.0]) ForwardDiff.hessian(myobj2, [1.0]) function myobj3(θ) f(u,p,t) = -θ[1]*u u0, _ = promote(10.0, θ[1]) tspan_end, _ = promote(1.0, θ[1]) prob = ODEProblem(f, u0, (0.0, tspan_end)) sol = solve(prob, Tsit5()) diff = sol.u - 10*exp.(-sol.t) return diff'diff end ForwardDiff.gradient(myobj3, [1.0]) ForwardDiff.hessian(myobj3, [1.0]) function myobj4(θ) f(du,u,p,t) = (du[1] = -θ[1]*u[1]) u0, _ = promote(10.0, θ[1]) tspan_end, _ = promote(1.0, θ[1]) prob = ODEProblem(f, [u0], (0.0, tspan_end)) sol = solve(prob, Tsit5()) diff = sol[:,1] .- 10 .* exp.(-sol.t) return diff'diff end ForwardDiff.gradient(myobj4, [1.0]) ForwardDiff.hessian(myobj4, [1.0]) f1s = function (du,u,p,t) du[1] = p[2] * u[1] du[2] = p[3] * u[2] du[3] = p[4] * u[3] du[4] = p[5] * u[4] nothing end f2s = function (du,u,p,t) du[1] = p[1]*u[2] du[2] = p[1]*u[3] du[3] = p[1]*u[4] du[4] = p[1]*u[1] nothing end u0 = [3.4, 3.3, 3.2, 3.1] params = [0.002, -0.005, -0.004, -0.003, -0.002] tspan = (7.0, 84.0) times = collect(minimum(tspan):0.5:maximum(tspan)) prob = SplitODEProblem(f1s,f2s, u0, tspan, params) sol2 = solve(prob, KenCarp4(); dt=0.5, saveat=times) function difffunc(p) tmp_prob = remake(prob,p=p) vec(solve(tmp_prob,KenCarp4(),saveat=times)) end ForwardDiff.jacobian(difffunc,ones(5)) # https://github.com/SciML/OrdinaryDiffEq.jl/issues/1221 f_a = function (du, u, p, t) du[1] = -p[1]*u[1] + exp(-t) end of_a = p -> begin u0 = [0.0] tspan = (0.0, 5.0) prob = ODEProblem(f_a, u0, tspan, p) # sol = solve(prob, Tsit5()) # works # sol = solve(prob, Rodas5(autodiff=false)) # works sol = solve(prob, Rodas5(autodiff=true),abstol=1e-14,reltol=1e-14) # fails return sum(t -> abs2(t[1]), sol([1.0, 2.0, 3.0])) end @test !iszero(ForwardDiff.gradient(t -> of_a(t), [1.0])) @test ForwardDiff.gradient(t -> of_a(t), [1.0]) ≈ FiniteDiff.finite_difference_gradient(t -> of_a(t), [1.0]) rtol=1e-5 SOLVERS_FOR_AD = ( (BS3 , 1e-12), (Tsit5 , 1e-12), (KenCarp4 , 1e-11), (KenCarp47 , 1e-11), (KenCarp5 , 1e-11), (KenCarp58 , 1e-12), (TRBDF2 , 1e-07), (Rodas4 , 1e-12), (Rodas5 , 1e-12), (Rosenbrock23, 1e-10), (Rosenbrock32, 1e-11), (Vern6 , 1e-11), (Vern7 , 1e-11), (RadauIIA3 , 1e-04), (RadauIIA5 , 1e-12), ) @testset "$alg can handle ForwardDiff.Dual in u0 with rtol=$rtol when iip=$iip" for (alg, rtol) in SOLVERS_FOR_AD, iip in (true, false) if iip f = (du, u, p, t) -> du .= -0.5*u else f = (u, p, t) -> -0.5*u end g = u0 -> begin tspan = (0.0, 1.0) prob = ODEProblem( f, u0, tspan ) solve(prob, alg(), abstol=1e-14, reltol=1e-14)(last(tspan))[1] end @test ForwardDiff.gradient(g, [10.0])[1] ≈ exp(-0.5) rtol=rtol end @testset "$alg can handle ForwardDiff.Dual in t0 with rtol=$rtol when iip=$iip" for (alg, rtol) in SOLVERS_FOR_AD, iip in (true, false) if iip f = (du, u, p, t) -> du .= -0.5*u else f = (u, p, t) -> -0.5*u end _u0 = 10.0 g = t0 -> begin tspan = (t0, 1.0) u0 = typeof(t0)[_u0] prob = ODEProblem( f, u0, tspan ) solve(prob, alg(), abstol=1e-14, reltol=1e-14)(last(tspan))[1] end @test ForwardDiff.derivative(g, 0.0) ≈ _u0/2*exp(-0.5) rtol=rtol end
@userplot ImPlot @recipe function f(h::ImPlot) if length(h.args) != 1 || !(typeof(h.args[1]) <: AbstractArray) error("Image plots require an arugment that is a subtype of AbstractArray. Got: $(typeof(h.args))") end data = only(h.args) if !(typeof(data) <: AstroImage) data = AstroImage(only(h.args)) end T = eltype(data) if ndims(data) != 2 error("Image passed to `implot` must be two-dimensional. Got ndims(img)=$(ndims(data))") end wcsn = get(plotattributes, :wcsn, 1) # Show WCS coordinates if wcsticks is true or unspecified, and has at least one WCS axis present. showwcsticks = get(plotattributes, :wcsticks, true) && !all(==(""), wcs(data, wcsn).ctype) showwcstitle = get(plotattributes, :wcstitle, true) && length(refdims(data)) > 0 && !all(==(""), wcs(data, wcsn).ctype) minx = first(parent(dims(data,1))) maxx = last(parent(dims(data,1))) miny = first(parent(dims(data,2))) maxy = last(parent(dims(data,2))) extent = (minx-0.5, maxx+0.5, miny-0.5, maxy+0.5) if haskey(plotattributes, :xlims) extent = (plotattributes[:xlims]..., extent[3:4]...) end if haskey(plotattributes, :ylims) extent = (extent[1:2]..., plotattributes[:ylims]...) end if showwcsticks wcsg = WCSGrid(data, Float64.(extent), wcsn) gridspec = wcsgridspec(wcsg) end # Use package defaults if not user provided. clims --> _default_clims[] stretch --> _default_stretch[] cmap --> _default_cmap[] bias = get(plotattributes, :bias, 0.5) contrast = get(plotattributes, :contrast, 1) platescale = get(plotattributes, :platescale, 1) grid := false # In most cases, a grid framestyle is a nicer looking default for images # but the user can override. framestyle --> :box if T <: Colorant imgv = data else clims = plotattributes[:clims] stretch = plotattributes[:stretch] cmap = plotattributes[:cmap] if T <: Complex img = abs.(data) img["UNIT"] = "magnitude" else img = data end imgv = imview(img; clims, stretch, cmap, contrast, bias) end # Reduce large images using the same heuristic as Images.jl maxpixels = get(plotattributes, :maxpixels, 10^6) _length1(A::AbstractArray) = length(eachindex(A)) _length1(A) = length(A) while _length1(imgv) > maxpixels imgv = restrict(imgv) end # We have to do a lot of flipping to keep the orientation corect yflip := false xflip := false # Disable equal aspect ratios if the scales are totally different displayed_data_ratio = (extent[2]-extent[1])/(extent[4]-extent[3]) if displayed_data_ratio >= 7 aspect_ratio --> :none end # we have a wcs flag (from the image by default) so that users can skip over # plotting in physical coordinates. This is especially important # if the WCS headers are mallformed in some way. showgrid = get(plotattributes, :xgrid, true) && get(plotattributes, :ygrid, true) # Display a title giving our position along unplotted dimensions if length(refdims(imgv)) > 0 if showwcstitle refdimslabel = join(map(refdims(imgv)) do d # match dimension with the wcs axis number i = wcsax(imgv, d) ct = wcs(imgv, wcsn).ctype[i] label = ctype_label(ct, wcs(imgv, wcsn).radesys) if label == "NONE" label = name(d) end value = pix_to_world(imgv, [1,1]; wcsn, all=true, parent=true)[i] unit = wcs(imgv, wcsn).cunit[i] if ct == "STOKES" return _stokes_name(_stokes_symbol(value)) else return @sprintf("%s = %.5g %s", label, value, unit) end end, ", ") else refdimslabel = join(map(d->"$(name(d))= $(d[1])", refdims(imgv)), ", ") end title --> refdimslabel end # To ensure the physical axis tick labels are correct the axes must be # tight to the image xl = (first(dims(imgv,1))-0.5)*platescale, (last(dims(imgv,1))+0.5)*platescale yl = (first(dims(imgv,2))-0.5)*platescale, (last(dims(imgv,2))+0.5)*platescale ylims --> yl xlims --> xl subplot_i = 0 # Actual image series (RGB pixels by this point) @series begin subplot_i += 1 subplot := subplot_i colorbar := false aspect_ratio --> 1 # Note: if the axes are on unusual sides (e.g. y-axis at right, x-axis at top) # then these coordinates are not correct. They are only correct exactly # along the axis. # In astropy, the ticks are actually tilted to reflect this, though in general # the transformation from pixel to coordinates can be non-linear and curved. if showwcsticks xticks --> (gridspec.tickpos1x, wcslabels(wcs(imgv, wcsn), wcsax(imgv, dims(imgv,1)), gridspec.tickpos1w)) xguide --> ctype_label(wcs(imgv, wcsn).ctype[wcsax(imgv, dims(imgv,1))], wcs(imgv, wcsn).radesys) yticks --> (gridspec.tickpos2x, wcslabels(wcs(imgv, wcsn), wcsax(imgv, dims(imgv,2)), gridspec.tickpos2w)) yguide --> ctype_label(wcs(imgv, wcsn).ctype[wcsax(imgv, dims(imgv,2))], wcs(imgv, wcsn).radesys) end ax1 = collect(parent(dims(imgv,1))) .* platescale ax2 = collect(parent(dims(imgv,2))) .* platescale # Views of images are not currently supported by plotly() so we have to collect them. # ax1, ax2, view(parent(imgv), reverse(axes(imgv,1)),:) ax1, ax2, parent(imgv)[reverse(axes(imgv,1)),:] end # If wcs=true (default) and grid=true (not default), overplot a WCS # grid. if showgrid && showwcsticks # Plot the WCSGrid as a second series (actually just lines) @series begin subplot := 1 # Use a default grid color that shows up across more # color maps if !haskey(plotattributes, :xforeground_color_grid) && !haskey(plotattributes, :yforeground_color_grid) gridcolor --> :lightgray end wcsg, gridspec end end # Disable the colorbar. # Plots.jl does not give us sufficient control to make sure the range and ticks # are correct after applying a non-linear stretch. # We attempt to make our own colorbar using a second plot. showcolorbar = !(T <: Colorant) && get(plotattributes, :colorbar, true) != :none if T <: Complex layout := @layout [ imgmag{0.5h} imgangle{0.5h} ] end if showcolorbar if T <: Complex layout := @layout [ imgmag{0.95w, 0.5h} colorbar{0.5h} imgangle{0.95w, 0.5h} colorbarangle{0.5h} ] else layout := @layout [ img{0.95w} colorbar ] end colorbar_title = get(plotattributes, :colorbar_title, "") if !haskey(plotattributes, :colorbar_title) if haskey(header(img), "UNIT") colorbar_title = string(img[:UNIT]) elseif haskey(header(img), "BUNIT") colorbar_title = string(img[:BUNIT]) end end subplot_i += 1 @series begin subplot := subplot_i aspect_ratio := :none colorbar := false cbimg, cbticks = imview_colorbar(img; clims, stretch, cmap, contrast, bias) xticks := [] ymirror := true yticks := cbticks yguide := colorbar_title xguide := "" xlims := Tuple(axes(cbimg, 2)) ylims := Tuple(axes(cbimg, 2)) title := "" # Views of images are not currently supported by plotly so we have to collect them # view(cbimg, reverse(axes(cbimg,1)),:) cbimg[reverse(axes(cbimg,1)),:] end end # TODO: refactor to reduce duplication if T <: Complex img = angle.(data) img["UNIT"] = "angle (rad)" imgv = imview(img, clims=(-1pi, 1pi),stretch=identity, cmap=:cyclic_mygbm_30_95_c78_n256_s25) @series begin subplot_i += 1 subplot := subplot_i colorbar := false title := "" aspect_ratio --> 1 # Note: if the axes are on unusual sides (e.g. y-axis at right, x-axis at top) # then these coordinates are not correct. They are only correct exactly # along the axis. # In astropy, the ticks are actually tilted to reflect this, though in general # the transformation from pixel to coordinates can be non-linear and curved. if showwcsticks xticks --> (gridspec.tickpos1x, wcslabels(wcs(imgv, wcsn), wcsax(imgv, dims(imgv,1)), gridspec.tickpos1w)) xguide --> ctype_label(wcs(imgv, wcsn).ctype[wcsax(imgv, dims(imgv,1))], wcs(imgv, wcsn).radesys) yticks --> (gridspec.tickpos2x, wcslabels(wcs(imgv, wcsn), wcsax(imgv, dims(imgv,2)), gridspec.tickpos2w)) yguide --> ctype_label(wcs(imgv, wcsn).ctype[wcsax(imgv, dims(imgv,2))], wcs(imgv, wcsn).radesys) end ax1 = collect(parent(dims(imgv,1))) .* platescale ax2 = collect(parent(dims(imgv,2))) .* platescale # Views of images are not currently supported by plotly() so we have to collect them. # ax1, ax2, view(parent(imgv), reverse(axes(imgv,1)),:) ax1, ax2, parent(imgv)[reverse(axes(imgv,1)),:] end if showcolorbar colorbar_title = get(plotattributes, :colorbar_title, "") if !haskey(plotattributes, :colorbar_title) && haskey(header(img), "UNIT") colorbar_title = string(img[:UNIT]) end @series begin subplot_i += 1 subplot := subplot_i aspect_ratio := :none colorbar := false cbimg, _ = imview_colorbar(img; stretch=identity, clims=(-pi, pi), cmap=:cyclic_mygbm_30_95_c78_n256_s25) xticks := [] ymirror := true ax = axes(cbimg,1) yticks := ([first(ax), mean(ax), last(ax)], ["-π", "0", "π"]) yguide := colorbar_title xguide := "" xlims := Tuple(axes(cbimg, 2)) ylims := Tuple(axes(cbimg, 2)) title := "" view(cbimg, reverse(axes(cbimg,1)),:) end end end return end """ implot( img::AbstractArray; clims=Percent(99.5), stretch=identity, cmap=:magma, bias=0.5, contrast=1, wcsticks=true, grid=true, platescale=1 ) Create a read only view of an array or AstroImageMat mapping its data values to an array of Colors. Equivalent to: implot( imview( img::AbstractArray; clims=Percent(99.5), stretch=identity, cmap=:magma, bias=0.5, contrast=1, ), wcsn=1, wcsticks=true, wcstitle=true, grid=true, platescale=1 ) ### Image Rendering See `imview` for how data is mapped to RGBA pixel values. ### WCS & Image Coordinates If provided with an AstroImage that has WCS headers set, the tick marks and plot grid are calculated using WCS.jl. By default, use the first WCS coordinate system. The underlying pixel coordinates are those returned by `dims(img)` multiplied by `platescale`. This allows you to overplot lines, regions, etc. using pixel coordinates. If you wish to compute the pixel coordinate of a point in world coordinates, see `world_to_pix`. * `wcsn` (default `1`) select which WCS transform in the headers to use for ticks & grid * `wcsticks` (default `true` if WCS headers present) display ticks and labels, and title using world coordinates * `wcstitle` (default `true` if WCS headers present and `length(refdims(img))>0`). When slicing a cube, display the location along unseen axes in world coordinates instead of pixel coordinates. * `grid` (default `true`) show a grid over the plot. Uses WCS coordinates if `wcsticks` is true, otherwise pixel coordinates multiplied by `platescale`. * `platescale` (default `1`). Scales the underlying pixel coordinates to ease overplotting, etc. If `wcsticks` is false, the displayed pixel coordinates are also scaled. ### Defaults The default values of `clims`, `stretch`, and `cmap` are `extrema`, `identity`, and `nothing` respectively. You may alter these defaults using `AstroImages.set_clims!`, `AstroImages.set_stretch!`, and `AstroImages.set_cmap!`. """ implot struct WCSGrid img::AstroImage extent::NTuple{4,Float64} wcsn::Int end """ wcsticks(img, axnum) Generate nice tick labels for an AstroImageMat along axis `axnum` Returns a vector of pixel positions and a vector of strings. Example: plot(img, xticks=wcsticks(WCSGrid(img), 1), yticks=wcsticks(WCSGrid(img), 2)) """ function wcsticks(wcsg::WCSGrid, axnum, gs = wcsgridspec(wcsg)) tickposx = axnum == 1 ? gs.tickpos1x : gs.tickpos2x tickposw = axnum == 1 ? gs.tickpos1w : gs.tickpos2w return tickposx, wcslabels( wcs(wcsg.img, wcsg.wcsn), axnum, tickposw ) end # Function to generate nice string coordinate labels given a WCSTransform, axis number, # and a vector of tick positions in world coordinates. # This is used for labelling ticks and for annotating grid lines. function wcslabels(w::WCSTransform, axnum, tickposw) if length(tickposw) == 0 return String[] end # Select a unit converter (e.g. 12.12 -> (a,b,c,d)) and list of units if w.cunit[axnum] == "deg" if startswith(uppercase(w.ctype[axnum]), "RA") converter = deg2hms units = hms_units else converter = deg2dmsmμ units = dmsmμ_units end else converter = x->(x,) units = ("",) end # Format inital ticklabel ticklabels = fill("", length(tickposw)) # We only include the part of the label that has changed since the last time. # Split up coordinates into e.g. sexagesimal parts = map(tickposw) do w vals = converter(w) return vals end # Start with something impossible of the same size: last_coord = Inf .* converter(first(tickposw)) zero_coords_i = maximum(map(parts) do vals changing_coord_i = findfirst(vals .!= last_coord) if isnothing(changing_coord_i) changing_coord_i = 1 end last_coord = vals return changing_coord_i end) # Loop through using only the relevant part of the label # Start with something impossible of the same size: last_coord = Inf .* converter(first(tickposw)) for (i,vals) in enumerate(parts) changing_coord_i = findfirst(vals .!= last_coord) if isnothing(changing_coord_i) changing_coord_i = 1 end # Don't display just e.g. 00" when we should display 50'00" if changing_coord_i > 1 && vals[changing_coord_i] == 0 changing_coord_i = changing_coord_i -1 end val_unit_zip = zip(vals[changing_coord_i:zero_coords_i],units[changing_coord_i:zero_coords_i]) ticklabels[i] = mapreduce(*, enumerate(val_unit_zip)) do (coord_i,(val,unit)) # If the last coordinate we print if the last coordinate we have available, # display it with decimal places if coord_i + changing_coord_i - 1== length(vals) str = @sprintf("%.2f", val) else str = @sprintf("%02d", val) end if length(str) > 0 return str * unit else return str end end last_coord = vals end return ticklabels end # Extended form of deg2dms that further returns mas, microas. function deg2dmsmμ(deg) d,m,s = deg2dms(deg) s_f = floor(s) mas = (s - s_f)*1e3 mas_f = floor(mas) μas = (mas - mas_f)*1e3 return (d,m,s_f,mas_f,μas) end const dmsmμ_units = [ "°", "'", "\"", "mas", "μas", ] const hms_units = [ "ʰ", "ᵐ", "ˢ", ] function ctype_label(ctype,radesys) if length(ctype) == 0 return radesys elseif startswith(ctype, "RA") return "Right Ascension ($(radesys))" elseif startswith(ctype, "GLON") return "Galactic Longitude" elseif startswith(ctype, "TLON") return "ITRS" elseif startswith(ctype, "DEC") return "Declination ($(radesys))" elseif startswith(ctype, "GLAT") return "Galactic Latitude" # elseif startswith(ctype, "TLAT") elseif ctype == "STOKES" return "Polarization" else return ctype end end """ WCSGrid(img::AstroImageMat, ax=(1,2), coords=(first(axes(img,ax[1])),first(axes(img,ax[2])))) Given an AstroImageMat, return information necessary to plot WCS gridlines in physical coordinates against the image's pixel coordinates. This function has to work on both plotted axes at once to handle rotation and general curvature of the WCS grid projected on the image coordinates. """ function WCSGrid(img::AstroImageMat, wcsn=1) minx = first(dims(img,2)) maxx = last(dims(img,2)) miny = first(dims(img,1)) maxy = last(dims(img,1)) extent = (minx-0.5, maxx+0.5, miny-0.5, maxy+0.5) @show extent return WCSGrid(img, extent, wcsn) end # Recipe for a WCSGrid with lines, optional ticks (on by default), # and optional grid labels (off by defaut). # The AstroImageMat plotrecipe uses this recipe for grid lines if `grid=true`. @recipe function f(wcsg::WCSGrid, gridspec=wcsgridspec(wcsg)) label --> "" xs, ys = wcsgridlines(gridspec) if haskey(plotattributes, :foreground_color_grid) color --> plotattributes[:foreground_color_grid] elseif haskey(plotattributes, :foreground_color) color --> plotattributes[:foreground_color] else color --> :black end if haskey(plotattributes, :foreground_color_text) textcolor = plotattributes[:foreground_color_text] else textcolor = plotattributes[:color] end annotate = haskey(plotattributes, :gridlabels) && plotattributes[:gridlabels] xguide --> ctype_label(wcs(wcsg.img, wcsg.wcsn).ctype[wcsax(wcsg.img, dims(wcsg.img,1))], wcs(wcsg.img, wcsg.wcsn).radesys) yguide --> ctype_label(wcs(wcsg.img, wcsg.wcsn).ctype[wcsax(wcsg.img, dims(wcsg.img,2))], wcs(wcsg.img, wcsg.wcsn).radesys) xlims --> wcsg.extent[1], wcsg.extent[2] ylims --> wcsg.extent[3], wcsg.extent[4] grid := false tickdirection := :none xticks --> wcsticks(wcsg, 1, gridspec) yticks --> wcsticks(wcsg, 2, gridspec) @series xs, ys # We can optionally annotate the grid with their coordinates. # These come after the grid lines so they appear overtop. if annotate @series begin # TODO: why is this reverse necessary? rotations = reverse(rad2deg.(gridspec.annotations1θ)) ticklabels = wcslabels(wcs(wcsg.img), 1, gridspec.annotations1w) seriestype := :line linewidth := 0 # TODO: we need to use requires to load in Plots for the necessary text control. Future versions of RecipesBase might fix this. series_annotations := [ Main.Plots.text(" $l", :right, :bottom, textcolor, 8, rotation=(-95 <= r <= 95) ? r : r+180) for (l, r) in zip(ticklabels, rotations) ] gridspec.annotations1x, gridspec.annotations1y end @series begin rotations = rad2deg.(gridspec.annotations2θ) ticklabels = wcslabels(wcs(wcsg.img), 2, gridspec.annotations2w) seriestype := :line linewidth := 0 series_annotations := [ Main.Plots.text(" $l", :right, :bottom, textcolor, 8, rotation=(-95 <= r <= 95) ? r : r+180) for (l, r) in zip(ticklabels, rotations) ] gridspec.annotations2x, gridspec.annotations2y end end return end # Helper: true if all elements in vector are equal to each other. allequal(itr) = all(==(first(itr)), itr) # This function is responsible for actually laying out grid lines for a WCSGrid, # ensuring they don't exceed the plot bounds, finding where they intersect the axes, # and picking tick locations at the appropriate intersections with the left and # bottom axes. function wcsgridspec(wsg::WCSGrid) # Most of the complexity of this function is making sure everything # generalizes to N different, possiby skewed axes, where a change in # the opposite coordinate or even an unplotted coordinate affects # the grid. # x and y denote pixel coordinates (along `ax`), u and v are world coordinates roughly along same. minx, maxx, miny, maxy = wsg.extent # Find the extent of this slice in world coordinates posxy = [ minx minx maxx maxx miny maxy miny maxy ] posuv = pix_to_world(wsg.img, posxy; wsg.wcsn, parent=true) (minu, maxu), (minv, maxv) = extrema(posuv, dims=2) # In general, grid can be curved when plotted back against the image, # so we will need to sample multiple points along the grid. # TODO: find a good heuristic for this based on the curvature. N_points = 50 urange = range(minu, maxu, length=N_points) vrange = range(minv, maxv, length=N_points) # Find nice grid spacings using PlotUtils.optimize_ticks # These heuristics can probably be improved # TODO: this does not handle coordinates that wrap around Q=[(1.0,1.0), (3.0, 0.8), (2.0, 0.7), (5.0, 0.5)] k_min = 3 k_ideal = 5 k_max = 10 tickpos2x = Float64[] tickpos2w = Float64[] gridlinesxy2 = NTuple{2,Vector{Float64}}[] # Not all grid lines will intersect the x & y axes nicely. # If we don't get enough valid tick marks (at least 2) loop again # requesting more locations up to three times. local tickposv j = 5 while length(tickpos2x) < 2 && j > 0 k_min += 2 k_ideal += 2 k_max += 2 j -= 1 tickposv = optimize_ticks(6minv, 6maxv; Q, k_min, k_ideal, k_max)[1]./6 empty!(tickpos2x) empty!(tickpos2w) empty!(gridlinesxy2) for tickv in tickposv # Make sure we handle unplotted slices correctly. griduv = repeat(posuv[:,1], 1, N_points) griduv[1,:] .= urange griduv[2,:] .= tickv posxy = world_to_pix(wsg.img, griduv; wsg.wcsn, parent=true) # Now that we have the grid in pixel coordinates, # if we find out where the grid intersects the axes we can put # the labels in the correct spot # We can use these masks to determine where, and in what direction # the gridlines leave the plot extent in_horz_ax = minx .<= posxy[1,:] .<= maxx in_vert_ax = miny .<= posxy[2,:] .<= maxy in_axes = in_horz_ax .& in_vert_ax if count(in_axes) < 2 continue elseif all(in_axes) point_entered = [ posxy[1,begin] posxy[2,begin] ] point_exitted = [ posxy[1,end] posxy[2,end] ] elseif allequal(posxy[1,findfirst(in_axes):findlast(in_axes)]) point_entered = [ posxy[1,max(begin,findfirst(in_axes)-1)] # posxy[2,max(begin,findfirst(in_axes)-1)] miny ] point_exitted = [ posxy[1,min(end,findlast(in_axes)+1)] # posxy[2,min(end,findlast(in_axes)+1)] maxy ] # Vertical grid lines elseif allequal(posxy[2,findfirst(in_axes):findlast(in_axes)]) point_entered = [ minx #posxy[1,max(begin,findfirst(in_axes)-1)] posxy[2,max(begin,findfirst(in_axes)-1)] ] point_exitted = [ maxx #posxy[1,min(end,findlast(in_axes)+1)] posxy[2,min(end,findlast(in_axes)+1)] ] else # Use the masks to pick an x,y point inside the axes and an # x,y point outside the axes. i = findfirst(in_axes) x1 = posxy[1,i] y1 = posxy[2,i] x2 = posxy[1,i+1] y2 = posxy[2,i+1] if x2-x1 ≈ 0 @warn "undef slope" end # Fit a line where we cross the axis m1 = (y2-y1)/(x2-x1) b1 = y1-m1*x1 # If the line enters via the vertical axes... if findfirst(in_vert_ax) <= findfirst(in_horz_ax) # Then we simply evaluate it at that axis x = abs(x1-maxx) < abs(x1-minx) ? maxx : minx x = clamp(x,minx,maxx) y = m1*x+b1 else # We must find where it enters the plot from # bottom or top x = abs(y1-maxy) < abs(y1-miny) ? (maxy-b1)/m1 : (miny-b1)/m1 x = clamp(x,minx,maxx) y = m1*x+b1 end # From here, do a linear fit to find the intersection with the axis. point_entered = [ x y ] # Use the masks to pick an x,y point inside the axes and an # x,y point outside the axes. i = findlast(in_axes) x1 = posxy[1,i-1] y1 = posxy[2,i-1] x2 = posxy[1,i] y2 = posxy[2,i] if x2-x1 ≈ 0 @warn "undef slope" end # Fit a line where we cross the axis m2 = (y2-y1)/(x2-x1) b2 = y2-m2*x2 if findlast(in_vert_ax) > findlast(in_horz_ax) # Then we simply evaluate it at that axis x = abs(x1-maxx) < abs(x1-minx) ? maxx : minx x = clamp(x,minx,maxx) y = m2*x+b2 else # We must find where it enters the plot from # bottom or top x = abs(y1-maxy) < abs(y1-miny) ? (maxy-b2)/m2 : (miny-b2)/m2 x = clamp(x,minx,maxx) y = m2*x+b2 end # From here, do a linear fit to find the intersection with the axis. point_exitted = [ x y ] end if point_entered[1] == minx push!(tickpos2x, point_entered[2]) push!(tickpos2w, tickv) end if point_exitted[1] == minx push!(tickpos2x, point_exitted[2]) push!(tickpos2w, tickv) end posxy_neat = [point_entered posxy[[1,2],in_axes] point_exitted] # posxy_neat = posxy # TODO: do unplotted other axes also need a fit? gridlinexy = ( posxy_neat[1,:], posxy_neat[2,:] ) push!(gridlinesxy2, gridlinexy) end end # Then do the opposite coordinate k_min = 3 k_ideal = 5 k_max = 10 tickpos1x = Float64[] tickpos1w = Float64[] gridlinesxy1 = NTuple{2,Vector{Float64}}[] # Not all grid lines will intersect the x & y axes nicely. # If we don't get enough valid tick marks (at least 2) loop again # requesting more locations up to three times. local tickposu j = 5 while length(tickpos1x) < 2 && j > 0 k_min += 2 k_ideal += 2 k_max += 2 j -= 1 tickposu = optimize_ticks(6minu, 6maxu; Q, k_min, k_ideal, k_max)[1]./6 empty!(tickpos1x) empty!(tickpos1w) empty!(gridlinesxy1) for ticku in tickposu # Make sure we handle unplotted slices correctly. griduv = repeat(posuv[:,1], 1, N_points) griduv[1,:] .= ticku griduv[2,:] .= vrange posxy = world_to_pix(wsg.img, griduv; wsg.wcsn, parent=true) # Now that we have the grid in pixel coordinates, # if we find out where the grid intersects the axes we can put # the labels in the correct spot # We can use these masks to determine where, and in what direction # the gridlines leave the plot extent in_horz_ax = minx .<= posxy[1,:] .<= maxx in_vert_ax = miny .<= posxy[2,:] .<= maxy in_axes = in_horz_ax .& in_vert_ax if count(in_axes) < 2 continue elseif all(in_axes) point_entered = [ posxy[1,begin] posxy[2,begin] ] point_exitted = [ posxy[1,end] posxy[2,end] ] # Horizontal grid lines elseif allequal(posxy[1,findfirst(in_axes):findlast(in_axes)]) point_entered = [ posxy[1,findfirst(in_axes)] miny ] point_exitted = [ posxy[1,findlast(in_axes)] maxy ] # push!(tickpos1x, posxy[1,findfirst(in_axes)]) # push!(tickpos1w, ticku) # Vertical grid lines elseif allequal(posxy[2,findfirst(in_axes):findlast(in_axes)]) point_entered = [ minx posxy[2,findfirst(in_axes)] ] point_exitted = [ maxx posxy[2,findfirst(in_axes)] ] else # Use the masks to pick an x,y point inside the axes and an # x,y point outside the axes. i = findfirst(in_axes) x1 = posxy[1,i] y1 = posxy[2,i] x2 = posxy[1,i+1] y2 = posxy[2,i+1] if x2-x1 ≈ 0 @warn "undef slope" end # Fit a line where we cross the axis m1 = (y2-y1)/(x2-x1) b1 = y1-m1*x1 # If the line enters via the vertical axes... if findfirst(in_vert_ax) < findfirst(in_horz_ax) # Then we simply evaluate it at that axis x = abs(x1-maxx) < abs(x1-minx) ? maxx : minx x = clamp(x,minx,maxx) y = m1*x+b1 else # We must find where it enters the plot from # bottom or top x = abs(y1-maxy) < abs(y1-miny) ? (maxy-b1)/m1 : (miny-b1)/m1 x = clamp(x,minx,maxx) y = m1*x+b1 end # From here, do a linear fit to find the intersection with the axis. point_entered = [ x y ] # Use the masks to pick an x,y point inside the axes and an # x,y point outside the axes. i = findlast(in_axes) x1 = posxy[1,i-1] y1 = posxy[2,i-1] x2 = posxy[1,i] y2 = posxy[2,i] if x2-x1 ≈ 0 @warn "undef slope" end # Fit a line where we cross the axis m2 = (y2-y1)/(x2-x1) b2 = y2-m2*x2 if findlast(in_vert_ax) > findlast(in_horz_ax) # Then we simply evaluate it at that axis x = abs(x1-maxx) < abs(x1-minx) ? maxx : minx x = clamp(x,minx,maxx) y = m2*x+b2 else # We must find where it enters the plot from # bottom or top x = abs(y1-maxy) < abs(y1-miny) ? (maxy-b2)/m2 : (miny-b2)/m2 x = clamp(x,minx,maxx) y = m2*x+b2 end # From here, do a linear fit to find the intersection with the axis. point_exitted = [ x y ] end posxy_neat = [point_entered posxy[[1,2],in_axes] point_exitted] # TODO: do unplotted other axes also need a fit? if point_entered[2] == miny push!(tickpos1x, point_entered[1]) push!(tickpos1w, ticku) end if point_exitted[2] == miny push!(tickpos1x, point_exitted[1]) push!(tickpos1w, ticku) end gridlinexy = ( posxy_neat[1,:], posxy_neat[2,:] ) push!(gridlinesxy1, gridlinexy) end end # Grid annotations are simpler: annotations1w = Float64[] annotations1x = Float64[] annotations1y = Float64[] annotations1θ = Float64[] for ticku in tickposu # Make sure we handle unplotted slices correctly. griduv = posuv[:,1] griduv[1] = ticku griduv[2] = mean(vrange) posxy = world_to_pix(wsg.img, griduv; wsg.wcsn, parent=true) if !(minx < posxy[1] < maxx) || !(miny < posxy[2] < maxy) continue end push!(annotations1w, ticku) push!(annotations1x, posxy[1]) push!(annotations1y, posxy[2]) # Now find slope (TODO: stepsize) # griduv[ax[2]] -= 1 griduv[2] += 0.1step(vrange) posxy2 = world_to_pix(wsg.img, griduv; wsg.wcsn, parent=true) θ = atan( posxy2[2] - posxy[2], posxy2[1] - posxy[1], ) push!(annotations1θ, θ) end annotations2w = Float64[] annotations2x = Float64[] annotations2y = Float64[] annotations2θ = Float64[] for tickv in tickposv # Make sure we handle unplotted slices correctly. griduv = posuv[:,1] griduv[1] = mean(urange) griduv[2] = tickv posxy = world_to_pix(wsg.img, griduv; wsg.wcsn, parent=true) if !(minx < posxy[1] < maxx) || !(miny < posxy[2] < maxy) continue end push!(annotations2w, tickv) push!(annotations2x, posxy[1]) push!(annotations2y, posxy[2]) griduv[1] += 0.1step(urange) posxy2 = world_to_pix(wsg.img, griduv; wsg.wcsn, parent=true) θ = atan( posxy2[2] - posxy[2], posxy2[1] - posxy[1], ) push!(annotations2θ, θ) end return (; gridlinesxy1, gridlinesxy2, tickpos1x, tickpos1w, tickpos2x, tickpos2w, annotations1w, annotations1x, annotations1y, annotations1θ, annotations2w, annotations2x, annotations2y, annotations2θ, ) end # From a WCSGrid, return just the grid lines as a single pair of x & y coordinates # suitable for plotting. function wcsgridlines(wcsg::WCSGrid) return wcsgridlines(wcsgridspec(wcsg)) end function wcsgridlines(gridspec::NamedTuple) # Unroll grid lines into a single series separated by NaNs xs1 = mapreduce(vcat, gridspec.gridlinesxy1, init=Float64[]) do gridline return vcat(gridline[1], NaN) end ys1 = mapreduce(vcat, gridspec.gridlinesxy1, init=Float64[]) do gridline return vcat(gridline[2], NaN) end xs2 = mapreduce(vcat, gridspec.gridlinesxy2, init=Float64[]) do gridline return vcat(gridline[1], NaN) end ys2 = mapreduce(vcat, gridspec.gridlinesxy2, init=Float64[]) do gridline return vcat(gridline[2], NaN) end xs = vcat(xs1, NaN, xs2) ys = vcat(ys1, NaN, ys2) return xs, ys end @userplot PolQuiver @recipe function f(h::PolQuiver) cube = only(h.args) bins = get(plotattributes, :bins, 4) ticklen = get(plotattributes, :ticklen, nothing) minpol = get(plotattributes, :minpol, 0.1) i = cube[Pol=At(:I)] q = cube[Pol=At(:Q)] u = cube[Pol=At(:U)] polinten = @. sqrt(q^2 + u^2) linpolfrac = polinten ./ i binratio=1/bins xs = imresize([x for x in dims(cube,1), y in dims(cube,2)], ratio=binratio) ys = imresize([y for x in dims(cube,1), y in dims(cube,2)], ratio=binratio) qx = imresize(q, ratio=binratio) qy = imresize(u, ratio=binratio) qlinpolfrac = imresize(linpolfrac, ratio=binratio) qpolintenr = imresize(polinten, ratio=binratio) # We want the longest ticks to be around 1 bin long by default. qmaxlen = quantile(filter(isfinite,qpolintenr), 0.98) if isnothing(ticklen) a = bins / qmaxlen else a = ticklen / qmaxlen end # Only show arrows where the data is finite, and more than a couple pixels # long. mask = (isfinite.(qpolintenr)) .& (qpolintenr .>= minpol.*qmaxlen) pointstmp = map(xs[mask],ys[mask],qx[mask],qy[mask]) do x,y,qxi,qyi return ([x, x+a*qxi, NaN], [y, y+a*qyi, NaN]) end xs = reduce(vcat, getindex.(pointstmp, 1)) ys = reduce(vcat, getindex.(pointstmp, 2)) colors = qlinpolfrac[mask] if !isnothing(colors) line_z := repeat(colors, inner=3) end label --> "" color --> :turbo framestyle --> :box aspect_ratio --> 1 linewidth --> 1.5 colorbar --> true colorbar_title --> "Linear polarization fraction" xl = first(dims(i,2)), last(dims(i,2)) yl = first(dims(i,1)), last(dims(i,1)) ylims --> yl xlims --> xl @series begin xs, ys end end """ polquiver(polqube::AstroImage) Given a data cube (of at least 2 spatial dimensions, plus a polarization axis), plot a vector field of polarization data. The tick length represents the polarization intensity, sqrt(q^2 + u^2), and the color represents the linear polarization fraction, sqrt(q^2 + u^2) / i. There are several ways you can adjust the appearance of the plot using keyword arguments: * `bins` (default = 1) By how much should we bin down the polarization data before drawing the ticks? This reduced clutter from higher resolution datasets. Can be fractional. * `ticklen` (default = bins) How long the 98th percentile arrow should be. By default, 1 bin long. Make this larger to draw longer arrows. * `color` (default = :turbo) What colorscheme should be used for linear polarization fraction. * `minpol` (default = 0.2) Hides arrows that are shorter than `minpol` times the 98th percentile arrow to make a cleaner image. Set to 0 to display all data. Use `implot` and `polquiver!` to overplot polarization data over an image. """ polquiver
# COV_EXCL_START using .CUDA, Cassette cuda_is_loaded = true #! format: off const cudafuns = ( :cos, :cospi, :sin, :sinpi, :tan, :acos, :asin, :atan, :cosh, :sinh, :tanh, :acosh, :asinh, :atanh, :log, :log10, :log1p, :log2, :exp, :exp2, :exp10, :expm1, :ldexp, :abs, :sqrt, :cbrt, :ceil, :floor, ) #! format: on Cassette.@context CeedCudaContext @inline function Cassette.overdub(::CeedCudaContext, ::typeof(Core.kwfunc), f) return Core.kwfunc(f) end @inline function Cassette.overdub(::CeedCudaContext, ::typeof(Core.apply_type), args...) return Core.apply_type(args...) end @inline function Cassette.overdub( ::CeedCudaContext, ::typeof(StaticArrays.Size), x::Type{<:AbstractArray{<:Any,N}}, ) where {N} return StaticArrays.Size(x) end for f in cudafuns @eval @inline function Cassette.overdub( ::CeedCudaContext, ::typeof(Base.$f), x::Union{Float32,Float64}, ) return CUDA.$f(x) end end function setarray!(v::CeedVector, mtype::MemType, cmode::CopyMode, arr::CuArray) ptr = Ptr{CeedScalar}(UInt64(pointer(arr))) C.CeedVectorSetArray(v[], mtype, cmode, ptr) if cmode == USE_POINTER v.arr = arr end end struct FieldsCuda inputs::NTuple{16,Int} outputs::NTuple{16,Int} end function generate_kernel(qf_name, kf, dims_in, dims_out) ninputs = length(dims_in) noutputs = length(dims_out) input_sz = prod.(dims_in) output_sz = prod.(dims_out) f_ins = [Symbol("rqi$i") for i = 1:ninputs] f_outs = [Symbol("rqo$i") for i = 1:noutputs] args = Vector{Union{Symbol,Expr}}(undef, ninputs + noutputs) def_ins = Vector{Expr}(undef, ninputs) f_ins_j = Vector{Union{Symbol,Expr}}(undef, ninputs) for i = 1:ninputs if length(dims_in[i]) == 0 def_ins[i] = :(local $(f_ins[i])) f_ins_j[i] = f_ins[i] args[i] = f_ins[i] else def_ins[i] = :($(f_ins[i]) = LibCEED.MArray{Tuple{$(dims_in[i]...)},Float64}(undef)) f_ins_j[i] = :($(f_ins[i])[j]) args[i] = :(LibCEED.SArray{Tuple{$(dims_in[i]...)},Float64}($(f_ins[i]))) end end for i = 1:noutputs args[ninputs+i] = f_outs[i] end def_outs = [ :($(f_outs[i]) = LibCEED.MArray{Tuple{$(dims_out[i]...)},Float64}(undef)) for i = 1:noutputs ] device_ptr_type = Core.LLVMPtr{CeedScalar,LibCEED.AS.Global} read_quads_in = [ :( for j = 1:$(input_sz[i]) $(f_ins_j[i]) = unsafe_load( reinterpret($device_ptr_type, fields.inputs[$i]), q + (j - 1)*Q, a, ) end ) for i = 1:ninputs ] write_quads_out = [ :( for j = 1:$(output_sz[i]) unsafe_store!( reinterpret($device_ptr_type, fields.outputs[$i]), $(f_outs[i])[j], q + (j - 1)*Q, a, ) end ) for i = 1:noutputs ] qf = gensym(qf_name) quote function $qf(ctx_ptr, Q, fields) gd = LibCEED.gridDim() bi = LibCEED.blockIdx() bd = LibCEED.blockDim() ti = LibCEED.threadIdx() inc = bd.x*gd.x $(def_ins...) $(def_outs...) # Alignment for data read/write a = Val($(Base.datatype_alignment(CeedScalar))) # Cassette context for replacing intrinsics with CUDA versions ctx = LibCEED.CeedCudaContext() for q = (ti.x+(bi.x-1)*bd.x):inc:Q $(read_quads_in...) LibCEED.Cassette.overdub(ctx, $kf, ctx_ptr, $(args...)) $(write_quads_out...) end return end end end function mk_cufunction(ceed, def_module, qf_name, kf, dims_in, dims_out) k_fn = Core.eval(def_module, generate_kernel(qf_name, kf, dims_in, dims_out)) tt = Tuple{Ptr{Nothing},Int32,FieldsCuda} host_k = cufunction(k_fn, tt; maxregs=64) return host_k.fun.handle end # COV_EXCL_STOP
function Glonass(arg0::jdouble, arg1::AbsoluteDate, arg2::AbsoluteDate, arg3::ExtendedPVCoordinatesProvider, arg4::Frame) return Glonass((jdouble, AbsoluteDate, AbsoluteDate, ExtendedPVCoordinatesProvider, Frame), arg0, arg1, arg2, arg3, arg4) end
# Note that this script can accept some limited command-line arguments, run # `julia build_tarballs.jl --help` to see a usage message. using BinaryBuilder, Pkg name = "Raylib" version = v"4.0.0" # Collection of sources required to complete build sources = [ GitSource("https://github.com/raysan5/raylib.git", "0851960397f02a477d80eda2239f90fae14dec64"), DirectorySource("./bundled"), ] # Bash recipe for building across all platforms script = raw""" cd $WORKSPACE/srcdir/raylib/src/ atomic_patch -p1 ../../patches/add-missing-header.patch atomic_patch -p1 ../../patches/make-install-everywhere.patch atomic_patch -p2 ../../patches/make-ldflags-windows.patch export CFLAGS="-D_POSIX_C_SOURCE=200112L" if [[ "${target}" == *-freebsd* ]]; then # Allow definition of `u_char`, `u_short`, `u_int`, and `u_long` in sys/types.h CFLAGS="${CFLAGS} -D__BSD_VISIBLE" fi CFLAGS="${CFLAGS} -DSUPPORT_EVENTS_AUTOMATION -DSUPPORT_FILEFORMAT_BMP -DSUPPORT_FILEFORMAT_JPG" FLAGS=() if [[ "${target}" == *-mingw* ]]; then # raylib.rc.data is broken for x64, remove it from compilation sed -i 's+$(RAYLIB_RES_FILE)+ +g' Makefile # we need to specify the OS in the flags to make for Windows FLAGS+=(OS=Windows_NT) fi make -j${nproc} USE_EXTERNAL_GLFW=TRUE PLATFORM=PLATFORM_DESKTOP RAYLIB_LIBTYPE=SHARED RAYLIB_MODULE_RAYGUI=TRUE RAYLIB_MODULE_PHYSAC=TRUE "${FLAGS[@]}" make install RAYLIB_LIBTYPE=SHARED DESTDIR="${prefix}" RAYLIB_INSTALL_PATH="${libdir}" """ # These are the platforms we will build for by default, unless further # platforms are passed in on the command line platforms = supported_platforms(; exclude=p->arch(p)=="armv6l") # The products that we will ensure are always built products = [ LibraryProduct(["libraylib","raylib"], :libraylib) ] x11_platforms = filter(p ->Sys.islinux(p) || Sys.isfreebsd(p), platforms) # Dependencies that must be installed before this package can be built dependencies = [ Dependency(PackageSpec(name="alsa_jll", uuid="45378030-f8ea-5b20-a7c7-1a9d95efb90e"); platforms=filter(Sys.islinux, platforms)) Dependency(PackageSpec(name="Mesa_jll", uuid="78dcde23-ec64-5e07-a917-6fe22bbc0f45"); platforms=filter(Sys.iswindows, platforms)) Dependency(PackageSpec(name="Xorg_libX11_jll", uuid="4f6342f7-b3d2-589e-9d20-edeb45f2b2bc"); platforms=x11_platforms) Dependency(PackageSpec(name="Xorg_libXrandr_jll", uuid="ec84b674-ba8e-5d96-8ba1-2a689ba10484"); platforms=x11_platforms) Dependency(PackageSpec(name="Xorg_libXi_jll", uuid="a51aa0fd-4e3c-5386-b890-e753decda492"); platforms=x11_platforms) Dependency(PackageSpec(name="Xorg_libXcursor_jll", uuid="935fb764-8cf2-53bf-bb30-45bb1f8bf724"); platforms=x11_platforms) Dependency(PackageSpec(name="Xorg_libXinerama_jll", uuid="d1454406-59df-5ea1-beac-c340f2130bc3"); platforms=x11_platforms) BuildDependency(PackageSpec(name="Xorg_xorgproto_jll", uuid="c4d99508-4286-5418-9131-c86396af500b")) Dependency(PackageSpec(name="GLFW_jll", uuid="0656b61e-2033-5cc2-a64a-77c0f6c09b89")) ] # Build the tarballs, and possibly a `build.jl` as well. build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6")
export GenNeighbourhood export GenNeighbourhoodIesimo using Distributions """ GenNeighbourhood(w::Vector{Real} ,µ::Real, var ::Real) Devuelve vecino del vector `w` de acorde a una normal de media `µ` y varianza `var`. """ function GenNeighbourhood(w::Vector{<:Real} ,µ::Real, var ::Real)::Vector{<:Real} distribution = Normal(µ, var) z=rand(distribution,size(w)) w_new = map( x -> min(1, max(0,x)), w-z ) return w_new end """ GenNeighbourhoodIesimo(w::Vector{<:Real} ,µ::Real, var ::Real, index::Int)::Vector{<:Real} Devuelve vecino del vector `w` de acorde a una normal de media `µ` y varianza `var` donde solo se ha cambia la componente iéxima. """ function GenNeighbourhoodIesimo(w::Vector{<:Real} ,µ::Real, var ::Real, index::Int)::Vector{<:Real} distribution = Normal(µ, var) z=rand(distribution) w_new = w w_new[index] = min(1, max(0,w_new[index]-z)) return w_new end
module Milann using Flux import Flux.Tracker: data, @grad, track using Statistics # This implemens a MIL version where the bag instances are stored in a continuous tensor and bags are delimited by ranges. export RangeMIL, segmax, segmean, segmax_naive, segmean_naive, segmaxmean struct RangeMIL premodel aggregation postmodel end @Flux.treelike RangeMIL function (m::RangeMIL)(X::AbstractArray, B::AbstractArray) (nfeatures, ninsts), nbags = size(X), length(B) # X: nfeatures x ninsts, B: nbags Ypre = m.premodel(X) # Ypre: npremodeloutput x ninstances Yagg = m.aggregation(Ypre, B) # Yagg: npremodeloutput x nbags m.postmodel(Yagg) end """ segmax(X, segments) Compute segmented maximum for instances `X` and bags indexed by `segments`. """ function segmax(X, segments) Y = similar(X, size(X, 1), length(segments)) # naive approach, fast on CPU # for (i, seg) in enumerate(segments) # Y[:, i:i] .= mean(view(X, :, seg), dims=2) # end # sliced approach much better for GPU Y .= 0 mlen = maximum(length.(segments)) for i in 1:mlen Yindices = [j for (j, e) in enumerate(segments) if length(e) >= i] Xindices = map(q -> first(q) + i - 1, filter(e -> length(e) >= i, segments)) Y[:, Yindices] = max.(view(Y, :, Yindices), view(X, :, Xindices)) end Y end """ segmax_idx(X, segments) Compute segmented maximum for instances `X` and bags indexed by `segments`. Same as segmax, but returns also the indices of maxima in input (used for grad computation). """ function segmax_idx(X, segments) Y = similar(X, size(X, 1), length(segments)) Y2 = similar(X, size(Y)...) # twice the memmory! idxs = similar(X, size(Y)...) Y .= -Inf Y2 .= NaN idxs .= 0 mlen = maximum(length.(segments)) for i in 1:mlen Yindices = [j for (j, e) in enumerate(segments) if length(e) >= i] Xindices = map(q -> first(q) + i - 1, filter(e -> length(e) >= i, segments)) Y2[:, Yindices] = max.(view(Y, :, Yindices), view(X, :, Xindices)) idxs[:, Yindices] += view(Y, :, Yindices) .!= view(Y2, :, Yindices) # has been max increased since last iteration? tmp = Y; Y = Y2; Y2 = tmp # just copy references end # idxs now holds indices of maxima relative to bags, make them relative to inputs offsets = first.(segments) .- 1 # first indices in X minus 1 Y, Int.(cpu(idxs) .+ reshape(offsets, 1, length(offsets))) end segmax(X::TrackedArray, segments) = track(segmax, X, segments) function dsegmax(Δ, segments, idxs) grads = similar(Δ, size(Δ, 1), last(last(segments))) grads .= 0 for (i, row) in enumerate(eachrow(idxs)) # @show size(row), minimum(row), size(Δ) grads[i, row] .= Δ[i, :] end grads, nothing end @grad function segmax(X, segments) Y, idxs = segmax_idx(data(X), segments) Y, Δ -> dsegmax(Δ, segments, idxs) end """ segmean(X, segments) Compute segmented mean for instances `X` and bags indexed by `segments`. """ function segmean(X, segments) Y = similar(X, size(X, 1), length(segments)) # naive approach, fast on CPU # for (i, seg) in enumerate(segments) # Y[:, i:i] .= mean(view(X, :, seg), dims=2) # end # sliced approach much better for GPU Y .= 0 mlen = maximum(length.(segments)) for i in 1:mlen Yindices = [j for (j, e) in enumerate(segments) if length(e) >= i] Xindices = map(q -> first(q) + i - 1, filter(e -> length(e) >= i, segments)) Y[:, Yindices] += view(X, :, Xindices) end Y ./= reshape(gpu(length.(segments)), 1, length(segments)) Y end segmean(X::TrackedArray, segments) = track(segmean, X, segments) function dsegmean(Δ, segments) grads = similar(Δ, size(Δ, 1), last(last(segments))) # naive approach, fast on CPU # for (i, seg) in enumerate(segments) # grads[:, seg] .= view(Δ, :,i) / length(seg) # end # sliced approach much better for GPU mlen = maximum(length.(segments)) for i in 1:mlen Yindices = [j for (j, e) in enumerate(segments) if length(e) >= i] Xindices = map(q -> first(q) + i - 1, filter(e -> length(e) >= i, segments)) grads[:, Xindices] .= view(Δ, :, Yindices) end for i in 2:mlen # normalization Xindices = vcat((collect(seg) for seg in segments if length(seg) == i)...) if length(Xindices) > 0 grads[:, Xindices] ./= i end end grads, nothing end @grad segmean(X, segments) = segmean(data(X), segments), Δ -> dsegmean(Δ, segments) """ segmax_naive(X, segments) Segmented maximum: naive reference implementation using default AD. """ function segmax_naive(X, segments) hcat((maximum(X[:,s], dims=ndims(X)) for s in segments)...) end """ segmean_naive(X, segments) Segmented mean: naive reference implementation using default AD. """ function segmean_naive(X, segments) hcat((mean(X[:,s], dims=ndims(X)) for s in segments)...) end """ segmaxmean(X, segments) Combine `segmax` and `segmean`. """ segmaxmean(X, segments) = vcat(segmax(X, segments), segmean(X, segments)) end # module
module ITKFFI include("image.jl") include("filter.jl") @wraptype Float2D @wraptype Float3D @wraptype Double2D @wraptype Double3D @wraptype Short2D @wraptype Short3D end
module SWScale include(joinpath(Pkg.dir("VideoIO"),"src","init.jl")) w(f) = joinpath(swscale_dir, f) using AVUtil include(w("LIBSWSCALE.jl")) end
for i in 1:2:9 println(i) end #> 1 3 5 7 9 typeof(1:1000) #> UnitRange{Int64} a = split("A,B,C,D",",") typeof(a) #> Array{SubString{String},1} show(a) #> SubString{String}["A","B","C","D"] arr = [100, 25, 37] arra = Any[100, 25, "ABC"] #> element type Any arr[1] #> 100 arr[end] #> 37 # arr[6] #> ERROR: BoundsError: attempt to access 3-element Array{Int64,1} at index [6] println(eltype(arr)) #> Int64 println(length(arr)) #> 3 println(ndims(arr)) #> 1 println(size(arr,1)) #> 3 println(size(arr)) #> (3,) arr2 = Array{Int64}(undef, 5) show(arr2) #> [1, 2, 3, 4, 5] sizehint!(arr2, 10^5) arr3 = Float64[] #> 0-element Array{Float64,1} push!(arr3, 1.0) #> 1-element Array{Float64,1} arr4 = collect(1:7) #> 7-element Array{Int64,1} show(arr4) #> [1, 2, 3, 4, 5, 6, 7] # for in loop and changing the array: da = [1,2,3,4,5] for n in da n *= 2 end da #> 5-element Array{Int64,1}: 1 2 3 4 5 for i in 1:length(da) da[i] *= 2 end da #> 5-element Array{Int64,1}: 2 4 6 8 10 arr4 = [1,2,3,4,5,6,7] #> 7-element Array{Int64,1}: [1,2,3,4,5,6,7] join(arr4, ", ") #> "1, 2, 3, 4, 5, 6, 7" arr4[1:3] # => [1, 2, 3] arr4[4:end] # => [4, 5, 6, 7] arr = [1,2,3,4,5] arr[2:4] = [8,9,10] println(arr) #> 1 8 9 10 5 zeros(5) ones(4) ones(3, 2) eqa = range(0, step=10, length=5) #> 0:10:40 println() show(eqa) #> 0:10:40 fill!(arr, 42) #> [42, 42, 42, 42, 42] println() println(Array{Any}(undef, 4)) #> Any[#undef,#undef,#undef,#undef] v1 = rand(Int32, 5) println(v1) #> Int32[1735276173,972339632,1303377282,1493859467,-788555652] b = collect(1:7) c = [100,200,300] append!(b,c) # Now b is [1, 2, 3, 4, 5, 6, 7, 100, 200, 300] pop!(b) #> 300, b is now [1, 2, 3, 4, 5, 6, 7, 100, 200] push!(b, 42) # b is now [1, 2, 3, 4, 5, 6, 7, 100, 200, 42] popfirst!(b) #> 1, b is now [2, 3, 4, 5, 6, 7, 100, 200, 42] pushfirst!(b, 42) # b is now [1, 2, 3, 4, 5, 6, 7, 100, 200, 42] splice!(b,8) #> 100, b is now [42, 2, 3, 4, 5, 6, 7, 200, 42] in(42, b) #> true in(43, b) #> false println() println("sorting:") sort(b) #> [2,3,4,5,6,7,42,42,200], b is not changed println(b) #> [42,2,3,4,5,6,7,200,42] sort!(b) #> b is now changed to [2,3,4,5,6,7,42,42,200] println(b) #> [2,3,4,5,6,7,42,42,200] println() arr = [1, 5, 3] # looping for e in arr print("$e ") end # prints 1 5 3 arr = [1, 2, 3] arr .+ 2 #> [3, 7, 5] arr * 2 #> [2, 10, 6] a1 = [1, 2, 3] a2 = [4, 5, 6] a1 .* a2 #> [4, 10, 18] using LinearAlgebra LinearAlgebra.dot(a1, a2) #> 32 sum(a1 .* a2) repeat([1, 2, 3], inner = [2]) #> [1,1,2,2,3,3] a = [1,2,4,6] a1 = a show(a1) a[4] = 0 show(a) #> [1,2,4,0] show(a1) #> [1,2,4,0] b = copy(a) b = deepcopy(a) a = [1,2,3] function change_array(arr) arr[2] = 25 end change_array(a) println(a) #>[ 1, 25, 3] # the splat operator: arr = ['a', 'b', 'c'] show(join(arr)) #> "abc" show(string(arr)) #> "['a', 'b', 'c']" show(string(arr...)) #> "abc"
module ImageUtilities export save_image_grid export image_grid_figure export image_grid_tensor export image_grid export color_image export color_image_tensor using FluxGAN: GAN using Flux: cpu using CairoMakie using Images using FileIO using Dates using EllipsisNotation using Random ########################### # image utility functions # ########################### # save image grid figure from model # function save_image_grid(model::GAN, output_dir::String; layout=(5, 5), date=false, file_info=[], img_res=150, kws...) if file_info == [] info = "" else info = mapreduce(tag -> string(tag) * "_", *, file_info) end file = info * "grid_$(layout[1])_$(layout[2])" * (date ? "_" * string(today()) : "") imgs = image_grid_tensor(model, *(layout...); kws...) fig = image_grid_figure(imgs, layout; img_res=img_res) save(output_dir * "/" * file * ".png", fig) end # generate and return color images tensor from model # function image_grid_tensor(model::GAN, n::Int; uncenter=true, seed=false) @assert model.hparams.img_size ≠ undef "Image size not defined!" if seed Random.seed!(69) end imgs = cpu(model.G)(randn(Float32, model.hparams.latent_dim, n)) if uncenter imgs = @. (imgs + 1f0) / 2f0 end imgs = reshape(imgs, model.hparams.img_size..., :) color_image_tensor(imgs) end # return image grid makie figure from image grid tensor # function image_grid_figure(imgs::Array, layout::Tuple{Int,Int}; img_res=150, hflip=true) n = size(imgs)[end] rows, cols = layout @assert rows * cols == n "Number of images ≠ grid size!" imgs = [imgs[.., i] for i in 1:n] if hflip imgs = map(img -> reverse(img, dims=2), imgs) end fig = Figure(resolution=(cols * img_res, rows * img_res)) for i = 1:rows, j = 1:cols ax, = image(fig[i,j], imgs[i + rows * (j - 1)]) hidedecorations!(ax) hidexdecorations!(ax, ticks=false) hideydecorations!(ax, ticks=false) end fig end # return image grid from GAN and layout # function image_grid(model::GAN, layout::Tuple{Int,Int}; kws...) imgs = image_grid_tensor(model, *(layout...); kws...) image_grid(imgs, layout) end # convert images tensor into an image grid # function image_grid(imgs::Array{Color, 3}, layout::Tuple{Int,Int}) h, w, n = size(imgs) rows, cols = layout @assert rows * cols == n "Number of images ≠ grid size!" grid = Array{Color}(undef, h * rows, w * cols) for i = 1:rows, j = 1:cols img = imgs[:, :, i + rows*(j - 1)] grid[((i - 1)*h + 1):i*h, ((j - 1)*w + 1):j*w] = img' end grid end # return color RGB image from image array # function color_image(img::Array) @assert length(size(img)) ∈ [2, 3] "Image tensor dimension ∉ [2, 3]!" if length(size(img)) == 3 img = permutedims(img, (3, 1, 2)) img = Matrix(colorview(RGB, img)) else img = Matrix(colorview(Gray, img)) end img end # convert tensor of image data into color image tensor # function color_image_tensor(imgs::Array) color_imgs = Array{Color}(undef, size(imgs)[1:2]..., size(imgs)[end]) for i = 1:size(imgs)[end] color_imgs[:, :, i] = color_image(imgs[.., i]) end color_imgs end end
# # Magnetic liquid droplet in magnetic field # The behaviour of droplets under the action of magnetic fields of different configurations is an important issue in many domains, including microfluidics (Seeman et al. 2012), mechanics of tissues (Douezan et al. 2011; Frasca et al. 2014), studies of dynamic self-assembly (Timonen et al. 2013) and many others. After the successful synthesis of magnetic fluids in the late sixties by (Rosensweig 1985) an exciting story about droplets of magnetic fluid began. At first, the elongation of the droplets in an external field was observed and explained by Arhipenko et al. (1978). Later on, different droplet configurations were experimentally observed in the high-frequency rotating field, which was subject to our numerical study in [^1]. # Here I present the essential ingredients to reproduce the results of the paper with the new tools SurfaceTopology, LaplaceBIE and ElTopo (optional). using LinearAlgebra using GeometryTypes using SurfaceTopology using LaplaceBIE using AbstractPlotting, GLMakie ## using ElTopo # The calculation requires normal vector and vertex areas methods. Latter one gives the area of 1/3 of the vertex ring, so the sum is the area of the droplet. function normals(vertices,topology) n = Point{3,Float64}[] for v in 1:length(vertices) s = Point(0,0,0) for (v1,v2) in EdgeRing(v,topology) s += cross(vertices[v1],vertices[v2]) end normal = s ./ norm(s) push!(n,normal) end return n end function vertexareas(points,topology) vareas = zeros(Float64,length(points)) for face in Faces(topology) v1,v2,v3 = face area = norm(cross(points[v3]-points[v1],points[v2]-points[v1])) /2 vareas[v1] += area/3 vareas[v2] += area/3 vareas[v3] += area/3 end return vareas end # These are tools to keep track if the calculation is sensible. Since we are working in an incompressible fluid, the volume needs to be constant, and the energy of the droplet decreases until equilibrium is reached. function surfacevolume(points,topology) normal0 = [0,0,1] s = 0 for face in Faces(topology) y1 = points[face[1]] y2 = points[face[2]] y3 = points[face[3]] normaly = cross(y2-y1,y3-y1) normaly /= norm(normaly) area = norm(cross(y2-y1,y3-y1))/2 areaproj = dot(normaly,normal0)*area volume = dot(y1 + y2 + y3,normal0)/3*areaproj s += volume end return s end function energy(points,normals,faces,psi,mup,gammap,H0) vareas = vertexareas(points,faces) Area = sum(vareas) s = 0 for xkey in 1:length(points) s += psi[xkey]*dot(H0,normals[xkey]) * vareas[xkey] end Es = gammap * Area Em = 1/8/pi * (1 - mup) * s return Es+Em end # For calculating the equilibrium of the droplet, we use a curvatureless algorithm for a vicious droplet developed by Zinchenko 1997. He found a way to calculate velocity generated by a surface tension without explicitly calculating the curvature, which makes it easier to implement and from some tests also more stable. The following method accepts surface defined by points, normals and faces (or topology) and surface force as well as surface tension γ and viscosity η (which only affects the scaling of time). function stokesvelocity(points,normals,faces,forcen,etaP,gammap) vareas = vertexareas(points,faces) velocityn = zeros(Float64,length(points)) for xkey in 1:length(points) x = points[xkey] nx = normals[xkey] fx = forcen[xkey] s = 0 for ykey in 1:length(points) if ykey==xkey continue end y = points[ykey] ny = normals[ykey] fy = forcen[ykey] ### Need to check a missing 2 s += vareas[ykey]*1 ./8/pi/etaP* dot(y-x,nx+ny)/norm(y-x)^3*(1-3*dot(y-x,nx)*dot(y-x,ny)/norm(y-x)^2) * gammap s += vareas[ykey]*1 ./8/pi/etaP* ( dot(nx,ny)/norm(x-y) + dot(nx,x -y)*dot(ny,x-y)/norm(x-y)^3 )*(fy - fx) end velocityn[xkey] = s end return velocityn end # Now having methods defined, we can include a sphere and proceed with calculation. include("sphere.jl") msh = unitsphere(2) vertices, faces = msh.vertices, msh.faces ## Now let's do something fun. Visualize the process with Makie in real time. x = Node(msh) y = lift(x->x,x) scene = Scene(show_axis=false) wireframe!(scene,y,linewidth = 3f0) mesh!(scene,y, color = :white, shading = false) display(scene) ## Initial parameters H0 = [4.,0.,0.] etap = 1. gammap = 1. μ = 10. t = 0. Δt = 0.1 N = 100 volume0 = surfacevolume(vertices,faces) record(scene, "mdrop.gif", 1:N) do i # for i in 1:N n = normals(vertices,faces) psi = surfacepotential(vertices,n,faces,μ,H0) P∇ψ = tangentderivatives(vertices,n,faces,psi) Hn = normalderivatives(vertices,n,faces,P∇ψ,μ,H0) E = energy(vertices,n,faces,psi,μ,gammap,H0) rV = surfacevolume(vertices,faces)/volume0 @show E,rV Ht = [norm(j) for j in P∇ψ] # The force generated (M⋅∇)H, which includes a jump of magnetization at the surface and force coming from the whole bulk. tensorn = μ*(μ-1)/8/pi * Hn.^2 + (μ-1)/8/pi * Ht.^2 vn = stokesvelocity(vertices,n,faces,tensorn,etap,gammap) vertices .+= n .* vn * Δt msh = HomogenousMesh(vertices,faces) ### ElTopo stabilization ## par = SurfTrack(allow_vertex_movement=true) ## msh = stabilize(msh,par) push!(x,msh) AbstractPlotting.force_update!() global vertices, faces = msh.vertices, msh.faces global t += Δt end # ![](mdrop.gif) # [^1]: Erdmanis, J. & Kitenbergs, G. & Perzynski, R. & Cebers, A. (2017) Magnetic micro-droplet in rotating field: numerical simulation and comparison with experiment
# This script will usually fail as Stan gives up when the integration fails. using StanSample, StatsPlots ProjDir = @__DIR__ ben_model = " functions { real[] dz_dt(real t, // time real[] z, // system state {prey, predator} real[] theta, // parameters real[] x_r, // unused data int[] x_i) { real u = z[1]; real v = z[2]; real alpha = theta[1]; real beta = theta[2]; real gamma = theta[3]; real delta = theta[4]; real du_dt = (alpha - beta * v) * u; real dv_dt = (-gamma + delta * u) * v; return { du_dt, dv_dt }; } } data { int<lower = 0> N; real t0; real ts[N]; real y_init[2]; real y[N, 2]; } transformed data { real beta = 1.0; real gamma = 3.0; real delta = 1.0; } parameters { real alpha; real z_init[2]; real<lower = 0> sigma[2]; } transformed parameters { real theta[4] = { alpha, beta, gamma, delta }; real z[N, 2] = integrate_ode_rk45(dz_dt, z_init, t0, ts, theta, rep_array(0.0, 0), rep_array(0, 0), 1e-5, 1e-3, 500); } model { alpha ~ normal(1.5, 0.01); sigma ~ inv_gamma(3, 3); z_init ~ normal(1, 0.01); for (k in 1:2) { y_init[k] ~ normal(z_init[k], sigma[k]); y[ , k] ~ normal(z[, k], sigma[k]); } } "; sm = SampleModel("Ben", ben_model, tmpdir="$(@__DIR__)/tmp") obs = reshape([ 2.75487369287842, 6.77861583902452, 0.977380864533721, 1.87996617432547,6.10484970865812, 1.38241825210688, 1.32745986436496, 4.35128045090906, 3.28082272129074, 1.02627964892546, 0.252582832985904, 2.01848763447693, 1.91654508055532, 0.33796473710305, 0.621805831293324, 3.47392930294277, 0.512736737236118, 0.304559407399392, 4.56901766791213, 0.91966250277948], (10,2)) ben_data = Dict( :N => 10, :t0 => 0, :ts => 1:10, :y => obs, :y_init => [1.01789244983237, 0.994539126829031] ) t = ben_data[:ts] plot(xlab="t", ylab="prey and pred") plot!(t, obs[:,1], lab="prey") plot!(t, obs[:, 2], lab="pred") savefig("$(ProjDir)/observations.png") @time rc = stan_sample(sm; data=ben_data) if success(rc) p = read_samples(sm, output_format=:particles) display(p) end
using Flux struct NeuralNetworkQ{Tm, To, Tp} <: AbstractQApproximator{Any, Int} model::Tm opt::To ps::Tp function NeuralNetworkQ(model::Tm, opt::To) where {Tm, To} m = gpu(model) ps = params(m) new{typeof(m), To, typeof(ps)}(m, opt, ps) end end (Q::NeuralNetworkQ)(s, ::Val{:dist}) = Q.model(s) (Q::NeuralNetworkQ)(s) = Q(s, Val(:dist)) (Q::NeuralNetworkQ)(s, ::Val{:argmax}) = reshape(map(i -> i[1], findmax(Q(s).data, dims=1)[2]), :) (Q::NeuralNetworkQ)(s, ::Val{:max}) = dropdims(maximum(Q(s), dims=1), dims=1) (Q::NeuralNetworkQ)(s, a::Int) = Q(s)[a] function (Q::NeuralNetworkQ)(s, a::AbstractArray{Int, 1}) dist = Q(s) inds = CartesianIndex.(a, axes(dist, 2)) dist[inds] end function update!(Q::NeuralNetworkQ, loss) Flux.back!(loss) Flux.Optimise.update!(Q.opt, Q.ps) end
module AnnDatas using HDF5 using SparseArrays using DataFrames export AnnData struct AnnData X::SparseMatrixCSC obsm::Union{Nothing, Dict{String, Any}} obsp::Union{Nothing, Dict{String, Any}} uns::Union{Nothing, Dict{String, Any}} obs::Union{Nothing, DataFrame} var::Union{Nothing, DataFrame} end """ Read a CSR matrix in a SparseMatrixCSC """ function read_csr_matrix(g::HDF5.Group) attr = attributes(g) @assert read(attr["encoding-type"]) == "csr_matrix" m, n = read(attr["shape"]) V = read(g["data"]) csr_indices = read(g["indices"]) .+ 1 csr_indptr = read(g["indptr"]) .+ 1 nnz = length(V) # easiest way to do this is to go CSR -> COO -> CSC I = Vector{Int32}(undef, nnz) J = Vector{Int32}(undef, nnz) for i in 1:m for k in csr_indptr[i]:csr_indptr[i+1]-1 I[k] = i J[k] = csr_indices[k] end end return sparse(I, J, V, m, n) end """ Read a serialized data frame into a DataFrame """ function read_dataframe(input::HDF5.File, path::String) if !haskey(input, path) return nothing end g = input[path] columns = Dict{String, Any}() attr = attributes(g) @assert read(attr["encoding-type"]) == "dataframe" columnorder = read(attr["column-order"]) for key in keys(g) columns[key] = read(g[key]) end df = DataFrame(Dict(key => columns[key] for key in columnorder)) df[!,"_index"] = read(g["_index"]) return df end """ General purpose function to read a groups into a dictionary tree structure. """ function read_group(input::HDF5.File, path::String) if !haskey(input, path) return nothing end g = input[path] data = Dict{String, Any}() for key in keys(g) dataset = g[key] if isa(dataset, HDF5.Group) attr = attributes(dataset) if length(attr) == 0 # data[key] = read_group(dataset) data[key] = read(dataset) elseif haskey(attr, "encoding-type") && read(attr["encoding-type"]) == "csr_matrix" data[key] = read_csr_matrix(dataset) else data[key] = read(dataset) end # TODO: special cases for other types of data else data[key] = read(dataset) end end return data end """ Read an AnnData struct from the given h5ad filename. """ function Base.read(filename::AbstractString, ::Type{AnnData}) input = h5open(filename) if isa(input["X"], HDF5.Group) X = read_csr_matrix(input["X"]) else X = read(input["X"]) end obsm = read_group(input, "obsm") obsp = read_group(input, "obsp") uns = read_group(input, "uns") obs = read_dataframe(input, "obs") var = read_dataframe(input, "var") close(input) return AnnData(X, obsm, obsp, uns, obs, var) end end # module
module BIFMHelperNodeTest using Test using ReactiveMP using Random import ReactiveMP: @test_rules @testset "BIFMHelperNode" begin @testset "Creation" begin node = make_node(BIFMHelper) @test functionalform(node) === BIFMHelper @test sdtype(node) === Stochastic() @test name.(interfaces(node)) === (:out, :in) @test factorisation(node) === ((1, 2), ) @test length(methods(functional_dependencies, (Any, FactorNode{Type{BIFMHelper}}, Int))) === 1 end @testset "Average energy" begin node = make_node(BIFMHelper) @test score(AverageEnergy(), BIFMHelper, Val{(:out, :in)}, (Marginal(MvNormalMeanCovariance([1,1], [2 0; 0 3]), false, false), Marginal(MvNormalMeanCovariance([1,1], [2 0; 0 3]), false, false)), nothing) ≈ entropy(MvNormalMeanCovariance([1,1], [2 0; 0 3])) @test score(AverageEnergy(), BIFMHelper, Val{(:out, :in)}, (Marginal(MvNormalMeanCovariance([1,2], [2 0; 0 1]), false, false), Marginal(MvNormalMeanPrecision([1,2], [0.5 0; 0 1]), false, false)), nothing) ≈ entropy(MvNormalMeanCovariance([1,2], [2 0; 0 1])) end end end
__precompile__() module MicroLogging # ----- Core API to go in Base ----- export ## Logger types AbstractLogger, LogLevel, NullLogger, # Public logger API: # handle_message, shouldlog, min_enabled_level, catch_exceptions # (not exported, as they're not generally called by users) # ## Log creation @debug, @info, @warn, @error, @logmsg, ## Logger installation and control # TODO: Should some of these go into stdlib ? with_logger, current_logger, global_logger, disable_logging # ----- API to go in StdLib package ? ----- export SimpleLogger, # Possibly needed in Base? # TODO: configure_logging needs a big rethink (see, eg, python's logger # config system) configure_logging # ----- MicroLogging stuff, for now ----- export InteractiveLogger # core.jl includes the code which will hopefully go into Base in 0.7 const core_in_base = isdefined(Base, :CoreLogging) if core_in_base import Logging: @debug, @info, @warn, @error, @logmsg, AbstractLogger, LogLevel, BelowMinLevel, Debug, Info, Warn, Error, AboveMaxLevel, with_logger, current_logger, global_logger, disable_logging, handle_message, shouldlog, min_enabled_level, catch_exceptions, SimpleLogger else include("core.jl") end include("loggers.jl") include("config.jl") if !core_in_base include("test.jl") end function __init__() global_logger(InteractiveLogger(STDERR)) end end
using Stheno, Test, Random, LinearAlgebra, Statistics @testset "Stheno" begin @testset "util" begin include("util/covariance_matrices.jl") include("util/woodbury.jl") include("util/block_arrays.jl") include("util/abstract_data_set.jl") end @testset "mean_and_kernel" begin include("test_util.jl") include("mean_and_kernel/mean.jl") include("mean_and_kernel/kernel.jl") include("mean_and_kernel/compose.jl") include("mean_and_kernel/finite.jl") include("mean_and_kernel/conditional.jl") include("mean_and_kernel/block.jl") # include("mean_and_kernel/transform.jl") include("mean_and_kernel/input_transform.jl") include("mean_and_kernel/zero.jl") include("mean_and_kernel/degenerate.jl") include("mean_and_kernel/derivative.jl") include("mean_and_kernel/conversion.jl") end @testset "gp" begin include("gp/abstract_gp.jl") include("gp/gp.jl") include("gp/block_gp.jl") end @testset "linops" begin include("linops/indexing.jl") include("linops/addition.jl") include("linops/product.jl") # include("linops/integrate.jl") include("linops/project.jl") include("linops/conditioning.jl") end @testset "integration" begin include("util/toeplitz_integration.jl") end end
""" Get the curl of a vector f w.r.t Ds """ function curl(vec, Ds) [Ds[2](vec[3]) - Ds[3](vec[2]), Ds[3](vec[1]) - Ds[1](vec[3]), Ds[1](vec[2]) - Ds[2](vec[1])] end """ Get the divergence of a function f w.r.t Ds with the option of multiplying each part of the sum by a v """ function divergence(Ds, f, v=ones(length(Ds))) if f isa AbstractArray sum([v[i] * Ds[i](f[i]) for i in eachindex(Ds)]) else sum([v[i] * Ds[i](f) for i in eachindex(Ds)]) end end """ Print the loss of the loss function """ function print_loss(timeCounter, startTime, times, losses) deltaT_s = time_ns() #Start a clock when the callback begins timeCounter = timeCounter + time_ns() - deltaT_s ctime = time_ns() - startTime - timeCounter #This variable is the time to use for the time benchmark plot append!(times, ctime/10^9) #Conversion nanosec to seconds function cb(p, l) append!(losses, l) println("Current loss is: $l") return false end end """ Simulates a collisionless plasma given: plasma – Struct of type CollisionlessPlasma lb – lower bound ub – upper bound time_lb – lower time boundary time_ub – upper time boundary GPU – whether this should be executed on the GPU or not inner_layers – how many layers in the neural network strategy – what NeuralPDE training strategy should be used """ function solve(plasma::CollisionlessPlasma; lb=0.0, ub=1.0, time_lb=lb, time_ub=ub, GPU=true, inner_layers=16, strategy=StochasticTraining(100), E_bcs=Neumann, f_bcs=(a=1, g=0), maxiters=[30,100], normalized=true) if lb > ub error("lower bound must be larger than upper bound") end if GPU && strategy == QuadratureTraining() error("QuadratureTraining does not have GPU support. Use another strategy (e.g. StochasticTraining(200)) instead") end losses = [] times = [] timeCounter = 0.0 startTime = time_ns() # constants dim = 3 geometry = plasma.geometry.f # this might change with a geometry refactor dis = plasma.distributions species = [d.species for d in dis] consts = Constants() μ_0, ϵ_0 = consts.μ_0, consts.ϵ_0 # get qs, ms, Ps from species qs, ms = Float64[], Float64[] for s in species push!(qs,s.q) push!(ms,s.m) end Ps = [d.P for d in dis] if normalized qs .= 1 ms .= 1 ϵ_0 = 1 μ_0 = 0 end # variables fs = Symbolics.variables(:f, eachindex(species); T=SymbolicUtils.FnType{Tuple,Real}) Es = Symbolics.variables(:E, 1:dim; T=SymbolicUtils.FnType{Tuple,Real}) Bs = Symbolics.variables(:B, 1:dim; T=SymbolicUtils.FnType{Tuple,Real}) # parameters @parameters t xs,vs = Symbolics.variables(:x, 1:dim), Symbolics.variables(:v, 1:dim) # integrals _I = Integral(tuple(vs...) in DomainSets.ProductDomain(ClosedInterval(-Inf ,Inf), ClosedInterval(-Inf ,Inf), ClosedInterval(-Inf ,Inf))) # differentials Dxs = Differential.(xs) Dvs = Differential.(vs) Dt = Differential(t) # domains xs_int = xs .∈ Interval(lb, ub) vs_int = vs .∈ Interval(lb, ub) t_int = t ∈ Interval(time_lb, time_ub) domains = [t_int;xs_int;vs_int] # helpers _Es = [E(t,xs...) for E in Es] _Bs = [B(t,xs...) for B in Bs] _fs = [f(t,xs...,vs...) for f in fs] # divergences div_vs = [divergence(Dxs, _f, vs) for _f in _fs] div_B = divergence(Dxs, _Bs) div_E = divergence(Dxs, _Es) Fs = [qs[i]/ms[i] * (_Es + cross(vs,_Bs)) for i in eachindex(qs)] divv_Fs = [divergence(Dvs, _fs[i], Fs[i]) for i in eachindex(_fs)] # charge and current densities ρ = sum([qs[i] * _I(_fs[i]) for i in eachindex(qs)]) J = sum([qs[i] * _I(_fs[i]) * vs[j] for i in 1:length(_fs), j in 1:length(vs)]) # system of equations vlasov_eqs = Dt.(_fs) .~ .- div_vs .- divv_Fs curl_E_eqs = curl(_Es, Dxs) .~ Dt.(_Bs) curl_B_eqs = ϵ_0*μ_0 * Dt.(_Es) .- curl(_Bs, Dxs) .~ - μ_0.*J div_E_eq = div_E ~ ρ/ϵ_0 div_B_eq = div_B ~ 0 eqs = [vlasov_eqs; curl_E_eqs; curl_B_eqs; div_E_eq; div_B_eq] # boundary conditions div_E0 = sum([Dxs[i](Es[i](time_lb, xs...)) for i in eachindex(Dxs)]) div_B0 = sum([Dxs[i](Bs[i](time_lb, xs...)) for i in eachindex(Dxs)]) vlasov_ics = [fs[i](time_lb,xs...,vs...) ~ Ps[i](xs,vs) * geometry(xs) for i in eachindex(fs)] div_B_ic = div_B0 ~ 0 div_E_ic = div_E0 ~ sum([qs[i] * _I(fs[i](time_lb,xs...,vs...)) for i in eachindex(qs)])/ϵ_0 * geometry(xs) E_bcs = [E_bcs(t, xs, Dxs, Es, lb); E_bcs(t, xs, Dxs, Es, ub)] f_bcs = [Reflective(t, xs, vs, fs, lb, f_bcs.a, f_bcs.g); Reflective(t, xs, vs, fs, ub, f_bcs.a, f_bcs.g)] bcs = [vlasov_ics;div_B_ic; div_E_ic; E_bcs; f_bcs] # get variables vars_arg = [_fs...; _Es...; _Bs...] vars = [fs, Bs, Es] dict_vars = Dict() for var in vars push!(dict_vars, var => [v for v in var]) end # set up PDE System @named pde_system = PDESystem(eqs, bcs, domains, [t,xs...,vs...], vars_arg) # set up problem il = inner_layers ps_chains = [FastChain(FastDense(length(domains), il, Flux.σ), FastDense(il,il,Flux.σ), FastDense(il, 1)) for _ in 1:length(_fs)] xs_chains = [FastChain(FastDense(length([t, xs...]), il, Flux.σ), FastDense(il,il,Flux.σ), FastDense(il, 1)) for _ in 1:length([_Es; _Bs])] chain = [ps_chains;xs_chains] initθ = GPU ? map(c -> CuArray(Float64.(c)), DiffEqFlux.initial_params.(chain)) : map(c -> Float64.(c), DiffEqFlux.initial_params.(chain)) discretization = NeuralPDE.PhysicsInformedNN(chain, strategy, init_params=initθ) prob = SciMLBase.discretize(pde_system, discretization) # solve opt = Optim.BFGS() res = GalacticOptim.solve(prob, opt, cb = print_loss(timeCounter, startTime, times, losses), maxiters=maxiters[1]) prob = remake(prob, u0=res.minimizer) res = GalacticOptim.solve(prob, ADAM(0.01), cb = print_loss(timeCounter, startTime, times, losses), maxiters=maxiters[2]) phi = discretization.phi return PlasmaSolution(plasma, vars, dict_vars, phi, res, initθ, domains, losses, times) end """ Simulates an electrostatic plasma given: plasma – Struct of type ElectrostaticPlasma dim – in how many D and V dimensions should the simulation happen lb – lower bound ub – upper bound time_lb – lower time boundary time_ub – upper time boundary GPU – whether this should be executed on the GPU or not inner_layers – how many layers in the neural network strategy – what NeuralPDE training strategy should be used """ function solve(plasma::ElectrostaticPlasma; lb=0.0, ub=1.0, time_lb=lb, time_ub=ub, dim=3, GPU=true, inner_layers=16, strategy=StochasticTraining(80*dim), E_bcs=Neumann,f_bcs=(a=1, g=0), maxiters=[30,100], normalized=true) if lb > ub error("lower bound must be larger than upper bound") end if GPU && strategy == QuadratureTraining() error("QuadratureTraining does not have GPU support. Use another strategy (e.g. StochasticTraining(200)) instead") end losses = [] times = [] timeCounter = 0.0 startTime = time_ns() # constants geometry = plasma.geometry.f # this might change with a geometry refactor dis = plasma.distributions species = [d.species for d in dis] consts = Constants() ϵ_0 = consts.ϵ_0 # get qs, ms, Ps from species qs, ms = Float64[], Float64[] for s in species push!(qs,s.q) push!(ms,s.m) end Ps = [d.P for d in dis] if normalized qs .= 1 ms .= 1 ϵ_0 = 1 end # variables fs = Symbolics.variables(:f, eachindex(species); T=SymbolicUtils.FnType{Tuple,Real}) Es = Symbolics.variables(:E, 1:dim; T=SymbolicUtils.FnType{Tuple,Real}) # parameters @parameters t xs,vs = Symbolics.variables(:x, 1:dim), Symbolics.variables(:v, 1:dim) # integrals _I = if length(vs) > 1 intervals = [ClosedInterval(-Inf ,Inf) for _ in 1:length(vs)] _I = Integral(tuple(vs...) in DomainSets.ProductDomain(intervals...)) else _I = Integral(first(vs) in DomainSets.ClosedInterval(-Inf ,Inf)) end # differentials Dxs = Differential.(xs) Dvs = Differential.(vs) Dt = Differential(t) # domains xs_int = xs .∈ Interval(lb, ub) vs_int = vs .∈ Interval(lb, ub) t_int = t ∈ Interval(time_lb, time_ub) domains = [t_int;xs_int;vs_int] # helpers _Es = [E(t,xs...) for E in Es] _fs = [f(t,xs...,vs...) for f in fs] # divergences div_vs = [divergence(Dxs, _f, vs) for _f in _fs] div_E = divergence(Dxs, _Es) Fs = [qs[i]/ms[i] * _Es for i in eachindex(qs)] divv_Fs = [divergence(Dvs, _fs[i], Fs[i]) for i in eachindex(_fs)] # charge density ρ = sum([qs[i] * _I(_fs[i]) for i in eachindex(qs)]) # equations vlasov_eqs = Dt.(_fs) .~ .- div_vs .- divv_Fs div_E_eq = div_E ~ ρ/ϵ_0 eqs = [vlasov_eqs; div_E_eq] # boundary and initial conditions div_E0 = sum([Dxs[i](Es[i](time_lb, xs...)) for i in eachindex(Dxs)]) vlasov_ics = [fs[i](time_lb,xs...,vs...) ~ Ps[i](xs,vs) * geometry(xs) for i in eachindex(fs)] div_E_ic = div_E0 ~ sum([qs[i] * _I(fs[i](time_lb,xs...,vs...)) for i in eachindex(qs)])/ϵ_0 * geometry(xs) f_bcs = [Reflective(t, xs, vs, fs, lb, f_bcs.a, f_bcs.g); Reflective(t, xs, vs, fs, ub, f_bcs.a, f_bcs.g)] E_bcs = [E_bcs(t, xs, Dxs, Es, lb); E_bcs(t, xs, Dxs, Es, ub)] bcs = [vlasov_ics; div_E_ic; E_bcs; f_bcs] # set up variables vars_arg = [_fs; _Es] vars = [fs, Es] dict_vars = Dict() for var in vars push!(dict_vars, var => [v for v in var]) end # set up and return PDE System @named pde_system = PDESystem(eqs, bcs, domains, [t,xs...,vs...], vars_arg) # set up problem il = inner_layers ps_chains = [FastChain(FastDense(length(domains), il, Flux.σ), FastDense(il,il,Flux.σ), FastDense(il, 1)) for _ in 1:length(_fs)] xs_chains = [FastChain(FastDense(length([t, xs...]), il, Flux.σ), FastDense(il,il,Flux.σ), FastDense(il, 1)) for _ in 1:length(_Es)] chain = [ps_chains;xs_chains] initθ = GPU ? map(c -> CuArray(Float64.(c)), DiffEqFlux.initial_params.(chain)) : map(c -> Float64.(c), DiffEqFlux.initial_params.(chain)) discretization = NeuralPDE.PhysicsInformedNN(chain, strategy, init_params=initθ) prob = SciMLBase.discretize(pde_system, discretization) # solve opt = Optim.BFGS() res = GalacticOptim.solve(prob, opt, cb = print_loss(timeCounter, startTime, times, losses), maxiters=maxiters[1]) prob = remake(prob, u0=res.minimizer) res = GalacticOptim.solve(prob, ADAM(0.01), cb = print_loss(timeCounter, startTime, times, losses), maxiters=maxiters[2]) phi = discretization.phi return PlasmaSolution(plasma, vars, dict_vars, phi, res, initθ, domains, losses, times) end
struct BoundingBox ramin::Float64 ramax::Float64 decmin::Float64 decmax::Float64 function BoundingBox(ramin::Float64, ramax::Float64, decmin::Float64, decmax::Float64) @assert ramax > ramin "ramax must be greater than ramin" @assert decmax > decmin "decmax must be greater than decmin" new(ramin, ramax, decmin, decmax) end end function BoundingBox(ramin::String, ramax::String, decmin::String, decmax::String) BoundingBox(parse(Float64, ramin), parse(Float64, ramax), parse(Float64, decmin), parse(Float64, decmax)) end """ SurveyDataSet Abstract type representing a collection of imaging data and associated metadata from a survey. Concrete subtypes are for specific surveys. They provide methods for querying which images are available and loading Celeste Image objects from disk. In short, they provide an interface between survey data organized on disk and in-memory Celeste objects. """ abstract type SurveyDataSet end load_images(::SurveyDataSet, box::BoundingBox) = error("load_images() not defined for this SurveyDataSet type")
# wraps variables found in ASWING.INC for use in Julia struct ASWING_s PI::Array{Float64,1} DTOR::Array{Float64,1} VERSION::Array{Float64,1} STIPL::Array{Float64,1} STIPR::Array{Float64,1} TBTIPL::Array{Float64,1} TBTIPR::Array{Float64,1} MACHPG::Array{Float64,1} GEEW::Array{Float64,1} SREF::Array{Float64,1} CREF::Array{Float64,1} BREF::Array{Float64,1} XYZREF::Array{Float64,2} BGREFX::Array{Float64,1} BGREFY::Array{Float64,1} BGREFZ::Array{Float64,1} ULCON::Array{Float64,1} GRNORM::Array{Float64,1} VSOSL::Array{Float64,1} VSO_SI::Array{Float64,1} VSOSL_SI::Array{Float64,1} RHOSL::Array{Float64,1} RHO_SI::Array{Float64,1} RHOSL_SI::Array{Float64,1} RMUSL::Array{Float64,1} RMU_SI::Array{Float64,1} RMUSL_SI::Array{Float64,1} EXPII::Array{Float64,1} EXPNN::Array{Float64,1} LALTKM::Array{Int32,1} AUTSCL::Array{Int32,1} LTERSE::Array{Int32,1} LVLFIX::Array{Int32,1} LAELAG::Array{Int32,1} LLEVEC::Array{Int32,1} STEADY::Array{Int32,1} CONLAW::Array{Int32,1} CONSET::Array{Int32,1} LFGUST::Array{Int32,1} LROMFR::Array{Int32,1} LVISEN::Array{Int32,1} LLGROU::Array{Int32,1} LLREFP::Array{Int32,1} LAXPLT::Array{Int32,1} LELIST::Array{Int32,1} LENGLI::Array{Int32,1} LESPEC::Array{Int32,1} LNODES::Array{Int32,1} LUNSWP::Array{Int32,1} LPLRIB::Array{Int32,1} LPLZLO::Array{Int32,1} LPLBAR::Array{Int32,1} LFRPAN::Array{Int32,1} LFRROT::Array{Int32,1} LGEOM::Array{Int32,1} LLRHS::Array{Int32,1} LVAIC::Array{Int32,1} LWSET::Array{Int32,1} LCSET::Array{Int32,1} LQBDEF::Array{Int32,2} LBSYMM::OffsetArrays.OffsetArray{Int32,2,Array{Int32,2}} LSFLAP::Array{Int32,1} LSPENG::Array{Int32,1} LSSENS::Array{Int32,1} LQINI::Array{Int32,1} LAINI::Array{Int32,1} LCONV::Array{Int32,1} LMACH::Array{Int32,1} PSTEADY::Array{Int32,1} LPBEAM::Array{Int32,1} LPWAKE::Array{Int32,1} LDCON::Array{Int32,1} LUCON::Array{Int32,1} LQCON::Array{Int32,2} NQ::Array{Int32,1} NCP::Array{Int32,1} IBEAM::Array{Int32,1} IICON::Array{Int32,1} II::Array{Int32,1} IFRST::Array{Int32,1} ILAST::Array{Int32,1} IITOT::Array{Int32,1} NNCON::Array{Int32,1} NN::Array{Int32,1} NFRST::Array{Int32,1} NLAST::Array{Int32,1} NNTOT::Array{Int32,1} KEQ0::Array{Int32,2} KEQ::Array{Int32,2} NRHS::Array{Int32,1} NGVAR::Array{Int32,1} NGPAR::Array{Int32,1} NGFOR::Array{Int32,1} NGFEQ::Array{Int32,1} NFRP::Array{Int32,1} NFRPF::Array{Int32,1} NFRPR::Array{Int32,1} NBEAM::Array{Int32,1} NFUSE::Array{Int32,1} NSURF::Array{Int32,1} ICOORD::Array{Int32,1} IENGTYP::Array{Int32,1} IGUSDIR::Array{Int32,1} NXGUST::Array{Int32,1} NYGUST::Array{Int32,1} NZGUST::Array{Int32,1} NFGUST::Array{Int32,1} IGRIM::Array{Int32,1} LRES::Array{Int32,1} LQJOIN::Array{Int32,2} LAN::Array{Int32,1} LHEAD::Array{Int32,1} LELEV::Array{Int32,1} LBANK::Array{Int32,1} LVAC::Array{Int32,1} LRAC::Array{Int32,1} LVEL::Array{Int32,1} LROT::Array{Int32,1} LPOS::Array{Int32,1} LFLAP::Array{Int32,1} LPENG::Array{Int32,1} LVIDT::Array{Int32,1} LALDT::Array{Int32,1} LBEDT::Array{Int32,1} LHEDT::Array{Int32,1} LELDT::Array{Int32,1} LBADT::Array{Int32,1} LWDT::Array{Int32,1} LADT::Array{Int32,1} LVIDTS::Array{Int32,1} LALDTS::Array{Int32,1} LBEDTS::Array{Int32,1} LHEDTS::Array{Int32,1} LELDTS::Array{Int32,1} LBADTS::Array{Int32,1} LWDTS::Array{Int32,2} LADTS::Array{Int32,2} LFRPK::Array{Int32,1} KFRPL::Array{Int32,1} LFLAPF::Array{Int32,1} LPENGF::Array{Int32,1} LGUS1F::Array{Int32,1} LGUS2F::Array{Int32,1} LGUS3F::Array{Int32,1} LGUS4F::Array{Int32,1} VGI_FRP::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} AFORCE::Array{Float64,1} RFORCE::Array{Float64,1} EFORCE::Array{Float64,1} GFORCE::Array{Float64,1} TFORCE::Array{Float64,1} AMOMNT::Array{Float64,1} RMOMNT::Array{Float64,1} EMOMNT::Array{Float64,1} GMOMNT::Array{Float64,1} TMOMNT::Array{Float64,1} AFOR_Q::Array{Float64,3} AFOR_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} AFOR_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} AMOM_Q::Array{Float64,3} AMOM_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} AMOM_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} RFOR_Q::Array{Float64,3} RFOR_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} RFOR_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} RMOM_Q::Array{Float64,3} RMOM_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} RMOM_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} EFOR_Q::Array{Float64,3} EFOR_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} EFOR_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} EMOM_Q::Array{Float64,3} EMOM_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} EMOM_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GFOR_Q::Array{Float64,3} GFOR_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GFOR_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GMOM_Q::Array{Float64,3} GMOM_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GMOM_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} AFOR_UT::Array{Float64,3} AFOR_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} AMOM_UT::Array{Float64,3} AMOM_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} RFOR_UT::Array{Float64,3} RFOR_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} RMOM_UT::Array{Float64,3} RMOM_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} EFOR_UT::Array{Float64,3} EFOR_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} EMOM_UT::Array{Float64,3} EMOM_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GFOR_UT::Array{Float64,3} GFOR_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GMOM_UT::Array{Float64,3} GMOM_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} FAERO::Array{Float64,1} FAERO_Q::Array{Float64,3} FAERO_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} FAERO_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} FAERO_UT::Array{Float64,3} FAERO_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} MAERO::Array{Float64,1} MAERO_Q::Array{Float64,3} MAERO_GL::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} MAERO_FRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} MAERO_UT::Array{Float64,3} MAERO_GLT::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} DVENG::Array{Float64,2} XENG::Array{Float64,3} XENG_ANG::Array{Float64,3} RENG::Array{Float64,3} RENG_ANG::Array{Float64,3} VENG::Array{Float64,3} VENG_Q::Array{Float64,3} VENG_GL::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} FENG::Array{Float64,3} FENG_Q::Array{Float64,3} FENG_GL::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} MENG::Array{Float64,3} MENG_Q::Array{Float64,3} MENG_GL::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} MASS::Array{Float64,1} MASSP::Array{Float64,1} MASSB::Array{Float64,1} AREAB::Array{Float64,1} RCGXYZ0::Array{Float64,1} RMASST0::Array{Float64,2} RINERT0::Array{Float64,2} RCGXYZ::Array{Float64,2} RMASST::Array{Float64,3} RINERT::Array{Float64,3} PCGXYZ0::Array{Float64,1} PMASST0::Array{Float64,2} PINERT0::Array{Float64,2} PCGXYZ::Array{Float64,2} PMASST::Array{Float64,3} PINERT::Array{Float64,3} AMASST0::Array{Float64,2} AINERT0::Array{Float64,2} AMASST::Array{Float64,3} AINERT::Array{Float64,3} RCGXYZB0::Array{Float64,2} RMASSTB0::Array{Float64,3} AMASSTB0::Array{Float64,3} RINERTB0::Array{Float64,3} AINERTB0::Array{Float64,3} RCGXYZB::Array{Float64,3} RMASSTB::Array{Float64,4} RINERTB::Array{Float64,4} AMASSTB::Array{Float64,4} AINERTB::Array{Float64,4} QPYLO::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} TB::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} QB::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} QBT::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} TJOIN::Array{Float64,2} TGROU::Array{Float64,1} SBRK::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} TBFIL::Array{Float64,1} QBFIL::Array{Float64,1} QBTFIL::Array{Float64,1} ANGJ::Array{Float64,2} ANGJM::Array{Float64,2} MOMJ::Array{Float64,2} HJAX::Array{Float64,2} NB::OffsetArrays.OffsetArray{Int32,2,Array{Int32,2}} KBTYPE::Array{Int32,1} KBNUM::Array{Int32,1} KBPYLO::Array{Int32,1} KBJOIN::Array{Int32,2} KBGROU::Array{Int32,1} NPYLO::Array{Int32,1} ISPYLO::Array{Int32,1} IPYLO::Array{Int32,1} KPTYPE::Array{Int32,1} ISSENS::Array{Int32,1} ISENS::Array{Int32,1} NJOIN::Array{Int32,1} ISJOIN::Array{Int32,2} IJOIN::Array{Int32,2} KJTYPE::Array{Int32,1} NGROU::Array{Int32,1} ISGROU::Array{Int32,1} IGROU::Array{Int32,1} KGTYPE::Array{Int32,1} NCORN::Array{Int32,1} ISCORN::Array{Int32,1} ICORN::Array{Int32,1} JBCORN::Array{Int32,1} IBCORN::Array{Int32,1} NBRK::Array{Int32,1} IBRK::OffsetArrays.OffsetArray{Int32,2,Array{Int32,2}} JFIL::Array{Int32,1} ISFIL::Array{Int32,1} NBFIL::Array{Int32,1} NANGJ::Array{Int32,1} QSNSP::Array{Float64,3} QSENS::Array{Float64,3} QSENS_Q::Array{Float64,3} QSENS_QT::Array{Float64,3} QSENS_GL::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} QSENS_GLT::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} QSENS_FRP::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} TPMAT::Array{Float64,3} VIWIND::Array{Float64,1} ALWIND::Array{Float64,1} BEWIND::Array{Float64,1} VIW_VEL::Array{Float64,1} ALW_VEL::Array{Float64,1} BEW_VEL::Array{Float64,1} Q::Array{Float64,3} Q0::Array{Float64,2} QPAR::Array{Float64,2} S::Array{Float64,1} THET::Array{Float64,1} SPLT::Array{Float64,1} TBI::Array{Float64,1} SCP::Array{Float64,1} XYZTFZ::Array{Float64,2} XYZTFZI::Array{Float64,2} PARAM::Array{Float64,2} AN::Array{Float64,2} PSPEC::Array{Float64,2} PSPECSET::Array{Float64,2} WFLAP::Array{Float64,2} WPENG::Array{Float64,2} QJOIN::Array{Float64,3} QPNT::Array{Float64,3} DTIME::Array{Float64,1} TIME::Array{Float64,1} QTWT::OffsetArrays.OffsetArray{Float64,1,Array{Float64,1}} RDOT::Array{Float64,2} UDOT::Array{Float64,2} PSDOT::Array{Float64,1} ANDOT::Array{Float64,1} QSDOT::Array{Float64,2} AKGUST::Array{Float64,2} ALGUST::Array{Float64,2} VFGUST::Array{Float64,3} NPOINT::Array{Int32,1} IPOINT::Array{Int32,1} NPTIME::Array{Int32,1} IPNTD::Array{Int32,1} IPNTVL::Array{Int32,1} KCSET::Array{Int32,1} IQEXP::Array{Int32,3} IPPAR::Array{Int32,2} IPPARSET::Array{Int32,2} ANF::Array{Float64,2} RCCORE::Array{Float64,1} VIB::Array{Float64,2} WIB::Array{Float64,2} VEB::Array{Float64,2} VIC::Array{Float64,2} WIC::Array{Float64,2} VEC::Array{Float64,2} VIP::Array{Float64,2} WIP::Array{Float64,2} VEP::Array{Float64,2} VIB_MA::Array{Float64,2} WIB_MA::Array{Float64,2} VIC_MA::Array{Float64,2} WIC_MA::Array{Float64,2} VIP_MA::Array{Float64,2} WIP_MA::Array{Float64,2} VIB_AL::Array{Float64,2} WIB_AL::Array{Float64,2} VEB_AL::Array{Float64,2} VIC_AL::Array{Float64,2} WIC_AL::Array{Float64,2} VEC_AL::Array{Float64,2} VIP_AL::Array{Float64,2} WIP_AL::Array{Float64,2} VEP_AL::Array{Float64,2} VIB_BE::Array{Float64,2} WIB_BE::Array{Float64,2} VEB_BE::Array{Float64,2} VIC_BE::Array{Float64,2} WIC_BE::Array{Float64,2} VEC_BE::Array{Float64,2} VIP_BE::Array{Float64,2} WIP_BE::Array{Float64,2} VEP_BE::Array{Float64,2} VIB_POS::Array{Float64,3} WIB_POS::Array{Float64,3} VIC_POS::Array{Float64,3} WIC_POS::Array{Float64,3} VIP_POS::Array{Float64,3} WIP_POS::Array{Float64,3} VIB_EUL::Array{Float64,3} WIB_EUL::Array{Float64,3} VIC_EUL::Array{Float64,3} WIC_EUL::Array{Float64,3} VIP_EUL::Array{Float64,3} WIP_EUL::Array{Float64,3} VIB_AN::Array{Float64,3} WIB_VI::Array{Float64,2} VIC_AN::Array{Float64,3} WIC_VI::Array{Float64,2} VIP_AN::Array{Float64,3} WIP_VI::Array{Float64,2} VEB_XENG::Array{Float64,4} VEB_RENG::Array{Float64,4} VEC_XENG::Array{Float64,4} VEC_RENG::Array{Float64,4} VEP_XENG::Array{Float64,4} VEP_RENG::Array{Float64,4} VEB_VENG::Array{Float64,4} VEC_VENG::Array{Float64,4} VEP_VENG::Array{Float64,4} VEB_FENG::Array{Float64,4} VEB_MENG::Array{Float64,4} VEC_FENG::Array{Float64,4} VEC_MENG::Array{Float64,4} VEP_FENG::Array{Float64,4} VEP_MENG::Array{Float64,4} VIB_AN_MA::Array{Float64,3} WIB_VI_MA::Array{Float64,2} VIC_AN_MA::Array{Float64,3} WIC_VI_MA::Array{Float64,2} VIP_AN_MA::Array{Float64,3} WIP_VI_MA::Array{Float64,2} VIB_AN_AL::Array{Float64,3} WIB_VI_AL::Array{Float64,2} VIC_AN_AL::Array{Float64,3} WIC_VI_AL::Array{Float64,2} VIP_AN_AL::Array{Float64,3} WIP_VI_AL::Array{Float64,2} VIB_AN_BE::Array{Float64,3} WIB_VI_BE::Array{Float64,2} VIC_AN_BE::Array{Float64,3} WIC_VI_BE::Array{Float64,2} VIP_AN_BE::Array{Float64,3} WIP_VI_BE::Array{Float64,2} VIB_AN_POS::Array{Float64,4} WIB_VI_POS::Array{Float64,3} VIC_AN_POS::Array{Float64,4} WIC_VI_POS::Array{Float64,3} VIP_AN_POS::Array{Float64,4} WIP_VI_POS::Array{Float64,3} VIB_AN_EUL::Array{Float64,4} WIB_VI_EUL::Array{Float64,3} VIC_AN_EUL::Array{Float64,4} WIC_VI_EUL::Array{Float64,3} VIP_AN_EUL::Array{Float64,4} WIP_VI_EUL::Array{Float64,3} VEB_GL::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} VEC_GL::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} VEP_GL::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} AJSAV::Array{Float64,3} CJSAV::Array{Float64,3} RJSAV::Array{Float64,3} ATJSAV::Array{Float64,3} CTJSAV::Array{Float64,3} RTJSAV::Array{Float64,3} RFRPJSAV::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} A::Array{Float64,3} B::Array{Float64,3} C::Array{Float64,3} R::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} AT::Array{Float64,3} BT::Array{Float64,3} CT::Array{Float64,3} RT::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} RFRP::OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}} GVSYS::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GPSYS::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GFSYS::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GVSYST::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GPSYST::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GFSYST::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GVQ::Array{Float64,2} GPQ::Array{Float64,2} GFQ::Array{Float64,2} GVQT::Array{Float64,2} GPQT::Array{Float64,2} GFQT::Array{Float64,2} GVFRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GPFRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GFFRP::OffsetArrays.OffsetArray{Float64,2,Array{Float64,2}} GFLSQ::Array{Float64,2} WLSQ::Array{Float64,1} ZA::Array{ComplexF64,3} ZB::Array{ComplexF64,3} ZC::Array{ComplexF64,3} ZR::OffsetArrays.OffsetArray{ComplexF64,3,Array{ComplexF64,3}} ZGVSYS::OffsetArrays.OffsetArray{ComplexF64,2,Array{ComplexF64,2}} ZGPSYS::OffsetArrays.OffsetArray{ComplexF64,2,Array{ComplexF64,2}} ZGFSYS::OffsetArrays.OffsetArray{ComplexF64,2,Array{ComplexF64,2}} ZGVQ::Array{ComplexF64,2} ZGPQ::Array{ComplexF64,2} ZGFQ::Array{ComplexF64,2} NGVQ::Array{Int32,1} KGVQ::Array{Int32,1} IGVQ::Array{Int32,1} NGPQ::Array{Int32,1} KGPQ::Array{Int32,1} IGPQ::Array{Int32,1} NGFQ::Array{Int32,1} KGFQ::Array{Int32,1} IGFQ::Array{Int32,1} NGVQZ::Array{Int32,1} KGVQZ::Array{Int32,1} IGVQZ::Array{Int32,1} NGPQZ::Array{Int32,1} KGPQZ::Array{Int32,1} IGPQZ::Array{Int32,1} NGFQZ::Array{Int32,1} KGFQZ::Array{Int32,1} IGFQZ::Array{Int32,1} NGVQ1::Array{Int32,1} NGPQ1::Array{Int32,1} NGFQ1::Array{Int32,1} IGVPIV::Array{Int32,1} IGPPIV::Array{Int32,1} IGFPIV::Array{Int32,1} ITER::Array{Int32,1} ITMAX::Array{Int32,1} NEIGIT::Array{Int32,1} EPS::Array{Float64,1} DELRMS::Array{Float64,1} DELMAX::Array{Float64,1} DGLOB::OffsetArrays.OffsetArray{Float64,1,Array{Float64,1}} DQ::Array{Float64,2} ARGP1::Array{Cchar,1} ARGP2::Array{Cchar,1} PREFIX::Array{Cchar,1} NAME::Array{Cchar,1} ANAME::Array{Array{Cchar,1}} BNAME::Array{Array{Cchar,1}} CNAME::Array{Array{Cchar,1}} CUNIT::Array{Array{Cchar,1}} CKEY::Array{Array{Cchar,1}} RNAME::Array{Array{Cchar,1}} RUNIT::Array{Array{Cchar,1}} RKEY::Array{Array{Cchar,1}} IDEV::Array{Int32,1} IDEVRP::Array{Int32,1} IDEVM::Array{Int32,1} IPSLU::Array{Int32,1} NCOLOR::Array{Int32,1} NBFREQ::Array{Int32,1} NBEIGEN::Array{Int32,1} NFRAME::Array{Int32,1} IVGCUT::Array{Int32,1} IVGFUN::Array{Int32,1} ILINE::Array{Int32,1} ICOLOR::Array{Int32,1} ICOLB::Array{Int32,1} ICOLF::Array{Int32,1} LPLOT::Array{Int32,1} LPGRID::Array{Int32,1} LCEDPL::Array{Int32,1} LSVMOV::Array{Int32,1} SCRNFL::Array{Float64,1} SCRNFP::Array{Float64,1} SIZE::Array{Float64,1} CSIZ::Array{Float64,1} XWIND::Array{Float64,1} YWIND::Array{Float64,1} AZIMOB::Array{Float64,1} ELEVOB::Array{Float64,1} ROBINV::Array{Float64,1} XYZUP::Array{Float64,1} WAKLFR::Array{Float64,1} SAXLFR::Array{Float64,1} SLOMOF::Array{Float64,1} EIGENF::Array{Float64,1} TMOVIE::Array{Float64,1} TIME1::Array{Float64,1} TIME2::Array{Float64,1} DPHASE::Array{Float64,1} SCALEF::Array{Float64,1} DTDUMP::Array{Float64,1} BFREQ1::Array{Float64,1} BFREQ2::Array{Float64,1} VGCXYZ::Array{Float64,1} VGCLIM::Array{Float64,2} CL_VEL::Array{Float64,2} CM_VEL::Array{Float64,2} CN_VEL::Array{Float64,2} CR_VEL::Array{Float64,2} CL_ROT::Array{Float64,2} CM_ROT::Array{Float64,2} CN_ROT::Array{Float64,2} CR_ROT::Array{Float64,2} FOR_VEL::Array{Float64,3} MOM_VEL::Array{Float64,3} FOR_ROT::Array{Float64,3} MOM_ROT::Array{Float64,3} FOR_FLAP::Array{Float64,3} MOM_FLAP::Array{Float64,3} FOR_PENG::Array{Float64,3} MOM_PENG::Array{Float64,3} JEDIT::Array{Int32,1} ISEDIT::Array{Int32,1} LSLOPE::Array{Int32,1} LEDSYM::OffsetArrays.OffsetArray{Int32,2,Array{Int32,2}} EDPAR::Array{Float64,1} TOFFE::Array{Float64,1} TFACE::Array{Float64,1} QOFFE::Array{Float64,1} QFACE::Array{Float64,1} TBMIN::Array{Float64,1} TBMAX::Array{Float64,1} DELTB::Array{Float64,1} QBMIN::Array{Float64,1} QBMAX::Array{Float64,1} DELQB::Array{Float64,1} IGUST::Array{Int32,1} VGCON::Array{Float64,1} function ASWING_s() as_con = cglobal((:as_con_, libaswing), Float64); as_con_idx = as_con PI = unsafe_wrap(Array, as_con_idx, 1); as_con_idx += sizeof(Float64) DTOR = unsafe_wrap(Array, as_con_idx, 1); as_con_idx += sizeof(Float64) VERSION = unsafe_wrap(Array, as_con_idx, 1) as_par = cglobal((:as_par_, libaswing), Float64); as_par_idx = as_par STIPL = unsafe_wrap(Array, as_par_idx, NBX); as_par_idx += sizeof(Float64)*NBX STIPR = unsafe_wrap(Array, as_par_idx, NBX); as_par_idx += sizeof(Float64)*NBX TBTIPL = unsafe_wrap(Array, as_par_idx, NBX); as_par_idx += sizeof(Float64)*NBX TBTIPR = unsafe_wrap(Array, as_par_idx, NBX); as_par_idx += sizeof(Float64)*NBX MACHPG = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) GEEW = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) SREF = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) CREF = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) BREF = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) XYZREF = unsafe_wrap(Array, as_par_idx, (3,3)); as_par_idx += sizeof(Float64)*3*3 BGREFX = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) BGREFY = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) BGREFZ = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) ULCON = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) GRNORM = unsafe_wrap(Array, as_par_idx, 3); as_par_idx += sizeof(Float64)*3 VSOSL = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) VSO_SI = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) VSOSL_SI = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) RHOSL = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) RHO_SI = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) RHOSL_SI = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) RMUSL = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) RMU_SI = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) RMUSL_SI = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) EXPII = unsafe_wrap(Array, as_par_idx, 1); as_par_idx += sizeof(Float64) EXPNN = unsafe_wrap(Array, as_par_idx, 1) as_log = cglobal((:as_log_, libaswing), Int32); as_log_idx = as_log LALTKM = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) AUTSCL = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LTERSE = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LVLFIX = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LAELAG = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LLEVEC = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) STEADY = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) CONLAW = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) CONSET = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LFGUST = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LROMFR = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LVISEN = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LLGROU = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LLREFP = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LAXPLT = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LELIST = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LENGLI = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LESPEC = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LNODES = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LUNSWP = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LPLRIB = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LPLZLO = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LPLBAR = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LFRPAN = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LFRROT = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LGEOM = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LLRHS = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LVAIC = unsafe_wrap(Array, as_log_idx, 1); as_log_idx += sizeof(Int32) LWSET = unsafe_wrap(Array, as_log_idx, NBX); as_log_idx += sizeof(Int32)*NBX LCSET = unsafe_wrap(Array, as_log_idx, NSETX); as_log_idx += sizeof(Int32)*NSETX LQBDEF = unsafe_wrap(Array, as_log_idx, (JBX, NBX)); as_log_idx += sizeof(Int32)*JBX*NBX lbsymm = unsafe_wrap(Array, as_log_idx, (JBX+1, NBX)); as_log_idx += sizeof(Int32)*(JBX+1)*NBX LBSYMM = OffsetArrays.OffsetArray(lbsymm,0:JBX,1:NBX) LSFLAP = unsafe_wrap(Array, as_log_idx, NFLPX); as_log_idx += sizeof(Int32)*NFLPX LSPENG = unsafe_wrap(Array, as_log_idx, NENGX); as_log_idx += sizeof(Int32)*NENGX LSSENS = unsafe_wrap(Array, as_log_idx, NSENX); as_log_idx += sizeof(Int32)*NSENX LQINI = unsafe_wrap(Array, as_log_idx, NPNTX); as_log_idx += sizeof(Int32)*NPNTX LAINI = unsafe_wrap(Array, as_log_idx, NPNTX); as_log_idx += sizeof(Int32)*NPNTX LCONV = unsafe_wrap(Array, as_log_idx, NPNTX); as_log_idx += sizeof(Int32)*NPNTX LMACH = unsafe_wrap(Array, as_log_idx, NPNTX); as_log_idx += sizeof(Int32)*NPNTX PSTEADY = unsafe_wrap(Array, as_log_idx, NPNTX); as_log_idx += sizeof(Int32)*NPNTX LPBEAM = unsafe_wrap(Array, as_log_idx, NBX); as_log_idx += sizeof(Int32)*NBX LPWAKE = unsafe_wrap(Array, as_log_idx, NBX); as_log_idx += sizeof(Int32)*NBX LDCON = unsafe_wrap(Array, as_log_idx, NDDIM); as_log_idx += sizeof(Int32)*NDDIM LUCON = unsafe_wrap(Array, as_log_idx, NUDIM); as_log_idx += sizeof(Int32)*NUDIM LQCON = unsafe_wrap(Array, as_log_idx, (NQDIM, NSENX)) as_int = cglobal((:as_int_, libaswing), Int32); as_int_idx = as_int NQ = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NCP = unsafe_wrap(Array, as_int_idx, NBX); as_int_idx += sizeof(Int32)*NBX IBEAM = unsafe_wrap(Array, as_int_idx, NBX); as_int_idx += sizeof(Int32)*NBX IICON = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) II = unsafe_wrap(Array, as_int_idx, NBX); as_int_idx += sizeof(Int32)*NBX IFRST = unsafe_wrap(Array, as_int_idx, NBX); as_int_idx += sizeof(Int32)*NBX ILAST = unsafe_wrap(Array, as_int_idx, NBX); as_int_idx += sizeof(Int32)*NBX IITOT = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NNCON = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NN = unsafe_wrap(Array, as_int_idx, NBX); as_int_idx += sizeof(Int32)*NBX NFRST = unsafe_wrap(Array, as_int_idx, NBX); as_int_idx += sizeof(Int32)*NBX NLAST = unsafe_wrap(Array, as_int_idx, NBX); as_int_idx += sizeof(Int32)*NBX NNTOT = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) KEQ0 = unsafe_wrap(Array, as_int_idx, (12, NBX)); as_int_idx += sizeof(Int32)*12*NBX KEQ = unsafe_wrap(Array, as_int_idx, (12, IIX)); as_int_idx += sizeof(Int32)*12*IIX NRHS = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NGVAR = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NGPAR = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NGFOR = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NGFEQ = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NFRP = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NFRPF = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NFRPR = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NBEAM = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NFUSE = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NSURF = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) ICOORD = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) IENGTYP = unsafe_wrap(Array, as_int_idx, NENGX); as_int_idx += sizeof(Int32)*NENGX IGUSDIR = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NXGUST = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NYGUST = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NZGUST = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) NFGUST = unsafe_wrap(Array, as_int_idx, 1); as_int_idx += sizeof(Int32) IGRIM = unsafe_wrap(Array, as_int_idx, NPNTX) as_gll = cglobal((:as_gll_, libaswing), Int32); as_gll_idx = as_gll LRES = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LQJOIN = unsafe_wrap(Array, as_gll_idx, (12, NJX)); as_gll_idx += sizeof(Int32)*12*NJX LAN = unsafe_wrap(Array, as_gll_idx, NNX); as_gll_idx += sizeof(Int32)*NNX LHEAD = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LELEV = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LBANK = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LVAC = unsafe_wrap(Array, as_gll_idx, 3); as_gll_idx += sizeof(Int32)*3 LRAC = unsafe_wrap(Array, as_gll_idx, 3); as_gll_idx += sizeof(Int32)*3 LVEL = unsafe_wrap(Array, as_gll_idx, 3); as_gll_idx += sizeof(Int32)*3 LROT = unsafe_wrap(Array, as_gll_idx, 3); as_gll_idx += sizeof(Int32)*3 LPOS = unsafe_wrap(Array, as_gll_idx, 3); as_gll_idx += sizeof(Int32)*3 LFLAP = unsafe_wrap(Array, as_gll_idx, NFLPX); as_gll_idx += sizeof(Int32)*NFLPX LPENG = unsafe_wrap(Array, as_gll_idx, NENGX); as_gll_idx += sizeof(Int32)*NENGX LVIDT = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LALDT = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LBEDT = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LHEDT = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LELDT = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LBADT = unsafe_wrap(Array, as_gll_idx, 1); as_gll_idx += sizeof(Int32) LWDT = unsafe_wrap(Array, as_gll_idx, 3); as_gll_idx += sizeof(Int32)*3 LADT = unsafe_wrap(Array, as_gll_idx, 3); as_gll_idx += sizeof(Int32)*3 LVIDTS = unsafe_wrap(Array, as_gll_idx, NSENX); as_gll_idx += sizeof(Int32)*NSENX LALDTS = unsafe_wrap(Array, as_gll_idx, NSENX); as_gll_idx += sizeof(Int32)*NSENX LBEDTS = unsafe_wrap(Array, as_gll_idx, NSENX); as_gll_idx += sizeof(Int32)*NSENX LHEDTS = unsafe_wrap(Array, as_gll_idx, NSENX); as_gll_idx += sizeof(Int32)*NSENX LELDTS = unsafe_wrap(Array, as_gll_idx, NSENX); as_gll_idx += sizeof(Int32)*NSENX LBADTS = unsafe_wrap(Array, as_gll_idx, NSENX); as_gll_idx += sizeof(Int32)*NSENX LWDTS = unsafe_wrap(Array, as_gll_idx, (3,NSENX)); as_gll_idx += sizeof(Int32)*NSENX*3 LADTS = unsafe_wrap(Array, as_gll_idx, (3,NSENX)); as_fpi = cglobal((:as_fpi_, libaswing), Int32); as_fpi_idx = as_fpi LFRPK = unsafe_wrap(Array, as_fpi_idx, NFRPX); as_fpi_idx += sizeof(Int32)*NFRPX KFRPL = unsafe_wrap(Array, as_fpi_idx, NFRLX); as_fpi_idx += sizeof(Int32)*NFRLX LFLAPF = unsafe_wrap(Array, as_fpi_idx, NFLPX); as_fpi_idx += sizeof(Int32)*NFLPX LPENGF = unsafe_wrap(Array, as_fpi_idx, NENGX); as_fpi_idx += sizeof(Int32)*NENGX LGUS1F = unsafe_wrap(Array, as_fpi_idx, NGUSX); as_fpi_idx += sizeof(Int32)*NGUSX LGUS2F = unsafe_wrap(Array, as_fpi_idx, NGUSX); as_fpi_idx += sizeof(Int32)*NGUSX LGUS3F = unsafe_wrap(Array, as_fpi_idx, NGUSX); as_fpi_idx += sizeof(Int32)*NGUSX LGUS4F = unsafe_wrap(Array, as_fpi_idx, NGUSX); as_fpr = cglobal((:as_fpr_, libaswing), Float64); as_fpr_idx = as_fpr vgi_frp = unsafe_wrap(Array, as_fpr_idx, (3, IIX, NFRLX+1)) VGI_FRP = OffsetArrays.OffsetArray(vgi_frp,1:3, 1:IIX, 0:NFRLX) as_frc = cglobal((:as_frc_, libaswing), Float64); as_frc_idx = as_frc AFORCE = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 RFORCE = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 EFORCE = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 GFORCE = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 TFORCE = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 AMOMNT = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 RMOMNT = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 EMOMNT = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 GMOMNT = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 TMOMNT = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 AFOR_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX afor_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) AFOR_GL = OffsetArrays.OffsetArray(afor_gl, 1:3, 0:NGLX) afor_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) AFOR_FRP = OffsetArrays.OffsetArray(afor_frp, 1:3, 0:NFRLX) AMOM_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX amom_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) AMOM_GL = OffsetArrays.OffsetArray(amom_gl, 1:3, 0:NGLX) amom_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) AMOM_FRP = OffsetArrays.OffsetArray(amom_frp, 1:3, 0:NFRLX) RFOR_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX rfor_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) RFOR_GL = OffsetArrays.OffsetArray(rfor_gl, 1:3, 0:NGLX) rfor_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) RFOR_FRP = OffsetArrays.OffsetArray(rfor_frp, 1:3, 0:NFRLX) RMOM_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX rmom_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) RMOM_GL = OffsetArrays.OffsetArray(rmom_gl, 1:3, 0:NGLX) rmom_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) RMOM_FRP = OffsetArrays.OffsetArray(rmom_frp, 1:3, 0:NFRLX) EFOR_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX efor_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) EFOR_GL = OffsetArrays.OffsetArray(efor_gl, 1:3, 0:NGLX) efor_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) EFOR_FRP = OffsetArrays.OffsetArray(efor_frp, 1:3, 0:NFRLX) EMOM_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX emom_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) EMOM_GL = OffsetArrays.OffsetArray(emom_gl, 1:3, 0:NGLX) emom_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) EMOM_FRP = OffsetArrays.OffsetArray(emom_frp, 1:3, 0:NFRLX) GFOR_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX gfor_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) GFOR_GL = OffsetArrays.OffsetArray(gfor_gl, 1:3, 0:NGLX) gfor_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) GFOR_FRP = OffsetArrays.OffsetArray(gfor_frp, 1:3, 0:NFRLX) GMOM_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX gmom_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) GMOM_GL = OffsetArrays.OffsetArray(gmom_gl, 1:3, 0:NGLX) gmom_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) GMOM_FRP = OffsetArrays.OffsetArray(gmom_frp, 1:3, 0:NFRLX) AFOR_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX afor_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) AFOR_GLT = OffsetArrays.OffsetArray(afor_glt, 1:3, 0:NGLX) AMOM_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX amom_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) AMOM_GLT = OffsetArrays.OffsetArray(amom_glt, 1:3, 0:NGLX) RFOR_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX rfor_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) RFOR_GLT = OffsetArrays.OffsetArray(rfor_glt, 1:3, 0:NGLX) RMOM_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX rmom_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) RMOM_GLT = OffsetArrays.OffsetArray(rmom_glt, 1:3, 0:NGLX) EFOR_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX efor_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) EFOR_GLT = OffsetArrays.OffsetArray(efor_glt, 1:3, 0:NGLX) EMOM_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX emom_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) EMOM_GLT = OffsetArrays.OffsetArray(emom_glt, 1:3, 0:NGLX) GFOR_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX gfor_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) GFOR_GLT = OffsetArrays.OffsetArray(gfor_glt, 1:3, 0:NGLX) GMOM_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX gmom_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) GMOM_GLT = OffsetArrays.OffsetArray(gmom_glt, 1:3, 0:NGLX) FAERO = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 FAERO_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX faero_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) FAERO_GL = OffsetArrays.OffsetArray(faero_gl, 1:3, 0:NGLX) faero_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) FAERO_FRP = OffsetArrays.OffsetArray(faero_frp, 1:3, 0:NFRLX) FAERO_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX faero_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) FAERO_GLT = OffsetArrays.OffsetArray(faero_glt, 1:3, 0:NGLX) MAERO = unsafe_wrap(Array, as_frc_idx, 3); as_frc_idx += sizeof(Float64)*3 MAERO_Q = unsafe_wrap(Array, as_frc_idx, (3, 18, IIX)); as_frc_idx += sizeof(Float64)*3*18*IIX maero_gl = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); as_frc_idx += sizeof(Float64)*3*(NGLX+1) MAERO_GL = OffsetArrays.OffsetArray(maero_gl, 1:3, 0:NGLX) maero_frp = unsafe_wrap(Array, as_frc_idx, (3, NFRLX+1)); as_frc_idx += sizeof(Float64)*3*(NFRLX+1) MAERO_FRP = OffsetArrays.OffsetArray(maero_frp, 1:3, 0:NFRLX) MAERO_UT = unsafe_wrap(Array, as_frc_idx, (3, 6, IIX)); as_frc_idx += sizeof(Float64)*3*6*IIX maero_glt = unsafe_wrap(Array, as_frc_idx, (3, NGLX+1)); MAERO_GLT = OffsetArrays.OffsetArray(maero_glt, 1:3, 0:NGLX) as_eng = cglobal((:as_eng_, libaswing), Float64); as_eng_idx = as_eng DVENG = unsafe_wrap(Array, as_eng_idx, (NPX, NPNTX)); as_eng_idx += sizeof(Float64)*NPX*NPNTX XENG = unsafe_wrap(Array, as_eng_idx, (3, NPX, NPNTX)); as_eng_idx += sizeof(Float64)*3*NPX*NPNTX XENG_ANG = unsafe_wrap(Array, as_eng_idx, (3, 3, NPX)); as_eng_idx += sizeof(Float64)*3*3*NPX RENG = unsafe_wrap(Array, as_eng_idx, (3, NPX, NPNTX)); as_eng_idx += sizeof(Float64)*3*NPX*NPNTX RENG_ANG = unsafe_wrap(Array, as_eng_idx, (3, 3, NPX)); as_eng_idx += sizeof(Float64)*3*3*NPX VENG = unsafe_wrap(Array, as_eng_idx, (3, NPX, NPNTX)); as_eng_idx += sizeof(Float64)*3*NPX*NPNTX VENG_Q = unsafe_wrap(Array, as_eng_idx, (3, 18, NPX)); as_eng_idx += sizeof(Float64)*3*18*NPX veng_gl = unsafe_wrap(Array, as_eng_idx, (3, NGLX+1, NPX)); as_eng_idx += sizeof(Float64)*3*(NGLX+1)*NPX VENG_GL = OffsetArrays.OffsetArray(veng_gl, 1:3, 0:NGLX, 1:NPX) FENG = unsafe_wrap(Array, as_eng_idx, (3, NPX, NPNTX)); as_eng_idx += sizeof(Float64)*3*NPX*NPNTX FENG_Q = unsafe_wrap(Array, as_eng_idx, (3, 18, NPX)); as_eng_idx += sizeof(Float64)*3*18*NPX feng_gl = unsafe_wrap(Array, as_eng_idx, (3, NGLX+1, NPX)); as_eng_idx += sizeof(Float64)*3*(NGLX+1)*NPX FENG_GL = OffsetArrays.OffsetArray(feng_gl, 1:3, 0:NGLX, 1:NPX) MENG = unsafe_wrap(Array, as_eng_idx, (3, NPX, NPNTX)); as_eng_idx += sizeof(Float64)*3*NPX*NPNTX MENG_Q = unsafe_wrap(Array, as_eng_idx, (3, 18, NPX)); as_eng_idx += sizeof(Float64)*3*18*NPX meng_gl = unsafe_wrap(Array, as_eng_idx, (3, NGLX+1, NPX)) MENG_GL = OffsetArrays.OffsetArray(meng_gl, 1:3, 0:NGLX, 1:NPX) as_awt = cglobal((:as_awt_, libaswing), Float64); as_awt_idx = as_awt MASS = unsafe_wrap(Array, as_awt_idx, 1); as_awt_idx += sizeof(Float64) MASSP = unsafe_wrap(Array, as_awt_idx, 1); as_awt_idx += sizeof(Float64) MASSB = unsafe_wrap(Array, as_awt_idx, NBX); as_awt_idx += sizeof(Float64)*NBX AREAB = unsafe_wrap(Array, as_awt_idx, NBX); as_awt_idx += sizeof(Float64)*NBX RCGXYZ0 = unsafe_wrap(Array, as_awt_idx, 3); as_awt_idx += sizeof(Float64)*3 RMASST0 = unsafe_wrap(Array, as_awt_idx, (3,3)); as_awt_idx += sizeof(Float64)*3*3 RINERT0 = unsafe_wrap(Array, as_awt_idx, (3,3)); as_awt_idx += sizeof(Float64)*3*3 RCGXYZ = unsafe_wrap(Array, as_awt_idx, (3,NPNTX)); as_awt_idx += sizeof(Float64)*3*NPNTX RMASST = unsafe_wrap(Array, as_awt_idx, (3,3,NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NPNTX RINERT = unsafe_wrap(Array, as_awt_idx, (3,3,NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NPNTX PCGXYZ0 = unsafe_wrap(Array, as_awt_idx, 3); as_awt_idx += sizeof(Float64)*3 PMASST0 = unsafe_wrap(Array, as_awt_idx, (3,3)); as_awt_idx += sizeof(Float64)*3*3 PINERT0 = unsafe_wrap(Array, as_awt_idx, (3,3)); as_awt_idx += sizeof(Float64)*3*3 PCGXYZ = unsafe_wrap(Array, as_awt_idx, (3,NPNTX)); as_awt_idx += sizeof(Float64)*3*NPNTX PMASST = unsafe_wrap(Array, as_awt_idx, (3,3,NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NPNTX PINERT = unsafe_wrap(Array, as_awt_idx, (3,3,NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NPNTX AMASST0 = unsafe_wrap(Array, as_awt_idx, (3,3)); as_awt_idx += sizeof(Float64)*3*3 AINERT0 = unsafe_wrap(Array, as_awt_idx, (3,3)); as_awt_idx += sizeof(Float64)*3*3 AMASST = unsafe_wrap(Array, as_awt_idx, (3,3,NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NPNTX AINERT = unsafe_wrap(Array, as_awt_idx, (3,3,NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NPNTX RCGXYZB0 = unsafe_wrap(Array, as_awt_idx, (3, NBX)); as_awt_idx += sizeof(Float64)*3*NBX RMASSTB0 = unsafe_wrap(Array, as_awt_idx, (3, 3, NBX)); as_awt_idx += sizeof(Float64)*3*3*NBX AMASSTB0 = unsafe_wrap(Array, as_awt_idx, (3, 3, NBX)); as_awt_idx += sizeof(Float64)*3*3*NBX RINERTB0 = unsafe_wrap(Array, as_awt_idx, (3, 3, NBX)); as_awt_idx += sizeof(Float64)*3*3*NBX AINERTB0 = unsafe_wrap(Array, as_awt_idx, (3, 3, NBX)); as_awt_idx += sizeof(Float64)*3*3*NBX RCGXYZB = unsafe_wrap(Array, as_awt_idx, (3, NBX, NPNTX)); as_awt_idx += sizeof(Float64)*3*NBX*NPNTX RMASSTB = unsafe_wrap(Array, as_awt_idx, (3, 3, NBX, NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NBX*NPNTX AMASSTB = unsafe_wrap(Array, as_awt_idx, (3, 3, NBX, NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NBX*NPNTX RINERTB = unsafe_wrap(Array, as_awt_idx, (3, 3, NBX, NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NBX*NPNTX AINERTB = unsafe_wrap(Array, as_awt_idx, (3, 3, NBX, NPNTX)); as_awt_idx += sizeof(Float64)*3*3*NBX*NPNTX as_inr = cglobal((:as_inr_, libaswing), Float64); as_inr_idx = as_inr qpylo = unsafe_wrap(Array, as_inr_idx, (KPX+1, NPX)); as_inr_idx += sizeof(Float64)*(KPX+1)*NPX QPYLO = OffsetArrays.OffsetArray(qpylo, 0:KPX, 1:NPX) tb = unsafe_wrap(Array, as_inr_idx, (IBX, JBX+1, NBX)); as_inr_idx += sizeof(Float64)*IBX*(JBX+1)*NBX TB = OffsetArrays.OffsetArray(tb, 1:IBX, 0:JBX, 1:NBX) qb = unsafe_wrap(Array, as_inr_idx, (IBX, JBX+1, NBX)); as_inr_idx += sizeof(Float64)*IBX*(JBX+1)*NBX QB = OffsetArrays.OffsetArray(qb, 1:IBX, 0:JBX, 1:NBX) qbt = unsafe_wrap(Array, as_inr_idx, (IBX, JBX+1, NBX)); as_inr_idx += sizeof(Float64)*IBX*(JBX+1)*NBX QBT = OffsetArrays.OffsetArray(qbt, 1:IBX, 0:JBX, 1:NBX) TJOIN = unsafe_wrap(Array, as_inr_idx, (2, NJX)); as_inr_idx += sizeof(Float64)*2*NJX TGROU = unsafe_wrap(Array, as_inr_idx, NGX); as_inr_idx += sizeof(Float64)*NGX sbrk = unsafe_wrap(Array, as_inr_idx, (NBRKX+2, NBX)); as_inr_idx += sizeof(Float64)*(NBRKX+2)*NBX SBRK = OffsetArrays.OffsetArray(sbrk,0:NBRKX+1,1:NBX) TBFIL = unsafe_wrap(Array, as_inr_idx, IBX); as_inr_idx += sizeof(Float64)*IBX QBFIL = unsafe_wrap(Array, as_inr_idx, IBX); as_inr_idx += sizeof(Float64)*IBX QBTFIL = unsafe_wrap(Array, as_inr_idx, IBX); as_inr_idx += sizeof(Float64)*IBX ANGJ = unsafe_wrap(Array, as_inr_idx, (NAJX, NJX)); as_inr_idx += sizeof(Float64)*NAJX*NJX ANGJM = unsafe_wrap(Array, as_inr_idx, (NAJX, NJX)); as_inr_idx += sizeof(Float64)*NAJX*NJX MOMJ = unsafe_wrap(Array, as_inr_idx, (NAJX, NJX)); as_inr_idx += sizeof(Float64)*NAJX*NJX HJAX = unsafe_wrap(Array, as_inr_idx, (3, NJX)); as_inr_idx += sizeof(Float64)*3*NJX as_ini = cglobal((:as_ini_, libaswing), Int32); as_ini_idx = as_ini nb = unsafe_wrap(Array, as_ini_idx, (JBX+1, NBX)); as_ini_idx += sizeof(Int32)*(JBX+1)*NBX NB = OffsetArrays.OffsetArray(nb, 0:JBX, 1:NBX) KBTYPE = unsafe_wrap(Array, as_ini_idx, NBX); as_ini_idx += sizeof(Int32)*NBX KBNUM = unsafe_wrap(Array, as_ini_idx, NBX); as_ini_idx += sizeof(Int32)*NBX KBPYLO = unsafe_wrap(Array, as_ini_idx, NPX); as_ini_idx += sizeof(Int32)*NPX KBJOIN = unsafe_wrap(Array, as_ini_idx, (2, NJX)); as_ini_idx += sizeof(Int32)*2*NJX KBGROU = unsafe_wrap(Array, as_ini_idx, NGX); as_ini_idx += sizeof(Int32)*NGX NPYLO = unsafe_wrap(Array, as_ini_idx, 1); as_ini_idx += sizeof(Int32) ISPYLO = unsafe_wrap(Array, as_ini_idx, NPX); as_ini_idx += sizeof(Int32)*NPX IPYLO = unsafe_wrap(Array, as_ini_idx, NPX); as_ini_idx += sizeof(Int32)*NPX KPTYPE = unsafe_wrap(Array, as_ini_idx, NPX); as_ini_idx += sizeof(Int32)*NPX ISSENS = unsafe_wrap(Array, as_ini_idx, NSENX); as_ini_idx += sizeof(Int32)*NSENX ISENS = unsafe_wrap(Array, as_ini_idx, NSENX); as_ini_idx += sizeof(Int32)*NSENX NJOIN = unsafe_wrap(Array, as_ini_idx, 1); as_ini_idx += sizeof(Int32) ISJOIN = unsafe_wrap(Array, as_ini_idx, (2, NJX)); as_ini_idx += sizeof(Int32)*2*NJX IJOIN = unsafe_wrap(Array, as_ini_idx, (2, NJX)); as_ini_idx += sizeof(Int32)*2*NJX KJTYPE = unsafe_wrap(Array, as_ini_idx, NJX); as_ini_idx += sizeof(Int32)*NJX NGROU = unsafe_wrap(Array, as_ini_idx, 1); as_ini_idx += sizeof(Int32) ISGROU = unsafe_wrap(Array, as_ini_idx, NGX); as_ini_idx += sizeof(Int32)*NGX IGROU = unsafe_wrap(Array, as_ini_idx, NGX); as_ini_idx += sizeof(Int32)*NGX KGTYPE = unsafe_wrap(Array, as_ini_idx, NGX); as_ini_idx += sizeof(Int32)*NGX NCORN = unsafe_wrap(Array, as_ini_idx, 1); as_ini_idx += sizeof(Int32) ISCORN = unsafe_wrap(Array, as_ini_idx, NCX); as_ini_idx += sizeof(Int32)*NCX ICORN = unsafe_wrap(Array, as_ini_idx, NCX); as_ini_idx += sizeof(Int32)*NCX JBCORN = unsafe_wrap(Array, as_ini_idx, NCX); as_ini_idx += sizeof(Int32)*NCX IBCORN = unsafe_wrap(Array, as_ini_idx, NCX); as_ini_idx += sizeof(Int32)*NCX NBRK = unsafe_wrap(Array, as_ini_idx, NBX); as_ini_idx += sizeof(Int32)*NBX ibrk = unsafe_wrap(Array, as_ini_idx, (NBRKX+2, NBX)); as_ini_idx += sizeof(Int32)*(NBRKX+2)*NBX IBRK = OffsetArrays.OffsetArray(ibrk, 0:NBRKX+1, 1:NBX) JFIL = unsafe_wrap(Array, as_ini_idx, 1); as_ini_idx += sizeof(Int32) ISFIL = unsafe_wrap(Array, as_ini_idx, 1); as_ini_idx += sizeof(Int32) NBFIL = unsafe_wrap(Array, as_ini_idx, 1); as_ini_idx += sizeof(Int32) NANGJ = unsafe_wrap(Array, as_ini_idx, NJX); as_snr = cglobal((:as_snr_, libaswing), Float64); as_snr_idx = as_snr QSNSP = unsafe_wrap(Array, as_snr_idx, (IRTOT, NSENX, NPNTX)); as_snr_idx += sizeof(Float64)*IRTOT*NSENX*NPNTX QSENS = unsafe_wrap(Array, as_snr_idx, (KSTOT, NSENX, NPNTX)); as_snr_idx += sizeof(Float64)*KSTOT*NSENX*NPNTX QSENS_Q = unsafe_wrap(Array, as_snr_idx, (KSTOT, 18, NSENX)); as_snr_idx += sizeof(Float64)*KSTOT*18*NSENX QSENS_QT = unsafe_wrap(Array, as_snr_idx, (KSTOT, 6, NSENX)); as_snr_idx += sizeof(Float64)*KSTOT*6*NSENX qsens_gl = unsafe_wrap(Array, as_snr_idx, (KSTOT, NGLX+1, NSENX)); as_snr_idx += sizeof(Float64)*KSTOT*(NGLX+1)*NSENX QSENS_GL = OffsetArrays.OffsetArray(qsens_gl, 1:KSTOT, 0:NGLX, 1:NSENX) qsens_glt = unsafe_wrap(Array, as_snr_idx, (KSTOT, NGLX+1, NSENX)); as_snr_idx += sizeof(Float64)*KSTOT*(NGLX+1)*NSENX QSENS_GLT = OffsetArrays.OffsetArray(qsens_glt, 1:KSTOT, 0:NGLX, 1:NSENX) qsens_frp = unsafe_wrap(Array, as_snr_idx, (KSTOT, NFRLX+1, NSENX)); as_snr_idx += sizeof(Float64)*KSTOT*(NFRLX+1)*NSENX QSENS_FRP = OffsetArrays.OffsetArray(qsens_frp, 1:KSTOT, 0:NFRLX, 1:NSENX) TPMAT = unsafe_wrap(Array, as_snr_idx, (3, 3, NPX)) as_vab = cglobal((:as_vab_, libaswing), Float64); as_vab_idx = as_vab VIWIND = unsafe_wrap(Array, as_vab_idx, 1); as_vab_idx += sizeof(Float64) ALWIND = unsafe_wrap(Array, as_vab_idx, 1); as_vab_idx += sizeof(Float64) BEWIND = unsafe_wrap(Array, as_vab_idx, 1); as_vab_idx += sizeof(Float64) VIW_VEL = unsafe_wrap(Array, as_vab_idx, 3); as_vab_idx += sizeof(Float64)*3 ALW_VEL = unsafe_wrap(Array, as_vab_idx, 3); as_vab_idx += sizeof(Float64)*3 BEW_VEL = unsafe_wrap(Array, as_vab_idx, 3); as_vab_idx += sizeof(Float64)*3 as_var = cglobal((:as_var_, libaswing), Float64); as_var_idx = as_var Q = unsafe_wrap(Array, as_var_idx, (18, IIX, NPNTX)); as_var_idx += sizeof(Float64)*18*IIX*NPNTX Q0 = unsafe_wrap(Array, as_var_idx, (6, IIX)); as_var_idx += sizeof(Float64)*6*IIX QPAR = unsafe_wrap(Array, as_var_idx, (IIX, JBX)); as_var_idx += sizeof(Float64)*IIX*JBX S = unsafe_wrap(Array, as_var_idx, IIX); as_var_idx += sizeof(Float64)*IIX THET = unsafe_wrap(Array, as_var_idx, IIX); as_var_idx += sizeof(Float64)*IIX SPLT = unsafe_wrap(Array, as_var_idx, IIX); as_var_idx += sizeof(Float64)*IIX TBI = unsafe_wrap(Array, as_var_idx, IIX); as_var_idx += sizeof(Float64)*IIX SCP = unsafe_wrap(Array, as_var_idx, IIX); as_var_idx += sizeof(Float64)*IIX XYZTFZ = unsafe_wrap(Array, as_var_idx, (3, IIX)); as_var_idx += sizeof(Float64)*3*IIX XYZTFZI = unsafe_wrap(Array, as_var_idx, (3, IIX)); as_var_idx += sizeof(Float64)*3*IIX PARAM = unsafe_wrap(Array, as_var_idx, (KPTOT, NPNTX)); as_var_idx += sizeof(Float64)*KPTOT*NPNTX AN = unsafe_wrap(Array, as_var_idx, (NNX, NPNTX)); as_var_idx += sizeof(Float64)*NNX*NPNTX PSPEC = unsafe_wrap(Array, as_var_idx, (IPTOT, NPNTX)); as_var_idx += sizeof(Float64)*IPTOT*NPNTX PSPECSET = unsafe_wrap(Array, as_var_idx, (IPTOT, NSETX)); as_var_idx += sizeof(Float64)*IPTOT*NSETX WFLAP = unsafe_wrap(Array, as_var_idx, (NFLPX, NPNTX)); as_var_idx += sizeof(Float64)*NFLPX*NPNTX WPENG = unsafe_wrap(Array, as_var_idx, (NENGX, NPNTX)); as_var_idx += sizeof(Float64)*NENGX*NPNTX QJOIN = unsafe_wrap(Array, as_var_idx, (12, NJX, NPNTX)); as_var_idx += sizeof(Float64)*12*NJX*NPNTX QPNT = unsafe_wrap(Array, as_var_idx, (IIX, IQTOT, NPNTX)); as_var_idx += sizeof(Float64)*IIX*IQTOT*NPNTX DTIME = unsafe_wrap(Array, as_var_idx, 1); as_var_idx += sizeof(Float64) TIME = unsafe_wrap(Array, as_var_idx, NPNTX); as_var_idx += sizeof(Float64)*NPNTX qtwt = unsafe_wrap(Array, as_var_idx, 3); as_var_idx += sizeof(Float64)*3 QTWT = OffsetArrays.OffsetArray(qtwt,0:2) RDOT = unsafe_wrap(Array, as_var_idx, (6, IIX)); as_var_idx += sizeof(Float64)*6*IIX UDOT = unsafe_wrap(Array, as_var_idx, (6, IIX)); as_var_idx += sizeof(Float64)*6*IIX PSDOT = unsafe_wrap(Array, as_var_idx, KPTOT); as_var_idx += sizeof(Float64)*KPTOT ANDOT = unsafe_wrap(Array, as_var_idx, NNX); as_var_idx += sizeof(Float64)*NNX QSDOT = unsafe_wrap(Array, as_var_idx, (KSTOT, NSENX)); as_var_idx += sizeof(Float64)*KSTOT*NSENX AKGUST = unsafe_wrap(Array, as_var_idx, (3, NGUSX)); as_var_idx += sizeof(Float64)*3*NGUSX ALGUST = unsafe_wrap(Array, as_var_idx, (3, NGUSX)); as_var_idx += sizeof(Float64)*3*NGUSX VFGUST = unsafe_wrap(Array, as_var_idx, (3, 4, NGUSX)); as_pti = cglobal((:as_pti_, libaswing), Int32); as_pti_idx = as_pti NPOINT = unsafe_wrap(Array, as_pti_idx, 1); as_pti_idx += sizeof(Int32) IPOINT = unsafe_wrap(Array, as_pti_idx, 1); as_pti_idx += sizeof(Int32) NPTIME = unsafe_wrap(Array, as_pti_idx, 1); as_pti_idx += sizeof(Int32) IPNTD = unsafe_wrap(Array, as_pti_idx, 1); as_pti_idx += sizeof(Int32) IPNTVL = unsafe_wrap(Array, as_pti_idx, 1); as_pti_idx += sizeof(Int32) KCSET = unsafe_wrap(Array, as_pti_idx, 1); as_pti_idx += sizeof(Int32) IQEXP = unsafe_wrap(Array, as_pti_idx, (IQTOT, NBX, NPNTX)); as_pti_idx += sizeof(Int32)*IQTOT*NBX*NPNTX IPPAR = unsafe_wrap(Array, as_pti_idx, (KPFREE, NPNTX)); as_pti_idx += sizeof(Int32)*KPFREE*NPNTX IPPARSET = unsafe_wrap(Array, as_pti_idx, (KPFREE, NSETX)); as_pti_idx += sizeof(Int32)*KPFREE*NSETX as_aic = cglobal((:as_aic_, libaswing), Float64); as_aic_idx = as_aic ANF = unsafe_wrap(Array, as_aic_idx, (NNX, IIX)); as_aic_idx += sizeof(Float64)*NNX*IIX RCCORE = unsafe_wrap(Array, as_aic_idx, 1); as_aic_idx += sizeof(Float64) VIB = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX WIB = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VEB = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIC = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX WIC = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VEC = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIP = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX WIP = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VEP = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VIB_MA = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX WIB_MA = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIC_MA = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX WIC_MA = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIP_MA = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX WIP_MA = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VIB_AL = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX WIB_AL = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VEB_AL = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIC_AL = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX WIC_AL = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VEC_AL = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIP_AL = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX WIP_AL = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VEP_AL = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VIB_BE = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX WIB_BE = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VEB_BE = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIC_BE = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX WIC_BE = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VEC_BE = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIP_BE = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX WIP_BE = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VEP_BE = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VIB_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX WIB_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX VIC_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX WIC_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX VIP_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX WIP_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX VIB_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX WIB_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX VIC_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX WIC_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX VIP_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX WIP_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX VIB_AN = unsafe_wrap(Array, as_aic_idx, (3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*NNX*IIX WIB_VI = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIC_AN = unsafe_wrap(Array, as_aic_idx, (3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*NNX*IIX WIC_VI = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIP_AN = unsafe_wrap(Array, as_aic_idx, (3, NNX, NPX)); as_aic_idx += sizeof(Float64)*3*NNX*NPX WIP_VI = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VEB_XENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEB_RENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEC_XENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEC_RENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEP_XENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX*NPX VEP_RENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX*NPX VEB_VENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEC_VENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEP_VENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX*NPX VEB_FENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEB_MENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEC_FENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEC_MENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NPX*IIX VEP_FENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX*NPX VEP_MENG = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX*NPX VIB_AN_MA = unsafe_wrap(Array, as_aic_idx, (3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*NNX*IIX WIB_VI_MA = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIC_AN_MA = unsafe_wrap(Array, as_aic_idx, (3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*NNX*IIX WIC_VI_MA = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIP_AN_MA = unsafe_wrap(Array, as_aic_idx, (3, NNX, NPX)); as_aic_idx += sizeof(Float64)*3*NNX*NPX WIP_VI_MA = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VIB_AN_AL = unsafe_wrap(Array, as_aic_idx, (3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*NNX*IIX WIB_VI_AL = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIC_AN_AL = unsafe_wrap(Array, as_aic_idx, (3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*NNX*IIX WIC_VI_AL = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIP_AN_AL = unsafe_wrap(Array, as_aic_idx, (3, NNX, NPX)); as_aic_idx += sizeof(Float64)*3*NNX*NPX WIP_VI_AL = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VIB_AN_BE = unsafe_wrap(Array, as_aic_idx, (3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*NNX*IIX WIB_VI_BE = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIC_AN_BE = unsafe_wrap(Array, as_aic_idx, (3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*NNX*IIX WIC_VI_BE = unsafe_wrap(Array, as_aic_idx, (3, IIX)); as_aic_idx += sizeof(Float64)*3*IIX VIP_AN_BE = unsafe_wrap(Array, as_aic_idx, (3, NNX, NPX)); as_aic_idx += sizeof(Float64)*3*NNX*NPX WIP_VI_BE = unsafe_wrap(Array, as_aic_idx, (3, NPX)); as_aic_idx += sizeof(Float64)*3*NPX VIB_AN_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NNX*IIX WIB_VI_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX VIC_AN_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NNX*IIX WIC_VI_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX VIP_AN_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, NNX, NPX)); as_aic_idx += sizeof(Float64)*3*3*NNX*NPX WIP_VI_POS = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX VIB_AN_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NNX*IIX WIB_VI_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX VIC_AN_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, NNX, IIX)); as_aic_idx += sizeof(Float64)*3*3*NNX*IIX WIC_VI_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, IIX)); as_aic_idx += sizeof(Float64)*3*3*IIX VIP_AN_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, NNX, NPX)); as_aic_idx += sizeof(Float64)*3*3*NNX*NPX WIP_VI_EUL = unsafe_wrap(Array, as_aic_idx, (3, 3, NPX)); as_aic_idx += sizeof(Float64)*3*3*NPX veb_gl = unsafe_wrap(Array, as_aic_idx, (3, NGLX+1, IIX)); as_aic_idx += sizeof(Float64)*3*(NGLX+1)*IIX VEB_GL = OffsetArrays.OffsetArray(veb_gl,1:3, 0:NGLX, 1:IIX) vec_gl = unsafe_wrap(Array, as_aic_idx, (3, NGLX+1, IIX)); as_aic_idx += sizeof(Float64)*3*(NGLX+1)*IIX VEC_GL = OffsetArrays.OffsetArray(vec_gl,1:3, 0:NGLX, 1:IIX) vep_gl = unsafe_wrap(Array, as_aic_idx, (3, NGLX+1, NPX)); as_aic_idx += sizeof(Float64)*3*(NGLX+1)*NPX VEP_GL = OffsetArrays.OffsetArray(vep_gl,1:3, 0:NGLX, 1:NPX) as_syj = cglobal((:as_syj_, libaswing), Float64); as_syj_idx = as_syj AJSAV = unsafe_wrap(Array, as_syj_idx, (12, 18, NJX)); as_syj_idx += sizeof(Float64)*12*18*NJX CJSAV = unsafe_wrap(Array, as_syj_idx, (12, 18, NJX)); as_syj_idx += sizeof(Float64)*12*18*NJX RJSAV = unsafe_wrap(Array, as_syj_idx, (12, NGLX, NJX)); as_syj_idx += sizeof(Float64)*12*NGLX*NJX ATJSAV = unsafe_wrap(Array, as_syj_idx, (12, 6, NJX)); as_syj_idx += sizeof(Float64)*12*6*NJX CTJSAV = unsafe_wrap(Array, as_syj_idx, (12, 6, NJX)); as_syj_idx += sizeof(Float64)*12*6*NJX RTJSAV = unsafe_wrap(Array, as_syj_idx, (12, NGLX, NJX)); as_syj_idx += sizeof(Float64)*12*NGLX*NJX rfrpjsav = unsafe_wrap(Array, as_syj_idx, (12, NFRLX+1, NJX)); as_syj_idx += sizeof(Float64)*12*(NFRLX+1)*NJX RFRPJSAV = OffsetArrays.OffsetArray(rfrpjsav, 1:12, 0:NFRLX, 1:NJX) as_syr = cglobal((:as_syr_, libaswing), Float64); as_syr_idx = as_syr A = unsafe_wrap(Array, as_syr_idx, (18, 18, IIX)); as_syr_idx += sizeof(Float64)*18*18*IIX B = unsafe_wrap(Array, as_syr_idx, (18, 18, IIX)); as_syr_idx += sizeof(Float64)*18*18*IIX C = unsafe_wrap(Array, as_syr_idx, (18, 18, IIX)); as_syr_idx += sizeof(Float64)*18*18*IIX r = unsafe_wrap(Array, as_syr_idx, (18, NGLX+1, IIX)); as_syr_idx += sizeof(Float64)*18*(NGLX+1)*IIX R = OffsetArrays.OffsetArray(r, 1:18, 0:NGLX, 1:IIX) AT = unsafe_wrap(Array, as_syr_idx, (18, 6, IIX)); as_syr_idx += sizeof(Float64)*18*6*IIX BT = unsafe_wrap(Array, as_syr_idx, (18, 6, IIX)); as_syr_idx += sizeof(Float64)*18*6*IIX CT = unsafe_wrap(Array, as_syr_idx, (18, 6, IIX)); as_syr_idx += sizeof(Float64)*18*6*IIX rt = unsafe_wrap(Array, as_syr_idx, (18, NGLX+1, IIX)); as_syr_idx += sizeof(Float64)*18*(NGLX+1)*IIX RT = OffsetArrays.OffsetArray(rt, 1:18, 0:NGLX, 1:IIX) rfrp = unsafe_wrap(Array, as_syr_idx, (18, NFRLX+1, IIX)); as_syr_idx += sizeof(Float64)*18*(NFRLX+1)*IIX RFRP = OffsetArrays.OffsetArray(rfrp, 1:18, 0:NFRLX, 1:IIX) as_syg = cglobal((:as_syg_, libaswing), Float64); as_syg_idx = as_syg gvsys = unsafe_wrap(Array, as_syg_idx, (NGVX, NGLX+1)); as_syg_idx += sizeof(Float64)*NGVX*(NGLX+1) GVSYS = OffsetArrays.OffsetArray(gvsys, 1:NGVX, 0:NGLX) gpsys = unsafe_wrap(Array, as_syg_idx, (NGPX, NGLX+1)); as_syg_idx += sizeof(Float64)*NGPX*(NGLX+1) GPSYS = OffsetArrays.OffsetArray(gpsys, 1:NGPX, 0:NGLX) gfsys = unsafe_wrap(Array, as_syg_idx, (NGFX, NGLX+1)); as_syg_idx += sizeof(Float64)*NGFX*(NGLX+1) GFSYS = OffsetArrays.OffsetArray(gfsys, 1:NGFX, 0:NGLX) gvsyst = unsafe_wrap(Array, as_syg_idx, (NGVX, NGLX+1)); as_syg_idx += sizeof(Float64)*NGVX*(NGLX+1) GVSYST = OffsetArrays.OffsetArray(gvsyst, 1:NGVX, 0:NGLX) gpsyst = unsafe_wrap(Array, as_syg_idx, (NGPX, NGLX+1)); as_syg_idx += sizeof(Float64)*NGPX*(NGLX+1) GPSYST = OffsetArrays.OffsetArray(gpsyst, 1:NGPX, 0:NGLX) gfsyst = unsafe_wrap(Array, as_syg_idx, (NGFX, NGLX+1)); as_syg_idx += sizeof(Float64)*NGFX*(NGLX+1) GFSYST = OffsetArrays.OffsetArray(gfsyst, 1:NGFX, 0:NGLX) GVQ = unsafe_wrap(Array, as_syg_idx, (18, NGVQX)); as_syg_idx += sizeof(Float64)*18*NGVQX GPQ = unsafe_wrap(Array, as_syg_idx, (18, NGPQX)); as_syg_idx += sizeof(Float64)*18*NGPQX GFQ = unsafe_wrap(Array, as_syg_idx, (18, NGFQX)); as_syg_idx += sizeof(Float64)*18*NGFQX GVQT = unsafe_wrap(Array, as_syg_idx, (6, NGVQX)); as_syg_idx += sizeof(Float64)*6*NGVQX GPQT = unsafe_wrap(Array, as_syg_idx, (6, NGPQX)); as_syg_idx += sizeof(Float64)*6*NGPQX GFQT = unsafe_wrap(Array, as_syg_idx, (6, NGFQX)); as_syg_idx += sizeof(Float64)*6*NGFQX gvfrp = unsafe_wrap(Array, as_syg_idx, (NGVX, NFRLX+1)); as_syg_idx += sizeof(Float64)*NGVX*(NFRLX+1) GVFRP = OffsetArrays.OffsetArray(gvfrp, 1:NGVX, 0:NFRLX) gpfrp = unsafe_wrap(Array, as_syg_idx, (NGPX, NFRLX+1)); as_syg_idx += sizeof(Float64)*NGPX*(NFRLX+1) GPFRP = OffsetArrays.OffsetArray(gpfrp, 1:NGPX, 0:NFRLX) gffrp = unsafe_wrap(Array, as_syg_idx, (NGFX, NFRLX+1)); as_syg_idx += sizeof(Float64)*NGFX*(NFRLX+1) GFFRP = OffsetArrays.OffsetArray(gffrp, 1:NGFX, 0:NFRLX) GFLSQ = unsafe_wrap(Array, as_syg_idx, (NGFX, NGFX)); as_syg_idx += sizeof(Float64)*NGFX*NGFX WLSQ = unsafe_wrap(Array, as_syg_idx, NGFX); as_syz = cglobal((:as_syz_, libaswing), ComplexF64); as_syz_idx = as_syz ZA = unsafe_wrap(Array, as_syz_idx, (18, 18, IIX)); as_syz_idx += sizeof(ComplexF64)*18*18*IIX ZB = unsafe_wrap(Array, as_syz_idx, (18, 18, IIX)); as_syz_idx += sizeof(ComplexF64)*18*18*IIX ZC = unsafe_wrap(Array, as_syz_idx, (18, 18, IIX)); as_syz_idx += sizeof(ComplexF64)*18*18*IIX zr = unsafe_wrap(Array, as_syz_idx, (18, NGLX+1, IIX)); as_syz_idx += sizeof(ComplexF64)*18*(NGLX+1)*IIX ZR = OffsetArrays.OffsetArray(zr, 1:18, 0:NGLX, 1:IIX) zgvsys = unsafe_wrap(Array, as_syz_idx, (NGVX, NGLX+1)); as_syz_idx += sizeof(ComplexF64)*NGVX*(NGLX+1) ZGVSYS = OffsetArrays.OffsetArray(zgvsys, 1:NGVX, 0:NGLX) zgpsys = unsafe_wrap(Array, as_syz_idx, (NGPX, NGLX+1)); as_syz_idx += sizeof(ComplexF64)*NGPX*(NGLX+1) ZGPSYS = OffsetArrays.OffsetArray(zgpsys, 1:NGPX, 0:NGLX) zgfsys = unsafe_wrap(Array, as_syz_idx, (NGFX, NGLX+1)); as_syz_idx += sizeof(ComplexF64)*NGFX*(NGLX+1) ZGFSYS = OffsetArrays.OffsetArray(zgfsys, 1:NGFX, 0:NGLX) ZGVQ = unsafe_wrap(Array, as_syz_idx, (18, NGVQX)); as_syz_idx += sizeof(ComplexF64)*18*NGVQX ZGPQ = unsafe_wrap(Array, as_syz_idx, (18, NGPQX)); as_syz_idx += sizeof(ComplexF64)*18*NGPQX ZGFQ = unsafe_wrap(Array, as_syz_idx, (18, NGFQX)); as_syz_idx += sizeof(ComplexF64)*18*NGFQX as_syi = cglobal((:as_syi_, libaswing), Int32); as_syi_idx = as_syi NGVQ = unsafe_wrap(Array, as_syi_idx, 1); as_syi_idx += sizeof(Int32) KGVQ = unsafe_wrap(Array, as_syi_idx, NGVQX); as_syi_idx += sizeof(Int32)*NGVQX IGVQ = unsafe_wrap(Array, as_syi_idx, NGVQX); as_syi_idx += sizeof(Int32)*NGVQX NGPQ = unsafe_wrap(Array, as_syi_idx, 1); as_syi_idx += sizeof(Int32) KGPQ = unsafe_wrap(Array, as_syi_idx, NGPQX); as_syi_idx += sizeof(Int32)*NGPQX IGPQ = unsafe_wrap(Array, as_syi_idx, NGPQX); as_syi_idx += sizeof(Int32)*NGPQX NGFQ = unsafe_wrap(Array, as_syi_idx, 1); as_syi_idx += sizeof(Int32) KGFQ = unsafe_wrap(Array, as_syi_idx, NGFQX); as_syi_idx += sizeof(Int32)*NGFQX IGFQ = unsafe_wrap(Array, as_syi_idx, NGFQX); as_syi_idx += sizeof(Int32)*NGFQX NGVQZ = unsafe_wrap(Array, as_syi_idx, 1); as_syi_idx += sizeof(Int32) KGVQZ = unsafe_wrap(Array, as_syi_idx, NGVQX); as_syi_idx += sizeof(Int32)*NGVQX IGVQZ = unsafe_wrap(Array, as_syi_idx, NGVQX); as_syi_idx += sizeof(Int32)*NGVQX NGPQZ = unsafe_wrap(Array, as_syi_idx, 1); as_syi_idx += sizeof(Int32) KGPQZ = unsafe_wrap(Array, as_syi_idx, NGPQX); as_syi_idx += sizeof(Int32)*NGPQX IGPQZ = unsafe_wrap(Array, as_syi_idx, NGPQX); as_syi_idx += sizeof(Int32)*NGPQX NGFQZ = unsafe_wrap(Array, as_syi_idx, 1); as_syi_idx += sizeof(Int32) KGFQZ = unsafe_wrap(Array, as_syi_idx, NGFQX); as_syi_idx += sizeof(Int32)*NGFQX IGFQZ = unsafe_wrap(Array, as_syi_idx, NGFQX); as_syi_idx += sizeof(Int32)*NGFQX NGVQ1 = unsafe_wrap(Array, as_syi_idx, 1); as_syi_idx += sizeof(Int32) NGPQ1 = unsafe_wrap(Array, as_syi_idx, 1); as_syi_idx += sizeof(Int32) NGFQ1 = unsafe_wrap(Array, as_syi_idx, 1); as_syi_idx += sizeof(Int32) IGVPIV = unsafe_wrap(Array, as_syi_idx, NGVX); as_syi_idx += sizeof(Int32)*NGVX IGPPIV = unsafe_wrap(Array, as_syi_idx, NGPX); as_syi_idx += sizeof(Int32)*NGPX IGFPIV = unsafe_wrap(Array, as_syi_idx, NGFX); as_syi_idx += sizeof(Int32)*NGFX as_itr = cglobal((:as_itr_, libaswing), Int32); as_itr_idx = as_itr ITER = unsafe_wrap(Array, as_itr_idx, 1); as_itr_idx += sizeof(Int32) ITMAX = unsafe_wrap(Array, as_itr_idx, 1); as_itr_idx += sizeof(Int32) NEIGIT = unsafe_wrap(Array, as_itr_idx, 1); as_itr_idx += sizeof(Int32) as_tol = cglobal((:as_tol_, libaswing), Float64); as_tol_idx = as_tol EPS = unsafe_wrap(Array, as_tol_idx, 1); as_tol_idx += sizeof(Float64) DELRMS = unsafe_wrap(Array, as_tol_idx, 1); as_tol_idx += sizeof(Float64) DELMAX = unsafe_wrap(Array, as_tol_idx, 1); as_tol_idx += sizeof(Float64) dglob = unsafe_wrap(Array, as_tol_idx, NGLX+1); as_tol_idx += sizeof(Float64)*(NGLX+1) DGLOB = OffsetArrays.OffsetArray(dglob, 0:NGLX) DQ = unsafe_wrap(Array, as_tol_idx, (18, IIX)); as_tol_idx += sizeof(Float64)*18*IIX as_nam = cglobal((:as_nam_, libaswing), Cchar); as_nam_idx = as_nam ARGP1 = unsafe_wrap(Array, as_nam_idx, 80); as_nam_idx += sizeof(Cchar)*80 ARGP2 = unsafe_wrap(Array, as_nam_idx, 80); as_nam_idx += sizeof(Cchar)*80 PREFIX = unsafe_wrap(Array, as_nam_idx, 80); as_nam_idx += sizeof(Cchar)*80 NAME = unsafe_wrap(Array, as_nam_idx, 80); as_nam_idx += sizeof(Cchar)*80 ANAME = Array{Array{Cchar,1}, 1}(undef, NPNTX) for i = 1:NPNTX ANAME[i] = unsafe_wrap(Array, as_nam_idx, 64); as_nam_idx += sizeof(Cchar)*64 end BNAME = Array{Array{Cchar,1}, 1}(undef, NBX) for i = 1:NBX BNAME[i] = unsafe_wrap(Array, as_nam_idx, 64); as_nam_idx += sizeof(Cchar)*64 end CNAME = Array{Array{Cchar,1}, 1}(undef, IPTOT) for i = 1:IPTOT CNAME[i] = unsafe_wrap(Array, as_nam_idx, 16); as_nam_idx += sizeof(Cchar)*16 end CUNIT = Array{Array{Cchar,1}, 1}(undef, IPTOT) for i = 1:IPTOT CUNIT[i] = unsafe_wrap(Array, as_nam_idx, 16); as_nam_idx += sizeof(Cchar)*16 end CKEY = Array{Array{Cchar,1}, 1}(undef, IPTOT) for i = 1:IPTOT CKEY[i] = unsafe_wrap(Array, as_nam_idx, 2); as_nam_idx += sizeof(Cchar)*2 end RNAME = Array{Array{Cchar,1}, 1}(undef, IPTOT) for i = 1:IPTOT RNAME[i] = unsafe_wrap(Array, as_nam_idx, 12); as_nam_idx += sizeof(Cchar)*12 end RUNIT = Array{Array{Cchar,1}, 1}(undef, IPTOT) for i = 1:IPTOT RUNIT[i] = unsafe_wrap(Array, as_nam_idx, 16); as_nam_idx += sizeof(Cchar)*16 end RKEY = Array{Array{Cchar,1}, 1}(undef, IPTOT) for i = 1:IPTOT RKEY[i] = unsafe_wrap(Array, as_nam_idx, 2); as_nam_idx += sizeof(Cchar)*2 end as_pli = cglobal((:as_pli_, libaswing), Int32); as_pli_idx = as_pli IDEV = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) IDEVRP = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) IDEVM = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) IPSLU = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) NCOLOR = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) NBFREQ = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) NBEIGEN = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) NFRAME = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) IVGCUT = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) IVGFUN = unsafe_wrap(Array, as_pli_idx, 1); as_pli_idx += sizeof(Int32) ILINE = unsafe_wrap(Array, as_pli_idx, NPNTX); as_pli_idx += sizeof(Int32)*NPNTX ICOLOR = unsafe_wrap(Array, as_pli_idx, NPNTX); as_pli_idx += sizeof(Int32)*NPNTX ICOLB = unsafe_wrap(Array, as_pli_idx, NBX); as_pli_idx += sizeof(Int32)*NBX ICOLF = unsafe_wrap(Array, as_pli_idx, NFRPX); as_pli_idx += sizeof(Int32)*NFRPX as_pll = cglobal((:as_pll_, libaswing), Int32); as_pll_idx = as_pll LPLOT = unsafe_wrap(Array, as_pll_idx, 1); as_pll_idx += sizeof(Int32) LPGRID = unsafe_wrap(Array, as_pll_idx, 1); as_pll_idx += sizeof(Int32) LCEDPL = unsafe_wrap(Array, as_pll_idx, 1); as_pll_idx += sizeof(Int32) LSVMOV = unsafe_wrap(Array, as_pll_idx, 1); as_pll_idx += sizeof(Int32) as_plr = cglobal((:as_plr_, libaswing), Float64); as_plr_idx = as_plr SCRNFL = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) SCRNFP = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) SIZE = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) CSIZ = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) XWIND = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) YWIND = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) AZIMOB = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) ELEVOB = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) ROBINV = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) XYZUP = unsafe_wrap(Array, as_plr_idx, 3); as_plr_idx += sizeof(Float64)*3 WAKLFR = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) SAXLFR = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) SLOMOF = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) EIGENF = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) TMOVIE = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) TIME1 = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) TIME2 = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) DPHASE = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) SCALEF = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) DTDUMP = unsafe_wrap(Array, as_plr_idx, NBX); as_plr_idx += sizeof(Float64)*NBX BFREQ1 = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) BFREQ2 = unsafe_wrap(Array, as_plr_idx, 1); as_plr_idx += sizeof(Float64) VGCXYZ = unsafe_wrap(Array, as_plr_idx, 3); as_plr_idx += sizeof(Float64)*3 VGCLIM = unsafe_wrap(Array, as_plr_idx, (2,3)); as_plr_idx += sizeof(Float64)*2*3 as_sen = cglobal((:as_sen_, libaswing), Float64); as_sen_idx = as_sen CL_VEL = unsafe_wrap(Array, as_sen_idx, (3,NPNTX)); as_sen_idx += sizeof(Float64)*3*NPNTX CM_VEL = unsafe_wrap(Array, as_sen_idx, (3,NPNTX)); as_sen_idx += sizeof(Float64)*3*NPNTX CN_VEL = unsafe_wrap(Array, as_sen_idx, (3,NPNTX)); as_sen_idx += sizeof(Float64)*3*NPNTX CR_VEL = unsafe_wrap(Array, as_sen_idx, (3,NPNTX)); as_sen_idx += sizeof(Float64)*3*NPNTX CL_ROT = unsafe_wrap(Array, as_sen_idx, (3,NPNTX)); as_sen_idx += sizeof(Float64)*3*NPNTX CM_ROT = unsafe_wrap(Array, as_sen_idx, (3,NPNTX)); as_sen_idx += sizeof(Float64)*3*NPNTX CN_ROT = unsafe_wrap(Array, as_sen_idx, (3,NPNTX)); as_sen_idx += sizeof(Float64)*3*NPNTX CR_ROT = unsafe_wrap(Array, as_sen_idx, (3,NPNTX)); as_sen_idx += sizeof(Float64)*3*NPNTX FOR_VEL = unsafe_wrap(Array, as_sen_idx, (3,3,NPNTX)); as_sen_idx += sizeof(Float64)*3*3*NPNTX MOM_VEL = unsafe_wrap(Array, as_sen_idx, (3,3,NPNTX)); as_sen_idx += sizeof(Float64)*3*3*NPNTX FOR_ROT = unsafe_wrap(Array, as_sen_idx, (3,3,NPNTX)); as_sen_idx += sizeof(Float64)*3*3*NPNTX MOM_ROT = unsafe_wrap(Array, as_sen_idx, (3,3,NPNTX)); as_sen_idx += sizeof(Float64)*3*3*NPNTX FOR_FLAP = unsafe_wrap(Array, as_sen_idx, (3,NFLPX,NPNTX)); as_sen_idx += sizeof(Float64)*3*NFLPX*NPNTX MOM_FLAP = unsafe_wrap(Array, as_sen_idx, (3,NFLPX,NPNTX)); as_sen_idx += sizeof(Float64)*3*NFLPX*NPNTX FOR_PENG = unsafe_wrap(Array, as_sen_idx, (3,NENGX,NPNTX)); as_sen_idx += sizeof(Float64)*3*NENGX*NPNTX MOM_PENG = unsafe_wrap(Array, as_sen_idx, (3,NENGX,NPNTX)); as_sen_idx += sizeof(Float64)*3*NENGX*NPNTX as_edi = cglobal((:as_edi_, libaswing), Int32); as_edi_idx = as_edi JEDIT = unsafe_wrap(Array, as_edi_idx, 1); as_edi_idx += sizeof(Int32) ISEDIT = unsafe_wrap(Array, as_edi_idx, 1); as_edi_idx += sizeof(Int32) as_edl = cglobal((:as_edl_, libaswing), Int32); as_edl_idx = as_edl LSLOPE = unsafe_wrap(Array, as_edl_idx, 1); as_edl_idx += sizeof(Int32) ledsym = unsafe_wrap(Array, as_edl_idx, (JBX+1,NBX)); LEDSYM = OffsetArrays.OffsetArray(ledsym, 0:JBX, 1:NBX) as_edr = cglobal((:as_edr_, libaswing), Float64); as_edr_idx = as_edr EDPAR = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) TOFFE = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) TFACE = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) QOFFE = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) QFACE = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) TBMIN = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) TBMAX = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) DELTB = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) QBMIN = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) QBMAX = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) DELQB = unsafe_wrap(Array, as_edr_idx, 1); as_edr_idx += sizeof(Float64) com_vgi = cglobal((:com_vgi_, libaswing), Int32) IGUST = unsafe_wrap(Array, com_vgi, 1) com_vgr = cglobal((:com_vgr_, libaswing), Float64) VGCON = unsafe_wrap(Array, com_vgr, 6) new(PI, DTOR, VERSION, STIPL, STIPR, TBTIPL, TBTIPR, MACHPG, GEEW, SREF, CREF, BREF, XYZREF, BGREFX, BGREFY, BGREFZ, ULCON, GRNORM, VSOSL, VSO_SI, VSOSL_SI, RHOSL, RHO_SI, RHOSL_SI, RMUSL, RMU_SI, RMUSL_SI, EXPII, EXPNN, LALTKM, AUTSCL, LTERSE, LVLFIX, LAELAG, LLEVEC, STEADY, CONLAW, CONSET, LFGUST, LROMFR, LVISEN, LLGROU, LLREFP, LAXPLT, LELIST, LENGLI, LESPEC, LNODES, LUNSWP, LPLRIB, LPLZLO, LPLBAR, LFRPAN, LFRROT, LGEOM, LLRHS, LVAIC, LWSET, LCSET, LQBDEF, LBSYMM, LSFLAP, LSPENG, LSSENS, LQINI, LAINI, LCONV, LMACH, PSTEADY, LPBEAM, LPWAKE, LDCON, LUCON, LQCON, NQ, NCP, IBEAM, IICON, II, IFRST, ILAST, IITOT, NNCON, NN, NFRST, NLAST, NNTOT, KEQ0, KEQ, NRHS, NGVAR, NGPAR, NGFOR, NGFEQ, NFRP, NFRPF, NFRPR, NBEAM, NFUSE, NSURF, ICOORD, IENGTYP, IGUSDIR, NXGUST, NYGUST, NZGUST, NFGUST, IGRIM, LRES, LQJOIN, LAN, LHEAD, LELEV, LBANK, LVAC, LRAC, LVEL, LROT, LPOS, LFLAP, LPENG, LVIDT, LALDT, LBEDT, LHEDT, LELDT, LBADT, LWDT, LADT, LVIDTS, LALDTS, LBEDTS, LHEDTS, LELDTS, LBADTS, LWDTS, LADTS, LFRPK, KFRPL, LFLAPF, LPENGF, LGUS1F, LGUS2F, LGUS3F, LGUS4F, VGI_FRP, AFORCE, RFORCE, EFORCE, GFORCE, TFORCE, AMOMNT, RMOMNT, EMOMNT, GMOMNT, TMOMNT, AFOR_Q, AFOR_GL, AFOR_FRP, AMOM_Q, AMOM_GL, AMOM_FRP, RFOR_Q, RFOR_GL, RFOR_FRP, RMOM_Q, RMOM_GL, RMOM_FRP, EFOR_Q, EFOR_GL, EFOR_FRP, EMOM_Q, EMOM_GL, EMOM_FRP, GFOR_Q, GFOR_GL, GFOR_FRP, GMOM_Q, GMOM_GL, GMOM_FRP, AFOR_UT, AFOR_GLT, AMOM_UT, AMOM_GLT, RFOR_UT, RFOR_GLT, RMOM_UT, RMOM_GLT, EFOR_UT, EFOR_GLT, EMOM_UT, EMOM_GLT, GFOR_UT, GFOR_GLT, GMOM_UT, GMOM_GLT, FAERO, FAERO_Q, FAERO_GL, FAERO_FRP, FAERO_UT, FAERO_GLT, MAERO, MAERO_Q, MAERO_GL, MAERO_FRP, MAERO_UT, MAERO_GLT, DVENG, XENG, XENG_ANG, RENG, RENG_ANG, VENG, VENG_Q, VENG_GL, FENG, FENG_Q, FENG_GL, MENG, MENG_Q, MENG_GL, MASS, MASSP, MASSB, AREAB, RCGXYZ0, RMASST0, RINERT0, RCGXYZ, RMASST, RINERT, PCGXYZ0, PMASST0, PINERT0, PCGXYZ, PMASST, PINERT, AMASST0, AINERT0, AMASST, AINERT, RCGXYZB0, RMASSTB0, AMASSTB0, RINERTB0, AINERTB0, RCGXYZB, RMASSTB, RINERTB, AMASSTB, AINERTB, QPYLO, TB, QB, QBT, TJOIN, TGROU, SBRK, TBFIL, QBFIL, QBTFIL, ANGJ, ANGJM, MOMJ, HJAX, NB, KBTYPE, KBNUM, KBPYLO, KBJOIN, KBGROU, NPYLO, ISPYLO, IPYLO, KPTYPE, ISSENS, ISENS, NJOIN, ISJOIN, IJOIN, KJTYPE, NGROU, ISGROU, IGROU, KGTYPE, NCORN, ISCORN, ICORN, JBCORN, IBCORN, NBRK, IBRK, JFIL, ISFIL, NBFIL, NANGJ, QSNSP, QSENS, QSENS_Q, QSENS_QT, QSENS_GL, QSENS_GLT, QSENS_FRP, TPMAT, VIWIND, ALWIND, BEWIND, VIW_VEL, ALW_VEL, BEW_VEL, Q, Q0, QPAR, S, THET, SPLT, TBI, SCP, XYZTFZ, XYZTFZI, PARAM, AN, PSPEC, PSPECSET, WFLAP, WPENG, QJOIN, QPNT, DTIME, TIME, QTWT, RDOT, UDOT, PSDOT, ANDOT, QSDOT, AKGUST, ALGUST, VFGUST, NPOINT, IPOINT, NPTIME, IPNTD, IPNTVL, KCSET, IQEXP, IPPAR, IPPARSET, ANF, RCCORE, VIB, WIB, VEB, VIC, WIC, VEC, VIP, WIP, VEP, VIB_MA, WIB_MA, VIC_MA, WIC_MA, VIP_MA, WIP_MA, VIB_AL, WIB_AL, VEB_AL, VIC_AL, WIC_AL, VEC_AL, VIP_AL, WIP_AL, VEP_AL, VIB_BE, WIB_BE, VEB_BE, VIC_BE, WIC_BE, VEC_BE, VIP_BE, WIP_BE, VEP_BE, VIB_POS, WIB_POS, VIC_POS, WIC_POS, VIP_POS, WIP_POS, VIB_EUL, WIB_EUL, VIC_EUL, WIC_EUL, VIP_EUL, WIP_EUL, VIB_AN, WIB_VI, VIC_AN, WIC_VI, VIP_AN, WIP_VI, VEB_XENG, VEB_RENG, VEC_XENG, VEC_RENG, VEP_XENG, VEP_RENG, VEB_VENG, VEC_VENG, VEP_VENG, VEB_FENG, VEB_MENG, VEC_FENG, VEC_MENG, VEP_FENG, VEP_MENG, VIB_AN_MA, WIB_VI_MA, VIC_AN_MA, WIC_VI_MA, VIP_AN_MA, WIP_VI_MA, VIB_AN_AL, WIB_VI_AL, VIC_AN_AL, WIC_VI_AL, VIP_AN_AL, WIP_VI_AL, VIB_AN_BE, WIB_VI_BE, VIC_AN_BE, WIC_VI_BE, VIP_AN_BE, WIP_VI_BE, VIB_AN_POS, WIB_VI_POS, VIC_AN_POS, WIC_VI_POS, VIP_AN_POS, WIP_VI_POS, VIB_AN_EUL, WIB_VI_EUL, VIC_AN_EUL, WIC_VI_EUL, VIP_AN_EUL, WIP_VI_EUL, VEB_GL, VEC_GL, VEP_GL, AJSAV, CJSAV, RJSAV, ATJSAV, CTJSAV, RTJSAV, RFRPJSAV, A, B, C, R, AT, BT, CT, RT, RFRP, GVSYS, GPSYS, GFSYS, GVSYST, GPSYST, GFSYST, GVQ, GPQ, GFQ, GVQT, GPQT, GFQT, GVFRP, GPFRP, GFFRP, GFLSQ, WLSQ, ZA, ZB, ZC, ZR, ZGVSYS, ZGPSYS, ZGFSYS, ZGVQ, ZGPQ, ZGFQ, NGVQ, KGVQ, IGVQ, NGPQ, KGPQ, IGPQ, NGFQ, KGFQ, IGFQ, NGVQZ, KGVQZ, IGVQZ, NGPQZ, KGPQZ, IGPQZ, NGFQZ, KGFQZ, IGFQZ, NGVQ1, NGPQ1, NGFQ1, IGVPIV, IGPPIV, IGFPIV, ITER, ITMAX, NEIGIT, EPS, DELRMS, DELMAX, DGLOB, DQ, ARGP1, ARGP2, PREFIX, NAME, ANAME, BNAME, CNAME, CUNIT, CKEY, RNAME, RUNIT, RKEY, IDEV, IDEVRP, IDEVM, IPSLU, NCOLOR, NBFREQ, NBEIGEN, NFRAME, IVGCUT, IVGFUN, ILINE, ICOLOR, ICOLB, ICOLF, LPLOT, LPGRID, LCEDPL, LSVMOV, SCRNFL, SCRNFP, SIZE, CSIZ, XWIND, YWIND, AZIMOB, ELEVOB, ROBINV, XYZUP, WAKLFR, SAXLFR, SLOMOF, EIGENF, TMOVIE, TIME1, TIME2, DPHASE, SCALEF, DTDUMP, BFREQ1, BFREQ2, VGCXYZ, VGCLIM, CL_VEL, CM_VEL, CN_VEL, CR_VEL, CL_ROT, CM_ROT, CN_ROT, CR_ROT, FOR_VEL, MOM_VEL, FOR_ROT, MOM_ROT, FOR_FLAP, MOM_FLAP, FOR_PENG, MOM_PENG, JEDIT, ISEDIT, LSLOPE, LEDSYM, EDPAR, TOFFE, TFACE, QOFFE, QFACE, TBMIN, TBMAX, DELTB, QBMIN, QBMAX, DELQB, IGUST, VGCON ) end end
using UtilitiesForMRI, LinearAlgebra, PyPlot # Cartesian domain n = (64, 64, 64) h = (1.0, 1.0, 1.0) # o = (0.0, 0.0, 0.0) o = (-5.0, -5.0, 0.0) X = spatial_sampling(Float32, n; h=h, o=o) # Cartesian sampling in k-space phase_encoding = (1,2) K = kspace_Cartesian_sampling(X; phase_encoding=phase_encoding) nt, nk = size(K) # Fourier operator tol = 1f-6 F = nfft(X, K; tol=tol) F0 = F(zeros(Float32, nt, 6)) # Rigid-body perturbation θ = zeros(Float32, nt, 6) θ[:, 1] .= 0 θ[:, 2] .= 0 θ[:, 3] .= 0 θ[:, 4] .= 0 θ[:, 5] .= 0 θ[:, 6] .= 0 # Volume u = zeros(ComplexF32, n); u[33-5:33+5, 33-5:33+5, 33-5:33+5] .= 1 # Rigid-body motion # u_rbm = F0'*F(θ)*u figure() for θxy = range(0,2*pi; length=20) θ[:, 4] .= θxy u_rbm = F0'*F(θ)*u imshow(real(u_rbm)[:,:,33]) pause(0.1) end
using CSV csvlist = CSV.File("day2_input.txt", header=false) function check_passwd1(csvlist) valid = 0 for l in csvlist min, max = Tuple([parse(Int, n) for n in split(l[1], '-')]) char = l[2][1] passwd = l[3] len = length([c for c in passwd if c == char]) if min <= len <= max valid += 1 end end return valid end function check_passwd2(csvlist) valid = 0 for l in csvlist pos1, pos2 = Tuple([parse(Int, n) for n in split(l[1], '-')]) char = l[2][1] passwd = l[3] if (passwd[pos1] == char) ⊻ (passwd[pos2] == char) valid += 1 end end return valid end println("Number of valid lines in problem 1 of day 2 = $(check_passwd1(csvlist)) from a total of $(length(csvlist))") println("Number of valid lines in problem 2 of day 2 = $(check_passwd2(csvlist)) from a total of $(length(csvlist))")
### A Pluto.jl notebook ### # v0.16.1 using Markdown using InteractiveUtils # ╔═╡ c9994475-bef9-4557-b774-e20bd99c049d using DataFrames, Statistics, CategoricalArrays, DataFramesMeta # ╔═╡ aac765bf-9ccd-4442-beea-38a765c59d0a using CSV, SQLite, Query, Tables # ╔═╡ c8633fe3-cdfe-4346-bf2e-dc43c4d7a90c using Random # ╔═╡ 22c94091-2278-4f60-a57a-d8b5d419fd37 using BenchmarkTools # ╔═╡ 6047eebc-cc01-48e3-8d58-d7c2bb683389 import Downloads # ╔═╡ ceb84193-d5b6-493c-b109-9bb040dba50c #= DataFrame constructor A DataFrame object can be created with several columns, NamedTuple, Dicts, Arrays, Vectors, Arrays of Strings, matrices, etc. =# # ╔═╡ a5853228-b040-46e2-937b-134aa833b199 df = DataFrame((a=[7, 7], b=[3, 4])) # ╔═╡ 2dfeea25-0a7d-477b-8f0b-238cb5ac996f length(df[1,:]) # get number of elements in the DataFrameRow # ╔═╡ d4e72dfe-88cf-455c-8619-fa337d8ad198 df[1, :] # ╔═╡ 4276b4fc-83b2-45bb-a114-af205d47041b gf = groupby(df, :a)[1] # ╔═╡ c5337a2c-44ec-4813-8430-b3505b6488e1 ByRow(+)([1, 2, 3, 4, 5], [2, 4, 5, 6, 7]) # implements the function row-wise # ╔═╡ e2faa9b1-9ae0-4ef8-a235-5bc67f997f23 AsTable((Name = "Nabs", Age = 23)) # ╔═╡ 88224c4a-2e92-48be-a329-9a7e5b449d57 DataFrame([7 1 5; 9 10 11], :auto) # here columns x1, x2, x3, .. are auto generated # ╔═╡ d461a50d-bab2-4f46-b0d6-56568439b2e9 eachrow(df)[2] # ╔═╡ d8e290ee-42ee-42b9-b098-254e72af8638 eachcol(df) # ╔═╡ ff6bad5e-7373-4c2e-a69c-e4dc4ad4b620 similar(df, 4) # has same number of columns as the parent dataframe but with specified numer of rows # ╔═╡ 386f80f7-10d1-4075-897d-af48ff2f5eda # There are 3 ways to read CSV files to a DataFrame # ╔═╡ 46871146-e192-4d1a-944b-eb06fa3d44ec # Let's download the CSV file # ╔═╡ f24fb0a1-2a39-4a0d-aa7c-f60856307f6d Downloads.download("https://www.stats.govt.nz/assets/Uploads/Gross-domestic-product/Gross-domestic-product-March-2021-quarter/Download-data/gross-domestic-product-March-2021-quarter-csv.csv", "gdp.csv") # ╔═╡ 20e1013b-f753-4e21-a0f6-5afa50341811 # Pass to constructor # ╔═╡ 92083de8-cb06-48c8-bca3-14a84c80587f df1 = DataFrame(CSV.File("gdp.csv")) # ╔═╡ 9a12e206-a900-40e1-ad28-348dfba3b840 # Pipe it # ╔═╡ 286dff3d-d926-43b2-abcd-0c9c68fb978c df2 = CSV.File("gdp.csv") |> DataFrame # ╔═╡ 317347d7-54cd-4a01-bf61-6154e7a9e63e #= Other formats from which a Julian DataFrame can be created and written to are: 1. Arrow.jl 2. Feather.jl 3. Avro.jl 4. JSONTables.jl 5. Parquet.jl (Parquet) 6. StatFiles.jl (Stata, SPSS, SAS) 7. XLSX.jl =# # You can also use DelimitedFiles.jl for creating DataFrame # ╔═╡ 50e83a4f-68c6-45ff-bc58-fb24a1fdda83 # using the CSV read() function # ╔═╡ b5352a9f-385f-4e1a-9bd4-c43a95681b9e df3 = CSV.read("gdp.csv", DataFrame) # Here DataFrame is passed as an object # ╔═╡ 68a29a3d-040b-49d9-8453-0ec29b9ea91f isapprox.(df2, df3) # this won't work because the columns have String type data # ╔═╡ 87cb09b7-05d5-4863-8ec0-015ca5755cad isapprox.(DataFrame(a=rand(10), b=rand(10)), DataFrame(a=rand(10), b=rand(10))) #broadcasted over all values over columns # ╔═╡ 50b0a355-ebf8-4a5f-89ce-132724abf382 isapprox(DataFrame(a=rand(10), b=rand(10)), DataFrame(a=rand(10), b=rand(10))) # ╔═╡ 90f197cc-4fbd-4dc0-b7d0-1e8d37a592a1 values(df1) # ╔═╡ 44ba67f4-b846-4f8f-afd2-40f9bb6ee93c pairs(df1[!,:Period]) # ╔═╡ 2a147ec5-302b-4ef7-a25d-50a6a40916a6 # create DataFrame column by column # ╔═╡ 322d07a8-95dc-490c-be8b-68b2cf332c19 b = DataFrame() # ╔═╡ 946a5035-4586-442d-be37-b714ef171d99 b.A = 1:20 # ╔═╡ ed786d21-3bbf-4786-8ce1-3853de366a83 b.B = repeat(["M", "F"], 10) # ╔═╡ 9470fd0e-286d-4ad4-bb5f-d76916a84d0e # create DataFrame row by row # ╔═╡ 977c1861-f6ef-4505-94e6-cdf064679487 push!(b, [21, "M"]) # ╔═╡ b74f2b45-dcd8-4cc8-9043-71b1388e475a push!(b, Dict(:A => 22, :B => "F")) # ╔═╡ bd7ccba5-3eea-4fa9-ac1b-4a3f67760b18 # DataFrames supports Tables.jl which is the Julian interface to interact with tabular data # ╔═╡ 6a3c345c-4ea6-4b3f-9eb4-44779863d2d8 CSV.write("df2csv.csv", b) # write to a CSV file # ╔═╡ 7d40b765-b7f7-400d-9269-6906ffe0d922 SQLite.load!(b, SQLite.DB(), "df2sqlite_table") # in memory sqlite database # ╔═╡ 9a420cda-0e7b-4372-b5c5-bd8fd6319d42 b1 = b |> @map({_.A, _.B}) |> DataFrame # transform df through Query.jl # ╔═╡ f17ec4dc-8e3d-4381-9b29-5ef755592036 Tables.rowtable(b) # use NamedTuples for creating DataFrame # ╔═╡ f4b36082-c332-481c-96ba-dcbbd014cc80 gdp = copy(df3) # ╔═╡ f5d6e9e3-d260-4778-b19c-2d345c06d1e6 # iterate over the dataframe eachcol(gdp) # ╔═╡ 70474af2-007d-4a11-b7ce-d102916875b5 # Accessing columns of DataFrame # ╔═╡ 7e6cee35-cc6c-43bf-bb02-3584f4148bec # Using . or ! operators # ╔═╡ 7699de43-d5ca-42c2-b082-3a49e183152d gdp.Period # or gdp."Period" gives the same result. You have to make a copy of the DataFrame before accessing columns using '.' (dot operator) or '!' operator. # ╔═╡ f6d08f22-de4e-4a69-86f2-414445b980b2 gdp[!, :Period] # ╔═╡ d15d313c-8a75-42aa-918e-4d9cfb15509f gdp[!, "Period"] # ╔═╡ ff293953-6eef-4fd5-9399-80610c1e719b # Accessing dataframes with '!' is better as it makes a copy of the dataframe and any alteration made in the respective columns of the copy doesn't affect the actual dataframe. # ╔═╡ a6ebd155-2252-4059-96cc-7a1c77b14df1 # using names, propertynames function # ╔═╡ b3d029a5-4dab-42dd-9735-dd63082fb97f names(gdp) # returns an array of Strings # ╔═╡ c1f4417a-5940-48f3-84e5-2b7b6721e031 names(gdp, String) # return column names which are of a particular DataType # ╔═╡ aa9744b3-7a0f-4d26-8da5-933310ae5d3a propertynames(gdp) # here you can get column names as Symbols # ╔═╡ 9a1a83ed-2801-4f21-8a99-3a4e7ec70a5e rename(gdp, :UNITS => :UNITS_STATS) # ╔═╡ 499dc896-5c55-4bee-a9e3-e006c495c67d groupiegdp = groupby(gdp, [:Period, :Data_value]) # ╔═╡ 45060fd5-db50-4222-8e0d-3d7bb8be5b08 get(groupiegdp, (UNITS="Percent",), nothing) # ╔═╡ ec2e9079-f447-4da5-ac08-b63b7cf4d4a4 groupcols(groupiegdp) # ╔═╡ e027e8fd-a918-4a64-a88b-54fc7d5ce4b4 groupindices(groupiegdp) # ╔═╡ ffa1c8de-b952-4718-bcc5-5c65fe721dc8 keys(groupiegdp) # ╔═╡ 2a5f7dea-5ae4-4da7-906f-0b9810e9cea0 valuecols(groupiegdp) # ╔═╡ 311d401a-8778-4362-b2b3-01df66b37142 parent(groupiegdp) # ╔═╡ 28ea219e-fbf7-477a-b245-95fc7397b256 # Basic info about DataFrame # ╔═╡ 528af444-1692-433f-9800-763cb1da56d3 empty(gdp) # creates a 0x0 dataframe with similar column names. If you want to clear out the initial datframe then use in place empty!(). # ╔═╡ 764e6a45-fe29-47a8-914a-21c545887c3c size(gdp) # ╔═╡ bb22078d-fe42-4f4c-8b0b-0b4cb1f71469 nrow(gdp) # ╔═╡ bf4cbe82-43c8-4f5b-bffb-9a0e7ffa8d93 ncol(gdp) # ╔═╡ 08fa8033-ab7b-483d-9500-6c32c4f243c3 ndims(gdp) # ╔═╡ 98d20964-0a16-43d4-aadc-e56aec601213 rownumber(gdp[2,:]) # ╔═╡ 75fd60e7-d96d-4edb-9766-ff41ef600805 parentindices(gdp) # ╔═╡ f4408b75-8a25-42e7-917b-42f9c0bfff2e parent(gdp) # ╔═╡ 3093d613-5109-4051-b8f6-935b842246a6 describe(gdp, cols=4:7) # ╔═╡ 20270e3d-9e84-4ff5-811c-47e80d5459d3 show(stdout, MIME("text/latex"), gdp) # output is printed in terminal # ╔═╡ 0b86cc10-63cb-42a2-9812-1384c097ae35 show(stdout, MIME("text/csv"), gdp) # output is printed in terminal # ╔═╡ 626c4687-0719-4651-bb3b-1d638d936b7e show(stdout, MIME("text/html"), describe(gdp)) # output is printed in terminal # ╔═╡ 9ee344ee-e3a0-44c0-9627-6855e942c789 # While using Julia REPL, all the bulk of a dataframe is not shown in the screen. To fit the whole dataframe you can use show(df, allcols=true) or show(df, allrows=true). show(gdp, allcols=true) # ╔═╡ 34e7c893-902f-4868-8855-ad83b56b4b8c show(gdp, allrows=true) # ╔═╡ 6c7e3124-ea5f-4e58-820a-abaf55fed480 mean(gdp."MAGNTUDE") # ╔═╡ 009b37eb-f3a0-418b-971c-0bcbe9ef94fb mapcols(MAGNTUDE -> MAGNTUDE .^ 7, gdp) # other operators are not discussed as String type data doesn't have to do anything with any other operator other than `^`. # ╔═╡ c2db935d-f49c-4538-acbd-de75399ae932 first(gdp, 5) # ╔═╡ 2de6853a-9c0b-414f-a3fa-af38bf407a6a last(gdp, 5) # ╔═╡ e2bf6f84-a9f1-4dc4-be6a-3280451cc1ae view(gdp, 77:300, :) # or else use macro @view gdp[end:-1:1, [1, 4]]. No new objects is created while using view, hence gives better performance while you are trying to peek into the data. # ╔═╡ c901457f-312b-4dee-98ed-b81493f56030 @timev gdp[1:end-1, 1:end-1] # ╔═╡ b1a61755-8791-48e6-90dd-cb6023034395 @timev @view gdp[1:end-1, 1:end-1] # ╔═╡ 4e6fe563-2c1b-42dc-a83e-3c4207e447d2 # view creates a mapping of indices from the view to the indices of the parent. As you can see in the chapter, view uses less memory allocations and takes less time than accessing dataframe using '[]' operator because no new object is created and points to the same memory location as of the parent. You can update the dataset using view and '[]' operator. # ╔═╡ 107f0e6d-a9a1-4414-bf45-b0b0b1c57c67 # Broadcasting # ╔═╡ ee04f0e0-3a93-4adf-9b90-83987e1f1d1e # As opposed to R, broadcasting in Julia is similar to that of Python. We use '.' dot operator. # ╔═╡ e6da06de-fc3e-4a89-868f-62dc47490126 s = [24, 54.0, 345, 098765, 43, 231.4, 497.23] # ╔═╡ a2efce21-5f2a-43b9-9e1b-1861220617a7 s[3:7] .= 0 # ╔═╡ ed5802e5-65a1-4e8c-a633-613a07a3bfec # ':' operator does the broadcasting in place. '!' operator creates a new vector instead of replacing the old one. # ╔═╡ c0634c82-f36c-4bfa-8284-564adc309932 insertcols!(df1, 1, :Country => "India") # this is called pseudo-broadcasting. It inserts columns in arbitrary places. # ╔═╡ 3aeeeb61-e004-4317-81c7-aa37d7ade55e # Selectors in DataFrame # ╔═╡ ee03f50a-3def-44aa-b14d-c4b5da7a9a63 gdp[:, Not(:Period)] # ╔═╡ 72dfa3c2-ec92-4c97-98a7-525964218356 gdp[:, Between(:Data_value, :MAGNTUDE)] # ╔═╡ 6d699f5b-0ac0-40b9-a601-ec0205131cdd gdp[:, Cols("Period", Between("Data_value", "MAGNTUDE"))] # ╔═╡ 08c1fbea-ad4f-414d-a942-6445a5fc8f62 # You can use Regex to select columns too. Here, we select columns having number "6" and not the 3rd column. gdp[Not(3), r"6"] # ╔═╡ 2c1e30ce-f3fa-4a67-b4f3-0587f466ec00 sample = DataFrame(x = [("a", "z"), ("b", "y"), ("c","x")]) # ╔═╡ 12cb9501-d815-45ef-84b2-2886e180a90c sample1 = DataFrame(x = [("1", "10"), ("2", "9"), ("3","8")]) # ╔═╡ ecc4cd83-cc73-4358-8df5-25d566b36185 flatten(sample, :x) # ╔═╡ cbb9f819-2645-4f7d-9c61-537041bd5466 hcat(sample, sample1, makeunique=true) # ╔═╡ 263b9a78-34bb-44a5-bf76-b5d402a4579e vcat(sample, sample1) # ╔═╡ 52cf77af-1fee-4b47-8f02-5c94e060a401 reduce(vcat, [sample, sample1]) # ╔═╡ 50f35a40-8fee-4a3f-b3a9-b344a8c4253e repeat(sample, inner = 3, outer = 5) # ╔═╡ 6e8eafa8-6854-4b4b-8a02-a82f08314505 # Transformation functions # ╔═╡ 81ecd06e-8c13-4dc0-81c9-ed575b8303bb gdp # ╔═╡ 95cf6d4e-a89b-40c1-a6b0-2f0692c27651 append!(gdp, gdp) # ╔═╡ eccb8cec-d709-4682-bc34-2867402a6cfc combine(gdp, :Data_value => mean => :mean_data_value) # this aggregates data and makes a copy # ╔═╡ 86bbd468-ecc4-4026-9dd4-5d8f2b9d50dc select(gdp, :Data_value => mean => :mean_data_value) # this broadcasted the result of the mean # in mean missing takes precedence # ╔═╡ e69776d2-3640-4c9f-aef2-d30a94dee390 transform(gdp, :Data_value => maximum) # inserts a column with the maximum value of the dataframe # ╔═╡ 8ba893b5-97fc-4a41-9dc5-67f9c11708bc transform(gdp, :Subject => :Group, :Group => :Subject) # transform retains all columns present in parent dataframe unlike select # ╔═╡ acec4361-d271-41dd-b6cf-4571eae16406 select(gdp, :Period, :Data_value, [:Period, :Data_value] => (-) => :resulting_vector) # this assumes both the columns to be consecutive and calculates the specified operation. Only +, - works. select always makes a copy of the columns. You can change this with argument copycols set to false. # ╔═╡ 38fb2132-8f03-4b5c-aa76-a265bac69497 # Joins # ╔═╡ 454d0957-0cdc-4490-bbdc-8409b07cddcd #= Julia supports innerjoin, leftjoin, rightjoin, outerjoin, semijoin, antijoin and crossjoin. =# # ╔═╡ ff622ae3-b4ea-4b0c-90cb-a6d1cd7c857e pupil = DataFrame(Rno = [40, 50, 60, 80, 90, 100, 130], Name = ["P1", "P2", "P3", "P4", "P5", "P6", "P7"]) # ╔═╡ c49773c7-cb73-437c-abb2-3e05e9b3c4f7 mark = DataFrame(Rno = [20, 30, 60, 70, 90, 110, 120], Marks = [25, 45, 63, 72, 64, 87, 36]) # ╔═╡ cd93d1b5-b587-4dc3-ae93-de0489163c3a innerjoin(pupil, mark, on = :Rno) # ╔═╡ 96202339-68d6-4d8b-af6e-f56e4b6b282d leftjoin(pupil, mark, on = :Rno) # ╔═╡ fd9351e2-e0b8-4042-b2d2-0b8cddf76b8a rightjoin(pupil, mark, on = :Rno) # ╔═╡ efdf00c9-f0b0-4d9b-b940-e0f4168220ac outerjoin(pupil, mark, on = :Rno) # ╔═╡ c1ad8951-554a-4f9c-ac02-2b86c69210e9 semijoin(pupil, mark, on = :Rno) # ╔═╡ 005f08fc-15b8-4927-bf4f-6f656bd7c509 antijoin(pupil, mark, on = :Rno) # ╔═╡ 0b81cbeb-e441-4ff7-8586-4aaaa14a5204 crossjoin(pupil, mark, makeunique = true) # ╔═╡ 85c381d1-aa5b-4e36-b764-4f2c08056723 new_pupil = DataFrame(Rno = [40, 50, 60, 80, 90, 100, 130], Name = ["P1", "P2", "P3", "P4", "P5", "P6", "P7"]) # ╔═╡ bdab1a2a-e3e9-4dd6-ba5a-3f1cbd430e9a new_mark = DataFrame(ID = [20, 30, 60, 70, 90, 110, 120], Marks = [25, 45, 63, 72, 64, 87, 36]) # ╔═╡ d348eb2c-ce88-4813-9fdd-dbb9f6263c79 innerjoin(new_pupil, new_mark, on = :Rno => :ID) # if you have two columns conveying the same meaning but with differing names use on argument. # ╔═╡ f66dca42-73e6-4ed9-be87-8092f45f75ae outerjoin(new_pupil, new_mark, on = :Rno => :ID) # ╔═╡ 87c933d0-d56f-41ec-9740-42da3aea7b02 outerjoin(pupil, mark, on=:Rno, validate=(true, true), source=:source) # for the two columns to be equal according to `isequal()`, an argument `validate` is introduced # ╔═╡ adef617a-8b1f-4198-ba22-95c2fc23e487 # Grouping # ╔═╡ 7d8430ce-3b06-4007-a091-dd00ebe5a4bd grby = groupby(gdp, :Period) # ╔═╡ 46f31f61-afaa-4788-8f44-b83face4b005 combine(gdp, :Period => mean) # ╔═╡ cb438dec-931a-4856-91ad-809d9d4d9106 # Reshaping # ╔═╡ 490769ee-72b2-46cd-aa88-e5b3bfe2ca9e stack(gdp, 1:4) # convert from landscape to portrait format # ╔═╡ 6310d056-f97b-444e-b257-3b22774f7e86 stack(gdp, [:MAGNTUDE, :UNITS], :Subject) # the 3rd argument shows which columsn are repeated # ╔═╡ e946a789-e9e1-4f46-b7b6-d278c0d6234c unstack(stack(gdp, Not(:Subject)), allowduplicates=true) # ╔═╡ bcae0cbd-d30f-458a-bc74-e969dab36ed1 permutedims(b, 2, makeunique=true) # ╔═╡ 783edc23-96fe-4484-bef0-7666668171ac # Sorting # ╔═╡ a63091de-654b-43fa-93ab-466fb7ad7f38 sort!(gdp) # ╔═╡ 5e351fca-85ea-4e52-b607-e693deac1719 sort!(gdp, rev = true) # ╔═╡ 64d4462f-f8fd-4186-9d48-dffd76c12fe6 sort!(gdp, [:Data_value, :MAGNTUDE]) # ╔═╡ 38a542dc-eee3-45b5-a52f-e342af3da728 sort!(gdp, [order(:Period, by=length), order(:Data_value, rev=true)]) # specify ordering for a particular set of columns # ╔═╡ e2518ebc-0bfe-4ce4-9775-cd2c5abaf201 issorted(gdp) # ╔═╡ 49c607c2-c386-4ba9-817b-c80317c0c51f sortperm(gdp, [:Data_value, :MAGNTUDE]) # ╔═╡ 3bf66bee-e84b-4293-83f0-b5af13a3f3eb # ╔═╡ c2d3f70e-19ef-4e59-9d22-5728a1e0f0e7 # Filtering # ╔═╡ ff666cf9-42dc-4dfc-88bc-6ccd5f1065d5 delete!(gdp, [5, 7, 9]) # indices must be unique and sorted # ╔═╡ 222b9658-7aba-426a-a5bd-42dee53f4365 empty(df) # clear all values from the rows # ╔═╡ 46253de4-245c-449f-9144-5fbe0fe52af1 unique(df1) # ╔═╡ 99a8113d-19c3-484c-a589-d75174b27422 subset(df, :b => x -> x .> 3) # ╔═╡ adb5bf96-3f83-41ac-bfb0-2e2e1ee2e8b6 filter!(row -> row.b > 3, df) # ╔═╡ 362bf8c3-e5d4-4631-849e-9f1af5264453 only(df) # ╔═╡ 79a0555b-3815-4a8a-ad82-297bb0721c34 nonunique(df1) # ╔═╡ 4ac3df0d-cf63-4cab-8c7c-6ce37a3589b2 # Handling missing values # ╔═╡ 3845701a-4d36-4b40-a5e9-df3b3578c7a5 allowmissing!(df2) # The DataType has changed for each column. # ╔═╡ 38f77f4d-da45-4ebf-9916-a3ddb03fb39e disallowmissing!(DataFrame(x=Union{Int, Missing}[7, 9, 7, 6, 53, missing, 3, 2, 56, missing]), error=false) # ╔═╡ 17536f1d-bbb0-46d9-91a6-e094b749ec9e dropmissing!(DataFrame(x=Union{Int, Missing}[7, 9, 7, 6, 53, missing, 3, 2, 56, missing])) # ╔═╡ 9eeb9b8a-c943-421c-a414-7bd7069bbcae completecases(DataFrame(x=Union{Int, Missing}[7, 9, 7, 6, 53, missing, 3, 2, 56, missing])) # ╔═╡ 374a0805-1ed4-4eef-bab7-cc4da4659a72 # Categorical Data # ╔═╡ 1dd794a3-61c0-4f27-af0d-89bfdc973bdb dat = CategoricalArray(repeat(["M", "F", missing], 3)) # ╔═╡ d9a58858-2bb1-44b3-a4c6-30b5d62936c4 levels(dat) # ╔═╡ fe58c5a4-8193-440d-be36-ac989017dc42 levels!(dat, ["F", "M"]) # changes the order of appearance # ╔═╡ 4b158c96-0273-46f1-b6fe-c75fb0974dae sort(dat) # ╔═╡ 371e9b4c-1a94-42a9-b4ee-a837bd005a7a dat_new = compress(dat) # since Categorical Arrays can store upto \2^32 levels. compress() is used to lessen the memory space. # ╔═╡ fd45ccc8-7d10-4081-b681-ea398248b495 dat2 = categorical(repeat(["N", "A", "P"], 3), ordered=true) # ╔═╡ 05e57f17-784e-49e5-815e-f7d94aea5ab8 isordered(dat2) # ╔═╡ 466b9320-6fe1-41df-9dae-7c90a12fca5d dat == dat2 # ╔═╡ 8ae1afae-ea67-49d9-be53-7909885fb083 # Missing Data # We have gone through missing datatype previously. Here we will see just one examples of how to convert any missing data to have a numeric value in Julia # ╔═╡ 91559ca4-aa63-409c-a9da-c02726121bee missin = [8, 30, 41, missing] # ╔═╡ 27cdd96d-774e-4afb-b680-4f3f52a21e94 coalesce.(missin, 0) # ╔═╡ f23449ba-ad22-4f75-a896-3aa8f94a3b74 # Data Manipulation Frameworks # ╔═╡ 0d499e42-4467-4384-a5f9-193f259fec60 # The main part of data analysis work is data manipulation. In Julia, we can use DataFramesMeta.jl and Query.jl to manipulate DataFrames which is similar to frameworks in Python/R. # ╔═╡ 6b3dc5c1-7c61-47fc-ae1b-03f4116de245 @linq gdp |> where(:Period .> 2000) |> select(units="Percent", :Series_reference) # linq macro helps to perform a series of transformations of the DataFrame. You can use all the split-apply-combine methods here within linq macro. # ╔═╡ 27d5e59d-e9a0-49b3-805b-1637a5e9d078 @from i in gdp begin @where i.Period > 2000 && i.Data_value > 0 @select i.Series_reference @collect end # Query also helps you to manipulate the dataframe # ╔═╡ ca1077c7-6bfe-406f-95d5-1686328022e2 # ╔═╡ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" CategoricalArrays = "324d7699-5711-5eae-9e2f-1d82baa6b597" DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" DataFramesMeta = "1313f7d8-7da2-5740-9ea0-a2ca25f37964" Downloads = "f43a241f-c20a-4ad4-852c-f6b1247861c6" Query = "1a8c2f83-1ff3-5112-b086-8aa67b057ba1" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" SQLite = "0aa819cd-b072-5ff4-a722-6bc24af294d9" Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" Tables = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" [compat] BenchmarkTools = "~1.1.4" CSV = "~0.8.5" CategoricalArrays = "~0.10.0" DataFrames = "~1.2.2" DataFramesMeta = "~0.9.0" Query = "~1.0.0" SQLite = "~1.1.4" Tables = "~1.5.0" """ # ╔═╡ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised [[ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" [[Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[BenchmarkTools]] deps = ["JSON", "Logging", "Printf", "Statistics", "UUIDs"] git-tree-sha1 = "42ac5e523869a84eac9669eaceed9e4aa0e1587b" uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" version = "1.1.4" [[BinaryProvider]] deps = ["Libdl", "Logging", "SHA"] git-tree-sha1 = "ecdec412a9abc8db54c0efc5548c64dfce072058" uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232" version = "0.5.10" [[CSV]] deps = ["Dates", "Mmap", "Parsers", "PooledArrays", "SentinelArrays", "Tables", "Unicode"] git-tree-sha1 = "b83aa3f513be680454437a0eee21001607e5d983" uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" version = "0.8.5" [[CategoricalArrays]] deps = ["DataAPI", "Future", "JSON", "Missings", "Printf", "RecipesBase", "Statistics", "StructTypes", "Unicode"] git-tree-sha1 = "1562002780515d2573a4fb0c3715e4e57481075e" uuid = "324d7699-5711-5eae-9e2f-1d82baa6b597" version = "0.10.0" [[Chain]] git-tree-sha1 = "cac464e71767e8a04ceee82a889ca56502795705" uuid = "8be319e6-bccf-4806-a6f7-6fae938471bc" version = "0.4.8" [[Compat]] deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] git-tree-sha1 = "727e463cfebd0c7b999bbf3e9e7e16f254b94193" uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" version = "3.34.0" [[Crayons]] git-tree-sha1 = "3f71217b538d7aaee0b69ab47d9b7724ca8afa0d" uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" version = "4.0.4" [[DBInterface]] git-tree-sha1 = "d3e9099ef8d63b180a671a35552f93a1e0250cbb" uuid = "a10d1c49-ce27-4219-8d33-6db1a4562965" version = "2.4.1" [[DataAPI]] git-tree-sha1 = "ee400abb2298bd13bfc3df1c412ed228061a2385" uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" version = "1.7.0" [[DataFrames]] deps = ["Compat", "DataAPI", "Future", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrettyTables", "Printf", "REPL", "Reexport", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"] git-tree-sha1 = "d785f42445b63fc86caa08bb9a9351008be9b765" uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" version = "1.2.2" [[DataFramesMeta]] deps = ["Chain", "DataFrames", "MacroTools", "Reexport"] git-tree-sha1 = "807e984bf12084b39d99bb27e27ad45bf111d3a1" uuid = "1313f7d8-7da2-5740-9ea0-a2ca25f37964" version = "0.9.0" [[DataStructures]] deps = ["Compat", "InteractiveUtils", "OrderedCollections"] git-tree-sha1 = "7d9d316f04214f7efdbb6398d545446e246eff02" uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" version = "0.18.10" [[DataValueInterfaces]] git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" version = "1.0.0" [[DataValues]] deps = ["DataValueInterfaces", "Dates"] git-tree-sha1 = "d88a19299eba280a6d062e135a43f00323ae70bf" uuid = "e7dc6d0d-1eca-5fa6-8ad6-5aecde8b7ea5" version = "0.4.13" [[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" [[Downloads]] deps = ["ArgTools", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" [[Formatting]] deps = ["Printf"] git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8" uuid = "59287772-0a20-5a39-b81b-1366585eb4c0" version = "0.4.2" [[Future]] deps = ["Random"] uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" [[InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[InvertedIndices]] deps = ["Test"] git-tree-sha1 = "15732c475062348b0165684ffe28e85ea8396afc" uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f" version = "1.0.0" [[IterableTables]] deps = ["DataValues", "IteratorInterfaceExtensions", "Requires", "TableTraits", "TableTraitsUtils"] git-tree-sha1 = "70300b876b2cebde43ebc0df42bc8c94a144e1b4" uuid = "1c8ee90f-4401-5389-894e-7a04a3dc0f4d" version = "1.0.0" [[IteratorInterfaceExtensions]] git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" uuid = "82899510-4779-5014-852e-03e436cf321d" version = "1.0.0" [[JLLWrappers]] deps = ["Preferences"] git-tree-sha1 = "642a199af8b68253517b80bd3bfd17eb4e84df6e" uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" version = "1.3.0" [[JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.2" [[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" [[Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "0fb723cd8c45858c22169b2e42269e53271a6df7" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.7" [[Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" [[Missings]] deps = ["DataAPI"] git-tree-sha1 = "2ca267b08821e86c5ef4376cffed98a46c2cb205" uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" version = "1.0.1" [[Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" [[NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" [[OrderedCollections]] git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c" uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" version = "1.4.1" [[Parsers]] deps = ["Dates"] git-tree-sha1 = "bfd7d8c7fd87f04543810d9cbd3995972236ba1b" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "1.1.2" [[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" [[PooledArrays]] deps = ["DataAPI", "Future"] git-tree-sha1 = "a193d6ad9c45ada72c14b731a318bedd3c2f00cf" uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720" version = "1.3.0" [[Preferences]] deps = ["TOML"] git-tree-sha1 = "00cfd92944ca9c760982747e9a1d0d5d86ab1e5a" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.2.2" [[PrettyTables]] deps = ["Crayons", "Formatting", "Markdown", "Reexport", "Tables"] git-tree-sha1 = "0d1245a357cc61c8cd61934c07447aa569ff22e6" uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d" version = "1.1.0" [[Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[Query]] deps = ["DataValues", "IterableTables", "MacroTools", "QueryOperators", "Statistics"] git-tree-sha1 = "a66aa7ca6f5c29f0e303ccef5c8bd55067df9bbe" uuid = "1a8c2f83-1ff3-5112-b086-8aa67b057ba1" version = "1.0.0" [[QueryOperators]] deps = ["DataStructures", "DataValues", "IteratorInterfaceExtensions", "TableShowUtils"] git-tree-sha1 = "911c64c204e7ecabfd1872eb93c49b4e7c701f02" uuid = "2aef5ad7-51ca-5a8f-8e88-e75cf067b44b" version = "0.9.3" [[REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[Random]] deps = ["Serialization"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[RecipesBase]] git-tree-sha1 = "44a75aa7a527910ee3d1751d1f0e4148698add9e" uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" version = "1.1.2" [[Reexport]] git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" uuid = "189a3867-3050-52da-a836-e630ba90ab69" version = "1.2.2" [[Requires]] deps = ["UUIDs"] git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621" uuid = "ae029012-a4dd-5104-9daa-d747884805df" version = "1.1.3" [[SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" [[SQLite]] deps = ["BinaryProvider", "DBInterface", "Dates", "Libdl", "Random", "SQLite_jll", "Serialization", "Tables", "Test", "WeakRefStrings"] git-tree-sha1 = "97261d38a26415048ce87f49a7a20902aa047836" uuid = "0aa819cd-b072-5ff4-a722-6bc24af294d9" version = "1.1.4" [[SQLite_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "9a0e24b81e3ce02c4b2eb855476467c7b93b8a8f" uuid = "76ed43ae-9a5d-5a62-8c75-30186b810ce8" version = "3.36.0+0" [[SentinelArrays]] deps = ["Dates", "Random"] git-tree-sha1 = "54f37736d8934a12a200edea2f9206b03bdf3159" uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c" version = "1.3.7" [[Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[SharedArrays]] deps = ["Distributed", "Mmap", "Random", "Serialization"] uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" [[Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[SortingAlgorithms]] deps = ["DataStructures"] git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508" uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c" version = "1.0.1" [[SparseArrays]] deps = ["LinearAlgebra", "Random"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" [[Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [[StructTypes]] deps = ["Dates", "UUIDs"] git-tree-sha1 = "8445bf99a36d703a09c601f9a57e2f83000ef2ae" uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4" version = "1.7.3" [[TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" [[TableShowUtils]] deps = ["DataValues", "Dates", "JSON", "Markdown", "Test"] git-tree-sha1 = "14c54e1e96431fb87f0d2f5983f090f1b9d06457" uuid = "5e66a065-1f0a-5976-b372-e0b8c017ca10" version = "0.2.5" [[TableTraits]] deps = ["IteratorInterfaceExtensions"] git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" version = "1.0.1" [[TableTraitsUtils]] deps = ["DataValues", "IteratorInterfaceExtensions", "Missings", "TableTraits"] git-tree-sha1 = "78fecfe140d7abb480b53a44f3f85b6aa373c293" uuid = "382cd787-c1b6-5bf2-a167-d5b971a19bda" version = "1.0.2" [[Tables]] deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"] git-tree-sha1 = "d0c690d37c73aeb5ca063056283fde5585a41710" uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" version = "1.5.0" [[Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" [[Test]] deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [[UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[WeakRefStrings]] deps = ["DataAPI", "Random", "Test"] git-tree-sha1 = "28807f85197eaad3cbd2330386fac1dcb9e7e11d" uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5" version = "0.6.2" [[Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" [[nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" [[p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" """ # ╔═╡ Cell order: # ╠═c9994475-bef9-4557-b774-e20bd99c049d # ╠═aac765bf-9ccd-4442-beea-38a765c59d0a # ╠═6047eebc-cc01-48e3-8d58-d7c2bb683389 # ╠═c8633fe3-cdfe-4346-bf2e-dc43c4d7a90c # ╠═22c94091-2278-4f60-a57a-d8b5d419fd37 # ╠═ceb84193-d5b6-493c-b109-9bb040dba50c # ╠═a5853228-b040-46e2-937b-134aa833b199 # ╠═2dfeea25-0a7d-477b-8f0b-238cb5ac996f # ╠═d4e72dfe-88cf-455c-8619-fa337d8ad198 # ╠═4276b4fc-83b2-45bb-a114-af205d47041b # ╠═c5337a2c-44ec-4813-8430-b3505b6488e1 # ╠═e2faa9b1-9ae0-4ef8-a235-5bc67f997f23 # ╠═88224c4a-2e92-48be-a329-9a7e5b449d57 # ╠═d461a50d-bab2-4f46-b0d6-56568439b2e9 # ╠═d8e290ee-42ee-42b9-b098-254e72af8638 # ╠═ff6bad5e-7373-4c2e-a69c-e4dc4ad4b620 # ╠═386f80f7-10d1-4075-897d-af48ff2f5eda # ╠═46871146-e192-4d1a-944b-eb06fa3d44ec # ╠═f24fb0a1-2a39-4a0d-aa7c-f60856307f6d # ╠═20e1013b-f753-4e21-a0f6-5afa50341811 # ╠═92083de8-cb06-48c8-bca3-14a84c80587f # ╠═9a12e206-a900-40e1-ad28-348dfba3b840 # ╠═286dff3d-d926-43b2-abcd-0c9c68fb978c # ╠═317347d7-54cd-4a01-bf61-6154e7a9e63e # ╠═50e83a4f-68c6-45ff-bc58-fb24a1fdda83 # ╠═b5352a9f-385f-4e1a-9bd4-c43a95681b9e # ╠═68a29a3d-040b-49d9-8453-0ec29b9ea91f # ╠═87cb09b7-05d5-4863-8ec0-015ca5755cad # ╠═50b0a355-ebf8-4a5f-89ce-132724abf382 # ╠═90f197cc-4fbd-4dc0-b7d0-1e8d37a592a1 # ╠═44ba67f4-b846-4f8f-afd2-40f9bb6ee93c # ╠═2a147ec5-302b-4ef7-a25d-50a6a40916a6 # ╠═322d07a8-95dc-490c-be8b-68b2cf332c19 # ╠═946a5035-4586-442d-be37-b714ef171d99 # ╠═ed786d21-3bbf-4786-8ce1-3853de366a83 # ╠═9470fd0e-286d-4ad4-bb5f-d76916a84d0e # ╠═977c1861-f6ef-4505-94e6-cdf064679487 # ╠═b74f2b45-dcd8-4cc8-9043-71b1388e475a # ╠═bd7ccba5-3eea-4fa9-ac1b-4a3f67760b18 # ╠═6a3c345c-4ea6-4b3f-9eb4-44779863d2d8 # ╠═7d40b765-b7f7-400d-9269-6906ffe0d922 # ╠═9a420cda-0e7b-4372-b5c5-bd8fd6319d42 # ╠═f17ec4dc-8e3d-4381-9b29-5ef755592036 # ╠═f5d6e9e3-d260-4778-b19c-2d345c06d1e6 # ╠═f4b36082-c332-481c-96ba-dcbbd014cc80 # ╠═70474af2-007d-4a11-b7ce-d102916875b5 # ╠═7e6cee35-cc6c-43bf-bb02-3584f4148bec # ╠═7699de43-d5ca-42c2-b082-3a49e183152d # ╠═f6d08f22-de4e-4a69-86f2-414445b980b2 # ╠═d15d313c-8a75-42aa-918e-4d9cfb15509f # ╠═ff293953-6eef-4fd5-9399-80610c1e719b # ╠═a6ebd155-2252-4059-96cc-7a1c77b14df1 # ╠═b3d029a5-4dab-42dd-9735-dd63082fb97f # ╠═c1f4417a-5940-48f3-84e5-2b7b6721e031 # ╠═aa9744b3-7a0f-4d26-8da5-933310ae5d3a # ╠═9a1a83ed-2801-4f21-8a99-3a4e7ec70a5e # ╠═499dc896-5c55-4bee-a9e3-e006c495c67d # ╠═45060fd5-db50-4222-8e0d-3d7bb8be5b08 # ╠═ec2e9079-f447-4da5-ac08-b63b7cf4d4a4 # ╠═e027e8fd-a918-4a64-a88b-54fc7d5ce4b4 # ╠═ffa1c8de-b952-4718-bcc5-5c65fe721dc8 # ╠═2a5f7dea-5ae4-4da7-906f-0b9810e9cea0 # ╠═311d401a-8778-4362-b2b3-01df66b37142 # ╠═28ea219e-fbf7-477a-b245-95fc7397b256 # ╠═528af444-1692-433f-9800-763cb1da56d3 # ╠═764e6a45-fe29-47a8-914a-21c545887c3c # ╠═bb22078d-fe42-4f4c-8b0b-0b4cb1f71469 # ╠═bf4cbe82-43c8-4f5b-bffb-9a0e7ffa8d93 # ╠═08fa8033-ab7b-483d-9500-6c32c4f243c3 # ╠═98d20964-0a16-43d4-aadc-e56aec601213 # ╠═75fd60e7-d96d-4edb-9766-ff41ef600805 # ╠═f4408b75-8a25-42e7-917b-42f9c0bfff2e # ╠═3093d613-5109-4051-b8f6-935b842246a6 # ╠═20270e3d-9e84-4ff5-811c-47e80d5459d3 # ╠═0b86cc10-63cb-42a2-9812-1384c097ae35 # ╠═626c4687-0719-4651-bb3b-1d638d936b7e # ╠═9ee344ee-e3a0-44c0-9627-6855e942c789 # ╠═34e7c893-902f-4868-8855-ad83b56b4b8c # ╠═6c7e3124-ea5f-4e58-820a-abaf55fed480 # ╠═009b37eb-f3a0-418b-971c-0bcbe9ef94fb # ╠═c2db935d-f49c-4538-acbd-de75399ae932 # ╠═2de6853a-9c0b-414f-a3fa-af38bf407a6a # ╠═e2bf6f84-a9f1-4dc4-be6a-3280451cc1ae # ╠═c901457f-312b-4dee-98ed-b81493f56030 # ╠═b1a61755-8791-48e6-90dd-cb6023034395 # ╠═4e6fe563-2c1b-42dc-a83e-3c4207e447d2 # ╠═107f0e6d-a9a1-4414-bf45-b0b0b1c57c67 # ╠═ee04f0e0-3a93-4adf-9b90-83987e1f1d1e # ╠═e6da06de-fc3e-4a89-868f-62dc47490126 # ╠═a2efce21-5f2a-43b9-9e1b-1861220617a7 # ╠═ed5802e5-65a1-4e8c-a633-613a07a3bfec # ╠═c0634c82-f36c-4bfa-8284-564adc309932 # ╠═3aeeeb61-e004-4317-81c7-aa37d7ade55e # ╠═ee03f50a-3def-44aa-b14d-c4b5da7a9a63 # ╠═72dfa3c2-ec92-4c97-98a7-525964218356 # ╠═6d699f5b-0ac0-40b9-a601-ec0205131cdd # ╠═08c1fbea-ad4f-414d-a942-6445a5fc8f62 # ╠═2c1e30ce-f3fa-4a67-b4f3-0587f466ec00 # ╠═12cb9501-d815-45ef-84b2-2886e180a90c # ╠═ecc4cd83-cc73-4358-8df5-25d566b36185 # ╠═cbb9f819-2645-4f7d-9c61-537041bd5466 # ╠═263b9a78-34bb-44a5-bf76-b5d402a4579e # ╠═52cf77af-1fee-4b47-8f02-5c94e060a401 # ╠═50f35a40-8fee-4a3f-b3a9-b344a8c4253e # ╠═6e8eafa8-6854-4b4b-8a02-a82f08314505 # ╠═81ecd06e-8c13-4dc0-81c9-ed575b8303bb # ╠═95cf6d4e-a89b-40c1-a6b0-2f0692c27651 # ╠═eccb8cec-d709-4682-bc34-2867402a6cfc # ╠═86bbd468-ecc4-4026-9dd4-5d8f2b9d50dc # ╠═e69776d2-3640-4c9f-aef2-d30a94dee390 # ╠═8ba893b5-97fc-4a41-9dc5-67f9c11708bc # ╠═acec4361-d271-41dd-b6cf-4571eae16406 # ╠═38fb2132-8f03-4b5c-aa76-a265bac69497 # ╠═454d0957-0cdc-4490-bbdc-8409b07cddcd # ╠═ff622ae3-b4ea-4b0c-90cb-a6d1cd7c857e # ╠═c49773c7-cb73-437c-abb2-3e05e9b3c4f7 # ╠═cd93d1b5-b587-4dc3-ae93-de0489163c3a # ╠═96202339-68d6-4d8b-af6e-f56e4b6b282d # ╠═fd9351e2-e0b8-4042-b2d2-0b8cddf76b8a # ╠═efdf00c9-f0b0-4d9b-b940-e0f4168220ac # ╠═c1ad8951-554a-4f9c-ac02-2b86c69210e9 # ╠═005f08fc-15b8-4927-bf4f-6f656bd7c509 # ╠═0b81cbeb-e441-4ff7-8586-4aaaa14a5204 # ╠═85c381d1-aa5b-4e36-b764-4f2c08056723 # ╠═bdab1a2a-e3e9-4dd6-ba5a-3f1cbd430e9a # ╠═d348eb2c-ce88-4813-9fdd-dbb9f6263c79 # ╠═f66dca42-73e6-4ed9-be87-8092f45f75ae # ╠═87c933d0-d56f-41ec-9740-42da3aea7b02 # ╠═adef617a-8b1f-4198-ba22-95c2fc23e487 # ╠═7d8430ce-3b06-4007-a091-dd00ebe5a4bd # ╠═46f31f61-afaa-4788-8f44-b83face4b005 # ╠═cb438dec-931a-4856-91ad-809d9d4d9106 # ╠═490769ee-72b2-46cd-aa88-e5b3bfe2ca9e # ╠═6310d056-f97b-444e-b257-3b22774f7e86 # ╠═e946a789-e9e1-4f46-b7b6-d278c0d6234c # ╠═bcae0cbd-d30f-458a-bc74-e969dab36ed1 # ╠═783edc23-96fe-4484-bef0-7666668171ac # ╠═a63091de-654b-43fa-93ab-466fb7ad7f38 # ╠═5e351fca-85ea-4e52-b607-e693deac1719 # ╠═64d4462f-f8fd-4186-9d48-dffd76c12fe6 # ╠═38a542dc-eee3-45b5-a52f-e342af3da728 # ╠═e2518ebc-0bfe-4ce4-9775-cd2c5abaf201 # ╠═49c607c2-c386-4ba9-817b-c80317c0c51f # ╠═3bf66bee-e84b-4293-83f0-b5af13a3f3eb # ╠═c2d3f70e-19ef-4e59-9d22-5728a1e0f0e7 # ╠═ff666cf9-42dc-4dfc-88bc-6ccd5f1065d5 # ╠═222b9658-7aba-426a-a5bd-42dee53f4365 # ╠═46253de4-245c-449f-9144-5fbe0fe52af1 # ╠═99a8113d-19c3-484c-a589-d75174b27422 # ╠═adb5bf96-3f83-41ac-bfb0-2e2e1ee2e8b6 # ╠═362bf8c3-e5d4-4631-849e-9f1af5264453 # ╠═79a0555b-3815-4a8a-ad82-297bb0721c34 # ╠═4ac3df0d-cf63-4cab-8c7c-6ce37a3589b2 # ╠═3845701a-4d36-4b40-a5e9-df3b3578c7a5 # ╠═38f77f4d-da45-4ebf-9916-a3ddb03fb39e # ╠═17536f1d-bbb0-46d9-91a6-e094b749ec9e # ╠═9eeb9b8a-c943-421c-a414-7bd7069bbcae # ╠═374a0805-1ed4-4eef-bab7-cc4da4659a72 # ╠═1dd794a3-61c0-4f27-af0d-89bfdc973bdb # ╠═d9a58858-2bb1-44b3-a4c6-30b5d62936c4 # ╠═fe58c5a4-8193-440d-be36-ac989017dc42 # ╠═4b158c96-0273-46f1-b6fe-c75fb0974dae # ╠═371e9b4c-1a94-42a9-b4ee-a837bd005a7a # ╠═fd45ccc8-7d10-4081-b681-ea398248b495 # ╠═05e57f17-784e-49e5-815e-f7d94aea5ab8 # ╠═466b9320-6fe1-41df-9dae-7c90a12fca5d # ╠═8ae1afae-ea67-49d9-be53-7909885fb083 # ╠═91559ca4-aa63-409c-a9da-c02726121bee # ╠═27cdd96d-774e-4afb-b680-4f3f52a21e94 # ╠═f23449ba-ad22-4f75-a896-3aa8f94a3b74 # ╠═0d499e42-4467-4384-a5f9-193f259fec60 # ╠═6b3dc5c1-7c61-47fc-ae1b-03f4116de245 # ╠═27d5e59d-e9a0-49b3-805b-1637a5e9d078 # ╠═ca1077c7-6bfe-406f-95d5-1686328022e2 # ╟─00000000-0000-0000-0000-000000000001 # ╟─00000000-0000-0000-0000-000000000002
import GetC.@getCFun #function bodies @getCFun "libGLU" gluQuadricTexture gluQuadricTexture(quad::Ptr{Void},texture::GLboolean)::Void @getCFun "libGLU" strtoimax strtoimax(__nptr::Ptr,__endptr::Ptr,__base::Int32)::intmax_t @getCFun "libGLU" wcstoimax wcstoimax(__nptr::Ptr,__endptr::Ptr,__base::Int32)::intmax_t @getCFun "libGLU" imaxabs imaxabs(__n::intmax_t)::intmax_t @getCFun "libGLU" imaxdiv imaxdiv(__numer::intmax_t,__denom::intmax_t)::imaxdiv_t @getCFun "libGLU" strtoumax strtoumax(__nptr::Ptr,__endptr::Ptr,__base::Int32)::uintmax_t @getCFun "libGLU" gluDisk gluDisk(quad::Ptr{Void},inner::GLdouble,outer::GLdouble,slices::GLint,stacks::GLint)::Void @getCFun "libGLU" wcstoumax wcstoumax(__nptr::Ptr,__endptr::Ptr,__base::Int32)::uintmax_t @getCFun "libGLU" gluNewQuadric gluNewQuadric()::Ptr{Void} @getCFun "libGLU" gluPerspective gluPerspective(fovy::GLdouble,aspect::GLdouble,znear::GLdouble,zfar::GLdouble)::Void @getCFun "libGLU" gluBuild2DMipmaps gluBuild2DMipmaps(target::GLenum,internalFormat::GLint,width::GLsizei,height::GLsizei,format::GLenum,thetype::GLenum,data::Ptr{Uint8})::GLint @getCFun "libGLU" gluCylinder gluCylinder(quad::Ptr{Void},base::GLdouble,top::GLdouble,height::GLdouble,slices::GLint,stacks::GLint)::Void @getCFun "libGLU" gluPartialDisk gluPartialDisk(quad::Ptr{Void},inner::GLdouble,outer::GLdouble,slices::GLint,loops::GLint,start::GLdouble,sweep::GLdouble)::Void @getCFun "libGLU" gluSphere gluSphere(quad::Ptr{Void},radius::GLdouble,slices::GLint,stacks::GLint)::Void @getCFun "libGLU" gluQuadricNormals gluQuadricNormals(quad::Ptr{Void},normal::GLenum)::Void #constants const GL_GLU_VERTEX = 100101 const GL_GLU_NURBS_ERROR6 = 100256 const GL_GLU_NURBS_TESSELLATOR_EXT = 100161 const GL_GLU_TESS_BOUNDARY_ONLY = 100141 const GL_GLU_TESS_END = 100102 const GL_GLU_OUTLINE_POLYGON = 100240 const GL_GLU_NURBS_ERROR19 = 100269 const GL_GLU_NURBS_ERROR21 = 100271 const GL_GLU_NURBS_ERROR20 = 100270 const GL_GLU_NURBS_ERROR36 = 100286 const GL_GLU_DISPLAY_MODE = 100204 const GL_GLU_SILHOUETTE = 100013 const GL_GLU_OUTSIDE = 100020 const GL_GLU_CCW = 100121 const GL_GLU_TESS_WINDING_NEGATIVE = 100133 const GL_GLU_TESS_ERROR8 = 100158 const GL_GLU_NURBS_ERROR18 = 100268 const GL_GLU_NURBS_BEGIN_EXT = 100164 const GL_GLU_NURBS_NORMAL = 100166 const GL_GLU_CULLING = 100201 const GL_GLU_EXT_object_space_tess = 1 const GL_GLU_NURBS_TEX_COORD_DATA_EXT = 100174 const GL_GLU_PARAMETRIC_ERROR = 100216 const GL_GLU_TESS_BEGIN_DATA = 100106 const GL_GLU_NURBS_ERROR12 = 100262 const GL_GLU_NURBS_MODE = 100160 const GL_GLU_TESS_ERROR3 = 100153 const GL_GLU_TESS_NEED_COMBINE_CALLBACK = 100156 const GL_GLU_INTERIOR = 100122 const GL_GLU_INSIDE = 100021 const GL_GLU_TESS_EDGE_FLAG = 100104 const GL_GLU_NURBS_ERROR9 = 100259 const GL_GLU_TESS_MISSING_END_CONTOUR = 100154 const GL_GLU_NURBS_ERROR7 = 100257 const GL_GLU_V_STEP = 100207 const GL_GLU_TESS_MISSING_BEGIN_CONTOUR = 100152 const GL_GLU_INVALID_VALUE = 100901 const GL_GLU_PATH_LENGTH = 100215 const GL_GLU_TESS_ERROR_DATA = 100109 const GL_GLU_EXTENSIONS = 100801 const GL_GLU_NURBS_ERROR17 = 100267 const GL_GLU_NURBS_ERROR1 = 100251 const GL_GLU_NURBS_NORMAL_EXT = 100166 const GL_GLU_NURBS_ERROR29 = 100279 const GL_GLU_AUTO_LOAD_MATRIX = 100200 const GL_GLU_MAP1_TRIM_3 = 100211 const GL_GLU_NONE = 100002 const GL_GLU_NURBS_ERROR16 = 100266 const GL_GLU_NURBS_VERTEX = 100165 const GL_GLU_EXT_nurbs_tessellator = 1 const GL_GLU_NURBS_ERROR33 = 100283 const GL_GLU_OBJECT_PARAMETRIC_ERROR = 100208 const GL_GLU_NURBS_END_EXT = 100169 const GL_GLU_EDGE_FLAG = 100104 const GL_GLU_TESS_ERROR5 = 100155 const GL_GLU_TESS_MISSING_END_POLYGON = 100153 const GL_GLU_TRUE = 1 const GL_GLU_NURBS_ERROR26 = 100276 const GL_GLU_NURBS_END_DATA = 100175 const GL_GLU_NURBS_TEXTURE_COORD_DATA = 100174 const GL_GLU_INVALID_ENUM = 100900 const GL_GLU_SAMPLING_TOLERANCE = 100203 const GL_GLU_TESS_WINDING_POSITIVE = 100132 const GL_GLU_LINE = 100011 const GL_GLU_VERSION_1_1 = 1 const GL_GLU_NURBS_COLOR_DATA = 100173 const GL_GLU_NURBS_ERROR25 = 100275 const GL_GLU_TESS_ERROR = 100103 const GL_GLU_NURBS_VERTEX_DATA = 100171 const GL_GLU_TESS_ERROR2 = 100152 const GL_GLU_NURBS_ERROR = 100103 const GL_GLU_VERSION_1_3 = 1 const GL_GLU_TESS_BEGIN = 100100 const GL_GLU_NURBS_RENDERER = 100162 const GL_GLU_TESS_WINDING_ODD = 100130 const GL_GLU_TESS_ERROR1 = 100151 const GL_GLU_TESS_ERROR6 = 100156 const GL_GLU_OUTLINE_PATCH = 100241 const GL_GLU_VERSION = 100800 const GL_GLU_OBJECT_PARAMETRIC_ERROR_EXT = 100208 const GL_GLU_SAMPLING_METHOD = 100205 const GL_GLU_NURBS_TEX_COORD_EXT = 100168 const GL_GLU_TESS_VERTEX = 100101 const GL_GLU_POINT = 100010 const GL_GLU_FALSE = 0 const GL_GLU_NURBS_VERTEX_EXT = 100165 const GL_GLU_NURBS_BEGIN_DATA_EXT = 100170 const GL_GLU_TESS_EDGE_FLAG_DATA = 100110 const GL_GLU_FILL = 100012 const GL_GLU_OBJECT_PATH_LENGTH = 100209 const GL_GLU_NURBS_ERROR30 = 100280 const GL_GLU_SMOOTH = 100000 const GL_GLU_CW = 100120 const GL_GLU_TESS_END_DATA = 100108 const GL_GLU_NURBS_ERROR15 = 100265 const GL_GLU_NURBS_ERROR27 = 100277 const GL_GLU_NURBS_ERROR22 = 100272 const GL_GLU_NURBS_ERROR32 = 100282 const GL_GLU_EXTERIOR = 100123 const GL_GLU_TESS_ERROR4 = 100154 const GL_GLU_NURBS_ERROR13 = 100263 const GL_GLU_DOMAIN_DISTANCE = 100217 const GL_GLU_NURBS_ERROR34 = 100284 const GL_GLU_NURBS_ERROR23 = 100273 const GL_GLU_NURBS_ERROR4 = 100254 const GL_GLU_NURBS_COLOR_DATA_EXT = 100173 const GL_GLU_NURBS_ERROR8 = 100258 const GL_GLU_NURBS_COLOR_EXT = 100167 const GL_GLU_NURBS_ERROR31 = 100281 const GL_GLU_NURBS_ERROR2 = 100252 const GL_GLU_NURBS_ERROR28 = 100278 const GL_GLU_TESS_WINDING_ABS_GEQ_TWO = 100134 const GL_GLU_NURBS_ERROR11 = 100261 const GL_GLU_NURBS_END_DATA_EXT = 100175 const GL_GLU_NURBS_ERROR37 = 100287 const GL_GLU_UNKNOWN = 100124 const GL_GLU_BEGIN = 100100 const GL_GLU_NURBS_ERROR24 = 100274 const GL_GLU_OBJECT_PATH_LENGTH_EXT = 100209 const GL_GLU_ERROR = 100103 const GL_GLU_TESS_VERTEX_DATA = 100107 const GL_GLU_TESS_ERROR7 = 100157 const GL_GLU_NURBS_NORMAL_DATA_EXT = 100172 const GL_GLU_TESS_COORD_TOO_LARGE = 100155 const GL_GLU_NURBS_BEGIN_DATA = 100170 const GL_GLU_NURBS_VERTEX_DATA_EXT = 100171 const GL_GLU_NURBS_TEXTURE_COORD = 100168 const GL_GLU_NURBS_NORMAL_DATA = 100172 const GL_GLU_NURBS_ERROR10 = 100260 const GL_GLU_TESS_MISSING_BEGIN_POLYGON = 100151 const GL_GLU_NURBS_END = 100169 const GL_GLU_NURBS_ERROR5 = 100255 const GL_GLU_END = 100102 const GL_GLU_TESS_WINDING_NONZERO = 100131 const GL_GLU_TESS_MAX_COORD = 1.0e150 const GL_GLU_NURBS_ERROR35 = 100285 const GL_GLU_TESS_COMBINE_DATA = 100111 const GL_GLU_TESS_WINDING_RULE = 100140 const GL_GLU_NURBS_ERROR3 = 100253 const GL_GLU_NURBS_RENDERER_EXT = 100162 const GL_GLU_TESS_TOLERANCE = 100142 const GL_GLU_FLAT = 100001 const GL_GLU_PARAMETRIC_TOLERANCE = 100202 const GL_GLU_INVALID_OPERATION = 100904 const GL_GLU_NURBS_MODE_EXT = 100160 const GL_GLU_NURBS_TESSELLATOR = 100161 const GL_GLU_TESS_COMBINE = 100105 const GL_GLU_INCOMPATIBLE_GL_VERSION = 100903 const GL_GLU_VERSION_1_2 = 1 const GL_GLU_NURBS_ERROR14 = 100264 const GL_GLU_MAP1_TRIM_2 = 100210 const GL_GLU_OUT_OF_MEMORY = 100902 const GL_GLU_NURBS_COLOR = 100167 const GL_GLU_NURBS_BEGIN = 100164 const GL_GLU_U_STEP = 100206 # Export everything! export gluQuadricTexture, strtoimax, wcstoimax, imaxabs, imaxdiv, strtoumax, gluDisk, wcstoumax, gluNewQuadric, gluPerspective, gluBuild2DMipmaps, gluCylinder, gluPartialDisk, gluSphere, gluQuadricNormals, GL_GLU_VERTEX, GL_GLU_NURBS_ERROR6, GL_GLU_NURBS_TESSELLATOR_EXT, GL_GLU_TESS_BOUNDARY_ONLY, GL_GLU_TESS_END, GL_GLU_OUTLINE_POLYGON, GL_GLU_NURBS_ERROR19, GL_GLU_NURBS_ERROR21, GL_GLU_NURBS_ERROR20, GL_GLU_NURBS_ERROR36, GL_GLU_DISPLAY_MODE, GL_GLU_SILHOUETTE, GL_GLU_OUTSIDE, GL_GLU_CCW, GL_GLU_TESS_WINDING_NEGATIVE, GL_GLU_TESS_ERROR8, GL_GLU_NURBS_ERROR18, GL_GLU_NURBS_BEGIN_EXT, GL_GLU_NURBS_NORMAL, GL_GLU_CULLING, GL_GLU_EXT_object_space_tess, GL_GLU_NURBS_TEX_COORD_DATA_EXT, GL_GLU_PARAMETRIC_ERROR, GL_GLU_TESS_BEGIN_DATA, GL_GLU_NURBS_ERROR12, GL_GLU_NURBS_MODE, GL_GLU_TESS_ERROR3, GL_GLU_TESS_NEED_COMBINE_CALLBACK, GL_GLU_INTERIOR, GL_GLU_INSIDE, GL_GLU_TESS_EDGE_FLAG, GL_GLU_NURBS_ERROR9, GL_GLU_TESS_MISSING_END_CONTOUR, GL_GLU_NURBS_ERROR7, GL_GLU_V_STEP, GL_GLU_TESS_MISSING_BEGIN_CONTOUR, GL_GLU_INVALID_VALUE, GL_GLU_PATH_LENGTH, GL_GLU_TESS_ERROR_DATA, GL_GLU_EXTENSIONS, GL_GLU_NURBS_ERROR17, GL_GLU_NURBS_ERROR1, GL_GLU_NURBS_NORMAL_EXT, GL_GLU_NURBS_ERROR29, GL_GLU_AUTO_LOAD_MATRIX, GL_GLU_MAP1_TRIM_3, GL_GLU_NONE, GL_GLU_NURBS_ERROR16, GL_GLU_NURBS_VERTEX, GL_GLU_EXT_nurbs_tessellator, GL_GLU_NURBS_ERROR33, GL_GLU_OBJECT_PARAMETRIC_ERROR, GL_GLU_NURBS_END_EXT, GL_GLU_EDGE_FLAG, GL_GLU_TESS_ERROR5, GL_GLU_TESS_MISSING_END_POLYGON, GL_GLU_TRUE, GL_GLU_NURBS_ERROR26, GL_GLU_NURBS_END_DATA, GL_GLU_NURBS_TEXTURE_COORD_DATA, GL_GLU_INVALID_ENUM, GL_GLU_SAMPLING_TOLERANCE, GL_GLU_TESS_WINDING_POSITIVE, GL_GLU_LINE, GL_GLU_VERSION_1_1, GL_GLU_NURBS_COLOR_DATA, GL_GLU_NURBS_ERROR25, GL_GLU_TESS_ERROR, GL_GLU_NURBS_VERTEX_DATA, GL_GLU_TESS_ERROR2, GL_GLU_NURBS_ERROR, GL_GLU_VERSION_1_3, GL_GLU_TESS_BEGIN, GL_GLU_NURBS_RENDERER, GL_GLU_TESS_WINDING_ODD, GL_GLU_TESS_ERROR1, GL_GLU_TESS_ERROR6, GL_GLU_OUTLINE_PATCH, GL_GLU_VERSION, GL_GLU_OBJECT_PARAMETRIC_ERROR_EXT, GL_GLU_SAMPLING_METHOD, GL_GLU_NURBS_TEX_COORD_EXT, GL_GLU_TESS_VERTEX, GL_GLU_POINT, GL_GLU_FALSE, GL_GLU_NURBS_VERTEX_EXT, GL_GLU_NURBS_BEGIN_DATA_EXT, GL_GLU_TESS_EDGE_FLAG_DATA, GL_GLU_FILL, GL_GLU_OBJECT_PATH_LENGTH, GL_GLU_NURBS_ERROR30, GL_GLU_SMOOTH, GL_GLU_CW, GL_GLU_TESS_END_DATA, GL_GLU_NURBS_ERROR15, GL_GLU_NURBS_ERROR27, GL_GLU_NURBS_ERROR22, GL_GLU_NURBS_ERROR32, GL_GLU_EXTERIOR, GL_GLU_TESS_ERROR4, GL_GLU_NURBS_ERROR13, GL_GLU_DOMAIN_DISTANCE, GL_GLU_NURBS_ERROR34, GL_GLU_NURBS_ERROR23, GL_GLU_NURBS_ERROR4, GL_GLU_NURBS_COLOR_DATA_EXT, GL_GLU_NURBS_ERROR8, GL_GLU_NURBS_COLOR_EXT, GL_GLU_NURBS_ERROR31, GL_GLU_NURBS_ERROR2, GL_GLU_NURBS_ERROR28, GL_GLU_TESS_WINDING_ABS_GEQ_TWO, GL_GLU_NURBS_ERROR11, GL_GLU_NURBS_END_DATA_EXT, GL_GLU_NURBS_ERROR37, GL_GLU_UNKNOWN, GL_GLU_BEGIN, GL_GLU_NURBS_ERROR24, GL_GLU_OBJECT_PATH_LENGTH_EXT, GL_GLU_ERROR, GL_GLU_TESS_VERTEX_DATA, GL_GLU_TESS_ERROR7, GL_GLU_NURBS_NORMAL_DATA_EXT, GL_GLU_TESS_COORD_TOO_LARGE, GL_GLU_NURBS_BEGIN_DATA, GL_GLU_NURBS_VERTEX_DATA_EXT, GL_GLU_NURBS_TEXTURE_COORD, GL_GLU_NURBS_NORMAL_DATA, GL_GLU_NURBS_ERROR10, GL_GLU_TESS_MISSING_BEGIN_POLYGON, GL_GLU_NURBS_END, GL_GLU_NURBS_ERROR5, GL_GLU_END, GL_GLU_TESS_WINDING_NONZERO, GL_GLU_TESS_MAX_COORD, GL_GLU_NURBS_ERROR35, GL_GLU_TESS_COMBINE_DATA, GL_GLU_TESS_WINDING_RULE, GL_GLU_NURBS_ERROR3, GL_GLU_NURBS_RENDERER_EXT, GL_GLU_TESS_TOLERANCE, GL_GLU_FLAT, GL_GLU_PARAMETRIC_TOLERANCE, GL_GLU_INVALID_OPERATION, GL_GLU_NURBS_MODE_EXT, GL_GLU_NURBS_TESSELLATOR, GL_GLU_TESS_COMBINE, GL_GLU_INCOMPATIBLE_GL_VERSION, GL_GLU_VERSION_1_2, GL_GLU_NURBS_ERROR14, GL_GLU_MAP1_TRIM_2, GL_GLU_OUT_OF_MEMORY, GL_GLU_NURBS_COLOR, GL_GLU_NURBS_BEGIN, GL_GLU_U_STEP
module EqualitySaturation using Mixtape using MacroTools using BenchmarkTools f(x) = (x - x) + (10 * 15) @ctx (true, true, false) struct MyMix end allow(ctx::MyMix, m::Module) = m == EqualitySaturation swap(e) = e function swap(e::Expr) new = MacroTools.postwalk(e) do s isexpr(s, :call) || return s s.args[1] == Base.literal_pow || return s return Expr(:call, apply, Base.:(*), s.args[3:end]...) end return new end function transform(::MyMix, b) return b end Mixtape.@load_call_interface() display(call(MyMix(), f, 3)) end # module
#= --------------------------------------------------------------------------- Implements a few collections that the main mcmc sampler from the file `mcmc.jl` uses to keep track of the current state and history of where it was. The following structures are defined: - AccptTracker : for tracking historical acceptance rate - ParamHistory : for storing the parameter chain - ActionTracker : keeps track of what to do on a given iteration - Workspace : main workspace for `mcmc` function from `mcmc.jl` - ParamUpdtDefn : defines a single parameter update step - GibbsDefn : defines an entire gibbs sweep of parameter updates --------------------------------------------------------------------------- =# import Base: last, getindex, length, display, eltype #=============================================================================== Workspace for the MCMC chain ===============================================================================# """ struct MCMCWorkspace{T,S,V} Implements a few collections that the main mcmc sampler from the file `mcmc.jl` uses to keep track of the current state and history of where it was. The following structures are defined: - `θ_chain` for the parameter chain - `updates` #TODO - `pos` for the current position of the sampler - `mean` for the current sample mean of the sampler - `cov` for the current sample covariance matrix of sampler - `updates_hist` #TODO """ struct MCMCWorkspace{T,S,V} θ_chain::Vector{T} updates::S pos::Vector{Bool} mean::Vector{V} cov::Matrix{V} updates_hist::Vector function MCMCWorkspace(setup::MCMCSetup, schedule, θ::T) where T # TODO create an object that pre-allocates the memory based on schedule # this is difficult due to potential fusing of kernels which results # in a random overall number of updates θ_chain = [θ] S = typeof(setup.updates) pos = list_of_pos_params(setup.updates, θ) V = eltype(θ) new{T,S,V}(θ_chain, setup.updates, pos, copy(θ), zero(θ*θ'), []) end end function list_of_pos_params(updates, θ) pos = fill(false, length(θ)) for updt in updates if typeof(updt) <: ParamUpdate{MetropolisHastingsUpdt} ind_pos = indices_of_pos(updt.updt_coord, updt.t_kernel.pos) for (c,p) in ind_pos if p pos[c] = true end end end end pos end function indices_of_pos(coords, pos) coord_indices = indices(coords) @assert length(coord_indices) == length(pos) zip(coord_indices, pos) end function update!(ws::MCMCWorkspace, acc, θ, i) not_imputation = !(typeof(ws.updates[i]) <: Imputation) not_imputation && push!(ws.θ_chain, θ) not_imputation && update_mean_cov!(ws.mean, ws.cov, θ, length(ws.θ_chain), ws.pos) register_accpt!(ws.updates[i], acc) end function update_mean_cov!(θ_mean, θ_cov, θ, θ_len, pos) ϑ = neutralise_domain(θ, pos) prev_mean = copy(θ_mean) θ_mean .*= θ_len/(θ_len+1) θ_mean .+= (ϑ./(θ_len+1)) old_sum_sq = (θ_len-1)/θ_len * θ_cov + prev_mean * prev_mean' new_sum_sq = old_sum_sq + (ϑ * ϑ')/(θ_len) θ_cov .= new_sum_sq - (θ_len+1)/θ_len * (θ_mean * θ_mean') end function neutralise_domain(θ, pos) ϑ = copy(θ) ϑ[pos] = log.(ϑ[pos]) ϑ end function readjust!(ws::MCMCWorkspace, mcmc_iter) for i in 1:length(ws.updates) readjust!(ws.updates[i], ws.cov, mcmc_iter) end end function fuse!(ws::MCMCWorkspace, schedule) # NOTE for now, the `fuse!` function is quite restricted and will fuse all # Metropolis-Hastings transition kernels into a single one MH_updates = [u for u in ws.updates if typeof(u) <: ParamUpdate{<:MetropolisHastingsUpdt}] order_updates!(MH_updates) fusion_updt_coord = fuse_coord(MH_updates) fusion_cov = Matrix(view(ws.cov, fusion_updt_coord, fusion_updt_coord)) fusion_kernel = fuse_kernels(MH_updates, fusion_cov) fusion_priors = fuse_priors(MH_updates) fusion_aux = fuse_aux(MH_updates) fusion_param_updt = ParamUpdate(MetropolisHastingsUpdt(), fusion_updt_coord, ws.θ_chain[end], fusion_kernel, fusion_priors, fusion_aux) push!(ws.updates, fusion_param_updt) MH_updt_idx = [i for (i,u) in enumerate(ws.updates) if typeof(u) <: ParamUpdate{<:MetropolisHastingsUpdt}] reschedule!(schedule, MH_updt_idx, length(ws.updates)) end """ getindex(g::MCMCWorkspace, i::Int) Return `i`th definition of parameter update """ getindex(g::MCMCWorkspace, i::Int) = g.updates[i] """ length(g::MCMCWorkspace) Return the total number of parameter updates in a single Gibbs sweep """ length(g::MCMCWorkspace) = length(g.updates) mutable struct SingleElem{T} val::T end set!(x::SingleElem{T}, y::T) where T = (x.val = y) #=============================================================================== Workspace for the Diffusion Model ===============================================================================# """ Workspace{ObsScheme,S,TX,TW,R,TP,TZ} The main container of the `mcmc` function from `mcmc.jl` in which most data pertinent to sampling is stored """ struct Workspace{ObsScheme,S,TX,TW,R,TP,TZ}# ,Q, where Q = eltype(result) # Related to imputed path Wnr::Wiener{S} # Wiener, driving law XXᵒ::Vector{TX} # Diffusion proposal paths XX::Vector{TX} # Accepted diffusion paths WWᵒ::Vector{TW} # Driving noise of proposal WW::Vector{TW} # Driving noise of the accepted paths Pᵒ::Vector{R} # Guided proposals parameterised by proposal param P::Vector{R} # Guided proposals parameterised by accepted param fpt::Vector # Additional information about first passage times # Related to historically sampled paths skip_for_save::Int64 # Thining parameter for saving path paths::Vector # Storage with historical, accepted paths time::Vector{Float64} # Storage with time axis # Related to the starting point x0_prior::TP z::SingleElem{TZ} #recompute_ODEs::Vector{Bool} # Info on whether to recompute H,Hν,c after resp. param updt """ Workspace(setup::DiffusionSetup{ObsScheme}) Initialise workspace of the mcmc sampler according to a `setup` variable """ function Workspace(setup::DiffusionSetup{ObsScheme}) where ObsScheme x0_prior, Wnr = deepcopy(setup.x0_prior), deepcopy(setup.Wnr) XX, WW = deepcopy(setup.XX), deepcopy(setup.WW) P, fpt = deepcopy(setup.P), deepcopy(setup.fpt) # forcedSolve defines type by the starting point, make sure it matches x0_guess = eltype(eltype(XX))(setup.x0_guess) TW, TX, S, R = eltype(WW), eltype(XX), valtype(Wnr), eltype(P) TP = typeof(x0_prior) m = length(P) y = copy(x0_guess) for i in 1:m WW[i] = Bridge.samplepath(P[i].tt, zero(S)) sample!(WW[i], Wnr) WW[i], XX[i] = forcedSolve(EulerMaruyamaBounded(), y, WW[i], P[i]) # this will enforce adherence to domain while !checkFpt(ObsScheme(), XX[i], fpt[i]) sample!(WW[i], Wnr) forcedSolve!(EulerMaruyamaBounded(), XX[i], y, WW[i], P[i]) # this will enforce adherence to domain end y = XX[i].yy[end] end y = x0_guess ll = ( logpdf(x0_prior, y) + path_log_likhd(ObsScheme(), XX, P, 1:m, fpt, skipFPT=true) + lobslikelihood(P[1], y) ) XXᵒ, WWᵒ, Pᵒ = deepcopy(XX), deepcopy(WW), deepcopy(P) # compute the white noise that generates x0_guess under the initial posterior z = inv_start_pt(y, x0_prior, P[1]) TZ = typeof(z) z = SingleElem{TZ}(z) skip = setup.skip_for_save _time = collect(Iterators.flatten(p.tt[1:skip:end-1] for p in P)) #check_if_recompute_ODEs(setup) (workspace = new{ObsScheme,S,TX,TW,R,TP,TZ}(Wnr, XXᵒ, XX, WWᵒ, WW, Pᵒ, P, fpt, skip, [], _time, x0_prior, z), ll = ll, θ = params(P[1].Target)) end function Workspace(ws::Workspace{ObsScheme,S,TX,TW,R̃,TP,TZ}, P::Vector{R}, Pᵒ::Vector{R}) where {ObsScheme,S,TX,TW,R̃,R,TP,TZ} new{ObsScheme,S,TX,TW,R,TP,TZ}(ws.Wnr, ws.XXᵒ, ws.XX, ws.WWᵒ, ws.WW, Pᵒ, P, ws.fpt, ws.skip_for_save, ws.paths, ws.time, ws.x0_prior, ws.z) end end eltype(::SamplePath{T}) where T = T eltype(::Type{SamplePath{T}}) where T = T solver_type(::Workspace{O,B,ST}) where {O,B,ST} = ST obs_scheme(::Workspace{O}) where O = O() next(ws::Workspace, ::Any) = ws function next(ws::Workspace, updt::Imputation{<:Block}) XX, P, Pᵒ, bl = ws.XX, ws.P, ws.Pᵒ, updt.blocking θ = params(P[1].Target) vs = find_end_pts(bl, XX) P_new = [GuidPropBridge(Pi, bl.Ls[i], vs[i], bl.Σs[i], bl.change_pts[i], θ, bl.aux_flags[i]) for (i,Pi) in enumerate(P)] Pᵒ_new = [GuidPropBridge(Pᵒi, bl.Ls[i], vs[i], bl.Σs[i], bl.change_pts[i], θ, bl.aux_flags[i]) for (i,Pᵒi) in enumerate(Pᵒ)] Workspace(ws, P_new, Pᵒ_new) end """ save_imputed!(ws::Workspace) Save the entire path spanning all segments in `XX`. Only 1 in every `ws.skip_for_save` points is saved to reduce storage space. """ function save_imputed!(ws::Workspace) skip = ws.skip_for_save push!(ws.paths, collect(Iterators.flatten(ws.XX[i].yy[1:skip:end-1] for i in 1:length(ws.XX)))) end function adaptation_object(setup::DiffusionSetup, ws::Workspace) adpt = deepcopy(setup.adaptive_prop) if typeof(adpt) <: Adaptation{Val{false}} return nothing end m = length(ws.XX) resize!(adpt, m, [length(ws.XX[i]) for i in 1:m]) adpt end function create_workspace(setup::MCMCSetup, schedule::MCMCSchedule, θ) MCMCWorkspace(setup, schedule, θ) end function create_workspace(setup::T) where {T <: ModelSetup} Workspace(setup) end
## Poisson regression struct analysis_Poisson_Reg formula::FormulaTerm #modelClass::PoissonRegression #LikelihoodMod::String #PriorMod::String #Link::String #ComputeMethod::String fit beta LogLike::Float64 #LogPost::Float64 AIC::Float64 BIC::Float64 #R_sqr::Float64 #Adjusted_R_sqr::Float64 #sigma::Float64 #Cooks_distance end function Poisson_Reg(formula::FormulaTerm,data::DataFrame) formula = apply_schema(formula, schema(formula, data)); y, X = modelcols(formula, data); fm_frame=ModelFrame(formula,data); X=modelmatrix(fm_frame); p = size(X, 2); n = size(X, 1); ## Fit Model res = glm(formula,data,Poisson(), LogLink()); fit = coeftable(res) beta_hat = coef(res) logLike = GLM.loglikelihood(res) npar = p; AIC = 2*npar - 2*logLike BIC = log(n)*npar - 2*logLike ans = analysis_Poisson_Reg(formula,fit,beta_hat,logLike,AIC,BIC) ans end function Poisson_Reg_predicts(obj,newdata::DataFrame) formula = obj.formula; fm_frame=ModelFrame(formula,newdata); X=modelmatrix(fm_frame); beta = obj.beta z = X*beta; μ = exp.(z) ; μ end ## Poisson Regression with Ridge Prior function Poisson_Reg(formula::FormulaTerm,data::DataFrame,PriorMod::Prior_Ridge,h::Float64,sim_size::Int64) formula = apply_schema(formula, schema(formula, data)); y, X = modelcols(formula, data); @model PoissonReg(X, y) = begin p = size(X, 2); n = size(X, 1); #priors λ~InverseGamma(h,h) α ~ Normal(0,λ) β ~ filldist(Normal(0,λ), p) ## link z = α .+ X * β mu = exp.(z) #likelihood for i = 1:n y[i] ~ Poisson(mu[i]) end end PoissonReg_model=PoissonReg(X,y); chain = sample(CRRao_rng, PoissonReg_model, NUTS(), sim_size); summaries, quantiles = describe(chain); ans = MCMC_chain(chain,summaries,quantiles) ans end ## Poisson Regression with Laplace Prior function Poisson_Reg(formula::FormulaTerm,data::DataFrame,PriorMod::Prior_Laplace,h::Float64,sim_size::Int64) formula = apply_schema(formula, schema(formula, data)); y, X = modelcols(formula, data); @model PoissonReg(X, y) = begin p = size(X, 2); n = size(X, 1); #priors λ~InverseGamma(h,h) α ~ Laplace(0,λ) β ~ filldist(Laplace(0,λ), p) ## link z = α .+ X * β mu = exp.(z) #likelihood for i = 1:n y[i] ~ Poisson(mu[i]) end end PoissonReg_model=PoissonReg(X,y); chain = sample(CRRao_rng, PoissonReg_model, NUTS(), sim_size); summaries, quantiles = describe(chain); ans = MCMC_chain(chain,summaries,quantiles) ans end ## Poisson Regression with Cauchy Prior function Poisson_Reg(formula::FormulaTerm,data::DataFrame,PriorMod::Prior_Cauchy,h::Float64,sim_size::Int64) formula = apply_schema(formula, schema(formula, data)); y, X = modelcols(formula, data); @model PoissonReg(X, y) = begin p = size(X, 2); n = size(X, 1); #priors λ~InverseGamma(h,h) α ~ TDist(1)*λ β ~ filldist(TDist(1)*λ, p) ## link z = α .+ X * β mu = exp.(z) #likelihood for i = 1:n y[i] ~ Poisson(mu[i]) end end PoissonReg_model=PoissonReg(X,y); chain = sample(CRRao_rng, PoissonReg_model, NUTS(), sim_size); summaries, quantiles = describe(chain); ans = MCMC_chain(chain,summaries,quantiles) ans end ## Poisson Regression with T-Distributed Prior function Poisson_Reg(formula::FormulaTerm,data::DataFrame,PriorMod::Prior_TDist,h::Float64,sim_size::Int64) formula = apply_schema(formula, schema(formula, data)); y, X = modelcols(formula, data); @model PoissonReg(X, y) = begin p = size(X, 2); n = size(X, 1); #priors λ~InverseGamma(h,h) ν~InverseGamma(h,h) α ~ TDist(ν)*λ β ~ filldist(TDist(ν)*λ, p) ## link z = α .+ X * β mu = exp.(z) #likelihood for i = 1:n y[i] ~ Poisson(mu[i]) end end PoissonReg_model=PoissonReg(X,y); chain = sample(CRRao_rng, PoissonReg_model, NUTS(), sim_size); summaries, quantiles = describe(chain); ans = MCMC_chain(chain,summaries,quantiles) ans end ## Poisson Regression with Uniform Prior function Poisson_Reg(formula::FormulaTerm,data::DataFrame,PriorMod::Prior_Uniform,h::Float64,sim_size::Int64) formula = apply_schema(formula, schema(formula, data)); y, X = modelcols(formula, data); @model PoissonReg(X, y) = begin p = size(X, 2); n = size(X, 1); #priors λ~InverseGamma(h,h) α ~ Uniform(-λ,λ) β ~ filldist(Uniform(-λ,λ), p) ## link z = α .+ X * β mu = exp.(z) #likelihood for i = 1:n y[i] ~ Poisson(mu[i]) end end PoissonReg_model=PoissonReg(X,y); chain = sample(CRRao_rng, PoissonReg_model, NUTS(), sim_size); summaries, quantiles = describe(chain); ans = MCMC_chain(chain,summaries,quantiles) ans end
using BOMBS using Test using CSV using DataFrames using LinearAlgebra using Dates using Distributions using Random using CmdStan # -------------------------------------------------------- MODEL DEFINITION TESTS model_def = Dict(); model_def["NameF"] = []; model_def["nStat"] = []; model_def["nPar"] = []; model_def["nInp"] = []; model_def["stName"] = []; model_def["parName"] = []; model_def["inpName"] = []; model_def["eqns"] = []; model_def["Y0eqs"] = []; model_def["Y0Sim"] = []; model_def["tols"] = []; model_def["solver"] = []; model_def2 = defModStruct(); model_def2["NameF"] = "Test"; model_def2["nStat"] = 2; model_def2["nPar"] = 4; model_def2["nInp"] = 1; model_def2["stName"] = ["A", "B"]; model_def2["parName"] = ["k1", "k2", "k3", "k4"]; model_def2["inpName"] = ["inp1"]; model_def2["eqns"] = ["dA = k1*A - k2*A*inp1", "dB = k3*(A^2) - k4*B"]; model_def2["Y0eqs"] = ["A = 1", "B = k3*(A^2)/k4"]; model_def2["Y0Sim"] = false; model_def2["tols"] = [1e-5,1e-5]; model_def2["solver"] = "CVODE_BDF"; # -------------------------------------------------------- SIMULATION TESTS simul_def = Dict() simul_def["Nexp"] = []; simul_def["finalTime"] = []; simul_def["switchT"] = []; simul_def["y0"] = []; simul_def["preInd"] = []; simul_def["uInd"] = []; simul_def["theta"] = []; simul_def["tsamps"] = []; simul_def["plot"] = []; simul_def["flag"] = []; simul_def2 = defSimulStruct(); simul_def2["Nexp"] = 2; simul_def2["finalTime"] = [40, 40]; simul_def2["switchT"] = [[0,20,40], [0,20,40]]; simul_def2["y0"] = [[0,0], [0,0]]; simul_def2["preInd"] = [[0.1], [0.1]]; simul_def2["uInd"] = [[1,1], [1,1]]; simul_def2["theta"] = [0.1 0.2 0.2 0.02; 0.2 0.1 0.2 0.01; 1 1 1 0.1]; simul_def2["tsamps"] = [[0,5,10,15,20,25,30,35,40], [0,3,5,10,12,15,20,25,27, 30,33, 35,40]]; simul_def2["plot"] = false; simul_def2["flag"] = "testsim"; simul_def3 = Dict() simul_def3["ObservablesFile"] = []; simul_def3["EventInputsFile"] = []; simul_def3["theta"] = []; simul_def3["MainDir"] = []; simul_def3["plot"] = []; simul_def3["flag"] = []; simul_defCSV1 = Dict(); simul_defCSV1["ObservablesFile"] = ["TestSimulCSVObs.csv"]; simul_defCSV1["EventInputsFile"] = ["TestSimulCSVInps.csv"]; simul_defCSV1["theta"] = ["Theta1.csv"]; simul_defCSV1["MainDir"] = []; simul_defCSV1["plot"] = false; simul_defCSV1["flag"] = "testsimCSV"; simul_defCSV2 = Dict(); simul_defCSV2["Nexp"] = 1; simul_defCSV2["finalTime"] = [40]; simul_defCSV2["switchT"] = [[0.0,20.0,40.0]]; simul_defCSV2["y0"] = [[0,0]]; simul_defCSV2["preInd"] = [[0.1]]; simul_defCSV2["uInd"] = [reshape([1, 0.5], 2,1)]; simul_defCSV2["theta"] = [0.1 0.2 0.2 0.002]; simul_defCSV2["tsamps"] = [[0,5,10,15,20,25,30,35,40]]; simul_defCSV2["plot"] = false; simul_defCSV2["flag"] = "testsimCSV"; # -------------------------------------------------------- PSEUDO-DATA TESTS pseudo_def = Dict(); pseudo_def["Nexp"] = []; pseudo_def["finalTime"] = []; pseudo_def["switchT"] = []; pseudo_def["y0"] = []; pseudo_def["preInd"] = []; pseudo_def["uInd"] = []; pseudo_def["theta"] = []; pseudo_def["tsamps"] = []; pseudo_def["plot"] = []; pseudo_def["flag"] = []; pseudo_def["Obs"] = []; pseudo_def["Noise"] = []; pseudo_def2 = defPseudoDatStruct(); pseudo_def2["Nexp"] = 2; pseudo_def2["finalTime"] = [40, 40]; pseudo_def2["switchT"] = [[0,20,40], [0,20,40]]; pseudo_def2["y0"] = [[0,0], [0,0]]; pseudo_def2["preInd"] = [[0.1], [0.1]]; pseudo_def2["uInd"] = [[1,1], [1,1]]; pseudo_def2["theta"] = [0.1 0.2 0.2 0.02; 0.2 0.1 0.2 0.01; 1 1 1 0.1]; pseudo_def2["tsamps"] = [[0,5,10,15,20,25,30,35,40], [0,3,5,10,12,15,20,25,27, 30,33, 35,40]]; pseudo_def2["plot"] = false; pseudo_def2["flag"] = "testPD"; pseudo_def2["Obs"] = ["B*2"]; pseudo_def2["Noise"] = [0.1]; pseudo_def3 = Dict() pseudo_def3["ObservablesFile"] = []; pseudo_def3["EventInputsFile"] = []; pseudo_def3["theta"] = []; pseudo_def3["MainDir"] = []; pseudo_def3["plot"] = []; pseudo_def3["flag"] = []; pseudo_def3["Obs"] = []; pseudo_def3["Noise"] = []; pseudo_defCSV1 = Dict(); pseudo_defCSV1["ObservablesFile"] = ["TestSimulCSVObsPD.csv"]; pseudo_defCSV1["EventInputsFile"] = ["TestSimulCSVInpsPD.csv"]; pseudo_defCSV1["theta"] = ["Theta1PD.csv"]; pseudo_defCSV1["MainDir"] = []; pseudo_defCSV1["plot"] = false; pseudo_defCSV1["flag"] = "testPDCSV"; pseudo_defCSV1["Obs"] = ["B*2"]; pseudo_defCSV1["Noise"] = [0.1]; pseudo_defCSV2 = Dict(); pseudo_defCSV2["Nexp"] = 1; pseudo_defCSV2["finalTime"] = [40]; pseudo_defCSV2["switchT"] = [[0.0,20.0,40.0]]; pseudo_defCSV2["y0"] = [[0,0]]; pseudo_defCSV2["preInd"] = [[0.1]]; pseudo_defCSV2["uInd"] = [reshape([1, 0.5], 2,1)]; pseudo_defCSV2["theta"] = [0.1 0.2 0.2 0.002]; pseudo_defCSV2["tsamps"] = [[0,5,10,15,20,25,30,35,40]]; pseudo_defCSV2["plot"] = false; pseudo_defCSV2["flag"] = "testPDCSV"; pseudo_defCSV2["Obs"] = ["B*2"]; pseudo_defCSV2["Noise"] = [0.1]; # -------------------------------------------------------- MLE TESTS mle_def = Dict(); mle_def["Nexp"] = []; mle_def["finalTime"] = []; mle_def["switchT"] = []; mle_def["y0"] = []; mle_def["preInd"] = []; mle_def["uInd"] = []; mle_def["tsamps"] = []; mle_def["plot"] = []; mle_def["flag"] = []; mle_def["thetaMAX"] = []; mle_def["thetaMIN"] = []; mle_def["runs"] = []; mle_def["parallel"] = []; mle_def["DataMean"] = []; mle_def["DataError"] = []; mle_def["Obs"] = []; mle_def["OPTsolver"] = []; mle_def["MaxTime"] = []; mle_def["MaxFuncEvals"] = []; mle_def2 = Dict(); mle_def2["Nexp"] = 1; mle_def2["finalTime"] = [40]; mle_def2["switchT"] = [[0,20,40]]; mle_def2["y0"] = [[0,0]]; mle_def2["preInd"] = [[0.1]]; mle_def2["uInd"] = [[1,1]]; mle_def2["tsamps"] = [[0,5,10,15,20,25,30,35,40]]; mle_def2["plot"] = false; mle_def2["flag"] = "testmle"; mle_def2["thetaMAX"] = [0.15 0.25 0.25 0.025]; mle_def2["thetaMIN"] = [0.1 0.2 0.2 0.02]; mle_def2["runs"] = 2; mle_def2["parallel"] = false; mle_def2["DataMean"] = [[0 1 2 3 4 5 6 7 8; 0 1 2 3 4 5 6 7 8]']; mle_def2["DataError"] = [[[0,1,2,3,4,5,6,7,8], [0,1,2,3,4,5,6,7,8]]]; mle_def2["Obs"] = ["A", "B"]; mle_def2["OPTsolver"] = "adaptive_de_rand_1_bin_radiuslimited"; mle_def2["MaxTime"] = []; mle_def2["MaxFuncEvals"] = 10; cvmle_def = Dict(); cvmle_def["Nexp"] = []; cvmle_def["finalTime"] = []; cvmle_def["switchT"] = []; cvmle_def["y0"] = []; cvmle_def["preInd"] = []; cvmle_def["uInd"] = []; cvmle_def["theta"] = []; cvmle_def["tsamps"] = []; cvmle_def["plot"] = []; cvmle_def["flag"] = []; cvmle_def["DataMean"] = []; cvmle_def["DataError"] = []; cvmle_def["Obs"] = []; cvmle_def2 = Dict(); cvmle_def2["Nexp"] = 1; cvmle_def2["finalTime"] = [40]; cvmle_def2["switchT"] = [[0,20,40]]; cvmle_def2["y0"] = [[0,0]]; cvmle_def2["preInd"] = [[0.1]]; cvmle_def2["uInd"] = [[1,1]]; cvmle_def2["theta"] = convert(Array, [0.1 0.2 0.2 0.02;0.12 0.22 0.22 0.022]'); cvmle_def2["tsamps"] = [[0,5,10,15,20,25,30,35,40]]; cvmle_def2["plot"] = false; cvmle_def2["flag"] = "cvmletest"; cvmle_def2["DataMean"] = [[0 1 2 3 4 5 6 7 8]']; cvmle_def2["DataError"] = [[[0,1,2,3,4,5,6,7,8]]];; cvmle_def2["Obs"] = ["B"]; testdict1 = Dict(); testdict2 = Dict(); testdict1["a"] = "a"; testdict1["b"] = "b"; testdict2["a"] = []; testdict2["b"] = 1; @testset "ModelGenTests" begin # In case any modification to the structure is made, this will be the test to see if I have forgot some entry @test model_def == defModStruct() # Check function does some modifications, so it is good to see that it does what it should @test model_def2 == checkStruct(model_def2) # Check that a file has been generated (the functions containing the ODEs) GenerateModel(model_def2) @test isfile(string(pwd(),"\\ModelsFunctions\\", model_def2["NameF"], "_Model.jl")) rm(string(pwd(),"\\ModelsFunctions\\", model_def2["NameF"], "_Model.jl")) # rm(string(pwd(),"\\ModelsFunctions")) end @testset "ModelSimulationTests" begin CSV.write("Theta1.csv", DataFrame([0.1 0.2 0.2 0.002])) CSV.write("TestSimulCSVInps.csv", DataFrame([0 40 0.1 1; 20 40 0.1 0.5])) CSV.write("TestSimulCSVObs.csv", DataFrame([0 0 0; 5 0 0; 10 0 0; 15 0 0; 20 0 0; 25 0 0; 30 0 0; 35 0 0; 40 0 0])) # In case any modification to the structure is made, this will be the test to see if I have forgot some entry @test simul_def == defSimulStruct() # Check function does some modifications, so it is good to see that it does what it should @test simul_def2 == checkStructSimul(model_def2, simul_def2) # In case any modification to the structure is made, this will be the test to see if I have forgot some entry @test simul_def3 == defSimulStructFiles() # Might need to add a test for this, but then I need some example CSV files @test simul_defCSV2 == extractSimulCSV(model_def2, simul_defCSV1) rm("Theta1.csv") rm("TestSimulCSVInps.csv") rm("TestSimulCSVObs.csv") GenerateModel(model_def2); simuls, ~, ~ = simulateODEs(model_def2, simul_def2); @test length(simuls) == simul_def2["Nexp"] for i in 1:2 a,b,c = size(simuls[string("Exp_", i)]) @test a == length(simul_def2["tsamps"][i]) @test b == (model_def2["nStat"]) @test c == length(simul_def2["theta"])/model_def2["nPar"] @test sum(simuls[string("Exp_", i)]) != 0 end plotSimsODE(simuls,model_def2,simul_def2) for i in 1:2 @test isfile(string(simul_def2["savepath"], "\\PlotSimulation_Exp", i,"_", simul_def2["flag"], ".png")) rm(string(simul_def2["savepath"], "\\PlotSimulation_Exp", i,"_", simul_def2["flag"], ".png")) end rm(string(pwd(),"\\ModelsFunctions\\", model_def2["NameF"], "_Model.jl")) rm(string(simul_def2["savepath"], "\\", simul_def2["savename"])) rm(string(simul_def2["savepath"])) end @testset "PseudoDataGenerationTests" begin CSV.write("Theta1PD.csv", DataFrame([0.1 0.2 0.2 0.002])) CSV.write("TestSimulCSVInpsPD.csv", DataFrame([0 40 0.1 1; 20 40 0.1 0.5])) CSV.write("TestSimulCSVObsPD.csv", DataFrame([0 0 0; 5 0 0; 10 0 0; 15 0 0; 20 0 0; 25 0 0; 30 0 0; 35 0 0; 40 0 0])) # In case any modification to the structure is made, this will be the test to see if I have forgot some entry @test pseudo_def == defPseudoDatStruct() # Check function does some modifications, so it is good to see that it does what it should @test pseudo_def2 == checkStructPseudoDat(model_def2, pseudo_def2) # In case any modification to the structure is made, this will be the test to see if I have forgot some entry @test pseudo_def3 == defPseudoDatStructFiles() # Might need to add a test for this, but then I need some example CSV files @test pseudo_defCSV2 == extractPseudoDatCSV(model_def2, pseudo_defCSV1) rm("Theta1PD.csv") rm("TestSimulCSVInpsPD.csv") rm("TestSimulCSVObsPD.csv") GenerateModel(model_def2) pdat, ~, ~ = GenPseudoDat(model_def2, pseudo_def2); @test length(pdat["SimsObs"]) == pseudo_def2["Nexp"] @test length(pdat["Sims"]) == pseudo_def2["Nexp"] @test length(pdat["PData"]) == pseudo_def2["Nexp"] @test length(pdat["PError"]) == pseudo_def2["Nexp"] for i in 1:2 a,b,c = size(pdat["Sims"][string("Exp_", i)]) @test a == length(pseudo_def2["tsamps"][i]) @test b == (model_def2["nStat"]) @test c == length(pseudo_def2["theta"])/model_def2["nPar"] @test sum(pdat["Sims"][string("Exp_", i)]) != 0 a,b,c = size(pdat["SimsObs"][string("PDExp_", i)]) @test b == length(pseudo_def2["Obs"]); @test pdat["SimsObs"][string("PDExp_", i)][:,1,:] == pdat["Sims"][string("Exp_", i)][:,2,:].*2 a,b,c = size(pdat["PData"][string("PDExp_", i)]) @test b == length(pseudo_def2["Obs"]); @test length(pdat["PData"][string("PDExp_", i)]) == length(pdat["PError"][string("PDExp_", i)]) end plotPseudoDatODE(pdat,model_def2,pseudo_def2) for i in 1:2 @test isfile(string(pseudo_def2["savepath"], "\\PlotPseudoDat_Exp", i,"_", pseudo_def2["flag"], ".png")) rm(string(pseudo_def2["savepath"], "\\PlotPseudoDat_Exp", i,"_", pseudo_def2["flag"], ".png")) end rm(string(pwd(),"\\ModelsFunctions\\", model_def2["NameF"], "_Model.jl")) rm(string(pseudo_def2["savepath"], "\\", pseudo_def2["savename"])) for i in 1:2 rm(string(pseudo_def2["savepath"], "\\PseudoDataFiles\\", model_def2["NameF"], "_EXP", i, "_", pseudo_def2["flag"], "_Events_Inputs.csv")) rm(string(pseudo_def2["savepath"], "\\PseudoDataFiles\\", model_def2["NameF"], "_EXP", i, "_", pseudo_def2["flag"], "_Observables.csv")) rm(string(pseudo_def2["savepath"], "\\PseudoDataFiles\\", model_def2["NameF"], "_EXP", i, "_", pseudo_def2["flag"], "_Simulations.csv")) end rm(string(pseudo_def2["savepath"], "\\PseudoDataFiles")) rm(string(pseudo_def2["savepath"])) end @testset "MLESeriesTests" begin # First check that both structure calls give what it is supposed to @test mle_def == defMLEStruct(); @test cvmle_def == defCrossValMLEStruct(); # Check functionality of helpping functions testdict3 = SimToMle(testdict1, testdict2); @test testdict3 == testdict2; simst = reshape([1 2 3 4; 1 2 3 4; 1 2 3 4], 3,4,1); obst = ["c*2"]; stnamest = ["a","b","c","d"]; @test sum(selectObsSim_te(simst, obst, stnamest)) == sum(simst[:,3,:]*2); @test (selectObsSim_te(simst, [2], stnamest)) == reshape([2,2,2], 3,1,1); ttess1 = Dict(); ttess1["nInp"] = 2; ttess2 = Dict(); ttess2["uInd"] = [[1 1 1; 2 2 2]']; @test restructInputs_te(ttess1, ttess2, 1) == [1,2,1,2,1,2]; ttess1["nInp"] = 3; ttess2["uInd"] = [[1 1 1; 2 2 2; 3 3 3]']; @test restructInputs_te(ttess1, ttess2, 1) == [1,2,3,1,2,3,1,2,3]; # More tests might be needed? m=10; s=1; d=9; @test (-0.5)*(log(2*pi) + 0 + (1)) == UVloglike(d, m, s); m=[10, 10, 10, 10]; s=[1,1,1,1]; d=[9, 11, 9, 11]; @test ((-0.5)*(log(2*pi) + 0 + (1)))*4 == UVloglike(d, m, s); m=[10, 15, 10, 15]; s=[0.5,0.5,0.5,0.5]; d=[12, 12, 12, 12]; @test ((-0.5)*(log(2*pi) + log(0.25) + (2^2)/0.25)) + ((-0.5)*(log(2*pi) + log(0.25) + (2^2)/0.25)) + ((-0.5)*(log(2*pi) + log(0.25) + (3^2)/0.25)) + ((-0.5)*(log(2*pi) + log(0.25) + (3^2)/0.25)) == UVloglike(d, m, s); m=[10, 10]; s=[1 1; 1 1]; # Diagonal element of 0.1 is added to avoid Infs due to non positive definite covariances. d=[9, 11]; correcmat = Diagonal(ones(length(d))).*0.1; @test [MVloglike(d, m, s)] == (-0.5) * ((length(d)*log(2*pi)) .+ log(det(s.+correcmat)) .+ ([-1 1]*inv(s.+correcmat)*[-1,1])); # Check structure check functions (with and without CSVs) @test mle_def2 == checkStructMLE(model_def2, mle_def2) @test cvmle_def2 == checkStructCrossValMLE(model_def2, cvmle_def2) # Check MLE GenerateModel(model_def2); mle_res, model_def3, mle_def3 = MLEtheta(model_def2, mle_def2); @test !isempty(mle_res); @test typeof(mle_res["StanDict"]) <: Array; @test typeof(mle_res["StanDict"][1]) <: Dict; @test typeof(mle_res["StanDict"][2]) <: Dict; @test symdiff(["k1","k2","k3","k4"],keys(mle_res["StanDict"][1])) == []; @test symdiff(["k1","k2","k3","k4"],keys(mle_res["StanDict"][2])) == []; @test length(mle_res["Theta"]) == 4*2; @test size(mle_res["Theta"]) == (4,2); @test length(mle_res["convCurv"]) == 2; @test (typeof(mle_res["convCurv"][1][1]) == Tuple{Int,Float64} || typeof(mle_res["convCurv"][1][1]) == Tuple{Int,Float32}); @test (typeof(mle_res["convCurv"][1][2]) == Tuple{Int,Float64} || typeof(mle_res["convCurv"][1][2]) == Tuple{Int,Float32}); @test (typeof(mle_res["convCurv"][2][1]) == Tuple{Int,Float64} || typeof(mle_res["convCurv"][2][1]) == Tuple{Int,Float32}); @test (typeof(mle_res["convCurv"][2][2]) == Tuple{Int,Float64} || typeof(mle_res["convCurv"][2][2]) == Tuple{Int,Float32}); @test length(mle_res["BestTheta"]) == 4; @test length(mle_res["BestCFV"]) == 2; #----------------------------- the parallel stuff!!!! mle_def2["parallel"] = true; mle_res2, model_def3, mle_def3 = MLEtheta(model_def2, mle_def2); @test isempty(mle_res2); @test isfile(string(mle_def3["savepath"], "\\MLEScripts\\", model_def3["NameF"], "_MLE.jl")); mle_res3, ~, ~ = finishMLEres(mle_res, model_def2, mle_def2); @test !isempty(mle_res3); mle_def2["parallel"] = false; # Check CV for MLE results cvmle_res, ~, ~ = CrossValMLE(model_def2, cvmle_def2); @test !isempty(cvmle_res); @test !isempty(cvmle_res["BestSimulations"][1]); @test size(cvmle_res["BestSimulations"][1])[2] == 2; @test length(cvmle_res["Costs"]) == 2; @test !isempty(cvmle_res["BestSimObservables"][1]); @test size(cvmle_res["BestSimObservables"][1])[2] == 1; @test length(cvmle_res["BestTheta"]) == 4; @test typeof(cvmle_res["SimObservables"]) <: Dict; @test size(cvmle_res["SimObservables"]["ExpObs_1"])[2] == 1; @test typeof(cvmle_res["Simulations"]) <: Dict; @test size(cvmle_res["Simulations"]["Exp_1"])[2] == 2; # Test Plotting plotMLEResults(mle_res,model_def2,mle_def2) @test isfile(string(mle_def2["savepath"], "\\PlotMLEResults_Exp", 1,"_", mle_def2["flag"], ".png")) @test isfile(string(mle_def2["savepath"], "\\Plot_MLEConvergence", "_", mle_def2["flag"], ".png")) rm(string(mle_def2["savepath"], "\\PlotMLEResults_Exp", 1,"_", mle_def2["flag"], ".png")) rm(string(mle_def2["savepath"], "\\Plot_MLEConvergence", "_", mle_def2["flag"], ".png")) rm(string(pwd(),"\\ModelsFunctions\\", model_def2["NameF"], "_Model.jl")) rm(string(mle_def2["savepath"], "\\", mle_def2["savename"])) rm(string(mle_def2["savepath"], "\\MLEScripts\\", model_def2["NameF"], "_MLE.jl")) rm(string(mle_def2["savepath"], "\\MLEScripts")) rm(string(cvmle_def2["savepath"], "\\", cvmle_def2["savename"])) rm(string(mle_def2["savepath"], "\\",model_def2["NameF"], "_", today(), "_SimulationResults_MLEsimulations1.jld")) rm(string(mle_def2["savepath"], "\\",model_def2["NameF"], "_", today(), "_SimulationResults_MLEsimulations2.jld")) rm(string(mle_def2["savepath"])) end @testset "StanInferenceTests" begin # Tests on structure definitions bayinf_def = defBayInfStruct(); @test typeof(bayinf_def) <: Dict; entries1 = ["Priors", "Data", "StanSettings", "flag", "plot", "runInf", "MultiNormFit"]; @test isempty(symdiff(entries1,keys(bayinf_def))); datinf_def = defBayInfDataStruct(); @test typeof(datinf_def) <: Dict; entries2 = ["Nexp", "finalTime", "switchT", "y0", "preInd", "uInd", "tsamps", "Obs", "DataMean", "DataError"]; @test isempty(symdiff(entries2,keys(datinf_def))); csvinf_def = defBayInfDataFromFilesStruct(); @test typeof(csvinf_def) <: Dict; entries3 = ["Obs", "Observables", "Inputs", "y0"]; @test isempty(symdiff(entries3,keys(csvinf_def))); stainf_def = defBasicStanSettingsStruct(); @test typeof(stainf_def) <: Dict; entries4 = ["cmdstan_home", "nchains", "nsamples", "nwarmup", "printsummary", "init", "maxdepth", "adaptdelta", "jitter"]; @test isempty(symdiff(entries4,keys(stainf_def))); # Check structures stainf_def["cmdstan_home"] = "C:/Users/David/.cmdstanpy/cmdstan-2.20.0"; stainf_def["nchains"] = 2; stainf_def["nsamples"] = 20; stainf_def["nwarmup"] = 20; stainf_def["printsummary"] = false; stainf_def["init"] = []; stainf_def["maxdepth"] = 13; stainf_def["adaptdelta"] = 0.95; stainf_def["jitter"] = 0.5; @test stainf_def == checkStructBayInfStanSettings(model_def2, stainf_def); datinf_def["Nexp"] = 1; datinf_def["finalTime"] = [40]; datinf_def["switchT"] = [[0,20,40]]; datinf_def["y0"] = [[0,0]]; datinf_def["preInd"] = [[0.1]]; datinf_def["uInd"] = [[1,1]]; datinf_def["tsamps"] = [[0,5,10,15,20,25,30,35,40]]; datinf_def["DataMean"] = [[0 1 2 3 4 5 6 7 8; 0 1 2 3 4 5 6 7 8]']; datinf_def["DataError"] = [[[0,1,2,3,4,5,6,7,8], [0,1,2,3,4,5,6,7,8]]]; datinf_def["Obs"] = ["A", "B"]; @test datinf_def == checkStructBayInfData(model_def2, datinf_def); bayinf_def["Priors"] = [0.15 0.25 0.25 0.025; 0.1 0.2 0.2 0.02]''; bayinf_def["Data"] = datinf_def; bayinf_def["StanSettings"] = stainf_def; bayinf_def["flag"] = "stantest"; bayinf_def["plot"] = false; bayinf_def["runInf"] = false; bayinf_def["MultiNormFit"] = false; bayinf_def2 = checkStructBayInf(model_def2, bayinf_def); @test bayinf_def["Data"] == bayinf_def2["Data"] @test bayinf_def["StanSettings"] == bayinf_def2["StanSettings"] @test bayinf_def["flag"] == bayinf_def2["flag"] @test bayinf_def["plot"] == bayinf_def2["plot"] @test bayinf_def["runInf"] == bayinf_def2["runInf"] @test bayinf_def["MultiNormFit"] == bayinf_def2["MultiNormFit"] @test length(bayinf_def2["Priors"]) == 3; @test typeof(bayinf_def2["Priors"]) <: Dict # checkStructBayInfDataFiles(model_def, data_def) # Helpper functions tests s1 = [0,1,3,9,10] @test convertBoundTo2(s1, 10, 20) == s1.+10; @test convertBoundTo2(s1.+10, 0, 10) == s1; samp1 = rand(Normal(10,1), 80000,4); fipri1 = fitPriorSamps(samp1, model_def2); @test length(fipri1["pars"]) == 4; @test length(fipri1["transpars"]) == 5; @test length(fipri1["pridis"]) == 4; fipri2 = fitPriorSampsMultiNorm(samp1, model_def2); @test length(fipri2["pars"]) < 4; @test length(fipri2["transpars"]) == 5; @test length(fipri2["pridis"]) < 4; kee = ["transpars","mera","cora","pars","pridis","numN"] @test isempty(symdiff(kee,keys(fipri2))); dis1 = genStanInitDict(samp1', model_def2["parName"], 10); @test typeof(dis1[1]) <: Dict; @test isempty(symdiff(model_def2["parName"],keys(dis1[1]))); @test length(dis1) == 10; # reparamDictStan(dis1, bayinf_def) # Stan genStanModel(model_def2, bayinf_def) @test isfile(string(pwd(),"\\ModelsFunctions\\", model_def2["NameF"], "_StanModel.stan")) sdat = restructureDataInference(model_def2, bayinf_def); datks = ["elm","tml","ts","tsl","tsmax","Nsp","inputs","evnT","m","stsl","stslm","sts","obser","obSta","nindu","preInd","Means","Y0us","Erros"] for i in 1:length(datks) @test datks[i] in keys(sdat) @test !isempty(sdat[datks[i]]) end modelpath, Model, StanModel, inferdata, init, ~, ~ = getStanInferenceElements(model_def2, bayinf_def); @test isfile(modelpath); rm(modelpath) @test typeof(Model) == String; @test typeof(StanModel) == CmdStan.Stanmodel; @test inferdata == sdat; @test isempty(init); # saveStanResults(rc, chns, cnames, model_def, bayinf_def) # runStanInference(model_def, bayinf_def) stin, ~, ~ = StanInfer(model_def2, bayinf_def); kssm = ["init", "StanModel", "inferdata", "Model", "modelpath"] @test isempty(symdiff(kssm,keys(stin))); # Entropy tests ps = genSamplesPrior(model_def2, bayinf_def, 100); @test size(ps) == (100, 4); w = [1]; E = [[1 0; 0 1]]; MU = reshape([10, 10], 2, 1); x = reshape([10, 10], 2, 1); @test round(BOMBS.H_Upper(w,E)) == 3; @test round(BOMBS.mvGauss(x, MU, E[1])[1], digits=2) == 0.16; @test round(BOMBS.H_Lower(w, E, MU'), digits = 1) == 2.5; @test round(BOMBS.GaussMix(x[:,1], convert(Array, MU'), E, w), digits=2) == 0.16; @test round(BOMBS.ZOTSE(MU', E, w)) == 2; # Due to the use of global variables I cannot test the other functions... But I can test that the main script runs. # Do not know why, but I cannot make ScikitLearn work in the test file (works in scripts and jupyter)??? Need to have a look at it. # computeH(ps, model_def2, "test") # Plots # plotStanResults(staninf_res, model_def, bayinf_def) rm(string(pwd(),"\\ModelsFunctions\\", model_def2["NameF"], "_StanModel.stan")); rm(string(pwd(),"\\tmp\\", model_def2["NameF"], "_Stan_",bayinf_def["flag"],".stan")); end @testset "OEDModelSelectionTests" begin # structure definition oedms_def = defODEModelSelectStruct(); @test typeof(oedms_def) <: Dict; entries1 = ["Model_1", "Model_2", "Obs", "Theta_M1", "Theta_M2", "y0_M1", "y0_M2", "preInd_M1", "preInd_M2", "finalTime", "switchT", "tsamps", "equalStep", "fixedInp", "fixedStep", "plot", "flag", "uUpper", "uLower", "maxiter"]; @test isempty(symdiff(entries1,keys(oedms_def))); #structure check model_def3 = defModStruct(); model_def3["NameF"] = "Test2"; model_def3["nStat"] = 2; model_def3["nPar"] = 4; model_def3["nInp"] = 1; model_def3["stName"] = ["A", "B"]; model_def3["parName"] = ["k1", "k2", "k3", "k4"]; model_def3["inpName"] = ["inp1"]; model_def3["eqns"] = ["dA = k1*A - k2*A*inp1", "dB = k3*(A^2) - k4*B"]; model_def3["Y0eqs"] = ["A = 1", "B = k3*(A^2)/k4"]; model_def3["Y0Sim"] = false; model_def3["tols"] = [1e-5,1e-5]; model_def3["solver"] = "CVODE_BDF"; oedms_def = Dict() oedms_def["Model_1"] = model_def2; oedms_def["Model_2"] = model_def3; oedms_def["Obs"] = ["B"]; oedms_def["Theta_M1"] = [0.1 0.2 0.2 0.02; 0.11 0.21 0.21 0.021; 0.12 0.22 0.22 0.022]; oedms_def["Theta_M2"] = [0.13 0.23 0.23 0.023; 0.14 0.24 0.24 0.024; 0.15 0.25 0.25 0.025]; oedms_def["y0_M1"] = [0,0]; oedms_def["y0_M2"] = [0,0]; oedms_def["preInd_M1"] = [0.1]; oedms_def["preInd_M2"] = [0.1]; oedms_def["finalTime"] = [40]; oedms_def["switchT"] = [0,20,30,40]; oedms_def["tsamps"] = [0,5,10,15,20,25,30,35,40]; oedms_def["fixedInp"] = []; oedms_def["fixedStep"] = [(1,[0])]; oedms_def["equalStep"] = [[2,3]]; oedms_def["plot"] = false; oedms_def["flag"] = "testoedms"; oedms_def["uUpper"] = [1]; oedms_def["uLower"] = [0]; oedms_def["maxiter"] = 5; @test oedms_def == checkStructOEDMS(oedms_def); # Distance functions m1 = [10, 10]; s1 = [1 0; 0 1]; m2 = [11, 11]; s2 = [1 0; 0 1]; m3 = [15, 15]; s3 = [1 0; 0 1]; @test BhattacharyyaDist(m1, m1, s1, s1) == 0; @test BhattacharyyaDist(m1, m2, s1, s2) == 0.25; @test BhattacharyyaDist(m1, m3, s1, s3) == 6.25; @test EuclideanDist(m1, m1) == 0; @test EuclideanDist(m1, m2) == sqrt(2); @test EuclideanDist(m1, m3) == sqrt(50); # Generate utility script oedms_def = genOptimMSFuncts(oedms_def); @test isfile(string(pwd(), "\\ModelsFunctions\\", model_def2["NameF"], "_Model.jl")); @test isfile(string(pwd(), "\\ModelsFunctions\\", model_def3["NameF"], "_Model.jl")); @test isfile(string(pwd(), "\\Results\\", model_def2["NameF"], "_VS_", model_def3["NameF"], "_", today(), "\\OEDModelSelectionScripts\\", model_def2["NameF"], "_VS_", model_def3["NameF"], "_OEDMS.jl")); # Bayes settings # Need to figure out if there is any test I can do here # opt = settingsBayesOpt(oedms_def); # Main function oedms_res, oedms_def = mainOEDMS(oedms_def); @test !isempty(oedms_res); @test typeof(oedms_res) <: Dict; @test isfile(string(pwd(), "\\Results\\", model_def2["NameF"], "_VS_", model_def3["NameF"], "_", today(),"\\OEDModelSelectResults_", oedms_def["flag"], ".jld")); @test oedms_res["uInpOpt"]["inp1"][1] == 0; @test oedms_res["uInpOpt"]["inp1"][2] == oedms_res["uInpOpt"]["inp1"][3]; @test length(oedms_res["BestUtil"]) == 1; @test size(oedms_res["ConvCurv"])[1] == 5; @test size(oedms_res["Simul_M1"]) == size(oedms_res["Simul_M2"]); @test size(oedms_res["SimulObs_M1"])[2] == size(oedms_res["Simul_M1"])[2]-1; @test size(oedms_res["SimulObs_M2"])[2] == size(oedms_res["Simul_M2"])[2]-1; # Plot results plotOEDMSResults(oedms_res, oedms_def); @test isfile(string(oedms_def["savepath"], "\\Plot_OEDMSConvergence_", oedms_def["flag"], ".png")); rm(string(oedms_def["savepath"], "\\Plot_OEDMSConvergence_", oedms_def["flag"], ".png")); @test isfile(string(oedms_def["savepath"], "\\PlotOEDMSResults_Exp1_", oedms_def["flag"], ".png")); rm(string(oedms_def["savepath"], "\\PlotOEDMSResults_Exp1_", oedms_def["flag"], ".png")); rm(string(pwd(), "\\Results\\", model_def2["NameF"], "_VS_", model_def3["NameF"], "_", today(),"\\OEDModelSelectResults_", oedms_def["flag"], ".jld")); rm(string(pwd(), "\\ModelsFunctions\\", model_def2["NameF"], "_Model.jl")) rm(string(pwd(), "\\ModelsFunctions\\", model_def3["NameF"], "_Model.jl")) rm(string(pwd(), "\\Results\\", model_def2["NameF"], "_VS_", model_def3["NameF"], "_", today(), "\\OEDModelSelectionScripts\\", model_def2["NameF"], "_VS_", model_def3["NameF"], "_OEDMS.jl")); rm(string(pwd(), "\\Results\\", model_def2["NameF"], "_VS_", model_def3["NameF"], "_", today(), "\\OEDModelSelectionScripts")); rm(string(pwd(), "\\Results\\", model_def2["NameF"], "_VS_", model_def3["NameF"], "_", today())); end @testset "OEDModelCalibrationTests" begin # structure definition oedmc_def = defODEModelCalibrStruct(); @test typeof(oedmc_def) <: Dict; entries1 = ["Model", "Obs", "Theta", "y0", "preInd", "finalTime", "switchT", "tsamps", "equalStep", "fixedInp", "fixedStep", "plot", "flag", "uUpper", "uLower", "maxiter", "util"]; @test isempty(symdiff(entries1,keys(oedmc_def))); oedmc_def = Dict() oedmc_def["Model"] = model_def2; oedmc_def["Obs"] = ["B"]; oedmc_def["Theta"] = [0.1 0.2 0.2 0.02; 0.11 0.21 0.21 0.021; 0.12 0.22 0.22 0.022]; oedmc_def["y0"] = [0,0]; oedmc_def["preInd"] = [0.1]; oedmc_def["finalTime"] = [40]; oedmc_def["switchT"] = [0,20,30,40]; oedmc_def["tsamps"] = [0,5,10,15,20,25,30,35,40]; oedmc_def["fixedInp"] = []; oedmc_def["fixedStep"] = [(1,[0])]; oedmc_def["equalStep"] = [[2,3]]; oedmc_def["plot"] = false; oedmc_def["flag"] = "testoedmc"; oedmc_def["uUpper"] = [1]; oedmc_def["uLower"] = [0]; oedmc_def["maxiter"] = 5; oedmc_def["util"] = "perc"; @test oedmc_def == checkStructOEDMC(oedmc_def); # Generate utility script oedmc_def = genOptimMCFuncts(oedmc_def); @test isfile(string(pwd(), "\\ModelsFunctions\\", model_def2["NameF"], "_Model.jl")); @test isfile(string(pwd(), "\\Results\\", model_def2["NameF"], "_", today(), "\\OEDModelCalibrationScripts\\", model_def2["NameF"], "_OEDMC.jl")); # Main function oedmc_res, oedmc_def = mainOEDMC(oedmc_def); @test !isempty(oedmc_res); @test typeof(oedmc_res) <: Dict; @test isfile(string(pwd(), "\\Results\\", model_def2["NameF"], "_", today(),"\\OEDModelCalibrationResults_", oedmc_def["flag"], ".jld")); @test oedmc_res["uInpOpt"]["inp1"][1] == 0; @test oedmc_res["uInpOpt"]["inp1"][2] == oedmc_res["uInpOpt"]["inp1"][3]; @test length(oedmc_res["BestUtil"]) == 1; @test size(oedmc_res["ConvCurv"])[1] == 5; @test size(oedmc_res["SimulObs_MC"])[2] == size(oedmc_res["Simul_MC"])[2]-1; # Plot results plotOEDMCResults(oedmc_res, oedmc_def); @test isfile(string(oedmc_def["savepath"], "\\Plot_OEDMCConvergence_", oedmc_def["flag"], ".png")); rm(string(oedmc_def["savepath"], "\\Plot_OEDMCConvergence_", oedmc_def["flag"], ".png")); @test isfile(string(oedmc_def["savepath"], "\\PlotOEDMCResults_Exp1_", oedmc_def["flag"], ".png")); rm(string(oedmc_def["savepath"], "\\PlotOEDMCResults_Exp1_", oedmc_def["flag"], ".png")); rm(string(pwd(), "\\ModelsFunctions\\", model_def2["NameF"], "_Model.jl")); rm(string(pwd(), "\\Results\\", model_def2["NameF"], "_", today(), "\\OEDModelCalibrationScripts\\", model_def2["NameF"], "_OEDMC.jl")); rm(string(pwd(), "\\Results\\", model_def2["NameF"], "_", today(),"\\OEDModelCalibrationResults_", oedmc_def["flag"], ".jld")); rm(string(pwd(), "\\Results\\", model_def2["NameF"], "_", today(), "\\OEDModelCalibrationScripts")); rm(string(pwd(), "\\Results\\", model_def2["NameF"], "_", today())); end # rm(string(pwd(), "\\ModelsFunctions")) # rm(string(pwd(), "\\Results")) # rm(string(pwd(), "\\tmp"))
#prelude.jl #some common imports used by almost all scripts: using Base.MPFR: ROUNDING_MODE, big_ln2 using Base.Math: @horner, libm, nan_dom_err
struct Graph n :: Int32 # |V| m :: Int32 # |E| V :: Array{Int32, 1} # V[i] = Real Index of node i E :: Array{Tuple{Int32, Int32, Int32, Float64}, 1} # (ID, u, v, w) in Edge Set end function readGraph(fileName, graphType) # Read graph from a file | graphType = [weighted, unweighted] # Initialized n = 0 origin = Dict{Int32, Int32}() label = Dict{Int32, Int32}() edge = Set{Tuple{Int32, Int32, Float64}}() getid(x :: Int32) = haskey(label, x) ? label[x] : label[x] = n += 1 open(fileName) do f1 for line in eachline(f1) # Read origin data from file buf = split(line) u = parse(Int32, buf[1]) v = parse(Int32, buf[2]) if graphType == "weighted" w = parse(Float64, buf[3]) else w = 1.0 end if u == v continue end # Label the node u1 = getid(u) v1 = getid(v) origin[u1] = u origin[v1] = v # Store the edge if u1 > v1 u1, v1 = v1, u1 end push!(edge, (u1, v1, w)) end end # Store data into the struct Graph m = length(edge) V = Array{Int32, 1}(undef, n) E = Array{Tuple{Int32, Int32, Int32, Float64}, 1}(undef, m) for i = 1 : n V[i] = origin[i] end ID = 0 for (u, v, w) in edge ID = ID + 1 E[ID] = (ID, u, v, w) end return Graph(n, m, V, E) end function getConnectedComponents(G) F = zeros(Int, G.n) foreach(i -> F[i] = i, 1 : G.n) find(x) = begin if F[x] != x F[x] = find(F[x]) end return F[x] end for (ID, u, v, w) in G.E p = find(u) q = find(v) (p != q) ? F[p] = q : nothing end CC = zeros(Int, G.n) foreach(i -> CC[i] = find(i), 1 : G.n) return CC end function getBiconnectedComponents(G) dfn = zeros(Int, G.n) low = zeros(Int, G.n) cnt = 0 cutPoint = zeros(Bool, G.n) bccid = zeros(Int, G.n) edgeC = zeros(Int, G.m) S = zeros(Int, 2*G.m) top = 0 nbcc = 0 bcc = Array{Array{Int, 1}, 1}(undef, G.n) g = Array{Array{Int, 1}, 1}(undef, G.n) gID = Array{Array{Int, 1}, 1}(undef, G.n) for i = 1 : G.n g[i] = [] gID[i] = [] bcc[i] = [] end for (ID, u, v, w) in G.E push!(g[u], v) push!(gID[u], ID) push!(g[v], u) push!(gID[v], ID) end DFS(u, fa) = begin cnt += 1 dfn[u] = cnt low[u] = cnt son = 0 for i = 1 : size(g[u], 1) v = g[u][i] if dfn[v] == 0 top += 1 S[top] = gID[u][i] son += 1 DFS(v, u) low[u] = min(low[u], low[v]) if dfn[u] <= low[v] cutPoint[u] = true nbcc += 1 while true x = S[top] top -= 1 if bccid[G.E[x][2]] != nbcc bccid[G.E[x][2]] = nbcc push!(bcc[nbcc], G.E[x][2]) end if bccid[G.E[x][3]] != nbcc bccid[G.E[x][3]] = nbcc push!(bcc[nbcc], G.E[x][3]) end if x == gID[u][i] break end end end elseif ((v != fa) && (dfn[v] < dfn[u])) top += 1 S[top] = gID[u][i] low[u] = min(low[u], dfn[v]) end end if (fa == 0) && (son <= 1) cutPoint[u] = false end end for i = 1 : G.n if dfn[i] == 0 DFS(i, 0) end end timeStamp = 0 fill!(bccid, 0) for i = 1 : nbcc timeStamp += 1 for j = 1 : size(bcc[i], 1) bccid[bcc[i][j]] = timeStamp end for u in bcc[i] for j = 1 : size(g[u], 1) v = g[u][j] ei = gID[u][j] (bccid[v] == timeStamp) ? edgeC[ei] = timeStamp : nothing end end end for i = 1 : G.m if edgeC[i] == 0 timeStamp += 1 edgeC[i] = timeStamp end end cutList = Array{Int, 1}() for i = 1 : G.n if cutPoint[i] == true push!(cutList, i) end end return cutList, edgeC end function IsBiconnected(G) cutList, edgeC = getBiconnectedComponents(G) return size(cutList, 1) == 0 end function getAdjacentList(G) g = Array{Array{Int, 1}, 1}(undef, G.n) foreach(i -> g[i] = [], 1 : G.n) for (ID, u, v, w) in G.E push!(g[u], v) push!(g[v], u) end return g end function SubGraph(G, Selected, EC) n = 0 label = Dict{Int32, Int32}() nodeList = Array{Int32, 1}() for i = 1 : G.n if Selected[i] n += 1 push!(nodeList, i) label[i] = n end end m = 0 edges = Array{Tuple{Int32, Int32, Int32, Float64}, 1}() for (ID, u, v, w) in G.E if haskey(label, u) && haskey(label, v) m += 1 push!(edges, (m, label[u], label[v], EC[ID])) end end V = zeros(Int, n) foreach(i -> V[i] = G.V[nodeList[i]], 1 : n) return Graph(n, m, V, edges) end
function Sockets.connect(fun::Function, args...) client = connect(args...) res = fun(client) close(client) res end @enum Magic::Int NEW_WORKER NEW_TASK RESULT ALIVE FINISHED struct Tasker{XT,YT,Sampler<:AbstractSampler{XT,YT}, Server,ActiveTasks, LifeSigns,AliveThreshold,Mutex} sampler::Sampler server::Server active_tasks::ActiveTasks life_signs::LifeSigns alive_threshold::AliveThreshold mutex::Mutex end Tasker(sampler::AbstractSampler, server, alive_threshold::Number) = Tasker(sampler, server, Int[], Vector{typeof(now())}(), alive_threshold, Threads.SpinLock()) function Base.show(io::IO, t::Tasker) s = t.sampler n = length(s) write(io, "$(n) ($(count(s.done)) done) samples Tasker listening on ") show(io, t.server) end function Base.show(io::IO, ::MIME"text/plain", t::Tasker) show(io, t) println(io) tn = now() pretty_table(io, hcat(eachindex(t.active_tasks), t.active_tasks, tn .- t.life_signs), header=["Worker id", "Current task", "Alive"], hlines=[1], vlines=[]) println(io) end function serve_tasks!(tasker::Tasker{XT,YT}; plot_fun::Union{Function,Nothing}=nothing) where {XT,YT} server = tasker.server s = tasker.sampler load_samples!(s) pf = () -> begin if !isnothing(plot_fun) sel = done(s) plot_fun(s.x[sel], s.y[sel]) end end pf() # At the moment, we run the task server synchronously, i.e. we do # not allow any workers in the same Julia process. while !isdone(s) || any(!iszero, tasker.active_tasks) sock = accept(server) magic = read(sock, Magic) tasks_left = !isdone(s) @info "Got connected" sock magic tasks_left islocked(tasker.mutex) if magic == NEW_WORKER if tasks_left lock(tasker.mutex) do push!(tasker.active_tasks, 0) push!(tasker.life_signs, now()) end worker_id = length(tasker.active_tasks) @info "Assigning new worker id #$(worker_id)" write(sock, NEW_WORKER, worker_id) else write(sock, FINISHED) end elseif magic == NEW_TASK worker_id = read(sock, Int) if tasks_left lock(tasker.mutex) do nd = filter(∉(tasker.active_tasks), not_done(s)) if isempty(nd) @warn "Could not find next sample, weird" tasker.active_tasks[worker_id] = 0 write(sock, FINISHED) else i = first(nd) tasker.active_tasks[worker_id] = i tasker.life_signs[worker_id] = now() x = get_sample!(s, i) write(sock, NEW_TASK, i, x) @info "Worker #$(worker_id) asks for work, gets it" i x end end else tasker.active_tasks[worker_id] = 0 write(sock, FINISHED) @info "Worker #$(worker_id) asks for work, none left" end elseif magic == RESULT worker_id = read(sock, Int) x = read(sock, XT) y = read(sock, YT) lock(tasker.mutex) do i = tasker.active_tasks[worker_id] @info "Worker #$(worker_id) tells us the following result" i x y s[i] = (x,y) tasker.life_signs[worker_id] = now() save_samples!(s) end pf() elseif magic == ALIVE worker_id = read(sock, Int) @info "Worker #$(worker_id) is still alive, nice" lock(tasker.mutex) do tasker.life_signs[worker_id] = now() end end horizontal_line(color=:red) display(tasker) horizontal_line() horizontal_line(color=:yellow) end close(server) end function task_farm(fun::Function, sampler::AbstractSampler{XT,YT}; host=localhost, port=2000, alive_sleep=60, alive_threshold=3alive_sleep, kwargs...) where {XT,YT} server = try if host == localhost || hostname() == host listen(host == localhost ? localhost : IPv4(0), port) else nothing end catch IOError nothing end if !isnothing(server) @info "We are the server, yay!" tasker = Tasker(sampler, server, alive_threshold) serve_tasks!(tasker; kwargs...) else @info "We are a measly worker" worker_id = connect(host, port) do client write(client, NEW_WORKER) response = read(client, Magic) if response == NEW_WORKER read(client, Int) elseif response == FINISHED @info "There's not even anything to do" end end if !isnothing(worker_id) @info "We are measly worker #$(worker_id)" @sync begin # @async while isopen(client) # lock(mutex) do # write(client, ALIVE, worker_id) # end # sleep(alive_sleep) # end while true horizontal_line(color=:green) ix = connect(host, port) do client write(client, NEW_TASK, worker_id) response = read(client, Magic) @info "Requested work" response if response == NEW_TASK read(client, Int), read(client, XT) elseif response == FINISHED @info "We must go home" end end isnothing(ix) && break i,x = ix @info "We are asked to work" i x y = fun(i, x) connect(host, port) do client write(client, RESULT, worker_id, x, y) end end end end end horizontal_line(color=:blue) @info "We are done" end export task_farm
# High-level tests makearray(D, val) = fill(val, ntuple(d -> 1, D)) if comm_rank == 0 const dirname2 = Filesystem.mktempdir(; cleanup=true) const filename2 = "$dirname2/test.bp" @testset "High-level write tests " begin file = adios_open_serial(filename2, mode_write) adios_define_attribute(file, "a1", float(π)) adios_define_attribute(file, "a2", [float(π)]) adios_define_attribute(file, "a3", [float(π), 0]) adios_put!(file, "v1", float(ℯ)) adios_put!(file, "v3", makearray(1, float(ℯ))) adios_put!(file, "v4", makearray(2, float(ℯ))) adios_put!(file, "v5", makearray(3, float(ℯ))) adios_put!(file, "g1/v6", makearray(4, float(ℯ))) adios_put!(file, "g1/g2/v7", makearray(5, float(ℯ))) @test shapeid(inquire_variable(file.io, "v1")) == shapeid_local_value @test shapeid(inquire_variable(file.io, "v3")) == shapeid_local_array @test shapeid(inquire_variable(file.io, "v4")) == shapeid_local_array @test shapeid(inquire_variable(file.io, "v5")) == shapeid_local_array @test shapeid(inquire_variable(file.io, "g1/v6")) == shapeid_local_array @test shapeid(inquire_variable(file.io, "g1/g2/v7")) == shapeid_local_array adios_define_attribute(file, "v4/a4", float(π)) adios_define_attribute(file, "v5", "a5", [float(π)]) adios_define_attribute(file, "g1/v6", "a6", [float(π), 0]) adios_perform_puts!(file) close(file) end # run(`/Users/eschnett/src/CarpetX/Cactus/view/bin/bpls -aD $filename2`) @testset "High-level read tests " begin file = adios_open_serial(filename2, mode_read) @test Set(adios_subgroup_names(file, "")) == Set(["g1"]) @test_broken Set(adios_subgroup_names(file, "g1")) == Set(["g2"]) @test Set(adios_subgroup_names(file, "g1")) == Set(["/g2"]) # don't want this @test Set(adios_all_attribute_names(file)) == Set(["a1", "a2", "a3", "v4/a4", "v5/a5", "g1/v6/a6"]) @test Set(adios_group_attribute_names(file, "g1")) == Set() @test Set(adios_group_attribute_names(file, "g1/v6")) == Set(["g1/v6/a6"]) @test adios_attribute_data(file, "a1") == float(π) @test adios_attribute_data(file, "a2") == float(π) @test adios_attribute_data(file, "a3") == [float(π), 0] @test adios_attribute_data(file, "v4", "a4") == float(π) @test adios_attribute_data(file, "v5/a5") == float(π) @test adios_attribute_data(file, "g1/v6", "a6") == [float(π), 0] @test Set(adios_all_variable_names(file)) == Set(["v1", "v3", "v4", "v5", "g1/v6", "g1/g2/v7"]) @test Set(adios_group_variable_names(file, "g1")) == Set(["g1/v6"]) @test Set(adios_group_variable_names(file, "g1/g2")) == Set(["g1/g2/v7"]) # Local values are converted to global arrays @test shapeid(inquire_variable(file.io, "v1")) == shapeid_global_array @test shapeid(inquire_variable(file.io, "v3")) == shapeid_local_array @test shapeid(inquire_variable(file.io, "v4")) == shapeid_local_array @test shapeid(inquire_variable(file.io, "v5")) == shapeid_local_array @test shapeid(inquire_variable(file.io, "g1/v6")) == shapeid_local_array @test shapeid(inquire_variable(file.io, "g1/g2/v7")) == shapeid_local_array @test ndims(inquire_variable(file.io, "v1")) == 1 @test ndims(inquire_variable(file.io, "v3")) == 1 @test ndims(inquire_variable(file.io, "v4")) == 2 @test ndims(inquire_variable(file.io, "v5")) == 3 @test ndims(inquire_variable(file.io, "g1/v6")) == 4 @test ndims(inquire_variable(file.io, "g1/g2/v7")) == 5 @test shape(inquire_variable(file.io, "v1")) == (1,) @test shape(inquire_variable(file.io, "v3")) ≡ nothing @test shape(inquire_variable(file.io, "v4")) ≡ nothing @test shape(inquire_variable(file.io, "v5")) ≡ nothing @test shape(inquire_variable(file.io, "g1/v6")) ≡ nothing @test shape(inquire_variable(file.io, "g1/g2/v7")) ≡ nothing @test start(inquire_variable(file.io, "v1")) == (0,) @test start(inquire_variable(file.io, "v3")) ≡ nothing @test start(inquire_variable(file.io, "v4")) ≡ nothing @test start(inquire_variable(file.io, "v5")) ≡ nothing @test start(inquire_variable(file.io, "g1/v6")) ≡ nothing @test start(inquire_variable(file.io, "g1/g2/v7")) ≡ nothing @test count(inquire_variable(file.io, "v1")) == (1,) @test count(inquire_variable(file.io, "v3")) == (1,) @test count(inquire_variable(file.io, "v4")) == (1, 1) @test count(inquire_variable(file.io, "v5")) == (1, 1, 1) @test count(inquire_variable(file.io, "g1/v6")) == (1, 1, 1, 1) @test count(inquire_variable(file.io, "g1/g2/v7")) == (1, 1, 1, 1, 1) v1 = adios_get(file, "v1") @test !isready(v1) @test fetch(v1) == fill(float(ℯ), 1) @test isready(v1) v3 = adios_get(file, "v3") v4 = adios_get(file, "v4") @test !isready(v3) @test fetch(v3) == makearray(1, float(ℯ)) @test fetch(v4) == makearray(2, float(ℯ)) @test isready(v3) v5 = adios_get(file, "v5") v6 = adios_get(file, "g1/v6") v7 = adios_get(file, "g1/g2/v7") @test !isready(v5) adios_perform_gets(file) @test isready(v5) @test fetch(v5) == makearray(3, float(ℯ)) @test fetch(v6) == makearray(4, float(ℯ)) @test fetch(v7) == makearray(5, float(ℯ)) close(file) end end
module DecimalNumbers export Decimal importall Base.Operators # https://books.google.com/books?id=pNdiJMvPoZMC&pg=PA11&lpg=PA11&dq=IEEE+BID+format&source=bl&ots=-GbBYEh6Sa&sig=7_LN575lYEa8443zTGtFEOuLv1o&hl=en&sa=X&ved=0ahUKEwiqudHy0fLSAhUP62MKHbigDkwQ6AEIPjAI#v=onepage&q=IEEE%20BID%20format&f=false immutable Decimal{T <: Integer} value::T exp::T end Decimal{T, T2}(value::T, exp::T2) = Decimal(promote(value, exp)...) # normalize function normalize{T <: Integer}(x::T) value = x exp = Z = zero(T) for d in digits(x) if d == Z value = div(value, T(10)) exp += T(1) else break end end return value, exp end function Decimal{T}(d::Decimal{T}) v, e = normalize(d.value) return Decimal(v, e + d.exp) end Base.convert{T, T2}(::Type{Decimal{T}}, d::Decimal{T2}) = Decimal(T(d.value), T(d.exp)) # from int Base.convert{T}(::Type{Decimal{T}}, x) = convert(Decimal, x) function Base.convert{T <: Integer}(::Type{Decimal}, x::T) x == T(0) && return Decimal(T(0), T(0)) return Decimal(normalize(x)...) end # to int function Base.convert{T <: Integer}(::Type{T}, d::Decimal) d.exp < 0 && throw(InexactError()) return T(d.value * T(10)^d.exp) end Base.zero{T}(::Union{Decimal{T}, Type{Decimal{T}}}) = Decimal(zero(T)) Base.one{T}(::Union{Decimal{T}, Type{Decimal{T}}}) = Decimal(one(T)) float2int(::Type{BigFloat}) = BigInt float2int(::Type{Float64}) = Int64 float2int(::Type{Float32}) = Int32 float2int(::Type{Float16}) = Int16 # from float function Base.convert{T <: AbstractFloat}(::Type{Decimal}, x::T) # easy if float is int trunc(x) == x && return Decimal(float2int(T)(x)) # otherwise, go string route for now return parse(Decimal{float2int(T)}, string(x)) end # to float Base.convert{T <: AbstractFloat}(::Type{T}, d::Decimal) = T(d.value * exp10(d.exp)) function ==(a::Decimal, b::Decimal) aa, bb = _scale(a, b) return aa.value == bb.value && aa.exp == bb.exp end =={T}(a::Decimal, b::T) = ==(promote(a, b)...) =={T}(a::T, b::Decimal) = ==(promote(a, b)...) function <(a::Decimal, b::Decimal) aa, bb = _scale(a, b) return aa.value < bb.value end <{T}(a::Decimal, b::T) = <(promote(a, b)...) <{T}(a::T, b::Decimal) = <(promote(a, b)...) const ZERO = UInt8('0') const DOT = UInt8('.') const MINUS = UInt8('-') const PLUS = UInt8('+') """ Parse a Decimal from a string. Supports decimals of the following form: * "101" * "101." * "101.0" * "1.01" * ".101" * "0.101" * "0.0101" """ function Base.parse{T}(::Type{Decimal{T}}, str::String) str = strip(str) bytes = Vector{UInt8}(str) value = exp = zero(T) frac = neg = false for i = 1:length(bytes) b = bytes[i] if b == MINUS neg = true elseif b == PLUS continue elseif b == DOT frac = true continue else value *= T(10) value += T(b - ZERO) frac && (exp -= T(1)) end end for i = length(bytes):-1:1 b = bytes[i] if b == ZERO if exp < 0 value = div(value, T(10)) end exp += 1 else break end end return Decimal(ifelse(neg, T(-1), T(1)) * value, exp) end function Base.show(io::IO, d::Decimal) print(io, "dec\"") if d.value == 0 print(io, "0.0") else sn = sign(d.value) < 0 ? "-" : "" str = string(abs(d.value)) if d.exp == 0 print(io, sn, str, ".0") else if d.exp > 0 print(io, sn, rpad(str, length(str) + d.exp, '0'), ".0") else d = length(str) + d.exp if d == 0 print(io, sn, "0.", str) elseif d > 0 print(io, sn, str[1:d], ".", str[d+1:end]) else print(io, sn, "0.", "0"^abs(d), str) end end end end print(io, '"') return end # math -(d::Decimal) = Decimal(-d.value, d.exp) Base.abs(d::Decimal) = Decimal(abs(d.value), d.exp) # 10, 100 # (1, 1), (1, 2) # (1, 1), (10, 1) # 1.1, 0.001 # (11, -1), (1, -3) # (1100, -3), (1, -3) # 10, 0.1 # (1, 1), (1, -1) # (100, -1), (1, -1) # scales two decimals to the same exp _scale{T, T2}(a::Decimal{T}, b::Decimal{T2}) = _scale(promote(a, b)...) function _scale{T}(a::Decimal{T}, b::Decimal{T}) a.exp == b.exp && return a, b if a.exp < b.exp return a, Decimal(b.value * T(10)^(abs(b.exp - a.exp)), a.exp) else return Decimal(a.value * T(10)^(abs(a.exp - b.exp)), b.exp), b end end function +(a::Decimal, b::Decimal) a2, b2 = _scale(a, b) return Decimal(Decimal(a2.value + b2.value, a2.exp)) end function -(a::Decimal, b::Decimal) a2, b2 = _scale(a, b) return Decimal(Decimal(a2.value - b2.value, a2.exp)) end function *(a::Decimal, b::Decimal) exp = a.exp + b.exp val = a.value * b.value return Decimal(Decimal(val, exp)) end maxprec{T <: Integer}(::Type{T}) = T(length(string(typemax(T)))) function /{T}(a::Decimal{T}, b::Decimal{T}) b.value == 0 && throw(DivideError()) # scale num up to max precision scale = maxprec(T) - T(length(string(a.value))) aa = a.value * (widen(T)(10) ^ scale) # simulate division q, r = divrem(aa, b.value) # return scaled results return Decimal(Decimal(T(q + ifelse(div(r * 10, b.value) > 5, 1, 0)), a.exp - b.exp - scale)) end Base.promote_rule{T, T2}(::Type{Decimal{T}}, ::Type{Decimal{T2}}) = Decimal{promote_type(T, T2)} Base.promote_rule{T, TI <: Integer}(::Type{Decimal{T}}, ::Type{TI}) = Decimal{promote_type(T, TI)} Base.promote_rule{T, TF <: AbstractFloat}(::Type{Decimal{T}}, ::Type{TF}) = Decimal{float2int(promote_type(T, TF))} # TODO: # rounding, trunc, floor, ceil # maybe: # equality: isapprox? # ranges # fld, mod, rem, divrem, divmod, mod1, # fma, muladd # shifts? # trig functions # log, log2, log10 # exp, ldexp, modf # sqrt # special functions end # module
using HDF5,JLD,KUparser,Base.Test @date d = load("conll07.tst.jld4") @show ndeps = length(d["deprel"]) @date corpus = d["corpus"] @date feats = Flist.acl11eager # We try each arctype with rparse and oparse # They will complain if movecosts or nmoves is buggy for pt in (ArcEager13, ArcEagerR1, ArcHybrid13, ArcHybridR1) @show pt @date r = rparse(pt, corpus, ndeps) @show evalparse(r, corpus) @date (p,x,y) = oparse(pt, corpus, ndeps, feats) @show evalparse(p, corpus) p1 = pt(1, ndeps) @test @show size(x) == KUparser.xsize(p1, corpus, feats) @test @show size(y) == KUparser.ysize(p1, corpus) end
@testset "reified fixed to 1 or constraint violated or solved?" begin m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, x in CS.AllDifferent() || sum(x) > 2 || x[1] > 1) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] @test CS.fix!(com, variables[constraint.indices[1]], 1; check_feasibility = false) @test CS.fix!(com, variables[constraint.indices[2]], 1; check_feasibility = false) @test CS.is_constraint_violated(com, constraint, constraint.fct, constraint.set) ################# m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b := {x in CS.AllDifferent() || sum(x) <= 2 || 2x[1]+2x[2] > 8}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] @test CS.fix!(com, variables[constraint.indices[2]], 2; check_feasibility = false) @test CS.fix!(com, variables[constraint.indices[3]], 2; check_feasibility = false) @test CS.is_constraint_violated(com, constraint, constraint.fct, constraint.set) ################# m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b := {x in CS.AllDifferent() || sum(x) > 2}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] or_constraint = com.constraints[1].inner_constraint @test CS.fix!(com, variables[or_constraint.indices[1]], 1; check_feasibility = false) @test CS.fix!(com, variables[or_constraint.indices[2]], 1; check_feasibility = false) @test CS.is_constraint_violated(com, or_constraint, or_constraint.fct, or_constraint.set) ############################### m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b := {sum(x) > 2 || x in CS.AllDifferent()}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] or_constraint = com.constraints[1].inner_constraint @test CS.fix!(com, variables[or_constraint.indices[1]], 1; check_feasibility = false) @test CS.fix!(com, variables[or_constraint.indices[2]], 1; check_feasibility = false) @test CS.is_constraint_violated(com, or_constraint, or_constraint.fct, or_constraint.set) ################## m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b := {x in CS.AllDifferent() || sum(x) <= 2}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] @test CS.fix!(com, variables[constraint.indices[2]], 1; check_feasibility = false) @test CS.fix!(com, variables[constraint.indices[3]], 1; check_feasibility = false) @test CS.is_constraint_solved(com, constraint, constraint.fct, constraint.set) end @testset "Indicator fixed to 1 or constraint violated or solved?" begin m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b => {x in CS.AllDifferent() || sum(x) > 2 || x[1] > 1 }) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] @test CS.fix!(com, variables[constraint.indices[2]], 1; check_feasibility = false) @test CS.fix!(com, variables[constraint.indices[3]], 1; check_feasibility = false) @test CS.is_constraint_violated(com, constraint, constraint.fct, constraint.set) ################# m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b => {x in CS.AllDifferent() || sum(x) <= 2 || 2x[1]+2x[2] > 8}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] @test CS.fix!(com, variables[constraint.indices[2]], 2; check_feasibility = false) @test CS.fix!(com, variables[constraint.indices[3]], 2; check_feasibility = false) @test CS.is_constraint_violated(com, constraint, constraint.fct, constraint.set) ################# m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b => {x in CS.AllDifferent() || sum(x) > 2}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] or_constraint = com.constraints[1].inner_constraint @test CS.fix!(com, variables[or_constraint.indices[1]], 1; check_feasibility = false) @test CS.fix!(com, variables[or_constraint.indices[2]], 1; check_feasibility = false) @test CS.is_constraint_violated(com, or_constraint, or_constraint.fct, or_constraint.set) ############################### m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b => {sum(x) > 2 || x in CS.AllDifferent()}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] or_constraint = com.constraints[1].inner_constraint @test CS.fix!(com, variables[or_constraint.indices[1]], 1; check_feasibility = false) @test CS.fix!(com, variables[or_constraint.indices[2]], 1; check_feasibility = false) @test CS.is_constraint_violated(com, or_constraint, or_constraint.fct, or_constraint.set) ################## m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b => {x in CS.AllDifferent() || sum(x) <= 2}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] @test CS.fix!(com, variables[constraint.indices[2]], 1; check_feasibility = false) @test CS.fix!(com, variables[constraint.indices[3]], 1; check_feasibility = false) @test CS.is_constraint_solved(com, constraint, constraint.fct, constraint.set) end @testset "reified or constraint prune_constraint!" begin m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b := {2x[1]+x[2] >= 3 || x[1] > 1}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] constr_indices = constraint.indices @test CS.fix!(com, variables[constraint.indices[2]], 0; check_feasibility = false) CS.changed!(com, constraint, constraint.fct, constraint.set) @test CS.prune_constraint!(com, constraint, constraint.fct, constraint.set) for v in 0:2 @test !CS.has(variables[constraint.indices[3]], v) end # prune rhs m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @constraint(m, b := {x[1] > 1 || 2x[1]+x[2] >= 3}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] constr_indices = constraint.indices @test CS.fix!(com, variables[constraint.indices[2]], 0; check_feasibility = false) CS.changed!(com, constraint, constraint.fct, constraint.set) @test CS.prune_constraint!(com, constraint, constraint.fct, constraint.set) for v in 0:2 @test !CS.has(variables[constraint.indices[4]], v) end end @testset "reified or constraint still_feasible" begin m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @variable(m, 0 <= y <= 5, Int) @constraint(m, b := { x in CS.AllDifferent() || y < 1}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] or_constraint =constraint.inner_constraint constr_indices = or_constraint.indices @test CS.fix!(com, variables[constraint.indices[2]], 0; check_feasibility = false) @test CS.fix!(com, variables[constraint.indices[3]], 0; check_feasibility = false) @test !CS.still_feasible(com, or_constraint, or_constraint.fct, or_constraint.set, constr_indices[3], 1) # swap lhs and rhs m = Model(optimizer_with_attributes(CS.Optimizer, "no_prune" => true, "logging" => [])) @variable(m, b >= 1, Bin) @variable(m, 0 <= x[1:2] <= 5, Int) @variable(m, 0 <= y <= 5, Int) @constraint(m, b := { y < 1 || x in CS.AllDifferent()}) optimize!(m) com = CS.get_inner_model(m) variables = com.search_space constraint = com.constraints[1] or_constraint =constraint.inner_constraint constr_indices = or_constraint.indices @test CS.fix!(com, variables[constr_indices[2]], 0; check_feasibility = false) @test CS.fix!(com, variables[constr_indices[3]], 0; check_feasibility = false) @test !CS.still_feasible(com, or_constraint, or_constraint.fct, or_constraint.set, constr_indices[1], 1) end
using Test, DataFrames, CSV, BDisposal println("Testing BDisposal...") println("Testing BDisposal on js-data...") # Byung M. Jeon, Robin C. Sickles, "The Role of Environmental Factors in # Growth Accounting: a Nonparametric Analysis", Journal of Applied # Econometrics, Vol. 19, No. 5, 2004, pp. 567-591. data = CSV.read(joinpath(dirname(pathof(BDisposal)),"..","test","data","js-data","oecd.txt"),DataFrame; delim=' ',ignorerepeated=true,copycols=true,header=false) rename!(data,[:ccid,:year,:gdp,:co2,:capital,:labour,:energy]) goodInputsLabels = ["capital","labour"] badInputsLabels = ["energy"] goodOutputsLabels = ["gdp"] badOutputsLabels = ["co2"] sort!(data, [:year, :ccid]) # sort data by period and dmu periods = unique(data.year) dmus = unique(data.ccid) nGI, nBI, nGO, nBO, nPer, nDMUs, = length(goodInputsLabels), length(badInputsLabels), length(goodOutputsLabels), length(badOutputsLabels), length(periods),length(dmus) gI = Array{Float64}(undef, (nDMUs,nGI,nPer)) bI = Array{Float64}(undef, (nDMUs,nBI,nPer)) gO = Array{Float64}(undef, (nDMUs,nGO,nPer)) bO = Array{Float64}(undef, (nDMUs,nBO,nPer)) for (p,period) in enumerate(periods) periodData = data[data.year .== period,:] gI[:,:,p] = Matrix{Float64}(periodData[:,goodInputsLabels]) if nBI > 0 bI[:,:,p] = Matrix{Float64}(periodData[:,badInputsLabels]) end gO[:,:,p] = Matrix{Float64}(periodData[:,goodOutputsLabels]) bO[:,:,p] = Matrix{Float64}(periodData[:,badOutputsLabels]) end ################################################################################ # Testing prodIndex oecdAnalysis = prodIndex(gI,gO,bO,bI; retToScale="variable",prodStructure="multiplicative",convexAssumption=true) @test oecdAnalysis.prodIndexes[1,10] == 1.02891196267105 @test isapprox(oecdAnalysis.prodIndexes_G .* oecdAnalysis.prodIndexes_B, oecdAnalysis.prodIndexes, atol=0.000001) decomp = isapprox.(oecdAnalysis.prodIndexes_T .* oecdAnalysis.prodIndexes_E .* oecdAnalysis.prodIndexes_S, oecdAnalysis.prodIndexes, atol=0.000001) @test all(skipmissing(decomp)) == true oecdAnalysisA = prodIndex(gI,gO,bO,bI; retToScale="variable",prodStructure="addittive",convexAssumption=true) @test oecdAnalysisA.prodIndexes[1,10] == 0.02111291275337509 @test isapprox(oecdAnalysisA.prodIndexes_G .+ oecdAnalysisA.prodIndexes_B, oecdAnalysisA.prodIndexes, atol=0.000001) decomp = isapprox.(oecdAnalysisA.prodIndexes_T .+ oecdAnalysisA.prodIndexes_E .+ oecdAnalysisA.prodIndexes_S, oecdAnalysisA.prodIndexes, atol=0.000001) @test all(skipmissing(decomp)) == true oecdAnalysis_nc = prodIndex(gI,gO,bO,bI; retToScale="variable",prodStructure="multiplicative",convexAssumption=false) @test isapprox(oecdAnalysis_nc.prodIndexes_G .* oecdAnalysis_nc.prodIndexes_B, oecdAnalysis_nc.prodIndexes, atol=0.000001) oecdAnalysis_ncA = prodIndex(gI,gO,bO,bI; retToScale="variable",prodStructure="additive",convexAssumption=false) @test isapprox(oecdAnalysis_ncA.prodIndexes_G .+ oecdAnalysis_ncA.prodIndexes_B, oecdAnalysis_ncA.prodIndexes, atol=0.000001) @test isapprox(log.(oecdAnalysis_nc.prodIndexes), oecdAnalysis_ncA.prodIndexes, atol=0.05) ################################################################################ # Testing efficiencyScore using the Airports dataset.. println("Testing BDisposal on airport data...") airportData = CSV.read(joinpath(dirname(pathof(BDisposal)),"..","test","data","airports.csv"),DataFrame; delim=';',copycols=true) airportGoodInputs = ["employees","totalCosts"] airportBadInputs = [] airportGoodOutputs = ["passengers"] airportBadOutputs = ["co2emissions"] sort!(airportData, [:period, :dmu]) # sort data by period and dmu periods = unique(airportData.period) dmus = unique(airportData.dmu) nGI, nBI, nGO, nBO, nPer, nDMUs, = length(airportGoodInputs), length(airportBadInputs), length(airportGoodOutputs), length(airportBadOutputs), length(periods),length(dmus) # Setting empty containers for our data # Each of them is a 3D matrix where the first dimension is the decision units, the second one is the individual input or output item and the third dimension is the period to which the data refer gI = Array{Float64}(undef, (nDMUs,nGI,nPer)) # Good inputs bI = Array{Float64}(undef, (nDMUs,nBI,nPer)) # Bad inputs (optional) gO = Array{Float64}(undef, (nDMUs,nGO,nPer)) # Good outputs, aka "desiderable" outputs bO = Array{Float64}(undef, (nDMUs,nBO,nPer)) # Bad outputs, aka "undesiderable" outputs for (p,period) in enumerate(periods) periodData = airportData[airportData.period .== period,:] gI[:,:,p] = Matrix{Float64}(periodData[:,airportGoodInputs]) if nBI > 0 bI[:,:,p] = Matrix{Float64}(periodData[:,airportBadInputs]) end gO[:,:,p] = Matrix{Float64}(periodData[:,airportGoodOutputs]) bO[:,:,p] = Matrix{Float64}(periodData[:,airportBadOutputs]) end (λ_crs, λ_convex_crs, λ_nonconvex_crs, nonConvTest_crs, nonConvTest_value_crs) = efficiencyScores( gI,gO,bO,bI,retToScale="variable", dirGI=0,dirBI=0,dirGO=1,dirBO=0, prodStructure="multiplicative") @test nonConvTest_value_crs[3,2] ≈ 0.8842007631310966 ################################################################################ # Basic testing of dmuEfficiency println("Testing of the basic dmuEfficiency function..") I = [10 2; 8 4; 12 1.5; 24 3] O = [100;80;120;120] I₀ = [24 3] O₀ = [120] results = dmuEfficiency(I₀,O₀,I,O) I = [ 3 5 2.5 4.5 4 6 6 7 2.3 3.5 4 6.5 7 10 4.4 6.4 3 5 5 7 5 7 2 4 5 7 4 4 2 3 3 6 7 11 4 6 3 4 5 6 ] O = [ 40 55 30 45 50 40 55 45 30 48 20 60 28 50 25 48 20 65 80 65 57 25 48 30 45 64 42 70 65 48 45 65 40 45 40 44 65 25 35 38 18 64 20 50 15 38 20 60 68 64 54 25 38 20 45 67 32 57 60 40] nDMU = size(I,1) efficiencies = [dmuEfficiency(I[d,:],O[d,:],I,O)[:obj] for d in 1:nDMU] efficiencies = hcat(1:nDMU,efficiencies) efficiencies = efficiencies[sortperm(efficiencies[:, 2],rev=true), :] # Test treating last output as bad O2 = convert(Array{Float64,2},copy(O)) O2[:,3] = 1 ./ O2[:,3] # third is a bad output efficiencies = [dmuEfficiency(I[d,:],O2[d,:],I,O2)[:obj] for d in 1:nDMU] efficiencies = hcat(1:nDMU,efficiencies) efficiencies = efficiencies[sortperm(efficiencies[:, 2],rev=true), :] #Table 13.1 Cooper 2006 I = ones(Float64,9) O = [ 1 1 2 1 6 2 8 4 9 7 5 2 4 3 6 4 4 6 ] nDMU = size(I,1) O2 = convert(Array{Float64,2},copy(O)) O2[:,2] = 1 ./ O2[:,2] # third is a bad output efficiencies = [dmuEfficiency(I[d,:],O2[d,:],I,O2)[:obj] for d in 1:nDMU] efficiencies = hcat(1:nDMU,efficiencies) efficiencies = efficiencies[sortperm(efficiencies[:, 2],rev=true), :] I = [ 4 140 5 90 6 36 10 300 11 66 8 36 9 12 5 210 5.5 33 8 288 10 80 8 8 ] O =[ 2 28 1 22.5 6 12 8 60 7 16.5 6 12 7 6 3 30 4.4 5.5 4 72 2 20 1 4 ] nDMU = size(I,1) efficiencies = [dmuEfficiency(I[d,:],O[d,:],I,O)[:obj] for d in 1:nDMU] efficiencies = hcat(1:nDMU,efficiencies) efficiencies = efficiencies[sortperm(efficiencies[:, 2],rev=true), :] I = [ 1 1 1 1 1 1 1 1] O = [ 1 7 2 7 4 6 6 4 7 2 7 1 2 2 5.3 5.3 ] nDMU = size(I,1) efficiencies = [dmuEfficiency(I[d,:],O[d,:],I,O)[:obj] for d in 1:nDMU] #efficiencies = hcat(1:nDMU,efficiencies) #scatter(O[:,1],O[:,2]) @test efficiencies == [1.0,1.0,1.0,1.0,1.0,1.0,0.37735849056603776,1.0] # From Example 2.2 of Cooper et oth. 2006 "Data envelopment Analysis. A Comprehensive Text with...." X = [4 7 8 4 2 10; 3 3 1 2 4 1] Y = [1 1 1 1 1 1] nDMU = size(X,2) out = [dmuEfficiency(X[:,d],Y[:,d],X',Y') for d in 1:nDMU] @test out[1].obj ≈ 0.8571428571428571 @test out[1].wI ≈ [0.14285714285714285, 0.14285714285714285] @test out[1].wO ≈ [0.8571428571428571] @test collect(keys(out[1].refSet)) ≈ [5,4] || collect(keys(out[1].refSet)) ≈ [4,5] @test collect(values(out[1].refSet)) ≈ [0.2857142857142857,0.7142857142857143] || collect(values(out[1].refSet)) ≈ [0.7142857142857143,0.2857142857142857] @test [i[:eff] for i in out] == [false,false,true,true,true,false] outDual = [dmuEfficiencyDual(X[:,d],Y[:,d],X',Y') for d in 1:nDMU] @test [i[:eff] for i in outDual] == [false,false,true,true,true,false] # From Example 2.2 of Cooper et oth. 2006 "Data envelopment Analysis. A Comprehensive Text with...." X = [4 7 8 4 2 10; 3 3 1 2 4 1] Y = [1 1 1 1 1 1] nDMU = size(X,2) out = [dmuEfficiency(X[:,d],Y[:,d],X',Y') for d in 1:nDMU] @test out[1].obj ≈ 0.8571428571428571 @test out[1].wI ≈ [0.14285714285714285, 0.14285714285714285] @test out[1].wO ≈ [0.8571428571428571] @test collect(keys(out[1].refSet)) ≈ [5,4] || collect(keys(out[1].refSet)) ≈ [4,5] @test collect(values(out[1].refSet)) ≈ [0.2857142857142857,0.7142857142857143] || collect(values(out[1].refSet)) ≈ [0.7142857142857143,0.2857142857142857] @test [i[:eff] for i in out] == [false,false,true,true,true,false] outDual = [dmuEfficiencyDual(X[:,d],Y[:,d],X',Y') for d in 1:nDMU] @test [i[:eff] for i in outDual] == [false,false,true,true,true,false]
############################################################################################ # Import External Packages using Test using Random: Random, AbstractRNG, seed! using UnPack: UnPack, @unpack, @pack! using Distributions ############################################################################################ # Import Baytes Packages using BaytesCore, ModelWrappers, BaytesMCMC ############################################################################################ # Include Files include("TestHelper.jl") ############################################################################################ # Run Tests @testset "All tests" begin include("test-construction.jl") #include("test-nuts.jl") end
function spdiags(B,d,m,n) d = d[:] p = length(d) len = zeros(p+1,1) for k = 1:p len[k+1] = int(len[k]+length(Base.max(1,1-d[k]): Base.min(m,n-d[k]))) end a = zeros(int(len[p+1]),3) for k = 1:p # Append new d[k]-th diagonal to compact form i = Base.max(1,1-d[k]):Base.min(m,n-d[k]) a[(int(len[k])+1):int(len[k+1]),:] = [i i+d[k] B[i+(m>=n)*d[k],k]] end A = sparse(int(a[:,1]),int(a[:,2]),a[:,3],m,n) return A end y = readcsv("snp_500.txt") n = length(y) e = ones(n, 1) D = spdiags([e -2*e e], 0:2, n-2, n) lambda = 50 start = time() D*x println(time() - start) x = Variable(n) p = minimize(lambda*sum(D*x)) println(time() - start) solve!(p) p.optval println(time() - start)
abstract type AbstractJones{T} <: AbstractMatrix{T} end struct Gain{S, T<:Number} <: AbstractJones{T} g1::T g2::T end struct DTerm{S, T<:Number} <: AbstractJones{T} d1::T d2::T end
@testset "Heat balance for single line" begin I_lim = 732.147 # A V_base = 138.0e3 # V emm = 0.7 # emissivity, [0.23, 0.91] T_s = 70.0 # conductor surface temperature, C T_a = 35.0 # ambient temperature, C phi = 90.0 # wind/line angle in degrees: wind perpendicular to line. H_e = 61.0 # height above sea level in m. Avg PJM elevation. V_w = 0.61 # wind speed in m/s alpha = 0.9 # solar absorptivity, [0.23, 0.91] lat = 40.0 # latitude in deg N = 161 # day of year: June 10 Z_l = 90.0 # line azimuth: West-to-East hours_from_noon = 0.0 # time: noon # R and bundle are not necessary here a = acsr_interpolation(I_lim, V_base) D, Al_m, St_m, R, bundle, label = a.D, a.Al_m, a.St_m, a.R, a.bundle, a.label A_prime = D # conductor area, m^2 per linear m eta_r = eq_eta_r(D, emm) T_film = eq6_T_film(T_s, T_a) k_f = eq15a_k_f(T_film) K_angle = eq4a_K_angle(phi) p_f = eq14a_p_f(H_e, T_film) mu_f = eq13a_mu_f(T_film) N_Re = eq2c_N_Re(D, p_f, V_w, mu_f) eta_c = eq_eta_c(k_f, K_angle, N_Re) omega = eq_omega(hours_from_noon) delta = eq16b_delta(N) H_c = eq16a_H_c(lat, delta, omega) chi = eq17b_chi(omega, lat, delta) C = eqtable2_C(omega, chi) Z_c = eq17a_Z_c(C, chi) theta = eq9_theta(H_c, Z_c, Z_l) Q_s = eq18_Q_s(H_c) K_solar = eq20_K_solar(H_e) Q_se = eq19_Q_se(K_solar, Q_s) eta_s = eq8_q_s(alpha, Q_se, theta, A_prime) @test D ≈ 0.0232156 atol=atol @test Al_m ≈ 0.779797 atol=atol @test St_m ≈ 0.285727 atol=atol @test R ≈ 6.167979e-5 atol=atol @test bundle == 1 @test label == "Parakeet" @test eta_r ≈ 0.289266376 atol=atol @test T_film == 52.5 @test k_f ≈ 0.02815328 atol=atol @test K_angle ≈ 1.2311481927818961 atol=atol @test p_f ≈ 1.0763378424625318 atol=atol @test mu_f ≈ 1.9642517300084803e-5 atol=atol @test N_Re ≈ 775.999091387987 atol=atol @test eta_c ≈ 1.5240287413704434 atol=atol @test omega == 0.0 @test delta ≈ 23.021449792571953 atol=atol @test H_c ≈ 73.02144979257197 atol=atol @test chi == 0.0 @test C == 180.0 @test Z_c == 180.0 @test theta == 90.0 @test Q_s ≈ 1025.3693031729497 atol=atol @test K_solar ≈ 1.00696157132 atol=atol @test Q_se ≈ 1032.5074847063267 atol=atol @test eta_s ≈ 21.57325268575338 atol=atol end @testset "ACSR interpolation" begin acsr = acsr_interpolation(400.0, 138e3) @test acsr isa ACSRSpecsMetric @test acsr.label == "Penguin" @test acsr.R ≈ 1.9520997e-4 atol=atol acsr = acsr_interpolation(400.0, 138e3; metric=false) @test acsr isa ACSRSpecsEnglish @test acsr.label == "Penguin" @test acsr.R ≈ 0.119 atol=atol acsr = acsr_interpolation(1200.0, 138e3) @test acsr.label == "Lark" @test acsr.bundle == 2 acsr = acsr_interpolation(10.0, 138e3) @test acsr.label == "Turkey" acsr = acsr_interpolation(3e3, 338e3) @test acsr.label == "Chukar" @test acsr.bundle == 2 acsr = acsr_interpolation(200.0, 20e3) @test acsr.label == "Sparrow" @test acsr.bundle == 1 @test_logs (:warn, "No ACSR match for line with I_lim = 6.0e6 A and V_base = 20000.0 kV") acsr_interpolation(6e6, 20e3) acsr = acsr_interpolation(6e6, 20e3) @test acsr.label == "" @test acsr.bundle == 1000 @test isnan(acsr.D) end @testset "Line lengths" begin I_lim = 400.0 V_base = 138e3 acsr = acsr_interpolation(I_lim, V_base) S_base = 100e6 R_pu = 0.001 l = estimate_length(S_base, V_base, R_pu, acsr.R, acsr.bundle) l_test = 975.5649076 @test l ≈ l_test atol=atol l = estimate_length(S_base, V_base, R_pu * 10, acsr.R, acsr.bundle) @test l ≈ l_test * 10 atol=atol l = estimate_length(S_base, V_base, R_pu, acsr.R, acsr.bundle * 2) @test l ≈ l_test * 2 atol=atol l = estimate_length(S_base, V_base / 10, R_pu, acsr.R, acsr.bundle * 2) @test l ≈ 19.511298 atol=atol end
# save current configuration to EEPROM. # power supply will power up in this state. # EEP export psp_savepreset const SAVE_PRESET = [0x45, 0x45, 0x50, 0x0d] """ psp_savepreset(io) Save current configuration to EEPROM. """ function psp_savepreset(io_psp::IO) write(io_psp, SAVE_PRESET) return nothing end
function metronome(bpm::Real=72, bpb::Int=4) s = 60.0 / bpm counter = 0 while true counter += 1 if counter % bpb != 0 println("tick") else println("TICK") end sleep(s) end end
include("bimodal_cauchy_distribution.jl") ADE_DefaultOptions = merge(DE_DefaultOptions, { # Distributions we will use to generate new F and CR values. "fdistr" => bimodal_cauchy(0.65, 0.1, 1.0, 0.1), "crdistr" => bimodal_cauchy(0.1, 0.1, 0.95, 0.1), }) # An Adaptive DE typically change parameters of the search dynamically. This is # typically done in the tell! function when we know if the trial vector # was better than the target vector. type AdaptConstantsDiffEvoOpt <: DifferentialEvolutionOpt name::ASCIIString # A population is a matrix of floats. population::Array{Float64, 2} search_space::SearchSpace # Options options # Set of functions that together define a specific DE strategy. sample::Function mutate::Function crossover::Function bound::Function # Specific data and functions for adaptation fs::Vector{Float64} # One f value per individual in population crs::Vector{Float64} # One cr value per individual in population function AdaptConstantsDiffEvoOpt(name, pop, ss, options, sample, mutate, crossover, bound) popsize = size(pop, 1) fs = [sample_bimodal_cauchy(options["fdistr"]; truncateBelow0 = false) for i in 1:popsize] crs = [sample_bimodal_cauchy(options["crdistr"]) for i in 1:popsize] new(name, pop, ss, merge(DE_DefaultOptions, options), sample, mutate, crossover, bound, fs, crs) end end # To get the constants for an adaptive DE we access the vectors of constants. fconst(ade::AdaptConstantsDiffEvoOpt, i) = ade.fs[i] crconst(ade::AdaptConstantsDiffEvoOpt, i) = ade.crs[i] # To sample we use the distribution given as options sample_f(ade::AdaptConstantsDiffEvoOpt) = sample_bimodal_cauchy(ade.options["fdistr"]; truncateBelow0 = false) sample_cr(ade::AdaptConstantsDiffEvoOpt) = sample_bimodal_cauchy(ade.options["crdistr"]; truncateBelow0 = false) # Tell the optimizer about the ranking of candidates. Returns the number of # better candidates that were inserted into the population. function tell!(de::AdaptConstantsDiffEvoOpt, # archive::Archive, # Skip for now rankedCandidates) num_candidates = length(rankedCandidates) num_better = 0 for i in 1:div(num_candidates, 2) candidate, index = rankedCandidates[i] if candidate != de.population[index, :] num_better += 1 old = de.population[index,:] de.population[index,:] = candidate # Since the trial vector was better we keep the f and cr values for this target. else # The trial vector for this target was not better so we change the f and cr constants. de.fs[index] = sample_f(de) de.crs[index] = sample_cr(de) end end num_better end function adaptive_de_rand_1_bin(parameters = Dict()) params = Parameters(parameters, ADE_DefaultOptions) ss = get(params, :SearchSpace, BlackBoxOptim.symmetric_search_space(1)) population = get(params, :Population, BlackBoxOptim.rand_individuals_lhs(ss, 50)) AdaptConstantsDiffEvoOpt("AdaptiveDE/rand/1/bin", population, ss, params, random_sampler, de_mutation_rand_1, de_crossover_binomial, rand_bound_from_target!) end function adaptive_de_rand_1_bin_radiuslimited(parameters = Dict()) params = Parameters(parameters, ADE_DefaultOptions) ss = get(params, :SearchSpace, BlackBoxOptim.symmetric_search_space(1)) population = get(params, :Population, BlackBoxOptim.rand_individuals_lhs(ss, 50)) AdaptConstantsDiffEvoOpt("AdaptiveDE/rand/1/bin/radiuslimited", population, ss, params, radius_limited_sampler, de_mutation_rand_1, de_crossover_binomial, rand_bound_from_target!) end
@testset "SMeasure" begin x, y = rand(100), rand(100) X, Y = Dataset(rand(100, 3)), Dataset(rand(100, 2)) Z, W = Dataset(rand(110, 2)), Dataset(rand(90, 4)) dx, τx = 2, 1 dy, τy = 2, 1 @test s_measure(x, y) isa Float64 @test s_measure(x, Y, dx = dx, τx = τx) isa Float64 @test s_measure(X, y, dy = dy, τy = τy) isa Float64 @test s_measure(X, Y) isa Float64 # test that multivariate datasets are being length-matched @test s_measure(X, Z) isa Float64 @test s_measure(W, X) isa Float64 end
############################################################################## # # Accelerators.jl # # Part of CVortex.jl # Control use of accelerators such as GPUs. # # Copyright 2019 HJA Bird # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. ############################################################################## """ The number of GPU or other accelerators found by the CVortex library. It is possible that accelerators may be listed multiple times if they can be used by more than one installed platform. To know how many are in use see number_of_enabled_accelerators() """ function number_of_accelerators() res = ccall(("cvtx_num_accelerators", libcvortex), Cint, ()) return res end """ The number of accelerators that CVortex has been directed to use. If no accelerators are in use this is zero, and the CPU is used for all computation. Find which accelerators are enabled using accelerator_enabled, and enable and disable with accelerator_enable and accelerator_disable. """ function number_of_enabled_accelerators() # int cvtx_num_enabled_accelerators(); res = ccall(("cvtx_num_enabled_accelerators", libcvortex), Cint, ()) return res end """ The name of an accelerator. Input is an integer in the range 1:number_of_accelerators(). Returns the name of the accelerator as a string. """ function accelerator_name(accelerator_id :: Int) @assert(accelerator_id >= 1, "Minimum accelerator id is 1.") @assert(accelerator_id <= number_of_accelerators(), "accelerator_id is higher than the number of accelerators found.") # char* cvtx_accelerator_name(int accelerator_id); res = ccall(("cvtx_accelerator_name", libcvortex), Cstring, (Cint,), accelerator_id-1) return unsafe_string(res) end """ States whether CVortex is in use. """ function accelerator_enabled(accelerator_id :: Int) @assert(accelerator_id >= 1, "Minimum accelerator id is 1.") @assert(accelerator_id <= number_of_accelerators(), "accelerator_id is higher than the number of accelerators found.") # int cvtx_accelerator_enabled(int accelerator_id); res = ccall(("cvtx_accelerator_enabled", libcvortex), Cint, (Cint,), accelerator_id-1) return res end """ Allows CVortex to use an accelerator. """ function accelerator_enable(accelerator_id :: Int) @assert(accelerator_id >= 1, "Minimum accelerator id is 1.") @assert(accelerator_id <= number_of_accelerators(), "accelerator_id is higher than the number of accelerators found.") # void cvtx_accelerator_enable(int accelerator_id); ccall(("cvtx_accelerator_enable", libcvortex), Cvoid, (Cint,), accelerator_id-1) return end """ Stops CVortex using an accelerator. """ function accelerator_disable(accelerator_id :: Int) @assert(accelerator_id >= 1, "Minimum accelerator id is 1.") @assert(accelerator_id <= number_of_accelerators(), "accelerator_id is higher than the number of accelerators found.") # void cvtx_accelerator_disable(int accelerator_id); ccall(("cvtx_accelerator_disable", libcvortex), Cvoid, (Cint,), accelerator_id-1) return end
#= https://dtai.cs.kuleuven.be/problog/tutorial/basic/03_dice.html """ The following example illustrates the use of a logic program with recursion and lists. We start by rolling the first die. Every roll determines the next die to roll, but we stop if we have used that die before. We query for the possible sequences of rolled dice. We use three-sided dice instead of the regular six-sided ones simply to restrict the number of possible outcomes (and thus inference time). """ Cf ~/blog/rolling_dice5.blog ~/webppl/rolling_dice5.wppl =# using Turing, StatsPlots, DataFrames include("jl_utils.jl") @model function rolling_dice5(n=3) function roll(a) # t ~ DiscreteUniform(1,n) t = rand(DiscreteUniform(1,n)) if t in a return a else return roll(vcat(a,t)) end end a = roll([]) len ~ DiscreteUniform(1,n) len ~ Dirac(length(a)) # In the example, the first roll is 1. true ~ Dirac(a[1] == 1) end function run_model(len=0) model = rolling_dice5(len) num_chns = 4 # chns = sample(model, Prior(), 10_000) # chns = sample(model, MH(), 10_000) chns = sample(model, MH(), 100_000) # chns = sample(model, PG(15), MCMCThreads(), 1_000, num_chns) # chns = sample(model, SMC(1000), MCMCThreads(), 10_000, num_chns) # chns = sample(model, SMC(1000), 10_000) # chns = sample(model, IS(), 10_000) # display(chns) show_var_dist_pct(chns,:len,1000) end genq = undef for val in 1:6 global genq println("\nval:$val") @time run_model(val) end println("\nval=10") # println("mean:", mean(run_model(10))) run_model(10) println("\nval=100") # println("mean:", mean(run_model(100))) run_model(100)
# # Traversal # # This code demonstrates how to use and extend advanced optics. # The examples are taken from the README.md of the specter clojure library. # Many of the features here are experimental, please consult the docstrings of the # involved optics. using Test using Accessors import Accessors: modify, OpticStyle using Accessors: ModifyBased, SetBased, setindex # ### Increment all even numbers # We have the following data and the goal is to increment all nested even numbers. data = (a = [(aa=1, bb=2), (cc=3,)], b = [(dd=4,)]) # To acomplish this, we define a new optic `Vals`. function mapvals(f, d) Dict(k => f(v) for (k,v) in pairs(d)) end mapvals(f, nt::NamedTuple) = map(f, nt) struct Vals end OpticStyle(::Type{Vals}) = ModifyBased() modify(f, obj, ::Vals) = mapvals(f, obj) # Now we can increment as follows: out = @set data |> Vals() |> Elements() |> Vals() |> If(iseven) += 1 @test out == (a = [(aa = 1, bb = 3), (cc = 3,)], b = [(dd = 5,)]) struct Filter{F} keep_condition::F end OpticStyle(::Type{<:Filter}) = ModifyBased() (o::Filter)(x) = filter(o.keep_condition, x) function modify(f, obj, optic::Filter) I = eltype(eachindex(obj)) inds = I[] for i in eachindex(obj) x = obj[i] if optic.keep_condition(x) push!(inds, i) end end vals = f(obj[inds]) setindex(obj, vals, inds) end # ### Append to nested vector data = (a = 1:3,) out = @modify(v -> vcat(v, [4,5]), data.a) @test out == (a = [1,2,3,4,5],) # ### Increment last odd number in a sequence data = 1:4 out = @set data |> Filter(isodd) |> last += 1 @test out == [1,2,4,4] ### Map over a sequence data = 1:3 out = @set data |> Elements() += 1 @test out == [2,3,4] # ### Increment all values in a nested Dict data = Dict(:a => Dict(:aa =>1), :b => Dict(:ba => -1, :bb => 2)) out = @set data |> Vals() |> Vals() += 1 @test out == Dict(:a => Dict(:aa => 2),:b => Dict(:bb => 3,:ba => 0)) # ### Increment all the even values for :a keys in a sequence of maps data = [Dict(:a => 1), Dict(:a => 2), Dict(:a => 4), Dict(:a => 3)] out = @set data |> Elements() |> _[:a] += 1 @test out == [Dict(:a => 2), Dict(:a => 3), Dict(:a => 5), Dict(:a => 4)] # ### Retrieve every number divisible by 3 out of a sequence of sequences function getall(obj, optic) out = Any[] modify(obj, optic) do val push!(out, val) end out end data = [[1,2,3,4],[], [5,3,2,18],[2,4,6], [12]] optic = @optic _ |> Elements() |> Elements() |> If(x -> mod(x, 3) == 0) out = getall(data, optic) @test out == [3, 3, 18, 6, 12] @test_broken eltype(out) == Int # ### Increment the last odd number in a sequence data = [2, 1, 3, 6, 9, 4, 8] out = @set data |> Filter(isodd) |> _[end] += 1 @test out == [2, 1, 3, 6, 10, 4, 8] @test_broken eltype(out) == Int # ### Remove nils from a nested sequence data = (a = [1,2,missing, 3, missing],) optic = @optic _.a |> Filter(!ismissing) out = optic(data) @test out == [1,2,3]
using SplitApplyCombine """ normalize_year(fun, fams) Compute function `fun` for each family in `fams` and divide the result by the average for all families with the same earliest filing date. """ function normalize_year(fun, fams::Vector{Family}) year = Dates.year.(earliest_filing.(fams)) vals = fun.(fams) dict = group(year, vals) refs = mean.(dict) map(zip(year, vals)) do (y, v) r = refs[y] r == 0 ? 0 : v / r end end """ normalize_year(fun, g, fams) Compute function `fun` for all vertices in `g` and divide the result by the average for all families with the same earliest filing date. """ function normalize_year(fun, g::AbstractGraph, fams::Vector{Family}) year = Dates.year.(earliest_filing.(fams)) vals = fun(g) dict = group(year, vals) refs = mean.(dict) map(zip(year, vals)) do (y, v) r = refs[y] r == 0.0 ? 0.0 : v / r end end function component(g::AbstractGraph, which=1) cc = weakly_connected_components(g) idx = sortperm(length.(cc), rev=true) vids = reduce(vcat, cc[idx[which]]) induced_subgraph(g, vids) end function top_applicants(families, k) apps = reduce(vcat, applicants.(families)) c = StatsBase.countmap(apps) ks = collect(keys(c)); vs = collect(values(c)) idx = sortperm(vs, rev=true) NamedTuple(Symbol.(first(ks[idx], k)) .=> first(vs[idx], k)) end function maxcentralization_degree(g) N = nv(g) if is_directed(g) return (N-1)*(N-1) else return (N-1)*(N-2) end end function centralization(g, measure) c = measure(g) @assert measure in [degree, indegree, outdegree] val, ind = findmax(c) return sum(val .- c) / maxcentralization_degree(g) end using MainPaths function component(mp::MainPaths.MainPathResult, which=1) g, cs = Patents.component(mp.mainpath, which) vs = mp.vertices[cs] s = Set(mp.vertices[mp.start]) start = findall(v -> v in s, vs) MainPaths.MainPathResult(g, vs, start) end function get_stats(mp, segment, families, g) idxs = mp.vertices[segment.intermediates] fams = families[idxs] ef = Dates.year.(earliest_filing.(fams)) (; size = length(fams), span = maximum(ef) - minimum(ef), density = (maximum(ef) - minimum(ef)) / length(fams), weight = MainPaths.meanweight(mp, segment, SPCEdge(:log)(g)), familysize = mean(f.size for f in fams), citedinternal = mean(outdegree(g, idxs)), citedexternal = mean(citedby_count.(fams)), citinginternal = mean(indegree(g, idxs)), citingexternal = mean(cites_count.(fams)), classdiversity = Patents.diversity(fams, subclass), jurdiversity = Patents.jurdiversity(fams), applicant_homogeneity = Patents.share_same_applicant(fams), topapplicant = Patents.top_applicants(fams, 2) ) end function findstart(g, fams, k; period=(2000, 2015), cpc=["Y", "B", "C"], levelfun=section) idx = map(fams) do f y = Dates.year(earliest_filing(f)) c = levelfun.(classification(f)) (period[1] .<= y .<= period[2]) && any(s in cpc for s in c) end |> findall cit = Patents.normalize_year(outdegree, g, fams) ck = sort(cit[idx], rev=true)[k] intersect(idx, findall(cit .>= ck)) end
abstract type BoundaryComponent{N} end """ get_positions(boundary_component::BoundaryComponent{N}) -> Vector{SVectorF{N}} Return the positions of the boundary particles. """ function get_positions end """ get_velocities(boundary_component::BoundaryComponent{N}) -> Vector{SVectorF{N}} Return the velocities of the boundary particles. """ function get_velocities end """ get_velocity(boundary_component::BoundaryComponent{N}, i::Unsigned) -> SVectorF{N} Return the velocity of the boundary particle with the given index. """ function get_velocity(boundary_component::BoundaryComponent, i::Unsigned) velocities = get_boundary_velocities(boundary_component) velocities[i] end """ get_pressures(boundary_component::BoundaryComponent) -> Vector{Float} Return the virtual pressures of the boundary particles. """ function get_pressures end """ get_pressure(boundary_component::BoundaryComponent, i::Unsigned) -> Float Return the virtual pressure of the boundary particle with the given index. """ function get_pressure(boundary_component::BoundaryComponent, i::Unsigned) pressures = get_boundary_pressures(boundary_component) pressures[i] end """ compute_boundary_mass_density( boundary_component::BoundaryComponent, energy_component::EnergyComponent, eos::EquationOfState, idx_fluid::Unsigned, idx_boundary::Unsigned, ) Compute the virtual mass density of the boundary particle with index `idx_boundary` due to its interaction with the fluid particle with index `idx_fluid`. """ function compute_mass_density end """ updateboundaries!( boundary_component::BoundaryComponent{N}, positions::AbstractVector{SVectorF{N}}, velocities::Velocities{N}, mass_component::MassComponent{MD,<:Kernel{N}}, pressures::Pressures, ) Update the state of the boundary particles according to the given fluid particles. """ function updateboundaries! end """ evolveboundaries!(boundary_component::BoundaryComponent, Δt::Number) Evolves the boundary particles with the given time step. """ function evolveboundaries! end include("boundary/none.jl") include("boundary/wall.jl")
@testset "AnalyticVI" begin seed!(42) L = 3 D = 10 N = 20 b = 5 i = AnalyticVI() @test i isa AnalyticVI{Float64} @test AnalyticVI(; ϵ=0.0001f0) isa AnalyticVI{Float32} @test AnalyticSVI(10; ϵ=0.0001f0) isa AnalyticVI{Float32} @test repr(i) == "Analytic Variational Inference" @test AGP.ρ(i) == 1.0 @test AGP.is_stochastic(i) == false i = AnalyticSVI(b) @test i isa AnalyticVI{Float64} AGP.set_ρ!(i, N / b) @test AGP.ρ(i) == N / b @test AGP.is_stochastic(i) == true end
""" Main module for `GigaSOM.jl` - Huge-scale, high-performance flow cytometry clustering The documentation is here: http://LCSB-BioCore.github.io/GigaSOM.jl """ module GigaSOM using CSV using DataFrames using Distances using Distributed using DistributedData using Distributions using FCSFiles using FileIO using DistributedArrays using NearestNeighbors using Serialization using StableRNGs include("base/structs.jl") include("base/dataops.jl") include("base/trainutils.jl") include("analysis/core.jl") include("analysis/embedding.jl") include("io/input.jl") include("io/process.jl") include("io/splitting.jl") #core export initGigaSOM, trainGigaSOM, mapToGigaSOM #trainutils export linearRadius, expRadius, gaussianKernel, bubbleKernel, thresholdKernel, distMatrix #embedding export embedGigaSOM # structs export Som #io/input export readFlowset, readFlowFrame, loadFCS, loadFCSHeader, getFCSSize, loadFCSSizes, loadFCSSet, selectFCSColumns, distributeFCSFileVector, distributeFileVector, getCSVSize, loadCSV, loadCSVSizes, loadCSVSet #io/splitting export slicesof, vcollectSlice, collectSlice #io/process export cleanNames!, getMetaData, getMarkerNames #dataops (higher-level operations on data) export dtransform_asinh end # module
const _parker_params = ( A = [0.809, 0.330], T = [0.17046, 0.365], σ = [0.0563, 0.132], α = 1.050, β = 0.1685, s = 38.078, τ = 0.483, ) """ aif_parker(t; params, hct = 0.42) Returns the arterial input function defined in Parker et al. [@Parker2006]. The timepoints `t` are in minutes with the bolus arrival time defined as `t = 0`. The model parameters from Ref [@Parker2006] will be used by default unless an optional `params` input is provided. The hematocrit `hct` is used to convert the concentration in blood to plasma and has default value of 0.42. """ function aif_parker(t; params = _parker_params, hct = 0.42) @extract (A, T, σ, α, β, s, τ) params cb = [ (A[1] / (σ[1] * sqrt(2 * pi))) * exp(-(t - T[1])^2 / (2 * (σ[1])^2)) + (A[2] / (σ[2] * sqrt(2 * pi))) * exp(-(t - T[2])^2 / (2 * (σ[2])^2)) + α * exp(-β * t) / (1.0 + exp(-s * (t - τ))) for t in t ] cb[t.<=0] .= 0 ca = cb ./ (1 - hct) return ca end const _georgiou_params = (A = [0.37, 0.33, 10.06], m = [0.11, 1.17, 16.02], α = 5.26, β = 0.032, τ = 0.129) """ aif_georgiou(t; params, hct = 0.35) Returns the concentration in blood plasma using the model defined in Georgiou et al. [@Georgiou2018]. The timepoints `t` are in minutes with the bolus arrival defined as `t = 0`. The model parameters from the paper will be used by default unless an optional `params` input is provided. The hematocrit `hct` is used to convert the concentration in blood to plasma and has default value of 0.35. """ function aif_georgiou(t; params = _georgiou_params, hct = 0.35) @extract (A, m, α, β, τ) params # The AIF can be split into two parts exponential_part = zeros(size(t)) gammavariate_part = zeros(size(t)) for (i, t) in enumerate(t) exponential_part[i] = sum(A .* exp.(-m * t)) if t > 7.5 # Gamma variate part undefined for high N (i.e. t > 7.5 min), so fix its value gammavariate_part[i] = 3.035 continue end N = fld(t, τ) # `fld` might be more efficient than `floor` for j = 0:N gammavariate_part[i] += gammavariate((j + 1) * α + j, β, t - j * τ) end end cb = exponential_part .* gammavariate_part cb[t.<=0] .= 0 ca = cb ./ (1 - hct) return ca end function gammavariate(α, β, t)::Float64 if t > 0 gammavalue = (t^α * exp(-t / β)) / (β^(α + 1) * gamma(α + 1)) if !isnan(gammavalue) return gammavalue end end return 0 end """ aif_biexponential(t; params, hct = 0) Returns an AIF defined by the biexponential model with the form ``D * (a_1 exp(-m_1 t) + a_2 exp(-m_2 t))``. The `t` input is in minutes with the bolus arriving at 0. The `params` can be a named tuple, e.g. `params = (D=0.1, a=[4.0, 4.78], m=[0.144, 0.011])`. The `hct` is used to convert the concentration in blood to plasma. The default value is set to to zero, i.e. no conversion takes place. """ function aif_biexponential(t; params, hct = 0) @extract (D, a, m) params cb = [D * (a[1] * exp(-m[1] * t) + a[2] * exp(-m[2] * t)) for t in t] cb[t.<=0] .= 0 ca = cb ./ (1 - hct) return ca end """ aif_weinmann(t) Returns an AIF defined by the biexponential model with parameters from Tofts & Kermode [@Tofts1991] and Weinmann et al. [@Weinmann1984]. The `t` input is in minutes with the bolus arriving at 0. The model describes concentration in plasma, therefore a hematocrit is not necessary. """ function aif_weinmann(t) params = (; D = 0.1, a = [3.99, 4.78], m = [0.144, 0.0111]) return aif_biexponential(t; params, hct = 0) end """ aif_fritzhansen(t) Returns an AIF defined by the biexponential model with parameters based on data from Fritz-Hansen et al. [@Fritz-Hansen1996]. The model parameters were adopted from Whitcher & Schmid [@Whitcher2011] The `t` input is in minutes with the bolus arriving at 0. The model describes concentration in plasma, therefore a hematocrit is not necessary. """ function aif_fritzhansen(t; hct = 0) params = (; D = 1.0, a = [2.4, 0.62], m = [3.0, 0.016]) return aif_biexponential(t; params, hct) end """ aif_orton1(t; params = (aB = 10.4, μB = 12.0, aG = 1.24, μG = 0.169), hct = 0.42) Returns the concentration in blood plasma using the bi-exponential model defined in Orton et al. [@Orton2008]. The timepoints `t` are in minutes with the bolus arriving at 0. The model parameters from the paper will be used by default unless an optional `params` input is provided. The `hct` is used to convert the concentration in blood to plasma and has default value of 0.42. """ function aif_orton1(t; params = (aB = 10.4, μB = 12.0, aG = 1.24, μG = 0.169), hct = 0.42) @extract (aB, μB, aG, μG) params AB = aB - aB * aG / (μB - μG) AG = aB * aG / (μB - μG) cb = [AB * exp(-μB * t) + AG * exp(-μG * t) for t in t] cb[t.<0] .= 0 ca = cb ./ (1 - hct) return ca end """ aif_orton2(t; params = (aB = 344, μB = 20.2, aG = 1.24, μG = 0.172), hct = 0.42) Returns the concentration in blood plasma using the 2nd model defined in Orton et al. [@Orton2008]. The timepoints `t` are in minutes with the bolus arriving at 0. The model parameters from the paper will be used by default unless an optional `params` input is provided. The `hematocrit` is used to convert the concentration in blood to plasma and has default value of 0.42. """ function aif_orton2(t; params = (aB = 344, μB = 20.2, aG = 1.24, μG = 0.172), hct = 0.42) @extract (aB, μB, aG, μG) params AB = aB - aB * aG / (μB - μG) AG = aB * aG / (μB - μG)^2 cb = [AB * t * exp(-μB * t) + AG * (exp(-μG * t) - exp(-μB * t)) for t in t] cb[t.<=0] .= 0 ca = cb ./ (1 - hct) return ca end """ aif_orton3(t; params = (aB = 2.84, μB = 22.8, aG = 1.36, μG = 0.171), hct = 0.42) Returns the concentration in blood plasma using the 3rd model defined in Orton et al. [@Orton2008]. The timepoints `t` are in minutes with the bolus arriving at `t = 0`. The model parameters from the paper will be used by default unless an optional `params` input is provided. The `hct` is used to convert the concentration in blood to plasma and has default value of 0.42. """ function aif_orton3(t; params = (aB = 2.84, μB = 22.8, aG = 1.36, μG = 0.171), hct = 0.42) @extract (aB, μB, aG, μG) params tb = 2 * pi / μB cb = zeros(length(t)) for (i, t) in enumerate(t) if t <= tb cb[i] = aB * (1 - cos(μB * t)) + aB * aG * _orton3_f(t, μG, μB) else cb[i] = aB * aG * _orton3_f(tb, μG, μB) * exp(-μG * (t - tb)) end end cb[t.<=0] .= 0 ca = cb ./ (1 - hct) return ca end function _orton3_f(t, α, μB) (1 / α) * (1 - exp(-α * t)) - (1 / (α^2 + μB^2)) * (α * cos(μB * t) + μB * sin(μB * t) - α * exp(-α * t)) end
@enum dq_ref begin q = 1 d = 2 end @enum RI_ref begin R = 1 I = 2 end function dq_ri(δ::Float64) ## Uses the referenceframe of the Kundur page 852 of dq to RI dq_ri = [sin(δ) cos(δ); -cos(δ) sin(δ)] end function ri_dq(δ::Float64) #Uses the reference frame of the Kundur page 852 of RI to dq ri_dq = [sin(δ) -cos(δ); cos(δ) sin(δ)] end
using JSON @testset "test matpower parser" begin @testset "30-bus case file" begin result = run_opf("../test/data/case30.m", ACPPowerModel, ipopt_solver) @test result["status"] == :LocalOptimal @test isapprox(result["objective"], 204.96; atol = 1e-1) end @testset "30-bus case matpower data" begin data = PowerModels.parse_file("../test/data/case30.m") @test isa(JSON.json(data), String) result = run_opf(data, ACPPowerModel, ipopt_solver) @test result["status"] == :LocalOptimal @test isapprox(result["objective"], 204.96; atol = 1e-1) end @testset "14-bus case file with bus names" begin data = PowerModels.parse_file("../test/data/case14.m") @test data["bus"]["1"]["bus_name"] == "Bus 1 HV" @test isa(JSON.json(data), String) end @testset "5-bus case file with pwl cost functions" begin data = PowerModels.parse_file("../test/data/case5_pwlc.m") @test data["gen"]["1"]["model"] == 1 @test isa(JSON.json(data), String) end @testset "3-bus case file with hvdc lines" begin data = PowerModels.parse_file("../test/data/case3.m") @test length(data["dcline"]) > 0 @test isa(JSON.json(data), String) end @testset "2-bus case file with spaces" begin result = run_pf("../test/data/case2.m", ACPPowerModel, ipopt_solver) @test result["status"] == :LocalOptimal @test isapprox(result["objective"], 0.0; atol = 1e-1) end end @testset "test matpower data coercion" begin @testset "ACP Model" begin result = run_opf("../test/data/case14.m", ACPPowerModel, ipopt_solver) @test result["status"] == :LocalOptimal @test isapprox(result["objective"], 8081.5; atol = 1e0) #@test result["status"] = bus_name end @testset "DC Model" begin result = run_opf("../test/data/case14.m", DCPPowerModel, ipopt_solver) @test result["status"] == :LocalOptimal @test isapprox(result["objective"], 7642.6; atol = 1e0) end @testset "QC Model" begin result = run_opf("../test/data/case14.m", QCWRPowerModel, ipopt_solver) @test result["status"] == :LocalOptimal @test isapprox(result["objective"], 8075.1; atol = 1e0) end end @testset "test matpower extentions parser" begin @testset "3-bus extended constants" begin data = PowerModels.parse_file("../test/data/case3.m") @test data["const_int"] == 123 @test data["const_float"] == 4.56 @test data["const_str"] == "a string" @test isa(JSON.json(data), String) end @testset "3-bus extended matrix" begin data = PowerModels.parse_file("../test/data/case3.m") @test haskey(data, "areas") @test data["areas"]["1"]["col_1"] == 1 @test data["areas"]["1"]["col_2"] == 1 @test data["areas"]["2"]["col_1"] == 2 @test data["areas"]["2"]["col_2"] == 3 @test isa(JSON.json(data), String) end @testset "3-bus extended named matrix" begin data = PowerModels.parse_file("../test/data/case3.m") @test haskey(data, "areas_named") @test data["areas_named"]["1"]["area"] == 4 @test data["areas_named"]["1"]["refbus"] == 5 @test data["areas_named"]["2"]["area"] == 5 @test data["areas_named"]["2"]["refbus"] == 6 @test isa(JSON.json(data), String) end @testset "3-bus extended predefined matrix" begin data = PowerModels.parse_file("../test/data/case3.m") @test haskey(data, "areas_named") @test data["branch"]["1"]["rate_i"] == 50.2 @test data["branch"]["1"]["rate_p"] == 45 @test data["branch"]["2"]["rate_i"] == 36 @test data["branch"]["2"]["rate_p"] == 60.1 @test data["branch"]["3"]["rate_i"] == 12 @test data["branch"]["3"]["rate_p"] == 30 @test isa(JSON.json(data), String) end @testset "3-bus extended matrix from cell" begin data = PowerModels.parse_file("../test/data/case3.m") @test haskey(data, "areas_cells") @test data["areas_cells"]["1"]["col_1"] == "Area 1" @test data["areas_cells"]["1"]["col_2"] == 123 @test data["areas_cells"]["1"]["col_4"] == "Slack \\\"Bus\\\" 1" @test data["areas_cells"]["1"]["col_5"] == 1.23 @test data["areas_cells"]["2"]["col_1"] == "Area 2" @test data["areas_cells"]["2"]["col_2"] == 456 @test data["areas_cells"]["2"]["col_4"] == "Slack Bus 3" @test data["areas_cells"]["2"]["col_5"] == 4.56 @test isa(JSON.json(data), String) end @testset "3-bus extended named matrix from cell" begin data = PowerModels.parse_file("../test/data/case3.m") @test haskey(data, "areas_named_cells") @test data["areas_named_cells"]["1"]["area_name"] == "Area 1" @test data["areas_named_cells"]["1"]["area"] == 123 @test data["areas_named_cells"]["1"]["area2"] == 987 @test data["areas_named_cells"]["1"]["refbus_name"] == "Slack Bus 1" @test data["areas_named_cells"]["1"]["refbus"] == 1.23 @test data["areas_named_cells"]["2"]["area_name"] == "Area 2" @test data["areas_named_cells"]["2"]["area"] == 456 @test data["areas_named_cells"]["2"]["area2"] == 987 @test data["areas_named_cells"]["2"]["refbus_name"] == "Slack Bus 3" @test data["areas_named_cells"]["2"]["refbus"] == 4.56 @test isa(JSON.json(data), String) end @testset "3-bus extended predefined matrix from cell" begin data = PowerModels.parse_file("../test/data/case3.m") @test haskey(data, "areas_named") @test data["branch"]["1"]["name"] == "Branch 1" @test data["branch"]["1"]["number_id"] == 123 @test data["branch"]["2"]["name"] == "Branch 2" @test data["branch"]["2"]["number_id"] == 456 @test data["branch"]["3"]["name"] == "Branch 3" @test data["branch"]["3"]["number_id"] == 789 @test isa(JSON.json(data), String) end @testset "3-bus tnep case" begin data = PowerModels.parse_file("../test/data/case3_tnep.m") @test haskey(data, "ne_branch") @test data["ne_branch"]["1"]["f_bus"] == 1 @test data["ne_branch"]["1"]["construction_cost"] == 1 @test isa(JSON.json(data), String) end @testset "`build_ref` for 3-bus tnep case" begin data = PowerModels.parse_file("../test/data/case3_tnep.m") ref = PowerModels.build_ref(data) @assert !(data["multinetwork"]) ref = ref[:nw][0] @test haskey(data, "name") @test haskey(ref, :name) @test data["name"] == ref[:name] end end
# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/ # Niccolò Antonello <nantonel@idiap.ch> fst = WFST(["a","b","c"],["p","q","r"]) add_arc!(fst,1,1,"a","p",2) add_arc!(fst,1,2,"b","q",3) add_arc!(fst,2,2,"c","r",4) initial!(fst,1) final!(fst,2,5) fst_plus = closure(fst; star=false) println(fst_plus) fst_star = closure(fst; star=true) println(fst_star) @test isinitial(fst_star,3) @test isfinal(fst_star,3) @test isfinal(fst_star,2) W = typeofweight(fst) ilabels=["a","b","c"] o1,w1 = fst(ilabels) @test o1 == ["p","q","r"] @test w1 == W(2)*W(3)*W(4)*W(5) o2,w2 = fst_star([ilabels;ilabels]) @test o2 == [o1;o1] @test w2 == w1*w1 o3,w3 = fst_star([ilabels;ilabels]) @test o3 == o3 @test w2 == w3 o,w = fst([ilabels;ilabels]) @test w == zero(W) # fst star accepts empty string and returns the same with weight one o,w = fst_star(String[]) @test o == String[] @test w == one(W) # fst plus does not accept empty string o,w = fst_plus(String[]) @test w == zero(W)
function _maximise_nonlinear_through_budgeted(instance::CombinatorialInstance{T}, rewards::Dict{T, Float64}, weights::Dict{T, Int}, max_weight::Int, nl_func::Function, solve_all_budgets_at_once::Bool) where T solutions = _maximise_nonlinear_through_budgeted_sub(instance, rewards, weights, max_weight, Val(solve_all_budgets_at_once)) # TODO: Replace the mandatory parameter solve_all_budgets_at_once by a function defined on the solvers, so that each of them can indicate what they support? Then, if this parameter is not set, the most efficient implementation is called if available; otherwise, follow this parameter (and still warn if the required implementation is not available). # TODO: make it a trait of the underlying algorithm to get a default value. Do the same for ESCB2. best_solution = Int[] best_objective = -Inf for (budget, sol) in solutions # Ignore infeasible cases. if length(sol) == 0 || sol == [-1] continue end # Compute the maximum. f_x = nl_func(sol, budget) if f_x > best_objective best_solution = sol best_objective = f_x end end return best_solution, best_objective end function _maximise_nonlinear_through_budgeted_sub(instance::CombinatorialInstance{T}, rewards::Dict{T, Float64}, weights::Dict{T, Int}, max_weight::Int, ::Val{true})::Dict{Int, Vector{T}} where T if ! applicable(solve_all_budgeted_linear, instance.solver, rewards, weights, max_weight) if applicable(solve_budgeted_linear, instance.solver, rewards, weights, max_weight) # @warn("The function solve_all_budgeted_linear is not defined for the solver $(typeof(instance.solver)).") return _maximise_nonlinear_through_budgeted_sub(instance, rewards, weights, max_weight, Val(false)) else error("Neither solve_budgeted_linear nor solve_all_budgeted_linear are not defined for the solver $(typeof(instance.solver)).") end end return solve_all_budgeted_linear(instance.solver, rewards, weights, max_weight) end function _maximise_nonlinear_through_budgeted_sub(instance::CombinatorialInstance{T}, rewards::Dict{T, Float64}, weights::Dict{T, Int}, max_weight::Int, ::Val{false})::Dict{Int, Vector{T}} where T if ! applicable(solve_budgeted_linear, instance.solver, rewards, weights, max_weight) if applicable(solve_all_budgeted_linear, instance.solver, rewards, weights, max_weight) # @warn("The function solve_budgeted_linear is not defined for the solver $(typeof(instance.solver)).") return _maximise_nonlinear_through_budgeted_sub(instance, rewards, weights, max_weight, Val(true)) else error("Neither solve_budgeted_linear nor solve_all_budgeted_linear are not defined for the solver $(typeof(instance.solver)).") end end # Assumption: rewards is more complete than weights. @assert length(keys(rewards)) >= length(keys(weights)) # Start the computation, memorising all solutions (one per value of the budget) along the way. solutions = Dict{Int, Vector{T}}() budget = 0 while budget <= max_weight sol = solve_budgeted_linear(instance.solver, rewards, weights, budget) if length(sol) == 0 || sol == [-1] # Infeasible! for b in budget:max_weight solutions[b] = sol end break end # Feasible. Fill the dictionary as much as possible for this budget: if the constraint is not tight, the solution # is constant for all budgets between the value prescribed in the budget constraint until the obtained budget. sol_budget = sum(arm in keys(weights) ? weights[arm] : 0 for arm in keys(rewards) if arm in sol) for b in budget:sol_budget solutions[b] = sol end budget = sol_budget + 1 end return solutions end
# Errors. using Base.Libc: errno """ e.g. constant_name(32; prefix="POLL") -> [:POLLNVAL] Look up name for C-constant(s) with value `n`. """ function constant_name(n::Integer; prefix="", first=false) @nospecialize v = get(C.constants, n, Symbol[]) if prefix != "" v = filter(x -> startswith(String(x), prefix), v) end if length(v) == 0 string(n) elseif first || length(v) == 1 string(v[1]) else string("Maybe: ", join(("$(n)?" for n in v), ", ")) end end constant_name(n; kw...) = constant_name(Int(n); kw...) """ Throw SystemError with `errno` info for failed C call. """ systemerror(p, errno::Cint=errno(); kw...) = Base.systemerror(p, errno; extrainfo=errname(errno)) errname(n) = constant_name(n; prefix="E") """ @cerr [allow=C.EINTR] f(args...) If `f` returns -1 throw SystemError with `errno` info. """ macro cerr(a, b=nothing) ex = b == nothing ? a : b allow = b == nothing ? b : a @require ex isa Expr && ex.head == :call @require allow == nothing || ( allow isa Expr && allow.head == Symbol("=") && allow.args[1] == :allow) f = ex.args[1] args = ex.args[2:end] r = gensym() condition = allow == nothing ? :($r == -1) : :($r == -1 && errno() ∉ $(allow.args[2])) esc(:(begin $r = $ex $condition && systemerror(dbstring($f, ($(args...),))) @assert $r >= -1 $r end)) end """ @czero f(args...) If `f` returns non-zero throw SystemError with return value as `errno`. """ macro cerr0(ex) @require ex isa Expr && ex.head == :call f = ex.args[1] args = ex.args[2:end] r = gensym() esc(:(begin $r = $ex $r != 0 && systemerror(dbstring($f, ($(args...),)), $r) nothing end)) end # End of file: errors.jl
using PyPlot if !@isdefined(CGS) include("../../../src/CGS.jl") using Main.CGS end include("../../../src/seager_mr.jl") include("../../../src/loglinspace.jl") #function mass_radius2(mass_ratio_total,mstar,smstar,flatchain,logplot) nplanet = 7 # Give names to planets: planet_name=["b","c","d","e","f","g","h"] #cname = ["b","g","r","c","m","y","k"] cname = ["C0","C1","C2","C3","C4","C5","C6","C7"] r1 = 0.6 r2 = 1.2 nr = 200 if logplot m1 = 0.01 m2 = 4.0 else m1 = 0.20 m2 = 1.6 end nm = 600 mrgrid = zeros(nplanet,nr,nm) rgrid = zeros(nr) mgrid = zeros(nm) for i=1:nr rgrid[i] = (i-0.5)*(r2-r1)/nr+r1 end for i=1:nm if logplot mgrid[i] = 10 .^((i-0.5)*(log10(m2)-log10(m1))/nm)*m1 else mgrid[i] = (i-0.5)*(m2-m1)/nm+m1 end end # Set up plotting window in Matplotlib (called by PyPlot): #fig,axes = subplots() # Number of posterior samples to select: nsamp = 10000000 cmf = zeros(nplanet,nsamp) #nsamp = 30000 npoints = [100,100,100,100,100,100,1000] i0 = 20001 # Factor to convert from solar masses to Earth masses: fac_mass = MSUN/MEARTH # Factor to convert from solar radii to Earth radii: fac_rad = RSUN/REARTH # Average mass of star in solar masses: #mstar = 0.09 # Mass of star # Stand deviation of mass of star in solar masses: #smstar = 0.01 # Uncertainty on stellar mass # Loop over planets: #conf = [0.997, 0.95, 0.683] conf = [0.95, 0.683] nconf = length(conf) level_mr = zeros(nplanet,nconf) mavg = zeros(nplanet) merror = zeros(nplanet) ravg = zeros(nplanet) rerror = zeros(nplanet) # Photodynamic size: pdsize = size(flatchain)[2] # N-body HMC size: nhmc = size(mass_ratio_total)[2] # Use latest markov chain radius ratios: # Set up vectors for samples: msamp = zeros(nplanet,nsamp) rsamp = zeros(nplanet,nsamp) mstar_samp = zeros(nsamp) rho_samp = zeros(nsamp) rstar_samp = zeros(nsamp) # Loop over number of samples: for isamp=1:nsamp # Draw from posterior distribution: mplanet = mass_ratio_total[:,ceil(Int64,rand()*nhmc)] # Select a stellar mass: mstar_samp[isamp] = mstar+randn()*smstar # Compute the mass of planet in Earth mass units: msamp[:,isamp] = mplanet .*(mstar_samp[isamp]*fac_mass) # Select a density (relative to Solar): ipd = ceil(Int64,rand()*pdsize) rho_samp[isamp] = flatchain[15,ipd] # Compute the radius of the star in solar radii: rstar_samp[isamp] = (mstar_samp[isamp]/rho_samp[isamp])^(1/3) # Compute the radius of planet in Earth radii units: # Randomly select a radius ratio: rsamp[:,isamp] = flatchain[1:nplanet,ipd] .*(rstar_samp[isamp]*fac_rad) # Compute CMF from Zeng et al. (2016) formula: cmf[:,isamp] = (1.07 .-rsamp[:,isamp] .*msamp[:,isamp].^(-1/3.7))./0.21 # Now compute density distribution: for j=1:nplanet if msamp[j,isamp] > m1 && msamp[j,isamp] < m2 && rsamp[j,isamp] > r1 && rsamp[j,isamp] < r2 ir = ceil(Int64,(rsamp[j,isamp]-r1)/(r2-r1)*nr) if logplot im = ceil(Int64,(log(msamp[j,isamp])-log(m1))/(log(m2)-log(m1))*nm) else im = ceil(Int64,(msamp[j,isamp]-m1)/(m2-m1)*nm) end mrgrid[j,ir,im] +=1.0 end end end for j=1:nplanet # Set levels for each planet: mrgrid[j,:,:] /= float(sum(mrgrid[j,:,:])) mrgrid_sort = sort(vec(mrgrid[j,:,:])) i0 = nm*nr mrgrid_cum = mrgrid_sort[i0] while mrgrid_cum < conf[1] && i0 > 1 i0 -= 1 for k=1:nconf if mrgrid_cum < conf[k] && (mrgrid_cum+mrgrid_sort[i0]) > conf[k] level_mr[j,k] = 0.5*(mrgrid_sort[i0]+mrgrid_sort[i0+1]) end end mrgrid_cum += mrgrid_sort[i0] end println(j," Mass: ",mean(msamp[j,:])," ",std(msamp[j,:])," fractional error: ",std(msamp[j,:])/mean(msamp[j,:])*100.0,"%") println(j," Radius: ",mean(rsamp[j,:])," ",std(rsamp[j,:])," fractional error: ",std(rsamp[j,:])/mean(rsamp[j,:])*100.0,"%") merror[j] = std(msamp[j,:]) mavg[j] = mean(msamp[j,:]) rerror[j] = std(rsamp[j,:]) ravg[j] = mean(rsamp[j,:]) end # Plot maximum likelihood values: #mopt = readdlm("optimum_values.txt") #ropt = [0.08581987985664834,0.08461786201718988,0.060328647716537474,0.07106532992445118, 0.08035101963995364, 0.08570949401350199, 0.057994985982196025, 53.833783736830554] for j=1:nplanet # cs = axes.contour(mgrid,rgrid,mrgrid[j,:,:],levels = level_mr[j,:],colors=cname[j],linewidth=2.0,label=planet_name[j]) cs = contour(mgrid,rgrid,mrgrid[j,:,:],levels = level_mr[j,:],colors=cname[j],linewidth=2.0) # plot(mopt[(j-1)*5+1]*fac_mass*mstar,ropt[j]*(mstar/ropt[8])^(1/3)*fac_rad,"o",label=planet_name[j],color=cname[j]) plot(mavg[j],ravg[j],"o",label=planet_name[j],color=cname[j]) # axes[:imshow](mrgrid[j,:,:],alpha=0.1) end # Make some plots: #axes.set_xlabel(L"Mass $[M_\oplus]$") xlabel(L"Mass $[M_\oplus]$") #axes.set_ylabel(L"Radius $[R_\oplus]$") ylabel(L"Radius $[R_\oplus]$") #axes.axis([m1,m2,r1,r2]) axis([m1,m2,r1,r2]) text(1.0,1.00,"Earth") text(0.85,0.93,"Venus") if logplot #axes.set_xscale("log") set_xscale("log") end #mm = logarithmspace(-2.5,0.2,1000) #plot(mm,seager_mr(mm,"H2O"),label="Water",linewidth=3,linestyle="--") #plot(mm,seager_mr(mm,"Fe"),label="Iron",linewidth=3,linestyle="--") #plot(mm,seager_mr(mm,"Earth"),label="Earth",linewidth=3,linestyle="--") #plot(mm,seager_mr(mm,"MgSiO3"),label="Rock",linewidth=3,linestyle="--") #axes[:legend](loc = "upper left",fontsize=10) #axes.legend(loc = "upper left",fontsize=10) #legend(loc = "upper left",fontsize=10) #return merror #end
@testset "1143.longest-common-subsequence.jl" begin @test longest_common_subsequence("abcde", "ace") == 3 @test longest_common_subsequence("abc", "abc") == 3 @test longest_common_subsequence("abc", "def") == 0 end
#initialize queens variables and domains columns = [1, 2, 3, 4, 5, 6, 7, 8] rows = Dict(col => columns for col in columns) println("defining columns and rows") #----------------------------------------------------------------- mutable struct QueensConstraint variables::Vector{Int} function QueensConstraint(columns::Vector{Int}) println("creating constraint") variables = columns return new(variables) end end #----------------------------------------------------------------- #checks if the constraint is satisfied returns boolean function satisfied(cons::QueensConstraint,assignment) println("check if satisfied") for (q1c,q1r) in assignment # q1c = queen 1 column, q1r = queen 1 row for q2c in range(q1c + 1, stop=length(cons.variables)+1) # q2c = queen 2 column if q2c in keys(assignment) q2r = assignment[q2c] # q2r = queen 2 row if q1r == q2r # same row? return false end if abs(q1r-q2r) == abs(q1c-q2c) # same diagonal? return false end end end end return true # no conflict end #----------------------------------------------------------------- #csp struct for struct CSP #the problem's fields variables::Vector domains::Dict{Int, Vector} constraints::Dict{Int, Vector{}} #constructor function CSP(vars, doms, cons=Dict()) println("creating csp") variables = vars domains = doms constraints = cons for var in vars constraints[var] = Vector() if (!haskey(domains, var)) error("Every variable should have a domain assigned to it.") end end return new(variables, domains, constraints) end end #----------------------------------------------------------------- function add_constraint(csp:: CSP, constraint::QueensConstraint) for var in constraint.variables println("adding cons") if (!(var in csp.variables)) error("Variable in constraint not in CSP") else push!(csp.constraints[var], constraint) end end end #----------------------------------------------------------------- function consistent(csp:: CSP, variable, assignment)::Bool println("check consistency") for constraint in csp.constraints[variable] if (!satisfied(constraint, assignment)) return false end return true end end #----------------------------------------------------------------- function backtracking_search(csp:: CSP, assignment=Dict(), path=Dict())::Union{Dict,Nothing} println("back tracking") # assignment is complete if every variable is assigned (our base case) if length(assignment) == length(csp.variables) return assignment end unassigned = [v for v in csp.variables if!(v in keys(assignment))] #= # get all variables without assignments unassigned::Vector{Int} = [] for v in csp.variables if (!haskey(assignment, v)) push!(unassigned, v) end end =# # get the every possible domain value of the first unassigned variable first = unassigned[1] # println(first) # pretty_print(csp.domains) for value in csp.domains[first] local_assignment = deepcopy(assignment) local_assignment[first] = value # if we're still consistent, we recurse (continue) if consistent(csp, first, local_assignment) # forward checking, prune future assignments that will be inconsistent for un in unassigned ass = deepcopy(local_assignment) for (i, val) in enumerate(csp.domains[un]) ass[un] = val if un != first if(!consistent(csp, un, ass)) deleteat!(csp.domains[un], i) end end end end path[first] = csp.domains # println("reduced") #out(csp.domains) result = backtracking_search(csp, local_assignment) #backtrack if nothing is found if result !== nothing out(path) return result end end end return nothing end #----------------------------------------------------------------- function out(d::Dict, pre=1) for (k,v) in d if typeof(v) <: Dict s = "$(repr(k)) => " println(join(fill(" ", pre)) * s) out(v, pre+1+length(s)) else println(join(fill(" ", pre)) * "$(repr(k)) => $(repr(v))") end end nothing end #----------------------------------------------------------------- csp = CSP(columns,rows) add_constraint(csp, QueensConstraint(columns)) solution = backtracking_search(csp) if solution != Nothing print("solution is: ", solution) else println("No solution found!") end
#= Implement a stack that has the following methods: push(val), which pushes an element onto the stack pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null. max(), which returns the maximum value in the stack currently. If there are no elements in the stack, then it should throw an error or return null. Each method should run in constant time. =# using Test include("Solutions/problem43_implement_stack.jl") push(2) push(5) @test stack == [2, 5] @test max() == 5 @test pop() == 5 @test stack == [2] @test pop() == 2 @test stack == [] @test isnothing(max()) @test isnothing(pop())
using Test, LinearAlgebra, SparseArrays, Random using QDLDL rng = Random.MersenneTwister(2401) @testset "refactoring checks" begin m = 20 n = 30 A = random_psd(n) + Diagonal(rand(n)) B = sprandn(m,n,0.2) C1 = -Diagonal(rand(m)) C2 = -Diagonal(rand(m)) M1 = [A B' ; B C1] M2 = [A B' ; B C2] M3 = [A B' ; B -pi*I] b = randn(m+n) F = qdldl(M1,perm = randperm(m+n)) @test norm(M1\b - F\b) <= 1e-10 #update the diagonal of M and F and try again update_diagonal!(F,(n+1):(m+n),diag(C2)) @test norm(M2\b - F\b) <= 1e-10 #update to a scalar and try again update_diagonal!(F,(n+1):(m+n),-pi) @test norm(M3\b - F\b) <= 1e-10 end
using Brownian using Base.Test @test convert(FGN, FBM(0:0.5:10, 0.4)) == FGN(0.757858283255199,0.4) p = FBM(0:1/2^10:1, 0.4) # fBm using FFT approach rand(p) rand(p, fbm=false) rand([p, p]) # fBm using Riemann-Liouville approach rand(p, method=:rl) rand(p, method=:rl, wtype=:improved) rand([p, p], method=:rl) rand([p, p], method=:rl, wtype=:improved) # fBm using Cholesky approach rand(p, method=:chol) rand(p, fbm=false, method=:chol) rand([p, p], method=:chol) # Checking function for efficient Cholesky update p = FBM(0:.1:.1*100, 0.4) q = FBM(0:.1:.1*101, 0.4) P = autocov(p) Q = autocov(q) c = chol(P)' chol_update(convert(Array{Float64, 2}, c), Q)
function strip_output_color(cur_string::AbstractString) replace(cur_string, r"\e[^m]*m", "") end
function type1totype0!(data::MIDIFile) if data.format != UInt8(1) error("Got type $(data.format); expecting type 1") end if dochannelsconflict(getprogramchangeevents(data)) error("Conversion failed since different tracks patch different instruments to the same channel. Use getprogramchangeevents for inspection.") end for track in data.tracks toabsolutetime!(track) end for track in data.tracks[2:end] insertsorted!(data.tracks[1].events, track.events) end data.tracks = data.tracks[1:1] fromabsolutetime!(data.tracks[1]) data.format = 0 data end function type1totype0(data::MIDIFile) newdata = deepcopy(data) type1totype0!(newdata) end function type0totype1!(data::MIDIFile) if data.format != UInt8(0) error("Got type $(data.format); expecting type 0") end toabsolutetime!(data.tracks[1]) push!(data.tracks, MIDITrack(Array{TrackEvent, 1}())) nofchannels = 0 for event in data.tracks[1].events if !isa(event, MIDIEvent) push!(data.tracks[2].events, event) else channelnum = channelnumber(event) while channelnum > nofchannels push!(data.tracks, MIDITrack(Array{TrackEvent, 1}())) nofchannels += 1 end push!(data.tracks[channelnum + 2].events, event) end end shift!(data.tracks) trackstoremove = [] for i in 1:length(data.tracks) if length(data.tracks[i].events) == 0 push!(trackstoremove, i) else fromabsolutetime!(data.tracks[i]) end end deleteat!(data.tracks, trackstoremove) data.format = 1 data end function type0totype1(data::MIDIFile) newdata = deepcopy(data) type0totype1!(newdata) end function insertsorted!(events1::Array{TrackEvent, 1}, events2::Array{TrackEvent, 1}) map(x -> insertsorted!(events1, x), events2) end function insertsorted!(events1::Array{TrackEvent, 1}, event::TrackEvent) i = 0 while i < length(events1) && events1[end - i].dT > event.dT i += 1 end insert!(events1, length(events1) - i + 1, event) end function toabsolutetime!(track::MIDITrack) t = Int(0) for event in track.events t += event.dT event.dT = t end end function fromabsolutetime!(track::MIDITrack) t0 = t1 = Int(0) for event in track.events t1 = event.dT event.dT = event.dT - t0 if event.dT < 0 error("Negative deltas are not allowed. Please reorder your events.") end t0 = t1 end end function getprogramchangeevents(data::MIDIFile) pgevents = [] t = 0 for track in data.tracks t += 1 i = 0 for event in track.events i += 1 if event isa ProgramChangeEvent push!(pgevents, [t, i, event]) end end end pgevents end function dochannelsconflict(pgevents) channels = Dict() for pgevent in pgevents newkey = pgevent[3].status if haskey(channels, newkey) if channels[newkey][1] != pgevent[1] && channels[newkey][2] != pgevent[3].data[1] return true end else channels[newkey] = (pgevent[1], pgevent[3].data[1]) end end false end
# This file was generated by the Julia Swagger Code Generator # Do not modify this file directly. Modify the swagger specification instead. mutable struct IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation <: SwaggerModel description::Any # spec type: Union{ Nothing, String } # spec name: description url::Any # spec type: Union{ Nothing, String } # spec name: url function IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation(;description=nothing, url=nothing) o = new() validate_property(IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation, Symbol("description"), description) setfield!(o, Symbol("description"), description) validate_property(IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation, Symbol("url"), url) setfield!(o, Symbol("url"), url) o end end # type IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation const _property_map_IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation = Dict{Symbol,Symbol}(Symbol("description")=>Symbol("description"), Symbol("url")=>Symbol("url")) const _property_types_IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation = Dict{Symbol,String}(Symbol("description")=>"String", Symbol("url")=>"String") Base.propertynames(::Type{ IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation }) = collect(keys(_property_map_IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation)) Swagger.property_type(::Type{ IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation[name]))} Swagger.field_name(::Type{ IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation }, property_name::Symbol) = _property_map_IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation[property_name] function check_required(o::IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation) true end function validate_property(::Type{ IoK8sApiextensionsApiserverPkgApisApiextensionsV1ExternalDocumentation }, name::Symbol, val) end
# NOTE: # Type fields # fieldnames(Stan.Sample) # num_samples, num_warmup, save_warmup, thin, adapt, algorithm # fieldnames(Stan.Hmc) # engine, metric, stepsize, stepsize_jitter # fieldnames(Stan.Adapt) # engaged, gamma, delta, kappa, t0, init_buffer, term_buffer, window # Ref # http://goedman.github.io/Stan.jl/latest/index.html#Types-1 sample(mf::T, ss::Stan.Sample) where {T<:Function} = sample(mf, ss.num_samples, ss.num_warmup, ss.save_warmup, ss.thin, ss.adapt, ss.alg) sample(mf::T, num_samples::Int, num_warmup::Int, save_warmup::Bool, thin::Int, ss::Stan.Sample) where{T<:Function} = sample(mf, num_samples, num_warmup, save_warmup, thin, ss.adapt, ss.alg) sample(mf::T, num_samples::Int, num_warmup::Int, save_warmup::Bool, thin::Int, adapt::Stan.Adapt, alg::Stan.Hmc) where {T<:Function} = begin if alg.stepsize_jitter != 0 error("[Turing.sample] Turing does not support adding noise to stepsize yet.") end if adapt.engaged == false if isa(alg.engine, Stan.Static) # hmc stepnum = Int(round(alg.engine.int_time / alg.stepsize)) sample(mf, HMC(num_samples, alg.stepsize, stepnum); adapt_conf=adapt) elseif isa(alg.engine, Stan.Nuts) # error error("[Turing.sample] Stan.Nuts cannot be used with adapt.engaged set as false") end else if isa(alg.engine, Stan.Static) # hmcda sample(mf, HMCDA(num_samples, num_warmup, adapt.delta, alg.engine.int_time); adapt_conf=adapt) elseif isa(alg.engine, Stan.Nuts) # nuts if alg.metric == Stan.dense_e sample(mf, NUTS(num_samples, num_warmup, adapt.delta); adapt_conf=adapt) else error("[Turing.sample] Turing does not support full covariance matrix for pre-conditioning yet.") end end end end
#Machinery to convert calls to random variables to scalls, e.g. #normal(a,3) = scall(Normal, (), nocond, a, 3). #scall has no optional args, so we can exploit type information properly. as = map(i -> symbol(string("a", i)), 1:10) #typed_as = map(a -> :($a::Union(Number, Array)), as) macro entry(Dist, i) dist = symbol(string(lowercase(string(Dist)))) esc(quote @sf function $dist($(as[1:i]...); dims::(Int...)=(), condition=nocond, whitened=default_whitened(condition, $Dist), sampler=default_sampler(condition, $Dist)) scall($Dist, dims, condition, whitened, sampler, $(as[1:i]...)) end $(Expr(:export, symbol(lowercase(string(Dist))))) end) end @entry(Normal, 2) @entry(MvNormal, 2) @entry(Chisq, 1) @entry(Exponential, 1) @entry(Bernoulli, 1) @entry(Cauchy, 2) @entry(Laplace, 2) import Base.gamma @entry(Gamma, 2) @entry(Beta, 2) @entry(Dirichlet, 1) @entry(Categorical, 1) default_whitened(::NoCond, _) = whitened default_whitened(_, ::Type) = unwhitened default_whitened(::NoCond, ::Type{Bernoulli}) = unwhitened default_whitened(::NoCond, ::Type{Categorical}) = unwhitened default_sampler(::NoCond, _) = langevinprior default_sampler(_, ::Type) = conditioned default_sampler(::NoCond, ::Type{Bernoulli}) = gibbs default_sampler(::NoCond, ::Type{Categorical}) = gibbs const VectorParams = Union(MvNormal, Dirichlet, Categorical) const RealParams = Union(Normal, LogNormal, Chisq, Exponential, Bernoulli, Cauchy, Laplace, Gamma, Beta) const AN = Union(Array, Number) #Conditioning functions. scall(state::State, D, dims::(Int...), x::Union(Number, Array), ::UnWhitened, ::Conditioned, params...) = begin state.counter[end] += 1 if isend(state, state.counter[end]) push!(state, Sample(unwhitened, conditioned, x, logpdf(D, x, params...))) else state[state.counter[end]] = Sample(unwhitened, conditioned, x, logpdf(D, x, params...)) end x end #Sampling functions #Transform N(0, 1), (parameter independent) @sf lognormal(μ, σ; condition=nocond, dims=()::(Int...)) = lognormal(μ, σ, dims, condition) @sf lognormal(μ, σ, dims::(Int...), cond::NoCond) = exp(normal(μ, σ; dims=dims)) @sf lognormal(μ, σ, dims::(Int...), cond) = exp(normal(μ, σ; condition=log(cond), dims=dims)) #Transform N(0, 1), (parameter dependent) macro direct_sampler(Dist, expr) name = Dist.args[1] params = Dist.args[2:end] esc(quote @sf scall(::Type{$name}, dims, ::NoCond, ::Whitened, sampler::Sampler, $(params...)) = $expr end) end @direct_sampler(Normal(μ, σ), μ .+ σ.*white_rand(maxsize(dims, μ, σ), sampler)) @direct_sampler(MvNormal(μ, Σ), μ + sqrtm(Σ)*white_rand((length(μ),), sampler)) @direct_sampler(Chisq(k::Int), squeeze(sum(white_rand(tuple(k,dims...), sampler.value).^2, 1), 1)) #Only works for multiple samples, not multiple #Transform cdf normal_cdf(z) = 0.5*erfc(-z/√2) @sf scall(D, dims, ::NoCond, ::Whitened, sampler::Sampler, params...) = quantile(D, normal_cdf(white_rand(maxsize(D, dims, params...), sampler)), params...) #Non-differentiable fallback using Distributions.jl import Distributions.quantile quantile{D <: UnivariateDistribution}(d::Type{D}, p, params...) = begin quantile_(d, p, params...) end quantile_{D <: RealParams}(d::Type{D}, p, params::Number...) = quantile(d(params...), p) import Base.broadcast broadcast(d::DataType, argss...) = broadcast!((args...) -> d(args...), Array(d, maxsize(argss...)), argss...) quantile_{D <: RealParams}(d::Type{D}, p, params...) = begin #Check for subtle bug where not enough gaussian random variables are drawn. @assert size(p) == maxsize(params...) broadcast(quantile, broadcast(d, params...), p) end quantile_{D <: VectorParams}(d::Type{D}, p, params...) = quantile(d(params...), p) #Differentiable definitions. quantile(::Type{Exponential}, p, scale) = -scale.*log1p(-p) quantile(::Type{Bernoulli}, p, p0) = p.<p0 quantile(::Type{Cauchy}, p, location, scale) = location .- scale.*cospi(p)./sinpi(p) #laplace_quantile(p::Real, location::Real, scale::Real) = # p < 0.5 ? location + scale*log(2.0*p) : location - scale*log(2.0*(1.0-p)) #laplace_quantile(p, location, scale) = broadcast(laplace_quantile, p, location, scale) #@cdf_transform(laplace(location, scale), laplace_quantile(p, location, scale)) # #mapfirst(f::Function, ps, args...) = broadcast(p -> f(p, args...), ps) #categorical_quantile(p::Real, pv::Vector) = begin # i = 1 # v = pv[1] # while v < p && i < length(pv) # i += 1 # @inbounds v += pv[i] # end # i #end #@cdf_transform(categorical(pv), mapfirst(categorical_quantile, p, pv)) # #Directly call Rmath quantile, because fallbacks are super-slow quantile_gamma(p::Real, shape::Real, scale::Real) = begin ccall((:qgamma, "libRmath-julia"), Float64, (Float64, Float64, Float64, Int32, Int32), p, shape, scale, 1, 0) end const delta = 1E-6 import ReverseDiffOverload.diff_con #@d3(quantile_gamma, # if 0.5<x # d*(quantile_gamma(x, y, z) - quantile_gamma(x-delta, y, z))/delta # else # d*(quantile_gamma(x+delta, y, z) - quantile_gamma(x, y, z))/delta # end, # d*(quantile_gamma(x, y+delta, z) - quantile_gamma(x, y, z))/delta, # d*(quantile_gamma(x, y, z+delta) - quantile_gamma(x, y, z))/delta) quantile_gamma(x, y, z) = broadcast(quantile_gamma, x, y, z) dx_quantile_gamma(x::Real, y::Real, z::Real) = if 0.5<x (quantile_gamma(x, y, z) - quantile_gamma(x-delta, y, z))/delta else (quantile_gamma(x+delta, y, z) - quantile_gamma(x, y, z))/delta end dx_quantile_gamma(x, y, z) = broadcast(dx_quantile_gamma, x, y, z) dy_quantile_gamma(x, y, z) = (quantile_gamma(x, y+delta, z) - quantile_gamma(x, y, z))/delta dz_quantile_gamma(x, y, z) = (quantile_gamma(x, y, z+delta) - quantile_gamma(x, y, z))/delta @d3(quantile_gamma, (res = d.*dx_quantile_gamma(x, y, z); isa(x, Real) ? sum(res) : res), (res = d.*dy_quantile_gamma(x, y, z); isa(y, Real) ? sum(res) : res), (res = d.*dz_quantile_gamma(x, y, z); isa(z, Real) ? sum(res) : res)) testdiff(quantile_gamma, 0.4, 5., 6.) testdiff(quantile_gamma, 0.6, 5., 6.) testdiff((x, y, z) -> sum(quantile_gamma(x, y, z)), [0.4, 0.6], 5., 6.) testdiff((x, y, z) -> sum(quantile_gamma(x, y, z)), 0.4, [5., 6], 6.) quantile(::Type{Gamma}, args::Real...) = quantile_gamma(args...) quantile(::Type{Gamma}, args...) = broadcast(quantile_gamma, args...) #Transform gamma @direct_sampler(Beta(alpha, beta), begin X = gamma(alpha, 1; dims=dims) Y = gamma(beta, 1; dims=dims) X./(X+Y) end) @direct_sampler(Dirichlet(alpha::Vector), begin X = gamma(alpha, 1) X/sum(X) end) #MaxDims reports the dimensionality of the largest incoming parameter. #Common cases for speed. maxsize(as::Number...) = () maxsize(a::Array) = size(a) maxsize(r::Number, a::Array) = size(a) maxsize(a::Array, r::Number) = size(a) #General case. maxdims(as::AN...) = max(map(ndims, as)...) maxsize(as::AN...) = map(i -> max(map(a -> size(a, i), as)...), tuple(1:maxdims(as...)...)) #Include dims argument. maxsize(dims::(), as::Number...) = () maxsize(dims::(Int...), as::Number...) = dims maxsize(dims::(), as::AN...) = maxsize(as...) #Deal with distributions with vector arguments. maxsize{D <: RealParams}(d::Type{D}, dims, as...) = maxsize(dims, as...) maxsize{D <: VectorParams}(d::Type{D}, dims, as...) = dims #UnWhitened sample scall(state::State, d, dims::(Int...), condition::NoCond, ::UnWhitened, sampler::Sampler, params...) = begin state.counter[end] += 1 isend_ = isend(state, state.counter[end]) if isend_ || isa(state[state.counter[end]], Resample) dist = d(params...) val = rand(dist, dims...) sample = Sample(unwhitened, sampler, val, sum(logpdf(dist, val))) if isend_ push!(state, sample) else#if isresample state[state.counter[end]] = sample end end #val state[state.counter[end]].value #state.counter += 1 #if (state.endifs_before_resume > 0) || # (state.counter == length(state.trace) + 1) # dist = d(params...) # value = rand(dist, dims...) # insert!(state.trace, state.counter, # Sample(unwhitened, sampler, value, sum(logpdf(dist, value)))) #elseif (state.trace[state.counter] == resample) # dist = d(params...) # value = rand(dist, dims...) # state.trace[state.counter] = Sample(unwhitened, sampler, value, sum(logpdf(dist, value))) #end #state.trace[state.counter].logpdf = sum(logpdf(d(params...), state.trace[state.counter].value)) #@assert size(state.trace[state.counter].value) == dims #state.trace[state.counter].value end
module OrthPolys using SparseArrays using LinearAlgebra: dot import ACE import ACE: evaluate!, evaluate_d!, fltype, read_dict, write_dict, alloc_B, alloc_dB, transform, transform_d, inv_transform, ACEBasis, ScalarACEBasis using ACE.Transforms: DistanceTransform import Base: == export transformed_jacobi # this is a hack to prevent a weird compiler error that I don't understand # at all yet ___f___(D::Dict) = (@show D) function _fcut_(pl, tl, pr, tr, t) if (pl > 0 && t < tl) || (pr > 0 && t > tr) return zero(t) end return (t - tl)^pl * (t - tr)^pr end function _fcut_d_(pl, tl, pr, tr, t) if (pl > 0 && t < tl) || (pr > 0 && t > tr) return zero(t) end df = 0.0 if pl > 0; df += pl * (t - tl)^(pl-1) * (t-tr )^pr ; end if pr > 0; df += pr * (t - tr)^(pr -1) * (t-tl)^pl; end return df end @doc raw""" `OrthPolyBasis:` defined a basis of orthonormal polynomials in terms of the recursion coefficients. What is slightly unusual is that the polynomials have an "envelope". This results in the recursion ```math \begin{aligned} J_1(x) &= A_1 (x - x_l)^{p_l} (x - x_r)^{p_r} \\ J_2 &= (A_2 x + B_2) J_1(x) \\ J_{n} &= (A_n x + B_n) J_{n-1}(x) + C_n J_{n-2}(x) \end{aligned} ``` Orthogonality is achieved with respect to a user-specified distribution, which can be either continuous or discrete. TODO: say more on the distribution! """ struct OrthPolyBasis{T} <: ScalarACEBasis # ----------------- the parameters for the cutoff function pl::Int # cutoff power left tl::T # cutoff left (transformed variable) pr::Int # cutoff power right tr::T # cutoff right (transformed variable) # ----------------- the recursion coefficients A::Vector{T} B::Vector{T} C::Vector{T} # ----------------- used only for construction ... # but useful to have since it defines the notion of orth. tdf::Vector{T} ww::Vector{T} end fltype(P::OrthPolyBasis{T}) where {T} = T Base.length(P::OrthPolyBasis) = length(P.A) ==(J1::OrthPolyBasis, J2::OrthPolyBasis) = all( getfield(J1, sym) == getfield(J2, sym) for sym in (:pr, :tr, :pl, :tl, :A, :B, :C) ) write_dict(J::OrthPolyBasis{T}) where {T} = Dict( "__id__" => "ACE_OrthPolyBasis", "T" => write_dict(T), "pr" => J.pr, "tr" => J.tr, "pl" => J.pl, "tl" => J.tl, "A" => J.A, "B" => J.B, "C" => J.C ) OrthPolyBasis(D::Dict, T=read_dict(D["T"])) = OrthPolyBasis( D["pl"], D["tl"], D["pr"], D["tr"], Vector{T}(D["A"]), Vector{T}(D["B"]), Vector{T}(D["C"]), T[], T[] ) read_dict(::Val{:ACE_OrthPolyBasis}, D::Dict) = OrthPolyBasis(D) # rand applied to a J will return a random transformed distance drawn from # the measure w.r.t. which the polynomials were constructed. # TODO: allow non-constant weights! function ACE.rand_radial(J::OrthPolyBasis) @assert maximum(abs, diff(J.ww)) == 0 return rand(J.tdf) end function OrthPolyBasis(N::Integer, pcut::Integer, tcut::T, pin::Integer, tin::T, tdf::AbstractVector{T}, ww::AbstractVector{T} = ones(T, length(tdf)) ) where {T <: AbstractFloat} @assert pcut >= 0 && pin >= 0 @assert N > 2 if tcut < tin tl, tr = tcut, tin pl, pr = pcut, pin else tl, tr = tin, tcut pl, pr = pin, pcut end if minimum(tdf) < tl || maximum(tdf) > tr @warn("OrthoPolyBasis: t range outside [tl, tr]") end A = zeros(T, N) B = zeros(T, N) C = zeros(T, N) # normalise the weights s.t. <1, 1> = 1 ww = ww ./ sum(ww) # define inner products dotw = (f1, f2) -> dot(f1, ww .* f2) # start the iteration _J1 = _fcut_.(pl, tl, pr, tr, tdf) a = sqrt( dotw(_J1, _J1) ) A[1] = 1/a J1 = A[1] * _J1 # a J2 = (t - b) J1 b = dotw(tdf .* J1, J1) _J2 = (tdf .- b) .* J1 a = sqrt( dotw(_J2, _J2) ) A[2] = 1/a B[2] = -b / a J2 = (A[2] * tdf .+ B[2]) .* J1 # keep the last two for the 3-term recursion Jprev = J2 Jpprev = J1 for n = 3:N # a Jn = (t - b) J_{n-1} - c J_{n-2} b = dotw(tdf .* Jprev, Jprev) c = dotw(tdf .* Jprev, Jpprev) _J = (tdf .- b) .* Jprev -c * Jpprev a = sqrt( dotw(_J, _J) ) A[n] = 1/a B[n] = - b / a C[n] = - c / a Jprev, Jpprev = _J / a, Jprev end return OrthPolyBasis(pl, tl, pr, tr, A, B, C, collect(tdf), collect(ww)) end alloc_B( J::OrthPolyBasis{T}) where {T} = zeros(T, length(J)) alloc_dB(J::OrthPolyBasis{T}) where {T} = zeros(T, length(J)) # alloc_B( J::OrthPolyBasis{T}, ::Integer) where {T} = zeros(T, length(J)) # alloc_dB(J::OrthPolyBasis{T}, ::Integer) where {T} = zeros(T, length(J)) # # TODO: revisit this to allow type genericity!!! # alloc_B( J::OrthPolyBasis, # ::Union{SVector{3, TX}, AbstractVector{SVector{3, TX}}}) where {TX} = # zeros(TX, length(J)) # alloc_dB( J::OrthPolyBasis, # ::Union{SVector{3, TX}, AbstractVector{SVector{3, TX}}}) where {TX} = # zeros(TX, length(J)) # TODO -> should do a type promotion here??? alloc_B( J::OrthPolyBasis, ::TX) where {TX <: Number} = zeros(TX, length(J)) alloc_dB(J::OrthPolyBasis, ::TX) where {TX <: Number} = zeros(TX, length(J)) evaluate_P1(J::OrthPolyBasis, t) = J.A[1] * _fcut_(J.pl, J.tl, J.pr, J.tr, t) function evaluate!(P, tmp, J::OrthPolyBasis, t; maxn=length(J)) @assert length(P) >= maxn P[1] = evaluate_P1(J, t) if maxn == 1; return P; end P[2] = (J.A[2] * t + J.B[2]) * P[1] if maxn == 2; return P; end @inbounds for n = 3:maxn P[n] = (J.A[n] * t + J.B[n]) * P[n-1] + J.C[n] * P[n-2] end return P end function evaluate_d!(dP, tmp, J::OrthPolyBasis, t; maxn=length(J)) @assert maxn <= length(dP) P1 = J.A[1] * _fcut_(J.pl, J.tl, J.pr, J.tr, t) dP[1] = J.A[1] * _fcut_d_(J.pl, J.tl, J.pr, J.tr, t) if maxn == 1; return dP; end α = J.A[2] * t + J.B[2] P2 = α * P1 dP[2] = α * dP[1] + J.A[2] * P1 if maxn == 2; return dP; end @inbounds for n = 3:maxn α = J.A[n] * t + J.B[n] P3 = α * P2 + J.C[n] * P1 P2, P1 = P3, P2 dP[n] = α * dP[n-1] + J.C[n] * dP[n-2] + J.A[n] * P1 end return dP end function evaluate_ed!(P, dP, tmp, J::OrthPolyBasis, t; maxn=length(J)) @assert maxn <= min(length(P), length(dP)) P[1] = J.A[1] * _fcut_(J.pl, J.tl, J.pr, J.tr, t) dP[1] = J.A[1] * _fcut_d_(J.pl, J.tl, J.pr, J.tr, t) if maxn == 1; return dP; end α = J.A[2] * t + J.B[2] P[2] = α * P[1] dP[2] = α * dP[1] + J.A[2] * P[1] if maxn == 2; return dP; end @inbounds for n = 3:maxn α = J.A[n] * t + J.B[n] P[n] = α * P[n-1] + J.C[n] * P[n-2] dP[n] = α * dP[n-1] + J.C[n] * dP[n-2] + J.A[n] * P[n-1] end return dP end """ `discrete_jacobi(N; pcut=0, tcut=1.0, pin=0, tin=-1.0, Nquad = 1000)` A utility function to generate a jacobi-type basis """ function discrete_jacobi(N; pcut=0, tcut=1.0, pin=0, tin=-1.0, Nquad = 1000) tl, tr = minmax(tin, tcut) dt = (tr - tl) / Nquad tdf = range(tl + dt/2, tr - dt/2, length=Nquad) return OrthPolyBasis(N, pcut, tcut, pin, tin, tdf) end # ---------------------------------------------------------------- # Transformed Polynomials Basis # ---------------------------------------------------------------- struct TransformedPolys{T, TT, TJ} <: ScalarACEBasis J::TJ # the actual basis trans::TT # coordinate transform rl::T # lower bound r ru::T # upper bound r = rcut end ==(J1::TransformedPolys, J2::TransformedPolys) = ( (J1.J == J2.J) && (J1.trans == J2.trans) && (J1.rl == J2.rl) && (J1.ru == J2.ru) ) TransformedPolys(J, trans, rl, ru) = TransformedPolys(J, trans, rl, ru) write_dict(J::TransformedPolys) = Dict( "__id__" => "ACE_TransformedPolys", "J" => write_dict(J.J), "rl" => J.rl, "ru" => J.ru, "trans" => write_dict(J.trans) ) TransformedPolys(D::Dict) = TransformedPolys( read_dict(D["J"]), read_dict(D["trans"]), D["rl"], D["ru"] ) read_dict(::Val{:SHIPs_TransformedPolys}, D::Dict) = read_dict(Val{:ACE_TransformedPolys}(), D) read_dict(::Val{:ACE_TransformedPolys}, D::Dict) = TransformedPolys(D) Base.length(J::TransformedPolys) = length(J.J) fltype(P::TransformedPolys{T}) where {T} = T function ACE.rand_radial(J::TransformedPolys) t = ACE.rand_radial(J.J) return inv_transform(J.trans, t) end cutoff(J::TransformedPolys) = J.ru alloc_B( J::TransformedPolys, args...) = alloc_B(J.J, args...) alloc_dB(J::TransformedPolys) = alloc_dB(J.J) alloc_dB(J::TransformedPolys, N::Integer) = alloc_dB(J.J) function evaluate!(P, tmp, J::TransformedPolys, r; maxn=length(J)) # transform coordinates t = transform(J.trans, r) # evaluate the actual polynomials evaluate!(P, nothing, J.J, t; maxn=maxn) return P end function evaluate_d!(dP, tmp, J::TransformedPolys, r; maxn=length(J)) # transform coordinates t = transform(J.trans, r) dt = transform_d(J.trans, r) # evaluate the actual Jacobi polynomials + derivatives w.r.t. x evaluate_d!(dP, nothing, J.J, t, maxn=maxn) @. dP *= dt return dP end function evaluate_ed!(P, dP, tmp, J::TransformedPolys, r; maxn=length(J)) # transform coordinates t = transform(J.trans, r) dt = transform_d(J.trans, r) # evaluate the actual Jacobi polynomials + derivatives w.r.t. x evaluate_d!(P, dP, nothing, J.J, t, maxn=maxn) @. dP *= dt return dP end """ `transformed_jacobi(maxdeg, trans, rcut, rin = 0.0; kwargs...)` : construct a `TransformPolys` basis with an inner polynomial basis of `OrthPolys` type. * `maxdeg` : maximum degree * `trans` : distance transform; normally `PolyTransform(...)` * `rin, rcut` : inner and outer cutoff **Keyword arguments:** * `pcut = 2` : cutoff parameter * `pin = 0` : inner cutoff parameter * `Nquad = 1000` : number of quadrature points """ function transformed_jacobi(maxdeg::Integer, trans::DistanceTransform, rcut::Real, rin::Real = 0.0; kwargs...) J = discrete_jacobi(maxdeg; tcut = transform(trans, rcut), tin = transform(trans, rin), pcut = 2, kwargs...) return TransformedPolys(J, trans, rin, rcut) end # ------------- MORE FUNCTIONALITY ------------- # include("products.jl"); end
@enum Frame IncidentFrame TargetFrame @enum Orientation FixedOrientation RandomOrientation """ A spherical particle. $(FIELDS) """ Base.@kwdef struct Sphere "Radius of the sphere." r::Float64 "x coordinate of the sphere." x::Float64 "y coordinate of the sphere." y::Float64 "z coordinate of the sphere." z::Float64 "Complex refractive index of the sphere. Default is `1.0`." m::ComplexF64 = 1.0 "Complex chiral factor of the sphere. Default is `0.0`." β::ComplexF64 = 0.0 "The T matrix file specifying the scattering properties of the sphere. Default is `\"\"` (empty)." t_matrix::String = "" end """ A horizontally infinite medium layer with certain thickness. $(FIELDS) """ Base.@kwdef struct Layer "Thickness of the layer. Default is `0.0`." d::Float64 = 0.0 "Complex refractive index of the layer. Default is `1.0`." m::ComplexF64 = 1.0 "Complex chiral factor of the layer. Default is `0.0`." β::ComplexF64 = 0.0 end """ Configuration for an STMM run. $(FIELDS) """ Base.@kwdef struct STMMConfig "The folder for storing intermediate results. Default is `\"\"`, which means a temporary folder will be created inside the current directory and be used as the working directory." working_directory::String = "" "The number of processes to be initiated. Default is `1`." number_processors::Int = 1 "Name of the output file. Default is `\"mstm.out\"`." output_file::String = "mstm.out" "Name of the file for storing run information. Default is `\"mstm.run\"`." run_print_file::String = "mstm.run" "[**MSTM v3**] Rotate the target about the target coordinate frame using a z-y-z specified Euler angle. Default is `(0.0, 0.0, 0.0)`." target_euler_angles_deg::NTuple{3,Float64} = (0.0, 0.0, 0.0) """ [**MSTM v3**, **MSTM v4**] Convergence criterion for determining the truncation order for the wave function expansions for each sphere. Default is `1e-6`. > Can also be set as a negative integer `-L` to force all sphere expansions to be truncated at `L`-th order. """ mie_epsilon::Float64 = 1e-6 "[**MSTM v3**, **MSTM v4**] Convergence criterion for estimating the maximum order of the T matrix for the cluster. Default is `1e-6`." translation_epsilon::Float64 = 1e-6 "[**MSTM v3**, **MSTM v4**] Error criterion for the biconjugate gradient iterative solver. Default is `1e-8`." solution_epsilon::Float64 = 1e-8 "[**MSTM v4**] The maximum truncation degree of the T matrix. This is needed to mostly to keep the code from crashing due to memory allocation limits. Default is `120`." max_t_matrix_order::Int = 120 """ [**MSTM v3**] Convergence criterion for T matrix solution. Default is `1e-7`. > MSTM v4 should also support this option, but it is not yet implemented. """ t_matrix_epsilon::Float64 = 1e-7 "[**MSTM v3**, **MSTM v4**] The maximum number of iterations attempted to reach a solution. Default is `5000`." max_iterations::Int64 = 5000 """ [**MSTM v3**, **MSTM v4**] `= false`, the near field translation matrices are calculated during iteration and not stored in memory; `= true`, near field matrices are calculated prior to the solution and stored in memory. Storing the matrices in memory results in some improvement in execution time, yet the amount of memory used vs. the resources available is not checked. Use this option at your own peril. Default is `false`. """ store_translation_matrix::Bool = false """ [**MSTM v3**] The number of processors to be used on parallel platform runs to calculate the expansion coefficients for the random orientation scattering matrix. The actual number of processors used during this step will be the minimum of the total number of processors for the run (the MPI size) and sm_number_processors. Default is `1`. """ sm_number_processors::Int64 = 1 """ [**MSTM v3**] The threshold for the translation from near-field calculation to far-field calculation. - A value larger than the maximum sphere-to-sphere ``kr`` (i.e., a sufficiently large number, say 1e6) causes all spheres to belong to the near field set. - A value smaller than the minimum sphere-to-sphere ``kr`` (i.e., zero) causes all spheres to belong to the far field set. - A negative value enables the automatic criterion: ```math kr_{i-j}\\le\\left[\\frac{1}{2}(L_i+L_j)^2\\right] ``` Default is `1e6`, which means all spheres are considered to be within each other's near field. """ near_field_translation_distance::Float64 = 1e6 """ [**MSTM v3**] The maximum number of BCGM iterations for a given correction stage. Default is `20`. Only works when there are some sphere pairs belonging to the far field set. """ iterations_per_correction::Int64 = 20 "[**MSTM v3**] The minimum scattering polar angle. Default is `0.0`." θ_min::Float64 = 0.0 "[**MSTM v3**] The maximum scattering polar angle. Default is `0.0`." θ_max::Float64 = 180.0 "[**MSTM v3**] The minimum scattering azimuthal angle. Default is `0.0`." ϕ_min::Float64 = 0.0 "[**MSTM v3**] The maximum scattering azimuthal angle. Default is `0.0`." ϕ_max::Float64 = 0.0 "[**MSTM v3**, **MSTM v4**] The interval of θ for scattering matrix calculation. Default is `1.0`." Δθ::Float64 = 1.0 """ [**MSTM v3**, **MSTM v4**] This selects the reference coordinate frame upon which the scattering angles are based. - `IncidentFrame`, the frame is based on the incident field so that `θ = 0` is the forward scattering direction (i.e., the direction of incident field propagation) and `θ = β, φ = 180` is the target z axis direction. - `TargetFrame`, the frame is based on the target frame so that `θ = 0`` corresponds to the target z axis and `θ = β, φ = α`` is the incident field direction .false. Random orientation calculations force this option. """ frame::Frame = TargetFrame "[**MSTM v3**, **MSTM v4**] Whether or not to normalize the scattering matrix. Default is `true`." normalize_scattering_matrix::Bool = true "[**MSTM v3**, **MSTM v4**] Whether or not to take azimuthal average for fixed orientation calculations. Default is `false`." azimuthal_average::Bool = false """ [**MSTM v3**, **MSTM v4**] Dimensionless inverse width CB, at the focal point, of an incident Gaussian profile beam. Setting to `0`` selects plane wave incidence. The localized approximation used to represent the Gaussian beam is accurate for CB ≤ 0.2. Default is `0.0` (plane wave). """ gaussian_beam_constant::Float64 = 0.0 """ [**MSTM v3**, **MSTM v4**] x, y, and z coordinates of the focal point of the Gaussian beam, relative to the origin defined by `spheres`. Default is `(0.0, 0.0, 0.0)`. """ gaussian_beam_focal_point::NTuple{3,Float64} = (0.0, 0.0, 0.0) """ [**MSTM v3**, **MSTM v4**] - Use `FixedOrientation` for a fixed orientation calculation. - Use `RandomOrientation` for a random orientation calculation. Default is `FixedOrientation`. """ orientation::Orientation = FixedOrientation "[**MSTM v4**] Use Monte Carlo integration instead of analytical average. Default is `false`." use_monte_carlo_integration::Bool = false "[**MSTM v4**] Number of directions used for Monte Carlo integration. Works only when `use_monte_carlo_integration = true`. Default is `100`." number_incident_directions::Int = 100 "The azimuthal angle (in degrees) of the incident wave. Default is `0.0`." α::Float64 = 0.0 "The polar angle (in degrees) of the incident wave. Default is `0.0`." β::Float64 = 0.0 "[**MSTM v4**] Whether or not to calculate the scattering matrix. Default is `true`." calculate_scattering_matrix::Bool = true """ [**MSTM v3**] Whether or not to calculate the scattering oefficients. Default is `true`. When `= false`, the scattering coefficients will be read from the file specified by `scattering_coefficient_file`. """ calculate_scattering_coefficients::Bool = true """ [**MSTM v3**] File name for the scattering coefficient file. Default is `\"mstm.sca\"`. - When `calculate_scattering_coefficients = false`, the scattering coefficients will be read from this file. - When `calculate_scattering_coefficients = true`, the scattering coefficients will be written to this file. """ scattering_coefficient_file::String = "mstm.scat" "[**MSTM v4**] Whether or not to use the FFT-based accelerated algorithm. Default is `false`." use_fft_translation::Bool = false """ [**MSTM v4**] This determines the grid size ``d`` of the cubic lattice used in the algorithm. The formula is: ```math d=\\left(\\frac{V_S}{cN_{s,ext}}\\right)^{1/3} ``` where ``V_S`` is the dimensionless total volume of the external spheres and ``c`` is `cell_volume_fraction`. The optimum value is usually where the total number of nodes is close to the total number of external spheres NS,ext. Setting `cell_volume_fraction = 0` will automate the setting of d using an estimate of the sphere volume fraction. Default is `0.0`. Works only when `use_fft_translation = true`. """ cell_volume_fraction::Float64 = 0.0 """ [**MSTM v4**] Truncation degree for the node–based expansions of the scattered field. Set `node_order = −L`, where `L` is a positive integer, will set the node order to `ceil(d) + L`. Default is `-1`. Works only when `use_fft_translation = true`. """ node_order::Int = -1 """ [**MSTM v4**] `= 0` will have the scattering matrix printed at a range of polar angles (θ), with angular increment given in degrees by `Δθ`. The scattering plane coincides with the incident azimuth plane. The limits on θ depend on the number of plane boundaries NB. scattering_map_model= 1 will print the scattering matrix in a pair (cosθ > 0, < 0) of 2D arrays, with coordinates `kx = sinθcosφ`, `ky = sinθsinφ`. The number of points on each axis is given by `scattering_map_dimension`. Default is `0`, and random orientation calculations force `0`. """ scattering_map_model::Int = 0 """ [**MSTM v4**] The number of points on each axis. Default is `15`. Works only when `scattering_map_model = 1`. """ scattering_map_dimension::Int = 15 "[**MSTM v3**] Whether or not to print each iteration's error in the run print file. Default is `true`." track_iterations::Bool = true "[**MSTM v3**, **MSTM v4**] Whether or not to calculate the near field. Default is `false`." calculate_near_field::Bool = false "[**MSTM v3**] Coordinate of the near field plane. `1` = y-z, `2` = z-x, `3` = x-y. Default is `1`." near_field_plane_coord::Int64 = 1 """ [**MSTM v3**] Position of the near field plane. - When `near_field_plane_coord = 1`, this is the x-coordinate. - When `near_field_plane_coord = 2`, this is the y-coordinate. - When `near_field_plane_coord = 3`, this is the z-coordinate. Default is `0.0`. """ near_field_plane_position::Float64 = 0.0 """ [**MSTM v3**] Rectangle region of the near field plane. - When passing `(ΔX, ΔY)`, the actual region would be `(X_min-ΔX, X_max+ΔX) x (Y_min-ΔY, Y_max+ΔY)`, where `X_min`, `X_max`,`Y_min` and `Y_max` are automatically calculated. - When passing `(X_min, Y_min, X_max, Y_max)`, the region would be used as it is. Default is `(0.0, 0.0)`. """ near_field_plane_vertices::Union{NTuple{2,Float64},NTuple{4,Float64}} = (0.0, 0.0) "[**MSTM v4**] The minimum x coordinate of the near field calculation region. Default is `0.0`." near_field_x_min::Float64 = 0.0 "[**MSTM v4**] The maximum x coordinate of the near field calculation region. Default is `0.0`." near_field_x_max::Float64 = 0.0 "[**MSTM v4**] The minimum y coordinate of the near field calculation region. Default is `0.0`." near_field_y_min::Float64 = 0.0 "[**MSTM v4**] The maximum y coordinate of the near field calculation region. Default is `0.0`." near_field_y_max::Float64 = 0.0 "[**MSTM v4**] The minimum z coordinate of the near field calculation region. Default is `0.0`." near_field_z_min::Float64 = 0.0 "[**MSTM v4**] The maximum z coordinate of the near field calculation region. Default is `0.0`." near_field_z_max::Float64 = 0.0 "[**MSTM v3**, **MSTM v4**] The spacial step size of the grid points. Default is `0.1`." near_field_step_size::Float64 = 0.1 """ [**MSTM v4**] Controls where the incident field appears in the calculation results; `= 1` is the standard model, where the external field is = scattered + incident and the field inside the spheres is calculated from the internal field expansions; `≠ 1` has the external field due solely to the scattered field, and the field inside the particles is now internal-incident. Default is `1`. """ near_field_calculation_model::Int = 1 """ [**MSTM v3**] A specific polarization state of the incident field is needed to calculate the near field. The field is taken to be linearly polarized, with a polarization angle of `γ` relative to the k–z plane. When `β = 0`, `γ` becomes the azimuth angle of the incident electric field vector relative to the cluster coordinate system. Default is `0.0`. """ polarization_angle_deg::Float64 = 0.0 """ [**MSTM v4**] Whether or not to enable an accelerated algorithm for calculation of field value. Default is `true`. """ store_surface_vector::Bool = true """ [**MSTM v4**] Size of the grid used for re–expansion of fields resulting from plane boundary and periodic lattice interactions. Default is `5.0`. Experiment with this if your calculations are taking too long. Only works when `store_surface_vector = true`. """ near_field_expansion_spacing::Float64 = 5.0 """ [**MSTM v4**] Expansion truncation order used for the grid re–expansion of the secondary field, per the above option. Should scale with near_field_expansion_spacing following a Mie–type criteria. The bigger the value, the more accurate the results, but the slower the calculations and the greater the memory demands. Default is `10`. Only works when `store_surface_vector = true`. """ near_field_expansion_order::Int = 10 "File name for the near field output. Default is `\"mstm.nf\"`." near_field_output_file::String = "mstm.nf" """ [**MSTM v3**] The incident field component for the near field calculations -- for either the plane wave or Gaussian beam models –- is calculated using a single, regular VSWF expansion centered about the beam focal point. The plane wave epsilon is a convergence criterion for this expansion. Default is `1e-4`. """ plane_wave_epsilon::Float64 = 1e-4 """ [**MSTM v3**] Option to calculate the T matrix or use an exisiting T matrix file. Default is `true`, which calculates the T matrix. """ calculate_t_matrix::Bool = true """ [**MSTM v3**] - When `calculate_t_matrix = true`, this is the file name for the T matrix output. - When `calculate_t_matrix = false`, this is the file name for reading the T matrix from. Default is `\"mstm.tm\"`. """ t_matrix_file::String = "mstm.tm" """ [**MSTM v3**, **MSTM v4**] Medium layers. - For **MSTM v3**, only the refractive index and chiral factor of the first layer will be used. Thickness is ignored. - For **MSTM v4**, the first layer locates at `z=0` and extends to `-∞`. The last layer extends to `+∞`. The thickness of the first and the last layer is ignored. """ layers::Vector{Layer} = [Layer()] "[**MSTM v3**, **MSTM v4**] Spheres." spheres::Vector{Sphere} = Sphere[] "[**MSTM v4**] When `periodic = true`, the spheres will be considered to construct a periodic lattice in the x-y plane. Note that periodic lattice is incompatible with random orientation." periodic::Bool = false "[**MSTM v4**] When `periodic = true`, this option sets the size of the periodic lattice. The cell size will be automatically enlarged if it cannot contain all the spheres." cell_size::Tuple{Float64,Float64} = (0.0, 0.0) end """ Helper function for building a configuration on basis of an existing configuration. $(SIGNATURES) """ function STMMConfig(original::STMMConfig; kwargs...) dict = Dict(key => getfield(original, key) for key in propertynames(original)) for (key, value) in kwargs dict[key] = value end return STMMConfig(; dict...) end export Orientation, FixedOrientation, RandomOrientation export Frame, IncidentFrame, TargetFrame export Sphere, Layer, STMMConfig
columnbuttons = Observable{Any}(dom"div"()) plt = Observable{Any}() function makebuttons(ph) prop = propertynames(ph)[5:end-3] #Removes name,x,y,z and ux,uy,uz propnm = [s for s=string.(prop)] buttons = button.(propnm) for (btn, key) in zip(reverse(buttons), reverse(prop)) map!(t -> begin @manipulate for t0_ms = range(0,dur(seq),5)*1e3 plot_phantom_map(ph, key; t0=t0_ms, darkmode) end end , plt, btn) end dom"div"(hbox(buttons)) end map!(makebuttons, columnbuttons, pha_obs) ui = dom"div"(vbox(columnbuttons, plt)) content!(w, "div#content", ui)
@testset "Dual numbers" begin f(x,y) = x[1]^2+y[1]^2 g(param) = Optim.minimum(optimize(x->f(x,param), -1,1)) @test ForwardDiff.gradient(g, [1.0]) == [2.0] end
# Direct minimization of the energy using Optim using LineSearches # This is all a bit annoying because our ψ is represented as ψ[k][G,n], and Optim accepts # only dense arrays. We do a bit of back and forth using custom `pack` (ours -> optim's) and # `unpack` (optim's -> ours) functions # Orbitals inside each kblock must be kept orthogonal: the # project_tangent and retract work per kblock struct DMManifold <: Optim.Manifold Nk::Int unpack::Function end function Optim.project_tangent!(m::DMManifold, g, x) g_unpack = m.unpack(g) x_unpack = m.unpack(x) for ik = 1:m.Nk Optim.project_tangent!(Optim.Stiefel(), g_unpack[ik], x_unpack[ik]) end g end function Optim.retract!(m::DMManifold, x) x_unpack = m.unpack(x) for ik = 1:m.Nk Optim.retract!(Optim.Stiefel(), x_unpack[ik]) end x end # Array of preconditioners struct DMPreconditioner Nk::Int Pks::Vector # Pks[ik] is the preconditioner for k-point ik unpack::Function end function LinearAlgebra.ldiv!(p, P::DMPreconditioner, d) p_unpack = P.unpack(p) d_unpack = P.unpack(d) for ik = 1:P.Nk ldiv!(p_unpack[ik], P.Pks[ik], d_unpack[ik]) end p end function LinearAlgebra.dot(x, P::DMPreconditioner, y) x_unpack = P.unpack(x) y_unpack = P.unpack(y) sum(dot(x_unpack[ik], P.Pks[ik], y_unpack[ik]) for ik = 1:P.Nk) end function precondprep!(P::DMPreconditioner, x) x_unpack = P.unpack(x) for ik = 1:P.Nk precondprep!(P.Pks[ik], x_unpack[ik]) end P end """ Computes the ground state by direct minimization. `kwargs...` are passed to `Optim.Options()`. Note that the resulting ψ are not necessarily eigenvectors of the Hamiltonian. """ direct_minimization(basis::PlaneWaveBasis; kwargs...) = direct_minimization(basis, nothing; kwargs...) function direct_minimization(basis::PlaneWaveBasis{T}, ψ0; prec_type=PreconditionerTPA, optim_solver=Optim.LBFGS, tol=1e-6, kwargs...) where T if mpi_nprocs() > 1 # need synchronization in Optim error("Direct minimization with MPI is not supported yet") end model = basis.model @assert model.temperature == 0 # temperature is not yet supported filled_occ = filled_occupation(model) n_spin = model.n_spin_components n_bands = div(model.n_electrons, n_spin * filled_occ, RoundUp) Nk = length(basis.kpoints) if ψ0 === nothing ψ0 = [ortho_qr(randn(Complex{T}, length(G_vectors(basis, kpt)), n_bands)) for kpt in basis.kpoints] end occupation = [filled_occ * ones(T, n_bands) for ik = 1:Nk] # we need to copy the reinterpret array here to not raise errors in Optim.jl # TODO raise this issue in Optim.jl pack(ψ) = copy(reinterpret_real(pack_ψ(ψ))) unpack(x) = unpack_ψ(reinterpret_complex(x), size.(ψ0)) # this will get updated along the iterations H = nothing energies = nothing ρ = nothing # computes energies and gradients function fg!(E, G, ψ) ψ = unpack(ψ) ρ = compute_density(basis, ψ, occupation) energies, H = energy_hamiltonian(basis, ψ, occupation; ρ=ρ) # The energy has terms like occ * <ψ|H|ψ>, so the gradient is 2occ Hψ if G !== nothing G = unpack(G) for ik = 1:Nk mul!(G[ik], H.blocks[ik], ψ[ik]) G[ik] .*= 2*filled_occ end end energies.total end manif = DMManifold(Nk, unpack) Pks = [prec_type(basis, kpt) for kpt in basis.kpoints] P = DMPreconditioner(Nk, Pks, unpack) kwdict = Dict(kwargs) optim_options = Optim.Options(; allow_f_increases=true, show_trace=true, x_tol=pop!(kwdict, :x_tol, tol), f_tol=pop!(kwdict, :f_tol, -1), g_tol=pop!(kwdict, :g_tol, -1), kwdict...) res = Optim.optimize(Optim.only_fg!(fg!), pack(ψ0), optim_solver(P=P, precondprep=precondprep!, manifold=manif, linesearch=LineSearches.BackTracking()), optim_options) # return copy to ensure we have a plain array ψ = deepcopy(unpack(res.minimizer)) # Final Rayleigh-Ritz (not strictly necessary, but sometimes useful) eigenvalues = [] for ik = 1:Nk Hψk = H.blocks[ik] * ψ[ik] F = eigen(Hermitian(ψ[ik]'Hψk)) push!(eigenvalues, F.values) ψ[ik] .= ψ[ik] * F.vectors end εF = nothing # does not necessarily make sense here, as the # Aufbau property might not even be true # We rely on the fact that the last point where fg! was called is the minimizer to # avoid recomputing at ψ (ham=H, basis=basis, energies=energies, converged=true, ρ=ρ, ψ=ψ, eigenvalues=eigenvalues, occupation=occupation, εF=εF, optim_res=res) end
__precompile__() module SpecialFunctions using Compat if VERSION >= v"0.7.0-DEV.1760" depsfile = joinpath(dirname(@__FILE__), "..", "deps", "deps.jl") if isfile(depsfile) include(depsfile) else error("SpecialFunctions is not properly installed. Please run " * "Pkg.build(\"SpecialFunctions\") and restart Julia.") end else using Base.Math: openspecfun end if isdefined(Base, :airyai) && VERSION < v"0.7.0-DEV.986" #22763 import Base: airyai, airyaix, airyaiprime, airyaiprimex, airybi, airybix, airybiprime, airybiprimex, besselh, besselhx, besseli, besselix, besselj, besselj0, besselj1, besseljx, besselk, besselkx, bessely, bessely0, bessely1, besselyx, hankelh1, hankelh1x, hankelh2, hankelh2x, dawson, erf, erfc, erfcinv, erfcx, erfi, erfinv, eta, digamma, invdigamma, polygamma, trigamma, zeta, # deprecated airy, airyx, airyprime else export airyai, airyaiprime, airybi, airybiprime, airyaix, airyaiprimex, airybix, airybiprimex, besselh, besselhx, besseli, besselix, besselj, besselj0, besselj1, besseljx, besselk, besselkx, bessely, bessely0, bessely1, besselyx, dawson, erf, erfc, erfcinv, erfcx, erfi, erfinv, eta, digamma, invdigamma, polygamma, trigamma, hankelh1, hankelh1x, hankelh2, hankelh2x, zeta end export sinint, cosint include("bessel.jl") include("erf.jl") include("sincosint.jl") include("gamma.jl") include("deprecated.jl") end # module
__precompile__() module TMCM3110 export encode_command function encode_command(m_address, n_command, n_type, n_motor, value) m_address = UInt8( m_address % (1<<8) ) n_command = UInt8( n_command % (1<<8) ) n_type = UInt8( n_type % (1<<8) ) n_motor = UInt8( n_motor % (1<<8) ) value = Int32( value ) values = [ parse(UInt8, bits(value)[ 1+(8*(i-1)) : 8+(8*(i-1)) ] , 2) for i in 1:4] checksum = UInt8( (m_address + n_command + n_type + n_motor + sum(values)) % (1<<8) ) tmcl_bytes = [m_address, n_command, n_type, n_motor, values..., checksum] return tmcl_bytes end export decode_reply function decode_reply(reply) r_address = UInt8( reply[1] ) m_address = UInt8( reply[2] ) r_status = UInt8( reply[3] ) Int32(r_status) != 100 ? warn(STATUSCODES[Int(r_status)]) : nothing n_command = UInt8( reply[4] ) values = [ UInt8(value) for value in reply[5:8] ] r_checksum = UInt8( reply[9] ) checksum = UInt8( (r_address + m_address + r_status + n_command + sum(values)) % (1<<8) ) value = parse( UInt32, "$(bits(values[1]))$(bits(values[2]))$(bits(values[3]))$(bits(values[4]))" , 2 ) value = reinterpret(Int32, value) return value end export STATUSCODES STATUSCODES = Dict( 100 => "Succesfully executed, no error", 101 => "Command loaded into TMCL program EEPROM", 1 => "Wrong Checksum", 2 => "Invalid command", 3 => "Wrong type", 4 => "Invalid value", 5 => "Configuration EEPROM locked", 6 => "Command not available" ) export COMMAND_NUMBERS COMMAND_NUMBERS = Dict( 1 => "ROR", 2 => "ROL", 3 => "MST", 4 => "MVP", 5 => "SAP", 6 => "GAP", 7 => "STAP", 8 => "RSAP", 9 => "SGP", 10 => "GGP", 11 => "STGP", 12 => "RSGP", 13 => "RFS", 14 => "SIO", 15 => "GIO", 19 => "CALC", 20 => "COMP", 21 => "JC", 22 => "JA", 23 => "CSUB", 24 => "RSUB", 25 => "EI", 26 => "DI", 27 => "WAIT", 28 => "STOP", 30 => "SCO", 31 => "GCO", 32 => "CCO", 33 => "CALCX", 34 => "AAP", 35 => "AGP", 37 => "VECT", 38 => "RETI", 39 => "ACO" ) export AXIS_PARAMETER AXIS_PARAMETER = Dict( 0 => "target position", 1 => "actual position", 2 => "target speed", 3 => "actual speed", 4 => "max positioning speed", 5 => "max acceleration", 6 => "abs max current", 7 => "standby current", 8 => "target pos reached", 9 => "ref switch status", 10 => "right limit switch status", 11 => "left limit switch status", 12 => "right limit switch disable", 13 => "left limit switch disable", 130 => "minimum speed", 135 => "actual acceleration", 138 => "ramp mode", 140 => "microstep resolution", 141 => "ref switch tolerance", 149 => "soft stop flag", 153 => "ramp divisor", 154 => "pulse divisor", 160 => "step interpolation enable", 161 => "double step enable", 162 => "chopper blank time", 163 => "chopper mode", 164 => "chopper hysteresis dec", 165 => "chopper hysteresis end", 166 => "chopper hysteresis start", 167 => "chopper off time", 168 => "smartEnergy min current", 169 => "smartEnergy current downstep", 170 => "smartEnergy hysteresis", 171 => "smartEnergy current upstep", 172 => "smartEnergy hysteresis start", 173 => "stallGuard2 filter enable", 174 => "stallGuard2 threshold", 175 => "slope control high side", 176 => "slope control low side", 177 => "short protection disable", 178 => "short detection timer", 179 => "Vsense", 180 => "smartEnergy actual current", 181 => "stop on stall", 182 => "smartEnergy threshold speed", 183 => "smartEnergy slow run current", 193 => "ref. search mode", 194 => "ref. search speed", 195 => "ref. switch speed", 196 => "distance end switches", 204 => "freewheeling", 206 => "actual load value", 208 => "TMC262 errorflags", 209 => "encoder pos", 210 => "encoder prescaler", 212 => "encoder max deviation", 214 => "power down delay" ) export INTERRUPT_VECTORS INTERRUPT_VECTORS = Dict( 0 => "Timer 0", 1 => "Timer 1", 2 => "Timer 2", 3 => "Target position 0 reached", 4 => "Target position 1 reached", 5 => "Target position 2 reached", 15 => "stallGuard2 axis 0", 16 => "stallGuard2 axis 1", 17 => "stallGuard2 axis 2", 21 => "Deviation axis 0", 22 => "Deviation axis 1", 23 => "Deviation axis 2", 27 => "Left stop switch 0", 28 => "Right stop switch 0", 29 => "Left stop switch 1", 30 => "Right stop switch 1", 31 => "Left stop switch 2", 32 => "Right stop switch 2", 39 => "Input change 0", 40 => "Input change 1", 41 => "Input change 2", 42 => "Input change 3", 43 => "Input change 4", 44 => "Input change 5", 45 => "Input change 6", 46 => "Input change 7", 255 => "Global interrupts" ) end # module
using BlossomV using Metis using SparseArrays using LightGraphs: add_edge! using SimpleWeightedGraphs using MetaGraphs using ..Utils export learn_vtree ############# # Metis top down method ############# # Add edge weights to Metis.jl using Metis: idx_t, ishermitian struct WeightedGraph nvtxs::idx_t xadj::Vector{idx_t} adjncy::Vector{idx_t} adjwgt::Vector{idx_t} # edge weights WeightedGraph(nvtxs, xadj, adjncy, adjwgt) = new(nvtxs, xadj, adjncy, adjwgt) end function my_graph(G::SparseMatrixCSC; check_hermitian=true) if check_hermitian ishermitian(G) || throw(ArgumentError("matrix must be Hermitian")) end N = size(G, 1) xadj = Vector{idx_t}(undef, N+1) xadj[1] = 1 adjncy = Vector{idx_t}(undef, nnz(G)) adjncy_i = 0 adjwgt = Vector{idx_t}(undef, nnz(G)) @inbounds for j in 1:N n_rows = 0 for k in G.colptr[j] : (G.colptr[j+1] - 1) i = G.rowval[k] if i != j # don't include diagonal elements n_rows += 1 adjncy_i += 1 adjncy[adjncy_i] = i adjwgt[adjncy_i] = G[i, j] end end xadj[j+1] = xadj[j] + n_rows end resize!(adjncy, adjncy_i) resize!(adjwgt, adjncy_i) return WeightedGraph(idx_t(N), xadj, adjncy, adjwgt) end function my_partition(G::WeightedGraph, nparts::Integer) part = Vector{Metis.idx_t}(undef, G.nvtxs) edgecut = fill(idx_t(0), 1) # if alg === :RECURSIVE Metis.METIS_PartGraphRecursive(G.nvtxs, idx_t(1), G.xadj, G.adjncy, C_NULL, C_NULL, G.adjwgt, idx_t(nparts), C_NULL, C_NULL, Metis.options, edgecut, part) # elseif alg === :KWAY # Metis.METIS_PartGraphKway(G.nvtxs, idx_t(1), G.xadj, G.adjncy, C_NULL, C_NULL, G.adjwgt, # idx_t(nparts), C_NULL, C_NULL, Metis.options, edgecut, part) # else # throw(ArgumentError("unknown algorithm $(repr(alg))")) # end return part end my_partition(G, nparts) = my_partition(my_graph(G), nparts) "Metis top down method" function metis_top_down(data::DataFrame;α) δINT = 999999 MIN_INT = 1 MAX_INT = δINT + MIN_INT weight=ones(Float64, num_examples(data)) (_, mi) = mutual_information(data, weight; α=α) vars = Var.(collect(1:num_features(data))) info = to_long_mi(mi, MIN_INT, MAX_INT) function f(leafs::Vector{PlainVtreeLeafNode})::Tuple{Vector{PlainVtreeLeafNode}, Vector{PlainVtreeLeafNode}} var2leaf = Dict([(variable(x),x) for x in leafs]) vertices = sort(variable.(leafs)) sub_context = info[vertices, vertices] len = length(vertices) for i in 1 : len sub_context[i, i] = 0 end g = convert(SparseMatrixCSC, sub_context) partition = my_partition(my_graph(g), 2) subsets = (Vector{PlainVtreeLeafNode}(), Vector{PlainVtreeLeafNode}()) for (index, p) in enumerate(partition) push!(subsets[p], var2leaf[vertices[index]]) end return subsets end return f end ############# # Blossom bottom up method ############# "Blossom bottom up method, vars are not used" function blossom_bottom_up(data::DataFrame;α) weight = ones(Float64, num_examples(data)) (_, mi) = mutual_information(data, weight; α) vars = Var.(collect(1:num_features(data))) info = round.(Int64, 1000001 .+ to_long_mi(mi, -1, -1000000)) function f(leaf::Vector{<:Vtree}) variable_sets = collect.(variables.(leaf)) # even number of nodes, use blossomv alg function blossom_bottom_up_even!(variable_sets)::Tuple{Vector{Tuple{Var, Var}}, Int64} # 1. calculate pMI pMI = set_mutual_information(info, variable_sets) pMI = round.(Int64, pMI) # 2. solve by blossomv alg len = length(variable_sets) m = Matching(len) for i in 1 : len, j in i + 1 : len add_edge(m, i - 1, j - 1, pMI[i, j]) # blossomv index start from 0 end solve(m) all_matches = Set{Tuple{Var, Var}}() for v in 1 : len push!(all_matches, order_asc(v, get_match(m, v - 1) + 1)) end # 3. calculate scores, map index to var all_matches = Vector(collect(all_matches)) score = 0 for i in 1 : length(all_matches) (x, y) = all_matches[i] score += pMI[x, y] end return (all_matches, score) end # odd number of nodes, try every 2 combinations function blossom_bottom_up_odd!(variable_sets) # try all len - 1 conditions, find best score(minimun cost) (best_matches, best_score) = (nothing, typemax(Int64)) len = length(variable_sets) for index in 1 : len indices = [collect(1:index-1);collect(index+1:len)] (matches, score) = blossom_bottom_up_even!(variable_sets[indices]) if score < best_score (best_matches, best_score) = ([[(indices[l], indices[r]) for (l,r) in matches];[index]], score) end end return (best_matches, best_score) end if length(variable_sets) % 2 == 0 (matches, score) = blossom_bottom_up_even!(variable_sets) else (matches, score) = blossom_bottom_up_odd!(variable_sets) end pairs = [] for x in matches if x isa Tuple push!(pairs, (leaf[x[1]], leaf[x[2]])) else push!(pairs, leaf[x]) end end return pairs end return f end function learn_vtree(data::DataFrame; α=0.0, alg=:bottomup) if alg==:topdown PlainVtree(num_features(data), :topdown; f=metis_top_down(data;α)) elseif alg==:bottomup PlainVtree(num_features(data), :bottomup; f=blossom_bottom_up(data;α)) elseif alg==:clt clt = learn_chow_liu_tree(data) learn_vtree_from_clt(clt, vtree_mode="balanced") else error("Vtree learner $(alg) not supported.") end end
# functions for building various standard types of graphs export Complete, Path, Cycle, RandomGraph, RandomRegular export RandomTree, code_to_tree export Grid, Wheel, Cube, BuckyBall export Petersen, Kneser, Paley, Knight """ `Complete(n)` returns a complete graph with `n` vertices `1:n`. `Complete(n,m)` returns a complete bipartite graph with `n` vertices in one part and `m` vertices in the other. `Complete([n1,n2,...,nt])` returns a complete multipartite graph with parts of size `n1`, `n2`, ..., `nt`. """ # Create a complete graph function Complete(n::Int) G = IntGraph(n) for k=1:n-1 for j=k+1:n add!(G,j,k) end end return G end # Create a complete bipartite graph function Complete(n::Int, m::Int) G = IntGraph(n+m) for u=1:n for v=n+1:n+m add!(G,u,v) end end return G end # Create the complete multipartite graph with given part sizes function Complete(parts::Array{Int,1}) # check all part sizes are positive for p in parts if p < 1 error("All part sizes must be positive") end end n = sum(parts) G = IntGraph(n) np = length(parts) if np < 2 return G end # create table of part ranges ranges = Array(Int,np,2) ranges[1,1] = 1 ranges[1,2] = parts[1] for k = 2:np ranges[k,1] = ranges[k-1,2] + 1 ranges[k,2] = ranges[k,1] + parts[k] - 1 end # Add all edges between all parts for i=1:np-1 for j=i+1:np for u=ranges[i,1]:ranges[i,2] for v=ranges[j,1]:ranges[j,2] add!(G,u,v) end end end end return G end # Create a path graph on n vertices """ `Path(n)` creates a path graph with `n` vertices named `1:n`. `Path(array)` creates a path graph with vertices `array[1]`, `array[2]`, etc. """ function Path(n::Int) G = IntGraph(n) for v = 1:n-1 add!(G,v,v+1) end return G end # Create a path graph from a list of vertices function Path{T}(verts::Array{T}) G = SimpleGraph{T}() n = length(verts) if n==1 add!(G,verts[1]) end for k = 1:n-1 add!(G,verts[k],verts[k+1]) end return G end # Create a cycle graph on n vertices function Cycle(n::Int) if n<3 error("Cycle requires 3 or more vertices") end G = Path(n) add!(G,1,n) return G end # Create the wheel graph on n vertices: a cycle on n-1 vertices plus # an additional vertex adjacent to all the vertices on the wheel. """ `Wheel(n)` creates a wheel graph with `n` vertices. That is, a cycle with `n-1` vertices `1:(n-1)` all adjacent to a common single vertex, `n`. """ function Wheel(n::Int) if n < 4 error("Wheel graphs must have at least 4 vertices") end G = Cycle(n-1) for k=1:n-1 add!(G,k,n) end return G end # Create a grid graph """ `Grid(n,m)` creates an `n`-by-`m` grid graph. For other grids, we suggest `Path(n1)*Path(n2)*Path(n3)` optionally wrapped in `relabel`. See also: `Cube`. """ function Grid(n::Int, m::Int) G = SimpleGraph{Tuple{Int,Int}}() # add the vertices for u=1:n for v=1:m add!(G,(u,v)) end end #horizontal edges for u=1:n for v=1:m-1 add!(G,(u,v),(u,v+1)) end end # vertical edges for v=1:m for u=1:n-1 add!(G,(u,v),(u+1,v)) end end return G end # Create an Erdos-Renyi random graph """ `RandomGraph(n,p=0.5)` creates an Erdos-Renyi random graph with `n` vertices and edge probability `p`. """ function RandomGraph(n::Int, p::Real=0.5) G = IntGraph(n) # guess the size of the edge set to preallocate storage m = round(Int,n*n*p)+1 # generate the edges for v=1:n-1 for w=v+1:n if (rand() < p) add!(G,v,w) end end end return G end # Generate a random tree on vertex set 1:n. All n^(n-2) trees are # equally likely. """ `RandomTree(n)` creates a random tree on `n` vertices each with probability `1/n^(n-2)`. """ function RandomTree(n::Int) if n<0 # but we allow n==0 to give empty graph error("Number of vertices cannot be negative") end if n<2 return IntGraph(n) end code = [ mod(rand(Int),n)+1 for _ in 1:n-2 ] return code_to_tree(code) end # This is a helper function for RandomTree that converts a Prufer code # to a tree. No checks are done on the array fed into this function. function code_to_tree(code::Array{Int,1}) n = length(code)+2 G = IntGraph(n) degree = ones(Int,n) # initially all 1s #every time a vertex appears in code[], up its degree by 1 for c in code degree[c]+=1 end for u in code for v in 1:n if degree[v]==1 add!(G,u,v) degree[u] -= 1 degree[v] -= 1 break end end end last = find(degree) add!(G,last[1],last[2]) return G end # Create the Cube graph with 2^n vertices """ `Cube(n)` creates the `n`-dimensional cube graph. This graph has `2^n` vertices named by all possible length-`n` strings of 0s and 1s. Two vertices are adjacent iff they differ in exactly one position. """ function Cube(n::Integer=3) G = StringGraph() for u=0:2^n-1 for shift=0:n-1 v = (1<<shift) $ u add!(G,bin(u,n), bin(v,n)) end end return G end # Create the BuckyBall graph """ `BuckyBall()` returns the Bucky ball graph. """ function BuckyBall() G = IntGraph() edges = [(1,3), (1,49), (1,60), (2,4), (2,10), (2,59), (3,4), (3,37), (4,18), (5,7), (5,9), (5,13), (6,8), (6,10), (6,17), (7,8), (7,21), (8,22), (9,10), (9,57), (11,12), (11,13), (11,21), (12,28), (12,48), (13,14), (14,47), (14,55), (15,16), (15,17), (15,22), (16,26), (16,42), (17,18), (18,41), (19,20), (19,21), (19,27), (20,22), (20,25), (23,24), (23,32), (23,35), (24,26), (24,39), (25,26), (25,31), (27,28), (27,31), (28,30), (29,30), (29,32), (29,36), (30,45), (31,32), (33,35), (33,40), (33,51), (34,36), (34,46), (34,52), (35,36), (37,38), (37,41), (38,40), (38,53), (39,40), (39,42), (41,42), (43,44), (43,47), (43,56), (44,46), (44,54), (45,46), (45,48), (47,48), (49,50), (49,53), (50,54), (50,58), (51,52), (51,53), (52,54), (55,56), (55,57), (56,58), (57,59), (58,60), (59,60), ] for e in edges add!(G,e[1],e[2]) end return G end # The Kneser graph Kneser(n,k) has C(n,k) vertices that are the # k-element subsets of 1:n in which two vertices are adjacent if (as # sets) they are disjoint. The Petersen graph is Kneser(5,2). """ `Kneser(n,m)` creates the Kneser graph whose vertices are all the `m`-element subsets of `1:n` in which two vertices are adjacent iff they are disjoint. """ function Kneser(n::Int,k::Int) A = collect(1:n) vtcs = [Set(v) for v in subsets(A,k)] G = SimpleGraph{Set{Int}}() for v in vtcs add!(G,v) end n = length(vtcs) for i=1:n-1 u = vtcs[i] for j=i+1:n v = vtcs[j] if length(intersect(u,v))==0 add!(G,u,v) end end end return G end # Create the Petersen graph. """ `Petersen()` returns the Petersen graph. The vertices are labeled as the 2-element subsets of `1:5`. Wrap in `relabel` to have vertices named `1:10`. See also: `Kneser`. """ Petersen() = Kneser(5,2) # Create Paley graphs """ `Paley(p)` creates the Paley graph with `p` vertices named `0:(p-1)`. Here `p` must be a prime with `p%4==1`. Vertices `u` and `v` are adjacent iff `u-v` is a quadratic residue (perfect square) modulo `p`. """ function Paley(p::Int) if mod(p,4) != 1 || ~isprime(p) error("p must be a prime congruent to 1 mod 4") end # Quadratic residues mod p qrlist = unique( [ mod(k*k,p) for k=1:p ] ) G = IntGraph() for u = 0:p-1 for k in qrlist v = mod(u+k,p) add!(G,u,v) end end return G end # Called by RandomRegular ... one step function RandomRegularBuilder(n::Int, d::Int) # caller has already checked the values of n,d are legit vlist = randperm(n*d) G = IntGraph(n*d) for v=1:2:n*d add!(G,vlist[v], vlist[v+1]) end for v = n:-1:1 mushlist = collect( d*(v-1)+1 : v*d ) for k=d-1:-1:1 contract!(G,mushlist[k],mushlist[k+1]) end end return relabel(G) end """ `RandomRegular(n,d)` creates a random `d`-regular graph on `n` vertices. This can take a while especially if the arguments are large. Call with an optional third argument to activate verbose progress reports: `RandomRegular(n,p,true)`. """ function RandomRegular(n::Int, d::Int, verbose::Bool=false) # sanity checks if n<1 || d<1 || (n*d)%2==1 error("n,d must be positive integers and n*d even") end if verbose println("Trying to build ", d, "-regular graph on ", n, " vertices") count::Int = 0 end while true if verbose count += 1 println("Attempt ", count) tic() end g = RandomRegularBuilder(n,d) if verbose toc(); end dlist = deg(g) if dlist[1] == dlist[n] if verbose println("Success") end return g end if verbose println("Failed; trying again") end end end """ `Knight(r::Int=8,c::Int=8)` creates a Knight's Moves graph on a `r`-by-`c` grid. That is, the vertices of this graph are the squares of an `r`-by-`c` chess board. Two vertices are adjacent if a Knight can go from one of these squares to the other in a single move. """ function Knight(r::Int=8,c::Int=8) vtcs = collect(product(1:r,1:c)) G = SimpleGraph{Tuple{Int64,Int64}}() for v in vtcs add!(G,v) end for v in vtcs for w in vtcs xv = collect(v) xw = collect(w) z = sort(map(abs,xv - xw)) if z==[1,2] add!(G,v,w) end end end return G end
using Sounds lines, cols = displaysize(stdout) clear() = join(repeat([""], cols), "\n") |> print ft(t) = string(round(Int, 1e-6t)) * "s" file = joinpath(@__DIR__, "piano.wav") sound = Sound(file) d = duration(sound) function progress(p::Int, N = 100) str = "" for n in 1:N str *= n > p ? "░" : "▓" end return str end interval = 0.5 try play!(sound) while isplaying(sound) t = timepos(sound) pre = ft(t) * " / " * ft(d) n = cols - length(pre) - 2 p = floor(Int, n * t / d) clear() print(pre, " ", progress(p, n)) sleep(interval) end finally stop!(sound) end
@model function form_model(y :: Vector{Float64}) N = length(y) s = Vector(undef, N) start ~ Uniform(-1, 1) s[1] ~ Normal(start, 0.05) y[1] ~ Normal(s[1], 0.5) for i ∈ 2:N s[i] ~ Normal(s[i-1], 0.05) y[i] ~ Normal(s[i], 0.5) end end function run_form_analysis(games :: Dict{String, Vector{Game}}) results = Dict{String, Pair}() teams = [team for team ∈ keys(games)] pbar = Progress(length(teams)) Threads.@threads for team ∈ teams N = 100 g = NUTS() samples = sample(form_model(discounted_score.(games[team])), g, N); s = @pipe describe(group(samples, :s))[1][:, :mean] |> vec s_σ = @pipe describe(group(samples, :s))[1][:, :std] |> vec results[team] = Pair(s, s_σ) next!(pbar) end return results end
@testset "Scalar product" begin @test 1v1 ⦿ 2v3 == 0 @test 1v1 ⦿ 2v1 == 2 @test ((1v1 + 2v2) ⦿ (1v1 + 2v2)) == (triplet(SIGNATURE) == (1, 3, 0) ? -3 : 5) end
""" Base.show(io::IO, a::FlexibilityExpr) Extend `Base.show` to print flexibility expressions. """ function Base.show(io::IO, a::FlexibilityExpr) # Setup empty case if length(a.vars) == 0 return print(io, a.constant) end # Otherwise get data and parse it m = a.vars[1].m flex_data = getflexibilitydata(m) vars = a.vars names = [] coeffs = [] for i = 1:length(vars) push!(coeffs, a.coeffs[i]) var = vars[i] if isa(var, RecourseVariable) push!(names, flex_data.recourse_names[var.idx]) elseif isa(var, RandomVariable) push!(names, flex_data.RVnames[var.idx]) end end # Print the expressions to the io strs = ["$(JuMP.aff_str(JuMP.REPLMode,coeffs[i], true))*$(names[i])" for i in 1:length(a.vars)] print(io,string(join(strs," + "), " + ", JuMP.aff_str(JuMP.REPLMode, a.constant, true))) end """ JuMP.addconstraint(m::Model, constr::FlexibilityConstraint) Extend the `JuMP.addconstraint` function to handle `FlexibilityConstraint` types. """ function JuMP.addconstraint(m::Model, constr::FlexibilityConstraint) # Get the data flex_data = getflexibilitydata(m) push!(flex_data.flexibility_constraints, constr) # Add constraint to model here using the flexibility constraint information expr = constr.flex_expr sense = constr.sense #NOTE Look into why these coeffcients get conflated as expressions flex_coeffs = [expr.coeffs[i].constant for i = 1:length(expr.coeffs)] flex_vars = expr.vars # Parse the variable information flex_vars_jump = [] for var in flex_vars if isa(var, RecourseVariable) jump_var = Variable(m, flex_data.recourse_cols[linearindex(var)]) push!(flex_vars_jump, jump_var) elseif isa(var, RandomVariable) jump_var = Variable(m, flex_data.RVcols[linearindex(var)]) push!(flex_vars_jump, jump_var) else error("Variable type $(typeof(var)) not recognized for constructing constraint") end end # Get non flexibility variable information state_coeffs = expr.constant.coeffs state_vars = expr.constant.vars constant = expr.constant.constant #should be the right hand side of the constraint # Add constraints to the model using the anonymous variables all_coeffs = vcat(flex_coeffs,state_coeffs) all_vars = vcat(flex_vars_jump,state_vars) if sense == :(<=) con_reference = @constraint(m, sum(all_coeffs[i]*all_vars[i] for i = 1:length(all_coeffs)) + constant <= 0) elseif sense == :(>=) con_reference = @constraint(m, sum(all_coeffs[i]*all_vars[i] for i = 1:length(all_coeffs)) + constant >= 0) elseif sense == :(==) con_reference = @constraint(m, sum(all_coeffs[i]*all_vars[i] for i = 1:length(all_coeffs)) + constant == 0) else error("Constraint sense $(sense) not recognized") end return ConstraintRef{JuMP.Model,FlexibilityConstraint}(m, length(flex_data.flexibility_constraints)) end """ JuMP.show(io::IO,c::FlexibilityConstraint) Extend the `JuMP.show` function to handle `FlexibilityConstraint` types. """ function JuMP.show(io::IO,c::FlexibilityConstraint) s = "$(string(c.flex_expr)) $(c.sense) 0" return print(io,s) end
include("ITI_additional.jl") """ Computes a global solution for a model via backward Improved Time Iteration. The algorithm is applied to the residuals of the arbitrage equations. The idea is to solve the system G(x) = 0 as a big nonlinear system in x, where the inverted Jacobian matrix is approximated by an infinite sum (Neumann series). If the initial guess for the decision rule is not explicitly provided, the initial guess is provided by `ConstantDecisionRule`. If the stochastic process for the model is not explicitly provided, the process is taken from the default provided by the model object, `model.exogenous` # Arguments * `model::NumericModel`: Model object that describes the current model environment. * `dprocess`: The stochastic process associated with the exogenous variables in the model. * `init_dr`: Initial guess for the decision rule. * `maxbsteps` Maximum number of backsteps. * `verbose` Set "true" if you would like to see the details of the infinite sum convergence. * `smaxit` Maximum number of iterations to compute the Neumann series. * `complementarities` * `compute_radius` * `trace` Record Iteration informations # Returns * `sol`: Improved Time Iteration results """ function improved_time_iteration(model::AbstractModel, dprocess::AbstractDiscretizedProcess, init_dr::AbstractDecisionRule, grid; maxbsteps::Int=10, verbose::Bool=true, verbose_jac::Bool=false, tol::Float64=1e-8, smaxit::Int=500, maxit::Int=1000, complementarities::Bool=true, compute_radius::Bool=false, trace::Bool=false, method=:gmres) parms = model.calibration[:parameters] n_m = max(n_nodes(dprocess), 1) # number of exo states today n_mt = n_inodes(dprocess,1) # number of exo states tomorrow n_s = length(model.symbols[:states]) # number of endo states s = nodes(ListOfPoints, grid) N_s = length(s) n_x = size(model.calibration[:controls],1) x0 = [init_dr(i, s) for i=1:n_m] ddr = CachedDecisionRule(dprocess, grid, x0) ddr_filt = CachedDecisionRule(dprocess, grid, x0) set_values!(ddr,x0) steps = 0.5.^collect(0:maxbsteps) p = SVector(parms...) x = x0 N = length(x[1]) if complementarities == true x_lb = [controls_lb(model, node(Point,dprocess,i),s,p) for i=1:n_m] x_ub = [controls_ub(model, node(Point,dprocess,i),s,p) for i=1:n_m] BIG = 100000 for i=1:n_m for n=1:N x_lb[i][n] = max.(x_lb[i][n],-BIG) x_ub[i][n] = min.(x_ub[i][n], BIG) end end end trace_data = [] ######### Loop for it in range(maxit): it=0 it_invert=0 err_0 = 1.0 #abs(maximum(res_init)) err_2 = err_0 lam0 = 0.0 verbose && println(repeat("-", 120)) verbose && println("N\tf_x\t\td_x\tTime_residuals\tTime_inversion\tTime_search\tLambda_0\tN_invert\tN_search\t") verbose && println(repeat("-", 120)) while it <= maxit && err_0>tol it += 1 t1 = time(); # compute derivatives and residuals: # R_i: residuals # D_i: derivatives w.r.t. x # J_ij: derivatives w.r.t. ~x # S_ij: future states # set_values!(ddr,x) # implicit in the next call _,J_ij,S_ij = euler_residuals(model,s,x,ddr,dprocess,p,keep_J_S=true,set_dr=true) fun(u) = euler_residuals(model,s,u,ddr,dprocess,p,keep_J_S=false,set_dr=false) R_i, D_i = DiffFun(fun, x) if complementarities == true PhiPhi!(R_i,x,x_lb,x_ub,D_i,J_ij) end J_ij *= -1.0 push!(trace_data, [deepcopy(R_i)]) err_0 = maxabs((R_i)) #################### # Invert Jacobians t2 = time(); π_i, M_ij, S_ij = Dolo.preinvert!(R_i, D_i, J_ij, S_ij) if method==:gmres L = LinearThing(M_ij, S_ij, ddr_filt) v = cat([reshape(reinterpret(Float64, vec(e)), (n_x*N,)) for e in π_i]...; dims=1) n1 = L.counter w = gmres(L, v, verbose=false) it_invert = L.counter-n1 ww = reshape(w,n_x,N,n_m) tt = [ww[:,:,i] for i=1:n_m] tot = [reshape(reinterpret(SVector{n_x,Float64}, vec(t)), (N,)) for t in tt] else tot, it_invert, lam0, errors = invert_jac(π_i, M_ij, S_ij, ddr_filt; maxit=smaxit) end t3 = time(); i_bckstps=0 new_err=err_0 new_x = x while new_err>=err_0 && i_bckstps<length(steps) i_bckstps +=1 new_x = x-tot*steps[i_bckstps] new_res = euler_residuals(model,s,new_x,ddr,dprocess,p,keep_J_S=false,set_dr=true) if complementarities == true new_res = [PhiPhi0.(new_res[i],new_x[i],x_lb[i],x_ub[i]) for i=1:n_m] end new_err = maxabs(new_res) end err_2 = maxabs(tot) t4 = time(); x = new_x verbose && @printf "%-6i% -10e% -17e% -15.4f% -15.4f% -15.5f% -17.3f%-17i%-5i\n" it err_0 err_2 t2-t1 t3-t2 t4-t3 lam0 it_invert i_bckstps end verbose && println(repeat("-", 120)) set_values!(ddr,x) if compute_radius == true lam, lam_max, lambdas = radius_jac(res,dres,jres,S_ij,ddr_filt) else lam = NaN end converged = err_0<tol return ImprovedTimeIterationResult(ddr.dr, it, err_0, err_2, converged, complementarities, tol, lam0, it_invert, 5.0, lam, trace_data) end function improved_time_iteration(model:: AbstractModel, dprocess::AbstractDiscretizedProcess, init_dr::AbstractDecisionRule;grid=Dict(), kwargs...) grid = get_grid(model, options=grid) return improved_time_iteration(model, dprocess, init_dr, grid; kwargs...) end function improved_time_iteration(model, dprocess::AbstractDiscretizedProcess; grid=Dict(), kwargs...) init_dr = ConstantDecisionRule(model.calibration[:controls]) return improved_time_iteration(model, dprocess, init_dr; grid=grid, kwargs...) end function improved_time_iteration(model, init_dr; grid=Dict(), kwargs...) dprocess = discretize( model.exogenous ) return improved_time_iteration(model, dprocess, init_dr; grid=grid, kwargs...) end function improved_time_iteration(model; grid=Dict(), kwargs...) dprocess = discretize( model.exogenous ) init_dr = ConstantDecisionRule(model.calibration[:controls]) return improved_time_iteration(model, dprocess, init_dr; grid=grid, kwargs...) end
module VennDiagrams using Compose using Color function venn(xs::Union(AbstractArray,Set)...; proportional::Bool = true, labels=Union(Bool,Vector{String}), colors=Union(Bool,Vector{ColorValue},Vector{AlphaColorValue})) n = length(xs) if eltype(xs) != Set cols = map(Set, xs) else cols = xs end if proportional error("Not implemented yet!") #sizes = 0 end return p end end # module
@block SimonDanisch [layout] begin @cell "Layouting" [scatter, lines, surface, heatmap, vbox] begin p1 = scatter(rand(10), markersize = 1) p2 = lines(rand(10), rand(10)) p3 = surface(0..1, 0..1, rand(100, 100)) p4 = heatmap(rand(100, 100)) x = 0:0.1:10 p5 = lines(0:0.1:10, sin.(x)) pscene = vbox( hbox(p1, p2), p3, hbox(p4, p5, sizes = [0.7, 0.3]), sizes = [0.2, 0.6, 0.2] ) end @cell "Comparing contours, image, surfaces and heatmaps" [image, contour, surface, heatmap, vbox] begin N = 20 x = LinRange(-0.3, 1, N) y = LinRange(-1, 0.5, N) z = x .* y' hbox( vbox( contour(x, y, z, levels = 20, linewidth =3), contour(x, y, z, levels = 0, linewidth = 0, fillrange = true), heatmap(x, y, z), ), vbox( image(x, y, z, colormap = :viridis), surface(x, y, fill(0f0, N, N), color = z, shading = false), image(-0.3..1, -1..0.5, AbstractPlotting.logo()) ) ) end end @block JuliusKrumbiegel ["layout", "2d"] begin using MakieLayout @cell "Faceting" [faceting, grid] begin # layoutscene is a convenience function that creates a Scene and a GridLayout # that are already connected correctly and with Outside alignment scene, layout = layoutscene(30, resolution = (1200, 900)) using ColorSchemes ncols = 4 nrows = 4 # create a grid of LAxis objects axes = [LAxis(scene) for i in 1:nrows, j in 1:ncols] # and place them into the layout layout[1:nrows, 1:ncols] = axes # link x and y axes of all LAxis objects linkxaxes!(axes...) linkyaxes!(axes...) lineplots = [lines!(axes[i, j], (1:0.1:8pi) .+ i, sin.(1:0.1:8pi) .+ j, color = get(ColorSchemes.rainbow, ((i - 1) * nrows + j) / (nrows * ncols)), linewidth = 4) for i in 1:nrows, j in 1:ncols] for i in 1:nrows, j in 1:ncols # remove unnecessary decorations in some of the facets, this will have an # effect on the layout as the freed up space will be used to make the axes # bigger i > 1 && (axes[i, j].titlevisible = false) j > 1 && (axes[i, j].ylabelvisible = false) j > 1 && (axes[i, j].yticklabelsvisible = false) j > 1 && (axes[i, j].yticksvisible = false) i < nrows && (axes[i, j].xticklabelsvisible = false) i < nrows && (axes[i, j].xticksvisible = false) i < nrows && (axes[i, j].xlabelvisible = false) end autolimits!(axes[1]) # hide legend = LLegend(scene, permutedims(lineplots, (2, 1)), ["Line $i" for i in 1:length(lineplots)], ncols = 2) # place a legend on the side by indexing into one column after the current last layout[:, end+1] = legend # index into the 0th row, thereby adding a new row into the layout and place # a text object across the first four columns as a super title layout[0, 1:4] = LText(scene, text="MakieLayout Facets", textsize=50) scene end @cell "ManualTicks" [layout, ticks] begin scene = Scene(resolution = (1000, 1000)); campixel!(scene); maingl = GridLayout(scene, alignmode = Outside(30)) la = maingl[1, 1] = LAxis(scene) la.attributes.yautolimitmargin = (0f0, 0.05f0) poly!(la, BBox(0, 1, 4, 0), color=:blue) poly!(la, BBox(1, 2, 7, 0), color=:red) poly!(la, BBox(2, 3, 1, 0), color=:green) la.attributes.xticks = ManualTicks([0.5, 1.5, 2.5], ["blue", "red", "green"]) la.attributes.xlabel = "Color" la.attributes.ylabel = "Value" scene end @cell "Protrusion changes" [protrusions] begin using MakieLayout.Animations scene, layout = layoutscene(resolution = (600, 600)) axes = [LAxis(scene) for i in 1:2, j in 1:2] layout[1:2, 1:2] = axes a_title = Animation([0, 2], [30.0, 50.0], sineio(n=2, yoyo=true, prewait=0.2)) a_xlabel = Animation([2, 4], [20.0, 40.0], sineio(n=2, yoyo=true, prewait=0.2)) a_ylabel = Animation([4, 6], [20.0, 40.0], sineio(n=2, yoyo=true, prewait=0.2)) record(scene, @replace_with_a_path(mp4), 0:1/60:6, framerate = 60) do t axes[1, 1].titlesize = a_title(t) axes[1, 1].xlabelsize = a_xlabel(t) axes[1, 1].ylabelsize = a_ylabel(t) end end @cell "Hiding decorations" [decorations] begin scene = Scene(resolution = (600, 600), camera=campixel!) layout = GridLayout( scene, 2, 2, # we need to specify rows and columns so the gap sizes don't get lost addedcolgaps = Fixed(0), addedrowgaps = Fixed(0), alignmode = Outside(30) ) axes = [LAxis(scene) for j in 1:2, i in 1:2] layout[1:2, 1:2] = axes re = record(scene, @replace_with_a_path(mp4), framerate=3) do io recordframe!(io) for ax in axes ax.titlevisible = false recordframe!(io) end for ax in axes ax.xlabelvisible = false recordframe!(io) end for ax in axes ax.ylabelvisible = false recordframe!(io) end for ax in axes ax.xticklabelsvisible = false recordframe!(io) end for ax in axes ax.yticklabelsvisible = false recordframe!(io) end for ax in axes ax.xticksvisible = false recordframe!(io) end for ax in axes ax.yticksvisible = false recordframe!(io) end for ax in axes ax.bottomspinevisible = false ax.leftspinevisible = false ax.topspinevisible = false ax.rightspinevisible = false recordframe!(io) end end return re end @cell "Axis aspects" [axis, aspect] begin using FileIO scene, layout = layoutscene(30, resolution = (1200, 900)) axes = [LAxis(scene) for i in 1:2, j in 1:3] tightlimits!.(axes) layout[1:2, 1:3] = axes img = rotr90(MakieGallery.loadasset("cow.png")) for ax in axes image!(ax, img) end axes[1, 1].title = "Default" axes[1, 2].title = "DataAspect" axes[1, 2].aspect = DataAspect() axes[1, 3].title = "AxisAspect(418/348)" axes[1, 3].aspect = AxisAspect(418/348) axes[2, 1].title = "AxisAspect(1)" axes[2, 1].aspect = AxisAspect(1) axes[2, 2].title = "AxisAspect(2)" axes[2, 2].aspect = AxisAspect(2) axes[2, 3].title = "AxisAspect(0.5)" axes[2, 3].aspect = AxisAspect(0.5) scene end @cell "Linked axes" [axis, link] begin scene, layout = layoutscene() layout[1, 1:3] = axs = [LAxis(scene) for i in 1:3] linkxaxes!(axs[1:2]...) linkyaxes!(axs[2:3]...) axs[1].title = "x linked" axs[2].title = "x & y linked" axs[3].title = "y linked" for i in 1:3 lines!(axs[i], 1:10, 1:10, color = "green") if i != 1 lines!(axs[i], 1:10, 11:20, color = "blue") end if i != 3 lines!(axs[i], 11:20, 1:10, color = "red") end end scene end @cell "Nested grids" [grid] begin scene, layout = layoutscene(30, resolution = (1200, 900)) subgl_left = GridLayout() subgl_left[1:2, 1:2] = [LAxis(scene) for i in 1:2, j in 1:2] subgl_right = GridLayout() subgl_right[1:3, 1] = [LAxis(scene) for i in 1:3] layout[1, 1] = subgl_left layout[1, 2] = subgl_right scene end @cell "Grid alignment" [grid] begin scene, layout = layoutscene(30, resolution = (1200, 1200)) layout[1, 1] = LAxis(scene, title="No grid layout") layout[2, 1] = LAxis(scene, title="No grid layout") layout[3, 1] = LAxis(scene, title="No grid layout") subgl_1 = layout[1, 2] = GridLayout(alignmode=Inside()) subgl_2 = layout[2, 2] = GridLayout(alignmode=Outside()) subgl_3 = layout[3, 2] = GridLayout(alignmode=Outside(50)) subgl_1[1, 1] = LAxis(scene, title="Inside") subgl_2[1, 1] = LAxis(scene, title="Outside") subgl_3[1, 1] = LAxis(scene, title="Outside(50)") layout[1:3, 2] = [LRect(scene, color = :transparent, strokecolor = :red) for i in 1:3] scene end @cell "Spanned grid content" [grid] begin scene, layout = layoutscene(4, 4, 30, resolution = (1200, 1200)) layout[1, 1:2] = LAxis(scene, title="[1, 1:2]") layout[2:4, 1:2] = LAxis(scene, title="[2:4, 1:2]") layout[:, 3] = LAxis(scene, title="[:, 3]") layout[1:3, end] = LAxis(scene, title="[1:3, end]") layout[end, end] = LAxis(scene, title="[end, end]") scene end @cell "Indexing outside grid" [grid] begin scene, layout = layoutscene(30, resolution = (1200, 1200)) layout[1, 1] = LAxis(scene) for i in 1:3 layout[:, end+1] = LAxis(scene) layout[end+1, :] = LAxis(scene) end layout[0, :] = LText(scene, text="Super Title", textsize=50) layout[end+1, :] = LText(scene, text="Sub Title", textsize=50) layout[2:end-1, 0] = LText(scene, text="Left Text", textsize=50, rotation=pi/2) layout[2:end-1, end+1] = LText(scene, text="Right Text", textsize=50, rotation=-pi/2) scene end @cell "Column and row sizes" [grid] begin scene = Scene(resolution = (1200, 900), camera=campixel!) layout = GridLayout( scene, 6, 6, colsizes = [Fixed(200), Relative(0.25), Auto(), Auto(), Auto(2), Auto()], rowsizes = [Auto(), Fixed(100), Relative(0.25), Aspect(2, 1), Auto(), Auto()], alignmode = Outside(30, 30, 30, 30)) for i in 2:6, j in 1:5 if i == 6 && j == 3 layout[i, j] = LText(scene, text="My Size is Inferred") else layout[i, j] = LRect(scene) end end for (j, label) in enumerate(["Fixed(200)", "Relative(0.25)", "Auto()", "Auto()", "Auto(2)"]) layout[1, j] = LText(scene, width = Auto(), text = label, tellwidth = false ) end for (i, label) in enumerate(["Fixed(100)", "Relative(0.25)", "Aspect(2, 1)", "Auto()", "Auto()"]) layout[i + 1, 6] = LText(scene, height = Auto(), text = label, tellwidth = false) end scene end @cell "Trimming grids" [grid] begin scene, layout = layoutscene(resolution = (600, 600)) record(scene, @replace_with_a_path(mp4), framerate=1) do io ax1 = layout[1, 1] = LAxis(scene, title = "Axis 1") recordframe!(io) ax2 = layout[1, 2] = LAxis(scene, title = "Axis 2") recordframe!(io) layout[2, 1] = ax2 recordframe!(io) trim!(layout) recordframe!(io) layout[2, 3:4] = ax1 recordframe!(io) trim!(layout) recordframe!(io) end end @cell "3D scenes" ["3d"] begin scene, layout = layoutscene() makescene() = LScene(scene, camera = cam3d!, raw = false, scenekw = (backgroundcolor = RGBf0(0.9, 0.9, 0.9), clear = true)) layout[1, 1] = makescene() layout[1, 2] = makescene() layout[2, 1:2] = makescene() layout[1:2, 3] = makescene() foreach(LScene, layout) do s scatter!(s, rand(100, 3)); end scene end @cell "Window resizing" [record] begin using MakieLayout.Animations container_scene = Scene(camera = campixel!, resolution = (1200, 1200)) t = Node(0.0) a_width = Animation([1.0, 7.0], [1200.0, 800.0], sineio(n=2, yoyo=true, postwait=0.5)) a_height = Animation([2.5, 8.5], [1200.0, 800.0], sineio(n=2, yoyo=true, postwait=0.5)) scene_area = lift(t) do t IRect(0, 0, a_width(t), a_height(t)) end scene = Scene(container_scene, scene_area, camera = campixel!) rect = poly!(scene, scene_area, raw=true, color=RGBf0(0.97, 0.97, 0.97), strokecolor=:transparent, strokewidth=0)[end] outer_gl = GridLayout(scene, alignmode = Outside(30)) inner_gl = outer_gl[1, 1] = GridLayout() ax1 = inner_gl[1, 1] = LAxis(scene, xautolimitmargin=(0, 0), yautolimitmargin=(0, 0)) ax2 = inner_gl[1, 2] = LAxis(scene, xautolimitmargin=(0, 0), yautolimitmargin=(0, 0)) ax3 = inner_gl[2, 1:2] = LAxis(scene, xautolimitmargin=(0, 0), yautolimitmargin=(0, 0)) guigl = inner_gl[3, 1:2] = GridLayout() b1 = guigl[1, 1] = LButton(scene, label = "prev", width = Auto()) sl = guigl[1, 2] = LSlider(scene, startvalue = 6, height = 40) b2 = guigl[1, 3] = LButton(scene, label = "next", width = Auto()) data = randn(200, 200) .+ 3 .* sin.((1:200) ./ 20) .* sin.((1:200)' ./ 20) h1 = heatmap!(ax1, data) h2 = heatmap!(ax2, data, colormap = :blues) h3 = heatmap!(ax3, data, colormap = :heat) agl1 = gridnest!(inner_gl, 1, 1) agl1[1, 2] = LColorbar(scene, h1, width = 30, label = "normal bar") agl1[2, 1:2] = LSlider(scene, height = 20, startvalue = 4) agl1[3, 1:2] = LSlider(scene, height = 20, startvalue = 5) agl1[4, 1:2] = LSlider(scene, height = 20, startvalue = 6) agl2 = gridnest!(inner_gl, 1, 2) agl2[1, 2] = LColorbar(scene, h2, width = 30, height = Relative(0.66), label = "two thirds bar") agl2gl = agl2[2, :] = GridLayout() agl2gl[1, 1] = LButton(scene, label = "Run", height = Auto()) agl2gl[1, 2] = LButton(scene, label = "Start") agl3 = gridnest!(inner_gl, 2, 1:2) agl3[:, 3] = LColorbar(scene, h3, width = 30, height=200, label = "fixed height bar") rowsize!(agl3, 1, Auto(1.0)) inner_gl[0, :] = LText(scene, text = "MakieLayout", textsize = 50) record(container_scene, @replace_with_a_path(mp4), 0:1/30:9; framerate=30) do ti t[] = ti end end @cell "Aspect ratios stretching circles" [layout] begin using Animations # scene setup for animation container_scene = Scene(camera = campixel!, resolution = (1200, 1200)) t = Node(0.0) a_width = Animation([1, 7], [1200.0, 800], sineio(n=2, yoyo=true, postwait=0.5)) a_height = Animation([2.5, 8.5], [1200.0, 800], sineio(n=2, yoyo=true, postwait=0.5)) scene_area = lift(t) do t IRect(0, 0, round(Int, a_width(t)), round(Int, a_height(t))) end scene = Scene(container_scene, scene_area, camera = campixel!) rect = poly!(scene, scene_area, raw=true, color=RGBf0(0.97, 0.97, 0.97), strokecolor=:transparent, strokewidth=0)[end] outer_layout = GridLayout(scene, alignmode = Outside(30)) # example begins here layout = outer_layout[1, 1] = GridLayout() titles = ["aspect via layout", "axis aspect", "no aspect", "data aspect"] axs = layout[1:2, 1:2] = [LAxis(scene, title = t) for t in titles] # plot to all axes using an array comprehension [lines!(a, Circle(Point2f0(0, 0), 100f0)) for a in axs] rowsize!(layout, 1, Fixed(400)) # force the layout cell [1, 1] to be square colsize!(layout, 1, Aspect(1, 1)) axs[2].aspect = 1 axs[4].autolimitaspect = 1 rects = layout[1:2, 1:2] = [LRect(scene, color = (:black, 0.05), strokecolor = :transparent) for _ in 1:4] record(container_scene, @replace_with_a_path(mp4), 0:1/60:9; framerate=60) do ti t[] = ti end end @cell "Ellipse markers and arrows" [layout, "2d"] begin # here we plot some grouped coordinates, find their mean and variance which # we plot as ellipses, plot their actual means, and some additional details. using DataFrames, Distributions, Colors using MakieLayout import AbstractPlotting:px # Here we create `ngrp` groups of `n` coordinates. The mean coordinates of # the groups are distributed equally around the unit circle. The coordinates # are drawn from a normal distribution (with standard deviation σ). ngrp = 4 groups = Symbol.(Iterators.take('a':'z', ngrp)) n = 5 σ = [0.2, 0.4] intended = (; Dict(g => Point2f0(Iterators.reverse(sincos(θ))...) for (g, θ) in zip(groups, range(0, step = 2π/ngrp, length = ngrp)))...) df = DataFrame(group = Symbol[], x = Point2f0[]) for g in groups d = MvNormal(intended[g], σ) for _ in 1:n push!(df, (group = g, x = rand(d))) end end # assign colors to each group colors = Dict(zip(groups, distinguishable_colors(ngrp, [colorant"white", colorant"black"], dropseed = true))) # calculate the mean of each group, and the FWHM of a Gaussian fit to the # data. We later use the mean and FWHM to plot ellipses. ellipses = by(df, :group) do g n = length(g.x) X = Array{Float64}(undef, 2, n) for i in 1:n X[:,i] = g.x[i] end dis = fit(DiagNormal, X) radii = sqrt(2log(2))*sqrt.(var(dis)) # half the FWHM ellipse = (origin = Point2f0(mean(dis)), radius = Vec2f0(radii)) (ellipse = ellipse, ) end # some helper functions # return a vector of coordinates of an ellipse mydecompose(origin, radii) = [origin + radii .* Iterators.reverse(sincos(t)) for t in range(0, stop = 2π, length = 51)] # brighten a color brighten(c, p = 0.5) = weighted_color_mean(p, c, colorant"white") # darken a color darken(c, p = 0.5) = weighted_color_mean(p, c, colorant"black") scene, layout = layoutscene(0, fontsize = 10, resolution = (500,400)); ax = layout[1,1] = LAxis(scene, xlabel = "X (cm)", ylabel = "Y (cm)", xticklabelsize = 8, yticklabelsize = 8, aspect = DataAspect() ) for r in eachrow(ellipses) c = r.ellipse xy = mydecompose(c...) poly!(ax, xy, color = brighten(colors[r.group], 0.25)) end scatter!(ax, getfield.(ellipses.ellipse, :origin), color = :white, marker = '+', markersize = 10px) scatter!(ax, [zero(Point2f0)], color = :black, strokecolor = :black, marker = '⋆', strokewidth = 0.5, markersize = 15px) scatter!(ax, [intended[k] for k in keys(colors)], color = :white, strokecolor = collect(values(colors)), marker = '⋆', strokewidth = 0.5, markersize = 15px) for g in groupby(df, :group) scatter!(ax, g.x, color = RGBA(colors[g.group[1]], 0.75), marker = '●', markersize = 5px) end # Here, we manually construct a list of legend entries to be provided to the # LLegend constructor. This allows us a larger degree of control over how # the legend looks. polys = [PolyElement(color = colors[k], strokecolor = :transparent) for k in unique(df.group)] shapes = [MarkerElement(color = :black, marker = '⋆', strokecolor = :black, markerstrokewidth = 0.5, markersize = 15px), MarkerElement(color = :white, marker = '⋆', strokecolor = :black, markerstrokewidth = 0.5, markersize = 15px), MarkerElement(color = :black, marker = '●', strokecolor = :transparent, markersize = 5px), [PolyElement(color = brighten(colorant"black", 0.75), strokecolor = :transparent, polypoints = mydecompose(Point2f0(0.5, 0.5), Vec2f0(0.75, 0.5))), MarkerElement(color = :white, marker = '+', strokecolor = :transparent, markersize = 10px), ]] leg = ([polys, shapes], [string.(unique(df.group)), ["center", "intended means", "coordinates", "μ ± FWHM"]], ["Groups", "Shapes"]) layout[1, 2] = LLegend(scene, leg..., markersize = 10px, markerstrokewidth = 1, patchsize = (10, 10), rowgap = Fixed(0), titlegap = Fixed(5), groupgap = Fixed(10), titlehalign = :left, gridshalign = :left) # draw an arrow with some text textlayer = Scene(scene, ax.scene.px_area, camera = campixel!, raw = true) topright = lift(textlayer.px_area) do w xy = widths(w) xy .- 0.05max(xy...) end text!(textlayer, "arrow", position = topright, align = (:right, :top), textsize = 10, font = "noto sans") lines!(textlayer, @lift([$topright, $topright .- (30, 0)])) scatter!(textlayer, @lift([$topright]), marker = '►', markersize = 10px) scene end end
module SalsaML using Salsa const N_FEATURES = 1 const Sample = NTuple{N_FEATURES, Number} const learning_rate = 0.0005 @declare_input num_samples(s)::Int @declare_input sample(s, i::Int)::Sample @declare_input response(s, i::Int)::Float64 init_lr!(s::Runtime) = set_num_samples!(s, 0) function new_lr_runtime() s = Runtime() init_lr!(s) return s end function insert_training_pair!(s, sample::Sample, response::Float64) i = num_samples(s) + 1 set_num_samples!(s, i) set_sample!(s, i, sample) set_response!(s, i, response) end function predict(s::Runtime, x::Sample)::Float64 sum(x .* lr_learned_weights(s)) end # Derived function with no inputs (essentially a constant) @derived init_weights(s::Runtime) = Tuple(rand(Float64, N_FEATURES)) @derived function lr_learned_weights(s::Runtime)::NTuple{N_FEATURES,Float64} if num_samples(s) == 0 error("Cannot learn a linear regression with no samples.") end weights = lr_learned_weights_unrolled(s, 0) for i in 1:100 # Stop after 100 iterations new_weights = lr_learned_weights_unrolled(s, i) if abs(sum(new_weights .- weights)) < 0.0001 @info "stopped after $i iterations" return weights end weights = new_weights end @info "timed out in learn iterations" return weights end @derived function lr_learned_weights_unrolled(s::Runtime, iteration::Int) if iteration == 0 return init_weights(s) else n = num_samples(s) weights = lr_learned_weights_unrolled(s, iteration-1) δweights_δcost = lr_δweights_δmse(s, iteration-1) .* learning_rate weights = weights .- δweights_δcost return weights end end @derived function lr_δweights_δmse(s::Runtime, iteration::Int) n = num_samples(s) (-2/n) * sum( sum(sample(s, i) .* (response(s, i) - lr_predicted_unrolled(s, i, iteration))) for i in 1:n ) end @derived function lr_predicted_unrolled(s::Runtime, i::Int, iteration::Int) sum(sample(s, i) .* lr_learned_weights_unrolled(s, iteration)) end # For logging purposes @derived function lr_mse(s::Runtime) n = num_samples(s) 1/n * sum( (response(s, i) - lr_predicted(s, i)) ^ 2 for i in 1:num_samples(s) ) end end
using PowerDynamics: simulate, Perturbation, Inc, PowerGrid using Distributions: Uniform using Sundials using Statistics using NetworkDynamics using LaTeXStrings using FileIO, JLD2 using DelimitedFiles include("../new node types/plotting.jl") include("../new node types/ThirdOrderEq.jl") include("../../src/Random-Pertubation-on-Constrained-Manifolds/RandPertOnConstraindManifolds.jl") include("../../src/PDpatches.jl") """ Evaluates the result of a simulation after a pertubation. Checks if conditions for a stable synchronous state where met. Conditions implemented so far: 1. Is ω returning to zero? (Realized through checking the deviations from 0) #2. Did one of the machines get too far away from a stable state? -> Survivability Inputs: pg: Power grid, a graph containg nodes and lines result: Solution of a power grid after a pertubation nodesarray: Array containg the index of all nodes that contain varible endtime: Endtime of the simulation Outputs: Returns 1 if the system fullfills the condition for a stable state Returns 0 if the condition was not met """ function StableState(result::PowerGridSolution,nodesarray,variable,endtime) #= maxdeviation = maximum(result(0:endtime,node,:ω)) if abs(maxdeviation) > threshold, (5) # this could be used for Survivability later on... return 0 end =# for node in 1:length(powergrid.nodes) # runs over all nodes summation = 0 for time in endtime-10:0.1:endtime if node in nodesarray # checks only nodes which have ω as a symbol summation =+ abs.(result(time,node,:ω)) end if summation > 100 # checks if ω returns to 0 #this is just an arbitrary value that i have choosen so far return 0 end if isapprox(result(time,node, :v) , 0, atol=1e-2) # checks for a short cirtuit return 0 end end end return 1 end function sim(pg::PowerGrid, x0::State, timespan, force_dtmin::Bool, rpg) problem = ODEProblem(rpg,x0.vec,timespan) # sets the kwarg force_dtmin to avoid the dt < dtmin error if force_dtmin == true solution = solve(problem, Rodas5(autodiff=false), abstol=1e-8,reltol=1e-6,tspan=Inf, force_dtmin = true) else solution = solve(problem, Rodas5(autodiff=false), abstol=1e-8,reltol=1e-6,tspan=Inf) end PowerGridSolution(solution, pg) end function dae_sim(rpg_ode, tspan, x0::State,pg) function dae_form(res, du, u, p, t) du_temp = similar(du) rpg_ode.f(du_temp, u, p, t) @. res = du - du_temp end u0 = x0.vec du0 = similar(u0) p = nothing diff_vars = (diag(rpg_ode.mass_matrix) .== 1) rpg_dae = DAEFunction{true, true}(dae_form, syms = rpg_ode.syms) dae = DAEProblem(rpg_dae, du0, u0, tspan, p; differential_vars=diff_vars) sol = solve(dae, DABDF2(autodiff=false), initializealg=BrownFullBasicInit(), force_dtmin = true, matiters= 1e7,save_everystep=false) #sol = solve(dae, IDA(linear_solver=:GMRES)) return PowerGridSolution(sol,pg) end """ Removes all nodes from the from the calculation procedure that do not contain variable as a symbol. Returns a list containg the indexes of all the remaning nodes. Inputs: pg: Power grid, a graph containg nodes and lines Outputs: nodesarray: Array containg the index of all nodes with the symbol varibale """ function RemoveNodes(pg::PowerGrid, variable::Symbol) nodesarray = findall(variable.∈ symbolsof.(pg.nodes)) return nodesarray end """ Produces a plot of the calulated basin stability against the nodes index. Inputs: nodesarray: Array containg the index of all nodes that contain varible basinstability: Array containing the basin stability of each node standarddev: Array of the standard deviations of the basin stability """ function PlotBasinStability(nodesarray, basinstability, standarddev; labtext = "Basin Stability") plot( nodesarray, basinstability, xlabel = "Node Index", ylabel = "Basin Stability", marker = (:circle, 8, "red"), line = (:path, 2,"gray"), label = labtext, grid = false, show = true ) end function PlotBasinStability!(nodesarray, basinstability, standarddev; labtext = "Basin Stability") plot!( nodesarray, basinstability, xlabel = "Node Index", ylabel = "Basin Stability", marker = (:circle, 8, "blue"), line = (:path, 2,"gray"), label = labtext, grid = false, show = true ) end """ Calculates the single node basin stability of the nodes in a power grid using PowerDynamics.jl. The calculations were performed on the basis of the three following papers: 1. Menck, P., Heitzig, J., Marwan, N. et al. How basin stability complements the linear-stability paradigm. Nature Phys 9, 89–92 (2013) 2. Menck, P., Heitzig, J., Kurths, J. et al. How dead ends undermine power grid stability. Nat Commun 5, 3969 (2014). 3. C Mitra, A Choudhary, S Sinha, J Kurths, and R V Donnerk, Multiple-node basin stability in complex dynamical networks Physical Review E, (2017) To calculate the basin stability "numtries" random pertubations are drawn according to the interval. The behaviour of the power grid after the pertubation is then calculated. In the function StableState the number of times the system returns to the stable synchronous state is counted. If numtries -> ∞: Then BasinStability ≈ stablecounter / numtries. Inputs: pg: Power grid, a graph containg nodes and lines endtime: Endtime of the simulation variable: Internal variable of the node types to be perturbed numtries: Number of random pertubations within interval to be evaluated interval: Lower and Upper Bound for the pertubation Outputs: basinstability: Array conating the basinstability of each node standarddev: Array of the standard deviations of the basin stability """ function BasinStability(pg::PowerGrid, endtime::Int, variable::Symbol, numtries::Int, interval_v::Vector{Float64}, interval_θ::Vector{Float64}; ProjectionMethod = "Optim") @assert interval_v[2] >= interval_v[1] "Upper bound should be bigger than lower bound!" num_errors = 0 operationpoint = find_steady_state(pg) nodesarray = RemoveNodes(pg,variable) basinstability = [] standarddev = [] P, Q = SimplePowerFlow(pg, operationpoint) rpg = rhs(pg) state_file = File(format"JLD2","State_File.jld2") save(state_file, "operationpoint", operationpoint) for node in nodesarray stablecounter = Array{Int64}(undef,numtries) # do some parralelization\ multithreading here to speed up calculation? for tries = 1:numtries println("NODE:",node," TRY:",tries) PerturbedState, dz = RandPertWithConstrains(powergrid, operationpoint,node, interval_v, interval_θ, Q[node], ProjectionMethod = ProjectionMethod) column_name = string(node) * string(tries) save(state_file, column_name, PerturbedState) λ, stable = check_eigenvalues(powergrid, PerturbedState) #= if stable != true println("Positive eigenvalue detected. The system might be unstable.") try result = sim(pg, PerturbedState, (0.0, endtime),true, rpg) stablecounter[tries] = StableState(result, nodesarray, variable, endtime, interval) if stablecounter[tries] == 0 display(plot_res(result, pg, node)) fn = "node$(node)_try$(tries)" png(fn) end catch err if isa(err, GridSolutionError) stablecounter[tries] = 0 # counted as an unstable solution num_errors += 1 end end else =# result = sim(pg, PerturbedState, (0.0, endtime),false, rpg) stablecounter[tries] = StableState(result,nodesarray,variable,endtime) #if stablecounter[tries] == 0 display(plot_res(result, pg, node)) #fn = "node$(node)_try$(tries)" #png(fn) #end end append!(basinstability, mean(stablecounter)) append!(standarddev, std(stablecounter)) # is this even a useful measure here? end println("Percentage of failed Simualtions: ",100 * num_errors/(numtries * length(nodesarray))) display(PlotBasinStability(nodesarray, basinstability, standarddev)) png("BasinStability_Plot") writedlm("bs.txt", basinstability) return basinstability, standarddev end function BasinStability(pg::PowerGrid, endtime::Float64, variable::Symbol, numtries::Int, interval_v::Vector{Float64}, interval_θ::Vector{Float64}; ProjectionMethod = "Optim", dae) @assert interval_v[2] >= interval_v[1] "Upper bound should be bigger than lower bound!" num_errors = 0 operationpoint = find_steady_state(pg) nodesarray = RemoveNodes(pg,variable) basinstability = [] standarddev = [] P, Q = SimplePowerFlow(pg, operationpoint) rpg = rhs(pg) state_file = File(format"JLD2","State_File.jld2") save(state_file, "operationpoint", operationpoint) for node in nodesarray stablecounter = Array{Int64}(undef,numtries) # do some parralelization\ multithreading here to speed up calculation? for tries = 1:numtries println("NODE:",node," TRY:",tries) PerturbedState, dz = RandPertWithConstrains(powergrid, operationpoint,node, interval_v, interval_θ, Q[node], ProjectionMethod = ProjectionMethod) column_name = string(node) * string(tries) save(state_file, column_name, PerturbedState) result = dae_sim(rpg, (0.0, endtime), PerturbedState,pg) stablecounter[tries] = StableState(result,nodesarray,variable,endtime) display(plot_res(result, pg, node)) fn = "node$(node)_try$(tries)" png(fn) end append!(basinstability, mean(stablecounter)) append!(standarddev, std(stablecounter)) # is this even a useful measure here? end println("Percentage of failed Simualtions: ",100 * num_errors/(numtries * length(nodesarray))) display(PlotBasinStability(nodesarray, basinstability, standarddev)) png("BasinStability_Plot") writedlm("bs.txt", basinstability) return basinstability, standarddev end
struct MaybeKnown hint::Int sym::Symbol known::Bool end struct Loop itersymbol::Symbol start::MaybeKnown stop::MaybeKnown step::MaybeKnown rangesym::Symbol# === Symbol("") means loop is static lensym::Symbol end struct UnrollSymbols u₁loopsym::Symbol u₂loopsym::Symbol vloopsym::Symbol end struct UnrollArgs u₁loop::Loop u₂loop::Loop vloop::Loop u₁::Int u₂max::Int suffix::Int # -1 means not tiled end UnPack.unpack(ua::UnrollArgs, ::Val{:u₁loopsym}) = getfield(getfield(ua, :u₁loop), :itersymbol) UnPack.unpack(ua::UnrollArgs, ::Val{:u₂loopsym}) = getfield(getfield(ua, :u₂loop), :itersymbol) UnPack.unpack(ua::UnrollArgs, ::Val{:vloopsym}) = getfield(getfield(ua, :vloop), :itersymbol) UnPack.unpack(ua::UnrollArgs, ::Val{:u₁step}) = getfield(getfield(ua, :u₁loop), :step) UnPack.unpack(ua::UnrollArgs, ::Val{:u₂step}) = getfield(getfield(ua, :u₂loop), :step) UnPack.unpack(ua::UnrollArgs, ::Val{:vstep}) = getfield(getfield(ua, :vloop), :step) struct UnrollSpecification u₁loopnum::Int u₂loopnum::Int vloopnum::Int u₁::Int u₂::Int end # UnrollSpecification(ls::LoopSet, u₁loop::Loop, vloopsym::Symbol, u₁, u₂) = UnrollSpecification(ls, u₁loop.itersymbol, vloopsym, u₁, u₂) function UnrollSpecification(us::UnrollSpecification, u₁, u₂) @unpack u₁loopnum, u₂loopnum, vloopnum = us UnrollSpecification(u₁loopnum, u₂loopnum, vloopnum, u₁, u₂) end # function UnrollSpecification(us::UnrollSpecification; u₁ = us.u₁, u₂ = us.u₂) # @unpack u₁loopnum, u₂loopnum, vloopnum = us # UnrollSpecification(u₁loopnum, u₂loopnum, vloopnum, u₁, u₂) # end isunrolled1(us::UnrollSpecification, n::Int) = us.u₁loopnum == n isunrolled2(us::UnrollSpecification, n::Int) = !isunrolled1(us, n) && us.u₂loopnum == n isvectorized(us::UnrollSpecification, n::Int) = us.vloopnum == n function unrollfactor(us::UnrollSpecification, n::Int) @unpack u₁loopnum, u₂loopnum, u₁, u₂ = us (u₁loopnum == n) ? u₁ : ((u₂loopnum == n) ? u₂ : 1) end function pushexpr!(ex::Expr, mk::MaybeKnown) if isknown(mk) push!(ex.args, staticexpr(gethint(mk))) else push!(ex.args, getsym(mk)) end nothing end pushexpr!(ex::Expr, x::Union{Symbol,Expr}) = (push!(ex.args, x); nothing) pushexpr!(ex::Expr, x::Integer) = (push!(ex.args, staticexpr(convert(Int, x))); nothing) MaybeKnown(x::Integer) = MaybeKnown(convert(Int, x), Symbol("##UNDEFINED##"), true) MaybeKnown(x::Integer, default::Int) = MaybeKnown(x) MaybeKnown(x::Symbol, default::Int) = MaybeKnown(default, x, false) isknown(mk::MaybeKnown) = getfield(mk, :known) getsym(mk::MaybeKnown) = getfield(mk, :sym) gethint(mk::MaybeKnown) = getfield(mk, :hint) Base.isone(mk::MaybeKnown) = isknown(mk) && isone(gethint(mk)) Base.iszero(mk::MaybeKnown) = isknown(mk) && iszero(gethint(mk)) gethint(a::Integer) = a function Loop( itersymbol::Symbol, start::Union{Int,Symbol}, stop::Union{Int,Symbol}, step::Union{Int,Symbol}, rangename::Symbol, lensym::Symbol ) Loop(itersymbol, MaybeKnown(start, 1), MaybeKnown(stop, 1024), MaybeKnown(step, 1), rangename, lensym) end startstopΔ(loop::Loop) = gethint(last(loop)) - gethint(first(loop)) function Base.length(loop::Loop) l = startstopΔ(loop) s = gethint(step(loop)) (isone(s) ? l : cld(l, s)) + 1 end Base.first(l::Loop) = getfield(l, :start) Base.last(l::Loop) = getfield(l, :stop) Base.step(l::Loop) = getfield(l, :step) isstaticloop(l::Loop) = isknown(first(l)) & isknown(last(l)) & isknown(step(l)) unitstep(l::Loop) = isone(step(l)) function startloop(loop::Loop, itersymbol, staticinit::Bool=false) start = first(loop) if isknown(start) if staticinit Expr(:(=), itersymbol, staticexpr(gethint(start))) else Expr(:(=), itersymbol, gethint(start)) end else Expr(:(=), itersymbol, Expr(:call, lv(:Int), getsym(start))) end end pushmulexpr!(q, a, b) = (push!(q.args, mulexpr(a, b)); nothing) function pushmulexpr!(q, a, b::Integer) isone(b) ? push!(q.args, a) : push!(q.args, mulexpr(a, b)) nothing end # function arithmetic_expr(f, a, b) # call = Expr(:call, lv(f)) # if isa(a, MaybeKnown) # pushexpr!( # end isknown(x::Union{Symbol,Expr}) = false isknown(x::Integer) = true addexpr(a,b) = arithmeticexpr(+, :vadd_nsw, a, b) subexpr(a,b) = arithmeticexpr(-, :vsub_nsw, a, b) mulexpr(a,b) = arithmeticexpr(*, :vmul_nsw, a, b) lazymulexpr(a,b) = arithmeticexpr(*, :lazymul, a, b) function arithmeticexpr(op, f, a::Union{Integer,MaybeKnown}, b::Union{Integer,MaybeKnown}) if isknown(a) & isknown(b) return staticexpr(op(gethint(a), gethint(b))) else return _arithmeticexpr(f, a, b) end end arithmeticexpr(op, f, a, b) = _arithmeticexpr(f, a, b) function _arithmeticexpr(f, a, b) ex = Expr(:call, lv(f)) pushexpr!(ex, a) pushexpr!(ex, b) return ex end mulexpr(a,b,c) = arithmeticexpr(*, 1, :vmul_nsw, a, b, c) addexpr(a,b,c) = arithmeticexpr(+, 0, :vadd_nsw, a, b, c) function arithmeticexpr(op, init, f, a, b, c) ex = Expr(:call, lv(f)) p = init if isknown(a) p = op(p, gethint(a)) known = 1 else pushexpr!(ex, a) known = 0 end if isknown(b) p = op(p, gethint(b)) known += 1 else pushexpr!(ex, b) end if isknown(c) p = op(p, gethint(c)) known += 1 else if known == 0 ex = Expr(:call, lv(f), ex) end pushexpr!(ex, c) end if known == 3 return staticexpr(p) else if known == 2 pushexpr!(ex, p) return ex elseif known == 1 if ((op === (+)) && (p == 0)) || ((op === (*)) && (p == 1)) return ex else return Expr(:call, lv(f), ex, staticexpr(p)) end else#known == 0 return ex end end end function addexpr(ex, incr::Integer) if incr > 0 f = :vadd_nsw else f = :vsub_nsw incr = -incr end expr = Expr(:call, lv(f)) pushexpr!(expr, ex) pushexpr!(expr, convert(Int, incr)) expr end staticmulincr(ptr, incr) = Expr(:call, lv(:staticmul), Expr(:call, :eltype, ptr), incr) @inline cmpend(i::Int, r::CloseOpen) = i < getfield(r,:upper) @inline cmpend(i::Int, r::AbstractUnitRange) = i ≤ last(r) @inline cmpend(i::Int, r::AbstractRange) = i ≤ last(r) @inline vcmpend(i::Int, r::CloseOpen, ::StaticInt{W}) where {W} = i ≤ vsub_nsw((getfield(r,:upper) % Int), W) @inline vcmpendzs(i::Int, r::CloseOpen, ::StaticInt{W}) where {W} = i ≠ ((getfield(r,:upper) % Int) & (-W)) @inline vcmpend(i::Int, r::AbstractUnitRange, ::StaticInt{W}) where {W} = i ≤ vsub_nsw(last(r), W-1) @inline vcmpendzs(i::Int, r::AbstractUnitRange, ::StaticInt{W}) where {W} = i ≠ (length(r) & (-W)) # i = 0 # i += 4*3 # i = 12 @inline vcmpend(i::Int, r::AbstractRange, ::StaticInt{W}) where {W} = i ≤ vsub_nsw(last(r), vsub_nsw(W*step(r), 1)) @inline vcmpendzs(i::Int, r::AbstractRange, ::StaticInt{W}) where {W} = i ≤ vsub_nsw(last(r), vsub_nsw(W*step(r), 1)) function staticloopexpr(loop::Loop) f = first(loop) s = step(loop) l = last(loop) if isone(s) Expr(:call, GlobalRef(Base, :(:)), staticexpr(gethint(f)), staticexpr(gethint(l))) else Expr(:call, GlobalRef(Base, :(:)), staticexpr(gethint(f)), staticexpr(gethint(s)), staticexpr(gethint(l))) end end function vec_looprange(loop::Loop, UF::Int, mangledname) fast = ispow2(UF) && iszero(first(loop)) if loop.rangesym === Symbol("") # means loop is static vec_looprange(UF, mangledname, staticloopexpr(loop), fast) else vec_looprange(UF, mangledname, loop.rangesym, fast) end end function vec_looprange(UF::Int, mangledname, r::Union{Expr,Symbol}, zerostart::Bool) cmp = zerostart ? lv(:vcmpendzs) : lv(:vcmpend) if isone(UF) Expr(:call, cmp, mangledname, r, VECTORWIDTHSYMBOL) else Expr(:call, cmp, mangledname, r, mulexpr(VECTORWIDTHSYMBOL, UF)) end end function looprange(loop::Loop, UF::Int, mangledname) if loop.rangesym === Symbol("") # means loop is static looprange(UF, mangledname, staticloopexpr(loop)) else looprange(UF, mangledname, loop.rangesym) end end function looprange(UF::Int, mangledname, r::Union{Expr,Symbol}) if isone(UF) Expr(:call, lv(:cmpend), mangledname, r) else Expr(:call, lv(:vcmpend), mangledname, r, staticexpr(UF)) end end function terminatecondition( loop::Loop, us::UnrollSpecification, n::Int, mangledname::Symbol, inclmask::Bool, UF::Int = unrollfactor(us, n) ) if !isvectorized(us, n) looprange(loop, UF, mangledname) elseif inclmask looprange(loop, 1, mangledname) else vec_looprange(loop, UF, mangledname) # may not be u₂loop end end function incrementloopcounter(us::UnrollSpecification, n::Int, mangledname::Symbol, UF::Int, l::Loop) incr = step(l) if isknown(incr) incrementloopcounter(us, n, mangledname, UF * gethint(incr)) else incrementloopcounter(us, n, mangledname, UF, getsym(incr)) end end function incrementloopcounter(us::UnrollSpecification, n::Int, mangledname::Symbol, UF::Int) if isvectorized(us, n) if isone(UF) Expr(:(=), mangledname, addexpr(VECTORWIDTHSYMBOL, mangledname)) else Expr(:(=), mangledname, addexpr(mulexpr(VECTORWIDTHSYMBOL, staticexpr(UF)), mangledname)) end else Expr(:(=), mangledname, addexpr(mangledname, UF)) end end function incrementloopcounter(us::UnrollSpecification, n::Int, mangledname::Symbol, UF::Int, incr::Symbol) if isvectorized(us, n) if isone(UF) Expr(:(=), mangledname, addexpr(mulexpr(VECTORWIDTHSYMBOL, incr), mangledname)) else Expr(:(=), mangledname, addexpr(mulexpr(mulexpr(VECTORWIDTHSYMBOL, staticexpr(UF)), incr), mangledname)) end else Expr(:(=), mangledname, addexpr(mangledname, mulexpr(incr, UF))) end end function incrementloopcounter!(q, us::UnrollSpecification, n::Int, UF::Int, l::Loop) incr = step(l) if isknown(incr) incrementloopcounter!(q, us, n, UF * gethint(incr)) else incrementloopcounter!(q, us, n, UF, getsym(incr)) end end function incrementloopcounter!(q, us::UnrollSpecification, n::Int, UF::Int) if isvectorized(us, n) if isone(UF) push!(q.args, VECTORWIDTHSYMBOL) else push!(q.args, mulexpr(VECTORWIDTHSYMBOL, staticexpr(UF))) end else push!(q.args, staticexpr(UF)) end end function incrementloopcounter!(q, us::UnrollSpecification, n::Int, UF::Int, incr::Symbol) if isvectorized(us, n) if isone(UF) push!(q.args, mulexpr(VECTORWIDTHSYMBOL, incr)) else push!(q.args, mulexpr(mulexpr(VECTORWIDTHSYMBOL, staticexpr(UF)), incr)) end else push!(q.args, mulexpr(staticexpr(UF), incr)) end end # load/compute/store × isunrolled × istiled × pre/post loop × Loop number struct LoopOrder <: AbstractArray{Vector{Operation},5} oporder::Vector{Vector{Operation}} loopnames::Vector{Symbol} bestorder::Vector{Symbol} end # function LoopOrder(N::Int) # LoopOrder( # [ Operation[] for _ ∈ 1:8N ], # Vector{Symbol}(undef, N), Vector{Symbol}(undef, N) # ) # end LoopOrder() = LoopOrder(Vector{Operation}[],Symbol[],Symbol[]) Base.empty!(lo::LoopOrder) = foreach(empty!, lo.oporder) function Base.resize!(lo::LoopOrder, N::Int) Nold = length(lo.loopnames) resize!(lo.oporder, 8N) for n ∈ 8Nold+1:8N lo.oporder[n] = Operation[] end resize!(lo.loopnames, N) resize!(lo.bestorder, N) lo end Base.size(lo::LoopOrder) = (2,2,2,length(lo.loopnames)) Base.@propagate_inbounds Base.getindex(lo::LoopOrder, i::Int) = lo.oporder[i] Base.@propagate_inbounds Base.getindex(lo::LoopOrder, i::Vararg{Int,K}) where {K} = lo.oporder[LinearIndices(size(lo))[i...]] @enum NumberType::Int8 HardInt HardFloat IntOrFloat INVALID struct LoopStartStopManager terminators::Vector{Int} incrementedptrs::Vector{Vector{ArrayReferenceMeta}} uniquearrayrefs::Vector{ArrayReferenceMeta} end # Must make it easy to iterate # outer_reductions is a vector of indices (within operation vectors) of the reduction operation, eg the vmuladd op in a dot product # O(N) search is faster at small sizes mutable struct LoopSet loopsymbols::Vector{Symbol} loopsymbol_offsets::Vector{Int} # symbol loopsymbols[i] corresponds to loops[lso[i]+1:lso[i+1]] (CartesianIndex handling) loops::Vector{Loop} opdict::Dict{Symbol,Operation} operations::Vector{Operation} # Split them to make it easier to iterate over just a subset operation_offsets::Vector{Int} outer_reductions::Vector{Int} # IDs of reduction operations that need to be reduced at end. loop_order::LoopOrder preamble::Expr prepreamble::Expr # performs extractions that must be performed first, and don't need further registering preamble_symsym::Vector{Tuple{Int,Symbol}} preamble_symint::Vector{Tuple{Int,Tuple{Int,Int32,Bool}}} # (id,(intval,intsz,signed)) preamble_symfloat::Vector{Tuple{Int,Float64}} preamble_zeros::Vector{Tuple{Int,NumberType}} preamble_funcofeltypes::Vector{Tuple{Int,Float64}} includedarrays::Vector{Symbol} includedactualarrays::Vector{Symbol} syms_aliasing_refs::Vector{Symbol} refs_aliasing_syms::Vector{ArrayReferenceMeta} cost_vec::Matrix{Float64} reg_pres::Matrix{Float64} included_vars::Vector{Bool} place_after_loop::Vector{Bool} unrollspecification::UnrollSpecification loadelimination::Bool lssm::LoopStartStopManager vector_width::Int symcounter::Int isbroadcast::Bool register_size::Int register_count::Int cache_linesize::Int cache_size::Tuple{Int,Int,Int} ureduct::Int equalarraydims::Vector{Tuple{Vector{Symbol},Vector{Int}}} omop::OffsetLoadCollection loopordermap::Vector{Int} loopindexesbit::Vector{Bool} validreorder::Vector{UInt8} mod::Symbol LoopSet() = new() end function UnrollArgs(ls::LoopSet, u₁::Int, unrollsyms::UnrollSymbols, u₂max::Int, suffix::Int) @unpack u₁loopsym, u₂loopsym, vloopsym = unrollsyms u₁loop = getloop(ls, u₁loopsym) u₂loop = u₂loopsym === Symbol("##undefined##") ? u₁loop : getloop(ls, u₂loopsym) vloop = getloop(ls, vloopsym) UnrollArgs(u₁loop, u₂loop, vloop, u₁, u₂max, suffix) end function cost_vec_buf(ls::LoopSet) cv = @view(ls.cost_vec[:,2]) @inbounds for i ∈ 1:4 cv[i] = 0.0 end cv end function reg_pres_buf(ls::LoopSet) ps = @view(ls.reg_pres[:,2]) @inbounds for i ∈ 1:4 ps[i] = 0 end ps[4] = reg_count(ls) ps end function save_tilecost!(ls::LoopSet) @inbounds for i ∈ 1:4 ls.cost_vec[i,1] = ls.cost_vec[i,2] ls.reg_pres[i,1] = ls.reg_pres[i,2] end # ls.reg_pres[5,1] = ls.reg_pres[5,2] end function set_hw!(ls::LoopSet, rs::Int, rc::Int, cls::Int, l1::Int, l2::Int, l3::Int) ls.register_size = rs ls.register_count = rc ls.cache_linesize = cls ls.cache_size = (l1,l2,l3) # ls.opmask_register[] = omr nothing end available_registers() = ifelse(has_opmask_registers(), register_count(), register_count() - One()) function set_hw!(ls::LoopSet) set_hw!( ls, Int(register_size()), Int(available_registers()), Int(cache_linesize()), Int(cache_size(StaticInt(1))), Int(cache_size(StaticInt(2))), Int(cache_size(StaticInt(3))) ) end reg_size(ls::LoopSet) = ls.register_size reg_count(ls::LoopSet) = ls.register_count cache_lnsze(ls::LoopSet) = ls.cache_linesize cache_sze(ls::LoopSet) = ls.cache_size pushprepreamble!(ls::LoopSet, ex) = push!(ls.prepreamble.args, ex) function pushpreamble!(ls::LoopSet, op::Operation, v::Symbol) if v !== mangledvar(op) push!(ls.preamble_symsym, (identifier(op),v)) end nothing end function integer_description(@nospecialize(v::Integer))::Tuple{Int,Int32,Bool} if v isa Bool ((v % Int)::Int, one(Int32), false) else ((v % Int)::Int, ((8sizeof(v))%Int32)::Int32, (v isa Signed)::Bool) end end function pushpreamble!(ls::LoopSet, op::Operation, v::Number) typ = v isa Integer ? HardInt : HardFloat id = identifier(op) if iszero(v) push!(ls.preamble_zeros, (id, typ)) elseif v isa Integer push!(ls.preamble_symint, (id, integer_description(v))) else push!(ls.preamble_symfloat, (id, convert(Float64,v))) end end pushpreamble!(ls::LoopSet, ex::Expr) = push!(ls.preamble.args, ex) # function pushpreamble!(ls::LoopSet, op::Operation, RHS::Expr) # c = gensym(:licmconst) # if RHS.head === :call && first(RHS.args) === :zero # push!(ls.preamble_zeros, (identifier(op), IntOrFloat)) # elseif RHS.head === :call && first(RHS.args) === :one # push!(ls.preamble_funcofeltypes, (identifier(op), MULTIPLICATIVE_IN_REDUCTIONS)) # else # pushpreamble!(ls, Expr(:(=), c, RHS)) # pushpreamble!(ls, op, c) # end # nothing # end function zerotype(ls::LoopSet, op::Operation) opid = identifier(op) for (id,typ) ∈ ls.preamble_zeros id == opid && return typ end INVALID end includesarray(ls::LoopSet, array::Symbol) = array ∈ ls.includedarrays function LoopSet(mod::Symbol) ls = LoopSet() ls.loopsymbols = Symbol[] ls.loopsymbol_offsets = [0] ls.loops = Loop[] ls.opdict = Dict{Symbol,Operation}() ls.operations = Operation[] ls.operation_offsets = Int[0] ls.outer_reductions = Int[] ls.loop_order = LoopOrder() ls.preamble = Expr(:block) ls.prepreamble = Expr(:block) ls.preamble_symsym = Tuple{Int,Symbol}[] ls.preamble_symint = Tuple{Int,Tuple{Int,Int32,Bool}}[] ls.preamble_symfloat = Tuple{Int,Float64}[] ls.preamble_zeros = Tuple{Int,NumberType}[] ls.preamble_funcofeltypes = Tuple{Int,Float64}[] ls.includedarrays = Symbol[] ls.includedactualarrays = Symbol[] ls.syms_aliasing_refs = Symbol[] ls.refs_aliasing_syms = ArrayReferenceMeta[] ls.cost_vec = Matrix{Float64}(undef, 4, 2) ls.reg_pres = Matrix{Float64}(undef, 4, 2) ls.included_vars = Bool[] ls.place_after_loop = Bool[] ls.unrollspecification ls.loadelimination = false ls.vector_width = 0 ls.symcounter = 0 ls.isbroadcast = 0 ls.register_size = 0 ls.register_count = 0 ls.cache_linesize = 0 ls.cache_size = (0,0,0) ls.ureduct = -1 ls.equalarraydims = Tuple{Vector{Symbol},Vector{Int}}[] ls.omop = OffsetLoadCollection() ls.loopordermap = Int[] ls.loopindexesbit = Bool[] ls.validreorder = UInt8[] ls.mod = mod ls end """ Used internally to create symbols unique for this loopset. This is used so that identical loops will create identical `_turbo_!` calls in the macroexpansions, hopefully reducing recompilation. """ gensym!(ls::LoopSet, s) = Symbol("###$(s)###$(ls.symcounter += 1)###") function fill_children!(ls::LoopSet) for op ∈ operations(ls) empty!(children(op)) for opp ∈ parents(op) push!(children(opp), op) end end end function cacheunrolled!(ls::LoopSet, u₁loop::Symbol, u₂loop::Symbol, vloopsym::Symbol) vloop = getloop(ls, vloopsym) for op ∈ operations(ls) setunrolled!(ls, op, u₁loop, u₂loop, vloopsym) if accesses_memory(op) rc = rejectcurly(ls, op, u₁loop, vloopsym) op.rejectcurly = rc if rc op.rejectinterleave = true else omop = ls.omop batchid, opind = omop.batchedcollectionmap[identifier(op)] op.rejectinterleave = ((batchid == 0) || (!isvectorized(op))) || rejectinterleave(ls, op, vloop, omop.batchedcollections[batchid]) end end end end function setunrolled!(ls::LoopSet, op::Operation, u₁loopsym::Symbol, u₂loopsym::Symbol, vectorized::Symbol) u₁::Bool = u₂::Bool = v::Bool = false for ld ∈ loopdependencies(op) u₁ |= ld === u₁loopsym u₂ |= ld === u₂loopsym v |= ld === vectorized end if isconstant(op) for opp ∈ children(op) u₁ = u₁ && u₁loopsym ∈ loopdependencies(opp) u₂ = u₂ && u₂loopsym ∈ loopdependencies(opp) v = v && vectorized ∈ loopdependencies(opp) end if isouterreduction(ls, op) ≠ -1 && !all((u₁,u₂,v)) opv = true for opp ∈ parents(op) if iscompute(opp) && instruction(opp).instr ≢ :identity opv = false break end end if opv if !u₁ && u₁loopsym ∈ reduceddependencies(op) u₁ = true end if !u₂ && u₂loopsym ∈ reduceddependencies(op) u₂ = true end if !v && vectorized ∈ reduceddependencies(op) v = true end end end end op.u₁unrolled = u₁ op.u₂unrolled = u₂ op.vectorized = v nothing end rejectcurly(op::Operation) = op.rejectcurly rejectinterleave(op::Operation) = op.rejectinterleave num_loops(ls::LoopSet) = length(ls.loops) function oporder(ls::LoopSet) N = length(ls.loop_order.loopnames) reshape(ls.loop_order.oporder, (2,2,2,N)) end names(ls::LoopSet) = ls.loop_order.loopnames reversenames(ls::LoopSet) = ls.loop_order.bestorder function getloopid_or_nothing(ls::LoopSet, s::Symbol) for (loopnum,sym) ∈ enumerate(ls.loopsymbols) s === sym && return loopnum end end getloopid(ls::LoopSet, s::Symbol) = getloopid_or_nothing(ls, s)::Int getloop(ls::LoopSet, i::Integer) = ls.loops[ls.loopordermap[i]] # takes nest level after reordering getloop_from_id(ls::LoopSet, i::Integer) = ls.loops[i] # takes w/ respect to original loop order. getloop(ls::LoopSet, s::Symbol) = getloop_from_id(ls, getloopid(ls, s)) getloopsym(ls::LoopSet, i::Integer) = ls.loopsymbols[i] Base.length(ls::LoopSet, s::Symbol) = length(getloop(ls, s)) function init_loop_map!(ls::LoopSet) @unpack loopordermap = ls order = names(ls) resize!(loopordermap, length(order)) for (i,o) ∈ enumerate(order) loopordermap[i] = getloopid(ls,o) end nothing end # isstaticloop(ls::LoopSet, s::Symbol) = isstaticloop(getloop(ls,s)) # looprangehint(ls::LoopSet, s::Symbol) = length(getloop(ls, s)) # looprangesym(ls::LoopSet, s::Symbol) = getloop(ls, s).rangesym """ getop only works while construction a LoopSet object. You cannot use it while lowering. """ getop(ls::LoopSet, var::Number, elementbytes) = add_constant!(ls, var, elementbytes) function getop(ls::LoopSet, var::Symbol, elementbytes::Int) get!(ls.opdict, var) do add_constant!(ls, var, elementbytes) end end function getop(ls::LoopSet, var::Symbol, deps, elementbytes::Int) get!(ls.opdict, var) do add_constant!(ls, var, deps, gensym!(ls, "constant"), elementbytes) end end getop(ls::LoopSet, i::Int) = ls.operations[i] findop(ls::LoopSet, s::Symbol) = findop(operations(ls), s) function findop(ops::Vector{Operation}, s::Symbol) for op ∈ ops name(op) === s && return op end throw(ArgumentError("Symbol $s not found.")) end # """ # Returns an operation with the same name as `s`. # """ # function getoperation(ls::LoopSet, s::Symbol) # for op ∈ Iterators.Reverse(operations(ls)) # name(op) === s && return op # end # throw("Symbol $s not found among operations(ls).") # end function Operation( ls::LoopSet, variable, elementbytes, instruction, node_type, dependencies, reduced_deps, parents, ref = NOTAREFERENCE ) Operation( length(operations(ls)), variable, elementbytes, instruction, node_type, dependencies, reduced_deps, parents, ref ) end function Operation(ls::LoopSet, variable, elementbytes, instr, optype, mpref::ArrayReferenceMetaPosition) Operation(length(operations(ls)), variable, elementbytes, instr, optype, mpref) end operations(ls::LoopSet) = ls.operations function getconstvalues(ls::LoopSet, opparents::Vector{Operation})::Tuple{Bool,Vector{Any}} vals = sizehint!(Any[], length(opparents)) for i ∈ eachindex(opparents) pushconstvalue!(vals, ls, opparents[i]) && return true, vals end false, vals end function add_constant_compute!(ls::LoopSet, op::Operation, var::Symbol)::Operation op.node_type = constant instr = instruction(op) opparents = parents(op) if Base.sym_in(instr.instr, (:add_fast,:mul_fast,:sub_fast,:div_fast,:vfmadd_fast, :vfnmadd_fast, :vfmsub_fast, :vfnmsub_fast)) getconstfailed, vals = getconstvalues(ls, opparents) if !getconstfailed f = instr.instr if f === :add_fast return add_constant!(ls, sum(vals), 8)::Operation elseif f === :mul_fast return add_constant!(ls, prod(vals), 8)::Operation elseif f === :sub_fast if length(opparents) == 2 return add_constant!(ls, vals[1] - vals[2], 8)::Operation elseif length(opparents) == 1 return add_constant!(ls, - vals[1], 8)::Operation end elseif f === :div_fast if length(opparents) == 2 return add_constant!(ls, vals[1] / vals[2], 8)::Operation end elseif length(opparents) == 3 T = typeof(sum(vals)) if f === :vfmadd_fast return add_constant!(ls, T( (big(vals[1])*big(vals[2]) + big(vals[3]))), 8)::Operation elseif f === :vfnmadd_fast return add_constant!(ls, T(big(vals[3]) - big(vals[1])*big(vals[2])), 8)::Operation elseif f === :vfmsub_fast return add_constant!(ls, T((big(vals[1])*big(vals[2]) - big(vals[3]))), 8)::Operation elseif f === :vfnmsub_fast return add_constant!(ls, T(- (big(vals[1])*big(vals[2]) + big(vals[3]))), 8)::Operation end end end end opdef = callexpr(instr) mangledname = Symbol('#', instruction(op).instr, '#') while length(opparents) > 0 oppname = name(popfirst!(opparents)) mangledname = Symbol(mangledname, oppname, '#') push!(opdef.args, oppname) end op.mangledvariable = mangledname pushpreamble!(ls, Expr(:(=), name(op), opdef)) op.instruction = LOOPCONSTANT push!(ls.preamble_symsym, (identifier(op), name(op))) _pushop!(ls, op, var) end function _pushop!(ls::LoopSet, op::Operation, var::Symbol) for opp ∈ operations(ls) if matches(op, opp) ls.opdict[var] = opp return opp end end push!(ls.operations, op) ls.opdict[var] = op op end function pushop!(ls::LoopSet, op::Operation, var::Symbol = name(op)) if (iscompute(op) && length(loopdependencies(op)) == 0) add_constant_compute!(ls, op, var) else _pushop!(ls, op, var) end end function add_block!(ls::LoopSet, ex::Expr, elementbytes::Int, position::Int) for x ∈ ex.args x isa Expr || continue # be that general? x.head === :inbounds && continue push!(ls, x, elementbytes, position) end end function maybestatic!(expr::Expr) if expr.head === :call f = first(expr.args) if f === :length expr.args[1] = GlobalRef(ArrayInterface,:static_length) elseif f === :size && length(expr.args) == 3 i = expr.args[3] if i isa Integer expr.args[1] = GlobalRef(ArrayInterface,:size) expr.args[3] = staticexpr(convert(Int,i)::Int) end else static_literals!(expr) end end expr end add_loop_bound!(ls::LoopSet, itersym::Symbol, bound::Union{Integer,Symbol}, upper::Bool, step::Bool)::MaybeKnown = MaybeKnown(bound, upper ? 1024 : 1) function add_loop_bound!(ls::LoopSet, itersym::Symbol, bound::Expr, upper::Bool, step::Bool)::MaybeKnown maybestatic!(bound) N = gensym!(ls, string(itersym) * (upper ? "_loop_upper_bound" : (step ? "_loop_step" : "_loop_lower_bound"))) pushprepreamble!(ls, Expr(:(=), N, bound)) MaybeKnown(N, upper ? 1024 : 1) end static_literals!(s::Symbol) = s function static_literals!(q::Expr) for (i,ex) ∈ enumerate(q.args) if ex isa Number q.args[i] = staticexpr(ex) elseif ex isa Expr static_literals!(ex) end end q end function range_loop!(ls::LoopSet, itersym::Symbol, l::MaybeKnown, u::MaybeKnown, s::MaybeKnown) rangename = gensym!(ls, "range"); lenname = gensym!(ls, "length") range = Expr(:call, :(:)) pushexpr!(range, l) isone(s) || pushexpr!(range, s) pushexpr!(range, u) pushprepreamble!(ls, Expr(:(=), rangename, range)) pushprepreamble!(ls, Expr(:(=), lenname, Expr(:call, GlobalRef(ArrayInterface,:static_length), rangename))) Loop(itersym, l, u, s, rangename, lenname) end function range_loop!(ls::LoopSet, r::Expr, itersym::Symbol)::Loop lower = r.args[2] sii::Bool = if length(r.args) == 3 step = 1 upper = r.args[3] true elseif length(r.args) == 4 step = r.args[3] upper = r.args[4] isa(step, Integer) else throw("Literal ranges must have either 2 or 3 arguments.") end lii::Bool = lower isa Integer uii::Bool = upper isa Integer l::MaybeKnown = add_loop_bound!(ls, itersym, lower, false, false) u::MaybeKnown = add_loop_bound!(ls, itersym, upper, true, false) s::MaybeKnown = add_loop_bound!(ls, itersym, step, false, true) range_loop!(ls, itersym, l, u, s) end function oneto_loop!(ls::LoopSet, r::Expr, itersym::Symbol)::Loop otN = r.args[2] l = MaybeKnown(1, 0) s = MaybeKnown(1, 0) u::MaybeKnown = if otN isa Integer rangename = lensym = Symbol("") MaybeKnown(convert(Int, otN)::Int, 0) else otN isa Expr && maybestatic!(otN) lensym = N = gensym!(ls, "loop" * string(itersym)) rangename = gensym!(ls, "range"); pushprepreamble!(ls, Expr(:(=), N, otN)) pushprepreamble!(ls, Expr(:(=), rangename, Expr(:call, :(:), staticexpr(1), N))) MaybeKnown(N, 1024) end Loop(itersym, l, u, s, rangename, lensym) end @inline _reverse(r) = maybestaticlast(r):-static_step(r):maybestaticfirst(r) @inline canonicalize_range(r::OptionallyStaticUnitRange) = r @inline function canonicalize_range(r::OptionallyStaticRange, ::StaticInt{S}) where {S} ifelse(ArrayInterface.gt(StaticInt{S}(), Zero()), r, _reverse(r)) end @inline canonicalize_range(r::OptionallyStaticRange, s::Integer) = s > 0 ? r : _reverse(r) @inline canonicalize_range(r::CloseOpen) = r @inline canonicalize_range(r::AbstractUnitRange) = maybestaticfirst(r):maybestaticlast(r) @inline canonicalize_range(r::OptionallyStaticRange) = canonicalize_range(r, static_step(r)) @inline canonicalize_range(r::AbstractRange) = canonicalize_range(maybestaticfirst(r):static_step(r):maybestaticlast(r)) @inline canonicalize_range(r::CartesianIndices) = CartesianIndices(map(canonicalize_range, r.indices)) @inline canonicalize_range(r::Base.OneTo{U}) where {U <: Unsigned} = One():last(r) function misc_loop!(ls::LoopSet, r::Union{Expr,Symbol}, itersym::Symbol, staticstepone::Bool)::Loop rangename = gensym!(ls, "looprange" * string(itersym)); lenname = gensym!(ls, "looplen" * string(itersym)); pushprepreamble!(ls, Expr(:(=), rangename, Expr(:call, lv(:canonicalize_range), :(@inbounds $(static_literals!(r)))))) pushprepreamble!(ls, Expr(:(=), lenname, Expr(:call, GlobalRef(ArrayInterface,:static_length), rangename))) L = add_loop_bound!(ls, itersym, Expr(:call, lv(:maybestaticfirst), rangename), false, false) U = add_loop_bound!(ls, itersym, Expr(:call, lv(:maybestaticlast), rangename), true, false) if staticstepone Loop(itersym, L, U, MaybeKnown(1), rangename, lenname) else S = add_loop_bound!(ls, itersym, Expr(:call, lv(:static_step), rangename), false, true) Loop(itersym, L, U, S, rangename, lenname) end end function indices_loop!(ls::LoopSet, r::Expr, itersym::Symbol)::Loop if length(r.args) == 3 arrays = r.args[2] dims = r.args[3] if isexpr(arrays, :tuple) && length(arrays.args) > 1 && all(s -> s isa Symbol, arrays.args) narrays = length(arrays.args)::Int axessyms = Vector{Symbol}(undef, narrays) if dims isa Integer # ids = Vector{NTuple{2,Int}}(undef, narrays) vptrs = Vector{Symbol}(undef, narrays) mdims = fill(dims::Int, narrays) # _d::Int = dims for n ∈ 1:narrays a_s::Symbol = arrays.args[n] vptrs[n] = vptr(a_s) axessyms[n] = axsym = gensym!(ls, "#axes#$(a_s)#") pushprepreamble!(ls, Expr(:(=), axsym, Expr(:call, GlobalRef(ArrayInterface, :axes), a_s, staticexpr(dims::Int)))) if n > 1 axsym_prev = axessyms[n-1] pushprepreamble!(ls, Expr(:call, GlobalRef(VectorizationBase,:assume), Expr(:call, GlobalRef(Base,:(==)), Expr(:call, GlobalRef(ArrayInterface, :static_first), axsym), Expr(:call, GlobalRef(ArrayInterface, :static_first), axsym_prev)))) pushprepreamble!(ls, Expr(:call, GlobalRef(VectorizationBase,:assume), Expr(:call, GlobalRef(Base,:(==)), Expr(:call, GlobalRef(ArrayInterface, :static_last), axsym), Expr(:call, GlobalRef(ArrayInterface, :static_last), axsym_prev)))) end end push!(ls.equalarraydims, (vptrs, mdims)) elseif isexpr(dims, :tuple) && length(dims.args) == narrays && all(i -> i isa Integer, dims.args) # ids = Vector{NTuple{2,Int}}(undef, narrays) vptrs = Vector{Symbol}(undef, narrays) mdims = Vector{Int}(undef, narrays) axessyms = Vector{Symbol}(undef, narrays) for n ∈ 1:narrays a_s::Symbol = arrays.args[n] vptrs[n] = vptr(a_s) mdim::Int = dims.args[n] mdims[n] = mdim axessyms[n] = axsym = gensym!(ls, "#axes#$(a_s)#") pushprepreamble!(ls, Expr(:(=), axsym, Expr(:call, GlobalRef(ArrayInterface, :axes), a_s, staticexpr(mdim)))) if n > 1 axsym_prev = axessyms[n-1] pushprepreamble!(ls, Expr(:call, GlobalRef(VectorizationBase,:assume), Expr(:call, GlobalRef(Base,:(==)), Expr(:call, GlobalRef(ArrayInterface, :static_first), axsym), Expr(:call, GlobalRef(ArrayInterface, :static_first), axsym_prev)))) pushprepreamble!(ls, Expr(:call, GlobalRef(VectorizationBase,:assume), Expr(:call, GlobalRef(Base,:(==)), Expr(:call, GlobalRef(ArrayInterface, :static_last), axsym), Expr(:call, GlobalRef(ArrayInterface, :static_last), axsym_prev)))) end end push!(ls.equalarraydims, (vptrs, mdims)) # push!(ls.equalarraydims, ids) end end end misc_loop!(ls, r, itersym, true) end """ This function creates a loop, while switching from 1 to 0 based indices """ function register_single_loop!(ls::LoopSet, looprange::Expr) itersym = (looprange.args[1])::Symbol r = looprange.args[2] loop = if isexpr(r, :call) r = r::Expr # julia#37342 f = first(r.args) if f === :(:) range_loop!(ls, r, itersym) elseif f === :OneTo || isscopedname(f, :Base, :OneTo) oneto_loop!(ls, r, itersym) elseif f === :indices || (isexpr(f, :(.), 2) && (f.args[2] === QuoteNode(:indices)) && ((f.args[1] === :ArrayInterface) || (f.args[1] === :LoopVectorization))) indices_loop!(ls, r, itersym) else (f === :axes) && (r.args[1] = lv(:axes)) misc_loop!(ls, r, itersym, (f === :eachindex) | (f === :axes)) end elseif isa(r, Symbol) misc_loop!(ls, r, itersym, false) else throw(LoopError("Unrecognized loop range type: $r.")) end add_loop!(ls, loop, itersym) nothing end function register_loop!(ls::LoopSet, looprange::Expr) if looprange.head === :block # multiple loops for lr ∈ looprange.args register_single_loop!(ls, lr::Expr) end else @assert looprange.head === :(=) register_single_loop!(ls, looprange) end end function add_loop!(ls::LoopSet, q::Expr, elementbytes::Int) register_loop!(ls, q.args[1]::Expr) body = q.args[2]::Expr position = length(ls.loopsymbols) if body.head === :block add_block!(ls, body, elementbytes, position) else push!(ls, q, elementbytes, position) end end function add_loop!(ls::LoopSet, loop::Loop, itersym::Symbol = loop.itersymbol) push!(ls.loopsymbols, itersym) push!(ls.loops, loop) nothing end # function instruction(x) # x isa Symbol ? x : last(x.args).value # end # instruction(ls::LoopSet, f::Symbol) = instruction!(ls, f) function instruction!(ls::LoopSet, x::Expr) # x isa Symbol && return x if x.head === :$ _x = only(x.args) _x isa Symbol && return instruction!(ls, _x) @assert _x isa Expr x = _x end # if x.head ≢ :(->) instr = last(x.args).value instr ∈ keys(COST) && return Instruction(:LoopVectorization, instr) # end instr = gensym!(ls, "f") pushpreamble!(ls, Expr(:(=), instr, x)) Instruction(Symbol(""), instr) end instruction!(ls::LoopSet, x::Symbol) = instruction(x) function instruction!(ls::LoopSet, f::F) where {F <: Function} get(FUNCTIONSYMBOLS, F) do instr = gensym!(ls, "f") pushpreamble!(ls, Expr(:(=), instr, f)) Instruction(Symbol(""), instr) end end function maybe_const_compute!(ls::LoopSet, LHS::Symbol, op::Operation, elementbytes::Int, position::Int) # return op if iscompute(op) && iszero(length(loopdependencies(op))) ls.opdict[LHS] = add_constant!(ls, LHS, ls.loopsymbols[1:position], gensym!(ls, instruction(op).instr), elementbytes, :numericconstant) else # op.dependencies = ls.loopsymbols[1:position] op end end strip_op_linenumber_nodes(q::Expr) = only(filter(x -> !isa(x, LineNumberNode), q.args)) function add_operation!(ls::LoopSet, LHS::Symbol, RHS::Symbol, elementbytes::Int, position::Int) add_constant!(ls, RHS, ls.loopsymbols[1:position], LHS, elementbytes) end function add_comparison!(ls::LoopSet, LHS::Symbol, RHS::Expr, elementbytes::Int, position::Int) Nargs = length(RHS.args) @assert (Nargs ≥ 5) & isodd(Nargs) p1 = add_assignment!(ls, gensym!(ls, "leftcmp"), RHS.args[1], elementbytes, position)::Operation p2 = add_assignment!(ls, gensym!(ls, "middlecmp"), RHS.args[3], elementbytes, position)::Operation cmpname = Nargs == 3 ? LHS : gensym!(ls, "cmp") cmp = add_compute!(ls, cmpname, RHS.args[2], Operation[p1, p2], elementbytes)::Operation for i ∈ 5:2:Nargs pnew = add_assignment!(ls, gensym!(ls, "rightcmp"), RHS.args[i], elementbytes, position)::Operation cmpchain = add_compute!(ls, gensym!(ls, "cmpchain"), RHS.args[i-1], Operation[p2, pnew], elementbytes)::Operation cmpname = Nargs == i ? LHS : gensym!(ls, "cmp") cmp = add_compute!(ls, cmpname, :&, [cmp, cmpchain], elementbytes)::Operation p2 = pnew end return cmp end function add_operation!( ls::LoopSet, LHS::Symbol, RHS::Expr, elementbytes::Int, position::Int ) if RHS.head === :ref add_load_ref!(ls, LHS, RHS, elementbytes) elseif RHS.head === :call f = first(RHS.args) if f === :getindex add_load_getindex!(ls, LHS, RHS, elementbytes) elseif f isa Symbol && Base.sym_in(f, (:zero, :one, :typemin, :typemax)) c = gensym!(ls, f) op = add_constant!(ls, c, ls.loopsymbols[1:position], LHS, elementbytes, :numericconstant) if f === :zero push!(ls.preamble_zeros, (identifier(op), IntOrFloat)) else push!(ls.preamble_funcofeltypes, (identifier(op), reduction_zero_class(f))) end op else # maybe_const_compute!(ls, add_compute!(ls, LHS, RHS, elementbytes, position), elementbytes, position) add_compute!(ls, LHS, RHS, elementbytes, position) end elseif RHS.head === :if add_if!(ls, LHS, RHS, elementbytes, position) elseif RHS.head === :block add_operation!(ls, LHS, strip_op_linenumber_nodes(RHS), elementbytes, position) elseif RHS.head === :(.) c = gensym!(ls, "getproperty") pushpreamble!(ls, Expr(:(=), c, RHS)) add_constant!(ls, c, elementbytes) # op = add_constant!(ls, c, ls.loopsymbols[1:position], LHS, elementbytes, :numericconstant) # pushpreamble!(ls, op, c) # op elseif Meta.isexpr(RHS, :comparison) add_comparison!(ls, LHS, RHS, elementbytes, position) else throw(LoopError("Expression not recognized.", RHS)) end end add_operation!(ls::LoopSet, RHS::Expr, elementbytes::Int, position::Int) = add_operation!(ls, gensym!(ls, "LHS"), RHS, elementbytes, position) function add_operation!( ls::LoopSet, LHS_sym::Symbol, RHS::Expr, LHS_ref::ArrayReferenceMetaPosition, elementbytes::Int, position::Int ) if RHS.head === :ref# || (RHS.head === :call && first(RHS.args) === :getindex) array, rawindices = ref_from_expr!(ls, RHS) RHS_ref = array_reference_meta!(ls, array, rawindices, elementbytes, gensym!(ls, LHS_sym)) op = add_load!(ls, RHS_ref, elementbytes) iop = add_compute!(ls, LHS_sym, :identity, [op], elementbytes) # pushfirst!(LHS_ref.parents, iop) elseif RHS.head === :call f = first(RHS.args) if f === :getindex add_load!(ls, LHS_sym, LHS_ref, elementbytes) elseif f isa Symbol && Base.sym_in(f, (:zero, :one, :typemin, :typemax)) c = gensym!(ls, f) op = add_constant!(ls, c, ls.loopsymbols[1:position], LHS_sym, elementbytes, :numericconstant) # op = add_constant!(ls, c, Symbol[], LHS_sym, elementbytes, :numericconstant) if f === :zero push!(ls.preamble_zeros, (identifier(op), IntOrFloat)) else push!(ls.preamble_funcofeltypes, (identifier(op), reduction_zero_class(f))) end op else add_compute!(ls, LHS_sym, RHS, elementbytes, position, LHS_ref) end elseif RHS.head === :if add_if!(ls, LHS_sym, RHS, elementbytes, position, LHS_ref) elseif RHS.head === :block add_operation!(ls, LHS, strip_op_linenumber_nodes(RHS), elementbytes, position) elseif RHS.head === :(.) c = gensym!(ls, "getproperty") pushpreamble!(ls, Expr(:(=), c, RHS)) add_constant!(ls, c, elementbytes) # op = add_constant!(ls, c, ls.loopsymbols[1:position], LHS_sym, elementbytes, :numericconstant) # pushpreamble!(ls, op, c) # op elseif Meta.isexpr(RHS, :comparison, 5) add_comparison!(ls, LHS, RHS, elementbytes, position) else throw(LoopError("Expression not recognized.", RHS)) end end function prepare_rhs_for_storage!(ls::LoopSet, RHS::Union{Symbol,Expr}, array, rawindices, elementbytes::Int, position::Int)::Operation RHS isa Symbol && return add_store!(ls, RHS, array, rawindices, elementbytes) mpref = array_reference_meta!(ls, array, rawindices, elementbytes) cachedparents = copy(mpref.parents) ref = mpref.mref.ref lrhs = gensym!(ls, "RHS") mpref.varname = lrhs add_operation!(ls, lrhs, RHS, mpref, elementbytes, position) mpref.parents = cachedparents op = add_store!(ls, mpref, elementbytes) if lrhs ∈ keys(ls.opdict) ls.syms_aliasing_refs[findfirst(==(mpref.mref), ls.refs_aliasing_syms)] = lrhs end return op end function add_assignment!(ls::LoopSet, LHS, RHS, elementbytes::Int, position::Int) if LHS isa Symbol if RHS isa Expr maybe_const_compute!(ls, LHS, add_operation!(ls, LHS, RHS, elementbytes, position), elementbytes, position) else add_constant!(ls, RHS, ls.loopsymbols[1:position], LHS, elementbytes) end elseif LHS isa Expr if LHS.head === :ref if RHS isa Symbol add_store_ref!(ls, RHS, LHS, elementbytes) elseif RHS isa Expr # need to check if LHS appears in RHS # assign RHS to lrhs array, rawindices = ref_from_expr!(ls, LHS) prepare_rhs_for_storage!(ls, RHS, array, rawindices, elementbytes, position) else add_store_ref!(ls, RHS, LHS, elementbytes) # is this necessary? (Extension API?) end elseif LHS.head === :tuple if RHS.head === :tuple for i ∈ eachindex(LHS.args) add_assignment!(ls, LHS.args[i], RHS.args[i], elementbytes, position) end return last(operations(ls)) # FIXME: dummy end @assert length(LHS.args) ≤ 14 "Functions returning more than 9 values aren't currently supported." lhstemp = gensym!(ls, "lhstuple") vparents = Operation[maybe_const_compute!(ls, lhstemp, add_operation!(ls, lhstemp, RHS, elementbytes, position), elementbytes, position)] for i ∈ eachindex(LHS.args) f = (:first,:second,:third,:fourth,:fifth,:sixth,:seventh,:eighth,:ninth,:tenth,:eleventh,:twelfth,:thirteenth,:last)[i] lhsi = LHS.args[i] if lhsi isa Symbol add_compute!(ls, lhsi, f, vparents, elementbytes) elseif lhsi isa Expr && lhsi.head === :ref tempunpacksym = gensym!(ls, "tempunpack") add_compute!(ls, tempunpacksym, f, vparents, elementbytes) add_store_ref!(ls, tempunpacksym, lhsi, elementbytes) else throw(LoopError("Unpacking the above expression in the left hand side was not understood/supported.", lhsi)) end end first(vparents) else throw(LoopError("LHS not understood; only `:ref`s and `:tuple`s are currently supported.", LHS)) end else throw(LoopError("LHS not understood.", LHS)) end end function Base.push!(ls::LoopSet, ex::Expr, elementbytes::Int, position::Int, mpref::Union{Nothing,ArrayReferenceMetaPosition} = nothing) if ex.head === :call finex = first(ex.args)::Symbol if finex === :setindex! array, rawindices = ref_from_setindex!(ls, ex) prepare_rhs_for_storage!(ls, ex.args[3]::Union{Symbol,Expr}, array, rawindices, elementbytes, position) else error("Function $finex not recognized.") end elseif ex.head === :(=) add_assignment!(ls, ex.args[1], ex.args[2], elementbytes, position) elseif ex.head === :block add_block!(ls, ex, elementbytes, position) elseif ex.head === :for add_loop!(ls, ex, elementbytes) elseif ex.head === :&& add_andblock!(ls, ex, elementbytes, position) elseif ex.head === :|| add_orblock!(ls, ex, elementbytes, position) elseif ex.head === :local # Handle locals introduced by `@inbounds`; using `local` with `@turbo` is not recomended (nor is `@inbounds`; which applies automatically regardless) @assert length(ex.args) == 1 # TODO replace assert + first with "only" once support for Julia < 1.4 is dropped localbody = first(ex.args) @assert localbody.head === :(=) @assert length(localbody.args) == 2 LHS = (localbody.args[1])::Symbol RHS = push!(ls, (localbody.args[2]), elementbytes, position, mpref) if isstore(RHS) RHS else add_compute!(ls, LHS, :identity, [RHS], elementbytes) end else throw(LoopError("Don't know how to handle expression.", ex)) end end function UnrollSpecification(ls::LoopSet, u₁loop::Symbol, u₂loop::Symbol, vloopsym::Symbol, u₁, u₂) order = names(ls) nu₁ = findfirst(Base.Fix2(===,u₁loop), order)::Int nu₂ = u₂ == -1 ? nu₁ : findfirst(Base.Fix2(===,u₂loop), order)::Int nv = findfirst(Base.Fix2(===,vloopsym), order)::Int UnrollSpecification(nu₁, nu₂, nv, u₁, u₂) end """ looplengthprod(ls::LoopSet) Convert to `Float64` for the sake of non-64 bit platforms. """ function looplengthprod(ls::LoopSet) l = 1.0 for loop ∈ ls.loops l *= Float64(length(loop)) end l end # prod(Float64 ∘ length, ls.loops) function looplength(ls::LoopSet, s::Symbol) # search_tree(parents(operations(ls)[i]), name(op)) && return true id = getloopid_or_nothing(ls, s) if id === nothing l = 0.0 # TODO: we could double count a loop. for op ∈ operations(ls) name(op) === s || continue for opp ∈ parents(op) if isloopvalue(opp) oppname = first(loopdependencies(opp)) l += looplength(ls, oppname) elseif iscompute(opp) oppname = name(opp) l += looplength(ls, oppname) # TODO elseif isconstant(opp) end end l += 1 - length(parents(op)) end l else Float64(length(ls.loops[id])) end end function accept_reorder_according_to_tracked_reductions(ls::LoopSet, reordered::Symbol) for op ∈ operations(ls) if reordered ∈ loopdependencies(op) for opp ∈ parents(op) (iscompute(opp) && isanouterreduction(ls, opp)) && return 0x00 end end end 0x03 end function check_valid_reorder_dims!(ls::LoopSet) validreorder = ls.validreorder resize!(validreorder, num_loops(ls)) fill!(validreorder, 0x03) omop = offsetloadcollection(ls) @unpack opids = omop num_collections = length(opids) ops = operations(ls) for i ∈ eachindex(opids) opidsᵢ = opids[i] opi = ops[first(opidsᵢ)] opiref = opi.ref.ref isl = isload(opi) for j ∈ 1:i-1 opidsⱼ = opids[j] opj = ops[first(opidsⱼ)] (isl ⊻ isload(opj)) || continue # try and find load/store combo opjref = opj.ref.ref sameref(opiref, opjref) || continue # possible they have shared offsets in certain directions for k ∈ eachindex(ls.loops) validreorder[k] == 0x03 || continue# if already demoted, don't need to check again loopk = ls.loops[k] itersym = loopk.itersymbol for (l,isym) ∈ enumerate(getindicesonly(opi)) isym === itersym || continue # we match, now we check if this load is offset # we'll require all offsets in this index be equal, across both loads and stores firstoff = opiref.offsets[l] maxdiff = max(checkmismatch(ops, opidsᵢ, l, firstoff, 2:length(opidsᵢ)), checkmismatch(ops, opidsⱼ, l, firstoff, 1:length(opidsⱼ))) if maxdiff ≥ (isknown(step(loopk)) ? abs(gethint(step(loopk))) : 1) validreorder[k] = 0x00#0x01 end end end end end length(ls.outer_reductions) == 0 && return for i ∈ eachindex(validreorder) validreorder[i] &= accept_reorder_according_to_tracked_reductions(ls, ls.loops[i].itersymbol) end end function checkmismatch(ops::Vector{Operation}, opids::Vector{Int}, l::Int, firstoff::Int8, checkrange::UnitRange{Int}) maxabsdiff = 0 for m ∈ checkrange diff = ops[opids[m]].ref.ref.offsets[l] - firstoff maxabsdiff = max(maxabsdiff, abs(diff%Int)) end return maxabsdiff end offsetloadcollection(ls::LoopSet) = ls.omop function fill_offset_memop_collection!(ls::LoopSet) omop = offsetloadcollection(ls) ops = operations(ls) num_ops = length(ops) @unpack opids, opidcollectionmap, batchedcollections, batchedcollectionmap = omop length(opidcollectionmap) == 0 || return resize!(opidcollectionmap, num_ops) fill!(opidcollectionmap, (0,0)); resize!(batchedcollectionmap, num_ops) fill!(batchedcollectionmap, (0,0)) empty!(opids);# empty!(offsets); for i ∈ 1:num_ops op = ops[i] isconditionalmemop(op) && continue # not supported yet opref = op.ref.ref opisload = isload(op) (opisload | isstore(op)) || continue opidcollectionmap[i] === (0,0) || continue # if not -1, we already handled isdiscontiguous(op) && continue collectionsize = 0 for j ∈ i+1:num_ops opp = ops[j] isconditionalmemop(opp) && continue # not supported yet if opisload # Each collection is either entirely loads or entirely stores isload(opp) || continue else isstore(opp) || continue end oppref = opp.ref.ref sameref(opref, oppref) || continue if collectionsize == 0 push!(opids, [identifier(op), identifier(opp)]) # push!(offsets, [opref.offsets, oppref.offsets]) opidcollectionmap[identifier(op)] = (length(opids),1) else push!(last(opids), identifier(opp)) # push!(last(offsets), oppref.offsets) end opidcollectionmap[identifier(opp)] = (length(opids),length(last(opids))) collectionsize += 1 end end for (collectionid,opidc) ∈ enumerate(opids) length(opidc) > 1 || continue # we check if we can turn the offsets into an unroll # we have up to `length(opidc)` loads to do, so we allocate that many "base" vectors # then we iterate through them, adding them to collections as appropriate # inner vector tuple is of (op_pos_w/in collection,o) unroll_collections = Vector{Vector{Tuple{Int,Int}}}(undef, length(opidc)) num_unroll_collections = 0 # num_ops_considered = length(opidc) r = 2:length(getindices(ops[first(opidc)])) for (i,opid) ∈ enumerate(opidc) op = ops[opid] offset = getoffsets(op) o = offset[1] v = view(offset, r) found_match = false for j ∈ 1:num_unroll_collections collectionⱼ = unroll_collections[j] # giet id (`first`) of first item in collection to get base offsets for comparison if view(getoffsets(ops[opidc[first(first(collectionⱼ))]]), r) == v found_match = true push!(collectionⱼ, (i, o)) end end if !found_match num_unroll_collections += 1 # the `i` points to position within `opidc` unroll_collections[num_unroll_collections] = [(i,o)] end end for j ∈ 1:num_unroll_collections collectionⱼ = unroll_collections[j] collen = length(collectionⱼ) collen ≤ 1 && continue # we have multiple, easiest to process if we sort them sort!(collectionⱼ, by=last) istart = 1; ostart = last(first(collectionⱼ)) oprev = ostart for i ∈ 2:collen onext = last(collectionⱼ[i]) if onext == oprev + 1 oprev = onext continue end # we skipped one, so we must now lower all previous if oprev ≠ ostart # it's just 1 pushbatchedcollection!(batchedcollections, batchedcollectionmap, opidc, ops, collectionⱼ, istart, i-1) end # restart istart and ostart istart = i ostart = onext oprev = onext end if istart ≠ collen pushbatchedcollection!(batchedcollections, batchedcollectionmap, opidc, ops, collectionⱼ, istart, collen) end end end check_valid_reorder_dims!(ls) end function pushbatchedcollection!(batchedcollections, batchedcollectionmap, opidc, ops, collectionⱼ, istart, istop) colview = view(collectionⱼ, istart:istop) push!(batchedcollections, colview) bclen = length(batchedcollections) for (i,(k,_)) ∈ enumerate(colview) # batchedcollectionmap[identifier(op)] gives index into `batchedcollections` containing `colview` batchedcollectionmap[identifier(ops[opidc[k]])] = (bclen,i) end end """ Returns `0` if the op is the declaration of the constant outerreduction variable. Returns `n`, where `n` is the constant declarations's index among parents(op), if op is an outter reduction. Returns `-1` if not an outerreduction. """ function isouterreduction(ls::LoopSet, op::Operation) if isconstant(op) # equivalent to checking if length(loopdependencies(op)) == 0 instr = op.instruction instr == LOOPCONSTANT && return Core.ifelse(length(loopdependencies(op)) == 0, 0, -1) instr.mod === GLOBALCONSTANT && return -1 ops = operations(ls) for or ∈ ls.outer_reductions name(op) === name(ops[or]) && return 0 end -1 elseif iscompute(op) var = op.variable for opid ∈ ls.outer_reductions rop = operations(ls)[opid] if rop === op for (n,opp) ∈ enumerate(parents(op)) opp.variable === var && return n end else for (n,opp) ∈ enumerate(parents(op)) opp === rop && return n search_tree(parents(opp), rop.variable) && return n end end end -1 else -1 end end struct LoopError <: Exception msg ex LoopError(msg, ex=nothing) = new(msg, ex) end function Base.showerror(io::IO, err::LoopError) printstyled(io, err.msg; color = :red) err.ex === nothing || printstyled(io, '\n', err.ex) end
function cc_avg(x::Neuro1DRealSignal; channels::Union{Vector{Int64}, Nothing} = nothing)::Neuro1DRealSignal if (channels == nothing) return cc_avg(x, channels = [1:1:size(x.signal)[2];]) end Neuro1DRealSignal( signal = Statistics.mean(x.signal[:, channels]; dims = 2), sample_rate = x.sample_rate ) end
# License for module ModiaMath.Logging: MIT # Copyright 2017-2018, DLR Institute of System Dynamics and Control """ module ModiaMath.Logger Log model evaluations. # Main developer Martin Otter, [DLR - Institute of System Dynamics and Control](https://www.dlr.de/sr/en) """ module Logging @eval using Printf import ..TypesAndStructs: Logger, SimulationStatistics export setLog!, setAllLogCategories!, setLogCategories! export isLogStatistics, isLogProgress, isLogInfos, isLogWarnings, isLogEvents export logOn!, logOff!, setLogCategories export reInitializeStatistics!, set_nResultsForSimulationStatistics! function setLog!(logger::Logger, log::Bool) logger.log = log return nothing end function setAllLogCategories!(logger::Logger; default=true) logger.statistics = default logger.progress = default logger.infos = default logger.warnings = default logger.events = default end """ ModiaMath.setLogCategories!(obj, categories; reinit=true) Set log categories on obj (of type ModiaMath.SimulationState, ModiaMath.AbstractSimulationModel, or ModiaMath.Logger) as vector of symbols, e.g. setLogCategories!(simulationModel, [:LogProgess]). Supported categories: - `:LogStatistics`, print statistics information at end of simulation - `:LogProgress`, print progress information during simulation - `:LogInfos`, print information messages of the model - `:LogWarnings`, print warning messages of the model - `:LogEvents`, log events of the model If option reinit=true, all previous set categories are reinitialized to be no longer present. If reinit=false, previously set categories are not changed. """ function setLogCategories!(logger::Logger, categories::Vector{Symbol}; reinit=true) if reinit setAllLogCategories!(logger;default=false) end for c in categories if c == :LogStatistics logger.statistics = true elseif c == :LogProgress logger.progress = true elseif c == :LogInfos logger.infos = true elseif c == :LogWarnings logger.warnings = true elseif c == :LogEvents logger.events = true else warning("Log categorie ", c, " not known (will be ignored)") end end return nothing end """ ModiaMath.logOn!(obj) Enable logging on `obj` (of type ModiaMath.SimulationState, ModiaMath.AbstractSimulationModel, or ModiaMath.Logger) """ function logOn!(logger::Logger) logger.log = true return nothing end """ ModiaMath.logOff!(obj) Disable logging on `obj` (of type ModiaMath.SimulationState, ModiaMath.AbstractSimulationModel, or ModiaMath.Logger) """ function logOff!(logger::Logger) logger.log = false return nothing end """ ModiaMath.isLogStatistics(logger::ModiaMath.Logger) Return true, if logger settings require to print **statistics** messages of the model. """ isLogStatistics(logger::Logger) = logger.log && logger.statistics """ ModiaMath.isLogProgress(logger::ModiaMath.Logger) Return true, if logger settings require to print **progress** messages of the model """ isLogProgress(logger::Logger) = logger.log && logger.progress """ ModiaMath.isLogInfos(obj) Return true, if logger settings require to print **info** messages of the model (obj must be of type ModiaMath.SimulationState, ModiaMath.AbstractSimulationModel, or ModiaMath.Logger). """ isLogInfos(logger::Logger) = logger.log && logger.infos """ ModiaMath.isLogWarnings(obj) Return true, if logger settings require to print **warning** messages of the model (obj must be of type ModiaMath.SimulationState, ModiaMath.AbstractSimulationModel, or ModiaMath.Logger). """ isLogWarnings(logger::Logger) = logger.log && logger.warnings """ ModiaMath.isLogEvents(obj) Return true, if logger settings require to print **event** messages of the model (obj must be of type ModiaMath.SimulationState, ModiaMath.AbstractSimulationModel, or ModiaMath.Logger). """ isLogEvents(logger::Logger) = logger.log && logger.events function reInitializeStatistics!(stat::SimulationStatistics, startTime::Float64, stopTime::Float64, interval::Float64, tolerance::Float64) stat.cpuTimeInitialization = 0.0 stat.cpuTimeIntegration = 0.0 stat.startTime = startTime stat.stopTime = stopTime stat.interval = interval stat.tolerance = tolerance stat.nResults = 0 stat.nSteps = 0 stat.nResidues = 0 stat.nZeroCrossings = 0 stat.nJac = 0 stat.nTimeEvents = 0 stat.nStateEvents = 0 stat.nRestartEvents = 0 stat.nErrTestFails = 0 stat.h0 = floatmax(Float64) stat.hMin = floatmax(Float64) stat.hMax = 0.0 stat.orderMax = 0 end import Base.show Base.print(io::IO, stat::SimulationStatistics) = show(io, stat) function Base.show(io::IO, stat::SimulationStatistics) println(io, " structureOfDAE = ", stat.structureOfDAE) @printf(io, " cpuTime = %.2g s (init: %.2g s, integration: %.2g s)\n", stat.cpuTimeInitialization + stat.cpuTimeIntegration, stat.cpuTimeInitialization, stat.cpuTimeIntegration) println(io, " startTime = ", stat.startTime, " s") println(io, " stopTime = ", stat.stopTime, " s") println(io, " interval = ", stat.interval, " s") println(io, " tolerance = ", stat.tolerance) println(io, " nEquations = ", stat.nEquations, typeof(stat.nConstraints)!=Missing ? " (includes " * string(stat.nConstraints) * " constraints)" : "" ) println(io, " nResults = ", stat.nResults) println(io, " nSteps = ", stat.nSteps) println(io, " nResidues = ", stat.nResidues, " (includes residue calls for Jacobian)") println(io, " nZeroCrossings = ", stat.nZeroCrossings) println(io, " nJac = ", stat.nJac) println(io, " nTimeEvents = ", stat.nTimeEvents) println(io, " nStateEvents = ", stat.nStateEvents) println(io, " nRestartEvents = ", stat.nRestartEvents) println(io, " nErrTestFails = ", stat.nErrTestFails) @printf(io, " h0 = %.2g s\n", stat.h0) @printf(io, " hMin = %.2g s\n", stat.hMin) @printf(io, " hMax = %.2g s\n", stat.hMax) println(io, " orderMax = ", stat.orderMax) println(io, " sparseSolver = ", stat.sparseSolver) if stat.sparseSolver println(io, " nGroups = ", stat.nGroups) end end function set_nResultsForSimulationStatistics!(stat::SimulationStatistics, nt::Int) stat.nResults = nt return nothing end end
const _allAxes = [:auto, :left, :right] @compat const _axesAliases = KW( :a => :auto, :l => :left, :r => :right ) const _3dTypes = [:path3d, :scatter3d, :surface, :wireframe, :contour3d] const _allTypes = vcat([ :none, :line, :path, :steppre, :steppost, :sticks, :scatter, :heatmap, :hexbin, :hist, :hist2d, :hist3d, :density, :bar, :hline, :vline, :ohlc, :contour, :pie, :shape, :box, :violin, :quiver, :image ], _3dTypes) @compat const _typeAliases = KW( :n => :none, :no => :none, :l => :line, :p => :path, :stepinv => :steppre, :stepsinv => :steppre, :stepinverted => :steppre, :stepsinverted => :steppre, :step => :steppost, :steps => :steppost, :stair => :steppost, :stairs => :steppost, :stem => :sticks, :stems => :sticks, :dots => :scatter, :histogram => :hist, :pdf => :density, :contours => :contour, :line3d => :path3d, :surf => :surface, :wire => :wireframe, :shapes => :shape, :poly => :shape, :polygon => :shape, :boxplot => :box, :velocity => :quiver, :gradient => :quiver, :img => :image, :imshow => :image, :imagesc => :image, ) like_histogram(linetype::Symbol) = linetype in (:hist, :density) like_line(linetype::Symbol) = linetype in (:line, :path, :steppre, :steppost) like_surface(linetype::Symbol) = linetype in (:contour, :contour3d, :heatmap, :surface, :wireframe, :image) is3d(linetype::Symbol) = linetype in _3dTypes is3d(d::KW) = trueOrAllTrue(is3d, d[:linetype]) const _allStyles = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot] @compat const _styleAliases = KW( :a => :auto, :s => :solid, :d => :dash, :dd => :dashdot, :ddd => :dashdotdot, ) # const _allMarkers = [:none, :auto, :ellipse, :rect, :diamond, :utriangle, :dtriangle, # :cross, :xcross, :star5, :star8, :hexagon, :octagon, Shape] const _allMarkers = vcat(:none, :auto, sort(collect(keys(_shapes)))) @compat const _markerAliases = KW( :n => :none, :no => :none, :a => :auto, :circle => :ellipse, :c => :ellipse, :square => :rect, :sq => :rect, :r => :rect, :d => :diamond, :^ => :utriangle, :ut => :utriangle, :utri => :utriangle, :uptri => :utriangle, :uptriangle => :utriangle, :v => :dtriangle, :V => :dtriangle, :dt => :dtriangle, :dtri => :dtriangle, :downtri => :dtriangle, :downtriangle => :dtriangle, :+ => :cross, :plus => :cross, :x => :xcross, :X => :xcross, :star => :star5, :s => :star5, :star1 => :star5, :s2 => :star8, :star2 => :star8, :p => :pentagon, :pent => :pentagon, :h => :hexagon, :hex => :hexagon, :hep => :heptagon, :o => :octagon, :oct => :octagon, :spike => :vline, ) const _allScales = [:identity, :ln, :log2, :log10, :asinh, :sqrt] @compat const _scaleAliases = KW( :none => :identity, :log => :log10, ) # ----------------------------------------------------------------------------- const _seriesDefaults = KW() # series-specific _seriesDefaults[:axis] = :left _seriesDefaults[:label] = "AUTO" _seriesDefaults[:seriescolor] = :auto _seriesDefaults[:seriesalpha] = nothing _seriesDefaults[:linetype] = :path _seriesDefaults[:linestyle] = :solid _seriesDefaults[:linewidth] = :auto _seriesDefaults[:linecolor] = :match _seriesDefaults[:linealpha] = nothing _seriesDefaults[:fillrange] = nothing # ribbons, areas, etc _seriesDefaults[:fillcolor] = :match _seriesDefaults[:fillalpha] = nothing _seriesDefaults[:markershape] = :none _seriesDefaults[:markercolor] = :match _seriesDefaults[:markeralpha] = nothing _seriesDefaults[:markersize] = 6 _seriesDefaults[:markerstrokestyle] = :solid _seriesDefaults[:markerstrokewidth] = 1 _seriesDefaults[:markerstrokecolor] = :match _seriesDefaults[:markerstrokealpha] = nothing _seriesDefaults[:bins] = 30 # number of bins for hists _seriesDefaults[:smooth] = false # regression line? _seriesDefaults[:group] = nothing # groupby vector _seriesDefaults[:x] = nothing _seriesDefaults[:y] = nothing _seriesDefaults[:z] = nothing # depth for contour, surface, etc _seriesDefaults[:marker_z] = nothing # value for color scale _seriesDefaults[:levels] = 15 _seriesDefaults[:orientation] = :vertical _seriesDefaults[:bar_position] = :overlay # for bar plots and histograms: could also be stack (stack up) or dodge (side by side) _seriesDefaults[:xerror] = nothing _seriesDefaults[:yerror] = nothing _seriesDefaults[:ribbon] = nothing _seriesDefaults[:quiver] = nothing _seriesDefaults[:normalize] = false # do we want a normalized histogram? _seriesDefaults[:weights] = nothing # optional weights for histograms (1D and 2D) _seriesDefaults[:contours] = false # add contours to 3d surface and wireframe plots _seriesDefaults[:match_dimensions] = false # do rows match x (true) or y (false) for heatmap/image/spy? see issue 196 const _plotDefaults = KW() # plot globals _plotDefaults[:title] = "" _plotDefaults[:xlabel] = "" _plotDefaults[:ylabel] = "" _plotDefaults[:zlabel] = "" _plotDefaults[:yrightlabel] = "" _plotDefaults[:legend] = :best _plotDefaults[:colorbar] = :legend _plotDefaults[:background_color] = colorant"white" # default for all backgrounds _plotDefaults[:background_color_legend] = :match # background of legend _plotDefaults[:background_color_inside] = :match # background inside grid _plotDefaults[:background_color_outside] = :match # background outside grid _plotDefaults[:foreground_color] = :auto # default for all foregrounds _plotDefaults[:foreground_color_legend] = :match # foreground of legend _plotDefaults[:foreground_color_grid] = :match # grid color _plotDefaults[:foreground_color_axis] = :match # axis border/tick colors _plotDefaults[:foreground_color_border] = :match # plot area border/spines _plotDefaults[:foreground_color_text] = :match # tick text color _plotDefaults[:foreground_color_guide] = :match # guide text color _plotDefaults[:xlims] = :auto _plotDefaults[:ylims] = :auto _plotDefaults[:zlims] = :auto _plotDefaults[:xticks] = :auto _plotDefaults[:yticks] = :auto _plotDefaults[:zticks] = :auto _plotDefaults[:xscale] = :identity _plotDefaults[:yscale] = :identity _plotDefaults[:zscale] = :identity _plotDefaults[:xrotation] = 0 _plotDefaults[:yrotation] = 0 _plotDefaults[:zrotation] = 0 _plotDefaults[:xflip] = false _plotDefaults[:yflip] = false _plotDefaults[:zflip] = false _plotDefaults[:size] = (600,400) _plotDefaults[:pos] = (0,0) _plotDefaults[:windowtitle] = "Plots.jl" _plotDefaults[:show] = false _plotDefaults[:layout] = nothing _plotDefaults[:n] = -1 _plotDefaults[:nr] = -1 _plotDefaults[:nc] = -1 _plotDefaults[:color_palette] = :auto _plotDefaults[:link] = false _plotDefaults[:linkx] = false _plotDefaults[:linky] = false _plotDefaults[:linkfunc] = nothing _plotDefaults[:tickfont] = font(8) _plotDefaults[:guidefont] = font(11) _plotDefaults[:legendfont] = font(8) _plotDefaults[:grid] = true _plotDefaults[:annotation] = nothing # annotation tuple(s)... (x,y,annotation) _plotDefaults[:overwrite_figure] = false _plotDefaults[:polar] = false _plotDefaults[:aspect_ratio] = :none # choose from :none or :equal # TODO: x/y scales const _allArgs = sort(collect(union(keys(_seriesDefaults), keys(_plotDefaults)))) supportedArgs(::AbstractBackend) = error("supportedArgs not defined") #_allArgs supportedArgs() = supportedArgs(backend()) RecipesBase.is_key_supported(k::Symbol) = (k in supportedArgs()) # ----------------------------------------------------------------------------- makeplural(s::Symbol) = symbol(string(s,"s")) autopick(arr::AVec, idx::Integer) = arr[mod1(idx,length(arr))] autopick(notarr, idx::Integer) = notarr autopick_ignore_none_auto(arr::AVec, idx::Integer) = autopick(setdiff(arr, [:none, :auto]), idx) autopick_ignore_none_auto(notarr, idx::Integer) = notarr function aliasesAndAutopick(d::KW, sym::Symbol, aliases::KW, options::AVec, plotIndex::Int) if d[sym] == :auto d[sym] = autopick_ignore_none_auto(options, plotIndex) elseif haskey(aliases, d[sym]) d[sym] = aliases[d[sym]] end end function aliases(aliasMap::KW, val) sortedkeys(filter((k,v)-> v==val, aliasMap)) end # ----------------------------------------------------------------------------- const _keyAliases = KW() function add_aliases(sym::Symbol, aliases::Symbol...) for alias in aliases if haskey(_keyAliases, alias) error("Already an alias $alias => $(_keyAliases[alias])... can't also alias $sym") end _keyAliases[alias] = sym end end # colors add_aliases(:seriescolor, :c, :color, :colour) add_aliases(:linecolor, :lc, :lcolor, :lcolour, :linecolour) add_aliases(:markercolor, :mc, :mcolor, :mcolour, :markercolour) add_aliases(:markerstokecolor, :msc, :mscolor, :mscolour, :markerstokecolour) add_aliases(:fillcolor, :fc, :fcolor, :fcolour, :fillcolour) add_aliases(:background_color, :bg, :bgcolor, :bg_color, :background, :background_colour, :bgcolour, :bg_colour) add_aliases(:background_color_legend, :bg_legend, :bglegend, :bgcolor_legend, :bg_color_legend, :background_legend, :background_colour_legend, :bgcolour_legend, :bg_colour_legend) add_aliases(:background_color_inside, :bg_inside, :bginside, :bgcolor_inside, :bg_color_inside, :background_inside, :background_colour_inside, :bgcolour_inside, :bg_colour_inside) add_aliases(:background_color_outside, :bg_outside, :bgoutside, :bgcolor_outside, :bg_color_outside, :background_outside, :background_colour_outside, :bgcolour_outside, :bg_colour_outside) add_aliases(:foreground_color, :fg, :fgcolor, :fg_color, :foreground, :foreground_colour, :fgcolour, :fg_colour) add_aliases(:foreground_color_legend, :fg_legend, :fglegend, :fgcolor_legend, :fg_color_legend, :foreground_legend, :foreground_colour_legend, :fgcolour_legend, :fg_colour_legend) add_aliases(:foreground_color_grid, :fg_grid, :fggrid, :fgcolor_grid, :fg_color_grid, :foreground_grid, :foreground_colour_grid, :fgcolour_grid, :fg_colour_grid, :gridcolor) add_aliases(:foreground_color_axis, :fg_axis, :fgaxis, :fgcolor_axis, :fg_color_axis, :foreground_axis, :foreground_colour_axis, :fgcolour_axis, :fg_colour_axis, :axiscolor) add_aliases(:foreground_color_border, :fg_border, :fgborder, :fgcolor_border, :fg_color_border, :foreground_border, :foreground_colour_border, :fgcolour_border, :fg_colour_border, :bordercolor, :border) add_aliases(:foreground_color_text, :fg_text, :fgtext, :fgcolor_text, :fg_color_text, :foreground_text, :foreground_colour_text, :fgcolour_text, :fg_colour_text, :textcolor) add_aliases(:foreground_color_guide, :fg_guide, :fgguide, :fgcolor_guide, :fg_color_guide, :foreground_guide, :foreground_colour_guide, :fgcolour_guide, :fg_colour_guide, :guidecolor) # alphas add_aliases(:seriesalpha, :alpha, :α, :opacity) add_aliases(:linealpha, :la, :lalpha, :lα, :lineopacity, :lopacity) add_aliases(:makeralpha, :ma, :malpha, :mα, :makeropacity, :mopacity) add_aliases(:markerstrokealpha, :msa, :msalpha, :msα, :markerstrokeopacity, :msopacity) add_aliases(:fillalpha, :fa, :falpha, :fα, :fillopacity, :fopacity) add_aliases(:label, :lab) add_aliases(:line, :l) add_aliases(:linewidth, :w, :width, :lw) add_aliases(:linetype, :lt, :t, :seriestype) add_aliases(:linestyle, :style, :s, :ls) add_aliases(:marker, :m, :mark) add_aliases(:markershape, :shape) add_aliases(:markersize, :ms, :msize) add_aliases(:marker_z, :markerz, :zcolor) add_aliases(:fill, :f, :area) add_aliases(:fillrange, :fillrng, :frange, :fillto, :fill_between) add_aliases(:group, :g, :grouping) add_aliases(:bins, :bin, :nbin, :nbins, :nb) add_aliases(:ribbon, :rib) add_aliases(:annotation, :ann, :anns, :annotate, :annotations) add_aliases(:xlabel, :xlab, :xl) add_aliases(:xlims, :xlim, :xlimit, :xlimits) add_aliases(:xticks, :xtick) add_aliases(:xrotation, :xrot, :xr) add_aliases(:ylabel, :ylab, :yl) add_aliases(:ylims, :ylim, :ylimit, :ylimits) add_aliases(:yticks, :ytick) add_aliases(:yrightlabel, :yrlab, :yrl, :ylabel2, :y2label, :ylab2, :y2lab, :ylabr, :ylabelright) add_aliases(:yrightlims, :yrlim, :yrlimit, :yrlimits) add_aliases(:yrightticks, :yrtick) add_aliases(:yrotation, :yrot, :yr) add_aliases(:zlabel, :zlab, :zl) add_aliases(:zlims, :zlim, :zlimit, :zlimits) add_aliases(:zticks, :ztick) add_aliases(:zrotation, :zrot, :zr) add_aliases(:legend, :leg, :key) add_aliases(:colorbar, :cb, :cbar, :colorkey) add_aliases(:smooth, :regression, :reg) add_aliases(:levels, :nlevels, :nlev, :levs) add_aliases(:size, :windowsize, :wsize) add_aliases(:windowtitle, :wtitle) add_aliases(:show, :gui, :display) add_aliases(:color_palette, :palette) add_aliases(:linkx, :xlink) add_aliases(:linky, :ylink) add_aliases(:nr, :nrow, :nrows, :rows) add_aliases(:nc, :ncol, :ncols, :cols, :ncolumns, :columns) add_aliases(:overwrite_figure, :clf, :clearfig, :overwrite, :reuse) add_aliases(:xerror, :xerr, :xerrorbar) add_aliases(:yerror, :yerr, :yerrorbar, :err, :errorbar) add_aliases(:quiver, :velocity, :quiver2d, :gradient) add_aliases(:normalize, :norm, :normed, :normalized) add_aliases(:aspect_ratio, :aspectratio, :axis_ratio, :axisratio, :ratio) # add all pluralized forms to the _keyAliases dict for arg in keys(_seriesDefaults) _keyAliases[makeplural(arg)] = arg end # ----------------------------------------------------------------------------- # update the defaults globally """ `default(key)` returns the current default value for that key `default(key, value)` sets the current default value for that key `default(; kw...)` will set the current default value for each key/value pair """ function default(k::Symbol) k = get(_keyAliases, k, k) if haskey(_seriesDefaults, k) return _seriesDefaults[k] elseif haskey(_plotDefaults, k) return _plotDefaults[k] else error("Unknown key: ", k) end end function default(k::Symbol, v) k = get(_keyAliases, k, k) if haskey(_seriesDefaults, k) _seriesDefaults[k] = v elseif haskey(_plotDefaults, k) _plotDefaults[k] = v else error("Unknown key: ", k) end end function default(; kw...) for (k,v) in kw default(k, v) end end # ----------------------------------------------------------------------------- # if arg is a valid color value, then set d[csym] and return true function handleColors!(d::KW, arg, csym::Symbol) try if arg == :auto d[csym] = :auto else c = colorscheme(arg) d[csym] = c end return true end false end # given one value (:log, or :flip, or (-1,1), etc), set the appropriate arg # TODO: use trueOrAllTrue for subplots which can pass vectors for these function processAxisArg(d::KW, letter::AbstractString, arg) T = typeof(arg) arg = get(_scaleAliases, arg, arg) scale, flip, label, lim, tick = axis_symbols(letter, "scale", "flip", "label", "lims", "ticks") if typeof(arg) <: Font d[:tickfont] = arg elseif arg in _allScales d[scale] = arg elseif arg in (:flip, :invert, :inverted) d[flip] = true elseif T <: @compat(AbstractString) d[label] = arg # xlims/ylims elseif (T <: Tuple || T <: AVec) && length(arg) == 2 d[typeof(arg[1]) <: Number ? lim : tick] = arg # xticks/yticks elseif T <: AVec d[tick] = arg elseif arg == nothing d[tick] = [] else warn("Skipped $(letter)axis arg $arg") end end function processLineArg(d::KW, arg) # linetype if allLineTypes(arg) d[:linetype] = arg # linestyle elseif allStyles(arg) d[:linestyle] = arg elseif typeof(arg) <: Stroke arg.width == nothing || (d[:linewidth] = arg.width) arg.color == nothing || (d[:linecolor] = arg.color == :auto ? :auto : colorscheme(arg.color)) arg.alpha == nothing || (d[:linealpha] = arg.alpha) arg.style == nothing || (d[:linestyle] = arg.style) elseif typeof(arg) <: Brush arg.size == nothing || (d[:fillrange] = arg.size) arg.color == nothing || (d[:fillcolor] = arg.color == :auto ? :auto : colorscheme(arg.color)) arg.alpha == nothing || (d[:fillalpha] = arg.alpha) # linealpha elseif allAlphas(arg) d[:linealpha] = arg # linewidth elseif allReals(arg) d[:linewidth] = arg # color elseif !handleColors!(d, arg, :linecolor) warn("Skipped line arg $arg.") end end function processMarkerArg(d::KW, arg) # markershape if allShapes(arg) d[:markershape] = arg # stroke style elseif allStyles(arg) d[:markerstrokestyle] = arg elseif typeof(arg) <: Stroke arg.width == nothing || (d[:markerstrokewidth] = arg.width) arg.color == nothing || (d[:markerstrokecolor] = arg.color == :auto ? :auto : colorscheme(arg.color)) arg.alpha == nothing || (d[:markerstrokealpha] = arg.alpha) arg.style == nothing || (d[:markerstrokestyle] = arg.style) elseif typeof(arg) <: Brush arg.size == nothing || (d[:markersize] = arg.size) arg.color == nothing || (d[:markercolor] = arg.color == :auto ? :auto : colorscheme(arg.color)) arg.alpha == nothing || (d[:markeralpha] = arg.alpha) # linealpha elseif allAlphas(arg) d[:markeralpha] = arg # markersize elseif allReals(arg) d[:markersize] = arg # markercolor elseif !handleColors!(d, arg, :markercolor) warn("Skipped marker arg $arg.") end end function processFillArg(d::KW, arg) if typeof(arg) <: Brush arg.size == nothing || (d[:fillrange] = arg.size) arg.color == nothing || (d[:fillcolor] = arg.color == :auto ? :auto : colorscheme(arg.color)) arg.alpha == nothing || (d[:fillalpha] = arg.alpha) # fillrange function elseif allFunctions(arg) d[:fillrange] = arg # fillalpha elseif allAlphas(arg) d[:fillalpha] = arg elseif !handleColors!(d, arg, :fillcolor) d[:fillrange] = arg end end _replace_markershape(shape::Symbol) = get(_markerAliases, shape, shape) _replace_markershape(shapes::AVec) = map(_replace_markershape, shapes) _replace_markershape(shape) = shape function _add_markershape(d::KW) # add the markershape if it needs to be added... hack to allow "m=10" to add a shape, # and still allow overriding in _apply_recipe ms = pop!(d, :markershape_to_add, :none) if !haskey(d, :markershape) && ms != :none d[:markershape] = ms end end "Handle all preprocessing of args... break out colors/sizes/etc and replace aliases." function preprocessArgs!(d::KW) replaceAliases!(d, _keyAliases) # handle axis args for letter in ("x", "y", "z") asym = symbol(letter * "axis") for arg in wraptuple(get(d, asym, ())) processAxisArg(d, letter, arg) end delete!(d, asym) # turn :labels into :ticks_and_labels tsym = symbol(letter * "ticks") if haskey(d, tsym) && ticksType(d[tsym]) == :labels d[tsym] = (1:length(d[tsym]), d[tsym]) end ssym = symbol(letter * "scale") if haskey(d, ssym) && haskey(_scaleAliases, d[ssym]) d[ssym] = _scaleAliases[d[ssym]] end end # handle line args for arg in wraptuple(pop!(d, :line, ())) processLineArg(d, arg) end # handle marker args... default to ellipse if shape not set anymarker = false for arg in wraptuple(get(d, :marker, ())) processMarkerArg(d, arg) anymarker = true end delete!(d, :marker) if haskey(d, :markershape) d[:markershape] = _replace_markershape(d[:markershape]) elseif anymarker d[:markershape_to_add] = :ellipse # add it after _apply_recipe end # handle fill for arg in wraptuple(get(d, :fill, ())) processFillArg(d, arg) end delete!(d, :fill) # convert into strokes and brushes # legends if haskey(d, :legend) d[:legend] = convertLegendValue(d[:legend]) end if haskey(d, :colorbar) d[:colorbar] = convertLegendValue(d[:colorbar]) end # handle subplot links if haskey(d, :link) l = d[:link] if isa(l, Bool) d[:linkx] = l d[:linky] = l elseif isa(l, Function) d[:linkx] = true d[:linky] = true d[:linkfunc] = l else warn("Unhandled/invalid link $l. Should be a Bool or a function mapping (row,column) -> (linkx, linky), where linkx/y can be Bool or Void (nothing)") end delete!(d, :link) end # pull out invalid keywords into their own KW dict... these are likely user-defined through recipes kw = KW() for k in keys(d) try # this should error for invalid keywords (assume they are user-defined) k == :markershape_to_add || default(k) catch # not a valid key... pop and add to user list kw[k] = pop!(d, k) end end kw end # ----------------------------------------------------------------------------- "A special type that will break up incoming data into groups, and allow for easier creation of grouped plots" type GroupBy groupLabels::Vector{UTF8String} # length == numGroups groupIds::Vector{Vector{Int}} # list of indices for each group end # this is when given a vector-type of values to group by function extractGroupArgs(v::AVec, args...) groupLabels = sort(collect(unique(v))) n = length(groupLabels) if n > 20 warn("You created n=$n groups... Is that intended?") end groupIds = Vector{Int}[filter(i -> v[i] == glab, 1:length(v)) for glab in groupLabels] GroupBy(map(string, groupLabels), groupIds) end # expecting a mapping of "group label" to "group indices" function extractGroupArgs{T, V<:AVec{Int}}(idxmap::Dict{T,V}, args...) groupLabels = sortedkeys(idxmap) groupIds = VecI[collect(idxmap[k]) for k in groupLabels] GroupBy(groupLabels, groupIds) end # ----------------------------------------------------------------------------- function warnOnUnsupportedArgs(pkg::AbstractBackend, d::KW) for k in sortedkeys(d) if (!(k in supportedArgs(pkg)) && k != :subplot && d[k] != default(k)) warn("Keyword argument $k not supported with $pkg. Choose from: $(supportedArgs(pkg))") end end end _markershape_supported(pkg::AbstractBackend, shape::Symbol) = shape in supportedMarkers(pkg) _markershape_supported(pkg::AbstractBackend, shape::Shape) = Shape in supportedMarkers(pkg) _markershape_supported(pkg::AbstractBackend, shapes::AVec) = all([_markershape_supported(pkg, shape) for shape in shapes]) function warnOnUnsupported(pkg::AbstractBackend, d::KW) (d[:axis] in supportedAxes(pkg) || warn("axis $(d[:axis]) is unsupported with $pkg. Choose from: $(supportedAxes(pkg))")) (d[:linetype] == :none || d[:linetype] in supportedTypes(pkg) || warn("linetype $(d[:linetype]) is unsupported with $pkg. Choose from: $(supportedTypes(pkg))")) (d[:linestyle] in supportedStyles(pkg) || warn("linestyle $(d[:linestyle]) is unsupported with $pkg. Choose from: $(supportedStyles(pkg))")) (d[:markershape] == :none || _markershape_supported(pkg, d[:markershape]) || warn("markershape $(d[:markershape]) is unsupported with $pkg. Choose from: $(supportedMarkers(pkg))")) end function warnOnUnsupportedScales(pkg::AbstractBackend, d::KW) for k in (:xscale, :yscale) if haskey(d, k) d[k] in supportedScales(pkg) || warn("scale $(d[k]) is unsupported with $pkg. Choose from: $(supportedScales(pkg))") end end end # ----------------------------------------------------------------------------- # 1-row matrices will give an element # multi-row matrices will give a column # InputWrapper just gives the contents # anything else is returned as-is # getArgValue(v::Tuple, idx::Int) = v[mod1(idx, length(v))] function getArgValue(v::AMat, idx::Int) c = mod1(idx, size(v,2)) size(v,1) == 1 ? v[1,c] : v[:,c] end getArgValue(wrapper::InputWrapper, idx) = wrapper.obj getArgValue(v, idx) = v # given an argument key (k), we want to extract the argument value for this index. # if nothing is set (or container is empty), return the default. function setDictValue(d_in::KW, d_out::KW, k::Symbol, idx::Int, defaults::KW) if haskey(d_in, k) && !(typeof(d_in[k]) <: Union{AbstractArray, Tuple} && isempty(d_in[k])) d_out[k] = getArgValue(d_in[k], idx) else d_out[k] = defaults[k] end end function convertLegendValue(val::Symbol) if val in (:both, :all, :yes) :best elseif val in (:no, :none) :none elseif val in (:right, :left, :top, :bottom, :inside, :best, :legend) val else error("Invalid symbol for legend: $val") end end convertLegendValue(val::Bool) = val ? :best : :none # ----------------------------------------------------------------------------- # build the argument dictionary for the plot function getPlotArgs(pkg::AbstractBackend, kw, idx::Int; set_defaults = true) kwdict = KW(kw) d = KW() # add defaults? if set_defaults for k in keys(_plotDefaults) setDictValue(kwdict, d, k, idx, _plotDefaults) end end # # for k in (:xscale, :yscale) # if haskey(_scaleAliases, d[k]) # d[k] = _scaleAliases[d[k]] # end # end # handle legend/colorbar d[:legend] = convertLegendValue(d[:legend]) d[:colorbar] = convertLegendValue(d[:colorbar]) if d[:colorbar] == :legend d[:colorbar] = d[:legend] end # convert color handlePlotColors(pkg, d) # no need for these delete!(d, :x) delete!(d, :y) d end function has_black_border_for_default(lt::Symbol) like_histogram(lt) || lt in (:hexbin, :bar) end # build the argument dictionary for a series function getSeriesArgs(pkg::AbstractBackend, plotargs::KW, kw, commandIndex::Int, plotIndex::Int, globalIndex::Int) # TODO, pass in plotargs, not plt kwdict = KW(kw) d = KW() # add defaults? for k in keys(_seriesDefaults) setDictValue(kwdict, d, k, commandIndex, _seriesDefaults) end # groupby args? for k in (:idxfilter, :numUncounted, :dataframe) if haskey(kwdict, k) d[k] = kwdict[k] end end if haskey(_typeAliases, d[:linetype]) d[:linetype] = _typeAliases[d[:linetype]] end aliasesAndAutopick(d, :axis, _axesAliases, supportedAxes(pkg), plotIndex) aliasesAndAutopick(d, :linestyle, _styleAliases, supportedStyles(pkg), plotIndex) aliasesAndAutopick(d, :markershape, _markerAliases, supportedMarkers(pkg), plotIndex) # update color d[:seriescolor] = getSeriesRGBColor(d[:seriescolor], plotargs, plotIndex) # # update linecolor # c = d[:linecolor] # c = (c == :match ? d[:seriescolor] : getSeriesRGBColor(c, plotargs, plotIndex)) # d[:linecolor] = c # # update markercolor # c = d[:markercolor] # c = (c == :match ? d[:seriescolor] : getSeriesRGBColor(c, plotargs, plotIndex)) # d[:markercolor] = c # # update fillcolor # c = d[:fillcolor] # c = (c == :match ? d[:seriescolor] : getSeriesRGBColor(c, plotargs, plotIndex)) # d[:fillcolor] = c # update colors for csym in (:linecolor, :markercolor, :fillcolor) d[csym] = if d[csym] == :match if has_black_border_for_default(d[:linetype]) && csym == :linecolor :black else d[:seriescolor] end else getSeriesRGBColor(d[csym], plotargs, plotIndex) end end # update markerstrokecolor c = d[:markerstrokecolor] c = (c == :match ? plotargs[:foreground_color] : getSeriesRGBColor(c, plotargs, plotIndex)) d[:markerstrokecolor] = c # update alphas for asym in (:linealpha, :markeralpha, :markerstrokealpha, :fillalpha) if d[asym] == nothing d[asym] = d[:seriesalpha] end end # scatter plots don't have a line, but must have a shape if d[:linetype] in (:scatter, :scatter3d) d[:linewidth] = 0 if d[:markershape] == :none d[:markershape] = :ellipse end end # set label label = d[:label] label = (label == "AUTO" ? "y$globalIndex" : label) if d[:axis] == :right && !(length(label) >= 4 && label[end-3:end] != " (R)") label = string(label, " (R)") end d[:label] = label warnOnUnsupported(pkg, d) d end