Skip to content

Hahnfeldt system with effector cells, pharmacokinetics, resistance, and toxicity

The Hahnfeldt tumour with effector cells under bevacizumab and atezolizumab.

  • Class: AngiogenesisImmunotherapySystem
  • Import: from skcomplex.systems.biology.oncology import AngiogenesisImmunotherapySystem
  • Field: biology/oncology
  • Topics: antiangiogenic therapy, immunotherapy, combination therapy, pharmacokinetics, resistance, ode
  • References:
    • Padmanabhan, Meskin, and Al Moustafa 2021
    • Teles and Lemos 2019
    • Hahnfeldt et al. 1999

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.oncology import AngiogenesisImmunotherapySystem

trajectory = AngiogenesisImmunotherapySystem().prepare().simulate()

Parameters

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

Parameter Default
A 5000.0
Vb 625.0
E 0.1
dose_an 15.0
dose_im 20.0
a2 1.35
a3 0.1
period 21.0
doses 6
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 none
Laws rate
Randomness unknown
Domains real
Structure fixed

Class

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

class AngiogenesisImmunotherapySystem(BaseSystem):
    """The Hahnfeldt tumour with effector cells under bevacizumab and atezolizumab.

    The drugs are given every three weeks.

    Each drug alone holds the tumour or slows it, and together they shrink it. The drug amounts follow the
    two-compartment system whose bolus solution is the book's closed form, with the elimination rate `k10 = alpha beta /
    k21`. The effector cells grow as `r1 (A - c1 A^2) E`, so `1 / c1` is the volume above which the tumour suppresses
    them. The drug effects in the vasculature and effector balances are the saturating effects of the book's
    pharmacodynamics. The resistance capacity `delta_r = 0.01` and its threshold `u_theta = 5` mg per kg are a choice,
    since the book gives none. The toxicity of each drug is `exp(c / tox) - 1`, linear for a low amount and exponential
    for a high one, and the observable `toxicity` is the mean of both. Volumes are in mm³, drug amounts in mg per kg,
    and time is in days. The system has the tumour `tumour.A`, the capacity `tumour.Vb`, the effector cells `tumour.E`,
    the drug amounts `tumour.c_an` and `tumour.c_im`, and the observable `toxicity`.

    Args:
        A:
            The initial tumour volume.

        Vb:
            The initial vascular capacity.

        E:
            The initial effector cells, dimensionless.

        dose_an:
            The dose of bevacizumab, in mg per kg, 0 for immunotherapy alone.

        dose_im:
            The dose of atezolizumab, in mg per kg, 0 for antiangiogenic therapy alone.

        a2:
            The highest destruction rate of the vasculature by bevacizumab, in the book's range of 1.35 to 11.25.

        a3:
            The highest boost of effector cells by atezolizumab, in the book's range of 0.1 to 0.5.

        period:
            The time between doses.

        doses:
            The number of doses.

        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.oncology import AngiogenesisImmunotherapySystem
        >>> AngiogenesisImmunotherapySystem(dose_an=0.0).prepare().system_.elements[0].dose_an
        0.0
    """

    field = 'biology/oncology'
    topics = ('antiangiogenic therapy', 'immunotherapy', 'combination therapy', 'pharmacokinetics', 'resistance', 'ode')
    references = (BOOK, 'Teles and Lemos 2019', 'Hahnfeldt et al. 1999')
    until = 150.0
    dt = 0.25
    observables = (Observable('toxicity', _get_total_toxicity),)

    def __init__(
        self,
        A: float = 5000.0,
        Vb: float = 625.0,
        E: float = 0.1,
        *,
        dose_an: float = 15.0,
        dose_im: float = 20.0,
        a2: float = 1.35,
        a3: float = 0.1,
        period: float = 21.0,
        doses: int = 6,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.A = A
        self.Vb = Vb
        self.E = E
        self.dose_an = dose_an
        self.dose_im = dose_im
        self.a2 = a2
        self.a3 = a3
        self.period = period
        self.doses = doses

    @staticmethod
    def _get_elimination(target: SimpleNamespace, drug: str) -> Expression:
        """Return the elimination rate `k10 = alpha beta / k21` of a drug.

        The drug is eliminated from its central compartment.
        """
        alpha, beta, k21 = (getattr(target, f'{name}_{drug}') for name in ('alpha', 'beta', 'k21'))
        elimination: Expression = alpha * beta / k21
        return elimination

    @staticmethod
    def _get_drug_effect(target: SimpleNamespace, drug: str) -> Expression:
        """Return the Emax effect of a drug.

        The resistance shifts its half-effect concentration.
        """
        c, R, u50 = (getattr(target, f'{name}_{drug}') for name in ('c', 'R', 'u50'))
        effect: Expression = c**target.g / (((1 + target.delta_r * R) * u50) ** target.g + c**target.g)
        return effect

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the Hahnfeldt tumour.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        tumour = AngiogenesisImmunotherapyTumourElement(
            'tumour',
            A=self.A,
            Vb=self.Vb,
            E=self.E,
            dose_an=self.dose_an,
            dose_im=self.dose_im,
            a2=self.a2,
            a3=self.a3,
            period=self.period,
            doses=self.doses,
        )
        interactions = [
            Interaction(
                'tumour_growth',
                roles={'target': 'tumour'},
                laws=lambda s: [RateLaw(s.target.A, -s.target.v1 * s.target.A * log(s.target.A / s.target.Vb))],
            ),
            ReactionInteraction(
                'immune_kill',
                target='tumour',
                reactants={'A': 1},
                modifiers={'E': 1},
                propensity=lambda s: s.target.a1 * s.target.A * s.target.E,
            ),
            ReactionInteraction(
                'vessel_loss',
                target='tumour',
                reactants={'Vb': 1},
                propensity=lambda s: s.target.v2 * s.target.Vb,
            ),
            Interaction(
                'stimulation',
                roles={'target': 'tumour'},
                laws=lambda s: [RateLaw(s.target.Vb, s.target.xi_s * s.target.A)],
            ),
            ReactionInteraction(
                'inhibition',
                target='tumour',
                reactants={'Vb': 1},
                propensity=lambda s: s.target.xi_i * s.target.Vb * s.target.A ** (2 / 3),
            ),
            ReactionInteraction(
                'pruning',
                target='tumour',
                reactants={'Vb': 1},
                propensity=lambda s: s.target.a2 * s.target.Vb * self._get_drug_effect(s.target, 'an'),
            ),
            Interaction(
                'immune_growth',
                roles={'target': 'tumour'},
                laws=lambda s: [
                    RateLaw(s.target.E, s.target.r1 * (s.target.A - s.target.c1 * s.target.A**2) * s.target.E),
                ],
            ),
            ReactionInteraction(
                'immune_death',
                target='tumour',
                reactants={'E': 1},
                propensity=lambda s: s.target.d1 * s.target.E,
            ),
            Interaction(
                'immune_source',
                roles={'target': 'tumour'},
                laws=lambda s: [RateLaw(s.target.E, s.target.s_e)],
            ),
            Interaction(
                'immune_boost',
                roles={'target': 'tumour'},
                laws=lambda s: [RateLaw(s.target.E, s.target.a3 * s.target.E * self._get_drug_effect(s.target, 'im'))],
            ),
            DosingInteraction(
                'dosing_an',
                target='tumour',
                state='c_an',
                dose=lambda s: s.target.dose_an / tumour.width,
                period=tumour.period,
                width=tumour.width,
                count=tumour.doses,
            ),
            ReactionInteraction(
                'elimination_an',
                target='tumour',
                reactants={'c_an': 1},
                propensity=lambda s: self._get_elimination(s.target, 'an') * s.target.c_an,
            ),
            ReactionInteraction(
                'distribution_an',
                target='tumour',
                reactants={'c_an': 1},
                products={'q_an': 1},
                propensity=lambda s: s.target.k12_an * s.target.c_an,
            ),
            ReactionInteraction(
                'redistribution_an',
                target='tumour',
                reactants={'q_an': 1},
                products={'c_an': 1},
                propensity=lambda s: s.target.k21_an * s.target.q_an,
            ),
            Interaction(
                'resistance_an',
                roles={'target': 'tumour'},
                laws=lambda s: [
                    RateLaw(
                        s.target.R_an,
                        where(s.target.c_an < s.target.u_theta, s.target.u_theta - s.target.c_an, 0),
                    ),
                ],
            ),
            DosingInteraction(
                'dosing_im',
                target='tumour',
                state='c_im',
                dose=lambda s: s.target.dose_im / tumour.width,
                period=tumour.period,
                width=tumour.width,
                count=tumour.doses,
            ),
            ReactionInteraction(
                'elimination_im',
                target='tumour',
                reactants={'c_im': 1},
                propensity=lambda s: self._get_elimination(s.target, 'im') * s.target.c_im,
            ),
            ReactionInteraction(
                'distribution_im',
                target='tumour',
                reactants={'c_im': 1},
                products={'q_im': 1},
                propensity=lambda s: s.target.k12_im * s.target.c_im,
            ),
            ReactionInteraction(
                'redistribution_im',
                target='tumour',
                reactants={'q_im': 1},
                products={'c_im': 1},
                propensity=lambda s: s.target.k21_im * s.target.q_im,
            ),
            Interaction(
                'resistance_im',
                roles={'target': 'tumour'},
                laws=lambda s: [
                    RateLaw(
                        s.target.R_im,
                        where(s.target.c_im < s.target.u_theta, s.target.u_theta - s.target.c_im, 0),
                    ),
                ],
            ),
        ]
        self.system_ = System(self.label, elements=[tumour], interactions=interactions)

Components

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

Elements:

  • AngiogenesisImmunotherapyTumourElement, from Element

Interactions:

  • Interaction
  • ReactionInteraction, from Interaction, through the shared recipe ReactionInteraction
  • DosingInteraction, from Interaction
class AngiogenesisImmunotherapyTumourElement(Element):
    """Tumour, vasculature, and effector cells under bevacizumab and atezolizumab.

    The tumour develops resistance.

    The tumour `A` grows by the Hahnfeldt law toward its vascular capacity `Vb` and effector cells `E` kill it. The
    capacity is stimulated and inhibited by the tumour and destroyed by the antiangiogenic effect `UAn`, and the
    immunotherapy effect `UIm` boosts the effector cells. Each drug follows a two-compartment system with central amount
    `c` and peripheral amount `q`, in mg per kg, infused for `width` days every `period` days. Its effect is
    `c^g / ((f U50)^g + c^g)`, where `f = 1 + delta_r R` and `R` integrates `max(0, u_theta - c)`, so the drug loses
    potency while its concentration stays low. Volumes are in mm³, and time is in days.

    The element holds the states and parameters and has no laws of its own: the interactions of
    `AngiogenesisImmunotherapySystem` read its parameters.

    Args:
        label:
            The label of the tumour.

        A:
            The initial tumour volume.

        Vb:
            The initial vascular capacity.

        E:
            The initial effector cells, dimensionless.

        c_an:
            The initial central amount of the antiangiogenic drug.

        q_an:
            The initial peripheral amount of the antiangiogenic drug.

        R_an:
            The initial resistance integral of the antiangiogenic drug.

        c_im:
            The initial central amount of the immunotherapeutic drug.

        q_im:
            The initial peripheral amount of the immunotherapeutic drug.

        R_im:
            The initial resistance integral of the immunotherapeutic drug.

        v1:
            The growth constant of the tumour.

        v2:
            The spontaneous loss of vasculature.

        a1:
            The kill rate of the tumour by effector cells.

        xi_s:
            The stimulation of the vasculature by the tumour.

        xi_i:
            The inhibition of the vasculature by the tumour.

        a2:
            The highest destruction rate of the vasculature by the antiangiogenic drug.

        r1:
            The proliferation rate of effector cells.

        c1:
            The inverse of the tumour volume above which the tumour suppresses the effector cells.

        d1:
            The death rate of effector cells.

        s_e:
            The influx of effector cells.

        a3:
            The highest boost of effector cells by the immunotherapeutic drug.

        alpha_an:
            The distribution rate of the antiangiogenic drug.

        beta_an:
            The elimination rate of the antiangiogenic drug.

        k12_an:
            The rate from the central to the peripheral compartment of the antiangiogenic drug.

        k21_an:
            The rate from the peripheral to the central compartment of the antiangiogenic drug.

        u50_an:
            The amount of antiangiogenic drug of half effect before resistance.

        alpha_im:
            The distribution rate of the immunotherapeutic drug.

        beta_im:
            The elimination rate of the immunotherapeutic drug.

        k12_im:
            The rate from the central to the peripheral compartment of the immunotherapeutic drug.

        k21_im:
            The rate from the peripheral to the central compartment of the immunotherapeutic drug.

        u50_im:
            The amount of immunotherapeutic drug of half effect before resistance.

        g:
            The steepness of the drug effects.

        delta_r:
            The capacity of the tumour to resist the drugs.

        u_theta:
            The amount below which resistance develops.

        tox_an:
            The amount of antiangiogenic drug at which its toxicity turns exponential.

        tox_im:
            The amount of immunotherapeutic drug at which its toxicity turns exponential.

        dose_an:
            The dose of the antiangiogenic drug, in mg per kg.

        dose_im:
            The dose of the immunotherapeutic drug, in mg per kg.

        period:
            The time between the starts of doses.

        width:
            The duration of an infusion.

        doses:
            The number of doses.

    Examples:
        >>> from skcomplex.systems.biology.oncology import AngiogenesisImmunotherapyTumourElement
        >>> AngiogenesisImmunotherapyTumourElement('tumour').Vb
        625.0
    """

    def __init__(
        self,
        label: str,
        *,
        A: Annotated[float, RealSet.open(0, oo)] = 5000.0,
        Vb: Annotated[float, RealSet.open(0, oo)] = 625.0,
        E: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
        c_an: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        q_an: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        R_an: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        c_im: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        q_im: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        R_im: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        v1: Annotated[float, RealSet.closed_open(0, oo)] = 0.025,
        v2: Annotated[float, RealSet.closed_open(0, oo)] = 0.2,
        a1: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
        xi_s: Annotated[float, RealSet.closed_open(0, oo)] = 8.7,
        xi_i: Annotated[float, RealSet.closed_open(0, oo)] = 0.00873,
        a2: Annotated[float, RealSet.closed_open(0, oo)] = 1.35,
        r1: Annotated[float, RealSet.closed_open(0, oo)] = 3e-05,
        c1: Annotated[float, RealSet.closed_open(0, oo)] = 0.0005,
        d1: Annotated[float, RealSet.closed_open(0, oo)] = 0.37451,
        s_e: Annotated[float, RealSet.closed_open(0, oo)] = 0.15,
        a3: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
        alpha_an: Annotated[float, RealSet.open(0, oo)] = 0.4811,
        beta_an: Annotated[float, RealSet.open(0, oo)] = 0.0348,
        k12_an: Annotated[float, RealSet.closed_open(0, oo)] = 0.223,
        k21_an: Annotated[float, RealSet.open(0, oo)] = 0.215,
        u50_an: Annotated[float, RealSet.open(0, oo)] = 11.4274,
        alpha_im: Annotated[float, RealSet.open(0, oo)] = 0.5827,
        beta_im: Annotated[float, RealSet.open(0, oo)] = 0.0271,
        k12_im: Annotated[float, RealSet.closed_open(0, oo)] = 0.3,
        k21_im: Annotated[float, RealSet.open(0, oo)] = 0.2455,
        u50_im: Annotated[float, RealSet.open(0, oo)] = 7.1903,
        g: Annotated[float, RealSet.open(0, oo)] = 1.0,
        delta_r: Annotated[float, RealSet.closed_open(0, oo)] = 0.01,
        u_theta: Annotated[float, RealSet.closed_open(0, oo)] = 5.0,
        tox_an: Annotated[float, RealSet.open(0, oo)] = 10.0,
        tox_im: Annotated[float, RealSet.open(0, oo)] = 10.0,
        dose_an: Annotated[float, RealSet.closed_open(0, oo)] = 15.0,
        dose_im: Annotated[float, RealSet.closed_open(0, oo)] = 20.0,
        period: float = 21.0,
        width: float = 1 / 24,
        doses: int = 6,
    ) -> None:
        super().__init__(label)
        self.A = A
        self.Vb = Vb
        self.E = E
        self.c_an = c_an
        self.q_an = q_an
        self.R_an = R_an
        self.c_im = c_im
        self.q_im = q_im
        self.R_im = R_im
        self.v1 = v1
        self.v2 = v2
        self.a1 = a1
        self.xi_s = xi_s
        self.xi_i = xi_i
        self.a2 = a2
        self.r1 = r1
        self.c1 = c1
        self.d1 = d1
        self.s_e = s_e
        self.a3 = a3
        self.alpha_an = alpha_an
        self.beta_an = beta_an
        self.k12_an = k12_an
        self.k21_an = k21_an
        self.u50_an = u50_an
        self.alpha_im = alpha_im
        self.beta_im = beta_im
        self.k12_im = k12_im
        self.k21_im = k21_im
        self.u50_im = u50_im
        self.g = g
        self.delta_r = delta_r
        self.u_theta = u_theta
        self.tox_an = tox_an
        self.tox_im = tox_im
        self.dose_an = dose_an
        self.dose_im = dose_im
        self.period = period
        self.width = width
        self.doses = doses

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

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 DosingInteraction(Interaction):
    """Input of a drug into a state of a target at the rate `dose`.

    The drug enters constantly or in a schedule of infusions.

    Without a period the drug enters at the constant rate `dose`. With a period it enters at the rate `dose` for `width`
    time units every `period` from `start`, `count` times or without end. The dose is a function of the namespace,
    which reads the parameters of the target, or a number.

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

        target:
            The path of the element or group whose drug state the dose raises.

        state:
            The name of the state of the target that holds the drug.

        dose:
            A function of the namespace that returns the rate of the input during an infusion, or a number.

        period:
            The time between the starts of infusions, or `None` for a constant input.

        width:
            The duration of every infusion.

        start:
            The time of the first infusion.

        count:
            The number of infusions, or `None` for a schedule that never ends.

    Raises:
        ValidationError:
            The state is not a name, the dose is neither a function nor a number, or the schedule is not positive.

    Examples:
        >>> from skcomplex.systems.biology.common.kinetics import CompartmentElement
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.pharmacokinetics import DosingInteraction
        >>> dosing = DosingInteraction('dosing', target='patient', state='x', dose=2.0, period=10.0, count=3)
        >>> system = System(elements=[CompartmentElement('patient', x=0.0)], interactions=[dosing])
        >>> trajectory = system.prepare().simulate(until=40.0, dt=0.5)
        >>> round(float(trajectory.get_values('patient.x')[-1]), 3)
        6.0
    """

    law_classes = (RateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str = 'x',
        dose: Callable[[SimpleNamespace], object] | float = 1.0,
        period: float | None = None,
        width: float = 1.0,
        start: float = 0.0,
        count: int | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.dose = dose
        self.period = period
        self.width = width
        self.start = start
        self.count = count

    def _check_arguments(self) -> None:
        """Raise an error for a state, a dose, or a schedule the input cannot take.

        Raises:
            ValidationError:
                The state is not a name, the dose is neither a function nor a number, or the schedule is not positive.
        """
        super()._check_arguments()
        if not (callable(self.dose) or isinstance(self.dose, int | float)):
            error_msg = f'The dose of {self.label!r} is {self.dose!r}. Give a function of the namespace or a number.'
            raise ValidationError(error_msg)
        if self.period is not None and not (self.period > 0 and self.width > 0):
            error_msg = (
                f'The schedule of {self.label!r} has the period {self.period!r} and the width {self.width!r}. Give '
                'both above 0.'
            )
            raise ValidationError(error_msg)

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

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = [RateLaw(getattr(context.target, self.state), self._get_rate(context))]

    def _get_rate(self, namespace: SimpleNamespace) -> Expression:
        """Return the dose, times the schedule of infusions when the input has a period.

        Args:
            namespace:
                The namespace of the interaction, with the namespace of the target and the time `t`.

        Returns:
            rate:
                The rate of the input.
        """
        dose = self.dose(namespace) if callable(self.dose) else self.dose
        if self.period is None:
            constant: Expression = dose
            return constant
        schedule: Expression = dose * pulse_train(
            namespace.t,
            self.period,
            self.width,
            start=self.start,
            count=self.count,
        )
        return schedule

Equations

The equations are those that symbolic returns for the system with its default parameters.

tumour.A: diff(A_tumour(t), t) == -a1_tumour*A_tumour(t)*E_tumour(t) - v1_tumour*A_tumour(t)*log(A_tumour(t)/Vb_tumour(t))
tumour.Vb: diff(Vb_tumour(t), t) == -xi_i_tumour*A_tumour(t)^0.6666666666666666*Vb_tumour(t) + xi_s_tumour*A_tumour(t) - v2_tumour*Vb_tumour(t) - a2_tumour*c_an_tumour(t)^g_tumour*Vb_tumour(t)/(((delta_r_tumour*R_an_tumour(t) + 1)*u50_an_tumour)^g_tumour + c_an_tumour(t)^g_tumour)
tumour.E: diff(E_tumour(t), t) == -(c1_tumour*A_tumour(t)^2 - A_tumour(t))*r1_tumour*E_tumour(t) - d1_tumour*E_tumour(t) + a3_tumour*c_im_tumour(t)^g_tumour*E_tumour(t)/(((delta_r_tumour*R_im_tumour(t) + 1)*u50_im_tumour)^g_tumour + c_im_tumour(t)^g_tumour) + s_e_tumour
tumour.c_an: diff(c_an_tumour(t), t) == -k12_an_tumour*c_an_tumour(t) - alpha_an_tumour*beta_an_tumour*c_an_tumour(t)/k21_an_tumour + k21_an_tumour*q_an_tumour(t) + 24.0*dose_an_tumour*where(both(t >= 0.0, t < 126.0, mod(t, 21.0) < 0.041666666666666664), 1.0, 0)
tumour.q_an: diff(q_an_tumour(t), t) == k12_an_tumour*c_an_tumour(t) - k21_an_tumour*q_an_tumour(t)
tumour.R_an: diff(R_an_tumour(t), t) == where(c_an_tumour(t) < u_theta_tumour, u_theta_tumour - c_an_tumour(t), 0)
tumour.c_im: diff(c_im_tumour(t), t) == -k12_im_tumour*c_im_tumour(t) - alpha_im_tumour*beta_im_tumour*c_im_tumour(t)/k21_im_tumour + k21_im_tumour*q_im_tumour(t) + 24.0*dose_im_tumour*where(both(t >= 0.0, t < 126.0, mod(t, 21.0) < 0.041666666666666664), 1.0, 0)
tumour.q_im: diff(q_im_tumour(t), t) == k12_im_tumour*c_im_tumour(t) - k21_im_tumour*q_im_tumour(t)
tumour.R_im: diff(R_im_tumour(t), t) == where(c_im_tumour(t) < u_theta_tumour, u_theta_tumour - c_im_tumour(t), 0)