Algorithm Search⌘K

Modeladvanced

Replicator dynamics

Also called replicator equation.

A differential equation in which the share of each strategy in a population grows at a rate equal to its payoff minus the average payoff.

The replicator dynamics is a differential equation for the shares of the types in a large population: the share of a type grows when its fitness is above the mean fitness of the population and shrinks when it is below, at a rate equal to its share times the difference. In evolutionary game theory, the fitness of a type is its expected payoff in random encounters with the population, so it depends on the shares of all types; this is frequency-dependent selection. With fitnesses that do not depend on the shares it is the haploid selection equation, and with a symmetric payoff matrix it is the continuous-time selection equation at one diploid locus, for which Fisher's fundamental theorem holds. Taylor and Jonker (1978) introduced it as the dynamic counterpart of the evolutionarily stable strategy, which is a static test, and every such strategy is an asymptotically stable rest point of the equation.

The machine

The state. A population has nn types, or pure strategies, 1,…,n1, \ldots, n. The state is the vector of shares x=(x1,…,xn)x = (x_1, \ldots, x_n) in the simplex Δn={x:xi≥0, ∑ixi=1}\Delta_n = \{x : x_i \ge 0,\ \sum_i x_i = 1\}. A strategy here is a fixed behaviour of an individual, inherited by its offspring; nobody chooses.

The payoffs. An n×nn \times n matrix AA gives the payoff AijA_{ij} of type ii when it meets type jj. Individuals meet in random pairs, so the fitness of type ii is fi(x)=(Ax)if_i(x) = (Ax)_i, and the mean fitness is fˉ(x)=xTAx=∑ixifi(x)\bar f(x) = x^{\mathsf T} A x = \sum_i x_i f_i(x). Payoffs are increments of the growth rate over a common background rate.

The equation.

x˙i=xi((Ax)i−xTAx),i=1,…,n.\dot x_i = x_i \big( (Ax)_i - x^{\mathsf T} A x \big), \qquad i = 1, \ldots, n.

It follows from the growth of the absolute numbers: if type ii has NiN_i individuals and grows at the rate β+fi\beta + f_i, then xi=Ni/∑jNjx_i = N_i / \sum_j N_j satisfies this equation, and the background rate β\beta cancels.

Standing assumptions. The population is infinite, so there is no drift; it is well mixed, with random pairing; time is continuous and generations overlap; reproduction is asexual or the types are alleles at one locus with no other effects. For finite populations with random sampling, see the Wright-Fisher model.

Basic properties.

  • The simplex is invariant, and so is each face: a type with share 0 stays at 0, so the equation cannot create a new type. Each vertex is a rest point.
  • The rest points are the states xx at which every type in the support of xx has the same fitness.
  • Adding a constant to a column of AA does not change the orbits in Δn\Delta_n, since it adds the same number to every fif_i and to fˉ\bar f.
  • The right-hand side is a polynomial, so by the theory of the initial value problem each start has a unique solution, defined for all times.

What it counts

The model predicts the shares x(t)x(t) over time, and in particular where they end: at which rest points, cycles or other limit sets, and from which starts. The questions are the stability of rest points, the size of their basins, the mean fitness fˉ\bar f along the way, and how these compare with the static notions of game theory: Nash equilibrium and ESS.

A closed form. For two types with A=(1100)A = \begin{pmatrix} 1 & 1 \\ 0 & 0 \end{pmatrix}, type 1 always earns 1 more, and x˙1=x1(1−x1)\dot x_1 = x_1 (1 - x_1). This is the logistic equation, with the solution x1(t)=x1(0)et/(1−x1(0)+x1(0)et)x_1(t) = x_1(0) e^t / (1 - x_1(0) + x_1(0) e^t).

Numerical solution. In general the equation has no closed form, and it is solved with a fixed step by the classical Runge-Kutta method of order 4:

  1. REPLICATOR-RK4(A, x, h, T) ▷ T steps of size h from the shares x
  2. 1for t ← 1 to T
  3. 2k1 ← F(x)
  4. 3k2 ← F(x + (h/2) k1)
  5. 4k3 ← F(x + (h/2) k2)
  6. 5k4 ← F(x + h k3)
  7. 6x ← x + (h/6)(k1 + 2 k2 + 2 k3 + k4)
  8. 7return x
  9. F(x) ▷ the right-hand side
  10. 8f ← A x
  11. 9φ ← (Σ_i x_i f_i) / (Σ_i x_i)
  12. 10return (x_i (f_i - φ))_i

