Algorithm Search⌘K

Algorithmresearch

Barman-Krishnamurthy-Vaish algorithm

Also called EF1 and Pareto optimal allocation algorithm.

Finds an EF1 and Pareto optimal allocation of indivisible goods in pseudo-polynomial time by running a market with price rises.

Time
poly(n, m, V) worst
Space
O(n m) extra
Where
V = the largest value v_max (an integer); m = the number of goods; n = the number of agents
Properties
deterministicofflineiterative

The Barman-Krishnamurthy-Vaish (BKV) algorithm finds an allocation of indivisible goods that is both envy-free up to one good (EF1) and Pareto optimal (PO), for additive valuations, in time polynomial in nn, mm and the largest value vmax⁡v_{\max}. It treats the goods as a Fisher market: goods have prices, every agent holds only goods of maximum value per unit of price, so the allocation is efficient by the first welfare theorem, and the algorithm moves goods and raises prices until the spending of the agents is balanced up to one good. Maximum Nash welfare also gives EF1 and PO (the unreasonable fairness of MNW), but it is NP-hard to compute; BKV reaches the same two properties in pseudo-polynomial time. Barman, Krishnamurthy and Vaish presented it at EC 2018. Whether EF1 and PO can be reached in polynomial time is open (open problem, Mahara, November 2024).

In plain words

Put a price tag on every item. Each person looks at the value they get for each unit of money and only keeps items that are the best deal for them. When everybody holds only best deals, no trade can help someone without hurting someone else.

Now look at the money each person has spent on their items. If someone spent far more than the poorest person, even after ignoring their most expensive item, things are unfair. Then either an item moves from a rich person to a poorer person who also sees it as a best deal, or, when no such move is possible, the prices of the items held by the poorer group go up. Higher prices make other items better deals for that group, which opens new moves. When spending is balanced up to one item, the values are balanced up to one item too.

The problem

There are nn agents and mm indivisible goods, with additive values vij≥0v_{ij} \ge 0. The goal is an allocation x=(x1,…,xn)x = (x_1, \dots, x_n) of all goods that is EF1 and PO.

Market terms. Prices pj>0p_j > 0 are attached to the goods, and p(S)=∑j∈Spjp(S) = \sum_{j \in S} p_j is the spending on a set SS. The bang per buck of agent ii for good jj is vij/pjv_{ij}/p_j, its largest value is the MBB ratio βi=max⁡jvij/pj\beta_i = \max_j v_{ij}/p_j, and the goods that reach it form the MBB set of ii. An allocation satisfies the MBB condition if every agent owns only goods of its MBB set. A least spender is an agent of smallest spending pmin⁡=min⁡ip(xi)p_{\min} = \min_i p(x_i). The allocation is price-EF1 (pEF1) if for all agents i,ki, k with xk≠∅x_k \ne \emptyset some j∈xkj \in x_k has p(xi)≥p(xk∖{j})p(x_i) \ge p(x_k \setminus \{j\}); equivalently, p(xk)−max⁡j∈xkpj≤pmin⁡p(x_k) - \max_{j \in x_k} p_j \le p_{\min} for every agent kk.

Hierarchy. Start from the least spenders at level 0. An agent hh at level ℓ\ell adds to level ℓ+1\ell + 1 every agent not seen yet that owns an MBB good of hh. This is a breadth-first search along MBB edges (from an agent to a good) and allocation edges (from a good to its owner). A path violator is an agent hh at level ℓ≥1\ell \ge 1 with a good j∈xhj \in x_h that is an MBB good of some agent gg at level ℓ−1\ell - 1, such that p(xh∖{j})>pmin⁡p(x_h \setminus \{j\}) > p_{\min}.

The algorithm

The page gives the exact form of the algorithm, with no rounding, and with all least spenders at level 0; the paper's form is described after the walk-through.

  1. BKV-EXACT(v) ▷ n agents, m goods, values v_ij > 0
  2. 1give each good j to an agent k of largest v_kj, and set p_j ← v_kj
  3. 2loop
  4. 3if x is pEF1 for p then exit the loop
  5. 4H ← the hierarchy of the least spenders (levels by BFS)
  6. 5look for a path violator h with its good j and a parent g one level above
  7. 6if one is found then give j to g, and go back to line L3
  8. 7α1 ← min over h ∈ H and goods j owned outside H of β_h p_j / v_hj
  9. 8α2 ← max over agents k ∉ H of (p(x_k) - max_{j ∈ x_k} p_j) / p_min
  10. 9α3 ← min over agents k ∉ H of p(x_k) / p_min
  11. 10α ← min(α1, α2, α3); multiply the price of every good owned in H by α
  12. 11if α = α2 then exit the loop
  13. 12return x

