Skip to content

Dynamics

Define the dynamical systems that the systems of several fields share.

States evolve by their equations, in continuous or discrete time, on the nodes of a graph, as fields on a lattice, or as stocks that change through named flows.

AnnotatedElement(label, *, values=None, allowed=None, quantities=None)

Bases: Element

An element of values by name, with the allowed values and quantities of some.

It holds what a class would write in Annotated, for values known only as data. The values {'n': 40.0} with allowed={'n': RealSet.closed_open(0, oo)} and quantities={'n': 'people'} are read as n: Annotated[float, RealSet.closed_open(0, oo), Quantity('people')] = 40.0, so a negative n is rejected and the conservation monitor follows the people. The generic systems that build one element from a mapping of states, such as DynamicalSystem and StockFlowSystem, build this element.

Unlike Element, whose subclass writes the allowed values and quantities in Annotated on its arguments, it takes them as data. Choose it when the names of the values are known only when a system is built.

It appears in many fields. The stocks of a bathtub, the people of a diffusion of innovations, and the oil of an economy are each its values.

Parameters:

Name Type Description Default
label str

The name of the element, unique among the components of its system, such as 'population'.

required
values Mapping[str, object] | None

The values by name, such as {'n': 40.0, 'r': 0.5}, or None for none.

None
allowed Mapping[str, object] | None

The allowed values of some values by name, a RealSet such as RealSet.closed_open(0, oo) or a set such as {'S', 'I', 'R'}, or None for none.

None
quantities Mapping[str, str] | None

The quantity some values hold by name, such as {'n': 'people'}, or None for none.

None

Examples:

>>> from sage.all__sagemath_symbolics import oo
>>> from sage.sets.real_set import RealSet
>>> from skcomplex.systems.general.dynamics import AnnotatedElement
>>> from skcomplex.core.errors import ValidationError
>>> from skcomplex.core.systems import System
>>> tank = AnnotatedElement('tank', values={'level': -1.0}, allowed={'level': RealSet.closed_open(0, oo)})
>>> try:
...     System(elements=[tank]).prepare()
... except ValidationError as error:
...     print(error)
The system is not valid, with 1 error(s):
- tank: tank.level = -1.0 is not in its domain [0, +oo). Correct the component as the message describes. [value]
Source code in src/skcomplex/systems/general/dynamics/_annotated_element.py
56
57
58
59
60
61
62
63
64
65
66
def __init__(
    self,
    label: str,
    *,
    values: Mapping[str, object] | None = None,
    allowed: Mapping[str, object] | None = None,
    quantities: Mapping[str, str] | None = None,
) -> None:
    super().__init__(label, values=values)
    self.allowed = allowed
    self.quantities = quantities

DynamicalSystem(states=None, equations=None, *, parameters=None, noises=None, allowed=None, quantities=None, time='continuous', convention='ito', element='state', label='system', solver='auto', backend='auto')

Bases: BaseSystem

A system of states and the equations that evolve them, as rates or as maps.

The states and parameters are the values of one element. In continuous time the equation of a state is its rate, or the rate of its derivative when the state is named with primes, such as "x''" for an acceleration, and it may carry a noise amplitude in the Itô or Stratonovich convention. In discrete time it is the next value of the state, and every map reads the states at the start of the step. An equation is a function of a namespace whose target holds the states and parameters as functions of the time t, which it also holds. A derivative or a past value starts from the value named with primes or a past index among the states, such as {'y': 1.0, 'y[-1]': 1.0}.

A subclass takes the parameters of its model under its own names and returns the states, equations, parameters, and noises from _get_states, _get_equations, _get_parameters, and _get_noises, the allowed values and quantities of its states from _get_allowed and _get_quantities, the time from _get_time, and the label of the element from _get_element_label.

Unlike System, which takes any components, it is written with one element and one EquationInteraction per state. Choose it when a model is a set of equations, one per state.

It appears in many fields. The Lorenz flow of mathematics, the populations of Wilson and Cowan in neuroscience, the Hénon map, and the multiplier and accelerator model of economics are dynamical systems.

Attributes:

Name Type Description
system_ BaseSystem

The System of the element and its equations built from the parameters at the last prepare.

See Also

StockFlowSystem: Stocks that change only through named flows between them.

