Skip to content

Systems

Define systems, which are prepared once and simulated many times.

A system holds elements, interactions, nested systems, and a space, such as a ball and the law of its fall. prepare turns its laws into a problem once, as fit does, and simulate runs it from a starting point, as predict does.

BaseSystem(label='system', *, solver=AUTO, backend=AUTO)

Bases: BaseComponent[Sequence[Observable]]

An abstract system, which is prepared once and simulated many times.

prepare checks the components of the system and turns them into a problem once, as fit does for a scikit-learn estimator. simulate then solves that problem from a starting point and returns its trajectory, as predict does, so one prepared system runs many times, such as LotkaVolterraSystem().prepare().simulate(until=5.0). A ready-made system takes the parameters of its model as arguments of __init__, with solver and backend, and its _prepare builds system_, the System of its components. Class attributes may set the end time, the time between frames, the observables, and the starting values that simulate uses when a call leaves them out. It is the base of the ready-made systems of predators and prey, of reactions in a cell, and of prices in a market.

Read more in the user guide, under Systems.

Attributes:

Name Type Description
system_ BaseSystem

The prepared System of the components built from the parameters of the model.

observables_ tuple[Observable, ...]

The observables compiled with the problem, the class attribute observables unless _prepare sets them from the parameters of the model, such as the lowest energy found by an annealing.

initial_state_ Mapping[str, object] | None

The starting values simulate uses when a call gives none, the class attribute initial_state unless _prepare sets them from the parameters of the model, such as the ground state of a chain of spins.

See Also

System: The system of components that every ready-made system builds.

Examples:

>>> from skcomplex.core.systems import BaseSystem
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> system = LotkaVolterraSystem().prepare()
>>> isinstance(system, BaseSystem), float(system.simulate(until=5.0).times[-1])
(True, 5.0)

Parameters:

Name Type Description Default
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one system_ chooses.

AUTO
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one system_ chooses.

AUTO
Source code in src/skcomplex/core/systems/_base.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def __init__(
    self,
    label: str = 'system',
    *,
    solver: BaseSolver | str = AUTO,
    backend: BaseBackend | str = AUTO,
) -> None:
    """Store the label and the settings of the system.

    Args:
        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one `system_` chooses.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one `system_` chooses.
    """
    super().__init__(label)
    self.solver = solver
    self.backend = backend

prepare(context=None)

Check the system, build its components, and compile them into a problem.

Parameters:

Name Type Description Default
context Sequence[Observable] | None

The observables to compile with the problem, or None for the tuned ones.

None

Returns:

Name Type Description
self Self

The prepared system.

Raises:

Type Description
ValidationError

A model parameter or a component is invalid, named in the message.

Source code in src/skcomplex/core/systems/_base.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def prepare(self, context: Sequence[Observable] | None = None) -> Self:
    """Check the system, build its components, and compile them into a problem.

    Args:
        context:
            The observables to compile with the problem, or `None` for the tuned ones.

    Returns:
        self:
            The prepared system.

    Raises:
        ValidationError:
            A model parameter or a component is invalid, named in the message.
    """
    super().prepare(self.observables if context is None else context)
    if self.system_ is not self:
        settings = {name: getattr(self, name) for name in SETTINGS if getattr(self, name) != AUTO}
        self.system_.set_params(**settings).prepare(self.observables_)
        for name in LEARNED:
            setattr(self, name, getattr(self.system_, name))
    self._prepared_from = self._get_values()
    return self

simulate(until=None, *, dt=None, initial_state=None, random_state=None, observables=(), observers=(), invariants=None, schedule=None, clock=None, checked=False, record_draws=False, replay=None)

Simulate the prepared system until a time and return its trajectory.

A run reuses the problem compiled by prepare, so a prepared system simulates many times with different end times, initial states, and seeds. Observables other than the tuned ones compile the system again for that run.

Parameters:

Name Type Description Default
until float | None

The end time, or None for the tuned one. A static system, which only solves its objectives and constraints, needs none.

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, such as {'ball.x': 20.0}, or None for the tuned or the declared ones.

None
random_state int | Generator | None

The seed or the generator of the random numbers of the run, or None for fresh entropy.

None
observables Sequence[Observable]

The observables to record, or none for the tuned ones.

()
observers Sequence[BaseObserver]

The observers that watch the run, such as a Rerun recording.

()
invariants Mapping[str, float] | None

The tolerance of each observable that must stay constant, or None for the tuned ones.

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

The functions of time that drive parameters, by dotted name, or None for the tuned ones.

None
clock BaseClock | None

The clock that paces the run, or None to run as fast as possible.

None
checked bool

Whether every frame checks that states stay in their domains.

False
record_draws bool

Whether the run records its random draws.

False
replay Trajectory | None

A trajectory whose recorded draws the run replays, or None.

None

Returns:

Name Type Description
trajectory Trajectory

The states and observables of the run at every frame.

Raises:

Type Description
NotPreparedError

The system was not prepared, or a parameter changed since it was prepared.

Examples:

