Algorithm Search⌘K

Algorithmresearch

Aziz-Mackenzie protocol

Also called bounded envy-free cake cutting.

The first envy-free cake cutting protocol for n agents whose number of queries is bounded by a function of n, a tower of exponentials.

Time
O(n^(n^(n^(n^(n^n))))) worst
Space
O(n^(n^(n^(n^(n^n))))) extra
Where
n = the number of agents
Properties
deterministicofflinerecursive

The Aziz-Mackenzie protocol divides a cake among any number nn of agents so that no agent envies another, with a number of queries in the Robertson-Webb model that is bounded by a function of nn alone: at most nnnnnnn^{n^{n^{n^{n^n}}}}, a tower of six nn. It differs from the other envy-free protocols in its bound. The Brams-Taylor procedure also handles any nn and always stops, but its number of steps depends on the valuations and has no bound in nn. The Selfridge-Conway procedure is bounded but handles only three agents, and the Stromquist moving knife gives connected pieces to three agents but is not a finite protocol. The tower bound makes the protocol a result about what is possible, not a practical method.

In plain words

Several friends share a cake so that no friend wants another friend's piece. An older method does this, but the number of its steps has no limit set by the number of friends.

This method sets such a limit. It gives out the cake in rounds, as the older method does. In each round, a friend can build a lead over another friend: it thinks its own piece beats the other's piece by more than all the cake that is left. Once a friend has such a lead over everyone else, it no longer cares how the rest is shared, so it can step aside. The others then share the rest by the same method. The rounds are arranged so that leads come after a fixed number of steps. The limit is enormous, but it depends only on how many friends there are.

The problem

There are nn agents and a cake [0,1][0, 1]. Each agent ii has a nonnegative, additive and nonatomic valuation ViV_i with Vi([0,1])=1V_i([0, 1]) = 1. The protocol asks Eval and Cut queries and outputs disjoint pieces X1,…,XnX_1, \dots, X_n, each a finite union of intervals, that cover the cake, with Vi(Xi)≥Vi(Xj)V_i(X_i) \ge V_i(X_j) for all ii and jj. Its cost is the number of queries in the worst case over all valuations, and the goal is a bound that depends only on nn.

During the protocol, X1,…,XnX_1, \dots, X_n are the pieces given out so far and RR is the leftover. Agent ii dominates agent jj if Vi(Xi)−Vi(Xj)≥Vi(R)V_i(X_i) - V_i(X_j) \ge V_i(R), which is the irrevocable advantage of Brams and Taylor.

The algorithm

The pseudocode is a simplified outline. It shows how domination lets the protocol finish with fewer agents, not the exact order of the sub-protocols. The sub-protocols, and the counting that bounds them, are in the FOCS 2016 paper.

  1. AZIZ-MACKENZIE(agents N, leftover R)
  2. 1if |N| = 1 then give R to the agent in N; return
  3. 2repeat
  4. 3run the core protocol on R, with each agent of N in turn as cutter ▷ an envy-free partial allocation
  5. 4add the parts given out to the pieces; R ← what is left
  6. 5run the sub-protocols that turn the core rounds into domination
  7. 6until some agent i in N dominates every other agent in N
  8. 7AZIZ-MACKENZIE(N minus {i}, R) ▷ i no longer cares about R

The core protocol is a bounded sub-protocol that gives out part of the leftover with no envy. The other sub-protocols use the rounds where agents disagree about pieces to create domination. The key property is that each loop of lines L2 to L6 ends after a number of queries bounded by a function of ∣N∣|N|, which is the point where the Brams-Taylor procedure has no bound.

The code of this page is a toy, not the protocol of Aziz and Mackenzie, and it has none of their bounds. It works for three agents only. It keeps the recursion of lines L1 to L7, but with three agents a round is the first stage of the Selfridge-Conway procedure, and with two agents a round is divide and choose. These rounds cannot force domination, so the toy caps the number of rounds, and at the cap it divides the leftover with the second stage of the Selfridge-Conway procedure.

Example

