Min-protein skeleton system as mass-conserving reaction-diffusion
The skeleton system of the Min proteins on a periodic line.
- Class:
MinProteinSkeletonSystem - Import:
from skcomplex.systems.biology.systems_biology import MinProteinSkeletonSystem - Field:
biology/systems_biology - Topics:
field,min proteins,mass conserving,reaction-diffusion,traveling waves,pde - References:
- Brauns and Marchetti 2024
- Halatek and Frey 2018
- Huang, Meir, and Wingreen 2003
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.biology.systems_biology import MinProteinSkeletonSystem
trajectory = MinProteinSkeletonSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_sites |
128 |
length |
100.0 |
total_D |
200.0 |
total_E |
120.0 |
random_state |
0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | continuous |
| Space | lattice |
| Laws | rate |
| Randomness | deterministic |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class MinProteinSkeletonSystem(ReactionDiffusionSystem):
"""The skeleton system of the Min proteins on a periodic line.
It is a mass-conserving reaction-diffusion system.
MinD and MinE cycle between the membrane, where they diffuse slowly, and the cytosol, where they diffuse fast, with
the attachment and self-recruitment of MinD-ATP to the membrane, `(k_d + k_dd md) cdt`, the recruitment of MinE by
membrane MinD, `k_de md ce`, the dissociation of MinDE complexes, `k_off mde`, which releases MinD-ADP and MinE to
the cytosol, and the nucleotide exchange `lam cdd` from MinD-ADP to MinD-ATP. The reactions conserve the totals of
MinD and MinE, so only diffusion moves mass, and the local reactive equilibria map the dynamics onto conserved
fields with nonreciprocal cross-diffusion (Brauns and Marchetti, App. F). With the default totals, the uniform state
is unstable to an oscillatory band of wavelengths near 17, and narrow bands of membrane MinD travel along the line
and meet head-on. The fast cytosolic diffusion and the fast recruitment make the system stiff, so the catalog
registers the implicit `BDF` method with the exact Jacobian. The system has the membrane fields `cell.md` and
`cell.mde` and the cytosolic fields `cell.cdt`, `cell.cdd`, and `cell.ce`.
Args:
n_sites:
The number of sites of the periodic line.
length:
The length of the line.
total_D:
The mean total density of MinD.
total_E:
The mean total density of MinE.
random_state:
The seed or generator of the 1% noise that moves MinD between the membrane and the cytosol.
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.
Examples:
>>> from skcomplex.systems.biology.systems_biology import MinProteinSkeletonSystem
>>> values = MinProteinSkeletonSystem(32).prepare().system_.elements[0].values
>>> round(float(values['ce'].mean() + values['mde'].mean()), 6)
120.0
"""
field = 'biology/systems_biology'
topics = ('field', 'min proteins', 'mass conserving', 'reaction-diffusion', 'traveling waves', 'pde')
references = ('Brauns and Marchetti 2024', 'Halatek and Frey 2018', 'Huang, Meir, and Wingreen 2003')
until = 400.0
dt = 4.0
def __init__(
self,
n_sites: int = 128,
*,
length: float = 100.0,
total_D: float = 200.0,
total_E: float = 120.0,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label=label, solver=solver, backend=backend)
self.n_sites = n_sites
self.length = length
self.total_D = total_D
self.total_E = total_E
self.random_state = random_state
def _get_solver(self) -> BaseSolver:
"""Return the solver the system is tuned to."""
return ScipyODESolver(method='BDF', jacobian='exact')
@staticmethod
def _get_uniform_state(total_D: float, total_E: float) -> dict[str, float]:
"""Return the uniform steady state of the skeleton system.
It has the totals of MinD and MinE.
"""
def others(md: float) -> tuple[float, float, float, float]:
mde = total_E * RATES['k_de'] * md / (RATES['k_off'] + RATES['k_de'] * md)
return (
mde,
RATES['k_off'] * mde / (RATES['k_d'] + RATES['k_dd'] * md),
RATES['k_off'] * mde / RATES['lam'],
total_E - mde,
)
md = brentq(lambda md: md + sum(others(md)[:3]) - total_D, 0.0, total_D)
mde, cdt, cdd, ce = others(md)
return {'md': md, 'mde': mde, 'cdt': cdt, 'cdd': cdd, 'ce': ce}
def _get_element_label(self) -> str:
"""Return the label of the field of the sites."""
return 'cell'
def _get_space(self) -> LatticeSpace:
"""Return the periodic line of the sites."""
return LatticeSpace(self.n_sites, spacing=self.length / self.n_sites)
def _get_states(self) -> dict[str, object]:
"""Return the uniform state with 1% of MinD moved between the cytosol and the membrane."""
rng = np.random.default_rng(self.random_state)
uniform = self._get_uniform_state(self.total_D, self.total_E)
values: dict[str, Array] = {name: np.full(self.n_sites, value) for name, value in uniform.items()}
noise = 0.01 * uniform['md'] * rng.uniform(-1.0, 1.0, self.n_sites)
values['md'] = values['md'] + noise
values['cdt'] = values['cdt'] - noise
return dict(values)
def _get_parameters(self) -> dict[str, object]:
"""Return the rates."""
return dict(RATES)
def _get_equation_interactions(self) -> list[ReactionInteraction]:
"""Return the attachment, the recruitment, the release, and the nucleotide exchange."""
return [
ReactionInteraction(
'attachment',
target='cell',
reactants={'cdt': 1},
products={'md': 1},
propensity=lambda s: (s.target.k_d + s.target.k_dd * s.target.md) * s.target.cdt,
),
ReactionInteraction(
'recruitment',
target='cell',
reactants={'md': 1, 'ce': 1},
products={'mde': 1},
propensity=lambda s: s.target.k_de * s.target.md * s.target.ce,
),
ReactionInteraction(
'release',
target='cell',
reactants={'mde': 1},
products={'cdd': 1, 'ce': 1},
propensity=lambda s: s.target.k_off * s.target.mde,
),
ReactionInteraction(
'exchange',
target='cell',
reactants={'cdd': 1},
products={'cdt': 1},
propensity=lambda s: s.target.lam * s.target.cdd,
),
]
def _get_diffusivities(self) -> dict[str, Callable[[SimpleNamespace], object]]:
"""Return the slow diffusion on the membrane and the fast diffusion in the cytosol."""
membrane = {state: lambda s: s.target.Dm for state in ('md', 'mde')}
cytosol = {state: lambda s: s.target.Dc for state in ('cdt', 'cdd', 'ce')}
return {**membrane, **cytosol}
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
ReactionInteraction, fromInteraction, through the shared recipeReactionInteractionEquationInteraction, fromInteraction, through the shared recipeEquationInteraction
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 ReactionInteraction(Interaction):
"""An interaction that moves units from its reactants to its products.
A reactant, a product, or a modifier is a pair of the path of an element and the name of its state, mapped to its
stoichiometric coefficient, the number of units the reaction takes or gives. So `S + I -> 2 I` has the reactants
`{('S', 'n'): 1, ('I', 'n'): 1}` and the products `{('I', 'n'): 2}`. A coefficient is a positive number or a
function of the namespace. A species may also be the name of a state of `target` alone, such as `{'u': 1, 'v': 2}`,
and a target that is a group or a field reacts in every member. A subclass may bind its species under roles of its
own, such as `susceptible` and `infected`, and return its entries from `_get_reactants`, `_get_products`, and
`_get_modifiers`.
The propensity is the rate constant `k` times the product of the reactant and modifier amounts, each raised to its
coefficient, or the expression that `propensity` returns. Fields name this product their own way: mass action in
chemistry, homogeneous mixing in epidemiology, the encounter term of Lotka and Volterra in ecology. The `mode` says
how the reaction runs:
- `'rate'`: a rate equation.
- `'jump'`: a random event at the propensity that moves the units of the coefficients.
- `'langevin'`: the chemical Langevin equation, the rate equation with a noise of amplitude the square root of the
propensity.
With a `schedule` it sets one rule that walks the members of an agent group in that order, and every member reacts
on its own states at every step.
Unlike `Interaction`, which takes laws written by hand, it builds the changes from a stoichiometric vector and the
propensity from mass action, and the same reaction runs as a rate, a jump, or a Langevin equation. Choose it when a
model is written as reactions between species.
It appears in many fields. Molecules react in a cell, people pass from susceptible to infected in an epidemic,
predators eat prey, and enzymes bind their substrates.
Args:
label:
The label of the reaction, unique among the components of its system.
target:
The path of the element, group, or field whose states the species named by a state alone are, or `None`.
reactants:
The coefficients of the reactants, or `None` for a source.
products:
The coefficients of the products, or `None` for a sink.
k:
The rate constant.
propensity:
A function of the namespace of the reaction that returns the propensity, or `None` for the product
propensity. The namespace holds the tuples `reactants`, `products`, and `modifiers` of the namespaces of the
elements their pairs bind, in the order of their entries, `target`, the namespace of the target or of one of
its members, and the symbol `k`. With a schedule, a function `propensity(agent, system)` that returns a
number.
modifiers:
The coefficients of the modifiers, whose states the propensity reads but the reaction does not change, or
`None`.
mode:
The form of the laws, `'rate'`, `'jump'`, or `'langevin'`.
phase:
The phase of the step the rule of a schedule runs in, or `None` for the default phase.
schedule:
The order in which a rule walks the members, `'synchronous'` for every member at once, `'sequential'` or
`'random-sequential'` for one member after the other, or `'member'` for every member in its own activation,
or `None` for the laws of the states.
Raises:
ValidationError:
The mode or the schedule is unknown, the reaction has neither reactants nor products, an entry is neither a
pair of a path and a state name nor a state name of a given target, a coefficient is neither a positive
number nor a function, or a reaction with a schedule has no target, has an entry that is a pair, or has
the mode `'langevin'`.
Examples:
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.general.elements import NonnegativeElement
>>> from skcomplex.systems.general.reactions import ReactionInteraction
>>> infection = ReactionInteraction(
... 'infection', reactants={('S', 'x'): 1, ('I', 'x'): 1}, products={('I', 'x'): 2}, k=0.0005
... )
>>> recovery = ReactionInteraction('recovery', reactants={('I', 'x'): 1}, products={('R', 'x'): 1}, k=0.1)
>>> system = System(
... elements=[NonnegativeElement('S', x=990), NonnegativeElement('I', x=10), NonnegativeElement('R')],
... interactions=[infection, recovery],
... )
>>> states = system.prepare().simulate(until=50, dt=1.0).states
>>> round(float(states[-1].sum()), 6)
1000.0
The decay `x -> 0` at every site of a lattice, at the rate `k x` of the site:
>>> import numpy as np
>>> from skcomplex.core.components.spaces import LatticeSpace
>>> decay = ReactionInteraction('decay', target='cells', reactants={'x': 1}, k=1.0)
>>> cells = NonnegativeElement('cells', x=np.arange(3.0), space=LatticeSpace((3,)))
>>> trajectory = System(elements=[cells], interactions=[decay]).prepare().simulate(until=1, dt=1.0)
>>> np.round(trajectory.get_lattice('cells.x')[-1], 3).tolist()
[0.0, 0.368, 0.736]
A coefficient that is a parameter, the decay at the rate `x` that removes `1 / epsilon` units per event:
>>> from skcomplex.core.components.elements import Element
>>> scaled = ReactionInteraction(
... 'decay', target='box', reactants={'x': lambda s: 1 / s.target.epsilon}, propensity=lambda s: s.target.x
... )
>>> box = Element('box', values={'x': 1.0, 'epsilon': 0.5})
>>> trajectory = System(elements=[box], interactions=[scaled]).prepare().simulate(until=0.5, dt=0.01)
>>> round(float(trajectory.get_values('box.x')[-1]), 3)
0.368
Every agent of a group decays on its own states, by `k n` in a step of the rate equation:
>>> cells = Element('cells', values={'n': 3.0}, size=2)
>>> decay = ReactionInteraction('decay', target='cells', reactants={'n': 1}, k=0.1, schedule='synchronous')
>>> trajectory = System(elements=[cells], interactions=[decay]).prepare().simulate(until=2)
>>> np.round(trajectory.get_agents('cells', 2).values['n'], 6).tolist()
[2.43, 2.43]
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (RateLaw, NoiseLaw, JumpLaw, UpdateLaw)
def _get_tags(self) -> Tags:
"""Return the tags of the rule of a schedule, or of the laws without one.
The laws without a schedule are rate, jump, or Langevin laws.
"""
if self._get_argument('schedule') is not None:
return self._get_variant_tags((UpdateLaw,), stochastic=self._get_mode() == 'jump')
modes: dict[object, tuple[type[BaseLaw], ...]] = {'jump': (JumpLaw,), 'langevin': (RateLaw, NoiseLaw)}
return self._get_variant_tags(modes.get(self._get_mode(), (RateLaw,)))
def __init__(
self,
label: str,
*,
target: Role | None = None,
reactants: Stoichiometry | None = None,
products: Stoichiometry | None = None,
k: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
propensity: Callable[..., object] | None = None,
modifiers: Stoichiometry | None = None,
mode: str = 'rate',
phase: str | None = None,
schedule: str | None = None,
) -> None:
super().__init__(label)
self.target = target
self.reactants = reactants
self.products = products
self.k = k
self.propensity = propensity
self.modifiers = modifiers
self.mode = mode
self.phase = phase
self.schedule = schedule
def _get_reactants(self) -> Stoichiometry | None:
"""Return the coefficients of the reactants.
A subclass with roles of its own names returns them.
"""
return self.reactants
def _get_products(self) -> Stoichiometry | None:
"""Return the coefficients of the products.
A subclass with roles of its own names returns them.
"""
return self.products
def _get_modifiers(self) -> Stoichiometry | None:
"""Return the coefficients of the modifiers.
A subclass with roles of its own names returns them.
"""
return self.modifiers
def _get_mode(self) -> str:
"""Return the form of the laws.
A subclass that sets it by another argument returns it.
"""
return self.mode
def _get_bound(self, namespace: SimpleNamespace) -> dict[str, SimpleNamespace]:
"""Return the namespace of every path the plain roles of the reaction bind."""
roles = self._get_roles(single=True)
return {
getattr(self, name): getattr(namespace, name)
for name in roles
if isinstance(getattr(self, name), str) and hasattr(namespace, name)
}
def _get_terms(
self,
entries: Stoichiometry | None,
namespace: SimpleNamespace,
name: str,
) -> list[tuple[Expression, Expression | float]]:
"""Return the state symbol and the coefficient of every entry of a kind of species.
A state name alone is a state of the target. A pair reads the namespace of the plain role that binds its path,
or else the namespace of its variadic role `name`, in the order of the pairs. A coefficient that is a function
is its expression at the namespace.
"""
entries = entries or {}
pairs = [entry for entry in entries if not isinstance(entry, str)]
sources: dict[object, SimpleNamespace] = {}
if pairs and name in self._get_specs():
sources = dict(zip(pairs, getattr(namespace, name), strict=True))
elif pairs:
bound = self._get_bound(namespace)
sources = {pair: bound[pair[0]] for pair in pairs}
return [
(
getattr(
self._get_member(namespace, 'target') if isinstance(entry, str) else sources[entry],
self._get_state(entry),
),
SR(coefficient(namespace)) if callable(coefficient) else coefficient,
)
for entry, coefficient in entries.items()
]
def _get_state(self, entry: tuple[str, str] | str) -> str:
"""Return the name of the state of an entry.
The entry is a state name alone or the second item of a pair.
"""
return entry if isinstance(entry, str) else entry[1]
def _get_changes(self, namespace: SimpleNamespace) -> dict[Expression, float]:
"""Return the net change of every state the reaction changes.
It is the products minus the reactants.
"""
changes: dict[Expression, float] = {}
for sign, entries, name in (
(-1, self._get_reactants(), 'reactants'),
(1, self._get_products(), 'products'),
):
for state, coefficient in self._get_terms(entries, namespace, name):
changes[state] = changes.get(state, 0) + sign * coefficient
return {state: change for state, change in changes.items() if change}
def _get_product_propensity(self, namespace: SimpleNamespace, constant: Expression) -> Expression:
"""Return the product propensity of a rate constant.
It is the rate constant times the product of the reactant and modifier amounts, each raised to its coefficient.
"""
propensity = SR(constant)
for entries, name in ((self._get_reactants(), 'reactants'), (self._get_modifiers(), 'modifiers')):
for state, coefficient in self._get_terms(entries, namespace, name):
propensity *= state**coefficient
return propensity
def _get_rate(self, namespace: SimpleNamespace) -> Expression:
"""Return the propensity of the reaction.
It is given by the user's function or by the product propensity at the rate constant `k`.
"""
if self.propensity is not None:
return SR(self.propensity(namespace))
return self._get_product_propensity(namespace, self._get_parameter_symbol('k', namespace))
def _get_langevin_laws(self, propensity: Expression, changes: dict[Expression, float]) -> list[BaseLaw]:
"""Return the drift of the reaction and the noise of its Wiener process.
The noise of its one Wiener process acts on every state it changes.
"""
amplitude = sqrt(where(propensity > 0, propensity, 0))
rates: list[BaseLaw] = [RateLaw(state, change * propensity) for state, change in changes.items()]
noises: list[BaseLaw] = [
NoiseLaw(state, change * amplitude, process=self.label) for state, change in changes.items()
]
return rates + noises
def _is_entry(self, entry: object) -> bool:
"""Check whether an entry is a pair of a path and a state name, or a state name.
The state name is that of a given target.
"""
if isinstance(entry, str):
return self.target is not None and entry.isidentifier()
return (
isinstance(entry, tuple)
and len(entry) == ENTRY_SIZE
and all(isinstance(item, str) for item in entry)
and entry[1].isidentifier()
)
def _is_coefficient(self, coefficient: object) -> bool:
"""Check whether a coefficient is a positive number or a function."""
return callable(coefficient) or (isinstance(coefficient, int | float) and coefficient > 0)
def _check_entries(self, name: str, entries: Stoichiometry | None) -> None:
"""Raise an error for entries that are not pairs or target states, or coefficients.
The states are state names of the target.
"""
if entries is None:
return
valid = isinstance(entries, Mapping) and all(
self._is_entry(entry) and self._is_coefficient(coefficient) for entry, coefficient in entries.items()
)
if not valid:
error_msg = (
f'The {name} of reaction {self.label!r} are {entries!r}. Map pairs of a path and a state name, or '
'state names of the target, to positive numbers or functions, such as {("S", "n"): 1} or {"n": 1}.'
)
raise ValidationError(error_msg)
def _check_schedule(self) -> None:
"""Raise an error for an unknown schedule, or a bad reaction with one.
A bad reaction with a schedule has no target, has pairs, or is of Langevin mode.
"""
if self.schedule is None:
return
self._check_variant('schedule', self.schedule, ScheduleKind)
if self.target is None:
error_msg = (
f'Reaction {self.label!r} has the schedule {self.schedule!r} but no target. Give the agent group as '
'`target`.'
)
raise ValidationError(error_msg)
mode = self._get_mode()
if mode not in AGENT_MODES:
error_msg = (
f'Reaction {self.label!r} has the schedule {self.schedule!r} and the mode {mode!r}. Use '
f'{" or ".join(AGENT_MODES)}.'
)
raise ValidationError(error_msg)
entries = [*(self._get_reactants() or {}), *(self._get_products() or {}), *(self._get_modifiers() or {})]
if not all(isinstance(entry, str) for entry in entries):
error_msg = (
f'Reaction {self.label!r} has a schedule, so its species are states of every member. Name them by '
'state names alone, such as {"n": 1}.'
)
raise ValidationError(error_msg)
def _check_jump(self) -> None:
"""Raise an error for an unknown mode or schedule, no entries, or bad entries.
Raises:
ValidationError:
The mode or the schedule is unknown, the reaction has neither reactants nor products, an entry is
neither a pair of a path and a state name nor a state name of a given target, a coefficient is neither a
positive number nor a function, or a reaction with a schedule has no target, has an entry that is a
pair, or has the mode `'langevin'`.
"""
mode = self._get_mode()
if mode not in MODES:
error_msg = f'Reaction {self.label!r} has the mode {mode!r}. Use one of {", ".join(MODES)}.'
raise ValidationError(error_msg)
reactants, products = self._get_reactants(), self._get_products()
if not reactants and not products:
error_msg = f'Reaction {self.label!r} has neither reactants nor products. Give at least one of them.'
raise ValidationError(error_msg)
for name, entries in (('reactants', reactants), ('products', products), ('modifiers', self._get_modifiers())):
self._check_entries(name, entries)
self._check_schedule()
def _get_number(self, value: object, agent: AgentViewProtocol, system: SystemViewProtocol) -> float:
"""Return a number, or the value of a function of an agent and the system.
The value is returned as a number.
"""
found = value(agent, system) if callable(value) else value
if not isinstance(found, SupportsFloat):
error_msg = f'A function of reaction {self.label!r} returns {found!r} for an agent. Return a number.'
raise ValidationError(error_msg)
return float(found)
def _get_agent_changes(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> dict[str, float]:
"""Return the net change of every state of an agent the reaction changes.
It is the products minus the reactants.
"""
changes: dict[str, float] = {}
for sign, entries in ((-1, self._get_reactants()), (1, self._get_products())):
for entry, coefficient in (entries or {}).items():
state = self._get_state(entry)
changes[state] = changes.get(state, 0.0) + sign * self._get_number(coefficient, agent, system)
return changes
def _get_agent_propensity(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> float:
"""Return the propensity of an agent.
It is given by the user's function or by the product propensity at the rate constant `k`.
"""
if self.propensity is not None:
return self._get_number(self.propensity, agent, system)
propensity = self._get_parameter_value('k', system)
for entries in (self._get_reactants(), self._get_modifiers()):
for entry, coefficient in (entries or {}).items():
value = float(getattr(agent, self._get_state(entry)))
propensity *= value ** self._get_number(coefficient, agent, system)
return propensity
def _get_agent_scale(self, propensity: float, system: SystemViewProtocol) -> float:
"""Return the multiple of its changes an agent adds in a step.
It is its propensity or whether an event fires.
"""
if self._get_mode() == 'rate':
return propensity
return float(system.rng.random() < 1.0 - math.exp(-max(propensity, 0.0)))
def _get_agent_step(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> dict[str, float]:
"""Return the change of every state of an agent in the step.
It is its changes times its propensity or its event.
"""
changes, propensity = self._get_agent_changes(agent, system), self._get_agent_propensity(agent, system)
scale = self._get_agent_scale(propensity, system)
return {state: change * scale for state, change in changes.items()}
def _apply_agent_step(self, agent: AgentViewProtocol, changes: dict[str, float]) -> None:
"""Add their changes to the states of an agent."""
for state, change in changes.items():
setattr(agent, state, float(getattr(agent, state)) + change)
def _react_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
"""React in one agent on its own states, in its own activation."""
if agent.alive:
self._apply_agent_step(agent, self._get_agent_step(agent, system))
def react(self, system: SystemViewProtocol) -> None:
"""React in every agent of the target on its own states, by the schedule.
Without a schedule every agent reacts at once.
Args:
system:
The system view of the interaction.
"""
self._update_agents(system, self.schedule or 'synchronous', self._get_agent_step, self._apply_agent_step)
def _check_arguments(self) -> None:
"""Raise an error for an argument the interaction cannot take.
Raises:
ValidationError:
The mode or the schedule is unknown, the reaction has neither reactants nor products, or an entry or a
coefficient is not valid.
"""
super()._check_arguments()
self._check_jump()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set its laws or its agent rule for a binding.
Args:
context:
The namespace of the target, the reactants, the products, and the modifiers.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = self._get_reaction_laws(context)
def _get_reaction_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the laws of the reaction in its mode, or the rule of its schedule.
The rule of a schedule changes one member, or every member of the target in the order of the schedule.
"""
if self.schedule == 'member':
return [UpdateLaw(self._get_member(namespace, 'target'), self._react_member, phase=self.phase)]
if self.schedule is not None:
return [UpdateLaw(namespace, self.react, phase=self.phase)]
propensity = self._get_rate(namespace)
changes = self._get_changes(namespace)
mode = self._get_mode()
if mode == 'jump':
return [JumpLaw(propensity, changes)]
if mode == 'langevin':
return self._get_langevin_laws(propensity, changes)
return [RateLaw(state, change * propensity) for state, change in changes.items()]
class EquationInteraction(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.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the element whose state the equation changes.
state:
The name of the state, with a prime for every order of the derivative the equation gives.
equation:
The rate or the next value as a function of the namespace, or `None` for a noise alone.
noise:
The noise amplitude as a function of the namespace or a number, or `None` for none.
convention:
The stochastic calculus of the noise, `'ito'` or `'stratonovich'`.
time:
The time of the equation, `'continuous'` for a rate or `'discrete'` for a next value.
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
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (RateLaw, NoiseLaw, UpdateLaw)
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
def _get_tags(self) -> Tags:
"""Return the tags of the update, or of the rate and the noise the equation has."""
if self.time == 'discrete':
return self._get_variant_tags((UpdateLaw,))
classes = (RateLaw,) if self.equation is not None else ()
return self._get_variant_tags((*classes, NoiseLaw) if self.noise is not None else classes)
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rate and the noise, or the next value, of the state.
Args:
context:
The namespace of the element.
"""
super()._prepare(context)
name = self.state.rstrip("'")
order = len(self.state) - len(name)
state = getattr(context.target, name)
laws: list[BaseLaw] = []
if self.time == 'discrete' and self.equation is not None:
laws.append(UpdateLaw(state, self.equation(context)))
elif self.equation is not None:
laws.append(RateLaw(state.diff(context.t, max(order, 1)), self.equation(context)))
if self.time != 'discrete' and self.noise is not None:
noise = self.noise(context) if callable(self.noise) else self.noise
laws.append(NoiseLaw(state.diff(context.t, max(order, 1)), noise, convention=self.convention))
self.laws_: list[BaseLaw] = laws