Line L1 is Phase 1 of the paper: each good goes to an agent that values it most, at a price equal to that value, so every owner gets bang per buck 1 from its goods and nobody gets more from any good. Lines L4 to L6 are Phase 2: a swap moves a good one level down the hierarchy, toward the least spenders, along an MBB edge, so the MBB condition stays true. Lines L7 to L10 are Phase 3: the prices of all goods held inside HH rise by the same factor. The three bounds stop the rise at the first event: at α1\alpha_1 a good outside HH becomes an MBB good of an agent in HH, so HH grows; at α2\alpha_2 the least spenders have caught up with every agent outside HH, up to one good; at α3\alpha_3 an agent outside HH becomes a least spender.

The paper's version. Barman, Krishnamurthy and Vaish run the same three phases with a parameter ε>0\varepsilon > 0 on a rounded instance, whose positive values are rounded up to integer powers of 1+ε1 + \varepsilon, and test ε\varepsilon-versions of the violator conditions. They show that the run takes poly(m,n,1/ε,ln⁡vmax⁡)\mathrm{poly}(m, n, 1/\varepsilon, \ln v_{\max}) time (Lemma 4) and returns a 3ε3\varepsilon-EF1 and fractionally PO allocation of the rounded instance (Lemma 3). For ε=1/(14m3vmax⁡4)\varepsilon = 1/(14 m^3 v_{\max}^4), this allocation is EF1 and PO for the original integer values (Lemma 5 and Theorem 1). The paper also handles zero values and a single least spender chosen by a fixed order.

Example

Three agents value four goods a,b,c,da, b, c, d:

aa bb cc dd
agent 1 5 8 1 6
agent 2 3 1 2 2
agent 3 1 5 4 4
  1. Line L1. Agent 1 gets a,b,da, b, d and agent 3 gets cc, at prices (5,8,4,6)(5, 8, 4, 6). Spending is 19, 0 and 4. Agent 1 spends 19−8=11>019 - 8 = 11 > 0 without its most expensive good, so the allocation is not pEF1.
  2. Swap. The least spender is agent 2. Its MBB ratio is 3/53/5, reached by aa, which agent 1 owns, so agent 1 is at level 1. Since p({b,d})=14>0p(\{b, d\}) = 14 > 0, agent 1 is a path violator, and aa moves to agent 2. Spending is now 14, 5 and 4.
  3. Price rise. The least spender is agent 3, with pmin⁡=4p_{\min} = 4; its only MBB good is its own cc, so H={3}H = \{3\}. Then α1=min⁡(5/1,8/5,6/4)=3/2\alpha_1 = \min(5/1, 8/5, 6/4) = 3/2, α2=max⁡(6/4,0/4)=3/2\alpha_2 = \max(6/4, 0/4) = 3/2 and α3=min⁡(14,5)/4=5/4\alpha_3 = \min(14, 5)/4 = 5/4. The price of cc rises by 5/45/4 to 5.
  4. Price rise. Agents 2 and 3 both spend 5 and form level 0, each holding only its own MBB good. Now α1=6/5\alpha_1 = 6/5 (agent 3 and good dd: (4/5)⋅6/4(4/5) \cdot 6/4), α2=(14−8)/5=6/5\alpha_2 = (14 - 8)/5 = 6/5 and α3=14/5\alpha_3 = 14/5. The prices of aa and cc rise to 6, and since α=α2\alpha = \alpha_2 the loop ends.

The output is x1={b,d}x_1 = \{b, d\}, x2={a}x_2 = \{a\}, x3={c}x_3 = \{c\} with prices (6,8,6,6)(6, 8, 6, 6) and values 14, 3 and 4. It is pEF1: 14−8≤614 - 8 \le 6. Agent 3 values {b,d}\{b, d\} at 9 but without bb at 44, its own value, so it is EF1; and it is PO.