Suppose that after some rounds with four agents, agent 1 values the pieces given out so far and the leftover as follows.

X1X_1 X2X_2 X3X_3 X4X_4 RR
V1V_1 0.40 0.15 0.20 0.20 0.05

For each jj, V1(X1)−V1(Xj)V_1(X_1) - V_1(X_j) is at least 0.40−0.20=0.20≥0.05=V1(R)0.40 - 0.20 = 0.20 \ge 0.05 = V_1(R). So agent 1 dominates the three others. In whatever way agents 2, 3 and 4 later share RR, each of their pieces stays worth at most 0.20+0.05=0.25<0.400.20 + 0.05 = 0.25 < 0.40 to agent 1. The protocol removes agent 1 and continues with three agents on RR. If V1(R)V_1(R) were 0.300.30, agent 1 would not dominate agent 3, and giving all of RR to agent 3 would make agent 1 envious.

Correctness

Domination lasts. Each core round divides a part PP of the leftover with no envy, so if ii dominates jj, then ii values its part of PP at least as much as the part of jj, and the leftover only shrinks. So Vi(Xi)−Vi(Xj)V_i(X_i) - V_i(X_j) does not decrease and Vi(R)V_i(R) does not increase.

No envy at the end, by induction on ∣N∣|N|. Before line L7, the pieces given out have no envy. In line L7, agent ii dominates every other agent of NN, so whatever part of RR an agent jj gets later, Vi(Xj)+Vi(R)≤Vi(Xi)V_i(X_j) + V_i(R) \le V_i(X_i), and ii does not envy jj. The other agents share RR envy-free among themselves, by induction, and they do not envy ii, because XiX_i does not grow and their own pieces do not shrink. With one agent, line L1 gives it all of RR and creates no envy. So the final division is envy-free, and, since it covers the cake, proportional.

Bounded. Aziz and Mackenzie prove that the loop in lines L2 to L6 ends after a number of queries bounded in terms of ∣N∣|N|, and that the bound for nn agents is at most nnnnnnn^{n^{n^{n^{n^n}}}}.

Proof: The Aziz-Mackenzie recursion is envy-free, and the toy for three agents is envy-freepartial

Setting. The cake is [0,1][0, 1]. Agents 1,…,n1, \dots, n have nonnegative, additive and nonatomic valuations ViV_i with Vi([0,1])=1V_i([0, 1]) = 1. At each moment the pieces X1,…,XnX_1, \dots, X_n given out so far and the leftover RR are disjoint and cover the cake. Agent ii dominates agent jj if Vi(Xi)−Vi(Xj)≥Vi(R)V_i(X_i) - V_i(X_j) \ge V_i(R). We refer to the lines L1 to L7 of the page, and we assume only that each round of line L3 gives out a part of RR with no envy among the agents of NN. This proof shows that the recursion is envy-free when it stops, and that the toy for three agents in impl/python is envy-free and stops. It does not prove that the loop of lines L2 to L6 ends within the bound of Aziz and Mackenzie; that is the theorem of their FOCS 2016 paper, and it is the reason for the status "partial".

Lemma 1 (domination lasts). If ii dominates jj before a round, it dominates jj after the round.

Proof. Let the round give the parts PkP_k of a part PP of RR with Vi(Pi)≥Vi(Pj)V_i(P_i) \ge V_i(P_j). Then Vi(Xi∪Pi)−Vi(Xj∪Pj)≥Vi(Xi)−Vi(Xj)≥Vi(R)≥Vi(R∖P)V_i(X_i \cup P_i) - V_i(X_j \cup P_j) \ge V_i(X_i) - V_i(X_j) \ge V_i(R) \ge V_i(R \setminus P). If ii is not in NN, it gets no part and jj gets Pj⊆RP_j \subseteq R; then Vi(Xi)−Vi(Xj∪Pj)≥Vi(R)−Vi(Pj)≥Vi(R∖P)V_i(X_i) - V_i(X_j \cup P_j) \ge V_i(R) - V_i(P_j) \ge V_i(R \setminus P), since Pj⊆PP_j \subseteq P. □\square

