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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 matrices and with rational entries. On this page and are the numbers of pure strategies of the row player and the column player, not the number of players. The row player gets and the column player gets , and both maximize. The output is one Nash equilibrium , , . The test is the best response fact: is a best response to if and only if each row with maximizes , and the same for with the columns .
Adding a constant to all entries of or of does not change the equilibria, so assume that and have all entries at least 1. The best response polytopes are
Number the labels for the rows and for the columns. A point has label if and label if , that is, if column is a best response to . A point has label if (row is a best response to ) and label if . A pair is completely labeled if every label appears at or at . The completely labeled pairs other than are exactly the equilibria, after scaling and to sum 1: a strategy is either unused or a best response.
The game is nondegenerate if no point of has more than labels and no point of has more than , which is the same as: no mixed strategy with strategies in its support has more than pure best responses.
The algorithm
Write as the tableau : with slack variables , and as the tableau : with slacks . Give and the label , and and the label . 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.
LEMKE-HOWSON(A, B, k) ▷ labels 0..m-1 for rows, m..m+n-1 for columns; k is dropped- 1
shift A, B to A', B' ≥ 1; T1: B'ᵀ x + s = 1 with basis s; T2: r + A' y = 1 with basis r - 2
ℓ ← k; T ← T1 if k < m, else T2 ▷ start at the artificial pair (0, 0) - 3
repeat - 4
enter the variable with label ℓ into the basis of T; ℓ' ← the label of the leaving variable ▷ the minimum ratio test is lexicographic- 5
ℓ ← ℓ' ▷ ℓ is now nonbasic in both tableaux: the double label - 6
if ℓ = k then stop the loop ▷ k is back: the pair is completely labeled - 7
T ← the other tableau - 8
return x / Σ x and y / Σ y, read from T1 and T2
At each pair on the path every label except appears, and exactly one label, , appears at both points. Line L4 removes 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 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 game of von Stengel's chapter in NRTV,
with labels 0, 1, 2 for the rows and 3, 4 for the columns. The code shifts by 1, so , and keeps . Its three equilibria, found by support enumeration, are , and . The path for the dropped label :
| step | tableau | enters | leaves | point after the step | labels of | labels of |
|---|---|---|---|---|---|---|
| start | , | 0, 1, 2 | 3, 4 | |||
| 1 | 1 | 4 | 0, 2, 4 | 3, 4 | ||
| 2 | 4 | 2 | 0, 2, 4 | 2, 3 | ||
| 3 | 2 | 3 | 0, 3, 4 | 2, 3 | ||
| 4 | 3 | 1 | 0, 3, 4 | 1, 2 |
After step 4 label 1 is back, and scaling gives the equilibrium , . The paths for all five labels:
| dropped label | pivots (enters, leaves) | equilibrium reached |
|---|---|---|
| 0 | (0, 3), (3, 0) | |
| 1 | (1, 4), (4, 2), (2, 3), (3, 1) | |
| 2 | (2, 3), (3, 0), (0, 2) | |
| 3 | (3, 0), (0, 3) | |
| 4 | (4, 2), (2, 3), (3, 1), (1, 4) |
The middle equilibrium is reached from no label. For each label, the path from 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, and , the labels 0 and 2 lead to , the labels 1 and 3 lead to , and the mixed equilibrium is never reached from .
Correctness
Fix the dropped label and look at the graph whose nodes are the vertex pairs that have every label except possibly , with an edge between two pairs that differ by one pivot in one polytope and keep all labels other than . In a nondegenerate game:
- a completely labeled pair, which is or an equilibrium, has exactly one neighbor: the edge that drops label at the point that has it;
- every other pair has exactly one double label, and exactly two neighbors: drop the double label at , or drop it at .
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 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 , and one of them is the artificial pair . 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 be an bimatrix game, shifted so that all entries of and are at least 1. Let and , with the labels of the page: has label if and label if ; has label if and label if . Write and for the sets of labels, and .
Lemma 1 (bounded polytopes). and are bounded, and they are full-dimensional with as a vertex.
Proof. For and each , , because and . The same holds for . The point satisfies the independent constraints with equality, and a small positive is inside .
Lemma 2 (completely labeled pairs). with and gives a Nash equilibrium , and every Nash equilibrium arises in this way.
Proof. Suppose and . If , then no label is at , so all of them are at and , a contradiction; so , and in the same way when . Let , . For each row with , the label is not at , so it is at : , so row is a best response to in , and so in , since the shift adds the same constant to every row. By the same argument every column in the support of is a best response to , and by the best response fact the pair is an equilibrium.
Conversely, let be an equilibrium, and . Then and , and each row with is a best response, so it has ; hence label is at or at . The same holds for the columns.
Lemma 3 (the graph). Assume the game is nondegenerate: every has at most labels and every at most . Fix . Let be the graph whose nodes are the pairs of vertices of with , and whose edges join to when is an edge of , or to when is an edge of . Then every completely labeled node has degree 1 and every other node has degree 2.
Proof. By nondegeneracy, a vertex of has exactly labels, and for each there is exactly one edge of from on which the labels stay and is dropped; its other end has the labels plus exactly one new label. The same holds for . Since , a node with has no repeated label, and the only move that keeps all of drops at the point that has it: one neighbor. A node that misses has , so exactly one label is at both points; the moves that keep are to drop at or to drop at : two neighbors.
Theorem 1. For a nondegenerate game and any , lines L1 to L8 end, and they return a Nash equilibrium.
Proof. The tableaux and have the basic solutions and ; the nonbasic variables are zero, and they carry the labels of the vertex, because a zero slack means and a zero slack means . At line L2 the pair is , which is completely labeled. Line L4 enters the variable with label : in the polytope of this moves along the edge that drops label , 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 . So each iteration is one step along from the current node to a neighbor. The first step leaves 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 that contains . By Lemma 3 that component is a path, since a cycle has no node of degree 1. A path visits no node twice, and is finite, so the walk ends, at the other end of the path. The walk stops when the leaving label is (line L6), which is when the pair becomes completely labeled, and that end is not . By Lemma 2, line L8 returns a Nash equilibrium.
Corollary (odd number). A nondegenerate game has an odd number of Nash equilibria.
Proof. The nodes of degree 1 in are the completely labeled pairs, and they are the ends of the paths of , two per path. So their number is even. One of them is , and by Lemma 2 the others are in one-to-one correspondence with the equilibria.
Degenerate games and the lexicographic rule. Replace the right-hand side of both tableaux by for a small . For all small enough 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 . The ratio test on the perturbed tableau compares the values , where the are the entries in the columns of the first basis; for small this is the lexicographic comparison of the vector (rhs, the first basis columns) divided by the pivot entry , 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 tend to 0 keeps every equation, so the result is completely labeled for the original game. It is not . Suppose . Then , so all slacks are basic and has its first basis. The labels are not at , because , so they are at , which gives , and in the same way 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 arithmetic operations on the tableau. The path visits each pair of vertices at most once. A vertex of in a nondegenerate game is fixed by its labels, and given the labels of , at most sets of labels for complete them up to label , so the path has at most steps. This gives the worst-case bound .
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, 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 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 and is a linear complementarity problem with , whose trivial solution is the artificial start of this method. Lemke's algorithm uses an equivalent form with positive cost matrices and , 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 , and so it can give other equilibria.
- Degenerate games. The lexicographic rule of line L4, or a perturbation of the right-hand side by , 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. uses , the payoffs of the column player, because the labels of say which columns are best responses to . uses .
- 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 and 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag W47DAN Edit this page History Report an error Markdown