Algorithm Search⌘K

Algorithmcore

Lemke-Howson algorithm

Also called Lemke-Howson, complementary pivoting for bimatrix games.

Finds a Nash equilibrium of a nondegenerate bimatrix game by following a path of almost complementary vertices by pivoting.

Time
O(2^(m + n) (m + n)^3) worst
Space
O((m + n)^2) 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
Carlton E. Lemke, Joseph T. Howson Jr., 1964

The Lemke-Howson algorithm finds one Nash equilibrium of a two-player game in strategic form (a bimatrix game) by pivoting, as the simplex method does, on the two best response polytopes of the game. It starts at an artificial point that is not an equilibrium, drops one label, and follows a unique path of almost complementary vertices until the dropped label comes back, which happens exactly at an equilibrium. The problem itself and the other methods are on the Nash equilibrium computation page. It differs from Lemke's algorithm, which solves a general linear complementarity problem with an extra covering variable, and from support enumeration, which lists all equilibria by a search. The method assumes a nondegenerate game; for a degenerate game it needs a lexicographic pivot rule, which the code on this page uses.

In plain words

Draw for each player a shape whose corners are the useful ways to play, and tag each corner with labels: "this move is not used" or "this move of the other player is a best reply". An equilibrium is a pair of corners that together carry every label. The pair "nobody plays anything" also carries every label, but it is not a real answer. Start there and give up one chosen label. Now exactly one label is carried twice. Move one player along an edge to get rid of the double, which gives a new label to that player; if that label is again a double, move the other player. Each step is forced, the path never comes back, and it can end only when the given-up label returns, at an equilibrium.

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. The row player gets AijA_{ij} and the column player gets BijB_{ij}, and both maximize. The output is one Nash equilibrium (x,y)(x, y), x∈Δmx \in \Delta_m, y∈Δny \in \Delta_n. The test is the best response fact: xx is a best response to yy if and only if each row with xi>0x_i > 0 maximizes (Ay)i(Ay)_i, and the same for yy with the columns (xTB)j(x^{\mathsf T} B)_j.

Adding a constant to all entries of AA or of BB does not change the equilibria, so assume that A′=A+cA' = A + c and B′=B+dB' = B + d have all entries at least 1. The best response polytopes are

P={x∈Rm:x≥0,  B′Tx≤1},Q={y∈Rn:A′y≤1,  y≥0}.P = \{x \in \mathbb{R}^m : x \ge 0,\; B'^{\mathsf T} x \le \mathbf 1\}, \qquad Q = \{y \in \mathbb{R}^n : A' y \le \mathbf 1,\; y \ge 0\}.

Number the labels 0,…,m−10, \ldots, m - 1 for the rows and m,…,m+n−1m, \ldots, m + n - 1 for the columns. A point x∈Px \in P has label ii if xi=0x_i = 0 and label m+jm + j if (B′Tx)j=1(B'^{\mathsf T} x)_j = 1, that is, if column jj is a best response to xx. A point y∈Qy \in Q has label ii if (A′y)i=1(A' y)_i = 1 (row ii is a best response to yy) and label m+jm + j if yj=0y_j = 0. A pair (x,y)(x, y) is completely labeled if every label appears at xx or at yy. The completely labeled pairs other than (0,0)(0, 0) are exactly the equilibria, after scaling xx and yy to sum 1: a strategy is either unused or a best response.

The game is nondegenerate if no point of PP has more than mm labels and no point of QQ has more than nn, which is the same as: no mixed strategy with kk strategies in its support has more than kk pure best responses.

The algorithm

Write PP as the tableau T1T_1: B′Tx+s=1B'^{\mathsf T} x + s = \mathbf 1 with slack variables sjs_j, and QQ as the tableau T2T_2: r+A′y=1r + A' y = \mathbf 1 with slacks rir_i. Give xix_i and rir_i the label ii, and sjs_j and yjy_j the label m+jm + j. Then the labels of a vertex are the labels of its nonbasic variables, and the pair of basic solutions is completely labeled when no label is basic in both tableaux.

  1. LEMKE-HOWSON(A, B, k) ▷ labels 0..m-1 for rows, m..m+n-1 for columns; k is dropped
  2. 1shift A, B to A', B' ≥ 1; T1: B'ᵀ x + s = 1 with basis s; T2: r + A' y = 1 with basis r
  3. 2ℓ ← k; T ← T1 if k < m, else T2 ▷ start at the artificial pair (0, 0)
  4. 3repeat
  5. 4enter the variable with label ℓ into the basis of T; ℓ' ← the label of the leaving variable
  6. ▷ the minimum ratio test is lexicographic
  7. 5ℓ ← ℓ' ▷ ℓ is now nonbasic in both tableaux: the double label
  8. 6if ℓ = k then stop the loop ▷ k is back: the pair is completely labeled
  9. 7T ← the other tableau
  10. 8return x / Σ x and y / Σ y, read from T1 and T2