Each step costs 4 evaluations of FF, each O(n2)O(n^2). On the simplex the denominator in L9 is 1, so this is the equation above. Off the simplex it makes the entries of FF sum to exactly 0, so ∑ixi\sum_i x_i stays 1 up to rounding. Without it, rounding errors in ∑ixi\sum_i x_i grow like e−fˉte^{-\bar f t} near a rest point with fˉ<0\bar f < 0. The global error of the method is O(h4)O(h^4) on a fixed time interval. The implementation is in float. Its tests check the logistic closed form to 10−910^{-9}, the order 4 (halving hh divides the error by about 16), and each example below.

Relation to other models

  • Population genetics. With constant fitnesses, fif_i not depending on xx, the equation is the selection equation for haploid types, whose solution moves all weight to the fittest of the types present at the start. With a symmetric matrix AA of genotype fitnesses at one locus, xx is the vector of allele frequencies under random mating (Hardy-Weinberg proportions), and the equation is the continuous-time selection equation. Adding mutation gives the replicator-mutator equation, whose rest points describe a mutation-selection balance.
  • Lotka-Volterra equations. The replicator equation for nn types is equivalent, by a change of variables and of the time scale, to a Lotka-Volterra equation for n−1n - 1 species (Hofbauer and Sigmund 1998). So results move between the two.
  • Learning. The update xi←xieηfi(x)/∑jxjeηfj(x)x_i \leftarrow x_i e^{\eta f_i(x)} / \sum_j x_j e^{\eta f_j(x)} of multiplicative weights has the first-order expansion xi+ηxi(fi−fˉ)x_i + \eta x_i (f_i - \bar f), so the replicator equation is its limit as the step η→0\eta \to 0.
  • Two populations. For a bimatrix game (A,B)(A, B), one population plays rows and another columns: x˙i=xi((Ay)i−xTAy)\dot x_i = x_i((Ay)_i - x^{\mathsf T} A y) and y˙j=yj((BTx)j−xTBy)\dot y_j = y_j((B^{\mathsf T} x)_j - x^{\mathsf T} B y).
  • Discrete time. The map xi←xifi(x)/fˉ(x)x_i \leftarrow x_i f_i(x) / \bar f(x), for positive payoffs, is the discrete-time replicator dynamics. Its stability properties can differ from those of the continuous equation.

Known results in the model

  • Nash equilibria and rest points (Hofbauer and Sigmund 1998, Chapter 7). If (x,x)(x, x) is a symmetric Nash equilibrium, xx is a rest point; the converse fails, since every vertex is a rest point. A rest point that is Lyapunov stable is a Nash equilibrium, and so is the limit of an orbit that starts in the interior and converges. A strict equilibrium is asymptotically stable.
  • ESS are asymptotically stable. Every evolutionarily stable state is an asymptotically stable rest point (Taylor and Jonker 1978 for regular ESS; Hofbauer and Sigmund 1998, Theorem 7.2.4). For an ESS x^\hat x, the relative entropy ∑i:x^i>0x^ilog⁡(x^i/xi)\sum_{i : \hat x_i > 0} \hat x_i \log(\hat x_i / x_i) decreases along orbits near x^\hat x, so it is a Lyapunov function. An interior ESS attracts every orbit that starts in the interior. In the Hawk-Dove game, A=(−1201)A = \begin{pmatrix} -1 & 2 \\ 0 & 1 \end{pmatrix}, the share qq of Hawks follows q˙=q(1−q)(1−2q)\dot q = q(1 - q)(1 - 2q), and every interior start goes to the ESS q=1/2q = 1/2.
  • The converse is false. For
A=(06−4−305−130),A = \begin{pmatrix} 0 & 6 & -4 \\ -3 & 0 & 5 \\ -1 & 3 & 0 \end{pmatrix},

