Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 d≥1d \ge 1 and let Δd={p∈Rd+1:p≥0,∑ipi=1}\Delta_d = \{p \in \mathbb{R}^{d+1} : p \ge 0, \sum_i p_i = 1\} be the standard simplex, with coordinates 0,…,d0, \dots, d. The input is a map f:Δd→Δdf : \Delta_d \to \Delta_d that we can evaluate at any point, with a Lipschitz bound ∥f(p)−f(q)∥∞≤λ∥p−q∥∞\|f(p) - f(q)\|_\infty \le \lambda \|p - q\|_\infty, and a target accuracy. The output is a point p∗p^* with ∥f(p∗)−p∗∥∞\|f(p^*) - p^*\|_\infty at most the target. On this page NN is the number of grid steps on each edge, so the grid points are the points v/Nv/N where vv has d+1d + 1 nonnegative integer entries with sum NN.

For a finite game the same method gives an ε\varepsilon-Nash equilibrium. For a symmetric two-player game with a k×kk \times k payoff matrix CC with entries in [0,1][0, 1], the row player gets CrcC_{rc} and the column player gets CcrC_{cr}. A pair (q,q)(q, q) is an ε\varepsilon-Nash equilibrium if max⁡r(Cq)r−qTCq≤ε\max_r (Cq)_r - q^{\mathsf T} C q \le \varepsilon. 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 d+1d + 1 slack vectors s0,…,sds_0, \dots, s_d and the grid points, and there is one strict order for each coordinate ii:

  • sis_i is the lowest vector in order ii;
  • next come all grid points, by the value of pip_i, with ties broken by a fixed index;
  • the slacks sjs_j with j≠ij \ne i come last, in the order of jj.

A set SS of d+1d + 1 vectors is primitive if no vector is above the lowest member of SS in every order at the same time. The member that is lowest in order ii holds order ii, 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 (d+1)/N(d + 1)/N in each coordinate. The slack sjs_j has label jj. A grid point pp has the least label ii with fi(p)≥pif_i(p) \ge p_i, and such an ii exists because f(p)f(p) and pp both sum to 1. For a game, the label of qq is the least pure best response to qq.

  1. SCARF(d, N, label) ▷ label maps each grid point to 0..d
  2. 1z ← e_0 ; P ← {s_1, ..., s_d, z} ▷ e_0 is the grid point with p_0 = 1
  3. 2while label(z) ≠ 0
  4. 3y ← the member of P other than z with label(y) = label(z)
  5. 4Q ← P minus y ; a ← the order that y holds in P
  6. 5w ← the lowest member of Q in order a ; b ← the order that w holds in P
  7. 6z ← 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
  8. 7P ← Q plus z
  9. 8return P

Every set PP on the path has the labels 1,…,d1, \dots, d. If the new vector zz has label 0, then PP has all the labels and the loop ends. If not, the label of zz appears twice, and line L3 removes the old member with that label. Lines L4 to L6 compute the only vector z≠yz \ne y that makes QQ plus zz primitive again. This is the replacement step: the member ww loses order aa to the new vector or keeps it, and the new member takes the order bb that ww held. It is the ordinal form of a pivot of the Lemke-Howson algorithm.

Example

Take d=2d = 2, N=4N = 4 and the cyclic map f(p0,p1,p2)=(p1,p2,p0)f(p_0, p_1, p_2) = (p_1, p_2, p_0), which has the fixed point (1/3,1/3,1/3)(1/3, 1/3, 1/3) and Lipschitz constant 1. We write a grid point by its integer vector vv, so (3,1,0)(3, 1, 0) means (3/4,1/4,0)(3/4, 1/4, 0). The point (3,1,0)(3, 1, 0) has f=(1,0,3)f = (1, 0, 3), so coordinates 0 and 1 go down and coordinate 2 goes up, and its label is 2.

