Algorithm Search⌘K

Algorithmadvanced

Equilibria of symmetric network congestion games by min-cost flow

Also called Fabrikant-Papadimitriou-Talwar algorithm, min-cost flow algorithm for symmetric network congestion games.

Finds a pure Nash equilibrium of a symmetric network congestion game by minimizing Rosenthal's potential as a min-cost flow.

Time
O(n v m) worst
Space
O(v + m) extra
Where
m = the number of edges; n = the number of players; v = the number of vertices
Properties
not comparison baseddeterministiciterative
Origin
Alex Fabrikant, Christos Papadimitriou, Kunal Talwar, 2004

In a symmetric network congestion game, every player sends one unit from the same source ss to the same sink tt of a directed graph, and the cost of an edge depends on how many players use it. This algorithm finds a pure Nash equilibrium in polynomial time. It builds a flow of value nn that minimizes Rosenthal's potential, by successive shortest paths on the marginal terms of the potential, and then splits the flow into nn paths. It differs from the min-cost flow problem in its costs: the cost to minimize is the potential, a separable convex function of the loads, not a linear cost per unit, and the answer must be read as a profile of paths. It differs from cycle canceling in method: it never starts from a feasible flow, but grows the flow one unit at a time, as successive shortest paths does.

In plain words

Many drivers go from the same start to the same goal. Each road gets slower when more drivers use it, and each driver picks the route that is fastest for that driver. A stable state is one where no driver can change route and arrive sooner. There is a score of the whole traffic such that, when one driver changes route, the score changes by exactly the time that driver gains or loses. So the state with the lowest score is stable. The algorithm finds that state by adding drivers one at a time. Each new driver takes the cheapest route, and the route may move some earlier drivers to other roads. At the end it reads off one route for each driver.

The problem

The input is a directed graph G=(V,E)G = (V, E) with v=∣V∣v = |V| and m=∣E∣m = |E|, a source ss and a sink t≠st \ne s, a number of players n≥1n \ge 1, and for each edge ee the costs ce(1),…,ce(n)c_e(1), \ldots, c_e(n), where ce(j)c_e(j) is what each of the jj players on ee pays. The costs are nonnegative and nondecreasing in jj. The strategy set of every player is the set of simple directed ss-tt paths, so the game is symmetric. In a profile P=(P1,…,Pn)P = (P_1, \ldots, P_n) the load of ee is xex_e, the number of players whose path uses ee, and player ii pays ci(P)=∑e∈Pice(xe)c_i(P) = \sum_{e \in P_i} c_e(x_e) and minimizes it. The output is a pure Nash equilibrium: a profile where no player can lower its own cost by a change of path while the others stay. One exists by Rosenthal's theorem, because every minimizer of the potential

Φ(P)=∑e∈E∑j=1xece(j)\Phi(P) = \sum_{e \in E} \sum_{j=1}^{x_e} c_e(j)

is one. The number of paths can be exponential in vv, so the game is given by the graph and the cost tables, not as a table of payoffs.

The algorithm

  1. SYM-CONGESTION-EQ(G, s, t, n, c)
  2. 1x_e ← 0 for each edge e
  3. 2for k ← 1 to n do
  4. 3P ← a cheapest s-t path, by Bellman-Ford, in the residual graph: arc u→v of cost c_e(x_e + 1) if x_e < n, and arc v→u of cost -c_e(x_e) if x_e > 0, for each edge e = (u, v)
  5. 4for each arc of P: x_e ← x_e + 1 if the arc is forward, x_e ← x_e - 1 if it is backward
  6. 5for k ← 1 to n do
  7. 6walk from s along edges with x_e > 0 until the walk reaches t
  8. 7if the walk comes back to a vertex on it: x_e ← x_e - 1 on that cycle, and cut the cycle from the walk
  9. 8P_k ← the walk; x_e ← x_e - 1 on each edge of P_k
  10. 9return (P_1, ..., P_n)

The forward arc of ee costs ce(xe+1)c_e(x_e + 1), the amount that one more unit on ee adds to the potential. The backward arc costs −ce(xe)-c_e(x_e), the amount that one unit less on ee removes from it. These are the marginal costs of a separable convex cost, so line L3 is one step of successive shortest paths on the network where each edge is nn parallel unit arcs of costs ce(1),…,ce(n)c_e(1), \ldots, c_e(n). A backward arc moves part of the route of an earlier player. The flow after line L4 can hold cycles of zero cost, and line L7 removes them, so each PkP_k is simple.

Example

Take the graph with vertices s,a,b,ts, a, b, t, n=3n = 3 players and these edges, where xx is the load: s→as \to a costs 2x2x, a→ta \to t costs 5, s→bs \to b costs 5, b→tb \to t costs 2x2x, and a→ba \to b costs 0. The three paths are sats a t, sabts a b t and sbts b t. The table traces lines L2 to L4. The loads are listed in the order sas a, ata t, sbs b, btb t, aba b.

