Algorithmadvanced
Scarf's algorithm
Also called Scarf simplicial algorithm, simplicial fixed-point algorithm.
Finds an approximate fixed point of a continuous map, or an approximate equilibrium, by path following on a simplicial subdivision.
- Time
- O(T d M) worstO(d M) pivot
- Space
- O(d M) extra
- Where
- M = the number of grid points, binomial(N + d, d); N = the number of grid steps on each edge; T = the number of pivots; d = the dimension of the simplex
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Herbert Scarf, 1967
Scarf's algorithm finds a point of the simplex that a continuous map moves only a little. By the Brouwer fixed-point theorem, such a map has a fixed point, and Scarf (1967) gave the first method that computes an approximation of it. The method puts a grid on the simplex, gives each grid point a label from the map, and follows a path of small sets of grid points from a fixed start until it reaches a set that carries every label. A set with every label is small, so the map moves all its points by a small amount. The same path argument proves the Sperner lemma, and it is the model of the END OF THE LINE problem that defines the class PPAD. With labels from best responses, the method gives an approximate Nash equilibrium of any finite game.
In plain words
Think of a triangle covered by a fine grid of points. A rule moves each point to a new point of the triangle, and we want a point that stays almost where it is. Give each grid point a color: the color names a corner that the point does not move away from. A small group of points with all colors at once must sit next to a point that hardly moves. To find such a group, start in a corner with a group that misses one color. Trade one member of the group at a time, so that the group always keeps the other colors. Each trade has only one way forward, and the walk can never come back to a group that it saw before. So the walk must stop, and it stops at a group with all colors.
The problem
Let and let be the standard simplex, with coordinates . The input is a map that we can evaluate at any point, with a Lipschitz bound , and a target accuracy. The output is a point with at most the target. On this page is the number of grid steps on each edge, so the grid points are the points where has nonnegative integer entries with sum .
For a finite game the same method gives an -Nash equilibrium. For a symmetric two-player game with a payoff matrix with entries in , the row player gets and the column player gets . A pair is an -Nash equilibrium if . Pure deviations are enough, because a mixed strategy is a best response if and only if its support is inside the set of pure best responses. Any finite game reduces to a fixed point of a continuous map, and a bimatrix game reduces to a symmetric game, so the symmetric case shows the main idea.
The algorithm
The code uses the ordinal form of the method, with Scarf's primitive sets. There are slack vectors and the grid points, and there is one strict order for each coordinate :
- is the lowest vector in order ;
- next come all grid points, by the value of , with ties broken by a fixed index;
- the slacks with come last, in the order of .
A set of vectors is primitive if no vector is above the lowest member of in every order at the same time. The member that is lowest in order holds order , and in a primitive set each member holds exactly one order. Primitive sets play the part of the small simplices of a triangulation: their grid points differ by less than in each coordinate. The slack has label . A grid point has the least label with , and such an exists because and both sum to 1. For a game, the label of is the least pure best response to .
SCARF(d, N, label) ▷ label maps each grid point to 0..d- 1
z ← e_0 ; P ← {s_1, ..., s_d, z} ▷ e_0 is the grid point with p_0 = 1 - 2
while label(z) ≠ 0 - 3
y ← the member of P other than z with label(y) = label(z) - 4
Q ← P minus y ; a ← the order that y holds in P - 5
w ← the lowest member of Q in order a ; b ← the order that w holds in P - 6
z ← the highest vector in order b among the vectors u not in Q that are above the lowest member of Q in every order i ≠ b - 7
P ← Q plus z - 8
return P
Every set on the path has the labels . If the new vector has label 0, then has all the labels and the loop ends. If not, the label of appears twice, and line L3 removes the old member with that label. Lines L4 to L6 compute the only vector that makes plus primitive again. This is the replacement step: the member loses order to the new vector or keeps it, and the new member takes the order that held. It is the ordinal form of a pivot of the Lemke-Howson algorithm.
Example
Take , and the cyclic map , which has the fixed point and Lipschitz constant 1. We write a grid point by its integer vector , so means . The point has , so coordinates 0 and 1 go down and coordinate 2 goes up, and its label is 2.
| step | labels | new vector | removed | |
|---|---|---|---|---|
| 0 | 1, 2, 1 | |||
| 1 | 2, 1, 2 | |||
| 2 | 1, 2, 1 | |||
| 3 | 2, 1, 0 | stop |
After 3 pivots the set has the labels . Its points , and lie around the fixed point. On this coarse grid the bound of the theorem below, , says nothing, but it goes to 0 as grows.
For a game, take rock-paper-scissors with payoff 1 for a win, for a tie and 0 for a loss. With the code returns the points , , and after 13, 25, 49 and 97 pivots. The gains are , , and , so each time the grid doubles, the gain goes down by half.
Correctness
Call a set of vectors a door if its labels are exactly . The replacement step shows that every door lies in exactly two primitive sets, except the door , which lies only in the start set. A primitive set with all labels has one door, and any other primitive set that has a door has two. So the primitive sets with a door form a graph in which every node has degree at most 2. The start set has degree 1 (or it is complete already), so the walk from it is a path. It cannot repeat a set, and there are finitely many sets, so it ends at a set with all labels. The same count shows that the number of completely labeled primitive sets is odd. This is the Sperner argument, and it is the reason why the search problem is in PPAD.
Next, every primitive set is small. Let . Any two grid points of a primitive set differ by less than in every coordinate, and if is in the set, its grid points have . Now take any grid point of the output and let . For each , label comes either from a grid point with , or from with . In both cases . Since the entries of sum to 0, also . So
For a symmetric game with labels from best responses, the same lemma gives that is a -Nash equilibrium. The proof file has the full proofs of the replacement step, the path, the size lemma and both bounds.
Proof: Scarf's ordinal algorithm ends at a completely labeled primitive set, and its points give approximate fixed points and equilibriafull
Setting. Fix and . The vectors are the slacks and the grid points of the simplex , where has nonnegative integer entries with sum . For each there is a strict total order on all vectors:
- is the lowest vector in order ;
- next come all grid points, by the value of , with ties broken by a fixed index of the points;
- the slacks with are above all grid points, in the order of .
So for grid points, implies . A set of distinct vectors is primitive if there is no vector with for every , where is the lowest member of in order . We say that a member of holds order if . Each slack has label , and each grid point has a label in given by a labeling function. A set is completely labeled if its labels are exactly .
The algorithm starts from , where is the grid point with , and it calls the newest member . While does not have label 0, it removes the other member with the label of , lets , lets be the order that holds and , lets be the order that holds in , and adds the vector
Lemma 1. In a primitive set, each member holds exactly one order.
Proof. If a member holds no order, then for every , so itself breaks primitivity. So each of the members holds at least one of the orders, and then each holds exactly one.
Lemma 2. is primitive. The set of all slacks is not primitive.
Proof. In , holds order for , and holds order 0, because the slacks with are above all points in order 0. A vector above all these minima must satisfy . Since is the highest grid point in order 0, is a slack with . But must also satisfy , which fails for . So no vector is above all the minima. For the slacks, , and every grid point is above in order , so any grid point breaks primitivity.
Lemma 3 (the pivot). Let be primitive, and .
- If for some , then is the only primitive set that contains .
- Otherwise there is exactly one vector such that is primitive, and it is the vector of the rule above.
Proof. Let be the order that holds in , and write . For , , since held only order . Let . Then , and holds some order in , so in the member is the minimum of both orders and , and every other member of holds the same single order as in .
Let be primitive with , . By Lemma 1, holds exactly one order, and every member of keeps at least one order. A member of other than holds only one order in , so cannot take it. So holds order or order .
holds order . Then and for . The vector has the same two properties. Let be the set of vectors outside with both properties. Primitivity of says that no vector of is above in order , and primitivity of says that no vector of is above in order . So both are the highest vector of in order , and , which is excluded.
holds order . Then for all (for because , not , holds order ), so . Primitivity of says that no vector of is above in order , so is the highest vector of in order . So there is at most one such , and it is the of the rule.
works when is not empty. First, every satisfies : otherwise , and for the other , so would break the primitivity of . So , and in the minima are for and for order . A vector above all of them is not in (members of hold an order), so it lies in and is above in order , which contradicts the choice of . So is primitive. Also , because and .
When is empty. For , the minimum is either a grid point, or a slack. A slack in holds its own order, so if is a slack and , then . If , then : it is above every grid point in each order , above in order , and if is a slack then holds order , so . Hence is empty only if . Then , so every member of is above in order ; grid points are below in order , and would be the minimum of order , so consists of slacks other than , that is, . Conversely, for this , the only candidate is the one that holds order , and the argument of the first case shows that is the only primitive set that contains . If is not of this form, is not empty and part 2 holds.
Theorem 1 (the path). The algorithm ends after finitely many pivots with a completely labeled primitive set. The number of completely labeled primitive sets is odd.
Proof. Call a -subset of a primitive set a door if its labels are exactly . Among the slack sets , only is a door, since the others contain with label 0. By Lemma 3, every door other than lies in exactly two primitive sets, and lies only in .
Build a graph whose nodes are the primitive sets that contain a door, with an edge between two of them if they share a door. A completely labeled set has exactly one door (remove its member with label 0). Any other node has labels with one label twice, and so exactly two doors (remove either member with the repeated label). The edges at a node are its doors other than . So every node has degree at most 2, the nodes of degree 1 are (if it is not complete) and the complete sets other than , and has degree 0 if it is complete.
The algorithm walks in this graph. At it enters through with . At each node entered through the door , if has label 0 the node is complete and the walk stops. Otherwise the repeated label is the label of , and the walk leaves through the other door , to the other primitive set that contains it, which Lemma 3 computes. A walk in a graph of maximum degree 2 that starts at a node of degree at most 1 never repeats a node, and the graph is finite (there are finitely many sets of vectors). So the walk ends, at a node of degree 1 other than , which is complete, or at itself if is complete.
The number of nodes of degree 1 is even, because each path component has two ends. If is complete, the nodes of degree 1 are the other complete sets, which is an even number, and with the total is odd. If is not complete, the nodes of degree 1 are and all complete sets, so the number of complete sets is odd.
Lemma 4 (primitive sets are small). Let be primitive, let be the set of indices with , and let . For any two grid points in and every , , and for every .
Proof. Let . For , the minimum is a grid point; write for its coordinate . Every grid point of has , so . If , the grid point with for , with the rest of the mass put on one coordinate in (or on any coordinate if is empty), satisfies for and for , which breaks primitivity. So . Then for , , so . For , . Since , the claim follows.
Theorem 2 (approximate fixed point). Let satisfy . Label each grid point by the least with ; such an exists because both and sum to 1. Then every grid point of the output satisfies .
Proof. contains a grid point by Lemma 2. Let , so . Fix . If the label comes from a grid point , then , and by Lemma 4, and . So . If the label comes from , then by Lemma 4, and . So for every , and then . As , .
Theorem 3 (symmetric games). Let be a matrix with entries in , , and consider the symmetric game where the row player gets and the column player gets . Label each grid point by the least pure best response to , that is, the least with . Then for every grid point of the output, is a -Nash equilibrium.
Proof. Let . The gain of the row player from a pure deviation is at most . For any grid point , let ; then , and by Lemma 4, so for every row . If the label comes from a grid point , then , and so . If it comes from , then and . Summing, the gain is less than . By symmetry, the column player has the same gain.
Running time. There are vectors. One pivot finds , and in comparisons and the new vector in comparisons for each vector, so time. The number of pivots is at most the number of primitive sets, which is finite but can be large; no polynomial bound in and is known, and none is expected, since the problem is PPAD-complete.
Complexity
There are grid points. The code stores one rank array for each of the orders, so the extra space is . One pivot finds , and in steps, and it finds the new vector in one scan over all vectors with comparisons each, so a pivot costs . With pivots the time is . A real implementation does not scan: with the standard triangulations of Kuhn or Freudenthal, a pivot is a reflection of one vertex and costs steps.
The number of pivots is the problem. The path visits only primitive sets, but it can visit a large part of them, and is exponential in for fixed accuracy. To reach accuracy the grid needs of order . Hirsch, Papadimitriou and Vavasis (1989) showed that every method that only evaluates the map needs a number of evaluations that is exponential in the dimension for some maps, and Chen and Deng (2008) gave matching upper and lower bounds for each fixed dimension. For games, the problem that the path solves is PPAD-complete (PPAD-completeness of Nash), so no polynomial method is expected.
Properties
- Deterministic. The path depends only on the orders and the labels, and the ties are broken by index.
- Exact arithmetic is enough. The code uses rational numbers, and a pivot needs only comparisons of coordinates and labels.
- Only labels matter. The walk uses the map only through the label of each new grid point, one evaluation for each pivot.
- Approximate, not exact. The output is a set of nearby grid points, and none of them needs to be close to an actual fixed point. It only satisfies .
- Odd number of solutions. The number of completely labeled primitive sets is odd, as in the Sperner lemma.
Variants and improvements
- Simplicial form. Kuhn (1968) and Hansen and Scarf (1973) used a triangulation of the simplex and integer labels in place of primitive sets. The pivot then replaces one vertex of a small simplex by the reflection of that vertex, in time.
- Vector labels. Each grid point can get a vector label in place of an integer, and the pivot is then a linear-programming pivot. The output is then a fixed point of a piecewise linear approximation of .
- Restarts and homotopy. Eaves (1972) and Merrill (1972) started the path from a coarse grid and refined it on the way, or restarted from the last answer on a finer grid. This is the idea of homotopy continuation on a grid.
- Lemke-Howson. For a bimatrix game the Lemke-Howson algorithm follows the same kind of path on the best-response polytopes and finds an exact equilibrium.
- Scarf's lemma. In the same year Scarf used primitive sets to prove that balanced games have a nonempty core, with the same pivot.
When to use it
Use it when the map has no structure apart from continuity, and the dimension is small: a few coordinates, and a grid of moderate size. It is a good choice to teach the path argument, to test claims about Sperner labelings, and to find an approximate equilibrium of a small game with any number of players. For two-player games use Lemke-Howson or support enumeration, which give exact answers. For large dimensions use a method that exploits the structure of the map, because no method that only evaluates the map can be fast in general.
Pitfalls
- Ties in the orders. The orders must be strict. If two grid points have the same coordinate and no tie rule, the replacement step is not unique and the walk can split or loop.
- Labels on the boundary in the simplicial form. The ordinal form with slacks accepts any labeling, because the slacks cover the faces. The simplicial form needs a Sperner labeling, in which a point with never has label . The rule "least with " does not have this property. There, use an with and , which exists because both vectors sum to 1.
- Wrong member removed. Line L3 must remove the old member with the repeated label, not the new one. Removing the new vector walks back along the path.
- Grid too coarse. The bound has the factor . With a small the output can be far from a fixed point, as in the example.
- Reading the output as an exact fixed point. A point with small can be far from every fixed point when the map is nearly flat. Use a finer grid, or an exact method, if a point near a true fixed point is needed.
Implementations
The Python code builds the orders of the grid as rank arrays and runs lines L1 to L8 in exact rational arithmetic. approximate_fixed_point labels points by the Brouwer rule, and approximate_symmetric_equilibrium labels points by the least pure best response. The tests list all primitive sets of small grids by brute force and check that each member holds one order, that each door lies in two primitive sets except the start door, and that random labelings give an odd number of complete sets with a path that stays primitive. They also check the cyclic example above, random stochastic linear maps against the bound, and rock-paper-scissors and chicken against the bound , with the shared exact checker for the gains.
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
scarf_algorithm.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/scarf-algorithm/. The authors are listed in prov/E57190.jsonl.
"""Scarf's algorithm in the ordinal form of primitive sets, on the grid of step 1/N in the simplex.
The vectors are the slack vectors s_0, ..., s_d and the grid points p = v / N of the simplex
Delta_d, where v is a tuple of d + 1 nonnegative integers with sum N. There is one strict order
for each coordinate i:
- s_i is the lowest vector in order i;
- the grid points follow, by the value of p_i, and ties go by the index of the point;
- the slacks s_j with j != i are above all the points, in the order of j.
A set S of d + 1 vectors is primitive if no vector is above the minimum of S in every order.
The slack s_j has label j, and a grid point gets its label from a labeling function. The
algorithm walks from the primitive set {s_1, ..., s_d, e_0} to a primitive set with all the
labels 0, ..., d. Every step keeps the labels 1, ..., d, so the walk is a path in an END OF THE
LINE graph, and it ends because it cannot repeat a set.
Vector v is the slack s_v if v <= d, and the grid point self.points[v - d - 1] otherwise.
"""
from fractions import Fraction
from itertools import combinations
def compositions(total, parts):
"""Return all tuples of `parts` nonnegative integers with sum `total`, in lexicographic order."""
if parts == 1:
return [(total,)]
out = []
for first in range(total + 1):
for rest in compositions(total - first, parts - 1):
out.append((first,) + rest)
return out
class ScarfGrid:
"""The vectors and the d + 1 orders of the ordinal Scarf algorithm."""
def __init__(self, d, N):
self.d, self.N = d, N
self.points = compositions(N, d + 1)
self.size = d + 1 + len(self.points)
npts = len(self.points)
self.rank = []
for i in range(d + 1):
r = [0] * self.size
by_coord = sorted(range(npts), key=lambda q: (self.points[q][i], q))
for pos, q in enumerate(by_coord):
r[d + 1 + q] = 1 + pos
for j in range(d + 1):
r[j] = 0 if j == i else 1 + npts + j
self.rank.append(r)
def is_slack(self, v):
return v <= self.d
def point(self, v):
"""Return the grid point of vector v as a tuple of Fraction."""
return tuple(Fraction(c, self.N) for c in self.points[v - self.d - 1])
def vertex_e0(self):
return self.d + 1 + self.points.index((self.N,) + (0,) * self.d)
def minimum(self, S, i):
return min(S, key=lambda v: self.rank[i][v])
def holder(self, S, v):
"""Return the order in which v is the minimum of S (one order if S is primitive)."""
return next(i for i in range(self.d + 1) if self.minimum(S, i) == v)
def is_primitive(self, S):
S = list(S)
if len(S) != self.d + 1 or len(set(S)) != len(S):
return False
mins = [self.rank[i][self.minimum(S, i)] for i in range(self.d + 1)]
return not any(all(self.rank[i][u] > mins[i] for i in range(self.d + 1)) for u in range(self.size))
def highest_above(self, Q, b):
"""Return the highest vector in order b among those not in Q that are above min_i Q in every order i != b."""
mins = [self.rank[i][self.minimum(Q, i)] for i in range(self.d + 1)]
inQ = set(Q)
cands = [u for u in range(self.size) if u not in inQ
and all(self.rank[i][u] > mins[i] for i in range(self.d + 1) if i != b)]
return max(cands, key=lambda u: self.rank[b][u])
def replace(self, S, y):
"""Return the vector z != y such that (S minus y) plus z is primitive (the ordinal pivot)."""
Q = [v for v in S if v != y]
w = self.minimum(Q, self.holder(S, y))
return self.highest_above(Q, self.holder(S, w))
def scarf(grid, point_label, trace=None):
"""Return (P, pivots): a completely labeled primitive set and the number of pivots.
point_label maps a grid point (a tuple of Fraction) to a label in 0, ..., d. If trace is a
list, each primitive set of the path is appended to it.
"""
d = grid.d
def label(v):
return v if grid.is_slack(v) else point_label(grid.point(v))
z = grid.vertex_e0()
P = list(range(1, d + 1)) + [z] # @line L1
pivots = 0
if trace is not None:
trace.append(list(P))
while label(z) != 0: # @line L2
y = next(v for v in P if v != z and label(v) == label(z)) # @line L3
Q, a = [v for v in P if v != y], grid.holder(P, y) # @line L4
w = grid.minimum(Q, a) # @line L5
b = grid.holder(P, w)
z = grid.highest_above(Q, b) # @line L6
P = Q + [z] # @line L7
pivots += 1
if trace is not None:
trace.append(list(P))
return P, pivots # @line L8
def brouwer_label(f):
"""The label of a point p is the least i with f_i(p) >= p_i."""
def label(p):
fp = f(p)
return next(i for i in range(len(p)) if fp[i] >= p[i])
return label
def approximate_fixed_point(f, d, N):
"""Return a grid point p with |f(p) - p|_inf <= d (1 + lam) (d + 1) / N, for f lam-Lipschitz in sup norm."""
grid = ScarfGrid(d, N)
P, _ = scarf(grid, brouwer_label(f))
return next(grid.point(v) for v in P if not grid.is_slack(v))
def best_response_label(C):
"""For a symmetric game with payoff matrix C, label q by the least pure best response to q."""
def label(q):
pay = [sum((Fraction(C[r][c]) * q[c] for c in range(len(q))), Fraction(0)) for r in range(len(q))]
best = max(pay)
return pay.index(best)
return label
def approximate_symmetric_equilibrium(C, N):
"""Return q such that (q, q) is a (2 k^2 / N)-Nash equilibrium of the symmetric game (C, C^T).
C is k by k with payoffs in [0, 1]; the row player gets C[r][c] and the column player C[c][r].
"""
k = len(C)
grid = ScarfGrid(k - 1, N)
P, _ = scarf(grid, best_response_label(C))
return list(next(grid.point(v) for v in P if not grid.is_slack(v)))
def primitive_sets(grid):
"""Return all primitive sets, by brute force (small grids only)."""
return [S for S in combinations(range(grid.size), grid.d + 1) if grid.is_primitive(S)]
test_scarf_algorithm.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/scarf-algorithm/. The authors are listed in prov/E57190.jsonl.
import random
from fractions import Fraction
from itertools import combinations
from agtgame import from_bimatrix, is_epsilon_nash, max_gain
from scarf_algorithm import (ScarfGrid, approximate_fixed_point, approximate_symmetric_equilibrium,
brouwer_label, primitive_sets, scarf)
F = Fraction
HALF = F(1, 2)
SMALL = [(1, 3), (2, 3), (2, 4), (3, 2)]
_CACHE = {}
def grid_and_prims(d, N):
if (d, N) not in _CACHE:
grid = ScarfGrid(d, N)
_CACHE[(d, N)] = (grid, primitive_sets(grid))
return _CACHE[(d, N)]
def labels_of(grid, S, point_label):
return sorted(v if grid.is_slack(v) else point_label(grid.point(v)) for v in S)
def test_each_member_of_a_primitive_set_holds_one_order():
for d, N in SMALL:
grid, prims = grid_and_prims(d, N)
for S in prims:
assert len({grid.minimum(S, i) for i in range(d + 1)}) == d + 1
def test_doors_lie_in_two_primitive_sets_except_the_slack_sets():
for d, N in SMALL:
grid, prims = grid_and_prims(d, N)
count = {}
for S in prims:
for Q in combinations(S, d):
count[Q] = count.get(Q, 0) + 1
boundary = sorted(Q for Q, c in count.items() if c == 1)
assert boundary == sorted(combinations(range(d + 1), d))
assert all(c <= 2 for c in count.values())
for S in prims:
for y in S:
Q = [v for v in S if v != y]
if count[tuple(Q)] == 2:
z = grid.replace(list(S), y)
assert z != y and grid.is_primitive(Q + [z])
def test_random_labelings_odd_count_and_path():
rng = random.Random(20261120)
for d, N in SMALL:
grid, prims = grid_and_prims(d, N)
for _ in range(15):
table = {p: rng.randint(0, d) for p in grid.points}
def lab(p):
return table[tuple(int(c * N) for c in p)]
full = [S for S in prims if labels_of(grid, S, lab) == list(range(d + 1))]
assert len(full) % 2 == 1
trace = []
P, pivots = scarf(grid, lab, trace)
assert tuple(sorted(P)) in full
assert len(trace) == pivots + 1
assert len({tuple(sorted(S)) for S in trace}) == len(trace)
for S in trace:
assert grid.is_primitive(S)
assert set(range(1, d + 1)) <= set(labels_of(grid, S, lab))
def test_start_is_already_complete():
grid = ScarfGrid(2, 5)
P, pivots = scarf(grid, lambda p: 0)
assert pivots == 0 and sorted(P) == [1, 2, grid.vertex_e0()]
def test_cyclic_map_example():
grid = ScarfGrid(2, 4)
f = (lambda p: (p[1], p[2], p[0]))
P, pivots = scarf(grid, brouwer_label(f))
assert pivots == 3
assert sorted(grid.points[v - 3] for v in P) == [(1, 2, 1), (2, 1, 1), (3, 1, 0)]
def stochastic_map(rng, k):
cols = []
for _ in range(k):
w = [rng.randint(0, 5) for _ in range(k)]
if sum(w) == 0:
w[0] = 1
cols.append([F(v, sum(w)) for v in w])
M = [[cols[c][r] for c in range(k)] for r in range(k)]
lam = max(sum(row) for row in M)
return (lambda p: tuple(sum((M[r][c] * p[c] for c in range(k)), F(0)) for r in range(k))), lam
def test_linear_maps_within_the_bound():
rng = random.Random(4)
for d, N in [(1, 10), (1, 31), (2, 8), (2, 15), (3, 6)]:
for _ in range(3):
f, lam = stochastic_map(rng, d + 1)
p = approximate_fixed_point(f, d, N)
assert sum(p) == 1 and min(p) >= 0
err = max(abs(a - b) for a, b in zip(f(p), p))
assert err <= F(d * (d + 1), N) * (1 + lam)
def test_symmetric_games():
rps = [[HALF, 0, 1], [1, HALF, 0], [0, 1, HALF]]
chicken = [[0, 1], [F(2, 7), F(6, 7)]]
for C in (rps, chicken):
k = len(C)
game = from_bimatrix(C, [list(r) for r in zip(*C)])
gains = []
for N in (6, 12, 24):
q = approximate_symmetric_equilibrium(C, N)
assert is_epsilon_nash(game, [q, q], F(2 * k * k, N))
gains.append(max_gain(game, [q, q]))
assert gains[-1] <= F(2 * k * k, 24)
# Chicken: the mixed equilibrium plays C (strategy 1) with probability 2/3, a grid point for N = 24.
q = approximate_symmetric_equilibrium(chicken, 24)
assert abs(q[1] - F(2, 3)) <= F(4, 24)
History
Lemke and Howson (1964) found the complementary pivot path for bimatrix games. Scarf (1967) used a path of the same kind to approximate fixed points of continuous maps, and in the same year to prove his lemma on the core of balanced games. Kuhn (1968) gave the simplicial form with integer labels, and Hansen and Scarf (1973) wrote it up for economic equilibrium models. Restart and homotopy methods followed in the 1970s. Hirsch, Papadimitriou and Vavasis (1989) showed exponential lower bounds for methods that only evaluate the map. Papadimitriou (1994) defined PPAD from the parity argument of this path, and Daskalakis, Goldberg and Papadimitriou (2006, 2009) and Chen, Deng and Teng (2006, 2009) showed that the problems it solves for games are PPAD-complete.
References
- Herbert Scarf, The approximation of fixed points of a continuous mapping, SIAM Journal on Applied Mathematics 15(5) (1967), 1328-1343, primitive sets, the replacement step and the approximate fixed point of a continuous map of the simplex
- C. E. Lemke and J. T. Howson, Jr., Equilibrium points of bimatrix games, Journal of the Society for Industrial and Applied Mathematics 12(2) (1964), 413-423, the complementary pivot path that Scarf's method follows in a different setting
- Xi Chen and Xiaotie Deng, Matching algorithmic bounds for finding a Brouwer fixed point, Journal of the ACM 55(3) (2008), 13:1-13:26, upper and lower bounds on the number of function values that any method of this kind needs, for each fixed dimension
- Constantinos Daskalakis, Paul W. Goldberg and Christos H. Papadimitriou, The complexity of computing a Nash equilibrium, SIAM Journal on Computing 39(1) (2009), 195-259, the path-following argument behind Scarf's method as the defining problem of PPAD, and the hardness of approximate fixed points
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 E57190 Edit this page History Report an error Markdown