Skip to content

Food webs

A food web of logistic basal species and Lotka-Volterra consumers.

  • Class: FoodWebsSystem
  • Import: from skcomplex.systems.biology.ecology import FoodWebsSystem
  • Field: biology/ecology
  • Topics: food web, predator-prey, ode
  • References:
    • Argun et al. 2021
    • Pimm 1982

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 FoodWebsSystem

trajectory = FoodWebsSystem().prepare().simulate()

Parameters

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

Parameter Default
populations None
growth None
mortality None
links 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 FoodWebsSystem(BaseSystem):
    """A food web of logistic basal species and Lotka-Volterra consumers.

    The basal species grow logistically and the consumers live on Lotka-Volterra predation.

    The default web has frogs and mice at its base, snakes that eat frogs and mice, and hawks that eat snakes and mice.
    Its four species coexist at a stable equilibrium. The system has one population per species.

    Args:
        populations:
            The initial size of every species by name, or `None` for the default web.

        growth:
            The growth rate and the carrying capacity of every basal species, or `None` for the default web.

        mortality:
            The death rate of every consumer, or `None` for the default web.

        links:
            The links `(predator, prey, a, b)`, with the attack rate `a` and the conversion rate `b`, or `None` for the
            default web.

        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 FoodWebsSystem
        >>> [element.label for element in FoodWebsSystem().prepare().system_.elements]
        ['frogs', 'mice', 'snakes', 'hawks']
    """

    field = 'biology/ecology'
    topics = ('food web', 'predator-prey', 'ode')
    references = ('Argun et al. 2021', 'Pimm 1982')
    until = 100.0
    dt = 0.5

    def __init__(
        self,
        populations: Mapping[str, float] | None = None,
        *,
        growth: Mapping[str, tuple[float, float]] | None = None,
        mortality: Mapping[str, float] | None = None,
        links: Sequence[tuple[str, str, float, float]] | None = None,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.populations = populations
        self.growth = growth
        self.mortality = mortality
        self.links = links

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of a food web.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        populations = self.populations
        growth = self.growth
        mortality = self.mortality
        links = self.links
        populations = WEB_POPULATIONS if populations is None else populations
        growth = WEB_GROWTH if growth is None else growth
        mortality = WEB_MORTALITY if mortality is None else mortality
        links = WEB_LINKS if links is None else links
        interactions: list[BaseInteraction] = [
            LogisticGrowthInteraction(f'growth_{name}', target=name, r=r, K=K) for name, (r, K) in growth.items()
        ]
        interactions += [MortalityInteraction(f'death_{name}', target=name, d=d) for name, d in mortality.items()]
        interactions += [
            PredationInteraction(f'{predator}_eat_{prey}', predator=predator, prey=prey, a=a, b=b)
            for predator, prey, a, b in links
        ]
        self.system_ = System(
            self.label,
            elements=[PopulationElement(name, x=n) for name, n in populations.items()],
            interactions=interactions,
        )

Components

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

Elements:

Interactions:

  • LogisticGrowthInteraction, from Interaction
  • MortalityInteraction, from Interaction
  • PredationInteraction, 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 LogisticGrowthInteraction(GrowthInteraction):
    """Verhulst's growth limited by a carrying capacity, without harvest.

    The population follows `dx/dt = r x (1 - x(t - tau) / K)`.

    A delay `tau` above 0 gives Hutchinson's delayed logistic equation. The generalized logistic of Richards, with an
    exponent on the crowding, is `GrowthInteraction(form='logistic', p=...)`.

    Args:
        label:
            The label of the interaction.

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

        r:
            The per capita growth rate at low density.

        K:
            The carrying capacity.

        tau:
            The delay of the limiting factor, 0 for none.

        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 LogisticGrowthInteraction
        >>> system = System(
        ...     elements=[CompartmentElement('rabbits', x=1.0)],
        ...     interactions=[LogisticGrowthInteraction('growth', target='rabbits', r=1.0, K=50.0)],
        ... )
        >>> trajectory = system.prepare().simulate(until=30.0, dt=0.1)
        >>> round(float(trajectory.get_values('rabbits.x')[-1]), 3)
        50.0
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        r: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        K: Annotated[float, RealSet.open(0, oo)] = 100.0,
        tau: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        state: str = 'x',
    ) -> None:
        super().__init__(label, target=target, r=r, K=K, tau=tau, form='logistic', state=state)

    def _get_crowding(self, namespace: SimpleNamespace) -> Expression:
        """Return the crowding `x / K` of Verhulst's logistic.

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

        Returns:
            crowding:
                The ratio of the population the limiting factor reads to the capacity.
        """
        crowding: Expression = self._get_limited(namespace) / self._get_capacity(namespace)
        return crowding

    def _get_rate(self, namespace: SimpleNamespace) -> Expression:
        """Return the logistic growth, 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 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

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)]

Equations

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

frogs.x: diff(x_frogs(t), t) == -r_growth_frogs*(x_frogs(t)/K_growth_frogs - 1)*x_frogs(t) - a_snakes_eat_frogs*x_frogs(t)*x_snakes(t)
mice.x: diff(x_mice(t), t) == -r_growth_mice*(x_mice(t)/K_growth_mice - 1)*x_mice(t) - a_hawks_eat_mice*x_hawks(t)*x_mice(t) - a_snakes_eat_mice*x_mice(t)*x_snakes(t)
snakes.x: diff(x_snakes(t), t) == b_snakes_eat_frogs*x_frogs(t)*x_snakes(t) - a_hawks_eat_snakes*x_hawks(t)*x_snakes(t) + b_snakes_eat_mice*x_mice(t)*x_snakes(t) - d_death_snakes*x_snakes(t)
hawks.x: diff(x_hawks(t), t) == b_hawks_eat_mice*x_hawks(t)*x_mice(t) + b_hawks_eat_snakes*x_hawks(t)*x_snakes(t) - d_death_hawks*x_hawks(t)