Algorithm Search⌘K

Algorithmcore

Support enumeration

Also called Porter-Nudelman-Shoham algorithm, support enumeration for bimatrix games.

Finds Nash equilibria of a bimatrix game by trying pairs of supports and solving the linear indifference equations for each pair.

Time
O(2^(m + n) (m n + min(m, n)^3)) worst
Space
O(m n) extra
Where
m = the number of pure strategies of the row player; n = the number of pure strategies of the column player
Properties
deterministicexactofflineiterative
Origin
Ryan Porter, Eugene Nudelman, Yoav Shoham, 2004

Support enumeration finds the Nash equilibria of a two-player game in strategic form (a bimatrix game) by guessing which pure strategies each player uses, the supports, and solving a small linear system for each guess. A pair of supports gives equations that make each player indifferent among the strategies in its own support, by the indifference principle; if the solution is a pair of probability vectors and no outside strategy does better, it is an equilibrium. The method is one of the basic exact methods behind the problem of Nash equilibrium computation, which gives the overview; this page goes deep on the enumeration. It is exponential in the worst case, while the Lemke-Howson algorithm follows one path of pivots to one equilibrium and is also exponential in the worst case.

In plain words

In a mixed equilibrium, each player mixes only among moves that are equally good for it, given the mix of the other player. If we knew which moves each player uses, we could write "these moves give the same payoff" as linear equations and solve them. We do not know the moves, so we try every choice: one move each, then two moves each, and so on. For each choice we solve the equations, throw the answer away if a chance is not positive, and check that no unused move pays more. Every answer that passes is an equilibrium. In a game without special ties, both players always use the same number of moves, which cuts the search.

The problem

The input is two m×nm \times n matrices AA and BB with rational entries. On this page mm and nn are the numbers of pure strategies of the row player and the column player, not the number of players. If the row player plays row ii and the column player plays column jj, the row player gets AijA_{ij} and the column player gets BijB_{ij}, and both maximize. A mixed strategy is x∈Δm={x≥0,∑ixi=1}x \in \Delta_m = \{x \ge 0, \sum_i x_i = 1\} for the row player and y∈Δny \in \Delta_n for the column player. The support of xx is supp⁡(x)={i:xi>0}\operatorname{supp}(x) = \{i : x_i > 0\}.

A pair (x,y)(x, y) is a Nash equilibrium if xx is a best response to yy and yy is a best response to xx. The best response fact makes this a finite test: xx is a best response to yy if and only if every row in supp⁡(x)\operatorname{supp}(x) maximizes (Ay)i(Ay)_i, and the same holds for yy with the columns (xTB)j(x^{\mathsf T} B)_j. The output is a list of equilibria; for a nondegenerate game it is the list of all of them.

The game is nondegenerate if no mixed strategy with a support of kk pure strategies has more than kk pure best responses. Random games with continuous payoffs are nondegenerate with probability 1, but games with structure, such as integer payoffs with many ties, often are not.

The algorithm

  1. SUPPORT-ENUMERATION(A, B) ▷ A, B are m by n; row player gets A, column player gets B
  2. 1for k ← 1 to min(m, n)
  3. 2for each set I of k rows and each set J of k columns
  4. 3solve Σ_{j∈J} A[i][j] y_j = u for i in I, and Σ_{j∈J} y_j = 1 ▷ unknowns y_J, u
  5. 4solve Σ_{i∈I} x_i B[i][j] = v for j in J, and Σ_{i∈I} x_i = 1 ▷ unknowns x_I, v
  6. 5if a system is singular, or some y_j or x_i is not positive: skip this pair
  7. 6set x_i ← 0 for i not in I and y_j ← 0 for j not in J
  8. 7if (A y)_i ≤ u for every row i and (xᵀ B)_j ≤ v for every column j
  9. 8output (x, y)

Line L3 makes the row player indifferent among the rows of II: it is a square system of k+1k + 1 equations in the k+1k + 1 unknowns yjy_j (j∈Jj \in J) and uu. Note that yy, the strategy of the column player, is found from the payoffs AA of the row player, because yy must make the rows of II equally good. Line L4 is the same for the column player, with BB. Line L7 is the best response test: the rows in II all earn uu, so they are best responses if no other row earns more, and the same for the columns.

Only supports of equal size are tried. In a nondegenerate game this loses nothing (see Correctness). In a degenerate game the method can miss equilibria, and the complete version tries all pairs (I,J)(I, J) of any sizes and solves the systems as feasibility problems, which allows a set of solutions instead of one point.

Example

Take the 3×23 \times 2 game of von Stengel's chapter in NRTV, which is nondegenerate:

A=(332506),B=(322631).A = \begin{pmatrix} 3 & 3 \\ 2 & 5 \\ 0 & 6 \end{pmatrix}, \qquad B = \begin{pmatrix} 3 & 2 \\ 2 & 6 \\ 3 & 1 \end{pmatrix}.

For k=1k = 1 there are 6 pure pairs, and only (row 0, column 0) passes line L7: row 0 is best against column 0 (3≥2,03 \ge 2, 0), and column 0 is best against row 0 (3≥23 \ge 2). For k=2k = 2 the column set is {0,1}\{0, 1\} and there are three row sets.

rows II line L3: yy, uu line L4: xx, vv line L7 result
{0,1}\{0, 1\} 3y0+3y1=2y0+5y13y_0 + 3y_1 = 2y_0 + 5y_1 gives y=(2/3,1/3)y = (2/3, 1/3), u=3u = 3 3x0+2x1=2x0+6x13x_0 + 2x_1 = 2x_0 + 6x_1 gives x=(4/5,1/5,0)x = (4/5, 1/5, 0), v=14/5v = 14/5 row 2 earns 2≤32 \le 3 equilibrium
{0,2}\{0, 2\} y=(1/2,1/2)y = (1/2, 1/2), u=3u = 3 x0=−2x2x_0 = -2x_2, not positive skipped at L5
{1,2}\{1, 2\} y=(1/3,2/3)y = (1/3, 2/3), u=4u = 4 x=(0,1/3,2/3)x = (0, 1/3, 2/3), v=8/3v = 8/3 row 0 earns 3≤43 \le 4 equilibrium

So the game has exactly three equilibria, with payoffs (3,3)(3, 3), (3,14/5)(3, 14/5) and (4,8/3)(4, 8/3). The number is odd, as it is in every nondegenerate game. The same game is the example of the Lemke-Howson page, where only the first and the third equilibrium are reached from the artificial start.

Two more check values. In battle of the sexes, A=(2001)A = \begin{pmatrix} 2 & 0 \\ 0 & 1 \end{pmatrix} and B=(1002)B = \begin{pmatrix} 1 & 0 \\ 0 & 2 \end{pmatrix}, the method returns the two pure equilibria and x=(2/3,1/3)x = (2/3, 1/3), y=(1/3,2/3)y = (1/3, 2/3), where the row player gets 2/32/3. In matching pennies and rock-paper-scissors it returns only the uniform pair.

Correctness

Each output is an equilibrium. At line L8 the strategies are distributions by lines L3 to L6. Every row in I=supp⁡(x)I = \operatorname{supp}(x) earns exactly uu against yy by line L3, and no row earns more by line L7, so by the best response fact xx is a best response to yy. The same argument with line L4 shows that yy is a best response to xx.

In a nondegenerate game, each equilibrium is found. Let (x,y)(x, y) be an equilibrium with supports II and JJ. Each column of JJ is a best response to xx, so ∣J∣≤∣I∣|J| \le |I| by nondegeneracy; in the same way ∣I∣≤∣J∣|I| \le |J|, so the sizes are equal. Then yy and u=max⁡i(Ay)iu = \max_i (Ay)_i solve the system of line L3. That system has only this solution: if it had a line of solutions, move yy along the line inside the simplex. The move must stop where a yjy_j becomes 0 or where an outside row ties with uu, and at that point a strategy with a support of at most kk has more than kk pure best responses, or one with a support of k−1k - 1 has kk, which nondegeneracy forbids. So the solver finds yy, the same holds for xx, and the pair passes lines L5 and L7. The proof file has the details.

Proof: Support enumeration outputs only equilibria, and all of them in a nondegenerate gamefull

Let (A,B)(A, B) be an m×nm \times n bimatrix game. For a mixed strategy yy of the column player write (Ay)i(Ay)_i for the payoff of row ii, and for xx write (xTB)j(x^{\mathsf T} B)_j for the payoff of column jj. The game is nondegenerate if no mixed strategy with kk strategies in its support has more than kk pure best responses.

Lemma 1 (best response fact). xx is a best response to yy if and only if every ii with xi>0x_i > 0 satisfies (Ay)i=max⁡r(Ay)r(Ay)_i = \max_r (Ay)_r.

Proof. xTAy=∑ixi(Ay)ix^{\mathsf T} A y = \sum_i x_i (Ay)_i is an average of the numbers (Ay)i(Ay)_i with weights xix_i. It equals the maximum max⁡r(Ay)r\max_r (Ay)_r, which is the most any mixed strategy can earn, if and only if all weight is on rows that reach the maximum. □\square

Theorem 1 (soundness). Every pair (x,y)(x, y) output at line L8 is a Nash equilibrium.

Proof. By line L3, yj>0y_j > 0 for j∈Jj \in J (line L5), yj=0y_j = 0 for j∉Jj \notin J (line L6), and ∑jyj=1\sum_j y_j = 1, so y∈Δny \in \Delta_n; in the same way x∈Δmx \in \Delta_m with support II. By line L3, (Ay)i=∑j∈JAijyj=u(Ay)_i = \sum_{j \in J} A_{ij} y_j = u for each i∈Ii \in I, and by line L7, (Ay)r≤u(Ay)_r \le u for each row rr. So max⁡r(Ay)r=u\max_r (Ay)_r = u, and every row of the support of xx reaches it. By Lemma 1, xx is a best response to yy. Lines L4 and L7 give the same for yy against xx. □\square

Lemma 2 (equal supports). In a nondegenerate game every Nash equilibrium (x,y)(x, y) has ∣supp⁡(x)∣=∣supp⁡(y)∣|\operatorname{supp}(x)| = |\operatorname{supp}(y)|.

Proof. By Lemma 1 every column of supp⁡(y)\operatorname{supp}(y) is a pure best response to xx, so xx has at least ∣supp⁡(y)∣|\operatorname{supp}(y)| pure best responses, and nondegeneracy gives ∣supp⁡(y)∣≤∣supp⁡(x)∣|\operatorname{supp}(y)| \le |\operatorname{supp}(x)|. Swap the players for the other inequality. □\square

Lemma 3 (unique solution). Let the game be nondegenerate, let (x,y)(x, y) be an equilibrium with supports II and JJ, ∣I∣=∣J∣=k|I| = |J| = k, and let u=max⁡r(Ay)ru = \max_r (Ay)_r. Then (yJ,u)(y_J, u) is the only solution of the system SS of line L3: ∑j∈JAijzj=t\sum_{j \in J} A_{ij} z_j = t for i∈Ii \in I and ∑j∈Jzj=1\sum_{j \in J} z_j = 1, in the unknowns z∈RJz \in \mathbb{R}^J and tt.

Proof. (yJ,u)(y_J, u) solves SS by Lemma 1. Suppose that SS has a second solution. Then the solutions form an affine set of dimension at least 1, and it contains a line (yJ,u)+λ(d,δ)(y_J, u) + \lambda (d, \delta) with (d,δ)≠0(d, \delta) \ne 0. Here ∑jdj=0\sum_j d_j = 0, and d≠0d \ne 0, because d=0d = 0 forces δ=0\delta = 0 by the equations. Extend zz by 0 outside JJ and set z(λ)=y+λdz(\lambda) = y + \lambda d.

At λ=0\lambda = 0, the rows outside II earn strictly less than uu: otherwise yy, with support size kk, would have more than kk pure best responses. Also yj>0y_j > 0 for j∈Jj \in J. Since dd has a negative entry, z(λ)jz(\lambda)_j becomes 0 for some j∈Jj \in J at a finite λ>0\lambda > 0. Let λ∗>0\lambda^* > 0 be the first value at which a coordinate zjz_j with j∈Jj \in J reaches 0 or a row r∉Ir \notin I reaches (Az)r=t(A z)_r = t. For 0≤λ≤λ∗0 \le \lambda \le \lambda^*, z(λ)z(\lambda) is a distribution on JJ, the rows of II all earn t(λ)=u+λδt(\lambda) = u + \lambda \delta, and the rows outside II earn at most t(λ)t(\lambda), so all rows of II are pure best responses to z(λ)z(\lambda).

At λ∗\lambda^*, in the first case the support of z(λ∗)z(\lambda^*) has at most k−1k - 1 elements and z(λ∗)z(\lambda^*) has at least kk pure best responses (the rows of II). In the second case the support has at most kk elements and there are at least k+1k + 1 pure best responses. Both contradict nondegeneracy. □\square

Theorem 2 (completeness). In a nondegenerate game, every Nash equilibrium is output.

Proof. Let (x,y)(x, y) be an equilibrium with supports II and JJ. By Lemma 2, ∣I∣=∣J∣=k|I| = |J| = k with 1≤k≤min⁡(m,n)1 \le k \le \min(m, n), so lines L1 and L2 reach the pair (I,J)(I, J). By Lemma 3 the square system of line L3 has a unique solution, so its matrix is nonsingular, and the solver returns (yJ,u)(y_J, u). The same lemma with the players swapped shows that line L4 returns (xI,v)(x_I, v) with v=max⁡c(xTB)cv = \max_c (x^{\mathsf T} B)_c. All these entries are positive, so line L5 does not skip the pair. Line L6 rebuilds xx and yy, and line L7 holds because uu and vv are the maximal payoffs. So line L8 outputs (x,y)(x, y). □\square

Termination. There are finitely many pairs (I,J)(I, J), and each step does a finite amount of work, so the method ends. Each equilibrium is output at most once, because the pair (I,J)(I, J) is its pair of supports.

Complexity

The number of support pairs of equal size is ∑k(mk)(nk)=(m+nm)−1\sum_{k} \binom{m}{k}\binom{n}{k} = \binom{m+n}{m} - 1, by Vandermonde's identity. For each pair, lines L3 and L4 solve two systems of size k+1k + 1 by Gaussian elimination in O(k3)O(k^3) arithmetic operations, and line L7 costs O(mn)O(m n). So the time is O((m+nm)(mn+min⁡(m,n)3))O\big(\binom{m+n}{m}(m n + \min(m, n)^3)\big) in the worst case, which is at most O(2m+n(mn+min⁡(m,n)3))O(2^{m+n}(m n + \min(m, n)^3)), and about 4n/n4^n / \sqrt{n} systems for an n×nn \times n game. The space is O(mn)O(m n) besides the output.

The exponential time is not only an artifact of the search. The coordination game A=B=InA = B = I_n has 2n−12^n - 1 equilibria, one for each nonempty support (both players uniform on the same set), so any method that lists all equilibria needs exponential time on it. The solutions are rational numbers with a polynomial number of digits, because each is the solution of a square system with entries from AA or BB. This is special to two players: games with three or more players can have only irrational equilibria. The code uses exact rational arithmetic, so the cost of one operation grows with the bit length of the entries.

Properties

  • Exact. With rational input, every equilibrium is computed exactly, and the best response test is an exact comparison.
  • Complete for nondegenerate games. It lists every equilibrium. For a degenerate game the list is correct but can be incomplete.
  • Embarrassingly parallel. The support pairs are independent.
  • Any order works. The method can stop at the first equilibrium, and the order of the pairs then decides the running time but not the correctness.

