API reference¶
Auto-generated from the radCAD source docstrings.
radcad.wrappers¶
The user-facing modelling classes: Model, Simulation, and Experiment.
radcad.wrappers ¶
User-facing classes for describing and running radCAD simulations.
This module provides the three classes that make up the radCAD modelling hierarchy: Model > Simulation > Experiment. A Model captures what the system is, a Simulation captures how long and how many times to run it, and an Experiment groups one or more simulations so they can be executed together by the Engine.
Model ¶
A dynamical-system model: an initial state plus the rules that evolve it.
A Model bundles together the three things needed to describe a system:
the initial_state of its State Variables, the state_update_blocks
(Partial State Update Blocks) that transition state from one timestep to
the next, and the params (System Parameters) those rules depend on.
A Model is also iterable: iterating over it advances the system one
timestep at a time, which is useful for live digital twins, gradient
descent, or composing one model inside another. See __iter__ and
__call__.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_state
|
dict
|
Mapping of State Variable name to initial value. |
{}
|
state_update_blocks
|
list
|
Ordered list of Partial State Update
Blocks, each a dict with |
[]
|
params
|
dict | dataclass
|
System Parameters, either as a dict of lists (for sweeps) or a (possibly nested) dataclass. |
{}
|
Source code in radcad/wrappers.py
__iter__ ¶
Advance the model one timestep per iteration, yielding self.
Each iteration runs a single-timestep simulation from the current
state, updates state and substeps, and yields
the model so the caller can read the new state. Only single-subset
models are supported (no parameter sweeps when iterating).
Source code in radcad/wrappers.py
__call__ ¶
Configure execution options for iteration, then return self.
Lets you set engine-style options before iterating, e.g.
next(model(deepcopy=False, drop_substeps=True)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**raise_exceptions
|
bool
|
Raise on failure rather than collecting
exceptions. Defaults to |
required |
**deepcopy
|
bool
|
Deepcopy state to prevent unintended mutation.
Defaults to |
required |
**deepcopy_method
|
Callable
|
Custom deepcopy implementation. |
required |
**drop_substeps
|
bool
|
Keep only the final substep per timestep.
Defaults to |
required |
Returns:
| Type | Description |
|---|---|
Model
|
|
Source code in radcad/wrappers.py
Simulation ¶
Bases: Executable
A Model together with a number of timesteps and runs.
A Simulation answers "run this model for how long, and how many times?".
The number of runs drives Monte Carlo analysis, while the model's
System Parameters drive parameter sweeps. Call run (or wrap it in
an Experiment) to execute it via the
Engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model
|
The model to simulate. |
required |
timesteps
|
int
|
Number of timesteps per run. Defaults to |
100
|
runs
|
int
|
Number of (Monte Carlo) runs. Defaults to |
1
|
Additional Executable keyword arguments (engine and the
lifecycle hooks) are also accepted.
Source code in radcad/wrappers.py
run ¶
Execute the simulation and return its results.
Returns:
| Type | Description |
|---|---|
SimulationResults
|
A flat list of state dictionaries, one per
substep, suitable for |
Experiment ¶
Bases: Executable
A collection of Simulation objects run together.
Grouping simulations into an Experiment lets the Engine execute them in parallel (e.g. for A/B tests) and collects their results and exceptions in one place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulations
|
Simulation | list
|
A simulation or list of simulations. |
[]
|
Additional Executable keyword arguments (engine and the
lifecycle hooks) are also accepted.
Source code in radcad/wrappers.py
run ¶
Execute every simulation in the experiment and return the results.
Returns:
| Type | Description |
|---|---|
SimulationResults
|
A flat list of state dictionaries across all
simulations, suitable for |
Source code in radcad/wrappers.py
add_simulations ¶
Append one or more Simulation objects to the experiment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulations
|
Simulation | list
|
Simulation(s) to add. |
required |
Raises:
| Type | Description |
|---|---|
Exception
|
If any item is not a Simulation. |
Source code in radcad/wrappers.py
clear_simulations ¶
Remove all simulations.
Returns:
| Type | Description |
|---|---|
bool
|
|
Executable ¶
Base class for things the Engine can run.
Holds the shared machinery for both Simulation and
Experiment: the Engine instance, the
results and exceptions populated after a run, and the lifecycle
hooks used to extend behaviour without modifying the core. Not intended to
be instantiated directly.
Accepts the following keyword arguments: engine (an
Engine, defaulting to a new instance) and the
optional lifecycle hooks before_experiment, after_experiment,
before_simulation, after_simulation, before_run, after_run,
before_subset, and after_subset.
Source code in radcad/wrappers.py
__deepcopy__ ¶
Deepcopy the executable, resetting the engine's run generator first.
The engine's _run_generator is not picklable/copyable once a run
has started, so it is reset to an empty iterator before copying.
Source code in radcad/wrappers.py
run ¶
radcad.engine¶
The execution engine.
radcad.engine ¶
The execution engine that runs simulations and experiments.
The Engine turns the declarative description in a Simulation or Experiment into actual computation. It expands parameter sweeps and runs, dispatches the work to a chosen parallel-processing Backend, fires lifecycle hooks, and gathers the results and any exceptions.
Engine ¶
Configures and executes experiments and simulations.
The Engine owns all execution-time settings (which parallel-processing backend to use, how many processes, whether to deepcopy state, how to handle exceptions) and drives the run loop over every simulation, run, and parameter subset. An Engine can be passed to a Simulation or Experiment to customise execution.
See __init__ for the full list of options.
Handles configuration and execution of experiments and simulations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**backend
|
Backend
|
Which execution backend to use (e.g. Pathos, Multiprocessing, etc.). Defaults to |
required |
**processes
|
int
|
Number of system CPU processes to spawn. Defaults to |
required |
**raise_exceptions
|
bool
|
Whether to raise exceptions, or catch them and return exceptions along with partial results. Default to |
required |
**deepcopy
|
bool
|
Whether to enable deepcopy of State Variables to avoid unintended state mutation. Defaults to |
required |
**deepcopy_method
|
Callable
|
Method to use for deepcopy of State Variables. By default uses Pickle for improved performance, use |
required |
**drop_substeps
|
bool
|
Whether to drop simulation result substeps during runtime to save memory and improve performance. Defaults to |
required |
**simulation_execution
|
SimulationExecution
|
Set a custom radCAD SimulationExecution class instance. Overrides setting of |
required |
**_run_generator
|
tuple_iterator
|
Generator to generate simulation runs, used to implement custom execution backends. Defaults to |
required |
Source code in radcad/engine.py
radcad.backends¶
Parallel-processing backends.
radcad.backends ¶
Parallel-processing backends that execute simulation runs.
A backend determines how the independent units of work produced by the
Engine are executed: in a single process, across local
CPU cores, or on a remote cluster. Select one via the
Engine backend option or the RADCAD_BACKEND
environment variable.
Backend ¶
Bases: Enum
Available execution backends.
DEFAULT: alias forPATHOS.PATHOS: local multiprocessing viapathos(dill-based pickling).MULTIPROCESSING: local multiprocessing via the standard library.RAY: local execution via Ray.RAY_REMOTE: distributed execution on a remote Ray cluster.SINGLE_PROCESS: no parallelisation; useful for debugging.
radcad.core¶
The core simulation loop. Most users never use this directly, but it defines radCAD's execution semantics.
radcad.core ¶
The core simulation loop that evaluates a single run of a model.
A SimulationExecution represents one fully-specified unit of work, a single run of a single parameter subset. Stepping through it produces the raw simulation result. The Engine creates one of these per run/subset and hands it to a backend, which calls multiprocess_wrapper to execute it (with exception handling) in a worker process.
Most models never touch this module directly; it is documented here because its state-transition logic defines radCAD's execution semantics.
SimulationExecution
dataclass
¶
SimulationExecution(
timesteps: int = 0,
timestep: int = None,
substep_index: int = 0,
substeps: List = default([]),
state_update_blocks: List[StateUpdateBlock] = default(
[]
),
result: SimulationResults = default([]),
initial_state: StateVariables = default({}),
params: SystemParameters = default({}),
enable_deepcopy: bool = True,
drop_substeps: bool = False,
raise_exceptions: bool = True,
simulation_index: int = 0,
run_index: int = 1,
subset_index: int = 0,
previous_state: StateVariables = None,
)
Bases: SimulationExecutionSpecification
One executable run of a model: a single run of a single parameter subset.
Implements radCAD's state-transition semantics on top of
SimulationExecutionSpecification. For each substep it executes the
block's Policy Functions, aggregates their signals, applies the State
Update Functions, and appends the new state to the result. Execution
options such as enable_deepcopy, drop_substeps, and
raise_exceptions control performance and error behaviour.
Subclass it and override deepcopy_method (or other methods) to
customise execution; see the README for an example.
logger
class-attribute
instance-attribute
¶
Use "radCAD" logging instance to avoid conflict with other projects
subset_index
class-attribute
instance-attribute
¶
Index starts at +1 to remain compatible with cadCAD implementation
initialise_state ¶
Stamp bookkeeping keys onto the initial state and seed the result.
Sets the simulation/subset/run/substep/timestep
keys and appends the initial state as the first entry of the result.
Source code in radcad/core.py
substep ¶
Evaluate a single Partial State Update Block.
Runs the block's policies to produce aggregated signals, applies each State Update Function to compute the new State Variable values, and records the resulting substate.
Source code in radcad/core.py
execute_policies ¶
Run a block's Policy Functions and merge their signals into one dict.
Each policy receives (params, substep, state_history, substate).
Where multiple policies emit the same signal key, their values are
summed (see add_signals).
Source code in radcad/core.py
update_state ¶
update_state(
substate: StateVariables,
signals: PolicySignal,
state_update: StateUpdate,
) -> StateUpdateResult
Apply one State Update Function and validate its returned key.
Calls function(params, substep, state_history, substate, signals)
and checks that the returned key matches the declared State Variable
and exists in the initial state.
Returns:
| Type | Description |
|---|---|
StateUpdateResult
|
The |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the declared or returned key is unknown, or they differ. |
Source code in radcad/core.py
add_signals
staticmethod
¶
Reduce two Policy Signals by summing values that share a key.
Source code in radcad/core.py
deepcopy_method
staticmethod
¶
SimulationExecutionSpecification
dataclass
¶
SimulationExecutionSpecification(
timesteps: int = 0,
timestep: int = None,
substep_index: int = 0,
substeps: List = default([]),
state_update_blocks: List[StateUpdateBlock] = default(
[]
),
result: SimulationResults = default([]),
)
Bases: ABC
Abstract template for the simulation loop, independent of state semantics.
Defines the nested execution structure (execution > timestep > substep) as
a sequence of overridable hook methods (before_step, substep,
after_step, ...). SimulationExecution implements these hooks
with radCAD's concrete state-transition behaviour. Separating the two
makes the loop structure explicit and the behaviour easy to customise.
execute ¶
Run the full simulation loop and return the accumulated result.
Calls before_execution, iterates over each timestep (which in
turn iterates over substeps via step), then
after_execution.
Returns:
| Type | Description |
|---|---|
SimulationResults
|
The per-timestep, per-substep state history. |
Source code in radcad/core.py
step ¶
Advance the system by one timestep, evaluating every substep.
Each Partial State Update Block in state_update_blocks is one
substep; they are evaluated in order, each building on the previous.
Source code in radcad/core.py
multiprocess_wrapper ¶
Execute one SimulationExecution, handling exceptions per policy.
This is the function dispatched to worker processes by every backend. If
raise_exceptions is True the exception propagates; otherwise the
partial result up to the failing timestep is returned alongside an
exception/traceback metadata dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulation_execution
|
SimulationExecution
|
The run to execute. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
|
Source code in radcad/core.py
radcad.types¶
Type aliases describing radCAD's core data structures.
radcad.types ¶
Type aliases describing radCAD's core data structures.
These aliases name the data shapes that flow through a simulation: the State Variables, System Parameters, Policy Signals, and Partial State Update Blocks. Use them as type hints in model functions for clearer, self-documenting models.
StateUpdateBlock
module-attribute
¶
A Partial State Update Block: {"policies": {...}, "variables": {...}}.
SystemParameters
module-attribute
¶
System Parameters as a dict of lists (sweepable) or a (nested) dataclass.
StateVariables
module-attribute
¶
A mapping of State Variable name to value at a single substep.
SimulationResults
module-attribute
¶
Raw nested results: a list of timesteps, each a list of substep states.
PolicySignal
module-attribute
¶
The aggregated output of a block's Policy Functions for one substep.
StateUpdate
module-attribute
¶
A (state_variable_name, state_update_function) pair.
StateUpdateResult
module-attribute
¶
The (key, value) returned by a State Update Function.
Dataclass ¶
Bases: Protocol
Structural type matching any @dataclass instance.
Used so System Parameters can be either a plain dict or a (nested)
dataclass. Membership is detected via the __dataclass_fields__
attribute, currently the most reliable check.
Context
dataclass
¶
Context(
simulation: int = None,
run: int = None,
subset: int = None,
timesteps: int = None,
initial_state: StateVariables = None,
parameters: SystemParameters = None,
state_update_blocks: List[StateUpdateBlock] = None,
)
Mutable context passed to simulation hooks
radcad.utils¶
Helpers for parameter sweeps, common State Update Functions, and dataclass parameters.
radcad.utils ¶
Helper functions for parameter sweeps, common State Update Functions, and dataclass params.
The most commonly used helpers here are the generic State Update Functions (update_from_signal, accumulate_from_signal, update_timestamp) that remove boilerplate from models, and default, required when giving a dataclass field a mutable default such as a list or nested dataclass. The remaining functions implement radCAD's parameter-sweep expansion and are used internally by the Engine.
update_from_signal ¶
A generic State Update Function to update a State Variable directly from a Policy Signal, avoiding boilerplate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_variable
|
str
|
State Variable key. |
required |
signal_key
|
str
|
Policy Signal key. Defaults to the State Variable key. |
None
|
optional_update
|
bool
|
If True, only update the State Variable when the Policy Signal key exists. |
False
|
Returns:
| Type | Description |
|---|---|
Callable
|
A generic State Update Function. |
Source code in radcad/utils.py
accumulate_from_signal ¶
A generic State Update Function to accumulate a State Variable directly from a Policy Signal, useful to avoid boilerplate code.
Source code in radcad/utils.py
update_timestamp ¶
A radCAD State Update Function used to calculate and update the current timestamp given a timestep and starting date parameter.
Source code in radcad/utils.py
generate_parameter_sweep ¶
Expand System Parameters into one parameter set per sweep subset.
Each parameter is a list of values; the sweep length is the longest such list, and shorter lists are extended by repeating their last value. Works with both dict and (nested) dataclass parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
SystemParameters
|
The parameters to expand. |
required |
Returns:
| Type | Description |
|---|---|
list
|
One concrete parameter set (same type as |
Source code in radcad/utils.py
generate_cartesian_product_parameter_sweep ¶
default ¶
flatten ¶
Flatten a list one level deep, leaving non-list items in place.
Source code in radcad/utils.py
extend_list ¶
Extend list to length by repeating last element
extract_exceptions ¶
Split backend output into a flat results list and an exceptions list.
local_variables ¶
Return a dictionary of all local variables, useful for debugging.