Runtime
Run systems frame by frame with clocks, observers, and trajectories.
A run hands every frame to its observers, such as a recorder or a check that money is conserved, waits between frames as its clock says, and returns a trajectory of the values over time, such as the size of a population at times 0, 1, and 2.
AsFastAsPossibleClock
Bases: BaseClock
A clock that never waits, so a run goes as fast as it can.
It hands each frame on as soon as the solver has computed it, so max_lag_ stays 0. It is the clock of every run
that names none, such as a batch of runs of an epidemic, a sweep of the rates of a reaction, or the training of a
network.
Read more in the user guide, under Observe.
Attributes:
| Name | Type | Description |
|---|---|---|
started_ |
The wall time at which the run started, in seconds of |
|
max_lag_ |
The largest delay of a frame behind its due time, always 0. |
See Also
RealTimeClock: Runs at a fixed speed against wall time.
Examples:
>>> from skcomplex.core.engine.runtime import AsFastAsPossibleClock
>>> clock = AsFastAsPossibleClock().prepare().run(10.0)
>>> clock.max_lag_
0.0
BaseClock
Bases: BaseConfig[None, float]
An abstract clock, which paces a run against wall time.
A clock decides how long a run waits between frames. prepare() marks the wall time at the start of a run, and
run(elapsed) waits until the frame elapsed time units after the start is due, so RealTimeClock(speed=100.0)
shows 100 time units per second. A subclass writes the private method _run. Clocks pace a live view of a pendulum,
a demo of a traffic jam, and a game against a model of a market.
Read more in the user guide, under Observe.
Attributes:
| Name | Type | Description |
|---|---|---|
started_ |
The wall time at which the run started, in seconds of |
|
max_lag_ |
The largest delay of a frame behind its due time, in seconds. |
See Also
AsFastAsPossibleClock: Never waits. RealTimeClock: Runs at a fixed speed against wall time.
Examples:
>>> from skcomplex.core.engine.runtime import BaseClock, RealTimeClock
>>> clock = RealTimeClock(speed=100.0).prepare()
>>> isinstance(clock, BaseClock)
True
prepare(context=None)
Mark the wall time at which the run of the checked clock starts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
None
|
Nothing: a clock prepares on no context. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
Self
|
The prepared clock. |
Source code in src/skcomplex/core/engine/runtime/_base.py
126 127 128 129 130 131 132 133 134 135 136 137 | |
run(elapsed=None, final=False)
Wait until the frame elapsed simulated time units after the start is due.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
elapsed
|
float | None
|
The simulated time since the start of the run. |
None
|
final
|
bool
|
Whether this is the last call of the run. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
Self
|
The clock. |
Source code in src/skcomplex/core/engine/runtime/_base.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
BaseObserver
Bases: BaseConfig[BaseProblemSpec, FrameSpec]
An abstract observer, which receives the frames of a run one by one.
A run calls prepare(problem) with the compiled problem before the first frame, run(frame) with every frame, such
as the frame of time 0 that holds the starting values, and run(final=True) once the run stops, which frees what
prepare took, such as an open file. A subclass writes any of the private methods _prepare, _run, and
_release. Observers record the course of an epidemic, check that the money of an economy is conserved, and draw a
flock as it moves.
Read more in the user guide, under Observe.
See Also
RecorderObserver: Keeps every frame. ConservationObserver: Checks that conserved quantities hold. InvariantObserver: Checks that observables stay near their first value.
Examples:
>>> from skcomplex.core.engine.runtime import BaseObserver, RecorderObserver
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> recorder = RecorderObserver()
>>> _ = LogisticGrowthSystem().prepare().simulate(until=2, dt=1, observers=[recorder])
>>> isinstance(recorder, BaseObserver), len(recorder.frames_)
(True, 3)
prepare(problem=None)
Prepare the checked observer for a run of a compiled problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
BaseProblemSpec | None
|
The compiled problem the run advances. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
Self
|
The prepared observer. |
Source code in src/skcomplex/core/engine/runtime/_base.py
50 51 52 53 54 55 56 57 58 59 60 61 | |
run(frame=None, final=False)
React to a frame.
At the last call, it releases what preparing acquired.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
FrameSpec | None
|
The frame, or |
None
|
final
|
bool
|
Whether this is the last call of the run. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
Self
|
The observer. |
Source code in src/skcomplex/core/engine/runtime/_base.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
ConservationObserver(*, rtol=1e-06, atol=1e-09)
Bases: BaseObserver
An observer that checks at every frame that each conserved quantity holds.
The total of a quantity is the sum of the values that hold it, such as the water in the tanks of a plant, and it may change only by its flows to and from the outside. The observer compares the change of each total since the first frame with the net inflow from the outside, and raises an error when they differ by more than the tolerance, such as after a law clips a value. It checks the money of an economy, the people of an epidemic, and the water of a bathtub.
Read more in the user guide, under Observe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rtol
|
float
|
The relative tolerance, a fraction of the largest absolute total seen. |
1e-06
|
atol
|
float
|
The absolute tolerance. |
1e-09
|
Attributes:
| Name | Type | Description |
|---|---|---|
problem_ |
The compiled problem of the run. |
|
transfer_network_ |
The quantities of the problem, with the values that hold them and their flows to and from the outside. |
|
totals_ |
The total of every quantity at the latest frame. |
|
initial_ |
The total of every quantity minus its inflow from the outside at the first frame, or |
|
scale_ |
The largest absolute total of every quantity seen so far. |
See Also
Quantity: Marks a value that holds a conserved quantity. InvariantObserver: Checks that observables stay near their first value.
Examples:
>>> from skcomplex.core.engine.runtime import ConservationObserver
>>> from skcomplex.systems.engineering.processes import BathtubSystem
>>> observer = ConservationObserver()
>>> _ = BathtubSystem().prepare().simulate(until=10, dt=1, observers=[observer])
>>> round(observer.totals_['water'], 6)
25.0
Source code in src/skcomplex/core/engine/runtime/_conservation.py
61 62 63 | |
InvariantObserver(invariants)
Bases: BaseObserver
An observer that checks that each named observable stays near its first value.
At every frame each observable must stay within its tolerance of its value at the first frame, such as the energy of
a star within 1e-6 of its starting energy, and the observer raises an error that names the observable and the
frame otherwise. A run adds one when simulate is given invariants. It checks the energy of a pendulum, the total
of a closed population, and the probability of a quantum state.
Read more in the user guide, under Observe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invariants
|
Mapping[str, float]
|
The tolerance of every invariant, by the path of its observable. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
initial_ |
The value of every invariant at the first frame. |
See Also
ConservationObserver: Checks that conserved quantities hold.
Examples:
>>> from skcomplex.core.engine.runtime import InvariantObserver
>>> from skcomplex.systems.physics.nonlinear_oscillators import HenonHeilesSystem
>>> observer = InvariantObserver({'star.energy': 1e-6})
>>> _ = HenonHeilesSystem().prepare().simulate(until=1, observers=[observer])
>>> round(observer.initial_['star.energy'], 4)
0.0659
Source code in src/skcomplex/core/engine/runtime/_invariants.py
45 46 | |
RealTimeClock(speed=1.0)
Bases: BaseClock
A clock that runs simulated time at a fixed speed against wall time.
It waits before each frame until its time is due, so RealTimeClock(speed=100.0) shows 100 time units per second of
wall time, and it records in max_lag_ how far a frame fell behind when the solver was slower. It paces a live view
of a pendulum, a demo of a traffic jam, and a game against a model of a market.
Read more in the user guide, under Observe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
float
|
The number of simulated time units per second of wall time. |
1.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
started_ |
The wall time at which the run started, in seconds of |
|
max_lag_ |
The largest delay of a frame behind its due time, in seconds. |
See Also
AsFastAsPossibleClock: Never waits.
Examples:
>>> from skcomplex.core.engine.runtime import RealTimeClock
>>> clock = RealTimeClock(speed=100.0).prepare().run(1.0)
>>> clock.max_lag_ < 0.1
True
Source code in src/skcomplex/core/engine/runtime/_real_time.py
42 43 | |
RecorderObserver
Bases: BaseObserver
An observer that keeps every frame it receives.
It stores each frame in frames_, such as the frames of times 0, 1, and 2 of a run until 2, and gathers them into
trajectory_. It keeps the course of an epidemic, the prices of a market, and the moves of a flock for later
reading.
Read more in the user guide, under Observe.
Attributes:
| Name | Type | Description |
|---|---|---|
problem_ |
The compiled problem of the run. |
|
frames_ |
The frames received so far. |
|
trajectory_ |
Trajectory
|
The trajectory of the frames received so far. |
See Also
BaseObserver: The base of every observer.
Trajectory: The record of a run that simulate returns.
Examples:
>>> from skcomplex.core.engine.runtime import RecorderObserver
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> recorder = RecorderObserver()
>>> _ = LogisticGrowthSystem().prepare().simulate(until=2, dt=1, observers=[recorder])
>>> [frame.time for frame in recorder.frames_]
[0.0, 1.0, 2.0]
trajectory_
property
Trajectory of the frames received so far.
Trajectory(problem, times, states, parameters, *, agents=(), reporters=(), observables=(), events=(), structures=(), draws=None, log_probability=None)
A record of the values of a run over time, which simulate returns.
It holds the time of every frame and the values of the states and parameters at each, read by name with
get_values, such as trajectory.get_values('population.x') for the size of a population at every frame. It also
holds the agents, observables, and events of a run that has them. It records the spread of an epidemic, the path of
a planet, and the prices of a market.
Read more in the user guide, under Simulate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
BaseProblemSpec
|
The compiled problem, which gives the names of the values. |
required |
times
|
NDArray[float64]
|
The time of each recorded frame. |
required |
states
|
NDArray[float64]
|
One row of state values per frame. |
required |
parameters
|
NDArray[float64]
|
One row of parameter values per frame. |
required |
agents
|
Sequence[Mapping[str, AgentSnapshotSpec]]
|
One mapping from the path of a group of agents to its agents per frame, empty for problems without agents. |
()
|
reporters
|
Sequence[Mapping[str, float]]
|
One mapping from the dotted name of a reporter to its value per frame, empty for problems without reporters. |
()
|
observables
|
Sequence[Mapping[str, object]]
|
One mapping from the path of an observable to its value per frame, empty for systems without observables. |
()
|
events
|
Sequence[BaseRecordSpec]
|
The events that fired during the run, in order, each with its time and the states before and after its reset, the cascades of lattices with their sizes, durations, and areas, and the renewals of renewal laws with their members. |
()
|
structures
|
Sequence[Mapping[str, object]]
|
One mapping from the path of a rewritten element to its structure per frame, empty for other systems. |
()
|
draws
|
_DrawLogSpec | None
|
The named draws and jump firings of a run that records or replays them, or |
None
|
log_probability
|
float | None
|
The total log probability of the draws and firings of a run that records or replays them, or |
None
|
See Also
System: Returns it from simulate.
RecorderObserver: Gathers the frames of a run into one.
Examples:
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> trajectory = LogisticGrowthSystem().prepare().simulate(until=2, dt=1)
>>> trajectory.times.tolist(), trajectory.get_values('population.x').round(2).tolist()
([0.0, 1.0, 2.0], [10.0, 23.2, 45.09])
Source code in src/skcomplex/core/engine/runtime/_trajectories.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
names
property
Names that values reads.
They are the names of the states, parameters, reporters, and observables.
get_agent_locations(group)
Return the locations of the agents of a group.
There is one array per frame with one row per agent alive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
str
|
The path of the agent group. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
locations |
list[AnyArray]
|
The locations at every frame, empty arrays for frames without locations. |
Examples:
>>> from skcomplex.systems.biology.collective_behaviour import BoidsSystem
>>> trajectory = (BoidsSystem().prepare().system_).prepare().simulate(until=2, random_state=0)
>>> [locations.shape[1] for locations in trajectory.get_agent_locations('flock')]
[2, 2, 2]
Source code in src/skcomplex/core/engine/runtime/_trajectories.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
get_agents(group, frame)
Return the agents of a group alive at a frame.
They come with their ids, states, and locations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
str
|
The path of the agent group. |
required |
frame
|
int
|
The index of the frame. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
agents |
AgentSnapshotSpec
|
The agents of the group at that frame. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The trajectory has no agent group of that path. |
Source code in src/skcomplex/core/engine/runtime/_trajectories.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | |
get_lattice(name)
Return the values of a lattice state over time in lattice shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name of a state of a lattice group, such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
values |
AnyArray
|
One array of the lattice shape per frame, with the components of a vector or a tensor state on a last axis. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The name is not a state of a lattice group. |
Source code in src/skcomplex/core/engine/runtime/_trajectories.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | |
get_member(index, problem)
Return the trajectory of one member of a replicated system.
It is a trajectory of the original system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
The member index, the same in every group of the replicated system. |
required |
problem
|
BaseProblemSpec
|
The compiled original system, whose single elements the replicated groups hold. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
trajectory |
Trajectory
|
The times, states, and parameters of the member, laid out as the original problem lays them out. |
Examples:
Three logistic maps run as one group, and the second member is the map that starts at 0.2.
>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.mathematics.dynamical_systems import LogisticMapInteraction
>>> logistic = LogisticMapInteraction('logistic', target='map')
>>> single = System(elements=[Element('map', values={'x': 0.2, 'r': 3.7})], interactions=[logistic])
>>> maps = Element('map', values={'x': [0.1, 0.2, 0.3], 'r': 3.7}, size=3)
>>> trajectory = System(elements=[maps], interactions=[logistic]).prepare().simulate(2, dt=1)
>>> original = single.prepare().simulate(0).problem
>>> trajectory.get_member(1, original).get_values('map.x').round(3).tolist()
[0.2, 0.592, 0.894]
Source code in src/skcomplex/core/engine/runtime/_trajectories.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
get_network(frame, nodes=None, layer=None)
Return the nodes and edges of a changing network at a frame.
The network is one whose topology changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
int
|
The index of the frame. |
required |
nodes
|
str | None
|
The path of a variable group on the nodes of the network, or |
None
|
layer
|
str | None
|
The layer, or |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
snapshot |
NetworkSnapshotSpec
|
The rows of the nodes present and the ends and rows of the edges present. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The system has no network whose topology changes. |
Source code in src/skcomplex/core/engine/runtime/_trajectories.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | |
get_structure(path, frame)
Return the word or patch of a rewritten element at a frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path of the rewritten element. |
required |
frame
|
int
|
The index of the frame. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
structure |
object
|
The structure recorded at that frame, which later generations do not change. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The path is not a rewritten element of the system. |
Examples:
>>> from skcomplex.systems.mathematics.fractals import CantorSetSystem
>>> trajectory = CantorSetSystem().prepare().simulate(until=4, random_state=0)
>>> trajectory.get_structure('cantor', 2).parts
4
Source code in src/skcomplex/core/engine/runtime/_trajectories.py
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | |
get_values(name)
Return the values of a state or a parameter over time by dotted name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name, such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
values |
AnyArray
|
One value per frame for a scalar, or one row per frame for a vector, NaN in the rows of a variable group on a network that hold no member at a frame. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The name is neither a state nor a parameter. |
Source code in src/skcomplex/core/engine/runtime/_trajectories.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
compile_problem(system, *, solver=None, backend=None, observables=())
Return the problem compiled from a system, and the solver of its runs.
It turns the laws of a system into a problem once, such as the problem of one state 'population.x' of a logistic
growth, so many runs through run_problem that change only starting values, schedules, or seeds skip compiling. An
experiment compiles a system once per structure this way, as for an ensemble of epidemics, a sweep of the rates of
a reaction, or a fit of a market model.
Read more in the user guide, under Run experiments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
_CompositeSystem
|
The system. |
required |
solver
|
BaseSolver | None
|
The solver, or |
None
|
backend
|
BaseBackend | None
|
The backend the problem is compiled for, such as |
None
|
observables
|
Sequence[Observable]
|
The observables, or none for the tuned ones. |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
problem |
BaseProblemSpec
|
The compiled problem, with the initial values of the system. |
solver |
BaseSolver
|
The solver of the runs, which every run copies. |
See Also
run_problem: Runs a system from the problem it returns.
Examples:
System.prepare compiles its components with it and keeps the solver of the runs.
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> system = LogisticGrowthSystem().prepare().system_
>>> system.states_, type(system.solver_).__name__
(('population.x',), 'ScipyODESolver')
Source code in src/skcomplex/core/engine/runtime/_simulate.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | |
run_problem(system, compiled, *, until=None, dt=None, initial_state=None, solver=None, backend=None, observables=(), observers=(), invariants=None, schedule=None, random_state=None, checked=False, clock=None, record_draws=False, replay=None)
Return the trajectory of a run of a system, as simulate does.
It runs a system from time 0 until until and starts from a problem that compile_problem built when one is given,
so runs that change only starting values, such as {'population.x': 2.0}, skip compiling. System.simulate and the
experiments call it, for the runs of an epidemic, a reaction, or a market alike.
Read more in the user guide, under Run experiments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
_CompositeSystem
|
The system to simulate. |
required |
compiled
|
tuple[BaseProblemSpec, BaseSolver] | None
|
The problem compiled from the system with the solver of its runs, or |
required |
until
|
float | None
|
The end time of the run, or |
None
|
dt
|
float | None
|
The time between frames, or |
None
|
initial_state
|
Mapping[str, object] | None
|
Initial values by dotted state name, or |
None
|
solver
|
BaseSolver | None
|
The solver, or |
None
|
backend
|
BaseBackend | None
|
The backend, or |
None
|
observables
|
Sequence[Observable]
|
The observables, or none for the tuned ones. |
()
|
observers
|
Sequence[BaseObserver]
|
The observers that receive every frame. |
()
|
invariants
|
Mapping[str, float] | None
|
The tolerance of every observable that must stay constant, or |
None
|
schedule
|
Mapping[str, Callable[[float], float | ArrayLike]] | None
|
A function of time per dotted parameter name, or |
None
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
checked
|
bool
|
Whether to check after every frame that every state lies in its domain. |
False
|
clock
|
BaseClock | None
|
The clock that paces frames against wall time, or |
None
|
record_draws
|
bool
|
Whether to record the named draws and jump firings of the run. |
False
|
replay
|
Trajectory | None
|
A trajectory recorded with its draws, whose draws the run forces, or |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
trajectory |
Trajectory
|
The trajectory of the system from time 0 until the end time. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
The system is not a system, or no end time is given or tuned. |
See Also
compile_problem: Compiles the problem it starts from.
Examples:
System.simulate runs the problem it prepared with it.
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> system = LogisticGrowthSystem().prepare()
>>> system.simulate(until=2, dt=1, initial_state={'population.x': 2.0}).times.tolist()
[0.0, 1.0, 2.0]
Source code in src/skcomplex/core/engine/runtime/_simulate.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |