Algorithm Search⌘K

Algorithmadvanced

Daskalakis-Mehta-Papadimitriou algorithm

Also called DMP algorithm, 1/2-approximate Nash algorithm.

Finds a 1/2-approximate Nash equilibrium of a bimatrix game in linear time from one action, its best response and the best response to that.

Time
O(m + n) worst
Space
O(m + n) extra
Where
m = the number of pure strategies of the row player; n = the number of pure strategies of the column player
Properties
deterministicnot exactofflineiterative
Origin
Constantinos Daskalakis, Aranyak Mehta, Christos H. Papadimitriou, 2006

The Daskalakis-Mehta-Papadimitriou (DMP) algorithm finds an approximate Nash equilibrium of a two-player game in strategic form (a bimatrix game) with payoffs in [0,1][0, 1]. It takes any row, a best column against that row, and a best row against that column. The row player mixes the two rows with equal weight and the column player plays the column. No player can then gain more than 1/21/2 by a change of strategy, so the pair is a 1/21/2-Nash equilibrium in the additive sense of the epsilon-Nash equilibrium page. The method reads only one row and one column of the input. It is the simplest member of a line of polynomial-time approximations, and the bound 1/21/2 is the best possible for every method whose strategies have small supports.

In plain words

Two players each pick a move, and every outcome pays each of them between 0 and 1. We want a pair of plans where nobody can win much by switching. Start with any move of the first player. Let the second player pick a best answer to it. Let the first player pick a best answer to that answer. Now the first player flips a fair coin between the start move and its best answer, and the second player keeps its answer. Half of the time the first player already plays its best move, so it loses at most half a point. Half of the time the second player meets the move it answered best, so it also loses at most half a point.

The problem

The input is two m×nm \times n matrices AA and BB with entries in [0,1][0, 1]. On this page mm and nn are the numbers of pure strategies of the row player and of the column player, not numbers of players. If the row player plays row rr and the column player plays column cc, they get ArcA_{rc} and BrcB_{rc}, and both maximize. A pair of mixed strategies x∈Δmx \in \Delta_m, y∈Δny \in \Delta_n is an ε\varepsilon-Nash equilibrium if

max⁡r(Ay)r−xTAy≤εandmax⁡c(xTB)c−xTBy≤ε.\max_r (Ay)_r - x^{\mathsf T} A y \le \varepsilon \quad\text{and}\quad \max_c (x^{\mathsf T} B)_c - x^{\mathsf T} B y \le \varepsilon.

The maxima are over pure strategies, and this is enough: a mixed strategy is a best response if and only if its support is inside the set of pure best responses, and any mixed deviation earns an average of pure deviation payoffs. The output is a pair (x,y)(x, y) with ε=1/2\varepsilon = 1/2. The scale [0,1][0, 1] matters, because the additive ε\varepsilon has a meaning only relative to the range of the payoffs.

The algorithm

  1. DMP(A, B, i) ▷ A, B are m by n with entries in [0, 1]; i is any row
  2. 1j ← a column that maximizes B[i][c] ▷ a best response to row i
  3. 2k ← a row that maximizes A[r][j] ▷ a best response to column j
  4. 3x ← (1/2) e_i + (1/2) e_k ▷ x = e_i if k = i
  5. 4y ← e_j
  6. 5return (x, y)

Line L1 reads one row of BB, and line L2 reads one column of AA. The code breaks ties to the smallest index, but any tie rule gives the same guarantee.

Example

Take A=(0010)A = \begin{pmatrix} 0 & 0 \\ 1 & 0 \end{pmatrix}, B=(1101)B = \begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix} and the start row i=0i = 0. Row 0 of BB is (1,1)(1, 1), so line L1 picks j=0j = 0. Column 0 of AA is (0,1)(0, 1), so line L2 picks k=1k = 1. The output is x=(1/2,1/2)x = (1/2, 1/2) and y=(1,0)y = (1, 0).

player payoff of (x,y)(x, y) best pure deviation gain
row 12⋅0+12⋅1=1/2\tfrac12 \cdot 0 + \tfrac12 \cdot 1 = 1/2 row 1, payoff 1 1/21/2
column 12⋅1+12⋅0=1/2\tfrac12 \cdot 1 + \tfrac12 \cdot 0 = 1/2 column 1, payoff 12⋅1+12⋅1=1\tfrac12 \cdot 1 + \tfrac12 \cdot 1 = 1 1/21/2

