Algorithm Search⌘K

Algorithmintro

Solving zero-sum games by linear programming

Also called LP for matrix games, linear programming solution of matrix games.

Computes the value and optimal mixed strategies of a two-player zero-sum matrix game with one linear program and its dual.

Time
poly(m, n, L) worst
Space
O(m n) extra
Where
L = the bit length of the matrix; m = the number of rows (pure strategies of the row player); n = the number of columns
Properties
deterministicexactofflineiterative
Origin
George B. Dantzig, John von Neumann, 1951

This algorithm solves a two-player zero-sum matrix game: it computes the value vv and an optimal mixed strategy for each player with one linear program, and reads the strategy of the second player from the dual solution. The minimax theorem says that the value exists; this page is the method that finds it, and LP duality is the reason it works. It differs from the minimax search of the games-and-search area, which walks a game tree of positions with pure moves, while here the input is a payoff matrix and the players randomize. The time is polynomial in the size of the matrix and the length of its numbers.

In plain words

Two players choose at the same time. The row player picks a row of a table of numbers, the column player picks a column, and the column player pays the number in the cell to the row player. Each player may pick at random, with chosen chances. The row player wants a mix that earns the most on average against the worst reply. For a fixed mix, the worst reply is one column, so the condition is "earn at least the target against each column". This is a list of linear conditions on the chances and the target, and the row player wants the largest target. That is a linear program. Its partner program, the dual, is the same question for the column player, and the two answers meet in one number, the value of the game.

The problem

The input is an m×nm \times n matrix MM with rational entries. On this page mm and nn are the numbers of pure strategies of the two players, not the number of players. If the row player plays row ii and the column player plays column jj, the column player pays MijM_{ij} to the row player; the row player maximizes and the column player minimizes. A mixed strategy of the row player is x∈Δm={x∈Rm:x≥0,∑ixi=1}x \in \Delta_m = \{x \in \mathbb{R}^m : x \ge 0, \sum_i x_i = 1\}, and of the column player y∈Δny \in \Delta_n. The expected payment is xTMyx^{\mathsf T} M y.

The output is the value vv and strategies x∗x^*, y∗y^* with

min⁡j(x∗TM)j  =  v  =  max⁡i(My∗)i.\min_{j} (x^{*\mathsf T} M)_j \;=\; v \;=\; \max_{i} (M y^*)_i .

So x∗x^* earns at least vv against every column, and y∗y^* pays at most vv against every row. This pair is exactly a Nash equilibrium of the bimatrix game (M,−M)(M, -M). Pure replies are enough in both tests, because xTMyx^{\mathsf T} M y is linear in yy for a fixed xx, so its minimum over Δn\Delta_n is at a vertex, a pure column. This is the best response fact: a mixed strategy is a best response if and only if each pure strategy in its support is one.

The algorithm

  1. ZERO-SUM-LP(M) ▷ M is m by n; the column player pays M[i][j] to the row player
  2. 1k ← 1 - min over i, j of M[i][j]
  3. 2M' ← M with k added to each entry ▷ now each entry is at least 1
  4. 3maximize v over x in R^m and v
  5. 4subject to v - Σ_i x_i M'[i][j] ≤ 0 for j = 1, ..., n ▷ dual variable y_j ≥ 0
  6. 5and Σ_i x_i = 1, x ≥ 0, v ≥ 0 ▷ dual variable w, free
  7. 6solve the LP by the simplex method: (x*, v*) optimal, (y*, w*) the optimal dual
  8. 7return (v* - k, x*, y*)

Lines L1 and L2 shift the matrix so that every entry is at least 1. The shift adds kk to every payoff xTMyx^{\mathsf T} M y, because xx and yy sum to 1, so it changes the value by kk and the optimal strategies not at all. After the shift the value is at least 1, so the bound v≥0v \ge 0 of line L5 cuts off nothing, and vv needs no split into two nonnegative parts. The LP of lines L3 to L5 has m+1m + 1 variables, nn inequalities and one equation.

The dual of this LP is the problem of the column player. With yj≥0y_j \ge 0 for the inequality of column jj and a free ww for the equation, the dual is

min⁡  wsubject to∑jMij′yj≤w    (i=1,…,m),∑jyj≥1,y≥0.\min\; w \quad \text{subject to} \quad \sum_j M'_{ij} y_j \le w \;\; (i = 1, \ldots, m), \qquad \sum_j y_j \ge 1, \qquad y \ge 0 .

