Algorithm Search⌘K

Algorithmresearch

Ellipsoid against hope

Also called Papadimitriou-Roughgarden algorithm.

Computes a correlated equilibrium of a succinct multiplayer game in polynomial time by running the ellipsoid method on an infeasible dual.

Time
poly(n, k, L) worst
Space
poly(n, k, L) extra
Where
L = the bit length of the game description; k = the largest number of pure strategies of a player; n = the number of players
Properties
deterministicexactofflineiterative
Origin
Christos H. Papadimitriou, Tim Roughgarden, Albert Xin Jiang, Kevin Leyton Brown, 2005

Ellipsoid against hope computes a correlated equilibrium of a game with many players in time polynomial in the size of a succinct description, such as a graphical game, a polymatrix game or a congestion game. The correlated equilibrium LP has one variable for each pure profile, which is exponentially many in the number of players, so it cannot even be written down for such games. Its dual has only ∑iki(ki−1)\sum_i k_i(k_i - 1) variables, and it is infeasible, because a correlated equilibrium exists. The algorithm runs the ellipsoid method on this infeasible dual, "against hope", and records the constraints that cut it. These constraints correspond to a polynomial number of profiles, and an LP restricted to them has a solution, which is a correlated equilibrium. The algorithm is due to Papadimitriou and Roughgarden (2008); the form given here, with a pure-profile oracle, is the exact version of Jiang and Leyton-Brown (2015). It finds some correlated equilibrium, not one of maximum welfare; for many succinct classes that optimization problem is NP-hard. Learning methods such as the Blum-Mansour reduction and regret matching also work on succinct games, but give only approximate equilibria.

In plain words

Writing down a correlated equilibrium directly means giving a chance to every combination of moves, and with many players there are far too many combinations. So the method works on the other side of the problem. There, a candidate is a small table of weights, one for each player and each pair of moves, that would prove that no correlated equilibrium exists. Such a proof is impossible, since an equilibrium always exists. The method still searches for one with the ellipsoid method. Each time, it finds a single combination of moves that shows the current candidate is wrong. After a polynomial number of rounds the search has run out of room, and the few combinations that it found are enough: a small linear program over just those combinations finds the equilibrium.

The problem

The input is a game with players 1,…,n1, \ldots, n, strategy sets SiS_i with ∣Si∣=ki≤k|S_i| = k_i \le k, and utilities uiu_i (maximized), given in a succinct form of bit length LL. The game must be of polynomial type (nn and kk are polynomial in LL) and have a polynomial expected utility algorithm: given a product distribution x=x1×⋯×xnx = x_1 \times \cdots \times x_n, it computes Es∼x[ui(s)]\mathbb{E}_{s \sim x}[u_i(s)] in time polynomial in LL. Graphical games, polymatrix games, congestion games and many other classes qualify. The output is a correlated equilibrium, given as a list of polynomially many profiles with their probabilities.

Write UU for the matrix of the incentive constraints. It has a row for each player ii and ordered pair j≠lj \ne l in SiS_i, a column for each profile ss, and the entry ui(s)−ui(l,s−i)u_i(s) - u_i(l, s_{-i}) if si=js_i = j and 0 otherwise. A distribution pp on profiles is a correlated equilibrium exactly when Up≥0Up \ge 0. For a dual vector y≥0y \ge 0 with one entry yi(j,l)y_i(j, l) per row, the value of column ss is

g(y,s)=(U⊤y)s=∑i=1n∑l≠siyi(si,l) [ui(s)−ui(l,s−i)].g(y, s) = (U^\top y)_s = \sum_{i=1}^{n} \sum_{l \ne s_i} y_i(s_i, l)\,\big[u_i(s) - u_i(l, s_{-i})\big].

The primal LP "maximize ∑sp(s)\sum_s p(s) subject to Up≥0Up \ge 0, p≥0p \ge 0" is unbounded, because a correlated equilibrium exists and can be scaled. So by LP duality, its dual system

y≥0,g(y,s)≤−1 for every profile sy \ge 0, \qquad g(y, s) \le -1 \text{ for every profile } s

is infeasible. It has d=∑iki(ki−1)≤nk2d = \sum_i k_i(k_i - 1) \le n k^2 variables and one constraint per profile.