>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> system = System(systems=[LotkaVolterraSystem(label='meadow')]).prepare()
>>> short, long = system.simulate(until=5.0), system.simulate(until=10.0)
>>> float(short.times[-1]), float(long.times[-1])
(5.0, 10.0)
Source code in src/skcomplex/core/systems/_base.py
212
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
def simulate(
    self,
    until: float | None = None,
    *,
    dt: float | None = None,
    initial_state: Mapping[str, object] | None = None,
    random_state: int | np.random.Generator | None = None,
    observables: Sequence[Observable] = (),
    observers: Sequence[BaseObserver] = (),
    invariants: Mapping[str, float] | None = None,
    schedule: Mapping[str, Callable[[float], float | npt.ArrayLike]] | None = None,
    clock: BaseClock | None = None,
    checked: bool = False,
    record_draws: bool = False,
    replay: Trajectory | None = None,
) -> Trajectory:
    """Simulate the prepared system until a time and return its trajectory.

    A run reuses the problem compiled by `prepare`, so a prepared system simulates many times with different end
    times, initial states, and seeds. Observables other than the tuned ones compile the system again for that run.

    Args:
        until:
            The end time, or `None` for the tuned one. A static system, which only solves its objectives and
            constraints, needs none.

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

        initial_state:
            Initial values by dotted state name, such as `{'ball.x': 20.0}`, or `None` for the tuned or the declared
            ones.

        random_state:
            The seed or the generator of the random numbers of the run, or `None` for fresh entropy.

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

        observers:
            The observers that watch the run, such as a Rerun recording.

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

        schedule:
            The functions of time that drive parameters, by dotted name, or `None` for the tuned ones.

        clock:
            The clock that paces the run, or `None` to run as fast as possible.

        checked:
            Whether every frame checks that states stay in their domains.

        record_draws:
            Whether the run records its random draws.

        replay:
            A trajectory whose recorded draws the run replays, or `None`.

    Returns:
        trajectory:
            The states and observables of the run at every frame.

    Raises:
        NotPreparedError:
            The system was not prepared, or a parameter changed since it was prepared.

    Examples:
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
        >>> system = System(systems=[LotkaVolterraSystem(label='meadow')]).prepare()
        >>> short, long = system.simulate(until=5.0), system.simulate(until=10.0)
        >>> float(short.times[-1]), float(long.times[-1])
        (5.0, 10.0)
    """
    self._check_prepared()
    prepared = self.system_
    starting = self.initial_state_ if initial_state is None else initial_state
    named = any(isinstance(value, str) for value in (starting or {}).values())
    compiled = None if observables or named else (prepared._problem, prepared.solver_)
    end = self.until if until is None else until
    return run_problem(
        prepared._composite,
        compiled,
        until=0.0 if end is None and prepared.form_ == FormKind.STATIC else end,
        dt=self.dt if dt is None else dt,
        initial_state=starting,
        solver=prepared.solver_ if compiled is None else None,
        backend=prepared._backend,
        observables=observables if compiled is not None or observables else self.observables_,
        observers=observers,
        invariants=self.invariants if invariants is None else invariants,
        schedule=self.schedule if schedule is None else schedule,
        random_state=random_state,
        checked=checked,
        clock=clock,
        record_draws=record_draws,
        replay=replay,
    )

System(label='system', *, elements=(), interactions=(), systems=(), space=None, solver=AUTO, backend=AUTO)

Bases: BaseSystem

A system of elements, interactions, nested systems, and a space.

It holds the components of a model and runs them, such as a falling ball made of the element Element('ball', values={'x': 10.0, 'm': 1.0}) and an interaction whose law says how its height changes. prepare checks every component, turns the laws of the interactions into one problem, and chooses the solver and the backend, and simulate solves the problem and returns the trajectory. The arguments of the components are reached by nested names, <label>__<name>, as the steps of a scikit-learn Pipeline are, so set_params(gravity__g=1.62) sets g of the component labelled gravity. A solver or backend left as 'auto' follows from the problem. It models an ecosystem of populations, a network of reactions, a circuit, or a market, and a system nests in another one as a component.

Read more in the user guide, under Systems.

Attributes:

Name Type Description
states_ tuple[str, ...]

The names of the values the laws change, with the derivatives and past values they need.

parameters_ tuple[str, ...]

The names of the values no law changes.

equations_ dict[str, str]

One readable equation per state, summed over the laws and reduced to first order.

form_ str

The kind of problem the laws make, such as ordinary differential equations.

solver_ BaseSolver

The solver that every run copies.

backend_ BaseBackend

The backend that evaluates the compiled functions.

See Also

BaseSystem: The base of ready-made systems, which build a system from the parameters of their model.

Examples:

>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> system = System(systems=[LotkaVolterraSystem(label='meadow')]).set_params(meadow__r=1.5)
>>> system.get_params()['meadow__r'], float(system.prepare().simulate(until=5.0).times[-1])
(1.5, 5.0)

Parameters:

Name Type Description Default
label str

The label of the system, which names it when it is nested in another one.

