Skip to content

Generalized stochastic predator-prey

Prey and predators born and killed one at a time.

  • Class: StochasticPredatorPreySystem
  • Import: from skcomplex.systems.biology.ecology import StochasticPredatorPreySystem
  • Field: biology/ecology
  • Topics: predator-prey, jump process, gillespie, paradox of enrichment
  • References:
    • Carmichael and Hadžikadić 2019
    • Rosenzweig 1971

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.ecology import StochasticPredatorPreySystem

trajectory = StochasticPredatorPreySystem().prepare().simulate()

Parameters

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

Parameter Default
prey 200.0
predators 200.0
r 1.0
K 600.0
a 0.005
h 0.5
e 0.5
m 0.3
stochastic True
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 jump, rate
Randomness stochastic
Domains real
Structure fixed

Class

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

class StochasticPredatorPreySystem(BaseSystem):
    """Prey and predators born and killed one at a time.

    The prey crowd and the predation saturates.

    The deterministic limit has the coexistence point `x = m / (a (e - m h))`. It is stable while `K < 2 x + 1 / (a h)`,
    and enriching the prey beyond that turns it into large cycles, which demographic noise drives to extinction. The
    system has the populations `prey` and `predators`.

    Args:
        prey:
            The initial number of prey.

        predators:
            The initial number of predators.

        r:
            The birth rate of the prey.

        K:
            The carrying capacity of the prey.

        a:
            The attack rate.

        h:
            The handling time.

        e:
            The number of predators born per prey eaten.

        m:
            The death rate of the predators.

        stochastic:
            Whether births, deaths, and kills are random events.

        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.ecology import StochasticPredatorPreySystem
        >>> StochasticPredatorPreySystem(K=1000.0).prepare().system_.interactions[0].K
        1000.0
    """

    field = 'biology/ecology'
    topics = ('predator-prey', 'jump process', 'gillespie', 'paradox of enrichment')
    references = ('Carmichael and Hadžikadić 2019', 'Rosenzweig 1971')
    until = 100.0
    dt = 0.5

    def __init__(
        self,
        prey: float = 200.0,
        predators: float = 200.0,
        *,
        r: float = 1.0,
        K: float = 600.0,
        a: float = 0.005,
        h: float = 0.5,
        e: float = 0.5,
        m: float = 0.3,
        stochastic: bool = True,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.prey = prey
        self.predators = predators
        self.r = r
        self.K = K
        self.a = a
        self.h = h
        self.e = e
        self.m = m
        self.stochastic = stochastic

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of prey and predators born and killed one at a time.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        self.system_ = System(
            self.label,
            elements=[PopulationElement('prey', x=self.prey), PopulationElement('predators', x=self.predators)],
            interactions=[
                PredatorPreyEventsInteraction(
                    'events',
                    prey='prey',
                    predators='predators',
                    r=self.r,
                    K=self.K,
                    a=self.a,
                    h=self.h,
                    e=self.e,
                    m=self.m,
                    stochastic=self.stochastic,
                ),
            ],
        )

Components

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

Elements:

Interactions:

  • PredatorPreyEventsInteraction, from Interaction
class PopulationElement(CompartmentElement):
    """Population of one species, a compartment whose state `x` holds its size.

    Args:
        label:
            The label of the population.

        x:
            The initial size.

    Examples:
        >>> from skcomplex.systems.biology.common.populations import PopulationElement
        >>> PopulationElement('rabbits', x=40).x
        40
    """

    def __init__(
        self,
        label: str,
        *,
        x: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
    ) -> None:
        super().__init__(label, x=x)

class PredatorPreyEventsInteraction(Interaction):
    """Births, crowding, saturating predation, and deaths of prey and predators.

    They are events of single individuals.

    Prey are born at the rate `r x` and die of crowding at the rate `r x^2 / K`. Predators kill prey at the Holling
    type II rate `a x y / (1 + a h x)`, are born at `e` times that rate, and die at the rate `m y`. In deterministic
    mode the rates drive the populations as differential equations.

    Args:
        label:
            The label of the interaction.

        prey:
            The path of the prey population `x`.

        predators:
            The path of the predator population `y`.

        r:
            The birth rate of the prey.

        K:
            The carrying capacity of the prey.

        a:
            The attack rate.

        h:
            The handling time.

        e:
            The number of predators born per prey eaten.

        m:
            The death rate of the predators.

        stochastic:
            Whether births, deaths, and kills are random events.

    Examples:
        >>> from skcomplex.systems.biology.ecology import PredatorPreyEventsInteraction
        >>> PredatorPreyEventsInteraction('events', prey='voles', predators='weasels', K=200.0).K
        200.0
    """

    law_classes = (JumpLaw, RateLaw)

    def __init__(
        self,
        label: str,
        *,
        prey: Role,
        predators: Role,
        r: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        K: Annotated[float, RealSet.open(0, oo)] = 200.0,
        a: Annotated[float, RealSet.closed_open(0, oo)] = 0.02,
        h: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
        e: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
        m: Annotated[float, RealSet.closed_open(0, oo)] = 0.3,
        stochastic: bool = True,
    ) -> None:
        super().__init__(label)
        self.prey = prey
        self.predators = predators
        self.r = r
        self.K = K
        self.a = a
        self.h = h
        self.e = e
        self.m = m
        self.stochastic = stochastic

    def _get_change(self, member: SimpleNamespace, step: int, propensity: Expression) -> BaseLaw:
        """Return the law that changes the population of a member by a step at a propensity.

        In stochastic mode the change is a jump of one individual, and otherwise a rate of the step times the
        propensity.
        """
        if self.stochastic:
            return JumpLaw(propensity, {member.x: step})
        return RateLaw(member.x, step * propensity)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the five channels of births and deaths.

        Args:
            context:
                The namespace of the bound elements, the time `t`, and the parameters.
        """
        super()._prepare(context)
        s = context
        prey, predators = s.prey, s.predators
        x, y = prey.x, predators.x
        kills = s.a * x * y / (1 + s.a * s.h * x)
        self.laws_ = [
            self._get_change(prey, 1, s.r * x),
            self._get_change(prey, -1, s.r * x**2 / s.K),
            self._get_change(prey, -1, kills),
            self._get_change(predators, 1, s.e * kills),
            self._get_change(predators, -1, s.m * y),
        ]