Algorithm Search⌘K

Algorithmcore

Correlated equilibrium by linear programming

Also called correlated equilibrium LP.

Computes a correlated equilibrium, or one of maximum welfare, of a normal-form game with a linear program over distributions on profiles.

Time
poly(n, k^n, L) worst
Space
O(n k^(n+2)) extra
Where
L = the bit length of the payoffs; k = the largest number of pure strategies of a player; n = the number of players
Properties
deterministicexactofflineiterative
Origin
Robert J. Aumann, Sergiu Hart, David Schmeidler, Itzhak Gilboa, Eitan Zemel, 1974

This algorithm computes a correlated equilibrium of a finite game given in normal form. The incentive constraints of a correlated equilibrium are linear in the probabilities p(s)p(s) of the profiles, so the set of correlated equilibria is a polytope, and one linear program finds a point of it that maximizes any linear objective, such as the total welfare. The LP has one variable per profile, so its size is polynomial in the size of the normal form, and the method runs in polynomial time. This is the main computational difference from Nash equilibria, which are PPAD-complete to find even for two players (Nash equilibrium computation). The LP needs the whole normal form; for succinct games with many players, where the normal form is exponentially large, the ellipsoid against hope works with the dual instead. In two-player zero-sum games the LP of zero-sum games is the smaller tool.

In plain words

A trusted mediator draws a combination of actions at random from a list of chances, and tells each player only its own part. The list is fair if no player, told its part, gains on average by doing something else. For each player, each action it could be told and each other action it could switch to, the fairness test is a sum of chances times gains, and it must not be positive. All these tests are straight-line conditions on the chances. So are the conditions that the chances are not negative and add up to one. Finding chances that pass all tests, and that give the largest total reward, is a linear program, and there are standard methods that solve it fast.

The problem

The input is a finite game with players N={1,…,n}N = \{1, \ldots, n\}, pure strategy sets SiS_i with ki=∣Si∣≤kk_i = |S_i| \le k, and rational utilities ui:S→Qu_i : S \to \mathbb{Q} on S=S1×⋯×SnS = S_1 \times \cdots \times S_n, maximized, given as the full table of n∣S∣n |S| numbers. An objective w:S→Qw : S \to \mathbb{Q} is also given; the default is the welfare w(s)=∑iui(s)w(s) = \sum_i u_i(s), and w=0w = 0 asks for any correlated equilibrium.

A distribution pp on SS is a correlated equilibrium if for every player ii and every pair j≠lj \ne l of strategies of ii,

∑s∈S:si=jp(s) [ui(l,s−i)−ui(s)]≤0.\sum_{s \in S : s_i = j} p(s)\,\big[u_i(l, s_{-i}) - u_i(s)\big] \le 0 .

This says that a player told to play jj does not gain, on average over the profiles that the mediator may have drawn, by playing ll instead. The output is a correlated equilibrium pp that maximizes ∑sw(s)p(s)\sum_s w(s) p(s). Every mixed Nash equilibrium, viewed as a product distribution, is a correlated equilibrium; for a product distribution the constraints are the Nash conditions, which hold exactly when every strategy in the support of σi\sigma_i is a pure best response. So the set is not empty.

The algorithm

  1. CE-LP(G, w) ▷ w(s) is the objective weight of profile s
  2. 1create a variable p(s) ≥ 0 for each profile s in S
  3. 2for each player i and each pair j ≠ l in S_i
  4. 3add the constraint Σ_{s : s_i = j} p(s) (u_i(l, s_-i) - u_i(s)) ≤ 0
  5. 4add the constraint Σ_s p(s) = 1
  6. 5maximize Σ_s w(s) p(s) subject to these constraints
  7. 6return p

Lines L1 to L4 build the LP. It has ∣S∣|S| variables, ∑iki(ki−1)≤nk2\sum_i k_i(k_i - 1) \le n k^2 inequalities of line L3 and one equation. The row of line L3 for (i,j,l)(i, j, l) has a nonzero entry only for the profiles with si=js_i = j, so the constraint matrix is sparse: each column, for a profile ss, has at most ∑i(ki−1)\sum_i (k_i - 1) nonzero entries in the incentive rows. Line L5 can use the simplex method, the ellipsoid method or an interior point method. The feasible set is bounded, because it lies in the simplex of distributions on SS, and it is not empty, so the LP has an optimal solution, at a vertex of the polytope.

