Skip to content

COMETS: dynamic flux balance on a lattice with diffusion

An expanding colony of the E. coli core system on a lattice.

  • Class: CometsSystem
  • Import: from skcomplex.systems.biology.ecology import CometsSystem
  • Field: biology/ecology
  • Topics: COMETS, dynamic flux balance, lattice, diffusion, linear program, metabolism
  • References:
    • Raman 2021
    • Harcombe et al. 2014

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.ecology import CometsSystem

trajectory = CometsSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
shape (50, 50)
box 0.02
inoculum 3e-07
glucose 5.0
plate_glucose 0.0088
biomass_diffusion 3e-10
glucose_diffusion 5e-06
vmax 10.0
km 0.01
interval 0.1
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 equation, rate
Randomness unknown
Domains real
Structure fixed

Class

The source of the class shows how it builds its components from its model parameters.

class CometsSystem(BaseSystem):
    """An expanding colony of the E. coli core system on a lattice.

    It needs the extra `metabolism`.

    Run with `IMEXEulerSolver`, every step is a growth step and then a diffusion step, the two steps that COMETS
    alternates (Raman 2021, Section 11.1.3.4). The growth step solves the program of every site that holds biomass and
    applies the update rules of Harcombe et al. (2014). The diffusion step solves one implicit Euler system, where
    Harcombe et al. use an alternating direction implicit scheme. Biomass and glucose both diffuse, as in Harcombe et
    al., while the short description of Raman names metabolites only.

    The states are gDW per L and mM of the medium under a box. A site whose program has no solution has zero fluxes,
    which happens when its glucose cannot pay for the maintenance flux of the network.

    Harcombe et al. in what follows is the main text of Harcombe et al. (2014), and the source of each default is named
    under its argument. The time step of 0.1 h of the registered run is from its In silico experiments. The length of
    the registered run keeps it within the budget of the gallery and has no source.

    These choices have no source in that text. The periodic edges are those of `LatticeSpace`, since the text does not
    state the outer boundary. The volume under a box is the amount of glucose under it over the concentration of the
    medium, since the text defers the volume to its supplement, which was not read. The molar mass of glucose is 180.16
    g/mol.

    The network is the E. coli core system, where Harcombe et al. use iJO1366. The death rate of 1% per step, the
    largest colony height of 200 um, and the oxygen of 0.25 mmol/cm^2 of Harcombe et al. are left out, so the biomass of
    a box has no upper limit and oxygen is limited only by the network.

    Args:
        shape:
            The number of boxes along each side, by default from Harcombe et al., Colony expansion comparisons.

        box:
            The side of a box in cm, by default from Harcombe et al., Colony expansion comparisons.

        inoculum:
            The initial biomass of the central box in g, by default from Harcombe et al., Colony expansion comparisons.

        glucose:
            The glucose of the medium in g/L, by default from Harcombe et al., In silico experiments.

        plate_glucose:
            The glucose of the medium per area of the plate in mmol/cm^2, by default from Harcombe et al., In silico
            experiments.

        biomass_diffusion:
            The diffusion coefficient of the biomass in cm^2/s, by default the value for colonies from Harcombe et al.,
            Table 1.

        glucose_diffusion:
            The diffusion coefficient of the glucose in cm^2/s, by default from Harcombe et al., Table 1.

        vmax:
            The largest glucose uptake in mmol/g/h, by default from Harcombe et al., Table 1.

        km:
            The half-saturation concentration of glucose in mM, by default from Harcombe et al., Table 1.

        interval:
            The time in h over which the glucose of a site must last, by default the time step, the bound of Raman
            (2021, Section 9.6).

        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one the system chooses.

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

    Raises:
        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.systems.biology.ecology import CometsSystem
        >>> [element.label for element in CometsSystem(shape=(2, 2)).prepare().system_.elements]
        ['cells', 'biomass', 'glucose']
    """

    field = 'biology/ecology'
    topics = ('COMETS', 'dynamic flux balance', 'lattice', 'diffusion', 'linear program', 'metabolism')
    references = ('Raman 2021', 'Harcombe et al. 2014')
    until = 14.0
    dt = STEP

    def __init__(
        self,
        shape: tuple[int, int] = (50, 50),
        *,
        box: float = 0.02,
        inoculum: float = 3e-7,
        glucose: float = 5.0,
        plate_glucose: float = 0.0088,
        biomass_diffusion: float = 3e-10,
        glucose_diffusion: float = 5e-6,
        vmax: float = 10.0,
        km: float = 0.01,
        interval: float = STEP,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.shape = shape
        self.box = box
        self.inoculum = inoculum
        self.glucose = glucose
        self.plate_glucose = plate_glucose
        self.biomass_diffusion = biomass_diffusion
        self.glucose_diffusion = glucose_diffusion
        self.vmax = vmax
        self.km = km
        self.interval = interval

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of an expanding colony of the E. coli core system on a lattice.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        source = load_network('textbook', 'cells', needed_by='comets')
        plain = {name: replace(spec, rule='') for name, spec in source.reactions.items()}
        network = source.set_params(
            reactions=plain,
            name='ColonyCell',
            infeasible='zero',
            biomass='biomass',
            threshold=0.0,
        )
        concentration = self.glucose / GLUCOSE_MOLAR_MASS * MMOL_PER_MOL
        volume = self.plate_glucose * self.box**2 / concentration
        initial = np.zeros(self.shape)
        initial[self.shape[0] // 2, self.shape[1] // 2] = self.inoculum / volume
        space = LatticeSpace(self.shape, spacing=self.box)
        self.system_ = System(
            self.label,
            elements=[
                ColonyCellElement('cells', values=network.get_values(), space=space),
                BiomassElement('biomass', x=initial, space=space),
                SubstrateElement('glucose', c=np.full(self.shape, concentration), space=space),
            ],
            interactions=[
                network,
                ExchangeInteraction(
                    'uptake',
                    cell='cells',
                    biomass='biomass',
                    substrate='glucose',
                    reaction=GLUCOSE_EXCHANGE,
                    vmax=self.vmax,
                    km=self.km,
                    interval=self.interval,
                ),
                GrowthInteraction('growth', cell='cells', biomass='biomass', reaction=GROWTH),
                Interaction(
                    'biomass_spread',
                    roles={'target': 'biomass'},
                    laws=lambda s: [
                        RateLaw(s.target.x, self.biomass_diffusion * SECONDS_PER_HOUR * laplacian(s.target.x)),
                    ],
                ),
                Interaction(
                    'glucose_spread',
                    roles={'target': 'glucose'},
                    laws=lambda s: [
                        RateLaw(s.target.c, self.glucose_diffusion * SECONDS_PER_HOUR * laplacian(s.target.c)),
                    ],
                ),
            ],
            space=space,
            solver=IMEXEulerSolver(dt=STEP),
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

Interactions:

  • FluxBalanceInteraction, from Interaction
  • ExchangeInteraction, from Interaction
  • GrowthInteraction, from Interaction
  • Interaction
class ColonyCellElement(Element):
    """Cell of a colony, whose values hold the fluxes of its network, drawn as an image of its growth flux.

    Examples:
        >>> from skcomplex.systems.biology.ecology import ColonyCellElement
        >>> ColonyCellElement('cells', values={'v_grow': 0.0}).values
        {'v_grow': 0.0}
    """

    visual = VisualSpec('image', {'states': [FluxBalanceInteraction.get_flux_name(GROWTH)]})

class BiomassElement(Element):
    """Biomass of a culture, in gDW per L.

    Args:
        label:
            The label of the element.

        x:
            The biomass in gDW per L.

        values:
            Further values by name.

        size:
            The number of members, or `None` for one.

        space:
            The space of the members, such as the plate of a culture with one biomass per cell, or `None`.

    Examples:
        >>> from skcomplex.systems.biology.common.metabolism import BiomassElement
        >>> BiomassElement('culture', x=0.01).x
        0.01
    """

    def __init__(
        self,
        label: str,
        *,
        x: float | npt.ArrayLike = 0.01,
        values: Mapping[str, object] | None = None,
        size: int | None = None,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, values=values, size=size, space=space)
        self.x = x

class SubstrateElement(Element):
    """Concentration of a metabolite of a medium, in mM.

    Args:
        label:
            The label of the element.

        c:
            The concentration in mM.

        values:
            Further values by name.

        size:
            The number of members, or `None` for one.

        space:
            The space of the members, such as the plate of a culture with one concentration per cell, or `None`.

    Examples:
        >>> from skcomplex.systems.biology.common.metabolism import SubstrateElement
        >>> SubstrateElement('glucose', c=10.0).c
        10.0
    """

    def __init__(
        self,
        label: str,
        *,
        c: float | npt.ArrayLike = 10.0,
        values: Mapping[str, object] | None = None,
        size: int | None = None,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, values=values, size=size, space=space)
        self.c = c

class FluxBalanceInteraction(Interaction):
    """Flux balance of a metabolic network, which sets its fluxes to the best ones its balances and bounds allow.

    A network is a set of reactions, each with the coefficients of its metabolites, its bounds, and the rule of the
    genes that make its enzymes. The interaction sets the flux `v_<reaction>` of its cell, one per reaction, to the
    optimum of a linear program: every metabolite balances, `sum_r S_mr v_r = 0`, every flux stays between the values
    `lower_<reaction>` and `upper_<reaction>` of the cell, and the weighted sum of the fluxes of `objective` is
    greatest (Raman 2021, Eq. 8.9). A reaction whose rule is false, read from the switches `g_<gene>` of the cell,
    carries no flux. The program is solved at every time of a run, so the network also drives a culture that changes
    in time, and `get_values` gives the values the cell starts with.

    Args:
        label:
            The label of the interaction.

        cell:
            The path of the cell whose values hold the fluxes, the bounds, and the switches.

        reactions:
            The reactions by name.

        objective:
            The coefficient of every reaction in the objective, or nothing for a network whose fluxes another objective
            chooses, such as the growth of a community.

        parsimonious:
            Whether to minimise the total absolute flux after the objective.

        infeasible:
            What a run does when the balances and bounds cannot all hold: `'raise'`, `'zero'` to set the fluxes to
            zero, or `'hold'` to keep their last values.

        name:
            The name of the network, or `None` for none.

        biomass:
            The path of the biomass that `threshold` reads, or `None` for none.

        threshold:
            The biomass above which the program is solved, or `None` for always. The fluxes are zero elsewhere, as at
            the empty boxes of a plate.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.metabolism import FluxBalanceInteraction, ReactionSpec
        >>> reactions = {'uptake': ReactionSpec({'A': 1.0}, upper=4.0), 'use': ReactionSpec({'A': -1.0})}
        >>> fba = FluxBalanceInteraction('fba', cell='cell', reactions=reactions, objective={'use': 1.0})
        >>> cell = Element('cell', values=fba.get_values())
        >>> trajectory = System(elements=[cell], interactions=[fba]).prepare().simulate(until=0.0)
        >>> float(trajectory.get_values('cell.v_use')[0])
        4.0
    """

    def __init__(
        self,
        label: str = 'fba',
        *,
        cell: Role = 'cell',
        reactions: Mapping[str, ReactionSpec] = NO_REACTIONS,
        objective: Mapping[str, float] = NO_OBJECTIVE,
        parsimonious: bool = False,
        infeasible: str = 'raise',
        name: str | None = None,
        biomass: Role | None = None,
        threshold: float | None = None,
    ) -> None:
        super().__init__(label)
        self.cell = cell
        self.reactions = reactions
        self.objective = objective
        self.parsimonious = parsimonious
        self.infeasible = infeasible
        self.name = name
        self.biomass = biomass
        self.threshold = threshold

    @staticmethod
    @functools.cache
    def _get_rule_genes(rule: str) -> tuple[str, ...]:
        """Return the gene names in a rule, read once per rule.

        Compiling reads the rules of a network often.
        """
        if not rule.strip():
            return ()
        return tuple(node.id for node in ast.walk(ast.parse(rule, mode='eval')) if isinstance(node, ast.Name))

    @staticmethod
    def _get_identifier(name: str) -> str:
        """Return a name as a part of an identifier."""
        return re.sub(r'\W', '_', name)

    @classmethod
    def get_flux_name(cls, reaction: str) -> str:
        """Return the name of the value of the cell that holds the flux of a reaction.

        Args:
            reaction:
                The name of the reaction.

        Returns:
            name:
                The name of the value, such as `v_PGI` for the reaction `PGI`.
        """
        return f'v_{cls._get_identifier(reaction)}'

    @classmethod
    def get_gene_name(cls, gene: str) -> str:
        """Return the name of the value of the cell that holds the switch of a gene.

        Args:
            gene:
                The name of the gene.

        Returns:
            name:
                The name of the value, such as `g_b4025` for the gene `b4025`.
        """
        return f'g_{cls._get_identifier(gene)}'

    def get_genes_of(self) -> tuple[str, ...]:
        """Return the names of the genes that the rules of the reactions read.

        Returns:
            genes:
                The names, in the order the rules name them.
        """
        names = [name for reaction in self.reactions.values() for name in self._get_rule_genes(reaction.rule)]
        return tuple(dict.fromkeys(names))

    def get_values(self) -> dict[str, float]:
        """Return the values the cell of the network starts with.

        They are, for every reaction in order, its flux at zero and its bounds, and then the switch of every gene, on
        at 1.

        Returns:
            values:
                The values by name, such as `{'v_r': 0.0, 'lower_r': 0.0, 'upper_r': 1000.0, 'g_g': 1.0}`.

        Examples:
            >>> from skcomplex.systems.biology.common.metabolism import FluxBalanceInteraction, ReactionSpec
            >>> reactions = {'r': ReactionSpec({'A': -1.0}, upper=4.0, rule='g')}
            >>> FluxBalanceInteraction('fba', reactions=reactions).get_values()
            {'v_r': 0.0, 'lower_r': 0.0, 'upper_r': 4.0, 'g_g': 1.0}
        """
        values = {}
        for reaction, spec in self.reactions.items():
            identifier = self._get_identifier(reaction)
            values[f'v_{identifier}'] = 0.0
            values[f'lower_{identifier}'] = float(spec.lower)
            values[f'upper_{identifier}'] = float(spec.upper)
        return values | dict.fromkeys(map(self.get_gene_name, self.get_genes_of()), 1.0)

    def _get_gate(self, cell: SimpleNamespace, rule: str) -> Expression | int:
        """Return the condition of a rule on the switches of its genes.

        A reaction without genes has the condition 1.
        """
        if not rule.strip():
            return 1
        return both(self._get_condition(cell, ast.parse(rule, mode='eval').body))

    def _get_condition(self, cell: SimpleNamespace, node: ast.expr) -> Expression:
        """Return the condition of a node of a rule."""
        if isinstance(node, ast.BoolOp):
            combine = both if isinstance(node.op, ast.And) else either
            return combine(*(self._get_condition(cell, item) for item in node.values))
        if isinstance(node, ast.Name):
            return getattr(cell, self.get_gene_name(node.id)) > SWITCH_THRESHOLD
        error_msg = f'A gene rule of {self.label} holds {ast.dump(node)}. Use gene names, `and`, `or`, and parentheses.'
        raise ValidationError(error_msg)

    def _get_balances(self, cell: SimpleNamespace) -> list[ConstraintLaw]:
        """Return the balance of every metabolite."""
        terms: dict[str, list[Expression]] = {}
        for reaction, spec in self.reactions.items():
            flux = getattr(cell, self.get_flux_name(reaction))
            for metabolite, coefficient in spec.coefficients.items():
                terms.setdefault(metabolite, []).append(float(coefficient) * flux)
        return [ConstraintLaw(sum(items[1:], items[0]) == 0) for items in terms.values()]

    def _get_bounds(self, cell: SimpleNamespace) -> list[ConstraintLaw]:
        """Return the lower and upper bound of every reaction, gated by its rule."""
        bounds = []
        for reaction, spec in self.reactions.items():
            flux = getattr(cell, self.get_flux_name(reaction))
            gate = self._get_gate(cell, spec.rule)
            identifier = self._get_identifier(reaction)
            bounds.append(ConstraintLaw(flux >= getattr(cell, f'lower_{identifier}') * gate))
            bounds.append(ConstraintLaw(flux <= getattr(cell, f'upper_{identifier}') * gate))
        return bounds

    def _get_objective(self, cell: SimpleNamespace, biomass: SimpleNamespace | None) -> ObjectiveLaw:
        """Return the objective of the network over its fluxes.

        It is the greatest weighted sum of `objective`, then the smallest total absolute flux for a parsimonious
        network, or any point that the balances and bounds allow for a network without an objective. With a threshold,
        it is sought only where the biomass lies above it.
        """
        active = None if self.threshold is None or biomass is None else biomass.x > float(self.threshold)
        fluxes = [getattr(cell, self.get_flux_name(name)) for name in self.reactions]
        values = []
        if self.objective:
            terms = [float(weight) * getattr(cell, self.get_flux_name(name)) for name, weight in self.objective.items()]
            values.append(-sum(terms[1:], terms[0]))
            if self.parsimonious:
                absolutes = [abs(flux) for flux in fluxes]
                values.append(sum(absolutes[1:], absolutes[0]))
        return ObjectiveLaw(values, fluxes, active=active, infeasible=self.infeasible)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the objective of the network with its balances and bounds.

        Args:
            context:
                The namespace of the cell and the biomass.
        """
        super()._prepare(context)
        laws: list[BaseLaw] = [*self._get_balances(context.cell), *self._get_bounds(context.cell)]
        self.laws_ = [*laws, self._get_objective(context.cell, None if self.biomass is None else context.biomass)]

class ExchangeInteraction(Interaction):
    """Exchange of a metabolite between a metabolic network and its medium.

    The exchange is bounded by Michaelis-Menten uptake.

    The law bounds the uptake, the negative flux of the exchange reaction, by `vmax c / (km + c)` and, with an interval,
    by what the medium holds per biomass over the interval (Raman 2021, Section 9.6). The medium changes at the rate
    `dc/dt = v x`, and a depleted medium loses nothing more.

    Args:
        label:
            The label of the interaction.

        cell:
            The path of the cell whose values hold the fluxes of the network.

        biomass:
            The path of the biomass.

        substrate:
            The path of the metabolite.

        reaction:
            The name of the exchange reaction.

        vmax:
            The largest uptake.

        km:
            The half-saturation concentration.

        interval:
            The time over which the medium must last, or `None` for no such bound.

    Examples:
        >>> from skcomplex.systems.biology.common.metabolism import ExchangeInteraction
        >>> ExchangeInteraction('uptake', reaction='EX_glc__D_e').vmax
        10.0
    """

    def __init__(
        self,
        label: str,
        *,
        cell: Role = 'cell',
        biomass: Role = 'biomass',
        substrate: Role = 'substrate',
        reaction: str = 'EX_glc__D_e',
        vmax: Annotated[float, POSITIVE] = 10.0,
        km: Annotated[float, POSITIVE] = 0.015,
        interval: float | None = None,
    ) -> None:
        super().__init__(label)
        self.cell = cell
        self.biomass = biomass
        self.substrate = substrate
        self.reaction = reaction
        self.vmax = vmax
        self.km = km
        self.interval = interval

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the bounds of the uptake and the rate of the medium.

        Args:
            context:
                The namespace of the roles and parameters.
        """
        super()._prepare(context)
        flux = getattr(context.cell, FluxBalanceInteraction.get_flux_name(self.reaction))
        amount, biomass = context.substrate.c, context.biomass.x
        held = where(amount > 0, amount, 0)
        laws: list[BaseLaw] = [ConstraintLaw(flux >= -context.vmax * held / (context.km + held), target=flux)]
        if self.interval is not None:
            laws.append(ConstraintLaw(flux >= -held / (biomass * float(self.interval)), target=flux))
        laws.append(RateLaw(amount, flux * biomass * where(either(amount > 0, flux > 0), 1, 0)))
        self.laws_ = laws

class GrowthInteraction(Interaction):
    """Growth of biomass at the rate a reaction of a metabolic network gives.

    The biomass follows `dx/dt = v x`.

    Args:
        label:
            The label of the interaction.

        cell:
            The path of the cell whose values hold the fluxes of the network.

        biomass:
            The path of the biomass.

        reaction:
            The name of the reaction of growth.

    Examples:
        >>> from skcomplex.systems.biology.common.metabolism import GrowthInteraction
        >>> GrowthInteraction('growth', cell='cell', biomass='culture', reaction='grow').reaction
        'grow'
    """

    def __init__(
        self,
        label: str,
        *,
        cell: Role = 'cell',
        biomass: Role = 'biomass',
        reaction: str = 'Biomass_Ecoli_core',
    ) -> None:
        super().__init__(label)
        self.cell = cell
        self.biomass = biomass
        self.reaction = reaction

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate of the biomass.

        Args:
            context:
                The namespace of the cell and the biomass.
        """
        super()._prepare(context)
        flux = getattr(context.cell, FluxBalanceInteraction.get_flux_name(self.reaction))
        self.laws_: list[BaseLaw] = [RateLaw(context.biomass.x, flux * context.biomass.x)]

class Interaction(BaseInteraction):
    """An interaction whose laws run once for the elements its roles bind.

    It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
    `Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
    role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
    edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
    random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
    members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
    parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
    populations, a reaction between two chemicals, and an infection along the contacts of a network.

    Read more in the user guide, under Interactions.

    Args:
        label:
            The name of the interaction, unique among the components of its system, such as `'predation'`.

        roles:
            The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
            without a class, or `None`.

        laws:
            The function of the namespace that returns the laws of a rule written without a class, such as
            `lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
            `None`.

        among:
            The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
            their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.

        along:
            `True` for the edges of the network the group lives on, the name of a layer of a network with several, such
            as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
            `RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
            member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
            element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.

        within:
            A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
            closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
            walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
            give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
            force `-dV/dx` on its position `x`.

    See Also:
        BaseInteraction: The base of every interaction.
        RandomPartition: Groups the members of a group at random at every step.
        TrainingInteraction: Trains the parameters of a nested system.

    Examples:
        >>> from skcomplex.core.components.interactions import Interaction
        >>> from skcomplex.core.components.laws import RateLaw
        >>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
        >>> birth.roles
        {'target': 'fish'}
    """

    def __init__(
        self,
        label: str,
        *,
        roles: Mapping[str, object] | None = None,
        laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
        among: str | None = None,
        along: bool | str | tuple[str, int] | RandomPartition | None = None,
        within: RadiusNeighborhood | None = None,
    ) -> None:
        super().__init__(label)
        self.roles = roles
        self.laws = laws
        self.among = among
        self.along = along
        self.within = within

    def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
        """Return the numeric arguments as parameters, and `roles` and `among` as roles.

        With `within`, `among` binds both members of a pair, `first` and `second`.
        """
        declared = dict(super()._get_declared())
        for name, binding in (self.roles or {}).items():
            declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
        if self.among is not None and self.within is not None:
            for name in PAIR_ROLES:
                declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
        elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
            declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
        return declared

    @classmethod
    def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
        """Return the arguments that name the states a role reads.

        The mapping `roles` of bindings names none.
        """
        return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')

    def _get_binding(self, role: str) -> object:
        """Return what a role binds, from `roles` or from the argument of its name.

        Args:
            role:
                The name of the role.

        Returns:
            binding:
                The label, labels, or entries the role binds, or `None` when it binds nothing.
        """
        if self.roles is not None and role in self.roles:
            return self.roles[role]
        if self.among is not None and self.within is not None and role in PAIR_ROLES:
            return self.among
        return super()._get_binding(role)

    def _check_arguments(self) -> None:
        """Raise an error for roles, laws, or groups the interaction cannot take.

        Raises:
            ValidationError:
                A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
                `along` names hyperedges of fewer than two members.
        """
        clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
        if clashes:
            error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
            raise ValidationError(error_msg)
        if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
            error_msg = (
                f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
                '`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, tuple) and not self._is_sized(self.along):
            error_msg = (
                f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
                "more, such as `along=('hyperedges', 3)`."
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, RandomPartition):
            self.along._check()
        grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
        if grouped and self.among is None:
            error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
            raise ValidationError(error_msg)
        super()._check_arguments()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of `laws` for a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        if self.laws is not None:
            self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)

    @staticmethod
    def _is_sized(along: tuple[object, ...]) -> bool:
        """Return whether `along` names hyperedges of a whole size of at least two."""
        if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
            return False
        size = along[1]
        return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE

    def _get_draws(self) -> bool:
        """Return whether the interaction draws, as it does along random groups."""
        return super()._get_draws() or isinstance(self.along, RandomPartition)

    def _runs_on_edges(self) -> bool:
        """Return whether the interaction runs along edges."""
        grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
        return self.along is not None and self.along is not False and not grouped

    def _runs_on_hyperedges(self) -> bool:
        """Return whether the interaction runs along the hyperedges of a network."""
        return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)

    def _get_hyperedge_size(self) -> int | None:
        """Return the size `along` gives the hyperedges, or `None` for every size."""
        return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None

    def _get_within(self) -> RadiusNeighborhood | None:
        """Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
        return self.within

    def _get_layer(self) -> str | None:
        """Return the layer `along` names, or `None` for no layer."""
        if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
            return None
        return self.along

    def _get_grouping(self) -> tuple[str, int, str] | None:
        """Return the kind, size, and reduction of the groups `along` names, or `None`."""
        if isinstance(self.along, RandomPartition):
            return ('partition', self.along.size, 'sum')
        if self.along == NEIGHBORHOODS:
            return ('neighborhood', 0, 'sum')
        return None