Variants and improvements

  • Heuristic order (Porter, Nudelman and Shoham). Try small supports first and, among supports of the same total size, balanced ones first, and prune a support when one of its strategies is dominated given the supports. On many generated test games this finds one equilibrium faster than Lemke-Howson. The same search with nonlinear feasibility problems handles games with more players.
  • Degenerate games. Enumerate all pairs (I,J)(I, J) of any sizes and replace the square systems by LP feasibility problems, or enumerate the vertices of the two best response polytopes and match their labels (vertex enumeration). In a degenerate game the equilibria form a finite union of polytopes, and vertex enumeration gives the extreme points of these sets.
  • One equilibrium. The Lemke-Howson algorithm finds one equilibrium by pivoting without a search, and is often faster, but it can take exponential time (Savani-von Stengel theorem).
  • Approximate equilibria. Restricting the supports to size O(log⁡n/ε2)O(\log n / \varepsilon^2) gives an ε\varepsilon-Nash equilibrium in quasi-polynomial time (Lipton-Markakis-Mehta algorithm).
  • Zero-sum games. For B=−AB = -A, use the linear program, which takes polynomial time.

When to use it

Use it for small games, when all equilibria are needed, for example to choose the best one, since selecting an equilibrium by welfare or support is NP-hard in general (hardness of optimal Nash equilibria). Use it as a reference to test other methods, as the tests of this site do. Use the heuristic order when one equilibrium is enough and the game is expected to have one with small supports. For large games, use Lemke-Howson or a learning method, or the LP when the game is zero-sum.

Pitfalls

  • Swapping the payoff matrices. The column player's mix yy comes from the row player's payoffs AA, and xx comes from BB. Using AA for xx is the most common bug.
  • Forgetting the outside strategies. Indifference on the support is not enough. Line L7 must check every row and every column, also those outside the supports.
  • Accepting zero probabilities. A solution with yj=0y_j = 0 for some j∈Jj \in J belongs to a smaller support; accepting it gives duplicates, and with yj<0y_j < 0 it is not a strategy at all.
  • Assuming completeness on degenerate games. In A=(1001)A = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}, B=(1103)B = \begin{pmatrix} 1 & 1 \\ 0 & 3 \end{pmatrix}, row 0 has two best responses. The equilibria with x=(1,0)x = (1, 0) form the segment y=(p,1−p)y = (p, 1 - p) for p≥1/2p \ge 1/2; the method finds the end point y=(1,0)y = (1, 0) but not y=(1/2,1/2)y = (1/2, 1/2).
  • Floating point. With floats, the tests of lines L5 and L7 need tolerances, and a degenerate game can give false equilibria. Use rationals for an exact list.

Implementations

The Python code follows lines L1 to L8 in exact rational arithmetic and includes a test for nondegeneracy on small games. The tests check battle of the sexes, chicken, matching pennies, rock-paper-scissors, the coordination games InI_n with 2n−12^n - 1 equilibria, and the example above. On 60 random nondegenerate games, every output is checked as an equilibrium by all pure deviations, the number of equilibria is odd, the supports have equal sizes, and the list equals the one found by an independent vertex enumeration of the best response polytopes. On random degenerate games every output must still be an equilibrium and an extreme one, and the degenerate example of the pitfalls must show the missed end point.

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
support_enumeration.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/support-enumeration/. The authors are listed in prov/GHTYAP.jsonl.
"""Support enumeration for bimatrix games, in exact rational arithmetic.

The row player gets A[i][j] and the column player gets B[i][j]; both maximize. For a
nondegenerate game the function returns every Nash equilibrium. For a degenerate game
every pair it returns is still a Nash equilibrium, but it can miss equilibria.
"""

from fractions import Fraction
from itertools import combinations