The constraint ∑jyj≥1\sum_j y_j \ge 1 comes from the column of vv; it holds with equality at the optimum, by complementary slackness, because v∗≥1>0v^* \ge 1 > 0. So the dual solution y∗y^* is a mixed strategy, and line L6 gets both strategies from one run of the simplex method.

Example

Take M=(3−1−21)M = \begin{pmatrix} 3 & -1 \\ -2 & 1 \end{pmatrix}. Line L1 gives k=1−(−2)=3k = 1 - (-2) = 3 and M′=(6214)M' = \begin{pmatrix} 6 & 2 \\ 1 & 4 \end{pmatrix}. The LP is: maximize vv subject to v≤6x1+x2v \le 6x_1 + x_2, v≤2x1+4x2v \le 2x_1 + 4x_2, x1+x2=1x_1 + x_2 = 1, x≥0x \ge 0.

quantity value
optimal primal solution x∗=(3/7,4/7)x^* = (3/7, 4/7), v∗=22/7v^* = 22/7
optimal dual solution y∗=(2/7,5/7)y^* = (2/7, 5/7), w∗=22/7w^* = 22/7
value of the game 22/7−3=1/722/7 - 3 = 1/7
x∗TMx^{*\mathsf T} M (one entry per column) (1/7,1/7)(1/7, 1/7)
My∗M y^* (one entry per row) (1/7,1/7)(1/7, 1/7)

Both strategies are fully mixed, and each makes the other player indifferent, as the indifference principle says. A second example shows an unused row: for M=(123004)M = \begin{pmatrix} 1 & 2 \\ 3 & 0 \\ 0 & 4 \end{pmatrix} the method returns v=12/7v = 12/7, x∗=(0,4/7,3/7)x^* = (0, 4/7, 3/7) and y∗=(4/7,3/7)y^* = (4/7, 3/7). Against y∗y^* the first row earns only 4/7+6/7=10/7<12/74/7 + 6/7 = 10/7 < 12/7, so it gets probability 0. For matching pennies and rock-paper-scissors the value is 0 and both strategies are uniform.

Correctness

The LP is feasible: any x∈Δmx \in \Delta_m with v=0v = 0 satisfies all constraints. It is bounded: v≤∑ixiMi1′≤max⁡iMi1′v \le \sum_i x_i M'_{i1} \le \max_i M'_{i1}. So the simplex method with Bland's rule ends with an optimal primal solution (x∗,v∗)(x^*, v^*) and an optimal dual solution (y∗,w∗)(y^*, w^*), and strong duality gives v∗=w∗v^* = w^*. Primal feasibility says that x∗x^* earns at least v∗v^* in M′M' against each column; dual feasibility says that y∗y^* pays at most w∗=v∗w^* = v^* in M′M' against each row. Remove the shift and both statements hold for MM with v∗−kv^* - k. The full proof, with the step that y∗y^* sums to 1, is in the proof file.

Proof: The LP of a matrix game gives its value and optimal strategies for both playersfull

Let MM be an m×nm \times n matrix, let k=1−min⁡i,jMijk = 1 - \min_{i,j} M_{ij} (line L1) and let Mij′=Mij+kM'_{ij} = M_{ij} + k (line L2), so Mij′≥1M'_{ij} \ge 1 for all ii and jj. Write (P) for the LP of lines L3 to L5 and (D) for its dual.

Lemma 1 (the shift). For x∈Δmx \in \Delta_m and y∈Δny \in \Delta_n, xTM′y=xTMy+kx^{\mathsf T} M' y = x^{\mathsf T} M y + k.

Proof. xTM′y=∑i,jxiyj(Mij+k)=xTMy+k(∑ixi)(∑jyj)=xTMy+kx^{\mathsf T} M' y = \sum_{i,j} x_i y_j (M_{ij} + k) = x^{\mathsf T} M y + k \left(\sum_i x_i\right)\left(\sum_j y_j\right) = x^{\mathsf T} M y + k. □\square

Lemma 2 (the dual). The dual of (P) is (D): minimize ww subject to ∑jMij′yj≤w\sum_j M'_{ij} y_j \le w for each ii, ∑jyj≥1\sum_j y_j \ge 1, y≥0y \ge 0, ww free.