round cheapest residual path length loads after line L4
1 s→a→b→ts \to a \to b \to t 2+0+2=42 + 0 + 2 = 4 1, 0, 0, 1, 1
2 s→a→b→ts \to a \to b \to t 4+0+4=84 + 0 + 4 = 8 2, 0, 0, 2, 2
3 s→bs \to b, back over a→ba \to b, then a→ta \to t 5−0+5=105 - 0 + 5 = 10 2, 1, 1, 2, 1

In round 3 the direct paths sats a t and sbts b t both cost 6+5=116 + 5 = 11 and the path sabts a b t costs 6+0+6=126 + 0 + 6 = 12, so the backward arc wins with 10. It moves the tail of one earlier player from b→tb \to t to a→ta \to t. The potential is 4+8+10=224 + 8 + 10 = 22, the sum of the three lengths. Lines L5 to L9 split the loads into sats a t, sabts a b t and sbts b t. The players pay 4+5=94 + 5 = 9, 4+0+4=84 + 0 + 4 = 8 and 5+4=95 + 4 = 9, so the total cost is 26.

This profile is an equilibrium. The player on sats a t would pay 4+0+6=104 + 0 + 6 = 10 on sabts a b t and 5+6=115 + 6 = 11 on sbts b t. The player on sabts a b t would pay 4+5=94 + 5 = 9 on either direct path. The player on sbts b t would pay 6+5=116 + 5 = 11 on sats a t and 6+0+4=106 + 0 + 4 = 10 on sabts a b t. A search over all 10 profiles shows that it is the only pure Nash equilibrium. The least total cost is 25, with two players on one direct path and one on the other, so the price of anarchy and the price of stability of this game are both 26/2526/25. Without the edge a→ba \to b the algorithm returns that optimum, with potential 23, so the free edge raises the equilibrium cost from 25 to 26, as in Braess's paradox.

Correctness

The file proofs/correctness.md has the full proof. Replace each edge by nn parallel unit arcs of costs ce(1)≤⋯≤ce(n)c_e(1) \le \cdots \le c_e(n). A flow that uses the cheapest xex_e copies of each edge costs exactly Φ(x)\Phi(x), and no flow with the same loads costs less, so a min-cost flow of value nn in this network gives loads that minimize Φ\Phi. The residual graph of line L3 is the residual graph of the expanded network with only the cheapest copy kept, so it has the same shortest paths and no negative cycle, and an augmentation keeps the "cheapest copies" form. By the successive shortest path theorem, after kk rounds the loads minimize Φ\Phi among integral flows of value kk. Removing a cycle cannot raise Φ\Phi, because the costs are nonnegative, so the nn paths of lines L5 to L9 still minimize Φ\Phi over all flows of value nn, and so over all profiles. If one player changes path, Φ\Phi changes by exactly the change of that player's cost, so at a minimizer no change gains.

Proof: Successive shortest paths on the marginal costs minimize Rosenthal's potential, and the minimizer is a pure Nash equilibriumfull

The input is a directed graph G=(V,E)G = (V, E) with v=∣V∣v = |V| and m=∣E∣m = |E|, two vertices s≠ts \ne t, a number of players n≥1n \ge 1, and for each edge ee the costs ce(1),…,ce(n)c_e(1), \ldots, c_e(n), which are nonnegative and nondecreasing. All players have the same strategy set, the simple directed ss-tt paths. In a profile P=(P1,…,Pn)P = (P_1, \ldots, P_n) the load of ee is xe(P)=∣{i:e∈Pi}∣x_e(P) = |\{i : e \in P_i\}|, player ii pays ci(P)=∑e∈Pice(xe(P))c_i(P) = \sum_{e \in P_i} c_e(x_e(P)), and Rosenthal's potential is

Φ(x)=∑e∈E∑j=1xece(j).\Phi(x) = \sum_{e \in E} \sum_{j=1}^{x_e} c_e(j).

The same formula defines Φ(x)\Phi(x) for any integral vector xx with 0≤xe≤n0 \le x_e \le n. We write Φ(P)\Phi(P) for Φ(x(P))\Phi(x(P)). A flow of value kk is an integral vector xx with 0≤xe≤n0 \le x_e \le n such that the net outflow is kk at ss, −k-k at tt and 0 at every other vertex.

Step 1. The potential is a min-cost flow cost