The algorithm

  1. ELLIPSOID-AGAINST-HOPE(G)
  2. 1E ← a ball of radius R around 0 in the space of the dual vectors y; X ← the empty set
  3. 2repeat
  4. 3y ← the center of E
  5. 4if y_r < 0 for some coordinate r, then cut E by the halfspace y_r ≥ 0
  6. 5else
  7. 6s ← ORACLE(y) ▷ a pure profile with g(y, s) ≥ 0
  8. 7add s to X, and cut E by the halfspace g(·, s) ≤ g(y, s)
  9. 8p ← a correlated equilibrium with support in X, from an LP, if one exists
  10. 9if p exists, return p

A cut replaces EE by the smallest ellipsoid that contains the half of EE on the given side of a hyperplane through its center. The oracle of line L6 works in two steps.

  1. For each player ii, the weights yi(j,l)y_i(j, l) define a continuous-time Markov chain on SiS_i with rate yi(j,l)y_i(j, l) from jj to ll. Let xix_i be a stationary distribution of this chain, so that xi(j)∑lyi(j,l)=∑lxi(l) yi(l,j)x_i(j) \sum_l y_i(j, l) = \sum_l x_i(l)\, y_i(l, j) for every jj. Then for the product x=x1×⋯×xnx = x_1 \times \cdots \times x_n, the expected value Es∼x g(y,s)\mathbb{E}_{s \sim x}\, g(y, s) is exactly 0. This is the key lemma of Papadimitriou and Roughgarden.
  2. Fix the players one at a time. For player ii, choose the strategy aa that maximizes the conditional expectation of g(y,s)g(y, s), given the strategies already fixed and si+1,…,sns_{i+1}, \ldots, s_n drawn from xx. The maximum is at least the average, so the conditional expectation never drops below 0, and the final pure profile has g(y,s)≥0g(y, s) \ge 0. This step is the derandomization of Jiang and Leyton-Brown. Each conditional expectation is a sum of expected utilities under product distributions, so it uses the expected utility algorithm.

Since g(y,s)≥0>−1g(y, s) \ge 0 > -1, the profile ss gives a dual constraint that the center violates, and line L7 is a valid cut for the dual system. The original analysis runs the ellipsoid method for a fixed polynomial number of steps NN, after which the volume argument shows that the cuts already make the dual infeasible, and then solves the LP of line L8 once. The code checks the LP each time XX grows, and stops at the first success.

Example

Take chicken with strategies D = 0 and C = 1, and payoffs (D, D) = (0, 0), (D, C) = (7, 2), (C, D) = (2, 7), (C, C) = (6, 6). The dual vector is y=(y1(D,C),y1(C,D),y2(D,C),y2(C,D))y = (y_1(\text{D}, \text{C}), y_1(\text{C}, \text{D}), y_2(\text{D}, \text{C}), y_2(\text{C}, \text{D})), so d=4d = 4. Start with the ball of radius R=10R = 10.

step center yy stationary x1x_1, x2x_2 oracle profile ss column of ss in UU g(y,s)g(y, s) LP on XX
1 (0, 0, 0, 0) any, say (1, 0), (1, 0) (D, D) (-2, 0, -2, 0) 0 infeasible
2 (1.414, 0, 1.414, 0) (0, 1), (0, 1) (D, C) (1, 0, 0, 2) 1.414 p(D,C)=1p(\text{D}, \text{C}) = 1

In step 1 the oracle returns (D, D), and the cut keeps the half where −2y1(D,C)−2y2(D,C)≤0-2y_1(\text{D}, \text{C}) - 2y_2(\text{D}, \text{C}) \le 0. For a ball, the new center moves a distance R/(d+1)=2R/(d + 1) = 2 away from the cut hyperplane, along the unit vector (1,0,1,0)/2(1, 0, 1, 0)/\sqrt{2}, so it is (1.414,0,1.414,0)(1.414, 0, 1.414, 0). At this center both chains flow only from D to C, so the stationary distributions sit on C. Starting from the product (C, C), player 1 compares gg at (D, C), which is 1.414⋅(7−6)1.414 \cdot (7 - 6), with gg at (C, C), which is 0, and picks D; player 2 then picks C. The LP on X={(D,D),(D,C)}X = \{(\text{D}, \text{D}), (\text{D}, \text{C})\} finds the pure Nash equilibrium (D, C), which is a correlated equilibrium.

Correctness