Proof. (P) is: maximize cTzc^{\mathsf T} z over z=(x,v)≥0z = (x, v) \ge 0 subject to v−∑iMij′xi≤0v - \sum_i M'_{ij} x_i \le 0 for each jj and ∑ixi=1\sum_i x_i = 1, with c=(0,…,0,1)c = (0, \ldots, 0, 1). The dual of a maximization in this form has one variable yj≥0y_j \ge 0 per inequality, one free variable ww per equation, objective min⁡(0⋅y+1⋅w)\min (0 \cdot y + 1 \cdot w), and one constraint ≥cℓ\ge c_\ell per primal variable zℓz_\ell. For the variable xix_i the constraint is −∑jMij′yj+w≥0-\sum_j M'_{ij} y_j + w \ge 0. For vv it is ∑jyj≥1\sum_j y_j \ge 1. □\square

Lemma 3 (both LPs have optimal solutions). (P) is feasible: x=(1,0,…,0)x = (1, 0, \ldots, 0) and v=0v = 0 satisfy every constraint, because M′≥1>0M' \ge 1 > 0. (P) is bounded: for every feasible point, v≤∑ixiMi1′≤max⁡iMi1′v \le \sum_i x_i M'_{i1} \le \max_i M'_{i1}. By the fundamental theorem of linear programming, (P) has an optimal basic solution, and the simplex method with Bland's rule finds one in a finite number of pivots. By strong duality, (D) has an optimal solution (y∗,w∗)(y^*, w^*) with w∗=v∗w^* = v^*.

Lemma 4 (y∗y^* is a mixed strategy). ∑jyj∗=1\sum_j y^*_j = 1.