At each pair on the path every label except kk appears, and exactly one label, ℓ\ell, appears at both points. Line L4 removes ℓ\ell from the point where it was just picked up by moving the other point along an edge of its polytope, which is the only edge that keeps all the other labels. The leaving variable gives a new label, and if it is not kk it is the next double label.

Ties in the minimum ratio test of line L4 occur only in degenerate games. The lexicographic rule breaks them by comparing, after the right-hand side, the columns of the first basis, each divided by the pivot entry. This is the same as solving a slightly perturbed nondegenerate game, so the path is still unique and still ends.

Example

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

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},

with labels 0, 1, 2 for the rows and 3, 4 for the columns. The code shifts AA by 1, so A′=A+1A' = A + 1, and keeps B′=BB' = B. Its three equilibria, found by support enumeration, are ((1,0,0),(1,0))((1, 0, 0), (1, 0)), ((4/5,1/5,0),(2/3,1/3))((4/5, 1/5, 0), (2/3, 1/3)) and ((0,1/3,2/3),(1/3,2/3))((0, 1/3, 2/3), (1/3, 2/3)). The path for the dropped label k=1k = 1:

step tableau enters leaves point after the step labels of xx labels of yy
start x=(0,0,0)x = (0, 0, 0), y=(0,0)y = (0, 0) 0, 1, 2 3, 4
1 T1T_1 1 4 x=(0,1/6,0)x = (0, 1/6, 0) 0, 2, 4 3, 4
2 T2T_2 4 2 y=(0,1/7)y = (0, 1/7) 0, 2, 4 2, 3
3 T1T_1 2 3 x=(0,1/8,1/4)x = (0, 1/8, 1/4) 0, 3, 4 2, 3
4 T2T_2 3 1 y=(1/15,2/15)y = (1/15, 2/15) 0, 3, 4 1, 2

After step 4 label 1 is back, and scaling gives the equilibrium x=(0,1/3,2/3)x = (0, 1/3, 2/3), y=(1/3,2/3)y = (1/3, 2/3). The paths for all five labels:

dropped label pivots (enters, leaves) equilibrium reached
0 (0, 3), (3, 0) ((1,0,0),(1,0))((1, 0, 0), (1, 0))
1 (1, 4), (4, 2), (2, 3), (3, 1) ((0,1/3,2/3),(1/3,2/3))((0, 1/3, 2/3), (1/3, 2/3))
2 (2, 3), (3, 0), (0, 2) ((1,0,0),(1,0))((1, 0, 0), (1, 0))
3 (3, 0), (0, 3) ((1,0,0),(1,0))((1, 0, 0), (1, 0))
4 (4, 2), (2, 3), (3, 1), (1, 4) ((0,1/3,2/3),(1/3,2/3))((0, 1/3, 2/3), (1/3, 2/3))

The middle equilibrium ((4/5,1/5,0),(2/3,1/3))((4/5, 1/5, 0), (2/3, 1/3)) is reached from no label. For each label, the path from (0,0)(0, 0) uses one of the other two equilibria as its end, and the remaining two equilibria are the two ends of a second path with the same dropped label. 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 labels 0 and 2 lead to ((1,0),(1,0))((1, 0), (1, 0)), the labels 1 and 3 lead to ((0,1),(0,1))((0, 1), (0, 1)), and the mixed equilibrium ((2/3,1/3),(1/3,2/3))((2/3, 1/3), (1/3, 2/3)) is never reached from (0,0)(0, 0).

Correctness