If line L9 returns pp, then pp is a correlated equilibrium, because the LP of line L8 has exactly the incentive constraints, restricted to profiles in XX. The oracle is correct by the two lemmas above, whose proofs are short: for a stationary xix_i, the balance equations make ∑jxi(j)∑lyi(j,l) [v(j)−v(l)]=0\sum_j x_i(j) \sum_l y_i(j, l)\,[v(j) - v(l)] = 0 for any values vv, which gives the first lemma after averaging over s−is_{-i}, and the second is the method of conditional expectations. The method terminates because of Farkas' lemma: if the cuts collected in XX, together with y≥0y \ge 0, already form an infeasible system, then the LP of line L8 is feasible. Papadimitriou and Roughgarden, and in the exact form Jiang and Leyton-Brown, show with the volume argument of the ellipsoid method that this happens after a number of steps polynomial in dd and in the bit length of the constraints. The proof file proves the lemmas and the Farkas step; the step count is cited.

Proof: The separation oracle of ellipsoid against hope always finds a violated dual constraint, and the profiles it finds support a correlated equilibrium once their cuts are infeasiblefull

The game has players 1,…,n1, \ldots, n with finite strategy sets SiS_i and utilities uiu_i. The dual vector y≥0y \ge 0 has one entry yi(j,l)y_i(j, l) for each player ii and ordered pair j≠lj \ne l in SiS_i, and for a pure profile ss,

g(y,s)=∑i=1n∑l≠siyi(si,l) [ui(s)−ui(l,s−i)].g(y, s) = \sum_{i=1}^{n} \sum_{l \ne s_i} y_i(s_i, l)\,\big[u_i(s) - u_i(l, s_{-i})\big].

This is (U⊤y)s(U^\top y)_s, where UU is the matrix of the incentive constraints: a distribution pp on profiles is a correlated equilibrium exactly when (Up)(i,j,l)=∑s:si=jp(s) [ui(s)−ui(l,s−i)]≥0(Up)_{(i, j, l)} = \sum_{s : s_i = j} p(s)\,[u_i(s) - u_i(l, s_{-i})] \ge 0 for every row. This is the definition, so the LP of line L8, with these rows, ∑s∈Xp(s)=1\sum_{s \in X} p(s) = 1 and p≥0p \ge 0, has as its feasible set exactly the correlated equilibria supported on XX. In particular, an output of line L9 is a correlated equilibrium.

Claim 1 (stationary distributions exist). Let r(j,l)≥0r(j, l) \ge 0 for j≠lj \ne l in a finite set SS. There is a distribution xx on SS with x(j)∑l≠jr(j,l)=∑l≠jx(l) r(l,j)x(j) \sum_{l \ne j} r(j, l) = \sum_{l \ne j} x(l)\, r(l, j) for every jj.

Proof. Consider the directed graph on SS with an edge j→lj \to l when r(j,l)>0r(j, l) > 0. Its strongly connected components form an acyclic graph, which has a component CC with no edge leaving it. Let λ\lambda be larger than every total rate ∑lr(j,l)\sum_l r(j, l), and let P(j,l)=r(j,l)/λP(j, l) = r(j, l)/\lambda for j≠lj \ne l and P(j,j)=1−∑lr(j,l)/λP(j, j) = 1 - \sum_l r(j, l)/\lambda, for j,l∈Cj, l \in C. Because CC is closed, PP is a stochastic matrix, and it is irreducible because CC is strongly connected. So it has a stationary distribution π\pi with π=πP\pi = \pi P. Written out, π=πP\pi = \pi P is λ\lambda times the balance equations on CC. Put x=πx = \pi on CC and x=0x = 0 elsewhere. For j∈Cj \in C, the balance equation holds because no state outside CC has positive mass. For j∉Cj \notin C, both sides are 0: the left side because x(j)=0x(j) = 0, and the right side because a state ll with x(l)>0x(l) > 0 is in CC, and r(l,j)=0r(l, j) = 0 for l∈Cl \in C, j∉Cj \notin C, since no edge leaves CC. □\square

The code computes exactly this distribution: it finds a closed class by reachability and solves the balance equations on it.

Claim 2 (the product has zero expected dual value). For each player ii, let xix_i be a distribution given by Claim 1 for the rates r=yir = y_i, and let x=x1×⋯×xnx = x_1 \times \cdots \times x_n. Then Es∼x g(y,s)=0\mathbb{E}_{s \sim x}\, g(y, s) = 0.

Proof. Fix ii and write vi(a)=Es−i∼x−i ui(a,s−i)v_i(a) = \mathbb{E}_{s_{-i} \sim x_{-i}}\, u_i(a, s_{-i}). Because sis_i is independent of s−is_{-i} under xx, the term of player ii has expectation

