SIR
An epidemic that moves individuals from susceptible to infected to recovered.
- Class:
SIRSystem - Import:
from skcomplex.systems.biology.epidemiology import SIRSystem - Field:
biology/epidemiology - Topics:
compartments,ode,jump - References:
- Kermack and McKendrick 1927
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.epidemiology import SIRSystem
trajectory = SIRSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
susceptible |
990.0 |
infected |
10.0 |
recovered |
0.0 |
beta |
0.0003 |
gamma |
0.1 |
stochastic |
False |
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 | deterministic |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class SIRSystem(ReactionNetworkSystem):
"""An epidemic that moves individuals from susceptible to infected to recovered.
The system has the compartments `S`, `I`, and `R`.
Args:
susceptible:
The initial number of susceptible individuals.
infected:
The initial number of infected individuals.
recovered:
The initial number of recovered individuals.
beta:
The infection rate per susceptible-infected pair.
gamma:
The recovery rate.
stochastic:
Whether infections and recoveries are random events of single individuals.
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.epidemiology import SIRSystem
>>> [element.label for element in SIRSystem().prepare().system_.elements]
['S', 'I', 'R']
"""
field = 'biology/epidemiology'
topics = ('compartments', 'ode', 'jump')
references = ('Kermack and McKendrick 1927',)
until = 160.0
dt = 1.0
def __init__(
self,
susceptible: float = 990.0,
infected: float = 10.0,
recovered: float = 0.0,
*,
beta: float = 0.0003,
gamma: float = 0.1,
stochastic: bool = False,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label=label, solver=solver, backend=backend)
self.susceptible = susceptible
self.infected = infected
self.recovered = recovered
self.beta = beta
self.gamma = gamma
self.stochastic = stochastic
def _get_species(self) -> dict[str, float]:
"""Return the initial numbers of susceptible, infected, and recovered individuals."""
return {'S': self.susceptible, 'I': self.infected, 'R': self.recovered}
def _get_interactions(self) -> list[ReactionInteraction]:
"""Return the infection and the recovery of an epidemic.
Returns:
interactions:
The infection and the recovery.
"""
return [
InfectionInteraction(
'infection',
susceptible='S',
infected='I',
beta=self.beta,
stochastic=self.stochastic,
),
RecoveryInteraction('recovery', infected='I', recovered='R', gamma=self.gamma, stochastic=self.stochastic),
]
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
NonnegativeElement, fromElement, through the shared recipeNonnegativeElement
Interactions:
InfectionInteraction, fromInteraction, through the shared recipeReactionInteractionRecoveryInteraction, fromInteraction, through the shared recipeReactionInteraction
class NonnegativeElement(Element):
"""An element that holds one nonnegative number `x`.
The number is an amount, a share, a concentration, or the density at one class of a distribution. The reactions,
flows, and encounters of its system change it, and a value below zero is rejected. With `size` it holds one number
per member, and with `space` one number per site, such as a distribution over the classes of a lattice.
Unlike `Element`, which takes any values, it fixes one value `x` at zero or above. Choose it when a system tracks an
amount that cannot be negative, such as a count, a mass, or a sum of money.
It appears in many fields. The number of people infected in an epidemic, the moles of a chemical species in a
reactor, the money in a bank account, and the tokens in a place of a Petri net are each one nonnegative number.
Args:
label:
The label of the element, unique among the components of its system.
x:
The initial value, a nonnegative number, or one per member or site.
size:
The number of members, or `None` for one.
space:
The space with one member per site, or `None` for none.
Attributes:
default_visual_:
How the element is drawn by default, the `visual` of its class.
Examples:
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.general.elements import NonnegativeElement
>>> System(elements=[NonnegativeElement('A', x=990)]).prepare().simulate(until=2).get_values('A.x').tolist()
[990.0]
>>> System(elements=[NonnegativeElement('A', x=-1.0)]).prepare()
Traceback (most recent call last):
...
skcomplex.core.errors.ValidationError: ...
"""
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, size=size, space=space)
self.x = x
class InfectionInteraction(ReactionInteraction):
"""Mass-action infection, the reaction `S + I -> 2 I` at the rate `beta S I`.
The reaction moves individuals from susceptible to infected.
It is a `ReactionInteraction` between the states `x` of the two compartments its roles bind, a rate equation, or
in stochastic mode a random event that moves one individual.
Args:
label:
The label of the interaction.
susceptible:
The path of the susceptible compartment.
infected:
The path of the infected compartment.
beta:
The transmission rate.
stochastic:
Whether infections are random events.
Examples:
>>> from skcomplex.systems.biology.common.kinetics import CompartmentElement
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.epidemiology import InfectionInteraction
>>> system = System(
... elements=[CompartmentElement('S', x=99.0), CompartmentElement('I', x=1.0)],
... interactions=[InfectionInteraction('infection', susceptible='S', infected='I', beta=0.01)],
... )
>>> trajectory = system.prepare().simulate(until=5.0, dt=0.1)
>>> round(float(trajectory.get_values('S.x')[-1] + trajectory.get_values('I.x')[-1]), 6)
100.0
"""
def __init__(
self,
label: str,
*,
susceptible: Role,
infected: Role,
beta: Annotated[float, RealSet.closed_open(0, oo)] = 0.001,
stochastic: bool = False,
) -> None:
super().__init__(label)
self.susceptible = susceptible
self.infected = infected
self.beta = beta
self.stochastic = stochastic
def _get_reactants(self) -> Stoichiometry:
"""Return the states `x` of the compartments the reaction consumes."""
return {(self.susceptible, 'x'): 1, (self.infected, 'x'): 1}
def _get_products(self) -> Stoichiometry:
"""Return the states `x` of the compartments the reaction produces."""
return {(self.infected, 'x'): 2}
def _get_mode(self) -> str:
"""Return the mode of the reaction.
The mode is random events when stochastic and a rate equation otherwise.
"""
return MODES[self.stochastic]
def _get_rate(self, namespace: SimpleNamespace) -> Expression:
"""Return the mass action of the reaction at the rate constant `beta`.
Args:
namespace:
The namespace of the symbols the rate can use, with the compartments.
Returns:
rate:
The propensity of the reaction.
"""
return self._get_product_propensity(namespace, namespace.beta)
class RecoveryInteraction(ReactionInteraction):
"""Recovery, the reaction `I -> R` at the rate `gamma I`.
The reaction moves individuals from infected to recovered.
It is a `ReactionInteraction` between the states `x` of the two compartments its roles bind, a rate equation, or
in stochastic mode a random event that moves one individual.
Args:
label:
The label of the interaction.
infected:
The path of the infected compartment.
recovered:
The path of the recovered compartment.
gamma:
The recovery rate.
stochastic:
Whether recoveries are random events.
Examples:
>>> from skcomplex.systems.biology.common.kinetics import CompartmentElement
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.epidemiology import RecoveryInteraction
>>> system = System(
... elements=[CompartmentElement('I', x=10.0), CompartmentElement('R')],
... interactions=[RecoveryInteraction('recovery', infected='I', recovered='R', gamma=0.5)],
... )
>>> trajectory = system.prepare().simulate(until=2.0, dt=0.01)
>>> round(float(trajectory.get_values('I.x')[-1]), 3)
3.679
"""
def __init__(
self,
label: str,
*,
infected: Role,
recovered: Role,
gamma: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
stochastic: bool = False,
) -> None:
super().__init__(label)
self.infected = infected
self.recovered = recovered
self.gamma = gamma
self.stochastic = stochastic
def _get_reactants(self) -> Stoichiometry:
"""Return the states `x` of the compartments the reaction consumes."""
return {(self.infected, 'x'): 1}
def _get_products(self) -> Stoichiometry:
"""Return the states `x` of the compartments the reaction produces."""
return {(self.recovered, 'x'): 1}
def _get_mode(self) -> str:
"""Return the mode of the reaction.
The mode is random events when stochastic and a rate equation otherwise.
"""
return MODES[self.stochastic]
def _get_rate(self, namespace: SimpleNamespace) -> Expression:
"""Return the mass action of the reaction at the rate constant `gamma`.
Args:
namespace:
The namespace of the symbols the rate can use, with the compartments.
Returns:
rate:
The propensity of the reaction.
"""
return self._get_product_propensity(namespace, namespace.gamma)
Equations
The equations are those that symbolic returns for the system with its default parameters.
S.x: diff(x_S(t), t) == -beta_infection*x_I(t)*x_S(t)
I.x: diff(x_I(t), t) == beta_infection*x_I(t)*x_S(t) - gamma_recovery*x_I(t)
R.x: diff(x_R(t), t) == gamma_recovery*x_I(t)