the centre c=(1/3,1/3,1/3)c = (1/3, 1/3, 1/3) has Ac=(2/3,2/3,2/3)Ac = (2/3, 2/3, 2/3), so it is a rest point and a Nash equilibrium. For z=(1,0,−1)z = (1, 0, -1), zTAz=5>0z^{\mathsf T} A z = 5 > 0, so the mutant y=c+δzy = c + \delta z gets u(y,y)−u(c,y)=5δ2>0u(y, y) - u(c, y) = 5\delta^2 > 0, and cc is not an ESS. Yet the linearization at cc, in the coordinates (x1,x2)(x_1, x_2), has trace −2/3-2/3 and determinant 1/31/3, so its eigenvalues are −1/3±i2/3-1/3 \pm i\sqrt{2}/3, and cc is asymptotically stable. The vertex e1e_1 is a strict equilibrium and attracts other orbits: the run from (0.4,0.3,0.3)(0.4, 0.3, 0.3) goes to cc, and the run from (0.8,0.1,0.1)(0.8, 0.1, 0.1) goes to e1e_1.

  • Dominated strategies die out. If type ii is strictly dominated by type jj, then xi/xj→0x_i / x_j \to 0 along every interior orbit, since ddtlog⁡(xi/xj)=fi−fj\frac{d}{dt} \log(x_i / x_j) = f_i - f_j stays below a negative constant. In the prisoner's dilemma, the share of cooperators tends to 0.
  • Cycles. In rock, paper, scissors, with 1 for a win, −1-1 for a loss and 0 for a tie, ddtlog⁡(x1x2x3)=∑ifi−3fˉ=0\frac{d}{dt}\log(x_1 x_2 x_3) = \sum_i f_i - 3\bar f = 0, because the columns of AA sum to 0 and xTAx=0x^{\mathsf T} A x = 0. So x1x2x3x_1 x_2 x_3 is constant along orbits, and every interior orbit other than the centre is a closed cycle. If each tie costs ε\varepsilon, so AA has −ε-\varepsilon on the diagonal, then ddtlog⁡(x1x2x3)=ε(3∥x∥2−1)\frac{d}{dt}\log(x_1x_2x_3) = \varepsilon(3\lVert x \rVert^2 - 1). For ε>0\varepsilon > 0 the product rises and orbits go to the centre, which is then an ESS; for ε<0\varepsilon < 0 it falls and orbits spiral out toward the boundary.
  • Fisher's fundamental theorem. If AA is symmetric, ddtfˉ=2∑ixi(fi−fˉ)2\frac{d}{dt} \bar f = 2 \sum_i x_i (f_i - \bar f)^2, twice the variance of the fitness, so the mean fitness never decreases and is a Lyapunov function. For a non-symmetric AA the mean fitness can fall, as in the prisoner's dilemma, where it drops from 3 to 1 as defectors take over.
  • Two populations. In the two-population dynamics of a bimatrix game, an interior rest point is never asymptotically stable, because after a change of the time scale the flow keeps volumes in the interior (Hofbauer and Sigmund 1998). This is one reason the one-population and two-population models give different predictions.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

replicator_dynamics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/replicator-dynamics/. The authors are listed in prov/DA7ATV.jsonl.

"""Replicator dynamics x_i' = x_i ((A x)_i - x^T A x), solved by RK4 with a fixed step.

A is a square payoff matrix given as a list of rows, and x is a list of shares
that sum to 1. The computation is in float; the tests state their tolerances.
"""


def fitness(A, x):
    """The payoff vector A x."""
    return [sum(a * xj for a, xj in zip(row, x)) for row in A]


def mean_fitness(A, x):
    """The mean payoff x^T A x of the population."""
    return sum(xi * fi for xi, fi in zip(x, fitness(A, x)))


def replicator_field(A, x):
    """The right-hand side F(x) of the replicator equation.

    The mean is divided by sum(x), which is 1 on the simplex. Then the entries of
    F(x) sum to exactly 0 for every x, so rounding errors in sum(x) do not grow.
    """
    f = fitness(A, x)  # @line L8
    phi = sum(xi * fi for xi, fi in zip(x, f)) / sum(x)  # @line L9
    return [xi * (fi - phi) for xi, fi in zip(x, f)]  # @line L10


