Algorithm Search⌘K

Algorithmadvanced

Hylland-Zeckhauser mechanism

Also called HZ mechanism, pseudo-market for assignment.

Assigns probability shares of objects by a competitive equilibrium with equal budgets over cardinal utilities. Approximate equilibria are PPAD-complete; the exact case is open.

Time
O(g^n n T) worst
Space
O(n^2) extra
Where
T = the time of one LP solve with at most n^2 variables; g = the number of grid values for one price; n = the number of agents and of objects
Properties
deterministicnot exactiterative
Origin
Aanund Hylland, Richard Zeckhauser, 1979

The Hylland-Zeckhauser mechanism solves the house allocation problem with cardinal utilities. Each of nn agents gets one unit of fake money, and each of nn objects gets a price. Agents buy probability shares of objects: each agent buys one unit of shares in total, the best bundle it can afford, and among the best bundles the cheapest one. Prices are set so that every object is sold exactly once. This is a competitive equilibrium, and the result is a bistochastic matrix that a Birkhoff-von Neumann decomposition turns into a lottery over matchings. Hylland and Zeckhauser (1979) proved that an equilibrium exists and that its allocation is Pareto efficient, and with equal budgets it is also envy-free. No efficient algorithm is known. Finding an approximate equilibrium is PPAD-complete, and the complexity of the exact problem is open. The code on this page is a toy: it tries the prices on a grid.

In plain words

A school must give nn rooms to nn students, one each, and it wants to be fair. It gives each student 1 coin of play money. The rooms get prices, and a student can buy a mix of chances, for example half a chance of room A and half of room C. A popular room gets a high price, so a student who wants it a lot pays for a large chance of it, and a student who cares less takes a sure chance of a cheap room. When the prices are right, all chances of every room are sold. Then the school draws the real rooms by lottery from these chances.

The problem

There are nn agents and nn objects, one unit of each. Agent ii has utility uij≥0u_{ij} \ge 0 for object jj, and its expected utility for a row of shares xix_i is ui⋅xi=∑juijxiju_i \cdot x_i = \sum_j u_{ij} x_{ij}. A price vector p≥0p \ge 0 and an allocation xx, an nn by nn matrix with xij≥0x_{ij} \ge 0, form an HZ equilibrium when:

  1. every agent gets one unit, ∑jxij=1\sum_j x_{ij} = 1, and every object is sold once, ∑ixij=1\sum_i x_{ij} = 1;
  2. xix_i is in the budget set {y≥0:∑jyj=1, p⋅y≤1}\{y \ge 0 : \sum_j y_j = 1,\ p \cdot y \le 1\} and maximizes ui⋅yu_i \cdot y over it;
  3. among those maximizers, xix_i has the least cost p⋅yp \cdot y.

Condition 3 is needed for efficiency: without it an agent could pay for shares that give it nothing more, and the money would be wasted. Some object must cost at most 1, or the budget sets are empty.