Example

Take chicken with strategies D (dare) and C (chicken) and payoffs (D, D) = (0, 0), (D, C) = (7, 2), (C, D) = (2, 7) and (C, C) = (6, 6). Write a,b,c,da, b, c, d for p(D,D)p(\text{D}, \text{D}), p(D,C)p(\text{D}, \text{C}), p(C,D)p(\text{C}, \text{D}) and p(C,C)p(\text{C}, \text{C}). Line L3 gives four constraints, and the welfare is 9b+9c+12d9b + 9c + 12d.

constraint of line L3 inequality at the max-welfare optimum
row player, told D, plays C 2a−b≤02a - b \le 0 −1/4-1/4, slack
row player, told C, plays D −2c+d≤0-2c + d \le 0 00, tight
column player, told D, plays C 2a−c≤02a - c \le 0 −1/4-1/4, slack
column player, told C, plays D −2b+d≤0-2b + d \le 0 00, tight

The optimum is a=0a = 0, b=c=1/4b = c = 1/4, d=1/2d = 1/2, with welfare 21/221/2, so each player gets 21/421/4. Compare the other equilibria of the same game: the pure Nash equilibria (D, C) and (C, D) give welfare 9; the mixed Nash equilibrium, which plays C with probability 2/32/3 and gives the product a=1/9a = 1/9, b=c=2/9b = c = 2/9, d=4/9d = 4/9, gives 14/314/3 each; the uniform distribution on (D, C), (C, D) and (C, C) gives 5 each. With w=−∑iuiw = -\sum_i u_i the same LP finds the worst correlated equilibrium, a=1/5a = 1/5, b=c=2/5b = c = 2/5, d=0d = 0, with welfare 36/536/5, which is below every Nash equilibrium.

Correctness

The constraints of lines L1 and L4 say that pp is a probability distribution on SS, and the constraints of line L3 are exactly the incentive constraints, one for each player and each ordered pair of strategies. So the feasible set of the LP is exactly the set of correlated equilibria. It is not empty, because a mixed Nash equilibrium exists and is a correlated equilibrium (Hart and Schmeidler give a proof that uses only LP duality), and it is bounded. So line L5 returns a correlated equilibrium of maximum objective value, and the simplex method with Bland's rule finds it in a finite number of pivots. The full proof is in the proof file.

Proof: The feasible set of the correlated equilibrium LP is the set of correlated equilibria, it is a nonempty polytope, and the LP returns an optimal correlated equilibriumfull

Let GG be a finite game with players 1,…,n1, \ldots, n, pure strategy sets SiS_i, profiles S=S1×⋯×SnS = S_1 \times \cdots \times S_n and utilities uiu_i (maximized). Let w:S→Qw : S \to \mathbb{Q} be the objective. Let PP be the feasible set of the LP built in lines L1 to L4: the vectors p∈RSp \in \mathbb{R}^S with p(s)≥0p(s) \ge 0 for all ss, ∑sp(s)=1\sum_s p(s) = 1, and, for every player ii and every ordered pair j≠lj \ne l in SiS_i,

gi(j,l;p)=∑s∈S:si=jp(s) [ui(l,s−i)−ui(s)]≤0.g_i(j, l; p) = \sum_{s \in S : s_i = j} p(s)\,\big[u_i(l, s_{-i}) - u_i(s)\big] \le 0 .

Claim 1 (the feasible set). PP is exactly the set of correlated equilibria of GG.

Proof. A distribution pp on SS is a correlated equilibrium if, for every player ii and every map δ:Si→Si\delta : S_i \to S_i, ∑sp(s) [ui(δ(si),s−i)−ui(s)]≤0\sum_s p(s)\,[u_i(\delta(s_i), s_{-i}) - u_i(s)] \le 0. Group the sum by the value j=sij = s_i: it equals ∑j∈Sigi(j,δ(j);p)\sum_{j \in S_i} g_i(j, \delta(j); p), where gi(j,j;p)=0g_i(j, j; p) = 0. If p∈Pp \in P, every term is at most 0, so pp is a correlated equilibrium. Conversely, if pp is a correlated equilibrium, fix ii and j≠lj \ne l and take δ(j)=l\delta(j) = l and δ(m)=m\delta(m) = m for m≠jm \ne j; then the sum is gi(j,l;p)g_i(j, l; p), so gi(j,l;p)≤0g_i(j, l; p) \le 0. Lines L1 and L4 say that pp is a distribution, and line L3 adds exactly the constraints gi(j,l;p)≤0g_i(j, l; p) \le 0, one for each ii (line L2) and each ordered pair. □\square

Claim 2 (nonempty). PP is not empty.

Proof. By Nash's theorem, GG has a mixed Nash equilibrium σ\sigma. Let p(s)=∏mσm(sm)p(s) = \prod_m \sigma_m(s_m). Then pp is a distribution, and

gi(j,l;p)=σi(j) [ui(l,σ−i)−ui(j,σ−i)].g_i(j, l; p) = \sigma_i(j)\,\big[u_i(l, \sigma_{-i}) - u_i(j, \sigma_{-i})\big].

If σi(j)=0\sigma_i(j) = 0 this is 0. If σi(j)>0\sigma_i(j) > 0, then jj is in the support of σi\sigma_i, so jj is a pure best response to σ−i\sigma_{-i} (a mixed strategy is a best response exactly when its support consists of pure best responses), and the bracket is at most 0. So p∈Pp \in P. Hart and Schmeidler (1989) give a second proof that uses only linear programming duality and no fixed point theorem. □\square

Claim 3 (the LP has an optimum). PP is a bounded polyhedron, so the LP of line L5 has an optimal solution, and the optimum is attained at a vertex of PP.

Proof. PP is the intersection of finitely many closed half spaces and one hyperplane, so it is a polyhedron. It lies in the simplex {p≥0,∑sp(s)=1}\{p \ge 0, \sum_s p(s) = 1\}, so 0≤p(s)≤10 \le p(s) \le 1 for all ss, and PP is bounded. A bounded nonempty polyhedron is a polytope, the convex hull of its finitely many vertices, and a linear function on it attains its maximum, at a vertex. □\square

Claim 4 (the method returns it). The two-phase simplex method with Bland's rule, run on the LP of lines L1 to L5, stops after finitely many pivots and returns a vertex p∗p^* of PP with ∑sw(s)p∗(s)=max⁡p∈P∑sw(s)p(s)\sum_s w(s) p^*(s) = \max_{p \in P} \sum_s w(s) p(s).

Proof. With Bland's rule, the simplex method does not cycle, so each phase stops after finitely many pivots. Phase 1 maximizes minus the sum of the artificial variables; by Claim 2 the original constraints are feasible, so the phase ends with value 0 and a basic feasible solution of the original LP. Phase 2 cannot report that the LP is unbounded, because by Claim 3 the objective is bounded on PP. So it stops with all reduced costs at most 0, which is the optimality condition, and the basic solution is a vertex of PP. In exact rational arithmetic, as in the code, no rounding error enters. □\square

Conclusion. By Claims 1 and 4, line L6 returns a correlated equilibrium of GG that maximizes ∑sw(s)p(s)\sum_s w(s) p(s) over all correlated equilibria. With w=0w = 0 it returns some correlated equilibrium. ■\blacksquare

Complexity

The LP has ∣S∣≤kn|S| \le k^n variables and at most nk2+1n k^2 + 1 constraints, and its coefficients are differences of payoffs, so its bit length is polynomial in nn, knk^n and LL. The ellipsoid method or an interior point method solves it in time polynomial in these numbers, so a correlated equilibrium of maximum welfare is found in time polynomial in the size of the normal form, which is nknn k^n numbers. The solution is a vertex, a rational vector with a polynomial number of digits. The dense constraint matrix takes O(nk2⋅kn)O(n k^2 \cdot k^n) space, or O(nk⋅kn)O(n k \cdot k^n) as a sparse matrix.

With the simplex method, the number of pivots can be exponential in the worst case, but it is small in practice. The code on this page uses exact rational arithmetic with Bland's rule.

The input size hides the catch: for nn players with 2 strategies each, the LP has 2n2^n variables. For games with a short description, such as graphical games or congestion games, this is exponential in the input, and the ellipsoid against hope is needed.

Properties

  • Exact and optimizing. Any linear objective can be optimized over the set, not only found in it; for Nash equilibria the analogous welfare question is NP-hard (Gilboa and Zemel, 1989).
  • A convex set. The correlated equilibria form a convex polytope, and so do the coarse correlated equilibria. Mixed Nash equilibria form a finite union of polytopes in two-player games and are not convex in general.
  • Vertices. The simplex method returns a vertex. A vertex has at most nk2+1n k^2 + 1 nonzero probabilities, the number of constraints, which is small compared with ∣S∣|S|.
  • Better than Nash. The optimal welfare is at least that of every Nash equilibrium, and can be strictly larger, as in chicken.

Variants and improvements

  • Coarse correlated equilibria. Replace line L3 by one constraint per player ii and strategy ll: ∑sp(s)[ui(l,s−i)−ui(s)]≤0\sum_s p(s)[u_i(l, s_{-i}) - u_i(s)] \le 0. This gives the larger set of coarse correlated equilibria, with ∑iki\sum_i k_i constraints.
  • Approximate equilibria. Replace 0 by ε\varepsilon on the right of line L3 for correlated ε\varepsilon-equilibria.
  • Succinct games. The dual LP has one variable per incentive constraint and one constraint per profile. The ellipsoid against hope runs the ellipsoid method on the dual and returns a mixture of polynomially many product distributions, in time polynomial in the description of games with a polynomial-time expected utility oracle.
  • Learning instead of solving. Regret matching and the Blum-Mansour reduction give approximate correlated equilibria by repeated play, with no LP and no knowledge of other players' payoffs, at a cost of O(1/ε2)O(1/\varepsilon^2) rounds or more.
  • Extensive-form games. Correlation in game trees leads to the extensive-form correlated equilibrium, whose LP is not the normal-form one; the normal form of a tree is exponentially large.

When to use it

Use it for a game given as a table, when the table fits in memory and an exact answer or an optimum over the correlated equilibria is needed. For two-player zero-sum games, the zero-sum LP is smaller and gives the same answer (every correlated equilibrium there pays the value). For many players with a succinct description, use the ellipsoid against hope. For a quick approximate answer in a large table, use no-swap-regret learning.

Pitfalls

  • Swapped sign in line L3. Writing ui(s)−ui(l,s−i)≤0u_i(s) - u_i(l, s_{-i}) \le 0 gives the correlated equilibria of the game with negated payoffs, in which no recommendation is better than a switch. The LP is still feasible, so the error is silent. The gain from deviating, ui(l,s−i)−ui(s)u_i(l, s_{-i}) - u_i(s), must be at most 0.
  • Summing over all profiles in line L3. The sum runs only over the profiles with si=js_i = j. Summing over all profiles gives the coarse constraint for ll, and the result is only a coarse correlated equilibrium.
  • Unordered pairs in line L2. Line L2 needs every ordered pair j≠lj \ne l. A loop over j<lj < l only checks the players who are told the smaller strategy, and the result can fail for a player told ll.
  • Floating-point solvers. A floating-point LP solver returns a point that may violate line L3 by rounding. Check the result with exact arithmetic, or accept a correlated ε\varepsilon-equilibrium.
  • Large games. With many players, line L1 creates knk^n variables. Use a succinct method instead.

Implementations

The Python code builds the LP of lines L1 to L4 with exact rational coefficients and solves it with the shared exact simplex code (two phases, Bland's rule). The tests check the chicken values above, the unique correlated equilibria of matching pennies, rock-paper-scissors (the uniform product, for random objectives) and the prisoner's dilemma, every incentive inequality of each output exactly, and the optimal value against an independent enumeration of all vertices of the polytope on random 2 by 2, 2 by 3 and 3 by 2 games, and against every pure Nash equilibrium on random games with up to 3 players.

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]
correlated_equilibrium_linear_program.py 64 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/correlated-equilibrium-linear-program/. The authors are listed in prov/V535CJ.jsonl.
"""A correlated equilibrium of a finite game in normal form, by one linear program.

The game is a pair (sizes, pay) as in the shared helper agtgame; players maximize. The LP
has one variable p(s) >= 0 per pure profile s, one inequality per player i and ordered pair
j != l of its strategies, and the equation sum_s p(s) = 1. Its feasible set is exactly the
set of correlated equilibria. The LP is solved exactly, in Fraction, by the shared helper
agtlp.
"""

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 ce_constraints(game):
    """Return (S, rows, labels): the profiles in a fixed order, and one row per incentive
    constraint, as a list of coefficients over S, with the label (i, j, l) of the row.

    The row (i, j, l) reads sum_{s: s_i = j} p(s) (u_i(l, s_-i) - u_i(s)) <= 0.
    """
    sizes, pay = game
    S = profiles(sizes)
    rows, labels = [], []
    for i, k in enumerate(sizes):  # @line L2
        for j in range(k):
            for l in range(k):
                if l == j:
                    continue
                row = [pay[_replace(s, i, l)][i] - pay[s][i] if s[i] == j else Fraction(0) for s in S]  # @line L3
                rows.append(row)
                labels.append((i, j, l))
    return S, rows, labels


