licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
2660
using Graphs: Graphs, DiGraph, add_edge!, add_vertex!, has_edge, nv struct Hierarchy <: Graph g::DiGraph N::Vector{Symbol} I::Dict{Symbol,Int} E::Dict{NTuple{2,Int},Symbol} C::Dict{Symbol,Any} end hierarchy(C=()) = Hierarchy(DiGraph(), Symbol[], Dict{Symbol,Int}(), Dict{NTuple{2,Int},Symbol}(), Dict{Symbol,Any}(C)) hierarchy(S::Type{<:System}; kw...) = begin h = hierarchy(kw) add!(h, S) h end hierarchy(::S; kw...) where {S<:System} = hierarchy(S; kw...) graph(h::Hierarchy) = h.g node!(h::Hierarchy, n::Symbol) = begin if !haskey(h.I, n) add_vertex!(h.g) h.I[n] = nv(h.g) end n end node!(h::Hierarchy, T::Type{<:System}) = node!(h, namefor(T)) using DataStructures: SortedDict nodes(h::Hierarchy) = SortedDict(v => k for (k, v) in h.I) |> values |> collect hasloop(h::Hierarchy, n::Symbol) = (i = h.I[n]; has_edge(h.g, i, i)) link!(h::Hierarchy, a::Symbol, b::Symbol, e=nothing) = begin ai = h.I[a] bi = h.I[b] add_edge!(h.g, ai, bi) (ai == bi) && (e = :loop) !isnothing(e) && (h.E[(ai, bi)] = e) end add!(h::Hierarchy, S::Type{<:System}) = begin #HACK: evaluation scope is the module where S was originally defined scope = S.name.module a = node!(h, S) (a in h.N || hasloop(h, a)) && return add!(h, a, mixinsof(S)) V = geninfos(S) for v in V T = @eval scope $(v.type) #HACK: skip Context since the graph tends to look too busy get(h.C, :skipcontext, false) && (T == typefor(Context)) && continue add!(h, a, T) end push!(h.N, a) end add!(h::Hierarchy, a::Symbol, M::Tuple) = begin for m in M (m == System) && continue add!(h, m) b = node!(h, m) link!(h, b, a, :mixin) end end add!(h::Hierarchy, a::Symbol, T::Type{<:System}) = begin b = node!(h, T) link!(h, b, a) add!(h, T) end add!(h::Hierarchy, a::Symbol, T::Type{Vector{S}}) where {S<:System} = add!(h, a, S) add!(h::Hierarchy, a::Symbol, T) = nothing label(n::Symbol) = string(n) labels(h::Hierarchy; kw...) = label.(nodes(h)) edgestyle(h::Hierarchy, e::Symbol) = begin if e == :mixin "dashed" elseif e == :loop "loop" else "solid" end end edgestyles(h::Hierarchy; kw...) = Dict(e => edgestyle(h, s) for (e, s) in h.E) Base.show(io::IO, h::Hierarchy) = print(io, "Hierarchy") Base.show(io::IO, ::MIME"text/plain", h::Hierarchy) = begin color = get(io, :color, false) SC = tokencolor(SystemColor(); color) MC = tokencolor(MiscColor(); color) print(io, MC("{")) print(io, join(SC.(labels(h)), MC(", "))) print(io, MC("}")) end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
4014
import Interact """ manipulate(f::Function; parameters, config=()) Create an interactive plot updated by callback `f`. Only works in Jupyter Notebook. # Arguments - `f::Function`: callback for generating a plot; interactively updated configuration `c` is provided. - `parameters`: parameters adjustable with interactive widgets; value should be an iterable. - `config=()`: a baseline configuration. """ manipulate(f::Function; parameters, config=()) = begin P = configure(parameters) C = configure(config) W = [] L = [] for (s, Q) in P n = Interact.node(:div, string(s)) #HACK: use similar style/color (:light_magenta) to Config l = Interact.style(n, "font-family" => "monospace", "color" => :rebeccapurple) push!(L, l) for (k, V) in Q u = fieldunit(s, k) b = label(k, u) v = option(C, s, k) #HACK: support Enum types if V isa Type && V <: Enum V = collect(instances(V)) end #TODO: use multiple dispatch? if V isa Union{AbstractArray{Symbol},AbstractArray{<:Enum},AbstractDict} kw = ismissing(v) ? (; label=b) : (; label=b, value=v) w = Interact.dropdown(V; kw...) d = w.layout(w).children[1].dom #TODO: make dropdown box smaller d.props[:style] = Dict("font-family" => "monospace", "padding" => "5px 10px 20px", "color" => :royalblue) d.children[2].props[:style] = Dict("margin" => "-5px 0 0 20px") elseif V isa Union{AbstractRange,AbstractArray} #HACK: remove units of reactive values for UI layout v = deunitfy(v, u) V = deunitfy(V, u) kw = ismissing(v) ? (; label=b) : (; label=b, value=v) w = Interact.widget(V; kw...) #HACK: use similar style/color (:light_blue) to Config d = w.layout(w).children[1].dom d.props[:style] = Dict("font-family" => "monospace", "width" => "80%") d.children[1].children[1].props[:style]["color"] = :royalblue d.children[1].children[1].props[:style]["white-space"] = :nowrap elseif V isa Bool kw = ismissing(v) ? (; label=b) : (; label=b, value=v) w = Interact.checkbox(V; kw...) d = w.layout(w).children[1].dom d.props[:style] = Dict("font-family" => "monospace", "color" => :royalblue) #TODO: tweak margin d.children[2].props[:style] = Dict("font-size" => "14px", "padding-left" => "40px") else error("unsupported values for interaction: $V") end push!(W, w) push!(L, w) end end K = parameterkeys(P) U = parameterunits(P) #HACK: update the widgets only when the change is finalized (i.e., mouse release) O = [Interact.onchange(w, w[!isnothing(w[:changes]) ? :changes : :index]) for w in W] c = map(O...) do (V...) X = parameterzip(K, V, U) _X = codify(X, :__manipulate__) configure(config, X, _X) end if isempty(Interact.WebIO.providers_initialised) @warn "interactive plot only works with a WebIO provider loaded" return f(c[]) end output = Interact.@map f(&c) z = Interact.Widget{:Cropbox}(Dict(zip(K, W)); output) Interact.@layout!(z, Interact.vbox(L..., output)) end """ manipulate(args...; parameters, kwargs...) Create an interactive plot by calling `manipulate` with `visualize` as a callback. See also: [`visualize`](@ref) # Arguments - `args`: positional arguments for `visualize`. - `parameters`: parameters for `manipulate`. - `kwargs`: keyword arguments for `visualize`. """ manipulate(args...; parameters, config=(), kwargs...) = manipulate(function (c) visualize(args...; config=c, kwargs...) end; parameters, config) export manipulate
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
8656
using DataFrames: DataFrame using MacroTools: @capture import Unitful struct Plot{T} obj::T opt::Dict{Symbol,Any} Plot(obj; kw...) = new{typeof(obj)}(obj, Dict(kw...)) end update!(p::Plot; kw...) = (mergewith!(vcat, p.opt, Dict(kw...)); p) getplotopt(p::Plot, k, v=nothing) = get(p.opt, k, v) getplotopt(::Nothing, k, v=nothing) = v value(p::Plot) = p.obj Base.getindex(p::Plot) = value(p) Base.adjoint(p::Plot) = value(p) Base.showable(m::MIME, p::Plot) = showable(m, p.obj) Base.show(p::Plot) = show(p.obj) Base.show(io::IO, p::Plot) = show(io, p.obj) #HACK: custom hook for intercepting 3-args show() from each backend (i.e. Gadfly) Base.show(io::IO, m::MIME, p::Plot) = _show(io, m, p.obj) _show(io::IO, m::MIME, o) = show(io, m, o) Base.show(io::IO, ::MIME"text/plain", p::P) where {P<:Plot} = show(io, "<$P>") Base.display(p::Plot) = display(p.obj) Base.display(d::AbstractDisplay, p::Plot) = display(d, p.obj) Base.display(m::MIME, p::Plot) = display(m, p.obj) Base.display(d::AbstractDisplay, m::MIME, p::Plot) = display(d, m, p.obj) extractcolumn(df::DataFrame, n::Symbol) = df[!, n] extractcolumn(df::DataFrame, n::String) = extractcolumn(df, Symbol(n)) extractcolumn(df::DataFrame, n::Expr) = begin ts(x) = x isa Symbol ? :(df[!, $(Meta.quot(x))]) : x te(x) = @capture(x, f_(a__)) ? :($f($(ts.(a)...))) : x #HACK: avoid world age problem for function scope eval e = Main.eval(:(df -> @. $(MacroTools.postwalk(te, n)))) (() -> @eval $e($df))() end convertcolumn(c::Vector{ZonedDateTime}) = Dates.DateTime.(c) convertcolumn(c) = c extractunit(df::DataFrame, n) = extractunit(extractcolumn(df, n)) extractunit(a) = unittype(a) extractarray(df::DataFrame, n) = begin #HACK: Gadfly doesn't support ZonedDateTime convertcolumn(extractcolumn(df, n)) end findlim(array::Vector{<:Number}) = begin a = skipmissing(array) l = isempty(a) ? 0 : floor(minimum(a)) u = isempty(a) ? 0 : ceil(maximum(a)) #HACK: avoid empty range l == u ? (l-1, l+1) : (l, u) end findlim(array) = extrema(skipmissing(array)) label(l, u) = begin l = isnothing(l) ? "" : l hasunit(u) ? "$l ($u)" : "$l" end detectbackend() = begin if isdefined(Main, :IJulia) && Main.IJulia.inited || isdefined(Main, :Juno) && Main.Juno.isactive() || isdefined(Main, :VSCodeServer) || isdefined(Main, :PlutoRunner) || isdefined(Main, :Documenter) && any(t -> startswith(string(t.func), "#makedocs#"), stacktrace()) || haskey(ENV, "NJS_VERSION") :Gadfly else :UnicodePlots end end """ plot(df::DataFrame, x, y; <keyword arguments>) -> Plot plot(X::Vector, Y::Vector; <keyword arguments>) -> Plot plot(df::DataFrame, x, y, z; <keyword arguments>) -> Plot Plot a graph from provided data source. The type of graph is selected based on arguments. See also: [`plot!`](@ref), [`visualize`](@ref) """ plot(df::DataFrame, x, y; name=nothing, color=nothing, kw...) = plot(df, x, [y]; names=[name], colors=[color], kw...) plot(df::DataFrame, x, ys::Vector; kw...) = plot!(nothing, df, x, ys; kw...) """ plot!(p, <arguments>; <keyword arguments>) -> Plot Update an existing `Plot` object `p` by appending a new graph made with `plot`. See also: [`plot`](@ref) # Arguments - `p::Union{Plot,Nothing}`: plot object to be updated; `nothing` creates a new plot. """ plot!(p::Union{Plot,Nothing}, df::DataFrame, x, y; name=nothing, color=nothing, kw...) = plot!(p, df, x, [y]; names=[name], colors=[color], kw...) plot!(p::Union{Plot,Nothing}, df::DataFrame, x, ys::Vector; xlab=nothing, ylab=nothing, names=nothing, colors=nothing, kw...) = begin arr(n) = extractarray(df, n) X = arr(x) Ys = arr.(ys) n = length(Ys) xlab = isnothing(xlab) ? x : xlab ylab = isnothing(ylab) ? "" : ylab names = isnothing(names) ? repeat([nothing], n) : names names = [isnothing(n) ? string(y) : n for (y, n) in zip(ys, names)] #HACK: support indirect referencing from the given data frame if name is Symbol names = [n isa Symbol ? repr(deunitfy(only(unique(df[!, n]))), context=:compact=>true) : n for n in names] colors = isnothing(colors) ? repeat([nothing], n) : colors plot!(p, X, Ys; xlab, ylab, names, colors, kw...) end """ plot(v::Number; kind, <keyword arguments>) -> Plot plot(V::Vector; kind, <keyword arguments>) -> Plot Plot a graph of horizontal/vertical lines depending on `kind`, which can be either `:hline` or `:vline`. An initial plotting of `hline` requires `xlim` and `vline` requires `ylim`, respectively. See also: [`plot!`](@ref), [`visualize`](@ref) """ plot(v::Number; kw...) = plot([v]; kw...) plot!(p::Union{Plot,Nothing}, v::Number; kw...) = plot!(p, [v]; kw...) plot(V::Vector; kw...) = plot!(nothing, V; kw...) plot!(p::Union{Plot,Nothing}, X::Vector; kind, xlim=nothing, ylim=nothing, kw...) = begin xlim = getplotopt(p, :xlim, xlim) ylim = getplotopt(p, :ylim, ylim) if kind == :hline isnothing(xlim) && error("hline requires `xlim`: $V") ylim = isnothing(ylim) ? findlim(X) : ylim elseif kind == :vline isnothing(ylim) && error("vline requires `ylim`: $V") xlim = isnothing(xlim) ? findlim(X) : xlim else error("unsupported `kind` for single value plot: $kind") end plot!(p, X, []; kind, xlim, ylim, kw...) end plot(X::Vector, Y::Vector; name=nothing, color=nothing, kw...) = plot(X, [Y]; names=isnothing(name) ? nothing : [name], colors=[color], kw...) plot(X::Vector, Ys::Vector{<:Vector}; kw...) = plot!(nothing, X, Ys; kw...) plot!(p::Union{Plot,Nothing}, X::Vector, Y::Vector; name=nothing, color=nothing, kw...) = plot!(p, X, [Y]; names=isnothing(name) ? nothing : [name], colors=[color], kw...) plot!(p::Union{Plot,Nothing}, X::Vector, Ys::Vector{<:Vector}; kind=:scatter, title=nothing, xlab=nothing, ylab=nothing, legend=nothing, legendpos=nothing, names=nothing, colors=nothing, xlim=nothing, ylim=nothing, ycat=nothing, xunit=nothing, yunit=nothing, aspect=nothing, backend=nothing, ) = begin u(a) = extractunit(a) xunit = getplotopt(p, :xunit, xunit) yunit = getplotopt(p, :yunit, yunit) isnothing(xunit) && (xunit = u(X)) isnothing(yunit) && (yunit = promoteunit(u.(Ys)...)) arr(a, u) = deunitfy(a, u) X = arr(X, xunit) Ys = arr.(Ys, yunit) isnothing(xlim) && (xlim = findlim(X)) if isnothing(ylim) l = findlim.(Ys) ylim = (minimum(minimum.(l)), maximum(maximum.(l))) end if kind == :step && isnothing(ycat) if all(isequal(Bool), eltype.(Ys)) ycat = [false, true] else l = unique.(Ys) ycat = unique(Iterators.flatten(l)) end end n = length(Ys) xlab = label(xlab, xunit) ylab = label(ylab, yunit) if legend === false legend = "" names = repeat([""], n) else legend = isnothing(legend) ? "" : string(legend) n0 = length(getplotopt(p, :Ys, [])) names = isnothing(names) ? "#" .* string.(n0+1:n0+n) : names end colors = isnothing(colors) ? repeat([nothing], n) : colors title = isnothing(title) ? "" : string(title) isnothing(backend) && (backend = detectbackend()) plot2!(Val(backend), p, X, Ys; kind, title, xlab, ylab, legend, legendpos, names, colors, xlim, ylim, ycat, xunit, yunit, aspect) end plot(df::DataFrame, x, y, z; kind=:heatmap, title=nothing, legend=nothing, legendpos=nothing, xlab=nothing, ylab=nothing, zlab=nothing, xlim=nothing, ylim=nothing, zlim=nothing, xunit=nothing, yunit=nothing, zunit=nothing, zgap=nothing, zlabgap=nothing, aspect=nothing, backend=nothing, ) = begin u(n) = extractunit(df, n) isnothing(xunit) && (xunit = u(x)) isnothing(yunit) && (yunit = u(y)) isnothing(zunit) && (zunit = u(z)) arr(n, u) = deunitfy(extractarray(df, n), u) X = arr(x, xunit) Y = arr(y, yunit) Z = arr(z, zunit) isnothing(xlim) && (xlim = findlim(X)) isnothing(ylim) && (ylim = findlim(Y)) isnothing(zlim) && (zlim = findlim(Z)) xlab = label(isnothing(xlab) ? x : xlab, xunit) ylab = label(isnothing(ylab) ? y : ylab, yunit) zlab = label(isnothing(zlab) ? z : zlab, zunit) title = isnothing(title) ? "" : string(title) legend = isnothing(legend) ? true : legend isnothing(backend) && (backend = detectbackend()) plot3!(Val(backend), X, Y, Z; kind, title, legend, legendpos, xlab, ylab, zlab, xlim, ylim, zlim, zgap, zlabgap, aspect) end include("plot/UnicodePlots.jl") include("plot/Gadfly.jl") export plot, plot!
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
10190
using DataStructures: OrderedDict using DataFrames: DataFrame using Dates: AbstractTime struct Simulation base::Union{String,Symbol,Nothing} index::OrderedDict{Symbol,Any} target::OrderedDict{Symbol,Any} mapping::OrderedDict{Symbol,Any} meta::OrderedDict{Symbol,Any} result::Vector{OrderedDict{Symbol,Any}} end simulation(s::System; config=(), base=nothing, index=nothing, target=nothing, meta=nothing) = begin sb = s[base] I = parseindex(index, sb) T = parsetarget(target, sb) #HACK: ignore unavailable properties (i.e. handle default :time in target) I = filtersimulationdict(I, sb) T = filtersimulationdict(T, sb) IT = merge(I, T) M = parsemeta(meta, s.context.config) Simulation(base, I, T, IT, M, Vector{OrderedDict{Symbol,Any}}()) end parsesimulationkey(p::Pair, s) = [p] parsesimulationkey(a::Symbol, s) = [a => a] parsesimulationkey(a::String, s) = [Symbol(a) => a] parsesimulationkey(a::String, s::System) = begin A = split(a, '.') # support wildcard names (i.e. "s.*" expands to ["s.a", "s.b", ...]) if A[end] == "*" a0 = join(A[1:end-1], '.') ss = s[a0] p(n) = let k = join(filter!(!isempty, [a0, string(n)]), '.') Symbol(k) => k end [p(n) for n in fieldnamesunique(ss)] else [Symbol(a) => a] end end parsesimulationkey(a::Vector, s) = parsesimulationkey.(a, Ref(s)) |> Iterators.flatten |> collect parsesimulation(a::Vector, s) = OrderedDict(parsesimulationkey.(a, Ref(s)) |> Iterators.flatten) parsesimulation(a::Tuple, s) = parsesimulation(collect(a), s) parsesimulation(::Tuple{}, s) = parsesimulation([], s) parsesimulation(::Missing, s) = parsesimulation([], s) parsesimulation(a, s) = parsesimulation([a], s) parseindex(::Nothing, s) = parsesimulation(:time => "context.clock.time", s) parseindex(I, s) = parsesimulation(I, s) parsetarget(::Nothing, s) = parsesimulation("*", s) parsetarget(T, s) = parsesimulation(T, s) filtersimulationdict(m::OrderedDict, s::System) = filter(m) do (k, v); hasproperty(s, v) end extract(s::System, m::Simulation) = extract(s[m.base], m.mapping) extract(s::System, m::OrderedDict{Symbol,Any}) = begin K = keys(m) V = (value(s[k]) for k in values(m)) #HACK: Any -- prevent type promotion with NoUnits d = OrderedDict{Symbol,Any}(zip(K, V)) filter!(p -> extractable(s, p), d) [d] end extract(b::Bundle{S}, m::OrderedDict{Symbol,Any}) where {S<:System} = begin [extract(s, m) for s in collect(b)] end extractable(s::System, p) = begin # only pick up variables of simple types by default p[2] isa Union{Number,Symbol,AbstractString,AbstractTime} end parsemetadata(p::Pair, c) = p parsemetadata(a::Symbol, c) = c[a] parsemetadata(a::String, c) = c[Symbol(a)] #HACK: support nested meta keyword list parsemetadata(::Nothing, c) = () parsemetadata(a, c) = parsemeta(a, c) parsemeta(a::Vector, c) = merge(parsemeta(nothing, c), OrderedDict.(parsemetadata.(a, Ref(c)))...) parsemeta(a::Tuple, c) = parsemeta(collect(a), c) parsemeta(a, c) = parsemeta([a], c) parsemeta(::Nothing, c) = OrderedDict() update!(m::Simulation, s::System, snatch!) = begin D = extract(s, m) snatch!(D, s) !isempty(D) && append!(m.result, D) end format!(m::Simulation; nounit=false, long=false) = begin r = DataFrame(DataFrames.Tables.dictcolumntable(m.result), copycols=false) for (k, v) in m.meta r[!, k] .= v end if nounit r = deunitfy.(r) end if long i = collect(keys(m.index)) t = setdiff(propertynames(r), i) r = DataFrames.stack(r, t, i) r = sort!(r, i) end r end using ProgressMeter: Progress, ProgressUnknown, ProgressMeter const barglyphs = ProgressMeter.BarGlyphs("[=> ]") progress!(s::System, M::Vector{Simulation}; stop=nothing, snap=nothing, snatch=nothing, callback=nothing, verbose=true, kwargs...) = begin probe(a::Union{Symbol,String}) = s -> s[a]' probe(a::Function) = s -> a(s) probe(a) = s -> a stopprobe(::Nothing) = probe(0) stopprobe(a) = probe(a) snapprobe(::Nothing) = probe(true) snapprobe(a::Quantity) = s -> let c = s.context.clock; (c.time' - c.init') % a |> iszero end snapprobe(a) = probe(a) stop = stopprobe(stop) snap = snapprobe(snap) snatch = isnothing(snatch) ? (D, s) -> nothing : snatch callback = isnothing(callback) ? (s, m) -> nothing : callback count(v::Number) = v count(v::Quantity) = ceil(Int, v / s.context.clock.step') count(v::Bool) = nothing count(v) = error("unrecognized stop condition: $v") n = count(stop(s)) dt = verbose ? 1 : Inf showspeed = true if n isa Number p = Progress(n; dt, barglyphs, showspeed) check = s -> p.counter < p.n else p = ProgressUnknown(; dt, desc="Iterations:", showspeed) check = s -> !stop(s) end snap(s) && update!.(M, s, snatch) while check(s) update!(s) snap(s) && for m in M update!(m, s, snatch) callback(s, m) end ProgressMeter.next!(p) end ProgressMeter.finish!(p) format!.(M; kwargs...) end """ simulate!([f,] s[, layout]; <keyword arguments>) -> DataFrame Run simulations with an existing instance of system `s`. The instance is altered by internal updates for running simulations. See also: [`simulate`](@ref) """ simulate!(s::System; base=nothing, index=nothing, target=nothing, meta=nothing, kwargs...) = begin simulate!(s, [(; base, index, target, meta)]; kwargs...) |> only end simulate!(s::System, layout::Vector; kwargs...) = begin M = [simulation(s; l...) for l in layout] progress!(s, M; kwargs...) end simulate!(f::Function, s::System, args...; kwargs...) = simulate!(s, args...; snatch=f, kwargs...) """ simulate([f,] S[, layout, [configs]]; <keyword arguments>) -> DataFrame Run simulations by making instance of system `S` with given configuration to generate an output in the form of DataFrame. `layout` contains a list of variables to be saved in the output. A layout of single simulation can be specified in the layout arguments placed as keyword arguments. `configs` contains a list of configurations for each run of simulation. Total number of simulation runs equals to the size of `configs`. For a single configuration, `config` keyword argument may be preferred. Optional callback function `f` allows do-block syntax to specify `snatch` argument for finer control of output format. See also: [`instance`](@ref), [`@config`](@ref) # Arguments - `S::Type{<:System}`: type of system to be simulated. - `layout::Vector`: list of output layout definition in a named tuple `(; base, index, target, meta)`. - `configs::Vector`: list of configurations for defining multiple runs of simluations. # Keyword Arguments ## Layout - `base=nothing`: base system where `index` and `target` are populated; default falls back to the instance of `S`. - `index=nothing`: variables to construct index columns of the output; default falls back to `context.clock.time`. - `target=nothing`: variables to construct non-index columns of the output; default includes most variables in the root instance. - `meta=nothing`: name of systems in the configuration to be included in the output as metadata. ## Configuration - `config=()`: a single configuration for the system, or a base for multiple configurations (when used with `configs`). - `configs=[]`: multiple configurations for the system. - `seed=nothing`: random seed for resetting each simulation run. ## Progress - `stop=nothing`: condition checked before calling updates for the instance; default stops with no update. - `snap=nothing`: condition checked to decide if a snapshot of current update is saved in the output; default snaps all updates. - `snatch=nothing`: callback for modifying intermediate output; list of DataFrame `D` collected from current update and the instance of system `s` are provided. - `verbose=true`: shows a progress bar. ## Format - `nounit=false`: remove units from the output. - `long=false`: convert output table from wide to long format. # Examples ```julia-repl julia> @system S(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate end; julia> simulate(S; stop=1) 2×3 DataFrame Row │ time a b │ Quantity… Float64 Float64 ─────┼───────────────────────────── 1 │ 0.0 hr 1.0 0.0 2 │ 1.0 hr 1.0 1.0 ``` """ simulate(; system, kw...) = simulate(system; kw...) simulate(S::Type{<:System}; base=nothing, index=nothing, target=nothing, meta=nothing, kwargs...) = begin simulate(S, [(; base, index, target, meta)]; kwargs...) |> only end simulate(S::Type{<:System}, layout::Vector; config=(), configs=[], parameters=(), options=(), seed=nothing, kwargs...) = begin if isempty(configs) && isempty(parameters) s = instance(S; config, options, seed) simulate!(s, layout; kwargs...) else if isempty(parameters) c = @config config + configs L = layout elseif isempty(configs) P = @config !parameters _P = codify.(P, :__manipulate__) c = @config(config + P + _P) #HACK: inject a meta keyword, assuming a single layout l = only(layout) L = [(; base=l.base, index=l.index, target=l.target, meta=(l.meta, :__manipulate__))] else @error "redundant configurations with parameters" configs parameters end simulate(S, L, c; options, seed, kwargs...) end end simulate(S::Type{<:System}, layout::Vector, configs::Vector; verbose=true, kwargs...) = begin n = length(configs) R = Vector(undef, n) dt = verbose ? 1 : Inf p = Progress(n; dt, barglyphs) Threads.@threads for i in 1:n R[i] = simulate(S, layout; config=configs[i], verbose=false, kwargs...) ProgressMeter.next!(p) end ProgressMeter.finish!(p) [vcat(r...) for r in eachrow(hcat(R...))] end simulate(f::Function, S::Type{<:System}, args...; kwargs...) = simulate(S, args...; snatch=f, kwargs...) export simulate, simulate!
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
9392
""" visualize(<arguments>; <keyword arguments>) -> Plot Make a plot from an output collected by running necessary simulations. A convenient function to run both `simulate` and `plot` together. See also: [`visualize!`](@ref), [`simulate`](@ref), [`plot`](@ref), [`manipulate`](@ref) # Examples ```julia-repl julia> @system S(Controller) begin a(a) => a ~ accumulate(init=1) end; julia> visualize(S, :time, :a; stop=5, kind=:line) ┌────────────────────────────────────────┐ 32 │ :│ │ : │ │ : │ │ : │ │ : │ │ : │ │ : │ a │ : │ │ .' │ │ .' │ │ .' │ │ ..' │ │ ..'' │ │ ....'' │ 1 │.........'''' │ └────────────────────────────────────────┘ 0 5 time (hr) ``` """ visualize(a...; kw...) = plot(a...; kw...) """ visualize!(p, <arguments>; <keyword arguments>) -> Plot Update an existing `Plot` object `p` by appending a new graph made with `visualize`. See also: [`visualize`](@ref) # Arguments - `p::Union{Plot,Nothing}`: plot object to be updated; `nothing` creates a new plot. """ visualize!(a...; kw...) = plot!(a...; kw...) visualize(S::Type{<:System}, x, y; kw...) = visualize!(nothing, S, x, y; kw...) visualize!(p, S::Type{<:System}, x, y; config=(), group=(), xstep=(), base=nothing, stop=nothing, snap=nothing, ylab=nothing, legend=nothing, names=nothing, colors=nothing, plotopts... ) = begin G = configure(group) C = @config config + !G n = length(C) legend!(k, S) = begin isnothing(legend) && (legend = string(k)) #TODO: support custom unit for legend? u = vartype(S, k) |> unittype legend = label(legend, u) end #HACK: support indirect referencing of label by variable name names = if names isa Symbol k = names legend!(k, S) repeat([k], n) elseif !isnothing(names) names elseif isempty(G) [""] elseif G isa Vector # temporary numeric labels string.(1:n) else K, V = only(G) k, v = only(V) T = K == Symbol(0) ? S : typefor(K, scopeof(S)) legend!(k, T) string.(v) end isnothing(colors) && (colors = repeat([nothing], n)) isnothing(ylab) && (ylab = y) s(c) = simulate(S; base, target=[x, y], configs=@config(c + !xstep), stop, snap, verbose=false) r = s(C[1]) p = plot!(p, r, x, y; ylab, legend, name=names[1], color=colors[1], plotopts...) for i in 2:n r = s(C[i]) p = plot!(p, r, x, y; name=names[i], color=colors[i], plotopts...) end p end visualize(SS::Vector, x, y; kw...) = visualize!(nothing, SS, x, y; kw...) visualize!(p, SS::Vector, x, y; configs=[], names=nothing, colors=nothing, kw...) = begin n = length(SS) isempty(configs) && (configs = repeat([()], n)) @assert length(configs) == n isnothing(names) && (names = string.(nameof.(SS))) isnothing(colors) && (colors = repeat([nothing], n)) for (S, config, name, color) in zip(SS, configs, names, colors) p = visualize!(p, S, x, y; config, name, color, kw...) end p end visualize(S::Type{<:System}, x, y::Vector; kw...) = visualize!(nothing, S, x, y; kw...) visualize!(p, S::Type{<:System}, x, y::Vector; config=(), xstep=(), base=nothing, stop=nothing, snap=nothing, plotopts... ) = begin r = simulate(S; base, target=[x, y], configs=@config(config + !xstep), stop, snap, verbose=false) plot!(p, r, x, y; plotopts...) end visualize(df::DataFrame, S::Type{<:System}, x, y; kw...) = visualize!(nothing, df, S, x, y; kw...) visualize!(p, df::DataFrame, S::Type{<:System}, x, y; config=(), kw...) = visualize!(p, df, [S], x, y; configs=[config], kw...) visualize(df::DataFrame, SS::Vector, x, y; kw...) = visualize!(nothing, df, SS, x, y; kw...) visualize!(p, df::DataFrame, SS::Vector, x, y; configs=[], xstep=(), base=nothing, stop=nothing, snap=nothing, xlab=nothing, ylab=nothing, name=nothing, names=nothing, colors=nothing, xunit=nothing, yunit=nothing, plotopts... ) = begin x = x isa Pair ? x : x => x y = y isa Pair ? y : y => y xo, xe = x yo, ye = y xlab = isnothing(xlab) ? xe : xlab ylab = isnothing(ylab) ? ye : ylab u(n) = extractunit(df, n) isnothing(xunit) && (xunit = u(xo)) isnothing(yunit) && (yunit = u(yo)) n = length(SS) isempty(configs) && (configs = repeat([()], n)) @assert length(configs) == n isnothing(names) && (names = string.(nameof.(SS))) isnothing(colors) && (colors = repeat([nothing], n)) p = plot!(p, df, xo, yo; kind=:scatter, name, xlab, ylab, xunit, yunit, plotopts...) for (S, c, name, color) in zip(SS, configs, names, colors) cs = isnothing(xstep) ? c : @config(c + !xstep) r = simulate(S; base, target=[xe, ye], configs=cs, stop, snap, verbose=false) p = plot!(p, r, xe, ye; kind=:line, name, color, xunit, yunit, plotopts...) end p end visualize(obs::DataFrame, S::Type{<:System}, y::Vector; kw...) = visualize!(nothing, obs, S, y; kw...) visualize!(p, obs::DataFrame, S::Type{<:System}, y::Vector; index, config=(), configs=[], base=nothing, stop=nothing, snap=nothing, names=nothing, plotopts... ) = begin #HACK: use copy due to normalize! obs = copy(obs) I = parseindex(index, S) |> keys |> collect T = parsetarget(y, S) Yo = T |> keys |> collect Ye = T |> values |> collect est = simulate(S; config, configs, base, index, target=Ye, stop, snap, verbose=false) normalize!(obs, est, on=I) df = DataFrames.innerjoin(obs, est, on=I) Xs = extractarray.(Ref(df), Yo) Ys = extractarray.(Ref(df), Ye) isnothing(names) && (names = [o == e ? "$o" : "$o ⇒ $e" for (o, e) in T]) _visualize_obs_vs_est!(p, Xs, Ys; names, plotopts...) end visualize(obs::DataFrame, S::Type{<:System}, y; kw...) = visualize!(nothing, obs, S, y; kw...) visualize!(p, obs::DataFrame, S::Type{<:System}, y; config=(), configs=[], name="", kw...) = visualize!(p, obs, [(; system=S, config, configs)], y; names=[name], kw...) visualize(obs::DataFrame, maps::Vector{<:NamedTuple}, y; kw...) = visualize!(nothing, obs, maps, y; kw...) visualize!(p, obs::DataFrame, maps::Vector{<:NamedTuple}, y; index, config=(), configs=[], base=nothing, stop=nothing, snap=nothing, names=nothing, plotopts... ) = begin #HACK: use copy due to normalize! obs = copy(obs) I = parseindex(index, obs) |> keys |> collect yo, ye = parsetarget(y, obs) |> collect |> only ests = map(m -> simulate(; m..., base, index, target=ye, stop, snap, verbose=false), maps) normalize!(obs, ests..., on=I) dfs = map(est -> DataFrames.innerjoin(obs, est, on=I), ests) Xs = extractarray.(dfs, yo) Ys = extractarray.(dfs, ye) isnothing(names) && (names = ["$(m.system)" for m in maps]) _visualize_obs_vs_est!(p, Xs, Ys; names, plotopts...) end _visualize_obs_vs_est!(p, Xs, Ys; xlab=nothing, ylab=nothing, names=nothing, colors=nothing, lim=nothing, plotopts...) = begin isnothing(xlab) && (xlab = "Observation") isnothing(ylab) && (ylab = "Model") n = length(Ys) isnothing(names) && (names = repeat([""], n)) isnothing(colors) && (colors = repeat([nothing], n)) if isnothing(lim) l = findlim.(deunitfy.([Xs..., Ys...])) lim = (minimum(minimum.(l)), maximum(maximum.(l))) end L = [lim[1], lim[2]] for (X, Y, name) in zip(Xs, Ys, names) p = plot!(p, X, Y; kind=:scatter, name, xlab, ylab, xlim=lim, ylim=lim, aspect=1, plotopts...) end !isnothing(lim) && plot!(p, L, L, kind=:line, color=:lightgray, name="") p end visualize(S::Type{<:System}, x, y, z; config=(), xstep=(), ystep=(), base=nothing, stop=nothing, snap=nothing, plotopts... ) = begin configs = @config config + xstep * ystep r = simulate(S; base, index=[x, y], target=z, configs, stop, snap, verbose=false) plot(r, x, y, z; plotopts...) end visualize_call(S::Type{<:System}, x, y, call...; config=(), xstep=(), plotopts...) = begin if isempty(xstep) s = instance(S; config) f = s[y]' i = findall(a -> a isa AbstractRange || a isa AbstractArray, call) |> only rx = call[i] |> collect ry = [f(a...) for a in Iterators.product(call...)] plot(rx, ry; xlab=x, ylab=y, plotopts...) else configs = @config(config + !xstep) r(c) = begin s = instance(S; config=c) f = s[y]' (s[x]', f(call...)) end l = [r(c) for c in configs] rx, ry = [first.(l), last.(l)] plot(rx, ry; xlab=x, ylab=y, plotopts...) end end export visualize, visualize!
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
7600
import Gadfly plot2!(::Val{:Gadfly}, p::Union{Plot,Nothing}, X, Ys; kind, title, xlab, ylab, legend, legendpos, names, colors, xlim, ylim, ycat, xunit, yunit, aspect) = begin n = length(Ys) Xs = [X for _ in 1:n] kinds = [kind for _ in 1:n] if kind == :line geoms = [Gadfly.Geom.line] elseif kind == :scatter geoms = [Gadfly.Geom.point] elseif kind == :scatterline geoms = [Gadfly.Geom.point, Gadfly.Geom.line] elseif kind == :step geoms = [Gadfly.Geom.step] elseif kind == :hline geoms = [Gadfly.Geom.hline] elseif kind == :vline geoms = [Gadfly.Geom.vline] else error("unrecognized plot kind = $kind") end #HACK: manual_color_key() expects [] while colorkey() expects nothing keypos = isnothing(legendpos) ? [] : legendpos .* [Gadfly.w, Gadfly.h] theme = Gadfly.Theme( background_color="white", plot_padding=[5*Gadfly.mm, 5*Gadfly.mm, 5*Gadfly.mm, 0*Gadfly.mm], major_label_font_size=10*Gadfly.pt, key_title_font_size=9*Gadfly.pt, key_position=isempty(keypos) ? :right : :inside, point_size=0.7*Gadfly.mm, discrete_highlight_color=_->Gadfly.RGBA(1, 1, 1, 0), ) create_colors(colors; n0=0) = begin n = length(colors) C = Gadfly.Scale.default_discrete_colors(n0+n)[n0+begin:end] f(c::Int, _) = p.opt[:colors][c] f(c, _) = parse(Gadfly.Colorant, c) f(::Nothing, i) = C[i] [f(c, i) for (i, c) in enumerate(colors)] end colorkey(colors) = begin NC = filter!(x -> let (n, c) = x; !isempty(n) end, collect(zip(names, colors))) if !isempty(NC) N, C = first.(NC), last.(NC) Gadfly.Guide.manual_color_key(legend, N, C; pos=keypos) end end colorkey!(key, colors) = begin k = colorkey(colors) if !isnothing(k) append!(key.labels, k.labels) append!(key.colors, k.colors) end k end update_color!(guides, colors) = begin #TODO: very hacky approach to append new plots... definitely need a better way keys = filter(x -> x isa Gadfly.Guide.ManualDiscreteKey, guides) if isempty(keys) key = colorkey(colors) !isnothing(key) && push!(guides, key) else key = only(keys) colorkey!(key, colors) end end create_layers(colors; n0=0) = begin f(i) = begin xy = if kind == :hline (; yintercept=Xs[i]) elseif kind == :vline (; xintercept=Xs[i]) else (; x=Xs[i], y=Ys[i]) end t = Gadfly.Theme(theme; default_color=colors[i]) Gadfly.layer(geoms..., t; xy..., order=n0+i) end [f(i) for i in 1:n] end if isnothing(p) xmin, xmax = xlim ymin, ymax = ylim scales = if kind == :step [ Gadfly.Scale.y_discrete(levels=ycat), Gadfly.Coord.cartesian(; xmin, xmax, ymin=1, ymax=length(ycat), aspect_ratio=aspect), ] #HACK: aesthetic adjustment for boolean (flag) plots #TODO: remove special adjustment in favor of new step plot elseif eltype(ylim) == Bool [ #HACK: ensure correct level order (false low, true high) Gadfly.Scale.y_discrete(levels=[false, true]), #HACK: shift ylim to avoid clipping true values (discrete false=1, true=2) Gadfly.Coord.cartesian(; xmin, xmax, ymin=1, ymax=2, aspect_ratio=aspect), ] else [ Gadfly.Coord.cartesian(; xmin, xmax, ymin, ymax, aspect_ratio=aspect), ] end guides = [ Gadfly.Guide.title(title), Gadfly.Guide.xlabel(xlab), Gadfly.Guide.ylabel(ylab), ] colors = create_colors(colors) update_color!(guides, colors) layers = create_layers(colors) obj = Gadfly.plot( scales..., guides..., layers..., theme, ) p = Plot(obj; Xs, Ys, kinds, colors, title, xlab, ylab, legend, names, xlim, ylim, xunit, yunit, aspect) else obj = p.obj n0 = length(obj.layers) colors = create_colors(colors; n0) update_color!(obj.guides, colors) for l in create_layers(colors; n0) Gadfly.push!(obj, l) end update!(p; Xs, Ys, kinds, colors, names) end p end plot3!(::Val{:Gadfly}, X, Y, Z; kind, title, legend, legendpos, xlab, ylab, zlab, xlim, ylim, zlim, zgap, zlabgap, aspect) = begin if kind == :heatmap geom = Gadfly.Geom.rectbin data = (x=X, y=Y, color=Z) elseif kind == :contour levels = isnothing(zgap) ? 100 : collect(zlim[1]:zgap:zlim[2]) geom = Gadfly.Geom.contour(; levels) data = (x=X, y=Y, z=Z) else error("unrecognized plot kind = $kind") end #HACK: colorkey() expects nothing while manual_color_key() expects [] keypos = isnothing(legendpos) ? nothing : legendpos .* [Gadfly.w, Gadfly.h] theme = Gadfly.Theme( background_color="white", plot_padding=[5*Gadfly.mm, 5*Gadfly.mm, 5*Gadfly.mm, 0*Gadfly.mm], major_label_font_size=10*Gadfly.pt, key_title_font_size=9*Gadfly.pt, key_position=legend ? isnothing(keypos) ? :right : :inside : :none, ) label(z) = begin #TODO: remove redundant creation of Scale zmin, zmax = zlim zspan = zmax - zmin scale = Gadfly.Scale.color_continuous(minvalue=zmin, maxvalue=zmax) color = scale.f((z - zmin) / zspan) i = findmin(abs.(Z .- z))[2] #HACK: ignore lables presumably out of bound if i == firstindex(Z) || i == lastindex(Z) Gadfly.Guide.annotation(Gadfly.compose(Gadfly.context())) else x, y = X[i], Y[i] Gadfly.Guide.annotation( Gadfly.compose( Gadfly.context(), Gadfly.Compose.text(x, y, string(z), Gadfly.hcenter, Gadfly.vcenter), Gadfly.font(theme.minor_label_font), Gadfly.fontsize(theme.minor_label_font_size), Gadfly.fill(color), Gadfly.stroke("white"), Gadfly.linewidth(0.1*Gadfly.pt), ) ) end end labels = isnothing(zlabgap) ? () : label.(zlim[1]:zlabgap:zlim[2]) scales = [ #TODO: fix performance regression with custom system image #Gadfly.Scale.x_continuous, #Gadfly.Scale.y_continuous, Gadfly.Scale.color_continuous(minvalue=zlim[1], maxvalue=zlim[2]), Gadfly.Coord.cartesian(xmin=xlim[1], ymin=ylim[1], xmax=xlim[2], ymax=ylim[2], aspect_ratio=aspect), ] guides = [ Gadfly.Guide.title(title), Gadfly.Guide.xlabel(xlab), Gadfly.Guide.ylabel(ylab), Gadfly.Guide.colorkey(title=zlab; pos=keypos), ] obj = Gadfly.plot( scales..., guides..., geom, labels..., theme; data..., ) Plot(obj; X, Y, Z, kind, title, xlab, ylab, zlab, xlim, ylim, zlim, aspect) end #HACK: use non-interactive SVG instead of SVGJS _show(io::IO, m::MIME"text/html", p::Gadfly.Plot) = begin w = Gadfly.Compose.default_graphic_width h = Gadfly.Compose.default_graphic_height Gadfly.SVG(io, w, h, false)(p) end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
4309
import UnicodePlots plot2!(::Val{:UnicodePlots}, p::Union{Plot,Nothing}, X, Ys; kind, title, xlab, ylab, legend, legendpos, names, colors, xlim, ylim, ycat, xunit, yunit, aspect, width=40, height=15) = begin canvas = if get(ENV, "CI", nothing) == "true" UnicodePlots.DotCanvas else UnicodePlots.BrailleCanvas end if kind == :line || kind == :scatterline plot! = UnicodePlots.lineplot! elseif kind == :scatter plot! = UnicodePlots.scatterplot! elseif kind == :step plot! = UnicodePlots.stairs! #HACK: convert symbol array to integer index array ylim = (1, length(ycat)) Ys = indexin.(Ys, Ref(ycat)) height = length(ycat) elseif kind == :hline plot! = UnicodePlots.hline! #HACK: no clipping on x axis Ys = [nothing] elseif kind == :vline plot! = UnicodePlots.vline! #HACK: no clipping on y axis Ys = [nothing] else error("unrecognized plot kind = $kind") end !isnothing(legendpos) && @warn "unsupported legend position = $legendpos" create_colors(colors; n0=0) = begin n = length(colors) C = collect(Iterators.take(Iterators.cycle(UnicodePlots.COLOR_CYCLE[]), n+n0))[n0+begin:end] f(c::Int, _) = p.opt[:colors][c] f(c, _) = c in keys(UnicodePlots.color_encode) ? c : :normal f(::Nothing, i) = C[i] [f(c, i) for (i, c) in enumerate(colors)] end #HACK: handle x-axis type of Date/DateTime adapted from UnicodePlots.lineplot() xlim_value(v::Dates.TimeType) = Dates.value(v) xlim_value(v) = v xlimval = xlim_value.(xlim) annotate_x_axis!(obj) = begin #HACK: override xlim string (for Date/DateTime) UnicodePlots.label!(obj, :bl, string(xlim[1]), color=:dark_gray) UnicodePlots.label!(obj, :br, string(xlim[2]), color=:dark_gray) end annotate_y_axis!(obj) = begin if kind == :step #HACK: show original string of symbol instead of index number for (i, y) in zip(height:-1:1, ycat) UnicodePlots.label!(obj, :l, i, string(y), color=:dark_gray) end end end if isnothing(p) a = Float64[] !isnothing(aspect) && (width = round(Int, aspect * 2height)) obj = UnicodePlots.Plot(a, a; canvas, title, xlabel=xlab, ylabel=ylab, xlim=xlimval, ylim, width, height) UnicodePlots.label!(obj, :r, legend) annotate_x_axis!(obj) annotate_y_axis!(obj) p = Plot(obj; Xs=[], Ys=[], kinds=[], colors=[], title, xlab, ylab, legend, names, xlim, ylim, xunit, yunit, aspect, width, height) end colors = create_colors(colors; n0=length(p.opt[:Ys])) for (i, (Y, name)) in enumerate(zip(Ys, names)) #HACK: UnicodePlots can't handle missing Y = coalesce.(Y, NaN) color = colors[i] plot!(p.obj, X, Y; name, color) #TODO: remember colors update!(p; Xs=[X], Ys=[Y], kinds=[kind], colors=[color]) end p end plot3!(::Val{:UnicodePlots}, X, Y, Z; kind, title, legend, legendpos, xlab, ylab, zlab, xlim, ylim, zlim, zgap, zlabgap, aspect, width=nothing, height=30) = begin if kind == :heatmap ; elseif kind == :contour @warn "unsupported plot kind = $kind" else error("unrecognized plot kind = $kind") end !legend && @warn "unsupported legend = $legend" !isnothing(legendpos) && @warn "unsupported legend position = $legendpos" !isnothing(zgap) && @warn "unsupported contour interval = $zgap" !isnothing(zlabgap) && @warn "unsupported countour label interval = $zlabgap" arr(a) = sort(unique(a)) x = arr(X) y = arr(Y) M = reshape(Z, length(y), length(x)) offset(a) = a[1] xoffset = offset(x) yoffset = offset(y) fact(a) = (a[end] - offset(a)) / (length(a) - 1) xfact = fact(x) yfact = fact(y) !isnothing(aspect) && (width = round(Int, aspect * height)) #TODO: support zlim (minz/maxz currentyl fixed in UnicodePlots) obj = UnicodePlots.heatmap(M; title, xlabel=xlab, ylabel=ylab, zlabel=zlab, xfact, yfact, xlim, ylim, xoffset, yoffset, width, height) Plot(obj; X, Y, Z, kind, title, xlab, ylab, zlab, xlim, ylim, zlim, aspect, width, height) end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
677
using Cropbox using Test @testset "cropbox" begin @testset "framework" begin include("framework/macro.jl") include("framework/state.jl") include("framework/system.jl") include("framework/unit.jl") include("framework/config.jl") include("framework/graph.jl") include("framework/util.jl") end @testset "examples" begin include("examples/lotka_volterra.jl") include("examples/pheno.jl") include("examples/gasexchange.jl") include("examples/root.jl") include("examples/soil.jl") include("examples/simplecrop.jl") include("examples/garlic.jl") end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
524
using Cropbox using Garlic using Test @testset "garlic" begin r = simulate(Garlic.Model; config=Garlic.Examples.AoB.KM_2014_P2_SR0, stop="calendar.count", snap=s -> Dates.hour(s.calendar.time') == 12, ) @test r.leaves_initiated[end] > 0 visualize(r, :DAP, [:leaves_appeared, :leaves_mature, :leaves_dropped], kind=:step) |> println # Fig. 3.D visualize(r, :DAP, :green_leaf_area) |> println # Fig. 4.D visualize(r, :DAP, [:leaf_mass, :bulb_mass, :total_mass]) |> println end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
4577
using Cropbox using LeafGasExchange using Test "Kim et al. (2007), Kim et al. (2006)" ge_maize1 = :C4 => ( Vpm25 = 70, Vcm25 = 50, Jm25 = 300, Rd25 = 2 ) "In von Cammerer (2000)" ge_maize2 = :C4 => ( Vpm25 = 120, Vcm25 = 60, Jm25 = 400, ) "In Kim et al.(2006), under elevated CO2, YY" ge_maize3 = :C4 => ( Vpm25 = 91.9, Vcm25 = 71.6, Jm25 = 354.2, Rd25 = 2, # Values in Kim (2006) are for 31C, and the values here are normalized for 25C. SK ) """ switchgrass params from Albaugha et al. (2014) https://doi.org/10.1016/j.agrformet.2014.02.013 """ ge_switchgrass1 = :C4 => (Vpm25 = 52, Vcm25 = 26, Jm25 = 145) """ switchgrass Vcmax from Le et al. (2010), others multiplied from Vcmax (x2, x5.5) """ ge_switchgrass2 = :C4 => (Vpm25 = 96, Vcm25 = 48, Jm25 = 264) ge_switchgrass3 = :C4 => (Vpm25 = 100, Vcm25 = 50, Jm25 = 200) ge_switchgrass4 = :C4 => (Vpm25 = 70, Vcm25 = 50, Jm25 = 180.8) "switchgrass params from Albaugha et al. (2014)" ge_switchgrass_base = :C4 => ( Rd25 = 3.6, # not sure if it was normalized to 25 C θ = 0.79, ) "In Sinclair and Horie, Crop Sciences, 1989" ge_ndep1 = :NitrogenDependence => (s = 4, N0 = 0.2) "In J Vos et al. Field Crop Research, 2005" ge_ndep2 = :NitrogenDependence => (s = 2.9, N0 = 0.25) "In Lindquist, Weed Science, 2001" ge_ndep3 = :NitrogenDependence => (s = 3.689, N0 = 0.5) """ in P. J. Sellers, et al.Science 275, 502 (1997) g0 is b, of which the value for c4 plant is 0.04 and g1 is m, of which the value for c4 plant is about 4 YY """ ge_stomata1 = :StomataBallBerry => (g0 = 0.04, g1 = 4.0) """ Ball-Berry model parameters from Miner and Bauerle 2017, used to be 0.04 and 4.0, respectively (2018-09-04: KDY) """ ge_stomata2 = :StomataBallBerry => (g0 = 0.017, g1 = 4.53) "calibrated above for our switchgrass dataset" ge_stomata3 = :StomataBallBerry => (g0 = 0.04, g1 = 1.89) ge_stomata4 = :StomataBallBerry => (g0 = 0.02, g1 = 2.0) "parameters from Le et. al (2010)" ge_stomata5 = :StomataBallBerry => (g0 = 0.008, g1 = 8.0) "for garlic" ge_stomata6 = :StomataBallBerry => (g0 = 0.0096, g1 = 6.824) ge_water1 = :StomataTuzet => ( sf = 2.3, # sensitivity parameter Tuzet et al. 2003 Yang ϕf = -1.2, # reference potential Tuzet et al. 2003 Yang ) "switchgrass params from Le et al. (2010)" ge_water2 = :StomataTuzet => ( #? = -1.68, # minimum sustainable leaf water potential (Albaugha 2014) sf = 6.5, ϕf = -1.3, ) """ August-Roche-Magnus formula gives slightly different parameters https://en.wikipedia.org/wiki/Clausius–Clapeyron_relation """ ge_vaporpressure1 = :VaporPressure => ( a = 0.61094, # kPa b = 17.625, # C c = 243.04, # C ) ge_weather = :Weather => ( PFD = 1500, CO2 = 400, RH = 60, T_air = 30, wind = 2.0, ) ge_spad = :Nitrogen => ( _a = 0.0004, _b = 0.0120, _c = 0, SPAD = 60, ) ge_water = :StomataTuzet => ( #WP_leaf = 0, sf = 2.3, Ψf = -1.2, ) ge_base = (ge_weather, ge_spad, ge_water) #HACK: zero CO2 prevents convergence of bisection method ge_step_c = :Weather => :CO2 => 10:10:1500 ge_step_q = :Weather => :PFD => 0:20:2000 ge_step_t = :Weather => :T_air => -10:1:50 @testset "gasexchange" begin @testset "C3" begin @testset "A-Ci" begin Cropbox.visualize(LeafGasExchange.ModelC3MD, :Ci, [:A_net, :Ac, :Aj, :Ap]; config=ge_base, xstep=ge_step_c) |> println end @testset "A-Q" begin Cropbox.visualize(LeafGasExchange.ModelC3MD, :PFD, [:A_net, :Ac, :Aj, :Ap]; config=ge_base, xstep=ge_step_q) |> println end @testset "A-T" begin Cropbox.visualize(LeafGasExchange.ModelC3MD, :T_air, [:A_net, :Ac, :Aj, :Ap]; config=ge_base, xstep=ge_step_t) |> println end end @testset "C4" begin @testset "A-Ci" begin Cropbox.visualize(LeafGasExchange.ModelC4MD, :Ci, [:A_net, :Ac, :Aj]; config=ge_base, xstep=ge_step_c) |> println end @testset "A-Q" begin Cropbox.visualize(LeafGasExchange.ModelC4MD, :PFD, [:A_net, :Ac, :Aj]; config=ge_base, xstep=ge_step_q) |> println end @testset "A-T" begin Cropbox.visualize(LeafGasExchange.ModelC4MD, :T_air, [:A_net, :Ac, :Aj]; config=ge_base, xstep=ge_step_t) |> println end end @testset "N vs Ψv" begin Cropbox.visualize(LeafGasExchange.ModelC4MD, :N, :Ψv, :A_net; config=ge_base, kind=:heatmap, xstep=:Nitrogen=>:N=>0:0.05:2, ystep=:StomataTuzet=>:WP_leaf=>-2:0.05:0, ) |> println end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
1074
@testset "lotka volterra" begin @system LotkaVolterra(Controller) begin t(context.clock.time) ~ track(u"yr") N(N, P, b, a): prey_population => b*N - a*N*P ~ accumulate(init=N0) P(N, P, c, a, m): predator_population => c*a*N*P - m*P ~ accumulate(init=P0) N0: prey_initial_population ~ preserve(parameter) P0: predator_initial_population ~ preserve(parameter) b: prey_birth_rate ~ preserve(u"yr^-1", parameter) a: predation_rate ~ preserve(u"yr^-1", parameter) c: predator_reproduction_rate ~ preserve(parameter) m: predator_mortality_rate ~ preserve(u"yr^-1", parameter) end config = @config ( :Clock => (; step = 1u"d", ), :LotkaVolterra => (; b = 0.6, a = 0.02, c = 0.5, m = 0.5, N0 = 20, P0 = 30, ), ) stop = 20u"yr" r = simulate(LotkaVolterra; config, stop) @test r.t[end] >= stop visualize(r, :t, [:N, :P], names=["prey", "predator"]) |> println end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
2431
module Pheno using Cropbox using TimeZones import Dates @system Estimator begin year ~ preserve::int(parameter) # 270(+1)th days of the first year (around end of September) Ds: start_date_offset => 270 ~ preserve::int(u"d") # 150 days after the second year (around end of May) De: end_date_offset => 150 ~ preserve::int(u"d") tz: timezone => tz"UTC" ~ preserve::TimeZone(parameter) t0(year, tz, Ds): start_date => begin ZonedDateTime(year-1, 1, 1, tz) + Dates.Day(Ds) end ~ preserve::datetime t1(year, tz, De): end_date => begin ZonedDateTime(year, 1, 1, tz) + Dates.Day(De) end ~ preserve::datetime calendar(context, init=t0') ~ ::Calendar t(calendar.time): current_date ~ track::datetime s: store ~ provide(init=t, parameter) match => false ~ flag stop(m=match, t, t1) => (m || t >= t1) ~ flag T: temperature ~ drive(from=s, by=:tavg, u"°C") end estimate(S::Type{<:Estimator}, years; config, index=[:year, "calendar.time"], target=[:match], stop=:stop, kwargs...) = begin configs = @config config + !(S => :year => years) simulate(S; index, target, configs, stop, snap=:match, kwargs...) end @system BetaFuncEstimator(BetaFunction, Estimator, Controller) <: Estimator begin Rg: growth_requirement ~ preserve(parameter) Cg(ΔT): growth_cumulated ~ accumulate match(Cg, Rg) => Cg >= Rg ~ flag end end using DataFrames using TimeZones import Dates @testset "pheno" begin t0 = ZonedDateTime(2016, 9, 1, tz"UTC") t1 = ZonedDateTime(2018, 9, 30, tz"UTC") dt = Dates.Hour(1) T = collect(t0:dt:t1); df = DataFrame(index=T, tavg=25.0); Rg = 1000 config = ( :Estimator => ( :tz => tz"UTC", :store => df, ), :BetaFuncEstimator => ( :To => 20, :Tx => 35, :Rg => Rg, ) ) @testset "single" begin r = Pheno.estimate(Pheno.BetaFuncEstimator, 2017; config, target=[:ΔT, :Cg, :match, :stop]) @test nrow(r) == 1 r1 = r[1, :] @test r1.match == true @test r1.stop == true @test r1.Cg >= Rg end @testset "double" begin r = Pheno.estimate(Pheno.BetaFuncEstimator, [2017, 2018]; config, target=[:ΔT, :Cg, :match, :stop]) @test nrow(r) == 2 @test all(r.match) @test all(r.stop) @test all(r.Cg .>= Rg) end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
14181
using Cropbox using CropRootBox using Test # using DataFrames # using Statistics # import Gadfly root_maize = ( :RootArchitecture => :maxB => 5, :BaseRoot => :T => [ # P F S 0 1 0 ; # P 0 0 1 ; # F 0 0 0 ; # S ], :PrimaryRoot => (; lb = 0.1 ± 0.01, la = 18.0 ± 1.8, ln = 0.6 ± 0.06, lmax = 89.7 ± 7.4, r = 6.0 ± 0.6, Δx = 0.5, σ = 10, θ = 80 ± 8, N = 1.5, a = 0.04 ± 0.004, color = CropRootBox.RGBA(1, 0, 0, 1), ), :FirstOrderLateralRoot => (; lb = 0.2 ± 0.04, la = 0.4 ± 0.04, ln = 0.4 ± 0.03, lmax = 0.6 ± 1.6, r = 2.0 ± 0.2, Δx = 0.1, σ = 20, θ = 70 ± 15, N = 1, a = 0.03 ± 0.003, color = CropRootBox.RGBA(0, 1, 0, 1), ), :SecondOrderLateralRoot => (; lb = 0, la = 0.4 ± 0.02, ln = 0, lmax = 0.4, r = 2.0 ± 0.2, Δx = 0.1, σ = 20, θ = 70 ± 10, N = 2, a = 0.02 ± 0.002, color = CropRootBox.RGBA(0, 0, 1, 1), ) ) root_switchgrass_N = ( :RootArchitecture => :maxB => 24, :BaseRoot => :T => [ # P F S 0 1 0 ; # P 0 0 1 ; # F 0 0 0 ; # S ], :PrimaryRoot => (; lb = 0.41 ± 0.26, la = 0.63 ± 0.50, ln = 0.27 ± 0.07, lmax = 33.92 ± 22.60, r = 1 ± 0.1, Δx = 0.5, σ = 9, θ = 60 ± 6, N = 1.5, a = (0.62 ± 0.06)u"mm", # (0.62 ± 0.41)u"mm", color = CropRootBox.RGBA(1, 0, 0, 1), ), :FirstOrderLateralRoot => (; lb = 0.63 ± 0.45, la = 1.12 ± 1.42, ln = 0.23 ± 0.11, lmax = 7.03 ± 6.84, r = 0.21 ± 0.02, Δx = 0.1, σ = 18, θ = 60 ± 6, N = 1, a = (0.22 ± 0.02)u"mm", # (0.22 ± 0.07)u"mm", color = CropRootBox.RGBA(0, 1, 0, 1), ), :SecondOrderLateralRoot => (; lb = 0.45 ± 0.64, la = 0.71 ± 0.64, ln = 0.14 ± 0.10, lmax = 2.77 ± 2.68, r = 0.08 ± 0.01, Δx = 1, σ = 20, θ = 60 ± 6, N = 2, a = (0.19 ± 0.02)u"mm", # (0.19 ± 0.10)u"mm", color = CropRootBox.RGBA(0, 0, 1, 1), ) ) root_switchgrass_W = ( :RootArchitecture => :maxB => 22, :BaseRoot => :T => [ # P F S 0 1 0 ; # P 0 0 1 ; # F 0 0 0 ; # S ], :PrimaryRoot => (; lb = 0.40 ± 0.45, la = 3.37 ± 2.89, ln = 0.31 ± 0.06, lmax = 42.33 ± 30.54, r = 1 ± 0.1, Δx = 0.5, σ = 9, θ = 60 ± 6, N = 1.5, a = (0.71 ± 0.07)u"mm", # (0.71 ± 0.65)u"mm", color = CropRootBox.RGBA(1, 0, 0, 1), ), :FirstOrderLateralRoot => (; lb = 0.59 ± 0.48, la = 0.74 ± 0.87, ln = 0.09 ± 0.09, lmax = 1.79 ± 1.12, r = 0.04 ± 0.01, Δx = 0.1, σ = 18, θ = 60 ± 6, N = 1, a = (0.19 ± 0.02)u"mm", # (0.19 ± 0.08)u"mm", color = CropRootBox.RGBA(0, 1, 0, 1), ), :SecondOrderLateralRoot => (; lb = 0, la = 0.07 ± 0.04, ln = 0, lmax = 0.07 ± 0.04, r = 0.002 ± 0.001, Δx = 1, σ = 20, θ = 60 ± 6, N = 2, a = (0.19 ± 0.08)u"mm", # 0.68 ± 0.77 color = CropRootBox.RGBA(0, 0, 1, 1), ) ) root_switchgrass_N2 = ( :RootArchitecture => :maxB => 24, :BaseRoot => :T => [ # P F S 0 1 0 ; # P 0 0 0 ; # F 0 0 0 ; # S ], :PrimaryRoot => (; lb = 0.67 ± 0.25, la = 0.58 ± 0.96, ln = 0.25 ± 0.06, lmax = 11.85 ± 12.63, r = 1 ± 0.1, Δx = 0.5, σ = 9, θ = 60 ± 6, N = 1.5, a = (0.78 ± 0.08)u"mm", # (0.78 ± 0.27)u"mm", color = CropRootBox.RGBA(1, 0, 0, 1), ), :FirstOrderLateralRoot => (; lb = 0.20 ± 0.15, la = 0.94 ± 1.12, ln = 0.12 ± 0.06, lmax = 8.04 ± 7.57, r = 0.68 ± 0.07, Δx = 0.1, σ = 18, θ = 60 ± 6, N = 1, a = (0.35 ± 0.04)u"mm", # (0.35 ± 0.38)u"mm", color = CropRootBox.RGBA(0, 1, 0, 1), ), ) root_switchgrass_W2 = ( :RootArchitecture => :maxB => 22, :BaseRoot => :T => [ # P F S 0 1 0 ; # P 0 0 0 ; # F 0 0 0 ; # S ], :PrimaryRoot => (; lb = 0.08 ± 0.07, la = 4.32 ± 1.86, ln = 0.21 ± 0.05, lmax = 22.80 ± 11.94, r = 1 ± 0.1, Δx = 0.5, σ = 9, θ = 60 ± 6, N = 1.5, a = (0.40 ± 0.04)u"mm", # (0.40 ± 0.15)u"mm", color = CropRootBox.RGBA(1, 0, 0, 1), ), :FirstOrderLateralRoot => (; lb = 0.41 ± 0.35, la = 1.39 ± 1.00, ln = 0.10 ± 0.13, lmax = 2.37 ± 1.41, r = 0.10 ± 0.01, Δx = 0.1, σ = 18, θ = 60 ± 6, N = 1, a = (0.21 ± 0.02)u"mm", # (0.21 ± 0.06)u"mm", color = CropRootBox.RGBA(0, 1, 0, 1), ), ) root_switchgrass_P = (root_switchgrass_W, :Clock => (; step = 1u"hr", ), :BaseRoot => :T => [ # P F S 0 1 0 ; # P 0 0 1 ; # F 0 0 0 ; # S ], :PrimaryRoot => (; Δx = 0.5, ), :FirstOrderLateralRoot => (; Δx = 0.1, ), :SecondOrderLateralRoot => (; Δx = 1, ) ) root_switchgrass_KH2PO4 = ( root_switchgrass_P, :PrimaryRoot => (; r = 1.28 ± 0.29, ), :FirstOrderLateralRoot => (; lmax = 1.63 ± 0.61, #ln = 0.163 ± 0.061, r = 0.31 ± 0.11, θ = 84.27 ± 3.03, ), :SecondOrderLateralRoot => (; lmax = 2.30 ± 0.65, r = 0.48 ± 0.15, θ = 41.87 ± 6.64, ) ) root_switchgrass_AlPO4 = ( root_switchgrass_P, :PrimaryRoot => (; r = 1.10 ± 0.32, ), :FirstOrderLateralRoot => (; lmax = 1.56 ± 0.55, #ln = 0.156 ± 0.055, r = 0.33 ± 0.11, θ = 83.53 ± 3.42, ), :SecondOrderLateralRoot => (; lmax = 2.29 ± 0.60, r = 0.48 ± 0.13, θ = 34.87 ± 5.17, ) ) root_switchgrass_C6H17NaO24P6 = ( root_switchgrass_P, :PrimaryRoot => (; r = 1.31 ± 0.35, ), :FirstOrderLateralRoot => (; lmax = 2.80 ± 0.61, #ln = 0.28 ± 0.061, r = 0.57 ± 0.09, θ = 78.07 ± 5.30, ), :SecondOrderLateralRoot => (; lmax = 3.05 ± 0.50, r = 0.65 ± 0.17, θ = 43.73 ± 6.71, ) ) container_pot = :Pot => (; r1 = 10, r2 = 6, height = 30, ) container_rhizobox = :Rhizobox => (; l = 16u"inch", w = 10.5u"inch", h = 42u"inch", ) soilcore = :SoilCore => (; d = 4, l = 20, x0 = 3, y0 = 3, ) @testset "root" begin b = instance(CropRootBox.Pot, config=container_pot) s = instance(CropRootBox.RootArchitecture; config=root_maize, options=(; box=b), seed=0) r = simulate!(s, stop=100u"d") @test r.time[end] == 100u"d" # using GLMakie # scn = CropRootBox.render(s) # GLMakie.save("root_maize.png", scn) CropRootBox.writevtk(tempname(), s) # CropRootBox.writepvd(tempname(), CropRootBox.RootArchitecture, config=root_maize, stop=50) CropRootBox.writestl(tempname(), s) end # @testset "switchgrass" begin # C = Dict( # :KH2PO4 => root_switchgrass_KH2PO4, # :AlPO4 => root_switchgrass_AlPO4, # :C6H17NaO24P6 => root_switchgrass_C6H17NaO24P6, # ) # b = instance(CropRootBox.Rhizobox, config=container_rhizobox) # P = [1, 4, 8, 12, 16, 20, 24]u"wk" # R = [] # for i in 1:10, c in (:KH2PO4, :AlPO4, :C6H17NaO24P6) # n = "$c-$i" # r = simulate(CropRootBox.RootArchitecture; config=C[c], options=(; box=b), seed=i, stop=P[end]) do D, s # t = s.context.clock.time' |> u"wk" # if t in P # p = deunitfy(t, u"wk") |> Int # CropRootBox.writevtk("$n-w$p", s) # G = gather!(s, CropRootBox.BaseRoot; callback=CropRootBox.gatherbaseroot!) # D[1][:time] = t # D[1][:treatment] = c # D[1][:repetition] = i # D[1][:length] = !isempty(G) ? sum([s.length' for s in G]) : 0.0u"cm" # D[1][:volume] = !isempty(G) ? sum([s.length' * s.radius'^2 for s in G]) : 0.0u"mm^3" # D[1][:count] = length(G) # else # empty!(D) # end # end # push!(R, r) # end # df = vcat(R...) # combine(groupby(df, [:treatment, :time]), :length => mean, :length => std) |> println # Gadfly.plot(df, x=:time, y=:length, color=:treatment, # Gadfly.Geom.boxplot, # Gadfly.Scale.x_discrete, # Gadfly.Guide.xlabel("Time"), # Gadfly.Guide.ylabel("Total Root Length Per Plant"), # Gadfly.Guide.colorkey(title="", pos=[0.05*Gadfly.w, -0.4*Gadfly.h]), # Gadfly.Theme(boxplot_spacing=7*Gadfly.mm) # ) |> Gadfly.SVG("switchgrass_P.svg") # end # using DataStructures: OrderedDict # @testset "switchgrass rhizobox" begin # C = OrderedDict( # :W => root_switchgrass_W, # :N => root_switchgrass_N, # ) # R = [] # for (k, c) in C # n = "switchgrass_$k" # b = instance(CropRootBox.Rhizobox, config=container_rhizobox) # s = instance(CropRootBox.RootArchitecture; config=c, options=(; box=b), seed=0) # r = simulate!(s, stop=1000) do D, s # G = gather!(s, CropRootBox.BaseRoot; callback=CropRootBox.gatherbaseroot!) # D[1][:length] = !isempty(G) ? sum([s.length' for s in G]) : 0.0u"cm" # D[1][:volume] = !isempty(G) ? sum([s.length' * s.radius'^2 for s in G]) : 0.0u"mm^3" # D[1][:count] = length(G) # end # push!(R, r) # plot(r, :time, :length, kind=:line, backend=:Gadfly)[] |> Cropbox.Gadfly.PDF("$n-length.pdf") # plot(r, :time, :volume, yunit=u"mm^3", kind=:line, backend=:Gadfly)[] |> Cropbox.Gadfly.PDF("$n-volume.pdf") # plot(r, :time, :count, kind=:line, backend=:Gadfly)[] |> Cropbox.Gadfly.PDF("$n-count.pdf") # CropRootBox.writevtk(n, s) # end # save(x, y, f; kw...) = begin # K = collect(keys(C)) # p = plot(R[1], x, y; name=string(K[1]), title=string(y), kind=:line, backend=:Gadfly, kw...) # for i in 2:length(R) # p = plot!(p, R[i], x, y; name=string(K[i]), kind=:line, backend=:Gadfly, kw...) # end # p[] |> Cropbox.Gadfly.PDF(f) # end # save(:time, :length, "switchgrass-length.pdf") # save(:time, :volume, "switchgrass-volume.pdf"; yunit=u"mm^3") # save(:time, :count, "switchgrass-count.pdf") # end # @testset "switchgrass layer" begin # C = Dict( # :W => root_switchgrass_W, # :N => root_switchgrass_N, # ) # for (k, c) in C # n = "switchgrass_$k" # b = instance(CropRootBox.Rhizobox, config=container_rhizobox) # L = [instance(CropRootBox.SoilLayer, config=:SoilLayer => (; d, t=1)) for d in 0:1:10] # s = instance(CropRootBox.RootArchitecture; config=c, options=(; box=b), seed=0) # r = simulate!(s, stop=300) do D, s # G = gather!(s, CropRootBox.BaseRoot; callback=CropRootBox.gatherbaseroot!) # for (i, l) in enumerate(L) # V = [s.length' for s in G if s.ii(l)] # D[1][Symbol("L$(i-1)")] = !isempty(V) ? sum(V) : 0.0u"cm" # end # end # plot(r, :time, [Symbol("L$(i-1)") for i in 1:length(L)], kind=:line, backend=:Gadfly)[] |> Cropbox.Gadfly.PDF("L$n.pdf") # CropRootBox.writevtk(n, s) # end # end # @testset "switchgrass" begin # C = Dict( # :KH2PO4 => root_switchgrass_KH2PO4, # :AlPO4 => root_switchgrass_AlPO4, # :C6H17NaO24P6 => root_switchgrass_C6H17NaO24P6, # ) # b = instance(CropRootBox.Rhizobox, config=container_rhizobox) # o = instance(CropRootBox.SoilCore, config=soilcore) # p = 24u"wk" # for i in 1:1, c in (:KH2PO4, :AlPO4, :C6H17NaO24P6) # n = "$c-$i" # s = instance(CropRootBox.RootArchitecture; config=C[c], options=(; box=b), seed=i) # simulate!(s, stop=p) # m = CropRootBox.mesh(s; container=o) # CropRootBox.writestl("switchgrass-core-" * n * ".stl", m) # CropRootBox.writestl("switchgrass-" * n * ".stl", s) # end # end # @testset "maize layer" begin # n = "maize" # b = instance(CropRootBox.Pot, config=container_pot) # t = 5 # L = [instance(CropRootBox.SoilLayer, config=:SoilLayer => (; d, t)) for d in 0:t:30-t] # s = instance(CropRootBox.RootArchitecture; config=root_maize, options=(; box=b), seed=0) # r = simulate!(s, stop=500) do D, s # G = gather!(s, CropRootBox.BaseRoot; callback=CropRootBox.gatherbaseroot!) # for (i, l) in enumerate(L) # ll = [s.length' for s in G if s.ii(l)] # D[1][Symbol("L$(i-1)")] = !isempty(ll) ? sum(ll) : 0.0u"cm" # vl = [s.length' * s.radius'^2 for s in G if s.ii(l)] # D[1][Symbol("V$(i-1)")] = !isempty(vl) ? sum(vl) : 0.0u"cm^3" # D[1][Symbol("C$(i-1)")] = length(vl) # end # end # plot(r, :time, [Symbol("L$(i-1)") for i in 1:length(L)], legend="soil depth", names=["$((i-1)*t) - $(i*t) cm" for i in 1:length(L)], title="total length", kind=:line, backend=:Gadfly)[] |> Cropbox.Gadfly.PDF("L$n.pdf") # plot(r, :time, [Symbol("V$(i-1)") for i in 1:length(L)], legend="soil depth", names=["$((i-1)*t) - $(i*t) cm" for i in 1:length(L)], title="total volume", yunit=u"mm^3", kind=:line, backend=:Gadfly)[] |> Cropbox.Gadfly.PDF("V$n.pdf") # plot(r, :time, [Symbol("C$(i-1)") for i in 1:length(L)], legend="soil depth", names=["$((i-1)*t) - $(i*t) cm" for i in 1:length(L)], title="count", kind=:line, backend=:Gadfly)[] |> Cropbox.Gadfly.PDF("C$n.pdf") # CropRootBox.writevtk(n, s) # end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
632
using Cropbox using SimpleCrop using Test using CSV using DataFrames using TimeZones loaddata(f) = CSV.File(joinpath(@__DIR__, "data/simplecrop", f)) |> DataFrame config = @config ( :Clock => :step => 1u"d", :Calendar => :init => ZonedDateTime(1987, 1, 1, tz"UTC"), :Weather => :weather_data => loaddata("weather.csv"), :SoilWater => :irrigation_data => loaddata("irrigation.csv"), ) @testset "simplecrop" begin r = simulate(SimpleCrop.Model; config, stop = :endsim) visualize(r, :DATE, :LAI; kind = :line) |> println visualize(r, :DATE, :(SWC/DP); yunit = u"mm^3/mm^3", kind = :line) |> println end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
14648
module SoilWater using Cropbox @system Pedotransfer begin Ψ_wp: tension_wilting_point => 1500 ~ preserve(u"kPa", parameter) Ψ_fc: tension_field_capacity => 33 ~ preserve(u"kPa", parameter) Ψ_sat: tension_saturation => 0.01 ~ preserve(u"kPa", parameter) θ_wp: vwc_wilting_point ~ hold θ_fc: vwc_field_capacity ~ hold θ_sat: vwc_saturation ~ hold K_at(; vwc): hydraulic_conductivity_at ~ hold Hm_at: matric_head_at ~ hold end @system TabularPedotransfer(Pedotransfer) begin vwc2hc => [ 0.005 3.46e-9; 0.050 4.32e-8; 0.100 1.3e-7; 0.150 6.91e-7; 0.200 4.32e-6; 0.250 2.59e-5; 0.300 0.000173; 0.350 0.001037; 0.400 0.006912; 0.450 0.0432; 1.000 0.0432; ] ~ interpolate(u"m/d") #hc_to_vwc(vwc_to_hc) ~ interpolate(reverse) vwc2ss => [ 0.005 10000; 0.010 3500; 0.025 1000; 0.050 200; 0.100 40; 0.150 10; 0.200 6; 0.250 3.5; 0.300 2.2; 0.350 1.4; 0.400 0.56; 0.450 0.001; #HACK: no duplicate 0 1.000 0; ] ~ interpolate(u"m") ss2vwc(vwc2ss) ~ interpolate(reverse) head(; Ψ(u"kPa")) => (Ψ * u"m" / 9.8041u"kPa") ~ call(u"m") θ_wp(ss2vwc, head, Ψ_wp): vwc_wilting_point => ss2vwc(head(Ψ_wp)) ~ preserve # 0.02? 0.06 θ_fc(ss2vwc, head, Ψ_fc): vwc_field_capacity => ss2vwc(head(Ψ_fc)) ~ preserve # 0.11? 0.26 θ_sat(ss2vwc, head, Ψ_sat): vwc_saturation => ss2vwc(head(Ψ_sat)) ~ preserve # 0.45 K_at(vwc2hc; θ): hydraulic_conductivity_at => vwc2hc(θ) ~ call(u"m/d") Hm_at(vwc2ss; θ): matric_head_at => vwc_ss(θ) ~ call(u"m") # vwc_airdry_water => 0.01 ~ preserve(parameter) # vwc_wilting_point => 0.07 ~ preserve(parameter) # initial_vwc => 0.4 ~ preserve(parameter) # rooting_depth => 0.2 ~ preserve(u"m", parameter) # iteration_per_time_step => 100 ~ preserve(parameter) end @system Texture begin S: sand => 0.29 ~ preserve(parameter) C: clay => 0.32 ~ preserve(parameter) OM: organic_matter => 1.5 ~ preserve(u"percent", parameter) end @system CharacteristicTransfer(Pedotransfer, Texture) begin DF: density_factor => 1.0 ~ preserve(parameter) # volumetric soil water content at permanent wilting point θ_1500t(S, C, OM): vwc_1500_first => begin -0.024S + 0.487C + 0.006OM + 0.005S*OM - 0.013C*OM + 0.068S*C + 0.031 end ~ preserve # theta_1500t (%v) θ_1500(θ=θ_1500t): vwc_1500 => begin θ + (0.14θ - 0.02) end ~ preserve # theta_1500 (%v) θ_wp(θ_1500): vwc_wilting_point ~ preserve # volumetric soil water content at field capacity θ_33t(S, C, OM): vwc_33_first => begin -0.251S + 0.195C + 0.011OM + 0.006S*OM - 0.027C*OM + 0.452S*C + 0.299 end ~ preserve # theta_33t (%v) θ_33(θ=θ_33t): vwc_33_normal => begin θ + (1.283θ^2 - 0.374θ - 0.015) end ~ preserve # theta_33 (%v) θ_33_DF(θ_33, θ_s, θ_s_DF): vwc_33_adjusted => begin θ_33 - 0.2(θ_s - θ_s_DF) end ~ preserve # theta_33_DF (%v) θ_fc(θ_33_DF): vwc_field_capacity ~ preserve # volumetric soil water content between saturation and field capacity θ_s_33t(S, C, OM): vwc_gravitation_first => begin 0.278S + 0.034C +0.022OM - 0.018S*OM - 0.027C*OM - 0.584S*C + 0.078 end ~ preserve # theta_s_33t (%v) θ_s_33(θ=θ_s_33t): vwc_gravitation_normal => begin θ + (0.636θ - 0.107) end ~ preserve # theta_s_33 (%v) θ_s_33_DF(θ_s_DF, θ_33_DF): vwc_gravitation_adjusted => begin θ_s_DF - θ_33_DF end ~ preserve # theta_s_33_DF (%v) # volumetric soil water content at saturation θ_s(θ_33, θ_s_33, S): vwc_saturation_normal => begin θ_33 + θ_s_33 - 0.097S + 0.043 end ~ preserve # theta_s (%v) θ_s_DF(θ_s, ρ_DF, ρ_P): vwc_saturation_adjusted => begin 1 - ρ_DF / ρ_P end ~ preserve # theta_s_DF (%v) θ_sat(θ_s_DF): vwc_saturation ~ preserve # density effects ρ_DF(ρ_N, DF): matric_density => begin ρ_N * DF end ~ preserve(u"g/cm^3") # rho_DF (g cm-3) ρ_N(θ_s, ρ_P): normal_density => begin (1 - θ_s) * ρ_P end ~ preserve(u"g/cm^3") # rho_N (g cm-3) ρ_P: particle_density => begin 2.65 end ~ preserve(u"g/cm^3") # (g cm-3) # hydraulic conductivity (moisture - conductivity) # coefficients of moisture-tension, Eq. 11 of Saxton and Rawls 2006 A(B, θ_33): moisture_tension_curve_coeff_A => begin exp(log(33) + B*log(θ_33)) end ~ preserve B(θ_33, θ_1500): moisture_tension_curve_coeff_B => begin (log(1500) - log(33)) / (log(θ_33) - log(θ_1500)) end ~ preserve # slope of logarithmic tension-moisture curve λ(B): pore_size_distribution => begin 1 / B end ~ preserve K_s(θ_s, θ_33, λ): saturated_hydraulic_conductivity => begin 1930(θ_s - θ_33)^(3-λ) end ~ preserve(u"mm/hr") # K_s,i (m day-1) K_at(K_s, θ_s, λ; θ): hydraulic_conductivity_at => begin #TODO: need bounds check? # θ = min(θ, θ_s) # (Ψ_at(vwc) < Ψ_ae) && (θ = θ_s) K_s * (θ / θ_s)^(3 + 2/λ) end ~ call(u"mm/hr") # K_theta,i (m day-1) # soil matric suction (moisture - tension) Ψ_et(S, C, OM, θ=θ_s_33): tension_air_entry_first => begin -21.674S - 27.932C - 81.975θ + 71.121S*θ + 8.294C*θ + 14.05S*C + 27.161 end ~ preserve(u"kPa") # psi_et (kPa) Ψ_e(Ψ=nounit(Ψ_et, u"kPa")): tension_air_entry => begin Ψ_e = Ψ + (0.02Ψ^2 - 0.113Ψ - 0.70) #TODO: need bounds check? # max(Ψ_e, zero(Ψ_e)) end ~ preserve(u"kPa") # psi_e (kPa) Ψ_at(θ_s, θ_33, θ_1500, Ψ_e, A, B; θ): tension_at => begin if θ_s <= θ Ψ_e elseif θ_33 <= θ 33u"kPa" - (θ - θ_33) * (33u"kPa" - Ψ_e) / (θ_s - θ_33) elseif θ_1500 <= θ A*θ^-B else #@show "too low θ = $θ < θ_1500 = $θ_1500" A*θ^-B end end ~ call(u"kPa") # psi_theta (kPa) Hm_at(Ψ_at; θ): matric_head_at => begin Ψ_at(θ) * u"m" / 9.8041u"kPa" end ~ call(u"m") # H_mi (m) end #TODO: support convenient way to set up custom Clock #TODO: support unit reference again? @system SoilClock(Clock) <: Clock begin step => 15u"minute" ~ preserve(u"hr", parameter) end @system SoilContext(Context) <: Context begin context ~ ::Context(override) clock(config) ~ ::SoilClock end #TODO: implement LayeredTexture for customization @system Layer(CharacteristicTransfer) begin context ~ ::SoilContext(override) i: index ~ ::int(override) θ_i: vwc_initial => 0.4 ~ preserve(extern) # Soil layer depth and cumulative thickness (2.4.2) z: depth ~ preserve(u"m", extern) # z_i (m) d_r: rooting_depth ~ track(u"m", override) # d_root (m) s: thickness ~ preserve(u"m", extern) # s_i (m) ss: cumulative_thickness ~ preserve(u"m", extern) # S_i (m) s_r(s, ss, d_r): root_zone_thickness => begin z = zero(d_r) max(s - max(ss - d_r, z), z) end ~ track(u"m") # s_i | s_i - (S_i - d_root) (m) 𝚯_r(θ, s_r): water_content_root_zone => θ * s_r ~ track(u"m") # Theta_root,i (m) (Eq. 2.95) 𝚯_r_wp(θ_wp, s_r): water_content_root_zone_wilting_point => θ_wp * s_r ~ track(u"m") 𝚯_r_fc(θ_fc, s_r): water_content_root_zone_field_capacity => θ_fc * s_r ~ track(u"m") 𝚯_r_sat(θ_sat, s_r): water_content_root_zone_saturation => θ_sat * s_r ~ track(u"m") # Root extraction of water (2.4.5) ϕ(z, d_r): water_extraction_ratio => begin cj = iszero(d_r) ? 0 : min(1, z / d_r) 1.8cj - 0.8cj^2 end ~ track # phi_i # Hydraulic conductivity (2.4.6) K(K_at, θ): hydraulic_conductivity => K_at(θ) ~ track(u"m/d") # k_i (m day-1) # Matric suction head (2.4.7) Hm(Hm_at, θ): matric_head => Hm_at(θ) ~ track(u"m") # H_mi (m) # Gravity head (2.4.8) Hg(z): gravity_head ~ preserve(u"m") # H_gi (m) # Total head H(Hm, Hg): total_head => Hm + Hg ~ track(u"m") # H_i (m) # Water content (2.4.10) qi: water_flux_in => 0 ~ track(u"m/d", ref, skip) # q_i (m day-1) qo: water_flux_out => 0 ~ track(u"m/d", ref, skip) # q_o (m day-1) q̂(qi, qo): water_flux_net => qi - qo ~ track(u"m/d") # q^hat_i (m day-1) 𝚯(q̂): water_content ~ accumulate(init=𝚯_i, u"m") # Theta_i (m) 𝚯_i(θ_i, s): water_content_initial => θ_i * s ~ preserve(u"m") 𝚯_wp(θ_wp, s): water_content_wilting_point => θ_wp * s ~ track(u"m") 𝚯_fc(θ_fc, s): water_content_field_capacity => θ_fc * s ~ track(u"m") 𝚯_sat(θ_sat, s): water_content_saturation => θ_sat * s ~ track(u"m") # Volumetric water content (-) θ(i, 𝚯, 𝚯_wp, 𝚯_sat, s): volumetric_water_content => begin #FIXME: remove clamping? #HACK: clamping only for vwc # Teh uses 0.005 m3/m3 instead of wilting point #𝚯 = clamp(𝚯, 𝚯_wp, 𝚯_sat) θ = min(𝚯, 𝚯_sat) / s θ = max(θ, 0.005) end ~ track # Theta_v,i (m3 m-3) end @system SurfaceInterface begin context ~ ::SoilContext(override) l: layer ~ ::Layer(override) R: precipitation ~ track(u"m/d", override) Ea: evaporation_actual ~ track(u"m/d", override) Ta: transpiration_actual ~ track(u"m/d", override) Tai(Ta, ϕ=l.ϕ): water_extraction => begin Ta * ϕ end ~ track(u"m/d") q(R, Ea, Tai): flux => begin R - Ea - Tai end ~ track(u"m/d") _q(l, q) => begin Cropbox.setvar!(l, :qi, q) end ~ ::Nothing end @system SoilInterface begin context ~ ::SoilContext(override) l1: upper_layer ~ ::Layer(override) l2: lower_layer ~ ::Layer(override) Ta: transpiration_actual ~ track(u"m/d", override) K(K1=l1.K, K2=l2.K, s1=l1.s, s2=l2.s): hydraulic_conductivity => begin ((K1*s1) + (K2*s2)) / (s1 + s2) end ~ track(u"m/d") # k^bar (m day-1) # Hydraulic gradient (2.4.9) ΔH(H1=l1.H, H2=l2.H): hydraulic_gradient => begin H2 - H1 end ~ track(u"m") # (m) Δz(z1=l1.z, z2=l2.z): depth_gradient => begin z2 - z1 end ~ track(u"m") # (m) Tai(Ta, ϕ1=l1.ϕ, ϕ2=l2.ϕ): water_extraction => begin Ta * (ϕ2 - ϕ1) end ~ track(u"m/d") q(K, ΔH, Δz, Tai): flux => begin K * (ΔH / Δz) - Tai end ~ track(u"m/d") # q_i (m day-1) _q(l1, l2, q) => begin Cropbox.setvar!(l1, :qo, q) Cropbox.setvar!(l2, :qi, q) end ~ ::Nothing end @system BedrockInterface begin context ~ ::SoilContext(override) l: layer ~ ::Layer(override) q(l.K): flux ~ track(u"m/d") _q(l, q) => begin Cropbox.setvar!(l, :qo, q) end ~ ::Nothing end @system SoilWeather begin s: store ~ provide(index=:timestamp, init=1u"d", parameter) R: precipitation ~ drive(from=s, by=:precipitation, u"mm/d") T: transpiration ~ drive(from=s, by=:transpiration, u"mm/d") E: evaporation ~ drive(from=s, by=:evaporation, u"mm/d") end # w = instance(SoilWeather, config=( # :Clock => (:step => 24), # :SoilWeather => (:filename => "test/PyWaterBal.csv") # )) #FIXME: not just SoilClock, but entire Context should be customized for sub-timestep handling #TODO: implement sub-timestep advance # 2.4.11 Daily integration # iterations=100 # Theta_i,t+1 (m day-1) (Eq. 2.105) @system SoilModule begin context ~ ::SoilContext(override) w: weather ~ ::SoilWeather(override) d_r: rooting_depth ~ track(u"m", override) # d_root (m) # Partitioning of soil profile into several layers (2.4.1) L(context, d_r): layers => begin # Soil layer depth and cumulative thickness (2.4.2) n = 5 s = 0.2u"m" # thickness ss = 0u"m" # cumulative_thickness θ = 0.4 # vwc_initial L = Layer[] for i in 1:n z = ss + s/2 # depth l = Layer(; context, i, θ_i=θ, z, d_r, s, ss) push!(L, l) ss += s end L end ~ ::Vector{Layer} surface_interface(context, layer=L[1], R, Ea, Ta) ~ ::SurfaceInterface soil_interfaces(context, L, Ta) => begin [SoilInterface(; context, l1=a, l2=b, Ta) for (a, b) in zip(L[1:end-1], L[2:end])] end ~ ::Vector{SoilInterface} bedrock_interface(context, layer=L[end]) ~ ::BedrockInterface interfaces(L, surface_interface, soil_interfaces, bedrock_interface) => begin [surface_interface, soil_interfaces..., bedrock_interface] end ~ ::Vector{System}(skip) # Actual evaporation (2.4.3) RD_e(θ=L[1].θ, θ_sat=L[1].θ_sat): evaporation_reduction_factor => begin 1 / (1 + (3.6073 * (θ / θ_sat))^-9.3172) end ~ track # R_D,e Ep(w.E): evaporation_potential ~ track(u"m/d") Ea(Ep, RD_e): evaporation_actual => Ep * RD_e ~ track(u"m/d") # E_a (m day-1) # Actual transpiration (2.4.4) θ_r(L, d_r): volumetric_water_content_root_zone => begin sum(l.𝚯_r' for l in L) / d_r end ~ track # Theta_v,root (m3 m-3) θ_r_wp(L, d_r): volumetric_water_content_root_zone_wilting_point => begin sum(l.𝚯_r_wp' for l in L) / d_r end ~ track # (m3 m-3) θ_r_fc(L, d_r): volumetric_water_content_root_zone_field_capacity => begin sum(l.𝚯_r_fc' for l in L) / d_r end ~ track # (m3 m-3) θ_r_sat(L, d_r): volumetric_water_content_root_zone_saturation => begin sum(l.𝚯_r_sat' for l in L) / d_r end ~ track # (m3 m-3) RD_t(θ_r, θ_r_wp, θ_r_sat): transpiration_reduction_factor => begin θ_cr = (θ_r_wp + θ_r_sat) / 2 (θ_r - θ_r_wp) / (θ_cr - θ_r_wp) #FIXME: 0 instead of 0.01? end ~ track(min=0.01, max=1) # R_D,t Tp(w.T): transpiration_potential ~ track(u"m/d") Ta(Tp, RD_t): transpiration_actual => Tp * RD_t ~ track(u"m/d") # T_a (m day-1) R(w.R): precipitation ~ track(u"m/d") end @system SoilController(Controller) begin w(context, config): weather ~ ::SoilWeather sc(context, config): soil_context ~ ::SoilContext(context) d_r: rooting_depth => 0.3 ~ track(u"m") s(context=soil_context, w, d_r): soil ~ ::SoilModule end end @testset "soil" begin r = simulate(SoilWater.SoilController, stop=80u"d", config=( :Clock => (:step => 1u"d"), :SoilClock => (:step => 15u"minute"), :SoilWeather => (:store => "$(@__DIR__)/data/soil/PyWaterBal.csv"), ), target=( :v1 => "s.L[1].θ", :v2 => "s.L[2].θ", :v3 => "s.L[3].θ", :v4 => "s.L[4].θ", :v5 => "s.L[5].θ", ), ) @test r.time[end] == 80u"d" visualize(r, :time, [:v1, :v2, :v3, :v4, :v5], ylim=(0.2, 0.45)) |> println end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
18307
using DataStructures: OrderedDict @testset "config" begin @testset "configure" begin @testset "default" begin c = Cropbox.Config() @test Cropbox.configure() == c @test Cropbox.configure(()) == c @test Cropbox.configure(nothing) == c end @testset "error" begin @test_throws ErrorException Cropbox.configure(missing) @test_throws ErrorException Cropbox.configure(0) @test_throws ErrorException Cropbox.configure(:a) @test_throws ErrorException Cropbox.configure("a") end end @testset "system" begin @testset "pair" begin c = :S => :a => 1 C = Cropbox.configure(c) @test C[:S][:a] == 1 end @testset "tuple" begin c = (:S1 => :a => 1, :S2 => :a => 2) C = Cropbox.configure(c) @test C[:S1][:a] == 1 @test C[:S2][:a] == 2 end @testset "vector" begin c = [:S1 => :a => 1, :S2 => :a => 2] C = Cropbox.configure(c) C1 = Cropbox.configure(c[1]) C2 = Cropbox.configure(c[2]) @test C == [C1, C2] end @testset "type" begin @system SConfigSystemType begin a ~ preserve(parameter) end c = SConfigSystemType => :a => 1 C = Cropbox.configure(c) @test C[:SConfigSystemType][:a] == 1 end @testset "type with unit" begin @system SConfigSystemTypeUnit begin a ~ preserve(parameter, u"m") end c = SConfigSystemTypeUnit => :a => 1 C = Cropbox.configure(c) @test C[:SConfigSystemTypeUnit][:a] == 1u"m" end end @testset "variable" begin @testset "dict" begin v = Dict(:a => 1, :b => 2) C = Cropbox.configure(:S => v) @test C[:S][:a] == 1 @test C[:S][:b] == 2 end @testset "ordered dict" begin v = OrderedDict(:a => 1, :b => 2) C = Cropbox.configure(:S => v) @test C[:S][:a] == 1 @test C[:S][:b] == 2 end @testset "tuple" begin v = (:a => 1, :b => 2) C = Cropbox.configure(:S => v) @test C[:S][:a] == 1 @test C[:S][:b] == 2 end @testset "named tuple" begin v = (a=1, b=2) C = Cropbox.configure(:S => v) @test C[:S][:a] == 1 @test C[:S][:b] == 2 end @testset "pair" begin v = :a => 1 C = Cropbox.configure(:S => v) @test C[:S][:a] == 1 end end @testset "value" begin @testset "dict" begin v = Dict(:a => 1, :b => 2) C = Cropbox.configure(:S => :v => v) @test C[:S][:v] == v end @testset "ordered dict" begin v = OrderedDict(:a => 1, :b => 2) C = Cropbox.configure(:S => :v => v) @test C[:S][:v] == v end @testset "tuple" begin v = (:a => 1, :b => 2) C = Cropbox.configure(:S => :v => v) @test C[:S][:v] == v end @testset "named tuple" begin v = (a=1, b=2) C = Cropbox.configure(:S => :v => v) @test C[:S][:v] == v end @testset "pair" begin v = :a => 1 C = Cropbox.configure(:S => :v => v) @test C[:S][:v] == v end end @testset "check" begin @system SConfigCheck begin a ~ preserve(parameter) b: bb ~ preserve(parameter) end @test Cropbox.configure(SConfigCheck => :a => 1) == @config(:SConfigCheck => :a => 1) @test_throws ErrorException Cropbox.configure(SConfigCheck => :aa => 2) @test Cropbox.configure(SConfigCheck => :b => 3) == @config(:SConfigCheck => :b => 3) @test Cropbox.configure(SConfigCheck => :bb => 4) == @config(:SConfigCheck => :bb => 4) end @testset "merge" begin @testset "tuple" begin c = (:S1 => (:a => 1, :b => 2), :S2 => (:a => 3, :b => 4)) C = Cropbox.configure(c) @test C[:S1][:a] == 1 @test C[:S1][:b] == 2 @test C[:S2][:a] == 3 @test C[:S2][:b] == 4 end @testset "tuple override" begin c = (:S => (:a => 1, :b => 2), :S => :b => 3) C = Cropbox.configure(c) @test C[:S][:a] == 1 @test C[:S][:b] == 3 end @testset "config" begin C1 = Cropbox.configure(:S1 => :a => 1) C2 = Cropbox.configure(:S2 => :a => 2) C3 = Cropbox.configure(:S3 => :a => 3) C = Cropbox.configure(C1, C2, C3) @test C[:S1][:a] == 1 @test C[:S2][:a] == 2 @test C[:S3][:a] == 3 end @testset "config override" begin C1 = Cropbox.configure(:S => :a => 1) C2 = Cropbox.configure(:S => :a => 2) C = Cropbox.configure(C1, C2) @test C[:S][:a] == 2 end end @testset "multiply" begin @testset "solo" begin p = :S => :a => 1:2 C = Cropbox.configmultiply(p) @test C == Cropbox.configure.([:S => :a => 1, :S => :a => 2]) end @testset "duo" begin p1 = :S => :a => 1:2 p2 = :S => :b => 3:4 C = Cropbox.configmultiply(p1, p2) @test C == Cropbox.configure.([ :S => (a=1, b=3), :S => (a=1, b=4), :S => (a=2, b=3), :S => (a=2, b=4), ]) end @testset "trio" begin p1 = :S => :a => 1:2 p2 = :S => :b => 3:4 p3 = :S => :c => 5:6 C = Cropbox.configmultiply(p1, p2, p3) @test C == Cropbox.configure.([ :S => (a=1, b=3, c=5), :S => (a=1, b=3, c=6), :S => (a=1, b=4, c=5), :S => (a=1, b=4, c=6), :S => (a=2, b=3, c=5), :S => (a=2, b=3, c=6), :S => (a=2, b=4, c=5), :S => (a=2, b=4, c=6), ]) end @testset "base" begin b = (:S => :c => 1) p1 = :S => :a => 1:2 p2 = :S => :b => 3:4 C = Cropbox.configmultiply(p1, p2; base=b) @test C == Cropbox.configure.([ :S => (c=1, a=1, b=3), :S => (c=1, a=1, b=4), :S => (c=1, a=2, b=3), :S => (c=1, a=2, b=4), ]) end @testset "array" begin b = (:S => :c => 1) p1 = :S => :a => 1:2 p2 = :S => :b => 3:4 p = [p1, p2] C1 = Cropbox.configmultiply(p1, p2; base=b) C2 = Cropbox.configmultiply(p; base=b) @test C1 == C2 end @testset "array single" begin p = [:S => :a => 1] C = Cropbox.configmultiply(p) @test C isa Array && length(C) == 1 @test C[1] == Cropbox.configure(p[1]) end @testset "array single empty" begin p = [()] C = Cropbox.configmultiply(p) @test C isa Array && length(C) == 1 @test C[1] == Cropbox.configure(p[1]) end @testset "empty tuple" begin p = () C = Cropbox.configmultiply(p) @test C isa Array && length(C) == 1 @test C[1] == Cropbox.configure(p) end end @testset "expand" begin @testset "patch" begin p = :S => :a => [1, 2] C = Cropbox.configexpand(p) @test C == Cropbox.configure.([:S => :a => 1, :S => :a => 2]) end @testset "patch with base" begin b = :S => :b => 0 p = :S => :a => [1, 2] C = Cropbox.configexpand(p; base=b) @test C == Cropbox.configure.([:S => (a=1, b=0), :S => (a=2, b=0)]) end @testset "range" begin p = :S => :a => 1:2 C = Cropbox.configexpand(p) @test C == Cropbox.configure.([:S => :a => 1, :S => :a => 2]) end @testset "single" begin p = :S => :a => 1 C = Cropbox.configexpand(p) @test C isa Array && length(C) == 1 @test C[1] == Cropbox.configure(p) end @testset "empty" begin p = () C = Cropbox.configexpand(p) @test C isa Array && length(C) == 1 @test C[1] == Cropbox.configure(p) end end @testset "rebase" begin @testset "nonempty configs + nonempty base" begin b = (:S => :b => 0) C0 = [:S => :a => 1, :S => :a => 2] C1 = Cropbox.configrebase(C0; base=b) @test C1 == Cropbox.configure.([:S => (a=1, b=0), :S => (a=2, b=0)]) end @testset "nonempty configs + empty base" begin C0 = [:S => :a => 1, :S => :a => 2] C1 = Cropbox.configrebase(C0) @test C1 == Cropbox.configure.(C0) end @testset "empty configs + nonempty base" begin b = :S => :a => 1 C0 = [] C1 = Cropbox.configrebase(C0; base=b) @test C1 == [Cropbox.configure(b)] end @testset "empty configs + empty base" begin C0 = [] C1 = Cropbox.configrebase(C0) @test C1 == [Cropbox.configure()] end @testset "single config + single base" begin c = :S => :a => 1 b = :S => :b => 2 C1 = Cropbox.configrebase(c; base=b) C2 = Cropbox.configure(b, c) @test C1 isa Array && length(C1) == 1 @test C1[1] == C2 end end @testset "reduce" begin @testset "array + single" begin a = [:S => :a => 1, :S => :a => 2] b = :S => :a => 0 C1 = Cropbox.configreduce(a, b) C2 = Cropbox.configure.([b, b]) @test C1 == C2 end @testset "single + array" begin a = :S => :a => 0 b = [:S => :a => 1, :S => :a => 2] C1 = Cropbox.configreduce(a, b) C2 = Cropbox.configure(b) @test C1 == C2 end @testset "array + array" begin a = [:S => :a => 1, :S => :a => 2] b = [:S => :a => 3, :S => :a => 4] C1 = Cropbox.configreduce(a, b) C2 = Cropbox.configure(b) @test C1 == C2 end @testset "single + single" begin a = :S => :a => 1 b = :S => :a => 2 C1 = Cropbox.configreduce(a, b) C2 = Cropbox.configure(b) @test C1 == C2 end end @testset "macro" begin @testset "merge" begin a = :S => :a => 1 b = :S => :b => 2 C1 = @config a + b C2 = Cropbox.configure(a, b) @test C1 == C2 end @testset "merge multiple" begin a = :S => :a => 1 b = :S => :b => 2 c = :S => :c => 3 C1 = @config a + b + c C2 = Cropbox.configure(a, b, c) @test C1 == C2 end @testset "rebase" begin a = :S => :a => 1 b = [:S => :b => 1, :S => :b => 2] C1 = @config a + b C2 = Cropbox.configrebase(b; base=a) @test C1 == C2 end @testset "reduce" begin a = :S => :a => 0 b = [:S => :a => 1, :S => :a => 2] c1(a, b) = @config a + b c2(a, b) = Cropbox.configreduce(a, b) @test c1(a, b) == c2(a, b) @test c1(b, a) == c2(b, a) @test c1(b, b) == c2(b, b) @test c1(a, a) == c2(a, a) end @testset "multiply" begin a = :S => :a => [1, 2] b = :S => :b => [3, 4] C1 = @config a * b C2 = Cropbox.configmultiply(a, b) @test C1 == C2 end @testset "multiply with base" begin a = :S => :a => [1, 2] b = :S => :b => [3, 4] c = :S => :c => 0 C1 = @config c + a * b C2 = Cropbox.configmultiply(a, b; base=c) @test C1 == C2 end @testset "expand" begin a = :S => :a => [1, 2] C1 = @config !a C2 = Cropbox.configexpand(a) @test C1 == C2 end @testset "expand with base" begin a = :S => :a => [1, 2] b = :S => :b => 1 C1 = @config b + !a C2 = Cropbox.configexpand(a; base=b) @test C1 == C2 end @testset "single" begin a = :S => :a => 1 C1 = @config a C2 = Cropbox.configure(a) @test C1 == C2 end @testset "multi" begin c1 = :S => :a => 1 c2 = :S => :b => 2 c3 = :S => :c => 3 c = Cropbox.configure(c1, c2, c3) C1 = @config(c1, c2, c3) C2 = @config((c1, c2, c3)) C3 = @config (c1, c2, c3) C4 = @config c1, c2, c3 @test C1 == c @test C2 == c @test C3 == c @test C4 == c end @testset "empty" begin c = Cropbox.Config() C1 = @config C2 = @config() C3 = @config () @test C1 == c @test C2 == c @test C3 == c end end @testset "string" begin @testset "basic" begin c = "S.a" => 1 C = Cropbox.configure(c) @test C[:S][:a] == 1 end @testset "system" begin c = "S" => :a => 1 C = Cropbox.configure(c) @test C[:S][:a] == 1 end @testset "error" begin c = "S.a.b" => 1 @test_throws ErrorException Cropbox.configure(c) end end @testset "calibrate" begin c = (:S1 => (:a => 1, :b => 2), :S2 => :c => 3) C = Cropbox.configure(c) K = Cropbox.parameterkeys(C) @test K == [(:S1, :a), (:S1, :b), (:S2, :c)] V = Cropbox.parametervalues(C) @test V == [1, 2, 3] P = Cropbox.parameterzip(K, V) @test P == C @test P[:S1][:a] == 1 @test P[:S1][:b] == 2 @test P[:S2][:c] == 3 end @testset "parameters" begin @testset "basic" begin @system SConfigParameters begin a => 1 ~ preserve(parameter) end c = Cropbox.parameters(SConfigParameters) @test c[:SConfigParameters][:a] == 1 end @testset "unit" begin @system SConfigParametersUnit begin a => 1 ~ preserve(u"m", parameter) end c = Cropbox.parameters(SConfigParametersUnit) @test c[:SConfigParametersUnit][:a] == 1u"m" end @testset "missing" begin @system SConfigParametersMissing begin a => 1 ~ preserve(parameter) b(a) => a ~ preserve(parameter) end c = Cropbox.parameters(SConfigParametersMissing) @test c[:SConfigParametersMissing][:a] == 1 @test c[:SConfigParametersMissing][:b] === missing end @testset "alias" begin @system SConfigParametersAlias begin a: aa => 1 ~ preserve(parameter) end c = Cropbox.parameters(SConfigParametersAlias, alias=true) @test_throws KeyError c[:SConfigParametersAlias][:a] @test c[:SConfigParametersAlias][:aa] == 1 end @testset "recursive" begin @system SConfigParametersRecursiveChild begin b => 2 ~ preserve(parameter) end @system SConfigParametersRecursive begin s ~ ::SConfigParametersRecursiveChild a => 1 ~ preserve(parameter) end c = Cropbox.parameters(SConfigParametersRecursive, recursive=true) @test haskey(c, :Context) @test haskey(c, :Clock) @test c[:SConfigParametersRecursive][:a] == 1 @test c[:SConfigParametersRecursiveChild][:b] == 2 end @testset "exclude" begin @system SConfigParametersExclude begin a => 1 ~ preserve(parameter) end X = (Cropbox.Context,) c = Cropbox.parameters(SConfigParametersExclude, recursive=true, exclude=X) @test !haskey(c, :Context) @test !haskey(c, :Clock) @test c[:SConfigParametersExclude][:a] == 1 end @testset "instance" begin @system SConfigParametersInstance(Controller) begin a => 1 ~ preserve(parameter) end c0 = :SConfigParametersInstance => :a => 2 s1 = instance(SConfigParametersInstance; config=c0) c1 = Cropbox.parameters(s1) @test @config(c0) == c1 s2 = instance(SConfigParametersInstance; config=c1) c2 = Cropbox.parameters(s2) @test c1 == c2 end end @testset "option" begin @testset "private" begin @system SConfigOptionPrivate(Controller) begin _a ~ preserve(parameter) a ~ preserve(parameter) b(_a) => 2a ~ track c(a) => 3a ~ track end c = :SConfigOptionPrivate => (_a = 1, a = 2) s = instance(SConfigOptionPrivate, config=c) @test s.b' == 2 @test s.c' == 6 end end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
647
#TODO: implement proper tests (i.e. string comparison w/o color escapes) @testset "graph" begin @testset "dependency" begin S = Cropbox.Context d = Cropbox.dependency(S) ds = repr(MIME("text/plain"), d) @test ds == "[config → clock → context]" n = tempname() @test Cropbox.writeimage(n, d; format=:svg) == n*".svg" end @testset "hierarchy" begin S = Cropbox.Context h = Cropbox.hierarchy(S) hs = repr(MIME("text/plain"), h) @test hs == "{Context, Clock}" n = tempname() @test Cropbox.writeimage(n, h; format=:svg) == n*".svg" end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
11558
@testset "macro" begin @testset "private name" begin @system SPrivateName(Controller) begin _a: _aa => 1 ~ preserve __b: __bb => 2 ~ preserve end s = instance(SPrivateName) @test_throws ErrorException s._a @test s.__SPrivateName__a' == 1 @test s.__SPrivateName__aa === s.__SPrivateName__a @test s.__b' == 2 @test s.__bb === s.__b end @testset "private name args" begin @system SPrivateNameArgs(Controller) begin _x: _xx => 1 ~ preserve a(_x) ~ preserve b(_x) => x ~ preserve c(y=_x) => y ~ preserve d(_y=_x) => _y ~ preserve aa(_xx) ~ preserve bb(_xx) => xx ~ preserve cc(y=_xx) => y ~ preserve dd(_y=_xx) => _y ~ preserve end s = instance(SPrivateNameArgs) @test s.a' == 1 @test s.b' == 1 @test s.c' == 1 @test s.d' == 1 @test s.aa' == 1 @test s.bb' == 1 @test s.cc' == 1 @test s.dd' == 1 end @testset "private name tags" begin @system SPrivateNameTags(Controller) begin _t: _true => true ~ flag _f: _false => false ~ flag a => 1 ~ track(when=_t) b => 1 ~ track(when=_t|_f) c => 1 ~ track(when=_t&_f) d => 1 ~ track(when=_false) end s = instance(SPrivateNameTags) @test s.a' == 1 @test s.b' == 1 @test s.c' == 0 @test s.d' == 0 end @testset "private name mixin" begin @system SPrivateNameMixin1 begin _a: aa1 => 1 ~ preserve b(_a) ~ track end @system SPrivateNameMixin2 begin _a: aa2 => 2 ~ preserve c(_a) ~ track end @eval @system SPrivateNameMixed1(SPrivateNameMixin1, SPrivateNameMixin2, Controller) s1 = instance(SPrivateNameMixed1) @test_throws ErrorException s1._a @test s1.__SPrivateNameMixin1__a' == 1 @test s1.__SPrivateNameMixin2__a' == 2 @test s1.b' == 1 @test s1.c' == 2 @eval @system SPrivateNameMixed11(SPrivateNameMixed1, Controller) s11 = instance(SPrivateNameMixed11) @test_throws ErrorException s11._a @test s11.__SPrivateNameMixin1__a' == 1 @test s11.__SPrivateNameMixin2__a' == 2 @test s11.b' == 1 @test s11.c' == 2 @test_throws ErrorException @eval @system SPrivateNameMixed2(SPrivateNameMixin1, Controller) begin _a: aa1 => 3 ~ preserve end @eval @system SPrivateNameMixed3(SPrivateNameMixin1, Controller) begin d(_a) ~ track end @test_throws UndefVarError instance(SPrivateNameMixed3) @eval @system SPrivateNameMixed4(SPrivateNameMixin1, SPrivateNameMixin2, Controller) begin d(a=__SPrivateNameMixin1__a) ~ track e(a=__SPrivateNameMixin2__a) ~ track end s4 = instance(SPrivateNameMixed4) @test s4.d' == 1 @test s4.e' == 2 end @testset "alias" begin @system SAlias(Controller) begin a: aa => 1 ~ track b(a, aa) => a + aa ~ track end s = instance(SAlias) @test s.a' == s.aa' == 1 @test s.b' == 2 end @testset "single arg without key" begin @system SSingleArgWithoutKey(Controller) begin a => 1 ~ track b(a) ~ track c(x=a) ~ track end s = instance(SSingleArgWithoutKey) @test s.a' == 1 @test s.b' == 1 @test s.c' == 1 end @testset "bool arg" begin @system SBoolArg(Controller) begin t => true ~ preserve::Bool f => false ~ preserve::Bool a(t & f) ~ track::Bool b(t | f) ~ track::Bool c(t & !f) ~ track::Bool d(x=t&f, y=t|f) => x | y ~ track::Bool end s = instance(SBoolArg) @test s.a' == false @test s.b' == true @test s.c' == true @test s.d' == true end @testset "type alias" begin @system STypeAlias(Controller) begin a => -1 ~ preserve::int b => 1 ~ preserve::uint c => 1 ~ preserve::float d => true ~ preserve::bool e => :a ~ preserve::sym f => "A" ~ preserve::str g => nothing ~ preserve::∅ h => missing ~ preserve::_ i => Cropbox.Dates.Date(2021) ~ preserve::date j => Cropbox.TimeZones.ZonedDateTime(2021, Cropbox.TimeZones.tz"UTC") ~ preserve::datetime end s = instance(STypeAlias) @test s.a' isa Int64 && s.a' === -1 @test s.b' isa UInt64 && s.b' == 1 @test s.c' isa Float64 && s.c' === 1.0 @test s.d' isa Bool && s.d' === true @test s.e' isa Symbol && s.e' === :a @test s.f' isa String && s.f' === "A" @test s.g' isa Nothing && s.g' === nothing @test s.h' isa Missing && s.h' === missing @test s.i' isa Cropbox.Dates.Date && s.i' === Cropbox.Dates.Date(2021) @test s.j' isa Cropbox.TimeZones.ZonedDateTime && s.j' === Cropbox.TimeZones.ZonedDateTime(2021, Cropbox.tz"UTC") end @testset "type union nothing" begin @system STypeUnionNothing(Controller) begin a ~ preserve::{sym|∅}(parameter) end a1 = :hello s1 = instance(STypeUnionNothing; config=:0 => :a => a1) @test s1.a' isa Union{Symbol,Nothing} @test s1.a' === a1 a2 = nothing s2 = instance(STypeUnionNothing; config=:0 => :a => a2) @test s2.a' isa Union{Symbol,Nothing} @test s2.a' === a2 end @testset "type union missing" begin @system STypeUnionMissing(Controller) begin a ~ preserve::{int|_}(parameter) end a1 = 0 s1 = instance(STypeUnionMissing; config=:0 => :a => a1) @test s1.a' isa Union{Int64,Missing} @test s1.a' === a1 a2 = missing # missing filtered out by genparameter, leaving no return value (nothing) @test_throws MethodError instance(STypeUnionMissing; config=:0 => :a => a2) end @testset "type vector single" begin @system STypeVectorSingle(Controller) begin a ~ preserve::int[](parameter) end a = [1, 2, 3] s = instance(STypeVectorSingle; config=:0 => :a => a) @test s.a' isa Vector{Int64} @test s.a' === a end @testset "type vector union" begin @system STypeVectorUnion(Controller) begin a ~ preserve::{sym|∅}[](parameter) end a = [:a, nothing, :c] s = instance(STypeVectorUnion; config=:0 => :a => a) @test s.a' isa Vector{Union{Symbol,Nothing}} @test s.a' === a end @testset "patch type" begin @system SPatchType{A => Int, Int => Float32, int => Float64}(Controller) begin a => 1 ~ preserve::A b => 1 ~ preserve::Int c => 1 ~ preserve::int end s = instance(SPatchType) @test s.a' isa Int @test s.b' isa Float32 @test s.c' isa Float64 end @testset "patch type cascade" begin @system SPatchTypeCascade0{A => Int} begin a => 1 ~ preserve::A end @eval @system SPatchTypeCascade(SPatchTypeCascade0, Controller) begin b => 1 ~ preserve::A end s = instance(SPatchTypeCascade) @test s.a' isa Int @test s.b' isa Int end @testset "patch const" begin @system SPatchConst{x = 1, y = u"m"}(Controller) begin a => 1 ~ accumulate(init=x, unit=y) end s = instance(SPatchConst) @test Cropbox.unittype(s.a) === u"m" @test s.a' == 1u"m" update!(s) @test s.a' == 2u"m" end @testset "override" begin @system SOverrideComponent begin a ~ track(override) end @system SOverride(Controller) begin c(context, a) ~ ::SOverrideComponent a => 1 ~ track end s = instance(SOverride) @test s.a' == s.c.a' == 1 @test s.a === s.c.a end @testset "override union" begin @system SOverrideUnionComponent begin a ~ track(override) end @system SOverrideUnionTrack(Controller) begin c(context, a) ~ ::SOverrideUnionComponent a => 1 ~ track end @system SOverrideUnionPreserve(Controller) begin c(context, a) ~ ::SOverrideUnionComponent a => 1 ~ preserve end @system SOverrideUnionDrive(Controller) begin c(context, a) ~ ::SOverrideUnionComponent a => [1] ~ drive end s1 = instance(SOverrideUnionTrack) @test s1.a' == s1.c.a' == 1 @test s1.a === s1.c.a s2 = instance(SOverrideUnionPreserve) @test s2.a' == s2.c.a' == 1 @test s2.a === s2.c.a s3 = instance(SOverrideUnionDrive) @test s3.a' == s3.c.a' == 1 @test s3.a === s3.c.a end @testset "dynamic type" begin @system SDynamicTypeBase(Controller) @system SDynamicTypeChild(Controller) <: SDynamicTypeBase @test SDynamicTypeChild <: SDynamicTypeBase @system SDynamicTypeBaseDynamic(Controller) begin x ~ <:SDynamicTypeBase(override) end @system SDynamicTypeBaseStatic(Controller) begin x ~ ::SDynamicTypeBase(override) end b = instance(SDynamicTypeBase) c = instance(SDynamicTypeChild) @test instance(SDynamicTypeBaseDynamic; options=(; x = b)).x === b @test instance(SDynamicTypeBaseDynamic; options=(; x = c)).x === c @test instance(SDynamicTypeBaseStatic; options=(; x = b)).x === b @test_throws MethodError instance(SDynamicTypeBaseStatic; options=(; x = c)) end @testset "duplicate variable" begin @test_logs (:warn, "duplicate variable") @eval @system SDuplicateVariable begin x => 1 ~ preserve x => 2 ~ preserve end end @testset "body replacement" begin @system SBodyReplacement1(Controller) begin a => 1 ~ preserve end @eval @system SBodyReplacement2(SBodyReplacement1) begin a => 2 end s1 = instance(SBodyReplacement1) s2 = instance(SBodyReplacement2) @test s1.a isa Cropbox.Preserve @test s1.a' == 1 @test s2.a isa Cropbox.Preserve @test s2.a' == 2 end @testset "replacement with different alias" begin @system SReplacementDifferentAlias1 begin x: aaa => 1 ~ preserve end @test_logs (:warn, "variable replaced with inconsistent alias") @eval @system SReplacementDifferentAlias2(SReplacementDifferentAlias1) begin x: bbb => 2 ~ preserve end end @testset "custom system" begin abstract type SAbstractCustomSystem <: System end @system SCustomSystem <: SAbstractCustomSystem @test SCustomSystem <: System @test SCustomSystem <: SAbstractCustomSystem end @testset "return" begin #TODO: reimplement more robust return checking @test_skip @test_throws LoadError @eval @system SReturn begin x => begin return 1 end ~ track end end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
655
@testset "state" begin include("state/core.jl") include("state/hold.jl") include("state/bring.jl") include("state/wrap.jl") include("state/advance.jl") include("state/preserve.jl") include("state/tabulate.jl") include("state/interpolate.jl") include("state/track.jl") include("state/remember.jl") include("state/provide.jl") include("state/drive.jl") include("state/call.jl") include("state/integrate.jl") include("state/accumulate.jl") include("state/capture.jl") include("state/flag.jl") include("state/produce.jl") include("state/bisect.jl") include("state/solve.jl") end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
190
@testset "system" begin include("system/core.jl") include("system/clock.jl") include("system/controller.jl") include("system/calendar.jl") include("system/store.jl") end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
8516
using DataFrames import Unitful using Dates: Date, Time @testset "unit" begin @testset "unit" begin @system SUnit(Controller) begin a => 2 ~ track(u"m") b => 1 ~ track(u"s") c(a, b) => a / b ~ track(u"m/s") end s = instance(SUnit) @test s.a' == 2u"m" && s.b' == 1u"s" && s.c' == 2u"m/s" end @testset "unitless" begin @system SUnitless(Controller) begin a => 200 ~ track(u"cm^2") b => 10 ~ track(u"m^2") c(a, b) => a / b ~ track(u"cm^2/m^2") d(a, b) => a / b ~ track(u"m^2/m^2") e(a, b) => a / b ~ track end s = instance(SUnitless) @test s.a' == 200u"cm^2" @test s.b' == 10u"m^2" @test s.c' == 20u"cm^2/m^2" @test s.d' == 0.002 @test s.e' == 0.002 end @testset "nounit" begin @system SNounit(Controller) begin a => 1 ~ track(u"m") b(nounit(a)) ~ track end s = instance(SNounit) @test s.a' == u"1m" @test s.b' == 1 end @testset "nounit with alias" begin @system SNounitAlias(Controller) begin a: aa => 1 ~ track(u"m") b(nounit(aa)): bb ~ track end s = instance(SNounitAlias) @test s.aa' == u"1m" @test s.bb' == 1 end @testset "nounit with call" begin @system SNounitCall(Controller) begin a => 1 ~ track(u"m") b(nounit(a); x) => (a + x) ~ call c(b) => b(1) ~ track end s = instance(SNounitCall) @test s.a' == u"1m" @test s.b'(1) == 2 @test s.c' == 2 end @testset "nounit nested" begin @system SNounitNestedComponent begin a => 1 ~ track(u"m") end @system SNounitNested(Controller) begin n(context) ~ ::SNounitNestedComponent a(n.a) ~ track(u"m") b(nounit(n.a)) ~ track c(x=nounit(n.a)) => 2x ~ track end s = instance(SNounitNested) @test s.n.a' == s.a' == u"1m" @test s.b' == 1 @test s.c' == 2 end @testset "nothing" begin @test Cropbox.unitfy(nothing, u"m") === nothing @test Cropbox.unitfy(nothing, nothing) === nothing end @testset "missing" begin @test Cropbox.unitfy(missing, u"m") === missing @test Cropbox.unitfy(missing, nothing) === missing end @testset "missing units" begin @test Cropbox.unitfy(1, missing) === 1 @test Cropbox.unitfy(1u"cm", missing) === 1u"cm" end @testset "single" begin @test Cropbox.unitfy(1, u"m") === 1u"m" @test Cropbox.unitfy(1.0, u"m") === 1.0u"m" @test Cropbox.unitfy(1u"m", u"cm") === 100u"cm" @test Cropbox.unitfy(1.0u"m", u"cm") === 100.0u"cm" end @testset "percent" begin @test Cropbox.unitfy(1, u"percent") === 1u"percent" @test 1 |> u"percent" === 100u"percent" @test Cropbox.unitfy(1u"percent", missing) === 1u"percent" @test Cropbox.unitfy(1u"percent", u"NoUnits") === 1//100 end @testset "array" begin @test Cropbox.unitfy([1, 2, 3], u"m") == [1, 2, 3]u"m" @test Cropbox.unitfy([1, 2, 3]u"m", u"cm") == [100, 200, 300]u"cm" @test Cropbox.unitfy([1u"cm", 0.02u"m", 30u"mm"], u"cm") == [1, 2, 3]u"cm" end @testset "tuple" begin @test Cropbox.unitfy((1, 2, 3), u"m") === (1u"m", 2u"m", 3u"m") @test Cropbox.unitfy((1u"m", 2u"m", 3u"m"), u"cm") === (100u"cm", 200u"cm", 300u"cm") @test Cropbox.unitfy((1u"cm", 0.02u"m", 30u"mm"), u"cm") === (1u"cm", 2.0u"cm", 3//1*u"cm") end @testset "array with missing" begin @test isequal(Cropbox.unitfy([1, 2, missing], u"m"), [1, 2, missing]u"m") @test isequal(Cropbox.unitfy([1, 2, missing]u"m", u"cm"), [100, 200, missing]u"cm") @test isequal(Cropbox.unitfy([1u"cm", 0.02u"m", missing], u"cm"), [1, 2, missing]u"cm") end @testset "tuple with missing" begin @test isequal(Cropbox.unitfy((1, 2, missing), u"m"), (1u"m", 2u"m", missing)) @test isequal(Cropbox.unitfy((1u"m", 2u"m", missing), u"cm"), (100u"cm", 200u"cm", missing)) @test isequal(Cropbox.unitfy((1u"cm", 0.02u"m", missing), u"cm"), (1u"cm", 2.0u"cm", missing)) end @testset "range" begin @test isequal(Cropbox.unitfy(1:3, u"m"), (1:3)u"m") @test isequal(Cropbox.unitfy(1:1:3, u"m"), (1:3)u"m") @test isequal(Cropbox.unitfy(1:1.0:3, u"m"), (1:1.0:3)u"m") @test isapprox(Cropbox.unitfy(1:0.1:3, u"m"), (1:0.1:3)u"m") end @testset "range affine" begin @test all(collect(Cropbox.unitfy(1:3, u"°C")) .=== [1, 2, 3]u"°C") @test all(collect(Cropbox.unitfy(1:1:3, u"°C")) .=== [1, 2, 3]u"°C") @test all(collect(Cropbox.unitfy(1:1.0:3, u"°C")) .=== [1.0, 2.0, 3.0]u"°C") end @testset "mixed units" begin #TODO: reduce subtlety @test_throws Unitful.DimensionError Cropbox.unitfy([1u"m", 2u"cm", 3], u"mm") @test Cropbox.unitfy(Any[1u"m", 2u"cm", 3], u"mm") == [1000u"mm", 20u"mm", 3u"mm"] @test Cropbox.unitfy((1u"m", 2u"cm", 3), u"mm") == (1000u"mm", 20u"mm", 3u"mm") end @testset "deunitfy" begin @test Cropbox.deunitfy(1) == 1 @test Cropbox.deunitfy(1u"m") == 1 @test Cropbox.deunitfy([1, 2, 3]u"m") == [1, 2, 3] @test Cropbox.deunitfy((1u"m", 2u"cm", 3)) === (1, 2, 3) end @testset "deunitfy with units" begin @test Cropbox.deunitfy(1, u"m") == 1 @test Cropbox.deunitfy(1u"m", u"cm") == 100 @test Cropbox.deunitfy([1, 2, 3]u"m", u"cm") == [100, 200, 300] @test Cropbox.deunitfy([1u"m", 2u"cm", 3u"mm"], u"mm") == [1000, 20, 3] @test Cropbox.deunitfy((1u"m", 2u"cm", 3u"mm"), u"mm") === (1000, 20, 3) @test Cropbox.deunitfy(Cropbox.unitfy(1:3, u"m"), u"cm") === 100:100:300 @test Cropbox.deunitfy(Cropbox.unitfy(1:3, u"°C"), u"°C") === 1:1:3 #HACK: unitfied StepRangeLen is not backed by TwicePrecision @test all(Cropbox.deunitfy(Cropbox.unitfy(1:0.1:3, u"°C"), u"°C") .≈ 1.0:0.1:3.0) end @testset "dataframe" begin df = DataFrame(a=[0], b=[0]) U = [u"s", nothing] r = Cropbox.unitfy(df, U) @test Cropbox.unittype(eltype(r[!, 1])) == u"s" @test Cropbox.unittype(eltype(r[!, 2])) == u"NoUnits" df1 = Cropbox.deunitfy(r) @test df1 == DataFrame("a (s)" => [0], "b" => [0]) df2 = Cropbox.unitfy(df1) @test df2 == r end @testset "dataframe auto unit" begin df = DataFrame() z = [0] df."a (g/cm^2)" = z df."c (a)(b)(s)" = z df."b ()" = z df."d" = z r = Cropbox.unitfy(df) @test Cropbox.unittype(eltype(r[!, 1])) == u"g/cm^2" @test Cropbox.unittype(eltype(r[!, 2])) == u"s" @test Cropbox.unittype(eltype(r[!, 3])) == u"NoUnits" @test Cropbox.unittype(eltype(r[!, 4])) == u"NoUnits" N = names(r) @test N[1] == "a" @test N[2] == "c (a)(b)" @test N[3] == "b ()" @test N[4] == "d" end @testset "dataframe auto type" begin df = DataFrame() z = ["2020-10-08"] df."a (:Date)" = z df."b (:String)" = z df."c (:Symbol)" = z df."d ()" = z df."e" = z r = Cropbox.unitfy(df) @test eltype(r[!, 1]) == Date @test eltype(r[!, 2]) == String @test eltype(r[!, 3]) == Symbol @test eltype(r[!, 4]) == String @test eltype(r[!, 5]) == String N = names(r) @test N[1] == "a" @test N[2] == "b" @test N[3] == "c" @test N[4] == "d ()" @test N[5] == "e" end @testset "dataframe auto datetime" begin df = DataFrame() d = Date("2020-11-10") t = Time("10:12") df."d1 (:Date)" = [d] df."d2" = [d] df."t1 (:Time)" = [t] df."t2" = [t] r = Cropbox.unitfy(df) @test r[1, 1] == d @test r[1, 2] == d @test r[1, 3] == t @test r[1, 4] == t @test eltype(r[!, 1]) == Date @test eltype(r[!, 2]) == Date @test eltype(r[!, 3]) == Time @test eltype(r[!, 4]) == Time N = names(r) @test N[1] == "d1" @test N[2] == "d2" @test N[3] == "t1" @test N[4] == "t2" end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
91
@testset "util" begin include("util/simulate.jl") include("util/calibrate.jl") end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
5699
@testset "accumulate" begin @testset "basic" begin @system SAccumulate(Controller) begin a => 1 ~ track b(a) => a + 1 ~ accumulate end s = instance(SAccumulate) @test s.a' == 1 && s.b' == 0 update!(s) @test s.a' == 1 && s.b' == 2 update!(s) @test s.a' == 1 && s.b' == 4 update!(s) @test s.a' == 1 && s.b' == 6 end @testset "cross reference" begin @system SAccumulateXRef(Controller) begin a(b) => b + 1 ~ accumulate b(a) => a + 1 ~ accumulate end s = instance(SAccumulateXRef) @test s.a' == 0 && s.b' == 0 update!(s) @test s.a' == 1 && s.b' == 1 update!(s) @test s.a' == 3 && s.b' == 3 update!(s) @test s.a' == 7 && s.b' == 7 end @testset "cross reference mirror" begin @system SAccumulateXrefMirror1(Controller) begin a(b) => b + 1 ~ accumulate b(a) => a + 2 ~ accumulate end @system SAccumulateXrefMirror2(Controller) begin a(b) => b + 2 ~ accumulate b(a) => a + 1 ~ accumulate end s1 = instance(SAccumulateXrefMirror1); s2 = instance(SAccumulateXrefMirror2) @test s1.a' == s2.b' == 0 && s1.b' == s2.a' == 0 update!(s1); update!(s2) @test s1.a' == s2.b' == 1 && s1.b' == s2.a' == 2 update!(s1); update!(s2) @test s1.a' == s2.b' == 4 && s1.b' == s2.a' == 5 update!(s1); update!(s2) @test s1.a' == s2.b' == 10 && s1.b' == s2.a' == 11 end @testset "time" begin @system SAccumulateTime(Controller) begin t(x=context.clock.time) => 0.5x ~ track(u"hr") a => 1 ~ track b(a) => a + 1 ~ accumulate c(a) => a + 1 ~ accumulate(time=t) end s = instance(SAccumulateTime) @test s.a' == 1 && s.b' == 0 && s.c' == 0 update!(s) @test s.a' == 1 && s.b' == 2 && s.c' == 1 update!(s) @test s.a' == 1 && s.b' == 4 && s.c' == 2 update!(s) @test s.a' == 1 && s.b' == 6 && s.c' == 3 end @testset "unit hour" begin @system SAccumulateUnitHour(Controller) begin a => 1 ~ accumulate(u"hr") end s = instance(SAccumulateUnitHour) @test iszero(s.a') update!(s) @test s.a' == 1u"hr" update!(s) @test s.a' == 2u"hr" end @testset "unit day" begin @system SAccumulateUnitDay(Controller) begin a => 1 ~ accumulate(u"d") end s = instance(SAccumulateUnitDay) @test iszero(s.a') update!(s) @test s.a' == 1u"hr" update!(s) @test s.a' == 2u"hr" end @testset "when" begin @system SAccumulateWhen(Controller) begin t(context.clock.tick) ~ track::int f ~ preserve(parameter) w(t, f) => t < f ~ flag a => 1 ~ accumulate b => 1 ~ accumulate(when=w) c => 1 ~ accumulate(when=!w) end n = 5 s = instance(SAccumulateWhen; config=:0 => :f => n) simulate!(s, stop=n) @test s.a' == n @test s.b' == n @test s.c' == 0 simulate!(s, stop=n) @test s.a' == 2n @test s.b' == n @test s.c' == n end @testset "minmax" begin @system SAccumulateMinMax(Controller) begin a => 1 ~ accumulate(min=2, max=5) end r = simulate(SAccumulateMinMax, stop=4) @test r[!, :a] == [2, 3, 4, 5, 5] end @testset "reset" begin @system SAccumulateReset(Controller) begin t(context.clock.tick) ~ track::int r(t) => t % 4 == 0 ~ flag a => 1 ~ accumulate b => 1 ~ accumulate(reset=r) c => 1 ~ accumulate(reset=r, init=10) end r = simulate(SAccumulateReset, stop=10) @test r[!, :a] == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] @test r[!, :b] == [0, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2] @test r[!, :c] == [10, 11, 12, 13, 14, 11, 12, 13, 14, 11, 12] end @testset "transport" begin @system SAccumulateTransport(Controller) begin a(a, b) => -max(a - b, 0) ~ accumulate(init=10) b(a, b, c) => max(a - b, 0) - max(b - c, 0) ~ accumulate c(b, c) => max(b - c, 0) ~ accumulate end s = instance(SAccumulateTransport) @test s.a' == 10 && s.b' == 0 && s.c' == 0 update!(s) @test s.a' == 0 && s.b' == 10 && s.c' == 0 update!(s) @test s.a' == 0 && s.b' == 0 && s.c' == 10 update!(s) @test s.a' == 0 && s.b' == 0 && s.c' == 10 end @testset "distribute" begin @system SAccumulateDistribute(Controller) begin s(x=context.clock.time) => (100u"hr^-1" * x) ~ track d1(s) => 0.2s ~ accumulate d2(s) => 0.3s ~ accumulate d3(s) => 0.5s ~ accumulate end s = instance(SAccumulateDistribute) c = s.context @test c.clock.time' == 0u"hr" && s.s' == 0 && s.d1' == 0 && s.d2' == 0 && s.d3' == 0 update!(s) @test c.clock.time' == 1u"hr" && s.s' == 100 && s.d1' == 0 && s.d2' == 0 && s.d3' == 0 update!(s) @test c.clock.time' == 2u"hr" && s.s' == 200 && s.d1' == 20 && s.d2' == 30 && s.d3' == 50 update!(s) @test c.clock.time' == 3u"hr" && s.s' == 300 && s.d1' == 60 && s.d2' == 90 && s.d3' == 150 update!(s) @test c.clock.time' == 4u"hr" && s.s' == 400 && s.d1' == 120 && s.d2' == 180 && s.d3' == 300 end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
1408
@testset "advance" begin @testset "basic" begin @system SAdvance(Controller) begin a ~ advance end s = instance(SAdvance) @test s.a' == 0 update!(s) @test s.a' == 1 update!(s) @test s.a' == 2 end @testset "custom" begin @system SAdvanceCustom(Controller) begin i => 1 ~ preserve(parameter) s => 2 ~ preserve(parameter) a ~ advance(init=i, step=s) end s1 = instance(SAdvanceCustom) @test s1.a' == 1 update!(s1) @test s1.a' == 3 update!(s1) @test s1.a' == 5 c = :0 => (i = 10, s = 20) s2 = instance(SAdvanceCustom, config=c) s2.a' == 10 update!(s2) s2.a' == 30 update!(s2) s2.a' == 50 end @testset "unit" begin @system SAdvanceUnit(Controller) begin a ~ advance(init=1, step=2, u"d") end s = instance(SAdvanceUnit) @test s.a' == 1u"d" update!(s) @test s.a' == 3u"d" update!(s) @test s.a' == 5u"d" end @testset "type" begin @system SAdvanceType(Controller) begin a ~ advance::int end s = instance(SAdvanceType) @test s.a' === 0 update!(s) @test s.a' === 1 update!(s) @test s.a' === 2 end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
1110
@testset "bisect" begin @testset "basic" begin @system SBisect(Controller) begin x(x) => x - 1 ~ bisect(lower=0, upper=2) end s = instance(SBisect) @test s.x' == 1 end @testset "unit" begin @system SBisectUnit(Controller) begin x(x) => x - u"1m" ~ bisect(lower=u"0m", upper=u"2m", u"m") end s = instance(SBisectUnit) @test s.x' == u"1m" end @testset "eval unit" begin @system SBisectEvalUnit(Controller) begin f(x) => (x/1u"s" - 1u"m/s") ~ track(u"m/s") x(f) ~ bisect(lower=0, upper=2, u"m", evalunit=u"m/s") end s = instance(SBisectEvalUnit) @test s.x' == 1u"m" @test Cropbox.unittype(s.x) == u"m" @test Cropbox.evalunit(s.x) == u"m/s" end @testset "equal" begin @system SBisectEqual(Controller) begin x1(x1) => (x1 - 1) ~ bisect(lower=0, upper=2) x2(x2) => (x2 - 1 ⩵ 0) ~ bisect(lower=0, upper=2) end s = instance(SBisectEqual) @test s.x1' == s.x2' end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
2226
@testset "bring" begin @testset "basic" begin @system SBringPart begin a ~ preserve(parameter) b(a) => 2a ~ track c(b) ~ accumulate end @eval @system SBring(Controller) begin p(context) ~ bring::SBringPart end o = SBringPart => :a => 1 s = instance(SBring; config=o) @test s.a' == s.p.a' == 1 @test s.b' == s.p.b' == 2 @test_throws ErrorException s.c' @test s.p.c' == 0 update!(s) @test_throws ErrorException s.c' @test s.p.c' == 2 end @testset "override" begin @system SBringOverridePart begin a ~ preserve(parameter) b(a) => 2a ~ track c(b) ~ accumulate end @eval @system SBringOverrideMod begin p ~ bring::SBringOverridePart(override) end @eval @system SBringOverride(Controller) begin p(context) ~ ::SBringOverridePart m(context, p) ~ ::SBringOverrideMod end o = SBringOverridePart => :a => 1 s = instance(SBringOverride; config=o) @test s.p === s.m.p @test s.m.a' == s.p.a' == 1 @test s.m.b' == s.p.b' == 2 @test_throws ErrorException s.m.c' @test s.p.c' == 0 update!(s) @test_throws ErrorException s.m.c' @test s.p.c' == 2 end @testset "parameters" begin @system SBringParamsPart begin a => 1 ~ preserve b(a) => 2a ~ track c(b) ~ accumulate d => true ~ flag end @eval @system SBringParams(Controller) begin p(context) ~ bring::SBringParamsPart(parameters) end #TODO: support system-based configuration for implicitly generated parameters o = :SBringParams => (; a = 0, b = 1, c = 2, d = false, ) s = instance(SBringParams; config=o) @test s.a' == 0 @test s.b' == 1 @test_throws ErrorException s.c' == 2 @test s.d' == false @test s.p.a' == 1 @test s.p.b' == 2 @test s.p.c' == 0 @test s.p.d' == true end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
1314
@testset "call" begin @testset "basic" begin @system SCall(Controller) begin fa(; x) => x ~ call a(fa) => fa(1) ~ track fb(i; x) => i + x ~ call b(fb) => fb(1) ~ track i => 1 ~ preserve end s = instance(SCall) @test s.a' === 1.0 @test s.b' === 2.0 end @testset "unit" begin @system SCallUnit(Controller) begin fa(; x(u"m")) => x ~ call(u"m") a(fa) => fa(1u"m") ~ track(u"m") fb(i; x(u"m")) => i + x ~ call(u"m") b(fb) => fb(1u"m") ~ track(u"m") i => 1 ~ preserve(u"m") end s = instance(SCallUnit) @test s.a' === 1.0u"m" @test s.b' === 2.0u"m" end @testset "type and unit" begin @system SCallTypeUnit(Controller) begin fa(; x::Int(u"m")) => x ~ call::int(u"m") a(fa) => fa(1u"m") ~ track::int(u"m") fb(i; x::Int(u"m")) => i + x ~ call::int(u"m") b(fb) => fb(1u"m") ~ track::int(u"m") i => 1 ~ preserve::int(u"m") end s = instance(SCallTypeUnit) @test s.a' === 1u"m" @test s.b' === 2u"m" @test s.a' |> Cropbox.deunitfy isa Int @test s.b' |> Cropbox.deunitfy isa Int end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
2043
@testset "capture" begin @testset "basic" begin @system SCapture(Controller) begin a => 1 ~ track b(a) => a + 1 ~ capture c(a) => a + 1 ~ accumulate end s = instance(SCapture) @test s.b' == 0 && s.c' == 0 update!(s) @test s.b' == 2 && s.c' == 2 update!(s) @test s.b' == 2 && s.c' == 4 end @testset "time" begin @system SCaptureTime(Controller) begin t(x=context.clock.time) => 2x ~ track(u"hr") a => 1 ~ track b(a) => a + 1 ~ capture(time=t) c(a) => a + 1 ~ accumulate(time=t) end s = instance(SCaptureTime) @test s.b' == 0 && s.c' == 0 update!(s) @test s.b' == 4 && s.c' == 4 update!(s) @test s.b' == 4 && s.c' == 8 end @testset "unit hour" begin @system SCaptureUnitHour(Controller) begin a => 1 ~ capture(u"hr") end s = instance(SCaptureUnitHour) @test iszero(s.a') update!(s) @test s.a' == 1u"hr" update!(s) @test s.a' == 1u"hr" end @testset "unit day" begin @system SCaptureUnitDay(Controller) begin a => 1 ~ capture(u"d") end s = instance(SCaptureUnitDay) @test iszero(s.a') update!(s) @test s.a' == 1u"hr" update!(s) @test s.a' == 1u"hr" end @testset "when" begin @system SCaptureWhen(Controller) begin t(context.clock.tick) ~ track::int f ~ preserve(parameter) w(t, f) => t <= f ~ flag a => 1 ~ capture b => 1 ~ capture(when=w) c => 1 ~ capture(when=!w) end n = 5 s = instance(SCaptureWhen; config=:0 => :f => n) simulate!(s, stop=n) @test s.a' == 1 @test s.b' == 1 @test s.c' == 0 simulate!(s, stop=n) @test s.a' == 1 @test s.b' == 0 @test s.c' == 1 end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
280
@testset "core" begin @testset "not" begin @system SStateNot(Controller) begin f => false ~ preserve::Bool a(f) ~ flag b(!f) ~ flag end s = instance(SStateNot) @test s.a' == false && s.b' == true end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
3107
using DataFrames: DataFrame @testset "drive" begin @testset "basic" begin @system SDrive(Controller) begin a => [2, 4, 6] ~ drive end s = instance(SDrive) @test s.a' == 2 update!(s) @test s.a' == 4 update!(s) @test s.a' == 6 end @testset "unit" begin @system SDriveUnit(Controller) begin a => [2, 4, 6] ~ drive(u"m") end s = instance(SDriveUnit) @test s.a' == 2u"m" update!(s) @test s.a' == 4u"m" update!(s) @test s.a' == 6u"m" end @testset "type" begin @system SDriveType(Controller) begin a => [2, 4, 6] ~ drive::int(u"m") end s = instance(SDriveType) @test s.a' === 2u"m" update!(s) @test s.a' === 4u"m" update!(s) @test s.a' === 6u"m" end @testset "parameter" begin @system SDriveParameter(Controller) begin a ~ drive(parameter) end a = [2, 4, 6] c = :0 => :a => a s = instance(SDriveParameter; config=c) @test s.a' == 2 update!(s) @test s.a' == 4 update!(s) @test s.a' == 6 end @testset "provide" begin @system SDriveProvide(Controller) begin p => DataFrame(index=(0:2)u"hr", a=[2,4,6], x=1:3, c=(4:6)u"m") ~ provide a ~ drive(from=p) b ~ drive(from=p, by=:x) c ~ drive(from=p, u"m") end s = instance(SDriveProvide) @test s.a' == 2 @test s.b' == 1 @test s.c' == 4u"m" update!(s) @test s.a' == 4 @test s.b' == 2 @test s.c' == 5u"m" update!(s) @test s.a' == 6 @test s.b' == 3 @test s.c' == 6u"m" end @testset "produce" begin @system SDriveProduce begin i(context.clock.tick) ~ preserve::int a => 0:3 ~ drive::int end @system SDriveProduceController(Controller) begin p => produce(SDriveProduce) ~ produce end s = instance(SDriveProduceController) p = s.p' @test isempty(p) update!(s) @test p[1].i' == 0 && p[1].a' == 1 update!(s) @test p[1].i' == 0 && p[1].a' == 2 @test p[2].i' == 1 && p[2].a' == 1 update!(s) @test p[1].i' == 0 && p[1].a' == 3 @test p[2].i' == 1 && p[2].a' == 2 @test p[3].i' == 2 && p[3].a' == 1 end @testset "error" begin @test_throws LoadError @eval @system SDriveErrorMissingFrom(Controller) begin a ~ drive(by=:a) end @test_throws LoadError @eval @system SDriveErrorProvideParameter(Controller) begin p => DataFrame(index=(0:2)u"hr", a=[2,4,6]) ~ provide a ~ drive(from=p, parameter) end @test_throws LoadError @eval @system SDriveErrorProvideBody(Controller) begin p => DataFrame(index=(0:2)u"hr", a=[2,4,6]) ~ provide a => [1, 2, 3] ~ drive(from=p) end end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
1359
@testset "flag" begin @testset "basic" begin @system SFlag(Controller) begin a => true ~ flag b => false ~ flag end s = instance(SFlag) @test s.a' == true && s.b' == false end @testset "flag vs track" begin @system SFlagVsTrack(Controller) begin a => 1 ~ accumulate f1(a) => a >= 1 ~ flag f2(a) => a >= 1 ~ track::Bool x1(f1) => (f1 ? 1 : 0) ~ track x2(f2) => (f2 ? 1 : 0) ~ track end s = instance(SFlagVsTrack) @test s.a' == 0 @test s.f1' == false && s.f2' == false @test s.x1' == 0 && s.x2' == 0 update!(s) @test s.a' == 1 @test s.f1' == true && s.f2' == true @test s.x1' == 1 && s.x2' == 1 update!(s) @test s.a' == 2 @test s.f1' == true && s.f2' == true @test s.x1' == 1 && s.x2' == 1 end @testset "flag parameter" begin @system SFlagParameter(Controller) begin a => true ~ flag(parameter) b => false ~ flag(parameter) end s1 = instance(SFlagParameter) @test s1.a' == true && s1.b' == false c = :SFlagParameter => (a = false, b = true) s2 = instance(SFlagParameter; config=c) @test s2.a' == false && s2.b' == true end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
186
@testset "hold" begin @testset "basic" begin @system SHold(Controller) begin a ~ hold end @test_throws ErrorException instance(SHold) end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
1313
@testset "integrate" begin @testset "basic" begin @system SIntegrate(Controller) begin w => 1 ~ preserve(parameter) a => 0 ~ preserve(parameter) b => π ~ preserve(parameter) f(w; x) => w*sin(x) ~ integrate(from=a, to=b) end s1 = instance(SIntegrate) @test s1.f' ≈ 2 s2 = instance(SIntegrate, config=:0 => :w => 2) @test s2.f' ≈ 4 s3 = instance(SIntegrate, config=:0 => :a => π/2) @test s3.f' ≈ 1 s4 = instance(SIntegrate, config=:0 => (a = π, b = 2π)) @test s4.f' ≈ -2 end @testset "unit" begin @system SIntegrateUnit(Controller) begin a => 1000 ~ preserve(u"mm") b => 3000 ~ preserve(u"mm") f1(; x) => x ~ integrate(from=a, to=b, u"cm^2") f2(; x(u"mm")) => x ~ integrate(from=a, to=b, u"cm^2") f3(; x(u"cm")) => x ~ integrate(from=a, to=b, u"cm^2") f4(; x(u"cm")) => x ~ integrate(from=a, to=b, u"m^2") end s = instance(SIntegrateUnit) @test s.f1' === 40000.0u"cm^2" @test s.f2' === 40000.0u"cm^2" @test s.f3' ≈ 4u"m^2" @test s.f3' isa typeof(40000.0u"cm^2") @test s.f4' ≈ 4u"m^2" @test s.f4' isa typeof(4.0u"m^2") end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
1569
@testset "interpolate" begin @testset "basic" begin @system SInterpolate(Controller) begin m => ([1 => 10, 2 => 20, 3 => 30]) ~ interpolate n(m) ~ interpolate(reverse) a(m) => m(2.5) ~ track b(n) => n(25) ~ track end s = instance(SInterpolate) @test s.a' == 25 @test s.b' == 2.5 end @testset "matrix" begin @system SInterpolateMatrix(Controller) begin m => ([1 10; 2 20; 3 30]) ~ interpolate n(m) ~ interpolate(reverse) a(m) => m(2.5) ~ track b(n) => n(25) ~ track end s = instance(SInterpolateMatrix) @test s.a' == 25 @test s.b' == 2.5 end @testset "config" begin @system SInterpolateConfig(Controller) begin m => ([1 => 10]) ~ interpolate(parameter) n(m) ~ interpolate(reverse) a(m) => m(2.5) ~ track b(n) => n(25) ~ track end o = SInterpolateConfig => :m => [1 => 10, 2 => 20, 3 => 30] s = instance(SInterpolateConfig; config=o) @test s.a' == 25 @test s.b' == 2.5 end @testset "unit" begin @system SInterpolateUnit(Controller) begin m => ([1 => 10, 2 => 20, 3 => 30]) ~ interpolate(u"s", knotunit=u"m") n(m) ~ interpolate(u"m", reverse) a(m) => m(2.5u"m") ~ track(u"s") b(n) => n(25u"s") ~ track(u"m") end s = instance(SInterpolateUnit) @test s.a' == 25u"s" @test s.b' == 2.5u"m" end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
4319
@testset "preserve" begin @testset "basic" begin @system SPreserve(Controller) begin a => 1 ~ track b(a) => a + 1 ~ accumulate c(b) => b ~ preserve end s = instance(SPreserve) @test s.a' == 1 && s.b' == 0 && s.c' == 0 update!(s) @test s.a' == 1 && s.b' == 2 && s.c' == 0 end @testset "optional" begin @system SPreserveOptional(Controller) begin a ~ preserve(optional) b => 1 ~ preserve(optional) end s = instance(SPreserveOptional) @test isnothing(s.a') && s.b' == 1 update!(s) @test isnothing(s.a') && s.b' == 1 end @testset "parameter" begin @system SParameter(Controller) begin a => 1 ~ preserve(parameter) end s = instance(SParameter) @test s.a' == 1 update!(s) @test s.a' == 1 end @testset "parameter with config" begin @system SParameterConfig(Controller) begin a => 1 ~ preserve(parameter) end o = SParameterConfig => :a => 2 s = instance(SParameterConfig; config=o) @test s.a' == 2 end @testset "parameter with config alias" begin @system SParameterConfigAlias(Controller) begin a: aa => 1 ~ preserve(parameter) bb: b => 1 ~ preserve(parameter) end o = SParameterConfigAlias => (:a => 2, :b => 2) s = instance(SParameterConfigAlias; config=o) @test s.a' == 2 @test s.b' == 2 end @testset "parameter missing" begin @system SParameterMissing(Controller) begin a => 1 ~ preserve(parameter) end o = SParameterMissing => :a => missing s = instance(SParameterMissing; config=o) @test s.a' == 1 end @testset "parameter nothing" begin @system SParameterNothing(Controller) begin a => 1 ~ preserve(parameter, optional) end o = SParameterNothing => :a => nothing s = instance(SParameterNothing; config=o) @test s.a' === nothing end @testset "minmax" begin @system SPreserveMinMax(Controller) begin a => 0 ~ preserve(parameter, min=1) b => 0 ~ preserve(parameter, max=2) c => 0 ~ preserve(parameter, min=1, max=2) end s = instance(SPreserveMinMax) @test s.a' == 1 @test s.b' == 0 @test s.c' == 1 end @testset "parameter minmax" begin @system SParameterMinMax(Controller) begin a => 0 ~ preserve(parameter, min=-1) b => 0 ~ preserve(parameter, max=1) c => 0 ~ preserve(parameter, min=-1, max=1) end o1 = SParameterMinMax => (:a => 2, :b => 2, :c => 2) s1 = instance(SParameterMinMax; config=o1) @test s1.a' == 2 @test s1.b' == 1 @test s1.c' == 1 o2 = SParameterMinMax => (:a => -2, :b => -2, :c => -2) s2 = instance(SParameterMinMax; config=o2) @test s2.a' == -1 @test s2.b' == -2 @test s2.c' == -1 end @testset "round" begin @system SPreserveRound(Controller) begin a => 1.4 ~ preserve(round) b => 1.4 ~ preserve(round=:round) c => 1.4 ~ preserve(round=:ceil) d => 1.4 ~ preserve(round=:floor) e => 1.4 ~ preserve(round=:trunc) end s = instance(SPreserveRound) @test s.a' === s.b' @test s.b' === 1.0 @test s.c' === 2.0 @test s.d' === 1.0 @test s.e' === 1.0 end @testset "parameter round" begin @system SParameterRound(Controller) begin a ~ preserve::int(parameter, round=:floor) b ~ preserve::int(parameter, round=:trunc) end o1 = :0 => (a = 1.4, b = 1.4) s1 = instance(SParameterRound; config=o1) @test s1.a' === 1 @test s1.b' === 1 o2 = :0 => (a = -1.4, b = -1.4) s2 = instance(SParameterRound; config=o2) @test s2.a' === -2 @test s2.b' === -1 end @testset "parameter typo" begin @test_throws LoadError @eval @system SParameterType(Controller) begin a ~ preserve(paramter) end end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
6392
@testset "produce" begin @testset "basic" begin @system SProduce begin a => produce(SProduce) ~ produce end @system SProduceController(Controller) begin s(context) ~ ::SProduce end sc = instance(SProduceController) s = sc.s @test length(s.a) == 0 @test collect(s.a) == [] update!(sc) @test length(s.a) == 1 @test collect(s.a) == [s.a[1]] @test length(s.a[1].a) == 0 update!(sc) @test length(s.a) == 2 @test collect(s.a) == [s.a[1], s.a[2]] @test length(s.a[1].a) == 1 @test length(s.a[2].a) == 0 end @testset "single" begin @system SProduceSingle begin a => produce(SProduceSingle) ~ produce::SProduceSingle end @system SProduceSingleController(Controller) begin s(context) ~ ::SProduceSingle end sc = instance(SProduceSingleController) s = sc.s @test length(s.a) == 0 @test collect(s.a) == [] update!(sc) @test length(s.a) == 1 a = s.a[1] @test collect(s.a) == [a] @test length(s.a[1].a) == 0 update!(sc) @test length(s.a) == 1 @test collect(s.a) == [a] @test a === s.a[1] @test length(s.a[1].a) == 1 @test_throws BoundsError s.a[2] end @testset "kwargs" begin @system SProduceKwargs begin a => produce(SProduceKwargs) ~ produce i(t=context.clock.time) => t ~ preserve(u"hr") end @system SProduceKwargsController(Controller) begin s(context) ~ ::SProduceKwargs end sc = instance(SProduceKwargsController) s = sc.s @test length(s.a) == 0 && s.i' == 0u"hr" update!(sc) @test length(s.a) == 1 && s.i' == 0u"hr" @test length(s.a[1].a) == 0 && s.a[1].i' == 0u"hr" update!(sc) @test length(s.a) == 2 && s.i' == 0u"hr" @test length(s.a[1].a) == 1 && s.a[1].i' == 0u"hr" @test length(s.a[2].a) == 0 && s.a[2].i' == 1u"hr" @test length(s.a[1].a[1].a) == 0 && s.a[1].a[1].i' == 1u"hr" end @testset "nothing" begin @system SProduceNothing begin a => nothing ~ produce end @system SProduceNothingController(Controller) begin s(context) ~ ::SProduceNothing end sc = instance(SProduceNothingController) s = sc.s @test length(s.a) == 0 update!(sc) @test length(s.a) == 0 end @testset "query index" begin @system SProduceQueryIndex begin p => produce(SProduceQueryIndex) ~ produce::SProduceQueryIndex[] i(context.clock.tick) ~ preserve::int a(x=p["*"].i) => sum(x) ~ track b(x=p["**"].i) => sum(x) ~ track end @system SProduceQueryIndexController(Controller) begin s(context) ~ ::SProduceQueryIndex end sc = instance(SProduceQueryIndexController) s = sc.s @test length(s.p) == 0 update!(sc) @test length(s.p) == 1 @test s.a' == 0 # (0) @test s.b' == 0 # (0) update!(sc) @test length(s.p) == 2 @test s.a' == 1 # (0 + 1) @test s.b' == 2 # ((0 ~ 1) + 1) update!(sc) @test length(s.p) == 3 @test s.a' == 3 # (0 + 1 + 2) @test s.b' == 10 # ((0 ~ ((1 ~ 2) + 2) + (1 ~ 2) + 2) end @testset "query condition with flag" begin @system SProduceQueryConditionTrackBool begin p => produce(SProduceQueryConditionTrackBool) ~ produce::SProduceQueryConditionTrackBool[] i(context.clock.tick) ~ preserve::int f(i) => isodd(i) ~ flag a(x=p["*/f"].i) => sum(x) ~ track b(x=p["**/f"].i) => sum(x) ~ track end @system SProduceQueryConditionTrackBoolController(Controller) begin s(context) ~ ::SProduceQueryConditionTrackBool end sc = instance(SProduceQueryConditionTrackBoolController) s = sc.s @test length(s.p) == 0 update!(sc) @test length(s.p) == 1 @test s.a' == 0 # (#0) @test s.b' == 0 # (#0) update!(sc) @test length(s.p) == 2 @test s.a' == 1 # (0 + #1) @test s.b' == 2 # (0 ~ #1) + #1) update!(sc) @test length(s.p) == 3 @test s.a' == 1 # (0 + #1 + 2) @test s.b' == 2 # (0 ~ ((#1 ~ 2) + 2) + (#1 ~ 2) + 2) update!(sc) @test length(s.p) == 4 @test s.a' == 4 # (0 + #1 + 2 + #3) @test s.b' == 26 # (0 ~ ((#1 ~ ((2 ~ #3) + #3)) + (2 ~ #3) + #3) + (#1 ~ ((2 ~ #3) + #3)) + (2 ~ #3) + #3) end @testset "adjoint" begin @system SProduceAdjoint begin p => produce(SProduceAdjoint) ~ produce::SProduceAdjoint[] i(context.clock.tick) ~ preserve::int end @system SProduceAdjointController(Controller) begin s(context) ~ ::SProduceAdjoint end sc = instance(SProduceAdjointController) s = sc.s update!(sc) @test length(s.p["*"]') == 1 @test length(s.p["**"]') == 1 @test s.p["*"].i' == [0] @test s.p["**"].i' == [0] update!(sc) @test length(s.p["*"]') == 2 @test length(s.p["**"]') == 3 @test s.p["*"].i' == [0, 1] @test s.p["**"].i' == [0, 1, 1] end @testset "when" begin @system SProduceWhen begin t(context.clock.tick) ~ track::int w(t) => isodd(t) ~ flag a => produce(SProduceWhen) ~ produce(when=w) end @system SProduceWhenController(Controller) begin s(context) ~ ::SProduceWhen end sc = instance(SProduceWhenController) s = sc.s @test length(s.a) == 0 update!(sc) @test length(s.a) == 0 update!(sc) @test length(s.a) == 1 @test length(s.a[1].a) == 0 update!(sc) @test length(s.a) == 1 @test length(s.a[1].a) == 0 update!(sc) @test length(s.a) == 2 @test length(s.a[1].a) == 1 @test length(s.a[2].a) == 0 update!(sc) @test length(s.a) == 2 @test length(s.a[1].a) == 1 @test length(s.a[2].a) == 0 end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
3233
using DataFrames: DataFrame using Dates using TimeZones @testset "provide" begin @testset "basic" begin @system SProvide(Controller) begin a => DataFrame(index=(0:3)u"hr", value=0:10:30) ~ provide end s = instance(SProvide) @test s.a'.index == [0, 1, 2, 3]u"hr" @test s.a'.value == [0, 10, 20, 30] end @testset "index" begin @system SProvideIndex(Controller) begin a => DataFrame(i=(0:3)u"hr", value=0:10:30) ~ provide(index=:i) end s = instance(SProvideIndex) @test s.a'.i == [0, 1, 2, 3]u"hr" end @testset "autounit" begin @system SProvideAutoUnit(Controller) begin a => DataFrame("index (hr)" => 0:3, "value (m)" => 0:10:30) ~ provide b => DataFrame("index" => (0:3)u"hr", "value (m)" => 0:10:30) ~ provide(autounit=false) end s = instance(SProvideAutoUnit) @test s.a'."index" == [0, 1, 2, 3]u"hr" @test s.a'."value" == [0, 10, 20, 30]u"m" @test s.b'."index" == [0, 1, 2, 3]u"hr" @test s.b'."value (m)" == [0, 10, 20, 30] end @testset "time" begin @system SProvideTime(Controller) begin a => DataFrame("index (d)" => 0:3, "value (m)" => 0:10:30) ~ provide end c = :Clock => :step => 1u"d" s = instance(SProvideTime; config=c) @test s.a'.index == [0, 1, 2, 3]u"d" @test s.a'.value == [0, 10, 20, 30]u"m" @test_throws ErrorException instance(SProvideTime) end @testset "tick" begin @system SProvideTick(Controller) begin a => DataFrame(index=0:3, value=0:10:30) ~ provide(init=context.clock.tick, step=1) end s = instance(SProvideTick) @test s.a'.index == [0, 1, 2, 3] end @testset "calendar" begin @system SProvideCalendar(Controller) begin calendar(context) ~ ::Calendar a ~ provide(init=calendar.time, parameter) end t0 = ZonedDateTime(2011, 10, 29, 0, tz"Asia/Seoul") t1 = ZonedDateTime(2011, 10, 29, 1, tz"Asia/Seoul") t2 = ZonedDateTime(2011, 10, 29, 3, tz"Asia/Seoul") Δt = Hour(1) df = DataFrame(index=t0:Δt:t2, value=0:3) c = (:Calendar => :init => t1, :0 => :a => df) s = instance(SProvideCalendar; config=c) @test s.a'.index == t1:Δt:t2 @test s.a'.value == 1:3 end @testset "parameter" begin @system SProvideParameter(Controller) begin a ~ provide(parameter) end df = DataFrame("index (hr)" => 0:3, "value (m)" => 0:10:30) c = :0 => :a => df s = instance(SProvideParameter; config=c) @test s.a'.index == [0, 1, 2, 3]u"hr" @test s.a'.value == [0, 10, 20, 30]u"m" end @testset "csv" begin @system SProvideCSV(Controller) begin a ~ provide(parameter) end s = mktemp() do f, io write(io, "index (hr),value\n0,0\n1,10\n2,20\n3,30") close(io) c = :0 => :a => f instance(SProvideCSV; config=c) end @test s.a'.index == [0, 1, 2, 3]u"hr" @test s.a'.value == [0, 10, 20, 30] end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
577
@testset "remember" begin @testset "basic" begin @system SRemember(Controller) begin t(context.clock.tick) ~ track w(t) => t >= 2 ~ flag i => -1 ~ preserve r(t) ~ remember(init=i, when=w) end s = instance(SRemember) @test !s.w' @test s.r' == s.i' update!(s) @test !s.w' @test s.r' == s.i' update!(s) @test s.w' @test s.r' == s.t' t = s.t' update!(s) @test s.w' @test s.r' != s.t' && s.r' == t end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
3446
@testset "solve" begin @testset "basic" begin @system SSolve(Controller) begin a ~ preserve(parameter) b ~ preserve(parameter) c ~ preserve(parameter) x(a, b, c) => begin a*x^2 + b*x + c end ~ solve end s1 = instance(SSolve, config=:SSolve => (a=1, b=2, c=1)) @test s1.x' == -1 s2 = instance(SSolve, config=:SSolve => (a=1, b=-2, c=1)) @test s2.x' == 1 s3 = instance(SSolve, config=:SSolve => (a=1, b=2, c=-3)) @test s3.x' ∈ [1, -3] s4 = instance(SSolve, config=:SSolve => (a=1, b=-2, c=-3)) @test s4.x' ∈ [-1, 3] end @testset "unit" begin @system SSolveUnit(Controller) begin a ~ preserve(u"m^-1", parameter) b ~ preserve(parameter) c ~ preserve(u"m", parameter) x(a, b, c) => begin a*x^2 + b*x + c end ~ solve(u"m") end s = instance(SSolveUnit, config=:SSolveUnit => (a=1, b=2, c=1)) @test s.x' == -1u"m" end @testset "unit with scale" begin @system SSolveUnitScale(Controller) begin a ~ preserve(u"m^-1", parameter) b ~ preserve(u"cm/m", parameter) #HACK: caution with dimensionless unit! c ~ preserve(u"cm", parameter) x(a, b, c) => begin a*x^2 + b*x + c end ~ solve(u"cm") end s = instance(SSolveUnitScale, config=:SSolveUnitScale => (a=0.01, b=2, c=1)) @test s.x' == -100u"cm" end @testset "linear" begin @system SSolveLinear(Controller) begin x => (2x ⩵ 1) ~ solve end s = instance(SSolveLinear) @test s.x' == 0.5 end @testset "quadratic single" begin @system SSolveQuadraticSingle(Controller) begin x => (x^2 ⩵ 1) ~ solve end s = instance(SSolveQuadraticSingle) @test s.x' == 1 end @testset "quadratic double" begin @system SSolveQuadraticDouble(Controller) begin l ~ preserve(parameter) u ~ preserve(parameter) x => (x^2 + 2x - 3) ~ solve(lower=l, upper=u) end s1 = instance(SSolveQuadraticDouble, config=:SSolveQuadraticDouble => (l=0, u=Inf)) @test s1.x' == 1 s2 = instance(SSolveQuadraticDouble, config=:SSolveQuadraticDouble => (l=-Inf, u=0)) @test s2.x' == -3 end @testset "cubic" begin @system SSolveCubic(Controller) begin l ~ preserve(parameter) u ~ preserve(parameter) x => ((x-5)*(x-15)*(x-25)) ~ solve(lower=l, upper=u) end s0 = instance(SSolveCubic, config=:SSolveCubic => (l=-Inf, u=0)) @test s0.x' == 0 s1 = instance(SSolveCubic, config=:SSolveCubic => (l=-Inf, u=10)) @test s1.x' ≈ 5 s2 = instance(SSolveCubic, config=:SSolveCubic => (l=10, u=20)) @test s2.x' ≈ 15 s3 = instance(SSolveCubic, config=:SSolveCubic => (l=20, u=30)) @test s3.x' ≈ 25 s4 = instance(SSolveCubic, config=:SSolveCubic => (l=30, u=Inf)) @test s4.x' == 30 end @testset "equal" begin @system SSolveEqual(Controller) begin x1 => (x1^2 + 2x1 - 3) ~ solve x2 => (x2^2 + 2x2 - 3 ⩵ 0) ~ solve end s = instance(SSolveEqual) @test s.x1' == s.x2' end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
2659
@testset "tabulate" begin @testset "basic" begin @system STabulate(Controller) begin T => [ # a b 0 4 ; # A 1 5 ; # B 2 6 ; # C 3 7 ; # D ] ~ tabulate(rows=(:A, :B, :C, :D), columns=(:a, :b)) Aa(T) => T.A.a ~ preserve Ba(T) => T.B[:a] ~ preserve Ca(T) => T[:C].a ~ preserve Da(T) => T[:D][:a] ~ preserve Ab(T.A.b) ~ preserve Bb(T.B[:b]) ~ preserve Cb(T[:C].b) ~ preserve Db(T[:D][:b]) ~ preserve end s = instance(STabulate) @test s.Aa' == 0 @test s.Ba' == 1 @test s.Ca' == 2 @test s.Da' == 3 @test s.Ab' == 4 @test s.Bb' == 5 @test s.Cb' == 6 @test s.Db' == 7 end @testset "parameter" begin @system STabulateParameter(Controller) begin T ~ tabulate(rows=(:A, :B, :C), columns=(:a, :b), parameter) Aa(T.A.a) ~ preserve Ba(T.B.a) ~ preserve Ca(T.C.a) ~ preserve Ab(T.A.b) ~ preserve Bb(T.B.b) ~ preserve Cb(T.C.b) ~ preserve end o = STabulateParameter => :T => [ # a b 0 3 ; # A 1 4 ; # B 2 5 ; # C ] s = instance(STabulateParameter, config=o) @test s.Aa' == 0 @test s.Ba' == 1 @test s.Ca' == 2 @test s.Ab' == 3 @test s.Bb' == 4 @test s.Cb' == 5 end @testset "default columns" begin @system STabulateDefaultColumns(Controller) begin T => [ # a b 0 2 ; # a 1 3 ; # b ] ~ tabulate(rows=(:a, :b)) aa(T) => T.a.a ~ preserve ba(T) => T.b.a ~ preserve ab(T) => T.a.b ~ preserve bb(T) => T.b.b ~ preserve end s = instance(STabulateDefaultColumns) @test getfield(s.T, :rows) == getfield(s.T, :columns) == (:a, :b) @test s.aa' == 0 @test s.ba' == 1 @test s.ab' == 2 @test s.bb' == 3 end @testset "arg" begin @system STabulateArg(Controller) begin x => 0 ~ preserve(parameter) T(x) => [ # a b x x+2 ; # A x+1 x+3 ; # B ] ~ tabulate(rows=(:A, :B), columns=(:a, :b)) end s = instance(STabulateArg) @test s.T.A.a == 0 @test s.T.B.a == 1 @test s.T.A.b == 2 @test s.T.B.b == 3 end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
5385
@testset "track" begin @testset "basic" begin @system STrack(Controller) begin a => 1 ~ track b => 2 ~ track c(a, b) => a + b ~ track end s = instance(STrack) @test s.a' == 1 && s.b' == 2 && s.c' == 3 end @testset "cross reference" begin @test_throws LoadError @eval @system STrackXRef(Controller) begin a(b) => b ~ track b(a) => a ~ track end end @testset "self reference without init" begin @eval @system STrackSRefWithoutInit(Controller) begin a(a) => 2a ~ track end @test_throws UndefVarError instance(STrackSRefWithoutInit) end @testset "self reference with init" begin @system STrackSRefWithInit(Controller) begin a(a) => 2a ~ track(init=1) end r = simulate(STrackSRefWithInit, stop=3) @test r[!, :a] == [2, 4, 8, 16] end @testset "init" begin @system STrackInit(Controller) begin a(a) => a + 1 ~ track(init=0) b(b) => b + 1 ~ track(init=1) c(c) => c + 1 ~ track(init=i) d => 1 ~ track(init=i) i(t=context.clock.tick) => t + 1 ~ track end r = simulate(STrackInit, stop=3) @test r[!, :a] == [1, 2, 3, 4] @test r[!, :b] == [2, 3, 4, 5] @test r[!, :c] == [2, 3, 4, 5] @test r[!, :d] == [1, 1, 1, 1] end @testset "minmax" begin @system STrackMinMax(Controller) begin a => 0 ~ track(min=1) b => 0 ~ track(max=2) c => 0 ~ track(min=1, max=2) end s = instance(STrackMinMax) @test s.a' == 1 @test s.b' == 0 @test s.c' == 1 end @testset "minmax unit" begin @system STrackMinMaxUnit(Controller) begin a => 0 ~ track(u"m", min=1) b => 0 ~ track(u"m", max=2u"cm") c => 0 ~ track(u"m", min=1u"cm", max=2) end s = instance(STrackMinMaxUnit) @test s.a' == 1u"m" @test s.b' == 0u"m" @test s.c' == 1u"cm" end @testset "round" begin @system STrackRound(Controller) begin a => 1.5 ~ track(round) b => 1.5 ~ track(round=:round) c => 1.5 ~ track(round=:ceil) d => -1.5 ~ track(round=:floor) e => -1.5 ~ track(round=:trunc) end s = instance(STrackRound) @test s.a' === s.b' @test s.b' === 2.0 @test s.c' === 2.0 @test s.d' === -2.0 @test s.e' === -1.0 end @testset "round int" begin @system STrackRoundInt(Controller) begin a => 1.5 ~ track::int(round) b => 1.5 ~ track::int(round=:round) c => 1.5 ~ track::int(round=:ceil) d => -1.5 ~ track::int(round=:floor) e => -1.5 ~ track::int(round=:trunc) end s = instance(STrackRoundInt) @test s.a' === s.b' @test s.b' === 2 @test s.c' === 2 @test s.d' === -2 @test s.e' === -1 end @testset "round int unit" begin @system STrackRoundIntUnit(Controller) begin a => 1.5 ~ track::int(u"d", round) b => 1.5 ~ track::int(u"d", round=:round) c => 1.5 ~ track::int(u"d", round=:ceil) d => -1.5 ~ track::int(u"d", round=:floor) e => -1.5 ~ track::int(u"d", round=:trunc) end s = instance(STrackRoundIntUnit) @test s.a' === s.b' @test s.b' === 2u"d" @test s.c' === 2u"d" @test s.d' === -2u"d" @test s.e' === -1u"d" end @testset "when" begin @system STrackWhen(Controller) begin T => true ~ preserve::Bool F => false ~ preserve::Bool a => 1 ~ track b => 1 ~ track(when=true) c => 1 ~ track(when=false) d => 1 ~ track(when=T) e => 1 ~ track(when=F) f => 1 ~ track(when=!F) end s = instance(STrackWhen) @test s.a' == 1 @test s.b' == 1 @test s.c' == 0 @test s.d' == 1 @test s.e' == 0 @test s.f' == 1 end @testset "when unit" begin @system STrackWhenUnit(Controller) begin T => true ~ preserve::Bool F => false ~ preserve::Bool a => 1 ~ track(u"d") b => 1 ~ track(u"d", when=true) c => 1 ~ track(u"d", when=false) d => 1 ~ track(u"d", when=T) e => 1 ~ track(u"d", when=F) f => 1 ~ track(u"d", when=!F) end s = instance(STrackWhenUnit) @test s.a' == 1u"d" @test s.b' == 1u"d" @test s.c' == 0u"d" @test s.d' == 1u"d" @test s.e' == 0u"d" @test s.f' == 1u"d" end @testset "when init" begin @system STrackWhenInit(Controller) begin T => true ~ preserve::Bool F => false ~ preserve::Bool I => 1 ~ preserve a => 0 ~ track(init=1, when=true) b => 0 ~ track(init=1, when=false) c => 0 ~ track(init=I, when=T) d => 0 ~ track(init=I, when=F) end s = instance(STrackWhenInit) @test s.a' == 0 @test s.b' == 1 @test s.c' == 0 @test s.d' == 1 end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
272
@testset "wrap" begin @testset "basic" begin @system SWrap(Controller) begin a => 1 ~ preserve b(a) => 2a ~ track c(wrap(a)) => 2a' ~ track end s = instance(SWrap) @test s.b' == s.c' == 2 end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
2349
using TimeZones import Dates @testset "calendar" begin @testset "basic" begin @system SCalendar(Calendar, Controller) d = Dates.Date(2011, 10, 29) t0 = ZonedDateTime(d, tz"Asia/Seoul") o = :Calendar => :init => t0 s = instance(SCalendar; config=o) @test s.init' == t0 @test s.time' == t0 @test s.date' == d @test s.step' == Dates.Hour(1) update!(s) @test s.time' == t0 + Dates.Hour(1) update!(s) @test s.time' == t0 + Dates.Hour(2) end @testset "stop" begin @system SCalendarStop(Calendar, Controller) t0 = ZonedDateTime(2011, 10, 29, tz"Asia/Seoul") t1 = t0 + Dates.Day(1) o = :Calendar => (init=t0, last=t1) s = instance(SCalendarStop; config=o) @test s.init' == t0 @test s.last' == t1 @test s.time' == t0 @test s.step' == Dates.Hour(1) @test s.stop' == false for i in 1:24 update!(s) end @test s.time' == t1 @test s.stop' == true end @testset "count" begin @system SCalendarCount(Calendar, Controller) t0 = ZonedDateTime(2011, 10, 29, tz"Asia/Seoul") t1 = t0 + Dates.Day(1) n = 24 o = :Calendar => (init=t0, last=t1) s = instance(SCalendarCount; config=o) @test s.count' == n r1 = simulate(SCalendarCount; config=o, stop=n) r2 = simulate(SCalendarCount; config=o, stop=:stop) r3 = simulate(SCalendarCount; config=o, stop=:count) @test r1 == r2 == r3 end @testset "count nothing" begin @system SCalendarCountNothing(Calendar, Controller) t0 = ZonedDateTime(2011, 10, 29, tz"Asia/Seoul") o = :Calendar => (init=t0, last=nothing) s = instance(SCalendarCountNothing; config=o) @test s.count' === nothing @test s.stop' == false end @testset "count seconds" begin @system SCalendarCountSeconds(Calendar, Controller) t0 = ZonedDateTime(2011, 10, 29, tz"Asia/Seoul") t1 = t0 + Dates.Hour(1) n = 60*60 o = ( :Calendar => (init=t0, last=t1), :Clock => (step=1u"s",), ) s = instance(SCalendarCountSeconds; config=o) @test s.count' == n end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
1419
@testset "clock" begin @testset "basic" begin @system SClock(Controller) s = instance(SClock) @test s.context.clock.time' == 0u"hr" @test s.context.clock.tick' === 0 update!(s) @test s.context.clock.time' == 1u"hr" @test s.context.clock.tick' === 1 update!(s) @test s.context.clock.time' == 2u"hr" @test s.context.clock.tick' === 2 end @testset "config" begin @system SClockConfig(Controller) o = :Clock => (#=:init => 5,=# :step => 10) s = instance(SClockConfig; config=o) @test s.context.clock.time' == 0u"hr" @test s.context.clock.tick' === 0 update!(s) @test s.context.clock.time' == 10u"hr" @test s.context.clock.tick' === 1 update!(s) @test s.context.clock.time' == 20u"hr" @test s.context.clock.tick' === 2 end @testset "daily" begin @system SClockDaily{Context => Cropbox.DailyContext}(Controller) begin a => 1 ~ accumulate end s = instance(SClockDaily) @test s.context isa Cropbox.DailyContext @test s.context.clock isa Cropbox.DailyClock @test s.context.clock.time' == 0u"d" @test s.context.clock.tick' === 0 update!(s) @test s.context.clock.time' == 1u"d" @test s.context.clock.tick' === 1 @test s.a' == 1 end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
1270
@testset "controller" begin @testset "options" begin @system SControllerOptions(Controller) begin a ~ preserve(extern) b ~ ::int(override) end o = (a=1, b=2) s = instance(SControllerOptions; options=o) @test s.a' == 1 @test s.b == 2 end @testset "config placeholder" begin @system SControllerConfigPlaceholder(Controller) begin a => 1 ~ preserve(parameter) end o = 0 => :a => 2 s = instance(SControllerConfigPlaceholder; config=o) @test s.a' == 2 end @testset "seed" begin @system SControllerSeed(Controller) begin a => 0 ± 1 ~ preserve end s1 = instance(SControllerSeed; seed=0) if VERSION >= v"1.7" @test s1.a' == 0.942970533446119 else @test s1.a' == 0.6791074260357777 end s2 = instance(SControllerSeed; seed=0) @test s1.a' == s2.a' end @testset "no seed" begin @system SControllerNoSeed(Controller) begin a => 0 ± 1 ~ preserve end s1 = instance(SControllerNoSeed; seed=nothing) s2 = instance(SControllerNoSeed; seed=nothing) @test s1.a' != s2.a' end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
2068
@testset "core" begin @testset "name" begin @system SSystemName(Controller) s = instance(SSystemName) @test Cropbox.namefor(s) == :SSystemName @test Cropbox.namefor(SSystemName) == :SSystemName S = typeof(s) @test startswith(string(S), "var\"##_SSystemName#") @test S <: SSystemName @test Cropbox.namefor(S) == :SSystemName end @testset "names" begin @test names(System) == [:System] @test names(Controller) == [:Controller] @test names(Context) == [:Context] @test names(Clock) == [:Clock] end @testset "iteration" begin @system SSystemCollect(Controller) begin a => 1 ~ preserve b(a) => 2a ~ track end s = instance(SSystemCollect) @test length(s) == 4 @test collect(s) == [s.context, s.config, s.a, s.b] @test s[:a] == s.a @test s["a"] == s.a @test s."a" == s.a @test s["context.clock"] == s.context.clock @test s."context.clock" == s.context.clock @test s[nothing] == s @test s[""] == s end @testset "setvar!" begin @system SSystemSetVar(Controller) begin a => 1 ~ preserve(ref) b => 2 ~ preserve(ref) end s = instance(SSystemSetVar) @test s.a' == 1 && s.b' == 2 a, b = s.a[], s.b[] Cropbox.setvar!(s, :b, a) Cropbox.setvar!(s, :a, b) @test s.a[] === b && s.b[] === a @test s.a' == 2 && s.b' == 1 end @testset "value" begin @system SSystemValue(Controller) begin a => 1 ~ preserve b(a) => 2a ~ preserve c(a, b) => a + b ~ track d(c) ~ accumulate end s = instance(SSystemValue) @test s.a' == 1 && s.b' == 2 && s.c' == 3 @test Cropbox.value(s, :b; a=2) == 4 @test Cropbox.value(s, :c; a=0, b=1) == 1 @test Cropbox.value(s, :c; a=0) == 2 @test_throws ErrorException Cropbox.value(s, :d; c=0) end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
2726
using DataFrames: DataFrames, DataFrame using Dates: Dates, Date using TimeZones using TypedTables: TypedTables, Table @testset "store" begin @testset "dataframe" begin @system SStoreDataFrame(DataFrameStore, Controller) begin a(s) => s[:a] ~ track::int b(s) => s[:b] ~ track end a = [1, 2, 3] b = [4.0, 5.0, 6.0] df = DataFrame(; a, b) n = DataFrames.nrow(df) r = simulate(SStoreDataFrame, config=:0 => (:df => df, :ik => :a), stop=n-1) @test r.a == a @test r.b == b end @testset "day" begin @system SStoreDay(DayStore, Controller) begin a(s) => s.a ~ track end r = mktemp() do f, io write(io, "day (d),a\n0,0\n1,10\n2,20") close(io) c = (:Clock => :step => 1u"d", :0 => :filename => f) simulate(SStoreDay, config=c, stop=2) end @test r.a[1] == 0 @test r.a[2] == 10 @test r.a[end] == 20 end @testset "date" begin @system SStoreDate(DateStore, Controller) begin a(s) => s.a ~ track end r = mktemp() do f, io write(io, "date (:Date),a\n2020-12-09,0\n2020-12-10,10\n2020-12-11,20") close(io) config = ( :Clock => :step => 1u"d", :Calendar => :init => ZonedDateTime(2020, 12, 9, tz"UTC"), :0 => :filename => f, ) simulate(SStoreDate; config, stop=2u"d") end @test r.a[1] == 0 @test r.a[2] == 10 @test r.a[end] == 20 end @testset "time" begin @system SStoreTime(TimeStore, Controller) begin a(s) => s.a ~ track end r = mktemp() do f, io write(io, "date (:Date),time (:Time),a\n2020-11-15,01:00,0\n2020-11-15,02:00,10\n2020-11-15,03:00,20") close(io) config = ( :Clock => :step => 1u"hr", :Calendar => :init => ZonedDateTime(2020, 11, 15, 1, tz"America/Los_Angeles"), :0 => (:filename => f, :tz => tz"America/Los_Angeles"), ) simulate(SStoreTime; config, stop=2u"hr") end @test r.a[1] == 0 @test r.a[2] == 10 @test r.a[end] == 20 end @testset "table" begin @system SStoreTable(TableStore, Controller) begin a(s) => s[:a] ~ track::int b(s) => s[:b] ~ track end a = [1, 2, 3] b = [4.0, 5.0, 6.0] tb = Table(; a, b) n = length(tb) r = simulate(SStoreTable, config=:0 => :tb => tb, stop=n-1) @test r.a == a @test r.b == b end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
2646
using DataFrames @testset "calibrate" begin @testset "basic" begin @system SCalibrate(Controller) begin a => 0 ~ preserve(parameter) b(a) ~ accumulate end n = 10 t, a, b = 10.0u"hr", 20, 200 A = (0.0, 100.0) obs = DataFrame(time=[t], b=[b]) p = calibrate(SCalibrate, obs, stop=n, target=:b, parameters=("SCalibrate.a" => A)) @test p[:SCalibrate][:a] == a r = simulate(SCalibrate, stop=n, config=p) @test r[r.time .== t, :][1, :b] == b end @testset "unit" begin @system SCalibrateUnit(Controller) begin a => 0 ~ preserve(parameter, u"cm/hr") b(a) ~ accumulate(u"m") end n = 10 t, a, b = 10.0u"hr", 20u"cm/hr", 200u"cm" A = [0, 1]u"m/hr" obs = DataFrame(time=[t], b=[b]) p = calibrate(SCalibrateUnit, obs, stop=n, target=:b, parameters=("SCalibrateUnit.a" => A)) @test p[:SCalibrateUnit][:a] ≈ a r = simulate(SCalibrateUnit, stop=n, config=p) @test r[r.time .== t, :][1, :b] == b end @testset "config" begin @system SCalibrateConfig(Controller) begin a => 0 ~ preserve(parameter) w => 1 ~ preserve(parameter) b(a, w) => w*a ~ accumulate end n = 10 t, a, b = 10.0u"hr", 20, 200 w1, w2 = 1, 2 A = (0.0, 100.0) obs = DataFrame(time=[t], b=[b]) params = :SCalibrateConfig => :a => A p1 = calibrate(SCalibrateConfig, obs, stop=n, target=:b, config=(:SCalibrateConfig => :w => w1), parameters=params) @test p1[:SCalibrateConfig][:a] == a/w1 p2 = calibrate(SCalibrateConfig, obs, stop=n, target=:b, config=(:SCalibrateConfig => :w => w2), parameters=params) @test p2[:SCalibrateConfig][:a] == a/w2 end @testset "configs as index" begin @system SCalibrateConfigsIndex(Controller) begin a => 0 ~ preserve(parameter) w => 1 ~ preserve(parameter) b(a, w) => w*a ~ accumulate end n = 10 t, w, b = [10.0u"hr", 10.0u"hr"], [1, 2], [100, 200] A = (0.0, 100.0) obs = DataFrame(; time=t, w, b) configs = [ :SCalibrateConfigsIndex => :w => 1, :SCalibrateConfigsIndex => :w => 2, ] index = [:time => "context.clock.time", :w] target = :b params = :SCalibrateConfigsIndex => :a => A p = calibrate(SCalibrateConfigsIndex, obs, configs; stop=n, index, target, parameters=params) @test p[:SCalibrateConfigsIndex][:a] == 10 end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
code
10992
using DataFrames using Dates @testset "simulate" begin @testset "basic" begin @system SSimulate(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate end n = 10 r = simulate(SSimulate, stop=n) @test r isa DataFrame @test size(r, 1) == (n+1) @test propertynames(r) == [:time, :a, :b] @test r[end, :time] == n*u"hr" @test r[end, :a] == 1 @test r[end, :b] == n r = simulate(SSimulate, stop=n, config=(:SSimulate => :a => 2)) @test r[end, :a] == 2 @test r[end, :b] == 2n r = simulate(SSimulate, stop=n, target=[:b]) @test size(r, 2) == 2 @test propertynames(r) == [:time, :b] r = simulate(SSimulate, stop=n, index=:b, target=[:b]) @test size(r, 2) == 1 @test propertynames(r) == [:b] end @testset "stop number" begin @system SSimulateStopNumber(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate end r = simulate(SSimulateStopNumber, stop=5) @test r[end-1, :b] == 4 @test r[end, :b] == 5 end @testset "stop number unit" begin @system SSimulateStopNumberUnit(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate end r1 = simulate(SSimulateStopNumberUnit, stop=2u"hr") @test r1[end, :b] == 2 * 1 r2 = simulate(SSimulateStopNumberUnit, stop=2u"d") @test r2[end, :b] == 2 * 24 r3 = simulate(SSimulateStopNumberUnit, stop=2u"yr") @test r3[end, :b] == 2 * 24 * 365.25 end @testset "stop count" begin @system SSimulateStopCount(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate c => 5 ~ preserve::int end r = simulate(SSimulateStopCount, stop=:c) @test r[end-1, :b] == 4 @test r[end, :b] == 5 end @testset "stop count unit" begin @system SSimulateStopCountUnit(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate c ~ preserve::Cropbox.Quantity(parameter) end r1 = simulate(SSimulateStopCountUnit, stop=:c, config=:0 => :c => 2u"hr") @test r1[end, :b] == 2 * 1 r2 = simulate(SSimulateStopCountUnit, stop=:c, config=:0 => :c => 2u"d") @test r2[end, :b] == 2 * 24 r3 = simulate(SSimulateStopCountUnit, stop=:c, config=:0 => :c => 2u"yr") @test r3[end, :b] == 2 * 24 * 365.25 end @testset "stop boolean" begin @system SSimulateStopBoolean(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate z(b) => b >= 5 ~ flag end r1 = simulate(SSimulateStopBoolean, stop=:z) @test r1[end-1, :b] == 4 @test r1[end, :b] == 5 r2 = simulate(SSimulateStopBoolean, stop="z") @test r1 == r2 r3 = simulate(SSimulateStopBoolean, stop=s -> s.b' >= 5) @test r1 == r3 end @testset "snap" begin @system SSimulateSnap(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate f(b) => (b % 2 == 0) ~ flag end n = 10 f(s) = s.b' % 2 == 0 r0 = simulate(SSimulateSnap, stop=n, snap=nothing) @test !all(r0.b .% 2 .== 0) r1 = simulate(SSimulateSnap, stop=n, snap=f) @test all(r1.b .% 2 .== 0) r2 = simulate(SSimulateSnap, stop=n, snap=:f) @test all(r2.b .% 2 .== 0) r3 = simulate(SSimulateSnap, stop=n, snap="f") @test all(r3.b .% 2 .== 0) end @testset "snatch" begin @system SSimulateSnatch(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate end n = 3 i = 0 f(D, s) = begin d = D[1] @test s.a' == d[:a] && s.b' == d[:b] i += 1 d[:c] = i end r = simulate(SSimulateSnatch, stop=n, snatch=f) @test i == 1 + n @test r[!, :c] == [1, 2, 3, 4] end @testset "callback" begin @system SSimulateCallback(Controller) begin a => 1 ~ preserve(parameter) b(a) ~ accumulate end n = 3 i = 0 f(s, m) = begin r = m.result[end] @test s.a' == r[:a] && s.b' == r[:b] i += 1 end simulate(SSimulateCallback, stop=n, callback=f) @test i == n end @testset "layout" begin @system SSimulateLayout(Controller) begin i => 1 ~ accumulate a(i) => i-1 ~ track b(i) => 2i ~ track end L = [ (target=:a,), (index=[:t => "context.clock.time", "i"], target=["a", :B => :b]), (base="context.clock", index="time", target="step"), (target=:b, meta=(:c => 0, :d => :D)), ] n = 1 r = simulate(SSimulateLayout, L, stop=n) @test propertynames(r[1]) == [:time, :a] @test propertynames(r[2]) == [:t, :i, :a, :B] @test propertynames(r[3]) == [:time, :step] @test propertynames(r[4]) == [:time, :b, :c, :d] @test r[1][end, :time] == r[2][end, :t] == r[3][end, :time] == r[4][end, :time] == n*u"hr" @test r[1][end, :a] == 0 @test r[2][end, :B] == 2 @test r[3][end, :step] == 1u"hr" @test all(r[4][!, :c] .== 0) && all(r[4][!, :d] .== :D) end @testset "layout and configs" begin @system SSimulateLayoutConfigs(Controller) begin p ~ preserve(parameter) i => 1 ~ accumulate a(i, p) => p*(i-1) ~ track b(i, p) => 2p*i ~ track end L = [ (index=:i, target=:a), (index=:t => "context.clock.time", target=:b), (target=[:i, :a, :b],), ] p1, p2 = 1, 2 C = [ :SSimulateLayoutConfigs => :p => p1, :SSimulateLayoutConfigs => :p => p2, ] n = 10 r = simulate(SSimulateLayoutConfigs, L, C, stop=n) @test length(r) == length(L) o = r[3] @test o[o.time .== n*u"hr", :i] == [n, n] @test o[o.time .== n*u"hr", :a] == [p1*(n-1), p2*(n-1)] @test o[o.time .== n*u"hr", :b] == [2p1*n, 2p2*n] end @testset "configs" begin @system SSimulateConfigs(Controller) begin a ~ preserve(parameter) b(a) ~ accumulate end p = [1, 2] C = @config !(:SSimulateConfigs => :a => p) n = 10 r = simulate(SSimulateConfigs, configs=C, stop=n) @test r[r.time .== n*u"hr", :a] == p @test r[r.time .== n*u"hr", :b] == p .* n end @testset "config and configs" begin @system SSimulateConfigConfigs(Controller) begin x ~ preserve(parameter) a ~ preserve(parameter) b(a) ~ accumulate end x = 0 A = [1, 2] c = @config :SSimulateConfigConfigs => :x => x C = @config !(:SSimulateConfigConfigs => :a => A) n = 10 r = simulate(SSimulateConfigConfigs; config=c, configs=C, stop=n) @test all(r[r.time .== n*u"hr", :x] .== x) @test r[r.time .== n*u"hr", :a] == A @test r[r.time .== n*u"hr", :b] == A .* n end @testset "meta" begin @system SSimulateMeta(Controller) begin a ~ preserve(parameter) b(a) ~ accumulate end C = ( :SSimulateMeta => (a=1,), :Extra => (b=2, c=:C), ) n = 10 r1 = simulate(SSimulateMeta, config=C, index=(), meta=:Extra, stop=n) @test propertynames(r1) == [:a, :b, :c] @test all(r1.b .== 2) @test all(r1.c .== :C) r2 = simulate(SSimulateMeta, config=C, index=(), meta=(:Extra, :d => 0), stop=n) @test propertynames(r2) == [:a, :b, :c, :d] @test r1.b == r2.b @test r1.c == r2.c @test all(r2.d .== 0) end @testset "wildcard" begin @system SSimulateWildcardA begin x => 1 ~ preserve y => 2 ~ preserve end @system SSimulateWildcard(Controller) begin A(context) ~ ::SSimulateWildcardA a => 3 ~ preserve b => 4 ~ preserve end r1 = simulate(SSimulateWildcard; target="*") @test names(r1) == ["time", "a", "b"] @test collect(r1[1,:]) == [0u"hr", 3, 4] r2 = simulate(SSimulateWildcard; target="A.*") @test names(r2) == ["time", "A.x", "A.y"] @test collect(r2[1,:]) == [0u"hr", 1, 2] r3 = simulate(SSimulateWildcard; target=["*", "A.*"]) @test names(r3) == ["time", "a", "b", "A.x", "A.y"] @test collect(r3[1,:]) == [0u"hr", 3, 4, 1, 2] r4 = simulate(SSimulateWildcard; target=["A.*", "*"]) @test names(r4) == ["time", "A.x", "A.y", "a", "b"] @test collect(r4[1,:]) == [0u"hr", 1, 2, 3, 4] end @testset "options" begin @system SSimulateOptions(Controller) begin a ~ preserve(extern) b ~ ::int(override) end n = 10 a, b = 1, 2 o = (; a, b) r = simulate(SSimulateOptions, options=o, stop=n) @test r[end, :a] == a @test r[end, :b] == b end @testset "seed" begin @system SSimulateSeed(Controller) begin a => rand() ~ track b(a) ~ accumulate end n = 10 r1 = simulate(SSimulateSeed, seed=0, stop=n) if VERSION >= v"1.7" @test r1[end, :a] == 0.8969897902567084 @test r1[end, :b] == 3.462686872284925 else @test r1[end, :a] == 0.5392892841426182 @test r1[end, :b] == 3.766035118243237 end r2 = simulate(SSimulateSeed, seed=0, stop=n) @test r1 == r2 end @testset "no seed" begin @system SSimulateNoSeed(Controller) begin a => rand() ~ track b(a) ~ accumulate end n = 10 r1 = simulate(SSimulateNoSeed, seed=nothing, stop=n) r2 = simulate(SSimulateNoSeed, seed=nothing, stop=n) @test r1 != r2 end @testset "extractable" begin @system SSimulateExtractable(Controller) begin a => 1 ~ track b => :hello ~ track::sym c => "world" ~ track::str d => DateTime(2020, 3, 1) ~ track::DateTime e => Dict(:k => 0) ~ track::Dict f => [1, 2, 3] ~ track::Vector g => (1, 2) ~ track::Tuple end r = simulate(SSimulateExtractable) N = propertynames(r) # default = Union{Number,Symbol,AbstractString,AbstractDateTime} @test :a ∈ N @test :b ∈ N @test :c ∈ N @test :d ∈ N @test :e ∉ N @test :f ∉ N @test :g ∉ N end end
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
2103
<a href="https://github.com/cropbox/Cropbox.jl"><img src="https://github.com/cropbox/Cropbox.jl/raw/main/docs/src/assets/logo.svg" alt="Cropbox" width="150"></a> # Cropbox.jl [![Stable Documentation](https://img.shields.io/badge/docs-stable-blue.svg)](https://cropbox.github.io/Cropbox.jl/stable/) [![Latest Documentation](https://img.shields.io/badge/docs-dev-blue.svg)](https://cropbox.github.io/Cropbox.jl/dev/) [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/cropbox/cropbox-binder/main) Cropbox is a declarative modeling framework specifically designed for developing crop models. The goal is to let crop modelers focus on *what* the model should look like rather than *how* the model is technically implemented under the hood. ## Talks - [JuliaCon 2022](https://youtu.be/l43ldy_L35A) -- "Cropbox.jl: A Declarative Crop Modeling Framework" ## Examples - 🍃 [LeafGasExchange.jl](https://github.com/cropbox/LeafGasExchange.jl) / [plants2020](https://github.com/cropbox/plants2020): coupled leaf gas-exchange model - 🧄 [Garlic.jl](https://github.com/cropbox/Garlic.jl): garlic growth simulation model - 🥬 [Cabbage.jl](https://github.com/cropbox/Cabbage.jl): port of pycabbage model - 🌱 [SimpleCrop.jl](https://github.com/cropbox/SimpleCrop.jl): example of DSSAT-like crop model written in Cropbox - 🪴 [CropRootBox.jl](https://github.com/cropbox/CropRootBox.jl): example of root system architecture simulation like CRootBox ## Tutorials - Cropbox Workshop: [2021](https://github.com/cropbox/cropbox-workshop-2021), [2022](https://github.com/cropbox/cropbox-workshop-2022) (Korea), [2022](https://github.com/cropbox/cropbox-workshop-2022-tw) (Taiwan) - [UW SEFS 508](https://github.com/uwkimlab/plant_modeling) -- "Plant Modeling" course at University of Washington - [Cropbox Tutorial](https://github.com/cropbox/cropbox-tutorial-KSAFM2020) presented at [KSAFM](http://www.ksafm.org/en/) 2020 Workshop ## Citation Yun K, Kim S-H (2023) Cropbox: a declarative crop modelling framework. in silico Plants, 5(1), diac021, https://doi.org/10.1093/insilicoplants/diac021
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
81
!!! warning "Warning" This page is incomplete. # Frequently Asked Questions
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
318
# Gallery Here are some models built using the Cropbox framework. ## [CropRootBox.jl](https://github.com/cropbox/CropRootBox.jl) ## [Garlic.jl](https://github.com/cropbox/Garlic.jl) ## [LeafGasExchange.jl](https://github.com/cropbox/LeafGasExchange.jl) ## [SimpleCrop.jl](https://github.com/cropbox/SimpleCrop.jl)
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
1051
# Cropbox ## What is Cropbox? Cropbox is a declarative modeling framework specifically designed for developing crop models. The goal is to let crop modelers focus on *what* the model should look like rather than *how* the model is technically implemented under the hood. ## Getting started * Read the [Installation](@ref Installation). * Read the [Tutorials](@ref Julia). * Read the [Manual](@ref system). * Check out the [Cropbox Tutorial](https://github.com/cropbox/cropbox-tutorial-KSAFM2020) presented at the [KSAFM](http://www.ksafm.org/en/) 2020 Workshop * Check out the course material for [SEFS 508](https://github.com/uwkimlab/plant_modeling), a plant modeling course at the University of Washington. * Check out the [Gallery](@ref Gallery) to see what others have done with the Cropbox framework. ## Citation When using Cropbox in your work, please cite the following paper: ``` Yun K, Kim S-H (2023) Cropbox: a declarative crop modelling framework. in silico Plants 5(1), diac021 (https://doi.org/10.1093/insilicoplants/diac021) ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
2981
# [Installation](@id Installation) ## Installing Julia Cropbox is a domain-specific language (DSL) for [Julia](https://julialang.org). To use Cropbox, you must first [download and install](https://julialang.org/downloads/) Julia. For new users, it is recommended to install the "Current stable release" for Julia. In general, you will want to install the 64-bit version. If you run into an issue installing the 64-bit version, you can try the 32-bit version. During installation, select "Add Julia to PATH". You can also add Julia to PATH after installation using the terminal. ```shell export PATH="$PATH:/path/to/<Julia directory>/bin" ``` For more detailed platform-specific instructions, you can check the [official Julia instructions](https://julialang.org/downloads/platform/). Once Julia is added to PATH, the interactive REPL can be started by double-clicking the Julia executable or running `julia` from the command line. ## Using JupyterLab While you can technically use the terminal or command prompt to run your code, it may be convenient to use an integrated development environment (IDE) or an interactive platform like [JupyterLab](https://jupyter.org/install). To add the Julia kernel to Jupyter, launch the REPL and add the IJulia package. ```julia using Pkg Pkg.add("IJulia") ``` When you launch Jupyter, you should now be able to select a Julia kernel to run your notebook. ## Installing Cropbox [Cropbox.jl](https://github.com/cropbox/Cropbox.jl) is available through Julia package manager and can be installed using the Julia REPL. ```julia using Pkg Pkg.add("Cropbox") ``` ## Using Docker If you would like to skip the process of installing Julia and Cropbox on your machine, there is a [Docker image](https://hub.docker.com/repository/docker/cropbox/cropbox) with Cropbox precompiled for convenience. Install [Docker Desktop](https://www.docker.com/products/docker-desktop/) on your machine by following the instructions on the website and run the following command in the terminal or command prompt. ```shell $ docker run -it --rm -p 8888:8888 cropbox/cropbox ``` By default, this will launch a JupyterLab session that you can access by opening the printed URL in your browser. If REPL is preferred, you can directly launch an instance of Julia session. ```shell docker run -it --rm cropbox/cropbox julia _ _ _ _(_)_ | Documentation: https://docs.julialang.org (_) | (_) (_) | _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help. | | | | | | |/ _` | | | | |_| | | | (_| | | Version 1.6.1 (2021-04-23) _/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release |__/ | julia> ``` ## Using Binder The docker image can be also launched via Binder without installing anything locally. This method is the least recommended due to its timeout duration. [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/cropbox/cropbox-binder/main)
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
6364
```@setup Cropbox using Cropbox using DataFrames ``` # [Configuration](@id Configuration1) In Cropbox, `Config` is a configuration object structured as a nested dictionary or a hash table. It stores user-defined parameter values as a triplet of *system* - *variable* - *value*. Providing a configuration object with specific parameter values during instantiation of a system allows the user to insert or replace values for parameter variables within the system. For a variable to be eligible for adjustment through a configuration, the variable must have the `parameter` tag. There are six possible variable states that have access to the `parameter` tag: [`preserve`](@ref preserve), [`flag`](@ref flag), [`provide`](@ref provide), [`drive`](@ref drive), [`tabulate`](@ref tabulate), and [`interpolate`](@ref interpolate). The type of *value* that you assign in a configuration will vary depending on the variable state. For example, a configuration for a `flag` variable will contain an expression that can be evaluated as `true` or `false`. ## Creating a Configuration Configurations are created using the `@config` macro. A basic unit of configuration for a system `S` is represented as a pair in the form of `S => p` (`p` represents a parameter). The parameter variable and its corresponding value is represented as another pair in the form of `p => v`. In other words, a configuration is created by pairing system `S` to a pairing of parameter variable and value `p => v`, like so: `:S => :p => v`. **Example** Here is an example of changing the value of a parameter variable using a configuration. ```@example Cropbox @system S(Controller) begin a => 1 ~ preserve(parameter) b => 2 ~ preserve(parameter) end config = @config(:S => :a => 2) instance(S; config) ``` In system `S`, the variable `a` is a `preserve` variable with the value of `1`. Because the variable has the `parameter` tag, its value can be reassigned with a configuration at instantiation. !!! note "Note" A configuration can be used to change the value of *any* parameter variable within a system. This includes parameters variables within built-in systems such as `Clock` and `Calendar`. ### Syntax The `@config` macro accepts a number of different syntaxes to create a configuration object. Below is an example of creating the most basic configuration. Note that the system `S` is written as a [symbol](https://docs.julialang.org/en/v1/base/base/#Core.Symbol). ```@example Cropbox @config :S => :a => 2 ``` !!! note "Note" When creating a configuration for a system, the system name is expressed as a symbol in the form of `:S`. If the actual system type is used in the form of `S`, its name will automatically be converted into a symbol. #### Multiple Parameters When specifying multiple parameters in a system, we can pair the system to either a tuple of pairs or named tuples. **Tuple of Pairs** ```@example Cropbox @config :S => (:a => 1, :b => 2) ``` **Named Tuples** ```@example Cropbox @config :S => (a = 1, b = 2) ``` #### Multiple Systems We can create configurations for multiple systems by concatenating the configuration for each system into a tuple. For multiple parameters in multiple systems, you can use either a tuple of pairs or named tuples, as shown previously. ```@example Cropbox @system S1 begin a ~ preserve end @system S2 begin b ~ preserve end @config(:S1 => :a => 1, :S2 => :b => 2) ``` #### Multiple Configurations When multiple sets of configurations are needed, as in the `configs` argument for `simulate()`, a vector of `Config` objects is used. ```@example Cropbox c = @config[:S => :a => 1, :S => :a => 2] ``` The `@config` macro also supports some convenient ways to construct a vector of configurations. The prefix operator `!` allows `expansion` of any iterable placed in the configuration value. For example, `!(:S => :a => 1:2)` is expanded into two sets of separate configurations [:S => :a => 1, :S => :a => 2]. ```@example Cropbox @config !(:S => :a => 1:2) ``` The infix operator `*` allows multiplication of a vector of configurations with another vector or a single configuration to construct multiple sets of configurations. For example, `(:S => :a => 1:2) * (:S => :b => 0)` is multiplied into [:S => (a = 1, b = 0), :S => (a = 2, b = 0)]. ```@example Cropbox @config (:S => :a => 1:2) * (:S => :b => 0) ``` #### Combining Configurations When you have multiple `Config` objects that you want to combine without making one from scratch, you can do that also using the `@config` macro. If there are variables with identical names, note that the value from the latter configuration will take precedence. ```@example Cropbox c1 = :S => (:a => 1, :b => 1) c2 = :S => (:b => 2) c3 = @config(c1, c2) ``` ## Changing the Time Step By default, a model simulation in Cropbox updates at an hourly interval. Based on your model, there may be times when you want to change the time step of the simulation. This can be done using a configuration. In order to change the time step value, all we need to do is assign a new value for `step`, which is simply a `preserve` variable with the `parameter` tag in the `Clock` system. **Example** Here we create a simple system with an `advance` variable that simply starts at 0 and increases by 1 every time step (the variable is irrelevant). ```@example Cropbox @system S(Controller) begin a ~ advance end simulate(S; stop=2u"hr") ``` \ We can configure the `step` variable within the `Clock` system to `1u"d"`, then insert the configuration object into the `simulate()` function, changing the simulation to a daily interval. ```@example Cropbox c = @config(:Clock => :step => 1u"d") simulate(S; config=c, stop=2u"d") ``` ## Supplying a DataFrame to a `provide` Variable Apart from changing numerical parameter values, configurations are also commonly used to provide a new DataFrame to a `provide` variable that stores data for simulation. The syntax of the configuration remains identical, but instead of a numerical value, we provide a DataFrame. This allows us to easily run multiple simulations of a model using different datasets. **Example** ```@example Cropbox @system S(Controller) begin D ~ provide(parameter) end c = @config( :S => :D => DataFrame(index=(0:2)u"hr", value=0:10:20) ) instance(S; config=c) ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
1578
```@setup Cropbox using Cropbox ``` # Inspection There are two inspective functions in Cropbox that allow us to look at systems more closely. For information regarding syntax, please check the [reference](@ref Inspection1). * [`look()`](@ref look) * [`dive()`](@ref dive) ## [`look()`](@id look) The `look()` provides a convenient way of accessing variables within a system. **Example** ```@example Cropbox """ This is a system. """ @system S begin """ This is a parameter. """ a ~ preserve(parameter) end look(S) ``` ```@example Cropbox look(S, :a) ``` !!! note "Note" There is a macro version of this function, `@look`, which allows you to access a variable without using a symbol. ``` @look S @look S a @look S, a ``` Both `@look S.a` and `@look S a` are identical to `look(S, :a)`. ## [`dive()`](@id dive) The `dive()` function allows us to inspect an instance of a system by navigating through the hierarchy of variables displayed in a tree structure. Pressing up/down arrow keys allows navigation. Press 'enter' to dive into a deeper level and press 'q' to come back. A leaf node of the tree shows an output of look regarding the variable. Pressing 'enter' again would return a variable itself and exit to REPL. This function only works in a terminal environment and will not work in Jupyter Notebook. **Example** ``` julia> @system S(Controller) begin a => 1 ~ preserve(parameter) end; julia> s = instance(S); julia> dive(s) S → context = <Context> config = <Config> a = 1.0 ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
4240
```@setup Cropbox using Cropbox using DataFrames ``` # Simulation There are four different functions in Cropbox for model simulation. For information regarding syntax, please check the [reference](@ref Simulation1). * [`instance()`](@ref instance) * [`simulate()`](@ref simulate) * [`evaluate()`](@ref evaluate) * [`calibrate()`](@ref calibrate) !!! tip "Tip" When running any of these functions, do not forget to include `Controller` as a mixin for the system. ## [`instance()`](@id instance) The `instance()` function is the core of all simulative functions. To run any kind of simulation of a system, the system must first be instantiated. The `instance()` function simply makes an instance of a system with an initial condition specified by a configuration and additional options. **Example** ```@example Cropbox @system S(Controller) begin a ~ advance b => 1 ~ preserve(parameter) c(a, b) => a*b ~ track end s = instance(S) ``` After creating an instance of a system, we can simulate the system manually, using the `update!()` function. ```@example Cropbox update!(s) ``` ```@example Cropbox update!(s) ``` We can also specify a configuration object in the function to change or fill in parameter values of the system. ```@example Cropbox c = @config(:S => :b => 2) instance(S; config=c) ``` ## [`simulate()`](@id simulate) `simulate()` runs a simulation by creating an instance of a specified system and updating it a specified number of times in order to generate an output in the form of a DataFrame. You can think of it as a combination of the `instance()` and the `update!()` function where each row of the DataFrame represents an update. **Example** ```@example Cropbox @system S(Controller) begin a ~ advance b => 1 ~ preserve(parameter) c(a, b) => a*b ~ track end simulate(S; stop=2) ``` Just like the `instance()` function, we can add a configuration object to change or fill in the parameter values. ```@example Cropbox c = @config(:S => :b => 2) simulate(S; config=c, stop=2) ``` \ !!! tip "Tip" When using the `simulate()` function, it is recommended to always include an argument for the `stop` keyword unless you only want to see the initial calculations. ## [`evaluate()`](@id evaluate) The `evaluate()` function compares two datasets with a choice of evaluation metric. You can compare two DataFrames (commonly the observation and the estimation data), or a System and a DataFrame, which will automatically simulate the system to generate a DataFrame that can be compared. Naturally, if you already have a DataFrame output from a previous simulation, you can use the first method. **Two DataFrames** ```@example Cropbox obs = DataFrame(time = [1, 2, 3]u"hr", a = [10, 20, 30]u"g") est = DataFrame(time = [1, 2, 3]u"hr", a = [11, 19, 31]u"g", b = [12, 22, 28]u"g") evaluate(obs, est; index = :time, target = :a, metric = :rmse) ``` If the column names are different, you can pair the columns in the `target` argument to compare the two. ```@example Cropbox evaluate(obs, est; index = :time, target = :a => :b) ``` **System and a DataFrame** ```@example Cropbox @system S(Controller) begin p => 10 ~ preserve(parameter, u"g/hr") t(context.clock.time) ~ track(u"hr") a(p, t) => p*t ~ track(u"g") end evaluate(S, est; target = :a, stop = 3) ``` ## [`calibrate()`](@id calibrate) `calibrate()` is a function used to estimate a set of parameters for a given system, that will yield a simulation as closely as possible to a provided observation data. A multitude of simulations are conducted using different combinations of parameter values specified by a range of possible values. The optimal set of parameters is selected based on the chosen evaluation metric (RMSE by default). The algorithm used is the differential evolution algorithm from [BlackBoxOptim.jl](https://github.com/robertfeldt/BlackBoxOptim.jl). The function returns a Config object that we can directly use in model simulations. **Example** ```@example Cropbox @system S(Controller) begin a => 0 ~ preserve(parameter) b(a) ~ accumulate end obs = DataFrame(time=10u"hr", b=200) p = calibrate(S, obs; target=:b, parameters=:S => :a => (0, 100), stop=10) ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
8121
```@setup Cropbox using Cropbox ``` # [System](@id system) In Cropbox, a system is a unit of model component that contains a collection of variables. The framework guarantees that the most current state of a variable is accessible by another variable that depends on said variable, provided that they are within the same system. To ensure a correct propagation of variable states, the system must have a linear order of computation that satisfies all the requirements for dependency imposed by variable declarations. Any inconsistency caused by a cyclic dependency between variables stops code generation and results in an error. This is intentional, as we want to avoid such logical errors from going through unnoticed. Once a system is defined, its structure is fixed and variables cannot be added or removed. The variables themselves, however, can still be updated throughout time steps. Variables declared in another system can be also accessed if the entire system holding dependent variables has already been updated. This is done by declaring an external system as a member of another system. ## Creating a System A system in Cropbox is created through the Cropbox-specific macro, `@system`. ``` @system name[{patches..}][(mixins..)] [<: type] [decl] -> Type{<:System} ``` `@system` declares a new system called `name`, with new variables declared in `decl` block using a custom syntax. `mixins` allow specifications of existing systems to be used for the new system. `patches` may provide type substitution and/or constant definition needed for advanced use. **Example** Here is an example of what a simple system may look like. ``` @system begin i => 1 ~ preserve a => 0.1 ~ preserve(parameter) r(a, x) => a*x ~ track x(r) ~ accumulate(init = i) end ``` In this system, we declared four [variables](@ref variable). - `i`: variable containing initial value of `x` which never changes (*preserved*) - `a`: variable containing constant **parameter** of exponential growth - `r`: rate variable which needs to be calculated or *tracked* every time step - `x`: state variable which *accumulates* by rate `r` over time with initial value `i` !!! note "Note" We can use the Julia macro `@macroexpand` to see the expression generated by the `@system` macro. ## Mixin A `mixin` is a system that is included as a part another system. While each system implements its own set of variables, these variables can be linked with variables from other systems through the use of mixins. [Controller](@ref Controller) is a mixin required to instantiate a system. **Example** Here is an example where the system `S3` is declared with systems `S1` and `S2` as mixins. ```@example Cropbox @system S1 begin a => 1 ~ preserve(parameter) b(a) => 2a ~ track end @system S2 begin a => 2 ~ preserve(parameter) b(a, c) => a*c ~ track c => 1 ~ preserve end @system S3(S1, S2, Controller) begin d(a) => 3a ~ preserve end instance(S3) ``` !!! note "Note" The order of mixins when creating a system is significant. When two variables from two different mixins share a name, the variable from the latter mixin in the system declaration will take priority over the first. ## Context Whenever a system is constructed in Cropbox, an internal variable named `context` referencing to an instance of a `Context` system is included by default. The purpose of the `Context` system is to manage the time and configuration of a system. This is what the `Context` system looks like: ``` @system Context begin context ~ ::Nothing config ~ ::Config(override) clock(config) ~ ::Clock end ``` The variables `config` and `clock`, referencing to the systems `Config` and `Clock` respectively, are necessary for system instantiation and thus included in every new system by default. ### Clock Within the `Context` system, there is a `clock` variable referring to the `Clock` system. The `Clock` system is responsible for keeping track of time-related variables, namely `init`, `step`, `time`, and `tick`. This is what the `Clock` system looks like: ``` abstract type Clock <: System end timeunit(::Type{<:Clock}) = u"hr" @system Clock{timeunit = timeunit(Clock)} begin context ~ ::Nothing config ~ ::Config(override) init => 0 ~ preserve(unit=timeunit, parameter) step => 1 ~ preserve(unit=timeunit, parameter) time => nothing ~ advance(init=init, step=step, unit=timeunit) tick => nothing ~ advance::int end ``` `time` is an `advance` variable which is essentially an `accumulate` variable tailored for keeping time of simulation. By default, `time` starts at hour 0 and increases by 1-hour intervals. `tick` is another time variable that is responsible for keeping track of the number of updates performed. As a result, `context.clock.time` and `context.clock.tick` are often used as the index for the x-axis of plots and visualizations. The `step` variable is determines the time-step intervals of simulation. ### Config Unlike the `Clock` system, the `Config` referred to by the `config` variable in `Context` is not a system. `Config` is a configuration object structured as a nested dictionary or hash table to store user-defined parameter values as a triplet of *system* - *variable* - *value*. When a configuration object containing specified parameter values are provided to a instantiation of a system, the corresponding variables in the system with the tag `parameter` will have the configuration values plugged in. Read more about configurations [here](@ref Configuration1). ## Controller An instance of context and configuration provided to an instance of a new system is usually sourced by a parent system that holds a variable referring to that system. However, because there is no parent system for the instantiation of the first system, context and configuration need to be supplied elsewhere. `Controller` is a pre-built system of Cropbox made to handle such issues by creating an instance of Context by itself. This is what the `Controller` system looks like: ``` @system Controller begin config ~ ::Config(override) context(config) ~ ::Context(context) end ``` The `Config` object referred to by the `config` variable is overridden by a keyword argument `(config)` of the system constructor `instance()` and functions such as `simulate()` and `visualize()`. Therefore at least one (and usually only one) system is designated to possess `Controller` as one of its mixins. In order to run an instance or a simulation of a system, `Controller` *must* be included as a mixin. Unlike the system `Context`, Controller must be explicitly declared as a mixin when declaring a system. !!! tip "Tip" When you create a system that you want to instantiate, make sure to have `Controller` as a mixin. You can also make a system instantiable by making a new system with the original system and `Controller` as mixins. ## Calendar `Calendar` is a system similar to the `Clock` system. `Calendar` provides `time` and `step` variables, but in the type of ZonedDateTime from [TimeZones.jl](https://github.com/JuliaTime/TimeZones.jl). Much like `Clock`, `Calendar` is a pre-built Cropbox system, but `Calendar` is not included by default as a variable reference like `context` for the system `Context`. Also, unlike `Clock`, `Calendar` is not embedded in `Context`. This is what the `Calendar` system looks like: ``` @system Calendar begin init ~ preserve::datetime(extern, parameter) last => nothing ~ preserve::datetime(extern, parameter, optional) time(t0=init, t=context.clock.time) => t0 + convert(Cropbox.Dates.Second, t) ~ track::datetime date(time) => Cropbox.Dates.Date(time) ~ track::date step(context.clock.step) ~ preserve(u"hr") stop(time, last) => begin isnothing(last) ? false : (time >= last) end ~ flag count(init, last, step) => begin if isnothing(last) nothing else # number of update!() required to reach `last` time (last - init) / step end end ~ preserve::int(round, optional) end ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
27212
```@setup Cropbox using Cropbox using DataFrames ``` # [Variable](@id variable) In Cropbox, a variable is defined as a unit element of modeling that denotes a value determined by a specific operation relying on other variables. Each variable represents a field within the system struct defined by the `@system` macro. ## Variable Declaration Variables are declared when a system is declared with the `@system` macro. `@system` macro accepts lines of variable declaration specified by its own syntax. They are loosely based on Julia syntax sharing common expressions and operators, but have distinct semantics as explained below. `name[(args..; kwargs..)][: alias] [=> body] ~ [state][::type][(tags..)]` - `name`: variable name (usually short abbreviation) - `args`: automatically bound depending variables - `kwargs`: custom bound depending variables (only for *call* now) - `alias`: alternative name (long description) - `body`: code snippet (state/type specific, `begin .. end` block for multiple lines) - `state`: verb indicating kind of state (empty if not `State`-based) - `type`: internal type (*i.e.* `Float64` by default for most `State` variable) - `tags`: variable specific options (*i.e.* unit, min/max, etc.) **Example** Here is an example of a system declaration where all three variables are valid declarations: ```@example Cropbox @system S begin a: variable_a ~ advance b(a) => a^2 ~ track c => true ~ ::Bool end ``` ## Variable States Within Cropbox, a variable inside a system can be one of many different abstract types based on the variable's purpose. Depending on its type, each variable has its own behavior when a system is instantiated. In Cropbox, we refer to these as the *state* of the variables, originating from the term *state variables* often used in mathematical modeling. !!! note "Note" Specifying a *state* is not mandatory when declaring a variable. Cropbox also allows plain variables, which are commonly used for creating variable references to other systems. Currently, there are 19 different variable states implemented in Cropbox. *Instant derivation* - [`preserve`](@ref preserve): keeps an initially assigned value with no further updates; constants, parameters - [`track`](@ref track) : evaluates expression and assigns a new value for each time step - [`flag`](@ref flag) : checks a conditional logic; similar to track with boolean type, but composition is allowed - [`remember`](@ref remember) : keeps tracking the variable until a certain condition is met; like track switching to preserve *Cumulative update* - [`accumulate`](@ref accumulate): emulates integration of a rate variable over time; essentially Euler method - [`capture`](@ref capture): calculates the difference between time steps - [`integrate`](@ref integrate): calculates an integral over a non-time variable using Gaussian method - [`advance`](@ref advance): updates an internal time-keeping variable *Data source* - [`provide`](@ref provide): provides a table-like multi-column time-series data; i.e. weather data - [`drive`](@ref drive): fetches the current value from a time-series; often used with provide; i.e. air temperature - [`tabulate`](@ref tabulate): makes a two dimensional table with named keys; i.e. partitioning table - [`interpolate`](@ref interpolate): makes a curve function interpolated with discrete values; i.e. soil characteristic curve *Equation solving* - [`solve`](@ref solve): solves a polynomial equation symbolically; *i.e.* quadratic equation for coupling photosynthesis - [`bisect`](@ref bisect): solves a nonlinear equation using bisection method; *i.e.* energy balance equation *Dynamic structure* - [`produce`](@ref produce): attaches a new instance of dynamically generated system; *i.e.* root structure growth *Language extension* - [`hold`](@ref hold): marks a placeholder for the variable shared between mixins - [`wrap`](@ref wrap): allows passing a reference to the state variable object, not a dereferenced value - [`call`](@ref call): defines a partial function accepting user-defined arguments, while bound to other variables - [`bring`](@ref bring): duplicates variables declaration from another system into the current system ### *Instant derivation* #### [`preserve`](@id preserve) `preserve` variables are fixed values with no further modification after instantiation of a system. As a result, they are often used as the `state` for `parameter` variables, which allow any initial value to be set via a configuration object supplied at the start of a simulation. Non-parameter constants are also used for fixed variables that do not need to be computed at each time step. Supported tags: [`unit`](@ref unit), [`optional`](@ref optional), [`parameter`](@ref parameter), [`override`](@ref override), [`extern`](@ref extern), [`ref`](@ref ref), [`min`](@ref min), [`max`](@ref max), [`round`](@ref round) **Example** ```@example Cropbox @system S(Controller) begin a => 1 ~ preserve end simulate(S; stop=2) ``` \ #### [`track`](@id track) `track` variables are evaluated and assigned a new value at every time step. In a conventional model, these are the variables that would be computed in every update loop. At every time step, the formula in the variable code is evaluated and saved for use. This assignment of value occurs only *once* per time step, as intended by the Cropbox framework. No manual assignment of computation at an arbitrary time is allowed. This is to ensure that that there are no logical errors resulting from premature or incorrectly ordered variable assignments. For example, a cyclical reference between two `track` variables is caught by Cropbox as an error. Supported tags: [`unit`](@ref unit), [`override`](@ref override), [`extern`](@ref extern), [`ref`](@ref ref), [`skip`](@ref skip), [`init`](@ref init), [`min`](@ref min), [`max`](@ref max), [`round`](@ref round), [`when`](@ref when) **Example** ```@example Cropbox @system S(Controller) begin a ~ advance b(a) => 2*a ~ track end simulate(S; stop=2) ``` \ #### [`flag`](@id flag) `flag` variables are expressed in a conditional statement or logical operator for which a boolean value is evaluated at every time step. They function like a `track` variable but with a boolean value. Supported tags: [`parameter`](@ref parameter), [`override`](@ref override), [`extern`](@ref extern), [`once`](@ref once), [`when`](@ref when) **Example** ```@example Cropbox @system S(Controller) begin a ~ advance b => 1 ~ preserve f(a, b) => (a > b) ~ flag end simulate(S; stop=2) ``` \ #### [`remember`](@id remember) `remember` variables keep track of a variable until a specified condition is met. When the condition is met, it is saved as either its latest update or a specified value. They are like track variables that turn into preserve variables. The `when` tag is required to specify condition. Unless specified, the initial value for `remember` defaults to `0`. Supported tags: [`unit`](@ref unit), [`init`](@ref init), [`when`](@ref when) **Example** ```@example Cropbox @system S(Controller) begin t(context.clock.tick) ~ track f(t) => t > 1 ~ flag r1(t) ~ remember(when=f) r2(t) => t^2 ~ remember(when=f) end simulate(S; stop=2) ``` \ ### *Cumulative update* #### [`accumulate`](@id accumulate) `accumulate` variables emulate the integration of a rate variable over time. It uses the Euler's method of integration. By default, an `accumulate` variable accumulates every hour, unless a unit of time is specified. Supported tags: [`unit`](@ref unit), [`init`](@ref init), [`time`](@ref time), [`timeunit`](@ref timeunit), [`reset`](@ref reset), [`min`](@ref min), [`max`](@ref max), [`when`](@ref when) **Example** ```@example Cropbox @system S(Controller) begin a => 1 ~ accumulate b => 1 ~ accumulate(u"d") end simulate(S; stop=2) ``` \ #### [`capture`](@id capture) `capture` variables calculate the difference of a variable between time steps. The `time` tag allows evaluations for varying rates of time. Supported tags: [`unit`](@ref unit), [`time`](@ref time), [`timeunit`](@ref timeunit), [`when`](@ref when) **Example** ```@example Cropbox @system S(Controller) begin a => 1 ~ track b(a) => a + 1 ~ capture c(a) => a + 1 ~ accumulate end simulate(S; stop=2) ``` \ #### [`integrate`](@id integrate) `integrate` variables calculate an integral over a non-time variable using the Gaussian method. Supported tags: [`unit`](@ref unit), [`from`](@ref from), [`to`](@ref to) **Example** ```@example Cropbox @system S(Controller) begin w => 1 ~ preserve(parameter) a => 0 ~ preserve(parameter) b => π ~ preserve(parameter) f(w; x) => w*sin(x) ~ integrate(from=a, to=b) end instance(S) ``` \ #### [`advance`](@id advance) `advance` variables update an internal time-keeping variable. By default, it starts at 0 and increases by 1 every time step. Note that the unit does not have to be time-related. Supported tags: [`init`](@ref init), [`step`](@ref step), [`unit`](@ref unit) **Example** ```@example Cropbox @system S(Controller) begin a ~ advance(init=1) b ~ advance(step=2) c ~ advance(u"m") end simulate(S; stop=2) ``` \ ### *Data source* #### [`provide`](@id provide) `provide` variables provide a DataFrame with a given index (`index`) starting from an initial value (`init`). By default, `autounit` is `true`, meaning that `provide` variables will attempt to get units from column names. Supported tags: [`index`](@ref index), [`init`](@ref init), [`step`](@ref step), [`autounit`](@ref autounit), [`parameter`](@ref parameter) **Example** ```@example Cropbox @system S(Controller) begin a => DataFrame("index (hr)" => 0:2, "value (m)" => 0:10:20) ~ provide end instance(S).a ``` \ #### [`drive`](@id drive) `drive` variables fetch the current value from a time-series. It is often used in conjunction with `provide`. Supported tags: [`tick`](@ref tick), [`unit`](@ref unit), [`from`](@ref from), [`by`](@ref by), [`parameter`](@ref parameter), [`override`](@ref override) **Example** ```@example Cropbox @system S(Controller) begin a => [2, 4, 6] ~ drive end simulate(S; stop=2) ``` \ #### [`tabulate`](@id tabulate) `tabulate` variables make a two dimensional table with named keys. The `rows` tag must be assigned. Supported tags: [`unit`](@ref unit), [`rows`](@ref rows), [`columns`](@ref columns), [`parameter`](@ref parameter) **Example** ```@example Cropbox @system S(Controller) begin T => [ # a b 0 4 ; # A 1 5 ; # B 2 6 ; # C 3 7 ; # D ] ~ tabulate(rows=(:A, :B, :C, :D), columns=(:a, :b)) end instance(S) ``` \ #### [`interpolate`](@id interpolate) `interpolate` variables make a curve function for a provided set of discrete values. Supported tags: [`unit`](@ref unit), [`knotunit`](@ref knotunit), [`reverse`](@ref reverse), [`parameter`](@ref parameter) **Example** ```@example Cropbox @system S(Controller) begin m => [1 => 10, 2 => 20, 3 => 30] ~ interpolate a(m) => m(2.5) ~ track end instance(S) ``` A matrix can also be used instead of a vector of pairs. ```@example Cropbox @system S(Controller) begin m => [1 10; 2 20; 3 30] ~ interpolate a(m) => m(2.5) ~ track end instance(S) ``` \ ### *Equation solving* #### [`solve`](@id solve) `solve` variables solve a polynomial equation symbolically. By default, it will return the highest solution. Therefore, when using the `lower` tag, it is recommended to pair it with another tag. Supported tags: [`unit`](@ref unit), [`lower`](@ref lower), [`upper`](@ref upper), [`pick`](@ref pick) **Example** *The solution is x = 1, 2, 3* ```@example Cropbox @system S(Controller) begin a => 1 ~ preserve(parameter) b => -6 ~ preserve(parameter) c => 11 ~ preserve(parameter) d => -6 ~ preserve(parameter) x(a, b, c, d) => begin a*x^3 + b*x^2 + c*x + d end ~ solve end instance(S) ``` \ #### [`bisect`](@id bisect) `bisect` variables solve a nonlinear equation using the bisection method. The tags `lower` and `upper` must be provided. Supported tags: [`unit`](@ref unit), [`evalunit`](@ref evalunit), [`lower`](@ref lower), [`upper`](@ref upper), [`maxiter`](@ref maxiter), [`tol`](@ref tol), [`min`](@ref min), [`max`](@ref max) **Example** The solution is x = 1, 2, 3 ```@example Cropbox @system S(Controller) begin x(x) => x^3 - 6x^2 + 11x - 6 ~ bisect(lower=0, upper=3) end instance(S) ``` \ ### *Dynamic structure* #### [`produce`](@id produce) `produce` variables attach a new instance of a dynamically generated system. Supported tags: [`single`](@ref single), [`when`](@ref when) **Example** ```@example Cropbox @system S begin a => produce(S) ~ produce end @system SController(Controller) begin s(context) ~ ::S end instance(SController) ``` \ ### *Language extension* #### `hold` `hold` variables are placeholders for variables that are supplied by another system as a mixin. Supported tags: None **Example** ```@example Cropbox @system S1 begin a ~ advance end @system S2(S1, Controller) begin a ~ hold b(a) => 2*a ~ track end simulate(S2; stop=2) ``` \ #### `wrap` `wrap` allows passing a reference to the state variable object, not a dereferenced value Supported tags: None **Example** ```@example Cropbox @system S(Controller) begin a => 1 ~ preserve b(a) => a == a' ~ flag c(wrap(a)) => a == a' ~ flag end instance(S) ``` \ #### [`call`](@id call) `call` defines a partial function accepting user-defined arguments Supported tags: [`unit`](@ref unit) **Example** ```@example Cropbox @system S(Controller) begin a => 1 ~ preserve f(a; x) => a + x ~ call b(f) => f(1) ~ track end instance(S) ``` \ #### [`bring`](@id bring) `bring` duplicates variable declaration from another system into the current system Supported tags: [`parameters`](@ref parameters), [`override`](@ref override) **Example** ```@example Cropbox @system S1 begin a => 1 ~ preserve b(a) => 2a ~ track end @system S2(Controller) begin c(context) ~ bring::S1 end instance(S2) ``` \ ## Variable Tags Most variable states have tags in the form of `(tag)` for tag-specific behaviors. Available tags vary between variable states. Some tags are shared by multiple variable states while some tags are exclusive to certain variable states. ### [`autounit`](@id autounit) Allows `provide` variables to automatically assign units to variables depending on column headers of the DataFrame. By default, `autounit` is `true` and only needs to be specified when `false`. Used by: [`provide`](@ref provide) **Example** ```@example Cropbox @system S(Controller) begin a => DataFrame("index" => (0:2)u"hr", "value (m)" => 0:10:20) ~ provide b => DataFrame("index" => (0:2)u"hr", "value (m)" => 0:10:20) ~ provide(autounit=false) end ``` ```@example Cropbox instance(S).a ``` ```@example Cropbox instance(S).b ``` \ ### [`by`](@id by) Specifies the column and series from which the `drive` variable receives data. Can be omitted if the variable name is identical to column name. Used by: [`drive`](@ref drive) **Example** ```@example Cropbox @system S(Controller) begin p => DataFrame(index=(0:2)u"hr", a=[2,4,6], x=1:3) ~ provide a ~ drive(from=p) b ~ drive(from=p, by=:x) end simulate(S; stop=2) ``` \ ### [`columns`](@id columns) Specifies the names of columns from the table created by the `tabulate` variable. Used by: [`tabulate`](@ref tabulate) **Example** ```@example Cropbox @system S(Controller) begin T => [ # a b 0 4 ; # A 1 5 ; # B 2 6 ; # C 3 7 ; # D ] ~ tabulate(rows=(:A, :B, :C, :D), columns=(:a, :b)) end instance(S).T ``` \ ### [`evalunit`](@id evalunit) Specifies the evaluation unit of `bisect`, as opposed to the unit of solution. Used by: [`bisect`](@ref bisect) **Example** ```@example Cropbox @system S(Controller) begin f(x) => (x/1u"s" - 1u"m/s") ~ track(u"m/s") x(f) ~ bisect(lower=0, upper=2, u"m", evalunit=u"m/s") end instance(S) ``` \ ### [`extern`](@id extern) Used by: [`preserve`](@ref preserve), [`track`](@ref track), [`flag`](@ref flag) ### [`from`](@id from) `drive`: Specifies the DataFrame that the `drive` variable will receive data from. If the variable name of the `drive` variable differs from column name, `from` must be accompanied with `by`. `integrate`: Specifies lower bound of integration. Used by: [`drive`](@ref drive), [`integrate`](@ref integrate) **Example**: `drive` ```@example Cropbox @system S(Controller) begin p => DataFrame(index=(0:2)u"hr", a=[2,4,6], x=1:3) ~ provide a ~ drive(from=p) b ~ drive(from=p, by=:x) end simulate(S; stop=2) ``` \ **Example**: `integrate` ```@example Cropbox @system S(Controller) begin w => 1 ~ preserve(parameter) a => 0 ~ preserve(parameter) b => π ~ preserve(parameter) f(w; x) => w*sin(x) ~ integrate(from=a, to=b) end instance(S) ``` \ ### [`index`](@id index) Used by `provide` variables to specify the index column from provided DataFrame. Can be omitted if DataFrame contains column "index". Used by: [`provide`](@ref provide) **Example** ```@example Cropbox @system S(Controller) begin a => DataFrame(i=(0:3)u"hr", value=0:10:30) ~ provide(index=:i) end instance(S) ``` \ ### [`init`](@id init) Assigns the first value of the variable at system instantiation. Used by: [`track`](@ref track), [`remember`](@ref remember), [`accumulate`](@ref accumulate), [`advance`](@ref advance), [`provide`](@ref provide) **Example** ```@example Cropbox @system S(Controller) begin a => 1 ~ accumulate(init=100) end simulate(S; stop=2) ``` \ ### [`knotunit`](@id knotunit) Specifies the unit of discrete x-values of `interpolate`. Used by: [`interpolate`](@ref interpolate) **Example** ```@example Cropbox @system S(Controller) begin m => ([1 => 10, 2 => 20, 3 => 30]) ~ interpolate(u"s", knotunit=u"m") n(m) ~ interpolate(u"m", reverse) a(m) => m(2.5u"m") ~ track(u"s") b(n) => n(25u"s") ~ track(u"m") end instance(S) ``` \ ### [`lower`](@id lower) Specifies the lower bound of the solution for `solve` and `bisect` variables. Used by: [`solve`](@ref solve), [`bisect`](@ref bisect) **Example** *The solution is x = 1, 2, 3* ```@example Cropbox @system S(Controller) begin a => 1 ~ preserve(parameter) b => -6 ~ preserve(parameter) c => 11 ~ preserve(parameter) d => -6 ~ preserve(parameter) x(a, b, c, d) => begin a*x^3 + b*x^2 + c*x + d end ~ solve(lower=1.1, upper=2.9) end instance(S) ``` \ ### [`max`](@id max) Defines the maximum value of the variable. Used by: [`preserve`](@ref preserve), [`track`](@ref track), [`accumulate`](@ref accumulate), [`bisect`](@ref bisect) **Example** ```@example Cropbox @system S(Controller) begin a => 1 ~ accumulate(max=1) end simulate(S; stop=2) ``` \ ### [`maxiter`](@id maxiter) Defines the maximum number of iterations for the `bisect`. Used by: [`bisect`](@ref bisect) **Example** ```@example Cropbox @system S(Controller) begin x(x) => x - 0.25 ~ bisect(lower=0, upper=1, maxiter=4) end instance(S) ``` \ ### [`min`](@id min) Defines the minimum value of the variable. Used by: [`preserve`](@ref preserve), [`track`](@ref track), [`accumulate`](@ref accumulate), [`bisect`](@ref bisect) **Example** ```@example Cropbox @system S(Controller) begin a => -1 ~ accumulate(min=-1) end simulate(S; stop=2) ``` \ ### [`once`](@id once) Makes a `flag` variable unable to go from `true` to `false`. Used by: [`flag`](@ref flag) **Example** ```@example Cropbox @system S(Controller)begin a ~ advance(init=1) f(a) => (a % 2 == 0) ~ flag(once) end simulate(S; stop=2) ``` \ ### [`optional`](@id optional) Makes a `preserve` variable optional, allowing a system to be instantiated without variable assignment. Used by: [`preserve`](@ref preserve) **Example** ```@example Cropbox @system S(Controller) begin a ~ preserve(optional, parameter) b => 1 ~ preserve end simulate(S; stop=2) ``` \ ### [`override`](@id override) Used by: [`preserve`](@ref preserve), [`track`](@ref track), [`flag`](@ref flag), [`drive`](@ref drive), [`bring`](@ref bring) **Example** ```@example Cropbox @system S1 begin a ~ track(override) end @system S2(Controller) begin c(context, a) ~ ::S1 a => 1 ~ track end instance(S2) ``` \ ### [`parameter`](@id parameter) Allows the variable to be altered through a configuration at system instantiation. Used by: [`preserve`](@ref preserve), [`flag`](@ref flag), [`provide`](@ref provide), [`drive`](@ref drive), [`tabulate`](@ref tabulate), [`interpolate`](@ref interpolate) **Example** ```@example Cropbox @system S(Controller) begin a ~ preserve(parameter) end instance(S; config = :S => :a => 1) ``` \ ### [`parameters`](@id parameters) Use by `bring` variables to duplicate only variables that *can* have the `parameter` tag (if they did not have the `parameter` tag originally, they become parameters regardless). The duplicated variables must have their values reassigned through a configuration. Used by: [`bring`](@ref bring) **Example** ```@example Cropbox @system S1 begin a => 1 ~ preserve b(a) => 2a ~ track c => true ~ flag d(a) ~ accumulate end @system S2(Controller) begin p(context) ~ bring::S1(parameters) end instance(S2; config = :S2 => (:a => 2, :b => 3, :c => false)) ``` \ ### [`pick`](@id pick) Picks which solution to return based on tag argument. Used by: [`solve`](@ref solve) **Example** *The solution is x = 1, 2, 3* ```@example Cropbox @system S(Controller) begin a => 1 ~ preserve(parameter) b => -3 ~ preserve(parameter) c => 2 ~ preserve(parameter) x(a, b, c) => begin a*x^2 + b*x + c end ~ solve(pick=:minimum) end instance(S) ``` \ ### [`ref`](@id ref) Used by: [`preserve`](@ref preserve), [`track`](@ref track) ### [`reset`](@id reset) Resets the sum to 0 at every time step. Used by: [`accumulate`](@ref accumulate) **Example** ```@example Cropbox @system S(Controller) begin a => 1 ~ accumulate(reset) end simulate(S; stop=2) ``` \ ### [`reverse`](@id reverse) Returns the inverse function of an existing `interpolate` variable. Used by: [`interpolate`](@ref interpolate) **Example** ```@example Cropbox @system S(Controller) begin m => ([1 => 10, 2 => 20, 3 => 30]) ~ interpolate n(m) ~ interpolate(reverse) a(m) => m(2.5) ~ preserve b(n) => n(25) ~ preserve end instance(S) ``` \ ### [`round`](@id round) Rounds to the nearest integer or to a floor or ceiling based on tag argument. Used by: [`preserve`](@ref preserve), [`track`](@ref track) **Example** ```@example Cropbox @system S(Controller) begin a => 1.4 ~ preserve(round) b => 1.4 ~ preserve(round=:round) c => 1.4 ~ preserve(round=:ceil) d => 1.6 ~ preserve(round=:floor) e => 1.6 ~ preserve(round=:trunc) end instance(S) ``` \ ### [`rows`](@id rows) Specifies the names of rows from the table created by the `tabulate` variable. Required tag for `tabulate`. Used by: [`tabulate`](@ref tabulate) **Example** ```@example Cropbox @system S(Controller) begin T => [ # a b 0 4 ; # A 1 5 ; # B 2 6 ; # C 3 7 ; # D ] ~ tabulate(rows=(:A, :B, :C, :D), columns=(:a, :b)) end ``` \ ### [`single`](@id single) Used by: [`produce`](@ref produce) ### [`skip`](@id skip) Used by: [`track`](@ref track) **Example** ```@example Cropbox @system S(Controller) begin a ~ advance b(a) => 2*a ~ track(skip=true) end simulate(S; stop=2) ``` \ ### [`step`](@id step) `advance`: Specifies the increments of the `advance` variable. `provide`: Specifies the intervals of the index column. Used by: [`advance`](@ref advance), [`provide`](@ref provide) **Example:** `advance` ```@example Cropbox @system S(Controller) begin a ~ advance b ~ advance(step=2) c ~ advance(step=-1) end simulate(S; stop=2) ``` \ **Example:** `integrate` ```@example Cropbox @system S(Controller) begin a => DataFrame("index (hr)" => 0:4, "value (m)" => 0:10:40) ~ provide(step=2u"hr") end instance(S).a ``` \ ### [`tick`](@id tick) Used by: [`drive`](@ref drive) ### [`time`](@id time) Accumulates variable at a specified rate of time. Used by: [`accumulate`](@ref accumulate), [`capture`](@ref capture) **Example** ```@example Cropbox @system S(Controller) begin t(x=context.clock.time) => 0.5x ~ track(u"hr") a => 1 ~ accumulate b => 1 ~ accumulate(time=t) end simulate(S; stop=5) ``` \ ### [`timeunit`](@id timeunit) Specifies the time unit of the variable. Used by: [`accumulate`](@ref accumulate), [`capture`](@ref capture) **Example** ```@example Cropbox @system S(Controller) begin a => 1 ~ accumulate(timeunit=u"d") end simulate(S; stop=2) ``` \ ### [`to`](@id to) Specifies upper bound of integration. Used by: [`integrate`](@ref integrate) **Example** ```@example Cropbox @system S(Controller) begin w => 1 ~ preserve(parameter) a => 0 ~ preserve(parameter) b => π ~ preserve(parameter) f(w; x) => w*sin(x) ~ integrate(from=a, to=b) end instance(S) ``` \ ### [`tol`](@id tol) Defines the tolerance for the bisection method used in `bisect`. Used by: [`bisect`](@ref bisect) **Example** ```@example Cropbox @system S(Controller) begin x(x) => x - 2.7 ~ bisect(lower=1, upper=3) y(y) => y - 2.7 ~ bisect(lower=1, upper=3, tol=0.05) end instance(S) ``` \ ### [`unit`](@id unit) Specifies the unit of the variable. The tag `unit` can be omitted. Used by: [`preserve`](@ref preserve), [`track`](@ref track), [`remember`](@ref remember), [`accumulate`](@ref accumulate), [`capture`](@ref capture), [`integrate`](@ref integrate), [`advance`](@ref advance), [`drive`](@ref drive), [`tabulate`](@ref tabulate), [`interpolate`](@ref interpolate), [`solve`](@ref solve), [`bisect`](@ref bisect), [`call`](@ref call) ```example Cropbox @system S(Controller) begin a => 1 ~ preserve(unit=u"hr") b => 1 ~ preserve(u"hr") end instance(S) ``` \ ### [`upper`](@id upper) Specifies the upper bound of solution. Used by: [`solve`](@ref solve), [`bisect`](@ref bisect) **Example** *The solution is x = 1, 2, 3* ```@example Cropbox @system S(Controller) begin a => 1 ~ preserve(parameter) b => -6 ~ preserve(parameter) c => 11 ~ preserve(parameter) d => -6 ~ preserve(parameter) x(a, b, c, d) => begin a*x^3 + b*x^2 + c*x + d end ~ solve(upper=2.9) end instance(S) ``` \ ### [`when`](@id when) Specifies when a variable should be evaluated. It is supplied with a `flag` variable, and the specified variable is evaluated when the `flag` variable is `true`. Used by: [`track`](@ref track), [`flag`](@ref flag), [`remember`](@ref remember), [`accumulate`](@ref accumulate), [`capture`](@ref capture), [`produce`](@ref produce) **Example** ```@example Cropbox @system S(Controller) begin a ~ advance flag(a) => (a >= 2) ~ flag b(a) => a ~ track(when=flag) end simulate(S; stop=3u"hr") ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
2577
```@setup Cropbox using Cropbox ``` # Visualization There are three main functions in Cropbox used for visualization. For information regarding syntax, please check the [reference](@ref Visualization1). * [`plot()`](@ref plot) * [`visualize()`](@ref visualize) * [`manipulate()`](@ref manipulate) ## [`plot()`](@id plot) The `plot()` function is used to plot two-dimensional graphs. **Two Vectors** Let's start by making a simple plot by using two vectors of discrete values. ```@example Cropbox x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plot(x, y) ``` \ **Multiple Vectors** You can also plot multiple series, by using a vector of vectors. ```@example Cropbox plot(x, [x, y]) ``` \ **DataFrame** We can also make a plot using a DataFrame and its columns. Recall that the `simulate()` function provides a DataFrame. ```@example Cropbox @system S(Controller) begin x ~ advance y1(x) => 2x ~ track y2(x) => x^2 ~ track end df = simulate(S; stop=10) p = plot(df, :x, [:y1, :y2]) ``` ### `plot!()` `plot!()` is an extension of the `plot()` function used to update an existing `Plot` object `p` by appending a new graph made with `plot()` **Example** ```@example Cropbox @system S(Controller) begin x ~ advance y3(x) => 3x ~ track end df = simulate(S; stop=10) plot!(p, df, :x, :y3) ``` ## [`visualize()`](@id visualize) The `visualize()` function is used to make a plot from an output collected by running simulations. It is essentially identical to running the `plot()` function with a DataFrame from the `simulate()` function, and can be seen as a convenient function to run both `plot()` and `simulate()` together. **Example** ```@example Cropbox @system S(Controller) begin x ~ advance y1(x) => 2x ~ track y2(x) => x^2 ~ track end v = visualize(S, :x, [:y1, :y2]; stop=10, kind=:line) ``` ### `visualize!()` `visualize!()` updates an existing `Plot` object `p` by appending a new graph generated with `visualize()`. **Example** ```@example Cropbox @system S(Controller) begin x ~ advance y3(x) => 3x ~ track end visualize!(v, S, :x, :y3; stop=10, kind=:line) ``` ## [`manipulate()`](@id manipulate) The `manipulate` function has two different [methods](https://docs.julialang.org/en/v1/manual/methods/) for creating an interactive plot. ``` manipulate(f::Function; parameters, config=()) ``` Create an interactive plot updated by callback f. Only works in Jupyter Notebook. ``` manipulate(args...; parameters, kwargs...) ``` Create an interactive plot by calling manipulate with visualize as a callback.
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
44
# Declaration ```@docs @system @config ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
57
# [Inspection](@id Inspection1) ```@docs @look dive ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
83
# [Simulation](@id Simulation1) ```@docs instance simulate evaluate calibrate ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
95
# [Visualization](@id Visualization1) ```@docs plot plot! visualize visualize! manipulate ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
4974
```@setup Cropbox using Cropbox ``` # [Getting Started with Cropbox](@id cropbox) This tutorial will cover basic macros and functions of Cropbox. ## Installing Cropbox [Cropbox.jl](https://github.com/cropbox/Cropbox.jl) is available through Julia package manager. You can install Cropbox running the following command in the Julia REPL. ```julia using Pkg Pkg.add("Cropbox") ``` If you are using a prebuilt docker image with Cropbox included, you can skip this step. ## Package Loading When using Cropbox, make sure to load the package into the environment by using the following command: ```@example Cropbox using Cropbox ``` ## Creating a System In Cropbox, a model is defined by a single system or a collection of systems. A system can be made by using a simple Cropbox macro, `@system`. ```@example Cropbox @system S ``` We have just created a system called `S`. In its current state, `S` is an empty system with no variables. Our next step is to define the variables that will represent our system. ### Defining Variables Suppose we want the system to represent exponential growth described by this differential equation $\frac{dx}{dt} = ax$ In Cropbox, we could define the system with the following: ```@example Cropbox @system S(Controller) begin i => 1 ~ preserve a => 0.1 ~ preserve(parameter) r(a, x) => a*x ~ track x(r) ~ accumulate(init = i) end ``` Here we declared four variables. - i: variable containing initial value of x which never changes (preserved) - a: variable containing constant parameter of exponential growth - r: rate variable which needs to be calculated or tracked every time step - x: state variable which accumulates by rate r over time with initial value i Each variable has been declared with a state, such as preserve or track, that describes its behavior when the system is instantiated. In Cropbox, there are 19 different variable states, which are described in more detail in the [Variable section of the Manual](@ref variable). ## Configuring Parameters In modeling, we often need to change the value of a parameter for different systems or species. We can change the value of variables declared with the paramater tag before running the model by creating a config with the new value. For example, we could change the value of parameter a in system S to be .05 and then create an instance of S with this new value. ```@example Cropbox config = @config(:S => :a => .05) instance(S; config) ``` Multiple parameters can be specified using tuples or named tuples. #### Tuple of Pairs ```@example Cropbox @config :S => (:a => 1, :b => 2) ``` #### Named Tuples ```@example Cropbox @config :S => (a = 1, b = 2) ``` ## Simulation The simulate function will create an instance of the system and update the values of all the variables in it at each time step until it reaches the stop time. By default, simulations in Cropbox use a time step of one hour. Let's use Cropbox to simulate the system for ten time steps. ```@example Cropbox df = simulate(S, config = config, stop = 10) ``` This will output the values of all the variables in the system as a DataFrame where each row represents one time step. ## Visualization Once we have simulated the system, we may want to visualize the resulting data by creating a graph. This can be done by using the plot() function, specifying the name of the dataframe as the first argument and then the names of variables we want to plot on the x and y axes. ```@example Cropbox p = plot(df, :time, :x) ``` The visualize() function can also be used to run a simulation and plot the results using one command. ```@example Cropbox v = visualize(S, :time, :x ; stop=50, kind=:line) ``` ## Evaluation The evaluate() function can be used to compare two datasets with a choice of evaluation metric, such as root-mean-square error. For instance, we could compare a dataset of the observed values from an experiment to the estimated values from a simulation. To do this, we would enter in the observed dataset as a DataFrame. ```@example Cropbox using DataFrames obs = DataFrame(time = [0.0 ,1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]u"hr", x = [1, .985, 1.06, 1.15, 1.14, 1.17, 1.24, 1.34, 1.76, 1.53, 1.68]) est = simulate(S, config = config, stop = 10) ``` We compare this dataset to the results of the simulation visually by adding it to the our previous plot `p` using the plot!() function. ```@example Cropbox plot!(p,obs, :time, :x) ``` Then, we can use the evaluate() function to calculate the error between the observed and simulated values. The index will be time by default and the target will be the variables we want to compare. ```@example Cropbox evaluate(obs, df; index = :time, target = :x, metric = :rmse) ``` In addition to being able to compare two DataFrames, the evaluate() function can also be used to compare a system to a DataFrame. ```@example Cropbox evaluate(S, est; target = :a, stop = 10) ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
2403
```@setup Cropbox using Cropbox ``` # [Getting Started with Julia](@id Julia) Julia is a relatively new programming language designed for scientific computing in mind. It is a dynamic programming language as convenient as Python and R, but also provides high performance and extensibility as C/C++ and Fortran. Check the chart [here](https://www.tiobe.com/tiobe-index/) to see where Julia stands as a programming language among other languages today; its position has been rising fast. If you already have a fair understanding of Julia or would like to skip ahead to learning about Cropbox, please go to [Getting Started With Cropbox](@ref cropbox). ## Installing Julia You can download and install Julia from the [official Julia downloads page](https://julialang.org/downloads/). For new users, it is recommended to install the "Current stable release" for Julia. In general, you will want to install the 64-bit version. If you run into an issue installing the 64-bit version, you can try the 32-bit version. During installation, select "Add Julia to PATH". You can also add Julia to PATH after installation using the command-line interface (CLI). For more detailed platform-specific instructions, you can check the [official Julia instructions](https://julialang.org/downloads/platform/). If you are new to coding and require a development environment, check the [Installation section](@ref Installation) for more information. ## The Julia REPL The quickest way to start using Julia is by opening the Julia executable or by running the command [julia] in your terminal or command prompt. In order to run [julia] from your terminal or command prompt, make sure that Julia is added to your PATH. By doing so, you can start an interactive session of Julia, also known as the REPL, which stands for "Read-Eval-Print Loop". Using the REPL, you can start running simple commands like the following: ```@repl a = 1 b = 2 c = a + b ``` ## Variables Variables in Julia refer to names that are associated with a value. The names can be associated with various different [types](https://docs.julialang.org/en/v1/manual/types/) of values. Take a look at the following example: ```@repl Cropbox a = 1 b = "string" c = [a, b] d = @system D ``` !!! warning "Warning" Julia variables are not to be confused with Cropbox [variables](@ref variable) defined within Cropbox [systems](@ref system).
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
35207
```@setup Cropbox using Cropbox using CSV using DataFrames using DataFramesMeta using Dates using TimeZones weather = DataFrame( "year" => Int.(2002*ones(139)), "doy" => [135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273], "rad (W/m^2)" => [295.8, 297.9, 224.2, 95.8, 314.9, 284.6, 275.0, 320.0, 318.5, 295.7, 226.1, 183.2, 203.4, 205.6, 209.8, 255.4, 274.0, 299.5, 294.5, 303.9, 268.1, 212.9, 192.4, 206.1, 242.1, 291.3, 282.2, 259.6, 236.1, 54.0, 50.0, 245.2, 237.5, 290.9, 257.1, 219.8, 248.3, 312.8, 297.8, 286.9, 282.4, 263.0, 222.4, 223.6, 183.7, 258.6, 261.1, 243.2, 257.3, 276.8, 275.9, 302.5, 299.9, 191.3, 240.2, 251.0, 146.8, 291.9, 311.6, 139.9, 86.3, 279.1, 294.8, 291.2, 172.0, 217.3, 225.9, 164.7, 232.5, 267.3, 124.2, 146.6, 77.5, 118.6, 243.5, 257.6, 256.6, 283.4, 284.3, 264.3, 187.6, 254.8, 210.9, 295.0, 256.9, 272.7, 275.0, 276.1, 259.7, 244.9, 248.2, 257.6, 226.2, 164.3, 195.4, 227.5, 241.6, 217.5, 209.3, 217.4, 168.0, 128.6, 229.4, 92.5, 129.3, 19.9, 65.7, 112.1, 126.7, 44.1, 146.1, 223.1, 226.6, 248.8, 244.8, 245.3, 204.7, 246.9, 232.0, 238.9, 240.7, 233.6, 106.7, 64.1, 147.8, 203.2, 192.0, 147.7, 157.4, 181.6, 161.8, 174.0, 215.9, 134.0, 32.0, 54.0, 205.7, 194.9, 143.1], "Tavg (°C)" => [14.9, 18.0, 21.3, 12.5, 9.6, 10.1, 8.8, 11.6, 14.7, 20.1, 20.3, 20.2, 21.6, 21.4, 21.8, 21.7, 25.8, 25.9, 23.1, 20.2, 22.8, 25.8, 23.5, 18.4, 17.5, 20.9, 24.9, 26.9, 25.9, 20.7, 18.4, 19.9, 19.8, 20.4, 20.7, 20.8, 21.7, 21.7, 22.4, 23.8, 26.1, 27.8, 27.8, 26.8, 23.5, 24.1, 24.0, 25.8, 27.9, 29.2, 29.9, 28.2, 23.1, 20.8, 23.5, 28.1, 24.9, 20.9, 20.5, 22.0, 20.8, 24.2, 26.7, 25.8, 27.1, 27.0, 26.0, 25.5, 27.7, 28.4, 23.4, 22.9, 20.0, 23.5, 28.1, 29.0, 27.9, 28.0, 27.9, 28.8, 25.9, 27.1, 27.1, 23.6, 20.0, 20.3, 21.4, 22.5, 25.0, 26.8, 27.9, 28.6, 28.7, 28.0, 28.2, 29.3, 28.2, 27.5, 25.4, 26.7, 27.1, 26.0, 25.4, 22.2, 23.9, 19.2, 17.7, 18.4, 19.9, 17.5, 19.3, 22.4, 24.9, 22.2, 20.3, 19.6, 19.8, 21.0, 23.8, 22.5, 17.5, 18.4, 21.3, 23.2, 23.4, 20.9, 20.5, 21.2, 22.8, 24.2, 23.7, 19.3, 16.3, 17.8, 17.5, 21.1, 20.2, 16.4, 17.9], "Tmax (°C)" => [22.1, 27.7, 27.3, 17.7, 15.6, 15.6, 14.5, 20.1, 24.0, 29.5, 24.6, 27.8, 27.7, 28.0, 27.7, 29.0, 32.3, 31.9, 29.1, 26.1, 28.7, 32.8, 32.4, 22.4, 24.3, 30.1, 32.7, 34.3, 32.8, 26.0, 20.6, 25.4, 26.8, 27.4, 28.8, 27.0, 28.4, 29.3, 30.0, 31.7, 34.2, 35.3, 34.9, 33.4, 29.0, 30.9, 31.5, 33.2, 35.3, 36.0, 36.4, 32.0, 29.6, 27.5, 32.7, 35.0, 29.0, 26.1, 29.7, 27.8, 24.4, 31.5, 32.7, 34.0, 32.7, 32.1, 32.2, 31.3, 34.6, 35.1, 28.6, 27.0, 21.6, 28.9, 35.0, 35.0, 33.1, 34.2, 35.6, 37.3, 35.9, 34.6, 35.0, 27.1, 26.3, 28.2, 29.6, 31.9, 34.5, 35.7, 36.9, 36.2, 34.8, 33.0, 33.8, 35.2, 34.7, 32.8, 31.1, 34.0, 31.4, 30.9, 31.1, 28.3, 29.7, 22.5, 21.1, 21.7, 25.2, 19.0, 24.0, 30.7, 31.7, 28.2, 26.8, 28.0, 29.6, 32.4, 32.8, 26.2, 25.4, 28.2, 27.3, 25.3, 29.8, 28.4, 28.4, 27.4, 29.2, 30.4, 29.7, 24.1, 25.5, 24.3, 19.3, 28.2, 25.4, 24.3, 24.0], "Tmin (°C)" => [8.6, 4.9, 14.3, 8.0, 4.0, 4.3, 2.6, 1.4, 3.0, 7.1, 16.1, 15.5, 17.2, 15.9, 15.3, 13.8, 17.9, 17.9, 15.4, 11.4, 16.8, 19.0, 17.8, 12.6, 11.3, 11.2, 16.1, 18.8, 18.4, 17.7, 16.7, 14.5, 12.0, 12.1, 12.5, 15.4, 15.2, 14.1, 13.9, 14.7, 17.9, 19.6, 22.3, 22.0, 19.9, 17.6, 15.9, 18.0, 19.7, 22.4, 22.3, 22.1, 15.3, 13.2, 13.3, 19.8, 21.4, 13.5, 10.4, 15.6, 18.1, 16.6, 19.7, 16.8, 21.1, 21.8, 21.1, 19.9, 19.3, 22.2, 20.2, 20.8, 16.9, 19.9, 21.9, 22.1, 21.9, 22.2, 19.8, 19.9, 21.1, 19.5, 21.1, 17.4, 13.1, 12.2, 12.9, 12.6, 15.6, 17.9, 19.7, 22.2, 21.9, 24.0, 22.4, 23.4, 21.5, 22.3, 18.7, 18.9, 23.3, 22.4, 20.4, 17.4, 17.4, 15.6, 15.3, 14.6, 15.2, 15.6, 14.6, 14.0, 18.2, 16.6, 15.0, 12.2, 13.3, 11.4, 15.3, 16.6, 9.0, 8.4, 14.3, 21.9, 18.2, 15.2, 14.1, 15.8, 16.5, 17.1, 18.6, 10.1, 7.8, 10.5, 15.7, 15.2, 13.2, 10.4, 12.2], "rainfall (mm)" => [0, 0, 3, 11, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 0, 0, 0, 0, 0, 0, 9, 3, 4, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 28, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 12, 1, 0, 0, 0, 0, 0, 0, 10, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 42, 3, 0, 1, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 5, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 26, 6, 0, 0, 0], "date (:Date)" => Date("2002-05-15"):Day(1):Date("2002-09-30"), "GDD (K)" => [6.9, 10.0, 13.3, 4.5, 1.6, 2.1, 0.8, 3.6, 6.7, 12.1, 12.3, 12.2, 13.6, 13.4, 13.8, 13.7, 17.8, 17.9, 15.1, 12.2, 14.8, 17.8, 15.5, 10.4, 9.5, 12.9, 16.9, 18.9, 17.9, 12.7, 10.4, 11.9, 11.8, 12.4, 12.7, 12.8, 13.7, 13.7, 14.4, 15.8, 18.1, 19.8, 19.8, 18.8, 15.5, 16.1, 16.0, 17.8, 19.9, 21.2, 21.9, 20.2, 15.1, 12.8, 15.5, 20.1, 16.9, 12.9, 12.5, 14.0, 12.8, 16.2, 18.7, 17.8, 19.1, 19.0, 18.0, 17.5, 19.7, 20.4, 15.4, 14.9, 12.0, 15.5, 20.1, 21.0, 19.9, 20.0, 19.9, 20.8, 17.9, 19.1, 19.1, 15.6, 12.0, 12.3, 13.4, 14.5, 17.0, 18.8, 19.9, 20.6, 20.7, 20.0, 20.2, 21.3, 20.2, 19.5, 17.4, 18.7, 19.1, 18.0, 17.4, 14.2, 15.9, 11.2, 9.7, 10.4, 11.9, 9.5, 11.3, 14.4, 16.9, 14.2, 12.3, 11.6, 11.8, 13.0, 15.8, 14.5, 9.5, 10.4, 13.3, 15.2, 15.4, 12.9, 12.5, 13.2, 14.8, 16.2, 15.7, 11.3, 8.3, 9.8, 9.5, 13.1, 12.2, 8.4, 9.9], "cGDD (K)" => [6.9, 10.0, 13.3, 4.5, 1.6, 2.1, 0.8, 3.6, 6.7, 12.1, 12.3, 12.2, 13.6, 13.4, 13.8, 13.7, 17.8, 17.9, 15.1, 12.2, 14.8, 17.8, 15.5, 10.4, 9.5, 12.9, 16.9, 18.9, 17.9, 12.7, 10.4, 11.9, 11.8, 12.4, 12.7, 12.8, 13.7, 13.7, 14.4, 15.8, 18.1, 19.8, 19.8, 18.8, 15.5, 16.1, 16.0, 17.8, 19.9, 21.2, 21.9, 20.2, 15.1, 12.8, 15.5, 20.1, 16.9, 12.9, 12.5, 14.0, 12.8, 16.2, 18.7, 17.8, 19.1, 19.0, 18.0, 17.5, 19.7, 20.4, 15.4, 14.9, 12.0, 15.5, 20.1, 21.0, 19.9, 20.0, 19.9, 20.8, 17.9, 19.1, 19.1, 15.6, 12.0, 12.3, 13.4, 14.5, 17.0, 18.8, 19.9, 20.6, 20.7, 20.0, 20.2, 21.3, 20.2, 19.5, 17.4, 18.7, 19.1, 18.0, 17.4, 14.2, 15.9, 11.2, 9.7, 10.4, 11.9, 9.5, 11.3, 14.4, 16.9, 14.2, 12.3, 11.6, 11.8, 13.0, 15.8, 14.5, 9.5, 10.4, 13.3, 15.2, 15.4, 12.9, 12.5, 13.2, 14.8, 16.2, 15.7, 11.3, 8.3, 9.8, 9.5, 13.1, 12.2, 8.4, 9.9] ) pelts = DataFrame( "Year (yr)" => [1845, 1846, 1847, 1848, 1849, 1850, 1851, 1852, 1853, 1854, 1855, 1856, 1857, 1858, 1859, 1860, 1861, 1862, 1863, 1864, 1865, 1866, 1867, 1868, 1869, 1870, 1871, 1872, 1873, 1874, 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1889, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935], "Hare" => [19.58, 19.6, 19.61, 11.99, 28.04, 58.0, 74.6, 75.09, 88.48, 61.28, 74.67, 88.06, 68.51, 32.19, 12.64, 21.49, 30.35, 2.18, 152.65, 148.36, 85.81, 41.41, 14.75, 2.28, 5.91, 9.95, 10.44, 70.64, 50.12, 50.13, 101.25, 97.12, 86.51, 72.17, 38.32, 10.11, 7.74, 9.67, 43.12, 52.21, 134.85, 134.86, 103.79, 46.1, 15.03, 24.2, 41.65, 52.34, 53.78, 70.4, 85.81, 56.69, 16.59, 6.16, 2.3, 12.82, 4.72, 4.73, 37.22, 69.72, 57.78, 28.68, 23.37, 21.54, 26.34, 53.1, 68.48, 75.58, 57.92, 40.97, 24.95, 12.59, 4.97, 4.5, 11.21, 56.6, 69.63, 77.74, 80.53, 73.38, 36.93, 4.64, 2.54, 1.8, 2.39, 4.23, 19.52, 82.11, 89.76, 81.66, 15.76], "Lynx" => [30.09, 45.15, 49.15, 39.52, 21.23, 8.42, 5.56, 5.08, 10.17, 19.6, 32.91, 34.38, 29.59, 21.3, 13.69, 7.65, 4.08, 4.09, 14.33, 38.22, 60.78, 70.77, 72.77, 42.68, 16.39, 9.83, 5.8, 5.26, 18.91, 30.95, 31.18, 46.34, 45.77, 44.15, 36.33, 12.03, 12.6, 18.34, 35.14, 43.77, 65.69, 79.35, 51.65, 32.59, 22.45, 16.16, 14.12, 20.38, 33.33, 46.0, 51.41, 46.43, 33.68, 18.01, 8.86, 7.13, 9.47, 14.86, 31.47, 60.57, 63.51, 54.7, 6.3, 3.41, 5.44, 11.65, 20.35, 32.88, 39.55, 43.36, 40.83, 30.36, 17.18, 6.82, 3.19, 3.52, 9.94, 20.3, 31.99, 42.36, 49.08, 53.99, 52.25, 37.7, 19.14, 6.98, 8.31, 16.01, 24.82, 29.7, 35.4] ) ``` # Making a Model This tutorial will cover the topic of creating a Cropbox model. ```@contents Pages = ["makingamodel.md"] Depth = 4 ``` ## [Growing Degree-Day](@id GDD) You might have heard the terms like growing degree days (GDD), thermal units, heat units, heat sums, temperature sums, and thermal-time that are used to relate the rate of plant or insect development to temperature. They are all synonymous. The concept of thermal-time or thermal-units derives from the long-standing observation and assumption that timing of development is primarily driven by temperature in plants and the relationship is largely linear. The linear relationship is generally held true over normal growing temperatures that are bracketed by the base temperature (*Tb*) and optimal temperature (*Topt*). Many existing crop models and tree growth models use thermal-unit approaches (e.g., GDD) for modeling phenology with some modifications to account for other factors like photoperiod, vernalization, dormancy, and stress. The growing degree days (GDD) is defined as the difference between the average daily air temperature (*T*) and the base temperature below which the developmental process stops. The bigger the difference in a day, the faster the development takes place up to a certain optimal temperature (*Topt*). The Cumulative GDD (cGDD) since the growth initiation (e.g., sowing, imbibition for germination) is then calculated by: ```math \begin{align} \mathrm{GDD}(T) &= \max \{ 0, \min \{ T, T_{opt} \} - T_b \} \\ \mathrm{cGDD} &= \sum_i^n \mathrm{GDD}(T_i) \\ \end{align} ``` In this section, we will create a model that simulates GDD and cGDD. ### System Let us start by making a system called `GrowingDegreeDay`. This can be done using a simple Cropbox macro `@system`. ``` @system GrowingDegreeDay ``` #### Variables From the equation, let's identify the variables we need to declare in our system. In the equation for GDD, we have two parameters *Topt* and *Tb*. Since they are fixed values, we will declare them as `preserve` variables, which are variables that remain constant throughout a simulation. ``` @system GrowingDegreeDay begin Tb ~ preserve To ~ preserve end ``` `Tb` and `To` are parameters that we may want to change depending on the simulation. To make this possible, we will assign them the `parameter` tag, which allows the tagged variables to be altered through a configuration for each simulation. Note that we will not assign values at declaration because we will configure them when we run the simulation. ``` @system GrowingDegreeDay begin Tb ~ preserve(parameter) To ~ preserve(parameter) end ``` Lastly, we will tag the variables with units. Tagging units is the recommended practice for many reasons, one of which is to catch mismatching units during calculations. ``` @system GrowingDegreeDay begin Tb ~ preserve(parameter, u"°C") To ~ preserve(parameter, u"°C") end ``` In the GDD equation, *T* represents the average daily temperature value necessary to calculate the GDD. Likewise, the variable in our system will represent a series of daily average temperatures. The series of temperature values will be driven from an external data source, for which we will create a separate system later on for data extraction. For the `GrowingDegreeDay` system, we will declare `T` as a `hold` variable, which represents a placeholder that will be replaced by a `T` from another system. ``` @system GrowingDegreeDay begin T ~ hold Tb ~ preserve(parameter, u"°C") To ~ preserve(parameter, u"°C") end ``` We declared all the necessary variables required to calculate GDD. Now it is time to declare GDD as a variable in the system. Because GDD is a variable that we want to evaluate and store in each update, we will declare it as a `track` variable with `T`, `Tb`, and `To` as its depending variables. ``` @system GrowingDegreeDay begin T ~ hold Tb ~ preserve(parameter, u"°C") To ~ preserve(parameter, u"°C") GDD(T, Tb, To) => begin min(T, To) - Tb end ~ track(min = 0, u"K") end ``` *Note that we have tagged the unit for* `GDD` *as* `u"K"`. *This is to avoid incompatibilities that* `u"°C"` *has with certain operations.* Now that `GDD` is declared in the system, we will declare cGDD as an `accumulate` variable with `GDD` as its depending variable. Recall that `accumulate` variables perform the Euler method of integration. ``` @system GrowingDegreeDay begin T ~ hold Tb ~ preserve(parameter, u"°C") To ~ preserve(parameter, u"°C") GDD(T, Tb, To) => begin min(T, To) - Tb end ~ track(min = 0, u"K") cGDD(GDD) ~ accumulate(u"K*d") end ``` We have declared all the necessary variables for `GrowingDegreeDay`. #### Mixins Now let's address the issue of the missing temperature values. We will make a new system that will provide the missing temperature data we need for simulating `GrowingDegreeDay`. We will call this system `Temperature`. The purpose of `Temperature` will be to obtain a time series of daily average temperature values from an external data source. ``` @system Temperature ``` For this tutorial, we will be using weather data from Beltsville, Maryland in 2002. The data is available [here](https://github.com/cropbox/Cropbox.jl/blob/main/docs/src/tutorials/weather.csv). If you are unsure how to read CSV files, check the following [documentation](https://csv.juliadata.org/stable/reading.html#CSV.read). You can also follow the template below (make sure `path` corresponds to the path to your data file). ``` using CSV, DataFrames weather = CSV.read(path, DataFrame) ``` The data should look something like the following: ```@example Cropbox first(weather, 3) ``` \ Notice that the column names have units in parentheses. The `unitfy()` function in Cropbox automatically assigns units to values based on names of the columns (if the unit is specified). ```@example Cropbox weather = unitfy(weather) first(weather, 3) ``` \ In the `Temperature` system, there is one variable that we will declare before declaring any other variable. We will name this variable `calendar`. ``` @system Temperature begin calendar(context) ~ ::Calendar end ``` The purpose of `calendar` is to have access to variables inside the `Calendar` system such as `init`, `last`, and `date`, which represent initial, last, and current date, respectively. !!! note "Note" `calendar` is a variable reference to the [`Calendar`](@ref Calendar) system (one of the built-in systems of Cropbox), which has a number of time-related variables in date format. Declaring `calendar` as a variable of type `Calendar` allows us to use the variables inside the `Calendar` system as variables for our current system. Recall that `context` is a reference to the `Context` system and is included in every Cropbox system by default. Inside the `Context` system there is the `config` variable which references a `Config` object. By having `context` as a depending variable for `calendar`, we can change the values of the variables in `calendar` with a configuration. The next variable we will add is a variable storing the weather data as a DataFrame. This variable will be a `provide` variable named `data`. ``` @system Temperature begin calendar(context) ~ ::Calendar data ~ provide(parameter, index=:date, init=calendar.date) end ``` Note that we have tagged the variable with a `parameter` tag so that we can assign a DataFrame during the configuration. We will set the index of the extracted DataFrame as the "date" column of the data source. The `init` tag is used to specify the starting row of the data that we want to store. `calendar.date` refers to the `date` variable in the `Calendar` system, and is a `track` variable that keeps track of the dates of simulation. The initial value of `date` is dependent on `calendar.init` which we will assign during configuration. By setting `init` to `calendar.date`, we are making sure that the `provide` variable extracts data from the correct starting row corresponding to the desired initial date of simulation. Now we can finally declare the temperature variable using one of the columns of the DataFrame represented by `data`. Because this variable is *driven* from a source, we will be declaring a `drive` variable named `T`. The `from` tag specifies the DataFrame source and the `by` tag specifies which column to take the values from. ```@example Cropbox @system Temperature begin calendar(context) ~ ::Calendar data ~ provide(parameter, index=:date, init=calendar.date) T ~ drive(from=data, by=:Tavg, u"°C") end ``` \ We finally have all the components to define our model. Because `GrowingDegreeDay` requires values for `T` from `Temperature`, let's redeclare `GrowingDegreeDay` with `Temperature` as a mixin. Because we want to run a simulation of `GrowingDegreeDay`, we also want to include `Controller` as a mixin. Recall that `Controller` must be included as a mixin for any system that you want to simulate. ```@example Cropbox @system GrowingDegreeDay(Temperature, Controller) begin T ~ hold Tb ~ preserve(parameter, u"°C") To ~ preserve(parameter, u"°C") GDD(T, Tb, To) => begin min(T, To) - Tb end ~ track(min = 0, u"K") cGDD(GDD) ~ accumulate(u"K*d") end ``` \ ### Configuration The next step is to create a configuration object to assign the values of parameters. Recall that `data`, `T`, `Tb`, and `To` are empty variables at the moment. As covered in the [Configuration](@ref Configuration1) section, we can make a single `Config` object with all the configurations we need for our systems. Given the nature of GDD, this model is a daily model. To run a daily simulation, we need to configure the `step` variable in the `Clock` system from `1u"hr"` to `1u"d"`. This will change the time interval of the simulation from hourly (default) to daily. ``` c = @config :Clock => :step => 1u"d" ``` Next we will add the configurations for `GrowingDegreeDay`. The only parameters we have to configure are `Tb` and `To`. ``` c = @config ( :Clock => ( :step => 1u"d" ), :GrowingDegreeDay => ( :Tb => 8.0u"°C", :To => 32.0u"°C" ) ) ``` Next we will pair the aforementioned DataFrame `weather` to `data` in `Temperature` ``` c = @config( :Clock => ( :step => 1u"d" ), :GrowingDegreeDay => ( :Tb => 8.0u"°C", :To => 32.0u"°C" ), :Temperature => ( :data => weather ) ) ``` Lastly, we will configure the `init` and `last` parameters of the `Calendar` system, which will define the time range of our simulation. ```@example Cropbox c = @config( :Clock => ( :step => 1u"d" ), :GrowingDegreeDay => ( :Tb => 8.0u"°C", :To => 32.0u"°C" ), :Temperature => ( :data => weather ), :Calendar => ( :init => ZonedDateTime(2002, 5, 15, tz"America/New_York"), :last => ZonedDateTime(2002, 9, 30, tz"America/New_York") ) ) ``` ### Simulation Now that we have fully defined `GrowingDegreeDay` and created a configuration for it, we can finally simulate the model. ```@example Cropbox s = simulate(GrowingDegreeDay; config = c, stop = "calendar.stop", index = "calendar.date", target = [:GDD, :cGDD] ) first(s, 10) ``` \ ### Visualization To end the tutorial, let's visualize the simulation using the `plot()` and `visualize()` functions. We can input the DataFrame from our simulation in the `plot()` function to create a plot. Here is a plot of `GDD` over time. ```@example Cropbox plot(s, "calendar.date", :GDD; kind=:line) ``` We can also simultaneously run a new simulation and plot its result using the `visualize()` function. Here is a plot of `cGDD` over time. ```@example Cropbox visualize(GrowingDegreeDay, "calendar.date", :cGDD; config=c, stop="calendar.stop", kind=:line) ``` ## Lotka-Volterra Equations In this tutorial, we will create a model that simulates population dynamics between prey and predator using the Lotka-Volterra equations. The Lotka-Volterra equations are as follows: ```math \begin{align} \frac{dN}{dt} &= bN - aNP \\ \frac{dP}{dt} &= caNP - mP \\ \end{align} ``` \ Here is a list of variables used in the system: | Symbol | Value | Units | Description | | :---: | :---: | :---: | :--- | | t | - | $\mathrm{yr}$ | Time unit used in the model | | N | - | - | Prey population as number of individuals (state variable) | | P | - | - | Predator population as number of individuals (state variable) | | b | - | $\mathrm{yr^{-1}}$ | Per capital birth rate that defines the intrinsic growth rate of prey population | | a | - | $\mathrm{yr^{-1}}$ | Attack rate or predation rate | | c | - | - | Conversion efficiency of an eaten prey into new predator; predator's reproduction efficiency per prey consumed) | | m | - | $\mathrm{yr^{-1}}$ | Mortality rate of predator population | \ ### System Let's begin by creating a [system](@ref system) called `LotkaVolterra`. Since this is a system that we want to simulate later on, we must include [`Controller`](@ref Controller) as a [mixin](@ref Mixin). ``` @system LotkaVolterra(Controller) ``` \ We will first declare a time variable with a yearly unit, which we will use for plotting the model simulations later on. Recall that `context.clock.time` is a variable that keeps track of the progression of time. We are simply declaring a variable to keep track of the time in years. ``` @system LotkaVolterra(Controller) begin t(context.clock.time) ~ track(u"yr") end ``` \ Next, we will declare the parameters in the equations as `preserve` variables. `preserve` variables are variables that remain constant throughout a simulation. ``` @system LotkaVolterra(Controller) begin t(context.clock.time) ~ track(u"yr") b: prey_birth_rate ~ preserve(parameter, u"yr^-1") a: predation_rate ~ preserve(parameter, u"yr^-1") c: predator_reproduction_rate ~ preserve(parameter) m: predator_mortality_rate ~ preserve(parameter, u"yr^-1") end ``` \ Now let's declare the prey and predator populations as variables. The Lotka-Volterra equations describe the rates of change for the two populations. As we want to track the actual number of the two populations, we will declare the two populations as `accumulate` variables, which are simply Euler integrations of the two population rates. Note that a variable can be used as its own depending variable. ``` @system LotkaVolterra(Controller) begin t(context.clock.time) ~ track(u"yr") b: prey_birth_rate ~ preserve(parameter, u"yr^-1") a: predation_rate ~ preserve(parameter, u"yr^-1") c: predator_reproduction_rate ~ preserve(parameter) m: predator_mortality_rate ~ preserve(parameter, u"yr^-1") N(N, P, b, a): prey_population => b*N - a*N*P ~ accumulate P(N, P, c, a, m): predator_population => c*a*N*P - m*P ~ accumulate end ``` \ By default, `accumulate` variables initialize at a value of zero. In our current model, that would result in two populations remaining at zero indefinitely. To address this, we will define the initial values for the two `accumulate` variables using the `init` tag. We can specify a particular value, or we can also create and reference new parameters representing the two initial populations. We will go with the latter option as it allows us to flexibly change the initial populations with a configuration. ```@example Cropbox @system LotkaVolterra(Controller) begin t(context.clock.time) ~ track(u"yr") b: prey_birth_rate ~ preserve(parameter, u"yr^-1") a: predation_rate ~ preserve(parameter, u"yr^-1") c: predator_reproduction_rate ~ preserve(parameter) m: predator_mortality_rate ~ preserve(parameter, u"yr^-1") N0: prey_initial_population ~ preserve(parameter) P0: predator_initial_population ~ preserve(parameter) N(N, P, b, a): prey_population => b*N - a*N*P ~ accumulate(init=N0) P(N, P, c, a, m): predator_population => c*a*N*P - m*P ~ accumulate(init=P0) end ``` \ ### Configuration With the system now defined, we will create a `Config` object to fill or adjust the parameters. First, we will change the `step` variable in the `Clock` system to `1u"d"`, which will make the system update at a daily interval. Recall that `Clock` is a system that is referenced in all systems by default. You can technically run the model with any timestep. ```@example Cropbox lvc = @config (:Clock => :step => 1u"d") ``` \ Next, we will configure the parameters in the `LotkaVolterra` system that we defined. Note that we can easily combine configurations by providing multiple elements. ```@example Cropbox lvc = @config (lvc, :LotkaVolterra => ( b = 0.6, a = 0.02, c = 0.5, m = 0.5, N0 = 20, P0 = 30 ) ) ``` \ ### Visualization Let's visualize the `LotkaVolterra` system with the configuration that we just created, using the `visualize()` function. The `visualize()` function both runs a simulation and plots the resulting DataFrame. ```@example Cropbox visualize(LotkaVolterra, :t, [:N, :P]; config = lvc, stop = 100u"yr", kind = :line) ``` ### Density-Dependent Lotka-Volterra Equations Now let's try to make a density-dependent version of the original Lotka-Volterra model which incorporates a new term in the prey population rate. The new variable *K* represents the carrying capacity of the prey population. ```math \begin{align} \frac{dN}{dt} &= bN-\frac{b}{K}N^2-aNP \\ \frac{dP}{dt} &= caNP-mP \\ \end{align} ``` #### System We will call this new system `LotkaVolterraDD`. ``` @system LotkaVolterraDD(Controller) ``` \ Since we already defined the `LotkaVolterra` system, which already has most of the variables we require, we can use `LotkaVolterra` as a mixin for `LotkaVolterraDD`. This makes our task a lot simpler, as all that remains is to declare the variable `K` for carrying capacity and redeclare the variable `N` for prey population. The variable `N` in the new system will automatically overwrite the `N` from `LotkaVolterra`. ```@example Cropbox @system LotkaVolterraDD(LotkaVolterra, Controller) begin N(N, P, K, b, a): prey_population => begin b*N - b/K*N^2 - a*N*P end ~ accumulate(init = N0) K: carrying_capacity ~ preserve(parameter) end ``` \ #### Configuration Much like the new system, the new configuration can be created by reusing the old configuration. All we need to configure is the new variable `K`. ```@example Cropbox lvddc = @config(lvc, (:LotkaVolterraDD => :K => 1000)) ``` \ #### Visualization Once again, let's visualize the system using the `visualize()` function. ```@example Cropbox visualize(LotkaVolterraDD, :t, [:N, :P]; config = lvddc, stop = 100u"yr", kind = :line) ``` \ #### Calibration If you want to calibrate the parameters according to a particular dataset, Cropbox provides the `calibrate()` function, which relies on [BlackBoxOptim.jl](https://github.com/robertfeldt/BlackBoxOptim.jl) for global optimization methods. If you are interested in local optimization methods, refer to [Optim.jl](https://github.com/JuliaNLSolvers/Optim.jl) package for more information. For this tutorial, we will use a dataset containing the number of pelts (in thousands) of Canadian lynx and snowshoe hare traded by the Hudson Bay Trading Company in Canada from 1845 to 1935. The data is available [here](https://github.com/cropbox/Cropbox.jl/blob/main/docs/src/tutorials/pelts.csv). If you are unsure how to read CSV files, check the following [documentation](https://csv.juliadata.org/stable/reading.html#CSV.read). You can also follow the template below (make sure `path` corresponds to the path to your data file). ``` using CSV, DataFrames pelts = CSV.read(path, DataFrame) ``` The data should look something like the this: ```@example Cropbox first(pelts, 3) ``` \ Recall that we can use the `unitfy()` function in Cropbox to automatically assign units when they are specified in the column headers. ```@example Cropbox pelts = unitfy(pelts) first(pelts, 3) ``` \ Let's plot the data and see what it looks like. ```@example Cropbox visualize(pelts, :Year, [:Hare, :Lynx], kind = :scatterline) ``` \ For our calibration, we will use a subset of the data covering years 1900 to 1920. ```@example Cropbox pelts_subset = @subset(pelts, 1900u"yr" .<= :Year .<= 1920u"yr") ``` \ Before we calibrate the parameters for `LotkaVolterra`, let's add one new variable to the system. We will name this variable `y` for year. The purpose of `y` is to keep track of the year in the same manner as the dataset. ```@example Cropbox @system LotkaVolterra(Controller) begin t(context.clock.time) ~ track(u"yr") y(t): year ~ track::Int(u"yr", round) b: prey_birth_rate ~ preserve(parameter, u"yr^-1") a: predation_rate ~ preserve(parameter, u"yr^-1") c: predator_reproduction_rate ~ preserve(parameter) m: predator_mortality_rate ~ preserve(parameter, u"yr^-1") N0: prey_initial_population ~ preserve(parameter) P0: predator_initial_population ~ preserve(parameter) N(N, P, b, a): prey_population => b*N - a*N*P ~ accumulate(init=N0) P(N, P, c, a, m): predator_population => c*a*N*P - m*P ~ accumulate(init=P0) end ``` \ We will now use the `calibrate()` function to find parameters that fit the data. Keep in mind that the search range for each parameter will be determined by you. We will use the `snap` option to explicitly indicate that the output should be recorded by 365-day intervals to avoid excessive rows in the DataFrame causing unnecessary slowdown. Note that we will use `365u"d"` instead of `1u"yr"` which is technically equivalent to `365.25u"d"` following the convention in astronomy. For information regarding syntax, please check the [reference](@ref Simulation1). ```@example Cropbox lvcc = calibrate(LotkaVolterra, pelts_subset; index = :Year => :y, target = [:Hare => :N, :Lynx => :P], config = :Clock => (:init => 1900u"yr", :step => 1u"d"), parameters = LotkaVolterra => (; b = (0, 2), a = (0, 2), c = (0, 2), m = (0, 2), N0 = (0, 100), P0 = (0, 100), ), stop = 20u"yr", snap = 365u"d" ) ``` \ As you can see above, the `calibrate()` function will return a `Config` object for the system. Using the new configuration, let's make a comparison plot to visualize how well the simualation with the new parameters fits the data. ```@example Cropbox p1 = visualize(pelts_subset, :Year, [:Hare, :Lynx]; kind = :scatterline) visualize!(p1, LotkaVolterra, :t, [:N, :P]; config = (lvcc, :Clock => (:init => 1900u"yr", :step => 1u"d")), stop = 20u"yr", kind = :line, colors = [1, 2], names = [], ) ``` \ Now let's try calibrating the density-dependent version of the model. Since we made a slight change to `LotkaVolterra`, let's make sure to define `LotkaVolterraDD` again. ```@example Cropbox @system LotkaVolterraDD(LotkaVolterra, Controller) begin N(N, P, K, b, a): prey_population => begin b*N - b/K*N^2 - a*N*P end ~ accumulate(init = N0) K: carrying_capacity ~ preserve(parameter) end ``` ```@setup Cropbox @system LotkaVolterraDD(Controller) begin t(context.clock.time) ~ track(u"yr") y(t): year ~ track::Int(u"yr", round) b: prey_birth_rate ~ preserve(parameter, u"yr^-1") a: predation_rate ~ preserve(parameter, u"yr^-1") c: predator_reproduction_rate ~ preserve(parameter) m: predator_mortality_rate ~ preserve(parameter, u"yr^-1") K: carrying_capacity ~ preserve(parameter) N0: prey_initial_population ~ preserve(parameter) P0: predator_initial_population ~ preserve(parameter) N(N, P, b, a, K): prey_population => b*N - b/K*N^2 - a*N*P ~ accumulate(init=N0) P(N, P, c, a, m): predator_population => c*a*N*P - m*P ~ accumulate(init=P0) end ``` \ Don't forget to add `K` among the parameters that we want to calibrate. ```@example Cropbox lvddcc = calibrate(LotkaVolterraDD, pelts_subset; index = :Year => :y, target = [:Hare => :N, :Lynx => :P], config = :Clock => (:init => 1900u"yr", :step => 1u"d"), parameters = LotkaVolterraDD => (; b = (0, 2), a = (0, 2), c = (0, 2), m = (0, 2), N0 = (0, 100), P0 = (0, 100), K = (0, 1000) ), stop = 20u"yr", snap = 365u"d" ) ``` \ Once again, let us make a comparison plot to see how the density-dependent version of the model fares against the original dataset. ```@example Cropbox p2 = visualize(pelts_subset, :Year, [:Hare, :Lynx]; kind = :scatterline) visualize!(p2, LotkaVolterraDD, :t, [:N, :P]; config = (lvddcc, :Clock => (:init => 1900u"yr", :step => 1u"d")), stop = 20u"yr", kind = :line, colors = [1, 2], names = [], ) ``` \ #### Evaluation We have visualized how the simulated `LotkaVolterra` and `LotkaVolterraDD` systems compare to the the original dataset. Let us obtain a metric for how well the simulations fit the original dataset using the `evaluate()` function in Cropbox. The `evaluate()` function supports numerous different metrics for evaluation. Here, we will calculate the root-mean-square error (RMSE) and modeling efficiency (EF). Here are the evaluation metrics for `LotkaVolterra`. The numbers in the tuples correspond to hare and lynx, respectively. ```@example Cropbox evaluate(LotkaVolterra, pelts_subset; index = :Year => :y, target = [:Hare => :N, :Lynx => :P], config = (lvcc, :Clock => (:init => 1900u"yr", :step => 1u"d")), stop = 20u"yr", snap = 365u"d", metric = :rmse, ) ``` ```@example Cropbox evaluate(LotkaVolterra, pelts_subset; index = :Year => :y, target = [:Hare => :N, :Lynx => :P], config = (lvcc, :Clock => (:init => 1900u"yr", :step => 1u"d")), stop = 20u"yr", snap = 365u"d", metric = :ef ) ``` \ Here are the evaluation metrics for `LotkaVolterraDD`: ```@example Cropbox evaluate(LotkaVolterraDD, pelts_subset; index = :Year => :y, target = [:Hare => :N, :Lynx => :P], config = (lvddcc, :Clock => (:init => 1900u"yr", :step => 1u"d")), stop = 20u"yr", snap = 365u"d", metric = :rmse ) ``` ```@example Cropbox evaluate(LotkaVolterraDD, pelts_subset; index = :Year => :y, target = [:Hare => :N, :Lynx => :P], config = (lvddcc, :Clock => (:init => 1900u"yr", :step => 1u"d")), stop = 20u"yr", snap = 365u"d", metric = :ef ) ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.3.50
92f7c427254bee725db295408ed3af6d9e2072cd
docs
4631
```@setup simple ``` # Using an Existing Cropbox Model This tutorial will teach you how to use an existing Cropbox model. For this tutorial, we will be importing and utilizing a Cropbox model from a julia package called SimpleCrop. ## Installing a Cropbox Model Often times, the Cropbox model that you want to use will be part of a Julia package. If the package you want to install is under the official [Julia package registry](https://github.com/JuliaRegistries/General), you can simply install the package using the following command. ``` using Pkg Pkg.add("SimpleCrop") ``` You can also install any Julia package using a GitHub link. ``` using Pkg Pkg.add("https://github.com/cropbox/SimpleCrop.jl") ``` ## Importing a Cropbox Model To start using a Julia package containing your desired model, you must first load the package into your environment. This can be done by using this simple command. ```@example simple using SimpleCrop ``` Let's not forget to load Cropbox as well. ```@example simple using Cropbox ``` ## Inspecting the Model The model is implemented as a system named `Model` defined in SimpleCrop module. We can inspect the model with the `@look` macro, which will show us all the variables in the system. ```@example simple @look SimpleCrop.Model ``` @look can also be used to inspect individual state variables. ```@example simple @look SimpleCrop.Model.W ``` The relationship between the variables in the model can be visualized using a dependency graph. ```@example simple Cropbox.dependency(SimpleCrop.Model) ``` If an arrow points from one variable to a second variable, then the value of the second variable depends on, or is calculated with, the value of the first. We can view the values of all the parameters of the model with the following command. ```@example simple parameters(SimpleCrop.Model; alias = true) ``` ## Running a Simulation As many parameters are already defined in the model, we only need to prepare time-series data for daily weather and irrigation, which are included in the package for convenience. ```@example simple using CSV using DataFrames using Dates using TimeZones loaddata(f) = CSV.File(joinpath(dirname(pathof(SimpleCrop)), "../test/data", f)) |> DataFrame ; # hide ``` ```@example simple config = @config ( :Clock => :step => 1u"d", :Calendar => :init => ZonedDateTime(1987, 1, 1, tz"UTC"), :Weather => :weather_data => loaddata("weather.csv"), :SoilWater => :irrigation_data => loaddata("irrigation.csv"), ) ; # hide ``` Let's run a simulation with the model using configuration we just created. Stop condition for simulation is defined in a flag variable named `endsim` which coincides with plant maturity or the end of reproductive stage. ```@example simple r = simulate(SimpleCrop.Model; config, stop = :endsim) ; # hide ``` ## Visualizing the Results The output of simulation is now contained in a data frame from which we generate multiple plots. The number of leaf (`N`) went from `initial_leaf_number` (= 2) to `maximum_leaf_number` (= 12) as indicated in the default set of parameters. ```@example simple visualize(r, :DATE, :N; ylim = (0, 15), kind = :line) ``` Thermal degree days (`INT`) started accumulating from mid-August with the onset of reproductive stage until late-October when it reaches the maturity indicated by `duration_of_reproductive_stage` (= 300 K d). ```@example simple visualize(r, :DATE, :INT; kind = :line) ``` Assimilated carbon (`W`) was partitioned into multiple parts of the plant as shown in the plot of dry biomass. ```@example simple visualize(r, :DATE, [:W, :Wc, :Wr, :Wf]; names = ["Total", "Canopy", "Root", "Fruit"], kind = :line) ``` Leaf area index (`LAI`) reached its peak at the end of vegetative stage then began declining throughout reproductive stage. ```@example simple visualize(r, :DATE, :LAI; kind = :line) ``` For soil water balance, here is a plot showing water runoff (`ROF`), infiltration (`INF`), and vertical drainage (`DRN`). ```@example simple visualize(r, :DATE, [:ROF, :INF, :DRN]; kind = :line) ``` Soil water status has influence on potential evapotranspiration (`ETp`), actual soil evaporation (`ESa`), and actual plant transpiration (`ESp`). ```@example simple visualize(r, :DATE, [:ETp, :ESa, :EPa]; kind = :line) ``` The resulting soil water content (`SWC`) is shown here. ```@example simple visualize(r, :DATE, :SWC; ylim = (0, 400), kind = :line) ``` Which, in turn, determines soil water stress factor (`SWFAC`) in this model. ```@example simple visualize(r, :DATE, [:SWFAC, :SWFAC1, :SWFAC2]; ylim = (0, 1), kind = :line) ```
Cropbox
https://github.com/cropbox/Cropbox.jl.git
[ "MIT" ]
0.1.1
60dd6a769d210c66b430162e47bfc00a3ceff749
code
531
using KissCaches using Documenter makedocs(; modules=[KissCaches], authors="Jan Weidner <[email protected]> and contributors", repo="https://github.com/jw3126/KissCaches.jl/blob/{commit}{path}#L{line}", sitename="KissCaches.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://jw3126.github.io/KissCaches.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/jw3126/KissCaches.jl", )
KissCaches
https://github.com/jw3126/KissCaches.jl.git
[ "MIT" ]
0.1.1
60dd6a769d210c66b430162e47bfc00a3ceff749
code
1482
module KissCaches export cached, @cached, iscached function cached(storage, f, args...; kw...) key = makekey(storage, f, args...; kw...) get!(storage, key) do @debug """ Adding to cache: f = $f args = $args kw = $kw key = $key cache = $cache """ f(args...; kw...) end end # makekey(storage, f, args...; kw...) = Base.hash((f, args, kw)) makekey(storage, f, args...; kw...) = (f, args, (;kw...)) function iscached(storage, f, args...; kw...) k = makekey(storage, f, args...; kw...) haskey(storage, k) end function deletecached!(storage, f, args...; kw...) k = makekey(storage, f, args...; kw...) delete!(storage, k) end const GLOBAL_CACHE = Dict() macro cached(ex) c = GLOBAL_CACHE esc(cachedmacro(c, ex)) end macro cached(cache, ex) esc(cachedmacro(cache, ex)) end function cachedmacro(cache, ex) if Meta.isexpr(ex, :call) if length(ex.args) >= 2 && Meta.isexpr(ex.args[2], :parameters) Expr(:call, cached, ex.args[2], cache, ex.args[1], ex.args[3:end]...) else Expr(:call, cached, cache, ex.args...) end else ex end end # function apply_cache_to_all_calls(cache, expr) # MacroTools.postwalk(expr) do ex # if Meta.isexpr(ex, :call) # Expr(:call, cached, cache, ex.args...) # else # ex # end # end # end Write your package code here. end
KissCaches
https://github.com/jw3126/KissCaches.jl.git
[ "MIT" ]
0.1.1
60dd6a769d210c66b430162e47bfc00a3ceff749
code
2088
using KissCaches using KissCaches: deletecached! using Test function self(args...; kw...) (args, kw) end function test_cached(cache, f, args...; kw...) @test !iscached(cache, f, args...; kw...) @cached cache f(args...; kw...) @test iscached(cache, f, args...; kw...) deletecached!(cache, f, args...; kw...) @test !iscached(cache, f, args...; kw...) end @testset "test" begin cache = Dict() @test !iscached(cache, sin, 1) @cached cache sin(1) @test iscached(cache, sin, 1) empty!(cache) @test !iscached(cache, sin, 1) @test !iscached(cache, cos, 1) test_cached(Dict(), sin, 1) test_cached(Dict(), self) test_cached(Dict(), self, 1) test_cached(Dict(), self, x=:x) test_cached(Dict(), self, 1, x=1) test_cached(Dict(), self, 1, x=1, y="hi", z=["a", Any]) test_cached(Dict(), self, 1, x=1, y="hi", z=["a", Any]) end @testset "GLOBAL_CACHE" begin @test !iscached(KissCaches.GLOBAL_CACHE, self) @cached self() @test iscached(KissCaches.GLOBAL_CACHE, self) for (args, kw) in [ ((1,), NamedTuple()), ((), (a=1,)), ] @test !iscached(KissCaches.GLOBAL_CACHE, self, args...; kw...) @cached self(args...; kw...) @test iscached(KissCaches.GLOBAL_CACHE, self, args...; kw...) end end @testset "interesting behaviour" begin # This behaviour is not necesserily desired. # These tests are there so that we don't forget # about it cache = Dict() @cached cache self(1.0) @test iscached(cache, self, UInt(1)) @test iscached(cache, self, Int(1)) @test iscached(cache, self, Float64(1)) @test iscached(cache, self, Bool(1)) @test iscached(cache, self, Complex(1)) @test !iscached(cache, self, fill(1, (1,1))) @cached cache self("hi") @test iscached(cache, self, "hi") @test !iscached(cache, self, :hi) @cached cache self(1:1) @test iscached(cache, self, 1:1) @test iscached(cache, self, [1]) @test iscached(cache, self, [true]) @test iscached(cache, self, [1.0]) end
KissCaches
https://github.com/jw3126/KissCaches.jl.git
[ "MIT" ]
0.1.1
60dd6a769d210c66b430162e47bfc00a3ceff749
docs
1338
# KissCaches [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://jw3126.github.io/KissCaches.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://jw3126.github.io/KissCaches.jl/dev) [![Build Status](https://github.com/jw3126/KissCaches.jl/workflows/CI/badge.svg)](https://github.com/jw3126/KissCaches.jl/actions) [![Coverage](https://codecov.io/gh/jw3126/KissCaches.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/jw3126/KissCaches.jl) # Usage ```julia julia> using KissCaches julia> f(x) = (println("hi"); return x) f (generic function with 1 method) julia> @cached f(1) hi 1 julia> @cached f(1) 1 julia> cache = Dict() # customize cache Dict{Any,Any}() julia> @cached cache f(1) hi 1 julia> @cached cache f(1) 1 julia> empty!(cache) Dict{Any,Any}() julia> @cached cache f(1) hi 1 ``` # Alternatives There are multiple excellent alternatives for caching function calls. Most are more sophisticted and work by altering the function definition. KissCaches on the other hand is really simple and alters the function call. See also: * [Anamnesis.jl](https://github.com/ExpandingMan/Anamnesis.jl) * [Caching.jl](https://github.com/zgornel/Caching.jl) * [Memoize.jl](https://github.com/JuliaCollections/Memoize.jl) * [Memoization.jl](https://github.com/marius311/Memoization.jl)
KissCaches
https://github.com/jw3126/KissCaches.jl.git
[ "MIT" ]
0.1.1
60dd6a769d210c66b430162e47bfc00a3ceff749
docs
110
```@meta CurrentModule = KissCaches ``` # KissCaches ```@index ``` ```@autodocs Modules = [KissCaches] ```
KissCaches
https://github.com/jw3126/KissCaches.jl.git
[ "MIT" ]
0.3.4
73615a75dd205151ac33f52c2d205373bb69fb4a
code
244
module FranklinUtils import Franklin const F = Franklin import ExprTools: splitdef, combinedef # misc export html, isapproxstr # lx_tools export lxd, lxproc, lxargs, lxmock, @lx, @env include("misc.jl") include("lx_tools.jl") end # module
FranklinUtils
https://github.com/tlienart/FranklinUtils.jl.git
[ "MIT" ]
0.3.4
73615a75dd205151ac33f52c2d205373bb69fb4a
code
3799
""" lxd(n) Create a dummy latex definition (useful for testing). """ lxd(n) = F.LxDef("\\" * n, 1, F.subs("")) """ lxproc(com) Extract the content of a single-brace lx command. For instance `\\com{foo}` would be extracted to `foo`. """ lxproc(com) = F.content(com.braces[1]) """ lxargs(s) Extract function-style arguments. Expect (arg1, arg2, ..., name1=val1, name2=val2, ...) Example: julia> a = ":section, 1, 3, title=\"hello\", name=\"bar\"" julia> lxargs(a) (Any[:section, 1, 3], Any[:title => "hello", :name => "bar"]) """ function lxargs(s, fname="") isempty(s) && return [], [] s = "(" * s * ",)" args = nothing try args = Meta.parse(s).args catch error("A command/env $fname had improper options:\n$s; verify.") end # unpack if multiple kwargs are given if !isempty(args) && args[1] isa Expr && args[1].head == :parameters nokw = args[2:end] args = [nokw..., args[1].args...] i = length(nokw) + 1 else i = findfirst(e -> isa(e, Expr) && e.head in (:(=), :parameters), args) end if isnothing(i) cand_args = args cand_kwargs = [] else cand_args = args[1:i-1] cand_kwargs = args[i:end] end proc_args = [] proc_kwargs = [] for arg in cand_args if arg isa QuoteNode push!(proc_args, arg.value) elseif arg isa Expr push!(proc_args, eval(arg)) else push!(proc_args, arg) end end all(e -> e isa Expr, cand_kwargs) || error(""" In command/env $fname, expected arguments followed by keyword arguments but got: $s; verify.""") cand_kwargs = map(e -> e.head == :parameters ? e.args : e, cand_kwargs) for kwarg in cand_kwargs v = kwarg.args[2] if v isa Expr v = eval(v) end push!(proc_kwargs, kwarg.args[1] => v) end return proc_args, proc_kwargs end """ lxarg(com) For a LxCom, extract the first brace and process as function arguments. """ lxargs(com::F.LxObj) = lxargs(lxproc(com), F.getname(com)) """ lxmock(s) Creates a mock command from a string so that it can be parsed as a Franklin.LxCom. """ function lxmock(s) F.def_GLOBAL_LXDEFS!() empty!(F.GLOBAL_LXDEFS) # create a dummy command with the name name = match(r"\\(.*?)\{", s).captures[1] F.GLOBAL_LXDEFS[name] = lxd(name) # parse looking for the comand tokens = F.find_tokens(s, F.MD_TOKENS, F.MD_1C_TOKENS) blocks, tokens = F.find_all_ocblocks(tokens, F.MD_OCB2) lxdefs, tokens, braces, _ = F.find_lxdefs(tokens, blocks) lxdefs = cat(collect(values(F.GLOBAL_LXDEFS)), lxdefs, dims=1) lxcoms, _ = F.find_lxcoms(tokens, lxdefs, braces) # return the lxcom return lxcoms[1] end """ @lx Streamlines the creation of a "latex-function". """ macro lx(defun) def = splitdef(defun) name = def[:name] body = def[:body] name_ = String(name) lxn_ = Symbol("lx_$(name)") fbn_ = Symbol("_lx_$(name)") def[:name] = fbn_ ex = quote eval(FranklinUtils.combinedef($def)) function $lxn_(c, _) a, kw = lxargs(lxproc(c), $name_) return $fbn_(a...; kw...) end end esc(ex) end """ @env Same as [`@lx`](@ref) but for environments """ macro env(defun) def = splitdef(defun) name = def[:name] body = def[:body] name_ = String(name) lxn_ = Symbol("env_$(name)") fbn_ = Symbol("_env_$(name)") def[:name] = fbn_ ex = quote eval(FranklinUtils.combinedef($def)) function $lxn_(e, _) _, kw = lxargs(lxproc(e), $name_) return $fbn_(Franklin.content(e); kw...) end end esc(ex) end
FranklinUtils
https://github.com/tlienart/FranklinUtils.jl.git
[ "MIT" ]
0.3.4
73615a75dd205151ac33f52c2d205373bb69fb4a
code
336
""" html(s) Mark a string as HTML to be included in Franklin-markdown. Line spacing is to reduce issues with `<p>`. """ html(s) = "~~~$s~~~" """ isapproxstr(s1, s2) Check if two strings are similar modulo spaces and line returns. """ isapproxstr(s1, s2) = isequal(map(s->replace(s, r"\s|\n"=>""), String.((s1, s2)))...)
FranklinUtils
https://github.com/tlienart/FranklinUtils.jl.git
[ "MIT" ]
0.3.4
73615a75dd205151ac33f52c2d205373bb69fb4a
code
1583
@testset "lxproc" begin c = lxmock(raw"\foo{bar baz}") @test lxproc(c) == "bar baz" end @testset "lxargs" begin s = """ :section, 1, 3, title="hello", foo="bar", a=5 """ a, ka = lxargs(s) @test all(a .== (:section, 1, 3)) @test all(ka .== ( :title => "hello", :foo => "bar", :a => 5)) s = """ title=5, foo="bar" """ a, ka = lxargs(s) @test isempty(a) @test all(ka .== (:title => 5, :foo => "bar")) s = """ 5, 3 """ a, ka = lxargs(s) @test isempty(ka) @test all(a .== (5, 3)) # bad ordering s = """ 5, a=3, 2 """ @test_throws ErrorException lxargs(s) end @testset "lx-macro" begin # single arg c = lxmock(raw"""\foo{"bar"}""") @lx foo(s) = "A-$s-B" @test lx_foo(c, NaN) == "A-bar-B" # two args c = lxmock(raw"""\bar{"aa", "bb"}""") @lx bar(s1, s2) = "A-$s1-B-$s2-C" @test lx_bar(c, NaN) == "A-aa-B-bb-C" # array args c = lxmock(raw"""\baz{[1,2,3]}""") @lx baz(a) = "A-$(sum(a))-B" @test lx_baz(c, NaN) == "A-6-B" # kwargs c = lxmock(raw"""\foo{a=5}""") @lx foo(;a=5) = "A-$a-B" @test lx_foo(c, NaN) == "A-5-B" # mix of everything c = lxmock(raw"""\foo{"bar"; a=5, b=[1,2,3]}""") @lx foo(s; a=0, b=[1,2]) = "A-$s-$a-$(sum(b))-B" @test lx_foo(c, NaN) == "A-bar-5-6-B" c = lxmock(raw"""\foo{"bar", (1, 2, 3); a=5, b=[1,2,3]}""") @lx foo(s, s2; a=0, b=[1,2]) = "A-$s-$(sum(s2))-$a-$(sum(b))-B" @test lx_foo(c, NaN) == "A-bar-6-5-6-B" end
FranklinUtils
https://github.com/tlienart/FranklinUtils.jl.git
[ "MIT" ]
0.3.4
73615a75dd205151ac33f52c2d205373bb69fb4a
code
144
@testset "html" begin @test html("aaa") == "~~~aaa~~~" end @testset "isapproxstr" begin @test isapproxstr(" aa b c\n", "a a b c") end
FranklinUtils
https://github.com/tlienart/FranklinUtils.jl.git
[ "MIT" ]
0.3.4
73615a75dd205151ac33f52c2d205373bb69fb4a
code
74
using FranklinUtils using Test include("misc.jl") include("lx_tools.jl")
FranklinUtils
https://github.com/tlienart/FranklinUtils.jl.git
[ "MIT" ]
0.3.4
73615a75dd205151ac33f52c2d205373bb69fb4a
docs
6139
# FranklinUtils.jl [![Build Status](https://travis-ci.com/tlienart/FranklinUtils.jl.svg?branch=master)](https://travis-ci.com/tlienart/FranklinUtils.jl) [![Coverage](https://codecov.io/gh/tlienart/FranklinUtils.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/tlienart/FranklinUtils.jl) This package aims to simplify building plugins for [Franklin](https://github.com/tlienart/Franklin.jl). In particular, the definition of * `hfun_*` (functions which will be called with `{{fname ...}}` either from Markdown or from HTML), * `lx_*` (functions which will be called with `\fname{...}` from Markdown only). **Which one should you use?**: both can be useful, as a rough guideline, `hfun_*` are simpler and `lx_*` are more flexible. If you would like to build a plugin package (e.g.: something like [FranklinBootstrap.jl](https://github.com/tlienart/FranklinBootstrap.jl) which makes it easy to work with Bootstrap), you should generally prefer `lx_*` as they will offer more flexibility, particularly in dealing with arguments etc. The present package will be particularly helpful for definitions of `lx_*` commands. ## What this package exports **main** * `lxproc` extract the content of a single-brace lx command/environment (returns the string contained in the first brace) * `lxargs` same as `lxproc` except it treats the string as a Julia function treats its arguments, returns `args, kwargs`. This allows options passed as `{1, 2, opt="hello", bar=true}`. Typically you'll want to use `kwargs` to keep things clear. **other** * `html` a dummy function to wrap something in `~~~` * `isapproxstr` a dummy function to compare two strings ignoring `\s` chars * `lxd` create a dummy latex definition (for testing) ## Where to put definitions ### General user You should put `lx_*` and `hfun_*` functions in the `utils.jl` file. **Note**: the `utils.jl` file can itself load other packages and include other files. ### Package developper Say you're developping a package like `FranklinBootstrap`. Then the corresponding module would export all `lx_*` and `hfun_*` definitions that you want to make available. Users of your package should then just add in their `utils.jl` file either: ```jl using FranklinBootstrap ``` or ```jl using FranklinBootstrap: lx_fun1, lx_fun2, hfun_3 ``` depending on whether they want a finer control over what they want to use (the former should be preferred). ## Defining `hfun_*` Let's say we want to define a function `hfun_foo` which will be called `{{foo ...}}`. To define such function, we must write: ```jl function hfun_foo(...)::String # definition return html_string end ``` that function **must** return a (possibly empty) String which is expected to be in HTML format. ### Arguments #### No arguments You could have a function without argument which would then be called `{{foo}}`. For this, without surprise, just leave the arguments empty in the definition: ```jl function hfun_foo()::String # definition return html_string end ``` #### With arguments Arguments are passed as a string separated by spaces and passed as a `Vector{String}`, it is _expected_ that these strings correspond to names of page variables though of course you can do whatever you want with them. The _expected_ workflow is: 1. define some page variables `var1`, `var2` (note that the definition can itself use Julia code), 1. call the function with `{{foo var1 var2}}` 1. the function `hfun_foo` checks the page variables `var1` and `var2`, accesses their value and proceeds. In all cases, the definition must now look like ```jl function hfun_foo(args::Vector{String})::String # definition return html_string end ``` The difference will lie in how you process the `args`. ### Access to page variables In both `hfun_*` and `lx_*` function you have access to the page variables defined on the page which calls the function and to page variables defined on other pages. To access _local_ page variables, call `locvar("name_of_var")`, to access a page variable defined on another page, call `pagevar("relative_path", "name_of_var")` where `relative_path` is the path to the page that defines the variable. In both case, if the variable is not found then `nothing` is returned. **Example**: page `bish/blah.md` defines `var1`, you can access it via `locvar("var1")` for any function called on `blah.md` and via `pagevar("bish/blah")` anywhere else. **Note**: the relative path for `pagevar` can have the extension, it will be ignored so `"bish/blah.md"` or `"bish/blah"` will be interpreted identically. ### Examples #### Example 1 In file `blah.md` ``` {{foo}} ``` In file `utils.jl` ```jl function hfun_foo() return "<h1>Hello!</h1>" end ``` #### Example 2 In file `blah.md` ``` @def var1 = 5 {{foo var1}} ``` In file `utils.jl` ```jl function hfun_foo(args) vname = args[1] val = locvar(vname) io = IOBuffer() for i in 1:val write(io, "<p>" * "*"^i * "</p>") end return String(take!(io)) end ``` ## Defining `lx_*` Let's say we want to define a function `lx_bar` which will be called `\bar{...}`. To define such function, we must write: ```jl function lx_bar(lxc, lxd)::String # definition return markdown_string end ``` that function **must** return a (possibly empty) String which is expected to be in HTML format. ### Arguments * `lxc` is a Franklin object which essentially contains the content of the braces. * `lxd` is a Franklin object which contains all the LaTeX-like definitions that have been defined up to the point where `\bar` is called, you should generally not use it. The **recommended** workflow is to use the `lxargs` function from `FranklinUtils` to read the content of the first brace as if it was the arguments passed to a Julia function: ```jl function lx_bar(lxc, _) args, kwargs = lxargs(lxc) # work with args, kwargs return markdown_string end ``` **Note**: a `lx_*` function can also build raw HTML, in that case just use the `html` function at the end so that it gets considered as such e.g.: `return html(html_string)`. ## Notes ### Nesting ...
FranklinUtils
https://github.com/tlienart/FranklinUtils.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
code
1214
# SPDX-License-Identifier: MIT # The extension module loading this file is required to define `nv`, `ne`, and # `outneighbors` following the Graphs.jl meanings. using Metis.LibMetis: idx_t using Metis: Graph function graph(G; weights::Bool=false, kwargs...) N = nv(G) xadj = Vector{idx_t}(undef, N+1) xadj[1] = 1 adjncy = Vector{idx_t}(undef, 2*ne(G)) vwgt = C_NULL # TODO: Vertex weights could be passed as an input argument adjwgt = weights ? Vector{idx_t}(undef, 2*ne(G)) : C_NULL adjncy_i = 0 for j in 1:N ne = 0 for i in outneighbors(G, j) i == j && continue # skip self edges ne += 1 adjncy_i += 1 adjncy[adjncy_i] = i if weights weight = get_weight(G, i, j) if !(isinteger(weight) && weight > 0) error("weights must be positive integers, got weight $(weight) for edge ($(i), $(j))") end adjwgt[adjncy_i] = weight end end xadj[j+1] = xadj[j] + ne end resize!(adjncy, adjncy_i) weights && resize!(adjwgt, adjncy_i) return Graph(idx_t(N), xadj, adjncy, vwgt, adjwgt) end
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
code
388
# SPDX-License-Identifier: MIT module MetisGraphs using Graphs: AbstractSimpleGraph, ne, nv, outneighbors using Metis: Metis """ graph(G::Graphs.AbstractSimpleGraph) :: Metis.Graph Construct the 1-based CSR representation of the (unweighted) graph `G`. """ Metis.graph(G::AbstractSimpleGraph; kwargs...) = graph(G; kwargs...) include("GraphsCommon.jl") end # module MetisGraphs
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
code
408
# SPDX-License-Identifier: MIT module MetisLightGraphs using LightGraphs: AbstractSimpleGraph, ne, nv, outneighbors using Metis: Metis """ graph(G::LightGraphs.AbstractSimpleGraph) :: Metis.Graph Construct the 1-based CSR representation of the (unweighted) graph `G`. """ Metis.graph(G::AbstractSimpleGraph; kwargs...) = graph(G; kwargs...) include("GraphsCommon.jl") end # module MetisLightGraphs
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
code
554
# SPDX-License-Identifier: MIT module MetisSimpleWeightedGraphs using Graphs: ne, nv, outneighbors using Metis: Metis using SimpleWeightedGraphs: AbstractSimpleWeightedGraph, get_weight """ graph(G::SimpleWeightedGraphs.AbstractSimpleGraph; weights=true) :: Metis.Graph Construct the 1-based CSR representation of the weighted graph `G`. """ function Metis.graph(G::AbstractSimpleWeightedGraph; weights::Bool=true, kwargs...) return graph(G; weights=weights, kwargs...) end include("GraphsCommon.jl") end # module MetisSimpleWeightedGraphs
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
code
651
using Clang.Generators using METIS_jll cd(@__DIR__) metis_include_dir = normpath(METIS_jll.artifact_dir, "include") options = load_options(joinpath(@__DIR__, "generator.toml")) args = get_default_args() push!(args, "-I$(metis_include_dir)") # Compiler flags from Yggdrasil (??) # https://github.com/JuliaPackaging/Yggdrasil/blob/ed9cc4d0cec8d3bbc973a47cb227c42180261782/M/METIS/METIS%405/build_tarballs.jl push!(args, "-DSHARED=1") # push!(args, "-DIDXTYPEWIDTH=32") # 32 and 64 # push!(args, "-DREALTYPEWIDTH=32") # 32 and 64 headers = joinpath.(metis_include_dir, [ "metis.h", ]) ctx = create_context(headers, args, options) build!(ctx)
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
code
5813
using METIS_jll export METIS_jll using CEnum const idx_t = Int32 const real_t = Cfloat function METIS_PartGraphRecursive(nvtxs, ncon, xadj, adjncy, vwgt, vsize, adjwgt, nparts, tpwgts, ubvec, options, edgecut, part) ccall((:METIS_PartGraphRecursive, libmetis), Cint, (Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{real_t}, Ptr{real_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}), nvtxs, ncon, xadj, adjncy, vwgt, vsize, adjwgt, nparts, tpwgts, ubvec, options, edgecut, part) end function METIS_PartGraphKway(nvtxs, ncon, xadj, adjncy, vwgt, vsize, adjwgt, nparts, tpwgts, ubvec, options, edgecut, part) ccall((:METIS_PartGraphKway, libmetis), Cint, (Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{real_t}, Ptr{real_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}), nvtxs, ncon, xadj, adjncy, vwgt, vsize, adjwgt, nparts, tpwgts, ubvec, options, edgecut, part) end function METIS_MeshToDual(ne, nn, eptr, eind, ncommon, numflag, r_xadj, r_adjncy) ccall((:METIS_MeshToDual, libmetis), Cint, (Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{Ptr{idx_t}}, Ptr{Ptr{idx_t}}), ne, nn, eptr, eind, ncommon, numflag, r_xadj, r_adjncy) end function METIS_MeshToNodal(ne, nn, eptr, eind, numflag, r_xadj, r_adjncy) ccall((:METIS_MeshToNodal, libmetis), Cint, (Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{Ptr{idx_t}}, Ptr{Ptr{idx_t}}), ne, nn, eptr, eind, numflag, r_xadj, r_adjncy) end function METIS_PartMeshNodal(ne, nn, eptr, eind, vwgt, vsize, nparts, tpwgts, options, objval, epart, npart) ccall((:METIS_PartMeshNodal, libmetis), Cint, (Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{real_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}), ne, nn, eptr, eind, vwgt, vsize, nparts, tpwgts, options, objval, epart, npart) end function METIS_PartMeshDual(ne, nn, eptr, eind, vwgt, vsize, ncommon, nparts, tpwgts, options, objval, epart, npart) ccall((:METIS_PartMeshDual, libmetis), Cint, (Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{real_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}), ne, nn, eptr, eind, vwgt, vsize, ncommon, nparts, tpwgts, options, objval, epart, npart) end function METIS_NodeND(nvtxs, xadj, adjncy, vwgt, options, perm, iperm) ccall((:METIS_NodeND, libmetis), Cint, (Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}), nvtxs, xadj, adjncy, vwgt, options, perm, iperm) end function METIS_Free(ptr) ccall((:METIS_Free, libmetis), Cint, (Ptr{Cvoid},), ptr) end function METIS_SetDefaultOptions(options) ccall((:METIS_SetDefaultOptions, libmetis), Cint, (Ptr{idx_t},), options) end function METIS_NodeNDP(nvtxs, xadj, adjncy, vwgt, npes, options, perm, iperm, sizes) ccall((:METIS_NodeNDP, libmetis), Cint, (idx_t, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, idx_t, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}), nvtxs, xadj, adjncy, vwgt, npes, options, perm, iperm, sizes) end function METIS_ComputeVertexSeparator(nvtxs, xadj, adjncy, vwgt, options, sepsize, part) ccall((:METIS_ComputeVertexSeparator, libmetis), Cint, (Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}), nvtxs, xadj, adjncy, vwgt, options, sepsize, part) end function METIS_NodeRefine(nvtxs, xadj, vwgt, adjncy, where, hmarker, ubfactor) ccall((:METIS_NodeRefine, libmetis), Cint, (idx_t, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, Ptr{idx_t}, real_t), nvtxs, xadj, vwgt, adjncy, where, hmarker, ubfactor) end @cenum rstatus_et::Int32 begin METIS_OK = 1 METIS_ERROR_INPUT = -2 METIS_ERROR_MEMORY = -3 METIS_ERROR = -4 end @cenum moptype_et::UInt32 begin METIS_OP_PMETIS = 0 METIS_OP_KMETIS = 1 METIS_OP_OMETIS = 2 end @cenum moptions_et::UInt32 begin METIS_OPTION_PTYPE = 0 METIS_OPTION_OBJTYPE = 1 METIS_OPTION_CTYPE = 2 METIS_OPTION_IPTYPE = 3 METIS_OPTION_RTYPE = 4 METIS_OPTION_DBGLVL = 5 METIS_OPTION_NITER = 6 METIS_OPTION_NCUTS = 7 METIS_OPTION_SEED = 8 METIS_OPTION_NO2HOP = 9 METIS_OPTION_MINCONN = 10 METIS_OPTION_CONTIG = 11 METIS_OPTION_COMPRESS = 12 METIS_OPTION_CCORDER = 13 METIS_OPTION_PFACTOR = 14 METIS_OPTION_NSEPS = 15 METIS_OPTION_UFACTOR = 16 METIS_OPTION_NUMBERING = 17 METIS_OPTION_HELP = 18 METIS_OPTION_TPWGTS = 19 METIS_OPTION_NCOMMON = 20 METIS_OPTION_NOOUTPUT = 21 METIS_OPTION_BALANCE = 22 METIS_OPTION_GTYPE = 23 METIS_OPTION_UBVEC = 24 end @cenum mptype_et::UInt32 begin METIS_PTYPE_RB = 0 METIS_PTYPE_KWAY = 1 end @cenum mgtype_et::UInt32 begin METIS_GTYPE_DUAL = 0 METIS_GTYPE_NODAL = 1 end @cenum mctype_et::UInt32 begin METIS_CTYPE_RM = 0 METIS_CTYPE_SHEM = 1 end @cenum miptype_et::UInt32 begin METIS_IPTYPE_GROW = 0 METIS_IPTYPE_RANDOM = 1 METIS_IPTYPE_EDGE = 2 METIS_IPTYPE_NODE = 3 METIS_IPTYPE_METISRB = 4 end @cenum mrtype_et::UInt32 begin METIS_RTYPE_FM = 0 METIS_RTYPE_GREEDY = 1 METIS_RTYPE_SEP2SIDED = 2 METIS_RTYPE_SEP1SIDED = 3 end @cenum mdbglvl_et::UInt32 begin METIS_DBG_INFO = 1 METIS_DBG_TIME = 2 METIS_DBG_COARSEN = 4 METIS_DBG_REFINE = 8 METIS_DBG_IPART = 16 METIS_DBG_MOVEINFO = 32 METIS_DBG_SEPINFO = 64 METIS_DBG_CONNINFO = 128 METIS_DBG_CONTIGINFO = 256 METIS_DBG_MEMORY = 2048 end @cenum mobjtype_et::UInt32 begin METIS_OBJTYPE_CUT = 0 METIS_OBJTYPE_VOL = 1 METIS_OBJTYPE_NODE = 2 end const IDXTYPEWIDTH = 32 const REALTYPEWIDTH = 32 const METIS_VER_MAJOR = 5 const METIS_VER_MINOR = 1 const METIS_VER_SUBMINOR = 0 const METIS_NOPTIONS = 40
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
code
1047
# SPDX-License-Identifier: MIT module LibMetis # Clang.jl auto-generated bindings include("../lib/LibMetis.jl") # Error checking struct MetisError <: Exception fn::Symbol code::Cint end function Base.showerror(io::IO, me::MetisError) print(io, "MetisError: LibMETIS.$(me.fn) returned error code $(me.code): ") if me.code == METIS_ERROR_INPUT print(io, "input error") elseif me.code == METIS_ERROR_MEMORY print(io, "could not allocate the required memory") else print(io, "unknown error") end return end # Macro for checking return codes of ccalls macro check(arg) Meta.isexpr(arg, :call) || throw(ArgumentError("wrong usage of @check")) return quote r = $(esc(arg)) if r != METIS_OK throw(MetisError($(QuoteNode(arg.args[1])), r)) end r end end # Export everything with METIS_ prefix for name in names(@__MODULE__; all=true) if startswith(string(name), "METIS_") @eval export $name end end end # module LibMetis
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
code
7960
# SPDX-License-Identifier: MIT module Metis using SparseArrays using LinearAlgebra: ishermitian, Hermitian, Symmetric using METIS_jll: libmetis # Metis C API: Clang.jl auto-generated bindings and some manual methods include("LibMetis.jl") using .LibMetis using .LibMetis: idx_t, @check # Global options array -- should probably do something better... const options = fill(Cint(-1), METIS_NOPTIONS) options[Int(METIS_OPTION_NUMBERING)+1] = 1 # Julia interface """ Metis.Graph 1-based CSR representation of a graph as defined in section 5.5 "Graph data structure" in the Metis manual. """ struct Graph nvtxs::idx_t xadj::Vector{idx_t} adjncy::Union{Vector{idx_t}, Ptr{Nothing}} vwgt::Union{Vector{idx_t}, Ptr{Nothing}} adjwgt::Union{Vector{idx_t}, Ptr{Nothing}} function Graph(nvtxs, xadj, adjncy, vwgt=C_NULL, adjwgt=C_NULL) return new(nvtxs, xadj, adjncy, vwgt, adjwgt) end end """ Metis.graph(G::SparseMatrixCSC; weights=false, check_hermitian=true) Construct the 1-based CSR representation of the sparse matrix `G`. If `check_hermitian` is `false` the matrix is not checked for being hermitian before constructing the graph. If `weights=true` the entries of the matrix are used as edge weights. """ function graph(G::SparseMatrixCSC; weights::Bool=false, check_hermitian::Bool=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)) vwgt = C_NULL # TODO: Vertex weights could be passed as input argument adjwgt = weights ? Vector{idx_t}(undef, nnz(G)) : C_NULL adjncy_i = 0 @inbounds for j in 1:N n_rows = 0 for k in G.colptr[j] : (G.colptr[j+1] - 1) i = G.rowval[k] i == j && continue # skip self edges n_rows += 1 adjncy_i += 1 adjncy[adjncy_i] = i if weights adjwgt[adjncy_i] = G.nzval[k] end end xadj[j+1] = xadj[j] + n_rows end resize!(adjncy, adjncy_i) weights && resize!(adjwgt, adjncy_i) return Graph(idx_t(N), xadj, adjncy, vwgt, adjwgt) end const HermOrSymCSC{Tv, Ti} = Union{ Hermitian{Tv, SparseMatrixCSC{Tv, Ti}}, Symmetric{Tv, SparseMatrixCSC{Tv, Ti}}, } if VERSION < v"1.10" # From https://github.com/JuliaSparse/SparseArrays.jl/blob/313a04f4a78bbc534f89b6b4d9c598453e2af17c/src/linalg.jl#L1106-L1117 # MIT license: https://github.com/JuliaSparse/SparseArrays.jl/blob/main/LICENSE.md function nzrangeup(A, i, excl=false) r = nzrange(A, i); r1 = r.start; r2 = r.stop rv = rowvals(A) @inbounds r2 < r1 || rv[r2] <= i - excl ? r : r1:(searchsortedlast(view(rv, r1:r2), i - excl) + r1-1) end function nzrangelo(A, i, excl=false) r = nzrange(A, i); r1 = r.start; r2 = r.stop rv = rowvals(A) @inbounds r2 < r1 || rv[r1] >= i + excl ? r : (searchsortedfirst(view(rv, r1:r2), i + excl) + r1-1):r2 end else using SparseArrays: nzrangeup, nzrangelo end """ Metis.graph(G::Union{Hermitian, Symmetric}; weights::Bool=false) Construct the 1-based CSR representation of the `Hermitian` or `Symmetric` wrapped sparse matrix `G`. Weights are not currently supported for this method so passing `weights=true` will throw an error. """ function graph(H::HermOrSymCSC; weights::Bool=false) # This method is derived from the method `SparseMatrixCSC(::HermOrSymCSC)` from # SparseArrays.jl # (https://github.com/JuliaSparse/SparseArrays.jl/blob/313a04f4a78bbc534f89b6b4d9c598453e2af17c/src/sparseconvert.jl#L124-L173) # with MIT license # (https://github.com/JuliaSparse/SparseArrays.jl/blob/main/LICENSE.md). weights && throw(ArgumentError("weights not supported yet")) # Extract data A = H.data upper = H.uplo == 'U' rowval = rowvals(A) m, n = size(A) @assert m == n # New colptr for the full matrix newcolptr = Vector{idx_t}(undef, n + 1) newcolptr[1] = 1 # SparseArrays.nzrange for the upper/lower part excluding the diagonal nzrng = if upper (A, col) -> nzrangeup(A, col, #=exclude diagonal=# true) else (A, col) -> nzrangelo(A, col, #=exclude diagonal=# true) end # If the upper part is stored we loop forward, otherwise backwards colrange = upper ? (1:1:n) : (n:-1:1) @inbounds for col in colrange r = nzrng(A, col) # Number of entries in the stored part of this column, excluding the diagonal entry newcolptr[col + 1] = length(r) # Increment columnptr corresponding to the stored rows for k in r row = rowval[k] @assert upper ? row < col : row > col @assert row != col # Diagonal entries should not be here newcolptr[row + 1] += 1 end end # Accumulate the colptr and allocate new rowval cumsum!(newcolptr, newcolptr) nz = newcolptr[n + 1] - 1 newrowval = Vector{idx_t}(undef, nz) # Populate the rowvals @inbounds for col = 1:n newk = newcolptr[col] for k in nzrng(A, col) row = rowval[k] @assert col != row newrowval[newk] = row newk += 1 ni = newcolptr[row] newrowval[ni] = col newcolptr[row] = ni + 1 end newcolptr[col] = newk end # Shuffle back the colptrs @inbounds for j = n:-1:1 newcolptr[j+1] = newcolptr[j] end newcolptr[1] = 1 # Return Graph N = n xadj = newcolptr adjncy = newrowval vwgt = C_NULL adjwgt = C_NULL return Graph(idx_t(N), xadj, adjncy, vwgt, adjwgt) end """ perm, iperm = Metis.permutation(G) Compute the fill reducing permutation `perm` and its inverse `iperm` of `G`. """ permutation(G) = permutation(graph(G)) function permutation(G::Graph) perm = Vector{idx_t}(undef, G.nvtxs) iperm = Vector{idx_t}(undef, G.nvtxs) @check METIS_NodeND(Ref{idx_t}(G.nvtxs), G.xadj, G.adjncy, G.vwgt, options, perm, iperm) return perm, iperm end """ Metis.partition(G, n; alg = :KWAY) Partition the graph `G` in `n` parts. The partition algorithm is defined by the `alg` keyword: - :KWAY: multilevel k-way partitioning - :RECURSIVE: multilevel recursive bisection """ partition(G, nparts; alg = :KWAY) = partition(graph(G), nparts, alg = alg) function partition(G::Graph, nparts::Integer; alg = :KWAY) part = Vector{idx_t}(undef, G.nvtxs) nparts == 1 && return fill!(part, 1) # https://github.com/JuliaSparse/Metis.jl/issues/49 edgecut = fill(idx_t(0), 1) if alg === :RECURSIVE @check METIS_PartGraphRecursive(Ref{idx_t}(G.nvtxs), Ref{idx_t}(1), G.xadj, G.adjncy, G.vwgt, C_NULL, G.adjwgt, Ref{idx_t}(nparts), C_NULL, C_NULL, options, edgecut, part) elseif alg === :KWAY @check METIS_PartGraphKway(Ref{idx_t}(G.nvtxs), Ref{idx_t}(1), G.xadj, G.adjncy, G.vwgt, C_NULL, G.adjwgt, Ref{idx_t}(nparts), C_NULL, C_NULL, options, edgecut, part) else throw(ArgumentError("unknown algorithm $(repr(alg))")) end return part end """ Metis.separator(G) Compute a vertex separator of the graph `G`. """ separator(G) = separator(graph(G)) function separator(G::Graph) part = Vector{idx_t}(undef, G.nvtxs) sepsize = fill(idx_t(0), 1) # METIS_ComputeVertexSeparator segfaults with 1-based indexing xadj = G.xadj .- idx_t(1) adjncy = G.adjncy .- idx_t(1) @check METIS_ComputeVertexSeparator(Ref{idx_t}(G.nvtxs), xadj, adjncy, G.vwgt, options, sepsize, part) part .+= 1 return part end # Compatibility for Julias that doesn't support package extensions if !(isdefined(Base, :get_extension)) include("../ext/MetisGraphs.jl") include("../ext/MetisLightGraphs.jl") end end # module
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
code
3292
using Metis using Random using Test using SparseArrays using LinearAlgebra: Symmetric, Hermitian import LightGraphs, Graphs @testset "Metis.graph(::SparseMatrixCSC)" begin rng = MersenneTwister(0) S = sprand(rng, Int, 10, 10, 0.2); S = S + S'; fill!(S.nzval, 1) foreach(i -> S[i, i] = 0, 1:10); dropzeros!(S) g = Metis.graph(S) gw = Metis.graph(S; weights=true) @test g.xadj == gw.xadj @test g.adjncy == gw.adjncy @test g.adjwgt == C_NULL @test gw.adjwgt == ones(Int, length(gw.adjncy)) G = SparseMatrixCSC(10, 10, g.xadj, g.adjncy, ones(Int, length(g.adjncy))) GW = SparseMatrixCSC(10, 10, gw.xadj, gw.adjncy, gw.adjwgt) @test iszero(S - G) @test iszero(S - GW) end @testset "Metis.graph(::Union{Hermitian, Symmetric})" begin rng = MersenneTwister(0) for T in (Symmetric, Hermitian), uplo in (:U, :L) S = sprand(rng, Int, 10, 10, 0.2); fill!(S.nzval, 1) TS = T(S, uplo) CSCS = SparseMatrixCSC(TS) @test TS == CSCS g1 = Metis.graph(TS) g2 = Metis.graph(CSCS) @test g1.nvtxs == g2.nvtxs @test g1.xadj == g2.xadj @test g1.adjncy == g2.adjncy @test g1.vwgt == g2.vwgt == C_NULL @test g1.adjwgt == g2.adjwgt == C_NULL @test_throws ArgumentError Metis.graph(TS; weights = true) end end @testset "Metis.permutation" begin rng = MersenneTwister(0) S = sprand(rng, 10, 10, 0.5); S = S + S'; fill!(S.nzval, 1) perm, iperm = Metis.permutation(S) @test isperm(perm) @test isperm(iperm) @test S == S[perm,perm][iperm,iperm] end @testset "Metis.partition" begin T = Graphs.smallgraph(:tutte) S = Graphs.adjacency_matrix(T) SG = Metis.graph(S; weights=true) TL = LightGraphs.smallgraph(:tutte) for G in (S, T, TL, SG), alg in (:RECURSIVE, :KWAY), nparts in (1, 3, 4) partition = Metis.partition(G, nparts, alg = alg) @test extrema(partition) == (1, nparts) @test all(x -> findfirst(==(x), partition) !== nothing, 1:nparts) end # With weights if isdefined(Base, :get_extension) import SimpleWeightedGraphs G1 = SimpleWeightedGraphs.SimpleWeightedGraph(Graphs.nv(T)) G2 = SimpleWeightedGraphs.SimpleWeightedGraph(Graphs.nv(T)) for edge in Graphs.edges(T) i, j = Tuple(edge) SimpleWeightedGraphs.add_edge!(G1, i, j, 1) SimpleWeightedGraphs.add_edge!(G2, i, j, i+j) end for alg in (:RECURSIVE, :KWAY), nparts in (3, 4) unwpartition = Metis.partition(T, nparts, alg = alg) partition = Metis.partition(G1, nparts, alg = alg) @test partition == unwpartition partition = Metis.partition(G2, nparts, alg = alg) @test partition != unwpartition @test extrema(partition) == (1, nparts) @test all(x -> findfirst(==(x), partition) !== nothing, 1:nparts) end end end @testset "Metis.separator" begin T = Graphs.smallgraph(:tutte) S = Graphs.adjacency_matrix(T) SG = Metis.graph(S; weights=true) T = Graphs.smallgraph(:tutte) TL = LightGraphs.smallgraph(:tutte) for G in (S, T, TL, SG) parts = Metis.separator(G) @test extrema(parts) == (1, 3) end end
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT", "Apache-2.0" ]
1.5.0
54aca4fd53d39dcd2c3f1bef367b6921e8178628
docs
6340
# Metis | **Build Status** | |:--------------------------------------------------------------------- | | [![][gh-actions-img]][gh-actions-url] [![][codecov-img]][codecov-url] | *Metis.jl* is a Julia wrapper to the [Metis library][metis-url] which is a library for partitioning unstructured graphs, partitioning meshes, and computing fill-reducing orderings of sparse matrices. ## Graph partitioning `Metis.partition` calculates graph partitions. As an example, here we partition a small graph into two, three and four parts, and visualize the result: | ![][partition2-url] | ![][partition3-url] | ![][partition4-url] | |:----------------------- |:----------------------- |:----------------------- | | `Metis.partition(g, 2)` | `Metis.partition(g, 3)` | `Metis.partition(g, 4)` | `Metis.partition` calls `METIS_PartGraphKway` or `METIS_PartGraphRecursive` from the Metis C API, depending on the optional keyword argument `alg`: - `alg = :KWAY`: multilevel k-way partitioning (`METIS_PartGraphKway`). - `alg = :RECURSIVE`: multilevel recursive bisection (`METIS_PartGraphRecursive`). ## Vertex separator `Metis.separator` calculates a [vertex separator](https://en.wikipedia.org/wiki/Vertex_separator) of a graph. `Metis.separator` calls `METIS_ComputeVertexSeparator` from the Metis C API. As an example, here we calculate a vertex separator (green) of a small graph: | ![][separator-url] | |:-------------------- | | `Metis.separator(g)` | ## Fill reducing permutation `Metis.permutation` calculates the fill reducing permutation for a sparse matrices. `Metis.permutation` calls `METIS_NodeND` from the Metis C API. As an example, we calculate the fill reducing permutation for a sparse matrix `S` originating from a typical (small) FEM problem, and visualize the sparsity pattern for the original matrix and the permuted matrix: ```julia perm, iperm = Metis.permutation(S) ``` | <pre>⠛⣤⢠⠄⠀⣌⠃⢠⠀⠐⠈⠀⠀⠀⠀⠉⠃⠀⠀⠀⠀⠀⠀⠀⠀⠘⠀⠂⠔⠀<br>⠀⠖⠻⣦⡅⠘⡁⠀⠀⠀⠀⠐⠀⠁⠀⢂⠀⠀⠠⠀⠀⠀⠁⢀⠀⢀⠀⠀⠄⢣<br>⡀⢤⣁⠉⠛⣤⡡⢀⠀⠂⠂⠀⠂⠃⢰⣀⠀⠔⠀⠀⠀⠀⠀⠀⠀⠀⠀⠄⠄⠀<br>⠉⣀⠁⠈⠁⢊⠱⢆⡰⠀⠈⠀⠀⠀⠀⢈⠉⡂⠀⠐⢀⡞⠐⠂⠀⠄⡀⠠⠂⠀<br>⢀⠀⠀⠀⠠⠀⠐⠊⠛⣤⡔⠘⠰⠒⠠⠀⡈⠀⠀⠀⠉⠉⠘⠂⠀⠀⠀⡐⢈⠀<br>⠂⠀⢀⠀⠈⠀⠂⠀⣐⠉⢑⣴⡉⡈⠁⡂⠒⠀⠁⢠⡄⠀⠐⠀⠠⠄⠀⠁⢀⡀<br>⠀⠀⠄⠀⠬⠀⠀⠀⢰⠂⡃⠨⣿⣿⡕⠂⠀⠨⠌⠈⠆⠀⠄⡀⠑⠀⠀⠘⠀⠀<br>⡄⠀⠠⢀⠐⢲⡀⢀⠀⠂⠡⠠⠱⠉⢱⢖⡀⠀⡈⠃⠀⠀⠀⢁⠄⢀⣐⠢⠀⠀<br>⠉⠀⠀⠀⢀⠄⠣⠠⠂⠈⠘⠀⡀⡀⠀⠈⠱⢆⣰⠠⠰⠐⠐⢀⠀⢀⢀⠀⠌⠀<br>⠀⠀⠀⠂⠀⠀⢀⠀⠀⠀⠁⣀⡂⠁⠦⠈⠐⡚⠱⢆⢀⢀⠡⠌⡀⡈⠸⠁⠂⠀<br>⠀⠀⠀⠀⠀⠀⣠⠴⡇⠀⠀⠉⠈⠁⠀⠀⢐⠂⠀⢐⣻⣾⠡⠀⠈⠀⠄⠀⡉⠄<br>⠀⠀⠁⢀⠀⠀⠰⠀⠲⠀⠐⠀⠀⠡⠄⢀⠐⢀⡁⠆⠁⠂⠱⢆⡀⣀⠠⠁⠉⠇<br>⣀⠀⠀⢀⠀⠀⠀⠄⠀⠀⠀⠆⠑⠀⠀⢁⠀⢀⡀⠨⠂⠀⠀⢨⠿⢇⠀⡸⠀⢀<br>⠠⠀⠀⠀⠀⠄⠀⡈⢀⠠⠄⠀⣀⠀⠰⡘⠀⠐⠖⠂⠀⠁⠄⠂⣀⡠⠻⢆⠄⠃<br>⠐⠁⠤⣁⠀⠁⠈⠀⠂⠐⠀⠰⠀⠀⠀⠀⠂⠁⠈⠀⠃⠌⠧⠄⠀⢀⠤⠁⠱⢆</pre> | <pre>⣕⢝⠀⠀⢸⠔⡵⢊⡀⠂⠀⠀⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣑⠑<br>⠀⠀⠑⢄⠀⠳⠡⢡⣒⣃⢣⠯⠆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠌<br>⢒⠖⢤⡀⠑⢄⢶⡈⣂⠎⢎⠉⠩⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀<br>⡱⢋⠅⣂⡘⠳⠻⢆⡥⣈⠆⡨⡩⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠀<br>⠠⠈⠼⢸⡨⠜⡁⢫⣻⢞⢔⠀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⠠<br>⠀⠀⡭⡖⡎⠑⡈⡡⠐⠑⠵⣧⣜⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀<br>⠀⠁⠈⠁⠃⠂⠃⠊⠀⠘⠒⠙⠛⢄⠀⠀⢄⠀⠤⢠⠀⢄⢀⢀⠀⡀⠀⠀⢄⢄<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⢄⠊⠀⣂⠅⢓⣤⡄⠢⠠⠀⠌⠉⢀⢁<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⠊⠀⠑⢄⠁⣋⠀⢀⢰⢄⢔⢠⡖⢥⠀⠁<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣃⠌⠜⡥⢠⠛⣤⠐⣂⡀⠀⡀⡁⠍⠤⠒⠀<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢄⠙⣴⠀⢀⠰⢠⠿⣧⡅⠁⠂⢂⠂⠋⢃⢀<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢐⠠⡉⠐⢖⠀⠈⠅⠉⢕⢕⠝⠘⡒⠠⠀⠀<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⠀⠂⠐⣑⠄⠨⠨⢀⣓⠁⣕⢝⡥⢉⠁⠠<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡆⠁⠜⣍⠃⡅⡬⠀⠘⡈⡅⢋⠛⣤⡅⠒<br>⢕⠘⡂⠄⠀⠀⠁⠀⠀⡂⠀⢠⠀⢕⠄⢐⠄⠀⠘⠀⠉⢐⠀⠀⠁⡀⢡⠉⢟⣵</pre> | |:---------------------- |:--------------------------------- | | `S` (5% stored values) | `S[perm,perm]` (5% stored values) | We can also visualize the sparsity pattern of the Cholesky factorization of the same matrix. It is here clear that using the fill reducing permutation results in a sparser factorization: |<pre>⠙⢤⢠⡄⠀⣜⠃⢠⠀⠐⠘⠀⠀⠀⠀⠛⠃⠀⠀⠀⠀⠀⠀⠀⠀⠘⠀⠂⡔⠀<br>⠀⠀⠙⢦⡇⠾⡃⠰⠀⠀⠀⠐⠀⠃⠀⢂⠀⠀⠠⠀⠀⠀⠃⢀⠀⢀⠀⠀⠆⢣<br>⠀⠀⠀⠀⠙⢼⣣⢠⠀⣂⣂⢘⡂⡃⢰⣋⡀⣔⢠⠀⠀⠀⡃⠈⠀⢈⠀⡄⣄⡋<br>⠀⠀⠀⠀⠀⠀⠑⢖⡰⠉⠉⠈⠁⠁⢘⢙⠉⡊⢐⢐⢀⣞⠱⠎⠀⠌⡀⡣⡊⠉<br>⠀⠀⠀⠀⠀⠀⠀⠀⠙⢤⣴⢸⣴⡖⢠⣤⡜⢣⠀⠀⠛⠛⡜⠂⠀⢢⠀⡔⢸⡄<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢼⣛⣛⣛⣛⣓⣚⡃⢠⣖⣒⣓⢐⢠⣜⠀⡃⢘⣓<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣾⣿⣿⠀⣿⢸⣿<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣒⣿⣺⣿<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣤⣿⣼⣿<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿</pre> | <pre>⠑⢝⠀⠀⢸⠔⡵⢊⡀⡂⠀⠀⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣕⢕<br>⠀⠀⠑⢄⠀⠳⠡⢡⣒⣃⢣⠯⠆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠌<br>⠀⠀⠀⠀⠑⢄⢶⡘⣂⡎⢎⡭⠯⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠶⠴<br>⠀⠀⠀⠀⠀⠀⠙⢎⣷⣏⢷⣯⡫⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠛⡛<br>⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⢼⣧⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠤⡤<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⢿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣭⣯<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢄⠀⠀⢄⠀⠤⢠⠀⢄⢀⢀⠀⡀⠀⠀⢟⢟<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⢄⠊⠀⣂⠅⢓⣤⡄⠢⠠⠀⠌⠉⢀⢁<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⢄⠉⣋⠀⢁⢰⢔⢔⢠⡖⢥⠁⠃<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢤⠘⣶⡂⠠⡀⣡⠭⣤⢓⢗<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢷⡇⡇⣢⣢⠂⣯⣷⣶<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⢕⢟⢝⣒⠭⠭⡭<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⢝⣿⣿⡭⡯<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿<br>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿</pre> | |:----------------------------- |:--------------------------------------- | | `chol(S)` (16% stored values) | `chol(S[perm,perm])` (6% stored values) | ## Direct access to the Metis C API For more fine tuned usage of Metis consider calling the C API directly. The following functions are currently exposed: - `METIS_PartGraphRecursive` - `METIS_PartGraphKway` - `METIS_ComputeVertexSeparator` - `METIS_NodeND` all with the same arguments and argument order as described in the [Metis manual][metis-manual-url]. [gh-actions-img]: https://github.com/JuliaSparse/Metis.jl/workflows/CI/badge.svg [gh-actions-url]: https://github.com/JuliaSparse/Metis.jl/actions?query=workflow%3ACI [codecov-img]: http://codecov.io/github/JuliaSparse/Metis.jl/coverage.svg?branch=master [codecov-url]: http://codecov.io/github/JuliaSparse/Metis.jl?branch=master [metis-url]: http://glaros.dtc.umn.edu/gkhome/metis/metis/overview [metis-manual-url]: http://glaros.dtc.umn.edu/gkhome/fetch/sw/metis/manual.pdf [S-url]: https://user-images.githubusercontent.com/11698744/38196722-dd9877c2-3684-11e8-8c02-a767604824d1.png [Spp-url]: https://user-images.githubusercontent.com/11698744/38196723-ddb62fba-3684-11e8-89ff-181128644294.png [C-url]: https://user-images.githubusercontent.com/11698744/38196720-dd5dd748-3684-11e8-8413-a52d336abe49.png [Cpp-url]: https://user-images.githubusercontent.com/11698744/38196721-dd7ac16e-3684-11e8-8a35-761e97d11235.png [partition2-url]: https://user-images.githubusercontent.com/11698744/38196819-65950f1e-3685-11e8-8db4-6aa9563bbd62.png [partition3-url]: https://user-images.githubusercontent.com/11698744/38196820-65b11c9a-3685-11e8-95a0-b3b280359b31.png [partition4-url]: https://user-images.githubusercontent.com/11698744/38196821-65ddc1dc-3685-11e8-8eb1-ce44ef1646f3.png [separator-url]: https://user-images.githubusercontent.com/11698744/38196822-65fffc34-3685-11e8-9575-4dba41faec41.png [vertex-separator-url]: https://en.wikipedia.org/wiki/Vertex_separator
Metis
https://github.com/JuliaSparse/Metis.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
1199
module MeshIO using GeometryBasics using ColorTypes using Printf using GeometryBasics: raw, value, decompose_normals, convert_simplex using FileIO: FileIO, @format_str, Stream, File, stream, skipmagic import Base.show include("util.jl") include("io/off.jl") include("io/ply.jl") include("io/stl.jl") include("io/obj.jl") include("io/2dm.jl") include("io/msh.jl") include("io/gts.jl") include("io/ifs.jl") """ load(fn::File{MeshFormat}; pointtype=Point3f, uvtype=Vec2f, facetype=GLTriangleFace, normaltype=Vec3f) """ function load(fn::File{format}; element_types...) where {format} open(fn) do s skipmagic(s) load(s; element_types...) end end function save(fn::File{format}, msh::AbstractMesh) where {format} open(fn, "w") do s save(s, msh) end end if Base.VERSION >= v"1.4.2" include("precompile.jl") _precompile_() end # `filter(f, ::Tuple)` is not available on Julia 1.3 # https://github.com/JuliaLang/julia/pull/29259 function filtertuple(f, xs::Tuple) return @static if VERSION < v"1.4.0-DEV.551" Base.afoldl((ys, x) -> f(x) ? (ys..., x) : ys, (), xs...) else filter(f, xs) end end end # module
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
1594
macro warnpcfail(ex::Expr) modl = __module__ file = __source__.file === nothing ? "?" : String(__source__.file) line = __source__.line quote $(esc(ex)) || @warn """precompile directive $($(Expr(:quote, ex))) failed. Please report an issue in $($modl) (after checking for duplicates) or remove this directive.""" _file=$file _line=$line end end function _precompile_() ccall(:jl_generating_output, Cint, ()) == 1 || return nothing if isdefined(FileIO, :action) @warnpcfail precompile(load, (File{format"2DM",IOStream},)) @warnpcfail precompile(load, (File{format"MSH",IOStream},)) @warnpcfail precompile(load, (File{format"OBJ",IOStream},)) @warnpcfail precompile(load, (File{format"OFF",IOStream},)) @warnpcfail precompile(load, (File{format"PLY_ASCII",IOStream},)) @warnpcfail precompile(load, (File{format"PLY_BINARY",IOStream},)) @warnpcfail precompile(load, (File{format"STL_ASCII",IOStream},)) @warnpcfail precompile(load, (File{format"STL_BINARY",IOStream},)) else @warnpcfail precompile(load, (File{format"2DM"},)) @warnpcfail precompile(load, (File{format"MSH"},)) @warnpcfail precompile(load, (File{format"OBJ"},)) @warnpcfail precompile(load, (File{format"OFF"},)) @warnpcfail precompile(load, (File{format"PLY_ASCII"},)) @warnpcfail precompile(load, (File{format"PLY_BINARY"},)) @warnpcfail precompile(load, (File{format"STL_ASCII"},)) @warnpcfail precompile(load, (File{format"STL_BINARY"},)) end end
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
2127
# Graphics backends like OpenGL only have one index buffer so the indices to # positions, normals and texture coordinates cannot be different. E.g. a face # cannot use positional indices (1, 2, 3) and normal indices (1, 1, 2). In that # case we need to remap normals such that new_normals[1, 2, 3] = normals[[1, 1, 2]] # ... _typemin(x) = typemin(x) _typemin(::Type{OffsetInteger{N, T}}) where {N, T} = typemin(T) - N merge_vertex_attribute_indices(faces...) = merge_vertex_attribute_indices(faces) function merge_vertex_attribute_indices(faces::Tuple) FaceType = eltype(faces[1]) IndexType = eltype(FaceType) D = length(faces) N = length(faces[1]) # (pos_idx, normal_idx, uv_idx, ...) -> new_idx vertex_index_map = Dict{NTuple{D, UInt32}, IndexType}() # faces after remapping (0 based assumed) new_faces = sizehint!(FaceType[], N) temp = IndexType[] # keeping track of vertex indices of a face counter = _typemin(IndexType) # for remaping attribs, i.e. `new_attrib = old_attrib[index2vertex[attrib_index]]` index2vertex = ntuple(_ -> sizehint!(UInt32[], N), D) for i in eachindex(faces[1]) # (pos_faces[i], normal_faces[i], uv_faces[i], ...) attrib_faces = getindex.(faces, i) empty!(temp) for j in eachindex(attrib_faces[1]) # (pos_index, normal_idx, uv_idx, ...) # = (pos_faces[i][j], normal_faces[i][j], uv_faces[i][j], ...) vertex = GeometryBasics.value.(getindex.(attrib_faces, j)) # 1 based # if combination of indices in vertex is new, make a new index if !haskey(vertex_index_map, vertex) vertex_index_map[vertex] = counter counter = IndexType(counter + 1) push!.(index2vertex, vertex) end # keep track of the (new) index for this vertex push!(temp, vertex_index_map[vertex]) end # store face with new indices push!(new_faces, FaceType(temp...)) end sizehint!(new_faces, length(new_faces)) return new_faces, index2vertex end
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
1422
# | Read a .2dm (SMS Aquaveo) mesh-file and construct a @Mesh@ function load(st::Stream{format"2DM"}; facetype=GLTriangleFace, pointtype=Point3f) faces = facetype[] vertices = pointtype[] io = stream(st) for line = readlines(io) if !isempty(line) && !all(iscntrl, line) line = chomp(line) w = split(line) if w[1] == "ND" push!(vertices, pointtype(parse.(eltype(pointtype), w[3:end]))) elseif w[1] == "E3T" push!(faces, GLTriangleFace(parse.(Cuint, w[3:5]))) elseif w[1] == "E4Q" push!(faces, convert_simplex(facetype, QuadFace{Cuint}(parse.(Cuint, w[3:6])))...) else continue end end end return Mesh(vertices, faces) end function print_face(io::IO, i::Int, f::TriangleFace) println(io, "E3T $i ", join(Int.(value.(f)), " ")) end function print_face(io::IO, i::Int, f::QuadFace) println(io, "E4Q $i ", join(Int.(value.(f)), " ")) end # | Write @Mesh@ to an IOStream function save(st::Stream{format"2DM"}, m::AbstractMesh) io = stream(st) println(io, "MESH2D") for (i, f) in enumerate(faces(m)) print_face(io, i, f) end for (i, v) in enumerate(coordinates(m)) println(io, "ND $i ", join(v, " ")) end return end show(io::IO, ::MIME"model/2dm", mesh::AbstractMesh) = save(io, mesh)
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
2309
function parseGtsLine( s::AbstractString, C, T=eltype(C) ) firstInd = findfirst( isequal(' '), s ) secondInd = findnext( isequal(' '), s, firstInd+1 ) firstNum = parse( T, s[1:firstInd] ) if secondInd != nothing secondNum = parse( T, s[firstInd:secondInd] ) thirdNum = parse( T, s[secondInd:end] ) return C([firstNum, secondNum, thirdNum]) else secondNum = parse( T, s[firstInd:end] ) return C([firstNum, secondNum]) end end function load( st::Stream{format"GTS"}, MeshType=GLNormalMesh ) io = stream(st) head = readline( io ) FT = facetype(MeshType) VT = vertextype(MeshType) nVertices, nEdges, nFacets = parseGtsLine( head, Tuple{Int,Int,Int} ) iV = iE = iF = 1 vertices = Vector{VT}(undef, nVertices) edges = Vector{Vector{Int}}(undef, nEdges) facets = Vector{Vector{Int}}(undef, nFacets) for full_line::String in eachline(io) # read a line, remove newline and leading/trailing whitespaces line = strip(chomp(full_line)) !isascii(line) && error("non valid ascii in obj") if !startswith(line, "#") && !isempty(line) && !all(iscntrl, line) #ignore comments if iV <= nVertices vertices[iV] = parseGtsLine( line, VT ) iV += 1 elseif iV > nVertices && iE <= nEdges edges[iE] = parseGtsLine( line, Array{Int} ) iE += 1 elseif iE > nEdges && iF <= nFacets facets[iF] = parseGtsLine( line, Array{Int} ) iF += 1 end # if end # if end # for faces = [ FT( union( edges[facets[i][1]], edges[facets[i][2]], edges[facets[i][3]] ) ) for i in 1:length(facets) ] # orientation not guaranteed return MeshType( vertices, faces ) end function save( st::Stream{format"GTS"}, mesh::AbstractMesh ) # convert faces to edges and facets edges = [[ 0, 0 ]] # TODO facets = [[ 0, 0 ]] # TODO # write to file io = stream( st ) println( io, length(mesh.vertices), legth(edges), length(mesh.faces) ) for v in mesh.vertices println( io, v[1], v[2], v[3] ) end for e in edges println( io, e[1], e[2] ) end for f in facets println( io, f[1], f[2], f[3] ) end end
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
1347
function load(fs::Stream{format"IFS"}, MeshType = GLNormalMesh) io = stream(fs) function str() n = read(io, UInt32) String(read(io, UInt8, n)) end name = str() # just skip name for now vertices = str() if vertices != "VERTICES\0" error("$(filename(fs)) does not seem to be of format IFS") end nverts = read(io, UInt32) verts_float = read(io, Float32, nverts * 3) verts = reinterpret(Point3f0, verts_float) tris = str() if tris != "TRIANGLES\0" error("$(filename(fs)) does not seem to be of format IFS") end nfaces = read(io, UInt32) faces_int = read(io, UInt32, nfaces * 3) faces = reinterpret(GLTriangle, faces_int) MeshType(vertices = verts, faces = faces) end function save(fs::Stream{format"IFS"}, msh::AbstractMesh; meshname = "mesh") io = stream(fs) function write0str(s) s0 = s * "\0" write(io, UInt32(length(s0))) write(io, s0) end vts = decompose(Point3f0, msh) fcs = decompose(GLTriangle, msh) # write the header write0str("IFS") write(io, 1f0) write0str(meshname) write0str("VERTICES") write(io, UInt32(length(vts))) write(io, reinterpret(Float32, vts)) write0str("TRIANGLES") write(io, UInt32(length(fcs))) write(io, reinterpret(UInt32, fcs)) end
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
2987
@enum MSHBlockType MSHFormatBlock MSHNodesBlock MSHElementsBlock MSHUnknownBlock function load(fs::Stream{format"MSH"}; facetype=GLTriangleFace, pointtype=Point3f) #GMSH MSH format (version 4) #http://gmsh.info/doc/texinfo/gmsh.html#MSH-file-format io = stream(fs) faces = facetype[] nodes = pointtype[] node_tags = Int[] while !eof(io) BlockType = parse_blocktype!(io) if BlockType == MSHNodesBlock parse_nodes!(io, nodes, node_tags) elseif BlockType == MSHElementsBlock parse_elements!(io, faces) else skip_block!(io) end end remap_faces!(faces, node_tags) return Mesh(nodes, faces) end function parse_blocktype!(io) header = readline(io) if header == "\$MeshFormat" return MSHFormatBlock elseif header == "\$Nodes" return MSHNodesBlock elseif header == "\$Elements" return MSHElementsBlock else return MSHUnknownBlock end end function skip_block!(io) while true line = readline(io) if line[1:4] == "\$End" break end end return nothing end function parse_nodes!(io, nodes, node_tags) entity_blocks, num_nodes, min_node_tag, max_node_tag = parse.(Int, split(readline(io))) for index_entity in 1:entity_blocks dim, tag, parametric, nodes_in_block = parse.(Int, split(readline(io))) for i in 1:nodes_in_block push!(node_tags, parse(eltype(node_tags), readline(io))) end for i in 1:nodes_in_block xyz = parse.(eltype(eltype(nodes)), split(readline(io))) push!(nodes, xyz) end end endblock = readline(io) if endblock != "\$EndNodes" error("expected end block tag, got $endblock") end return nodes, node_tags end function parse_elements!(io, faces::Vector{T}) where T <: TriangleFace num_elements = parse.(Int, split(readline(io))) num_entity_blocks, num_elements, min_element_tag, max_element_tag = num_elements for index_entity in 1:num_entity_blocks dim, tag, element_type, elements_in_block = parse.(Int, split(readline(io))) if element_type == 2 # Triangles for i in 1:elements_in_block tag, n1, n2, n3 = parse.(Int, split(readline(io))) push!(faces, (n1, n2, n3)) end else # for now we ignore all other elements (points, lines, hedrons, etc) for i in 1:elements_in_block readline(io) end end end endblock = readline(io) if endblock != "\$EndElements" error("expected end block tag, got $endblock") end return faces end function remap_faces!(faces, node_tags) node_map = indexin(1:maximum(node_tags), node_tags) for (i, face) in enumerate(faces) faces[i] = (node_map[face[1]], node_map[face[2]], node_map[face[3]]) end return faces end
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
4733
############################## # # obj-Files # ############################## function load(io::Stream{format"OBJ"}; facetype=GLTriangleFace, pointtype=Point3f, normaltype=Vec3f, uvtype=Any) points, v_normals, uv, faces = pointtype[], normaltype[], uvtype[], facetype[] f_uv_n_faces = (faces, facetype[], facetype[]) last_command = "" attrib_type = nothing for full_line in eachline(stream(io)) # read a line, remove newline and leading/trailing whitespaces line = strip(chomp(full_line)) !isascii(line) && error("non valid ascii in obj") if !startswith(line, "#") && !isempty(line) && !all(iscntrl, line) #ignore comments lines = split(line) command = popfirst!(lines) #first is the command, rest the data if "v" == command # mesh always has vertices push!(points, pointtype(parse.(eltype(pointtype), lines))) elseif "vn" == command push!(v_normals, normaltype(parse.(eltype(normaltype), lines))) elseif "vt" == command if length(lines) == 2 if uvtype == Any uvtype = Vec2f uv = uvtype[] end push!(uv, Vec{2,eltype(uvtype)}(parse.(eltype(uvtype), lines))) elseif length(lines) == 3 if uvtype == Any uvtype = Vec3f uv = uvtype[] end push!(uv, Vec{3,eltype(uvtype)}(parse.(eltype(uvtype), lines))) else error("Unknown UVW coordinate: $lines") end elseif "f" == command # mesh always has faces if any(x-> occursin("//", x), lines) fs = process_face_normal(lines) elseif any(x-> occursin("/", x), lines) fs = process_face_uv_or_normal(lines) else append!(faces, triangulated_faces(facetype, lines)) continue end for i = 1:length(first(fs)) append!(f_uv_n_faces[i], triangulated_faces(facetype, getindex.(fs, i))) end else #TODO end end end point_attributes = Dict{Symbol, Any}() non_empty_faces = filtertuple(!isempty, f_uv_n_faces) # Do we have faces with different indices for positions and normals # (and texture coordinates) per vertex? if length(non_empty_faces) > 1 # map vertices with distinct indices for possition and normal (and uv) # to new indices, updating faces along the way faces, attrib_maps = merge_vertex_attribute_indices(non_empty_faces) # Update order of vertex attributes points = points[attrib_maps[1]] counter = 2 if !isempty(uv) point_attributes[:uv] = uv[attrib_maps[counter]] counter += 1 end if !isempty(v_normals) point_attributes[:normals] = v_normals[attrib_maps[counter]] end else # we have vertex indexing - no need to remap if !isempty(v_normals) point_attributes[:normals] = v_normals end if !isempty(uv) point_attributes[:uv] = uv end end return Mesh(meta(points; point_attributes...), faces) end # of form "faces v1 v2 v3 ...."" process_face(lines::Vector) = (lines,) # just put it in the same format as the others # of form "faces v1//vn1 v2//vn2 v3//vn3 ..." process_face_normal(lines::Vector) = split.(lines, "//") # of form "faces v1/vt1 v2/vt2 v3/vt3 ..." or of form "faces v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3 ...." process_face_uv_or_normal(lines::Vector) = split.(lines, ('/',)) function triangulated_faces(::Type{Tf}, vertex_indices::Vector) where {Tf} poly_face = NgonFace{length(vertex_indices), UInt32}(parse.(UInt32, vertex_indices)) return convert_simplex(Tf, poly_face) end function _typemax(::Type{OffsetInteger{O, T}}) where {O, T} typemax(T) end function save(f::Stream{format"OBJ"}, mesh::AbstractMesh) io = stream(f) for p in decompose(Point3f, mesh) println(io, "v ", p[1], " ", p[2], " ", p[3]) end if hasproperty(mesh, :uv) for uv in mesh.uv println(io, "vt ", uv[1], " ", uv[2]) end end if hasproperty(mesh, :normals) for n in decompose_normals(mesh) println(io, "vn ", n[1], " ", n[2], " ", n[3]) end end F = eltype(faces(mesh)) for f in decompose(F, mesh) println(io, "f ", join(convert.(Int, f), " ")) end end
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
2400
function save(str::Stream{format"OFF"}, msh::AbstractMesh) # writes an OFF geometry file, with colors # see http://people.sc.fsu.edu/~jburkardt/data/off/off.html # for format description io = stream(str) vts = coordinates(msh) fcs = faces(msh) cs = hasproperty(msh, :color) ? msh.color : RGBA{Float32}(0,0,0,1) nV = size(vts, 1) nF = size(fcs, 1) nE = nF*3 # write the header println(io, "OFF") println(io, "$nV $nF $nE") # write the data for v in vts println(io, join(Vec{3, Float32}(v), " ")) end for i = 1:nF f = fcs[i] c = isa(cs, Array) ? RGBA{Float32}(cs[i]) : cs facelen = length(f) println(io, facelen, " ", join(raw.(ZeroIndex.(f)), " "), " ", join((red(c), green(c), blue(c), alpha(c)), " ") ) end close(io) end function load(st::Stream{format"OFF"}; facetype=GLTriangleFace, pointtype=Point3f) io = stream(st) points = pointtype[] faces = facetype[] # faces might be triangulated, so we can't assume count n_points = 0 n_faces = 0 found_counts = false read_verts = 0 while !eof(io) txt = readline(io) if startswith(txt, "#") || isempty(txt) || all(iscntrl, txt) #comment or others continue elseif found_counts && read_verts < n_points # read verts vert = pointtype(parse.(eltype(pointtype), split(txt))) if length(vert) == 3 read_verts += 1 points[read_verts] = vert end continue elseif found_counts # read faces splitted = split(txt) facelen = parse(Int, popfirst!(splitted)) if facelen == 3 push!(faces, GLTriangleFace(reinterpret(ZeroIndex{Cuint}, parse.(Cuint, splitted[1:3])))) elseif facelen == 4 push!(faces, convert_simplex(facetype, QuadFace{Cuint}(reinterpret(ZeroIndex{Cuint}, parse.(Cuint, splitted[1:4]))))...) end continue elseif !found_counts && all(isdigit, split(txt)[1]) # vertex and face counts counts = Int[parse(Int, s) for s in split(txt)] n_points = counts[1] n_faces = counts[2] resize!(points, n_points) found_counts = true end end return Mesh(points, faces) end
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git
[ "MIT" ]
0.4.12
dc182956229ff16d5a4d90a562035e633bd2561d
code
6418
function save(f::Stream{format"PLY_BINARY"}, msh::AbstractMesh) io = stream(f) points = coordinates(msh) point_normals = normals(msh) meshfaces = faces(msh) n_points = length(points) n_faces = length(meshfaces) # write the header write(io, "ply\n") write(io, "format binary_little_endian 1.0\n") write(io, "element vertex $n_points\n") write(io, "property float x\nproperty float y\nproperty float z\n") if !isnothing(point_normals) write(io, "property float nx\nproperty float ny\nproperty float nz\n") end write(io, "element face $n_faces\n") write(io, "property list uchar int vertex_index\n") write(io, "end_header\n") # write the vertices and faces if isnothing(point_normals) write(io, points) else for (v, n) in zip(points, point_normals) write(io, v) write(io, n) end end for f in meshfaces write(io, convert(UInt8, length(f))) write(io, raw.(ZeroIndex.(f))...) end close(io) end function save(f::Stream{format"PLY_ASCII"}, msh::AbstractMesh) io = stream(f) points = coordinates(msh) point_normals = normals(msh) meshfaces = faces(msh) n_points = length(points) n_faces = length(meshfaces) # write the header write(io, "ply\n") write(io, "format ascii 1.0\n") write(io, "element vertex $n_points\n") write(io, "property float x\nproperty float y\nproperty float z\n") if !isnothing(point_normals) write(io, "property float nx\nproperty float ny\nproperty float nz\n") end write(io, "element face $n_faces\n") write(io, "property list uchar int vertex_index\n") write(io, "end_header\n") # write the vertices and faces if isnothing(point_normals) for v in points println(io, join(Point{3, Float32}(v), " ")) end else for (v, n) in zip(points, point_normals) println(io, join([v n], " ")) end end for f in meshfaces println(io, length(f), " ", join(raw.(ZeroIndex.(f)), " ")) end close(io) end function load(fs::Stream{format"PLY_ASCII"}; facetype=GLTriangleFace, pointtype=Point3f, normalstype=Vec3f) io = stream(fs) n_points = 0 n_faces = 0 properties = String[] # read the header line = readline(io) has_normals = false while !startswith(line, "end_header") if startswith(line, "element vertex") n_points = parse(Int, split(line)[3]) elseif startswith(line, "property float nx") || startswith(line, "property double nx") has_normals = true elseif startswith(line, "element face") n_faces = parse(Int, split(line)[3]) elseif startswith(line, "property") push!(properties, line) end line = readline(io) end faceeltype = eltype(facetype) points = Array{pointtype}(undef, n_points) point_normals = Array{normalstype}(undef, n_points) #faces = Array{FaceType}(undef, n_faces) faces = facetype[] # read the data for i = 1:n_points numbers = parse.(eltype(pointtype), split(readline(io))) points[i] = pointtype(numbers[1:3]) if has_normals && length(numbers) >= 6 point_normals[i] = pointtype(numbers[4:6]) end end for i = 1:n_faces line = split(readline(io)) len = parse(Int, popfirst!(line)) if len == 3 push!(faces, NgonFace{3, faceeltype}(reinterpret(ZeroIndex{UInt32}, parse.(UInt32, line)))) # line looks like: "3 0 1 3" elseif len == 4 push!(faces, convert_simplex(facetype, QuadFace{faceeltype}(reinterpret(ZeroIndex{UInt32}, parse.(UInt32, line))))...) # line looks like: "4 0 1 2 3" end end if has_normals return Mesh(meta(points; normals=point_normals), faces) else return Mesh(points, faces) end end function load(fs::Stream{format"PLY_BINARY"}; facetype=GLTriangleFace, pointtype=Point3f, normalstype=Vec3f) io = stream(fs) n_points = 0 n_faces = 0 properties = String[] # read the header line = readline(io) has_normals = false has_doubles = Float32 xtype = Float32; ytype = Float32; ztype = Float32 nxtype = Float32; nytype = Float32; nztype = Float32 while !startswith(line, "end_header") if startswith(line, "element vertex") n_points = parse(Int, split(line)[3]) elseif startswith(line, "property double x") xtype = Float64 elseif startswith(line, "property double y") ytype = Float64 elseif startswith(line, "property double z") ztype = Float64 elseif startswith(line, "property float n") has_normals = true elseif startswith(line, "property double nx") has_normals = true nxtype = Float64 elseif startswith(line, "property double ny") has_normals = true nytype = Float64 elseif startswith(line, "property double nz") has_normals = true nztype = Float64 elseif startswith(line, "element face") n_faces = parse(Int, split(line)[3]) elseif startswith(line, "property") push!(properties, line) end line = readline(io) end faceeltype = eltype(facetype) points = Array{pointtype}(undef, n_points) point_normals = Array{normalstype}(undef, n_points) #faces = Array{FaceType}(undef, n_faces) faces = facetype[] # read the data for i = 1:n_points points[i] = pointtype(read(io, xtype), read(io, ytype), read(io, ztype)) if has_normals point_normals[i] = normalstype(read(io, nxtype), read(io, nytype), read(io, nztype)) end end for i = 1:n_faces len = read(io, UInt8) indices = reinterpret(ZeroIndex{UInt32}, [ read(io, UInt32) for _ in 1:len ]) if len == 3 push!(faces, NgonFace{3, faceeltype}(indices)) # line looks like: "3 0 1 3" elseif len == 4 push!(faces, convert_simplex(facetype, QuadFace{faceeltype}(indices))...) # line looks like: "4 0 1 2 3" end end if has_normals return Mesh(meta(points; normals=point_normals), faces) else return Mesh(points, faces) end end
MeshIO
https://github.com/JuliaIO/MeshIO.jl.git