Build the expanded network HH. Replace each edge e=(u,v)e = (u, v) by nn parallel arcs e1,…,ene^1, \ldots, e^n from uu to vv, each with capacity 1, where eje^j has cost ce(j)c_e(j). An integral flow yy in HH maps to the flow xx in GG with xe=∑jy(ej)x_e = \sum_j y(e^j), and every flow of GG is the image of some yy. Among the yy that map to a given xx, the cost ∑e,jce(j) y(ej)\sum_{e, j} c_e(j)\, y(e^j) is a sum of xex_e distinct values from the list ce(1)≤⋯≤ce(n)c_e(1) \le \cdots \le c_e(n) for each ee, so it is at least ∑j≤xece(j)\sum_{j \le x_e} c_e(j), with equality for the prefix flow that uses e1,…,exee^1, \ldots, e^{x_e}. So the least cost of an integral flow of value kk in HH equals min⁡Φ(x)\min \Phi(x) over the flows xx of value kk in GG, and a prefix flow of least cost gives a minimizer.

Step 2. Lines L1 to L4 run successive shortest paths on HH

Let the residual graph R(x)R(x) of the code be as in line L3: for each edge e=(u,v)e = (u, v) it has the arc u→vu \to v of cost ce(xe+1)c_e(x_e + 1) if xe<nx_e < n, and the arc v→uv \to u of cost −ce(xe)-c_e(x_e) if xe>0x_e > 0. Let yy be the prefix flow of xx. In the residual graph HyH_y of HH, the forward arcs of ee are the unused copies exe+1,…,ene^{x_e+1}, \ldots, e^n, and the cheapest of them costs ce(xe+1)c_e(x_e + 1); the backward arcs are the reverses of e1,…,exee^1, \ldots, e^{x_e}, of costs −ce(j)-c_e(j), and the cheapest costs −ce(xe)-c_e(x_e). So R(x)R(x) is HyH_y with only the cheapest copy kept between each ordered pair of endpoints for each edge.

A simple path in HyH_y uses at most one arc out of each vertex. Replacing each arc by the cheapest copy of the same edge and direction does not increase its length and gives a path of R(x)R(x). Conversely, each arc of R(x)R(x) is an arc of HyH_y. So the shortest ss-tt distance is the same in both graphs, and a shortest path QQ of R(x)R(x) is a shortest path of HyH_y. The same map sends a cycle of R(x)R(x) to a cycle of HyH_y of equal cost, because the arc u→vu \to v of ee and the arc v→uv \to u of ee come from the distinct copies exe+1e^{x_e+1} and exee^{x_e}. Pushing one unit along QQ in HH uses the copy exe+1e^{x_e+1} on a forward arc and frees the copy exee^{x_e} on a backward arc, so the new flow is again a prefix flow, and it is the prefix flow of the vector that line L4 computes.

Now use the successive shortest path theorem (Ahuja, Magnanti and Orlin, Chapter 9): if a flow has no negative cycle in its residual graph, then pushing flow along a shortest ss-tt path, by at most its bottleneck, gives a flow of least cost for its new value, and its residual graph again has no negative cycle. At the start, y=0y = 0 and every arc of HH has cost ce(j)≥0c_e(j) \ge 0, so there is no negative cycle. Each residual capacity in HH is 1, so one unit is within the bottleneck. By induction, after kk rounds of line L2 the prefix flow has least cost among the integral flows of value kk in HH, so by Step 1 the vector xx minimizes Φ\Phi over the flows of value kk in GG.

Two details remain. First, R(x)R(x) has no negative cycle, because HyH_y has none and cycles map to cycles of equal cost. So Bellman-Ford with v−1v - 1 rounds of relaxation finds exact distances, and because it updates a label only on a strict decrease, the predecessor pointers form a tree rooted at ss (Cormen, Leiserson, Rivest and Stein, Section 24.5, the predecessor-subgraph property), so line L3 reads off a simple path. Second, if tt is not reachable from ss in R(x)R(x), then no flow of value k+1k + 1 exists in HH, and since every ss-tt path of GG is a flow of value nn, there is no strategy at all. The code raises an error in that case, which can only happen in round 1.

After nn rounds, xx is a flow of value nn with Φ(x)≤Φ(z)\Phi(x) \le \Phi(z) for every flow zz of value nn.

Step 3. Lines L5 to L9 split the flow into simple paths

Claim: at the start of round kk of line L5 the current vector xx is a flow of value n−k+1n - k + 1, and round kk ends with a simple ss-tt path PkP_k such that every edge of PkP_k had xe≥1x_e \ge 1.

