Skip to content

Lotka-Volterra

Prey and predators whose populations oscillate through predation.

  • Class: LotkaVolterraSystem
  • Import: from skcomplex.systems.biology.ecology import LotkaVolterraSystem
  • Field: biology/ecology
  • Topics: predator-prey, ode, oscillation
  • References:
    • Lotka 1925
    • Volterra 1926

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 LotkaVolterraSystem

trajectory = LotkaVolterraSystem().prepare().simulate()

Parameters

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

Parameter Default
prey 40.0
predators 9.0
r 1.1
a 0.4
b 0.1
d 0.4
K None
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 LotkaVolterraSystem(BaseSystem):
    """Prey and predators whose populations oscillate through predation.

    The system has the populations `prey` and `predators`.

    Args:
        prey:
            The initial number of prey.

        predators:
            The initial number of predators.

        r:
            The growth rate of the prey.

        a:
            The rate at which predation removes prey.

        b:
            The rate at which predation feeds predators.

        d:
            The mortality rate of the predators.

        K:
            The carrying capacity of the prey, or `None` for exponential growth of the prey.

        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 LotkaVolterraSystem
        >>> [element.label for element in LotkaVolterraSystem().prepare().system_.elements]
        ['prey', 'predators']
    """

    field = 'biology/ecology'
    topics = ('predator-prey', 'ode', 'oscillation')
    references = ('Lotka 1925', 'Volterra 1926')
    until = 50.0
    dt = 0.1

    def __init__(
        self,
        prey: float = 40.0,
        predators: float = 9.0,
        *,
        r: float = 1.1,
        a: float = 0.4,
        b: float = 0.1,
        d: float = 0.4,
        K: float | None = None,
        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.a = a
        self.b = b
        self.d = d
        self.K = K

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of prey and predators whose populations oscillate.

        Their populations oscillate through predation.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        growth: BaseInteraction = (
            ExponentialGrowthInteraction('growth', target='prey', r=self.r)
            if self.K is None
            else LogisticGrowthInteraction('growth', target='prey', r=self.r, K=self.K)
        )
        self.system_ = System(
            self.label,
            elements=[PopulationElement('prey', x=self.prey), PopulationElement('predators', x=self.predators)],
            interactions=[
                growth,
                PredationInteraction('predation', predator='predators', prey='prey', a=self.a, b=self.b),
                MortalityInteraction('death', target='predators', d=self.d),
            ],
        )

Components

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

Elements:

Interactions:

  • ExponentialGrowthInteraction, from Interaction
  • PredationInteraction, from Interaction
  • MortalityInteraction, 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 ExponentialGrowthInteraction(GrowthInteraction):
    """Growth at a constant per capita rate, `dx/dt = r x`.

    It is the exponential form of a growth without harvest.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the element or group whose population grows.

        r:
            The per capita growth rate, negative for decay.

        state:
            The name of the state of the target that holds the population.

    Examples:
        >>> from skcomplex.systems.biology.common.kinetics import CompartmentElement
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.populations import ExponentialGrowthInteraction
        >>> system = System(
        ...     elements=[CompartmentElement('rabbits', x=1.0)],
        ...     interactions=[ExponentialGrowthInteraction('growth', target='rabbits', r=0.5)],
        ... )
        >>> trajectory = system.prepare().simulate(until=2.0, dt=0.01)
        >>> round(float(trajectory.get_values('rabbits.x')[-1]), 3)
        2.718
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        r: float = 1.0,
        state: str = 'x',
    ) -> None:
        super().__init__(label, target=target, r=r, form='exponential', state=state)

    def _get_rate(self, namespace: SimpleNamespace) -> Expression:
        """Return the growth `r x`, with no harvest.

        Args:
            namespace:
                The namespace of the symbols the rate can use, with the namespace of the target.

        Returns:
            rate:
                The rate of the population.
        """
        return self._get_growth(namespace)

class PredationInteraction(Interaction):
    """Lotka-Volterra predation, where encounters remove prey and feed predators.

    The prey loses `a * predator * prey` per unit time and the predator gains `b * predator * prey`.

    Args:
        label:
            The label of the interaction.

        predator:
            The path of the predator population.

        prey:
            The path of the prey population.

        a:
            The attack rate.

        b:
            The conversion rate of eaten prey into predators.

    Examples:
        >>> from skcomplex.systems.biology.ecology import PredationInteraction
        >>> PredationInteraction('hunt', predator='foxes', prey='rabbits', a=0.4, b=0.1).prey
        'rabbits'
    """

    law_classes = (RateLaw,)

    def __init__(
        self,
        label: str,
        *,
        predator: Role,
        prey: Role,
        a: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
        b: Annotated[float, RealSet.closed_open(0, oo)] = 0.01,
    ) -> None:
        super().__init__(label)
        self.predator = predator
        self.prey = prey
        self.a = a
        self.b = b

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rates `-a * predator * prey` and `b * predator * prey`.

        Args:
            context:
                The namespace of the bound elements, the time `t`, and the parameters.
        """
        super()._prepare(context)
        s = context
        encounters = s.predator.x * s.prey.x
        self.laws_ = [RateLaw(s.prey.x, -s.a * encounters), RateLaw(s.predator.x, s.b * encounters)]

class MortalityInteraction(Interaction):
    """Death or loss at a constant per capita rate, `dx/dt = -d x`.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the element or group whose population dies.

        d:
            The per capita death rate.

        state:
            The name of the state of the target that holds the population.

    Examples:
        >>> from skcomplex.systems.biology.common.kinetics import CompartmentElement
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.populations import MortalityInteraction
        >>> system = System(
        ...     elements=[CompartmentElement('foxes', x=8.0)],
        ...     interactions=[MortalityInteraction('death', target='foxes', d=0.5)],
        ... )
        >>> trajectory = system.prepare().simulate(until=2.0, dt=0.01)
        >>> round(float(trajectory.get_values('foxes.x')[-1]), 3)
        2.943
    """

    law_classes = (RateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        d: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
        state: str = 'x',
    ) -> None:
        super().__init__(label)
        self.target = target
        self.d = d
        self.state = state

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate of the population.

        Args:
            context:
                The namespace of the target, the time `t`, and the parameters.
        """
        super()._prepare(context)
        self.laws_ = [RateLaw(getattr(context.target, self.state), self._get_rate(context))]

    def _get_rate(self, namespace: SimpleNamespace) -> Expression:
        """Return the loss `-d x`.

        Args:
            namespace:
                The namespace of the symbols the rate can use, with the namespace of the target.

        Returns:
            rate:
                The rate of the population.
        """
        loss: Expression = -namespace.d * getattr(namespace.target, self.state)
        return loss

Equations

The equations are those that symbolic returns for the system with its default parameters.

prey.x: diff(x_prey(t), t) == -a_predation*x_predators(t)*x_prey(t) + r_growth*x_prey(t)
predators.x: diff(x_predators(t), t) == b_predation*x_predators(t)*x_prey(t) - d_death*x_predators(t)