Skip to content

Spatial prisoner's dilemma with best-neighbour and Fermi imitation

The spatial prisoner's dilemma of Nowak and May.

  • Class: SpatialPrisonersDilemmaSystem
  • Import: from skcomplex.systems.social.cooperation import SpatialPrisonersDilemmaSystem
  • Field: social/cooperation
  • Topics: lattice, games, cooperation, evolution
  • References:
    • Nowak and May 1992
    • Szabó and Fáth 2007
    • Argun et al. 2021
    • Gros 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.social.cooperation import SpatialPrisonersDilemmaSystem

trajectory = SpatialPrisonersDilemmaSystem().prepare().simulate()

Parameters

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

Parameter Default
shape (50, 50)
temptation 1.85
imitation 'best'
noise 0.1
share 0.9
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 unknown
Domains boolean
Structure fixed

Class

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

class SpatialPrisonersDilemmaSystem(BaseSystem):
    """The spatial prisoner's dilemma of Nowak and May.

    The imitation is of the best neighbour or by the Fermi rule. The system has the strategies `players.strategy`.

    Args:
        shape:
            The number of rows and columns of the periodic lattice.

        temptation:
            The payoff of a defector against a cooperator.

        imitation:
            `'best'` to copy the best neighbour, or `'fermi'` to copy a random neighbour with the Fermi probability.

        noise:
            The noise of the Fermi imitation.

        share:
            The share of cooperators at the start.

        random_state:
            The seed or generator of the initial strategies.

        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.social.cooperation import SpatialPrisonersDilemmaSystem
        >>> SpatialPrisonersDilemmaSystem((10, 10)).prepare().system_.elements[0].strategy.size
        100
    """

    field = 'social/cooperation'
    topics = ('lattice', 'games', 'cooperation', 'evolution')
    references = ('Nowak and May 1992', 'Szabó and Fáth 2007', 'Argun et al. 2021', 'Gros 2015')
    until = 50
    dt = 1

    @staticmethod
    def _get_random_strategies(
        shape: Sequence[int],
        share: float,
        random_state: int | np.random.Generator | None,
    ) -> Array:
        """Return strategies that are 1, cooperation, with a probability.

        The other strategies are 0, defection.
        """
        return (np.random.default_rng(random_state).random(tuple(shape)) < share).astype(float)

    def __init__(
        self,
        shape: Sequence[int] = (50, 50),
        *,
        temptation: float = 1.85,
        imitation: str = 'best',
        noise: float = 0.1,
        share: float = 0.9,
        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.temptation = temptation
        self.imitation = imitation
        self.noise = noise
        self.share = share
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_` to the components built from the model parameters."""
        super()._prepare(context)
        players = PrisonerElement(
            'players',
            strategy=SpatialPrisonersDilemmaSystem._get_random_strategies(
                self.shape,
                self.share,
                self.random_state,
            ),
            temptation=self.temptation,
            noise=self.noise,
            space=LatticeSpace(tuple(self.shape)),
        )
        self.system_ = System(
            self.label,
            elements=[players],
            interactions=[PrisonersDilemmaInteraction('play', target='players', imitation=self.imitation)],
        )

Components

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

Elements:

Interactions:

  • PrisonersDilemmaInteraction, from Interaction
class PrisonerElement(Element):
    """Player of the spatial prisoner's dilemma, a cooperator at 1 and a defector at 0.

    The play and the imitation are a `PrisonersDilemmaInteraction` of the lattice, which `SpatialPrisonersDilemmaSystem`
    adds.

    Args:
        label:
            The label of the player or the lattice group.

        strategy:
            The initial strategy, 1 or 0.

        temptation:
            The payoff of a defector against a cooperator.

        noise:
            The noise of the Fermi imitation.

        space:
            The space with one member per site, or `None` for one member.

    Examples:
        >>> from skcomplex.systems.social.cooperation import PrisonerElement
        >>> PrisonerElement('player').temptation
        1.85
    """

    def __init__(
        self,
        label: str,
        *,
        strategy: Annotated[object, FiniteEnumeratedSet([0, 1])] = 1.0,
        temptation: Annotated[object, RealSet.closed_open(0, oo)] = 1.85,
        noise: Annotated[object, RealSet.open(0, oo)] = 0.1,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.strategy = strategy
        self.temptation = temptation
        self.noise = noise

class PrisonersDilemmaInteraction(Interaction):
    """Play of the weak prisoner's dilemma between neighbours.

    The play is followed by imitation of more successful neighbours. It is a stochastic local rule of the strategies
    over the 5 by 5 square around a player, a cooperator at 1 and a defector at 0. Every step each player
    plays the weak dilemma, with reward 1, temptation `temptation`, and 0 otherwise, against itself and its eight
    neighbours. It then copies the best player among them, or a random neighbour with the Fermi probability
    `1 / (1 + exp((P_own - P_other) / noise))`. The temptation and the noise are parameters of the players.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the players on the lattice.

        imitation:
            `'best'` for the best neighbour, or `'fermi'` for the Fermi rule.

    Raises:
        ValidationError:
            The imitation is unknown, raised by `prepare`.

    Examples:
        >>> from skcomplex.systems.social.cooperation import PrisonersDilemmaInteraction
        >>> PrisonersDilemmaInteraction('play', target='players', imitation='fermi').imitation
        'fermi'
    """

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

    def _check_arguments(self) -> None:
        """Raise an error for an unknown imitation.

        Raises:
            ValidationError:
                The imitation is unknown.
        """
        super()._check_arguments()
        if self.imitation not in IMITATIONS:
            error_msg = f'Unknown imitation {self.imitation!r}. Use one of {", ".join(IMITATIONS)}.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the play and the imitation as the law.

        Args:
            context:
                The namespace of the players.
        """
        super()._prepare(context)
        strategy = context.target.strategy
        self.laws_: list[BaseLaw] = [
            UpdateLaw(strategy, self._play, neighborhood=SQUARE, label=self.label, stochastic=True),
        ]

    def _play(
        self,
        *values: Array,
        temptation: float | Array,
        noise: float | Array,
        random: Array,
        **kwargs: object,
    ) -> Array:
        """Return the strategies after the play and the imitation.

        Every player plays against its neighbours.
        """
        cells = dict(zip(SQUARE.offsets, values, strict=True))

        def payoff(center: Pair) -> Array:
            own = cells[center]
            around = sum(cells[PrisonersDilemmaInteraction._shift(center, offset)] for offset in (*MOORE, ORIGIN))
            return own * around + (1 - own) * around * temptation

        payoffs = [payoff(offset) for offset in MOORE]
        strategies = [cells[offset] for offset in MOORE]
        if self.imitation == 'best':
            return PrisonersDilemmaInteraction._imitate_best(cells[ORIGIN], payoff(ORIGIN), payoffs, strategies)
        return PrisonersDilemmaInteraction._imitate_fermi(
            cells[ORIGIN],
            payoff(ORIGIN),
            payoffs,
            strategies,
            noise=noise,
            random=random,
        )

    @staticmethod
    def _shift(first: Pair, second: Pair) -> Pair:
        """Return the sum of two offsets."""
        return first[0] + second[0], first[1] + second[1]

    @staticmethod
    def _imitate_fermi(
        own: Array,
        own_payoff: Array,
        payoffs: list[Array],
        strategies: list[Array],
        *,
        noise: float | Array,
        random: Array,
    ) -> Array:
        """Return the strategy of a random neighbour with the Fermi probability.

        The probability is `1 / (1 + exp((P_own - P_other) / noise))`.
        """
        count = len(payoffs)
        chosen = np.minimum((random * count).astype(int), count - 1)
        uniform = random * count - chosen
        picked = np.take_along_axis(np.stack(payoffs), chosen[None], axis=0)[0]
        strategy = np.take_along_axis(np.stack(strategies), chosen[None], axis=0)[0]
        exponent = np.clip((own_payoff - picked) / np.maximum(noise, 1e-12), -50, 50)
        return np.where(uniform < 1 / (1 + np.exp(exponent)), strategy, own)

    @staticmethod
    def _imitate_best(own: Array, own_payoff: Array, payoffs: list[Array], strategies: list[Array]) -> Array:
        """Return the strategy of the largest payoff among a player and its neighbours.

        Ties keep its own.
        """
        best, following = own_payoff.copy(), own.copy()
        for payoff, strategy in zip(payoffs, strategies, strict=True):
            following = np.where(payoff > best, strategy, following)
            best = np.maximum(best, payoff)
        return following