def correlated_equilibrium_lp(game, weight=None):
    """Return (p, value): a correlated equilibrium p (a dict from profiles to Fraction, with
    the profiles of probability 0 left out) that maximizes sum_s weight(s) p(s), and that
    maximum.

    weight is a function from profiles to numbers; the default is the social welfare
    sum_i u_i(s). Pass weight=lambda s: 0 for any correlated equilibrium.

    Precondition: a finite game with at least one strategy per player. Cost: one LP with
    |S| variables and sum_i k_i (k_i - 1) + 1 constraints; the exact simplex method used
    here takes an exponential number of pivots in the worst case.
    """
    sizes, pay = game
    if weight is None:
        weight = lambda s: sum(pay[s], Fraction(0))
    S, rows, _ = ce_constraints(game)  # @line L1
    A_eq = [[1] * len(S)]  # @line L4
    c = [Fraction(weight(s)) for s in S]
    status, x, value, _ = lp_max(c, rows, [0] * len(rows), A_eq, [1])  # @line L5
    if status != "optimal":
        raise AssertionError("the CE polytope is nonempty and bounded")
    p = {s: q for s, q in zip(S, x) if q != 0}  # @line L6
    return p, value
test_correlated_equilibrium_linear_program.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/correlated-equilibrium-linear-program/. The authors are listed in prov/V535CJ.jsonl.
"""Tests of the correlated equilibrium LP against check values and vertex enumeration."""

import random
from fractions import Fraction
from itertools import combinations

from agtgame import from_bimatrix, is_coarse_correlated, is_correlated, profiles, pure_nash_brute, random_game
from correlated_equilibrium_linear_program import ce_constraints, correlated_equilibrium_lp

F = Fraction
CHICKEN = from_bimatrix([[0, 7], [2, 6]], [[0, 2], [7, 6]])  # strategy 0 is D, 1 is C


def welfare(game, p):
    return sum((q * sum(game[1][s], F(0)) for s, q in p.items()), F(0))


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


def best_vertex(game, weight):
    """Maximize sum_s weight(s) p(s) over the CE polytope by enumerating all its vertices."""
    S, rows, _ = ce_constraints(game)
    N = len(S)
    ineq = rows + [[F(-1) if a == b else F(0) for a in range(N)] for b in range(N)]
    best = None
    for tight in combinations(range(len(ineq)), N - 1):
        z = solve_unique([[F(1)] * N] + [ineq[t] for t in tight], [F(1)] + [F(0)] * (N - 1))
        if z is None or any(sum((a * v for a, v in zip(row, z)), F(0)) > 0 for row in ineq):
            continue
        val = sum((F(weight(s)) * v for s, v in zip(S, z)), F(0))
        best = val if best is None or val > best else best
    return best


def test_chicken_check_values():
    p, value = correlated_equilibrium_lp(CHICKEN)
    assert p == {(0, 1): F(1, 4), (1, 0): F(1, 4), (1, 1): F(1, 2)}
    assert value == F(21, 2)
    assert all(sum(q * CHICKEN[1][s][i] for s, q in p.items()) == F(21, 4) for i in range(2))
    assert is_correlated(CHICKEN, p)
    third = {(0, 1): F(1, 3), (1, 0): F(1, 3), (1, 1): F(1, 3)}
    assert is_correlated(CHICKEN, third) and welfare(CHICKEN, third) == 10
    mixed = {(a, b): F([1, 2][a], 3) * F([1, 2][b], 3) for a in range(2) for b in range(2)}
    assert is_correlated(CHICKEN, mixed) and welfare(CHICKEN, mixed) == F(28, 3)
    low, low_value = correlated_equilibrium_lp(CHICKEN, weight=lambda s: -sum(CHICKEN[1][s]))
    assert is_correlated(CHICKEN, low) and low_value == best_vertex(CHICKEN, lambda s: -sum(CHICKEN[1][s]))
    assert welfare(CHICKEN, low) == -low_value == F(36, 5)
    assert low == {(0, 0): F(1, 5), (0, 1): F(2, 5), (1, 0): F(2, 5)}


