Algorithm Search⌘K

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)
Properties
deterministicexactofflineiterative
Origin
Carlton E. Lemke, 1965

Lemke's algorithm solves a linear complementarity problem (LCP): given an n×nn \times n matrix MM and a vector qq, find z≥0z \ge 0 with w=Mz+q≥0w = Mz + q \ge 0 and ziwi=0z_i w_i = 0 for each ii. In a contact simulation, ziz_i is the impulse or force at contact ii, wiw_i 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 z0z_0 that makes the start feasible, then follows a unique path of bases in which every pair (zi,wi)(z_i, w_i) has at least one zero, except one pair, until z0z_0 leaves the basis. It gives an exact solution in a finite number of steps for important classes of MM, 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 ziz_i and wiw_i must be nonnegative, and one of them must be zero. If qq has no negative entry, z=0z = 0 works. Otherwise, add an extra unknown z0z_0 that lifts every wiw_i by the same amount, enough to make all of them nonnegative. Now the only rule we break is that z0z_0 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 z0z_0 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 n×nn \times n matrix MM and a vector q∈Rnq \in \mathbb{R}^n, with rational entries. The output is a pair (z,w)(z, w) with

w=Mz+q,z≥0,w≥0,zTw=0,w = Mz + q, \qquad z \ge 0, \qquad w \ge 0, \qquad z^{\mathsf T} w = 0,

or the answer "ray". Since z,w≥0z, w \ge 0, the condition zTw=0z^{\mathsf T} w = 0 means ziwi=0z_i w_i = 0 for every ii. The variables ziz_i and wiw_i are a complementary pair. A basis of the system w−Mz=qw - Mz = q is complementary if it holds exactly one variable of each pair.

The algorithm also takes a covering vector d>0d > 0, by default d=1d = \mathbf 1. The augmented system is

w=Mz+d z0+q,z,w,z0≥0,zTw=0.w = Mz + d\, z_0 + q, \qquad z, w, z_0 \ge 0, \qquad z^{\mathsf T} w = 0 .

A basis of it is almost complementary if z0z_0 is basic and, of the nn pairs, exactly one has both variables nonbasic and the others have one variable basic each.

The algorithm

  1. LEMKE(M, q, d) ▷ w = M z + q; columns w_1..w_n, z_1..z_n, z_0; d > 0
  2. 1if q ≥ 0 then return z = 0, w = q
  3. 2build the tableau w - M z - d z_0 = q with the basis w
  4. 3enter z_0; the leaving row r is the lexicographic minimum of q_i / d_i (the most negative)
  5. 4e ← the complement of w_r, that is, z_r
  6. 5repeat
  7. 6if no row has a positive entry in column e then return "ray"
  8. 7enter e by the lexicographic minimum ratio test; if z_0 leaves then return (z, w)
  9. 8e ← the complement of the variable that left

After line L3 the basic solution is feasible: z0=max⁡i(−qi/di)>0z_0 = \max_i (-q_i / d_i) > 0 makes every wi=qi+diz0w_i = q_i + d_i z_0 nonnegative, and wr=0w_r = 0. The basis is almost complementary, and the pair (zr,wr)(z_r, w_r) has both variables nonbasic. Line L4 enters zrz_r, 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 z0z_0 leaves, the basis is complementary with z0=0z_0 = 0, 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 ww in the tableau), each divided by the pivot entry. This is the same as replacing qq by q+(ε,ε2,…,εn)q + (\varepsilon, \varepsilon^2, \ldots, \varepsilon^n) for a small ε>0\varepsilon > 0, and it makes every step unique, so the method cannot cycle on a degenerate input.

Example

A two-contact example: M=(2112)M = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix} and q=(−1,1)q = (-1, 1). Think of qq as the gap velocities before the impulses: contact 1 approaches at speed 1 and contact 2 separates at speed 1. MM says how impulses change the velocities, and it couples the two contacts.

step enters leaves z0z_0 zz ww
L3 z0z_0 w1w_1 1 (0,0)(0, 0) (0,2)(0, 2)
L7 z1z_1 z0z_0 0 (1/2,0)(1/2, 0) (0,3/2)(0, 3/2)

