Immune competition
The kinetic system of the competition between tumour cells and immune cells.
- Class:
ImmuneCompetitionSystem - Import:
from skcomplex.systems.biology.oncology import ImmuneCompetitionSystem - Field:
biology/oncology - Topics:
tumour,immune,kinetic,distribution - References:
- Bellomo et al. 2017
- Bellomo and Delitala 2008
- Bellomo, Bellouquid, and Delitala 2004
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 ImmuneCompetitionSystem
trajectory = ImmuneCompetitionSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
classes |
5 |
activation |
0.75 |
tumour |
0.05 |
immune |
1.0 |
growth |
0.3 |
progression |
0.05 |
kill |
1.0 |
inhibition |
0.2 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | continuous |
| Space | lattice |
| Laws | rate |
| Randomness | deterministic |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class ImmuneCompetitionSystem(BaseSystem):
"""The kinetic system of the competition between tumour cells and immune cells.
Tumour cells and immune cells are distributions over activity classes, the progression of tumour cells and the
activation of immune cells, held by site groups on a lattice of the classes. Tumour cells proliferate in the host
and progress, active immune cells destroy them, and tumour cells inhibit the activation of immune cells. The tumour
starts in the lowest progression class and the immune cells in the class nearest `activation`. While `kill
activation immune` exceeds `growth`, the immune response wins and the tumour density decays. Below that threshold
the tumour grows, inhibits the immune cells further, and escapes. The system has the distributions `tumour` and
`immune`, the host `host`, and the interactions `growth` and `competition`. Its standard observables are the tumour
density, the mean tumour progression, and the mean immune activation.
Args:
classes:
The number of activity classes of both distributions.
activation:
The initial activation of the immune cells, between 0 and 1.
tumour:
The initial density of tumour cells.
immune:
The density of immune cells.
growth:
The proliferation rate of tumour cells.
progression:
The rate at which tumour cells progress one class.
kill:
The rate at which fully active immune cells destroy tumour cells.
inhibition:
The rate at which the most progressed tumour cells inhibit immune cells.
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 ImmuneCompetitionSystem
>>> [item.label for item in ImmuneCompetitionSystem().prepare().system_.elements]
['tumour', 'immune', 'host']
"""
field = 'biology/oncology'
topics = ('tumour', 'immune', 'kinetic', 'distribution')
references = IMMUNE_REFERENCES
until = 40
dt = 0.5
@staticmethod
def _get_classes_of(system: System) -> int:
"""Return the number of activity classes of a system.
It is the size of its tumour distribution.
"""
return int(np.size(next(item.x for item in system.elements if item.label == 'tumour')))
def __init__(
self,
classes: int = 5,
*,
activation: float = 0.75,
tumour: float = 0.05,
immune: float = 1.0,
growth: float = 0.3,
progression: float = 0.05,
kill: float = 1.0,
inhibition: float = 0.2,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.classes = classes
self.activation = activation
self.tumour = tumour
self.immune = immune
self.growth = growth
self.progression = progression
self.kill = kill
self.inhibition = inhibition
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the competition between tumour cells and immune cells.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
activities = activity_grid(self.classes)
activation_rates = np.tile(activities, (self.classes, 1))
tumour_density = np.zeros(self.classes)
tumour_density[0] = self.tumour
immune_density = np.zeros(self.classes)
immune_density[int(np.argmin(np.abs(activities - self.activation)))] = self.immune
self.system_ = System(
self.label,
elements=[
PopulationDensityElement(
'tumour',
x=tumour_density,
space=LatticeSpace(self.classes, boundary='fixed'),
),
PopulationDensityElement(
'immune',
x=immune_density,
space=LatticeSpace(self.classes, boundary='fixed'),
),
PopulationDensityElement('host', x=[1.0], size=1),
],
interactions=[
EncounterInteraction(
'proliferation',
candidate='tumour',
field='host',
rate=lambda _: self.growth,
outcome='proliferative',
),
EncounterInteraction(
'progression',
candidate='tumour',
field='host',
rate=lambda _: self.progression,
kernel=lambda _: step_table(self.classes, 1),
),
EncounterInteraction(
'destruction',
candidate='tumour',
field='immune',
rate=lambda _: activation_rates * self.kill,
outcome='destructive',
),
EncounterInteraction(
'inhibition',
candidate='immune',
field='tumour',
rate=lambda _: activation_rates * self.inhibition,
kernel=lambda _: step_table(self.classes, -1, self.classes),
),
],
space=LatticeSpace(self.classes, boundary='fixed'),
)
self.observables_ = tuple(immune_observables(ImmuneCompetitionSystem._get_classes_of(self.system_)))
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
PopulationDensityElement, fromElement, through the shared recipeNonnegativeElement
Interactions:
EncounterInteraction, fromInteraction, through the shared recipeEncounterInteraction
class PopulationDensityElement(NonnegativeElement):
"""Value `x` of the density of a structured population at one class.
A structured population is this element on a lattice of classes, such as sizes or activities, with one value per
class, and growth, encounters, and transport change it. The element has no laws of its own.
Args:
label:
The label of the element, unique among the components of its system.
x:
The initial density, a nonnegative number.
size:
The number of members, or `None` for one.
space:
The space with one member per site, such as a lattice of classes, or `None` for none.
Examples:
>>> from skcomplex.core.components.spaces import LatticeSpace
>>> from skcomplex.systems.biology.common.populations import PopulationDensityElement
>>> classes = LatticeSpace(5, boundary='fixed')
>>> PopulationDensityElement('cells', x=[0.2] * 5, space=classes).x
[0.2, 0.2, 0.2, 0.2, 0.2]
"""
def __init__(
self,
label: str,
*,
x: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, x=x, size=size, space=space)
class EncounterInteraction(Interaction):
"""An interaction where members of two distributions meet and change class.
A distribution is a group of `NonnegativeElement` with one member per class of a trait. A candidate at class `h`
meets the field at class `k` at the rate `rate[h, k]`, and the `outcome` says what follows:
- `'conservative'`: the candidate moves to class `i` with the probability `kernel[h, k, i]`.
- `'destructive'`: the candidate is removed.
- `'proliferative'`: the candidate creates a new candidate at class `i` with the probability `kernel[h, k, i]`, or
at its own class without a kernel.
The rate and the kernel are functions of the namespace, which holds `namespace.candidate`, `namespace.field`, and
the parameters. On a `PhaseSpace` encounters pair classes at the same position. Without a field the encounter is a
linear redistribution between classes. With a `cross_section` the rate is the binary collision integral of kinetic
theory, evaluated by a fast spectral method, which keeps the density exactly and the momentum and energy to spectral
accuracy.
Unlike the `bilinear` form of the core, which its rate laws hold, it names the outcomes of an encounter and builds
the rates and kernels from them. Choose it when the change of a population comes from binary meetings of its
members.
It appears in many fields. Traders exchange wealth when they meet, people shift their opinion after a conversation,
immune cells destroy tumour cells they meet, and gas molecules change velocity when they collide.
Args:
label:
The label of the interaction, unique among the components of its system.
candidate:
The path of the group of the candidate density.
field:
The path of the group of the field density, or `None` for a linear redistribution.
rate:
The function `rate(namespace)` of the encounter rate, a number or an expression, or an array `eta[h, k]`
of them, or `eta[h]` without a field, or `None` with a cross-section.
kernel:
The function `kernel(namespace)` of the array `kernel[h, k, i]` of the probabilities of the class of the
moved or created candidate, or `kernel[h, i]` without a field, or `None` for a destructive encounter or the
candidate's own class.
outcome:
`'conservative'`, `'destructive'`, or `'proliferative'`.
state:
The name of the state of the densities.
cross_section:
The function `B(speed, cosine)` of arrays of the relative speed and the cosine of the deflection angle, or
`None` for encounters at a rate.
factor:
A function of the namespace that returns a factor of the collision frequency, such as a function of the
density moment, or `None` for none.
Raises:
ValidationError:
The outcome is unknown, the state is no name, a function is not callable, a conservative encounter has no
kernel, an encounter without a field is not conservative, an encounter has neither a rate nor a
cross-section, or a cross-section comes with a rate, a kernel, a field, or an outcome.
Examples:
>>> import numpy as np
>>> from skcomplex.systems.general.kinetics import EncounterInteraction
>>> kernel = np.full((3, 3, 3), 1 / 3)
>>> mixing = EncounterInteraction(
... 'mixing', candidate='population', field='population', rate=lambda s: 1.0, kernel=lambda s: kernel
... )
>>> mixing.outcome
'conservative'
>>> collide = EncounterInteraction('collide', candidate='gas', cross_section=lambda speed, cosine: 1.0)
>>> collide.rate is None
True
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (RateLaw,)
def __init__(
self,
label: str,
*,
candidate: Role,
field: Role | None = None,
rate: Callable[[SimpleNamespace], object] | None = None,
kernel: Callable[[SimpleNamespace], object] | None = None,
outcome: str = 'conservative',
state: str = 'x',
cross_section: Callable[..., object] | None = None,
factor: Callable[[SimpleNamespace], object] | None = None,
) -> None:
super().__init__(label)
self.candidate = candidate
self.field = field
self.rate = rate
self.kernel = kernel
self.outcome = outcome
self.state = state
self.cross_section = cross_section
self.factor = factor
def _check_collision(self) -> None:
"""Raise an error for a cross-section or factor that is no function, or misused.
A cross-section may not come with the others.
"""
if not callable(self.cross_section):
error_msg = f'The cross-section of {self.label!r} is {self.cross_section!r}. Give a function of two arrays.'
raise ValidationError(error_msg)
if self.factor is not None and not callable(self.factor):
error_msg = f'The factor of {self.label!r} is {self.factor!r}. Give a function of the namespace.'
raise ValidationError(error_msg)
others = self.rate, self.kernel, self.field
if any(item is not None for item in others) or self.outcome != 'conservative':
error_msg = f'The cross-section of {self.label!r} sets the rate. Give no rate, kernel, field, or outcome.'
raise ValidationError(error_msg)
def _check_arguments(self) -> None:
"""Raise an error for an argument the interaction cannot take.
Raises:
ValidationError:
The outcome is unknown, the state is no name, a function is not callable, a conservative encounter has
no kernel, an encounter without a field is not conservative, an encounter has neither a rate nor a
cross-section, or a cross-section comes with a rate, a kernel, a field, or an outcome.
"""
super()._check_arguments()
self._check_encounter()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rate law of the candidate for a binding.
Args:
context:
The namespace of the candidate and the field.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = self._get_encounter_laws(context)
def _check_encounter(self) -> None:
"""Raise an error for an unknown outcome, a bad function, or a missing kernel."""
if not isinstance(self.state, str) or not self.state.isidentifier():
error_msg = f'{type(self).__name__} {self.label!r} reads the state {self.state!r}, which is no name.'
raise ValidationError(error_msg)
if self.cross_section is not None:
self._check_collision()
return
if self.factor is not None:
error_msg = f'The factor of {self.label!r} scales a cross-section. Give `cross_section`.'
raise ValidationError(error_msg)
if self.outcome not in OUTCOMES:
error_msg = (
f'The outcome of encounter {self.label!r} is {self.outcome!r}. Use one of {", ".join(OUTCOMES)}.'
)
raise ValidationError(error_msg)
if not callable(self.rate) or (self.kernel is not None and not callable(self.kernel)):
error_msg = f'The rate and the kernel of encounter {self.label!r} must be functions of the namespace.'
raise ValidationError(error_msg)
if self.outcome == 'conservative' and self.kernel is None:
error_msg = f'The conservative encounter {self.label!r} moves candidates by a kernel. Give `kernel`.'
raise ValidationError(error_msg)
if self.field is None and self.outcome != 'conservative':
error_msg = f'The {self.outcome} encounter {self.label!r} reads a density of others. Give `field`.'
raise ValidationError(error_msg)
def _get_linear_laws(self, candidate: Expression, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the rate law of a redistribution without a field.
Its rate is a conserved bilinear form.
It uses one field class of value one.
"""
assert self.rate is not None
rate = np.asarray(self.rate(namespace), dtype=object)
rates = rate if rate.ndim == 0 else rate.reshape(-1, 1)
kernel = np.asarray(self.kernel(namespace) if self.kernel is not None else (), dtype=object)
outcomes = np.expand_dims(kernel, axis=1)
form = bilinear(rates[()], outcomes, candidate, conserved=True)
return [RateLaw(candidate, form)]
def _get_encounter_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
"""Return the rate law of the encounters or the collisions of the candidate."""
candidate = getattr(self._get_member(namespace, 'candidate'), self.state)
if self.cross_section is not None:
factor = SR(1 if self.factor is None else self.factor(namespace))
return [RateLaw(candidate, factor * collision_integral(candidate, self.cross_section))]
if self.field is None:
return self._get_linear_laws(candidate, namespace)
field = getattr(self._get_member(namespace, 'field'), self.state)
assert self.rate is not None
rate = self.rate(namespace)
kernel = None if self.kernel is None else self.kernel(namespace)
if self.outcome == 'destructive':
loss = -np.asarray(rate, dtype=object)
form = bilinear(loss, None, candidate, field)
elif self.outcome == 'proliferative':
form = bilinear(rate, kernel, candidate, field)
else:
form = bilinear(rate, kernel, candidate, field, conserved=True)
return [RateLaw(candidate, form)]