step PP labels new vector zz removed yy
0 s1,s2,(4,0,0)s_1, s_2, (4, 0, 0) 1, 2, 1 (4,0,0)(4, 0, 0) s1s_1
1 s2,(4,0,0),(3,1,0)s_2, (4, 0, 0), (3, 1, 0) 2, 1, 2 (3,1,0)(3, 1, 0) s2s_2
2 (4,0,0),(3,1,0),(2,1,1)(4, 0, 0), (3, 1, 0), (2, 1, 1) 1, 2, 1 (2,1,1)(2, 1, 1) (4,0,0)(4, 0, 0)
3 (3,1,0),(2,1,1),(1,2,1)(3, 1, 0), (2, 1, 1), (1, 2, 1) 2, 1, 0 (1,2,1)(1, 2, 1) stop

After 3 pivots the set has the labels {0,1,2}\{0, 1, 2\}. Its points (3/4,1/4,0)(3/4, 1/4, 0), (1/2,1/4,1/4)(1/2, 1/4, 1/4) and (1/4,1/2,1/4)(1/4, 1/2, 1/4) lie around the fixed point. On this coarse grid the bound of the theorem below, 2⋅2⋅3/4=32 \cdot 2 \cdot 3/4 = 3, says nothing, but it goes to 0 as NN grows.

For a game, take rock-paper-scissors with payoff 1 for a win, 1/21/2 for a tie and 0 for a loss. With N=6,12,24,48N = 6, 12, 24, 48 the code returns the points (1/6,1/2,1/3)(1/6, 1/2, 1/3), (1/4,5/12,1/3)(1/4, 5/12, 1/3), (7/24,3/8,1/3)(7/24, 3/8, 1/3) and (5/16,17/48,1/3)(5/16, 17/48, 1/3) after 13, 25, 49 and 97 pivots. The gains are 1/61/6, 1/121/12, 1/241/24 and 1/481/48, so each time the grid doubles, the gain goes down by half.

Correctness

Call a set of dd vectors a door if its labels are exactly 1,…,d1, \dots, d. The replacement step shows that every door lies in exactly two primitive sets, except the door {s1,…,sd}\{s_1, \dots, s_d\}, 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 δ=(d+1)/N\delta = (d + 1)/N. Any two grid points of a primitive set differ by less than δ\delta in every coordinate, and if sjs_j is in the set, its grid points have pj<δp_j < \delta. Now take any grid point p∗p^* of the output and let g=f(p∗)−p∗g = f(p^*) - p^*. For each ii, label ii comes either from a grid point qq with fi(q)≥qif_i(q) \ge q_i, or from sis_i with pi∗<δp^*_i < \delta. In both cases gi>−(1+λ)δg_i > -(1 + \lambda)\delta. Since the entries of gg sum to 0, also gi<d(1+λ)δg_i < d(1 + \lambda)\delta. So

∥f(p∗)−p∗∥∞<d(1+λ)(d+1)N.\|f(p^*) - p^*\|_\infty < \frac{d(1 + \lambda)(d + 1)}{N}.

For a symmetric game with labels from best responses, the same lemma gives that (p∗,p∗)(p^*, p^*) is a 2k2/N2k^2/N-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 d≥1d \ge 1 and N≥1N \ge 1. The vectors are the slacks s0,…,sds_0, \dots, s_d and the grid points p=v/Np = v/N of the simplex Δd={x∈Rd+1:x≥0,∑ixi=1}\Delta_d = \{x \in \mathbb{R}^{d+1} : x \ge 0, \sum_i x_i = 1\}, where vv has nonnegative integer entries with sum NN. For each i∈{0,…,d}i \in \{0, \dots, d\} there is a strict total order ≺i\prec_i on all vectors:

  • sis_i is the lowest vector in order ii;
  • next come all grid points, by the value of pip_i, with ties broken by a fixed index of the points;
  • the slacks sjs_j with j≠ij \ne i are above all grid points, in the order of jj.