def _axpy(x, h, k):
    return [xi + h * ki for xi, ki in zip(x, k)]


def rk4_step(A, x, h):
    """One step of the classical Runge-Kutta method of order 4."""
    k1 = replicator_field(A, x)  # @line L2
    k2 = replicator_field(A, _axpy(x, h / 2, k1))  # @line L3
    k3 = replicator_field(A, _axpy(x, h / 2, k2))  # @line L4
    k4 = replicator_field(A, _axpy(x, h, k3))  # @line L5
    return [  # @line L6
        xi + h / 6 * (a + 2 * b + 2 * c + d)
        for xi, a, b, c, d in zip(x, k1, k2, k3, k4)
    ]


def replicator_rk4(A, x0, h, steps, record=False):
    """Run `steps` RK4 steps of size h from x0.

    Returns the final state, or the list of all states (x0 first) if record is true.
    """
    x = list(map(float, x0))
    path = [x] if record else None
    for _ in range(steps):  # @line L1
        x = rk4_step(A, x, h)
        if record:
            path.append(x)
    return path if record else x  # @line L7
test_replicator_dynamics.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/replicator-dynamics/. The authors are listed in prov/DA7ATV.jsonl.

import math
import random
from fractions import Fraction as F

from replicator_dynamics import fitness, mean_fitness, replicator_field, replicator_rk4, rk4_step

HAWK_DOVE = [[-1, 2], [0, 1]]
PRISONERS_DILEMMA = [[3, 0], [5, 1]]  # strategies C, D
RPS = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]
ZEEMAN = [[0, 6, -4], [-3, 0, 5], [-1, 3, 0]]


def dist(x, y):
    return max(abs(a - b) for a, b in zip(x, y))


def test_logistic_closed_form() -> None:
    # With A = [[1, 1], [0, 0]], x_1' = x_1 (1 - x_1), the logistic equation.
    A = [[1, 1], [0, 0]]
    h, steps = 0.01, 500
    for x0 in (0.01, 0.3, 0.9):
        path = replicator_rk4(A, [x0, 1 - x0], h, steps, record=True)
        for k in (100, 250, 500):
            t = k * h
            exact = x0 * math.exp(t) / (1 - x0 + x0 * math.exp(t))
            assert abs(path[k][0] - exact) < 1e-9
            assert abs(sum(path[k]) - 1) < 1e-12


def test_hawk_dove_goes_to_the_ess() -> None:
    # q' = q (1 - q) (1 - 2q), so every interior start goes to q = 1/2.
    for q0 in (0.05, 0.4, 0.9):
        x = replicator_rk4(HAWK_DOVE, [q0, 1 - q0], 0.05, 1200)
        assert dist(x, [0.5, 0.5]) < 1e-9
    # The vertices are rest points, but not stable.
    assert replicator_field(HAWK_DOVE, [1.0, 0.0]) == [0.0, 0.0]


def test_prisoners_dilemma_cooperation_dies_out() -> None:
    path = replicator_rk4(PRISONERS_DILEMMA, [0.99, 0.01], 0.05, 800, record=True)
    shares = [x[0] for x in path]
    assert all(b < a for a, b in zip(shares, shares[1:]))
    assert shares[-1] < 1e-6


def test_rock_paper_scissors_keeps_the_product() -> None:
    x0 = [0.5, 0.3, 0.2]
    p0 = x0[0] * x0[1] * x0[2]
    path = replicator_rk4(RPS, x0, 0.01, 3000, record=True)
    for x in path[::100]:
        assert abs(x[0] * x[1] * x[2] - p0) < 1e-8 * p0
    # The orbit is closed and does not approach the centre.
    assert min(dist(x, [1 / 3] * 3) for x in path) > 0.05


def test_rock_paper_scissors_with_a_cost_or_bonus_for_ties() -> None:
    for eps in (0.2, -0.2):
        A = [[RPS[i][j] - (eps if i == j else 0) for j in range(3)] for i in range(3)]
        path = replicator_rk4(A, [0.5, 0.3, 0.2], 0.05, 8000, record=True)
        prods = [x[0] * x[1] * x[2] for x in path]
        if eps > 0:  # the centre is an ESS: the product rises to 1/27
            assert all(b >= a - 1e-13 for a, b in zip(prods, prods[1:]))
            assert dist(path[-1], [1 / 3] * 3) < 1e-6
        else:  # the product falls and the orbit moves to the boundary
            assert all(b <= a + 1e-13 for a, b in zip(prods, prods[1:]))
            assert prods[-1] < 1e-3