Lemma 2 (invariant). At every call of AZIZ-MACKENZIE(N,R)(N, R), there is no envy on the pieces given out, and every agent outside NN dominates every agent in NN.

Proof. At the first call, NN is all agents and nothing is given out. A round gives parts only to agents of NN, with no envy among them, so it keeps the first part of the invariant for pairs inside NN. An agent kk outside NN envies no one, because it dominates every agent of NN by Lemma 1, and Vk(Xk)≥Vk(Xj)+Vk(R)≥Vk(Xj∪Pj)V_k(X_k) \ge V_k(X_j) + V_k(R) \ge V_k(X_j \cup P_j); pieces of other agents outside NN do not change. No agent of NN envies kk, because XkX_k does not change and the pieces of NN only grow. Line L7 is reached when ii dominates every other agent of NN; then every agent outside N∖{i}N \setminus \{i\} dominates every agent in N∖{i}N \setminus \{i\}, by the invariant and Lemma 1. □\square

Theorem 1. If the recursion stops, the division is envy-free.

Proof. The recursion ends at line L1 with N={k}N = \{k\}. Before line L1 there is no envy, and every other agent ii dominates kk, so Vi(Xi)≥Vi(Xk)+Vi(R)=Vi(Xk∪R)V_i(X_i) \ge V_i(X_k) + V_i(R) = V_i(X_k \cup R). Agent kk only gains. No other piece changes. □\square

The toy. The toy has n=3n = 3. With three agents in NN, a round is stage one of the Selfridge-Conway procedure on RR, with the cutter taking turns. With two agents, a round is divide and choose on RR: one agent cuts RR into two parts of equal value to it, and the other picks the part it likes more. The toy checks for domination after each round.

Lemma 3 (toy rounds). Each toy round gives out a part of RR with no envy among the agents of NN. After a three-agent round with cutter cc, cc dominates the agent TT that took the trimmed piece. After a two-agent round, RR is empty.