'system'
elements Sequence[BaseElement]

The elements, which hold the states.

()
interactions Sequence[BaseInteraction]

The interactions, which change the states through their laws.

()
systems Sequence[BaseComponent]

The nested systems, each with a label of its own. Each keeps the time its own laws imply, so a nested system of updates steps once per unit of time beside a nested system of rates.

()
space BaseSpace | None

The space the elements live on, or None for none.

None
solver BaseSolver | str

The solver of the problem, or 'auto' for the default solver of the problem.

AUTO
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the default one.

AUTO
Source code in src/skcomplex/core/systems/_system.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def __init__(
    self,
    label: str = 'system',
    *,
    elements: Sequence[BaseElement] = (),
    interactions: Sequence[BaseInteraction] = (),
    systems: Sequence[BaseComponent] = (),
    space: BaseSpace | None = None,
    solver: BaseSolver | str = AUTO,
    backend: BaseBackend | str = AUTO,
) -> None:
    """Store the label, the components, and the settings of the system.

    Args:
        label:
            The label of the system, which names it when it is nested in another one.

        elements:
            The elements, which hold the states.

        interactions:
            The interactions, which change the states through their laws.

        systems:
            The nested systems, each with a label of its own. Each keeps the time its own laws imply, so a
            nested system of updates steps once per unit of time beside a nested system of rates.

        space:
            The space the elements live on, or `None` for none.

        solver:
            The solver of the problem, or `'auto'` for the default solver of the problem.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the default one.
    """
    super().__init__(label, solver=solver, backend=backend)
    self.elements = elements
    self.interactions = interactions
    self.systems = systems
    self.space = space

get_params(deep=True)

Return the parameters of the system and of its components by nested names.

Parameters:

Name Type Description Default
deep bool

Whether to add the parameters of the space, the solver, the backend, and every component, each under <name>__<parameter>.

True

Returns:

Name Type Description
params dict[str, object]

The parameters by name.

Examples:

>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> System(systems=[LotkaVolterraSystem(label='meadow')]).get_params()['meadow__prey']
40.0
Source code in src/skcomplex/core/systems/_system.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def get_params(self, deep: bool = True) -> dict[str, object]:
    """Return the parameters of the system and of its components by nested names.

    Args:
        deep:
            Whether to add the parameters of the space, the solver, the backend, and every component, each under
            `<name>__<parameter>`.

    Returns:
        params:
            The parameters by name.

    Examples:
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
        >>> System(systems=[LotkaVolterraSystem(label='meadow')]).get_params()['meadow__prey']
        40.0
    """
    params = super().get_params(deep=False)
    if not deep:
        return params
    for name in SETTINGS:
        value = params[name]
        if isinstance(value, BaseComponent | BaseSolver | BaseBackend):
            params.update({f'{name}__{key}': item for key, item in value.get_params(deep=True).items()})
    for component in self._get_components():
        params.update({f'{component.label}__{key}': item for key, item in component.get_params(deep=True).items()})
    return params

set_params(**params)

Set parameters of the system and of its components by nested names.

Parameters:

Name Type Description Default
**params object

The new values, by the name of a parameter of the system, or by <name>__<parameter> for a setting or a component.

{}

Returns:

Name Type Description
self System

The system.

Raises:

Type Description
ValidationError

A name matches no parameter, no setting, and no component, named in the message.

Examples:

>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> system = System(systems=[LotkaVolterraSystem(label='meadow')]).set_params(meadow__a=0.5)
>>> system.get_params()['meadow__a']
0.5
Source code in src/skcomplex/core/systems/_system.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def set_params(self, **params: object) -> System:
    """Set parameters of the system and of its components by nested names.

    Args:
        **params:
            The new values, by the name of a parameter of the system, or by `<name>__<parameter>` for a setting
            or a component.

    Returns:
        self:
            The system.

    Raises:
        ValidationError:
            A name matches no parameter, no setting, and no component, named in the message.

    Examples:
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
        >>> system = System(systems=[LotkaVolterraSystem(label='meadow')]).set_params(meadow__a=0.5)
        >>> system.get_params()['meadow__a']
        0.5
    """
    own = super().get_params(deep=False)
    nested: dict[str, dict[str, object]] = {}
    for key, value in params.items():
        head, separator, rest = key.partition('__')
        if separator:
            nested.setdefault(head, {})[rest] = value
            continue
        if key not in own:
            error_msg = f'The system {self.label!r} has no parameter {key!r}. Its parameters are {", ".join(own)}.'
            raise ValidationError(error_msg)
        setattr(self, key, value)
    for head, values in nested.items():
        target = self._get_target(head)
        accepted = target.get_params(deep=True)
        for name in values:
            first = name.partition('__')[0]
            if first not in accepted and name not in accepted:
                error_msg = (
                    f'The component {head!r} of the system {self.label!r} has no parameter {first!r}. '
                    f'Its parameters are {", ".join(target.get_params(deep=False))}.'
                )
                raise ValidationError(error_msg)
        target.set_params(**values)
    return self