Both gains are exactly 1/21/2, so the bound of the analysis is reached. The game also has the pure equilibrium (row 1, column 1), and the algorithm finds it from the start row i=1i = 1: then j=1j = 1 and k=1k = 1, and the output is pure.

In matching pennies scaled to [0,1][0, 1], with A=(1001)A = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} and B=(0110)B = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, the start row 0 gives j=1j = 1, k=1k = 1, x=(1/2,1/2)x = (1/2, 1/2) and y=(0,1)y = (0, 1). The column player has gain 0, and the row player has gain 1/21/2, while the only equilibrium is the uniform pair.

Correctness

Let y=ejy = e_j. The row player gets 12Aij+12Akj\tfrac12 A_{ij} + \tfrac12 A_{kj}, and its best pure payoff is AkjA_{kj} by line L2. So the row gain is 12(Akj−Aij)≤12\tfrac12(A_{kj} - A_{ij}) \le \tfrac12, because both entries are in [0,1][0, 1].

The column player gets 12Bij+12Bkj\tfrac12 B_{ij} + \tfrac12 B_{kj}. A deviation to column cc gives 12Bic+12Bkc\tfrac12 B_{ic} + \tfrac12 B_{kc}, and Bic≤BijB_{ic} \le B_{ij} by line L1. So the gain from column cc is at most 12(Bkc−Bkj)≤12\tfrac12 (B_{kc} - B_{kj}) \le \tfrac12. In words, on the half of the time when the row player plays ii, the column player already plays a best response, and on the other half it loses at most 1.

By the best-response fact, pure deviations give the largest gains, so (x,y)(x, y) is a 1/21/2-Nash equilibrium. If k=ik = i, both gains are 0 and the output is a pure Nash equilibrium. If the payoffs are in [a,b][a, b] instead of [0,1][0, 1], the same argument gives a (b−a)/2(b - a)/2-Nash equilibrium. The proof file has the details and the tight example.

Proof: The DMP pair is a 1/2-Nash equilibrium, and the bound 1/2 is tightfull

Let (A,B)(A, B) be an m×nm \times n bimatrix game with all entries in [0,1][0, 1]. Here mm and nn are the numbers of pure strategies of the row player and of the column player. For mixed strategies xx and yy, the row player gets xTAyx^{\mathsf T} A y and the column player gets xTByx^{\mathsf T} B y. The pair (x,y)(x, y) is an ε\varepsilon-Nash equilibrium if max⁡r(Ay)r−xTAy≤ε\max_r (Ay)_r - x^{\mathsf T} A y \le \varepsilon and max⁡c(xTB)c−xTBy≤ε\max_c (x^{\mathsf T} B)_c - x^{\mathsf T} B y \le \varepsilon.

Lemma 1 (pure deviations are enough). For every mixed strategy x′x' of the row player, x′TAy≤max⁡r(Ay)rx'^{\mathsf T} A y \le \max_r (Ay)_r, and the same holds for the column player.

Proof. x′TAy=∑rxr′(Ay)rx'^{\mathsf T} A y = \sum_r x'_r (Ay)_r is an average of the numbers (Ay)r(Ay)_r, so it is at most their maximum. □\square

So the gain of a player from any deviation is the gain from its best pure deviation, and the two inequalities above are the full definition.

The algorithm takes any row ii, then lets jj be a column with Bij=max⁡cBicB_{ij} = \max_c B_{ic} (line L1), and kk a row with Akj=max⁡rArjA_{kj} = \max_r A_{rj} (line L2). It outputs x=12ei+12ekx = \tfrac12 e_i + \tfrac12 e_k and y=ejy = e_j (lines L3 to L5). If k=ik = i, then x=eix = e_i.

Theorem 1. (x,y)(x, y) is a 1/21/2-Nash equilibrium. More exactly, the gain of the row player is (Akj−Aij)/2(A_{kj} - A_{ij})/2, and the gain of the column player is at most max⁡c(Bkc−Bkj)/2\max_c (B_{kc} - B_{kj})/2.