def test_unique_correlated_equilibria():
    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]])
    rng = random.Random(5)
    for _ in range(5):
        w = {s: rng.randint(-5, 5) for s in profiles((3, 3))}
        p, _ = correlated_equilibrium_lp(rps, weight=lambda s: w[s])
        assert p == {s: F(1, 9) for s in profiles((3, 3))}
        p, _ = correlated_equilibrium_lp(pennies, weight=lambda s: w[s] if s in w else 0)
        assert p == {s: F(1, 4) for s in profiles((2, 2))}
    assert correlated_equilibrium_lp(pd)[0] == {(1, 1): F(1)}


def test_feasibility_mode_and_one_player():
    p, value = correlated_equilibrium_lp(CHICKEN, weight=lambda s: 0)
    assert value == 0 and is_correlated(CHICKEN, p)
    solo = ((3,), {(0,): (F(2),), (1,): (F(5),), (2,): (F(5),)})
    p, value = correlated_equilibrium_lp(solo)
    assert value == 5 and is_correlated(solo, p) and set(p) <= {(1,), (2,)}


def test_constraint_count_and_meaning():
    game = random_game(random.Random(3), (2, 3, 2), -3, 3)
    S, rows, labels = ce_constraints(game)
    assert len(S) == 12 and len(rows) == 2 + 6 + 2
    for (i, j, l), row in zip(labels, rows):
        assert all(row[t] == 0 for t, s in enumerate(S) if s[i] != j)


def test_random_two_player_games_against_vertex_enumeration():
    rng = random.Random(1234)
    for _ in range(80):
        sizes = rng.choice([(2, 2), (2, 2), (2, 3), (3, 2)])
        game = random_game(rng, sizes, -4, 4)
        if sizes == (2, 2) or rng.random() < 0.08:
            p, value = correlated_equilibrium_lp(game)
            assert is_correlated(game, p) and is_coarse_correlated(game, p)
            assert welfare(game, p) == value
            assert value == best_vertex(game, lambda s: sum(game[1][s]))
            for s in pure_nash_brute(game):
                assert sum(game[1][s]) <= value


def test_random_multiplayer_games():
    rng = random.Random(77)
    for _ in range(40):
        sizes = tuple(rng.randint(2, 3) for _ in range(rng.choice([2, 3])))
        game = random_game(rng, sizes, -3, 3)
        w = {s: rng.randint(-3, 3) for s in profiles(sizes)}
        p, value = correlated_equilibrium_lp(game, weight=lambda s: w[s])
        assert is_correlated(game, p)
        assert sum((q * w[s] for s, q in p.items()), F(0)) == value
        # Every pure Nash equilibrium is a feasible point, so it cannot do better.
        for s in pure_nash_brute(game):
            assert w[s] <= value

History

Aumann (1974) defined correlated equilibria and showed with chicken that they can give more welfare than any Nash equilibrium. Because the definition consists of linear inequalities, a linear program finds one; Hart and Schmeidler (1989) proved existence by linear programming duality alone, without a fixed point theorem, and Gilboa and Zemel (1989) contrasted the polynomial time of correlated equilibria with the NP-hardness of related questions about Nash equilibria. Papadimitriou and Roughgarden (2008) extended polynomial-time computation to succinct games.

References

  1. Subjectivity and correlation in randomized strategies, the definition of correlated equilibrium and the chicken example with a correlated equilibrium better than every Nash equilibrium
  2. Existence of correlated equilibria, the elementary existence proof by linear programming duality
  3. Nash and correlated equilibria: some complexity considerations, the polynomial-time computation of correlated equilibria, against the NP-hardness of the same questions for Nash equilibria
  4. Christos H. Papadimitriou and Tim Roughgarden, Computing correlated equilibria in multi-player games, Journal of the ACM 55(3) (2008), article 14, the introduction (the LP for games in normal form, and why it is too large for succinct games)
  5. Tim Roughgarden, Twenty Lectures on Algorithmic Game Theory, Cambridge University Press, 2016, Lecture 13 (the hierarchy of equilibrium concepts) and Lecture 18 (swap regret and correlated equilibria)

Where this leads

About this page

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

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