Proof. In a three-agent round the chooser picks first; the trimmer values the trimmed piece and its second best piece equally and both at least as much as the third, and at most one of these two is taken before it; the cutter values the untrimmed pieces at Vc(R)/3V_c(R)/3 and the trimmed piece at Vc(R)/3−Vc(R′)V_c(R)/3 - V_c(R'), where R′R' is the trimmings, and the trimmed piece is never left for it. So the round has no envy, and the gain of cc over TT in this round is Vc(R′)V_c(R'). By induction over the earlier rounds, which have no envy, Vc(Xc)−Vc(XT)≥Vc(R′)V_c(X_c) - V_c(X_T) \ge V_c(R'). In divide and choose the chooser picks the better part and the cutter values both parts equally, and the two parts make up all of RR. □\square

Lemma 4 (the fallback). Suppose cc dominates TT among three agents in NN, and let uu be the third. If uu cuts RR into three parts of value Vu(R)/3V_u(R)/3 each, TT picks a best part, then cc picks a best remaining part, and uu takes the last, the final division is envy-free.

Proof. TT chooses first and uu values the parts equally, so neither envies another on RR. Agent cc can envy only TT on RR, and Vc(Xc)−Vc(XT)≥Vc(R)V_c(X_c) - V_c(X_T) \ge V_c(R) covers all of RR. □\square

Theorem 2. The toy stops and returns an envy-free division of [0,1][0, 1] among three agents.

Proof. With two agents, the first round leaves RR empty, and then each agent dominates the other, because the pieces have no envy and Vi(∅)=0V_i(\emptyset) = 0. So the loop ends after one round. With three agents, each pass of the loop either runs a round and adds 1 to the round counter, or, when the counter has reached max_rounds, returns through the fallback. The condition max_rounds >= 1 makes sure that at least one round ran, so the fallback has a cutter cc and a taker TT, and cc still dominates TT by Lemma 1. So the toy stops, and the result is envy-free by Lemma 4 or by Theorem 1. Every interval of RR goes to some agent, so the pieces cover the cake. □\square

The toy cannot force domination with three agents, which is why it needs the cap. The protocol of Aziz and Mackenzie forces domination with its core protocol and other sub-protocols, which this proof does not cover.

Complexity

The number of Robertson-Webb queries is at most nnnnnnn^{n^{n^{n^{n^n}}}} (Aziz and Mackenzie 2016). The best known lower bound for envy-free cake cutting is Ω(n2)\Omega(n^2) queries (Procaccia 2009), so the bounds are very far apart. Closing this gap is an open problem, as of the 2016 sources of this page. The extra space is the list of cuts and pieces, so it has the same bound. The arithmetic between queries is free in the model.

If the protocol is stopped early, it gives a partial allocation that is envy-free and proportional, in which each agent values its piece at least 1/n1/n of the whole cake, within n3(n2)nn^3 (n^2)^n queries. A variant gives an envy-free partial allocation with connected pieces, each worth at least 1/(3n)1/(3n) of the cake to its owner, with the same number of queries.

Properties

  • Envy-free and proportional, for every nn.
  • Bounded. The number of queries depends only on nn.
  • Pieces are not connected. An agent can get many intervals. With connected pieces, no finite protocol exists for n≥3n \ge 3, by Stromquist's impossibility theorem.
  • Deterministic and discrete. It uses only Eval and Cut queries.
  • Recursive. It removes one dominating agent at a time and recurses on fewer agents.

Variants and improvements

  • Four agents. Aziz and Mackenzie first gave a bounded envy-free protocol for four agents (STOC 2016), and then extended the ideas to any nn.
  • Partial allocations. The early-stopping versions above give envy-free partial allocations with much smaller bounds: exponential in nlog⁡nn \log n instead of a tower.
  • Chores. Dehghani, Farhadi, Hajiaghayi and Yami (2018) gave a bounded envy-free protocol for chore division with any number of agents.

When to use it

Use it as the reference result that envy-free cake cutting has bounded query complexity. For actual divisions its bound is far too large. For three agents use Selfridge-Conway; for proportional division use a protocol with O(nlog⁡n)O(n \log n) queries; and when some envy or some waste is allowed, use an approximate or partial method.

Pitfalls

  • Bounded is not small. For n=2n = 2 the tower of six nn is already 22655362^{2^{65536}}. The bound is a worst-case guarantee, not an estimate of a typical run.
  • Domination over everyone. The recursion may remove agent ii only when it dominates every remaining agent; domination over some of them is not enough.
  • Free disposal. The connected variant above throws part of the cake away. It is not a full envy-free division with connected pieces.

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.

agtcake.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Piecewise-constant cake valuations and a Robertson-Webb query oracle.

The cake is the interval [0, 1]. A valuation is a list of k nonnegative
Fraction densities d[0], ..., d[k - 1]. Density d[j] holds on the segment
[j/k, (j + 1)/k], so that segment has value d[j] / k. A valuation is
normalized when the value of the whole cake is 1, that is, sum(d) = k.

All numbers are Fraction, so every value and every cut point is exact.
This module holds no cake cutting protocol.
"""

from fractions import Fraction
from random import Random
from typing import Optional, Sequence

Valuation = list[Fraction]
Interval = tuple[Fraction, Fraction]

ZERO = Fraction(0)
ONE = Fraction(1)


def normalize(dens: Sequence) -> Valuation:
    """Scale nonnegative densities so that the whole cake has value 1."""
    d = [Fraction(x) for x in dens]
    if not d:
        raise ValueError("a valuation needs at least one segment")
    if any(x < 0 for x in d):
        raise ValueError("densities must be nonnegative")
    total = sum(d)
    if total == 0:
        raise ValueError("densities must not all be zero")
    k = len(d)
    return [x * k / total for x in d]


def _check_point(x: Fraction) -> None:
    if x < 0 or x > 1:
        raise ValueError("a point of the cake must be in [0, 1]")


def value(v: Valuation, a, b) -> Fraction:
    """Return the value of the interval [a, b] under v. Needs 0 <= a <= b <= 1."""
    a, b = Fraction(a), Fraction(b)
    _check_point(a)
    _check_point(b)
    if a > b:
        raise ValueError("value(v, a, b) needs a <= b")
    k = len(v)
    total = ZERO
    j = min(int(a * k), k - 1)
    while j < k:
        lo = Fraction(j, k)
        if lo >= b:
            break
        hi = Fraction(j + 1, k)
        left = a if a > lo else lo
        right = b if b < hi else hi
        if right > left:
            total += v[j] * (right - left)
        j += 1
    return total


def cut(v: Valuation, a, t) -> Optional[Fraction]:
    """Return the least x >= a with value(v, a, x) = t, or None if there is none."""
    a, t = Fraction(a), Fraction(t)
    _check_point(a)
    if t < 0:
        raise ValueError("cut(v, a, t) needs t >= 0")
    if t == 0:
        return a
    k = len(v)
    pos = a
    rest = t
    j = min(int(a * k), k - 1)
    while j < k:
        hi = Fraction(j + 1, k)
        d = v[j]
        if d > 0 and hi > pos:
            here = d * (hi - pos)
            if rest <= here:
                return pos + rest / d
            rest -= here
        if hi > pos:
            pos = hi
        j += 1
    return None


def piece_value(v: Valuation, piece: Sequence[Interval]) -> Fraction:
    """Return the value of a piece, given as a list of intervals (a, b)."""
    return sum((value(v, a, b) for a, b in piece), ZERO)


def random_valuation(rng: Random, k: int, hi: int) -> Valuation:
    """Return a normalized valuation with k segments and integer densities in 0..hi."""
    if k < 1 or hi < 1:
        raise ValueError("random_valuation needs k >= 1 and hi >= 1")
    while True:
        dens = [rng.randint(0, hi) for _ in range(k)]
        if any(dens):
            return normalize(dens)


class Oracle:
    """Answer Robertson-Webb queries for a list of valuations and count them.

    eval_query(i, a, b) returns V_i([a, b]). cut_query(i, a, t) returns the
    least x with V_i([a, x]) = t, or None. The lists evals and cuts hold the
    number of queries of each kind for each agent.
    """

    def __init__(self, valuations: Sequence[Valuation]) -> None:
        self.valuations = [list(v) for v in valuations]
        n = len(self.valuations)
        self.evals = [0] * n
        self.cuts = [0] * n

    @property
    def n(self) -> int:
        return len(self.valuations)

    def eval_query(self, i: int, a, b) -> Fraction:
        self.evals[i] += 1
        return value(self.valuations[i], a, b)

    def cut_query(self, i: int, a, t) -> Optional[Fraction]:
        self.cuts[i] += 1
        return cut(self.valuations[i], a, t)

    def total_evals(self) -> int:
        return sum(self.evals)

    def total_cuts(self) -> int:
        return sum(self.cuts)

    def total(self) -> int:
        return self.total_evals() + self.total_cuts()
aziz_mackenzie_protocol.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aziz-mackenzie-protocol/. The authors are listed in prov/3197Z9.jsonl.
"""A toy version of the Aziz-Mackenzie protocol, for three agents only.

This is a toy. It keeps the recursion of the page: give out parts of the
leftover in envy-free rounds until some agent dominates every other agent,
then remove that agent and divide the leftover among the others in the same
way. It does not implement the core protocol or the other sub-protocols of
Aziz and Mackenzie, so it has none of their bounds. With three agents a
round is the first stage of the Selfridge-Conway procedure, with the cutter
taking turns. With two agents a round is divide and choose, which leaves
nothing over. The toy cannot force domination with three agents, so after
max_rounds rounds it divides the leftover with the second stage of the
Selfridge-Conway procedure, which is envy-free because the cutter of the
last round dominates the agent that took the trimmed piece.
"""

from fractions import Fraction

from agtcake import Oracle

Interval = tuple[Fraction, Fraction]
Piece = list[Interval]


def piece_eval(oracle: Oracle, i: int, piece: Piece) -> Fraction:
    """V_i(piece), with one eval query per interval."""
    return sum((oracle.eval_query(i, a, b) for a, b in piece), Fraction(0))


def split_prefix(oracle: Oracle, i: int, piece: Piece, t: Fraction) -> tuple[Piece, Piece]:
    """Split a piece into a prefix of value t to agent i and the rest.

    The intervals of the piece are in increasing order. Needs t <= V_i(piece).
    """
    head: Piece = []
    rest: Piece = []
    left = t
    for idx, (a, b) in enumerate(piece):
        v = oracle.eval_query(i, a, b)
        if v <= left and left > 0:
            head.append((a, b))
            left -= v
            continue
        x = oracle.cut_query(i, a, left) if left > 0 else a
        if x > a:
            head.append((a, x))
        if b > x:
            rest.append((x, b))
        rest.extend(piece[idx + 1:])
        break
    return head, rest


def dominates_value(own: Fraction, other: Fraction, leftover: Fraction) -> bool:
    """V_i(X_i) - V_i(X_j) >= V_i(R)."""
    return own - other >= leftover


def dominates(oracle: Oracle, i: int, j: int, alloc: dict[int, Piece], rest: Piece) -> bool:
    return dominates_value(piece_eval(oracle, i, alloc[i]), piece_eval(oracle, i, alloc[j]),
                           piece_eval(oracle, i, rest))


def trimming_round(oracle: Oracle, rest: Piece, cutter: int, trimmer: int,
                   chooser: int) -> tuple[dict[int, Piece], Piece, int]:
    """Stage one of Selfridge-Conway on the leftover.

    Returns the three pieces given out, the new leftover (the trimmings) and
    the agent that took the trimmed piece.
    """
    third = piece_eval(oracle, cutter, rest) / 3
    p0, more = split_prefix(oracle, cutter, rest, third)
    p1, p2 = split_prefix(oracle, cutter, more, third)
    pieces = [p0, p1, p2]
    vals = [piece_eval(oracle, trimmer, p) for p in pieces]
    order = sorted(range(3), key=lambda k: (-vals[k], k))
    p, q = order[0], order[1]
    trimmings: Piece = []
    if vals[p] > vals[q]:
        pieces[p], trimmings = split_prefix(oracle, trimmer, pieces[p], vals[q])
    left = [0, 1, 2]
    cv = [piece_eval(oracle, chooser, pieces[k]) for k in left]
    c = cv.index(max(cv))
    left.remove(c)
    if p in left:
        t = p
    else:
        t = left[0] if vals[left[0]] >= vals[left[1]] else left[1]
    left.remove(t)
    give = {chooser: pieces[c], trimmer: pieces[t], cutter: pieces[left[0]]}
    taker = chooser if c == p else trimmer
    return give, trimmings, taker


def cut_and_choose(oracle: Oracle, rest: Piece, cutter: int, chooser: int) -> dict[int, Piece]:
    """Divide and choose on the leftover: it gives out all of it."""
    a, b = split_prefix(oracle, cutter, rest, piece_eval(oracle, cutter, rest) / 2)
    if piece_eval(oracle, chooser, a) >= piece_eval(oracle, chooser, b):
        return {chooser: a, cutter: b}
    return {chooser: b, cutter: a}


def finish_stage_two(oracle: Oracle, alloc: dict[int, Piece], rest: Piece, cutter: int,
                     taker: int) -> None:
    """Stage two of Selfridge-Conway: needs that cutter dominates taker."""
    other = 3 - cutter - taker
    third = piece_eval(oracle, other, rest) / 3
    a, more = split_prefix(oracle, other, rest, third)
    b, c = split_prefix(oracle, other, more, third)
    parts = [a, b, c]
    for agent in (taker, cutter):
        vals = [piece_eval(oracle, agent, part) for part in parts]
        alloc[agent].extend(parts.pop(vals.index(max(vals))))
    alloc[other].extend(parts[0])


class _Run:
    def __init__(self, oracle: Oracle, max_rounds: int) -> None:
        self.oracle = oracle
        self.max_rounds = max_rounds
        self.rounds = 0
        self.alloc: dict[int, Piece] = {i: [] for i in range(oracle.n)}

    def dominator(self, agents: list[int], rest: Piece) -> int | None:
        for i in agents:
            if all(dominates(self.oracle, i, j, self.alloc, rest) for j in agents if j != i):
                return i
        return None

    def divide(self, agents: list[int], rest: Piece) -> None:
        if len(agents) == 1:
            self.alloc[agents[0]].extend(rest)  # @line L1
            return
        last: tuple[int, int] | None = None
        turn = 0
        while True:  # @line L2
            if len(agents) == 2:
                give = cut_and_choose(self.oracle, rest, agents[turn % 2], agents[(turn + 1) % 2])  # @line L3
                rest = []
            else:
                if self.rounds == self.max_rounds and last is not None:
                    finish_stage_two(self.oracle, self.alloc, rest, *last)
                    return
                cutter = agents[turn % 3]
                a, b = [x for x in agents if x != cutter]
                trimmer, chooser = (a, b) if (turn // 3) % 2 == 0 else (b, a)
                give, rest, taker = trimming_round(self.oracle, rest, cutter, trimmer, chooser)  # @line L3
                # the toy has no sub-protocols for domination; it only records
                # that the cutter now dominates the taker of the trimmed piece
                last = (cutter, taker)  # @line L5
            for agent, piece in give.items():
                self.alloc[agent].extend(piece)  # @line L4
            self.rounds += 1
            turn += 1
            i = self.dominator(agents, rest)  # @line L6
            if i is not None:
                break
        self.divide([x for x in agents if x != i], rest)  # @line L7


def aziz_mackenzie_toy(oracle: Oracle, max_rounds: int = 40) -> tuple[dict[int, Piece], int]:
    """Return an envy-free division of [0, 1] among three agents and the number of rounds."""
    if oracle.n != 3:
        raise ValueError("this toy is for three agents")
    if max_rounds < 1:
        raise ValueError("max_rounds must be at least 1")
    run = _Run(oracle, max_rounds)
    run.divide([0, 1, 2], [(Fraction(0), Fraction(1))])
    return run.alloc, run.rounds
test_aziz_mackenzie_protocol.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aziz-mackenzie-protocol/. The authors are listed in prov/3197Z9.jsonl.
# Tests of a toy for three agents. They do not test the protocol of Aziz and Mackenzie or its bound.

import random
from fractions import Fraction

import pytest

from agtcake import Oracle, normalize, piece_value, random_valuation
from aziz_mackenzie_protocol import (
    aziz_mackenzie_toy,
    cut_and_choose,
    dominates,
    dominates_value,
    piece_eval,
    trimming_round,
)

F = Fraction


def check_partition(alloc) -> None:
    """The pieces are disjoint and cover [0, 1]."""
    assert sorted(alloc) == [0, 1, 2]
    ivs = sorted(iv for i in range(3) for iv in alloc[i])
    assert ivs[0][0] == 0 and ivs[-1][1] == 1
    for (a1, b1), (a2, b2) in zip(ivs, ivs[1:]):
        assert a1 < b1 == a2 < b2


def check_envy_free(vals, alloc) -> None:
    for i in range(3):
        own = piece_value(vals[i], alloc[i])
        for j in range(3):
            assert own >= piece_value(vals[i], alloc[j])


def test_page_example_domination() -> None:
    # The row of agent 1 in the example: X_1 = 0.40, X_2 = 0.15, X_3 = X_4 = 0.20, R = 0.05.
    own = F(40, 100)
    others = [F(15, 100), F(20, 100), F(20, 100)]
    assert all(dominates_value(own, x, F(5, 100)) for x in others)
    # With V_1(R) = 0.30, agent 1 does not dominate agent 3.
    assert not dominates_value(own, F(20, 100), F(30, 100))


def test_round_makes_cutter_dominate_taker() -> None:
    rng = random.Random(8)
    for _ in range(100):
        vals = [random_valuation(rng, 6, 5) for _ in range(3)]
        o = Oracle(vals)
        give, rest, taker = trimming_round(o, [(F(0), F(1))], 1, 2, 0)
        alloc = {i: list(give[i]) for i in range(3)}
        for i in range(3):
            for j in range(3):
                assert piece_eval(o, i, alloc[i]) >= piece_eval(o, i, alloc[j])
        assert dominates(o, 1, taker, alloc, rest)


def test_cut_and_choose_gives_out_everything() -> None:
    rng = random.Random(4)
    for _ in range(50):
        vals = [random_valuation(rng, 5, 5) for _ in range(3)]
        o = Oracle(vals)
        rest = [(F(0), F(1, 3)), (F(1, 2), F(1))]
        give = cut_and_choose(o, rest, 0, 2)
        assert sorted(give) == [0, 2]
        assert sum(b - a for p in give.values() for a, b in p) == F(1, 3) + F(1, 2)
        assert piece_eval(o, 2, give[2]) >= piece_eval(o, 2, give[0])
        assert piece_eval(o, 0, give[0]) == piece_eval(o, 0, give[2])


def test_identical_valuations() -> None:
    rng = random.Random(3)
    for _ in range(20):
        v = random_valuation(rng, rng.randint(1, 8), 5)
        alloc, rounds = aziz_mackenzie_toy(Oracle([v, v, v]))
        check_partition(alloc)
        assert all(piece_value(v, alloc[i]) == F(1, 3) for i in range(3))


def test_random_valuations() -> None:
    rng = random.Random(2024)
    for _ in range(100):
        vals = [random_valuation(rng, rng.randint(1, 6), 5) for _ in range(3)]
        o = Oracle(vals)
        alloc, rounds = aziz_mackenzie_toy(o, max_rounds=12)
        check_partition(alloc)
        check_envy_free(vals, alloc)
        assert 1 <= rounds <= 13


def test_round_cap_uses_the_fallback() -> None:
    vals = [normalize([1, 2, 3, 1, 1, 2]), normalize([3, 1, 1, 2, 2, 1]), normalize([1, 1, 2, 3, 1, 2])]
    for cap in (1, 2, 3):
        alloc, rounds = aziz_mackenzie_toy(Oracle(vals), max_rounds=cap)
        assert rounds <= cap + 1
        check_partition(alloc)
        check_envy_free(vals, alloc)


def test_only_three_agents() -> None:
    v = normalize([1])
    with pytest.raises(ValueError):
        aziz_mackenzie_toy(Oracle([v, v]))
    with pytest.raises(ValueError):
        aziz_mackenzie_toy(Oracle([v, v, v]), max_rounds=0)

History

Envy-free cake cutting for three agents was solved by Selfridge and Conway around 1960, and Brams and Taylor gave a finite protocol for any nn in 1995, without a bound in nn. Whether a bounded protocol exists for n≥4n \ge 4 was a well-known open question. Haris Aziz and Simon Mackenzie answered it for four agents in a paper posted in 2015 and presented at STOC 2016, and for any number of agents at FOCS 2016.

References

  1. Haris Aziz and Simon Mackenzie, A discrete and bounded envy-free cake cutting protocol for any number of agents, FOCS 2016, pp. 416-427, arXiv:1604.03655, the abstract (the bound of a tower of six n, and the partial allocations with n^3 (n^2)^n queries)
  2. Haris Aziz and Simon Mackenzie, A discrete and bounded envy-free cake cutting protocol for four agents, STOC 2016, arXiv:1508.05143, the abstract (the first bounded envy-free protocol for four agents)
  3. Steven J. Brams and Alan D. Taylor, An envy-free cake division protocol, American Mathematical Monthly 102(1) (1995), pp. 9-18 (the finite but unbounded protocol that this one improves)
  4. Felix Brandt, Vincent Conitzer, Ulle Endriss, Jerome Lang and Ariel D. Procaccia (eds.), Handbook of Computational Social Choice, Cambridge University Press, 2016, Chapter 13, Ariel D. Procaccia, Cake Cutting Algorithms (pp. 311-330)

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
  • a scene preset for the example