∑jxi(j)∑l≠jyi(j,l) [vi(j)−vi(l)]=∑avi(a)[xi(a)∑l≠ayi(a,l)−∑j≠axi(j) yi(j,a)],\sum_{j} x_i(j) \sum_{l \ne j} y_i(j, l)\,[v_i(j) - v_i(l)] = \sum_{a} v_i(a) \Big[x_i(a) \sum_{l \ne a} y_i(a, l) - \sum_{j \ne a} x_i(j)\, y_i(j, a)\Big],

where the second form collects the coefficient of each vi(a)v_i(a). Every bracket is 0 by Claim 1. Sum over ii. □\square

Claim 3 (the oracle returns a violated constraint). For every y≥0y \ge 0, the oracle of line L6 returns a pure profile ss with g(y,s)≥0g(y, s) \ge 0.

Proof. For 0≤m≤n0 \le m \le n and strategies a1,…,ama_1, \ldots, a_m, let φm(a1,…,am)\varphi_m(a_1, \ldots, a_m) be the expectation of g(y,(a1,…,am,sm+1,…,sn))g(y, (a_1, \ldots, a_m, s_{m+1}, \ldots, s_n)) with sm+1,…,sns_{m+1}, \ldots, s_n drawn independently from xm+1,…,xnx_{m+1}, \ldots, x_n. Then φ0=0\varphi_0 = 0 by Claim 2, and φm−1(a1,…,am−1)=∑axm(a) φm(a1,…,am−1,a)\varphi_{m-1}(a_1, \ldots, a_{m-1}) = \sum_{a} x_m(a)\, \varphi_m(a_1, \ldots, a_{m-1}, a), an average. An average is at most the maximum, so the choice of the oracle, ama_m that maximizes φm(a1,…,am−1,a)\varphi_m(a_1, \ldots, a_{m-1}, a), gives φm(a1,…,am)≥φm−1(a1,…,am−1)\varphi_m(a_1, \ldots, a_m) \ge \varphi_{m-1}(a_1, \ldots, a_{m-1}). By induction g(y,(a1,…,an))=φn≥φ0=0g(y, (a_1, \ldots, a_n)) = \varphi_n \ge \varphi_0 = 0. □\square

Each φm\varphi_m is a sum, with coefficients from yy, of expectations of uiu_i under product distributions in which the first mm players (and possibly player ii) use point masses. So for a succinct game, the expected utility algorithm computes it.

Claim 4 (every cut keeps the dual feasible set). Let DD be the set of z≥0z \ge 0 with g(z,s)≤−1g(z, s) \le -1 for every profile ss. Line L4 and line L7 never cut off a point of DD.

Proof. Line L4 keeps the halfspace zr≥0z_r \ge 0, which contains DD. In line L7, every z∈Dz \in D has g(z,s)≤−1<0≤g(y,s)g(z, s) \le -1 < 0 \le g(y, s) by Claim 3, so zz is in the kept halfspace g(z,s)≤g(y,s)g(z, s) \le g(y, s); this uses that g(⋅,s)g(\cdot, s) is linear. □\square

Claim 5 (infeasible cuts give an equilibrium on XX). Let XX be a set of profiles. If no z≥0z \ge 0 satisfies g(z,s)≤−1g(z, s) \le -1 for every s∈Xs \in X, then a correlated equilibrium supported on XX exists, and the LP of line L8 is feasible.

Proof. The system is Az≤bA z \le b, z≥0z \ge 0, where AA has the rows (U⊤)s(U^\top)_s for s∈Xs \in X and bb has all entries −1-1. By Farkas' lemma, in the form for nonnegative variables, this system is infeasible exactly when some w≥0w \ge 0 (one entry per s∈Xs \in X) has w⊤A≥0w^\top A \ge 0 and w⊤b<0w^\top b < 0. The second condition says ∑sws>0\sum_s w_s > 0, and the first says Uw≥0U w \ge 0, with ww read as a vector on profiles that is 0 outside XX. Then p=w/∑swsp = w / \sum_s w_s is a distribution supported on XX with Up≥0Up \ge 0, a correlated equilibrium. □\square

Claim 6 (existence). Every finite game has a correlated equilibrium.

Proof. By Claim 3, for every y≥0y \ge 0 some profile ss has g(y,s)≥0>−1g(y, s) \ge 0 > -1, so the dual system over all profiles has no solution. Apply Claim 5 with XX the set of all profiles. □\square

This is the existence proof of Hart and Schmeidler (1989) in the constructive form that the algorithm uses; Claim 6 shows that the dual DD is empty, so the method runs "against hope".