So for grid points, p⪯iqp \preceq_i q implies pi≤qip_i \le q_i. A set SS of d+1d + 1 distinct vectors is primitive if there is no vector uu with u≻imin⁡iSu \succ_i \min_i S for every ii, where min⁡iS\min_i S is the lowest member of SS in order ii. We say that a member uu of SS holds order ii if u=min⁡iSu = \min_i S. Each slack sjs_j has label jj, and each grid point has a label in {0,…,d}\{0, \dots, d\} given by a labeling function. A set is completely labeled if its labels are exactly {0,…,d}\{0, \dots, d\}.

The algorithm starts from P0={s1,…,sd,e0}P_0 = \{s_1, \dots, s_d, e_0\}, where e0e_0 is the grid point with p0=1p_0 = 1, and it calls the newest member zz. While zz does not have label 0, it removes the other member yy with the label of zz, lets Q=P∖{y}Q = P \setminus \{y\}, lets aa be the order that yy holds and w=min⁡aQw = \min_a Q, lets bb be the order that ww holds in PP, and adds the vector

z=the highest vector in order b of C={u∉Q:u≻imin⁡iQ for all i≠b}.z = \text{the highest vector in order } b \text{ of } C = \{u \notin Q : u \succ_i \min_i Q \text{ for all } i \ne b\}.

Lemma 1. In a primitive set, each member holds exactly one order.

Proof. If a member uu holds no order, then u≻imin⁡iSu \succ_i \min_i S for every ii, so uu itself breaks primitivity. So each of the d+1d + 1 members holds at least one of the d+1d + 1 orders, and then each holds exactly one. □\square

Lemma 2. P0P_0 is primitive. The set of all d+1d + 1 slacks is not primitive.

Proof. In P0P_0, sis_i holds order ii for i≥1i \ge 1, and e0e_0 holds order 0, because the slacks sjs_j with j≠0j \ne 0 are above all points in order 0. A vector uu above all these minima must satisfy u≻0e0u \succ_0 e_0. Since e0e_0 is the highest grid point in order 0, uu is a slack sis_i with i≥1i \ge 1. But uu must also satisfy u≻isiu \succ_i s_i, which fails for u=siu = s_i. So no vector is above all the minima. For the slacks, min⁡i=si\min_i = s_i, and every grid point is above sis_i in order ii, so any grid point breaks primitivity. □\square

Lemma 3 (the pivot). Let SS be primitive, y∈Sy \in S and Q=S∖{y}Q = S \setminus \{y\}.

  1. If Q={sj:j≠a}Q = \{s_j : j \ne a\} for some aa, then SS is the only primitive set that contains QQ.
  2. Otherwise there is exactly one vector z≠yz \ne y such that Q∪{z}Q \cup \{z\} is primitive, and it is the vector of the rule above.

Proof. Let aa be the order that yy holds in SS, and write mi=min⁡iQm_i = \min_i Q. For i≠ai \ne a, mi=min⁡iSm_i = \min_i S, since yy held only order aa. Let w=maw = m_a. Then w≻ayw \succ_a y, and ww holds some order b≠ab \ne a in SS, so in QQ the member ww is the minimum of both orders aa and bb, and every other member of QQ holds the same single order as in SS.

Let Q∪{z′}Q \cup \{z'\} be primitive with z′≠yz' \ne y, z′∉Qz' \notin Q. By Lemma 1, z′z' holds exactly one order, and every member of QQ keeps at least one order. A member of QQ other than ww holds only one order in QQ, so z′z' cannot take it. So z′z' holds order aa or order bb.

z′z' holds order aa. Then z′≺awz' \prec_a w and z′≻imiz' \succ_i m_i for i≠ai \ne a. The vector yy has the same two properties. Let DD be the set of vectors outside QQ with both properties. Primitivity of SS says that no vector of DD is above yy in order aa, and primitivity of Q∪{z′}Q \cup \{z'\} says that no vector of DD is above z′z' in order aa. So both are the highest vector of DD in order aa, and z′=yz' = y, which is excluded.