The prices can be normalized. If the smallest price mm is below 1, then p′=(p−m)/(1−m)p' = (p - m)/(1 - m) gives the same budget sets, since ∑jyj=1\sum_j y_j = 1 turns p⋅y≤1p \cdot y \le 1 into p′⋅y≤1p' \cdot y \le 1, and it orders the costs in the same way, so (p′,x)(p', x) is also an equilibrium. If m=1m = 1, then every share bought costs exactly 1, all prices are 1, every agent buys only top objects, and p=0p = 0 also works. So every equilibrium allocation has prices with smallest entry 0.

The algorithm

  1. HZ-GRID-SEARCH(u, k, pmax)
  2. 1for each price vector p with entries in {0, 1/k, 2/k, ..., pmax} and smallest entry 0 do
  3. 2for each agent i do
  4. 3U_i ← max { u_i · y : y ≥ 0, Σ_j y_j = 1, p · y ≤ 1 }
  5. 4C_i ← min { p · y : y ≥ 0, Σ_j y_j = 1, p · y ≤ 1, u_i · y = U_i }
  6. 5find x ≥ 0 with Σ_j x_ij = 1, u_i · x_i = U_i and p · x_i = C_i for each i, and Σ_i x_ij = 1 for each j
  7. 6if x exists then return (p, x)
  8. 7return none

This is a toy, not an efficient algorithm. For a fixed price vector, the demand set of agent ii, the set of rows that satisfy conditions 2 and 3, is the face {y≥0:∑jyj=1, ui⋅y=Ui, p⋅y=Ci}\{y \ge 0 : \sum_j y_j = 1,\ u_i \cdot y = U_i,\ p \cdot y = C_i\}. Lines L3 and L4 find UiU_i and CiC_i with two small linear programs, and line L5 checks with one more linear program whether the demand sets can be chosen so that every object is sold once. The hard part of the problem is to find the prices, and the toy just tries every price on a grid, in lexicographic order.

Example

Same favourite. Two agents both have u=(1,0)u = (1, 0). With p=(1,0)p = (1, 0) each agent can afford all of object 1, so both demand it and the market does not clear. With p=(2,0)p = (2, 0) an agent can buy at most half of object 1, so each agent buys (1/2,1/2)(1/2, 1/2), which costs 1, and the market clears. The toy tries (0,0)(0, 0), (1/5,0)(1/5, 0) and so on, and returns p=(2,0)p = (2, 0) with the uniform matrix. Every agent gets a fair coin flip.

Three identical agents. All three have u=(3,2,0)u = (3, 2, 0). They have the same demand set, which is convex, and the rows of an equilibrium allocation average to (1/3,1/3,1/3)(1/3, 1/3, 1/3), so the uniform row is a best bundle. The equilibrium prices are p=(9/5,6/5,0)p = (9/5, 6/5, 0). Check: the bundle (1/3,1/3,1/3)(1/3, 1/3, 1/3) costs 3/5+2/5=13/5 + 2/5 = 1 and has utility 5/35/3. The budget set is a polygon whose corners have at most two nonzero entries. The corner that mixes objects 1 and 3 is (5/9,0,4/9)(5/9, 0, 4/9), with utility 5/35/3; the corner that mixes objects 2 and 3 is (0,5/6,1/6)(0, 5/6, 1/6), also with utility 5/35/3; object 3 alone has utility 0; and no mix of objects 1 and 2 alone is affordable. So U=5/3U = 5/3, every best bundle costs 1, and (1/3,1/3,1/3)=35(5/9,0,4/9)+25(0,5/6,1/6)(1/3, 1/3, 1/3) = \frac35 (5/9, 0, 4/9) + \frac25 (0, 5/6, 1/6) is one of them. With the smallest price 0, these are the only equilibrium prices. The uniform row has no zero entry, so it is a best bundle only if the budget constraint is tight there and (3,2,0)=α(1,1,1)+βp(3, 2, 0) = \alpha (1, 1, 1) + \beta p with β≥0\beta \ge 0. If p3=0p_3 = 0, the third entry gives α=0\alpha = 0, so pp is proportional to (3,2,0)(3, 2, 0), and a cost of 1 for the uniform row gives p=(9/5,6/5,0)p = (9/5, 6/5, 0). If p1=0p_1 = 0 or p2=0p_2 = 0 instead, then α>0\alpha > 0 and the third entry 0=α+βp30 = \alpha + \beta p_3 is impossible. The toy finds these prices but returns a vertex of the clearing LP, which is not the uniform matrix.

No conflict. With u1=(2,1)u_1 = (2, 1) and u2=(1,2)u_2 = (1, 2), prices (0,0)(0, 0) work: each agent buys its favourite for free, and the cheapest-bundle rule plays no role.

Correctness

The toy returns (p,x)(p, x) only when line L5 finds xx. Then xx is bistochastic, and each row xix_i is in the budget set, has utility UiU_i, the largest possible by line L3, and has cost CiC_i, the least among the bundles with utility UiU_i by line L4. These are exactly conditions 1 to 3, so every answer is an equilibrium. Conversely, if some equilibrium has its normalized prices on the grid, the toy returns an equilibrium at those prices or at an earlier grid point. If no equilibrium has grid prices, it returns none, even though an equilibrium always exists. The proof file gives the details.

The properties of the equilibrium itself are theorems.

  • Existence. Hylland and Zeckhauser (1979) proved that an equilibrium exists for all utilities.
  • Pareto efficiency. The allocation is Pareto efficient among all random assignments (ex ante efficient), by a first welfare theorem argument that uses condition 3.
  • Envy-freeness. Every bundle xkx_k costs at most 1, so agent ii could afford it, and xix_i is a best affordable bundle. So ui⋅xi≥ui⋅xku_i \cdot x_i \ge u_i \cdot x_k, which is envy-freeness in expected utility.
Proof: The grid search returns only Hylland-Zeckhauser equilibria and stopsfull

This proof is about the toy on the page. It shows that every answer of the grid search is an equilibrium, that the search finds one whenever some equilibrium has its normalized prices on the grid, and that it stops. It does not prove that an equilibrium exists, which is the theorem of Hylland and Zeckhauser (1979), and it does not prove Pareto efficiency.

Fix nn agents and nn objects and utilities uij≥0u_{ij} \ge 0. Let Δ={y∈Rn:y≥0, ∑jyj=1}\Delta = \{y \in \mathbb{R}^n : y \ge 0,\ \sum_j y_j = 1\}. For prices p≥0p \ge 0 the budget set is B(p)={y∈Δ:p⋅y≤1}B(p) = \{y \in \Delta : p \cdot y \le 1\}. A pair (p,x)(p, x) is an equilibrium when (1) every row xix_i is in Δ\Delta and every column of xx sums to 1, (2) xi∈B(p)x_i \in B(p) and ui⋅xi=max⁡y∈B(p)ui⋅yu_i \cdot x_i = \max_{y \in B(p)} u_i \cdot y, and (3) p⋅xi≤p⋅yp \cdot x_i \le p \cdot y for every y∈B(p)y \in B(p) with ui⋅y=ui⋅xiu_i \cdot y = u_i \cdot x_i.

Claim 1 (the demand values exist). If some price is at most 1, then B(p)B(p) is a nonempty compact polytope, and the values Ui=max⁡y∈B(p)ui⋅yU_i = \max_{y \in B(p)} u_i \cdot y and Ci=min⁡{p⋅y:y∈B(p), ui⋅y=Ui}C_i = \min \{ p \cdot y : y \in B(p),\ u_i \cdot y = U_i \} exist. Every grid vector of line L1 has a price 0, so lines L3 and L4 are always feasible. Proof. If pj≤1p_j \le 1, the unit vector eje_j is in B(p)B(p). B(p)B(p) is a closed subset of the compact set Δ\Delta, defined by finitely many linear constraints. A linear function attains its maximum on a nonempty polytope, so UiU_i exists, and the set of maximizers is a nonempty polytope, on which p⋅yp \cdot y attains its minimum CiC_i. □\square

Claim 2 (the demand set is a face). Let Di(p)={y∈Δ:ui⋅y=Ui, p⋅y=Ci}D_i(p) = \{y \in \Delta : u_i \cdot y = U_i,\ p \cdot y = C_i\}. A row yy satisfies conditions 2 and 3 for agent ii exactly when y∈Di(p)y \in D_i(p). Proof. If yy satisfies 2 and 3, then y∈Δy \in \Delta, ui⋅y=Uiu_i \cdot y = U_i, and yy is a cheapest maximizer, so p⋅y=Cip \cdot y = C_i. Conversely, let y∈Di(p)y \in D_i(p). Then p⋅y=Ci≤1p \cdot y = C_i \le 1, because CiC_i is the cost of a point of B(p)B(p), so y∈B(p)y \in B(p). Its utility is UiU_i, the maximum, so condition 2 holds. Every maximizer in B(p)B(p) costs at least Ci=p⋅yC_i = p \cdot y, so condition 3 holds. □\square

Claim 3 (soundness). If the search returns (p,x)(p, x), then (p,x)(p, x) is an equilibrium. Proof. Line L5 returns x≥0x \ge 0 with ∑jxij=1\sum_j x_{ij} = 1, ui⋅xi=Uiu_i \cdot x_i = U_i and p⋅xi=Cip \cdot x_i = C_i for every ii, and ∑ixij=1\sum_i x_{ij} = 1 for every jj. So every row is in Di(p)D_i(p), which gives conditions 2 and 3 by Claim 2, and the row and column sums give condition 1. □\square

Claim 4 (normalization). If (p,x)(p, x) is an equilibrium, then there is an equilibrium (p′,x)(p', x) with the same allocation and min⁡jpj′=0\min_j p'_j = 0. Proof. Let m=min⁡jpjm = \min_j p_j. Every row xix_i is in B(p)B(p), so m≤p⋅xi≤1m \le p \cdot x_i \le 1. If m=0m = 0, take p′=pp' = p. If 0<m<10 < m < 1, let p′=(p−m1)/(1−m)p' = (p - m \mathbf{1})/(1 - m), so p′≥0p' \ge 0 and min⁡jpj′=0\min_j p'_j = 0. For y∈Δy \in \Delta we have p′⋅y=(p⋅y−m)/(1−m)p' \cdot y = (p \cdot y - m)/(1 - m), because ∑jyj=1\sum_j y_j = 1. This map is increasing in p⋅yp \cdot y and sends 1 to 1, so B(p′)=B(p)B(p') = B(p), and it orders the costs of the bundles in Δ\Delta in the same way. So conditions 2 and 3 hold for p′p' when they hold for pp, and condition 1 does not depend on the prices. If m=1m = 1, then every row costs at least 1 and at most 1, so xij>0x_{ij} > 0 only for pj=1p_j = 1. Every column sums to 1, so every object jj has some xij>0x_{ij} > 0, and all prices are 1. Then B(p)=ΔB(p) = \Delta and every bundle costs 1. Take p′=0p' = 0: again B(p′)=ΔB(p') = \Delta and every bundle costs 0, so conditions 2 and 3 hold for the same rows. □\square

Claim 5 (grid completeness). If some equilibrium (p,x)(p, x) has min⁡jpj=0\min_j p_j = 0 and every pjp_j in {0,1/k,…,pmax}\{0, 1/k, \dots, \text{pmax}\}, then the search does not return none. Proof. The loop of line L1 reaches pp unless it returned earlier. At pp, every row xix_i satisfies conditions 2 and 3, so xi∈Di(p)x_i \in D_i(p) by Claim 2, and xx is a feasible point of the linear program of line L5. So line L6 returns. □\square

By Claim 4, every equilibrium allocation has a price vector with smallest entry 0, so restricting line L1 to such vectors only loses equilibria whose normalized prices are off the grid. Such equilibria exist: an instance can have only irrational equilibrium prices (Vazirani and Yannakakis 2021). So an answer of none does not mean that no equilibrium exists.

Termination. The grid has (k⋅pmax+1)n(k \cdot \text{pmax} + 1)^n vectors, so line L1 runs a finite number of times. Each pass solves 2n+12n + 1 linear programs, and the exact simplex method with Bland's rule never repeats a basis, so each one stops. So the search stops.

The checker. The function is_equilibrium computes UiU_i and CiC_i by Claim 1 (it first rejects negative prices and price vectors whose smallest entry is above 1, for which B(p)B(p) is empty), and accepts exactly when every row is in Δ\Delta, every column sums to 1, and every row has utility UiU_i and cost CiC_i. By Claim 2 this is exactly conditions 1 to 3. All values are exact rationals, so the comparisons are exact.

Envy-freeness of every answer. For an equilibrium (p,x)(p, x) and agents i,ki, k, the row xkx_k is in B(p)B(p), so ui⋅xi=Ui≥ui⋅xku_i \cdot x_i = U_i \ge u_i \cdot x_k. ■\blacksquare

Complexity

The toy tries gng^n price vectors with g=k⋅pmax+1g = k \cdot \text{pmax} + 1, and for each it solves 2n+12n + 1 linear programs with at most n2n^2 variables, by an exact simplex method. With TT the time of one such solve, the total is O(gnnT)O(g^n n T). That is exponential in nn, and it is the reason the toy is only for n≤3n \le 3.

No polynomial algorithm is known for the general problem, and none is expected.

  • Vazirani and Yannakakis (2021) gave an instance whose only equilibria have irrational prices, so an exact answer cannot be written down in rational numbers. They showed that the exact problem is in FIXP and that finding an approximate equilibrium is in PPAD. For dichotomous and bi-valued utilities they gave polynomial time algorithms.
  • Chen, Chen, Peng and Yannakakis (2022) showed that finding an approximate equilibrium is PPAD-hard, even with an inverse polynomial precision and with four distinct utility values. With the membership above, the approximate problem is PPAD-complete.
  • The exact problem is open as of the 2022 paper: it is in FIXP, and FIXP-hardness is not known.

The model is the real RAM, since equilibrium prices can be irrational. The toy uses exact rational numbers and therefore only sees rational grid prices.

Properties

  • Cardinal. It uses the strength of preferences, not only the order. An agent who cares much more about one object than about the others can buy a larger chance of it, which probabilistic serial and random serial dictatorship cannot express.
  • Scale free. If an agent replaces uiu_i by aui+ba u_i + b with a>0a > 0, its utility for every unit bundle changes in the same way, so the equilibria do not change.
  • Efficient and fair. Ex ante Pareto efficient and envy-free, as above.
  • Not strategyproof. An agent can sometimes gain by reporting false utilities, since its report changes the prices.
  • Money is fake. The budgets only give each agent equal weight in the market; no real money changes hands.

Variants and improvements

  • Unequal budgets. Different budgets give priority to some agents. The envy-freeness argument then holds only among agents with equal budgets.
  • More objects and capacities. Objects with several copies, and more objects than agents, fit by changing the column sums to the capacities.
  • Fisher markets. In a linear Fisher market agents spend money on goods with no unit demand constraint. That market has a convex program and polynomial algorithms. The unit demand constraint ∑jxij=1\sum_j x_{ij} = 1 of HZ breaks this structure, and the problem becomes much harder.
  • CEEI. Competitive equilibrium from equal incomes is the same idea with real goods, and approximate CEEI is the version for indivisible goods used in course allocation.

When to use it

Use it when agents have cardinal preferences that matter, the market is small or has structure (for example two utility values), and fairness and ex ante efficiency are worth a heavy computation. For large markets, or when only rankings are known, probabilistic serial or random serial dictatorship are simple and fast. Use the toy on this page only to study small examples.

Pitfalls

  • Forgetting the cheapest-bundle rule. Without condition 3 the allocation can waste money on worthless shares and lose Pareto efficiency.
  • Trusting a grid. A price grid can miss all equilibria, since equilibrium prices can be irrational. A search that finds nothing proves nothing.
  • Floating point. The demand sets are faces of polytopes, and a small error in UiU_i or CiC_i makes the face empty. Compare exactly, or with care.
  • All prices positive. Normalize so that the smallest price is 0. Without it the same allocation appears at many price vectors, and a search wastes time.
  • Asymmetric answers. The clearing LP of line L5 returns a vertex, which can be an asymmetric allocation even for identical agents. All such answers are equilibria, but they may look less fair than the symmetric one.

Implementations

The Python version is a toy and says so. It takes the utility matrix and the grid parameters and returns the first price vector on the grid with a clearing allocation, or None. It uses the shared exact LP helper in Fraction for the demand values and the clearing step, and it has an exact equilibrium checker. The tests check the examples above, the checker on wrong prices, the demand values against a search over the corners of the budget set, and on random instances with 2 agents that every answer is an equilibrium, ex ante Pareto efficient by a linear program over all bistochastic matrices, and envy-free. The 3 agent example is checked at its known prices, because the grid search on 3 objects is too slow for a unit test.

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.

agtlp.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Exact linear programming in Fraction, by the two-phase simplex method with Bland's rule.

lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None) maximizes c x subject to A_ub x <= b_ub,
A_eq x = b_eq and x >= 0. lp_min does the same for minimization. Free variables must be
split by the caller (x = x+ - x-). Every input number is converted to Fraction, so the
result is exact: there is no tolerance anywhere.

Both functions return (status, x, value, dual). status is "optimal", "infeasible" or
"unbounded". When status is not "optimal", x, value and dual are None. dual has one entry
per constraint, the A_ub rows first and then the A_eq rows. It is the vector of shadow
prices: the value is sum_i b_i dual_i (strong duality). For lp_max, dual_i >= 0 on the
A_ub rows and A^T dual >= c. For lp_min, dual_i <= 0 on the A_ub rows and A^T dual <= c.
The entries for the A_eq rows have no sign condition.

Bland's rule (the smallest improving column enters, and among the rows with the smallest
ratio the one with the smallest basic variable leaves) makes the method finite on every
input, degenerate inputs included. There is no game algorithm in this module.
"""

from fractions import Fraction


def _frac(v):
    return v if isinstance(v, Fraction) else Fraction(v)


def _pivot(T, obj, basis, r, j):
    p = T[r][j]
    row = [v / p for v in T[r]]
    T[r] = row
    for k in range(len(T)):
        f = T[k][j]
        if k != r and f != 0:
            T[k] = [a - f * b for a, b in zip(T[k], row)]
    f = obj[j]
    if f != 0:
        obj[:] = [a - f * b for a, b in zip(obj, row)]
    basis[r] = j


def _simplex(T, obj, basis, ncols):
    """Maximize. obj[j] is the reduced cost of column j and obj[-1] is minus the value."""
    while True:
        enter = next((j for j in range(ncols) if obj[j] > 0), None)
        if enter is None:
            return "optimal"
        best = None
        for r, row in enumerate(T):
            a = row[enter]
            if a > 0:
                key = (row[-1] / a, basis[r])
                if best is None or key < best[0]:
                    best = (key, r)
        if best is None:
            return "unbounded"
        _pivot(T, obj, basis, best[1], enter)


def _objective_row(cost, T, basis):
    obj = list(cost) + [Fraction(0)]
    for r, j in enumerate(basis):
        f = obj[j]
        if f != 0:
            obj = [a - f * b for a, b in zip(obj, T[r])]
    return obj


def _any_solution(M, rhs, nvars):
    """Return one solution y of M y = rhs (a consistent system), with the free variables 0."""
    rows = [list(M[k]) + [rhs[k]] for k in range(len(M))]
    pivots = []
    r = 0
    for col in range(nvars):
        p = next((k for k in range(r, len(rows)) if rows[k][col] != 0), None)
        if p is None:
            continue
        rows[r], rows[p] = rows[p], rows[r]
        pv = rows[r][col]
        rows[r] = [v / pv for v in rows[r]]
        for k in range(len(rows)):
            f = rows[k][col]
            if k != r and f != 0:
                rows[k] = [a - f * b for a, b in zip(rows[k], rows[r])]
        pivots.append(col)
        r += 1
        if r == len(rows):
            break
    y = [Fraction(0)] * nvars
    for k, col in enumerate(pivots):
        y[col] = rows[k][-1]
    return y


def _matrix(A, width, name):
    A = [[_frac(v) for v in row] for row in (A or [])]
    if any(len(row) != width for row in A):
        raise ValueError(name + " must have one column per variable")
    return A


def lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None):
    """Maximize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
    c = [_frac(v) for v in c]
    n = len(c)
    A_ub = _matrix(A_ub, n, "A_ub")
    A_eq = _matrix(A_eq, n, "A_eq")
    b_ub = [_frac(v) for v in (b_ub or [])]
    b_eq = [_frac(v) for v in (b_eq or [])]
    if len(b_ub) != len(A_ub) or len(b_eq) != len(A_eq):
        raise ValueError("b_ub and b_eq must have one entry per row")
    m1, m2 = len(A_ub), len(A_eq)
    m = m1 + m2
    width = n + m1
    # Rows in the original orientation, with a slack column for each A_ub row.
    orig = [A_ub[i] + [Fraction(int(k == i)) for k in range(m1)] for i in range(m1)]
    orig += [A_eq[i] + [Fraction(0)] * m1 for i in range(m2)]
    rhs = b_ub + b_eq
    # A row gets an artificial variable if it is an equation or if its right side is negative.
    need = [i >= m1 or rhs[i] < 0 for i in range(m)]
    nart = sum(need)
    T, basis = [], []
    a = 0
    for i in range(m):
        sign = -1 if rhs[i] < 0 else 1
        row = [sign * v for v in orig[i]] + [Fraction(0)] * nart + [sign * rhs[i]]
        if need[i]:
            row[width + a] = Fraction(1)
            basis.append(width + a)
            a += 1
        else:
            basis.append(n + i)
        T.append(row)
    if nart:
        # Phase 1: maximize minus the sum of the artificial variables.
        obj = _objective_row([Fraction(0)] * width + [Fraction(-1)] * nart, T, basis)
        _simplex(T, obj, basis, width + nart)
        if obj[-1] != 0:
            return "infeasible", None, None, None
        keep = []
        for r in range(m):
            if basis[r] >= width:
                j = next((j for j in range(width) if T[r][j] != 0), None)
                if j is None:
                    continue  # the row is a combination of the other rows
                _pivot(T, [Fraction(0)] * (width + nart + 1), basis, r, j)
            keep.append(r)
        T = [T[r][:width] + [T[r][-1]] for r in keep]
        basis = [basis[r] for r in keep]
    # Phase 2: the original objective, without the artificial columns.
    cost = c + [Fraction(0)] * m1
    obj = _objective_row(cost, T, basis)
    if _simplex(T, obj, basis, width) == "unbounded":
        return "unbounded", None, None, None
    x = [Fraction(0)] * n
    for r, j in enumerate(basis):
        if j < n:
            x[j] = T[r][-1]
    value = sum((ci * xi for ci, xi in zip(c, x)), Fraction(0))
    # The dual solves y^T A_B = c_B, where A_B holds the basic columns of the original rows.
    M = [[orig[i][j] for i in range(m)] for j in basis]
    dual = _any_solution(M, [cost[j] for j in basis], m)
    return "optimal", x, value, dual