Inside a round the code keeps a simple walk WW from ss to the current vertex ww whose edges all have xe≥1x_e \ge 1. If w≠tw \ne t, some edge out of ww has xe≥1x_e \ge 1. For w=sw = s this holds because the net outflow of ss is n−k+1≥1n - k + 1 \ge 1. For w≠s,tw \ne s, t the last edge of WW enters ww with xe≥1x_e \ge 1, so the inflow of ww is positive, and by conservation so is its outflow. Take such an edge e=(w,u)e = (w, u). If uu is not on WW, line L6 extends WW and it stays simple. If uu is on WW, the part of WW from uu to ww together with ee is a simple cycle whose edges all have xe≥1x_e \ge 1, and line L7 lowers xx by 1 on it and cuts it from WW. Lowering a flow by 1 on a cycle keeps every net outflow, so xx stays a flow of the same value. Each extension makes WW longer, and WW has at most v−1v - 1 edges; each cut lowers ∑exe\sum_e x_e by at least 1. So the pair (∑exe\sum_e x_e, v−∣W∣v - |W|) decreases in lexicographic order at each step, and the round ends, at w=tw = t, with a simple ss-tt path. Line L8 lowers xx by 1 on it, which gives a flow of value n−kn - k. This proves the claim.

The pointer in the code only skips edges with xe=0x_e = 0. No step of the split raises any xex_e, so a skipped edge is never needed again.

Step 4. The output minimizes the potential

