Skip to content

Replicator dynamics and hawks and doves

The replicator dynamics of a game, by default hawks and doves.

  • Class: ReplicatorDynamicsSystem
  • Import: from skcomplex.systems.biology.evolution import ReplicatorDynamicsSystem
  • Field: biology/evolution
  • Topics: evolutionary game, replicator, ode, game theory
  • References:
    • Taylor and Jonker 1978
    • Maynard Smith 1982
    • Gros 2015
    • Szabó and Fáth 2007

The replicator_dynamics example

Example

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.evolution import ReplicatorDynamicsSystem

trajectory = ReplicatorDynamicsSystem().prepare().simulate()

Parameters

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

Parameter Default
x None
payoff None
V 2.0
C 3.0
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 ReplicatorDynamicsSystem(BaseSystem):
    """The replicator dynamics of a game, by default hawks and doves.

    Hawks and doves settle at a share `V / C` of hawks.

    Every strategy is a member of the group `population`, and it grows with its payoff above the mean payoff. The hawks
    and doves game has the payoff matrix `((V - C) / 2, V), (0, V / 2)` with hawks first. When the cost of a fight `C`
    exceeds the value `V`, hawks and doves coexist with `V / C` hawks, and otherwise hawks take over. A payoff matrix
    gives any other game, such as the prisoner's dilemma or rock, paper, scissors. The system has the shares
    `population.x` of the strategies, hawks first.

    Args:
        x:
            The initial shares of the strategies, or `None` for equal shares.

        payoff:
            The payoff matrix of another game, one row per strategy, or `None` for hawks and doves.

        V:
            The value of the resource contested by hawks and doves.

        C:
            The cost of a fight between hawks.

        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.evolution import ReplicatorDynamicsSystem
        >>> system = ReplicatorDynamicsSystem(payoff=((0, -1, 1), (1, 0, -1), (-1, 1, 0))).prepare().system_
        >>> system.elements[0].size
        3
    """

    field = 'biology/evolution'
    topics = ('evolutionary game', 'replicator', 'ode', 'game theory')
    references = ('Taylor and Jonker 1978', 'Maynard Smith 1982', 'Gros 2015', 'Szabó and Fáth 2007')
    until = 30.0
    dt = 0.1

    def __init__(
        self,
        x: Sequence[float] | None = None,
        *,
        payoff: Sequence[Sequence[float]] | None = None,
        V: float = 2.0,
        C: float = 3.0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.x = x
        self.payoff = payoff
        self.V = V
        self.C = C

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

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        matrix = (
            (((self.V - self.C) / 2, self.V), (0.0, self.V / 2))
            if self.payoff is None
            else tuple(tuple(row) for row in self.payoff)
        )
        strategies = len(matrix)
        shares = [1 / strategies] * strategies if self.x is None else list(self.x)
        population = StrategyElement('population', x=shares, size=strategies)
        weights = np.asarray(matrix, dtype=float)
        replication = ReplicatorInteraction(
            'replication',
            target='population',
            fitness=lambda s: total(s.target.x, weights=weights),
        )
        self.system_ = System(self.label, elements=[population], interactions=[replication])

Components

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

Elements:

Interactions:

  • ReplicatorInteraction, from Interaction
class StrategyElement(Element):
    """Strategy of an evolutionary game, with the share `x` of players.

    The share is the one of the population that plays the strategy.

    Args:
        label:
            The label of the strategy or of the group of strategies.

        x:
            The initial share, one per strategy or shared.

        size:
            The number of strategies, or `None` for one.

    Examples:
        >>> from skcomplex.systems.biology.evolution import StrategyElement
        >>> StrategyElement('hawks', x=0.4).x
        0.4
    """

    def __init__(
        self,
        label: str,
        *,
        x: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
        size: int | None = None,
    ) -> None:
        super().__init__(label, size=size)
        self.x = x

class ReplicatorInteraction(Interaction):
    """Replicator equation of the shares of a group, with a fitness `f`.

    The shares follow `dx_i/dt = x_i (f_i - sum_j x_j f_j)`.

    Every member of the group holds the share of a type, such as a strategy or a molecule. Its share grows with its
    fitness above the mean fitness of the group, so the total of the shares stays constant.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of types.

        fitness:
            The function of the namespace that returns the fitness of a member, such as
            `lambda s: total(s.target.x, weights=payoff)` for the payoff of a strategy against the others.

        state:
            The name of the state of the members that holds the share.

    Raises:
        ValidationError:
            The fitness is not callable, raised by `prepare`.

    Examples:
        >>> from skcomplex.core.components.laws.utils import total
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.evolution import ReplicatorInteraction, StrategyElement
        >>> population = StrategyElement('population', x=[0.5, 0.5], size=2)
        >>> payoff = ((1.0, 1.0), (0.0, 0.0))
        >>> replication = ReplicatorInteraction(
        ...     'replication', target='population', fitness=lambda s: total(s.target.x, weights=payoff)
        ... )
        >>> system = System(elements=[population], interactions=[replication])
        >>> trajectory = system.prepare().simulate(until=20.0, dt=0.1)
        >>> [round(float(share), 3) for share in trajectory.get_values('population.x')[-1]]
        [1.0, 0.0]
    """

    law_classes = (RateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        fitness: Callable[[SimpleNamespace], object] | None = None,
        state: str = 'x',
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.fitness = fitness

    def _check_fitness(self) -> None:
        """Raise an error for a fitness that is not callable.

        It is the hook a subclass that derives its fitness overrides.
        """
        if not callable(self.fitness):
            error_msg = f'The fitness of {self.label!r} is {self.fitness!r}. Give a function of the namespace.'
            raise ValidationError(error_msg)

    def _check_arguments(self) -> None:
        """Raise an error for a state, functions, or a fitness the interaction cannot take.

        Raises:
            ValidationError:
                The state is not a name, or the fitness is not callable.
        """
        super()._check_arguments()
        self._check_fitness()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = [RateLaw(getattr(context.target, self.state), self._get_rate(context))]

    def _get_fitness(self, namespace: SimpleNamespace) -> Expression:
        """Return the fitness of a member.

        It is the hook a subclass overrides to derive it from its parameters.
        """
        fitness = self.fitness
        if fitness is None:
            error_msg = f'The fitness of {self.label!r} is missing. Give a function of the namespace.'
            raise ValidationError(error_msg)
        value: Expression = fitness(namespace)
        return value

    def _get_rate(self, namespace: SimpleNamespace) -> Expression:
        """Return the replicator rate `x_i (f_i - sum_j x_j f_j)`.

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

        Returns:
            rate:
                The rate of the share.
        """
        share = getattr(namespace.target, self.state)
        fitness = self._get_fitness(namespace)
        rate: Expression = share * (fitness - total(share * fitness))
        return rate

Equations

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

population.x[i]: diff(x_population(t), t) == (_reduced_0 - _reduced_1)*x_population(t)