def solve_square(K, b):
    """Return the unique solution z of K z = b, or None if K is singular."""
    r = len(K)
    rows = [[Fraction(v) for v in K[k]] + [Fraction(b[k])] for k in range(r)]
    for col in range(r):
        p = next((k for k in range(col, r) if rows[k][col] != 0), None)
        if p is None:
            return None
        rows[col], rows[p] = rows[p], rows[col]
        pv = rows[col][col]
        rows[col] = [v / pv for v in rows[col]]
        for k in range(r):
            f = rows[k][col]
            if k != col and f != 0:
                rows[k] = [a - f * c for a, c in zip(rows[k], rows[col])]
    return [rows[k][-1] for k in range(r)]


def _indifferent_mix(P, rows, cols):
    """Solve sum_{c in cols} P[r][c] z_c = u for r in rows and sum z_c = 1. Return (z, u) or None."""
    k = len(cols)
    K = [[P[r][c] for c in cols] + [-1] for r in rows] + [[1] * k + [0]]
    sol = solve_square(K, [0] * k + [1])
    if sol is None:
        return None
    return sol[:k], sol[k]


def support_enumeration(A, B):
    """Return the list of the Nash equilibria (x, y) found from supports of equal size."""
    A = [[Fraction(v) for v in row] for row in A]
    B = [[Fraction(v) for v in row] for row in B]
    m, n = len(A), len(A[0])
    Bt = [[B[i][j] for i in range(m)] for j in range(n)]  # Bt[j][i] = B[i][j]
    found = []
    for k in range(1, min(m, n) + 1):  # @line L1
        for I in combinations(range(m), k):  # @line L2
            for J in combinations(range(n), k):
                ys = _indifferent_mix(A, I, J)  # @line L3
                xs = _indifferent_mix(Bt, J, I)  # @line L4
                if ys is None or xs is None:  # @line L5
                    continue
                (yJ, u), (xI, v) = ys, xs
                if min(yJ) <= 0 or min(xI) <= 0:
                    continue
                x, y = [Fraction(0)] * m, [Fraction(0)] * n  # @line L6
                for i, p in zip(I, xI):
                    x[i] = p
                for j, q in zip(J, yJ):
                    y[j] = q
                row_pay = [sum((A[i][j] * y[j] for j in J), Fraction(0)) for i in range(m)]  # @line L7
                col_pay = [sum((x[i] * B[i][j] for i in I), Fraction(0)) for j in range(n)]
                if max(row_pay) <= u and max(col_pay) <= v:
                    found.append((x, y))  # @line L8
    return found


def is_nondegenerate(A, B):
    """Return True if no mixed strategy with support size s has more than s pure best responses.

    It checks the equivalent condition of von Stengel: for every set I of rows and every set J of
    columns with |J| > |I|, no x with support exactly I makes all columns of J best responses,
    and the same with the players swapped. It drops one tie at a time and needs the rest of the
    system to be nonsingular, so it can miss a degeneracy whose systems are all singular. It is
    exponential; use it on small games.
    """
    A = [[Fraction(v) for v in row] for row in A]
    B = [[Fraction(v) for v in row] for row in B]
    m, n = len(A), len(A[0])
    Bt = [[B[i][j] for i in range(m)] for j in range(n)]
    for P, r, c in ((Bt, m, n), (A, n, m)):
        # P[c'][r'] is the payoff of the responding player; r is the number of mixing strategies.
        for s in range(1, r + 1):
            for I in combinations(range(r), s):
                for J in combinations(range(c), s + 1):
                    if _has_mix_with_ties(P, I, J):
                        return False
    return True


def _has_mix_with_ties(P, I, J):
    """Is there a z > 0 on I (sum 1) that gives every response in J the same payoff, which is the best?"""
    # The s + 1 ties and the sum give s + 2 equations in s + 1 unknowns. Drop each tie in turn.
    for drop in J:
        J2 = tuple(j for j in J if j != drop)
        sol = _indifferent_mix(P, J2, I)
        if sol is None:
            continue
        z, u = sol
        if min(z) <= 0:
            continue
        pay = [sum((P[j][i] * zi for i, zi in zip(I, z)), Fraction(0)) for j in range(len(P))]
        if pay[drop] == u and max(pay) == u:
            return True
    return False
