Skip to content

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 time.perf_counter.

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 time.perf_counter.

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
def prepare(self, context: None = None) -> Self:
    """Mark the wall time at which the run of the checked clock starts.

    Args:
        context:
            Nothing: a clock prepares on no context.

    Returns:
        self:
            The prepared clock.
    """
    return super().prepare(context)

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
def run(self, elapsed: float | None = None, final: bool = False) -> Self:
    """Wait until the frame `elapsed` simulated time units after the start is due.

    Args:
        elapsed:
            The simulated time since the start of the run.

        final:
            Whether this is the last call of the run.

    Returns:
        self:
            The clock.
    """
    super().run(elapsed, final)
    return self

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
def prepare(self, problem: BaseProblemSpec | None = None) -> Self:
    """Prepare the checked observer for a run of a compiled problem.

    Args:
        problem:
            The compiled problem the run advances.

    Returns:
        self:
            The prepared observer.
    """
    return super().prepare(problem)

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 for the call that ends the run.

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
def run(self, frame: FrameSpec | None = None, final: bool = False) -> Self:
    """React to a frame.

    At the last call, it releases what preparing acquired.

    Args:
        frame:
            The frame, or `None` for the call that ends the run.

        final:
            Whether this is the last call of the run.

    Returns:
        self:
            The observer.
    """
    super().run(frame, final)
    return self

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 None.

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
def __init__(self, *, rtol: float = 1e-6, atol: float = 1e-9) -> None:
    self.rtol = rtol
    self.atol = atol

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
def __init__(self, invariants: Mapping[str, float]) -> None:
    self.invariants = invariants

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 time.perf_counter.

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
def __init__(self, speed: float = 1.0) -> None:
    self.speed = speed

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.

None
log_probability float | None

The total log probability of the draws and firings of a run that records or replays them, or None.

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
def __init__(
    self,
    problem: BaseProblemSpec,
    times: npt.NDArray[np.float64],
    states: npt.NDArray[np.float64],
    parameters: npt.NDArray[np.float64],
    *,
    agents: Sequence[Mapping[str, AgentSnapshotSpec]] = (),
    reporters: Sequence[Mapping[str, float]] = (),
    observables: Sequence[Mapping[str, object]] = (),
    events: Sequence[BaseRecordSpec] = (),
    structures: Sequence[Mapping[str, object]] = (),
    draws: _DrawLogSpec | None = None,
    log_probability: float | None = None,
) -> None:
    self.problem = problem
    self.times = times
    self.states = states
    self.parameters = parameters
    self.agents_by_frame = agents
    self.reporters = reporters
    self.observables = observables
    self.events = list(events)
    self.structures = structures
    self.draws = draws
    self.log_probability = log_probability

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
def get_agent_locations(self, group: str) -> list[AnyArray]:
    """Return the locations of the agents of a group.

    There is one array per frame with one row per agent alive.

    Args:
        group:
            The path of the agent group.

    Returns:
        locations:
            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]
    """
    frames = [self.get_agents(group, frame) for frame in range(len(self.times))]
    return [
        np.asarray(snapshot.locations) if snapshot.locations is not None else np.zeros((0, 0))
        for snapshot in frames
    ]

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
def get_agents(self, group: str, frame: int) -> AgentSnapshotSpec:
    """Return the agents of a group alive at a frame.

    They come with their ids, states, and locations.

    Args:
        group:
            The path of the agent group.

        frame:
            The index of the frame.

    Returns:
        agents:
            The agents of the group at that frame.

    Raises:
        KeyError:
            The trajectory has no agent group of that path.
    """
    groups = self.agents_by_frame[frame] if self.agents_by_frame else {}
    if group not in groups:
        error_msg = f'No agent group {group!r}. Available groups are: {", ".join(groups)}.'
        raise KeyError(error_msg)
    return groups[group]

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 cells.alive.

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
def get_lattice(self, name: str) -> AnyArray:
    """Return the values of a lattice state over time in lattice shape.

    Args:
        name:
            The dotted name of a state of a lattice group, such as `cells.alive`.

    Returns:
        values:
            One array of the lattice shape per frame, with the components of a vector or a tensor state on a last
            axis.

    Raises:
        KeyError:
            The name is not a state of a lattice group.
    """
    shape = self.problem.get_lattice_shape(name)
    if shape is None:
        error_msg = f'{name!r} is not a state of a lattice group.'
        raise KeyError(error_msg)
    return self.get_values(name).reshape(len(self.times), *shape, *self.problem.states.get_entry(name).member_shape)

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
def get_member(self, index: int, problem: BaseProblemSpec) -> 'Trajectory':
    """Return the trajectory of one member of a replicated system.

    It is a trajectory of the original system.

    Args:
        index:
            The member index, the same in every group of the replicated system.

        problem:
            The compiled original system, whose single elements the replicated groups hold.

    Returns:
        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]
    """
    frames = len(self.times)
    states = np.zeros((frames, problem.states.size))
    parameters = np.zeros((frames, problem.parameters.size))
    for layout, source, target, values in (
        (problem.states, self.problem.states, states, self.states),
        (problem.parameters, self.problem.parameters, parameters, self.parameters),
    ):
        for entry in layout.entries:
            origin = source.get_entry(entry.name)
            if origin.size == entry.size:
                target[:, entry.start : entry.start + entry.size] = np.asarray(values)[
                    :,
                    origin.start : origin.start + origin.size,
                ]
                continue
            columns = np.asarray(values)[:, origin.start : origin.start + origin.size].reshape(
                frames,
                -1,
                entry.size,
            )
            target[:, entry.start : entry.start + entry.size] = columns[:, index]
    return Trajectory(problem, self.times, states, parameters)

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 for the first such network.