def lp_min(c, A_ub, b_ub, A_eq=None, b_eq=None):
    """Minimize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
    status, x, value, dual = lp_max([-_frac(v) for v in c], A_ub, b_ub, A_eq, b_eq)
    if status != "optimal":
        return status, None, None, None
    return status, x, -value, [-v for v in dual]
hylland_zeckhauser_mechanism.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hylland-zeckhauser-mechanism/. The authors are listed in prov/NMFNPQ.jsonl.
"""A toy Hylland-Zeckhauser solver: exact checks, and a search over a grid of prices.

This is a toy. It is not an efficient algorithm, and none is known: finding an approximate
HZ equilibrium is PPAD-complete. The search tries every price vector on a grid, so its
running time is exponential in the number of objects, and it can miss an equilibrium whose
prices are not on the grid (HZ equilibria can even be irrational). Use it on 2 or 3 objects.

The market has n agents and n objects, one unit of each. Agent i has utility u[i][j] for
object j and a budget of 1. An allocation x is an n by n matrix with x[i][j] the
probability share of object j given to agent i. All arithmetic is exact (Fraction).
"""

from fractions import Fraction
from itertools import product
from typing import Optional, Sequence

from agtlp import lp_max, lp_min

Matrix = list[list[Fraction]]


def demand_values(ui: Sequence[int], p: Sequence[Fraction]) -> tuple[Fraction, Fraction]:
    """Return (U, C): the best utility of a unit bundle with cost at most 1, and the least
    cost of a bundle with that utility. Two LPs with m variables."""
    m = len(p)
    ones = [[1] * m]
    st, x, U, _ = lp_max(list(ui), [list(p)], [1], ones, [1])  # @line L3
    if st != "optimal":
        raise ValueError("no unit bundle is affordable: some price must be at most 1")
    st, x, C, _ = lp_min(list(p), [list(p)], [1], ones + [list(ui)], [1, U])  # @line L4
    return U, C


def clearing_allocation(u: Sequence[Sequence[int]], p: Sequence[Fraction], vals) -> Optional[Matrix]:
    """Find x with x_i in the demand set of each agent and every object fully assigned, or None.

    The demand set of agent i is {x_i >= 0 : sum_j x_ij = 1, u_i x_i = U_i, p x_i = C_i}."""
    n = len(u)
    nv = n * n
    A_eq, b_eq = [], []

    def row():
        return [0] * nv

    for i in range(n):
        r = row()
        for j in range(n):
            r[i * n + j] = 1
        A_eq.append(r)
        b_eq.append(1)
        r = row()
        for j in range(n):
            r[i * n + j] = u[i][j]
        A_eq.append(r)
        b_eq.append(vals[i][0])
        r = row()
        for j in range(n):
            r[i * n + j] = p[j]
        A_eq.append(r)
        b_eq.append(vals[i][1])
    for j in range(n):
        r = row()
        for i in range(n):
            r[i * n + j] = 1
        A_eq.append(r)
        b_eq.append(1)
    st, x, _, _ = lp_max([0] * nv, [], [], A_eq, b_eq)
    if st != "optimal":
        return None
    return [[x[i * n + j] for j in range(n)] for i in range(n)]


def hz_grid_search(
    u: Sequence[Sequence[int]], k: int = 5, pmax: int = 2
) -> Optional[tuple[list[Fraction], Matrix]]:
    """Try the price vectors with entries in {0, 1/k, ..., pmax} and smallest entry 0, in
    lexicographic order, and return the first (p, x) that is an HZ equilibrium, or None.

    (k * pmax + 1)^n price vectors, each costing 2n + 1 small LPs: exponential in n."""
    n = len(u)
    if any(len(row) != n for row in u):
        raise ValueError("the toy needs n agents and n objects")
    grid = [Fraction(t, k) for t in range(k * pmax + 1)]
    for p in product(grid, repeat=n):  # @line L1
        if min(p) != 0:
            continue
        vals = []
        for i in range(n):  # @line L2
            vals.append(demand_values(u[i], p))
        x = clearing_allocation(u, p, vals)  # @line L5
        if x is not None:  # @line L6
            return list(p), x
    return None  # @line L7


def is_equilibrium(u: Sequence[Sequence[int]], p: Sequence[Fraction], x: Matrix) -> bool:
    """Exact check that (p, x) is an HZ equilibrium with budgets 1."""
    n = len(u)
    p = [Fraction(v) for v in p]
    if any(v < 0 for v in p) or min(p) > 1:
        return False
    for j in range(n):
        if sum(x[i][j] for i in range(n)) != 1:
            return False
    for i in range(n):
        if any(v < 0 for v in x[i]) or sum(x[i]) != 1:
            return False
        U, C = demand_values(u[i], p)
        util = sum(a * b for a, b in zip(u[i], x[i]))
        cost = sum(a * b for a, b in zip(p, x[i]))
        if util != U or cost != C:
            return False
    return True
test_hylland_zeckhauser_mechanism.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hylland-zeckhauser-mechanism/. The authors are listed in prov/NMFNPQ.jsonl.

import random
import unittest
from fractions import Fraction as F

from agtlp import lp_max
from hylland_zeckhauser_mechanism import clearing_allocation, demand_values, hz_grid_search, is_equilibrium


def utility(ui, xi):
    return sum(a * b for a, b in zip(ui, xi))


def best_by_vertices(ui, p):
    """Best utility of a unit bundle with cost <= 1, by trying the vertices of the polytope."""
    m = len(p)
    best = None
    for j in range(m):
        if p[j] <= 1:
            best = ui[j] if best is None else max(best, ui[j])
        for k in range(m):
            if p[j] < 1 < p[k]:
                t = (p[k] - 1) / (p[k] - p[j])
                v = t * ui[j] + (1 - t) * ui[k]
                best = v if best is None else max(best, v)
    return best


def ex_ante_pareto_optimal(u, x):
    """LP check: no fractional allocation gives every agent as much and the total more."""
    n = len(u)
    nv = n * n
    A_eq, b_eq, A_ub, b_ub = [], [], [], []
    for i in range(n):
        A_eq.append([1 if v // n == i else 0 for v in range(nv)])
        b_eq.append(1)
    for j in range(n):
        A_eq.append([1 if v % n == j else 0 for v in range(nv)])
        b_eq.append(1)
    for i in range(n):
        A_ub.append([-u[i][v % n] if v // n == i else 0 for v in range(nv)])
        b_ub.append(-utility(u[i], x[i]))
    c = [u[v // n][v % n] for v in range(nv)]
    st, _, value, _ = lp_max(c, A_ub, b_ub, A_eq, b_eq)
    return st == "optimal" and value == sum(utility(u[i], x[i]) for i in range(n))


def uniform(n):
    return [[F(1, n)] * n for _ in range(n)]


class TestHyllandZeckhauser(unittest.TestCase):
    def test_identical_agents(self):
        u = [[3, 2, 0]] * 3
        p = [F(9, 5), F(6, 5), F(0)]
        self.assertTrue(is_equilibrium(u, p, uniform(3)))
        vals = [demand_values(u[i], p) for i in range(3)]
        self.assertEqual(vals[0], (F(5, 3), F(1)))
        x = clearing_allocation(u, p, vals)
        self.assertIsNotNone(x)
        self.assertTrue(is_equilibrium(u, p, x))
        for q in ([F(2), F(1), F(0)], [F(8, 5), F(7, 5), F(0)], [F(9, 5), F(6, 5), F(1, 5)]):
            self.assertFalse(is_equilibrium(u, q, uniform(3)))
            vals = [demand_values(u[i], q) for i in range(3)]
            self.assertIsNone(clearing_allocation(u, q, vals))

    def test_same_favourite(self):
        u = [[1, 0], [1, 0]]
        self.assertEqual(hz_grid_search(u), ([F(2), F(0)], uniform(2)))
        self.assertFalse(is_equilibrium(u, [F(1), F(0)], uniform(2)))
        self.assertTrue(ex_ante_pareto_optimal(u, uniform(2)))

    def test_different_favourites(self):
        u = [[2, 1], [1, 2]]
        p, x = hz_grid_search(u)
        self.assertEqual(p, [F(0), F(0)])
        self.assertEqual(x, [[1, 0], [0, 1]])

    def test_edge_cases(self):
        self.assertEqual(hz_grid_search([[5]]), ([F(0)], [[F(1)]]))
        with self.assertRaises(ValueError):
            hz_grid_search([[1, 2]])
        with self.assertRaises(ValueError):
            demand_values([1, 2], [F(2), F(3)])
        self.assertFalse(is_equilibrium([[1, 0], [1, 0]], [F(2), F(2)], uniform(2)))

    def test_demand_against_vertices(self):
        rng = random.Random(6)
        for _ in range(150):
            m = rng.randint(1, 4)
            ui = [rng.randint(0, 6) for _ in range(m)]
            p = [F(rng.randint(0, 12), rng.randint(1, 4)) for _ in range(m)]
            p[rng.randrange(m)] = F(rng.randint(0, 4), 4)  # some price is at most 1
            U, C = demand_values(ui, p)
            self.assertEqual(U, best_by_vertices(ui, p))
            self.assertLessEqual(C, 1)

    def test_random_two_agents(self):
        rng = random.Random(12)
        found = 0
        for _ in range(25):
            u = [[rng.randint(0, 4) for _ in range(2)] for _ in range(2)]
            res = hz_grid_search(u, k=4, pmax=2)
            if res is None:
                continue
            found += 1
            p, x = res
            self.assertTrue(is_equilibrium(u, p, x))
            self.assertTrue(ex_ante_pareto_optimal(u, x))
            for i in range(2):
                self.assertEqual(utility(u[i], x[i]), demand_values(u[i], p)[0])
                self.assertEqual(utility(u[i], x[i]), best_by_vertices(u[i], p))
                for k in range(2):  # envy-free: every bundle costs at most the budget 1
                    self.assertGreaterEqual(utility(u[i], x[i]), utility(u[i], x[k]))
        self.assertGreaterEqual(found, 20)


if __name__ == "__main__":
    unittest.main()

History

Hylland and Zeckhauser (1979) proposed the pseudo-market for assigning individuals to positions, proved that an equilibrium exists and that its allocation is efficient. It was long seen as the ideal mechanism for one-sided matching with cardinal utilities, but too hard to compute. Vazirani and Yannakakis (2021) started its study in computer science, with irrational equilibria, FIXP and PPAD membership, and algorithms for special utilities. Chen, Chen, Peng and Yannakakis (2022) proved that the approximate problem is PPAD-hard.

References

  1. Aanund Hylland and Richard Zeckhauser, The efficient allocation of individuals to positions, Journal of Political Economy 87(2), 293 to 314 (1979), the pseudo-market with equal budgets, the existence of an equilibrium and its Pareto efficiency
  2. Vijay V. Vazirani and Mihalis Yannakakis, Computational complexity of the Hylland-Zeckhauser scheme for one-sided matching markets, 12th Innovations in Theoretical Computer Science Conference (ITCS 2021), an instance with only irrational equilibria, membership of the exact problem in FIXP and of the approximate problem in PPAD, and polynomial algorithms for dichotomous and bi-valued utilities
  3. Thomas Chen, Xi Chen, Binghui Peng and Mihalis Yannakakis, Computational hardness of the Hylland-Zeckhauser scheme, Proceedings of the 2022 ACM-SIAM Symposium on Discrete Algorithms (SODA 2022), PPAD-hardness of finding an approximate equilibrium, also for four-valued utilities

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