test_support_enumeration.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/support-enumeration/. The authors are listed in prov/GHTYAP.jsonl.

import random
from fractions import Fraction
from itertools import combinations

from agtgame import from_bimatrix, is_nash
from support_enumeration import is_nondegenerate, solve_square, support_enumeration

F = Fraction


def vertex_enumeration(A, B):
    """All extreme equilibria, from the vertices of the two best response polytopes.

    P = {x >= 0 : B'^T x <= 1} and Q = {y >= 0 : A' y <= 1}, with A', B' > 0. A vertex pair
    (x, y) other than (0, 0) whose labels cover all of rows and columns is an equilibrium.
    """
    m, n = len(A), len(A[0])
    shift = 1 - min(min(min(r) for r in A), min(min(r) for r in B))
    Ap = [[F(v) + shift for v in r] for r in A]
    Bp = [[F(v) + shift for v in r] for r in B]

    def vertices(cons, dim):
        # cons: list of (label, coefficients, rhs) for coefficients . z <= rhs.
        out = []
        for tight in combinations(range(len(cons)), dim):
            z = solve_square([cons[t][1] for t in tight], [cons[t][2] for t in tight])
            if z is None:
                continue
            if all(sum((c * v for c, v in zip(co, z)), F(0)) <= r for _, co, r in cons):
                labels = {lab for lab, co, r in cons if sum((c * v for c, v in zip(co, z)), F(0)) == r}
                if (z, labels) not in out:
                    out.append((z, labels))
        return out

    cp = [(i, [F(-int(k == i)) for k in range(m)], F(0)) for i in range(m)]
    cp += [(m + j, [Bp[i][j] for i in range(m)], F(1)) for j in range(n)]
    cq = [(i, Ap[i], F(1)) for i in range(m)]
    cq += [(m + j, [F(-int(k == j)) for k in range(n)], F(0)) for j in range(n)]
    eqs = []
    for x, lx in vertices(cp, m):
        for y, ly in vertices(cq, n):
            if any(x) and any(y) and lx | ly == set(range(m + n)):
                e = ([v / sum(x) for v in x], [v / sum(y) for v in y])
                if e not in eqs:
                    eqs.append(e)
    return eqs


def check_equilibria(A, B, eqs):
    game = from_bimatrix(A, B)
    for x, y in eqs:
        assert is_nash(game, [x, y])


def as_set(eqs):
    return {(tuple(x), tuple(y)) for x, y in eqs}


def test_battle_of_the_sexes():
    A, B = [[2, 0], [0, 1]], [[1, 0], [0, 2]]
    eqs = support_enumeration(A, B)
    assert as_set(eqs) == {((1, 0), (1, 0)), ((0, 1), (0, 1)), ((F(2, 3), F(1, 3)), (F(1, 3), F(2, 3)))}
    check_equilibria(A, B, eqs)
    x, y = eqs[2]
    assert sum(x[i] * y[j] * A[i][j] for i in range(2) for j in range(2)) == F(2, 3)


def test_zero_sum_check_values():
    MP = [[1, -1], [-1, 1]]
    RPS = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]
    for M in (MP, RPS):
        k = len(M)
        eqs = support_enumeration(M, [[-v for v in r] for r in M])
        assert eqs == [([F(1, k)] * k, [F(1, k)] * k)]


def test_chicken():
    A = [[0, 7], [2, 6]]  # strategy 0 is dare, 1 is chicken
    B = [[0, 2], [7, 6]]
    eqs = as_set(support_enumeration(A, B))
    assert eqs == {((1, 0), (0, 1)), ((0, 1), (1, 0)), ((F(1, 3), F(2, 3)), (F(1, 3), F(2, 3)))}