In the second step z1=tz_1 = t grows and w1=−1+2t+z0w_1 = -1 + 2t + z_0 stays 0, so z0=1−2tz_0 = 1 - 2t and w2=1+t+z0=2−tw_2 = 1 + t + z_0 = 2 - t. The ratio test stops at t=1/2t = 1/2, where z0z_0 reaches 0 before w2w_2 does. The solution is an impulse 1/21/2 at contact 1 and none at contact 2; contact 1 ends at rest and contact 2 separates at speed 3/23/2.

A ray example: M=(−1)M = (-1) and q=(−1)q = (-1). Then w=−z−1<0w = -z - 1 < 0 for every z≥0z \ge 0, so no solution exists. Line L3 enters z0=1z_0 = 1, line L4 enters z1z_1, 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 z0z_0 leaves, is complementary with z0=0z_0 = 0, 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 z0z_0 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 z0z_0 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 MM it does:

  • If MM is a P-matrix (all principal minors positive, for example a positive definite matrix), the LCP has a unique solution for every qq, and the method never ends on a ray.
  • If MM is copositive-plus (for example positive semidefinite), a ray proves that the system z≥0z \ge 0, Mz+q≥0Mz + q \ge 0 has no solution.
  • If MM is strictly copositive (zTMz>0z^{\mathsf T} M z > 0 for z≥0z \ge 0, z≠0z \ne 0, for example a matrix with positive entries), a solution exists for every qq 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 MM be an n×nn \times n matrix, q∈Rnq \in \mathbb{R}^n with some qi<0q_i < 0, and d>0d > 0. The augmented system is w−Mz−dz0=qw - Mz - d z_0 = q with 2n+12n + 1 variables w1,…,wn,z1,…,zn,z0w_1, \ldots, w_n, z_1, \ldots, z_n, z_0, all nonnegative. Its coefficient matrix [I,−M,−d][I, -M, -d] has rank nn, because of the identity block, so a basis is a set of nn columns whose submatrix GG is nonsingular, and its basic solution is G−1qG^{-1} q.

Perturbation. Let q(ε)=q+(ε,ε2,…,εn)q(\varepsilon) = q + (\varepsilon, \varepsilon^2, \ldots, \varepsilon^n). For a basis GG, the basic solution is G−1q(ε)=G−1q+∑tεt(G−1)⋅tG^{-1} q(\varepsilon) = G^{-1} q + \sum_t \varepsilon^t (G^{-1})_{\cdot t}. Each entry is a polynomial in ε\varepsilon whose coefficient vector is a row of [G−1q,G−1][G^{-1} q, G^{-1}], and it is not the zero polynomial, because G−1G^{-1} is nonsingular and has no zero row. So for all small enough ε>0\varepsilon > 0, no basic variable of any basis is 0, and comparing two entries for small ε\varepsilon is the lexicographic comparison of their coefficient vectors. In the tableau of the code the columns of ww hold G−1G^{-1}, because they started as the identity. So the lexicographic rule of lines L3 and L7 is the ordinary rule on the system with q(ε)q(\varepsilon), for all small ε>0\varepsilon > 0, 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 q(ε)q(\varepsilon).

Lemma 1 (start). After line L3 the basis is feasible and almost complementary, and the pair with both members nonbasic is (zr,wr)(z_r, w_r).

Proof. With z=0z = 0, the system says wi=qi+diz0w_i = q_i + d_i z_0. These are all nonnegative exactly when z0≥max⁡i(−qi/di)z_0 \ge \max_i (-q_i / d_i), which is positive. At the smallest such value, z0=−qr/drz_0 = -q_r / d_r, only wrw_r is 0 (the minimum is unique by the perturbation). Pivoting z0z_0 in for wrw_r gives the basis {z0}∪{wi:i≠r}\{z_0\} \cup \{w_i : i \ne r\}, which is feasible and almost complementary, with both zrz_r and wrw_r nonbasic. □\square

Lemma 2 (invariant). Before each execution of line L6, the basis is feasible and almost complementary, z0z_0 is basic, and ee 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 ee in and some variable v≠z0v \ne z_0 out. The ratio test keeps feasibility. The pair of ee now has one basic member. The variable vv was basic and is now nonbasic. Since the old basis had exactly one basic member in each pair other than the pair of ee, the pair of vv now has both members nonbasic, and it is the only such pair. Line L8 sets ee to the partner of vv. □\square