Termination. Papadimitriou and Roughgarden (2008), and Jiang and Leyton-Brown (2015) for the oracle with pure profiles, show that with a radius RR and a number of steps NN that are polynomial in dd and in the bit length of the entries of UU, the cuts collected after NN steps form an infeasible system. In outline, the argument is the volume argument of the ellipsoid method: if the cuts of XX had a solution, then by the bounds on the bit lengths of the cut coefficients, the solutions of a slightly relaxed system would contain a ball, and every ellipsoid keeps this ball (as in Claim 4), but after NN steps the volume of the ellipsoid is smaller than the volume of the ball. This step count is cited and not proved here. Since each step adds at most one profile to XX, ∣X∣≤N|X| \le N, and by Claim 5 the LP of line L8 is then feasible.

Conclusion. The oracle always returns a profile whose dual constraint the center violates (Claims 1 to 3), so every cut is valid (Claim 4). Once the collected cuts are infeasible, which happens within a polynomial number of steps, the LP over the collected profiles has a solution (Claim 5), and every solution of that LP is a correlated equilibrium supported on XX. The code stops at the first XX for which the LP is feasible, and it returns only a solution of that exact LP, so every output is an exact correlated equilibrium. ■\blacksquare

Complexity

The ellipsoid method runs in dimension d≤nk2d \le n k^2. Each step costs one oracle call: nn stationary distributions of kk-state chains, in O(nk3)O(n k^3) time, and O(nk)O(n k) conditional expectations, each made of a polynomial number of calls to the expected utility algorithm. The number of steps is polynomial in dd and in the bit length of the payoffs, and so is ∣X∣|X|. The final LP has ∣X∣|X| variables and d+1d + 1 constraints. The total is polynomial in nn, kk and LL. The output has polynomial support: it is a distribution on at most ∣X∣|X| pure profiles.

The code on this page is for games in normal form, where the conditional expectations sum over all profiles; one oracle call then costs O(nk⋅kn)O(n k \cdot k^n). The ellipsoid steps use floating point, and the final LP is exact.

Properties

  • Polynomial for succinct games. For a game of polynomial type with a polynomial expected utility algorithm, the time is polynomial in the description, not in the number of profiles.
  • Exact. The pure-profile oracle of Jiang and Leyton-Brown keeps all numbers of polynomial bit length, and the returned distribution satisfies the incentive constraints exactly.
  • Small support. The equilibrium is supported on the polynomially many profiles in XX.
  • Not optimizing. It finds some correlated equilibrium. Maximizing welfare over the correlated equilibria is NP-hard for several succinct classes (Papadimitriou and Roughgarden, 2008), and those results also cover other linear objectives.

Variants and improvements

  • Mixtures of product distributions. The original version of Papadimitriou and Roughgarden used the product distributions xx themselves as cuts and returned a convex combination of them. Stein, Parrilo and Ozdaglar showed that this version can fail to give an exact equilibrium, because of the numerical precision of these cuts. The pure-profile oracle removes this problem.
  • Approximate equilibria by learning. If every player runs a no-swap-regret algorithm, the empirical distribution of play is an approximate correlated equilibrium after a number of rounds polynomial in nn, kk and 1/ε1/\varepsilon, using the same expected utility algorithm in each round.
  • Coarse correlated equilibria. The same scheme works with the smaller dual of the coarse constraints, which has one variable yi(l)y_i(l) per player and strategy. There, the product of the distributions xix_i proportional to yiy_i has expected dual value 0, and no Markov chain is necessary.
  • Two players or a table. When the normal form is given, the correlated equilibrium LP is simpler and can optimize.

When to use it

Use it when a game has many players but a short description with a fast expected utility algorithm, and an exact correlated equilibrium is needed. It is mainly of theoretical interest: the ellipsoid method is slow in practice, and for an approximate answer, no-regret learning is much simpler. For games given as a table, use the LP directly.

Pitfalls

  • Expecting an optimal equilibrium. Line L9 returns the first correlated equilibrium supported on XX, not one of maximum welfare. Adding an objective to line L8 only optimizes over the support XX.
  • A product distribution as the cut in line L7. Cutting with Exg(⋅,s)\mathbb{E}_x g(\cdot, s) for the product xx instead of a pure profile is the original version, which can fail to give an exact equilibrium because of numerical precision. Use a pure profile from the conditional expectations.
  • A wrong stationary distribution in line L6. If a chain is reducible, a solution of the linear balance equations can have negative entries. Restrict the computation to a closed class of the chain, where the stationary distribution is unique and positive.
  • Stopping too early. With a fixed small number of steps, the LP of line L8 can still be infeasible. The step bound must come from the bit lengths, or the LP must be checked as XX grows, as in the code.

Implementations

