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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 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 , strategy sets with , and utilities (maximized), given in a succinct form of bit length . The game must be of polynomial type ( and are polynomial in ) and have a polynomial expected utility algorithm: given a product distribution , it computes in time polynomial in . 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 for the matrix of the incentive constraints. It has a row for each player and ordered pair in , a column for each profile , and the entry if and 0 otherwise. A distribution on profiles is a correlated equilibrium exactly when . For a dual vector with one entry per row, the value of column is
The primal LP "maximize subject to , " is unbounded, because a correlated equilibrium exists and can be scaled. So by LP duality, its dual system
is infeasible. It has variables and one constraint per profile.
The algorithm
ELLIPSOID-AGAINST-HOPE(G)- 1
E ← a ball of radius R around 0 in the space of the dual vectors y; X ← the empty set - 2
repeat - 3
y ← the center of E - 4
if y_r < 0 for some coordinate r, then cut E by the halfspace y_r ≥ 0 - 5
else - 6
s ← ORACLE(y) ▷ a pure profile with g(y, s) ≥ 0 - 7
add s to X, and cut E by the halfspace g(·, s) ≤ g(y, s) - 8
p ← a correlated equilibrium with support in X, from an LP, if one exists - 9
if p exists, return p
A cut replaces by the smallest ellipsoid that contains the half of on the given side of a hyperplane through its center. The oracle of line L6 works in two steps.
- For each player , the weights define a continuous-time Markov chain on with rate from to . Let be a stationary distribution of this chain, so that for every . Then for the product , the expected value is exactly 0. This is the key lemma of Papadimitriou and Roughgarden.
- Fix the players one at a time. For player , choose the strategy that maximizes the conditional expectation of , given the strategies already fixed and drawn from . The maximum is at least the average, so the conditional expectation never drops below 0, and the final pure profile has . 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 , the profile 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 , 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 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 , so . Start with the ball of radius .
| step | center | stationary , | oracle profile | column of in | LP on | |
|---|---|---|---|---|---|---|
| 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 |
In step 1 the oracle returns (D, D), and the cut keeps the half where . For a ball, the new center moves a distance away from the cut hyperplane, along the unit vector , so it is . 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 at (D, C), which is , with at (C, C), which is 0, and picks D; player 2 then picks C. The LP on finds the pure Nash equilibrium (D, C), which is a correlated equilibrium.
Correctness
If line L9 returns , then is a correlated equilibrium, because the LP of line L8 has exactly the incentive constraints, restricted to profiles in . The oracle is correct by the two lemmas above, whose proofs are short: for a stationary , the balance equations make for any values , which gives the first lemma after averaging over , and the second is the method of conditional expectations. The method terminates because of Farkas' lemma: if the cuts collected in , together with , 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 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 with finite strategy sets and utilities . The dual vector has one entry for each player and ordered pair in , and for a pure profile ,
This is , where is the matrix of the incentive constraints: a distribution on profiles is a correlated equilibrium exactly when for every row. This is the definition, so the LP of line L8, with these rows, and , has as its feasible set exactly the correlated equilibria supported on . In particular, an output of line L9 is a correlated equilibrium.
Claim 1 (stationary distributions exist). Let for in a finite set . There is a distribution on with for every .
Proof. Consider the directed graph on with an edge when . Its strongly connected components form an acyclic graph, which has a component with no edge leaving it. Let be larger than every total rate , and let for and , for . Because is closed, is a stochastic matrix, and it is irreducible because is strongly connected. So it has a stationary distribution with . Written out, is times the balance equations on . Put on and elsewhere. For , the balance equation holds because no state outside has positive mass. For , both sides are 0: the left side because , and the right side because a state with is in , and for , , since no edge leaves .
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 , let be a distribution given by Claim 1 for the rates , and let . Then .
Proof. Fix and write . Because is independent of under , the term of player has expectation
where the second form collects the coefficient of each . Every bracket is 0 by Claim 1. Sum over .
Claim 3 (the oracle returns a violated constraint). For every , the oracle of line L6 returns a pure profile with .
Proof. For and strategies , let be the expectation of with drawn independently from . Then by Claim 2, and , an average. An average is at most the maximum, so the choice of the oracle, that maximizes , gives . By induction .
Each is a sum, with coefficients from , of expectations of under product distributions in which the first players (and possibly player ) use point masses. So for a succinct game, the expected utility algorithm computes it.
Claim 4 (every cut keeps the dual feasible set). Let be the set of with for every profile . Line L4 and line L7 never cut off a point of .
Proof. Line L4 keeps the halfspace , which contains . In line L7, every has by Claim 3, so is in the kept halfspace ; this uses that is linear.
Claim 5 (infeasible cuts give an equilibrium on ). Let be a set of profiles. If no satisfies for every , then a correlated equilibrium supported on exists, and the LP of line L8 is feasible.
Proof. The system is , , where has the rows for and has all entries . By Farkas' lemma, in the form for nonnegative variables, this system is infeasible exactly when some (one entry per ) has and . The second condition says , and the first says , with read as a vector on profiles that is 0 outside . Then is a distribution supported on with , a correlated equilibrium.
Claim 6 (existence). Every finite game has a correlated equilibrium.
Proof. By Claim 3, for every some profile has , so the dual system over all profiles has no solution. Apply Claim 5 with the set of all profiles.
This is the existence proof of Hart and Schmeidler (1989) in the constructive form that the algorithm uses; Claim 6 shows that the dual 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 and a number of steps that are polynomial in and in the bit length of the entries of , the cuts collected after steps form an infeasible system. In outline, the argument is the volume argument of the ellipsoid method: if the cuts of 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 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 , , 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 . The code stops at the first for which the LP is feasible, and it returns only a solution of that exact LP, so every output is an exact correlated equilibrium.
Complexity
The ellipsoid method runs in dimension . Each step costs one oracle call: stationary distributions of -state chains, in time, and conditional expectations, each made of a polynomial number of calls to the expected utility algorithm. The number of steps is polynomial in and in the bit length of the payoffs, and so is . The final LP has variables and constraints. The total is polynomial in , and . The output has polynomial support: it is a distribution on at most 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 . 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 .
- 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 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 , and , 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 per player and strategy. There, the product of the distributions proportional to 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 , not one of maximum welfare. Adding an objective to line L8 only optimizes over the support .
- A product distribution as the cut in line L7. Cutting with for the product 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 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 , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag WQZKXN Edit this page History Report an error Markdown