def test_fisher_mean_fitness_rises_at_twice_the_variance() -> None:
    rng = random.Random(3)
    for _ in range(5):
        n = 4
        A = [[0.0] * n for _ in range(n)]
        for i in range(n):
            for j in range(i, n):
                A[i][j] = A[j][i] = rng.uniform(-1, 1)
        w = [rng.uniform(0.1, 1) for _ in range(n)]
        x = [v / sum(w) for v in w]
        h = 1e-3
        for _ in range(4):
            f, phi = fitness(A, x), mean_fitness(A, x)
            var = sum(xi * (fi - phi) ** 2 for xi, fi in zip(x, f))
            slope = (mean_fitness(A, rk4_step(A, x, h)) - mean_fitness(A, rk4_step(A, x, -h))) / (2 * h)
            assert abs(slope - 2 * var) < 1e-6
            x = replicator_rk4(A, x, 0.05, 100)
        path = replicator_rk4(A, x, 0.05, 400, record=True)
        phis = [mean_fitness(A, y) for y in path]
        assert all(b >= a - 1e-12 for a, b in zip(phis, phis[1:]))


def test_zeeman_stable_rest_point_that_is_not_an_ess() -> None:
    c = [F(1, 3)] * 3
    Ac = [sum(F(a) * x for a, x in zip(row, c)) for row in ZEEMAN]
    assert Ac == [F(2, 3)] * 3  # the centre is a rest point and a Nash equilibrium
    # The mutant y = c + d z with z = (1, 0, -1) does better against itself:
    # u(c, y) - u(y, y) = -d^2 z^T A z, and z^T A z = 5.
    z = [1, 0, -1]
    for d in (F(1, 10), F(1, 100)):
        y = [ci + d * zi for ci, zi in zip(c, z)]
        Ay = [sum(F(a) * v for a, v in zip(row, y)) for row in ZEEMAN]
        gap = sum((ci - yi) * v for ci, yi, v in zip(c, y, Ay))
        assert gap == -5 * d * d
    # Yet the centre attracts nearby orbits, and e_1, a strict equilibrium, attracts others.
    x = replicator_rk4(ZEEMAN, [0.4, 0.3, 0.3], 0.05, 2000)
    assert dist(x, [1 / 3] * 3) < 1e-9
    x = replicator_rk4(ZEEMAN, [0.8, 0.1, 0.1], 0.05, 2000)
    assert dist(x, [1.0, 0.0, 0.0]) < 1e-9


def test_rk4_order_four() -> None:
    # Halving the step divides the error at t = 2 by about 16.
    A = [[1, 1], [0, 0]]
    x0 = 0.2
    exact = x0 * math.exp(2) / (1 - x0 + x0 * math.exp(2))
    e1 = abs(replicator_rk4(A, [x0, 1 - x0], 0.2, 10)[0] - exact)
    e2 = abs(replicator_rk4(A, [x0, 1 - x0], 0.1, 20)[0] - exact)
    assert 12 < e1 / e2 < 20

References

  1. Peter D. Taylor and Leo B. Jonker, Evolutionarily stable strategies and game dynamics, Mathematical Biosciences 40(1-2) (1978), 145-156, the replicator equation for a population playing a symmetric game, and the asymptotic stability of a regular evolutionarily stable strategy
  2. Josef Hofbauer and Karl Sigmund, Evolutionary Games and Population Dynamics, Cambridge University Press, 1998, Chapter 7 (the replicator equation, Nash equilibria as rest points, and Theorem 7.2.4, every evolutionarily stable state is asymptotically stable)
  3. John Maynard Smith and George R. Price, The logic of animal conflict, Nature 246 (1973), 15-18, evolutionarily stable strategies, the static notion that the dynamics makes precise

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/DA7ATV/text.yaml