Correctness

Three facts hold whenever the algorithm returns. First, the MBB condition holds at every step: line L1 makes it true, a swap moves a good to an agent for which it is an MBB good, and the bound α≤α1\alpha \le \alpha_1 keeps the MBB goods of agents in HH ahead of goods outside HH, while agents outside HH own only goods whose prices do not change. Second, the output is pEF1: either line L3 saw it, or the rise stopped at α2\alpha_2 and the least spenders, which are inside HH because α≤α3\alpha \le \alpha_3, now spend at least as much as every agent's spending minus its most expensive good. Third, pEF1 with the MBB condition gives EF1, because agent ii values any set SS at most βip(S)\beta_i p(S) and its own bundle at exactly βip(xi)\beta_i p(x_i) (Lemma 2 of the paper). The MBB condition also gives PO by the first welfare theorem: an allocation that some agent prefers and nobody likes less would cost more than the total price of all goods. The full proof of these facts is in proofs/correctness.md. That the exact form ends is not proved; the paper proves termination for its rounded form.

Proof: When the exact BKV algorithm returns, its allocation is EF1 and Pareto optimalpartial

Setting. There are n≥1n \ge 1 agents and mm goods with values vij>0v_{ij} > 0. We refer to the lines L1 to L12 of the page and use its terms: prices pjp_j, spending p(S)p(S), MBB ratio βi=max⁡jvij/pj\beta_i = \max_j v_{ij}/p_j, MBB condition, least spender with spending pmin⁡p_{\min}, pEF1, hierarchy HH and path violator. This proof shows partial correctness: if the algorithm returns, the allocation is EF1 and Pareto optimal. It does not prove that the exact form ends. For the rounded form, Barman, Krishnamurthy and Vaish prove termination in poly(m,n,1/ε,ln⁡vmax⁡)\mathrm{poly}(m, n, 1/\varepsilon, \ln v_{\max}) time (Lemma 4 of their paper).

Lemma 1 (prices stay positive). At every step pj>0p_j > 0 for every good jj.

Proof. Line L1 sets pj=vkj>0p_j = v_{kj} > 0. A swap does not change prices. A rise multiplies some prices by α\alpha, and Lemma 3 below shows α>1\alpha > 1. □\square

Lemma 2 (MBB condition). At every step each agent owns only goods of its MBB set.

