Next-generation reservoir computer
A next-generation reservoir computer.
- Class:
NextGenerationReservoirSystem - Import:
from skcomplex.systems.computer_science.neural_networks import NextGenerationReservoirSystem - Field:
computer_science/neural_networks - Topics:
neural network,reservoir computing,next generation,lags,discrete map - References:
- Gauthier et al. 2021
- Cestnik and Martens 2025
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.computer_science.neural_networks import NextGenerationReservoirSystem
trajectory = NextGenerationReservoirSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
series |
None |
result |
None |
variables |
('x', 'y', 'z') |
delay |
2 |
order |
2 |
ridge |
2.5e-06 |
standardize |
False |
samples |
403 |
step |
0.025 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | discrete |
| Space | none |
| Laws | update |
| Randomness | unknown |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class NextGenerationReservoirSystem(BaseSystem):
"""A next-generation reservoir computer.
Its variables follow the ridge readout of their monomials.
Every variable keeps `delay - 1` lags, and one map in the increment mode adds to it the readout of the constant, the
variables with their lags, and the monomials of degree `order` of those. The readout comes from the result of
`reservoir(kind='next_generation')`, and the variables start at the end of its last series, so a run is the
autonomous forecast from there. One step of the system stands for one sample of the series. The defaults are those
of Gauthier et al. (2021) for the Lorenz flow: 400 training samples after a warmup of 2, one sample every 0.025 from
an explicit Runge-Kutta 3(2) integrator, and the ridge 2.5e-6 on features that are not standardized. A ridge this
small on these features diverges within one Lyapunov time when a series comes from a much more accurate integrator,
and such a series needs `standardize=True`. The system has the variables `reservoir.x` and their lags
`reservoir.x_lag1` for the Lorenz flow.
Args:
series:
The training series, one row per sample and one column per variable, or `None` for `samples` samples of the
Lorenz flow every `step`.
result:
The result of a next-generation `reservoir` to take the readout from, which replaces the fit.
variables:
The names of the columns of the series.
delay:
The number of consecutive samples the features read.
order:
The degree of the monomials.
ridge:
The strength of the ridge penalty.
standardize:
Whether the features read the standardized variables.
samples:
The number of samples of the Lorenz flow.
step:
The time between the samples of the Lorenz flow.
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 the system chooses.
backend:
The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.
Raises:
ValidationError:
The result is not that of a next-generation reservoir.
Examples:
>>> import numpy as np
>>> from skcomplex.systems.computer_science.neural_networks import NextGenerationReservoirSystem
>>> values = np.sin(0.1 * np.arange(200.0))[:, None]
>>> NextGenerationReservoirSystem(values, variables=['v']).prepare().states_
('reservoir.v', 'reservoir.v[-1]')
"""
field = 'computer_science/neural_networks'
topics = ('neural network', 'reservoir computing', 'next generation', 'lags', 'discrete map')
references = ('Gauthier et al. 2021', 'Cestnik and Martens 2025')
until = 200
dt = 1
def __init__(
self,
series: Array | None = None,
*,
result: ReservoirResult | None = None,
variables: Sequence[str] = LORENZ_VARIABLES,
delay: int = 2,
order: int = 2,
ridge: float = 2.5e-6,
standardize: bool = False,
samples: int = 403,
step: float = 0.025,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.series = series
self.result = result
self.variables = variables
self.delay = delay
self.order = order
self.ridge = ridge
self.standardize = standardize
self.samples = samples
self.step = step
@staticmethod
def _get_lorenz_series(
samples: int,
step: float,
sigma: float = 10.0,
rho: float = 28.0,
beta: float = 8.0 / 3.0,
) -> Array:
"""Return samples of the Lorenz flow on its attractor.
There is one row per sample and one column per variable.
"""
rates: dict[str, Callable[[SimpleNamespace], Expression]] = {
'x': lambda s: sigma * (s.target.y - s.target.x),
'y': lambda s: s.target.x * (rho - s.target.z) - s.target.y,
'z': lambda s: s.target.x * s.target.y - beta * s.target.z,
}
system = System(
elements=[LorenzFlowElement('flow')],
interactions=[
Interaction(
'lorenz',
roles={'target': 'flow'},
laws=lambda s: [RateLaw(getattr(s.target, name), rate(s)) for name, rate in rates.items()],
),
],
solver=ScipyODESolver(method='RK23', rtol=LORENZ_RTOL, atol=LORENZ_ATOL),
)
trajectory = system.prepare().simulate(until=LORENZ_TRANSIENT + step * (samples - 1), dt=step)
values: Array = np.column_stack(
[np.asarray(trajectory.get_values(f'flow.{name}'), dtype=np.float64) for name in LORENZ_VARIABLES],
)
return values[-samples:]
@staticmethod
def _get_reservoir_element(initial: Mapping[str, Sequence[float]]) -> Element:
"""Return the element of scalar states with their past values.
It is built from the values of every state and of its past values, named `x[-1]`, `x[-2]`, and so on.
"""
values = {
f'{name}[-{steps}]' if steps else name: float(value)
for name, past in initial.items()
for steps, value in enumerate(past)
}
return Element('reservoir', values=values)
@staticmethod
def _increment(
s: SimpleNamespace,
*,
names: Sequence[str],
delay: int,
powers: npt.NDArray[np.int_],
weights: Array,
bias: float,
mean: Array,
scale: Array,
spread: float,
) -> Expression:
"""Return the increment of a variable.
It is the ridge readout of the monomials of the rescaled lagged variables.
"""
linear = [
(getattr(s.target, name)(t=s.t - steps) - mean[index]) / scale[index]
for steps in range(delay)
for index, name in enumerate(names)
]
monomials = [np.prod([linear[int(column)] for column in row]) for row in powers]
features = [*linear, *monomials]
readout = sum(float(weight) * feature for weight, feature in zip(weights, features, strict=True) if weight)
return spread * (readout + bias)
@staticmethod
def _get_step(
s: SimpleNamespace,
*,
name: str,
increment: Callable[[SimpleNamespace], Expression],
) -> list[BaseLaw]:
"""Return the update that adds the increment of a variable to it."""
value = getattr(s.target, name)
return [UpdateLaw(value, value + increment(s), increment=True)]
@staticmethod
def _fit_reservoir(
series: Array | None,
variables: Sequence[str],
*,
delay: int,
order: int,
ridge: float,
standardize: bool,
samples: int,
step: float,
) -> ReservoirResult:
"""Return the next-generation reservoir fitted to a series.
Without a series, it is fitted to samples of the Lorenz flow.
"""
values = NextGenerationReservoirSystem._get_lorenz_series(samples, step) if series is None else series
return reservoir(
values,
variables=list(variables),
kind=REQUIRED_KIND,
delay=delay,
order=order,
ridge=ridge,
standardize=standardize,
validation=0.0,
dt=step,
)
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the components of the system built from its model parameters."""
super()._prepare(context)
fitted = self.result or self._fit_reservoir(
self.series,
self.variables,
delay=self.delay,
order=self.order,
ridge=self.ridge,
standardize=self.standardize,
samples=self.samples,
step=self.step,
)
if fitted.step.kind != REQUIRED_KIND:
error_msg = f'The readout comes from a {REQUIRED_KIND!r} reservoir, not from a {fitted.step.kind!r} one.'
raise ValidationError(error_msg)
names = fitted.states[: len(fitted.labels)]
readout = fitted.step
delay = (len(fitted.states) - len(names)) // len(names)
memory = fitted.samples.series[-1][-delay:][::-1]
initial = {name: memory[:, index].tolist() for index, name in enumerate(names)}
element = self._get_reservoir_element(initial)
weights = np.asarray(readout.readout.Wout, dtype=float)
bias = np.ravel(np.asarray(readout.readout.bias, dtype=float))
increments = {
name: functools.partial(
self._increment,
names=names,
delay=delay,
powers=readout.get_monomials(),
weights=weights[:, index],
bias=float(bias[index]),
mean=readout.mean,
scale=readout.scale,
spread=float(readout.scale[index]),
)
for index, name in enumerate(names)
}
maps = [
Interaction(
name,
roles={'target': 'reservoir'},
laws=functools.partial(self._get_step, name=name, increment=increments[name]),
)
for name in names
]
self.system_ = System(self.label, elements=[element], interactions=maps)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
Interaction
class Element(BaseElement):
"""An element that holds named values of one thing or of a group of members.
It holds its values by name, such as the height and mass of a ball in
`Element('ball', values={'x': 10.0, 'm': 1.0})`, and the laws of the interactions decide which values change. With
`size` it holds a group of members with values of their own, such as 1000 molecules of a gas, and with `space` one
member per site, such as the cells of a grid. A subclass may take its values as arguments of `__init__` instead,
such as a population class with a growth rate. Members whose values change by agent rules, Python functions run for
each member at each step, act as agents, and their values may be any Python object. It holds a prey population, a
firm of an economy, and the charge of a capacitor.
Read more in the user guide, under Elements.
Args:
label:
The name of the element, unique among the components of its system, such as `'rabbits'`.
values:
Values by name, such as `{'x': 10.0, 'm': 1.0}`. A derivative or a past value that a law reads starts from
the value named with primes or a past index, such as `{'x': 10.0, "x'": 3.0}` for a ball thrown upwards or
`{'y': 1.0, 'y[-1]': 0.5}` for an economy. A group of members takes one value per member as an array.
size:
The number of members, each with its own values, such as `1000` molecules of a gas, or `None` for one.
space:
The space of the element, with one member per site, such as a lattice of cells, or `None` for none.
on:
The part of a network space that holds one member each: `'edges'` for every link, `'hyperedges'` for every
hyperedge, the name of a layer for every link of that layer, such as `'immune'`, or `None` for every site.
Attributes:
default_visual_:
How the element is drawn by default, the `visual` of its class.
See Also:
BaseElement: The base of every element.
Interaction: States the laws that change the values of elements.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> ball = Element('ball', values={'x': 10.0, 'm': 1.0})
>>> ball.get_params()['x']
10.0
"""
law_classes: ClassVar[tuple[type, ...]] = ()
def __init__(
self,
label: str,
*,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
on: str | None = None,
) -> None:
super().__init__(label)
self.values = values
self.size = size
self.space = space
self.on: object = on
def get_params(self, deep: bool = True) -> dict[str, Any]:
"""Return the parameters of the element, with each entry of `values` when deep.
An entry of `values` whose name is a Python identifier is listed under its own name, so a system lists it as
`<element>__<name>` and `set_params(ball__x=2.0)`, grid searches, and sweeps reach it. A primed or past value,
such as `"x'"` or `'x[-1]'`, is no identifier and stays inside `values`. An entry that has the name of an
argument is not listed twice.
Args:
deep:
Whether to add the parameters of nested estimators and the entries of `values`.
Returns:
params:
The parameters by name.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> params = Element('ball', values={'x': 10.0, "x'": 3.0}).get_params()
>>> params['x'], "x'" in params
(10.0, False)
"""
params = super().get_params(deep=deep)
if deep and isinstance(self.values, Mapping):
entries = self._get_value_entries()
params.update({name: value for name, value in entries.items() if name not in params})
return params
def set_params(self, **params: object) -> Self:
"""Set parameters of the element and entries of `values` by name.
An entry of `values` takes its new value in a new mapping, so the mapping the user gave never changes, as
`clone` of scikit-learn leaves the arguments of an estimator unchanged. A new `values` is set first, so the
output of `get_params` is accepted as it is.
Args:
**params:
The new values, by the name of a parameter or of an entry of `values`, such as `x=2.0`.
Returns:
self:
The element.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> values = {'x': 10.0}
>>> Element('ball', values=values).set_params(x=2.0).values, values
({'x': 2.0}, {'x': 10.0})
"""
arguments = super().get_params(deep=True)
if 'values' in params:
super().set_params(values=params['values'])
entries = self._get_value_entries()
changed = {name: value for name, value in params.items() if name in entries and name not in arguments}
rest = {name: value for name, value in params.items() if name not in changed and name != 'values'}
super().set_params(**rest)
if changed:
self.values = {**(self.values or {}), **changed}
return self
def _get_value_entries(self) -> dict[str, object]:
"""Return the entries of `values` whose names are Python identifiers."""
values = self.values if isinstance(self.values, Mapping) else {}
return {name: value for name, value in values.items() if name.isidentifier()}
def _prepare(self, context: BaseSpace | None = None) -> None:
"""Set `default_visual_`, checking the reserved names.
Args:
context:
The space the element inherits from its system, which an element with `on` and no space of its own
sits on.
Raises:
ValidationError:
`size` is not a number of members, `space` is not a space, or `values` is not a mapping, as when a
subclass stores a quantity of its own under a reserved name.
"""
super()._prepare(context)
size = self.size
checks = {
'size': size is None or (isinstance(size, numbers.Integral) and not isinstance(size, bool) and size >= 1),
'space': self.space is None or isinstance(self.space, BaseSpace),
'values': self.values is None or isinstance(self.values, Mapping),
}
for name, valid in checks.items():
if not valid:
error_msg = (
f'Element {self.label!r} has {name} = {getattr(self, name)!r}, but {name} is the '
f'{RESERVED_MEANINGS[name]}. The names {", ".join(RESERVED)} are reserved, so rename the value, '
f'such as half_side for the half side of a table.'
)
raise ValidationError(error_msg)
self._check_on(self.space if self.space is not None else context)
def _get_tags(self) -> Tags:
"""Return the tags of the element, with the tags of its space when it has one.
A field on a phase space thus asks for a solver that supports phase spaces, as a group on it does.
"""
tags = super()._get_tags()
if not isinstance(self.space, BaseSpace):
return tags
return replace(tags, space=self.space.get_tags().space)
def _check_on(self, space: BaseSpace | None) -> None:
"""Raise an error for an `on` that names no part of a network space.
A value named `on` that the element declares as its own state or parameter names no place. The space is the
element's own, or else that of its system.
"""
if isinstance(type(self)._get_specs().get('on'), _StateSpec | _ParameterSpec):
return
on = getattr(self, 'on', None)
if on is None or (isinstance(space, NetworkSpace) and (on in LINKS or on in space.prepare().graphs_)):
return
error_msg = (
f'Element {self.label!r} has on = {on!r}, but on is the part of a network space that holds one member '
"each, 'edges', 'hyperedges', or the name of a layer for its edges, such as "
"Element('links', values={'sign': 1}, space=network, on='edges'). The names "
f'{", ".join(RESERVED)} are reserved, so rename a value of the element named on, such as closed for a '
'switch.'
)
raise ValidationError(error_msg)
@staticmethod
def _get_domain_of(annotation: object, value: object) -> object:
"""Return the domain of a value from its annotation or its Python type.
A value without an annotation, such as one given through `values`, takes the domain of its type, so `3` is an
integer and `0.5 + 1j` is complex. The annotation `object` says nothing of the kind, so a value annotated so,
such as a point that may be one number or an array of complex numbers, also takes the domain of its type, and
so does a value of one of several types, such as `float | Sequence[float]`. A subshift, such as
`Annotated[int, SubshiftSpec(LatticeNeighborhood(((0,), (1,))), ((1, 1),))]`, is the domain of the cells of a
lattice whose configurations hold no forbidden word.
"""
if get_origin(annotation) is Annotated:
for item in get_args(annotation)[1:]:
if isinstance(item, set | frozenset):
return FiniteEnumeratedSet(sorted(item, key=str))
allowed = hasattr(item, '__contains__') and not isinstance(item, str | MatrixGroupSpec)
if allowed or isinstance(item, SubshiftSpec | PowerSeriesSpec):
return item
annotation = get_args(annotation)[0]
annotated = isinstance(annotation, type) and annotation not in {inspect.Parameter.empty, object}
kind = annotation if annotated else type(value)
if kind is bool:
return BOOLEAN
if kind is int:
return ZZ
if kind is complex or (isinstance(kind, type) and issubclass(kind, np.complexfloating)):
return CC
return RR
def _get_domain_tags(self) -> frozenset[str]:
"""Return the domain tags of the states of the element.
An element that declares no states has the domains of all its numeric values, since the laws of the system
decide which of them are states, such as `boolean` for `opinion: Annotated[int, {0, 1}] = 0`.
"""
if self._get_component_specs():
return super()._get_domain_tags()
params = self.get_params(deep=False)
values = {name: params.get(name) for name in self._get_hints()}
values |= {name: value for name, value in (self.values or {}).items() if name.isidentifier()}
hints = self._get_hints()
domains = {
_StateSpec(domain=self._get_domain_of(hints.get(name, inspect.Parameter.empty), value))._get_domain_tag()
for name, value in values.items()
if isinstance(value, numbers.Number | list | np.ndarray)
}
return frozenset(domain for domain in domains if domain is not None)
def _get_hints(self) -> dict[str, object]:
"""Return the type hint of every value argument by name, in their order.
The hints are the annotations of the arguments of the class, such as `Annotated[float, Quantity('energy')]`,
from which the kind, the allowed values, the quantity, and the period of each value are read. A generic
subclass that takes its values through `values` gives their hints here instead, and the arguments it leaves
out, such as the allowed values themselves, are no values.
"""
parameters = inspect.signature(type(self)).parameters
return {name: parameter.annotation for name, parameter in parameters.items() if name not in RESERVED}
@classmethod
def _get_view(cls) -> type | None:
"""Return the class of the views of the element's agents.
The result is `None` for the engine's plain view. An agent element names a subclass of the engine's `AgentView`
that annotates its states and parameters, such as `class WordView(AgentView): count: float`, so its rules read
them with checked types.
"""
return None
class Interaction(BaseInteraction):
"""An interaction whose laws run once for the elements its roles bind.
It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
`Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
populations, a reaction between two chemicals, and an infection along the contacts of a network.
Read more in the user guide, under Interactions.
Args:
label:
The name of the interaction, unique among the components of its system, such as `'predation'`.
roles:
The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
without a class, or `None`.
laws:
The function of the namespace that returns the laws of a rule written without a class, such as
`lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
`None`.
among:
The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.
along:
`True` for the edges of the network the group lives on, the name of a layer of a network with several, such
as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
`RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.
within:
A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
force `-dV/dx` on its position `x`.
See Also:
BaseInteraction: The base of every interaction.
RandomPartition: Groups the members of a group at random at every step.
TrainingInteraction: Trains the parameters of a nested system.
Examples:
>>> from skcomplex.core.components.interactions import Interaction
>>> from skcomplex.core.components.laws import RateLaw
>>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
>>> birth.roles
{'target': 'fish'}
"""
def __init__(
self,
label: str,
*,
roles: Mapping[str, object] | None = None,
laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
among: str | None = None,
along: bool | str | tuple[str, int] | RandomPartition | None = None,
within: RadiusNeighborhood | None = None,
) -> None:
super().__init__(label)
self.roles = roles
self.laws = laws
self.among = among
self.along = along
self.within = within
def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
"""Return the numeric arguments as parameters, and `roles` and `among` as roles.
With `within`, `among` binds both members of a pair, `first` and `second`.
"""
declared = dict(super()._get_declared())
for name, binding in (self.roles or {}).items():
declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
if self.among is not None and self.within is not None:
for name in PAIR_ROLES:
declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
return declared
@classmethod
def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
"""Return the arguments that name the states a role reads.
The mapping `roles` of bindings names none.
"""
return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')
def _get_binding(self, role: str) -> object:
"""Return what a role binds, from `roles` or from the argument of its name.
Args:
role:
The name of the role.
Returns:
binding:
The label, labels, or entries the role binds, or `None` when it binds nothing.
"""
if self.roles is not None and role in self.roles:
return self.roles[role]
if self.among is not None and self.within is not None and role in PAIR_ROLES:
return self.among
return super()._get_binding(role)
def _check_arguments(self) -> None:
"""Raise an error for roles, laws, or groups the interaction cannot take.
Raises:
ValidationError:
A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
`along` names hyperedges of fewer than two members.
"""
clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
if clashes:
error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
raise ValidationError(error_msg)
if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
error_msg = (
f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
'`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
)
raise ValidationError(error_msg)
if isinstance(self.along, tuple) and not self._is_sized(self.along):
error_msg = (
f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
"more, such as `along=('hyperedges', 3)`."
)
raise ValidationError(error_msg)
if isinstance(self.along, RandomPartition):
self.along._check()
grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
if grouped and self.among is None:
error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
raise ValidationError(error_msg)
super()._check_arguments()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the laws of `laws` for a binding.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
if self.laws is not None:
self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)
@staticmethod
def _is_sized(along: tuple[object, ...]) -> bool:
"""Return whether `along` names hyperedges of a whole size of at least two."""
if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
return False
size = along[1]
return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE
def _get_draws(self) -> bool:
"""Return whether the interaction draws, as it does along random groups."""
return super()._get_draws() or isinstance(self.along, RandomPartition)
def _runs_on_edges(self) -> bool:
"""Return whether the interaction runs along edges."""
grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
return self.along is not None and self.along is not False and not grouped
def _runs_on_hyperedges(self) -> bool:
"""Return whether the interaction runs along the hyperedges of a network."""
return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)
def _get_hyperedge_size(self) -> int | None:
"""Return the size `along` gives the hyperedges, or `None` for every size."""
return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None
def _get_within(self) -> RadiusNeighborhood | None:
"""Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
return self.within
def _get_layer(self) -> str | None:
"""Return the layer `along` names, or `None` for no layer."""
if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
return None
return self.along
def _get_grouping(self) -> tuple[str, int, str] | None:
"""Return the kind, size, and reduction of the groups `along` names, or `None`."""
if isinstance(self.along, RandomPartition):
return ('partition', self.along.size, 'sum')
if self.along == NEIGHBORHOODS:
return ('neighborhood', 0, 'sum')
return None
Equations
The equations are those that symbolic returns for the system with its default parameters.
reservoir.x: x_reservoir(t + 1) == 0.17050883557479024*x_reservoir(t - 1)^2 - 0.4445426181745938*x_reservoir(t - 1)*x_reservoir(t) + 0.2897146386610814*x_reservoir(t)^2 + 0.07401707191745804*x_reservoir(t - 1)*y_reservoir(t - 1) - 0.09936512836523562*x_reservoir(t)*y_reservoir(t - 1) - 0.0012761830493759761*y_reservoir(t - 1)^2 + 0.044010028250892834*x_reservoir(t - 1)*y_reservoir(t) - 0.06144721930828467*x_reservoir(t)*y_reservoir(t) + 0.010673962725213287*y_reservoir(t - 1)*y_reservoir(t) + 0.011653632423364035*y_reservoir(t)^2 + 0.01314485941420484*x_reservoir(t - 1)*z_reservoir(t - 1) - 0.014048542801376254*x_reservoir(t)*z_reservoir(t - 1) + 0.00033039792113955825*y_reservoir(t - 1)*z_reservoir(t - 1) + 0.0033682015837940343*y_reservoir(t)*z_reservoir(t - 1) - 0.007732198996608577*z_reservoir(t - 1)^2 + 0.003201291465732947*x_reservoir(t - 1)*z_reservoir(t) - 0.005752516686640341*x_reservoir(t)*z_reservoir(t) + 0.001876618274372709*y_reservoir(t - 1)*z_reservoir(t) - 0.0017087047836610379*y_reservoir(t)*z_reservoir(t) - 0.0002569685617111461*z_reservoir(t - 1)*z_reservoir(t) + 0.009106497652138317*z_reservoir(t)^2 - 0.7563733844999379*x_reservoir(t - 1) + 1.716820390840865*x_reservoir(t) - 0.22957564017196186*y_reservoir(t - 1) + 0.257930784010802*y_reservoir(t) + 0.20495953945574263*z_reservoir(t - 1) - 0.2189645043193256*z_reservoir(t) - 0.0009915671569448517
reservoir.y: y_reservoir(t + 1) == 0.3837760040935468*x_reservoir(t - 1)^2 - 0.9404245945615081*x_reservoir(t - 1)*x_reservoir(t) + 0.5746687457998512*x_reservoir(t)^2 + 0.13655996343507026*x_reservoir(t - 1)*y_reservoir(t - 1) - 0.1717923820409355*x_reservoir(t)*y_reservoir(t - 1) + 0.006769327051808785*y_reservoir(t - 1)^2 + 0.09525045405071028*x_reservoir(t - 1)*y_reservoir(t) - 0.11884608400370415*x_reservoir(t)*y_reservoir(t) + 0.019756942076075756*y_reservoir(t - 1)*y_reservoir(t) + 0.00938438550558518*y_reservoir(t)^2 + 0.22551219900851466*x_reservoir(t - 1)*z_reservoir(t - 1) - 0.2840162037983414*x_reservoir(t)*z_reservoir(t - 1) + 0.020756445463053382*y_reservoir(t - 1)*z_reservoir(t - 1) + 0.04828624108647412*y_reservoir(t)*z_reservoir(t - 1) - 0.0036573525159888202*z_reservoir(t - 1)^2 - 0.18856172558506856*x_reservoir(t - 1)*z_reservoir(t) + 0.2129185546375565*x_reservoir(t)*z_reservoir(t) - 0.01376353188295018*y_reservoir(t - 1)*z_reservoir(t) - 0.04751163354962531*y_reservoir(t)*z_reservoir(t) - 0.0006122133142129663*z_reservoir(t - 1)*z_reservoir(t) + 0.004838276179139897*z_reservoir(t)^2 - 0.24544504892636543*x_reservoir(t - 1) + 0.9823487126030579*x_reservoir(t) - 0.006100456690071532*y_reservoir(t - 1) + 0.9811531406509877*y_reservoir(t) + 0.032260286880973724*z_reservoir(t - 1) - 0.03468224742266105*z_reservoir(t) + 0.0013288088543112891
reservoir.z: z_reservoir(t + 1) == 0.2691928846127659*x_reservoir(t - 1)^2 - 0.6273833545268067*x_reservoir(t - 1)*x_reservoir(t) + 0.36186157130339325*x_reservoir(t)^2 - 0.23965292038308034*x_reservoir(t - 1)*y_reservoir(t - 1) + 0.3097057388444604*x_reservoir(t)*y_reservoir(t - 1) - 0.019798910070759238*y_reservoir(t - 1)^2 + 0.30389265085373135*x_reservoir(t - 1)*y_reservoir(t) - 0.35003049477770676*x_reservoir(t)*y_reservoir(t) - 0.014160777009192438*y_reservoir(t - 1)*y_reservoir(t) + 0.03209242445910958*y_reservoir(t)^2 + 0.043832030925677154*x_reservoir(t - 1)*z_reservoir(t - 1) - 0.05866299185778247*x_reservoir(t)*z_reservoir(t - 1) + 0.00719970829262321*y_reservoir(t - 1)*z_reservoir(t - 1) + 0.006098702898783471*y_reservoir(t)*z_reservoir(t - 1) + 0.006689405467376683*z_reservoir(t - 1)^2 - 0.05669395406431819*x_reservoir(t - 1)*z_reservoir(t) + 0.07197536384314429*x_reservoir(t)*z_reservoir(t) - 0.008992790370354074*y_reservoir(t - 1)*z_reservoir(t) - 0.007630550740569115*y_reservoir(t)*z_reservoir(t) + 0.018463907696223456*z_reservoir(t - 1)*z_reservoir(t) - 0.027368256983809246*z_reservoir(t)^2 + 0.29657867695792034*x_reservoir(t - 1) - 0.28968188842629555*x_reservoir(t) + 0.15252339628114506*y_reservoir(t - 1) - 0.08161150368788703*y_reservoir(t) - 0.8129085105333808*z_reservoir(t - 1) + 1.8042273045123114*z_reservoir(t) - 0.0002622183573863703