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 |
required |
values
|
Mapping[str, object] | None
|
The values by name, such as |
None
|
allowed
|
Mapping[str, object] | None
|
The allowed values of some values by name, a |
None
|
quantities
|
Mapping[str, str] | None
|
The quantity some values hold by name, such as |
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 | |
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 |
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
|
equations
|
Equations | None
|
The rate or the next value of every state, by name, as a function of the namespace, or |
None
|
parameters
|
Mapping[str, object] | None
|
The value of every parameter the equations read, by name, or |
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
|
allowed
|
Mapping[str, object] | None
|
The allowed values of some states by name, a |
None
|
quantities
|
Mapping[str, str] | None
|
The quantity some states hold by name, such as |
None
|
time
|
str
|
The time of the equations, |
'continuous'
|
convention
|
str
|
The stochastic calculus of the noises, |
'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'
|
backend
|
BaseBackend | str
|
The backend that evaluates the compiled functions, or |
'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 | |
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
|
noise
|
Callable[[SimpleNamespace], object] | float | None
|
The noise amplitude as a function of the namespace or a number, or |
None
|
convention
|
str
|
The stochastic calculus of the noise, |
'ito'
|
time
|
str
|
The time of the equation, |
'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 | |
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 |
required |
target
|
Role
|
The path of the element that holds the stocks. |
required |
leaves
|
str | None
|
The stock the flow leaves, or |
None
|
enters
|
str | None
|
The stock the flow enters, or |
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 | |
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 |
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
|
coupling
|
Equations | None
|
The term |
None
|
parameters
|
Mapping[str, object] | None
|
The value of every parameter by name, or |
None
|
noises
|
Noises | None
|
The noise amplitude of every state that has one, by name, or |
None
|
convention
|
str
|
The stochastic calculus of the noises, |
'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'
|
backend
|
BaseBackend | str
|
The backend that evaluates the compiled functions, or |
'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 | |
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 |
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
|
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
|
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'
|
discretization
|
str
|
The discretization of the fields, |
'finite-difference'
|
parameters
|
Mapping[str, object] | None
|
The value of every parameter by name, or |
None
|
noises
|
Noises | None
|
The noise amplitude of every field that has one, by name, or |
None
|
convention
|
str
|
The stochastic calculus of the noises, |
'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'
|
backend
|
BaseBackend | str
|
The backend that evaluates the compiled functions, or |
'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 | |
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 |
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
|
flows
|
FlowTable | None
|
The stock it leaves, or |
None
|
parameters
|
Mapping[str, object] | None
|
The value of every parameter the rates read, by name, or |
None
|
allowed
|
Mapping[str, object] | None
|
The allowed values of some stocks by name, a |
None
|
quantities
|
Mapping[str, str] | None
|
The quantity some stocks hold by name, such as |
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'
|
backend
|
BaseBackend | str
|
The backend that evaluates the compiled functions, or |
'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 | |