Proof. After line L1, the owner kk of good jj has vkj/pj=1v_{kj}/p_j = 1, and every agent ii has vij′/pj′=vij′/vk′j′≤1v_{ij'}/p_{j'} = v_{ij'}/v_{k'j'} \le 1 for every good j′j' with owner k′k', because k′k' values j′j' most. So βk=1\beta_k = 1 and jj is an MBB good of kk.

A swap of line L6 gives jj to an agent gg for which jj is an MBB good, and changes no prices, so all MBB sets stay the same.

A rise of line L10 multiplies by α\alpha the prices of the goods owned in HH. By the construction of the hierarchy, every MBB good of an agent of HH is owned by an agent of HH. For h∈Hh \in H, the ratios of the goods owned in HH drop by the factor α\alpha, so the ratio of its own goods becomes βh/α\beta_h/\alpha. A good jj owned outside HH keeps its price, and α≤α1≤βhpj/vhj\alpha \le \alpha_1 \le \beta_h p_j / v_{hj} gives vhj/pj≤βh/αv_{hj}/p_j \le \beta_h/\alpha. So the goods of hh are still MBB goods of hh. For k∉Hk \notin H, the goods of kk keep their prices and the other prices do not drop, so the goods of kk are still MBB goods of kk. □\square

Lemma 3 (a rise has α>1\alpha > 1). When line L7 is reached, α1>1\alpha_1 > 1, α3>1\alpha_3 > 1 and α2>1\alpha_2 > 1, wherever they are defined, and at least one is defined.

Proof. Line L7 is reached only if the allocation is not pEF1 and no path violator exists. All least spenders are at level 0 of HH, so every k∉Hk \notin H has p(xk)>pmin⁡p(x_k) > p_{\min}, which gives α3>1\alpha_3 > 1. A good jj owned outside HH is not an MBB good of any h∈Hh \in H, since otherwise its owner would be in HH; so vhj/pj<βhv_{hj}/p_j < \beta_h and α1>1\alpha_1 > 1.

Every agent h∈Hh \in H has p(xh)−max⁡j∈xhpj≤pmin⁡p(x_h) - \max_{j \in x_h} p_j \le p_{\min}. At level 0 this holds because p(xh)=pmin⁡p(x_h) = p_{\min}. At a level ℓ≥1\ell \ge 1, agent hh owns a good jj that is an MBB good of an agent at level ℓ−1\ell - 1, and since hh is not a path violator, p(xh)−max⁡j′∈xhpj′≤p(xh∖{j})≤pmin⁡p(x_h) - \max_{j' \in x_h} p_{j'} \le p(x_h \setminus \{j\}) \le p_{\min}. Since the allocation is not pEF1, some agent kk has p(xk)−max⁡j∈xkpj>pmin⁡p(x_k) - \max_{j \in x_k} p_j > p_{\min}, and so k∉Hk \notin H. If pmin⁡>0p_{\min} > 0, then α2\alpha_2 and α3\alpha_3 are defined, and α2≥(p(xk)−max⁡j∈xkpj)/pmin⁡>1\alpha_2 \ge (p(x_k) - \max_{j \in x_k} p_j)/p_{\min} > 1. If pmin⁡=0p_{\min} = 0, the least spenders own no goods, α2\alpha_2 and α3\alpha_3 are not defined, and α1\alpha_1 is defined because the violator k∉Hk \notin H owns goods outside HH. □\square

Lemma 4 (the output is pEF1). When the loop exits, the allocation is pEF1 for the current prices.

Proof. If it exits in line L3, this is the test of that line. Otherwise it exits in line L11 after a rise with α=α2\alpha = \alpha_2. Write qq for the prices before the rise, pp for the prices after it, and qmin⁡q_{\min} for the least spending before it. Every agent of HH had spending at least qmin⁡q_{\min} and now has α\alpha times its old spending, so at least αqmin⁡\alpha q_{\min}. Every agent k∉Hk \notin H keeps its spending, which is at least α3qmin⁡≥αqmin⁡\alpha_3 q_{\min} \ge \alpha q_{\min}. So the new least spending is pmin⁡=αqmin⁡p_{\min} = \alpha q_{\min}, reached by the old least spenders.

Now check every agent kk. If k∉Hk \notin H, its spending minus its most expensive good is unchanged and at most α2qmin⁡=pmin⁡\alpha_2 q_{\min} = p_{\min} by the definition of α2\alpha_2. If k∈Hk \in H, the proof of Lemma 3 gave q(xk)−max⁡j∈xkqj≤qmin⁡q(x_k) - \max_{j \in x_k} q_j \le q_{\min}, and all prices of xkx_k were multiplied by α\alpha, so p(xk)−max⁡j∈xkpj≤αqmin⁡=pmin⁡p(x_k) - \max_{j \in x_k} p_j \le \alpha q_{\min} = p_{\min}. Hence the allocation is pEF1. □\square

Lemma 5 (pEF1 with the MBB condition gives EF1; Lemma 2 of the paper with ε=0\varepsilon = 0). If xx satisfies the MBB condition and is pEF1 for prices p>0p > 0, then xx is EF1.

Proof. Fix agents i≠ki \ne k with xk≠∅x_k \ne \emptyset, and let jj be a most expensive good of xkx_k. For any set SS, vi(S)=∑j′∈Svij′≤βi p(S)v_i(S) = \sum_{j' \in S} v_{ij'} \le \beta_i\, p(S), and by the MBB condition vi(xi)=βi p(xi)v_i(x_i) = \beta_i\, p(x_i). pEF1 gives p(xi)≥pmin⁡≥p(xk∖{j})p(x_i) \ge p_{\min} \ge p(x_k \setminus \{j\}). So vi(xi)=βip(xi)≥βip(xk∖{j})≥vi(xk∖{j})v_i(x_i) = \beta_i p(x_i) \ge \beta_i p(x_k \setminus \{j\}) \ge v_i(x_k \setminus \{j\}). □\square

Lemma 6 (MBB condition gives Pareto optimality; the first welfare theorem). If xx satisfies the MBB condition for prices p>0p > 0, then no fractional allocation yy has vi(yi)≥vi(xi)v_i(y_i) \ge v_i(x_i) for every agent with strict inequality for some agent.

Proof. Suppose yy is such an allocation, where yij≥0y_{ij} \ge 0 is the share of good jj given to ii and ∑iyij=1\sum_i y_{ij} = 1. For each agent, vi(yi)=∑jvijyij≤βi∑jpjyijv_i(y_i) = \sum_j v_{ij} y_{ij} \le \beta_i \sum_j p_j y_{ij}, and vi(xi)=βip(xi)v_i(x_i) = \beta_i p(x_i) with βi>0\beta_i > 0. So ∑jpjyij≥p(xi)\sum_j p_j y_{ij} \ge p(x_i) for every agent, with strict inequality for the agent that is strictly better off. Summing over the agents gives ∑jpj>∑jpj\sum_j p_j > \sum_j p_j, a contradiction. □\square

Theorem. If the algorithm returns an allocation, the allocation contains every good once, is EF1, and is Pareto optimal, even against fractional allocations.

Proof. Line L1 gives every good to one agent, and swaps move goods between agents, so every good stays in exactly one bundle. By Lemma 1 the prices are positive, by Lemma 2 the MBB condition holds, and by Lemma 4 the output is pEF1. Lemma 5 gives EF1 and Lemma 6 gives Pareto optimality, since an integral allocation is a special fractional one. ■\blacksquare

Termination of the exact form is not proved here. Barman, Krishnamurthy and Vaish prove that the rounded form ends in poly(m,n,1/ε,ln⁡vmax⁡)\mathrm{poly}(m, n, 1/\varepsilon, \ln v_{\max}) time and that, for their choice of ε\varepsilon, its output is EF1 and PO for the original values (Lemmas 3 to 5 and Theorem 1 of their paper).

Complexity

One step, a swap or a price rise, costs O(nm)O(n m) time: the MBB sets, the BFS of line L4 and the three bounds each read the value table once. The paper bounds the number of steps for the rounded form by poly(m,n,1/ε,ln⁡vmax⁡)\mathrm{poly}(m, n, 1/\varepsilon, \ln v_{\max}), and its choice of ε\varepsilon makes the whole run pseudo-polynomial, poly(n,m,vmax⁡)\mathrm{poly}(n, m, v_{\max}) (Theorem 1). When values are bounded by a polynomial in nn and mm, this is polynomial time (Remark 1). With exact rational arithmetic, as in the exact form, the bit length of the prices also matters. On 2000 random instances with 2 to 5 agents, 2 to 10 goods and integer values from 1 to 30, the exact form ended after at most 18 swaps and rises (measurement).

Properties

  • EF1 and PO, and in fact fractionally PO: no fractional allocation is better for some agent and worse for none (Theorem 2 of the paper states that EF1 and fPO allocations always exist).
  • Market equilibrium. The output with its prices is an equilibrium of a Fisher market in which each agent's budget is its final spending.
  • Approximate Nash welfare. A version of the same algorithm gives an e1/e≈1.45e^{1/e} \approx 1.45 approximation of the maximum Nash welfare (Theorem 3).
  • Approximate inputs run fast. For ε\varepsilon-EF1 and ε\varepsilon-PO, the time is poly(m,n,1/ε,ln⁡vmax⁡)\mathrm{poly}(m, n, 1/\varepsilon, \ln v_{\max}) (Remark 2).
  • Deterministic. Ties are broken by index.

Variants and improvements

  • Fixed number of agents. Mahara (2024) gives a polynomial-time algorithm for EF1 and fPO when nn is fixed, by adding agents one at a time.
  • Maximum Nash welfare. For small instances, an exact MNW allocation, for example from a mixed integer program, also gives EF1 and PO.
  • Divisible goods. For divisible goods, the market equilibrium with equal budgets, computed for example by the DPSV algorithm, is envy-free and PO.

When to use it

Use it when valuations are additive with small integer values, for example points that each agent spreads over the goods, and both EF1 and Pareto optimality are needed with a proof. For large instances where only EF1 is needed, round-robin allocation is simpler. When the Nash welfare itself matters, compute MNW directly if the instance is small.

Pitfalls

  • A single least spender with ties in the exact form. If line L4 starts the hierarchy from only one least spender when several exist, then α3=1\alpha_3 = 1 for a tied agent outside HH, the rise of line L10 changes nothing, and the loop can stall. Starting from all least spenders, as here, avoids this; the paper avoids it by its order on agents and its ε\varepsilon margins.
  • Breaking on α1\alpha_1 or α3\alpha_3. Line L11 may stop only when the rise reached α2\alpha_2. A rise that stopped at α1\alpha_1 or α3\alpha_3 has not balanced the spending, and the output need not be pEF1.
  • Raising prices of goods outside HH. Line L10 must scale exactly the goods owned by agents of HH. Scaling more breaks the MBB condition of agents outside HH; scaling less breaks it inside HH.
  • Swapping across a level. In line L5 the good must go from a level-ℓ\ell agent to an agent at level ℓ−1\ell - 1 for which it is an MBB good. Moving a good to an agent that does not see it as an MBB good destroys the MBB condition and with it Pareto optimality.

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.

ef1_and_pareto_optimal_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ef1-and-pareto-optimal-algorithm/. The authors are listed in prov/HCYFF2.jsonl.

from fractions import Fraction
from typing import Optional, Sequence


def bundles_of(owner: Sequence[int], n: int) -> list[list[int]]:
    bundles: list[list[int]] = [[] for _ in range(n)]
    for j, k in enumerate(owner):
        bundles[k].append(j)
    return bundles


def is_price_ef1(bundles: Sequence[Sequence[int]], p: Sequence[Fraction]) -> bool:
    """pEF1: for all agents i and k, p(x_i) >= p(x_k) - p_j for some good j of x_k."""
    spend = [sum((p[j] for j in b), Fraction(0)) for b in bundles]
    n = len(bundles)
    for k in range(n):
        if not bundles[k]:
            continue
        reduced = spend[k] - max(p[j] for j in bundles[k])
        if any(i != k and spend[i] < reduced for i in range(n)):
            return False
    return True


def bkv_exact(values: Sequence[Sequence], max_steps: int = 100000, stats: Optional[dict] = None) -> list[list[int]]:
    """Barman, Krishnamurthy and Vaish's market algorithm, exact variant (epsilon = 0).

    values[i][j] is the additive value of agent i for good j, a positive
    integer or Fraction (every value must be > 0). Returns the bundles of an
    allocation that is EF1 and Pareto optimal. If stats is a dict, it gets
    the final prices ("prices"), the numbers of swaps ("swaps") and of
    price rises ("rises"), and a list "trace" of the events, each a tuple
    (kind, owner of each good, prices) with kind "start", "swap" or "rise".

    The original algorithm rounds the values to powers of (1 + epsilon) and
    has a pseudo-polynomial bound for that version. Here epsilon = 0, all
    least spenders are sources of the hierarchy, and every number is an
    exact Fraction. When the function returns, the allocation is EF1 and
    PO; no bound on the number of steps is proved for epsilon = 0, so the
    loop stops with RuntimeError after max_steps swaps and rises. One step
    costs O(n m) time.
    """
    v = [[Fraction(x) for x in row] for row in values]
    n = len(v)
    if n == 0:
        raise ValueError("at least one agent is needed")
    m = len(v[0])
    if any(len(row) != m for row in v) or any(x <= 0 for row in v for x in row):
        raise ValueError("every agent needs a positive value for every good")
    owner = [max(range(n), key=lambda k: (v[k][j], -k)) for j in range(m)]  # @line L1
    p = [v[owner[j]][j] for j in range(m)]
    swaps = rises = 0
    trace = stats.setdefault("trace", []) if stats is not None else None
    if trace is not None:
        trace.append(("start", list(owner), list(p)))
    while True:  # @line L2
        if swaps + rises > max_steps:
            raise RuntimeError("step limit reached")
        x = bundles_of(owner, n)
        if is_price_ef1(x, p):  # @line L3
            break
        spend = [sum((p[j] for j in x[i]), Fraction(0)) for i in range(n)]
        ratio = [max(v[i][j] / p[j] for j in range(m)) for i in range(n)]
        mbb = [[j for j in range(m) if v[i][j] / p[j] == ratio[i]] for i in range(n)]
        pmin = min(spend)
        level = {i: 0 for i in range(n) if spend[i] == pmin}  # @line L4
        layers = [sorted(level)]
        while layers[-1]:
            nxt = set()
            for g in layers[-1]:
                for j in mbb[g]:
                    h = owner[j]
                    if h not in level:
                        level[h] = len(layers)
                        nxt.add(h)
            layers.append(sorted(nxt))
        swap = None
        for depth in range(1, len(layers)):  # @line L5
            for h in layers[depth]:
                for j in x[h]:
                    parents = [g for g in layers[depth - 1] if j in mbb[g]]
                    if parents and spend[h] - p[j] > pmin:
                        swap = (j, parents[0])
                        break
                if swap:
                    break
            if swap:
                break
        if swap:
            owner[swap[0]] = swap[1]  # @line L6
            swaps += 1
            if trace is not None:
                trace.append(("swap", list(owner), list(p)))
            continue
        tree = set(level)
        owned = [j for j in range(m) if owner[j] in tree]
        outside = [j for j in range(m) if owner[j] not in tree]
        cands1 = [ratio[h] * p[j] / v[h][j] for h in tree for j in outside]
        alpha1 = min(cands1) if cands1 else None  # @line L7
        rest = [k for k in range(n) if k not in tree]
        if pmin > 0:
            alpha2 = max((spend[k] - max(p[j] for j in x[k]) if x[k] else Fraction(0)) for k in rest) / pmin  # @line L8
            alpha3 = min(spend[k] for k in rest) / pmin  # @line L9
        else:
            alpha2 = alpha3 = None
        alpha = min(a for a in (alpha1, alpha2, alpha3) if a is not None)  # @line L10
        for j in owned:
            p[j] *= alpha
        rises += 1
        if trace is not None:
            trace.append(("rise", list(owner), list(p)))
        if alpha == alpha2:  # @line L11
            break
    if stats is not None:
        stats["prices"] = list(p)
        stats["swaps"] = swaps
        stats["rises"] = rises
    return bundles_of(owner, n)  # @line L12
test_ef1_and_pareto_optimal_algorithm.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ef1-and-pareto-optimal-algorithm/. The authors are listed in prov/HCYFF2.jsonl.

import itertools
import random
from fractions import Fraction

import pytest

from ef1_and_pareto_optimal_algorithm import bkv_exact, bundles_of, is_price_ef1

F = Fraction


def value(row, bundle):
    return sum(row[g] for g in bundle)


def is_ef1(values, bundles) -> bool:
    n = len(values)
    for i in range(n):
        mine = value(values[i], bundles[i])
        for k in range(n):
            if i != k and bundles[k]:
                other = value(values[i], bundles[k])
                if not any(mine >= other - values[i][g] for g in bundles[k]):
                    return False
    return True


def is_pareto_optimal(values, bundles) -> bool:
    """Brute force over all n^m allocations."""
    n, m = len(values), len(values[0])
    u = [value(values[i], bundles[i]) for i in range(n)]
    for owner in itertools.product(range(n), repeat=m):
        w = [0] * n
        for g, i in enumerate(owner):
            w[i] += values[i][g]
        if all(w[i] >= u[i] for i in range(n)) and any(w[i] > u[i] for i in range(n)):
            return False
    return True


def holds_only_mbb_goods(values, owner, p) -> bool:
    n, m = len(values), len(values[0])
    for i in range(n):
        best = max(F(values[i][j]) / p[j] for j in range(m))
        if any(owner[j] == i and F(values[i][j]) / p[j] != best for j in range(m)):
            return False
    return True


def test_worked_example():
    values = [[5, 8, 1, 6], [3, 1, 2, 2], [1, 5, 4, 4]]
    stats = {}
    bundles = bkv_exact(values, stats=stats)
    events = [(kind, owner, [str(q) for q in p]) for kind, owner, p in stats["trace"]]
    assert events == [
        ("start", [0, 0, 2, 0], ["5", "8", "4", "6"]),
        ("swap", [1, 0, 2, 0], ["5", "8", "4", "6"]),
        ("rise", [1, 0, 2, 0], ["5", "8", "5", "6"]),
        ("rise", [1, 0, 2, 0], ["6", "8", "6", "6"]),
    ]
    assert bundles == [[1, 3], [0], [2]]
    assert [value(values[i], bundles[i]) for i in range(3)] == [14, 3, 4]
    assert is_ef1(values, bundles)
    assert is_pareto_optimal(values, bundles)


def test_two_agents_with_a_tie():
    values = [[1, 3, 2], [1, 1, 1]]
    stats = {}
    assert bkv_exact(values, stats=stats) == [[1, 2], [0]]
    assert [kind for kind, _, _ in stats["trace"]] == ["start", "swap", "rise"]
    assert stats["prices"] == [2, 3, 2]


def test_random_ef1_and_pareto_optimal():
    rng = random.Random(31)
    count = 0
    while count < 700:
        n = rng.randint(2, 4)
        m = rng.randint(1, 6 if n < 4 else 5)
        top = rng.choice([2, 4, 10, 30])
        values = [[rng.randint(1, top) for _ in range(m)] for _ in range(n)]
        stats = {}
        bundles = bkv_exact(values, stats=stats)
        assert sorted(g for b in bundles for g in b) == list(range(m))
        assert is_ef1(values, bundles)
        assert is_pareto_optimal(values, bundles)
        count += 1


def test_invariants_along_the_run():
    rng = random.Random(32)
    for _ in range(400):
        n, m = rng.randint(2, 5), rng.randint(2, 9)
        values = [[rng.randint(1, 12) for _ in range(m)] for _ in range(n)]
        stats = {}
        bundles = bkv_exact(values, stats=stats)
        last = None
        for kind, owner, p in stats["trace"]:
            assert holds_only_mbb_goods(values, owner, p)
            if last is not None:
                assert all(a >= b for a, b in zip(p, last))
                if kind == "rise":
                    assert any(a > b for a, b in zip(p, last))
            last = p
        assert is_price_ef1(bundles, stats["prices"])
        assert is_ef1(values, bundles)


def test_one_agent_and_identical_values():
    assert bkv_exact([[3, 1, 2]]) == [[0, 1, 2]]
    rng = random.Random(33)
    for _ in range(100):
        n, m = rng.randint(2, 4), rng.randint(1, 7)
        row = [rng.randint(1, 9) for _ in range(m)]
        values = [row] * n
        assert is_ef1(values, bkv_exact(values))


def test_price_ef1_check():
    p = [F(5), F(8), F(4), F(6)]
    assert not is_price_ef1(bundles_of([0, 0, 2, 0], 3), p)
    assert is_price_ef1([[1, 3], [0], [2]], [F(6), F(8), F(6), F(6)])


def test_bad_input_and_step_limit():
    with pytest.raises(ValueError):
        bkv_exact([])
    with pytest.raises(ValueError):
        bkv_exact([[1, 0], [1, 1]])
    with pytest.raises(ValueError):
        bkv_exact([[1, 2], [1]])
    with pytest.raises(RuntimeError):
        bkv_exact([[5, 8, 1, 6], [3, 1, 2, 2], [1, 5, 4, 4]], max_steps=0)

History

Barman, Krishnamurthy and Vaish presented the algorithm at EC 2018 (arXiv 2017). They write that establishing its running time is an intricate task, which their analysis does for the rounded instance. Before it, the only general route to EF1 and PO was maximum Nash welfare, from Caragiannis et al. (EC 2016), which is NP-hard to compute.

References

  1. Siddharth Barman, Sanath Kumar Krishnamurthy and Rohit Vaish, Finding fair and efficient allocations, Proceedings of the 19th ACM Conference on Economics and Computation (EC 2018), 557-574 (arXiv:1707.04731), Section 4 (hierarchy, violators and path-violators, Algorithm 1 with its three phases), Lemma 2 (pEF1 with MBB gives EF1), Lemmas 3 to 5, Theorems 1 to 3 and Remarks 1 and 2
  2. Ryoga Mahara, A polynomial-time algorithm for fair and efficient allocation with a fixed number of agents, arXiv:2411.01810 (November 2024), abstract (the open problem of polynomial time, and the algorithm for a fixed number of agents)

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 correctness
  • 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
  • History with a source
  • at least three sources
  • a scene preset for the example