Skip to content

Reactions

Define the reactions and reaction networks that several fields share.

A reaction moves units between states, and a reaction network builds one element per species and one reaction per row of its table.

ReactionInteraction(label, *, target=None, reactants=None, products=None, k=1.0, propensity=None, modifiers=None, mode='rate', phase=None, schedule=None)

Bases: 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.

Parameters:

Name Type Description Default
label str

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

required
target Role | None

The path of the element, group, or field whose states the species named by a state alone are, or None.

None
reactants Stoichiometry | None

The coefficients of the reactants, or None for a source.

None
products Stoichiometry | None

The coefficients of the products, or None for a sink.

None
k Annotated[float, closed_open(0, oo)]

The rate constant.

1.0
propensity Callable[..., object] | None

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.

None
modifiers Stoichiometry | None

The coefficients of the modifiers, whose states the propensity reads but the reaction does not change, or None.

None
mode str

The form of the laws, 'rate', 'jump', or 'langevin'.

'rate'
phase str | None

The phase of the step the rule of a schedule runs in, or None for the default phase.

None
schedule str | None

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.

None

Raises:

Type Description
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]
Source code in src/skcomplex/systems/general/reactions/_reaction.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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

react(system)

React in every agent of the target on its own states, by the schedule.

Without a schedule every agent reacts at once.

Parameters:

Name Type Description Default
system SystemViewProtocol

The system view of the interaction.

required
Source code in src/skcomplex/systems/general/reactions/_reaction.py
460
461
462
463
464
465
466
467
468
469
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)

ReactionNetworkSystem(species=None, reactions=None, *, mode='rate', label='system', solver='auto', backend='auto')

Bases: BaseSystem

A system of amounts and the reactions between them, written as a table.

Every species is a NonnegativeElement named after it, whose state x holds its amount. Every reaction is a ReactionInteraction with a coefficient for each reactant and product and a rate constant k. Its propensity is k times the product of the reactant amounts, each raised to its coefficient. So S + I -> 2 I at the rate constant beta has the reactants {'S': 1, 'I': 1}, the products {'I': 2}, and the propensity beta S I. A species that is both a reactant and a product with one coefficient, such as a catalyst, enters the propensity and does not change.

In the mode 'rate' the reactions are rate equations, in the mode 'jump' the random events of a Markov chain in continuous time, run by the algorithm of Gillespie, and in the mode 'langevin' the chemical Langevin equations. A subclass takes the parameters of its model under its own names and gives its species, reactions, and mode from the hooks _get_species, _get_reactions, and _get_mode, or its reactions as interactions from _get_interactions.

Unlike System, which takes any components, it builds NonnegativeElement and ReactionInteraction components from a table of reactions. Choose it when a model is a list of reactions with rate constants.

It appears in many fields. Epidemics of susceptible, infected, and recovered people, enzyme kinetics of Michaelis and Menten, and predator and prey cycles of Lotka and Volterra are reaction networks.

Attributes:

Name Type Description
system_ BaseSystem

The System of the species and the reactions built from the parameters at the last prepare.

Examples:

The reversible isomerization A <-> B, whose amounts relax to k_back / (k_forth + k_back) of the total:

>>> from skcomplex.systems.general.reactions import ReactionNetworkSystem
>>> isomerization = ReactionNetworkSystem(
...     species={'A': 10.0, 'B': 0.0},
...     reactions={'forth': ({'A': 1}, {'B': 1}, 0.3), 'back': ({'B': 1}, {'A': 1}, 0.1)},
... )
>>> [element.label for element in isomerization.prepare().system_.elements]
['A', 'B']
>>> trajectory = isomerization.prepare().simulate(until=50.0, dt=1.0)
>>> round(float(trajectory.get_values('A.x')[-1]), 3)
2.5

The same reactions as jumps, whose tags are those of a stochastic system:

>>> tags = isomerization.set_params(mode='jump').get_tags()
>>> sorted(tags.laws), tags.randomness
(['jump'], 'stochastic')

Parameters:

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

The initial amount of every species, by name, or None for no species.

None
reactions ReactionTable | None

The reactants, the products, and the rate constant of every reaction, by label, the reactants and the products as coefficients by species name, empty for a source or a sink, or None for no reactions.

None
mode str

The form of the laws of the reactions, 'rate', 'jump', or 'langevin'.

'rate'
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/reactions/_reaction_network.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def __init__(
    self,
    species: Mapping[str, float] | None = None,
    reactions: ReactionTable | None = None,
    *,
    mode: str = 'rate',
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    """Store the species, the reactions, the mode, the label, and the settings.

    Args:
        species:
            The initial amount of every species, by name, or `None` for no species.

        reactions:
            The reactants, the products, and the rate constant of every reaction, by label, the reactants and the
            products as coefficients by species name, empty for a source or a sink, or `None` for no reactions.

        mode:
            The form of the laws of the reactions, `'rate'`, `'jump'`, or `'langevin'`.

        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.species = species
    self.reactions = reactions
    self.mode = mode