Examples:

The excitatory and inhibitory populations of Wilson and Cowan, which settle at a rest point:

>>> from sage.all__sagemath_symbolics import exp
>>> from skcomplex.systems.general.dynamics import DynamicalSystem
>>> def response(u):
...     return 1 / (1 + exp(-u))
>>> populations = DynamicalSystem(
...     states={'e': 0.1, 'i': 0.05},
...     equations={
...         'e': lambda s: -s.target.e + response(s.target.c_ee * s.target.e - s.target.c_ei * s.target.i),
...         'i': lambda s: -s.target.i + response(s.target.c_ie * s.target.e - s.target.c_ii * s.target.i),
...     },
...     parameters={'c_ee': 2.0, 'c_ei': 3.0, 'c_ie': 2.0, 'c_ii': 1.0},
...     element='populations',
... )
>>> trajectory = populations.prepare().simulate(until=50.0, dt=1.0)
>>> e, i = (float(trajectory.get_values(f'populations.{name}')[-1]) for name in 'ei')
>>> abs(e - float(response(2.0 * e - 3.0 * i))) < 1e-6
True

The multiplier-accelerator of Samuelson, whose income y of a period depends on the two before it:

>>> economy = DynamicalSystem(
...     states={'y': 1.0, 'previous': 1.0},
...     equations={
...         'y': lambda s: s.target.g + s.target.c * (1 + s.target.v) * s.target.y - s.target.c * s.target.v
...         * s.target.previous,
...         'previous': lambda s: s.target.y,
...     },
...     parameters={'g': 1.0, 'c': 0.5, 'v': 0.5},
...     time='discrete',
...     element='economy',
... )
>>> economy.prepare().simulate(until=3).get_values('economy.y').tolist()
[1.0, 1.5, 1.875, 2.03125]

Parameters:

Name Type Description Default
states Mapping[str, object] | None

The initial value of every state, by name, or None for no states.

None
equations Equations | None

The rate or the next value of every state, by name, as a function of the namespace, or None.

None
parameters Mapping[str, object] | None

The value of every parameter the equations read, by name, or None for none.

None
noises Noises | None

The noise amplitude of every state that has one, by name, as a function of the namespace or a number, or None for none. Only continuous time takes noise.

None
allowed Mapping[str, object] | None

The allowed values of some states by name, a RealSet such as RealSet.closed_open(0, oo) or a set such as {'S', 'I', 'R'}, or None for none. A state outside them is rejected.

None
quantities Mapping[str, str] | None

The quantity some states hold by name, such as {'n': 'people'}, which the conservation monitor follows, or None for none.

None
time str

The time of the equations, 'continuous' for rates or 'discrete' for maps.

'continuous'
convention str

The stochastic calculus of the noises, 'ito' or 'stratonovich'.

'ito'
element str

The label of the element that holds the states and the parameters.

'state'
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 the system chooses.

'auto'
backend BaseBackend | str

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

