Skip to content

Contact process

The contact process on a periodic lattice.

  • Class: ContactProcessSystem
  • Import: from skcomplex.systems.physics.statistical_mechanics import ContactProcessSystem
  • Field: physics/statistical_mechanics
  • Topics: lattice, stochastic, absorbing state, phase transition, epidemics
  • References:
    • Harris 1974
    • Marro and Dickman 1999
    • Pastor-Satorras et al. 2015

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.physics.statistical_mechanics import ContactProcessSystem

trajectory = ContactProcessSystem().prepare().simulate()

Parameters

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

Parameter Default
shape (64, 64)
rate 3.0
tau 0.1
infected 0.5
random_state 0
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time discrete
Space lattice
Laws update
Randomness deterministic
Domains real
Structure fixed

Class

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

class ContactProcessSystem(BaseSystem):
    """The contact process on a periodic lattice.

    The process survives above a critical infection rate near 1.65.

    Below the critical rate the infection dies out and the lattice falls into the absorbing healthy state. The system
    has the infections `lattice.infected`.

    Args:
        shape:
            The number of rows and columns.

        rate:
            The infection rate.

        tau:
            The time slice of one step.

        infected:
            The initial fraction of infected sites.

        random_state:
            The seed or generator of the initial infections.

        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.physics.statistical_mechanics import ContactProcessSystem
        >>> ContactProcessSystem((10, 10), rate=1.0).prepare().system_.elements[0].rate
        1.0
    """

    field = 'physics/statistical_mechanics'
    topics = ('lattice', 'stochastic', 'absorbing state', 'phase transition', 'epidemics')
    references = ('Harris 1974', 'Marro and Dickman 1999', 'Pastor-Satorras et al. 2015')
    until = 200
    dt = 1

    def __init__(
        self,
        shape: Sequence[int] = (64, 64),
        *,
        rate: float = 3.0,
        tau: float = 0.1,
        infected: float = 0.5,
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.shape = shape
        self.rate = rate
        self.tau = tau
        self.infected = infected
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the contact process on a lattice, with random infected sites at the start.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        shape = tuple(self.shape)
        states = (np.random.default_rng(self.random_state).random(shape) < self.infected).astype(float)
        lattice = ContactSiteElement(
            'lattice',
            infected=states.ravel(),
            rate=self.rate,
            tau=self.tau,
            space=LatticeSpace(shape),
        )
        infection = ContactInfectionInteraction('infection', target='lattice')
        self.system_ = System(self.label, elements=[lattice], interactions=[infection])

Components

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

Elements:

Interactions:

  • ContactInfectionInteraction, from Interaction
class ContactSiteElement(Element):
    """Sites of the contact process.

    Every site is infected at 1 or healthy at 0, and holds the infection rate `rate` and the time slice `tau` of one
    step, which `ContactInfectionInteraction` reads.

    Args:
        label:
            The label of the site or the lattice of sites.

        infected:
            The initial state, 1 for infected and 0 for healthy, or one state per site.

        rate:
            The infection rate.

        tau:
            The time slice of one step.

        space:
            The lattice of the sites, or `None` for one site.

    Examples:
        >>> from skcomplex.systems.physics.statistical_mechanics import ContactSiteElement
        >>> ContactSiteElement('site').rate
        3.0
    """

    def __init__(
        self,
        label: str,
        *,
        infected: object = 0.0,
        rate: Annotated[float, RealSet.closed_open(0, oo)] = 3.0,
        tau: Annotated[float, RealSet.open(0, oo)] = 0.1,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.infected = infected
        self.rate = rate
        self.tau = tau

class ContactInfectionInteraction(Interaction):
    """Infection and recovery of the contact process.

    A site infects a neighbour at the rate `rate / 4` and recovers at rate 1. One step is a time slice `tau`, in which
    an infected site recovers with probability `1 - exp(-tau)` and a healthy site is infected with probability
    `1 - exp(-rate tau f)`, where `f` is the fraction of its infected neighbours. It is an epidemic on a grid of
    villages, the spread of a plant across a field, or a rumour among neighbours.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the sites, whose values are `infected`, `rate`, and `tau`.

    Examples:
        >>> from skcomplex.systems.physics.statistical_mechanics import ContactInfectionInteraction
        >>> ContactInfectionInteraction('infection', target='lattice').target
        'lattice'
    """

    law_classes = (UpdateLaw,)

    def __init__(self, label: str, *, target: Role) -> None:
        super().__init__(label)
        self.target = target

    @staticmethod
    def _spread(
        infected: Array,
        *around: Array,
        rate: float | Array,
        tau: float | Array,
        random: Array,
        **kwargs: object,
    ) -> Array:
        """Return the next infections of the contact process over a time slice `tau`."""
        share = sum(around) / len(around)
        infects = random < -np.expm1(-rate * tau * share)
        recovers = random < -np.expm1(-tau)
        return np.where(infected == 1, np.where(recovers, 0.0, 1.0), np.where(infects, 1.0, 0.0))

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the stochastic infection and recovery of the sites.

        Args:
            context:
                The namespace of the target and the time `t`.
        """
        super()._prepare(context)
        self.laws_ = [UpdateLaw(context.target.infected, self._spread, neighborhood=NEAREST, stochastic=True)]