Fix the dropped label kk and look at the graph whose nodes are the vertex pairs (x,y)∈P×Q(x, y) \in P \times Q that have every label except possibly kk, with an edge between two pairs that differ by one pivot in one polytope and keep all labels other than kk. In a nondegenerate game:

  • a completely labeled pair, which is (0,0)(0, 0) or an equilibrium, has exactly one neighbor: the edge that drops label kk at the point that has it;
  • every other pair has exactly one double label, and exactly two neighbors: drop the double label at xx, or drop it at yy.

So the graph is a union of disjoint paths and cycles, and the ends of the paths are the completely labeled pairs. The path that starts at (0,0)(0, 0) cannot cycle and cannot stop in the middle, and the polytopes are bounded, so a pivot row always exists in line L4. The graph is finite, so the path ends at another completely labeled pair, which is an equilibrium. The proof file gives the details, also for the lexicographic rule.

The same argument shows that a nondegenerate game has an odd number of equilibria: the completely labeled pairs are matched in pairs by the paths of label kk, and one of them is the artificial pair (0,0)(0, 0). It is the two-player case of the Nash existence theorem, with a constructive proof.

Proof: The Lemke-Howson path from the artificial pair ends at a Nash equilibriumfull

Let (A,B)(A, B) be an m×nm \times n bimatrix game, shifted so that all entries of A′A' and B′B' are at least 1. Let P={x≥0:B′Tx≤1}P = \{x \ge 0 : B'^{\mathsf T} x \le \mathbf 1\} and Q={y≥0:A′y≤1}Q = \{y \ge 0 : A' y \le \mathbf 1\}, with the labels of the page: xx has label ii if xi=0x_i = 0 and label m+jm + j if (B′Tx)j=1(B'^{\mathsf T} x)_j = 1; yy has label ii if (A′y)i=1(A' y)_i = 1 and label m+jm + j if yj=0y_j = 0. Write L(x)L(x) and L(y)L(y) for the sets of labels, and N={0,…,m+n−1}N = \{0, \ldots, m + n - 1\}.

Lemma 1 (bounded polytopes). PP and QQ are bounded, and they are full-dimensional with 00 as a vertex.

Proof. For x∈Px \in P and each ii, xi≤∑rBr0′xr≤1x_i \le \sum_r B'_{r0} x_r \le 1, because Br0′≥1B'_{r0} \ge 1 and x≥0x \ge 0. The same holds for QQ. The point 00 satisfies the mm independent constraints x≥0x \ge 0 with equality, and a small positive xx is inside PP. □\square

Lemma 2 (completely labeled pairs). (x,y)∈P×Q(x, y) \in P \times Q with L(x)∪L(y)=NL(x) \cup L(y) = N and (x,y)≠(0,0)(x, y) \ne (0, 0) gives a Nash equilibrium (x/∑ixi,y/∑jyj)(x / \sum_i x_i, y / \sum_j y_j), and every Nash equilibrium arises in this way.

Proof. Suppose L(x)∪L(y)=NL(x) \cup L(y) = N and x≠0x \ne 0. If y=0y = 0, then no label i<mi < m is at yy, so all of them are at xx and x=0x = 0, a contradiction; so y≠0y \ne 0, and in the same way x≠0x \ne 0 when y≠0y \ne 0. Let xˉ=x/∑x\bar x = x / \sum x, yˉ=y/∑y\bar y = y / \sum y. For each row ii with xi>0x_i > 0, the label ii is not at xx, so it is at yy: (A′y)i=1=max⁡r(A′y)r(A'y)_i = 1 = \max_r (A'y)_r, so row ii is a best response to yˉ\bar y in A′A', and so in AA, since the shift adds the same constant to every row. By the same argument every column in the support of yˉ\bar y is a best response to xˉ\bar x, and by the best response fact the pair is an equilibrium.