Proof. For any x∈Δmx \in \Delta_m, the point (x,v)(x, v) with v=min⁡j(xTM′)jv = \min_j (x^{\mathsf T} M')_j is feasible, and this minimum is at least 1 because M′≥1M' \ge 1. So v∗≥1>0v^* \ge 1 > 0. By complementary slackness, a primal variable that is positive at an optimum has a tight dual constraint at every dual optimum. The variable vv is positive, so its dual constraint ∑jyj∗≥1\sum_j y^*_j \ge 1 holds with equality. Also y∗≥0y^* \ge 0, so y∗∈Δny^* \in \Delta_n. □\square

Theorem. Let (x∗,v∗)(x^*, v^*) be optimal for (P) and (y∗,w∗)(y^*, w^*) optimal for (D), as in line L6, and let v=v∗−kv = v^* - k (line L7). Then x∗∈Δmx^* \in \Delta_m, y∗∈Δny^* \in \Delta_n, and

min⁡j(x∗TM)j=v=max⁡i(My∗)i.\min_j (x^{*\mathsf T} M)_j = v = \max_i (M y^*)_i .

So vv is the value of the game, x∗x^* is an optimal (maximin) strategy of the row player, y∗y^* is an optimal (minimax) strategy of the column player, and (x∗,y∗)(x^*, y^*) is a Nash equilibrium of the bimatrix game (M,−M)(M, -M).

Proof. The constraints of (P) give x∗≥0x^* \ge 0 and ∑ixi∗=1\sum_i x^*_i = 1, so x∗∈Δmx^* \in \Delta_m, and Lemma 4 gives y∗∈Δny^* \in \Delta_n.

Primal feasibility gives (x∗TM′)j≥v∗(x^{*\mathsf T} M')_j \ge v^* for every column jj. Dual feasibility gives (M′y∗)i≤w∗=v∗(M' y^*)_i \le w^* = v^* for every row ii. Apply Lemma 1 with y=ejy = e_j (column jj as a pure strategy) and with x=eix = e_i: (x∗TM)j=(x∗TM′)j−k≥v(x^{*\mathsf T} M)_j = (x^{*\mathsf T} M')_j - k \ge v and (My∗)i=(M′y∗)i−k≤v(M y^*)_i = (M' y^*)_i - k \le v. Hence min⁡j(x∗TM)j≥v≥max⁡i(My∗)i\min_j (x^{*\mathsf T} M)_j \ge v \ge \max_i (M y^*)_i.

For the reverse, x∗TMy∗x^{*\mathsf T} M y^* is an average of the entries of x∗TMx^{*\mathsf T} M with the weights y∗y^*, so x∗TMy∗≥min⁡j(x∗TM)jx^{*\mathsf T} M y^* \ge \min_j (x^{*\mathsf T} M)_j; and it is an average of the entries of My∗M y^* with the weights x∗x^*, so x∗TMy∗≤max⁡i(My∗)ix^{*\mathsf T} M y^* \le \max_i (M y^*)_i. Together with the chain above, all these numbers are equal to vv.

For any x∈Δmx \in \Delta_m, xTMy∗≤max⁡i(My∗)i=vx^{\mathsf T} M y^* \le \max_i (M y^*)_i = v, so no strategy of the row player earns more than vv against y∗y^*; for any y∈Δny \in \Delta_n, x∗TMy≥vx^{*\mathsf T} M y \ge v. So max⁡xmin⁡yxTMy≥v≥min⁡ymax⁡xxTMy\max_x \min_y x^{\mathsf T} M y \ge v \ge \min_y \max_x x^{\mathsf T} M y, and the general inequality max⁡xmin⁡y≤min⁡ymax⁡x\max_x \min_y \le \min_y \max_x makes both equal to vv. In the game (M,−M)(M, -M), no pure deviation of the row player gains against y∗y^* and no pure deviation of the column player gains against x∗x^*, and checking pure deviations is enough because a payoff that is linear in a player's own mixed strategy is maximized at a pure strategy. ■\blacksquare

Termination. The LP has finitely many bases. Bland's rule never visits a basis twice (Bland 1977), so each phase of the simplex method ends after at most as many pivots as there are bases, a fixed finite number for the given mm and nn. The algorithm has no loop of its own.

Complexity

The LP has m+1m + 1 variables and n+1n + 1 constraints, and its numbers are those of MM plus a shift, so its bit length is O(L)O(L), where LL is the bit length of MM.

  • With the ellipsoid method or an interior point method, the time is polynomial in mm, nn and LL. The value and the strategies are rational numbers with a polynomial number of digits, because they solve a square linear system made of entries of MM.
  • With the simplex method, the number of pivots is exponential in the worst case for the common pivot rules (the Klee-Minty cube for Dantzig's rule), but small in practice. Each pivot costs O(mn)O(m n) arithmetic operations on the tableau. In the smoothed analysis model the shadow vertex simplex method takes polynomial time.
  • The space is O(mn)O(m n) numbers for the tableau.

The code on this page uses exact rational arithmetic, so a pivot costs O(mn)O(m n) operations on numbers whose size grows with LL.

Properties

  • Exact. With rational input and rational arithmetic, the value and the strategies are exact, and the equilibrium test of the problem statement is an exact comparison.
  • One LP for both players. The dual solution gives the second strategy, so one run solves the game.
  • The optimal strategies form a polytope. The set of optimal xx is the set of optimal solutions of the LP, a face of the feasible set, and the same holds for yy. Any optimal xx pairs with any optimal yy (the equilibria are interchangeable), and all pairs give the same value. The method returns one vertex of each set.
  • Strategic equivalence. Adding a constant to every entry, or multiplying every entry by a positive constant, changes the value in the same way and keeps the optimal strategies.

Variants and improvements

  • No shift, a free value. Keep MM and write v=v+−v−v = v^+ - v^- with v+,v−≥0v^+, v^- \ge 0. This avoids line L1, but gives one more column.
  • The scaled form. With M′>0M' > 0, set u=x/vu = x / v. Then the row player's LP becomes min⁡∑iui\min \sum_i u_i subject to M′Tu≥1M'^{\mathsf T} u \ge \mathbf 1, u≥0u \ge 0, and x=u/∑iuix = u / \sum_i u_i, v=1/∑iuiv = 1 / \sum_i u_i. This is the form in many textbooks.
  • Extensive-form games. A zero-sum game tree with perfect recall has an LP of size linear in the tree, the sequence-form linear program. The matrix of the normal form can be exponentially larger.
  • Approximation by learning. If two players run a no-regret algorithm such as multiplicative weights against each other, the average payoff converges to the value (no-regret zero-sum theorem). An ε\varepsilon-approximation with payoffs in [0,1][0, 1] takes O(log⁡(m+n)/ε2)O(\log(m + n) / \varepsilon^2) rounds of O(mn)O(m n) time each, which is faster than an LP for large games and moderate ε\varepsilon.
  • General sum. Without B=−AB = -A this LP does not apply. A Nash equilibrium of a general bimatrix game needs support enumeration or the Lemke-Howson algorithm, and the problem is PPAD-complete (Nash equilibrium computation).

When to use it

Use it for any two-player zero-sum or constant-sum game given as a matrix, when an exact answer is needed and the matrix fits in memory. A constant-sum game with A+B=cA + B = c for a constant cc is the zero-sum game (A,−A)(A, -A) shifted by cc for the second player, so it has the same equilibria. Use the sequence form when the game is a tree, and a learning method when the matrix is too large to write down but best responses are cheap.

Pitfalls

  • Applying it to a general-sum game. The LP of the row player then gives the maximin strategy of the row player, which in general is not part of a Nash equilibrium.
  • Forgetting the sign of vv. If v≥0v \ge 0 is kept as a bound while the value is negative, the LP becomes infeasible. Shift the matrix (lines L1 and L2) or split vv.
  • Reading yy from the wrong place. The column strategy is the vector of dual values of the nn column constraints, not of the equation. In a solver with a different sign convention for duals, check the signs.
  • Floating point. With floats, the equilibrium test needs a tolerance, and degenerate games may give a strategy that is off by rounding. Use rationals when the result must be exact.
  • Expecting a unique answer. Many games have many optimal strategies. The simplex method returns one vertex, and two solvers may return different ones.

Implementations

The Python code builds the LP of lines L3 to L5 and solves it with the shared exact simplex code (two phases, Bland's rule, rational numbers). The tests check matching pennies and rock-paper-scissors, the examples above, and 150 random games: each output must guarantee the value against every row and column, must be a Nash equilibrium of (M,−M)(M, -M) by a check of all pure deviations, and must match the value found by an independent method, a search over all square submatrices (the kernels of Shapley and Snow). The column player's LP, solved on its own, must give the same value.

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]
zero_sum_game_linear_programming.py 70 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-sum-game-linear-programming/. The authors are listed in prov/6NAYNS.jsonl.
"""Solve a two-player zero-sum matrix game by one linear program and its dual.

The game is a matrix M with m rows and n columns: when the row player plays i and the
column player plays j, the column player pays M[i][j] to the row player. The row player
maximizes and the column player minimizes. All arithmetic is exact, in Fraction.
"""

from fractions import Fraction

from agtlp import lp_max, lp_min


def _shift(M):
    M = [[Fraction(v) for v in row] for row in M]
    if not M or not M[0] or any(len(row) != len(M[0]) for row in M):
        raise ValueError("M must be a nonempty m by n matrix")
    k = 1 - min(min(row) for row in M)  # @line L1
    Mp = [[v + k for v in row] for row in M]  # @line L2
    return M, k, Mp


def zero_sum_lp(M):
    """Return (value, x, y): the value of the game, an optimal mixed strategy x of the row
    player and an optimal mixed strategy y of the column player.

    x comes from the primal LP of the row player and y from its dual.
    """
    M, k, Mp = _shift(M)
    m, n = len(M), len(M[0])
    # The variables are x_0, ..., x_(m-1) and v, in this order.
    c = [0] * m + [1]  # @line L3
    A_ub = [[-Mp[i][j] for i in range(m)] + [1] for j in range(n)]  # @line L4
    b_ub = [0] * n
    A_eq = [[1] * m + [0]]  # @line L5
    b_eq = [1]
    status, z, v, dual = lp_max(c, A_ub, b_ub, A_eq, b_eq)  # @line L6
    if status != "optimal":
        raise AssertionError("the LP of a matrix game is always feasible and bounded")
    x, y = z[:m], dual[:n]
    return v - k, x, y  # @line L7


def column_player_lp(M):
    """Return (value, y) from the LP of the column player, solved on its own.

    This minimizes w subject to sum_j M'[i][j] y_j <= w for each row i, sum_j y_j = 1 and
    y >= 0, where M' is the shifted matrix. It is the dual of the LP of zero_sum_lp, and
    serves as a second way to get y.
    """
    M, k, Mp = _shift(M)
    m, n = len(M), len(M[0])
    c = [0] * n + [1]
    A_ub = [Mp[i] + [-1] for i in range(m)]
    A_eq = [[1] * n + [0]]
    status, z, w, _ = lp_min(c, A_ub, [0] * m, A_eq, [1])
    if status != "optimal":
        raise AssertionError("the LP of a matrix game is always feasible and bounded")
    return w - k, z[:n]


def guarantees(M, x, y):
    """Return (lo, hi): the least payoff that x guarantees against every column, and the
    largest payoff that y concedes against every row. x and y are optimal if and only if
    lo == hi, and then lo is the value."""
    m, n = len(M), len(M[0])
    lo = min(sum((x[i] * M[i][j] for i in range(m)), Fraction(0)) for j in range(n))
    hi = max(sum((M[i][j] * y[j] for j in range(n)), Fraction(0)) for i in range(m))
    return lo, hi
test_zero_sum_game_linear_programming.py 294 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-sum-game-linear-programming/. The authors are listed in prov/6NAYNS.jsonl.
"""Tests of the page algorithm and of the shared helper agtlp."""

import random
from fractions import Fraction
from itertools import combinations

from agtgame import from_bimatrix, is_nash
from agtlp import lp_max, lp_min
from zero_sum_game_linear_programming import column_player_lp, guarantees, zero_sum_lp

F = Fraction


# Exact linear algebra for the brute force checks.

def _det(K):
    K = [list(row) for row in K]
    r = len(K)
    d = F(1)
    for col in range(r):
        p = next((k for k in range(col, r) if K[k][col] != 0), None)
        if p is None:
            return F(0)
        if p != col:
            K[col], K[p] = K[p], K[col]
            d = -d
        d *= K[col][col]
        for k in range(col + 1, r):
            f = K[k][col] / K[col][col]
            if f:
                K[k] = [a - f * b for a, b in zip(K[k], K[col])]
    return d


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


def _reduce(rows, rhs):
    """Drop dependent rows of rows z = rhs. Return (rows, rhs), or None if inconsistent."""
    keep_r, keep_b = [], []
    work = []
    for row, b in zip(rows, rhs):
        v = list(row) + [b]
        for piv, w in work:
            if v[piv]:
                f = v[piv] / w[piv]
                v = [a - f * c for a, c in zip(v, w)]
        piv = next((j for j in range(len(row)) if v[j] != 0), None)
        if piv is None:
            if v[-1] != 0:
                return None
            continue
        work.append((piv, v))
        keep_r.append(list(row))
        keep_b.append(b)
    return keep_r, keep_b


def _vertices(rows, rhs, ncols):
    """Yield every basic feasible solution of rows z = rhs, z >= 0."""
    red = _reduce(rows, rhs)
    if red is None:
        return
    rows, rhs = red
    r = len(rows)
    if r == 0:
        yield [F(0)] * ncols
        return
    for cols in combinations(range(ncols), r):
        K = [[rows[i][j] for j in cols] for i in range(r)]
        z = _solve_square(K, rhs)
        if z is not None and all(v >= 0 for v in z):
            full = [F(0)] * ncols
            for j, v in zip(cols, z):
                full[j] = v
            yield full


def brute_lp_max(c, A_ub, b_ub, A_eq, b_eq):
    """Return (status, value) by enumeration of all bases of the primal and the dual."""
    n, m1, m2 = len(c), len(A_ub), len(A_eq)
    A_ub = [[F(v) for v in row] for row in A_ub]
    A_eq = [[F(v) for v in row] for row in A_eq]
    b_ub, b_eq = [F(v) for v in b_ub], [F(v) for v in b_eq]
    rows = [list(A_ub[i]) + [F(int(k == i)) for k in range(m1)] for i in range(m1)]
    rows += [list(A_eq[i]) + [F(0)] * m1 for i in range(m2)]
    best = None
    for z in _vertices(rows, list(b_ub) + list(b_eq), n + m1):
        val = sum((F(c[j]) * z[j] for j in range(n)), F(0))
        if best is None or val > best:
            best = val
    if best is None:
        return "infeasible", None
    # Dual: A_ub^T u + A_eq^T (p - q) - t = c with u, p, q, t >= 0.
    drows = []
    for j in range(n):
        drows.append([F(A_ub[i][j]) for i in range(m1)] + [F(A_eq[i][j]) for i in range(m2)]
                     + [-F(A_eq[i][j]) for i in range(m2)] + [F(-int(k == j)) for k in range(n)])
    if next(_vertices(drows, [F(v) for v in c], m1 + 2 * m2 + n), None) is None:
        return "unbounded", None
    return "optimal", best


def check_certificate(c, A_ub, b_ub, A_eq, b_eq, x, value, dual, maximize=True):
    n, m1, m2 = len(c), len(A_ub), len(A_eq)
    A = [list(map(F, r)) for r in A_ub] + [list(map(F, r)) for r in A_eq]
    b = [F(v) for v in b_ub] + [F(v) for v in b_eq]
    assert len(x) == n and len(dual) == m1 + m2
    assert all(v >= 0 for v in x)
    ax = [sum((A[i][j] * x[j] for j in range(n)), F(0)) for i in range(m1 + m2)]
    assert all(ax[i] <= b[i] for i in range(m1))
    assert all(ax[i] == b[i] for i in range(m1, m1 + m2))
    assert sum((F(c[j]) * x[j] for j in range(n)), F(0)) == value
    # Strong duality.
    assert sum((b[i] * dual[i] for i in range(m1 + m2)), F(0)) == value
    aty = [sum((A[i][j] * dual[i] for i in range(m1 + m2)), F(0)) for j in range(n)]
    for i in range(m1):
        assert dual[i] >= 0 if maximize else dual[i] <= 0
        assert dual[i] * (b[i] - ax[i]) == 0  # complementary slackness
    for j in range(n):
        assert aty[j] >= c[j] if maximize else aty[j] <= c[j]
        assert x[j] * (aty[j] - c[j]) == 0  # complementary slackness


def random_lp(rng):
    n = rng.randint(1, 3)
    m1 = rng.randint(0, 3)
    m2 = rng.randint(0, 2)
    c = [rng.randint(-3, 3) for _ in range(n)]
    A_ub = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(m1)]
    b_ub = [rng.randint(-2, 4) for _ in range(m1)]
    A_eq = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(m2)]
    b_eq = [rng.randint(-2, 3) for _ in range(m2)]
    if m2 and rng.random() < 0.2:  # a redundant equation
        A_eq.append([2 * v for v in A_eq[0]])
        b_eq.append(2 * b_eq[0])
    if m1 and rng.random() < 0.3:  # zero right sides make degenerate vertices
        b_ub = [0 if rng.random() < 0.6 else v for v in b_ub]
    return c, A_ub, b_ub, A_eq, b_eq


