Algorithmadvanced
Devanur-Papadimitriou-Saberi-Vazirani algorithm
Also called DPSV algorithm, primal-dual Fisher market algorithm.
Computes an equilibrium of a linear Fisher market in polynomial time by raising prices and computing max flows in a primal-dual way.
- Time
- O(m^4 (log m + m log U + log M)) worst
- Space
- O(n m) extra
- Where
- M = the total budget; U = the largest utility; m = the number of goods; n = the number of buyers
- Model
- Real RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nikhil R. Devanur, Christos H. Papadimitriou, Amin Saberi, Vijay V. Vazirani, 2002
The DPSV algorithm, by Devanur, Papadimitriou, Saberi and Vazirani, computes the exact equilibrium of a Fisher market with linear utilities. It was the first combinatorial polynomial time algorithm for this problem. It is a primal-dual algorithm for the Eisenberg-Gale program: the prices are the dual variables, the money that flows from buyers to goods is the primal solution, and the algorithm is guided by the KKT conditions of the program instead of by LP duality. Prices start low and only go up. At all times, every good can be sold to buyers who like it best per unit of money, and the only defect is that buyers may keep money that they cannot spend. A maximum flow tells which sets of goods are already as expensive as they can be, and the algorithm raises the prices of the other goods until the surplus money is gone. The simple version below is easy to state and is exact, but its proven bound is exponential; the journal version adds balanced flows to get a polynomial bound, and Orlin's algorithm later made the bound strongly polynomial.
In plain words
Each buyer has money and likes each good to some degree. At given prices, a buyer only wants the goods that give her the most pleasure for each coin. Start with prices so low that every buyer could buy everything she wants, and make sure every good is wanted by someone. Then raise prices slowly, all by the same factor. At some point a group of goods becomes exactly as expensive as the total money of the buyers who want them. Those goods and their buyers are done, so freeze them and keep raising the other prices. If a buyer who is still active starts to like a frozen good as much as her own, wake up that frozen group again. When every good is frozen, every coin is spent and every good is sold.
The problem
There are buyers and goods, with one unit of each good. Buyer has a budget and a linear utility with . Every buyer likes some good and every good is liked by some buyer. Find prices and an allocation in which every buyer spends her whole budget on goods of maximum bang per buck and every good is sold completely. This is the Fisher market equilibrium, and the prices are unique.
At prices , let . The equality graph has an edge when . The network has arcs from a source to each good with capacity , from good to buyer with infinite capacity on every equality edge, and from buyer to a sink with capacity . For a set of goods, is the set of buyers joined to by an equality edge, and . The algorithm keeps the Invariant of the paper: the cut that separates the source from everything else is a minimum cut of . By the max-flow min-cut theorem, this holds exactly when for every set of goods (Lemma 5.1 of the paper). A set is tight when . Prices are an equilibrium exactly when the whole set of goods is also tight, so that a maximum flow saturates both the source arcs and the sink arcs.
The algorithm
The goods are split into active goods and frozen blocks. Each frozen block comes with its buyers, who are also frozen. The equality graph of the active part uses only active buyers, with taken over active goods. All arithmetic is exact.
DPSV(utilities u, budgets e)- 1
p_j ← min_i e_i / m for every good j - 2
p_j ← max_i u_ij / α_i for every good j, where α_i = max_k u_ik / p_k at the prices of L1 - 3
all goods and all buyers are active; no block is frozen - 4
while some good is active do - 5
(x1, S) ← the least factor x ≥ 1 at which a set of active goods goes tight, and the largest such set S - 6
x2 ← min over active buyers i and frozen goods j with u_ij > 0 of α_i p_j / u_ij (∞ if none) - 7
multiply the price of every active good by x = min(x1, x2) - 8
if x2 < x1 then make the frozen block that contains the good of x2 active again, with its buyers - 9
else freeze S with its buyers Γ(S) as a new block - 10
compute a maximum flow in N(p) and read the money that buyer i spends on good j from it - 11
return p and the money flows
Line L1 makes every price so low that the goods together cost at most the smallest budget. Line L2 lowers the price of each good until some buyer has it among her best buys, so every good has an edge; prices only go down in line L2, and the Invariant holds because every set of goods costs at most and has at least one buyer.
Line L5 is Section 6 of the paper. Raising the active prices by a factor multiplies by and keeps the equality graph of the active part, so a set goes tight at , and is the least of these ratios. Start with the set of all active goods and . Compute a maximum flow in the network of with the source arcs scaled by . If it has value , return . Otherwise, replace by the goods on the source side of the minimum cut whose source side is largest (the nodes that cannot reach the sink in the residual graph), and repeat. Each round removes at least one good (Lemma 6.3 of the paper), so line L5 costs at most maximum flows (Lemma 6.4).
Line L6 finds the first factor at which an active buyer starts to like a frozen good as much as her best active goods. Line L8 is the event in which this happens before any set goes tight; line L9 is the event in which a set goes tight first, and it also covers ties.
Example
Three buyers and three goods with , , and budgets . Line L1 sets every price to , and line L2 keeps it: buyer 1 likes good 2 best, buyer 2 likes good 1 best, and buyer 3 likes good 3 best.
| iteration | active goods | and the largest tight set | event | prices after | |
|---|---|---|---|---|---|
| 1 | 1, 2, 3 | , goods with buyers | none | freeze at factor | |
| 2 | 3 | , good with buyer | , buyer 3 and good 1 | unfreeze at factor | |
| 3 | 1, 2, 3 | , all goods with all buyers | none | freeze all at factor |
In iteration 1 the set has ratio , the set has ratio , and all goods together have ratio . In iteration 2, buyer 3 has bang per buck on good 3, and goods 1 and 2 give her per unit of money; when good 3 costs twice as much, they tie, so . In iteration 3, buyer 3 is indifferent between all three goods, and all goods together cost while the budgets add up to , so the ratio is . The flow of line L10 lets buyer 1 spend on good 2, buyer 2 spend on good 1, and buyer 3 spend , and on goods 1, 2 and 3. In units, buyer 1 gets of good 2, buyer 2 gets of good 1, and buyer 3 gets of goods 1 and 2 and all of good 3, and every buyer's bang per buck on her goods is her maximum.
For the market , with budgets , line L1 gives prices , the whole set goes tight at factor , and the algorithm returns , with each buyer spending her budget on her favorite good.
Correctness
The proof is in proofs/correctness.md. It keeps four invariants at the start of each iteration: the Invariant holds for the active part; no active buyer strictly prefers a frozen good to her best active goods; every frozen block is tight, satisfies the Invariant on its own, and its buyers like its goods best among all goods; and all prices are positive. Line L5 returns the true least factor and the largest tight set, because every set that goes tight first stays on the source side of every minimum cut. Prices never fall. After line L9 the remaining active part has no tight set, which bounds the number of iterations at a fixed price vector; and the prices of goods at the moments they are frozen or at which an unfreeze happens come from a finite set fixed by and , which bounds the number of iterations that raise prices. At the end every block is tight and every buyer is frozen, so the flow of line L10 spends every budget on best goods and sells every good.
Proof: The simple DPSV algorithm keeps its invariants, terminates, and returns the Fisher market equilibriumfull
Fix buyers with budgets , goods with one unit each, and utilities , where every buyer likes some good and every good is liked by some buyer. All arithmetic is exact. Write and .
At the start of an iteration, let be the set of active goods and the set of active buyers. For let . The active graph has an edge for , with , and is the set of buyers joined to in it. For a frozen block (goods , buyers ) and a buyer , let over all goods, and for the buyers with for some .
Invariants. At line L4:
- (I0) All prices are positive. and the blocks partition the goods, and the blocks partition the buyers, and for every .
- (I1) for every .
- (I2) for every and every frozen good .
- (I3) Every block has and for every , and every attains on some good of .
Claim 1 (start). The invariants hold at the first iteration.
Proof. Let be the price of line L1 and . Line L2 sets , which is positive because some buyer likes , and at most because . For every buyer, the maximum of is still (a good of maximum utility keeps price , and no ratio rises above by the choice of ), and every good has an edge to the buyer that attains its maximum. So for every nonempty , is nonempty and . No block is frozen, so (I2) and (I3) are empty.
Claim 2 (line L5). Let . Line L5 makes at most rounds and returns and the largest set with . By (I1), .
Proof. For a set of goods and a factor , the network of line L5 has source arcs of capacity for , infinite arcs on the edges of , and sink arcs of capacity for . A cut whose source side contains the goods must contain to be finite, and the cheapest such cut has capacity . The function is submodular in , because is a coverage function.
Call a set critical if its ratio equals . Critical sets are closed under union: for critical , , and (trivially if the intersection is empty), so , with equality by the definition of . So there is a largest critical set .
Suppose the current contains , which holds at the start since . Let . The cut has capacity , the same as . If the maximum flow has this value, then for all , that is , so , hence ; then is critical, and since , . Line L5 returns the right pair.
Otherwise , and let be the goods of any minimum cut. Then , since is not minimum, and . Indeed, let and suppose . By the choice of , , so , that is . By submodularity, , which contradicts the minimality of . So the new is a proper subset of the old one and still contains . Each round removes a good, so there are at most rounds.
Claim 3 (line L6). , and when it is finite, raising the active prices by any keeps (with the new prices and the new ) for all and frozen .
Proof. By (I2), for each pair in line L6. Multiplying the active prices by divides every by and keeps for frozen , so .
Raising all active prices by one factor keeps the active graph: every with and every are divided by the same number. Frozen buyers are unaffected, because their is attained on frozen goods whose prices stay, and active goods only get dearer.
Claim 4 (line L9 keeps the invariants, and the new active part has no tight set). Suppose . After line L9, the invariants hold, and every nonempty of the new active goods has , where is the new active graph.
Proof. After line L7, every has , with equality for , the largest such set (Claim 2). Let be frozen with .
(I3) for the new block: . For , and . A buyer has an edge into , so is attained on ; by Claim 3, no frozen good beats ; so is attained on , and for . Old blocks keep (I3) by the remark after Claim 3.
New active buyers and goods . A buyer has no edge into , so her maximum over is attained in : her is unchanged and positive, and her edges are the same. So for . Then , and if had , then , so would be a tight set larger than . Hence , which gives (I1).
(I2): for and , because is not an edge; for older frozen goods it is Claim 3. (I0) is clear.
Claim 5 (line L8 keeps the invariants). Suppose , attained by and a good of the block . After line L8, the invariants hold, and every set of the new active goods with in the new active graph is a subset of .
Proof. After line L7, every nonempty has . By Claim 3, (I2) holds at the new prices, with equality for .
The new active goods are and buyers . For , the maximum over equals by (I2), so her old edges stay and she may gain edges into , among them . For , the maximum over is , attained in by (I3), so her block edges stay. Take with and . Then contains the disjoint sets and , so , which is (I1). Equality needs , and it fails if , because then adds .
(I2) for the remaining blocks: buyers of by Claim 3, buyers of because is the maximum over all goods. (I3) for the remaining blocks holds by the remark after Claim 3. (I0) is clear.
Claim 6 (termination). The loop of lines L4 to L9 ends after finitely many iterations.
Proof. Every factor is at least (Claims 2 and 3), so prices never fall. Call an iteration flat if its factor is and rising otherwise.
Flat iterations. By Claim 4, after a freeze the next is above , so the next iteration is not a flat freeze. By Claim 5, a flat freeze right after an unfreeze of the block freezes fewer goods than has. At the very start there is no preceding unfreeze. So in a maximal run of consecutive flat iterations, every freeze except possibly the first is right after an unfreeze in the run. Group the run, after the possible first freeze, into units: an unfreeze alone, or an unfreeze followed by a freeze. Each unit lowers the number of frozen goods by at least , and the first freeze raises it by at most , so a run has at most units and at most iterations.
Rising iterations. Let be the set of all numbers of the form , where is a set of goods, a set of buyers, and a vector on obtained by choosing a spanning tree of a bipartite graph on whose edges have and setting along the tree by from one root with . is finite. When line L9 freezes with , the components of the equality graph on split and , each satisfies , and they add up to equality, so each component is tight; along its edges , so every price in is in . A frozen price does not change, so frozen goods always have prices in . When line L8 fires at a rising factor, the buyer ties her best active good with , so lies in the finite set . At a rising freeze, the prices of lie in . So each rising iteration leaves some good whose price it has just strictly raised at a value in . For a fixed good, these values strictly increase from one such iteration to the next, since prices never fall. So there are at most rising iterations.
Between two rising iterations there is at most one run of flat iterations, so the loop makes at most iterations.
The bound is far from sharp. With integer data, Lemma 7.1 of the paper bounds the denominators of the prices in a newly tight set by , and Corollary 7.5 bounds the phases of its Algorithm 1 by .
Claim 7 (output). The returned is the Fisher market equilibrium: every buyer spends exactly , only on goods with , and every good receives exactly , so it is sold completely.
Proof. The loop ends with . In the last iteration, line L9 froze all active goods , and every active buyer had an edge into because is attained there, so all buyers are frozen too. By (I3), every block is tight, its buyers attain their global maximum on , and for . The edges of are equality edges of . By the max-flow min-cut theorem (Lemma 5.1 of the paper), the network of the block has a flow that saturates every source arc of , of total , so it saturates every sink arc of too. The blocks partition goods and buyers, so has a flow of value , and the maximum flow of line L10 saturates all source and sink arcs. Its flow from good to buyer is the money she spends on , on equality edges only. A buyer who spends her whole budget only on goods of maximum bang per buck has an optimal bundle, so this is an equilibrium. The equilibrium prices of a linear Fisher market are unique (see the Eisenberg-Gale program).
Complexity
Each iteration costs at most maximum flows on nodes and at most arcs. With Edmonds-Karp, as in the implementation, one flow costs exact operations on rationals. With integer utilities and budgets, Corollary 7.5 of the paper bounds its Algorithm 1 by at most phases and max-flow computations, where . This bound is exponential in , and the paper does not know a polynomial bound for this version.
The balanced-flow version of Section 8 raises only the prices of goods next to buyers with large surplus, measured in a flow that minimizes the norm of the surplus vector. It needs max-flow computations, which is polynomial in the bit length of the input. It is not strongly polynomial: the number of flows depends on and . The extra space is for the network and the flows.
Properties
- Prices only rise. Every factor in line L7 is at least . Equality edges still appear and disappear, because the bang per buck of a buyer falls when her goods get dearer.
- Exact and rational. With rational data, every price is rational, and the output is exact. Lemma 7.1 of the paper bounds the denominators of the prices of a newly tight set by , which also shows that the equilibrium has polynomial bit length.
- Primal-dual with KKT conditions. At all times buyers spend only on equality edges and no buyer has a better good than her edges; only the condition that each buyer spends her whole budget is relaxed, and it holds at the end.
- Deterministic. The output is the unique equilibrium price vector, with one equilibrium allocation.
Variants and improvements
- Balanced flows. The polynomial version of Section 8 measures progress by the norm of the surplus vector, which falls by a polynomial factor in each phase.
- Strongly polynomial. Orlin's algorithm (2010) combines the same flow network with scaling and finds the equilibrium with a number of operations that depends only on and .
- Other utilities. The paper and the AGT book chapter describe extensions of the primal-dual approach, for example to spending constraint utilities (Vazirani). For utilities that are not linear, some market problems are PPAD-hard; see PPAD-hardness of market equilibria.
- Dynamics instead of algorithms. Proportional response dynamics and tatonnement approach the same equilibrium without a central planner, but only in the limit.
When to use it
Use it when an exact equilibrium of a linear Fisher market is needed and the market is small or medium sized, and when exact rational prices matter more than speed. It is also a good model for primal-dual algorithms that are guided by KKT conditions. For large markets where an approximate answer is enough, a convex solver on the Eisenberg-Gale program or proportional response dynamics is simpler. For guaranteed worst-case bounds, use the balanced-flow version or Orlin's algorithm.
Pitfalls
- Starting with prices that are too high in line L1 breaks the Invariant before the first iteration: a buyer who wants a set of goods may not be able to pay for it, and later tight sets are then wrong. The prices of line L1 must cost at most the smallest budget together.
- Skipping line L2 leaves goods with no equality edge. Such a good has no buyer, so the set that contains only it violates .
- Raising all prices in line L7, frozen ones included, breaks the tight blocks: their price then exceeds the money of their buyers.
- Freezing in line L9 without its buyers leaves buyers whose money is already used up by in the active part, so their budgets are counted twice in later tight sets.
- Floating point arithmetic in lines L2, L5 and L6 makes the equality tests fail at random, so edges are lost. Use exact rationals.
- Reading the allocation from the last flow of line L5 is wrong, because that flow covers only the last active part. Line L10 computes a fresh flow over all goods.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dpsv-algorithm/. The authors are listed in prov/MZRKQA.jsonl.
"""The primal-dual algorithm of Devanur, Papadimitriou, Saberi and Vazirani for linear Fisher markets.
Buyers are 0, ..., n - 1 and goods are 0, ..., m - 1, with one unit of each good. u[i][j] >= 0
is the utility of buyer i for all of good j, and e[i] > 0 is the budget of buyer i. Every buyer
must like some good and every good must be liked by some buyer. This is the simple version of
the algorithm (Algorithm 1 of the paper): prices only go up, by a common factor on the active
goods, until a set of goods goes tight and is frozen. All numbers are exact Fractions.
"""
from collections import deque
from fractions import Fraction
def max_flow(num_nodes, cap, s, t):
"""Edmonds-Karp maximum flow. cap maps (a, b) to a capacity. Returns the flow value, the
flow on each arc of cap, and the residual capacities."""
res = {}
adj = [[] for _ in range(num_nodes)]
for (a, b), c in cap.items():
if (a, b) not in res and (b, a) not in res:
adj[a].append(b)
adj[b].append(a)
res[(a, b)] = res.get((a, b), Fraction(0)) + c
res.setdefault((b, a), Fraction(0))
value = Fraction(0)
while True:
prev = {s: None}
queue = deque([s])
while queue and t not in prev:
a = queue.popleft()
for b in adj[a]:
if b not in prev and res[(a, b)] > 0:
prev[b] = a
queue.append(b)
if t not in prev:
break
path, b = [], t
while prev[b] is not None:
path.append((prev[b], b))
b = prev[b]
push = min(res[arc] for arc in path)
for a, b in path:
res[(a, b)] -= push
res[(b, a)] += push
value += push
flow = {arc: c - res[arc] for arc, c in cap.items()}
return value, flow, res, adj
def reaches_sink(num_nodes, res, adj, t):
"""The nodes that can reach t in the residual graph."""
seen = {t}
queue = deque([t])
while queue:
b = queue.popleft()
for a in adj[b]:
if a not in seen and res[(a, b)] > 0:
seen.add(a)
queue.append(a)
return seen
def bang(u, p, i, goods):
"""The maximum bang per buck of buyer i over the given goods."""
return max(Fraction(u[i][j]) / p[j] for j in goods)
def tight_set(u, e, p, goods, buyers, edges):
"""Section 6 of the paper: the least factor x >= 1 at which a set of the given goods goes
tight, and the largest such set S. A set S is tight at x when x p(S) = e(Gamma(S)), where
Gamma(S) is the set of buyers joined to S by an edge."""
S = set(goods)
while True:
nbrs = {i for (i, j) in edges if j in S}
x = sum(e[i] for i in nbrs) / sum(p[j] for j in S)
m = len(u[0])
src, snk = 0, len(u) + m + 1
big = sum(e) * (x + 1) + 1 # larger than any finite cut, so never cut
cap = {}
for j in S:
cap[(src, 1 + j)] = x * p[j]
for i, j in edges:
if j in S:
cap[(1 + j, 1 + m + i)] = big
for i in nbrs:
cap[(1 + m + i, snk)] = e[i]
value, _, res, adj = max_flow(snk + 1, cap, src, snk)
if value == sum(e[i] for i in nbrs):
return x, S
to_sink = reaches_sink(snk + 1, res, adj, snk)
# the largest minimum cut: every node that cannot reach the sink stays on the source side
S = {j for j in S if 1 + j not in to_sink}
def equality_flow(u, e, p):
"""A maximum flow in the network N(p): source to good j with capacity p_j, good j to buyer i
on every equality edge, buyer i to sink with capacity e_i. Returns (value, x) with x[i][j]
the money that buyer i spends on good j."""
n, m = len(u), len(u[0])
src, snk = 0, n + m + 1
alpha = [bang(u, p, i, range(m)) for i in range(n)]
cap = {}
for j in range(m):
cap[(src, 1 + j)] = p[j]
for i in range(n):
cap[(1 + m + i, snk)] = e[i]
for j in range(m):
if u[i][j] > 0 and Fraction(u[i][j]) / p[j] == alpha[i]:
cap[(1 + j, 1 + m + i)] = sum(e) + 1
value, flow, _, _ = max_flow(snk + 1, cap, src, snk)
x = [[flow.get((1 + j, 1 + m + i), Fraction(0)) for j in range(m)] for i in range(n)]
return value, x
def dpsv(u, e, trace=None):
"""Return equilibrium prices p and money spent x[i][j] for the linear Fisher market (u, e).
If trace is a list, one tuple (factor, event, goods) is appended per raise of prices."""
n, m = len(u), len(u[0])
e = [Fraction(b) for b in e]
p = [min(e) / m for _ in range(m)] # @line L1
alpha = [bang(u, p, i, range(m)) for i in range(n)]
for j in range(m): # @line L2
p[j] = max(Fraction(u[i][j]) / alpha[i] for i in range(n) if u[i][j] > 0)
active_goods = set(range(m)) # @line L3
frozen = [] # list of (goods, buyers) of frozen components
while active_goods: # @line L4
frozen_buyers = set().union(*[b for _, b in frozen]) if frozen else set()
active_buyers = [i for i in range(n) if i not in frozen_buyers]
a = {i: bang(u, p, i, active_goods) for i in active_buyers}
edges = [(i, j) for i in active_buyers for j in active_goods
if u[i][j] > 0 and Fraction(u[i][j]) / p[j] == a[i]]
x1, S = tight_set(u, e, p, active_goods, active_buyers, edges) # @line L5
x2, edge2 = None, None
for i in active_buyers: # @line L6
for j in range(m):
if j not in active_goods and u[i][j] > 0:
x = a[i] * p[j] / u[i][j]
if x2 is None or x < x2:
x2, edge2 = x, (i, j)
x = x1 if x2 is None or x1 <= x2 else x2
for j in active_goods: # @line L7
p[j] *= x
if x2 is not None and x2 < x1: # @line L8
k = next(c for c, (goods, _) in enumerate(frozen) if edge2[1] in goods)
goods, _ = frozen.pop(k)
active_goods |= goods
if trace is not None:
trace.append((x, "unfreeze", sorted(goods)))
else: # @line L9
buyers = {i for (i, j) in edges if j in S}
frozen.append((set(S), buyers))
active_goods -= S
if trace is not None:
trace.append((x, "freeze", sorted(S)))
value, x = equality_flow(u, e, p) # @line L10
return p, x # @line L11
test_dpsv_algorithm.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dpsv-algorithm/. The authors are listed in prov/MZRKQA.jsonl.
import random
import unittest
from fractions import Fraction
from itertools import combinations
from dpsv_algorithm import dpsv
# The example of the page: 3 buyers and 3 goods.
EXAMPLE_U = [[1, 4, 3], [4, 2, 1], [1, 1, 2]]
EXAMPLE_E = [1, 1, 3]
def is_equilibrium(u, e, p, x):
"""Exact check: every buyer spends all her money, only on goods of maximum bang per buck,
and every good is sold out (all prices are positive)."""
n, m = len(u), len(u[0])
if any(q <= 0 for q in p):
return False
for i in range(n):
best = max(Fraction(u[i][j]) / p[j] for j in range(m))
if sum(x[i]) != e[i]:
return False
for j in range(m):
if x[i][j] < 0 or (x[i][j] > 0 and Fraction(u[i][j]) / p[j] != best):
return False
return all(sum(x[i][j] for i in range(n)) == p[j] for j in range(m))
def brute_force_prices(u, e):
"""All equilibrium price vectors, by trying every set of spending edges as the support:
the prices on a connected support are fixed by the utility ratios and by the budgets."""
n, m = len(u), len(u[0])
all_edges = [(i, j) for i in range(n) for j in range(m) if u[i][j] > 0]
found = set()
for k in range(1, len(all_edges) + 1):
for H in combinations(all_edges, k):
p = prices_from_support(u, e, H)
if p is None:
continue
x = support_flow(u, e, p, H)
if x is not None and is_equilibrium(u, e, p, x):
found.add(tuple(p))
return found
def prices_from_support(u, e, H):
n, m = len(u), len(u[0])
rel = {} # node -> price (goods) or bang per buck (buyers), up to a factor per component
comps = []
for start in range(m):
if ("g", start) in rel:
continue
rel[("g", start)] = Fraction(1)
stack, comp = [("g", start)], [("g", start)]
while stack:
kind, a = stack.pop()
for i, j in H:
if kind == "g" and j == a:
nxt, val = ("b", i), Fraction(u[i][j]) / rel[("g", j)]
elif kind == "b" and i == a:
nxt, val = ("g", j), Fraction(u[i][j]) / rel[("b", i)]
else:
continue
if nxt in rel:
if rel[nxt] != val:
return None
else:
rel[nxt] = val
stack.append(nxt)
comp.append(nxt)
comps.append(comp)
if any(("b", i) not in rel for i in range(n)):
return None
p = [None] * m
for comp in comps:
money = sum(Fraction(e[a]) for kind, a in comp if kind == "b")
if money == 0:
return None
scale = money / sum(rel[(kind, a)] for kind, a in comp if kind == "g")
for kind, a in comp:
if kind == "g":
p[a] = rel[(kind, a)] * scale
return p
def support_flow(u, e, p, H):
"""Spend along the support H by solving the flow on a forest (peel leaves); None if H has a
cycle or the flow would be negative."""
n, m = len(u), len(u[0])
if len(H) > n + m - 1:
return None
x = [[Fraction(0)] * m for _ in range(n)]
left = set(H)
need = {("b", i): Fraction(e[i]) for i in range(n)}
need.update({("g", j): p[j] for j in range(m)})
while left:
deg = {}
for i, j in left:
deg[("b", i)] = deg.get(("b", i), 0) + 1
deg[("g", j)] = deg.get(("g", j), 0) + 1
leaf = next((v for v, d in deg.items() if d == 1), None)
if leaf is None:
return None
(i, j) = next(ed for ed in left if ("b", ed[0]) == leaf or ("g", ed[1]) == leaf)
amount = need[leaf]
if amount < 0:
return None
x[i][j] = amount
need[("b", i)] -= amount
need[("g", j)] -= amount
left.discard((i, j))
if any(v != 0 for v in need.values()):
return None
return x
def random_market(rng, n, m):
while True:
u = [[rng.choice([0, 1, 2, 3, 4, 5]) for _ in range(m)] for _ in range(n)]
if all(any(row) for row in u) and all(any(u[i][j] for i in range(n)) for j in range(m)):
return u, [rng.randint(1, 4) for _ in range(n)]
class TestDPSV(unittest.TestCase):
def test_check_value(self):
p, x = dpsv([[2, 1], [1, 2]], [1, 1])
self.assertEqual(p, [1, 1])
self.assertEqual(x, [[1, 0], [0, 1]])
def test_example(self):
trace = []
p, x = dpsv(EXAMPLE_U, EXAMPLE_E, trace)
self.assertEqual(p, [Fraction(5, 4), Fraction(5, 4), Fraction(5, 2)])
self.assertTrue(is_equilibrium(EXAMPLE_U, EXAMPLE_E, p, x))
self.assertEqual(x, [[0, 1, 0], [1, 0, 0], [Fraction(1, 4), Fraction(1, 4), Fraction(5, 2)]])
self.assertEqual(trace, [(Fraction(3), "freeze", [0, 1]), (Fraction(2), "unfreeze", [0, 1]),
(Fraction(5, 4), "freeze", [0, 1, 2])])
def test_one_buyer(self):
# A single buyer must find every good a best buy, so prices are proportional to utilities.
p, x = dpsv([[1, 3, 2]], [6])
self.assertEqual(p, [1, 3, 2])
self.assertEqual(x, [[1, 3, 2]])
def test_random_against_brute_force(self):
rng = random.Random(7)
for _ in range(40):
n, m = rng.randint(1, 3), rng.randint(1, 3)
u, e = random_market(rng, n, m)
p, x = dpsv(u, e)
self.assertTrue(is_equilibrium(u, e, p, x))
self.assertEqual(brute_force_prices(u, e), {tuple(p)})
def test_prices_never_fall(self):
rng = random.Random(11)
for _ in range(30):
u, e = random_market(rng, 3, 3)
trace = []
dpsv(u, e, trace)
self.assertTrue(all(f >= 1 for f, _, _ in trace))
if __name__ == "__main__":
unittest.main()
History
Devanur, Papadimitriou, Saberi and Vazirani presented the algorithm at FOCS 2002. Their first analysis had a subtle flaw, and the journal version (Journal of the ACM, 2008) fixed it with balanced flows and proved a polynomial bound. It was the first combinatorial polynomial time algorithm for the linear Fisher market, and it showed that the primal-dual method works for a convex program whose KKT conditions mix primal and dual variables. The paper stated a strongly polynomial algorithm as an open question, and Orlin answered it in 2010.
References
- Nikhil R. Devanur, Christos H. Papadimitriou, Amin Saberi and Vijay V. Vazirani, Market equilibrium via a primal-dual algorithm for a convex program, Journal of the ACM 55(5), Article 22 (2008), Section 3 (the network N(p) and the Invariant), Section 5 (Algorithm 1 and Lemma 5.1), Section 6 (Lemma 6.4, finding the tight set), Section 7 (Lemma 7.1 and Corollary 7.5), Section 8 (balanced flows and the polynomial bound)
- Noam Nisan, Tim Roughgarden, Eva Tardos and Vijay V. Vazirani (eds.), Algorithmic Game Theory, Cambridge University Press, 2007, Chapter 5, Vijay V. Vazirani, Combinatorial algorithms for market equilibria
- James B. Orlin, Improved algorithms for computing Fisher's market clearing prices, STOC 2010, 291-300, the whole paper (a strongly polynomial algorithm, which answers the open question that the DPSV paper states)
- Edmund Eisenberg and David Gale, Consensus of subjective probabilities: the pari-mutuel method, Annals of Mathematical Statistics 30(1), 165-168 (1959), the whole paper (the convex program whose KKT conditions the algorithm satisfies)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 MZRKQA Edit this page History Report an error Markdown