Proof. First, xx and yy are mixed strategies: the weights are 12\tfrac12 and 12\tfrac12 on rows ii and kk (or 1 on row ii if k=ik = i), and 1 on column jj.

Row player. Since y=ejy = e_j, (Ay)r=Arj(Ay)_r = A_{rj}, and max⁡r(Ay)r=Akj\max_r (Ay)_r = A_{kj} by the choice of kk. The row player gets xTAy=12Aij+12Akjx^{\mathsf T} A y = \tfrac12 A_{ij} + \tfrac12 A_{kj}. So the gain is

Akj−12Aij−12Akj=12(Akj−Aij)≤12Akj≤12,A_{kj} - \tfrac12 A_{ij} - \tfrac12 A_{kj} = \tfrac12 (A_{kj} - A_{ij}) \le \tfrac12 A_{kj} \le \tfrac12,

because Aij≥0A_{ij} \ge 0 and Akj≤1A_{kj} \le 1.

Column player. The column player gets xTBy=12Bij+12Bkjx^{\mathsf T} B y = \tfrac12 B_{ij} + \tfrac12 B_{kj}. A pure deviation to column cc gives 12Bic+12Bkc\tfrac12 B_{ic} + \tfrac12 B_{kc}. By the choice of jj, Bic≤BijB_{ic} \le B_{ij}. So the gain from column cc is

12Bic+12Bkc−12Bij−12Bkj≤12(Bkc−Bkj)≤12Bkc≤12,\tfrac12 B_{ic} + \tfrac12 B_{kc} - \tfrac12 B_{ij} - \tfrac12 B_{kj} \le \tfrac12 (B_{kc} - B_{kj}) \le \tfrac12 B_{kc} \le \tfrac12,

because Bkj≥0B_{kj} \ge 0 and Bkc≤1B_{kc} \le 1. By Lemma 1 the largest gain over all strategies is the largest of these numbers, so it is at most 12\tfrac12. □\square

Corollary 1 (pure equilibrium). If k=ik = i, then (ei,ej)(e_i, e_j) is a pure Nash equilibrium.

Proof. With k=ik = i the row gain is (Aij−Aij)/2=0(A_{ij} - A_{ij})/2 = 0. For the column player, x=eix = e_i and jj is a best column against row ii, so the gain is 0 too. □\square

Corollary 2 (other payoff ranges). If every entry of AA and of BB is in [a,b][a, b], the output is a (b−a)/2(b - a)/2-Nash equilibrium.

Proof. The algorithm only compares entries of the same matrix, so it gives the same output on (A′,B′)(A', B') with Arc′=(Arc−a)/(b−a)A'_{rc} = (A_{rc} - a)/(b - a) and Brc′=(Brc−a)/(b−a)B'_{rc} = (B_{rc} - a)/(b - a), whose entries are in [0,1][0, 1]. All gains scale by the factor b−ab - a. If a=ba = b, every gain is 0. □\square

Theorem 2 (the bound is tight). For every a,b∈[0,1]a, b \in [0, 1], the game

A=(0a1b),B=(1101)A = \begin{pmatrix} 0 & a \\ 1 & b \end{pmatrix}, \qquad B = \begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}

with start row i=0i = 0 and ties broken to the smallest index gives an output where both gains are exactly 12\tfrac12.

Proof. Row 0 of BB is (1,1)(1, 1), so the tie goes to j=0j = 0. Column 0 of AA is (0,1)(0, 1), so k=1k = 1. The output is x=(12,12)x = (\tfrac12, \tfrac12) and y=e0y = e_0. The row player gets 12(0+1)=12\tfrac12(0 + 1) = \tfrac12 and row 1 gives 1, a gain of 12\tfrac12. The column player gets 12(1+0)=12\tfrac12 (1 + 0) = \tfrac12, and column 1 gives 12(1+1)=1\tfrac12(1 + 1) = 1, a gain of 12\tfrac12. □\square

Running time. Line L1 reads the nn entries Bi0,…,Bi,n−1B_{i0}, \dots, B_{i,n-1} and line L2 reads the mm entries A0j,…,Am−1,jA_{0j}, \dots, A_{m-1,j}. The other lines write m+nm + n numbers. So the time is O(m+n)O(m + n), which is sublinear in the size 2mn2mn of the input when the matrices can be read at random positions.

