Algorithm Search⌘K

Algorithmintro

Best-response dynamics

Also called better-response dynamics, myopic best response.

Lets players in turn switch to a best response to the current pure profile. When it stops, the profile is a pure Nash equilibrium; in finite potential games it always stops.

Time
O(n k^(n+1)) worst
Space
O(n k^n) extra
Where
k = the largest number of pure strategies of a player; n = the number of players
Properties
deterministicexactofflineiterative
Origin
Antoine Augustin Cournot, Robert W. Rosenthal, Dov Monderer, Lloyd S. Shapley, 1838

Best-response dynamics is the simplest way for players to look for a pure Nash equilibrium: while some player can gain by a change of strategy, one such player switches to a best response to what the others play now. If the process stops, nobody can gain and the profile is a pure Nash equilibrium. In a finite potential game, such as an atomic congestion game, every switch raises the potential, so the process always stops. In a game without a pure equilibrium, such as matching pennies, it cycles. The better-response version lets a player move to any strictly better strategy, not only a best one; the finite improvement property is the statement that all such paths are finite. Unlike no-regret dynamics and fictitious play, the players here use only the current profile and play pure strategies.

In plain words

Several people each choose one option, and each person's reward depends on all the choices. Look at the current choices. If someone could do better by changing only their own choice, let one such person change to their best option. Then look again. Stop when nobody wants to change. At that point the choices are stable: every person already has the best option against the others. The process need not stop. In a game of guessing heads or tails, one player wants to match and the other wants to differ, and they chase each other for ever. In games where a single number goes up with every selfish change, the number cannot go up for ever, so the process stops.

The problem

The input is a finite game in normal form with players N={1,…,n}N = \{1, \ldots, n\}, pure strategy sets S1,…,SnS_1, \ldots, S_n with ∣Si∣≤k|S_i| \le k, and utilities ui:S→Qu_i : S \to \mathbb{Q} on S=S1×⋯×SnS = S_1 \times \cdots \times S_n, which each player maximizes. A cost game uses ui=−ciu_i = -c_i. A start profile s∈Ss \in S is also given. The set of pure best responses of player ii to s−is_{-i} is

BRi(s−i)=arg⁡max⁡b∈Siui(b,s−i).BR_i(s_{-i}) = \arg\max_{b \in S_i} u_i(b, s_{-i}).

A profile ss is a pure Nash equilibrium if si∈BRi(s−i)s_i \in BR_i(s_{-i}) for every ii. (For mixed strategies the same test reads: a mixed strategy is a best response if and only if its support lies in BRiBR_i. This page needs only pure strategies.) The output is a pure Nash equilibrium reached from ss, or the report that the dynamics cycle from ss.

The strategies of each player are numbered, and ties go to the smallest number. This makes the process deterministic, so that "it cycles" is a fact about the start profile.

The algorithm

  1. BEST-RESPONSE-DYNAMICS(G, s) ▷ G is a finite game, s a pure profile
  2. 1seen ← empty set
  3. 2repeat
  4. 3U ← the players i with s_i not in BR_i(s_-i)
  5. 4if U is empty then return (s, "equilibrium")
  6. 5if s is in seen then return (s, "cycle")
  7. 6add s to seen
  8. 7i ← the smallest player in U
  9. 8s_i ← the smallest strategy in BR_i(s_-i)

Line L3 finds the players who can gain by a change. A player whose current strategy is one of several best responses stays put; only a strict gain makes a player move. Line L4 stops at a pure Nash equilibrium. Lines L7 and L8 make one move. The next profile depends only on the current one, so if a profile comes back (line L5), the same sequence of moves repeats for ever and no equilibrium is reached from the start. The set seen of line L1 holds the profiles already left.

Other orders are common. In round-robin order the players take turns, and a player who cannot gain passes. In simultaneous best response all players switch at once, which can cycle even in a potential game: in a two-player coordination game started at a miscoordinated profile, both players switch at the same time and stay miscoordinated.

Example