The Python code implements lines L1 to L9 for games in normal form: central-cut ellipsoid steps in floating point, the stationary distributions on a closed class by Gaussian elimination, the conditional expectations by summing over the remaining profiles, and the LP of line L8 with the shared exact simplex code. The tests check the balance equations of the stationary step, that the oracle profile always violates its dual constraint, the unique correlated equilibria of matching pennies, rock-paper-scissors and the prisoner's dilemma, that the output on 40 random games with 2 and 3 players is an exact correlated equilibrium supported on XX, and that restricted LPs can be infeasible.

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]
ellipsoid_against_hope.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ellipsoid-against-hope/. The authors are listed in prov/WQZKXN.jsonl.
"""Ellipsoid against hope: a correlated equilibrium from the ellipsoid method on an infeasible dual.

The game is a pair (sizes, pay) as in the shared helper agtgame; players maximize. The dual
variables are y_i(j, l) >= 0, one per player i and ordered pair j != l of its strategies. For a
pure profile s, let

    g(y, s) = sum_i sum_{l != s_i} y_i(s_i, l) (u_i(s) - u_i(l, s_-i)).

The dual system "y >= 0 and g(y, s) <= -1 for every profile s" is infeasible, because the game
has a correlated equilibrium. The ellipsoid method runs on it with a separation oracle in the
pure-profile form of Jiang and Leyton-Brown: for every y >= 0 it returns a profile s with
g(y, s) >= 0 (up to rounding), so the constraint of s is violated. The profiles found are
collected, and the LP restricted to them gives a correlated equilibrium supported on them.

The ellipsoid steps and the oracle use float; the final LP is exact (Fraction, by agtlp), so
the returned distribution is an exact correlated equilibrium. The oracle sums over profiles
directly, as for a game in normal form; for a succinct game this sum is the expected utility
oracle of the game.
"""

import math
from fractions import Fraction

from agtgame import profiles
from agtlp import lp_max


def _replace(s, i, a):
    return s[:i] + (a,) + s[i + 1:]


def dual_index(sizes):
    """Return the list of the dual coordinates (i, j, l), in a fixed order."""
    return [(i, j, l) for i, k in enumerate(sizes) for j in range(k) for l in range(k) if l != j]


def gain_column(game, s, index):
    """Return the coefficients of g(., s): for coordinate (i, j, l), u_i(s) - u_i(l, s_-i) if s_i = j, else 0."""
    _, pay = game
    return [pay[s][i] - pay[_replace(s, i, l)][i] if s[i] == j else Fraction(0) for (i, j, l) in index]


def stationary_of_rates(rates):
    """Return a distribution x on 0..k-1 with x(j) sum_l r(j, l) = sum_l x(l) r(l, j) for the
    nonnegative rates r (a k by k list, diagonal ignored). It lives on a closed class of the
    graph of positive rates, where it is unique."""
    k = len(rates)
    succ = [[l for l in range(k) if l != j and rates[j][l] > 0] for j in range(k)]

    def reach(j):
        seen, stack = {j}, [j]
        while stack:
            a = stack.pop()
            for b in succ[a]:
                if b not in seen:
                    seen.add(b)
                    stack.append(b)
        return seen

    reachable = [reach(j) for j in range(k)]
    root = next(j for j in range(k) if all(j in reachable[b] for b in reachable[j]))
    cls = sorted(reachable[root])
    m = len(cls)
    # Balance equations on the class, with the last one replaced by sum x = 1.
    M = []
    for a in cls[:-1]:
        row = [(-sum(rates[a][b] for b in cls if b != a) if c == a else rates[c][a]) for c in cls]
        M.append(row + [0.0])
    M.append([1.0] * m + [1.0])
    for col in range(m):
        piv = max(range(col, m), key=lambda r: abs(M[r][col]))
        M[col], M[piv] = M[piv], M[col]
        for r in range(m):
            if r != col and M[r][col] != 0.0:
                f = M[r][col] / M[col][col]
                M[r] = [p - f * q for p, q in zip(M[r], M[col])]
    x = [0.0] * k
    for t, a in enumerate(cls):
        x[a] = max(M[t][m] / M[t][t], 0.0)
    total = sum(x)
    return [v / total for v in x]


