Algorithmadvanced
Lemke's algorithm
Also called Lemke's complementary pivot algorithm.
Solves a linear complementarity problem by adding an artificial variable and pivoting along almost complementary bases until it leaves.
- Time
- O(2^n n^3) worst
- Space
- O(n^2) extra
- Where
- n = the size of the matrix M (the number of complementary pairs)
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Carlton E. Lemke, 1965
Lemke's algorithm solves a linear complementarity problem (LCP): given an matrix and a vector , find with and for each . In a contact simulation, is the impulse or force at contact , is the gap velocity there, and the condition says that a contact pushes only while it is closed and never pulls (rigid contact complementarity). The method is a pivoting method like the simplex method: it adds one artificial variable that makes the start feasible, then follows a unique path of bases in which every pair has at least one zero, except one pair, until leaves the basis. It gives an exact solution in a finite number of steps for important classes of , and it can end on an unbounded edge, a ray, for others. Iterative methods such as projected Gauss-Seidel are cheaper per step and are the usual choice in real-time physics, but they give only approximations. Lemke's algorithm generalizes the Lemke-Howson algorithm, which is the special case for the equilibria of two-player games.
In plain words
Each pair of numbers and must be nonnegative, and one of them must be zero. If has no negative entry, works. Otherwise, add an extra unknown that lifts every by the same amount, enough to make all of them nonnegative. Now the only rule we break is that should be 0. Change one variable at a time, as in the simplex method: each step makes one variable zero, and the rule says that its partner in its pair must be the next one to grow. The path is forced at each step and never comes back. When falls to zero, we have the answer. If the variable that should grow can grow without limit, the method stops without an answer.
The problem
The input is an matrix and a vector , with rational entries. The output is a pair with
or the answer "ray". Since , the condition means for every . The variables and are a complementary pair. A basis of the system is complementary if it holds exactly one variable of each pair.
The algorithm also takes a covering vector , by default . The augmented system is
A basis of it is almost complementary if is basic and, of the pairs, exactly one has both variables nonbasic and the others have one variable basic each.
The algorithm
LEMKE(M, q, d) ▷ w = M z + q; columns w_1..w_n, z_1..z_n, z_0; d > 0- 1
if q ≥ 0 then return z = 0, w = q - 2
build the tableau w - M z - d z_0 = q with the basis w - 3
enter z_0; the leaving row r is the lexicographic minimum of q_i / d_i (the most negative) - 4
e ← the complement of w_r, that is, z_r - 5
repeat - 6
if no row has a positive entry in column e then return "ray" - 7
enter e by the lexicographic minimum ratio test; if z_0 leaves then return (z, w) - 8
e ← the complement of the variable that left
After line L3 the basic solution is feasible: makes every nonnegative, and . The basis is almost complementary, and the pair has both variables nonbasic. Line L4 enters , the partner of the variable that just left; this is the complementary pivot rule. Line L7 is the ratio test of the simplex method, so all variables stay nonnegative. If leaves, the basis is complementary with , which is a solution. Otherwise a variable of some pair leaves, that pair now has both variables nonbasic, and line L8 enters the partner of the one that left.
The ratio test of line L7 is lexicographic: ties in the ratio are broken by comparing the rows of the current inverse basis (the columns of in the tableau), each divided by the pivot entry. This is the same as replacing by for a small , and it makes every step unique, so the method cannot cycle on a degenerate input.
Example
A two-contact example: and . Think of as the gap velocities before the impulses: contact 1 approaches at speed 1 and contact 2 separates at speed 1. says how impulses change the velocities, and it couples the two contacts.
| step | enters | leaves | |||
|---|---|---|---|---|---|
| L3 | 1 | ||||
| L7 | 0 |
In the second step grows and stays 0, so and . The ratio test stops at , where reaches 0 before does. The solution is an impulse at contact 1 and none at contact 2; contact 1 ends at rest and contact 2 separates at speed .
A ray example: and . Then for every , so no solution exists. Line L3 enters , line L4 enters , and its column has no positive entry, so line L6 returns "ray".
Correctness
Each step keeps the basis almost complementary and feasible, so the solution it ends with, when leaves, is complementary with , which is a solution of the LCP. The method ends: in the perturbed (lexicographic) problem each almost complementary basis has at most two neighbors on the path, one by entering each variable of its pair whose both members are nonbasic. The starting basis has only one, because the other direction is the ray of that starts at the initial point. So the path is a simple path in a finite graph and it cannot return to a basis, which means that it ends in a finite number of steps, either when leaves or on a ray (line L6). The proof file has the details.
Ray termination does not always mean that no solution exists, but for important classes of it does:
- If is a P-matrix (all principal minors positive, for example a positive definite matrix), the LCP has a unique solution for every , and the method never ends on a ray.
- If is copositive-plus (for example positive semidefinite), a ray proves that the system , has no solution.
- If is strictly copositive ( for , , for example a matrix with positive entries), a solution exists for every and the method finds it.
Proof: Lemke's method ends, and when it does not end on a ray it returns a solution of the LCPfull
Let be an matrix, with some , and . The augmented system is with variables , all nonnegative. Its coefficient matrix has rank , because of the identity block, so a basis is a set of columns whose submatrix is nonsingular, and its basic solution is .
Perturbation. Let . For a basis , the basic solution is . Each entry is a polynomial in whose coefficient vector is a row of , and it is not the zero polynomial, because is nonsingular and has no zero row. So for all small enough , no basic variable of any basis is 0, and comparing two entries for small is the lexicographic comparison of their coefficient vectors. In the tableau of the code the columns of hold , because they started as the identity. So the lexicographic rule of lines L3 and L7 is the ordinary rule on the system with , for all small , and that system is nondegenerate: every feasible basis has all basic variables positive, and every ratio test has a unique minimum. From now on, argue with .
Lemma 1 (start). After line L3 the basis is feasible and almost complementary, and the pair with both members nonbasic is .
Proof. With , the system says . These are all nonnegative exactly when , which is positive. At the smallest such value, , only is 0 (the minimum is unique by the perturbation). Pivoting in for gives the basis , which is feasible and almost complementary, with both and nonbasic.
Lemma 2 (invariant). Before each execution of line L6, the basis is feasible and almost complementary, is basic, and is a member of the unique pair with both members nonbasic.
Proof. True at the first time by Lemma 1 and line L4. Suppose it holds and line L7 pivots in and some variable out. The ratio test keeps feasibility. The pair of now has one basic member. The variable was basic and is now nonbasic. Since the old basis had exactly one basic member in each pair other than the pair of , the pair of now has both members nonbasic, and it is the only such pair. Line L8 sets to the partner of .
Lemma 3 (exits). If line L7 removes , the returned solves the LCP. If line L6 returns "ray", the augmented system has an unbounded edge of feasible solutions on which all pairs except one are complementary.
Proof. When leaves, the new basis has members, none of them , and by Lemma 2 the pair of became basic, so each pair has exactly one basic member: the basis is complementary, and for its basic solution. It is feasible with , so , ; letting keeps all these conditions, which are closed, so the solution for itself also satisfies them. If no row has a positive entry in column , raising from 0 keeps all basic variables nonnegative forever, and all nonbasic variables other than stay 0; this is the ray.
Lemma 4 (no repetition). Call two feasible almost complementary bases adjacent if one pivot changes one into the other. In the nondegenerate perturbed system, a feasible almost complementary basis has at most two adjacent ones, one for each member of its pair with both members nonbasic. The basis of Lemma 1 has at most one, because entering in it gives back the initial point with on the ray that starts there.
Proof. Any pivot that keeps the basis almost complementary and basic must enter a member of the double nonbasic pair: entering a nonbasic member of another pair would give that pair two basic members, and then some pair would have to have none, but only one leaves. For each of the two choices of the entering variable, the ratio test has a unique minimum, so there is at most one adjacent basis. For the start, entering moves along the edge on which and grows, which is unbounded and gives no adjacent basis.
Theorem. With the lexicographic rule, Lemke's method ends after finitely many pivots, either at line L6 with a ray or at line L7 with a solution of the LCP.
Proof. By Lemmas 2 and 4, the method walks in the graph of feasible almost complementary bases, in which each node has degree at most 2 and the start has degree at most 1. Each step goes to the neighbor that is not the previous node, because it enters the partner of the variable that just left, and entering that variable again would undo the last pivot. A walk of this kind from a node of degree at most 1 never repeats a node: the first repeated node would have three distinct neighbors on the walk, or would be the start with two. There are finitely many bases, so the walk ends. It can only end at line L6 or at line L7 with leaving, and Lemma 3 describes both.
Classes of . The statements of the page about P-matrices, copositive-plus and strictly copositive matrices are the standard theorems on the matrix classes processed by Lemke's method, proved in the book of Cottle, Pang and Stone. For a strictly copositive the argument is short: on a ray, , , with , not all 0, , and complementarity for all large , because all but one pair stay complementary and the double nonbasic pair has both members 0. If , then , a contradiction. If , then (otherwise too) and . Then for large all and are positive, and the positive variables on the ray are the basic ones and the entering one, so the basis consists of and all but one, , which is the entering variable. The basic solution of that basis has and , so it is the basis of Lemma 1 (with ). But the walk never returns to the start (Theorem), and at the start it enters , not . This is a contradiction. So for strictly copositive the method returns a solution, which is the case used by the code for bimatrix games.
Complexity
Each pivot costs arithmetic operations on a tableau of rows and columns. An almost complementary basis is fixed by the pair with both members nonbasic ( choices) and by one member of each other pair ( choices), so the path has at most steps, and the time is in the worst case. This is not only a weak bound: Murty (1978) gave, for each , an LCP of order on which complementary pivot methods take pivots. On many practical problems the number of pivots is much smaller than this bound.
In exact rational arithmetic the numbers stay of polynomial bit length, as in the simplex method. The general LCP is NP-complete, so no method solves every LCP in polynomial time unless P = NP. The space is the tableau, numbers.
Properties
- Exact. With rational data the output is an exact rational solution.
- Finite. With the lexicographic rule it ends on every input, either with a solution or on a ray.
- A certificate for some classes. For copositive-plus a ray is a proof of infeasibility.
- Path following. The path is the same kind of object as in Lemke-Howson, which is why the problems it solves for games are in PPAD.
- Depends on . Different covering vectors give different paths, and can give different solutions when the solution is not unique.
Variants and improvements
- Bimatrix games. An equilibrium of a two-player game is a solution of an LCP. The plain form , with positive cost matrices , is copositive but not copositive-plus, and with the method can end on a ray (the tests show a game where it does). The Lemke-Howson algorithm solves this form from a dropped label instead. The code here uses the symmetrized game with costs , which is strictly copositive, so Lemke's method always succeeds.
- Games in extensive form. With the sequence form, the equilibria of a two-player game tree with perfect recall are the solutions of an LCP of size linear in the tree, and Lemke's method with a covering vector computes one.
- Quadratic programs. The KKT conditions of a convex quadratic program form an LCP with a positive semidefinite , and Lemke's method solves it exactly or proves it infeasible.
- Other pivoting methods. Principal pivoting methods (Murty's least index method, the Cottle-Dantzig method) need no artificial variable and work for P-matrices.
- Iterative methods. For large sparse problems, such as rigid-body contact in games and films, projected Gauss-Seidel, splitting methods and interior point methods are faster than pivoting, and give approximate solutions.
When to use it
Use it for a small or medium LCP where an exact solution is needed, or where the answer must say for sure that there is no solution (for copositive-plus ). Use it on the LCP of a bimatrix game or of a sequence form game. For real-time contact with many bodies, use projected Gauss-Seidel; for large convex quadratic programs, use an interior point method.
Pitfalls
- The sign convention. Lemke's 1965 paper writes ; this page writes . Moving between them changes the signs of and .
- Reading a ray as "no solution". That is right only for some classes of . A general can have solutions that the method does not find.
- A zero or negative covering vector. If for a row with , line L3 cannot make that row feasible. Use .
- Cycling. Without the lexicographic rule, a degenerate problem can make the method cycle.
- Floating point. In floating point, small pivot entries make the path wrong. Exact arithmetic avoids this but is slow on large problems.
Implementations
The Python code keeps the tableau in Fraction and follows lines L1 to L8 with the lexicographic ratio test; it can record the pivots. It also builds the strictly copositive LCP of a bimatrix game. The tests check the two examples above; random positive definite and diagonally dominant P-matrices, where the solution must be the only one found by a brute force over the complementary bases; random positive semidefinite matrices, where a ray must happen exactly when an exact LP shows that , is infeasible; random general matrices, where each solution is checked; degenerate inputs with ties; and 60 random nondegenerate bimatrix games, where the output must be a Nash equilibrium by a check of all pure deviations and must be in the list of an independent support enumeration.
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
agtlp.py 172 lines
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Exact linear programming in Fraction, by the two-phase simplex method with Bland's rule.
lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None) maximizes c x subject to A_ub x <= b_ub,
A_eq x = b_eq and x >= 0. lp_min does the same for minimization. Free variables must be
split by the caller (x = x+ - x-). Every input number is converted to Fraction, so the
result is exact: there is no tolerance anywhere.
Both functions return (status, x, value, dual). status is "optimal", "infeasible" or
"unbounded". When status is not "optimal", x, value and dual are None. dual has one entry
per constraint, the A_ub rows first and then the A_eq rows. It is the vector of shadow
prices: the value is sum_i b_i dual_i (strong duality). For lp_max, dual_i >= 0 on the
A_ub rows and A^T dual >= c. For lp_min, dual_i <= 0 on the A_ub rows and A^T dual <= c.
The entries for the A_eq rows have no sign condition.
Bland's rule (the smallest improving column enters, and among the rows with the smallest
ratio the one with the smallest basic variable leaves) makes the method finite on every
input, degenerate inputs included. There is no game algorithm in this module.
"""
from fractions import Fraction
def _frac(v):
return v if isinstance(v, Fraction) else Fraction(v)
def _pivot(T, obj, basis, r, j):
p = T[r][j]
row = [v / p for v in T[r]]
T[r] = row
for k in range(len(T)):
f = T[k][j]
if k != r and f != 0:
T[k] = [a - f * b for a, b in zip(T[k], row)]
f = obj[j]
if f != 0:
obj[:] = [a - f * b for a, b in zip(obj, row)]
basis[r] = j
def _simplex(T, obj, basis, ncols):
"""Maximize. obj[j] is the reduced cost of column j and obj[-1] is minus the value."""
while True:
enter = next((j for j in range(ncols) if obj[j] > 0), None)
if enter is None:
return "optimal"
best = None
for r, row in enumerate(T):
a = row[enter]
if a > 0:
key = (row[-1] / a, basis[r])
if best is None or key < best[0]:
best = (key, r)
if best is None:
return "unbounded"
_pivot(T, obj, basis, best[1], enter)
def _objective_row(cost, T, basis):
obj = list(cost) + [Fraction(0)]
for r, j in enumerate(basis):
f = obj[j]
if f != 0:
obj = [a - f * b for a, b in zip(obj, T[r])]
return obj
def _any_solution(M, rhs, nvars):
"""Return one solution y of M y = rhs (a consistent system), with the free variables 0."""
rows = [list(M[k]) + [rhs[k]] for k in range(len(M))]
pivots = []
r = 0
for col in range(nvars):
p = next((k for k in range(r, len(rows)) if rows[k][col] != 0), None)
if p is None:
continue
rows[r], rows[p] = rows[p], rows[r]
pv = rows[r][col]
rows[r] = [v / pv for v in rows[r]]
for k in range(len(rows)):
f = rows[k][col]
if k != r and f != 0:
rows[k] = [a - f * b for a, b in zip(rows[k], rows[r])]
pivots.append(col)
r += 1
if r == len(rows):
break
y = [Fraction(0)] * nvars
for k, col in enumerate(pivots):
y[col] = rows[k][-1]
return y
def _matrix(A, width, name):
A = [[_frac(v) for v in row] for row in (A or [])]
if any(len(row) != width for row in A):
raise ValueError(name + " must have one column per variable")
return A
def lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None):
"""Maximize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
c = [_frac(v) for v in c]
n = len(c)
A_ub = _matrix(A_ub, n, "A_ub")
A_eq = _matrix(A_eq, n, "A_eq")
b_ub = [_frac(v) for v in (b_ub or [])]
b_eq = [_frac(v) for v in (b_eq or [])]
if len(b_ub) != len(A_ub) or len(b_eq) != len(A_eq):
raise ValueError("b_ub and b_eq must have one entry per row")
m1, m2 = len(A_ub), len(A_eq)
m = m1 + m2
width = n + m1
# Rows in the original orientation, with a slack column for each A_ub row.
orig = [A_ub[i] + [Fraction(int(k == i)) for k in range(m1)] for i in range(m1)]
orig += [A_eq[i] + [Fraction(0)] * m1 for i in range(m2)]
rhs = b_ub + b_eq
# A row gets an artificial variable if it is an equation or if its right side is negative.
need = [i >= m1 or rhs[i] < 0 for i in range(m)]
nart = sum(need)
T, basis = [], []
a = 0
for i in range(m):
sign = -1 if rhs[i] < 0 else 1
row = [sign * v for v in orig[i]] + [Fraction(0)] * nart + [sign * rhs[i]]
if need[i]:
row[width + a] = Fraction(1)
basis.append(width + a)
a += 1
else:
basis.append(n + i)
T.append(row)
if nart:
# Phase 1: maximize minus the sum of the artificial variables.
obj = _objective_row([Fraction(0)] * width + [Fraction(-1)] * nart, T, basis)
_simplex(T, obj, basis, width + nart)
if obj[-1] != 0:
return "infeasible", None, None, None
keep = []
for r in range(m):
if basis[r] >= width:
j = next((j for j in range(width) if T[r][j] != 0), None)
if j is None:
continue # the row is a combination of the other rows
_pivot(T, [Fraction(0)] * (width + nart + 1), basis, r, j)
keep.append(r)
T = [T[r][:width] + [T[r][-1]] for r in keep]
basis = [basis[r] for r in keep]
# Phase 2: the original objective, without the artificial columns.
cost = c + [Fraction(0)] * m1
obj = _objective_row(cost, T, basis)
if _simplex(T, obj, basis, width) == "unbounded":
return "unbounded", None, None, None
x = [Fraction(0)] * n
for r, j in enumerate(basis):
if j < n:
x[j] = T[r][-1]
value = sum((ci * xi for ci, xi in zip(c, x)), Fraction(0))
# The dual solves y^T A_B = c_B, where A_B holds the basic columns of the original rows.
M = [[orig[i][j] for i in range(m)] for j in basis]
dual = _any_solution(M, [cost[j] for j in basis], m)
return "optimal", x, value, dual
def lp_min(c, A_ub, b_ub, A_eq=None, b_eq=None):
"""Minimize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
status, x, value, dual = lp_max([-_frac(v) for v in c], A_ub, b_ub, A_eq, b_eq)
if status != "optimal":
return status, None, None, None
return status, x, -value, [-v for v in dual]
lemke_algorithm.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lemke-algorithm/. The authors are listed in prov/8FV1QP.jsonl.
"""Lemke's complementary pivot algorithm for the linear complementarity problem, in Fraction.
The problem LCP(M, q): find z >= 0 with w = M z + q >= 0 and z . w = 0. The tableau is
w - M z - d z0 = q, with a covering vector d > 0 (all ones by default). Column i is w_i,
column n + i is z_i and column 2 n is the artificial variable z0. The minimum ratio test is
lexicographic, which is the same as perturbing q by (eps, eps^2, ..., eps^n); so the method
ends on every input, also on degenerate ones.
"""
from fractions import Fraction
def _complement(v, n):
return v + n if v < n else v - n
def lemke(M, q, d=None, trace=None):
"""Solve LCP(M, q) with Lemke's method.
Return ("solution", z, w) or ("ray", None, None). Ray termination means that the method
found an unbounded edge; for P-matrices it never happens, and for copositive-plus matrices
(for example positive semidefinite ones) it happens only if z >= 0, M z + q >= 0 has no solution.
If trace is a list, the pair (entering column, leaving column) of each pivot is appended to it.
"""
n = len(q)
q = [Fraction(v) for v in q]
if all(v >= 0 for v in q): # @line L1
return "solution", [Fraction(0)] * n, list(q)
d = [Fraction(1)] * n if d is None else [Fraction(v) for v in d]
if any(v <= 0 for v in d):
raise ValueError("the covering vector d must be positive")
rows = [[Fraction(int(c == i)) for c in range(n)] + [-Fraction(M[i][j]) for j in range(n)]
+ [-d[i], q[i]] for i in range(n)] # @line L2
basis = list(range(n))
def key(r, col):
# (rhs, the w columns, which hold the inverse of the basis), divided by the pivot entry
a = rows[r][col]
return tuple(rows[r][c] / a for c in [-1] + list(range(n)))
def pivot(r, col):
p = rows[r][col]
rows[r] = [v / p for v in rows[r]]
for i in range(n):
f = rows[i][col]
if i != r and f != 0:
rows[i] = [a - f * b for a, b in zip(rows[i], rows[r])]
leaving, basis[r] = basis[r], col
if trace is not None:
trace.append((col, leaving))
return leaving
z0 = 2 * n
# The column of z0 is -d; z0 enters at the row of the lexicographic minimum of q_i / d_i.
r = min(range(n), key=lambda i: tuple(rows[i][c] / d[i] for c in [-1] + list(range(n)))) # @line L3
entering = _complement(pivot(r, z0), n) # @line L4
while True: # @line L5
cand = [i for i in range(n) if rows[i][entering] > 0]
if not cand: # @line L6
return "ray", None, None
r = min(cand, key=lambda i: key(i, entering))
leaving = pivot(r, entering) # @line L7
if leaving == z0:
vals = [Fraction(0)] * (2 * n + 1)
for i, c in enumerate(basis):
vals[c] = rows[i][-1]
return "solution", vals[n:2 * n], vals[:n]
entering = _complement(leaving, n) # @line L8
def bimatrix_lcp(A, B):
"""Return (M, q) of an LCP whose solutions z = (x, y) give the equilibria (x / sum x, y / sum y).
Shift A and B to A', B' >= 1 and form the symmetric game S = [[0, A'], [B'^T, 0]] of size
m + n. With K = 1 + the largest entry of S, the cost matrix M = K - S is positive, so it is
strictly copositive and Lemke's method with d = 1 ends with a solution of LCP(M, -1).
In a solution, the rows i < m with z_i > 0 maximize (A' y)_i and the rows m + j with
z_(m+j) > 0 maximize (B'^T x)_j, and both parts of z are nonzero.
"""
m, n = len(A), len(A[0])
c = 1 - min(min(min(r) for r in A), min(min(r) for r in B), 1)
S = [[Fraction(0)] * (m + n) for _ in range(m + n)]
for i in range(m):
for j in range(n):
S[i][m + j] = Fraction(A[i][j]) + c
S[m + j][i] = Fraction(B[i][j]) + c
K = 1 + max(max(r) for r in S)
return [[K - v for v in r] for r in S], [Fraction(-1)] * (m + n)
def bimatrix_equilibrium(A, B):
"""Return a Nash equilibrium (x, y) of (A, B), found by Lemke's method on bimatrix_lcp(A, B)."""
m = len(A)
M, q = bimatrix_lcp(A, B)
status, z, _ = lemke(M, q)
if status != "solution":
raise AssertionError("Lemke's method does not end on a ray for this LCP")
x, y = z[:m], z[m:]
return [v / sum(x) for v in x], [v / sum(y) for v in y]
test_lemke_algorithm.py 238 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lemke-algorithm/. The authors are listed in prov/8FV1QP.jsonl.
import random
from fractions import Fraction
from itertools import combinations
from agtgame import from_bimatrix, is_nash
from agtlp import lp_max
from lemke_algorithm import bimatrix_equilibrium, bimatrix_lcp, lemke
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 is_lcp_solution(M, q, z, w):
n = len(q)
return (all(v >= 0 for v in z) and all(v >= 0 for v in w)
and all(w[i] == sum(F(M[i][j]) * z[j] for j in range(n)) + q[i] for i in range(n))
and sum(a * b for a, b in zip(z, w)) == 0)
def brute_force(M, q):
"""All solutions found from the 2^n complementary bases with a nonsingular principal block."""
n = len(q)
out = []
for k in range(n + 1):
for S in combinations(range(n), k):
z = [F(0)] * n
if S:
sol = solve_square([[M[i][j] for j in S] for i in S], [-q[i] for i in S])
if sol is None:
continue
for i, v in zip(S, sol):
z[i] = v
w = [sum(F(M[i][j]) * z[j] for j in range(n)) + q[i] for i in range(n)]
if is_lcp_solution(M, q, z, w) and z not in out:
out.append(z)
return out
def random_q(rng, n):
return [F(rng.randint(-6, 6)) for _ in range(n)]
def test_trivial_and_page_example():
assert lemke([[2, 1], [1, 2]], [1, 0]) == ("solution", [0, 0], [1, 0])
trace = []
status, z, w = lemke([[2, 1], [1, 2]], [-1, 1], trace=trace)
assert status == "solution" and z == [F(1, 2), 0] and w == [0, F(3, 2)]
assert trace == [(4, 0), (2, 4)] # z0 enters for w_0, then z_0 enters and z0 leaves
def test_ray_when_infeasible():
# w = -z - 1 >= 0 has no solution with z >= 0.
assert lemke([[-1]], [-1])[0] == "ray"
assert lemke([[0, 0], [0, 0]], [-1, 2])[0] == "ray"
def test_positive_definite_unique_solution():
rng = random.Random(1201)
for _ in range(120):
n = rng.randint(1, 5)
G = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(n)]
S = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(n)]
# M = G G^T + I plus a skew part: x^T M x > 0 for x != 0, so M is a P-matrix.
M = [[sum(G[i][k] * G[j][k] for k in range(n)) + int(i == j) + S[i][j] - S[j][i]
for j in range(n)] for i in range(n)]
q = random_q(rng, n)
status, z, w = lemke(M, q)
assert status == "solution" and is_lcp_solution(M, q, z, w)
assert brute_force(M, q) == [z]
def test_p_matrix_not_symmetric():
# Strictly row diagonally dominant with a positive diagonal: a P-matrix.
rng = random.Random(77)
for _ in range(120):
n = rng.randint(1, 5)
M = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(n)]
for i in range(n):
M[i][i] = sum(abs(M[i][j]) for j in range(n) if j != i) + rng.randint(1, 3)
q = random_q(rng, n)
status, z, w = lemke(M, q)
assert status == "solution" and is_lcp_solution(M, q, z, w)
assert brute_force(M, q) == [z]
def test_positive_semidefinite_ray_means_infeasible():
rng = random.Random(9)
rays = sols = 0
for _ in range(200):
n = rng.randint(1, 4)
r = rng.randint(1, n)
G = [[rng.randint(-2, 2) for _ in range(r)] for _ in range(n)]
M = [[sum(G[i][k] * G[j][k] for k in range(r)) for j in range(n)] for i in range(n)]
q = random_q(rng, n)
status, z, w = lemke(M, q)
# Feasibility of z >= 0, M z + q >= 0, that is, -M z <= q.
feasible = lp_max([0] * n, [[-v for v in row] for row in M], q)[0] == "optimal"
if status == "solution":
sols += 1
assert is_lcp_solution(M, q, z, w)
else:
rays += 1
assert not feasible and brute_force(M, q) == []
assert (status == "solution") == feasible
assert rays > 10 and sols > 10
def test_general_matrices_outputs_are_solutions():
rng = random.Random(31)
for _ in range(300):
n = rng.randint(1, 4)
M = [[rng.randint(-4, 4) for _ in range(n)] for _ in range(n)]
q = random_q(rng, n)
status, z, w = lemke(M, q)
if status == "solution":
assert is_lcp_solution(M, q, z, w)
def test_degenerate_q_ties():
for n in range(1, 6):
M = [[int(i == j) + int(j == (i + 1) % n) for j in range(n)] for i in range(n)]
q = [F(-1)] * n
status, z, w = lemke(M, q)
assert status == "solution" and is_lcp_solution(M, q, z, w)
def support_enumeration(A, B):
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, p in zip(J, sy):
y[j] = p
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):
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)):
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
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 test_bimatrix_games_against_support_enumeration():
A = [[3, 3], [2, 5], [0, 6]]
B = [[3, 2], [2, 6], [3, 1]]
x, y = bimatrix_equilibrium(A, B)
assert (tuple(x), tuple(y)) in support_enumeration(A, B)
rng = random.Random(606)
done = 0
while done < 60:
m, n = rng.randint(1, 4), rng.randint(1, 4)
A = [[rng.randint(-20, 20) for _ in range(n)] for _ in range(m)]
B = [[rng.randint(-20, 20) for _ in range(n)] for _ in range(m)]
if not nondegenerate(A, B):
continue
done += 1
M, q = bimatrix_lcp(A, B)
assert all(v > 0 for row in M for v in row) and q == [-1] * (m + n)
x, y = bimatrix_equilibrium(A, B)
assert is_nash(from_bimatrix(A, B), [x, y])
assert (tuple(x), tuple(y)) in support_enumeration(A, B)
def test_plain_bimatrix_lcp_can_end_on_a_ray():
# M = [[0, C], [D^T, 0]] with positive costs is copositive but not copositive-plus,
# and Lemke's method with d = 1 can end on a secondary ray on it.
A = [[1, 0, 0], [2, 0, 0]]
B = [[0, 0, 2], [0, 1, 2]]
m, n, c = 2, 3, 3
M = [[0] * (m + n) for _ in range(m + n)]
for i in range(m):
for j in range(n):
M[i][m + j] = c - A[i][j]
M[m + j][i] = c - B[i][j]
assert lemke(M, [-1] * (m + n))[0] == "ray"
x, y = bimatrix_equilibrium(A, B)
assert is_nash(from_bimatrix(A, B), [x, y])
def test_bimatrix_degenerate_games():
rng = random.Random(8)
for _ in range(100):
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)]
x, y = bimatrix_equilibrium(A, B)
assert is_nash(from_bimatrix(A, B), [x, y])
def test_bad_covering_vector():
try:
lemke([[1]], [-1], d=[0])
except ValueError:
return
raise AssertionError("expected ValueError")
History
Lemke and Howson gave the pivoting method for bimatrix games in 1964. Lemke (1965) added the artificial variable and the covering vector, which made the method work for a general LCP, and related it to mathematical programming. Murty (1978) showed that complementary pivot methods can need exponentially many steps. The theory of matrix classes and pivoting methods is collected in the book of Cottle, Pang and Stone (1992).
References
- C. E. Lemke, Bimatrix equilibrium points and mathematical programming, Management Science 11(7) (1965), 681-689, the complementary pivot method with the artificial variable z0; the paper writes the problem as M z - w = q, which is the form w = M z + q of this page with the signs of M and q changed
- Richard W. Cottle, Jong-Shi Pang and Richard E. Stone, The Linear Complementarity Problem, the chapter on pivoting methods (Lemke's method, the covering vector, ray termination, and the matrix classes that it processes)
- Katta G. Murty, Computational complexity of complementary pivot methods, Mathematical Programming Study 7 (1978), 61-73, for each n at least 2, an LCP of order n on which complementary pivot methods take 2^n pivots
- Noam Nisan, Tim Roughgarden, Éva Tardos and Vijay V. Vazirani (eds.), Algorithmic Game Theory, Cambridge University Press, 2007, Chapter 3 (Bernhard von Stengel), the LCP of a bimatrix game and Lemke's algorithm with a covering vector
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 8FV1QP Edit this page History Report an error Markdown