Four players each choose one of two links, AA (strategy 0) or BB (strategy 1). A link used by xx players costs each of them xx. This is an atomic congestion game, and Rosenthal's potential is Φ(s)=∑e(1+2+⋯+xe)\Phi(s) = \sum_{e} (1 + 2 + \cdots + x_e), where xex_e is the load of link ee. The run starts with all four players on AA.

step profile loads (A, B) costs Φ\Phi U (line L3) move (lines L7, L8)
0 (A, A, A, A) (4, 0) (4, 4, 4, 4) 10 {1, 2, 3, 4} player 1 to B
1 (B, A, A, A) (3, 1) (1, 3, 3, 3) 7 {2, 3, 4} player 2 to B
2 (B, B, A, A) (2, 2) (2, 2, 2, 2) 6 empty return at line L4

Each move lowers the cost of the mover by the same amount as it lowers Φ\Phi: by 3 in step 1 and by 1 in step 2. In matching pennies, where the row player gets 1 on a match and the column player gets 1 on a mismatch, the run from (H, H) visits (H, T), (T, T), (T, H) and then (H, H) again, and line L5 reports a cycle. That game has no pure Nash equilibrium, so every start cycles.

Correctness

If the algorithm returns at line L4, no player can gain by a unilateral change, which is the definition of a pure Nash equilibrium. If it returns at line L5, the current profile was left before, and since the next profile is a function of the current one, the run from the start profile is periodic from that point and never meets a profile where line L4 returns. Each pass that does not return adds a new profile to seen, so there are at most ∣S∣|S| passes. In a finite game with a generalized ordinal potential PP, each move of line L8 strictly increases PP, so no profile repeats and the algorithm always returns an equilibrium. Congestion games have such a potential. The full proof is in the proof file.

Proof: Best-response dynamics returns a pure Nash equilibrium or a true cycle, and never cycles in a potential gamefull

Let GG be a finite game with players 1,…,n1, \ldots, n, pure strategy sets Si={0,…,∣Si∣−1}S_i = \{0, \ldots, |S_i| - 1\} and utilities uiu_i on S=S1×⋯×SnS = S_1 \times \cdots \times S_n. For a profile ss let U(s)U(s) be the set computed in line L3, the players ii with si∉BRi(s−i)s_i \notin BR_i(s_{-i}). When U(s)U(s) is not empty, let f(s)f(s) be the profile that lines L7 and L8 produce: the smallest i∈U(s)i \in U(s) switches to the smallest element of BRi(s−i)BR_i(s_{-i}). Let s0s^0 be the start profile and st+1=f(st)s^{t+1} = f(s^t) as long as U(st)U(s^t) is not empty.

Claim 1 (an equilibrium return is correct). If the algorithm returns (s,"equilibrium")(s, \text{"equilibrium"}), then ss is a pure Nash equilibrium.

Proof. The return happens at line L4, so U(s)U(s) is empty, that is, si∈BRi(s−i)s_i \in BR_i(s_{-i}) for every player ii. Then ui(s)=max⁡bui(b,s−i)≥ui(b,s−i)u_i(s) = \max_{b} u_i(b, s_{-i}) \ge u_i(b, s_{-i}) for every ii and every b∈Sib \in S_i, which is the definition of a pure Nash equilibrium. □\square

Claim 2 (the invariant). At the start of each pass of the loop, seen is the set {s0,…,st−1}\{s^0, \ldots, s^{t-1}\} and the current profile is sts^t, where tt is the number of earlier passes. Also s0,…,st−1s^0, \ldots, s^{t-1} are pairwise distinct.

Proof. By induction on tt. Initialization: before the first pass, seen is empty (line L1) and the profile is s0s^0. Maintenance: suppose the pass with profile sts^t does not return. Then U(st)U(s^t) is not empty (line L4) and st∉{s0,…,st−1}s^t \notin \{s^0, \ldots, s^{t-1}\} (line L5), so after line L6 seen is {s0,…,st}\{s^0, \ldots, s^t\}, a set of t+1t + 1 distinct profiles, and lines L7 and L8 set the profile to f(st)=st+1f(s^t) = s^{t+1}. □\square