def test_helper_against_brute_force():
    rng = random.Random(7101)
    seen = set()
    for _ in range(1500):
        c, A_ub, b_ub, A_eq, b_eq = random_lp(rng)
        status, x, value, dual = lp_max(c, A_ub, b_ub, A_eq, b_eq)
        want, best = brute_lp_max(c, A_ub, b_ub, A_eq, b_eq)
        assert status == want
        seen.add(status)
        if status == "optimal":
            assert value == best
            check_certificate(c, A_ub, b_ub, A_eq, b_eq, x, value, dual)
        else:
            assert x is None and value is None and dual is None
        # lp_min of c is minus lp_max of -c.
        s2, x2, v2, d2 = lp_min([-v for v in c], A_ub, b_ub, A_eq, b_eq)
        assert s2 == status
        if s2 == "optimal":
            assert v2 == -value
            check_certificate([-v for v in c], A_ub, b_ub, A_eq, b_eq, x2, v2, d2, maximize=False)
    assert seen == {"optimal", "infeasible", "unbounded"}


def test_helper_beale_cycling_example():
    # Beale's example makes the simplex method cycle under the largest coefficient rule.
    c = [F(-3, 4), 20, F(-1, 2), 6]
    A_ub = [[F(1, 4), -8, -1, 9], [F(1, 2), -12, F(-1, 2), 3], [0, 0, 1, 0]]
    b_ub = [0, 0, 1]
    status, x, value, dual = lp_min(c, A_ub, b_ub)
    assert status == "optimal" and value == F(-5, 4)
    assert x == [1, 0, 1, 0]
    check_certificate(c, A_ub, b_ub, [], [], x, value, dual, maximize=False)
    assert brute_lp_max([-v for v in c], A_ub, b_ub, [], []) == ("optimal", F(5, 4))