def test_page_example():
    A = [[3, 3], [2, 5], [0, 6]]
    B = [[3, 2], [2, 6], [3, 1]]
    assert is_nondegenerate(A, B)
    eqs = support_enumeration(A, B)
    assert as_set(eqs) == {((1, 0, 0), (1, 0)), ((F(4, 5), F(1, 5), 0), (F(2, 3), F(1, 3))),
                           ((0, F(1, 3), F(2, 3)), (F(1, 3), F(2, 3)))}
    assert as_set(eqs) == as_set(vertex_enumeration(A, B))


def test_coordination_game_has_one_equilibrium_per_support():
    for n in range(1, 5):
        I = [[int(i == j) for j in range(n)] for i in range(n)]
        eqs = support_enumeration(I, I)
        assert len(eqs) == 2 ** n - 1
        for x, y in eqs:
            k = sum(1 for v in x if v)
            assert x == y and all(v in (0, F(1, k)) for v in x)


def test_random_nondegenerate_games():
    rng = random.Random(4417)
    done = 0
    while done < 60:
        m, n = rng.randint(1, 4), rng.randint(1, 4)
        A = [[rng.randint(-50, 50) for _ in range(n)] for _ in range(m)]
        B = [[rng.randint(-50, 50) for _ in range(n)] for _ in range(m)]
        if not is_nondegenerate(A, B):
            continue
        done += 1
        eqs = support_enumeration(A, B)
        check_equilibria(A, B, eqs)
        assert len(eqs) % 2 == 1  # a nondegenerate game has an odd number of equilibria
        assert as_set(eqs) == as_set(vertex_enumeration(A, B))
        for x, y in eqs:  # supports of equal size
            assert sum(1 for v in x if v) == sum(1 for v in y if v)


def test_degenerate_game_misses_an_extreme_equilibrium():
    # Against row 0 both columns are best responses, so the game is degenerate.
    A = [[1, 0], [0, 1]]
    B = [[1, 1], [0, 3]]
    assert not is_nondegenerate(A, B)
    eqs = support_enumeration(A, B)
    check_equilibria(A, B, eqs)
    allv = as_set(vertex_enumeration(A, B))
    assert as_set(eqs) <= allv
    assert ((1, 0), (F(1, 2), F(1, 2))) in allv - as_set(eqs)


def test_random_degenerate_games_give_only_equilibria():
    rng = random.Random(90)
    for _ in range(80):
        m, n = rng.randint(1, 4), rng.randint(1, 4)
        A = [[rng.randint(0, 2) for _ in range(n)] for _ in range(m)]
        B = [[rng.randint(0, 2) for _ in range(n)] for _ in range(m)]
        eqs = support_enumeration(A, B)
        check_equilibria(A, B, eqs)
        assert as_set(eqs) <= as_set(vertex_enumeration(A, B))

History

Solving the indifference equations on a guessed support is the basic way to compute a mixed equilibrium by hand, and textbooks such as von Stengel's chapter in NRTV (2007) give it as the first exact method for bimatrix games, together with the fact that equilibrium supports have equal sizes in nondegenerate games. Porter, Nudelman and Shoham presented the ordered search at AAAI 2004 and in the journal version of 2008, and showed that it competes with Lemke-Howson on generated test games.

References

  1. Ryan Porter, Eugene Nudelman and Yoav Shoham, Simple search methods for finding a Nash equilibrium, Games and Economic Behavior 63(2) (2008), 642-662, the support search for two-player games, with the order of the supports by size and balance and the pruning by conditional dominance
  2. Noam Nisan, Tim Roughgarden, Éva Tardos and Vijay V. Vazirani (eds.), Algorithmic Game Theory, Cambridge University Press, 2007, Chapter 3 (Bernhard von Stengel, Equilibrium computation for two-player games in strategic and extensive form), nondegenerate games, equal support sizes and support enumeration
  3. Yoav Shoham and Kevin Leyton-Brown, Multiagent Systems, Algorithmic, Game-Theoretic, and Logical Foundations, Cambridge University Press, 2009, Chapter 4 (computing Nash equilibria of two-player general-sum games, the search over supports)

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