| Title: | APSIM Next Generation as a Contract-Emitting Analysis Member |
|---|---|
| Description: | A typed, server-capable R interface to APSIM Next Generation, the process-based agricultural systems simulator. Drives the simulator for prediction over scenario designs, mechanism-parameter estimation, parameter calibration against observations (a bounded optimiser, or an iterative ensemble smoother when 'PESTO' is present), global sensitivity analysis (Morris and Sobol), Gaussian-process emulation with leave-one-out diagnostics, validation against observations (goodness-of-fit metrics and a typed verdict), and the generation of known-causal-structure datasets for testing causal-inference methods, and returns results as a versioned, provenance-complete 'apsim_manifest' object that is emitted natively into the shared orchestra manifest contract, so simulator output composes directly with downstream calibration, uncertainty-quantification and causal-inference tools; an ensemble inversion additionally bridges to a 'PESTO' ensemble manifest. Execution degrades gracefully: every entry point abstains with a typed reason when the simulator or its runtime is absent. |
| Authors: | Max Moldovan [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-9680-8474>) |
| Maintainer: | Max Moldovan <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.3.2.9000 |
| Built: | 2026-10-15 23:25:52 UTC |
| Source: | https://github.com/max578/apsimR |
Returns a small classed object signalling that a simulator-dependent operation could not be performed, with a machine-readable reason. Used in place of an error so that callers (and the orchestration layer) can branch on a refusal rather than catch an exception.
apsim_abstention(reason, detail = NA_character_, scope = "call")apsim_abstention(reason, detail = NA_character_, scope = "call")
reason |
Character scalar reason code. One of |
detail |
Character scalar human-readable detail, or |
scope |
Character scalar naming what was refused (default |
An object of class "apsim_abstention": a list with reason,
detail, scope and abstained = TRUE.
a <- apsim_abstention("runtime_unavailable", "no Models executable found") is_apsim_abstention(a)a <- apsim_abstention("runtime_unavailable", "no Models executable found") is_apsim_abstention(a)
Reports whether a runnable Models executable has been found (by
apsim_configure() or auto-discovery). When this is FALSE, the
simulator-dependent verbs return an apsim_abstention() rather than running.
apsim_available()apsim_available()
A single logical.
if (apsim_available()) { apsim_version() }if (apsim_available()) { apsim_version() }
Estimates the parm_paths parameters whose APSIM-simulated observations best
match observed, over the box [lower, upper]. The ies backend (default
when PESTO is installed) returns a posterior parameter ensemble through an
iterative ensemble smoother; the optim backend returns a single bounded
least-squares point estimate with no extra dependency. Several targets are
calibrated jointly – pass a named observed vector and, optionally, per-target
obs_sd or weights.
apsim_calibrate( sim, parm_paths, lower, upper, observed, output, obs_sd = NULL, weights = NULL, backend = c("auto", "ies", "optim"), n_real = 50L, noptmax = 4L, inflation = 0.8, report = NULL, seed = NULL )apsim_calibrate( sim, parm_paths, lower, upper, observed, output, obs_sd = NULL, weights = NULL, backend = c("auto", "ies", "optim"), n_real = 50L, noptmax = 4L, inflation = 0.8, report = NULL, seed = NULL )
sim |
An |
parm_paths |
Character vector of APSIM node paths to estimate. |
lower, upper
|
Numeric box bounds aligned to |
observed |
Named numeric vector of observed target values; the names must
match what |
output |
Either a |
obs_sd |
Numeric observation standard deviation(s): a scalar or a vector
aligned to |
weights |
Optional misfit weights aligned to |
backend |
Character: |
n_real |
Integer ensemble size for the |
noptmax |
Integer number of ensemble-smoother iterations ( |
inflation |
Numeric RTPS inflation strength in |
report |
Character report-table name, or |
seed |
Optional integer RNG seed (prior ensemble / reproducibility). |
An apsim_manifest with inferential_target = "parameters" whose
params holds the point estimate (optim) or the posterior ensemble
(ies), or an apsim_abstention() when the simulator (or, for ies, PESTO)
is unavailable.
# A calibration runs the simulator many times, so the example is wrapped in # \dontrun{}; see the package vignette for a runnable walk-through. ## Not run: f <- apsim_example("Wheat") if (!is.na(f)) { apsim_calibrate( f, parm_paths = "[Fertilise at sowing].Script.Amount", lower = 0, upper = 250, observed = c(Yield = 2200), output = "Yield", backend = "optim", seed = 1L) } ## End(Not run)# A calibration runs the simulator many times, so the example is wrapped in # \dontrun{}; see the package vignette for a runnable walk-through. ## Not run: f <- apsim_example("Wheat") if (!is.na(f)) { apsim_calibrate( f, parm_paths = "[Fertilise at sowing].Script.Amount", lower = 0, upper = 250, observed = c(Yield = 2200), output = "Yield", backend = "optim", seed = 1L) } ## End(Not run)
Pins the paths apsimR uses, overriding auto-discovery. Call this once per
session when APSIM is installed in a non-standard location or when more than
one version is present and a specific one is wanted. With all arguments NULL
it clears any pinned paths and reverts to discovery.
apsim_configure(models = NULL, server = NULL, dotnet_root = NULL)apsim_configure(models = NULL, server = NULL, dotnet_root = NULL)
models |
Character path to the |
server |
Character path to the |
dotnet_root |
Character path to the .NET runtime root (sets |
Invisibly, the resolved runtime list (see apsim_available()).
# Revert to auto-discovery. apsim_configure()# Revert to auto-discovery. apsim_configure()
Generates parameter points filling the box [lower, upper] for the named
parameters. A Latin-hypercube design (the default) spreads n points evenly
through the space – the standard choice for training an emulator; a grid gives
an exhaustive factorial (n becomes points-per-dimension); random gives an
independent uniform sample. The design is reproducible through seed.
apsim_design( parm_paths, lower, upper, n = 20L, method = c("lhs", "grid", "random"), seed = NULL )apsim_design( parm_paths, lower, upper, n = 20L, method = c("lhs", "grid", "random"), seed = NULL )
parm_paths |
Character vector of APSIM node paths (the design columns). |
lower, upper
|
Numeric vectors of box bounds, each aligned to |
n |
Integer. For |
method |
Character: |
seed |
Optional integer RNG seed for the stochastic methods. |
A numeric matrix with length(parm_paths) named columns, one row per
design point.
d <- apsim_design(c("[Sow].Script.Population", "[Fertilise].Amount"), lower = c(50, 0), upper = c(200, 200), n = 8, seed = 1L) dim(d)d <- apsim_design(c("[Sow].Script.Population", "[Fertilise].Amount"), lower = c(50, 0), upper = c(200, 200), n = 8, seed = 1L) dim(d)
[Node].Property = value edits through APSIM's validatorWrites an APSIM --apply config file from edits and runs the simulator's own
editor, so the change is validated against the model schema rather than poked
into raw JSON. Requires the simulator; returns an apsim_abstention() when it
is absent.
apsim_edit(x, edits, path = tempfile(fileext = ".apsimx"))apsim_edit(x, edits, path = tempfile(fileext = ".apsimx"))
x |
An |
edits |
A named character vector of edits, names being APSIM node paths
and values the new values, for example
|
path |
Character output path for the edited file. Defaults to a temporary
|
A new apsim_sim for the edited file, or an apsim_abstention.
f <- system.file("extdata", "Wheat.apsimx", package = "apsimR") if (nzchar(f)) { apsim_edit(apsim_sim(f), c("[Clock].End" = "1991-12-31")) }f <- system.file("extdata", "Wheat.apsimx", package = "apsimR") if (nzchar(f)) { apsim_edit(apsim_sim(f), c("[Clock].End" = "1991-12-31")) }
Runs APSIM at a space-filling design over [lower, upper], fits a GP surrogate
mapping the parm_paths parameters to a single scalar output, and returns it
with leave-one-out diagnostics. The default exact backend needs no extra
package; pesto uses PESTO's surrogate when installed. Predict at new
parameters with predict().
apsim_emulate( sim, parm_paths, lower, upper, output, target = NULL, n = 30L, design = c("lhs", "grid", "random"), backend = c("exact", "pesto"), report = NULL, seed = NULL )apsim_emulate( sim, parm_paths, lower, upper, output, target = NULL, n = 30L, design = c("lhs", "grid", "random"), backend = c("exact", "pesto"), report = NULL, seed = NULL )
sim |
An |
parm_paths |
Character vector of APSIM node paths (the emulator inputs). |
lower, upper
|
Numeric box bounds aligned to |
output |
A |
target |
Character naming the output column to emulate when |
n |
Integer number of design (training) points. |
design |
Character design method passed to |
backend |
Character: |
report |
Character report-table name, or |
seed |
Optional integer RNG seed (design reproducibility). |
An apsim_emulator, or an apsim_abstention() when the simulator
(or, for backend = "pesto", PESTO) is unavailable.
# Fitting an emulator runs the simulator at every design point, so the example # is wrapped in \dontrun{}; see the package vignette for a runnable walk-through. ## Not run: f <- apsim_example("Wheat") if (!is.na(f)) { em <- apsim_emulate( f, parm_paths = "[Fertilise at sowing].Script.Amount", lower = 0, upper = 250, output = "Yield", n = 12L, seed = 1L) if (!is_apsim_abstention(em)) predict(em, matrix(c(50, 150), ncol = 1L)) } ## End(Not run)# Fitting an emulator runs the simulator at every design point, so the example # is wrapped in \dontrun{}; see the package vignette for a runnable walk-through. ## Not run: f <- apsim_example("Wheat") if (!is.na(f)) { em <- apsim_emulate( f, parm_paths = "[Fertilise at sowing].Script.Amount", lower = 0, upper = 250, output = "Yield", n = 12L, seed = 1L) if (!is_apsim_abstention(em)) predict(em, matrix(c(50, 150), ncol = 1L)) } ## End(Not run)
Runs the simulator on a copy of sim, reads the report, and fits a
reduced-form response of the outcome y on the input x (the report must
already vary x, for example through a factorial over an N-rate). Returns the
fitted parameters as a parameters apsim_manifest(), or an
apsim_abstention() when the simulator is unavailable.
apsim_estimate( sim, x, y, response = c("mitscherlich", "linear"), report = NULL )apsim_estimate( sim, x, y, response = c("mitscherlich", "linear"), report = NULL )
sim |
An |
x |
Character name of the input column in the report. |
y |
Character name of the outcome column in the report. |
response |
Character mechanism form: |
report |
Character report-table name, or |
An apsim_manifest with inferential_target = "parameters", or an
apsim_abstention.
f <- apsim_example("Wheat") if (!is.na(f)) { # apsim_estimate(f, x = "Nitrogen", y = "Yield") apsim_available() }f <- apsim_example("Wheat") if (!is.na(f)) { # apsim_estimate(f, x = "Nitrogen", y = "Yield") apsim_available() }
Returns the path to one of the .apsimx examples shipped with the installed
APSIM, so examples and tests can run against a real simulation without the
package bundling APSIM's own (separately-licensed) files. Returns
NA_character_ when the simulator or the named example is not present.
apsim_example(name = "Wheat")apsim_example(name = "Wheat")
name |
Character example name without extension (default |
A single character path, or NA_character_.
apsim_example("Wheat")apsim_example("Wheat")
Enumerates the class-8 facts apsimR asserts about the APSIM simulator – the
DataStore SQLite schema, the "Current" checkpoint, report column names, and
manager node paths – with the oracle that grounds each and the date it was
last diffed against a live APSIM install. A fact is grounded only when
verified_on is a non-NA date; the DataStore-schema and report-column facts
are grounded by the replayed-real-run oracle test, not by a skipped test.
apsim_external_facts()apsim_external_facts()
A data.frame with fact_family, asserted_value, oracle_kind,
verified_on (Date/NA), evidence_path, and a derived grounding
token ("grounded" / "ungrounded").
apsim_external_facts()apsim_external_facts()
Collapses apsim_external_facts() to one row per fact family, so a caller
can see at a glance which classes of APSIM
fact are grounded by a replayed real run and which are still
"ungrounded".
apsim_fact_status()apsim_fact_status()
A data.frame with one row per fact_family: n_facts,
n_grounded, n_unverified.
status <- apsim_fact_status() status # families with at least one unverified fact status[status$n_unverified > 0, ]status <- apsim_fact_status() status # families with at least one unverified fact status[status$n_unverified > 0, ]
Returns a closure of the orchestra-standard forward-model shape:
function(theta) -> obs, where theta is an nreal x npar numeric matrix
(one row per parameter realisation, columns aligned to parm_paths) and obs
is an nreal x nobs numeric matrix. Each row is one APSIM run with the
corresponding parameters substituted; failed runs become NA rows. The closure
is what apsim_calibrate(), apsim_sensitivity() and apsim_emulate() all
evaluate, and it is directly accepted by PESTO::pesto_ies_callback() and by
the sensitivity package's model argument.
apsim_forward_model( sim, parm_paths, output, report = NULL, checkpoint = "Current", reduce = function(x) x[[length(x)]] )apsim_forward_model( sim, parm_paths, output, report = NULL, checkpoint = "Current", reduce = function(x) x[[length(x)]] )
sim |
An |
parm_paths |
Character vector of APSIM node paths to vary, for example
|
output |
Either a |
report |
Character report-table name, or |
checkpoint |
Character checkpoint name (default |
reduce |
When |
A function of one argument theta (an nreal x npar matrix or a
length-npar vector) returning an nreal x nobs numeric matrix, or an
apsim_abstention() when the simulator is unavailable.
f <- apsim_example("Wheat") if (!is.na(f)) { fm <- apsim_forward_model(f, "[Clock].End", output = "Wheat.AboveGround.Wt") if (!is_apsim_abstention(fm)) fm(matrix("1991-04-30", 1L, 1L)) }f <- apsim_example("Wheat") if (!is.na(f)) { fm <- apsim_forward_model(f, "[Clock].End", output = "Wheat.AboveGround.Wt") if (!is_apsim_abstention(fm)) fm(matrix("1991-04-30", 1L, 1L)) }
Runs each unit under a control and a treatment value of treatment – so both
potential outcomes are known – then assigns each unit to treatment or control
and reveals the corresponding outcome, producing a dataset whose true effects
are recorded. Each unit is one row of units, whose columns are further APSIM
node paths defining that unit's context (the heterogeneity, and the source of
confounding). The result is the test-bench for a causal member: hand it the
observed (covariates, W, Y) and compare its estimate to the recorded average
treatment effect.
apsim_ground_truth( sim, treatment, control, treated, units, output, target = NULL, assignment = c("random", "confounded"), prob = 0.5, confounder = NULL, confound_strength = 1, report = NULL, seed = NULL )apsim_ground_truth( sim, treatment, control, treated, units, output, target = NULL, assignment = c("random", "confounded"), prob = 0.5, confounder = NULL, confound_strength = 1, report = NULL, seed = NULL )
sim |
An |
treatment |
Character APSIM node path of the intervened parameter. |
control, treated
|
Numeric values of |
units |
A |
output |
A |
target |
Character naming the outcome column when |
assignment |
Character: |
prob |
Numeric treatment probability for |
confounder |
Character naming the |
confound_strength |
Numeric logistic coefficient on the standardised confounder (larger means stronger confounding). |
report |
Character report-table name, or |
seed |
Optional integer RNG seed (assignment reproducibility). |
An apsim_ground_truth_result, or an apsim_abstention() when the
simulator is unavailable.
# An OSSE varying sowing population (the unit covariate) under two N rates, # with treatment confounded by population. Runs the simulator twice per unit. ## Not run: f <- apsim_example("Wheat") units <- data.frame(`[Sow using a variable rule].Script.Population` = c(80, 120, 160, 200), check.names = FALSE) apsim_ground_truth( f, treatment = "[Fertilise at sowing].Script.Amount", control = 0, treated = 150, units = units, output = "Yield", assignment = "confounded", confounder = "[Sow using a variable rule].Script.Population", seed = 1L) ## End(Not run)# An OSSE varying sowing population (the unit covariate) under two N rates, # with treatment confounded by population. Runs the simulator twice per unit. ## Not run: f <- apsim_example("Wheat") units <- data.frame(`[Sow using a variable rule].Script.Population` = c(80, 120, 160, 200), check.names = FALSE) apsim_ground_truth( f, treatment = "[Fertilise at sowing].Script.Amount", control = 0, treated = 150, units = units, output = "Yield", assignment = "confounded", confounder = "[Sow using a variable rule].Script.Population", seed = 1L) ## End(Not run)
The typed result every verb returns. inferential_target follows the
orchestra contract enum ("predictions", "parameters"); params carries a
fitted-parameter table (empty for a pure prediction); outputs carries the
simulated report; provenance pins the APSIM version, an integrity hash, and the
seed.
apsim_manifest( inferential_target, method, params = data.frame(), outputs = NULL, metadata = list(), seed = NA_integer_ )apsim_manifest( inferential_target, method, params = data.frame(), outputs = NULL, metadata = list(), seed = NA_integer_ )
inferential_target |
Character: |
method |
Character method tag, for example |
params |
A |
outputs |
The simulated report ( |
metadata |
A named list of auxiliary provenance. |
seed |
Integer RNG seed ( |
An apsim_manifest S7 object.
m <- apsim_manifest("parameters", "apsim:estimate:mitscherlich", params = data.frame(ymax = 4.2, rate = 0.018, y0 = 1.1)) m@inferential_targetm <- apsim_manifest("parameters", "apsim:estimate:mitscherlich", params = data.frame(ymax = 4.2, rate = 0.018, y0 = 1.1)) m@inferential_target
Fetches columns of a report table produced by the most recent apsim_run(),
decoding the server's typed column stream into a data.frame. The named report
must contain rows (the server signals an empty report as an error, not an empty
frame).
apsim_output(server, table, columns)apsim_output(server, table, columns)
server |
An open |
table |
Character report-table name. |
columns |
Character vector of column names to fetch. |
A data.frame with one column per requested name.
f <- apsim_example("Wheat") if (!is.na(f) && apsim_available()) { srv <- apsim_server(f) if (!is_apsim_abstention(srv) && !is_apsim_abstention(apsim_run(srv))) { d <- apsim_output(srv, "Report", "Yield") } close(srv) }f <- apsim_example("Wheat") if (!is.na(f) && apsim_available()) { srv <- apsim_server(f) if (!is_apsim_abstention(srv) && !is_apsim_abstention(apsim_run(srv))) { d <- apsim_output(srv, "Report", "Yield") } close(srv) }
Runs the simulator on a copy of sim (the source file and its DataStore are
never touched), reads the requested report from the resulting DataStore, and
returns it as a predictions apsim_manifest(). A single Models invocation
builds the file once and runs every simulation it contains (including any
factorial fan-out) across cores. Returns an apsim_abstention() when the
simulator is unavailable or the run fails.
apsim_predict(sim, report = NULL, simulations = NULL, cpu = NULL)apsim_predict(sim, report = NULL, simulations = NULL, cpu = NULL)
sim |
An |
report |
Character report-table name, or |
simulations |
Optional regular expression selecting simulations to run
( |
cpu |
Optional integer thread cap; |
An apsim_manifest with inferential_target = "predictions" carrying
the simulated report in outputs, or an apsim_abstention.
# Running APSIM over a real simulation file takes several seconds, so the # call is wrapped in \donttest{}; it runs under R CMD check --run-donttest. f <- apsim_example("Wheat") if (!is.na(f)) { m <- apsim_predict(f) m@inferential_target }# Running APSIM over a real simulation file takes several seconds, so the # call is wrapped in \donttest{}; it runs under R CMD check --run-donttest. f <- apsim_example("Wheat") if (!is.na(f)) { m <- apsim_predict(f) m@inferential_target }
Returns one report table joined to its simulation names and filtered to a checkpoint. Reading is a single pushed-down SQL JOIN, so only the requested columns and rows leave SQLite.
apsim_read(db, report = NULL, checkpoint = "Current")apsim_read(db, report = NULL, checkpoint = "Current")
db |
Character path to a |
report |
Character report-table name, or |
checkpoint |
Character checkpoint name (default |
A data.frame: the report columns, prefixed with a SimulationName
column when the report is simulation-keyed.
# d <- apsim_read(run$db, report = "Report")# d <- apsim_read(run$db, report = "Report")
List the report tables in an APSIM DataStore
apsim_reports(db)apsim_reports(db)
db |
Character path to a |
A character vector of report-table names (metadata tables, prefixed
with _, are excluded).
# apsim_reports(run$db)# apsim_reports(run$db)
Runs the .apsimx the server holds, optionally overriding model parameters for
this run. The file is not reloaded, so an adaptive sweep pays the load cost
once. Read the results with apsim_output().
apsim_run(server, changes = NULL)apsim_run(server, changes = NULL)
server |
An open |
changes |
A named list of parameter overrides: names are APSIM model
paths (for example |
Invisibly TRUE on success; errors carry the simulator's message.
f <- apsim_example("Wheat") if (!is.na(f) && apsim_available()) { srv <- apsim_server(f) if (!is_apsim_abstention(srv)) { apsim_run(srv) close(srv) } }f <- apsim_example("Wheat") if (!is.na(f) && apsim_available()) { srv <- apsim_server(f) if (!is_apsim_abstention(srv)) { apsim_run(srv) close(srv) } }
Quantifies how the parm_paths parameters drive a single scalar APSIM output
over the box [lower, upper]. Morris screening (default) ranks the factors by
mean absolute elementary effect (mu_star) and flags interaction / non-linearity
(sigma) cheaply; the Sobol-Jansen method decomposes the output variance into
first-order (S) and total (T) indices at a higher run cost. The two stages
use the sensitivity package over the same forward model as the other verbs.
apsim_sensitivity( sim, parm_paths, lower, upper, output, target = NULL, method = c("morris", "sobol", "both"), morris_r = 10L, morris_levels = 6L, sobol_n = 100L, nboot = 100L, report = NULL, seed = NULL )apsim_sensitivity( sim, parm_paths, lower, upper, output, target = NULL, method = c("morris", "sobol", "both"), morris_r = 10L, morris_levels = 6L, sobol_n = 100L, nboot = 100L, report = NULL, seed = NULL )
sim |
An |
parm_paths |
Character vector of APSIM node paths (the factors). |
lower, upper
|
Numeric box bounds aligned to |
output |
A |
target |
Character naming the single output column to analyse when
|
method |
Character: |
morris_r |
Integer number of Morris elementary-effect repetitions. |
morris_levels |
Integer Morris grid levels. |
sobol_n |
Integer base sample size for Sobol (total runs |
nboot |
Integer bootstrap replicates for Sobol confidence intervals. |
report |
Character report-table name, or |
seed |
Optional integer RNG seed. |
An apsim_manifest with inferential_target = "sensitivity" whose
params holds one row per factor with the requested indices, or an
apsim_abstention() when the simulator is unavailable.
# Sensitivity analysis runs the simulator r(p + 1) times, so the example is # wrapped in \dontrun{}; see the package vignette for a runnable walk-through. ## Not run: f <- apsim_example("Wheat") if (!is.na(f)) { apsim_sensitivity( f, parm_paths = "[Fertilise at sowing].Script.Amount", lower = 0, upper = 250, output = "Yield", method = "morris", morris_r = 4L, seed = 1L) } ## End(Not run)# Sensitivity analysis runs the simulator r(p + 1) times, so the example is # wrapped in \dontrun{}; see the package vignette for a runnable walk-through. ## Not run: f <- apsim_example("Wheat") if (!is.na(f)) { apsim_sensitivity( f, parm_paths = "[Fertilise at sowing].Script.Amount", lower = 0, upper = 250, output = "Yield", method = "morris", morris_r = 4L, seed = 1L) } ## End(Not run)
Launches apsim-server over loopback TCP, holding sim in memory, and opens a
connection to it. The returned handle runs the file repeatedly – optionally
with modified parameters – without re-paying APSIM's per-run load cost, which
is the throughput path for calibration and uncertainty loops. Returns an
apsim_abstention() when the server executable is unavailable.
apsim_server(sim, port = NULL, timeout = 30)apsim_server(sim, port = NULL, timeout = 30)
sim |
An |
port |
Integer loopback port, or |
timeout |
Numeric seconds to wait for the server to accept a connection (default 30). |
Always close the handle with close() to stop the server process.
An apsim_server handle (a classed environment), or an
apsim_abstention.
f <- apsim_example("Wheat") if (!is.na(f) && apsim_available()) { srv <- apsim_server(f) if (!is_apsim_abstention(srv)) { apsim_run(srv) close(srv) } }f <- apsim_example("Wheat") if (!is.na(f) && apsim_available()) { srv <- apsim_server(f) if (!is_apsim_abstention(srv)) { apsim_run(srv) close(srv) } }
.apsimx) as a typed objectReads an .apsimx (JSON) file into an S7 object holding the absolute file
path, the parsed model tree, and the APSIM version that produced it (or NA).
The object round-trips: apsim_write() writes the tree back unchanged.
apsim_sim(file)apsim_sim(file)
file |
Character path to an |
An apsim_sim S7 object.
f <- system.file("extdata", "Wheat.apsimx", package = "apsimR") if (nzchar(f)) { sim <- apsim_sim(f) apsim_simulations(sim) }f <- system.file("extdata", "Wheat.apsimx", package = "apsimR") if (nzchar(f)) { sim <- apsim_sim(f) apsim_simulations(sim) }
apsim_sim
Walks the model tree and returns the Name of every Models.Core.Simulation
node. Needs no simulator (it reads the parsed JSON).
apsim_simulations(x)apsim_simulations(x)
x |
An |
A character vector of simulation names (possibly empty).
f <- system.file("extdata", "Wheat.apsimx", package = "apsimR") if (nzchar(f)) apsim_simulations(apsim_sim(f))f <- system.file("extdata", "Wheat.apsimx", package = "apsimR") if (nzchar(f)) apsim_simulations(apsim_sim(f))
Pairs predicted with observed values and reports goodness-of-fit metrics plus a
typed performance verdict. predicted may be an apsim_predict() manifest, a
data.frame, or a numeric vector; observed a data.frame or numeric vector.
When both are data frames and by is given, they are joined on that key
(matching simulated and observed rows by, say, date) before scoring; otherwise
the two columns are paired by position and must be equal length.
apsim_validate( predicted, observed, predicted_col = NULL, observed_col = NULL, by = NULL )apsim_validate( predicted, observed, predicted_col = NULL, observed_col = NULL, by = NULL )
predicted |
An |
observed |
A |
predicted_col, observed_col
|
Column names when the corresponding input is a
|
by |
Optional key column present in both data frames to join on before pairing. |
An apsim_manifest with inferential_target = "validation": params
holds the one-row metrics table, outputs the paired observed/predicted
values, and metadata$verdict the performance grade.
The typed grade in metadata$verdict reads on
Nash-Sutcliffe efficiency (NSE) alone. The bands are those of Moriasi et
al. (2007) [unverified against the source paper], derived for monthly
watershed and streamflow simulations, not paddock-scale crop yield; that
paper's own recommendation is a joint reading of NSE with rsr and
pbias (both already reported in params), not NSE on its own. Treat the
grade as a diagnostic starting point, and read all three metrics before
trusting it.
Moriasi, D. N. et al. (2007) Model evaluation guidelines for systematic quantification of accuracy in watershed simulations. Transactions of the ASABE 50(3), 885-900. doi:10.13031/2013.23153
obs <- c(2.1, 3.4, 4.0, 5.2) sim <- c(2.0, 3.6, 3.8, 5.0) v <- apsim_validate(sim, obs) v@metadata$verdictobs <- c(2.1, 3.4, 4.0, 5.2) sim <- c(2.0, 3.6, 3.8, 5.0) v <- apsim_validate(sim, obs) v@metadata$verdict
Builds an observed-versus-predicted scatter with the 1:1 line, titled with the
verdict and key metrics. Requires the optional ggplot2 package; returns an
apsim_abstention() when it is absent.
apsim_validation_plot(validation)apsim_validation_plot(validation)
validation |
An |
A ggplot object, or an apsim_abstention.
v <- apsim_validate(c(2, 3.6, 3.8, 5), c(2.1, 3.4, 4, 5.2)) apsim_validation_plot(v)v <- apsim_validate(c(2, 3.6, 3.8, 5), c(2.1, 3.4, 4, 5.2)) apsim_validation_plot(v)
Runs Models --version and returns the reported version (for example
"2026.5.8046.0"), cached for the session. Returns NA_character_ when the
simulator is not available.
apsim_version()apsim_version()
A single character string, or NA_character_.
apsim_version()apsim_version()
apsim_sim back to an .apsimx fileSerialises the model tree to JSON. With no edits this is a faithful round-trip
of the file apsim_sim() read. Needs no simulator.
apsim_write(x, path = tempfile(fileext = ".apsimx"))apsim_write(x, path = tempfile(fileext = ".apsimx"))
x |
An |
path |
Character output path. Defaults to a new temporary |
Invisibly, the output path.
f <- system.file("extdata", "Wheat.apsimx", package = "apsimR") if (nzchar(f)) apsim_write(apsim_sim(f), tempfile(fileext = ".apsimx"))f <- system.file("extdata", "Wheat.apsimx", package = "apsimR") if (nzchar(f)) apsim_write(apsim_sim(f), tempfile(fileext = ".apsimx"))
The federation's emit and adapt generic. The apsim_manifest() method lifts
any apsimR result into the shared contract: the apsimR target is mapped onto
the contract's target enum (a sensitivity table is a statement about
parameters, an emulator and a validation are statements about predictions),
the assimilation context of an ensemble result is carried into the contract's
weights and obs_target slots, and a validation verdict is lifted into the
typed summary rather than left buried in metadata.
as_orchestra_manifest(x, ...)as_orchestra_manifest(x, ...)
x |
An |
... |
Method-specific arguments. The |
Nothing is discarded: the original apsimR target, the APSIM build that
produced the result and apsimR's own payload hash all ride in metadata, so
a consumer can trace a contract manifest back to the apsimR result it came
from.
An orchestra_manifest S7 object.
verify_manifest(), as_pesto_manifest()
m <- apsim_manifest("validation", "apsim:validate", params = data.frame(nse = 0.82, rmse = 0.31), outputs = data.frame(observed = c(2, 3.6), predicted = c(2.1, 3.4)), metadata = list(verdict = "good")) as_orchestra_manifest(m)m <- apsim_manifest("validation", "apsim:validate", params = data.frame(nse = 0.82, rmse = 0.31), outputs = data.frame(observed = c(2, 3.6), predicted = c(2.1, 3.4)), metadata = list(verdict = "good")) as_orchestra_manifest(m)
apsim_manifest to a PESTO ensemble manifestConverts to PESTO's pesto_ensemble_manifest S7 object (the orchestra's C2
contract) so an APSIM inversion result can be consumed by the
PESTO / kernR / flexyBayes stack.
as_pesto_manifest(x)as_pesto_manifest(x)
x |
An |
PESTO's contract is an ensemble contract, and the bridge respects that
rather than forcing every payload through it. It requires two things, both
read from the installed PESTO (0.10.1 at the time of writing) rather than
assumed: a method tag drawn from PESTO's own enum, and a parameter ensemble
whose rows align one-for-one with a simulated-observation ensemble. Exactly
one apsimR result satisfies that – the posterior ensemble from
apsim_calibrate()'s ies backend, which PESTO's own ensemble smoother
produced. Every other apsimR result (a prediction, a screening table, an
emulator, a validation verdict) is not an ensemble inversion, so the bridge
returns a feature_unsupported apsim_abstention() naming the reason
instead of a manifest whose slots would have to be invented. Those results
compose through as_orchestra_manifest(), the federation's general contract.
The bridged manifest is re-hashed with PESTO's own payload recipe, so
PESTO::verify_manifest() verifies it; apsimR's own hash is kept in the
bridge's provenance chain through the source manifest.
A PESTO::pesto_ensemble_manifest, or an apsim_abstention with
reason "runtime_unavailable" (PESTO absent) or "feature_unsupported"
(the payload is not an ensemble inversion).
as_orchestra_manifest() for the general orchestra contract.
# A prediction is not an ensemble inversion, so the bridge declines. as_pesto_manifest(apsim_manifest("predictions", "apsim:predict", outputs = data.frame(Yield = 3.8)))# A prediction is not an ensemble inversion, so the bridge declines. as_pesto_manifest(apsim_manifest("predictions", "apsim:predict", outputs = data.frame(Yield = 3.8)))
Is an object an apsimR abstention?
is_apsim_abstention(x)is_apsim_abstention(x)
x |
Any object. |
A single logical: TRUE when x is an apsim_abstention.
is_apsim_abstention(apsim_abstention("run_failed")) is_apsim_abstention(42)is_apsim_abstention(apsim_abstention("run_failed")) is_apsim_abstention(42)
A non-ensemble inference – a validation verdict, a decision – has no meaningful
values for the ensemble payload slots and should not ride in params as a
one-row pseudo-parameter table. The contract's optional summary slot carries
the headline label, whether the emitter abstained, and the key metrics. It is
integrity-hashed with the rest of the payload, so a tampered verdict is
detected. The class and field names match the reference contract's
manifest_summary() exactly, so a consumer reads an apsimR verdict with no
special casing.
manifest_summary( headline, abstained = FALSE, metrics = list(), abstain_reason = NA_character_ )manifest_summary( headline, abstained = FALSE, metrics = list(), abstain_reason = NA_character_ )
headline |
Character scalar: the verdict itself, for example |
abstained |
Logical scalar: did the emitter decline to stand behind the result? |
metrics |
Named list of supporting numbers. |
abstain_reason |
Character scalar reason when |
A manifest_summary list.
manifest_summary("good", metrics = list(nse = 0.82))manifest_summary("good", metrics = list(nse = 0.82))
A versioned, hashed, provenance-complete S7 result object, property-compatible
with the federation's reference orchestra_manifest and carrying the same
bare class identity, so any orchestra consumer reads an apsimR result without
special casing. Build one from an apsim_manifest() with
as_orchestra_manifest() rather than calling this constructor directly.
An S7 object of class orchestra_manifest.
as_orchestra_manifest(), verify_manifest()
Recomputes the payload hash from the object's own load-bearing slots and
compares it to the stored data_hash. A mismatch means the payload was
modified after emission. Matches the reference contract's verify_manifest(),
so the check is symmetric across members.
verify_manifest(m)verify_manifest(m)
m |
An |
A list with a logical ok and a human-readable message.
m <- apsim_manifest("predictions", "apsim:predict", outputs = data.frame(Yield = c(3.8, 4.1))) verify_manifest(as_orchestra_manifest(m))m <- apsim_manifest("predictions", "apsim:predict", outputs = data.frame(Yield = c(3.8, 4.1))) verify_manifest(as_orchestra_manifest(m))