def test_helper_small_cases():
    assert lp_max([1], [], [])[0] == "unbounded"
    assert lp_max([-1], [], []) == ("optimal", [0], 0, [])
    assert lp_max([1, 1], [[1, 0]], [-1])[0] == "infeasible"
    assert lp_max([1, 0], [[1, -1]], [1])[0] == "unbounded"
    assert lp_max([1, 1], [], [], [[1, 1], [2, 2]], [1, 2])[2] == 1
    assert lp_max([1, 1], [], [], [[1, 1], [1, 1]], [1, 2])[0] == "infeasible"
    s, x, v, d = lp_max([3, 2], [[1, 1], [1, 3]], [4, 6])
    assert (s, x, v) == ("optimal", [4, 0], 12)
    check_certificate([3, 2], [[1, 1], [1, 3]], [4, 6], [], [], x, v, d)
    s, x, v, d = lp_min([1, 1], [[-1, -2], [-3, -1]], [-4, -6])
    assert (s, x, v) == ("optimal", [F(8, 5), F(6, 5)], F(14, 5))
    assert all(isinstance(t, Fraction) for t in x + d)


# The page algorithm.

def shapley_snow_value(M):
    """Return the value of the matrix game M by brute force over its square submatrices.

    For a square submatrix K with s = 1^T adj(K) 1 != 0, the candidates are v = det(K) / s,
    x = 1^T adj(K) / s and y = adj(K) 1 / s. Shapley and Snow (1950) show that some K gives
    optimal strategies. Each candidate is checked against every row and column.
    """
    k = 1 - min(min(row) for row in M)
    Mp = [[F(v) + k for v in row] for row in M]
    m, n = len(M), len(M[0])
    for r in range(1, min(m, n) + 1):
        for I in combinations(range(m), r):
            for J in combinations(range(n), r):
                K = [[Mp[i][j] for j in J] for i in I]
                d = _det(K)
                if d == 0:
                    continue
                # adj(K) = det(K) K^{-1}, so x and y solve K^T x = 1 and K y = 1, rescaled.
                xs = _solve_square([[K[a][b] for a in range(r)] for b in range(r)], [F(1)] * r)
                ys = _solve_square(K, [F(1)] * r)
                s = sum(xs)
                if s == 0:
                    continue
                v = 1 / s
                x = [F(0)] * m
                y = [F(0)] * n
                for a, i in enumerate(I):
                    x[i] = xs[a] * v
                for b, j in enumerate(J):
                    y[j] = ys[b] * v
                if min(x) < 0 or min(y) < 0:
                    continue
                lo, hi = guarantees(Mp, x, y)
                if lo == hi == v:
                    return v - k
    raise AssertionError("Shapley-Snow found no kernel")