Conversely, let (xˉ,yˉ)(\bar x, \bar y) be an equilibrium, u=max⁡r(A′yˉ)r>0u = \max_r (A' \bar y)_r > 0 and v=max⁡c(B′Txˉ)c>0v = \max_c (B'^{\mathsf T} \bar x)_c > 0. Then y=yˉ/u∈Qy = \bar y / u \in Q and x=xˉ/v∈Px = \bar x / v \in P, and each row with xˉi>0\bar x_i > 0 is a best response, so it has (A′y)i=1(A'y)_i = 1; hence label ii is at xx or at yy. The same holds for the columns. □\square

Lemma 3 (the graph). Assume the game is nondegenerate: every x∈Px \in P has at most mm labels and every y∈Qy \in Q at most nn. Fix k∈Nk \in N. Let GkG_k be the graph whose nodes are the pairs of vertices (x,y)(x, y) of P×QP \times Q with L(x)∪L(y)⊇N∖{k}L(x) \cup L(y) \supseteq N \setminus \{k\}, and whose edges join (x,y)(x, y) to (x′,y)(x', y) when xx′x x' is an edge of PP, or to (x,y′)(x, y') when yy′y y' is an edge of QQ. Then every completely labeled node has degree 1 and every other node has degree 2.

Proof. By nondegeneracy, a vertex xx of PP has exactly mm labels, and for each ℓ∈L(x)\ell \in L(x) there is exactly one edge of PP from xx on which the labels L(x)∖{ℓ}L(x) \setminus \{\ell\} stay and ℓ\ell is dropped; its other end x′x' has the labels L(x)∖{ℓ}L(x) \setminus \{\ell\} plus exactly one new label. The same holds for QQ. Since ∣L(x)∣+∣L(y)∣=m+n=∣N∣|L(x)| + |L(y)| = m + n = |N|, a node with L(x)∪L(y)=NL(x) \cup L(y) = N has no repeated label, and the only move that keeps all of N∖{k}N \setminus \{k\} drops kk at the point that has it: one neighbor. A node that misses kk has ∣L(x)∪L(y)∣=m+n−1|L(x) \cup L(y)| = m + n - 1, so exactly one label ℓ\ell is at both points; the moves that keep N∖{k}N \setminus \{k\} are to drop ℓ\ell at xx or to drop ℓ\ell at yy: two neighbors. □\square

Theorem 1. For a nondegenerate game and any kk, lines L1 to L8 end, and they return a Nash equilibrium.

Proof. The tableaux T1T_1 and T2T_2 have the basic solutions xx and yy; the nonbasic variables are zero, and they carry the labels of the vertex, because a zero slack sjs_j means (B′Tx)j=1(B'^{\mathsf T} x)_j = 1 and a zero slack rir_i means (A′y)i=1(A'y)_i = 1. At line L2 the pair is (0,0)(0, 0), which is completely labeled. Line L4 enters the variable with label ℓ\ell: in the polytope of TT this moves along the edge that drops label ℓ\ell, and the ratio test picks the end of the edge; the edge is finite by Lemma 1, so a row with a positive pivot entry exists. The leaving variable becomes nonbasic, which is the new label ℓ′\ell'. So each iteration is one step along GkG_k from the current node to a neighbor. The first step leaves (0,0)(0, 0) by its only edge. After that, the next step drops the double label at the other point (line L7), which is the neighbor other than the one we came from.

So the algorithm walks along the component of GkG_k that contains (0,0)(0, 0). By Lemma 3 that component is a path, since a cycle has no node of degree 1. A path visits no node twice, and GkG_k is finite, so the walk ends, at the other end of the path. The walk stops when the leaving label is kk (line L6), which is when the pair becomes completely labeled, and that end is not (0,0)(0, 0). By Lemma 2, line L8 returns a Nash equilibrium. □\square

Corollary (odd number). A nondegenerate game has an odd number of Nash equilibria.

Proof. The nodes of degree 1 in GkG_k are the completely labeled pairs, and they are the ends of the paths of GkG_k, two per path. So their number is even. One of them is (0,0)(0, 0), and by Lemma 2 the others are in one-to-one correspondence with the equilibria. □\square

Degenerate games and the lexicographic rule. Replace the right-hand side 1\mathbf 1 of both tableaux by 1+(ε,ε2,…)\mathbf 1 + (\varepsilon, \varepsilon^2, \ldots) for a small ε>0\varepsilon > 0. For all small enough ε\varepsilon the perturbed polytopes are nondegenerate, because a point with an extra label would solve one more equation than its dimension allows, which happens for only finitely many ε\varepsilon. The ratio test on the perturbed tableau compares the values (rhs+∑tεtβt)/a(\text{rhs} + \sum_t \varepsilon^t \beta_t) / a, where the βt\beta_t are the entries in the columns of the first basis; for small ε\varepsilon this is the lexicographic comparison of the vector (rhs, the first basis columns) divided by the pivot entry aa, which is what the code does. The rows of the first basis columns are the rows of the inverse of the current basis, so they are linearly independent, and the lexicographic minimum is unique. So the code follows the path of the perturbed game, which ends by Theorem 1. At the end the pair is completely labeled for the perturbed game; the labels of the unperturbed pair include them, since letting ε\varepsilon tend to 0 keeps every equation, so the result is completely labeled for the original game. It is not (0,0)(0, 0). Suppose x=0x = 0. Then s=1s = \mathbf 1, so all nn slacks are basic and T1T_1 has its first basis. The labels m,…,m+n−1m, \ldots, m + n - 1 are not at x=0x = 0, because s>0s > 0, so they are at yy, which gives y=0y = 0, and in the same way T2T_2 has its first basis. Then the end pair of bases is the start pair, which is impossible, because the perturbed path ends at a node other than its start. By Lemma 2 it is an equilibrium of the original game.

Complexity

Each pivot costs O((m+n)max⁡(m,n))O((m + n) \max(m, n)) arithmetic operations on the tableau. The path visits each pair of vertices at most once. A vertex of PP in a nondegenerate game is fixed by its mm labels, and given the labels of xx, at most m+n+1m + n + 1 sets of labels for yy complete them up to label kk, so the path has at most (m+nm)(m+n+1)\binom{m+n}{m}(m + n + 1) steps. This gives the worst-case bound O(2m+n(m+n)3)O(2^{m+n}(m + n)^3).

The exponential bound is real: Savani and von Stengel (2006) built square games on which every Lemke-Howson path, for every dropped label, is exponentially long in the number of strategies (Savani-von Stengel theorem). Goldberg, Papadimitriou and Savani (2013) showed that computing any equilibrium that the Lemke-Howson algorithm would find is PSPACE-complete. Finding some equilibrium of a bimatrix game is PPAD-complete (Chen, Deng and Teng), and the path structure above is the reason it lies in PPAD: it is an instance of the end of the line problem. By the same work of Chen, Deng and Teng, no algorithm runs in polynomial time in the smoothed analysis model unless PPAD is in RP. In practice the paths are often short.

With exact rational arithmetic the numbers in the tableau stay of polynomial bit length, as in the simplex method, and the result is the exact rational equilibrium. Two-player games always have rational equilibria; games with three or more players can have only irrational ones, so no method of this kind works there. The space is two tableaux, O((m+n)2)O((m + n)^2) numbers.

Properties

  • Exact. With rationals, the output is an exact equilibrium.
  • One equilibrium per label. Each dropped label gives one equilibrium. Different labels can give the same one, and some equilibria are reached from no label (the middle one in the example).
  • Not all equilibria. Starting from an equilibrium instead of (0,0)(0, 0) reaches more of them, but even the graph of all such paths does not have to connect all equilibria.
  • Deterministic. The label and the pivot rule fix the path.

Variants and improvements

  • Lemke's algorithm. The pair of conditions 0≤x⊥1−A′y≥00 \le x \perp \mathbf 1 - A' y \ge 0 and 0≤y⊥1−B′Tx≥00 \le y \perp \mathbf 1 - B'^{\mathsf T} x \ge 0 is a linear complementarity problem with q=1q = \mathbf 1, whose trivial solution (0,0)(0, 0) is the artificial start of this method. Lemke's algorithm uses an equivalent form with positive cost matrices and q=−1q = -\mathbf 1, and a covering vector instead of a dropped label.
  • Starting from other points. With a covering vector chosen from a given pair of mixed strategies, a Lemke path can start from that pair instead of from (0,0)(0, 0), and so it can give other equilibria.
  • Degenerate games. The lexicographic rule of line L4, or a perturbation of the right-hand side by (ε,ε2,…)(\varepsilon, \varepsilon^2, \ldots), makes the path unique.
  • Integer pivoting. Keeping the tableau in integers, with all entries divided by the previous pivot element, avoids fractions and keeps the numbers small.
  • All equilibria. For the full list use support enumeration or the enumeration of the vertices of both polytopes.

When to use it

Use it to find one exact equilibrium of a general-sum bimatrix game of moderate size, where support enumeration is too slow. Use the LP if the game is zero-sum, because that takes polynomial time. Do not use it to select a specific equilibrium, such as the one with the best welfare: it gives an arbitrary one, and selection is NP-hard in general. For games with more than two players use other methods, such as Scarf's algorithm for approximate fixed points.

Pitfalls

  • Ignoring degeneracy. With the plain minimum ratio test, a tie in a degenerate game can make the path cycle or end at a pair that is not completely labeled. Use the lexicographic rule.
  • Mixing up the matrices. PP uses BB, the payoffs of the column player, because the labels of xx say which columns are best responses to xx. QQ uses AA.
  • Forgetting the shift. With zero or negative entries the polytopes are not bounded, and the method breaks. Shift both matrices to positive entries first; the equilibria do not change.
  • Forgetting to scale. The vertex pair is not a pair of strategies until xx and yy are divided by their sums.
  • Expecting a polynomial bound. The method is exponential in the worst case, even if it is fast on most games.

Implementations

The Python code keeps the two tableaux in Fraction, with the column index equal to the label, and pivots by lines L1 to L8 with the lexicographic minimum ratio test; it can record the trace of pivots. The tests check the traces of the example for all five labels, battle of the sexes, matching pennies and rock-paper-scissors (the uniform pair from every label), and that shifting the payoffs does not change the result. On 60 random nondegenerate games, every output for every label is checked as an equilibrium by all pure deviations and must be one of the equilibria found by an independent support enumeration, whose number must be odd. On 150 random degenerate games with many ties, and on a constant game, every path must end at an equilibrium.

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
lemke_howson_algorithm.py 95 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lemke-howson-algorithm/. The authors are listed in prov/W47DAN.jsonl.
"""The Lemke-Howson algorithm for bimatrix games, with exact tableaux in Fraction.

The row player gets A[i][j] and the column player gets B[i][j]; both maximize. The labels
are 0, ..., m - 1 for the rows and m, ..., m + n - 1 for the columns. The minimum ratio test
is lexicographic, so the method also ends on degenerate games.
"""

from fractions import Fraction


def _positive(P):
    k = 1 - min(min(row) for row in P)
    return [[Fraction(v) + max(k, 0) for v in row] for row in P]


class _Tableau:
    """Rows of the system  coefficients . z = 1, with a basis. Column index = label."""

    def __init__(self, rows, basis, slack_cols):
        self.rows = rows  # each row: [coefficients for the m + n labels] + [rhs]
        self.basis = basis
        self.slack_cols = slack_cols  # the columns of the first basis, for the lexicographic rule

    def pivot_in(self, col):
        """Enter column col; return the label of the leaving variable."""
        best, best_r = None, None
        for r, row in enumerate(self.rows):
            a = row[col]
            if a > 0:
                key = tuple(row[c] / a for c in [-1] + self.slack_cols)
                if best is None or key < best:
                    best, best_r = key, r
        if best_r is None:
            raise AssertionError("the polytope is bounded, so a pivot row exists")
        row = self.rows[best_r]
        p = row[col]
        row = [v / p for v in row]
        self.rows[best_r] = row
        for r in range(len(self.rows)):
            f = self.rows[r][col]
            if r != best_r and f != 0:
                self.rows[r] = [a - f * b for a, b in zip(self.rows[r], row)]
        leaving = self.basis[best_r]
        self.basis[best_r] = col
        return leaving

    def values(self, size):
        z = [Fraction(0)] * size
        for r, c in enumerate(self.basis):
            z[c] = self.rows[r][-1]
        return z


def lemke_howson(A, B, k=0, trace=None):
    """Return a Nash equilibrium (x, y) of the bimatrix game (A, B), from the missing label k.

    If trace is a list, the pair (entering label, leaving label) of each pivot is appended to it.
    """
    m, n = len(A), len(A[0])
    if not 0 <= k < m + n:
        raise ValueError("the missing label must be in 0 .. m + n - 1")
    Ap, Bp = _positive(A), _positive(B)
    one = Fraction(1)
    # T1: B'^T x + s = 1, columns x_0..x_(m-1) (labels 0..m-1), s_0..s_(n-1) (labels m..).
    t1 = _Tableau([[Bp[i][j] for i in range(m)] + [Fraction(int(c == j)) for c in range(n)] + [one]
                   for j in range(n)], list(range(m, m + n)), list(range(m, m + n)))  # @line L1
    # T2: r + A' y = 1, columns r_0..r_(m-1) (labels 0..m-1), y_0..y_(n-1) (labels m..).
    t2 = _Tableau([[Fraction(int(c == i)) for c in range(m)] + Ap[i] + [one] for i in range(m)],
                  list(range(m)), list(range(m)))
    label = k  # @line L2
    tab = t1 if k < m else t2
    while True:  # @line L3
        leaving = tab.pivot_in(label)  # @line L4
        if trace is not None:
            trace.append((label, leaving))
        label = leaving  # @line L5
        if label == k:  # @line L6
            break
        tab = t2 if tab is t1 else t1  # @line L7
    x = t1.values(m + n)[:m]  # @line L8
    y = t2.values(m + n)[m:]
    sx, sy = sum(x), sum(y)
    return [v / sx for v in x], [v / sy for v in y]


def all_lemke_howson(A, B):
    """Return the distinct equilibria reached from the artificial equilibrium by each label."""
    out = []
    for k in range(len(A) + len(A[0])):
        eq = lemke_howson(A, B, k)
        if eq not in out:
            out.append(eq)
    return out
test_lemke_howson_algorithm.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lemke-howson-algorithm/. The authors are listed in prov/W47DAN.jsonl.

import random
from fractions import Fraction
from itertools import combinations

from agtgame import from_bimatrix, is_nash
from lemke_howson_algorithm import all_lemke_howson, lemke_howson

F = Fraction


def solve_square(K, b):
    r = len(K)
    rows = [[F(v) for v in K[k]] + [F(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]
        rows[col] = [v / rows[col][col] 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 support_enumeration(A, B):
    """Independent check: equilibria from supports of equal size (all of them if nondegenerate)."""
    m, n = len(A), len(A[0])
    out = []
    for k in range(1, min(m, n) + 1):
        for I in combinations(range(m), k):
            for J in combinations(range(n), k):
                sy = solve_square([[A[i][j] for j in J] + [-1] for i in I] + [[1] * k + [0]], [0] * k + [1])
                sx = solve_square([[B[i][j] for i in I] + [-1] for j in J] + [[1] * k + [0]], [0] * k + [1])
                if sy is None or sx is None or min(sy[:k]) <= 0 or min(sx[:k]) <= 0:
                    continue
                x, y = [F(0)] * m, [F(0)] * n
                for i, p in zip(I, sx):
                    x[i] = p
                for j, q in zip(J, sy):
                    y[j] = q
                if all(sum(A[i][j] * y[j] for j in J) <= sy[k] for i in range(m)) and \
                        all(sum(x[i] * B[i][j] for i in I) <= sx[k] for j in range(n)):
                    out.append((tuple(x), tuple(y)))
    return out


def nondegenerate(A, B):
    """True if no strategy with support size s has more than s pure best responses (checked on vertices)."""
    m, n = len(A), len(A[0])
    for P, r, c in (([[B[i][j] for i in range(m)] for j in range(n)], m, n), (A, n, m)):
        # P[j][i]: payoff to the responder for response j against the mixer's strategy i.
        for s in range(1, r + 1):
            for I in combinations(range(r), s):
                for J in combinations(range(c), s):
                    sol = solve_square([[P[j][i] for i in I] + [-1] for j in J] + [[1] * s + [0]], [0] * s + [1])
                    if sol is None:
                        if s == 1:
                            continue
                        return False  # a singular system: treat as degenerate to be safe
                    z, u = sol[:s], sol[s]
                    if min(z) <= 0:
                        continue
                    pay = [sum(P[j][i] * zi for i, zi in zip(I, z)) for j in range(c)]
                    if max(pay) == u and sum(1 for v in pay if v == u) > s:
                        return False
    return True


def tup(eq):
    return tuple(eq[0]), tuple(eq[1])


def check(A, B, eq):
    assert is_nash(from_bimatrix(A, B), [eq[0], eq[1]])


def test_page_example_traces():
    A = [[3, 3], [2, 5], [0, 6]]
    B = [[3, 2], [2, 6], [3, 1]]
    paths = {
        0: ([(0, 3), (3, 0)], ((1, 0, 0), (1, 0))),
        1: ([(1, 4), (4, 2), (2, 3), (3, 1)], ((0, F(1, 3), F(2, 3)), (F(1, 3), F(2, 3)))),
        2: ([(2, 3), (3, 0), (0, 2)], ((1, 0, 0), (1, 0))),
        3: ([(3, 0), (0, 3)], ((1, 0, 0), (1, 0))),
        4: ([(4, 2), (2, 3), (3, 1), (1, 4)], ((0, F(1, 3), F(2, 3)), (F(1, 3), F(2, 3)))),
    }
    for k, (want_trace, want_eq) in paths.items():
        trace = []
        eq = lemke_howson(A, B, k, trace)
        assert trace == want_trace
        assert tup(eq) == want_eq
        check(A, B, eq)
    # The middle equilibrium exists but no path from the artificial equilibrium ends there.
    every = set(support_enumeration(A, B))
    reached = {tup(e) for e in all_lemke_howson(A, B)}
    assert every - reached == {((F(4, 5), F(1, 5), 0), (F(2, 3), F(1, 3)))}


def test_battle_of_the_sexes():
    A, B = [[2, 0], [0, 1]], [[1, 0], [0, 2]]
    for k, want in ((0, ((1, 0), (1, 0))), (2, ((1, 0), (1, 0))), (1, ((0, 1), (0, 1))), (3, ((0, 1), (0, 1)))):
        assert tup(lemke_howson(A, B, k)) == want


def test_zero_sum_games():
    for M in ([[1, -1], [-1, 1]], [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]):
        k = len(M)
        for lab in range(2 * k):
            eq = lemke_howson(M, [[-v for v in r] for r in M], lab)
            assert tup(eq) == (tuple([F(1, k)] * k), tuple([F(1, k)] * k))


def test_negative_payoffs_and_shift():
    # Shifting all payoffs does not change the equilibria or the path.
    A = [[-7, -2], [-3, -9]]
    B = [[-1, -8], [-6, -2]]
    for k in range(4):
        assert lemke_howson(A, B, k) == lemke_howson([[v + 20 for v in r] for r in A],
                                                     [[v + 20 for v in r] for r in B], k)


def test_random_nondegenerate_games():
    rng = random.Random(3301)
    done = 0
    while done < 60:
        m, n = rng.randint(1, 4), rng.randint(1, 4)
        A = [[rng.randint(-30, 30) for _ in range(n)] for _ in range(m)]
        B = [[rng.randint(-30, 30) for _ in range(n)] for _ in range(m)]
        if not nondegenerate(A, B):
            continue
        done += 1
        every = set(support_enumeration(A, B))
        assert len(every) % 2 == 1
        for k in range(m + n):
            eq = lemke_howson(A, B, k)
            check(A, B, eq)
            assert tup(eq) in every


def test_degenerate_games_end_at_an_equilibrium():
    rng = random.Random(55)
    for _ in range(150):
        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)]
        for k in range(m + n):
            check(A, B, lemke_howson(A, B, k))


def test_constant_game():
    # Every profile is an equilibrium; the lexicographic rule still gives a finite path.
    A = [[1, 1, 1], [1, 1, 1]]
    for k in range(5):
        check(A, A, lemke_howson(A, A, k))


def test_bad_label():
    try:
        lemke_howson([[1]], [[1]], 2)
    except ValueError:
        return
    raise AssertionError("expected ValueError")

History

Lemke and Howson published the method in 1964. It gave an algorithmic proof that bimatrix games have equilibria, and the parity result, and Lemke extended it in 1965 to a general method for linear complementarity problems. Savani and von Stengel (2006) answered the question of its worst case with games on which all paths are exponentially long, and Goldberg, Papadimitriou and Savani (2013) showed that the specific equilibria it finds are PSPACE-complete to compute.

References

  1. C. E. Lemke and J. T. Howson Jr., Equilibrium points of bimatrix games, Journal of the Society for Industrial and Applied Mathematics 12(2) (1964), 413-423, the complementary pivoting method for bimatrix games and the parity of the number of equilibria
  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), best response polytopes, labels and the Lemke-Howson paths
  3. Rahul Savani and Bernhard von Stengel, Hard-to-solve bimatrix games, Econometrica 74(2) (2006), 397-429, games on which every Lemke-Howson path, from every missing label, is exponentially long
  4. Paul W. Goldberg, Christos H. Papadimitriou and Rahul Savani, The complexity of the homotopy method, equilibrium selection, and Lemke-Howson solutions, ACM Transactions on Economics and Computation 1(2) (2013), article 9, Theorem 7 (finding any of the equilibria that the Lemke-Howson algorithm constructs is PSPACE-complete)

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