Skip to content

SIRS

An epidemic whose immunity wanes.

  • Class: SIRSSystem
  • Import: from skcomplex.systems.biology.epidemiology import SIRSSystem
  • Field: biology/epidemiology
  • Topics: compartments, ode, jump, endemic, waning immunity
  • References:
    • Kermack and McKendrick 1932
    • Argun et al. 2021

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 SIRSSystem

trajectory = SIRSSystem().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
xi 0.02
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 SIRSSystem(ReactionNetworkSystem):
    """An epidemic whose immunity wanes.

    The epidemic returns in damped waves to an endemic equilibrium.

    The equilibrium has `S = gamma / beta` susceptible and `I = xi (N - S) / (gamma + xi)` infected. 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.

        xi:
            The rate at which immunity wanes.

        stochastic:
            Whether infections, recoveries, and losses of immunity 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 SIRSSystem
        >>> SIRSSystem(xi=0.1).prepare().system_.interactions[-1].xi
        0.1
    """

    field = 'biology/epidemiology'
    topics = ('compartments', 'ode', 'jump', 'endemic', 'waning immunity')
    references = ('Kermack and McKendrick 1932', 'Argun et al. 2021')
    until = 300.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,
        xi: float = 0.02,
        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.xi = xi
        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, the recovery, and the loss of immunity.

        They are the interactions of an epidemic whose immunity wanes.

        Returns:
            interactions:
                The infection, the recovery, and the loss of immunity.
        """
        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),
            ImmunityLossInteraction('waning', recovered='R', susceptible='S', xi=self.xi, stochastic=self.stochastic),
        ]

Components

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

Elements:

Interactions:

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)

class ImmunityLossInteraction(ReactionInteraction):
    """Loss of immunity, the reaction `R -> S` at the rate `xi R`.

    The reaction moves individuals from recovered back to susceptible.

    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.

        recovered:
            The path of the recovered compartment.

        susceptible:
            The path of the susceptible compartment.

        xi:
            The rate at which immunity wanes.

        stochastic:
            Whether losses of immunity are random events.

    Examples:
        >>> from skcomplex.systems.biology.epidemiology import ImmunityLossInteraction
        >>> ImmunityLossInteraction('waning', recovered='R', susceptible='S', xi=0.05).xi
        0.05
    """

    def __init__(
        self,
        label: str,
        *,
        recovered: Role,
        susceptible: Role,
        xi: Annotated[float, RealSet.closed_open(0, oo)] = 0.05,
        stochastic: bool = False,
    ) -> None:
        super().__init__(label)
        self.recovered = recovered
        self.susceptible = susceptible
        self.xi = xi
        self.stochastic = stochastic

    def _get_reactants(self) -> Stoichiometry:
        """Return the states `x` of the compartments the reaction consumes."""
        return {(self.recovered, 'x'): 1}

    def _get_products(self) -> Stoichiometry:
        """Return the states `x` of the compartments the reaction produces."""
        return {(self.susceptible, '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 `xi`.

        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.xi)

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) + xi_waning*x_R(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) - xi_waning*x_R(t)