def check_solution(M, value, x, y):
    Mf = [[F(v) for v in row] for row in M]
    assert all(t >= 0 for t in x) and sum(x) == 1
    assert all(t >= 0 for t in y) and sum(y) == 1
    lo, hi = guarantees(Mf, x, y)
    assert lo == value == hi
    # A Nash equilibrium of the bimatrix game (M, -M), checked by pure deviations.
    assert is_nash(from_bimatrix(Mf, [[-v for v in row] for row in Mf]), [x, y])


def test_matching_pennies_and_rps():
    for M in ([[1, -1], [-1, 1]], [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]):
        value, x, y = zero_sum_lp(M)
        k = len(M)
        assert value == 0
        assert x == [F(1, k)] * k and y == [F(1, k)] * k
        check_solution(M, value, x, y)


def test_page_example():
    M = [[3, -1], [-2, 1]]
    value, x, y = zero_sum_lp(M)
    assert value == F(1, 7)
    assert x == [F(3, 7), F(4, 7)]
    assert y == [F(2, 7), F(5, 7)]
    check_solution(M, value, x, y)


def test_saddle_point_and_dominated_rows():
    M = [[4, 2, 3], [1, 0, 5], [3, 1, 2]]
    value, x, y = zero_sum_lp(M)
    assert value == 2 and x == [1, 0, 0] and y == [0, 1, 0]
    check_solution(M, value, x, y)