Claim 3 (a cycle return is correct). If the algorithm returns (s,"cycle")(s, \text{"cycle"}) in the pass with profile sts^t, then no srs^r with r≥0r \ge 0 is a pure Nash equilibrium, so the dynamics from s0s^0 never stop.

Proof. The return is at line L5, so U(st)U(s^t) is not empty and, by Claim 2, st=sjs^t = s^j for some j<tj < t. For j≤r<tj \le r < t the pass with profile srs^r did not return at line L4, so U(sr)U(s^r) is not empty. Since sr+1=f(sr)s^{r+1} = f(s^r) depends only on srs^r, induction on rr gives sr+(t−j)=srs^{r + (t - j)} = s^r for all r≥jr \ge j. So the sequence from index jj on runs through the profiles sj,…,st−1s^j, \ldots, s^{t-1} for ever, and each has a player who can gain. For r<jr < j the profile srs^r also had U(sr)U(s^r) not empty, because the pass with srs^r did not return. So no profile of the sequence is a pure Nash equilibrium. □\square

Claim 4 (termination). The algorithm returns after at most ∣S∣|S| passes that do not return, so after at most ∣S∣+1|S| + 1 passes.

Proof. By Claim 2, after tt passes that do not return, seen holds tt distinct profiles of SS, so t≤∣S∣t \le |S|. The loop has no other exit than the two returns, so it returns in pass ∣S∣+1|S| + 1 at the latest. □\square

Claim 5 (potential games). Suppose GG has a generalized ordinal potential, a function P:S→RP : S \to \mathbb{R} such that ui(b,s−i)>ui(s)u_i(b, s_{-i}) > u_i(s) implies P(b,s−i)>P(s)P(b, s_{-i}) > P(s) for every ii, ss and bb. Then the algorithm never returns "cycle", so it returns a pure Nash equilibrium. Every exact potential (with ui(b,s−i)−ui(s)=P(b,s−i)−P(s)u_i(b, s_{-i}) - u_i(s) = P(b, s_{-i}) - P(s)), and so Rosenthal's potential of a congestion game written with ui=−ciu_i = -c_i, is a generalized ordinal potential.

Proof. In a pass that does not return, the mover ii of line L7 has si∉BRi(s−i)s_i \notin BR_i(s_{-i}), so its new strategy bb of line L8 has ui(b,s−i)=max⁡b′ui(b′,s−i)>ui(s)u_i(b, s_{-i}) = \max_{b'} u_i(b', s_{-i}) > u_i(s). Hence P(st+1)>P(st)P(s^{t+1}) > P(s^t) for every tt for which st+1s^{t+1} is defined, and P(s0)<P(s1)<⋯P(s^0) < P(s^1) < \cdots. So the profiles s0,s1,…s^0, s^1, \ldots are pairwise distinct, and line L5 never finds the current profile in seen. By Claim 4 the algorithm returns, so it returns at line L4, and Claim 1 applies. For an exact potential, a positive gain ui(b,s−i)−ui(s)u_i(b, s_{-i}) - u_i(s) equals the rise of PP, so PP is also a generalized ordinal potential. ■\blacksquare

Complexity

Line L3 checks each player against each of its strategies, so one pass costs O(nk)O(n k) payoff lookups plus O(n)O(n) for the set operations on a profile, if seen is a hash set of profiles. There are at most ∣S∣≤kn|S| \le k^n passes, so the worst case is O(nkn+1)O(n k^{n+1}) lookups, and seen holds at most knk^n profiles of length nn, which is O(nkn)O(n k^n) space. In the word RAM model each payoff is a rational number of bounded size, and a comparison costs O(1)O(1).