def separation_oracle(game, y, index):
    """For y >= 0, return a pure profile s with g(y, s) >= 0 (up to rounding).

    Each player's y_i defines a Markov chain; the product x of the stationary distributions has
    E_x g(y, s) = 0. The method of conditional expectations then fixes one player at a time,
    keeping the conditional expectation at least 0."""
    sizes, pay = game
    n = len(sizes)
    yv = {key: v for key, v in zip(index, y)}
    x = []
    for i, k in enumerate(sizes):
        rates = [[yv.get((i, j, l), 0.0) for l in range(k)] for j in range(k)]
        x.append(stationary_of_rates(rates))

    def g(s):
        return sum(yv[(i, s[i], l)] * float(pay[s][i] - pay[_replace(s, i, l)][i])
                   for i in range(n) for l in range(sizes[i]) if l != s[i])

    fixed = ()
    for i in range(n):
        rest = sizes[i + 1:]
        best, best_val = None, None
        for a in range(sizes[i]):
            val = 0.0
            for tail in profiles(rest):
                w = 1.0
                for t, b in enumerate(tail):
                    w *= x[i + 1 + t][b]
                if w:
                    val += w * g(fixed + (a,) + tail)
            if best_val is None or val > best_val:
                best, best_val = a, val
        fixed = fixed + (best,)
    return fixed


def restricted_lp(game, support):
    """Return a correlated equilibrium supported on the given profiles, or None if none exists."""
    sizes, pay = game
    S = sorted(support)
    rows = []
    for (i, j, l) in dual_index(sizes):
        rows.append([pay[_replace(s, i, l)][i] - pay[s][i] if s[i] == j else 0 for s in S])
    status, p, _, _ = lp_max([0] * len(S), rows, [0] * len(rows), [[1] * len(S)], [1])
    if status != "optimal":
        return None
    return {s: q for s, q in zip(S, p) if q != 0}


def ellipsoid_against_hope(game, radius=10.0, max_steps=20000):
    """Return (p, X, steps): a correlated equilibrium p (a dict from profiles to Fraction), the
    set X of profiles that the oracle produced, and the number of ellipsoid steps."""
    sizes, _ = game
    index = dual_index(sizes)
    d = len(index)
    if d == 0:  # every player has one strategy
        s = tuple(0 for _ in sizes)
        return {s: Fraction(1)}, {s}, 0
    c = [0.0] * d  # @line L1
    P = [[radius * radius if a == b else 0.0 for b in range(d)] for a in range(d)]
    X = set()
    p = None
    for step in range(1, max_steps + 1):  # @line L2
        y = c  # @line L3
        neg = next((r for r in range(d) if y[r] < 0), None)
        if neg is not None:  # @line L4
            a = [0.0] * d
            a[neg] = -1.0  # keep the half where y_r >= 0
        else:  # @line L5
            s = separation_oracle(game, y, index)  # @line L6
            if s not in X:
                X.add(s)  # @line L7
                p = restricted_lp(game, X)  # @line L8
                if p is not None:
                    return p, X, step  # @line L9
            a = [float(v) for v in gain_column(game, s, index)]  # keep the half where g(., s) <= g(y, s)
        # Central cut: the smallest ellipsoid that contains {z in E : a . z <= a . c}.
        Pa = [sum(P[r][t] * a[t] for t in range(d)) for r in range(d)]
        aPa = sum(a[r] * Pa[r] for r in range(d))
        if aPa <= 0:
            continue  # a = 0: the profile gives no information; another center will differ
        root = math.sqrt(aPa)
        c = [c[r] - Pa[r] / ((d + 1) * root) for r in range(d)]
        f = d * d / (d * d - 1.0)
        P = [[f * (P[r][t] - 2.0 / (d + 1) * Pa[r] * Pa[t] / aPa) for t in range(d)] for r in range(d)]
    raise RuntimeError("no correlated equilibrium found within max_steps ellipsoid steps")
test_ellipsoid_against_hope.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ellipsoid-against-hope/. The authors are listed in prov/WQZKXN.jsonl.
"""Tests of ellipsoid against hope: the stationary step, the separation oracle, and exact
correlated equilibria on games with known and unknown equilibria."""

import random
from fractions import Fraction

from agtgame import from_bimatrix, is_correlated, profiles, random_game
from ellipsoid_against_hope import (dual_index, ellipsoid_against_hope, gain_column, restricted_lp,
                                    separation_oracle, stationary_of_rates)

F = Fraction
CHICKEN = from_bimatrix([[0, 7], [2, 6]], [[0, 2], [7, 6]])
PENNIES = from_bimatrix([[1, -1], [-1, 1]], [[-1, 1], [1, -1]])
RPS = from_bimatrix([[0, -1, 1], [1, 0, -1], [-1, 1, 0]], [[0, 1, -1], [-1, 0, 1], [1, -1, 0]])
PD = from_bimatrix([[3, 0], [5, 1]], [[3, 5], [0, 1]])