None
layer str | None

The layer, or None for the graph of the network.

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
def get_network(self, frame: int, nodes: str | None = None, layer: str | None = None) -> NetworkSnapshotSpec:
    """Return the nodes and edges of a changing network at a frame.

    The network is one whose topology changes.

    Args:
        frame:
            The index of the frame.

        nodes:
            The path of a variable group on the nodes of the network, or `None` for the first such network.

        layer:
            The layer, or `None` for the graph of the network.

    Returns:
        snapshot:
            The rows of the nodes present and the ends and rows of the edges present.

    Raises:
        KeyError:
            The system has no network whose topology changes.
    """
    topology = self.problem.topology
    if topology is None:
        error_msg = 'The system has no network whose topology changes. Give its groups `variable=True`.'
        raise KeyError(error_msg)
    return topology.read_network(self.parameters[frame], nodes, layer)

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
def get_structure(self, path: str, frame: int) -> object:
    """Return the word or patch of a rewritten element at a frame.

    Args:
        path:
            The path of the rewritten element.

        frame:
            The index of the frame.

    Returns:
        structure:
            The structure recorded at that frame, which later generations do not change.

    Raises:
        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
    """
    structures = self.structures[frame] if self.structures else {}
    if path not in structures:
        names = ', '.join(structures) or 'none'
        error_msg = f'No rewritten element {path!r}. The rewritten elements of the system are: {names}.'
        raise KeyError(error_msg)
    return structures[path]

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 rabbits.n or growth.r.

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
def get_values(self, name: str) -> AnyArray:
    """Return the values of a state or a parameter over time by dotted name.

    Args:
        name:
            The dotted name, such as `rabbits.n` or `growth.r`.

    Returns:
        values:
            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:
        KeyError:
            The name is neither a state nor a parameter.
    """
    name = LayoutSpec._get_internal_name(name)
    if self.problem.states.has(name):
        entry = self.problem.states.get_entry(name)
        return self._get_present(name, entry.read(np.asarray(self.problem.states.read(self.states, name))))
    if self.problem.parameters.has(name):
        entry = self.problem.parameters.get_entry(name)
        values = entry.read(np.asarray(self.problem.parameters.read(self.parameters, name)))
        return self._get_present(name, values)
    if self.reporters and name in self.reporters[0]:
        found = [frame[name] for frame in self.reporters]
        if all(isinstance(item, numbers.Real) for item in found):
            return np.asarray(found, dtype=float)
        return np.fromiter(found, dtype=object, count=len(found))
    if self.observables and name in self.observables[0]:
        return np.asarray([frame[name] for frame in self.observables])
    reporter_names = list(self.reporters[0]) if self.reporters else []
    observable_names = list(self.observables[0]) if self.observables else []
    names = [
        LayoutSpec._get_display_name(item)
        for item in [*self.problem.states.names, *self.problem.parameters.names, *reporter_names, *observable_names]
    ]
    error_msg = f'No state or parameter named {name!r}. Available names are: {", ".join(names)}.'
    raise KeyError(error_msg)

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 for the tuned or the default one.

None
backend BaseBackend | None

