| Type: | Package |
| Title: | Probabilistic Simulation of Single-Entity Systems in Irregular Time |
| Version: | 2.0.0 |
| Author: | Jarrod Dalton [aut, cre] |
| Maintainer: | Jarrod Dalton <daltonj@ccf.org> |
| Description: | A foundation for probabilistic simulation of single-entity systems in which events occur at irregular times and each event updates only a small, sparse subset of the entity's state. Models are assembled from a declared schema and a 'ModelBundle' of callback functions (event proposal, state transition, stopping rule) and run through a single validated entry point, 'load_model()'. Supports competing event processes, schema-declared decision points with user-supplied policies, typed parameter draws for representing uncertainty, and optional trajectory recording for auditing simulated decisions. Designed to be domain agnostic: this package contains no model of any particular system, only the scaffolding for building one. |
| License: | LGPL-3 |
| Encoding: | UTF-8 |
| Imports: | R6 |
| Suggests: | future, future.apply, jsonlite, parallel, testthat (≥ 3.0.0) |
| Config/testthat/edition: | 3 |
| Config/roxygen2/version: | 8.0.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-07-17 23:10:01 UTC; daltonj |
| Repository: | CRAN |
| Date/Publication: | 2026-07-28 16:00:08 UTC |
Construct an ActionEvent
Description
Timeline-native action proposed by a policy at a decision point. ActionEvents enter the same arbitration and refresh lifecycle as all other events — no side-channel state mutation.
Usage
ActionEvent(
action_type,
time_next,
decision_point_id = NULL,
params = NULL,
metadata = NULL
)
Arguments
action_type |
Character scalar; must match an |
time_next |
Numeric scalar; realization time on the canonical timeline. |
decision_point_id |
Character scalar; which decision point produced this
action. If |
params |
Optional named list of action-specific parameters. |
metadata |
Optional named list for policy provenance or audit fields. |
Value
A list of class "ActionEvent".
Construct a DecisionPoint specification
Description
Declares a point in the simulation where a policy may be consulted. Decision
points are declared in the Schema (schema$decision_points), not inferred at
runtime.
Usage
DecisionPoint(
id,
trigger,
allowed_actions = NULL,
action_handlers = NULL,
condition = NULL,
audit = FALSE,
observation_fn = NULL,
label = NULL
)
Arguments
id |
Character scalar; unique identifier (e.g., |
trigger |
Character vector of event types and/or a predicate function
|
allowed_actions |
Optional character vector of named action types. If
|
action_handlers |
Optional named list of functions, keyed by action type.
Each function has signature |
condition |
Optional function |
audit |
Logical scalar (default |
observation_fn |
Optional function |
label |
Optional human-readable description. |
Value
A list of class "DecisionPoint".
Engine
Description
Orchestrates simulation by repeatedly proposing the next event(s), applying a transition patch, recording the event on a Entity, and stopping when bundle$stop() returns TRUE (or a max_time / max_events limit is reached).
Methods
Public methods
Engine$new()
Usage
Engine$new(bundle = NULL, ...)
Engine$run()
Usage
Engine$run( entity, max_events = 1000, max_time = NULL, return_observations = TRUE, .internal_ctx = NULL )
Engine$run_draw()
Usage
Engine$run_draw( entity, params = list(), draw_id = 1L, sim_id = 1L, max_events = 1000, max_time = NULL, return_observations = TRUE )
Engine$clone()
The objects of this class are cloneable with this method.
Usage
Engine$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Entity
Description
R6 simulation state container used by fluxCore::Engine. An Entity stores current state, event history, derived-variable registrations, and metadata such as id and optional meta$entity_type.
Methods
Public methods
Entity$new()
Usage
Entity$new( init = list(), schema, derived_vars = NULL, id = NULL, entity_type = NULL, time0 = 0, event_type0 = "init" )
Entity$state()
Usage
Entity$state(vars = NULL)
Entity$as_list()
Usage
Entity$as_list(vars = NULL)
Entity$update()
Usage
Entity$update(time, event_type, changes = NULL)
Entity$state_at_time()
Usage
Entity$state_at_time(time, vars = NULL)
Entity$snapshot()
Usage
Entity$snapshot(vars = NULL)
Entity$snapshot_at()
Usage
Entity$snapshot_at(j, vars = NULL)
Entity$snapshot_at_time()
Usage
Entity$snapshot_at_time(time, vars = NULL)
Entity$state_at()
Usage
Entity$state_at(j, vars = NULL)
Entity$clone()
The objects of this class are cloneable with this method.
Usage
Entity$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Construct an EnvironmentContext
Description
Optional. Provides named external signals and world-step/reset hooks for ABM or RL scenarios. Designed to accommodate multi-entity ABM (an add-on sub-repo) without requiring Engine architectural changes.
Usage
EnvironmentContext(
signals = NULL,
step_fn = NULL,
reset_fn = NULL,
info = NULL
)
Arguments
signals |
Optional named list of external signal values visible to the policy at each decision point. |
step_fn |
Optional function; advances the world by one step (ABM/RL use cases). |
reset_fn |
Optional function; resets the world state (RL use cases). |
info |
Optional named list of auxiliary metadata from the environment. |
Value
A list of class "EnvironmentContext".
FileProvider (internal)
Description
Loads a bundle from an .rds file. Expects model_spec$path.
Details
Deprecated in v2.0.0. Use load_model() or Engine$new(bundle = ...) instead.
Methods
Public methods
FileProvider$new()
Usage
FileProvider$new(base_path = NULL)
Arguments
base_pathOptional base directory.
FileProvider$load()
Usage
FileProvider$load(model_spec, ...)
FileProvider$sample_param_draws()
Usage
FileProvider$sample_param_draws(model_spec, n_param_draws = 1L, ...)
FileProvider$clone()
The objects of this class are cloneable with this method.
Usage
FileProvider$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
MLflowProvider (internal stub)
Description
Scaffold for MLflow-based workflows. model_spec should include at least model_uri and optionally references to artifacts needed to build a bundle.
Details
Deprecated in v2.0.0. Use load_model() or Engine$new(bundle = ...) instead.
Methods
Public methods
MLflowProvider$new()
Usage
MLflowProvider$new(builder_fn, sampler_fn = NULL)
Arguments
builder_fnFunction returning a ModelBundle.
sampler_fnOptional function returning a list of length D parameter contexts.
MLflowProvider$load()
Usage
MLflowProvider$load(model_spec, ...)
MLflowProvider$sample_param_draws()
Usage
MLflowProvider$sample_param_draws(model_spec, n_param_draws = 1L, ...)
MLflowProvider$clone()
The objects of this class are cloneable with this method.
Usage
MLflowProvider$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
PackageProvider (internal)
Description
Loads a bundle from in-package functions/objects. Use model_spec$name to select among multiple bundle builders.
Details
Deprecated in v2.0.0. Use load_model() or Engine$new(bundle = ...) instead.
Methods
Public methods
PackageProvider$new()
Usage
PackageProvider$new(registry)
Arguments
registryNamed list mapping bundle names to functions returning ModelBundles.
PackageProvider$load()
Usage
PackageProvider$load(model_spec = list(), ...)
PackageProvider$sample_param_draws()
Usage
PackageProvider$sample_param_draws( model_spec = list(), n_param_draws = 1L, ... )
PackageProvider$clone()
The objects of this class are cloneable with this method.
Usage
PackageProvider$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Construct a ParamContext
Description
Encapsulates one parameter realization for a simulation run. Resolved once
per draw by a ParamSource (or supplied directly) and injected into every
bundle callback that accepts a param_ctx argument.
Usage
ParamContext(draw_id, params, provenance = NULL)
Arguments
draw_id |
Integer scalar identifying this parameter draw. |
params |
Named list of concrete parameter values. |
provenance |
Optional character scalar labelling the source of this
draw (e.g., |
Value
A list of class "ParamContext".
Construct a RuntimeContext
Description
Captures reproducibility and backend settings for one simulation run.
Supplied to load_model() or run_cohort() in v2 mode; also accepted
by Engine$run() when the Engine was created via load_model().
Usage
RuntimeContext(
seed = NULL,
replicate_id = NULL,
backend = "none",
n_workers = NULL
)
Arguments
seed |
Optional integer scalar; top-level seed. NULL = unseeded. |
replicate_id |
Optional integer scalar; stochastic replicate index within a draw. |
backend |
Character scalar; one of |
n_workers |
Optional integer; number of parallel workers. |
Details
The public reproducibility contract is:
seed + draw_id + replicate_id + entity_id = deterministic output.
Internal stream allocation (stream_id) is set by the run harness and
must not be set by users directly.
Value
A list of class "RuntimeContext".
Construct a SimContext
Description
Captures invariant simulation-level metadata for one Engine run. Created
once by load_model() / Engine$run() in v2 mode and passed to every
bundle callback that accepts a sim_ctx argument.
Usage
SimContext(
run_id,
time_spec,
model_id = NULL,
scenario_id = NULL,
horizon = NULL
)
Arguments
run_id |
Character scalar; unique identifier for this simulation run. |
time_spec |
A |
model_id |
Optional character scalar identifying the model. |
scenario_id |
Optional character scalar labelling an experimental condition. |
horizon |
Optional numeric scalar declaring the simulation horizon. |
Value
A list of class "SimContext".
Construct a TrajectoryRecord
Description
Engine-owned audit record emitted at each decision point when a
TrajectoryLogger is configured. This is the canonical surface for policy
evaluation, audit, and RL reward computation.
Usage
TrajectoryRecord(
run_id,
entity_id,
t,
decision_point_id,
observation,
realized_event,
candidate_actions = NULL,
proposed_actions = NULL,
selected_action = NULL,
state_before = NULL,
state_after = NULL,
condition_met = NULL,
reward = NULL
)
Arguments
run_id |
Character scalar; run identifier (from |
entity_id |
Character scalar; entity identifier. |
t |
Numeric scalar; time at which the decision point fired. |
decision_point_id |
Character scalar; which decision point produced this record. |
observation |
Named list; output of the decision point's
|
realized_event |
The event record that triggered the decision point. |
candidate_actions |
Optional character vector of actions presented to the policy. |
proposed_actions |
Optional list of actions proposed by the policy. |
selected_action |
Optional |
state_before |
Optional named list; entity state before the event.
|
state_after |
Optional named list; entity state after the transition.
|
condition_met |
Logical scalar or |
reward |
Optional numeric or named list; reward signal(s). |
Details
state_before and state_after are NULL by default. Supply a
summary_fn to the TrajectoryLogger to enable summary-level or full capture.
Value
A list of class "TrajectoryRecord".
Coerce to time_spec
Description
Coerces various inputs into a validated time_spec object. Accepts:
A
time_specobject (pass-through)A named list with
unit(required) and optionallyorigin,zone
Usage
as_time_spec(x, ...)
Arguments
x |
Object to coerce. |
... |
Additional arguments (unused). |
Value
A validated time_spec object.
Get variable names in a schema block
Description
Convenience helper to look up the variables belonging to a named schema block (e.g., "bp", "cbc", "cbc_diff", "bmp", "cmp"). Membership is many-to-many: a variable may appear in multiple blocks.
Usage
block_vars(schema, block)
Arguments
schema |
An entity state schema (named list). |
block |
Block name (character scalar). |
Value
Character vector of variable names in the order they appear in schema.
Register derived variables on an Entity
Description
Validates and registers derived-variable functions for snapshot-time evaluation.
Usage
check_derived(entity, derived_vars, replace = FALSE)
Arguments
entity |
A Entity object. |
derived_vars |
Named list of derived-variable functions, or NULL. |
replace |
If TRUE, overwrite existing derived vars with the same names. |
Value
Returns entity invisibly.
Combine multiple update lists into one atomic update payload
Description
Convenience helper for transition() implementations that need to apply multiple update sources (e.g., scalar tweaks plus one or more block updates). The function concatenates named lists and errors if any variable is updated more than once within the same event.
Usage
combine_updates(...)
Arguments
... |
One or more named lists of updates (or NULL). |
Value
A single named list of updates, or NULL if all inputs are NULL.
Compose ModelBundles and transition components
Description
These helpers make it easy to layer policy/intervention logic on top of baseline natural history dynamics without rewriting the baseline bundle.
Usage
compose_bundles(
baseline,
policy = NULL,
merge = c("policy_wins", "baseline_wins", "error_on_conflict")
)
Arguments
baseline |
Baseline model bundle list. |
policy |
Optional policy/intervention bundle list overriding selected components. |
merge |
Patch conflict strategy for transition updates: "policy_wins", "baseline_wins", or "error_on_conflict". |
Target a variable for history-derived features
Description
declare_variable() constructs a target that refers to a state variable's sparse history in entity$hist. It is used to define derived features based on recent values (e.g., counts, means, lags) when building model-ready snapshots.
Usage
declare_variable(name)
Arguments
name |
Single variable name (character scalar). |
Value
A target list used by derive() and lag_of().
Define a derived feature
Description
derive() returns a function computing a history-derived feature as of (j, t). Intended to populate Entity$derived_vars and be used by Entity$snapshot*().
Usage
derive(
name,
target,
lookback_t = NULL,
lookback_j = NULL,
fn = c("count", "min", "max", "mean", "median", "sd", "iqr", "any", "all"),
include_current = TRUE,
force = FALSE,
na_value = NA,
clock = "time"
)
Arguments
name |
Name of the derived feature. |
target |
A target created by event() or declare_variable(). |
lookback_t |
Optional numeric lookback window on the time axis. Takes precedence over lookback_j. |
lookback_j |
Optional integer lookback window in event-index units. |
fn |
Summary function name. For event() targets, only count, any, and all are supported. |
include_current |
Logical; include the boundary event at t/j (default TRUE). |
force |
Logical; if TRUE, return a value when there is no history (default FALSE). |
na_value |
Value to return when force=TRUE and no history exists (default NA). |
clock |
Which column in entity$events defines the time axis for lookback_t (default "time"). |
Value
A function (entity, j, t) -> scalar or NULL.
Test whether a DecisionPoint fires for a given event
Description
Used internally by the Engine to detect decision points during the simulation loop.
Usage
dp_fires(dp, event)
Arguments
dp |
A |
event |
An event list with at least |
Value
Logical scalar.
Feature target: event type
Description
Create a target describing events of a given type in entity$events.
Usage
event(event_type)
Arguments
event_type |
Character scalar. |
Value
A target list used by derive().
Define a lagged feature from variable history
Description
Extract the k-th most recent value of a variable from sparse history as of (j, t).
Usage
lag_of(
name,
target,
k = 1,
lookback_t = NULL,
lookback_j = NULL,
include_current = FALSE,
force = FALSE,
na_value = NA,
clock = "time"
)
Arguments
name |
Name of the derived feature. |
target |
A target created by declare_variable(). |
k |
Positive integer lag order (1 = most recent prior value by default). |
lookback_t |
Optional numeric lookback window on the time axis. Takes precedence over lookback_j. |
lookback_j |
Optional integer lookback window in event-index units. |
include_current |
Logical; include boundary event at t/j (default FALSE). |
force |
Logical; if TRUE return na_value when insufficient history exists (default FALSE). |
na_value |
Value to return when force=TRUE and insufficient history exists (default NA). |
clock |
Which column in entity$events defines the time axis for lookback_t (default "time"). |
Value
A function (entity, j, t) -> scalar or NULL.
Assemble and validate a simulation model (v2.0.0 API)
Description
load_model() is the recommended entry point for the v2.0.0 architecture.
It validates all supplied components against the schema and against each
other, applies defaults, and returns a configured Engine in v2 mode.
Usage
load_model(
schema,
bundle,
policy = NULL,
environment = NULL,
trajectory = NULL,
runtime = NULL,
param_source = NULL
)
Arguments
schema |
A validated schema list (from |
bundle |
A ModelBundle list with at minimum |
policy |
Optional. A function or list with a |
environment |
Optional. An EnvironmentContext for ABM/RL scenarios. |
trajectory |
Optional. A TrajectoryLogger configuration list; enables
TrajectoryRecord emission. Requires |
runtime |
Optional. A RuntimeContext specifying reproducibility and
backend settings. Defaults are applied when |
param_source |
Optional. A ParamSource that resolves ParamContexts once per run. |
Details
Engines returned by load_model() enforce the following at runtime:
-
Fail fast on
ctx-style usage: passing actx=argument toEngine$run()raises an immediate error. Use typed context objects (SimContext,ParamContext,RuntimeContext) instead. All bundle callbacks must accept
sim_ctxandparam_ctxin their formals (warnings emitted for v1.x-stylectxformals).
Value
An Engine object with v2_mode = TRUE.
User experience tiers
| Level | Entry point | What you supply |
| 1 | load_model(schema, bundle) | In-memory schema + bundle |
| 2 | load_model(schema, bundle, ...) + JSON schema export | JSON spec + language code |
| 3 | All optional components supplied | Full stack |
Trajectory output contract
When trajectory is configured, the Engine returned by load_model() emits
trajectory_records in run outputs.
-
Engine$run(...)includestrajectory_recordswhen trajectory logging is enabled. -
run_cohort(...)run entries include per-runtrajectory_recordswhen enabled. -
trajectory_recordsis a list of plain named lists (JSON-serializable). -
trajectory$detailcontrols state capture:-
none:state_beforeandstate_afterareNULL. -
summary: both are outputs ofsummary_fn(defaultstate_summary_default()). -
full: both are full snapshots ofentity$current.
-
See Also
SimContext(), ParamContext(), RuntimeContext(),
EnvironmentContext(), DecisionPoint(), TrajectoryRecord()
Run a cohort of entities (serial or parallel) with optional global parameter draws
Description
These helpers support batch simulation with: global parameter draws reused across entities (parameter uncertainty) multiple stochastic sims per entity per draw (stochastic uncertainty) parallelization across entities
Usage
run_cohort(
engine,
entities,
n_param_draws = 1,
n_sims = 1,
param_draws = NULL,
runtime = NULL,
max_events = 1000,
max_time = NULL,
return_observations = TRUE,
backend = NULL,
n_workers = NULL,
seed = NULL
)
Arguments
engine |
An Engine object (with a materialized bundle). |
entities |
List of Entity objects. |
n_param_draws |
Integer; number of global parameter draws (D). Default 1. |
n_sims |
Integer; number of stochastic sims per entity per draw (S). Default 1. |
param_draws |
Optional; a list of length D with per-draw parameter contexts. If NULL, the function will attempt to call engine$bundle$sample_params(D) when available; otherwise it uses a single NULL draw (no global parameter variation). |
runtime |
Optional RuntimeContext; carries seed, backend, and n_workers for v2-mode
engines. Takes precedence over the individual |
max_events |
Max events per run. |
max_time |
Optional max time per run. |
return_observations |
Logical; whether to return observations (if bundle provides observe()). |
backend |
Backend used to parallelize across entities. One of "none", "cluster",
"mclapply", or "future". Default is "none". Ignored when |
n_workers |
Integer; workers for parallel; default parallel::detectCores() - 1.
Ignored when |
seed |
Optional base seed for reproducibility. Public contract:
fixed |
Value
A list with: runs: list of per-run outputs (entity/events/observations; plus trajectory_records when enabled) with labels index: data.frame mapping run_id -> entity_id/param_draw_id/sim_id
Assert that levels are declared in the schema
Description
For binary/categorical/ordinal variables, stops if any provided levels are not declared in the schema.
Usage
schema_assert_levels(schema, var, levels)
Arguments
schema |
A validated schema (or a raw schema that can be validated). |
var |
A single variable name. |
levels |
Character vector of levels to check. |
Value
Invisibly returns TRUE.
Assert that variables have allowed schema types
Description
Stops with an informative error if any variables have schema types outside the allowed set.
Usage
schema_assert_types(schema, vars, allowed_types)
Arguments
schema |
A validated schema (or a raw schema that can be validated). |
vars |
Character vector of variable names. |
allowed_types |
Character vector of allowed schema types. |
Value
Invisibly returns TRUE.
Assert that variables exist in a schema
Description
Stops with an informative error if any requested variable names are not present in the schema.
Usage
schema_assert_vars(schema, vars)
Arguments
schema |
A validated schema (or a raw schema that can be validated). |
vars |
Character vector of variable names. |
Value
Invisibly returns TRUE.
List unique schema blocks
Description
Extract the set of unique block names declared in a schema via the optional blocks metadata field on each variable entry. Variables may belong to multiple blocks (many-to-many).
Usage
schema_blocks(schema)
Arguments
schema |
An entity state schema (named list). |
Value
Character vector of unique block names.
Validate an entity schema
Description
Validates the structure and required metadata of an entity schema. The schema is a named list where each entry describes one state variable.
Usage
schema_validate(schema)
Arguments
schema |
A named list schema. |
Value
The validated schema (invisibly), with normalized type fields.
Create an integer schema validator
Description
Returns a predicate function that checks a scalar integer value against inclusive numeric bounds and optional missingness.
Usage
schema_validator_integer(min = -Inf, max = Inf, allow_na = FALSE)
Arguments
min |
A single numeric lower bound. |
max |
A single numeric upper bound. |
allow_na |
Logical scalar indicating whether missing values are permitted. |
Value
A function of signature function(x) -> TRUE/FALSE.
Create a levels-based schema validator
Description
Returns a predicate function that checks a scalar value against a set of allowed character levels and optional missingness.
Usage
schema_validator_levels(levels, allow_na = FALSE)
Arguments
levels |
A character vector of allowed level labels. |
allow_na |
Logical scalar indicating whether missing values are permitted. |
Value
A function of signature function(x) -> TRUE/FALSE.
Create a numeric schema validator
Description
Returns a predicate function that checks a scalar numeric value against inclusive numeric bounds and optional missingness.
Usage
schema_validator_numeric(min = -Inf, max = Inf, allow_na = FALSE)
Arguments
min |
A single numeric lower bound. |
max |
A single numeric upper bound. |
allow_na |
Logical scalar indicating whether missing values are permitted. |
Value
A function of signature function(x) -> TRUE/FALSE.
Get schema metadata for variables
Description
Returns schema metadata (type, levels, blocks) for the requested variables.
Usage
schema_var_info(schema, vars)
Arguments
schema |
A validated schema (or a raw schema that can be validated). |
vars |
Character vector of variable names. |
Value
A data.frame with columns var, type, levels, and blocks.
Build or extend a fluxCore schema with hybrid shorthand
Description
Constructs a validated fluxCore schema from a hybrid vars specification.
Each element of vars may be either a type-name string (e.g. "count") or
a fully-specified list (e.g. list(type = "positive_numeric", max = 20)).
Optionally merges onto an existing schema, with explicit overwrite and
remove controls.
Usage
set_schema(
vars = NULL,
schema = NULL,
remove = NULL,
overwrite = FALSE,
time_spec = NULL,
decision_points = NULL
)
Arguments
vars |
Named list (or character vector) of variable specs. Each element
is either a single type-name string or a list containing |
schema |
Optional existing schema to extend. If |
remove |
Optional character vector of variable names to remove from
|
overwrite |
Logical scalar. If |
time_spec |
Optional |
decision_points |
Optional list of |
Details
When time_spec or decision_points is supplied, set_schema() returns a
full schema list (with $variables, $time_spec, and
$decision_points) suitable for direct use with load_model(). When
neither is supplied, it returns just the validated variables spec (backward-
compatible with prior usage and with Entity$new(schema = ...)).
Value
A validated fluxCore variables spec (named list), or — when
time_spec or decision_points is supplied — a full schema list with
$variables, $time_spec, and $decision_points.
Examples
# Variables only (backward-compatible):
vars <- set_schema(vars = list(
route_zone = list(type = "categorical",
levels = c("urban", "suburban", "rural")),
battery_pct = "percent",
payload_kg = list(type = "positive_numeric", max = 20),
deliveries = "count",
prob_rain = "probability"
))
# Full schema for load_model():
dp <- DecisionPoint(id = "dp1", trigger = "event_A",
allowed_actions = c("accept", "decline"))
schema <- set_schema(
vars = list(battery_pct = "percent"),
time_spec = time_spec(unit = "hours"),
decision_points = list(dp)
)
# schema$variables, schema$time_spec, schema$decision_points are all set.
Create a named list of updates from variable names and values
Description
Many models generate multivariate predictions (e.g., SBP/DBP, CBC panels) but Entity$update() expects a named list of scalar changes. set_vars() converts vectors into the expected named-list format.
Usage
set_vars(vars, values)
Arguments
vars |
Character vector of variable names. |
values |
Vector of values (same length as vars). |
Value
Named list suitable for transition() returns.
Create a named list of updates from a named vector
Description
Convert a named vector into a named list suitable for returning from transition(). Optionally select and order a subset via vars.
Usage
set_vars_from_named(x, vars = NULL)
Arguments
x |
Named vector (e.g., numeric) of updates. |
vars |
Optional character vector specifying which names to take and in what order.
If provided, values are taken as |
Value
Named list suitable for transition() returns.
Default state summary function for TrajectoryRecord
Description
Captures a compact named list of all current variable values from an entity.
Used as the default summary_fn when state_before or state_after is
requested in a TrajectoryLogger with detail = "summary".
Usage
state_summary_default(entity, ...)
Arguments
entity |
An |
... |
Reserved for future arguments (ignored). |
Details
Implementors may supply a custom summary function with the same signature:
function(entity, ...) returning a named list.
Value
A named list of variable values.
Convert numeric model time to calendar time
Description
Converts numeric model time to Date or POSIXct using a compiled time spec.
Usage
time_from_model(t, time_spec, class = c("origin", "Date", "POSIXct"))
Arguments
t |
Numeric model time. |
time_spec |
A compiled time spec from time_spec(unit = ...). |
class |
Output class: 'origin' (match the origin class), 'Date', or 'POSIXct'. |
Value
A Date or POSIXct vector.
Compile and validate canonical time settings
Description
Compiles and validates time settings from explicit unit, origin, and zone parameters. v2.0 only supports explicit time_spec() calls; ctx fallback was removed.
Usage
time_spec(unit = NULL, origin = NULL, zone = "UTC")
Arguments
unit |
Required time unit. One of "seconds", "minutes", "hours", "days", "weeks", "months", "years". |
origin |
Optional Date or POSIXct/POSIXt origin used for calendar-time conversion. Defaults to Unix epoch. |
zone |
Time zone used for calendar-time conversion (default "UTC"). |
Value
An object of class time_spec with precomputed conversion constants.
Convert calendar time to numeric model time
Description
Converts numeric, Date, or POSIXct/POSIXt time to numeric model time under a compiled time spec.
Usage
time_to_model(x, time_spec)
Arguments
x |
A numeric vector, Date, or POSIXct/POSIXt vector of times. |
time_spec |
A compiled time spec from time_spec(unit = ...). |
Value
Numeric model time in units of time_spec$unit.
Compile trajectory records into a data frame
Description
Takes the list of trajectory records from an engine run and returns a tidy data frame with one row per decision point firing.
Usage
trajectory_table(records, vars = NULL)
Arguments
records |
List of trajectory records (from |
vars |
Character vector of state variable names to extract from
|
Value
A data.frame with columns: t, decision_point_id, trigger_event,
action_taken, condition_met, plus <var>_before and <var>_after for
each requested variable.
Block-oriented state updates for vectorized models
Description
Many models generate multivariate outputs (e.g., SBP/DBP or lab panels). update_block() validates a named payload against an entity's schema and a named schema block, then returns a named list of per-variable state updates for use as a transition() return value.
Usage
update_block(
entity,
block,
values,
require_all = TRUE,
unknown = c("error", "drop_warn_once", "drop_warn_always")
)
Arguments
entity |
A Entity object. |
block |
Block name (character scalar) corresponding to |
values |
Named vector or named list of values to update. Names must correspond to state variables in the entity's schema. |
require_all |
Logical; if TRUE (default) all variables belonging to block must be supplied in values. |
unknown |
Policy for variables supplied in values that are not present in the entity's schema. One of "error" (default), "drop_warn_once", or "drop_warn_always". |
Value
A named list of state updates suitable for returning from transition(). Values are returned in schema block order.