def g_value(game, y, s, index):
    return sum(float(c) * v for c, v in zip(gain_column(game, s, index), y))


def test_stationary_of_rates_balances_the_flows():
    rng = random.Random(5)
    for _ in range(300):
        k = rng.randint(1, 5)
        rates = [[rng.choice([0.0, 0.0, rng.random() * 3]) if j != l else 0.0 for l in range(k)] for j in range(k)]
        x = stationary_of_rates(rates)
        assert all(v >= 0 for v in x) and abs(sum(x) - 1) < 1e-12
        for j in range(k):
            out_flow = x[j] * sum(rates[j][l] for l in range(k) if l != j)
            in_flow = sum(x[l] * rates[l][j] for l in range(k) if l != j)
            assert abs(out_flow - in_flow) < 1e-9


def test_oracle_returns_a_violated_constraint():
    rng = random.Random(8)
    for _ in range(60):
        sizes = tuple(rng.randint(2, 3) for _ in range(rng.choice([2, 3])))
        game = random_game(rng, sizes, -4, 4)
        index = dual_index(sizes)
        y = [rng.choice([0.0, rng.random() * 5]) for _ in index]
        s = separation_oracle(game, y, index)
        assert s in set(profiles(sizes))
        assert g_value(game, y, s, index) >= -1e-9  # so g(y, s) <= -1 fails


def test_known_equilibria():
    for game in (PENNIES, RPS):
        p, X, _ = ellipsoid_against_hope(game)
        k = game[0][0]
        assert p == {s: F(1, k * k) for s in profiles(game[0])}  # the unique correlated equilibrium
    p, _, _ = ellipsoid_against_hope(PD)
    assert p == {(1, 1): F(1)}
    p, X, steps = ellipsoid_against_hope(CHICKEN)
    assert is_correlated(CHICKEN, p) and set(p) <= X and len(X) <= steps


def test_random_games_give_exact_correlated_equilibria():
    rng = random.Random(2008)
    for _ in range(40):
        sizes = tuple(rng.randint(2, 3) for _ in range(rng.choice([2, 2, 3])))
        game = random_game(rng, sizes, -3, 3)
        p, X, steps = ellipsoid_against_hope(game)
        assert is_correlated(game, p)
        assert set(p) <= X and len(X) <= steps
        # The returned distribution is one that the restricted LP accepts.
        assert restricted_lp(game, X) is not None


def test_restricted_lp_can_be_infeasible():
    # In matching pennies no correlated equilibrium has support smaller than all four profiles.
    assert restricted_lp(PENNIES, {(0, 0), (0, 1), (1, 0)}) is None
    assert restricted_lp(PD, {(0, 0)}) is None
    assert restricted_lp(PD, {(1, 1)}) == {(1, 1): F(1)}


def test_trivial_games():
    solo = ((1, 1), {(0, 0): (F(2), F(3))})
    p, X, steps = ellipsoid_against_hope(solo)
    assert p == {(0, 0): F(1)} and steps == 0
    one = ((3,), {(0,): (F(1),), (1,): (F(4),), (2,): (F(4),)})
    p, _, _ = ellipsoid_against_hope(one)
    assert is_correlated(one, p) and set(p) <= {(1,), (2,)}

History

Hart and Schmeidler (1989) proved the existence of correlated equilibria with LP duality. Papadimitriou (2005) turned this proof into a polynomial-time algorithm for succinct games, and the journal version with Roughgarden (2008) gave the full analysis and hardness results for optimal correlated equilibria. Stein, Parrilo and Ozdaglar noticed a gap in the precision of the original method, and Jiang and Leyton-Brown (2015) closed it with the pure-profile oracle.

References

  1. Christos H. Papadimitriou and Tim Roughgarden, Computing correlated equilibria in multi-player games, Journal of the ACM 55(3) (2008), article 14, the main theorem (a correlated equilibrium in polynomial time for succinct games of polynomial type with a polynomial expected utility algorithm), the lemma that every dual point has a product distribution with zero expected dual value, and the hardness of optimal correlated equilibria
  2. Albert Xin Jiang and Kevin Leyton-Brown, Polynomial-time computation of exact correlated equilibrium in compact games, Games and Economic Behavior 91 (2015), 347-359, the purified separation oracle (a pure profile found by the method of conditional probabilities) and the exact equilibrium with polynomial support
  3. Existence of correlated equilibria, the existence proof by LP duality that the algorithm makes constructive

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