Lemma 3 (exits). If line L7 removes z0z_0, the returned (z,w)(z, w) 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 z0z_0 leaves, the new basis has nn members, none of them z0z_0, and by Lemma 2 the pair of ee became basic, so each pair has exactly one basic member: the basis is complementary, and zTw=0z^{\mathsf T} w = 0 for its basic solution. It is feasible with z0=0z_0 = 0, so w=Mz+qw = Mz + q, z,w≥0z, w \ge 0; letting ε→0\varepsilon \to 0 keeps all these conditions, which are closed, so the solution for qq itself also satisfies them. If no row has a positive entry in column ee, raising ee from 0 keeps all basic variables nonnegative forever, and all nonbasic variables other than ee stay 0; this is the ray. □\square

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 wrw_r in it gives back the initial point z=0z = 0 with z0z_0 on the ray that starts there.

Proof. Any pivot that keeps the basis almost complementary and z0z_0 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 wrw_r moves along the edge on which z=0z = 0 and z0z_0 grows, which is unbounded and gives no adjacent basis. □\square

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 z0z_0 leaving, and Lemma 3 describes both. □\square

Classes of MM. 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 MM the argument is short: on a ray, z(t)=z+taz(t) = z + t a, w(t)=w+tbw(t) = w + t b, z0(t)=z0+tcz_0(t) = z_0 + t c with a,b,c≥0a, b, c \ge 0, not all 0, b=Ma+dcb = M a + d c, and complementarity aTb=0a^{\mathsf T} b = 0 for all large tt, because all but one pair stay complementary and the double nonbasic pair has both members 0. If a≠0a \ne 0, then 0=aTb=aTMa+c aTd>00 = a^{\mathsf T} b = a^{\mathsf T} M a + c\, a^{\mathsf T} d > 0, a contradiction. If a=0a = 0, then c>0c > 0 (otherwise b=0b = 0 too) and b=dc>0b = d c > 0. Then for large tt all wi(t)w_i(t) and z0(t)z_0(t) are positive, and the positive variables on the ray are the nn basic ones and the entering one, so the basis consists of z0z_0 and all wiw_i but one, wew_e, which is the entering variable. The basic solution of that basis has z=0z = 0 and we=0w_e = 0, so it is the basis of Lemma 1 (with e=re = r). But the walk never returns to the start (Theorem), and at the start it enters zrz_r, not wrw_r. This is a contradiction. So for strictly copositive MM the method returns a solution, which is the case used by the code for bimatrix games.

Complexity

Each pivot costs O(n2)O(n^2) arithmetic operations on a tableau of nn rows and 2n+22n + 2 columns. An almost complementary basis is fixed by the pair with both members nonbasic (nn choices) and by one member of each other pair (2n−12^{n-1} choices), so the path has at most n2n−1n 2^{n-1} steps, and the time is O(2nn3)O(2^n n^3) in the worst case. This is not only a weak bound: Murty (1978) gave, for each n≥2n \ge 2, an LCP of order nn on which complementary pivot methods take 2n2^n 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, O(n2)O(n^2) 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 MM 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 dd. 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 M=(0CDT0)M = \begin{pmatrix} 0 & C \\ D^{\mathsf T} & 0 \end{pmatrix}, q=−1q = -\mathbf 1 with positive cost matrices CC, DD is copositive but not copositive-plus, and with d=1d = \mathbf 1 the method can end on a ray (the tests show a 2×32 \times 3 game where it does). The Lemke-Howson algorithm solves this form from a dropped label instead. The code here uses the symmetrized game S=(0A′B′T0)S = \begin{pmatrix} 0 & A' \\ B'^{\mathsf T} & 0 \end{pmatrix} with costs M=K−S>0M = K - S > 0, 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 MM, 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 MM). 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 Mz−w=qMz - w = q; this page writes w=Mz+qw = Mz + q. Moving between them changes the signs of MM and qq.
  • Reading a ray as "no solution". That is right only for some classes of MM. A general MM can have solutions that the method does not find.
  • A zero or negative covering vector. If di≤0d_i \le 0 for a row with qi<0q_i < 0, line L3 cannot make that row feasible. Use d>0d > 0.
  • 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 2n2^n complementary bases; random positive semidefinite matrices, where a ray must happen exactly when an exact LP shows that z≥0z \ge 0, Mz+q≥0Mz + q \ge 0 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.

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

  1. 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
  2. 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)
  3. 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
  4. 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.

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