def test_random_games_against_shapley_snow():
    rng = random.Random(2028)
    for _ in range(150):
        m, n = rng.randint(1, 4), rng.randint(1, 4)
        M = [[rng.randint(-5, 5) for _ in range(n)] for _ in range(m)]
        value, x, y = zero_sum_lp(M)
        check_solution(M, value, x, y)
        assert value == shapley_snow_value(M)
        w, y2 = column_player_lp(M)
        assert w == value
        check_solution(M, value, x, y2)

History

Von Neumann proved the minimax theorem in 1928. In 1951 Dantzig published a proof that a matrix game is a linear program and that a linear program reduces to a symmetric matrix game. Adler (2013) showed that the reduction from linear programs to games misses one case, and gave a complete reduction.

References

  1. John von Neumann, Zur Theorie der Gesellschaftsspiele, Mathematische Annalen 100(1) (1928), 295-320, the minimax theorem for finite two-person zero-sum games, which the LP computes
  2. George B. Dantzig, A proof of the equivalence of the programming problem and the game problem, pp. 330 to 335 (a matrix game as a linear program, and the reduction back)
  3. Ilan Adler, The equivalence of linear programs and zero-sum games, International Journal of Game Theory 42(1) (2013), 165-177, the case that Dantzig's reduction from linear programs to games misses, and a complete reduction
  4. Yoav Shoham and Kevin Leyton-Brown, Multiagent Systems, Algorithmic, Game-Theoretic, and Logical Foundations, Cambridge University Press, 2009, Chapter 4 (computing the equilibria of two-player zero-sum games by linear programming)
  5. 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), the LP of a zero-sum game and its dual

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example