Complexity

Line L1 reads nn entries and line L2 reads mm entries, and the output has m+nm + n numbers. So the time is O(m+n)O(m + n) and the extra space is O(m+n)O(m + n), in the real-RAM model with one step for each comparison. This is sublinear in the input size 2mn2mn if the input can be read at any position. Trying all mm start rows and keeping the best pair costs O(m(m+n))O(m(m + n)) and still guarantees only 1/21/2.

Properties

  • Small supports. The row player uses at most 2 strategies and the column player uses 1.
  • Deterministic and exact. With rational payoffs the output and its gains are exact rationals.
  • Tight analysis. The example above reaches the bound 1/21/2 for both players at the same time.
  • Not an equilibrium in general. The output is an exact equilibrium only when k=ik = i, that is, when the start row is a best response to its own best response.
  • Additive only. The guarantee needs payoffs on a common scale. It says nothing about relative approximation.

Variants and improvements

  • Smaller ε\varepsilon in polynomial time. Larger supports and linear programs give better bounds: about 0.380.38 (Daskalakis, Mehta and Papadimitriou, EC 2007), 0.360.36 (Bosse, Byrka and Markakis), 0.33930.3393 (Tsaknakis and Spirakis 2008, by a descent method) and 1/3+δ1/3 + \delta for every constant δ>0\delta > 0 (Deligkas, Fasoulakis and Markakis, ESA 2022 and ACM Transactions on Algorithms 2023). A 2026 preprint of Li and Li claims about 0.3095+δ0.3095 + \delta, and it is not yet peer reviewed as of November 2026.
  • Quasi-polynomial time for any ε\varepsilon. The Lipton-Markakis-Mehta algorithm searches over supports of size O(log⁡n/ε2)O(\log n / \varepsilon^2). Under an exponential-time hypothesis for PPAD, constant ε\varepsilon cannot be done much faster (Rubinstein's theorem).
  • Well-supported equilibria. In an ε\varepsilon-well-supported equilibrium every strategy in the support must be within ε\varepsilon of a best response. The same note of DMP gives a reduction of this notion to win-lose games and a 5/65/6 bound that depends on a graph conjecture. The best known polynomial bound is 1/2+δ1/2 + \delta (Deligkas, Fasoulakis and Markakis).
  • Exact equilibria. Lemke-Howson or support enumeration give exact answers in exponential time in the worst case. The exact problem is PPAD-complete (PPAD-completeness of Nash).

When to use it

Use it as a fast baseline, as a warm start for a local search, or when the game is too large to read in full and only m+nm + n queries are allowed. Use it in tests and in teaching, because the analysis fits in a few lines. When 1/21/2 is too coarse, use the LP-based methods with a bound near 1/31/3, or an exact method on small games.

Pitfalls

  • Payoffs outside [0,1][0, 1]. The bound 1/21/2 is in units of the payoff range. Scale the payoffs first, or read the result as (b−a)/2(b - a)/2.
  • Wrong matrix in a step. Line L1 uses the column player's payoffs BB and line L2 uses the row player's payoffs AA. Swapping them breaks the proof.
  • Two entries for one row when k=ik = i. If the code stores xx as a list of (row, weight) pairs, row ii appears twice with weight 1/21/2. Merge the pairs, so that row ii has weight 1.
  • Expecting better on easy games. A good start row helps, but no choice of start row improves the worst-case bound, and the example above has gain 1/21/2 from row 0.
  • Small supports cannot do better. Feder, Nazerzadeh and Saberi (EC 2007) showed games in which every ε\varepsilon-Nash equilibrium with ε<1/2\varepsilon < 1/2 needs supports of logarithmic size. So no method of this kind, with supports of constant size, can beat 1/21/2.

Implementations

The Python code follows lines L1 to L5 in exact rational arithmetic and returns the two gains. The tests check the tight example for several values of the free entries, a pure equilibrium found when k=ik = i, battle of the sexes, matching pennies and chicken scaled to [0,1][0, 1], and 300 random games with every start row, each checked against the shared exact checker. They also scale random integer payoffs to test the bound (b−a)/2(b - a)/2, and count the entries that are read, which must be exactly m+nm + n.

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
dmp_half_approximate_nash.py 34 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dmp-half-approximate-nash/. The authors are listed in prov/F0ZSX8.jsonl.
"""The Daskalakis-Mehta-Papadimitriou algorithm for a 1/2-approximate Nash equilibrium.

The row player gets A[i][j] and the column player gets B[i][j]; both maximize. If all the
payoffs are in [0, 1], the output is a 1/2-Nash equilibrium in the additive sense: no player
gains more than 1/2 by a deviation. The method reads one row of B and one column of A, so
it reads m + n entries. Ties go to the smallest index.
"""

from fractions import Fraction


def dmp(A, B, i=0):
    """Return (x, y): x mixes row i and row k with weight 1/2 each, y is the pure column j."""
    m, n = len(A), len(A[0])
    j = max(range(n), key=lambda c: (B[i][c], -c))  # @line L1
    k = max(range(m), key=lambda r: (A[r][j], -r))  # @line L2
    x = [Fraction(0)] * m  # @line L3
    x[i] += Fraction(1, 2)
    x[k] += Fraction(1, 2)
    y = [Fraction(0)] * n  # @line L4
    y[j] = Fraction(1)
    return x, y  # @line L5


def gains(A, B, x, y):
    """Return the largest gain of the row player and of the column player from a pure deviation."""
    m, n = len(A), len(A[0])
    Ay = [sum((Fraction(A[r][c]) * y[c] for c in range(n)), Fraction(0)) for r in range(m)]
    xB = [sum((x[r] * Fraction(B[r][c]) for r in range(m)), Fraction(0)) for c in range(n)]
    u = sum((x[r] * Ay[r] for r in range(m)), Fraction(0))
    v = sum((xB[c] * y[c] for c in range(n)), Fraction(0))
    return max(Ay) - u, max(xB) - v
test_dmp_half_approximate_nash.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dmp-half-approximate-nash/. The authors are listed in prov/F0ZSX8.jsonl.

import random
from fractions import Fraction

from agtgame import from_bimatrix, is_epsilon_nash, is_nash, max_gain
from dmp_half_approximate_nash import dmp, gains

F = Fraction
HALF = F(1, 2)


def random_unit_matrix(rng, m, n, den):
    return [[F(rng.randint(0, den), den) for _ in range(n)] for _ in range(m)]


class CountingMatrix:
    """A matrix that counts how many entries are read."""

    def __init__(self, rows):
        self.rows = rows
        self.reads = 0

    def __len__(self):
        return len(self.rows)

    def __getitem__(self, r):
        return CountingRow(self, self.rows[r])


class CountingRow:
    def __init__(self, owner, row):
        self.owner = owner
        self.row = row

    def __len__(self):
        return len(self.row)

    def __getitem__(self, c):
        self.owner.reads += 1
        return self.row[c]


def test_tight_example_gains_are_exactly_half():
    for a, b in [(0, 0), (1, 1), (F(1, 3), F(2, 3))]:
        A = [[0, a], [1, b]]
        B = [[1, 1], [0, 1]]
        x, y = dmp(A, B, 0)
        assert x == [HALF, HALF] and y == [1, 0]
        assert gains(A, B, x, y) == (HALF, HALF)
        assert max_gain(from_bimatrix(A, B), [x, y]) == HALF


def test_pure_equilibrium_when_k_equals_i():
    # Prisoner's dilemma scaled to [0, 1]: defect (row 1, column 1) is dominant.
    A = [[F(3, 5), 0], [1, F(1, 5)]]
    B = [[F(3, 5), 1], [0, F(1, 5)]]
    x, y = dmp(A, B, 1)
    assert x == [0, 1] and y == [0, 1]
    assert is_nash(from_bimatrix(A, B), [x, y])


def test_check_games():
    # Battle of the sexes and matching pennies, scaled to [0, 1].
    bos = ([[1, 0], [0, HALF]], [[HALF, 0], [0, 1]])
    mp = ([[1, 0], [0, 1]], [[0, 1], [1, 0]])
    chicken = ([[0, 1], [F(2, 7), F(6, 7)]], [[0, F(2, 7)], [1, F(6, 7)]])
    for A, B in (bos, mp, chicken):
        g = from_bimatrix(A, B)
        for i in range(len(A)):
            x, y = dmp(A, B, i)
            assert is_epsilon_nash(g, [x, y], HALF)
    # In matching pennies the bound 1/2 is reached from row 0.
    x, y = dmp(*mp, 0)
    assert x == [HALF, HALF] and y == [0, 1]
    assert gains(*mp, x, y) == (HALF, 0)


def test_random_games_every_start_row():
    rng = random.Random(20261120)
    for _ in range(300):
        m, n = rng.randint(1, 6), rng.randint(1, 6)
        A = random_unit_matrix(rng, m, n, rng.choice([1, 2, 5, 12]))
        B = random_unit_matrix(rng, m, n, rng.choice([1, 2, 5, 12]))
        g = from_bimatrix(A, B)
        for i in range(m):
            x, y = dmp(A, B, i)
            assert sum(x) == 1 and sum(y) == 1 and min(x) >= 0
            assert sum(1 for p in x if p) <= 2 and sum(1 for p in y if p) == 1
            gr, gc = gains(A, B, x, y)
            assert gr <= HALF and gc <= HALF
            assert max_gain(g, [x, y]) == max(gr, gc)
            assert is_epsilon_nash(g, [x, y], HALF)


def test_gain_scales_with_the_payoff_range():
    rng = random.Random(7)
    for _ in range(200):
        m, n = rng.randint(1, 5), rng.randint(1, 5)
        lo, hi = rng.randint(-9, 0), rng.randint(1, 9)
        A = [[rng.randint(lo, hi) for _ in range(n)] for _ in range(m)]
        B = [[rng.randint(lo, hi) for _ in range(n)] for _ in range(m)]
        x, y = dmp(A, B, rng.randrange(m))
        gr, gc = gains(A, B, x, y)
        assert gr <= F(hi - lo, 2) and gc <= F(hi - lo, 2)


def test_reads_m_plus_n_entries():
    rng = random.Random(3)
    for m, n in [(1, 1), (3, 5), (8, 2), (10, 10)]:
        A = CountingMatrix(random_unit_matrix(rng, m, n, 4))
        B = CountingMatrix(random_unit_matrix(rng, m, n, 4))
        dmp(A, B, m - 1)
        assert B.reads == n and A.reads == m

History

Althöfer (1994) had shown that some games need supports of logarithmic size for a 1/41/4-approximation, and Lipton, Markakis and Mehta (2003) had given a quasi-polynomial algorithm. Daskalakis, Mehta and Papadimitriou presented the simple 1/21/2 method at WINE 2006, with the journal version in Theoretical Computer Science in 2009. The following year they gave the 0.380.38 bound at EC 2007, where Feder, Nazerzadeh and Saberi also showed that small supports cannot go below 1/21/2. The bound then went down to 0.33930.3393 in 2007 and 2008, and to 1/3+δ1/3 + \delta in 2022.

References

  1. Constantinos Daskalakis, Aranyak Mehta and Christos H. Papadimitriou, A note on approximate Nash equilibria, Theoretical Computer Science 410(17) (2009), 1581-1588, the linear-time algorithm that examines two strategies of one player and one of the other and reaches a 1/2-approximate equilibrium; conference version in WINE 2006
  2. Constantinos Daskalakis, Aranyak Mehta and Christos H. Papadimitriou, Progress in approximate Nash equilibria, Proceedings of the 8th ACM Conference on Electronic Commerce (EC 2007), 355-358, the improvement to about 0.38 with a linear program and larger supports
  3. Haralampos Tsaknakis and Paul G. Spirakis, An optimization approach for approximate Nash equilibria, Internet Mathematics 5(4) (2008), 365-382, the descent method that reaches a 0.3393-approximation
  4. Argyrios Deligkas, Michail Fasoulakis and Evangelos Markakis, A polynomial-time algorithm for 1/3-approximate Nash equilibria in bimatrix games, ACM Transactions on Algorithms 19(4) (2023), 31:1-31:17, the (1/3 + delta)-approximation in polynomial time; conference version in ESA 2022

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