The bound is linear in the size of the normal form, which already lists nknn k^n numbers. The interesting case is a succinct game, such as a congestion game given by its resources and cost functions. There the number of moves is at most the number of distinct values of the potential, which is polynomial when the costs are small integers but can be exponential in general. Finding a pure Nash equilibrium of a congestion game is PLS-complete (Fabrikant, Papadimitriou and Talwar, 2004), and there are congestion games with start profiles from which every improvement path to an equilibrium is exponentially long. PLS-complete does not mean NP-hard: a pure equilibrium always exists in these games.

Properties

  • Deterministic and exact. With the tie rule of lines L7 and L8 and exact payoffs, the run is a function of the start profile.
  • Uncoupled. A player needs only its own utility and the current profile, not the others' utilities.
  • Pure. It works with pure strategies only, so it cannot find a mixed equilibrium. A game with no pure equilibrium always cycles.
  • Monotone in potential games. In an exact potential game, the potential rises by exactly the gain of the mover at each step.
  • No welfare guarantee. The equilibrium it reaches depends on the start and the order, and it may be a bad one.

Variants and improvements

  • Better-response dynamics. A player may move to any strictly better strategy. In a game with the finite improvement property all such paths are finite, and Monderer and Shapley (1996) showed that a finite game has this property if and only if it has a generalized ordinal potential.
  • Epsilon-best responses. Move only when the gain is more than an ε\varepsilon fraction of the current cost. Roughgarden (Lecture 16) proves that in symmetric congestion games whose cost functions have bounded jumps, and with the player of largest gain moving first, this reaches an approximate equilibrium in a number of moves polynomial in nn, 1/ε1/\varepsilon and the bit length of the costs, while exact dynamics may take exponentially many.
  • Weakly acyclic games. In a game that is weakly acyclic under best responses, there is a path of best responses from every profile to an equilibrium, but not every path ends. If the mover is drawn at random at each step, the run reaches an equilibrium with probability 1.
  • Mixed-strategy learning. Fictitious play best-responds to the empirical mix of the past play of the others and can approach mixed equilibria (Robinson's theorem). No-regret dynamics and replicator dynamics are smoother forms of adaptation.

When to use it

Use it to find a pure Nash equilibrium of a potential game, in particular a congestion game, where it is simple, needs only local information and always stops. It is also a model of how myopic players adapt. In a general game, use it only with the cycle check, and expect cycles; a pure equilibrium may not exist at all, and brute force over the normal form is then as cheap. For mixed equilibria use Nash equilibrium computation methods, and for coarse correlated equilibria use no-regret dynamics.

Pitfalls

  • Moving on a tie. If line L3 also lets a player move between two equal best responses, the run can cycle in a potential game, because the potential does not rise on a tie. Move only on a strict gain, as line L3 does.
  • All players at once. Updating every player in line L8 at the same time breaks the potential argument, because the potential rises only for one mover at a time. The two-player coordination game cycles under simultaneous updates.
  • No cycle check. Without lines L1, L5 and L6 the loop never ends on matching pennies. Keep the check, or cap the number of steps.
  • Reading a stop as a good outcome. Line L4 certifies a pure Nash equilibrium, not an efficient one; the price of anarchy measures how bad it can be.

Implementations

The Python code follows the pseudocode with the profile as a tuple and seen as a set, and returns the path of visited profiles. The tests use the example above, matching pennies from every start, random congestion games with up to 4 players and 4 resources (each move must raise the mover's utility and lower Rosenthal's potential by the same amount, and the result must be a pure Nash equilibrium found by brute force), random exact potential games, and 500 random games compared with a direct simulation of the step rule.

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.

agtgame.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Finite games in normal form, with exact payoffs and exact equilibrium checks.

A game is a pair (sizes, pay). sizes is a tuple (k_1, ..., k_n) of the numbers of pure
strategies of the n players; the pure strategies of player i are 0, ..., k_i - 1. pay is a
dict that maps each profile, a tuple s = (s_1, ..., s_n), to a tuple of n Fraction
utilities, which each player maximizes. A cost game passes the utilities u = -c.

A mixed profile sigma is a list of n lists; sigma[i][a] is the probability, a Fraction,
that player i plays a. A distribution on profiles (for correlated and coarse correlated
equilibria) is a dict from profiles to Fraction; missing profiles have probability 0.

All checks are exact: there is no tolerance anywhere. There is no LP and no equilibrium
algorithm in this module.
"""

from fractions import Fraction
from itertools import product


def profiles(sizes):
    """Return the list of all pure profiles, in lexicographic order."""
    return list(product(*(range(k) for k in sizes)))


def from_bimatrix(A, B):
    """Return the game of the bimatrix (A, B): the row player gets A[r][c], the column player B[r][c]."""
    m, n = len(A), len(A[0])
    if len(B) != m or any(len(row) != n for row in A) or any(len(row) != n for row in B):
        raise ValueError("A and B must be m by n matrices of the same shape")
    pay = {(r, c): (Fraction(A[r][c]), Fraction(B[r][c])) for r in range(m) for c in range(n)}
    return (m, n), pay


def random_game(rng, sizes, lo, hi):
    """Return a game with integer utilities drawn uniformly from lo to hi (inclusive), as Fraction."""
    sizes = tuple(sizes)
    pay = {s: tuple(Fraction(rng.randint(lo, hi)) for _ in sizes) for s in profiles(sizes)}
    return sizes, pay


def _replace(s, i, a):
    return s[:i] + (a,) + s[i + 1:]


def _weight(sigma, s, skip=None):
    w = Fraction(1)
    for k, a in enumerate(s):
        if k != skip:
            w *= sigma[k][a]
            if w == 0:
                return w
    return w


def expected_utility(game, i, sigma):
    """Return u_i(sigma), the expected utility of player i when the players draw independently."""
    sizes, pay = game
    return sum((_weight(sigma, s) * pay[s][i] for s in profiles(sizes)), Fraction(0))


def deviation_payoffs(game, i, sigma):
    """Return the list of u_i(a, sigma_-i) for every pure strategy a of player i."""
    sizes, pay = game
    out = [Fraction(0)] * sizes[i]
    for s in profiles(sizes):
        w = _weight(sigma, s, skip=i)
        if w:
            out[s[i]] += w * pay[s][i]
    return out


def pure_best_responses(game, i, sigma):
    """Return the sorted list of the pure strategies of player i that maximize u_i(a, sigma_-i)."""
    d = deviation_payoffs(game, i, sigma)
    best = max(d)
    return [a for a, v in enumerate(d) if v == best]


def max_gain(game, sigma):
    """Return the largest gain of any player from a pure deviation: max_i (max_a u_i(a, sigma_-i) - u_i(sigma)).

    The result is never negative, because u_i(sigma) is an average of the deviation payoffs.
    """
    sizes, _ = game
    gain = Fraction(0)
    for i in range(len(sizes)):
        d = deviation_payoffs(game, i, sigma)
        u = sum((p * v for p, v in zip(sigma[i], d)), Fraction(0))
        gain = max(gain, max(d) - u)
    return gain


def is_distribution(p):
    """Return True if p (a sequence, or a dict of probabilities) is nonnegative and sums to exactly 1."""
    vals = list(p.values()) if isinstance(p, dict) else list(p)
    return all(v >= 0 for v in vals) and sum(vals, Fraction(0)) == 1


def _is_mixed_profile(game, sigma):
    sizes, _ = game
    return len(sigma) == len(sizes) and all(
        len(sigma[i]) == k and is_distribution(sigma[i]) for i, k in enumerate(sizes))


def is_nash(game, sigma):
    """Return True if sigma is a mixed Nash equilibrium: no pure deviation gains for any player."""
    return _is_mixed_profile(game, sigma) and max_gain(game, sigma) == 0


def is_epsilon_nash(game, sigma, eps):
    """Return True if no player gains more than eps by a pure deviation (the additive form)."""
    return _is_mixed_profile(game, sigma) and max_gain(game, sigma) <= eps


def _check_dist(game, dist):
    sizes, _ = game
    allowed = set(profiles(sizes))
    return all(s in allowed for s in dist) and is_distribution(dist)


def is_correlated(game, dist):
    """Return True if dist is a correlated equilibrium.

    For every player i and every pair a, b of its pure strategies, the sum over the profiles s
    with s_i = a of dist(s) (u_i(s) - u_i(b, s_-i)) is at least 0.
    """
    sizes, pay = game
    if not _check_dist(game, dist):
        return False
    for i, k in enumerate(sizes):
        for a in range(k):
            rows = [(q, s) for s, q in dist.items() if s[i] == a and q]
            for b in range(k):
                if b != a and sum((q * (pay[s][i] - pay[_replace(s, i, b)][i]) for q, s in rows), Fraction(0)) < 0:
                    return False
    return True


def is_coarse_correlated(game, dist):
    """Return True if dist is a coarse correlated equilibrium.

    For every player i and every pure strategy b, E_{s ~ dist} u_i(s) >= E_{s ~ dist} u_i(b, s_-i).
    """
    sizes, pay = game
    if not _check_dist(game, dist):
        return False
    for i, k in enumerate(sizes):
        here = sum((q * pay[s][i] for s, q in dist.items()), Fraction(0))
        for b in range(k):
            if sum((q * pay[_replace(s, i, b)][i] for s, q in dist.items()), Fraction(0)) > here:
                return False
    return True


def pure_nash_brute(game):
    """Return the list of all pure Nash equilibria, found by checking every profile."""
    sizes, pay = game
    out = []
    for s in profiles(sizes):
        if all(pay[s][i] >= pay[_replace(s, i, b)][i] for i in range(len(sizes)) for b in range(sizes[i])):
            out.append(s)
    return out
best_response_dynamics.py 56 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/best-response-dynamics/. The authors are listed in prov/0D2G4K.jsonl.
"""Best-response dynamics on a finite game in normal form, with cycle detection.

The game is a pair (sizes, pay) as in the shared helper agtgame: sizes[i] is the number of
pure strategies of player i, and pay maps each pure profile to a tuple of utilities, which
the players maximize. A cost game passes the utilities u = -c.

At each step, the smallest player who is not playing a best response to the others switches
to its smallest best response. The next profile depends only on the current one, so the run
either reaches a pure Nash equilibrium or repeats a profile, and then it cycles for ever.
"""


def _replace(s, i, a):
    return s[:i] + (a,) + s[i + 1:]


def best_responses(game, s, i):
    """Return the sorted list of the pure best responses of player i to s_-i.

    Cost: sizes[i] payoff lookups.
    """
    sizes, pay = game
    vals = [pay[_replace(s, i, b)][i] for b in range(sizes[i])]
    best = max(vals)
    return [b for b, v in enumerate(vals) if v == best]


def best_response_dynamics(game, start):
    """Run best-response dynamics from the pure profile start.

    Return (s, status, path). status is "equilibrium" when s is a pure Nash equilibrium, and
    "cycle" when s is a profile that the run has visited before. path is the list of the
    profiles visited, start first and s last.

    Precondition: start is a pure profile of the game. Cost: at most |S| steps, where |S| is
    the number of profiles, and O(n k) payoff lookups per step, where n is the number of
    players and k the largest number of strategies; the seen set holds at most |S| profiles.
    """
    sizes, _ = game
    s = tuple(start)
    if len(s) != len(sizes) or any(not 0 <= a < k for a, k in zip(s, sizes)):
        raise ValueError("start must be a pure profile of the game")
    seen = set()  # @line L1
    path = [s]
    while True:  # @line L2
        unhappy = [i for i in range(len(sizes)) if s[i] not in best_responses(game, s, i)]  # @line L3
        if not unhappy:  # @line L4
            return s, "equilibrium", path
        if s in seen:  # @line L5
            return s, "cycle", path
        seen.add(s)  # @line L6
        i = unhappy[0]  # @line L7
        s = _replace(s, i, best_responses(game, s, i)[0])  # @line L8
        path.append(s)
test_best_response_dynamics.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/best-response-dynamics/. The authors are listed in prov/0D2G4K.jsonl.
"""Tests of best-response dynamics: potential games, matching pennies and random games."""

import random
from fractions import Fraction
from itertools import product

import pytest

from agtgame import from_bimatrix, profiles, pure_nash_brute, random_game
from best_response_dynamics import best_response_dynamics, best_responses

F = Fraction


def congestion_game(strategies, costs):
    """Return (game, potential) of an atomic congestion game, with utilities u = -c.

    strategies[i] is the list of the strategies of player i, each a tuple of resources.
    costs[e][j - 1] is the cost of resource e to each of its j users.
    """
    sizes = tuple(len(st) for st in strategies)

    def loads(s):
        load = [0] * len(costs)
        for i, a in enumerate(s):
            for e in strategies[i][a]:
                load[e] += 1
        return load

    pay = {}
    for s in profiles(sizes):
        load = loads(s)
        pay[s] = tuple(F(-sum(costs[e][load[e] - 1] for e in strategies[i][a])) for i, a in enumerate(s))

    def potential(s):
        load = loads(s)
        return sum(sum(costs[e][:load[e]]) for e in range(len(costs)))

    return (sizes, pay), potential


def naive_run(game, start, limit):
    """Apply the step rule from its definition, and stop at the first repeat or equilibrium."""
    sizes, pay = game
    s = tuple(start)
    path = [s]
    for _ in range(limit):
        movers = []
        for i in range(len(sizes)):
            here = pay[s][i]
            if any(pay[s[:i] + (b,) + s[i + 1:]][i] > here for b in range(sizes[i])):
                movers.append(i)
        if not movers:
            return s, "equilibrium", path
        if s in path[:-1]:
            return s, "cycle", path
        i = movers[0]
        top = max(pay[s[:i] + (b,) + s[i + 1:]][i] for b in range(sizes[i]))
        b = min(b for b in range(sizes[i]) if pay[s[:i] + (b,) + s[i + 1:]][i] == top)
        s = s[:i] + (b,) + s[i + 1:]
        path.append(s)
    raise AssertionError("the step limit is too small")


def test_page_example_two_links():
    game, phi = congestion_game([[(0,), (1,)]] * 4, [[1, 2, 3, 4], [1, 2, 3, 4]])
    s, status, path = best_response_dynamics(game, (0, 0, 0, 0))
    assert status == "equilibrium"
    assert path == [(0, 0, 0, 0), (1, 0, 0, 0), (1, 1, 0, 0)]
    assert [phi(p) for p in path] == [10, 7, 6]
    assert s in pure_nash_brute(game)


def test_matching_pennies_cycles():
    game = from_bimatrix([[1, -1], [-1, 1]], [[-1, 1], [1, -1]])
    assert pure_nash_brute(game) == []
    s, status, path = best_response_dynamics(game, (0, 0))
    assert status == "cycle"
    assert path == [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]
    for start in profiles(game[0]):
        assert best_response_dynamics(game, start)[1] == "cycle"


def test_edge_cases():
    one = ((3,), {(0,): (F(1),), (1,): (F(5),), (2,): (F(5),)})
    assert best_response_dynamics(one, (0,)) == ((1,), "equilibrium", [(0,), (1,)])
    assert best_response_dynamics(one, (2,)) == ((2,), "equilibrium", [(2,)])
    flat = random_game(random.Random(1), (2, 3), 0, 0)
    assert best_response_dynamics(flat, (1, 2)) == ((1, 2), "equilibrium", [(1, 2)])
    assert best_responses(flat, (1, 2), 1) == [0, 1, 2]
    with pytest.raises(ValueError):
        best_response_dynamics(flat, (2, 0))
    with pytest.raises(ValueError):
        best_response_dynamics(flat, (0,))


def test_random_congestion_games_potential_strictly_falls():
    rng = random.Random(20240)
    for _ in range(250):
        n = rng.randint(2, 4)
        r = rng.randint(2, 4)
        subsets = [t for size in (1, 2) for t in product(range(r), repeat=size) if len(set(t)) == size and list(t) == sorted(t)]
        strategies = [rng.sample(subsets, rng.randint(2, min(4, len(subsets)))) for _ in range(n)]
        costs = []
        for _ in range(r):
            c, row = 0, []
            for _ in range(n):
                c += rng.randint(0, 4)
                row.append(c)
            costs.append(row)
        game, phi = congestion_game(strategies, costs)
        start = tuple(rng.randrange(k) for k in game[0])
        s, status, path = best_response_dynamics(game, start)
        assert status == "equilibrium"
        assert s in pure_nash_brute(game)
        for a, b in zip(path, path[1:]):
            mover = [i for i in range(n) if a[i] != b[i]]
            assert len(mover) == 1
            i = mover[0]
            gain = game[1][b][i] - game[1][a][i]
            assert gain > 0
            assert phi(a) - phi(b) == gain  # Rosenthal's potential is exact


def test_random_exact_potential_games():
    rng = random.Random(77)
    for _ in range(200):
        sizes = tuple(rng.randint(2, 3) for _ in range(rng.randint(2, 3)))
        phi = {s: F(rng.randint(-9, 9)) for s in profiles(sizes)}
        dummy = [{s[:i] + s[i + 1:]: F(rng.randint(-9, 9)) for s in profiles(sizes)} for i in range(len(sizes))]
        pay = {s: tuple(phi[s] + dummy[i][s[:i] + s[i + 1:]] for i in range(len(sizes))) for s in profiles(sizes)}
        game = (sizes, pay)
        start = tuple(rng.randrange(k) for k in sizes)
        s, status, path = best_response_dynamics(game, start)
        assert status == "equilibrium" and s in pure_nash_brute(game)
        assert all(phi[b] > phi[a] for a, b in zip(path, path[1:]))
        assert len(path) <= len(phi)


def test_random_games_against_naive_run():
    rng = random.Random(4242)
    cycles = 0
    for _ in range(500):
        sizes = tuple(rng.randint(2, 3) for _ in range(rng.randint(2, 3)))
        game = random_game(rng, sizes, -3, 3)
        start = tuple(rng.randrange(k) for k in sizes)
        got = best_response_dynamics(game, start)
        assert got == naive_run(game, start, len(game[1]) + 1)
        s, status, path = got
        nash = pure_nash_brute(game)
        if status == "equilibrium":
            assert s in nash
        else:
            cycles += 1
            assert s in path[:-1] and len(path) <= len(game[1]) + 1
        if not nash:
            assert status == "cycle"
    assert cycles > 0

History

Cournot (1838) described two producers who in turn set their quantity to the best reply to the other's quantity, and studied when this process settles. Rosenthal (1973) introduced congestion games and their potential, which shows that improving moves stop. Monderer and Shapley (1996) defined potential games and the finite improvement property. Fabrikant, Papadimitriou and Talwar (2004) proved that a pure Nash equilibrium of a congestion game is PLS-complete to find.

References

  1. Recherches sur les principes mathématiques de la théorie des richesses, the chapter on competition between producers (two producers who adjust their quantities in turn)
  2. Robert W. Rosenthal, A class of games possessing pure-strategy Nash equilibria, International Journal of Game Theory 2(1) (1973), 65-67, the potential function of a congestion game, which every improving move decreases
  3. Dov Monderer and Lloyd S. Shapley, Potential games, Games and Economic Behavior 14(1) (1996), 124-143, the finite improvement property, and its equivalence with a generalized ordinal potential
  4. The complexity of pure Nash equilibria, the PLS-completeness of a pure Nash equilibrium in congestion games, and congestion games with exponentially long improvement paths
  5. Tim Roughgarden, Twenty Lectures on Algorithmic Game Theory, Cambridge University Press, 2016, Lecture 16 (best-response dynamics in potential games and their speed)

Where this leads

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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example