Prostate cancer with an androgen cell quota and PSA
The Portz cell-quota system of prostate cancer.
- Class:
ProstateCellQuotaSystem - Import:
from skcomplex.systems.biology.oncology import ProstateCellQuotaSystem - Field:
biology/oncology - Topics:
hormone therapy,ode,prostate cancer,cell quota,intermittent - References:
- Padmanabhan, Meskin, and Al Moustafa 2021
- Portz, Kuang, and Nagy 2012
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 ProstateCellQuotaSystem
trajectory = ProstateCellQuotaSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
AD |
15.0 |
AI |
0.0 |
rm |
0.025 |
q1 |
0.3 |
q2 |
0.15 |
d1 |
0.015 |
d2 |
0.015 |
r0 |
0.01 |
r1 |
0.15 |
r2 |
0.15 |
n |
3.0 |
theta |
3.0 |
U0 |
15.0 |
Umin |
0.5 |
du1 |
0.08 |
period |
500.0 |
width |
250.0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | continuous |
| Space | 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 ProstateCellQuotaSystem(BaseSystem):
"""The Portz cell-quota system of prostate cancer.
The cells grow on their internal androgen.
The androgen-dependent and independent cells grow at the Droop rate `rm (1 - q_i / Q_i)` of their cell quotas, which
take up serum androgen, and the PSA they release follows the quotas. A deprived dependent cell turns independent
faster, and an independent cell full of androgen turns back. The serum androgen follows the exponential relaxation
of the book's equation 7.18 between the normal level `U0` and `Umin`, with therapy during the first `width` days of
every `period`. The book gives neither the steepness `n` of the mutation rates nor `theta` of the PSA production,
nor the serum levels, their relaxation rate, and the schedule, so these defaults are chosen, and the other defaults
lie within the book's ranges. Cells are in billions, quotas in nM, PSA in ng/mL, and time in days. The PSA starts
near its value for the initial quotas. The system has the cells `tumour.AD` and `tumour.AI`, the quotas `tumour.Q1`
and `tumour.Q2`, the PSA `tumour.P`, and the androgen `tumour.U`.
Args:
AD:
The initial androgen-dependent cells.
AI:
The initial androgen-independent cells.
rm:
The maximum proliferation rate.
q1:
The minimum quota of the dependent cells.
q2:
The minimum quota of the independent cells.
d1:
The death rate of the dependent cells.
d2:
The death rate of the independent cells.
r0:
The baseline PSA production per cell.
r1:
The androgen-driven PSA production per dependent cell.
r2:
The androgen-driven PSA production per independent cell.
n:
The steepness of the mutation rates.
theta:
The steepness of the PSA production.
U0:
The normal serum androgen.
Umin:
The serum androgen under therapy.
du1:
The rate at which the serum androgen relaxes.
period:
The time between the starts of therapy periods.
width:
The duration of a therapy period.
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 ProstateCellQuotaSystem
>>> ProstateCellQuotaSystem(q1=0.45).prepare().system_.elements[0].q1
0.45
"""
field = 'biology/oncology'
topics = ('hormone therapy', 'ode', 'prostate cancer', 'cell quota', 'intermittent')
references = (BOOK, 'Portz, Kuang, and Nagy 2012')
until = 1500.0
dt = 5.0
def __init__(
self,
AD: float = 15.0,
AI: float = 0.0,
*,
rm: float = 0.025,
q1: float = 0.3,
q2: float = 0.15,
d1: float = 0.015,
d2: float = 0.015,
r0: float = 0.01,
r1: float = 0.15,
r2: float = 0.15,
n: float = 3.0,
theta: float = 3.0,
U0: float = 15.0,
Umin: float = 0.5,
du1: float = 0.08,
period: float = 500.0,
width: float = 250.0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.AD = AD
self.AI = AI
self.rm = rm
self.q1 = q1
self.q2 = q2
self.d1 = d1
self.d2 = d2
self.r0 = r0
self.r1 = r1
self.r2 = r2
self.n = n
self.theta = theta
self.U0 = U0
self.Umin = Umin
self.du1 = du1
self.period = period
self.width = width
@staticmethod
def _get_quota_uptake(target: SimpleNamespace, Q: Expression, q: Expression) -> Expression:
"""Return the uptake of androgen into a quota.
The uptake slows as the quota fills.
"""
uptake: Expression = target.vm * (target.qm - Q) / (target.qm - q) * target.U / (target.U + target.v50)
return uptake
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the Portz cell-quota system of prostate cancer.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
tumour = CellQuotaProstateElement(
'tumour',
AD=self.AD,
AI=self.AI,
U=self.U0,
rm=self.rm,
q1=self.q1,
q2=self.q2,
d1=self.d1,
d2=self.d2,
r0=self.r0,
r1=self.r1,
r2=self.r2,
n=self.n,
theta=self.theta,
U0=self.U0,
Umin=self.Umin,
du1=self.du1,
period=self.period,
width=self.width,
)
interactions = [
Interaction(
'dependent_growth',
roles={'target': 'tumour'},
laws=lambda s: [RateLaw(s.target.AD, s.target.rm * (1 - s.target.q1 / s.target.Q1) * s.target.AD)],
),
ReactionInteraction(
'dependent_death',
target='tumour',
reactants={'AD': 1},
propensity=lambda s: s.target.d1 * s.target.AD,
),
ReactionInteraction(
'to_independent',
target='tumour',
reactants={'AD': 1},
products={'AI': 1},
propensity=lambda s: s.target.mx1 * (1 - hill(s.target.Q1, s.target.m501, s.target.n)) * s.target.AD,
),
ReactionInteraction(
'to_dependent',
target='tumour',
reactants={'AI': 1},
products={'AD': 1},
propensity=lambda s: s.target.mx2 * hill(s.target.Q2, s.target.m502, s.target.n) * s.target.AI,
),
Interaction(
'independent_growth',
roles={'target': 'tumour'},
laws=lambda s: [RateLaw(s.target.AI, s.target.rm * (1 - s.target.q2 / s.target.Q2) * s.target.AI)],
),
ReactionInteraction(
'independent_death',
target='tumour',
reactants={'AI': 1},
propensity=lambda s: s.target.d2 * s.target.AI,
),
Interaction(
'dependent_uptake',
roles={'target': 'tumour'},
laws=lambda s: [RateLaw(s.target.Q1, self._get_quota_uptake(s.target, s.target.Q1, s.target.q1))],
),
Interaction(
'dependent_use',
roles={'target': 'tumour'},
laws=lambda s: [RateLaw(s.target.Q1, -s.target.rm * (s.target.Q1 - s.target.q1))],
),
ReactionInteraction(
'dependent_degradation',
target='tumour',
reactants={'Q1': 1},
propensity=lambda s: s.target.d3 * s.target.Q1,
),
Interaction(
'independent_uptake',
roles={'target': 'tumour'},
laws=lambda s: [RateLaw(s.target.Q2, self._get_quota_uptake(s.target, s.target.Q2, s.target.q2))],
),
Interaction(
'independent_use',
roles={'target': 'tumour'},
laws=lambda s: [RateLaw(s.target.Q2, -s.target.rm * (s.target.Q2 - s.target.q2))],
),
ReactionInteraction(
'independent_degradation',
target='tumour',
reactants={'Q2': 1},
propensity=lambda s: s.target.d3 * s.target.Q2,
),
Interaction(
'psa_leak',
roles={'target': 'tumour'},
laws=lambda s: [RateLaw(s.target.P, s.target.r0 * (s.target.AD + s.target.AI))],
),
Interaction(
'psa_production',
roles={'target': 'tumour'},
laws=lambda s: [
RateLaw(
s.target.P,
s.target.r1 * s.target.AD * hill(s.target.Q1, s.target.rho1, s.target.theta)
+ s.target.r2 * s.target.AI * hill(s.target.Q2, s.target.rho2, s.target.theta),
),
],
),
ReactionInteraction(
'psa_clearance',
target='tumour',
reactants={'P': 1},
propensity=lambda s: s.target.du * s.target.P,
),
Interaction(
'androgen',
roles={'target': 'tumour'},
laws=lambda s: [
RateLaw(
s.target.U,
s.target.du1
* (
s.target.U0
- (s.target.U0 - s.target.Umin) * pulse_train(s.t, tumour.period, tumour.width)
- s.target.U
),
),
],
),
]
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:
CellQuotaProstateElement, fromElement
Interactions:
InteractionReactionInteraction, fromInteraction, through the shared recipeReactionInteraction
class CellQuotaProstateElement(Element):
"""Prostate cancer cells that follow their androgen cell quota.
The growth and the mutation of the cells follow the quota, and the cells release PSA.
The cells grow at the Droop rate `rm (1 - q_i / Q_i)`, die at `d_i`, and switch from dependent to independent at
`mx1 m501^n / (Q1^n + m501^n)` and back at `mx2 Q2^n / (Q2^n + m502^n)`. The quotas follow
`dQ_i/dt = vm (qm - Q_i) / (qm - q_i) U / (U + v50) - rm (Q_i - q_i) - d3 Q_i`, and the serum PSA
`dP/dt = r0 (AD + AI) + r1 AD Q1^theta / (Q1^theta + rho1^theta) + r2 AI Q2^theta / (Q2^theta + rho2^theta)
- du P`. The serum androgen relaxes at the rate `du1` to `Umin` during the `width` days of therapy that open
every `period` days and to `U0` otherwise.
The element holds the states and parameters and has no laws of its own: the interactions of
`ProstateCellQuotaSystem` read its parameters.
Args:
label:
The label of the tumour.
AD:
The initial number of androgen-dependent cells.
AI:
The initial number of androgen-independent cells.
Q1:
The initial cell quota of the dependent cells.
Q2:
The initial cell quota of the independent cells.
P:
The initial serum PSA.
U:
The initial serum androgen.
rm:
The maximum proliferation rate.
q1:
The minimum quota of the dependent cells.
q2:
The minimum quota of the independent cells.
d1:
The death rate of the dependent cells.
d2:
The death rate of the independent cells.
d3:
The degradation rate of the quota.
qm:
The maximum quota.
vm:
The maximum uptake rate of androgen.
v50:
The serum androgen at which the uptake is half way.
mx1:
The maximum mutation rate from dependent to independent.
mx2:
The maximum mutation rate from independent to dependent.
m501:
The quota at which the mutation to independence is half way.
m502:
The quota at which the mutation back to dependence is half way.
n:
The steepness of the mutation rates.
r0:
The baseline PSA production per cell.
r1:
The androgen-driven PSA production per dependent cell.
r2:
The androgen-driven PSA production per independent cell.
rho1:
The quota at which the PSA production of the dependent cells is half way.
rho2:
The quota at which the PSA production of the independent cells is half way.
theta:
The steepness of the PSA production.
du:
The clearance rate of the PSA.
U0:
The normal serum androgen.
Umin:
The serum androgen under therapy.
du1:
The rate at which the serum androgen relaxes.
period:
The time between the starts of therapy periods.
width:
The duration of a therapy period.
Examples:
>>> from skcomplex.systems.biology.oncology import CellQuotaProstateElement
>>> CellQuotaProstateElement('tumour').qm
5.0
"""
def __init__(
self,
label: str,
*,
AD: Annotated[float, RealSet.closed_open(0, oo)] = 15.0,
AI: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
Q1: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
Q2: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
P: Annotated[float, RealSet.closed_open(0, oo)] = 3.4,
U: Annotated[float, RealSet.closed_open(0, oo)] = 15.0,
rm: Annotated[float, RealSet.closed_open(0, oo)] = 0.025,
q1: Annotated[float, RealSet.open(0, oo)] = 0.3,
q2: Annotated[float, RealSet.open(0, oo)] = 0.15,
d1: Annotated[float, RealSet.closed_open(0, oo)] = 0.015,
d2: Annotated[float, RealSet.closed_open(0, oo)] = 0.015,
d3: Annotated[float, RealSet.closed_open(0, oo)] = 0.09,
qm: Annotated[float, RealSet.open(0, oo)] = 5.0,
vm: Annotated[float, RealSet.closed_open(0, oo)] = 0.275,
v50: Annotated[float, RealSet.open(0, oo)] = 4.0,
mx1: Annotated[float, RealSet.closed_open(0, oo)] = 0.00015,
mx2: Annotated[float, RealSet.closed_open(0, oo)] = 0.0001,
m501: Annotated[float, RealSet.open(0, oo)] = 0.08,
m502: Annotated[float, RealSet.open(0, oo)] = 1.7,
n: Annotated[float, RealSet.open(0, oo)] = 3.0,
r0: Annotated[float, RealSet.closed_open(0, oo)] = 0.01,
r1: Annotated[float, RealSet.closed_open(0, oo)] = 0.15,
r2: Annotated[float, RealSet.closed_open(0, oo)] = 0.15,
rho1: Annotated[float, RealSet.open(0, oo)] = 1.3,
rho2: Annotated[float, RealSet.open(0, oo)] = 1.1,
theta: Annotated[float, RealSet.open(0, oo)] = 3.0,
du: Annotated[float, RealSet.closed_open(0, oo)] = 0.08,
U0: Annotated[float, RealSet.closed_open(0, oo)] = 15.0,
Umin: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
du1: Annotated[float, RealSet.closed_open(0, oo)] = 0.08,
period: float = 500.0,
width: float = 250.0,
) -> None:
super().__init__(label)
self.AD = AD
self.AI = AI
self.Q1 = Q1
self.Q2 = Q2
self.P = P
self.U = U
self.rm = rm
self.q1 = q1
self.q2 = q2
self.d1 = d1
self.d2 = d2
self.d3 = d3
self.qm = qm
self.vm = vm
self.v50 = v50
self.mx1 = mx1
self.mx2 = mx2
self.m501 = m501
self.m502 = m502
self.n = n
self.r0 = r0
self.r1 = r1
self.r2 = r2
self.rho1 = rho1
self.rho2 = rho2
self.theta = theta
self.du = du
self.U0 = U0
self.Umin = Umin
self.du1 = du1
self.period = period
self.width = width
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()]
Equations
The equations are those that symbolic returns for the system with its default parameters.
tumour.AD: diff(AD_tumour(t), t) == mx1_tumour*(Q1_tumour(t)^n_tumour/(m501_tumour^n_tumour + Q1_tumour(t)^n_tumour) - 1)*AD_tumour(t) - rm_tumour*(q1_tumour/Q1_tumour(t) - 1)*AD_tumour(t) - d1_tumour*AD_tumour(t) + mx2_tumour*Q2_tumour(t)^n_tumour*AI_tumour(t)/(m502_tumour^n_tumour + Q2_tumour(t)^n_tumour)
tumour.AI: diff(AI_tumour(t), t) == -mx1_tumour*(Q1_tumour(t)^n_tumour/(m501_tumour^n_tumour + Q1_tumour(t)^n_tumour) - 1)*AD_tumour(t) - rm_tumour*(q2_tumour/Q2_tumour(t) - 1)*AI_tumour(t) - d2_tumour*AI_tumour(t) - mx2_tumour*Q2_tumour(t)^n_tumour*AI_tumour(t)/(m502_tumour^n_tumour + Q2_tumour(t)^n_tumour)
tumour.Q1: diff(Q1_tumour(t), t) == (q1_tumour - Q1_tumour(t))*rm_tumour - d3_tumour*Q1_tumour(t) - (qm_tumour - Q1_tumour(t))*vm_tumour*U_tumour(t)/((q1_tumour - qm_tumour)*(v50_tumour + U_tumour(t)))
tumour.Q2: diff(Q2_tumour(t), t) == (q2_tumour - Q2_tumour(t))*rm_tumour - d3_tumour*Q2_tumour(t) - (qm_tumour - Q2_tumour(t))*vm_tumour*U_tumour(t)/((q2_tumour - qm_tumour)*(v50_tumour + U_tumour(t)))
tumour.P: diff(P_tumour(t), t) == r0_tumour*(AD_tumour(t) + AI_tumour(t)) + r1_tumour*Q1_tumour(t)^theta_tumour*AD_tumour(t)/(rho1_tumour^theta_tumour + Q1_tumour(t)^theta_tumour) + r2_tumour*Q2_tumour(t)^theta_tumour*AI_tumour(t)/(rho2_tumour^theta_tumour + Q2_tumour(t)^theta_tumour) - du_tumour*P_tumour(t)
tumour.U: diff(U_tumour(t), t) == -((U0_tumour - Umin_tumour)*where(both(t >= 0.0, mod(t, 500.0) < 250.0), 1.0, 0) - U0_tumour + U_tumour(t))*du1_tumour