Let x∗x^* be the vector after line L4 and let x′x' be the load vector of the output (P1,…,Pn)(P_1, \ldots, P_n). Line L8 removes exactly one unit per path, and line L7 removes extra units on cycles, so x′≤x∗x' \le x^* coordinatewise. Each ce(j)≥0c_e(j) \ge 0, so Φ(x′)≤Φ(x∗)\Phi(x') \le \Phi(x^*). Also x′x' is a flow of value nn: it is a sum of nn unit ss-tt paths, and each load is at most nn. By Step 2, Φ(x∗)≤Φ(x′)\Phi(x^*) \le \Phi(x'). So Φ(x′)=Φ(x∗)\Phi(x') = \Phi(x^*).

Every profile PP of simple ss-tt paths has a load vector x(P)x(P) that is a flow of value nn. So Φ(P1,…,Pn)=Φ(x∗)≤Φ(x(P))=Φ(P)\Phi(P_1, \ldots, P_n) = \Phi(x^*) \le \Phi(x(P)) = \Phi(P) for every profile PP: the output minimizes Rosenthal's potential over all profiles.

Step 5. A minimizer of the potential is a pure Nash equilibrium

Let PP be a profile, let player ii change from PiP_i to another simple ss-tt path QQ, and let P′=(Q,P−i)P' = (Q, P_{-i}). Only the edges in exactly one of PiP_i and QQ change load. An edge e∈Q∖Pie \in Q \setminus P_i goes from load xex_e to xe+1x_e + 1, which adds ce(xe+1)c_e(x_e + 1) to Φ\Phi and is also the cost that player ii pays on it in P′P'. An edge e∈Pi∖Qe \in P_i \setminus Q goes from xex_e to xe−1x_e - 1, which removes ce(xe)c_e(x_e) from Φ\Phi, the cost that player ii paid on it in PP. Edges in both paths keep their load and their cost to player ii. So

Φ(P′)−Φ(P)=ci(P′)−ci(P).\Phi(P') - \Phi(P) = c_i(P') - c_i(P).

If PP minimizes Φ\Phi, the left side is at least 0 for every ii and QQ, so no player gains by a unilateral change. This is Rosenthal's theorem. Hence (P1,…,Pn)(P_1, \ldots, P_n) is a pure Nash equilibrium. ■\blacksquare

References: R. K. Ahuja, T. L. Magnanti and J. B. Orlin, Network Flows: Theory, Algorithms, and Applications, Prentice Hall, 1993, Chapter 9 (successive shortest paths) and Chapter 14 (convex cost flows). T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, 3rd edition, MIT Press, 2009, Sections 24.1 and 24.5. A. Fabrikant, C. Papadimitriou and K. Talwar, The complexity of pure Nash equilibria, STOC 2004, 604-612, the polynomial algorithm for the symmetric network case. R. W. Rosenthal, A class of games possessing pure-strategy Nash equilibria, International Journal of Game Theory 2 (1973), 65-67.

Complexity

Line L3 runs Bellman-Ford with at most v−1v - 1 rounds over 2m2m arcs, so it takes O(vm)O(v m) time, and lines L2 to L4 take O(nvm)O(n v m). In the split, each step either extends a simple walk, at most v−1v - 1 times between two cuts, or cuts a cycle and lowers ∑exe≤nm\sum_e x_e \le n m by at least 1. A pointer per vertex skips the edges whose load is already 0, which never become positive again, so lines L5 to L9 take O(n(v+m))O(n (v + m)) time. The total is O(nvm)O(n v m). The loads, labels and predecessors take O(v+m)O(v + m) extra space, and the output takes O(nv)O(n v). These bounds count arithmetic on costs as unit steps. The input holds nn costs per edge, so nn is at most the input size and the running time is polynomial in it.

Properties

  • It returns a global minimizer of the potential. That is more than an equilibrium: best-response dynamics stops at any local minimum of Φ\Phi, and those can be worse.
  • Social cost at most twice the optimum for affine costs. If ce(x)=aex+bec_e(x) = a_e x + b_e with ae,be≥0a_e, b_e \ge 0, then Φ≤C≤2Φ\Phi \le C \le 2 \Phi for the total cost CC, so the output has C≤2Φ(out)≤2Φ(opt)≤2C(opt)C \le 2 \Phi(\text{out}) \le 2 \Phi(\text{opt}) \le 2 C(\text{opt}). The price of anarchy for linear congestion games bounds the worst equilibrium by 5/25/2 times the optimum.
  • Exact. With rational costs the code uses exact fractions, so ties and equilibrium checks are decided exactly.
  • Deterministic. The output depends on the order of the edges only through ties between paths of equal length.

Variants and improvements

  • Dijkstra with potentials. Keep the distance labels of the previous round as node potentials. The reduced costs are then nonnegative, and Dijkstra's algorithm replaces Bellman-Ford, which gives O(n(m+vlog⁡v))O(n (m + v \log v)) time with a Fibonacci heap. This is the usual form of successive shortest paths.
  • Large nn. When the costs are given by formulas and nn is written in binary, nn augmentations take time exponential in the input size. Capacity scaling for convex cost flows (Ahuja, Magnanti and Orlin, Chapter 14) handles that case.
  • Parallel links. If every path is one edge, line L3 just picks the edge with the least ce(xe+1)c_e(x_e + 1) and never needs a backward arc. This greedy rule gives an equilibrium of a symmetric game on parallel links.
  • Several sources or sinks. With different source-sink pairs the loads would have to come from an integral multicommodity flow, and the reduction breaks. Fabrikant, Papadimitriou and Talwar proved that this case is PLS-complete; see PLS-completeness of congestion games.

When to use it

Use it when all players share one source and one sink and you need an equilibrium with a proof, or the equilibrium of least potential, for example as the start of a price of stability bound. For games with different source-sink pairs, or for symmetric games whose strategies are not paths of a graph, no polynomial method is known, and the search problem is PLS-complete; there, best-response dynamics is the usual heuristic.

Pitfalls

  • Minimizing the total cost in place of the potential. The marginal social cost (x+1)ce(x+1)−x ce(x)(x + 1) c_e(x + 1) - x\, c_e(x) on the arcs gives the social optimum, not an equilibrium. In the example that returns cost 25 with two players on one direct path, and each of them gains by moving to sabts a b t, from 9 to 8.
  • No backward arcs. Routing the players one by one on cheapest paths with costs ce(xe+1)c_e(x_e + 1), without the arcs of line L3 that go back, is a greedy heuristic. In the example its third player takes a direct path at cost 11, which gives potential 23 and a profile that is not an equilibrium.
  • Plain Dijkstra on the residual graph. The backward arcs have negative costs. Use Bellman-Ford, or Dijkstra on reduced costs with valid potentials.
  • Decreasing costs. With economies of scale the cheapest copies are no longer the first ones, the problem becomes a concave cost flow, and the reduction fails. Rosenthal's theorem still gives an equilibrium, but this algorithm does not find it. The code rejects such input.
  • Splitting a flow that holds cycles. Edges of cost 0 in both directions can carry flow around a cycle. A split that does not cut cycles may never reach tt or may return a path that repeats a vertex.

Implementations

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.

symmetric_network_congestion_min_cost_flow.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symmetric-network-congestion-min-cost-flow/. The authors are listed in prov/KZRBES.jsonl.

"""A pure Nash equilibrium of a symmetric network congestion game, by min-cost flow.

The network is directed. Vertices are hashable labels. An edge is a triple (u, v, costs),
where costs[j - 1] is c_e(j), the cost that each of the j players on the edge pays.
The costs of an edge must be nonnegative and nondecreasing in j. All n players go from
s to t, and a strategy is a simple s-t path, given as a list of edge indices.

The algorithm minimizes Rosenthal's potential Phi = sum_e sum_{j <= x_e} c_e(j) over all
integral flows of value n by successive shortest paths with the marginal costs
c_e(x_e + 1) forward and -c_e(x_e) backward, and then splits the flow into n paths.
A profile that minimizes Phi is a pure Nash equilibrium.
"""

from fractions import Fraction
from typing import Hashable, Sequence

Edge = tuple[Hashable, Hashable, Sequence]


def _check(edges: Sequence[Edge], n: int) -> None:
    if n < 1:
        raise ValueError("there must be at least one player")
    for u, v, costs in edges:
        if len(costs) < n:
            raise ValueError("each edge needs the costs c_e(1), ..., c_e(n)")
        if any(c < 0 for c in costs[:n]):
            raise ValueError("costs must be nonnegative")
        if any(costs[j] > costs[j + 1] for j in range(n - 1)):
            raise ValueError("costs must be nondecreasing in the number of users")


def _cheapest_path(vertices, edges, x, s, t, n):
    """Bellman-Ford on the residual graph. Return a list of (edge index, +1 or -1), or None."""
    dist = {v: None for v in vertices}
    pred = {}
    dist[s] = Fraction(0)
    for _ in range(len(vertices) - 1):
        changed = False
        for e, (u, v, costs) in enumerate(edges):
            if x[e] < n and dist[u] is not None:  # forward arc u -> v
                d = dist[u] + costs[x[e]]  # c_e(x_e + 1)
                if dist[v] is None or d < dist[v]:
                    dist[v], pred[v], changed = d, (e, 1), True
            if x[e] > 0 and dist[v] is not None:  # backward arc v -> u
                d = dist[v] - costs[x[e] - 1]  # -c_e(x_e)
                if dist[u] is None or d < dist[u]:
                    dist[u], pred[u], changed = d, (e, -1), True
        if not changed:
            break
    if dist[t] is None:
        return None
    path, w = [], t
    while w != s:
        e, d = pred[w]
        path.append((e, d))
        u, v, _ = edges[e]
        w = u if d == 1 else v
    path.reverse()
    return path


def min_potential_flow(vertices, edges: Sequence[Edge], s, t, n: int) -> list[int]:
    """Return integral edge loads x of an s-t flow of value n that minimize Rosenthal's potential."""
    _check(edges, n)
    vertices = list(vertices)
    x = [0] * len(edges)  # @line L1
    for _ in range(n):  # @line L2
        path = _cheapest_path(vertices, edges, x, s, t, n)  # @line L3
        if path is None:
            raise ValueError("t is not reachable from s")
        for e, d in path:  # @line L4
            x[e] += d
    return x


def split_into_paths(edges: Sequence[Edge], x: list[int], s, t, n: int) -> list[list[int]]:
    """Split the flow x of value n into n simple s-t paths. Cycles met on the way are removed."""
    x = list(x)
    out = {}
    for e, (u, v, _) in enumerate(edges):
        out.setdefault(u, []).append(e)
    ptr = {u: 0 for u in out}  # x only goes down here, so an edge with x = 0 is never needed again
    paths = []
    for _ in range(n):  # @line L5
        walk, where = [], {s: 0}  # walk is a list of edges; where maps a vertex to its place
        w = s
        while w != t:  # @line L6
            lst = out[w]
            while x[lst[ptr[w]]] == 0:
                ptr[w] += 1
            e = lst[ptr[w]]
            v = edges[e][1]
            if v in where:  # @line L7: the walk closes a cycle, so remove it
                i = where[v]
                for f in walk[i:] + [e]:
                    x[f] -= 1
                for f in walk[i:]:
                    del where[edges[f][1]]
                walk = walk[:i]
                w = v
            else:
                walk.append(e)
                where[v] = len(walk)
                w = v
        for f in walk:  # @line L8
            x[f] -= 1
        paths.append(walk)
    return paths  # @line L9


def symmetric_congestion_equilibrium(vertices, edges: Sequence[Edge], s, t, n: int) -> list[list[int]]:
    """Return a pure Nash equilibrium: one simple s-t path (a list of edge indices) per player."""
    x = min_potential_flow(vertices, edges, s, t, n)
    return split_into_paths(edges, x, s, t, n)


def loads(edges: Sequence[Edge], paths: list[list[int]]) -> list[int]:
    """Return the number of players on each edge."""
    x = [0] * len(edges)
    for p in paths:
        for e in p:
            x[e] += 1
    return x


def rosenthal_potential(edges: Sequence[Edge], paths: list[list[int]]) -> Fraction:
    """Return Phi = sum over edges of c_e(1) + ... + c_e(x_e)."""
    x = loads(edges, paths)
    return sum((Fraction(c) for e, (_, _, costs) in enumerate(edges) for c in costs[: x[e]]), Fraction(0))


def player_costs(edges: Sequence[Edge], paths: list[list[int]]) -> list[Fraction]:
    """Return the cost of each player: the sum of c_e(x_e) over the edges of its path."""
    x = loads(edges, paths)
    return [sum((Fraction(edges[e][2][x[e] - 1]) for e in p), Fraction(0)) for p in paths]
test_symmetric_network_congestion_min_cost_flow.py 223 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symmetric-network-congestion-min-cost-flow/. The authors are listed in prov/KZRBES.jsonl.

import itertools
import random
from fractions import Fraction

import pytest

from symmetric_network_congestion_min_cost_flow import (
    _cheapest_path,
    loads,
    min_potential_flow,
    player_costs,
    rosenthal_potential,
    split_into_paths,
    symmetric_congestion_equilibrium,
)


def simple_paths(edges, s, t):
    """All simple s-t paths, as lists of edge indices, by depth-first search."""
    out = []

    def go(u, seen, path):
        if u == t:
            out.append(list(path))
            return
        for e, (a, b, _) in enumerate(edges):
            if a == u and b not in seen:
                path.append(e)
                go(b, seen | {b}, path)
                path.pop()

    go(s, {s}, [])
    return out


def is_pure_nash(edges, profile, strategies):
    costs = player_costs(edges, profile)
    for i in range(len(profile)):
        for q in strategies:
            other = profile[:i] + [q] + profile[i + 1 :]
            if player_costs(edges, other)[i] < costs[i]:
                return False
    return True


def is_simple_st_path(edges, p, s, t):
    w, seen = s, {s}
    for e in p:
        u, v, _ = edges[e]
        if u != w or v in seen:
            return False
        seen.add(v)
        w = v
    return w == t


def braess_example():
    vertices = ["s", "a", "b", "t"]
    edges = [
        ("s", "a", [2, 4, 6]),
        ("a", "t", [5, 5, 5]),
        ("s", "b", [5, 5, 5]),
        ("b", "t", [2, 4, 6]),
        ("a", "b", [0, 0, 0]),
    ]
    return vertices, edges


def test_page_example():
    vertices, edges = braess_example()
    x = min_potential_flow(vertices, edges, "s", "t", 3)
    assert x == [2, 1, 1, 2, 1]
    paths = split_into_paths(edges, x, "s", "t", 3)
    assert sorted(paths) == [[0, 1], [0, 4, 3], [2, 3]]
    assert rosenthal_potential(edges, paths) == 22
    assert sorted(player_costs(edges, paths)) == [8, 9, 9]
    assert sum(player_costs(edges, paths)) == 26
    strategies = simple_paths(edges, "s", "t")
    assert is_pure_nash(edges, paths, strategies)
    best = min(
        sum(player_costs(edges, [strategies[i] for i in prof]))
        for prof in itertools.combinations_with_replacement(range(len(strategies)), 3)
    )
    assert best == 25


def test_without_the_middle_edge():
    vertices, edges = braess_example()
    edges = edges[:4]
    paths = symmetric_congestion_equilibrium(vertices, edges, "s", "t", 3)
    assert sum(player_costs(edges, paths)) == 25
    assert rosenthal_potential(edges, paths) == 23


def random_instance(rng, nv, n, zero_prob):
    vertices = list(range(nv))
    edges = []
    for u in range(nv):
        for v in range(nv):
            if u != v and rng.random() < 0.45:
                if rng.random() < zero_prob:
                    costs = [0] * n
                else:
                    a, b = rng.randint(0, 3), rng.randint(0, 4)
                    bumps = sorted(rng.randint(0, 3) for _ in range(n))
                    q = rng.randint(1, 2)
                    costs = [Fraction(a * j + b + bumps[j - 1], q) for j in range(1, n + 1)]
                edges.append((u, v, costs))
    return vertices, edges


def test_random_against_brute_force():
    rng = random.Random(20040613)
    done = 0
    while done < 120:
        nv = rng.randint(2, 5)
        n = rng.randint(1, 4)
        vertices, edges = random_instance(rng, nv, n, 0.25)
        s, t = 0, nv - 1
        strategies = simple_paths(edges, s, t)
        if not strategies or len(strategies) > 7:
            continue
        done += 1
        paths = symmetric_congestion_equilibrium(vertices, edges, s, t, n)
        assert len(paths) == n
        assert all(is_simple_st_path(edges, p, s, t) for p in paths)
        assert is_pure_nash(edges, paths, strategies)
        phi = rosenthal_potential(edges, paths)
        best = min(
            rosenthal_potential(edges, [strategies[i] for i in prof])
            for prof in itertools.combinations_with_replacement(range(len(strategies)), n)
        )
        assert phi == best


def braess_like_instance(rng, nv, n):
    """Steep edges s-a and b-t, flat edges a-t and s-b, a cheap edge a-b, and a few random edges."""

    def steep():
        a, z = rng.randint(1, 4), rng.randint(0, 1)
        return [a * j + z * j * j for j in range(1, n + 1)]

    def flat(lo, hi):
        return [rng.randint(lo, hi)] * n

    t = nv - 1
    edges = [(0, 1, steep()), (1, t, flat(2, 9)), (0, 2, flat(2, 9)), (2, t, steep()), (1, 2, flat(0, 1))]
    for u in range(nv):
        for v in range(nv):
            if u != v and rng.random() < 0.12:
                edges.append((u, v, steep() if rng.random() < 0.5 else flat(0, 9)))
    rng.shuffle(edges)
    return list(range(nv)), edges


def test_braess_like_instances_use_backward_arcs():
    rng = random.Random(2004)
    done = backward = 0
    while done < 120:
        nv, n = rng.randint(4, 5), rng.randint(2, 4)
        vertices, edges = braess_like_instance(rng, nv, n)
        s, t = 0, nv - 1
        strategies = simple_paths(edges, s, t)
        if len(strategies) > 9:
            continue
        done += 1
        x = [0] * len(edges)
        used = False
        for _ in range(n):
            path = _cheapest_path(vertices, edges, x, s, t, n)
            used = used or any(d == -1 for _, d in path)
            for e, d in path:
                x[e] += d
        backward += used
        assert x == min_potential_flow(vertices, edges, s, t, n)
        paths = split_into_paths(edges, x, s, t, n)
        assert all(is_simple_st_path(edges, p, s, t) for p in paths)
        assert is_pure_nash(edges, paths, strategies)
        best = min(
            rosenthal_potential(edges, [strategies[i] for i in prof])
            for prof in itertools.combinations_with_replacement(range(len(strategies)), n)
        )
        assert rosenthal_potential(edges, paths) == best
    assert backward >= 10


def test_flow_is_conserved():
    rng = random.Random(7)
    for _ in range(60):
        vertices, edges = random_instance(rng, 5, 3, 0.5)
        if not simple_paths(edges, 0, 4):
            continue
        x = min_potential_flow(vertices, edges, 0, 4, 3)
        for w in vertices:
            net = sum(x[e] for e, (u, _, _) in enumerate(edges) if u == w) - sum(
                x[e] for e, (_, v, _) in enumerate(edges) if v == w
            )
            assert net == (3 if w == 0 else -3 if w == 4 else 0)
        paths = split_into_paths(edges, x, 0, 4, 3)
        assert all(a <= b for a, b in zip(loads(edges, paths), x))


def test_zero_cost_cycle_is_removed():
    vertices = ["s", "a", "b", "t"]
    edges = [("s", "a", [1, 1]), ("a", "b", [0, 0]), ("b", "a", [0, 0]), ("a", "t", [1, 1])]
    x = [2, 1, 1, 2]
    paths = split_into_paths(edges, x, "s", "t", 2)
    assert paths == [[0, 3], [0, 3]]


def test_errors():
    vertices = ["s", "t"]
    with pytest.raises(ValueError):
        symmetric_congestion_equilibrium(vertices, [("s", "t", [3, 2])], "s", "t", 2)
    with pytest.raises(ValueError):
        symmetric_congestion_equilibrium(vertices, [("s", "t", [-1, 2])], "s", "t", 2)
    with pytest.raises(ValueError):
        symmetric_congestion_equilibrium(vertices, [("t", "s", [1, 2])], "s", "t", 2)
    with pytest.raises(ValueError):
        symmetric_congestion_equilibrium(vertices, [("s", "t", [1])], "s", "t", 2)

History

Rosenthal defined congestion games in 1973 and showed that a minimizer of his potential is a pure Nash equilibrium. Fabrikant, Papadimitriou and Talwar asked in 2004 how hard it is to find one. They showed that in the symmetric network case the minimizer is a min-cost flow and can be found in polynomial time, and that the problem is PLS-complete for general congestion games, for symmetric congestion games and for asymmetric network games. Ackermann, Roglin and Vocking later showed that matroid congestion games are also easy, because best-response dynamics converges after polynomially many steps there.

References

  1. Alex Fabrikant, Christos Papadimitriou and Kunal Talwar, The complexity of pure Nash equilibria, Proceedings of the 36th Annual ACM Symposium on Theory of Computing (STOC 2004), 604-612, the polynomial algorithm for symmetric network congestion games by reduction to min-cost flow, and the PLS-completeness of the general case
  2. Robert W. Rosenthal, A class of games possessing pure-strategy Nash equilibria, International Journal of Game Theory 2 (1973), 65-67, the potential function whose minimizers are pure Nash equilibria
  3. Ravindra K. Ahuja, Thomas L. Magnanti and James B. Orlin, Network Flows, Theory, Algorithms, and Applications, Prentice Hall, 1993, Chapter 9 (the successive shortest path algorithm) and Chapter 14 (convex cost flows)
  4. Tim Roughgarden, Twenty Lectures on Algorithmic Game Theory, Cambridge University Press, 2016, Lecture 19 (pure Nash equilibria, PLS-completeness and the tractable symmetric routing case)

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