Simulation

The simulation API separates four jobs: construct a model, advance it, collect selected values, and compare those values with observations.

FunctionMain roleResult
instanceconstruct and initialize one modela mutable system instance
simulateconstruct fresh instances and run themone DataFrame, or one per layout
simulate!continue an existing instanceone DataFrame, or one per layout
evaluatejoin observations and estimates and calculate metricsone number or a tuple
calibratesearch parameter bounds against those metricsa Config or Pareto frontier

For a first simulation, read Model Execution and Run Simulations and Shape Output. This page records the complete public call patterns and the less common options exercised by the test suite.

Construct one model with instance

instance(SystemType;
    config = (),
    options = (),
    seed = nothing,
)

instance normalizes config, calls the generated system constructor, and runs the initialization update. It returns the model itself, not a table.

  • config supplies values declared as parameters.
  • options is a named tuple of constructor resources, typically for extern or override declarations that are not ordinary parameters.
  • seed initializes Julia's random generator before configuration values are sampled and before the system is constructed.

Prefer a system type as a configuration key when it is in scope. Type keys check parameter names and convert compatible units immediately. Symbol or string keys remain useful when loading configuration before the system package, but validation is then deferred until construction.

Advance one update with update!

update!(instance)

One call performs one generated Cropbox update cycle in dependency order. It is useful in tests and tightly controlled interactive code:

s = instance(Model; config)
update!(s)
value(s.context.clock.time)

For normal runs, prefer simulate or simulate!; they also handle stopping, snapshots, callbacks, output selection, and progress. Do not manually update an instance while a simulation callback is traversing the same instance.

update! is also an internal extension point with stage arguments, and Cropbox uses the same exported name for updating a plot's option store. Those methods are implementation-facing; model code should normally call the one-argument system form or the documented visualize! function.

Run fresh models with simulate

simulate(SystemType; keywords...) -> DataFrame
simulate(SystemType, layout; keywords...) -> Vector{DataFrame}
simulate(SystemType, layout, configs; keywords...) -> Vector{DataFrame}
simulate(; system = SystemType, keywords...) -> DataFrame
simulate(f, SystemType, ...; keywords...) -> DataFrame

The last positional callback form is do-block syntax for snatch:

simulate(Model; stop = 10u"d") do rows, model
    rows[1][:count] = length(model.organs')
end

With no stop, snap, snatch, or callback, simulate returns the initialized snapshot and performs no time-step update. This fast snapshot form is useful for static response models and parameter grids.

Construction keywords

KeywordDefaultMeaning
config()one configuration, or a shared base for configs
configs[]scenario patches or complete configurations
parameters()a compact parameter sweep with automatic metadata
options()named constructor resources passed to every instance
seed0start each fresh simulation at this seed; nothing uses the current random stream

When both config and configs are present, Cropbox merges the shared config into every entry of configs, with the scenario entry taking precedence. parameters is a convenience sweep: Cropbox expands its iterable values and adds the selected parameter values as metadata. Do not combine nonempty parameters and configs; construct the configurations explicitly when a design needs both.

simulate(ResponseModel;
    config = Clock => :step => 1u"d",
    parameters = ResponseModel => :temperature => 5:5:30,
    target = :rate,
)

Batch runs may use Julia threads. Keep callbacks free of unsynchronized writes to shared state. By default all scenarios start at the same seed. For distinct, repeatable replicates, use a different seed per run, such as [simulate(Model; seed = i, stop = 10u"d") for i in 1:4].

Output layout

A simple call supplies one layout through keywords:

simulate(Model;
    base = nothing,
    index = :time => "context.clock.time",
    target = [:LAI, :biomass],
    meta = [:Treatment, :replicate => 1],
    stop = 100u"d",
)
KeywordDefaultMeaning
basenothingsystem or bundle relative to which selectors are resolved
indexclock timecolumns that identify output rows
targetsimple root valuesmodel values to collect
metanoneconfiguration values or constants copied to every row

Selectors accept:

  • a symbol such as :LAI;
  • a string path such as "calendar.date";
  • a renamed pair such as :date => "calendar.date";
  • a tuple or vector of selectors;
  • "*" for root fields or "soil.*" for one nested system's fields.

The left side of a pair is the output column and the right side is the model path. Explicit targets make downstream code stable when a model later gains new variables. Wildcards are best reserved for inspection.

An explicitly named variable in index or target must exist in the selected base when the output layout is created; otherwise an ArgumentError is raised. For a bundle, the same selectors are resolved and checked for each child at each saved snapshot. An empty bundle contributes no rows. Default selections and wildcard expansion keep omitting unavailable fields. A target may also repeat an existing index column, such as the default :time. Wildcards are standalone selectors and cannot be renamed with a pair.

Explicit selectors may reuse an output column only for the same variable; aliases and equivalent symbol/string paths are allowed. Mapping the same column to different variables raises an ArgumentError, even if their values match. Automatic selections and wildcard expansion retain their existing behavior.

Only simple scalar output is collected automatically: numbers, symbols, strings, and date/time values. Arrays, dictionaries, tuples, DataFrames, and nested systems are omitted. Add a scalar summary declaration or use snatch for those objects.

meta=:Treatment copies every configured entry under that system name. meta=(:Treatment, :replicate => 1) combines configured values with an explicit constant column. Metadata comes from configuration, not from the current state of a changing model variable.

Several layouts in one run

Pass a vector of named tuples when different tables should be collected from the same update sequence:

layout = [
    (index = :time, target = [:LAI, :biomass]),
    (base = :soil, index = :depth, target = [:water, :root_length]),
    (target = :mature, meta = (:site => "A",)),
]

tables = simulate(Model, layout; config, stop = :finished)

Each layout may contain base, index, target, and meta; omitted entries use the same defaults as a simple call. The result order matches the layout order. With a separate positional configs vector, each returned table combines the corresponding layout across all scenarios.

Stop and snapshot conditions

stop determines how long the model advances. It accepts:

FormMeaning
integer or real numberthat many update calls
time quantityenough updates to reach or pass the duration, using Clock.step
symbol or stringread a numeric, time, or Boolean model variable
function model -> valuecalculate the same kinds of condition
Boolean model conditionkeep updating until it becomes true

A numeric stop is interpreted once as an update count. A Boolean stop is tested before every update. If the stop threshold is already true after initialization, no update is made.

snap decides which initialized or updated states become output rows:

FormMeaning
nothingsave every state
time quantitysave at elapsed-time multiples measured from Clock.init
symbol or stringsave when that model value is true
function model -> Boolsave when the callback is true

Clock.step still controls every numerical update. snap=1u"d" does not turn an hourly model into a daily model; it only keeps every 24th hourly state. The initialized state is included whenever the snapshot condition is true, so a run with stop=10 normally has 11 rows.

Custom snapshot processing

snatch(rows, model) runs for every saved state. rows contains one extracted row per matching base-system item and may be edited, extended, or emptied. This is the intended extension point for dynamic structures such as root architectures.

callback(model, simulation_layout) runs after a saved state has been processed. The second argument is Cropbox's internal simulation accumulator. Its layout holds the original request; index and target map output column names to the model paths resolved so far. It is lower level and more sensitive to implementation changes than snatch; prefer snatch unless coordination with the accumulator is necessary. The current callback path runs after updated snapshots, not after the initial snapshot; snatch receives both initial and updated snapshots.

Supplying either callback disables the fastest column-oriented collection path. That is normally insignificant for complex callback work, but it matters for large scalar-only sweeps.

Output formatting

KeywordDefaultMeaning
nounitfalsestrip units from returned columns
longfalsestack target columns into variable/value rows
verbosetrueshow a progress display

nounit=true changes only the returned table. Model calculations remain unit-aware. Long format preserves index columns, stacks all remaining columns, and sorts by the index. Request it only when a plotting or statistics workflow needs tidy long data, since it can greatly increase the row count.

Continue one model with simulate!

simulate!(instance; layout_keywords..., run_keywords...) -> DataFrame
simulate!(instance, layout; run_keywords...) -> Vector{DataFrame}
simulate!(f, instance, ...; run_keywords...) -> DataFrame

simulate! continues the exact instance passed to it. It accepts output, stop/snapshot, callback, and formatting keywords, but not a new config, options, or seed. Use it for deliberate staged runs or manual management; use simulate(SystemType, ...) for independent treatments and replicates.

s = instance(Model; config, seed = 1)
first_stage = simulate!(s; stop = :emerged, target = :biomass)
second_stage = simulate!(s; stop = :mature, target = :biomass)

The second stop is evaluated from the already advanced state. The two returned tables are separate. Each call saves its current state first when the snapshot condition is true, so the stage boundary can appear in both tables.

Compare data with evaluate

evaluate(observations, estimates;
    index,
    target,
    metric = :rmse,
    warn = true,
)

evaluate(SystemType, observations;
    config = (), configs = [],
    index = nothing,
    target,
    metric = :rmse,
    warn = true,
    simulation_keywords...,
)

For two tables, target=:observed => :estimated maps different column names. For a score per model, evaluate each estimate group separately: [evaluate(obs, g; index = :year, target = :y) for g in groupby(est, :model)]. For a system, the same name is assumed unless a pair is supplied. Multiple targets return a tuple in target order.

Cropbox normalizes compatible index units and inner-joins rows on the index. Rows missing any requested observation target are omitted; the two-table form also omits missing estimates. An ArgumentError is raised if no complete matching rows remain. Rows are not compared merely because they have the same position. Partial matches warn with the number of matched and complete observations. The score still uses the matching subset, so check index coverage when interpreting a score; an explicit snap may intentionally select fewer observations. Set warn = false to suppress this warning without changing the score or empty-match errors.

Both evaluation forms support the following metrics:

SymbolMetricResult scale
:rmseroot mean square errortarget unit
:nrmseRMSE divided by observation meandimensionless
:rmsperoot mean square percentage errordimensionless
:maemean absolute errortarget unit
:mapemean absolute percentage errordimensionless
:efNash–Sutcliffe efficiencydimensionless
:drrefined index of agreementdimensionless

metric may also be a function (estimate, observation) -> score, receiving two vectors in that order in either evaluation form. Relative metrics need special care near zero. Efficiency metrics need enough variation in the observations to define their denominator. Error metrics are better when lower; :ef and :dr are better when higher, with a perfect match scoring one.

When evaluating several configurations, residuals are combined across their matching rows before one score per target is calculated. Give environment or treatment columns in index when otherwise identical dates must remain distinct.

Search parameters with calibrate

calibrate(SystemType, observations;
    config = (), configs = [],
    index = nothing,
    target,
    parameters,
    metric = :rmse,
    weight = nothing,
    pareto = false,
    optim = (),
    seed = 0,
    warn = true,
    simulation_keywords...,
)

parameters has the shape of a configuration, but each value is a two-value search bound:

parameters = Model => (
    base_temperature = (-5, 15),
    thermal_requirement = (100, 2000),
)

Plain bounds inherit the unit declared by each parameter and are converted before optimization. This is usually the clearest form. When explicit units are needed, put them on the values (for example (-5u"°C", 15u"°C")) or multiply a vector such as [0, 2]u"yr^-1"; (0, 2)u"yr^-1" is not valid Julia syntax. The result is a Config containing the selected values in model units.

calibrate and analyze check parameter definitions against declared child systems and mixins. A misspelled parameter, ambiguous system name, or system outside a fully known hierarchy is an error. The key :0 selects the root. Abstract child types also admit their loaded subtypes and mixins; untyped produce needs a resolvable type or qualified name (Child => :rate => (0, 1) or Symbol("MyModels.Child") => :rate => (0, 1)). Dynamic matches warn once before searching: the child may never be created or affect the result.

Cropbox uses BlackBoxOptim.jl differential-evolution methods. optim is a named tuple forwarded to bboptimize; Cropbox defaults are MaxSteps=5000 and TraceInterval=10.

Calibration always minimizes the supplied objective. Error metrics such as :rmse and :mae can be used directly. Do not pass the higher-is-better :ef or :dr unchanged: minimizing them searches in the wrong direction. A custom objective also receives (estimate, observation) vectors and must return a lower value for a better fit. For example, 1 - efficiency converts an efficiency score to a loss.

With several configurations, Cropbox calculates a metric separately for each configuration and sums those scores for each target. This differs from evaluate(...; configs), which pools matching rows before calculating the metric. A sum of site-year RMSE values is not a pooled RMSE, especially when site-years have different numbers of observations. Check which objective fits the study before calibrating.

Rows missing any requested observation target are omitted before the search. Candidates with no matching output receive an infinite penalty. If no finite result is found, calibration raises an ArgumentError instead of returning an unvalidated configuration. This does not change an explicit snap condition. Partial matching warns once per search, reporting coverage for the first finite candidate with incomplete coverage, not necessarily the final solution. Run evaluate with the fitted configuration to check its coverage. Use warn = false to suppress this warning across repeated calibration calls; this is independent of simulation verbose and optimizer TraceMode.

With one target, calibration minimizes that target's objective. With several targets, it uses a multi-objective method. weight changes how a single compromise is chosen from objective values. pareto=true returns an ordered mapping from objective tuples to configurations along the Pareto frontier instead of one Config.

Local or gradient-based methods are not selected through calibrate. When they are appropriate, construct and test an explicit objective with evaluate and pass it to an optimization package such as Optim.jl.

Do not pass nonempty config and configs together to evaluate or calibrate. For several environments, make each entry of configs complete and include environment-identifying columns in index. See Evaluate and Calibrate Models for validation splits, residual checks, and reporting practice.

Model sampling and the calibration seed

The optimizer tries candidate parameter values and compares their predictions with observations. This is separate from randomness inside the model: for example, each new root samples its own elongation rate from (6.0 ± 0.6)u"cm/d".

seedsimulatecalibrate
Omitted or 0Start each run at 0.Start the search once at 0 and each candidate's simulation at 0.
Another integerStart each run at that seed.Use that seed for the search and for each candidate and configuration.
nothingContinue drawing from the current random stream.Use the caller's random stream for the search and draw fresh model seeds in configuration order.

An integer seed reproduces the sequence of candidate evaluations for the same inputs, package versions and evaluation budget. Roots within one plant still draw different traits: the seed restarts the whole simulation, not each root. Changing a model parameter can still change the architecture. Previously, omitting seed left simulation draws unfixed and set only the optimizer to zero. To keep the old unseeded simulation behavior, pass seed = nothing. A stochastic fit can also change under the new default.

With either function, an integer seed leaves the caller's random stream unchanged. To replay a sequence of runs with fresh draws, call Random.seed!(42) once and pass seed = nothing to each call. Lower-level instance still defaults to seed = nothing; simulate! continues an existing instance without reseeding.

There is no separate optimizer seed: changing seed on a stochastic model changes both sources of variation. A fit does not average each candidate's score over replicate seeds. To check biological variation after fitting, keep the fitted configuration fixed and vary only simulate's seed, as in the CropRootBox replicate example.

API docstrings

Cropbox.instance — Function
instance(S; <keyword arguments>) -> S

Make an instance of system S with an initial condition specified in configuration and additional options.

See also: @config, simulate

Arguments

  • S::Type{<:System}: type of system to be instantiated.

Keyword Arguments

  • config=(): configuration containing parameter values for the system.
  • options=(): keyword arguments passed down to the constructor of S; named tuple expected.
  • seed=nothing: random seed initialized before parsing configuration and making an instance.

Examples

julia> @system S(Controller) begin
           a => 1 ~ preserve(parameter)
           b(a) ~ accumulate
       end;

julia> instance(S)
S
  context = <Context>
  config = <Config>
  a = 1.0
  b = 0.0
source
Cropbox.simulate — Function
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, @config

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=0: start each fresh simulation with this seed. Pass nothing to draw from the current random stream instead.

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> @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
source
Cropbox.simulate! — Function
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

source
Cropbox.evaluate — Function
evaluate(S, obs; <keyword arguments>) -> Number | Tuple

Compare output of simulation results for the given system S and observation data obs with a choice of evaluation metric.

Arguments

  • S::Type{<:System}: type of system to be evaluated.
  • obs::DataFrame: observation data to be used for evaluation.

Keyword Arguments

Configuration

  • config=(): a single configuration for the system (can't be used with configs).
  • configs=[]: multiple configurations for the system (can't be used with config).

Layout

  • index=nothing: variables to construct index columns of the output; default falls back to context.clock.time.
  • target: variables to construct non-index columns of the output.

Evaluation

  • metric=nothing: evaluation metric (:rmse, :nrmse, :mae, :mape, :ef, :dr); default is RMSE.
  • warn=true: warn when only part of the complete observations match.

Remaining keyword arguments are passed down to simulate with regard to running system S. Rows missing any requested observation target are omitted. An ArgumentError is raised if no complete observations or no matching output remain. Partial matches warn with the number of matched and complete observations.

See also: simulate, calibrate, @config

Examples

julia> @system S(Controller) begin
           a => 19 ~ preserve(u"m/hr", parameter)
           b(a) ~ accumulate(u"m")
       end;

julia> obs = DataFrame(time=10u"hr", b=200u"m");

julia> configs = @config !(:S => :a => [19, 21]);

julia> evaluate(S, obs; configs, target=:b, stop=10u"hr")
10.0 m
source
evaluate(obs, est; <keyword arguments>) -> Number | Tuple

Compare observation data obs and estimation data est with a choice of evaluation metric.

Arguments

  • obs::AbstractDataFrame: observation data to be used for evaluation.
  • est::AbstractDataFrame: estimated data from simulation.

Keyword Arguments

Layout

  • index=nothing: index columns, defaulting to :time; pairs map observation columns to estimate columns.
  • target: variables referring to non-index columns of the output.

Evaluation

  • metric=nothing: evaluation metric (:rmse, :nrmse, :mae, :mape, :ef, :dr); default is RMSE.
  • warn=true: warn when only part of the complete observations match.

See also: evaluate

Neither input table is modified. Rows missing any requested target are omitted. An ArgumentError is raised if no complete matching rows remain. Partial matches warn with the number of matched and complete observations.

Examples

julia> obs = DataFrame(time = [1, 2, 3]u"hr", b = [10, 20, 30]u"g");

julia> est = DataFrame(time = [1, 2, 3]u"hr", b = [10, 20, 30]u"g", c = [11, 19, 31]u"g");

julia> evaluate(obs, est; index = :time, target = :b)
0.0 g

julia> evaluate(obs, est; index = :time, target = :b => :c)
1.0 g
source
Cropbox.calibrate — Function
calibrate(S, obs; <keyword arguments>) -> Config | OrderedDict

Obtain a set of parameters for the given system S that simulates provided observation obs closely as possible. A multitude of simulations are conducted with a differing combination of parameter sets specified by the range of possible values and the optimum is selected based on a choice of evaluation metric. Internally, differential evolution algorithm from BlackboxOptim.jl is used.

Arguments

  • S::Type{<:System}: type of system to be calibrated.
  • obs::AbstractDataFrame: observation data to be used for calibration, including a DataFrame view.

Keyword Arguments

Configuration

  • config=(): a single base configuration for the system (can't be used with configs).
  • configs=[]: multiple base configurations for the system (can't be used with config).

Layout

  • index=nothing: variables to construct index columns of the output; default falls back to context.clock.time.
  • target: variables to construct non-index columns of the output.

Calibration

  • parameters: parameters with a range of boundary values to be calibrated within.
  • seed=0: start the optimizer once and each candidate's simulation with this seed. Use nothing to draw fresh model seeds from the caller's random stream.
  • metric=nothing: evaluation metric (:rmse, :nrmse, :mae, :mape, :ef, :dr); default is RMSE.
  • warn=true: warn once per search about partial observation matching.

Multi-objective

  • weight=nothing: weights for calibrating multiple targets; default assumes equal weights.
  • pareto=false: returns a dictionary containing Pareto frontier instead of a single solution satisfying multiple targets.

Advanced

  • optim=(): extra options for BlackBoxOptim.bboptimize.

Remaining keyword arguments are passed down to simulate with regard to running system S. Rows missing any requested observation target are omitted before the search. An ArgumentError is raised if no complete observations or no finite result remain. Partial matches warn once per search, with counts for the first finite candidate that uses only part of the complete observations. Parameter names and units are resolved against the model's declared systems and mixins. For dynamic children whose types are not known, an explicit system type or a name resolved in the model's modules or Main supplies the parameter definition. Its existence and unit are checked, but unverified participation is reported once before optimization. Unknown or ambiguous names, non-parameters and duplicate targets raise an ArgumentError. The key :0 selects the root system.

See also: simulate, evaluate, @config

Examples

julia> @system S(Controller) begin
           a => 0 ~ preserve(parameter)
           b(a) ~ accumulate
       end;

julia> obs = DataFrame(time=10u"hr", b=200);

julia> p = calibrate(S, obs; target=:b, parameters=:S => :a => (0, 100), stop=10)
...
Config for 1 system:
  S
    a = 20.0
source