z′z' holds order bb. Then z′≻imiz' \succ_i m_i for all i≠bi \ne b (for i=ai = a because ww, not z′z', holds order aa), so z′∈Cz' \in C. Primitivity of Q∪{z′}Q \cup \{z'\} says that no vector of CC is above z′z' in order bb, so z′z' is the highest vector of CC in order bb. So there is at most one such z′z', and it is the zz of the rule.

zz works when CC is not empty. First, every u∈Cu \in C satisfies u≺bwu \prec_b w: otherwise u≻bw=min⁡bSu \succ_b w = \min_b S, u≻aw≻ay=min⁡aSu \succ_a w \succ_a y = \min_a S and u≻imi=min⁡iSu \succ_i m_i = \min_i S for the other ii, so uu would break the primitivity of SS. So z≺bwz \prec_b w, and in Q∪{z}Q \cup \{z\} the minima are mim_i for i≠bi \ne b and zz for order bb. A vector above all of them is not in QQ (members of QQ hold an order), so it lies in CC and is above zz in order bb, which contradicts the choice of zz. So Q∪{z}Q \cup \{z\} is primitive. Also y∉Cy \notin C, because y≺aw=may \prec_a w = m_a and a≠ba \ne b.

When CC is empty. For i≠bi \ne b, the minimum mim_i is either a grid point, or a slack. A slack in QQ holds its own order, so if mim_i is a slack and i≠ai \ne a, then mi=sim_i = s_i. If sb∉Qs_b \notin Q, then sb∈Cs_b \in C: it is above every grid point in each order i≠bi \ne b, above sis_i in order ii, and if ma=wm_a = w is a slack then ww holds order bb, so w=sbw = s_b. Hence CC is empty only if w=sbw = s_b. Then sb=min⁡aQs_b = \min_a Q, so every member of QQ is above sbs_b in order aa; grid points are below sbs_b in order aa, and sas_a would be the minimum of order aa, so QQ consists of dd slacks other than sas_a, that is, Q={sj:j≠a}Q = \{s_j : j \ne a\}. Conversely, for this QQ, the only candidate z′z' is the one that holds order aa, and the argument of the first case shows that SS is the only primitive set that contains QQ. If QQ is not of this form, CC is not empty and part 2 holds. □\square

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 dd-subset QQ of a primitive set a door if its labels are exactly {1,…,d}\{1, \dots, d\}. Among the slack sets {sj:j≠a}\{s_j : j \ne a\}, only Q0={s1,…,sd}Q_0 = \{s_1, \dots, s_d\} is a door, since the others contain s0s_0 with label 0. By Lemma 3, every door other than Q0Q_0 lies in exactly two primitive sets, and Q0Q_0 lies only in P0P_0.

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 {1,…,d}\{1, \dots, d\} 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 Q0Q_0. So every node has degree at most 2, the nodes of degree 1 are P0P_0 (if it is not complete) and the complete sets other than P0P_0, and P0P_0 has degree 0 if it is complete.

The algorithm walks in this graph. At P0P_0 it enters through Q0Q_0 with z=e0z = e_0. At each node PP entered through the door P∖{z}P \setminus \{z\}, if zz has label 0 the node is complete and the walk stops. Otherwise the repeated label is the label of zz, and the walk leaves through the other door P∖{y}P \setminus \{y\}, 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 d+1d + 1 vectors). So the walk ends, at a node of degree 1 other than P0P_0, which is complete, or at P0P_0 itself if P0P_0 is complete.

The number of nodes of degree 1 is even, because each path component has two ends. If P0P_0 is complete, the nodes of degree 1 are the other complete sets, which is an even number, and with P0P_0 the total is odd. If P0P_0 is not complete, the nodes of degree 1 are P0P_0 and all complete sets, so the number of complete sets is odd. □\square

Lemma 4 (primitive sets are small). Let PP be primitive, let TT be the set of indices jj with sj∈Ps_j \in P, and let δ=(d+1)/N\delta = (d+1)/N. For any two grid points p,qp, q in PP and every ii, ∣pi−qi∣<δ|p_i - q_i| < \delta, and pj<δp_j < \delta for every j∈Tj \in T.

Proof. Let t=d+1−∣T∣t = d + 1 - |T|. For i∉Ti \notin T, the minimum mi=min⁡iPm_i = \min_i P is a grid point; write μi\mu_i for its coordinate ii. Every grid point pp of PP has p⪰imip \succeq_i m_i, so pi≥μip_i \ge \mu_i. If ∑i∉Tμi+t/N≤1\sum_{i \notin T} \mu_i + t/N \le 1, the grid point uu with ui=μi+1/Nu_i = \mu_i + 1/N for i∉Ti \notin T, with the rest of the mass put on one coordinate in TT (or on any coordinate if TT is empty), satisfies u≻imiu \succ_i m_i for i∉Ti \notin T and u≻jsju \succ_j s_j for j∈Tj \in T, which breaks primitivity. So ∑i∉Tμi>1−t/N\sum_{i \notin T} \mu_i > 1 - t/N. Then for i∉Ti \notin T, pi=1−∑l≠ipl≤1−∑l∉T,l≠iμl<μi+t/Np_i = 1 - \sum_{l \ne i} p_l \le 1 - \sum_{l \notin T, l \ne i} \mu_l < \mu_i + t/N, so pi∈[μi,μi+t/N)p_i \in [\mu_i, \mu_i + t/N). For j∈Tj \in T, pj≤1−∑l∉Tμl<t/Np_j \le 1 - \sum_{l \notin T} \mu_l < t/N. Since t≤d+1t \le d + 1, the claim follows. □\square

Theorem 2 (approximate fixed point). Let f:Δd→Δdf : \Delta_d \to \Delta_d satisfy ∥f(p)−f(q)∥∞≤λ∥p−q∥∞\|f(p) - f(q)\|_\infty \le \lambda \|p - q\|_\infty. Label each grid point pp by the least ii with fi(p)≥pif_i(p) \ge p_i; such an ii exists because both f(p)f(p) and pp sum to 1. Then every grid point p∗p^* of the output PP satisfies ∥f(p∗)−p∗∥∞<d(1+λ)(d+1)/N\|f(p^*) - p^*\|_\infty < d(1 + \lambda)(d + 1)/N.

Proof. PP contains a grid point by Lemma 2. Let g=f(p∗)−p∗g = f(p^*) - p^*, so ∑igi=0\sum_i g_i = 0. Fix ii. If the label ii comes from a grid point q∈Pq \in P, then fi(q)≥qif_i(q) \ge q_i, and by Lemma 4, ∣qi−pi∗∣<δ|q_i - p^*_i| < \delta and ∣fi(q)−fi(p∗)∣<λδ|f_i(q) - f_i(p^*)| < \lambda \delta. So gi>−(1+λ)δg_i > -(1 + \lambda)\delta. If the label ii comes from si∈Ps_i \in P, then pi∗<δp^*_i < \delta by Lemma 4, and gi≥−pi∗>−δg_i \ge -p^*_i > -\delta. So gi>−(1+λ)δg_i > -(1 + \lambda)\delta for every ii, and then gi=−∑l≠igl<d(1+λ)δg_i = -\sum_{l \ne i} g_l < d(1 + \lambda)\delta. As d≥1d \ge 1, ∣gi∣<d(1+λ)δ|g_i| < d(1 + \lambda)\delta. □\square

Theorem 3 (symmetric games). Let CC be a k×kk \times k matrix with entries in [0,1][0, 1], k=d+1k = d + 1, and consider the symmetric game where the row player gets CrcC_{rc} and the column player gets CcrC_{cr}. Label each grid point qq by the least pure best response to qq, that is, the least ii with (Cq)i=max⁡r(Cq)r(Cq)_i = \max_r (Cq)_r. Then for every grid point p∗p^* of the output, (p∗,p∗)(p^*, p^*) is a 2k2/N2k^2/N-Nash equilibrium.

Proof. Let M=max⁡r(Cp∗)rM = \max_r (Cp^*)_r. The gain of the row player from a pure deviation is at most M−p∗TCp∗=∑ipi∗(M−(Cp∗)i)M - p^{*\mathsf T} C p^* = \sum_i p^*_i (M - (Cp^*)_i). For any grid point q∈Pq \in P, let t=q−p∗t = q - p^*; then ∑ctc=0\sum_c t_c = 0, and ∥t∥1<kδ\|t\|_1 < k\delta by Lemma 4, so ∣(Cq)r−(Cp∗)r∣=∣∑cCrctc∣≤∑tc>0tc=∥t∥1/2<kδ/2|(Cq)_r - (Cp^*)_r| = |\sum_c C_{rc} t_c| \le \sum_{t_c > 0} t_c = \|t\|_1 / 2 < k\delta/2 for every row rr. If the label ii comes from a grid point qq, then (Cq)i=max⁡r(Cq)r(Cq)_i = \max_r (Cq)_r, and so M−(Cp∗)i<kδM - (Cp^*)_i < k\delta. If it comes from sis_i, then pi∗<δp^*_i < \delta and M−(Cp∗)i≤1M - (Cp^*)_i \le 1. Summing, the gain is less than kδ∑ipi∗+kδ=2kδ=2k2/Nk\delta \sum_i p^*_i + k \delta = 2k\delta = 2k^2/N. By symmetry, the column player has the same gain. □\square

Running time. There are d+1+(N+dd)d + 1 + \binom{N + d}{d} vectors. One pivot finds aa, ww and bb in O(d2)O(d^2) comparisons and the new vector in O(d)O(d) comparisons for each vector, so O(d(N+dd))O(d \binom{N + d}{d}) time. The number of pivots is at most the number of primitive sets, which is finite but can be large; no polynomial bound in log⁡N\log N and dd is known, and none is expected, since the problem is PPAD-complete.

Complexity

There are M=(N+dd)M = \binom{N + d}{d} grid points. The code stores one rank array for each of the d+1d + 1 orders, so the extra space is O(dM)O(d M). One pivot finds aa, ww and bb in O(d2)O(d^2) steps, and it finds the new vector in one scan over all vectors with O(d)O(d) comparisons each, so a pivot costs O(dM)O(d M). With TT pivots the time is O(TdM)O(T d M). A real implementation does not scan: with the standard triangulations of Kuhn or Freudenthal, a pivot is a reflection of one vertex and costs O(d)O(d) steps.

The number of pivots TT is the problem. The path visits only primitive sets, but it can visit a large part of them, and MM is exponential in dd for fixed accuracy. To reach accuracy ε\varepsilon the grid needs NN of order d2(1+λ)/εd^2(1 + \lambda)/\varepsilon. 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 f(p∗)≈p∗f(p^*) \approx p^*.
  • 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 O(d)O(d) 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 ff.
  • 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 pi=0p_i = 0 never has label ii. The rule "least ii with fi(p)≥pif_i(p) \ge p_i" does not have this property. There, use an ii with pi>0p_i > 0 and fi(p)≤pif_i(p) \le p_i, 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 d(d+1)(1+λ)/Nd(d + 1)(1 + \lambda)/N. With a small NN 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 ∥f(p)−p∥\|f(p) - p\| 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 2k2/N2k^2/N, 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.

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
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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.pivot
  • 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