The backend the problem is compiled for, such as NumbaBackend(), or None for the tuned or the default one.

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
def compile_problem(
    system: _CompositeSystem,
    *,
    solver: BaseSolver | None = None,
    backend: BaseBackend | None = None,
    observables: Sequence[Observable] = (),
) -> tuple[BaseProblemSpec, BaseSolver]:
    """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.

    Args:
        system:
            The system.

        solver:
            The solver, or `None` for the tuned or the default one.

        backend:
            The backend the problem is compiled for, such as `NumbaBackend()`, or `None` for the tuned or the default
            one.

        observables:
            The observables, or none for the tuned ones.

    Returns:
        problem:
            The compiled problem, with the initial values of the system.

        solver:
            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')
    """
    composite, stepper, runner, form, observed = _prepare_runners(system, solver, backend, observables)
    simulation = Simulation(composite, compiler=form, solver=stepper, backend=runner, observables=observed).prepare()
    return simulation.problem_, simulation.stepper_

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 None to compile the system.

required
until float | None

The end time of the run, or None for the tuned one.

None
dt float | None

The time between frames, or None for the tuned one.

None
initial_state Mapping[str, object] | None

Initial values by dotted state name, or None for the tuned initial state.

None
solver BaseSolver | None

The solver, or None for the tuned or the default one, or the one of the compiled problem.

None
backend BaseBackend | None

The backend, or None for the tuned one.

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 for the tuned invariants.

None
schedule Mapping[str, Callable[[float], float | ArrayLike]] | None

A function of time per dotted parameter name, or None for the tuned schedule.

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 to run as fast as possible.

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.

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
def run_problem(
    system: _CompositeSystem,
    compiled: tuple[BaseProblemSpec, BaseSolver] | None,
    *,
    until: float | None = None,
    dt: float | None = None,
    initial_state: Mapping[str, object] | None = None,
    solver: BaseSolver | None = None,
    backend: BaseBackend | None = None,
    observables: Sequence[Observable] = (),
    observers: Sequence[BaseObserver] = (),
    invariants: Mapping[str, float] | None = None,
    schedule: Mapping[str, Callable[[float], float | npt.ArrayLike]] | None = None,
    random_state: int | np.random.Generator | None = None,
    checked: bool = False,
    clock: BaseClock | None = None,
    record_draws: bool = False,
    replay: Trajectory | None = None,
) -> Trajectory:
    """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.

    Args:
        system:
            The system to simulate.

        compiled:
            The problem compiled from the system with the solver of its runs, or `None` to compile the system.

        until:
            The end time of the run, or `None` for the tuned one.

        dt:
            The time between frames, or `None` for the tuned one.

        initial_state:
            Initial values by dotted state name, or `None` for the tuned initial state.

        solver:
            The solver, or `None` for the tuned or the default one, or the one of the compiled problem.

        backend:
            The backend, or `None` for the tuned one.

        observables:
            The observables, or none for the tuned ones.

        observers:
            The observers that receive every frame.

        invariants:
            The tolerance of every observable that must stay constant, or `None` for the tuned invariants.

        schedule:
            A function of time per dotted parameter name, or `None` for the tuned schedule.


        random_state:
            The seed or generator of stochastic solvers.

        checked:
            Whether to check after every frame that every state lies in its domain.

        clock:
            The clock that paces frames against wall time, or `None` to run as fast as possible.

        record_draws:
            Whether to record the named draws and jump firings of the run.

        replay:
            A trajectory recorded with its draws, whose draws the run forces, or `None`.

    Returns:
        trajectory:
            The trajectory of the system from time 0 until the end time.

    Raises:
        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]
    """
    if not isinstance(system, _CompositeSystem):
        error_msg = f'simulate takes a system, not {system!r}.'
        raise ValidationError(error_msg)
    settings = system.get_run_settings()
    end = settings['until'] if until is None else until
    if end is None:
        error_msg = f'{type(system).__name__} has no tuned end time. Pass `until`.'
        raise ValidationError(error_msg)
    if (record_draws or replay is not None) and backend is None:
        backend = NumpyBackend()
    source: _CompositeSystem | BaseProblemSpec
    if compiled is None:
        source, stepper, runner, form, observed = _prepare_runners(system, solver, backend, observables)
    else:
        source, runner, form, observed = compiled[0], _clone_setting(backend), None, ()
        stepper = clone(compiled[1] if solver is None else solver)
    simulation = Simulation(
        source,
        compiler=form,
        solver=stepper,
        backend=runner,
        dt=settings['dt'] if dt is None else dt,
        observers=observers,
        schedule=settings['schedule'] if schedule is None else schedule,
        observables=observed,
        invariants=settings['invariants'] if invariants is None else invariants,
        initial_state=settings['initial_state'] if initial_state is None else initial_state,
        random_state=random_state,
        checked=checked,
        clock=clock,
        until=end,
        record_draws=record_draws,
        replay=replay,
    )
    trajectory: Trajectory = simulation.prepare().run().trajectory_
    return trajectory