'auto'
Source code in src/skcomplex/systems/general/dynamics/_dynamical.py
 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
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
152
153
154
155
156
157
158
def __init__(
    self,
    states: Mapping[str, object] | None = None,
    equations: Equations | None = None,
    *,
    parameters: Mapping[str, object] | None = None,
    noises: Noises | None = None,
    allowed: Mapping[str, object] | None = None,
    quantities: Mapping[str, str] | None = None,
    time: str = 'continuous',
    convention: str = 'ito',
    element: str = 'state',
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    """Store the states, equations, parameters, noises, time, labels, and settings.

    Args:
        states:
            The initial value of every state, by name, or `None` for no states.

        equations:
            The rate or the next value of every state, by name, as a function of the namespace, or `None`.

        parameters:
            The value of every parameter the equations read, by name, or `None` for none.

        noises:
            The noise amplitude of every state that has one, by name, as a function of the namespace or a
            number, or `None` for none. Only continuous time takes noise.

        allowed:
            The allowed values of some states by name, a `RealSet` such as `RealSet.closed_open(0, oo)` or a set
            such as `{'S', 'I', 'R'}`, or `None` for none. A state outside them is rejected.

        quantities:
            The quantity some states hold by name, such as `{'n': 'people'}`, which the conservation monitor
            follows, or `None` for none.

        time:
            The time of the equations, `'continuous'` for rates or `'discrete'` for maps.

        convention:
            The stochastic calculus of the noises, `'ito'` or `'stratonovich'`.

        element:
            The label of the element that holds the states and the parameters.

        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.
    """
    super().__init__(label, solver=solver, backend=backend)
    self.states = states
    self.equations = equations
    self.parameters = parameters
    self.noises = noises
    self.allowed = allowed
    self.quantities = quantities
    self.time = time
    self.convention = convention
    self.element = element

EquationInteraction(label, *, target, state, equation=None, noise=None, convention='ito', time='continuous')

Bases: Interaction

An interaction that gives one state of an element its rate or its next value.

In continuous time the equation is the rate of the state, or of its derivative of order k when the state is named with k primes, such as "x''" for an acceleration, and a noise amplitude adds a noise in the Itô or Stratonovich convention. In discrete time the equation is the next value of the state, read from the values at the start of the step. An equation and a noise are functions of the namespace whose target holds the values of the element and whose t holds the time.

Unlike Interaction, which a subclass gives laws of its own, it takes the equation as a function. Choose it when one state follows one formula, with no class of its own.

It appears in many fields. The decay of a tank, the logistic map of a population, and the income of an economy are each one equation of one state.

Parameters:

Name Type Description Default
label str

The label of the interaction, unique among the components of its system.

required
target Role

The path of the element whose state the equation changes.

required
state str

The name of the state, with a prime for every order of the derivative the equation gives.

required
equation Callable[[SimpleNamespace], object] | None

The rate or the next value as a function of the namespace, or None for a noise alone.

None
noise Callable[[SimpleNamespace], object] | float | None

The noise amplitude as a function of the namespace or a number, or None for none.

None
convention str

The stochastic calculus of the noise, 'ito' or 'stratonovich'.

'ito'
time str

The time of the equation, 'continuous' for a rate or 'discrete' for a next value.

'continuous'

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.general.dynamics import EquationInteraction
>>> decay = EquationInteraction('decay', target='tank', state='x', equation=lambda s: -s.target.k * s.target.x)
>>> system = System(elements=[Element('tank', values={'x': 1.0, 'k': 0.5})], interactions=[decay])
>>> round(float(system.prepare().simulate(until=2.0, dt=2.0).get_values('tank.x')[-1]), 4)
0.3679
Source code in src/skcomplex/systems/general/dynamics/_equation.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def __init__(
    self,
    label: str,
    *,
    target: Role,
    state: str,
    equation: Callable[[SimpleNamespace], object] | None = None,
    noise: Callable[[SimpleNamespace], object] | float | None = None,
    convention: str = 'ito',
    time: str = 'continuous',
) -> None:
    super().__init__(label)
    self.target = target
    self.state = state
    self.equation = equation
    self.noise = noise
    self.convention = convention
    self.time = time

FlowInteraction(label, *, target, leaves=None, enters=None, amount)

Bases: Interaction

An interaction that moves an amount from one stock of an element to another.

The flow f takes f from the stock it leaves and gives f to the stock it enters, as the one rate law RateLaw({leaves: -1, enters: +1}, f, label=label), so the total of the stocks is kept and the trajectory records f as <element>.<label>. A flow from outside the system enters a stock and leaves none, and a flow out of the system leaves a stock and enters none. The amount is a function of the namespace whose target holds the values of the element and whose t holds the time.

Unlike EquationInteraction, which gives one state its rate, it changes two stocks by one amount, so what leaves one enters the other. Choose it when an amount moves between stocks, as in system dynamics.

It appears in many fields. Water drains from a bathtub, people adopt a product in a diffusion of innovations, and capital depreciates in an economy.

Parameters:

Name Type Description Default
label str

The label of the interaction and the name of its flow, such as 'births'.

required
target Role

The path of the element that holds the stocks.

required
leaves str | None

The stock the flow leaves, or None for a flow from outside the system.

None
enters str | None

The stock the flow enters, or None for a flow out of the system.

None
amount Callable[[SimpleNamespace], object] | float

The amount per unit of time as a function of the namespace, or a number.

required

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.general.dynamics import FlowInteraction
>>> drain = FlowInteraction('drain', target='tub', leaves='water', amount=lambda s: s.target.k * s.target.water)
>>> system = System(elements=[Element('tub', values={'water': 10.0, 'k': 0.5})], interactions=[drain])
>>> trajectory = system.prepare().simulate(until=2.0, dt=2.0)
>>> [round(float(value), 4) for value in trajectory.get_values('tub.drain')]
[5.0, 1.8394]
Source code in src/skcomplex/systems/general/dynamics/_flow.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(
    self,
    label: str,
    *,
    target: Role,
    leaves: str | None = None,
    enters: str | None = None,
    amount: Callable[[SimpleNamespace], object] | float,
) -> None:
    super().__init__(label)
    self.target = target
    self.leaves = leaves
    self.enters = enters
    self.amount = amount

NetworkDynamicalSystem(graph=None, states=None, equations=None, coupling=None, *, parameters=None, noises=None, convention='ito', element='nodes', label='system', solver='auto', backend='auto')

Bases: DynamicalSystem

A dynamical system with states on every node of a graph and coupled neighbours.

The states and parameters are the values of an element with one member on every node of the NetworkSpace of the graph. The equations are the local rates of every node. For every state with a coupling g, the rate of node i gains sum_j g(x_i, x_j) over its neighbours j, where g reads node i as s.member and its neighbour as s.other. An initial value is one number for every node or an array with one value per node. The system runs in continuous time.

A subclass returns the graph from _get_graph and the couplings from _get_coupling, besides the hooks of DynamicalSystem.

Unlike DynamicalSystem, which holds one copy of its states, it puts one copy on every node of a network space and sums the couplings over the neighbours. Choose it when identical units interact along the edges of a graph.

It appears in many fields. Heat diffuses on a graph in mathematics, cells exchange ions through gap junctions in physiology, and oscillators synchronize on a network in physics.

Attributes:

Name Type Description
system_ BaseSystem

The System of the nodes, their equations, and their couplings built at the last prepare.

Examples:

Diffusion on a path of three nodes, which spreads the content of the first node evenly:

>>> import networkx as nx
>>> from skcomplex.systems.general.dynamics import NetworkDynamicalSystem
>>> diffusion = NetworkDynamicalSystem(
...     nx.path_graph(3),
...     states={'u': [1.0, 0.0, 0.0]},
...     coupling={'u': lambda s: s.member.D * (s.other.u - s.member.u)},
...     parameters={'D': 1.0},
... )
>>> trajectory = diffusion.prepare().simulate(until=20.0, dt=1.0)
>>> [round(float(value), 3) for value in trajectory.get_values('nodes.u')[-1]]
[0.333, 0.333, 0.333]

Cells coupled by gap junctions, each relaxing to its own rest value while it exchanges with its neighbours:

>>> cells = NetworkDynamicalSystem(
...     nx.cycle_graph(4),
...     states={'v': [1.0, 0.0, 0.0, 0.0]},
...     equations={'v': lambda s: -s.target.v / s.target.tau},
...     coupling={'v': lambda s: s.member.g * (s.other.v - s.member.v)},
...     parameters={'tau': 10.0, 'g': 0.5},
...     element='cells',
... )
>>> trajectory = cells.prepare().simulate(until=5.0, dt=1.0)
>>> bool(trajectory.get_values('cells.v')[-1][1] > 0)
True

Parameters:

Name Type Description Default
graph Graph | None

The NetworkX graph whose nodes hold the states, required.

None
states Mapping[str, object] | None

The initial value of every state by name, a number for every node or one value per node.

None
equations Equations | None

The local rate of every state by name, as a function of the namespace, or None.

None
coupling Equations | None

The term g(x_i, x_j) of one neighbour for every coupled state by name, as a function of a namespace whose member holds the node and other its neighbour, or None.

None
parameters Mapping[str, object] | None

The value of every parameter by name, or None for none.

None
noises Noises | None

The noise amplitude of every state that has one, by name, or None for none.

None
convention str

The stochastic calculus of the noises, 'ito' or 'stratonovich'.

'ito'
element str

The label of the field of the nodes.

'nodes'
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 the system chooses.

'auto'
backend BaseBackend | str

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

'auto'
Source code in src/skcomplex/systems/general/dynamics/_network_dynamical.py
 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
100
101
102
103
104
105
106
107
108
109
110
111
112
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
def __init__(
    self,
    graph: nx.Graph | None = None,
    states: Mapping[str, object] | None = None,
    equations: Equations | None = None,
    coupling: Equations | None = None,
    *,
    parameters: Mapping[str, object] | None = None,
    noises: Noises | None = None,
    convention: str = 'ito',
    element: str = 'nodes',
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    """Store the graph, states, equations, couplings, and the rest of the data.

    Args:
        graph:
            The NetworkX graph whose nodes hold the states, required.

        states:
            The initial value of every state by name, a number for every node or one value per node.

        equations:
            The local rate of every state by name, as a function of the namespace, or `None`.

        coupling:
            The term `g(x_i, x_j)` of one neighbour for every coupled state by name, as a function of a namespace
            whose `member` holds the node and `other` its neighbour, or `None`.

        parameters:
            The value of every parameter by name, or `None` for none.

        noises:
            The noise amplitude of every state that has one, by name, or `None` for none.

        convention:
            The stochastic calculus of the noises, `'ito'` or `'stratonovich'`.

        element:
            The label of the field of the nodes.

        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.
    """
    super().__init__(
        states,
        equations,
        parameters=parameters,
        noises=noises,
        convention=convention,
        element=element,
        label=label,
        solver=solver,
        backend=backend,
    )
    self.graph = graph
    self.coupling = coupling

ReactionDiffusionSystem(states=None, equations=None, diffusivities=None, *, shape=64, spacing=1.0, boundary='periodic', discretization='finite-difference', parameters=None, noises=None, convention='ito', element='medium', label='system', solver='auto', backend='auto')

Bases: DynamicalSystem

A dynamical system of fields on a lattice, with local kinetics and diffusion.

The states and parameters are the values of an element with one member on every site of a LatticeSpace. The equations are the local kinetics of every site, and every field u with a diffusivity D gains the rate D laplacian(u), a separate EquationInteraction, so a split solver can treat it apart. A diffusivity is a number or a function of the namespace. An initial value is one number for every site or an array of the shape of the lattice. The system runs in continuous time.

A subclass returns the diffusivities from _get_diffusivities, the lattice from _get_space, and the boundary of every field from _get_boundaries, besides the hooks of DynamicalSystem. A system whose kinetics are reactions returns them from _get_equation_interactions.

Unlike NetworkDynamicalSystem, which couples nodes of a graph, it couples the sites of a lattice by a Laplacian, written with an element on a lattice and a diffusion per field. Choose it when substances react locally and spread in space.

It appears in many fields. The Gray-Scott model makes spots and stripes in chemistry, the Fisher and Kolmogorov front spreads a species in ecology, and the FitzHugh-Nagumo model sends waves through heart tissue.

Attributes:

Name Type Description
system_ BaseSystem

The System of the field, its kinetics, and its diffusion built at the last prepare.

Examples:

The front of Fisher and Kolmogorov, which invades the empty right side of a line:

>>> import numpy as np
>>> from skcomplex.systems.general.dynamics import ReactionDiffusionSystem
>>> initial = np.zeros(50)
>>> initial[:5] = 1.0
>>> front = ReactionDiffusionSystem(
...     states={'u': initial},
...     equations={'u': lambda s: s.target.r * s.target.u * (1 - s.target.u)},
...     diffusivities={'u': 1.0},
...     shape=50,
...     boundary='reflecting',
...     parameters={'r': 1.0},
... )
>>> trajectory = front.prepare().simulate(until=10.0, dt=1.0)
>>> bool(trajectory.get_values('medium.u')[-1][20] > trajectory.get_values('medium.u')[0][20])
True

The Gray-Scott model, whose substrate u feeds the autocatalysis of the activator v:

>>> u, v = np.ones(32), np.zeros(32)
>>> u[12:20], v[12:20] = 0.5, 0.25
>>> gray_scott = ReactionDiffusionSystem(
...     states={'u': u, 'v': v},
...     equations={
...         'u': lambda s: -s.target.u * s.target.v**2 + s.target.F * (1 - s.target.u),
...         'v': lambda s: s.target.u * s.target.v**2 - (s.target.F + s.target.k) * s.target.v,
...     },
...     diffusivities={'u': 0.2, 'v': 0.1},
...     shape=32,
...     parameters={'F': 0.04, 'k': 0.06},
... )
>>> trajectory = gray_scott.prepare().simulate(until=20.0, dt=5.0)
>>> bool(trajectory.get_values('medium.v')[-1].max() > 0)
True

Parameters:

Name Type Description Default
states Mapping[str, object] | None

The initial value of every field by name, a number for every site or an array of the shape.

None
equations Equations | None

The local kinetics of every field by name, as a function of the namespace, or None.

None
diffusivities Mapping[str, Callable[[SimpleNamespace], object] | float] | None

The diffusivity of every field that diffuses, by name, a number or a function of the namespace, or None for none.

None
shape Sequence[int] | int

The number of sites along every axis of the lattice, or one number for a line.

64
spacing float

The distance between neighbouring sites.

1.0
boundary str

The boundary of the lattice, 'periodic', 'fixed', or 'reflecting'.

'periodic'
discretization str

The discretization of the fields, 'finite-difference' or 'spectral'.

'finite-difference'
parameters Mapping[str, object] | None

The value of every parameter by name, or None for none.

None
noises Noises | None

The noise amplitude of every field that has one, by name, or None for none.

None
convention str

The stochastic calculus of the noises, 'ito' or 'stratonovich'.

'ito'
element str

The label of the field.

'medium'
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 the system chooses.

'auto'
backend BaseBackend | str

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

'auto'
Source code in src/skcomplex/systems/general/dynamics/_reaction_diffusion.py
 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
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
152
153
154
155
156
157
158
159
160
161
162
def __init__(
    self,
    states: Mapping[str, object] | None = None,
    equations: Equations | None = None,
    diffusivities: Mapping[str, Callable[[SimpleNamespace], object] | float] | None = None,
    *,
    shape: Sequence[int] | int = 64,
    spacing: float = 1.0,
    boundary: str = 'periodic',
    discretization: str = 'finite-difference',
    parameters: Mapping[str, object] | None = None,
    noises: Noises | None = None,
    convention: str = 'ito',
    element: str = 'medium',
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    """Store the fields, kinetics, diffusivities, lattice, and the rest of the data.

    Args:
        states:
            The initial value of every field by name, a number for every site or an array of the shape.

        equations:
            The local kinetics of every field by name, as a function of the namespace, or `None`.

        diffusivities:
            The diffusivity of every field that diffuses, by name, a number or a function of the namespace, or
            `None` for none.

        shape:
            The number of sites along every axis of the lattice, or one number for a line.

        spacing:
            The distance between neighbouring sites.

        boundary:
            The boundary of the lattice, `'periodic'`, `'fixed'`, or `'reflecting'`.

        discretization:
            The discretization of the fields, `'finite-difference'` or `'spectral'`.

        parameters:
            The value of every parameter by name, or `None` for none.

        noises:
            The noise amplitude of every field that has one, by name, or `None` for none.

        convention:
            The stochastic calculus of the noises, `'ito'` or `'stratonovich'`.

        element:
            The label of the field.

        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.
    """
    super().__init__(
        states,
        equations,
        parameters=parameters,
        noises=noises,
        convention=convention,
        element=element,
        label=label,
        solver=solver,
        backend=backend,
    )
    self.diffusivities = diffusivities
    self.shape = shape
    self.spacing = spacing
    self.boundary = boundary
    self.discretization = discretization

StockFlowSystem(stocks=None, flows=None, *, parameters=None, allowed=None, quantities=None, element='stocks', label='system', solver='auto', backend='auto')

Bases: BaseSystem

A system of stocks that change only through named flows between them.

The stocks and parameters are the values of one element. Every flow leaves a stock, or comes from outside the system, and enters a stock, or leaves the system, at a rate that is a function of a namespace whose target holds the stocks and parameters and whose t holds the time. A flow is a FlowInteraction, the rate law RateLaw({leaves: -1, enters: +1}, f, label=flow), so the trajectory reports it as <element>.<flow>, and a flow between two stocks keeps their total.

A subclass returns the stocks, flows, and parameters from the hooks _get_stocks, _get_flows, and _get_parameters, the allowed values and quantities of its stocks from _get_allowed and _get_quantities, and the label of the element from _get_element_label.

Unlike DynamicalSystem, which writes a rate per state, it writes flows between stocks with a FlowInteraction, so what leaves one stock enters another. Choose it when a model is drawn as stocks and flows, as in system dynamics.

It appears in many fields. A bathtub fills and drains in engineering, nations build arms in the arms race of Richardson, and the models of system dynamics of Forrester follow stocks of people, capital, and goods.

Attributes:

Name Type Description
system_ BaseSystem

The System of the element and its flows built from the parameters at the last prepare.

Examples:

A bathtub whose faucet fills it as fast as its drain empties it:

>>> from skcomplex.systems.general.dynamics import StockFlowSystem
>>> tub = StockFlowSystem(
...     stocks={'water': 50.0},
...     flows={
...         'faucet': (None, 'water', lambda s: s.target.inflow),
...         'drain': ('water', None, lambda s: s.target.outflow),
...     },
...     parameters={'inflow': 5.0, 'outflow': 5.0},
...     element='tub',
... )
>>> trajectory = tub.prepare().simulate(until=10.0, dt=5.0)
>>> trajectory.get_values('tub.water').tolist(), trajectory.get_values('tub.faucet').tolist()
([50.0, 50.0, 50.0], [5.0, 5.0, 5.0])

The arms race of two nations, each arming faster the more the other holds:

>>> race = StockFlowSystem(
...     stocks={'a': 1.0, 'b': 1.0},
...     flows={
...         'arming_a': (None, 'a', lambda s: s.target.k * s.target.b),
...         'arming_b': (None, 'b', lambda s: s.target.k * s.target.a),
...     },
...     parameters={'k': 0.1},
...     element='nations',
... )
>>> trajectory = race.prepare().simulate(until=10.0, dt=10.0)
>>> round(float(trajectory.get_values('nations.a')[-1]), 3)
2.718

Parameters:

Name Type Description Default
stocks Mapping[str, float] | None

The initial value of every stock, by name, or None for no stocks.

None
flows FlowTable | None

The stock it leaves, or None for a flow from outside the system, the stock it enters, or None for a flow out of the system, and the rate of every flow, by name, or None for no flows.

None
parameters Mapping[str, object] | None

The value of every parameter the rates read, by name, or None for none.

None
allowed Mapping[str, object] | None

The allowed values of some stocks by name, a RealSet such as RealSet.closed_open(0, oo) for a stock that cannot go negative, or None for none. A stock outside them is rejected.

None
quantities Mapping[str, str] | None

The quantity some stocks hold by name, such as {'water': 'water'}, which the conservation monitor follows, or None for none.

None
element str

The label of the element that holds the stocks and the parameters.

'stocks'
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 the system chooses.

'auto'
backend BaseBackend | str

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

'auto'
Source code in src/skcomplex/systems/general/dynamics/_stock_flow.py
 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def __init__(
    self,
    stocks: Mapping[str, float] | None = None,
    flows: FlowTable | None = None,
    *,
    parameters: Mapping[str, object] | None = None,
    allowed: Mapping[str, object] | None = None,
    quantities: Mapping[str, str] | None = None,
    element: str = 'stocks',
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    """Store the stocks, the flows, the parameters, and the labels.

    Args:
        stocks:
            The initial value of every stock, by name, or `None` for no stocks.

        flows:
            The stock it leaves, or `None` for a flow from outside the system, the stock it enters, or `None` for a
            flow out of the system, and the rate of every flow, by name, or `None` for no flows.

        parameters:
            The value of every parameter the rates read, by name, or `None` for none.

        allowed:
            The allowed values of some stocks by name, a `RealSet` such as `RealSet.closed_open(0, oo)` for a stock
            that cannot go negative, or `None` for none. A stock outside them is rejected.

        quantities:
            The quantity some stocks hold by name, such as `{'water': 'water'}`, which the conservation monitor
            follows, or `None` for none.

        element:
            The label of the element that holds the stocks and the parameters.

        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.
    """
    super().__init__(label, solver=solver, backend=backend)
    self.stocks = stocks
    self.flows = flows
    self.parameters = parameters
    self.allowed = allowed
    self.quantities = quantities
    self.element = element