Algorithm Search⌘K

Algorithmresearch

Method of equal shares

Also called Rule X.

Gives each voter an equal budget and buys candidates or projects whose supporters can cover the cost at the lowest share each.

Time
O(k m n log n) worst
Space
O(m n) extra
Where
k = the committee size; m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
Dominik Peters, Piotr Skowron, Grzegorz Pierczynski, 2020

The method of equal shares (MES) is a voting rule for approval ballots that elects a committee or chooses projects for a participatory budget. Each voter gets an equal part of the budget, and the rule buys candidates one at a time, each time the candidate whose supporters can pay for it with the smallest equal share each. It runs in polynomial time and satisfies extended justified representation. Proportional approval voting also satisfies this axiom, but it is NP-hard to compute.

In plain words

Every voter gets the same amount of money at the start. A candidate has a price, and only the voters who want it may pay. For each candidate, ask how much each supporter must pay if they split the price as equally as they can, and voters who have less money pay all that they have. Buy the candidate for which this share is smallest, take the money from its supporters, and ask again. Stop when no candidate can be paid for. A large group has more money, so it buys more, but every purchase costs it money, so a small group keeps money for its own choices. If seats are still empty at the end, a second rule fills them.

The problem

The input is an approval profile, that is, for each voter i=1,…,ni = 1, \ldots, n a set AiA_i of approved candidates among 0,…,m−10, \ldots, m - 1, and a committee size kk with 0≤k≤m0 \le k \le m. For a candidate cc, N(c)N(c) is the set of voters who approve cc. The output is a committee WW of kk candidates.

In the budgeting form, candidate cc is a project with a cost cost(c)>0\mathrm{cost}(c) > 0, and the total budget is BB. The committee form is the case where every cost is 11 and B=kB = k. In the budgeting form, the rule stops after phase 1 and returns the bought projects.

Ties go to the smallest candidate index. In the completion, a candidate that no voter approves is added only when no supported candidate is left, smallest index first.

The algorithm

  1. EQUAL-SHARES(A_1, ..., A_n, m, k)
  2. 1x_i ← k/n for every voter i; W ← empty list
  3. 2repeat
  4. 3for each c ∉ W: ρ(c) ← the least ρ with Σ_{i ∈ N(c)} min(ρ, x_i) = 1, undefined if Σ_{i ∈ N(c)} x_i < 1
  5. 4c* ← the c with the least defined ρ(c), ties to the smallest index
  6. 5if no ρ(c) is defined then leave the loop
  7. 6append c* to W
  8. 7x_i ← x_i - min(ρ(c*), x_i) for every i ∈ N(c*)
  9. 8y_i ← -x_i for every voter i
  10. 9while |W| < k: add a candidate by sequential Phragmen started from the loads y
  11. 10return W

Lines L1 to L7 are phase 1. To compute ρ(c)\rho(c) on line L3, sort the budgets of the supporters in increasing order. The voters with small budgets pay all they have, and the others pay an equal share of what remains. In the budgeting form, line L1 gives each voter B/nB/n, and the 11 on line L3 becomes cost(c)\mathrm{cost}(c).

Lines L8 and L9 are the completion of Lackner and Skowron (Rule 11). Phase 1 can leave seats empty, and the completion runs sequential Phragmen where each voter starts with the load −xi-x_i, so that unspent money counts as a credit.

Example

This is Example 2.12 of Lackner and Skowron. The candidates are a,b,c,da, b, c, d, k=3k = 3, and eight voters have the ballots

3×{c,d},2×{a,b},2×{a,c},1×{b,d}.3 \times \{c, d\}, \quad 2 \times \{a, b\}, \quad 2 \times \{a, c\}, \quad 1 \times \{b, d\}.

Each voter starts with 3/83/8.

round ρ(a)\rho(a) ρ(b)\rho(b) ρ(c)\rho(c) ρ(d)\rho(d) bought
1 1/41/4 1/31/3 1/51/5 1/41/4 cc
2 13/4013/40 1/31/3 none aa
3 none none stop

In round 1 the five supporters of cc pay 1/51/5 each and keep 7/407/40. In round 2 the two {a,c}\{a, c\} voters have only 7/407/40 each, so they pay all of it, and the two {a,b}\{a, b\} voters pay (1−7/20)/2=13/40(1 - 7/20)/2 = 13/40 each. The supporters of dd have 3⋅7/40+3/8=9/10<13 \cdot 7/40 + 3/8 = 9/10 < 1 in total, so dd is not affordable. In round 3 neither bb nor dd is affordable, and phase 1 ends with {c,a}\{c, a\}.

The completion starts from the loads −7/40-7/40 for the {c,d}\{c, d\} voters, −1/20-1/20 for the {a,b}\{a, b\} voters, 00 for the {a,c}\{a, c\} voters and −3/8-3/8 for the {b,d}\{b, d\} voter. Then dd needs the time (1−3⋅7/40−3/8)/4=1/40(1 - 3 \cdot 7/40 - 3/8)/4 = 1/40 and bb needs (1−2/20−3/8)/3=7/40(1 - 2/20 - 3/8)/3 = 7/40, so dd is added. The committee is {a,c,d}\{a, c, d\}. Sequential Phragmen elects {b,c,d}\{b, c, d\} on the same profile.

Correctness

The full proof is in proofs/correctness.md. The sorted computation on line L3 gives the least price exactly, no voter ever pays more than it has, and the payments for each bought candidate add up to its cost. So phase 1 buys at most kk candidates, and the bought prices never decrease.

For EJR, suppose a group SS of s≥ℓn/ks \ge \ell n / k voters approves ℓ\ell common candidates, but each voter of SS approves at most ℓ−1\ell - 1 members bought in phase 1. Some common candidate cc is never bought. Look at the first round that buys at a price above 1/s1/s or buys nothing. Before it, each voter of SS paid at most 1/s1/s for each of at most ℓ−1\ell - 1 members, so each still has at least k/n−(ℓ−1)/s≥1/sk/n - (\ell - 1)/s \ge 1/s. Then the voters of SS alone can pay for cc at the price 1/s1/s, which contradicts the choice of the round. The completion only adds members, so EJR still holds.

Proof: The price rho is computed exactly, budgets are never overspent, and the committee satisfies extended justified representationfull

An approval profile has ballots A1,…,An⊆{0,…,m−1}A_1, \ldots, A_n \subseteq \{0, \ldots, m - 1\} with n≥1n \ge 1, and N(c)={i:c∈Ai}N(c) = \{i : c \in A_i\}. Each candidate cc has a cost cost(c)>0\mathrm{cost}(c) > 0, and the total budget is BB. For committees, every cost is 11 and B=kB = k. Each voter starts with xi=B/nx_i = B / n.

In a round, a candidate cc that is not yet bought is affordable if ∑i∈N(c)xi≥cost(c)\sum_{i \in N(c)} x_i \ge \mathrm{cost}(c). Its price is the least ρ\rho with

fc(ρ)=∑i∈N(c)min⁡(ρ,xi)=cost(c).f_c(\rho) = \sum_{i \in N(c)} \min(\rho, x_i) = \mathrm{cost}(c).

The round buys the affordable candidate with the least price, ties to the smallest index, and each supporter ii pays min⁡(ρ,xi)\min(\rho, x_i). Phase 1 ends when no candidate is affordable. For committees, phase 2 runs sequential Phragmen from the loads yi=−xiy_i = -x_i until there are kk members.

Computing the price

The function fcf_c is continuous and nondecreasing, with fc(0)=0f_c(0) = 0 and fc(ρ)=∑i∈N(c)xif_c(\rho) = \sum_{i \in N(c)} x_i for ρ≥max⁡ixi\rho \ge \max_i x_i. So a price exists exactly when cc is affordable.

rho sorts the budgets b0≤b1≤⋯≤bs−1b_0 \le b_1 \le \cdots \le b_{s-1} and keeps Rj=cost(c)−∑j′<jbj′R_j = \mathrm{cost}(c) - \sum_{j' < j} b_{j'}. At step jj it tests bj(s−j)≥Rjb_j (s - j) \ge R_j.

  • If the test fails at every step, the failed test at step s−1s - 1 gives bs−1<Rs−1b_{s-1} < R_{s-1}, so ∑b<cost(c)\sum b < \mathrm{cost}(c), and rho returns None. Conversely, if ∑b≥cost(c)\sum b \ge \mathrm{cost}(c), the test at step s−1s - 1 holds if no earlier test holds.
  • If the test first holds at step jj, let r=Rj/(s−j)r = R_j / (s - j). Then r≤bj≤bj+1≤⋯r \le b_j \le b_{j+1} \le \cdots. If j>0j > 0, the failed test at step j−1j - 1 says bj−1(s−j+1)<Rj−1=Rj+bj−1b_{j-1}(s - j + 1) < R_{j-1} = R_j + b_{j-1}, so bj−1(s−j)<Rjb_{j-1} (s - j) < R_j and bj−1<rb_{j-1} < r. Hence the voters 0,…,j−10, \ldots, j - 1 pay their whole budgets, the others pay rr, and fc(r)=∑j′<jbj′+(s−j)r=cost(c)f_c(r) = \sum_{j' < j} b_{j'} + (s - j) r = \mathrm{cost}(c). For ρ<r\rho < r, the s−j≥1s - j \ge 1 voters with b≥rb \ge r pay ρ<r\rho < r, so fc(ρ)<fc(r)f_c(\rho) < f_c(r). So rr is the least price.

Budgets

Each payment min⁡(ρ,xi)\min(\rho, x_i) is at most xix_i, so no budget becomes negative, and the payments for cc add up to fc(ρ)=cost(c)f_c(\rho) = \mathrm{cost}(c). So after phase 1, the total cost of the bought candidates plus the leftover budgets equals BB. For committees, phase 1 buys at most kk candidates, because each costs 11 and the budgets add up to kk.

Budgets only decrease, so each fcf_c only decreases, and the price of each candidate only increases. Hence the prices of the bought candidates do not decrease from round to round.

Extended justified representation

A committee WW satisfies extended justified representation (EJR) if for every ℓ\ell with 1≤ℓ≤k1 \le \ell \le k and every nonempty group SS of voters with ∣S∣≥ℓn/k|S| \ge \ell n / k and ∣⋂i∈SAi∣≥ℓ|\bigcap_{i \in S} A_i| \ge \ell, some voter i∈Si \in S has ∣Ai∩W∣≥ℓ|A_i \cap W| \ge \ell.

Theorem. For committees (all costs 11, B=kB = k), the set W1W_1 bought in phase 1 satisfies EJR. So does every committee that contains W1W_1, in particular the completed committee.

Proof. Suppose ℓ\ell and SS violate EJR for W1W_1: every voter of SS approves at most ℓ−1\ell - 1 members of W1W_1. Let s=∣S∣s = |S|. The common set T=⋂i∈SAiT = \bigcap_{i \in S} A_i has at least ℓ\ell candidates, and a voter of SS approves at most ℓ−1\ell - 1 members of W1W_1, so some c∈Tc \in T is not in W1W_1. This cc is never bought, so it is a candidate in every round.

Consider the rounds of phase 1 in order, and let round rr be the first round that either buys a candidate with price greater than 1/s1/s or finds no affordable candidate. Such a round exists, because phase 1 ends with a round that finds no affordable candidate. Before round rr, every price was at most 1/s1/s, so every payment was at most 1/s1/s. A voter of SS pays only for members of W1W_1 that it approves, at most ℓ−1\ell - 1 of them. So at the start of round rr, every voter of SS has at least

kn−ℓ−1s≥ℓs−ℓ−1s=1s,\frac{k}{n} - \frac{\ell - 1}{s} \ge \frac{\ell}{s} - \frac{\ell - 1}{s} = \frac{1}{s},

using s≥ℓn/ks \ge \ell n / k. Then fc(1/s)≥∑i∈Smin⁡(1/s,xi)=s⋅1/s=1f_c(1/s) \ge \sum_{i \in S} \min(1/s, x_i) = s \cdot 1/s = 1, so cc is affordable in round rr with price at most 1/s1/s. So round rr finds an affordable candidate and buys one with price at most 1/s1/s, which contradicts the choice of rr.

If W⊇W1W \supseteq W_1, every voter has at least as many approved members in WW as in W1W_1, so WW satisfies EJR as well. □\square

EJR implies proportional justified representation and justified representation. The completion by sequential Phragmen is not needed for EJR; it only fills the committee to kk members. The tests also check that the rule gives the D'Hondt seat counts on party lists, as Peters and Skowron proved.

Running time

A round computes the price of at most mm candidates; for cc this sorts ∣N(c)∣|N(c)| budgets. So a round takes O(∑c∣N(c)∣log⁡n)=O(mnlog⁡n)O(\sum_c |N(c)| \log n) = O(mn \log n) arithmetic operations. For committees phase 1 has at most k+1k + 1 rounds and the completion takes O(kmn)O(kmn), so the total is O(kmnlog⁡n)O(kmn \log n). With general costs phase 1 has at most m+1m + 1 rounds, O(m2nlog⁡n)O(m^2 n \log n) in total.

Complexity

Line L3 sorts the budgets of ∣N(c)∣|N(c)| supporters for each candidate, O(mnlog⁡n)O(mn \log n) arithmetic operations in each round. Phase 1 has at most k+1k + 1 rounds, and the completion takes O(kmn)O(kmn), so the rule takes O(kmnlog⁡n)O(kmn \log n) operations in the word RAM model and O(mn)O(mn) space for the lists of supporters. In the budgeting form, phase 1 has at most m+1m + 1 rounds. With exact fractions the numbers can grow, so the bit cost is larger than the count of operations.

Properties

  • Extended justified representation. The committee after phase 1 already satisfies EJR, so it also satisfies PJR and JR (Lackner and Skowron, Table 4.1).
  • Priceable and laminar proportional (Lackner and Skowron, Table 4.1).
  • D'Hondt on party lists. With disjoint party lists, the rule gives the seat numbers of the D'Hondt method (Lackner and Skowron, Table 4.1).
  • Not committee monotone, not Pareto efficient and not consistent (Lackner and Skowron, Table 3.1).
  • Not in the core. Some profiles have a group that could buy a better committee with its own share of the seats (Lackner and Skowron, Section 4.4, citing Peters and Skowron). Whether every approval profile has a committee in the core is open as of August 2022 (same section).
  • Anonymous. The resolute rule with fixed tie-breaking is not neutral; the set of committees over all tie-breaking orders is.

Variants and improvements

  • Additive utilities. If voter ii has utility ui(c)u_i(c) for project cc, voter ii pays min⁡(xi,ρ ui(c))\min(x_i, \rho \, u_i(c)), and ρ\rho is a price per unit of utility. Peters, Pierczynski and Skowron (2021) study this form for participatory budgeting.
  • Other completions. Phase 1 often leaves money unspent. Lackner and Skowron complete by sequential Phragmen. Another way is to raise the starting budget and run phase 1 again until the outcome is full. The choice changes the outcome but not EJR, because the completion only adds members.
  • Sequential Phragmen. Voters earn money at a steady rate instead of getting it all at the start. This rule is committee monotone but satisfies only PJR.

When to use it

Use it to elect a committee from approval ballots when extended justified representation is required and the committee must be computed in polynomial time, or to choose projects for a participatory budget where every group should get a share of the money in proportion to its size. If the committee must grow consistently with kk, use sequential Phragmen. If total approval matters more than fairness to groups, the usual greedy rule, which funds the most approved projects first while money is left, or a knapsack solution is simpler.

Pitfalls

  • Phase 1 can be short. In Example 2.11 of Lackner and Skowron, with k=4k = 4, phase 1 buys only one candidate. Always state the completion.
  • Paying more than the budget. A voter with less than ρ\rho pays only what it has. Charging ρ\rho to every supporter can make budgets negative and gives a different rule.
  • Floating point. Prices often tie in small instances, and rounding can change the order. Use exact fractions and state the tie-breaking rule.
  • Expecting committee monotonicity. The committee for k+1k + 1 seats can drop a member of the committee for kk seats, because every budget changes with kk.

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.

agtprefs.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Preference profiles, majority relations and brute force axiom checkers.

The candidates are 0, ..., m - 1. A ranking is a tuple of all m candidates, best first:
(2, 0, 1) means that 2 is preferred to 0 and 0 to 1. A profile is a tuple of n rankings,
one per voter. An approval ballot is a frozenset of candidates, and an approval profile is
a tuple of n ballots.

A rule is a function rule(profile, m). A resolute rule returns one candidate (an int); a
correspondence returns a nonempty frozenset of candidates. The checkers accept both: they
turn an int w into frozenset({w}).

Each checker takes the rule, m and n, and by default tries every profile of all_profiles(m,
n). Pass profiles= to check a given list of profiles instead (for example approval profiles,
or a random sample when the full domain is too large). Each checker returns None when the
property holds on every profile it tried, and else a counterexample tuple.

There is no voting rule in this module. Every count is an exact integer.
"""

from itertools import permutations, product


# ---------------------------------------------------------------- rankings and profiles


def all_rankings(m):
    """Return the list of the m! rankings of 0, ..., m - 1, in lexicographic order."""
    return list(permutations(range(m)))


def all_profiles(m, n):
    """Yield every profile of n rankings of m candidates: (m!)^n profiles, voters ordered."""
    return product(all_rankings(m), repeat=n)


def random_profile(rng, m, n):
    """Return a profile of n rankings drawn uniformly and independently (impartial culture)."""
    return tuple(tuple(rng.sample(range(m), m)) for _ in range(n))


def position(r, a):
    """Return the position of candidate a in ranking r: 0 for the top."""
    return r.index(a)


def prefers(r, a, b):
    """Return True if ranking r puts a above b."""
    return r.index(a) < r.index(b)


def pairwise(profile, m):
    """Return the m by m matrix N with N[a][b] the number of voters who rank a above b."""
    N = [[0] * m for _ in range(m)]
    for r in profile:
        for i, a in enumerate(r):
            for b in r[i + 1:]:
                N[a][b] += 1
    return N


def margins(profile, m):
    """Return the m by m matrix of margins N[a][b] - N[b][a]."""
    N = pairwise(profile, m)
    return [[N[a][b] - N[b][a] for b in range(m)] for a in range(m)]


def condorcet_winner(profile, m):
    """Return the candidate with a positive margin over every other candidate, or None."""
    M = margins(profile, m)
    for a in range(m):
        if all(M[a][b] > 0 for b in range(m) if b != a):
            return a
    return None


def weak_condorcet_winners(profile, m):
    """Return the frozenset of candidates whose margin over every other candidate is >= 0."""
    M = margins(profile, m)
    return frozenset(a for a in range(m) if all(M[a][b] >= 0 for b in range(m) if b != a))


def kendall_tau(r1, r2):
    """Return the number of pairs of candidates that r1 and r2 order differently."""
    pos = {a: i for i, a in enumerate(r2)}
    seq = [pos[a] for a in r1]
    return sum(1 for i in range(len(seq)) for j in range(i + 1, len(seq)) if seq[i] > seq[j])


def is_single_peaked_on(profile, axis):
    """Return True if every ranking of the profile is single-peaked on the axis.

    axis is a tuple of all candidates, left to right. A ranking is single-peaked on the axis
    exactly when, for each k, its k best candidates form a contiguous block of the axis.
    """
    where = {a: i for i, a in enumerate(axis)}
    for r in profile:
        lo = hi = where[r[0]]
        for a in r[1:]:
            p = where[a]
            if p == lo - 1:
                lo = p
            elif p == hi + 1:
                hi = p
            else:
                return False
    return True


def lex_tiebreak(candidates):
    """Return the candidate with the smallest index: the default tie-breaking rule."""
    return min(candidates)


def random_approval_profile(rng, m, n, p):
    """Return n approval ballots; each voter approves each candidate with probability p."""
    return tuple(frozenset(a for a in range(m) if rng.random() < p) for _ in range(n))


def permute_profile(profile, pi):
    """Rename the candidates: candidate a becomes pi[a]. Works for rankings and approval ballots."""
    out = []
    for ballot in profile:
        if isinstance(ballot, (set, frozenset)):
            out.append(frozenset(pi[a] for a in ballot))
        else:
            out.append(tuple(pi[a] for a in ballot))
    return tuple(out)


# ---------------------------------------------------------------- axiom checkers


def _as_set(result):
    if isinstance(result, (set, frozenset)):
        return frozenset(result)
    return frozenset([result])


def _domain(m, n, profiles):
    return all_profiles(m, n) if profiles is None else profiles


def _candidate_generators(m):
    """A transposition and an m-cycle: together they generate every permutation of the candidates."""
    gens = []
    if m >= 2:
        swap = list(range(m))
        swap[0], swap[1] = 1, 0
        gens.append(tuple(swap))
    if m >= 3:
        gens.append(tuple((a + 1) % m for a in range(m)))
    return gens


def check_anonymity(rule, m, n, profiles=None):
    """Check that permuting the voters does not change the result.

    It tries the swap of voters 0 and 1 and the cyclic shift of the voters. These generate all
    permutations, so on the full domain this is a complete test. Returns None or
    (profile, permuted_profile).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        if len(P) < 2:
            continue
        base = _as_set(rule(P, m))
        others = [(P[1], P[0]) + P[2:], P[1:] + P[:1]]
        for Q in others:
            if _as_set(rule(Q, m)) != base:
                return (P, Q)
    return None


def check_neutrality(rule, m, n, profiles=None):
    """Check that renaming the candidates by pi renames the result by pi.

    It tries a transposition and an m-cycle of the candidates, which generate all permutations.
    A resolute rule with a fixed tie-breaking order usually fails this test; test its
    correspondence instead. Returns None or (profile, pi).
    """
    gens = _candidate_generators(m)
    for P in _domain(m, n, profiles):
        P = tuple(P)
        base = _as_set(rule(P, m))
        for pi in gens:
            if _as_set(rule(permute_profile(P, pi), m)) != frozenset(pi[a] for a in base):
                return (P, pi)
    return None


def check_pareto(rule, m, n, profiles=None):
    """Check that no candidate b wins when every voter ranks some a above b.

    Returns None or (profile, a, b).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        W = _as_set(rule(P, m))
        N = pairwise(P, m)
        for b in W:
            for a in range(m):
                if a != b and N[a][b] == len(P):
                    return (P, a, b)
    return None


def check_condorcet_consistency(rule, m, n, profiles=None):
    """Check that a Condorcet winner, when one exists, is the unique winner.

    Returns None or (profile, condorcet_winner).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        c = condorcet_winner(P, m)
        if c is not None and _as_set(rule(P, m)) != frozenset([c]):
            return (P, c)
    return None


def _raise_once(r, w):
    """Return r with w moved up one place, or None if w is already on top."""
    i = r.index(w)
    if i == 0:
        return None
    s = list(r)
    s[i - 1], s[i] = s[i], s[i - 1]
    return tuple(s)


def check_monotonicity(rule, m, n, profiles=None):
    """Check that a winner stays a winner when one voter moves it up one place.

    Every raise of w, with no other change in the relative order of the others, is a chain of
    such one-place moves, so on the full domain this is a complete test. For a correspondence
    the test is that w stays in the winning set. Returns None or (profile, raised_profile, w).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        for w in _as_set(rule(P, m)):
            for i, r in enumerate(P):
                s = _raise_once(r, w)
                if s is None:
                    continue
                Q = P[:i] + (s,) + P[i + 1:]
                if w not in _as_set(rule(Q, m)):
                    return (P, Q, w)
    return None


def find_manipulation(rule, m, n, profiles=None):
    """Search for a voter who gets a strictly better winner by a false ranking.

    The rule must be resolute (a correspondence must return one winner on every profile it
    is called on). Returns None or (profile, voter, false_ranking): with the false ranking in
    place of the voter's true one, the winner is one that the true ranking strictly prefers.
    """
    rankings = all_rankings(m)
    for P in _domain(m, n, profiles):
        P = tuple(P)
        w = _single(rule(P, m))
        for i, r in enumerate(P):
            if r[0] == w:
                continue
            for s in rankings:
                if s == r:
                    continue
                Q = P[:i] + (s,) + P[i + 1:]
                if prefers(r, _single(rule(Q, m)), w):
                    return (P, i, s)
    return None


def _single(result):
    W = _as_set(result)
    if len(W) != 1:
        raise ValueError("find_manipulation needs a resolute rule")
    return next(iter(W))
method_of_equal_shares.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/method-of-equal-shares/. The authors are listed in prov/KK2YJY.jsonl.
"""The method of equal shares (MES, first called Rule X) for approval ballots.

An approval profile is a sequence of n ballots, each a set of candidates (or projects) among
0, ..., m - 1. Every voter starts with an equal share of the total budget. A candidate c with
cost cost[c] is affordable if its supporters have at least cost[c] left. For an affordable
candidate, rho(c) is the least amount such that the supporters pay cost[c] in total when each
pays min(rho, its budget). Each round buys the affordable candidate with the least rho, ties
to the smallest index. For committees (all costs 1, budget k), the committee is completed by
seq-Phragmen started from the leftover budgets, as in Lackner and Skowron (Rule 11). Every
amount is an exact Fraction.
"""

from fractions import Fraction
from typing import List, Optional, Sequence, Tuple


def rho(budgets: Sequence[Fraction], cost) -> Optional[Fraction]:
    """Return the least r with sum(min(r, b) for b in budgets) == cost, or None if sum < cost."""
    remaining = Fraction(cost)
    b = sorted(budgets)
    s = len(b)
    for j, x in enumerate(b):
        if x * (s - j) >= remaining:
            return remaining / (s - j)
        remaining -= x
    return None


def equal_shares_phase1(profile, m: int, budget, costs: Optional[Sequence] = None
                        ) -> Tuple[List[int], List[Fraction], List[Fraction]]:
    """Run the first phase. Return (order, rhos, leftover budgets of the voters).

    Each voter starts with budget / n. Costs default to 1 and must be positive.
    O(m n log n) arithmetic operations per round, at most m rounds.
    """
    n = len(profile)
    costs = [Fraction(1)] * m if costs is None else [Fraction(c) for c in costs]
    if any(c <= 0 for c in costs):
        raise ValueError("costs must be positive")
    supporters = [[i for i in range(n) if c in profile[i]] for c in range(m)]
    x = [Fraction(budget) / n] * n  # @line L1
    order, rhos = [], []
    chosen = [False] * m
    while True:  # @line L2
        best, best_rho = None, None
        for c in range(m):  # @line L3
            if chosen[c]:
                continue
            r = rho([x[i] for i in supporters[c]], costs[c])
            if r is not None and (best_rho is None or r < best_rho):  # @line L4
                best, best_rho = c, r
        if best is None:  # @line L5
            return order, rhos, x
        chosen[best] = True  # @line L6
        order.append(best)
        rhos.append(best_rho)
        for i in supporters[best]:  # @line L7
            x[i] -= min(best_rho, x[i])


def equal_shares(profile, m: int, k: int) -> Tuple[int, ...]:
    """Return the committee of size k elected by MES with seq-Phragmen completion, sorted."""
    return tuple(sorted(equal_shares_order(profile, m, k)[0]))


def equal_shares_order(profile, m: int, k: int) -> Tuple[Tuple[int, ...], int, List[Optional[Fraction]]]:
    """Return (order, phase1_size, completion_times) for committees: costs 1, budget k.

    The completion is seq-Phragmen with the starting loads -x_i, where x_i is the leftover
    budget of voter i; completion_times[j] is the time at which the j-th added candidate is
    bought (None for a candidate that no voter approves, added in index order at the end).
    """
    if not 0 <= k <= m:
        raise ValueError("need 0 <= k <= m")
    n = len(profile)
    if n == 0:
        return tuple(range(k)), 0, [None] * k
    order, _, x = equal_shares_phase1(profile, m, k)
    phase1 = len(order)
    supporters = [[i for i in range(n) if c in profile[i]] for c in range(m)]
    y = [-b for b in x]  # @line L8
    chosen = [c in order for c in range(m)]
    times = []
    while len(order) < k:  # @line L9
        best, best_t = None, None
        for c in range(m):
            if chosen[c] or not supporters[c]:
                continue
            t = (1 + sum((y[i] for i in supporters[c]), Fraction(0))) / len(supporters[c])
            if best_t is None or t < best_t:
                best, best_t = c, t
        if best is None:
            best = min(c for c in range(m) if not chosen[c])
        else:
            for i in supporters[best]:
                y[i] = best_t
        chosen[best] = True
        order.append(best)
        times.append(best_t)
    return tuple(order), phase1, times  # @line L10
test_method_of_equal_shares.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/method-of-equal-shares/. The authors are listed in prov/KK2YJY.jsonl.

import itertools
import random
from fractions import Fraction as F

import pytest

from agtprefs import check_anonymity, random_approval_profile
from method_of_equal_shares import equal_shares, equal_shares_order, equal_shares_phase1, rho


def ballots(*groups):
    return tuple(frozenset(A) for count, A in groups for _ in range(count))


def ejr_violation(P, m, k, W):
    n = len(P)
    W = set(W)
    for l in range(1, k + 1):
        for T in itertools.combinations(range(m), l):
            S = [i for i, A in enumerate(P) if set(T) <= A and len(A & W) < l]
            if S and len(S) * k >= l * n:
                return l, T, S
    return None


def random_instance(rng, mmax=6, nmax=8):
    m = rng.randint(1, mmax)
    n = rng.randint(1, nmax)
    k = rng.randint(1, m)
    return m, n, k, random_approval_profile(rng, m, n, rng.choice([0.2, 0.4, 0.6]))


def test_rho():
    assert rho([F(1), F(1)], 1) == F(1, 2)
    assert rho([F(1, 10), F(1), F(1)], 1) == F(9, 20)
    assert rho([F(1, 4), F(1, 4)], 1) is None
    assert rho([F(1, 2), F(1, 2)], 1) == F(1, 2)
    rng = random.Random(1)
    for _ in range(300):
        b = [F(rng.randint(0, 6), rng.randint(1, 4)) for _ in range(rng.randint(1, 5))]
        cost = F(rng.randint(1, 8), rng.randint(1, 3))
        r = rho(b, cost)
        if sum(b) < cost:
            assert r is None
            continue
        assert sum(min(r, x) for x in b) == cost
        assert sum(min(r - F(1, 10 ** 6), x) for x in b) < cost


def test_running_example_of_lackner_and_skowron():
    # Example 2.11: a, ..., g = 0, ..., 6, k = 4
    P = ballots((3, {0, 1}), (3, {0, 2}), (2, {0, 3}), (1, {1, 2, 5}), (1, {4}), (1, {5}), (1, {6}))
    order, rhos, x = equal_shares_phase1(P, 7, 4)
    assert order == [0] and rhos == [F(1, 8)]
    assert x == [F(1, 3) - F(1, 8)] * 8 + [F(1, 3)] * 4
    order, phase1, times = equal_shares_order(P, 7, 4)
    assert order == (0, 1, 2, 3) and phase1 == 1
    assert times == [F(1, 96), F(37, 384), F(7, 24)]


def test_second_example_of_lackner_and_skowron():
    # Example 2.12: a, b, c, d = 0, 1, 2, 3, k = 3
    P = ballots((3, {2, 3}), (2, {0, 1}), (2, {0, 2}), (1, {1, 3}))
    order, rhos, x = equal_shares_phase1(P, 4, 3)
    assert order == [2, 0] and rhos == [F(1, 5), F(13, 40)]
    assert x == [F(7, 40)] * 3 + [F(1, 20)] * 2 + [0, 0] + [F(3, 8)]
    order, phase1, times = equal_shares_order(P, 4, 3)
    assert order == (2, 0, 3) and phase1 == 2 and times == [F(1, 40)]
    assert equal_shares(P, 4, 3) == (0, 2, 3)


def test_ejr_after_phase_one_and_after_completion():
    rng = random.Random(2)
    for _ in range(300):
        m, n, k, P = random_instance(rng)
        order, _, x = equal_shares_phase1(P, m, k)
        assert len(order) <= k and all(b >= 0 for b in x)
        assert sum(x) == k - len(order)
        assert ejr_violation(P, m, k, order) is None
        W = equal_shares(P, m, k)
        assert len(W) == k and set(order) <= set(W)


def test_party_lists_give_dhondt():
    rng = random.Random(3)
    for _ in range(60):
        parties = rng.randint(1, 4)
        k = rng.randint(1, 5)
        votes = [rng.randint(1, 9) for _ in range(parties)]
        P = ballots(*((votes[p], set(range(p * k, p * k + k))) for p in range(parties)))
        seats = [0] * parties
        for _ in range(k):
            j = max(range(parties), key=lambda p: (F(votes[p], seats[p] + 1), -p))
            seats[j] += 1
        W = equal_shares(P, parties * k, k)
        assert [sum(1 for c in W if c // k == p) for p in range(parties)] == seats


def test_budgeting_with_costs():
    rng = random.Random(4)
    for _ in range(200):
        m, n, k, P = random_instance(rng)
        costs = [rng.randint(1, 5) for _ in range(m)]
        budget = rng.randint(1, 12)
        order, rhos, x = equal_shares_phase1(P, m, budget, costs)
        assert sum(costs[c] for c in order) + sum(x) == budget
        assert rhos == sorted(rhos)
        # every bought project was affordable at a price no voter exceeds
        y = [F(budget, n)] * n
        for c, r in zip(order, rhos):
            pay = [min(r, y[i]) if c in P[i] else 0 for i in range(n)]
            assert sum(pay) == costs[c]
            y = [a - b for a, b in zip(y, pay)]
        assert y == x
        # nothing left is affordable
        for c in range(m):
            if c not in order:
                assert sum(x[i] for i in range(n) if c in P[i]) < costs[c]
    with pytest.raises(ValueError):
        equal_shares_phase1(P, m, 1, [0] * m)


def test_unit_costs_match_the_committee_version():
    rng = random.Random(5)
    for _ in range(100):
        m, n, k, P = random_instance(rng)
        assert equal_shares_phase1(P, m, k, [1] * m) == equal_shares_phase1(P, m, k)


def test_edge_cases():
    assert equal_shares((), 3, 2) == (0, 1)
    assert equal_shares((frozenset(),), 3, 2) == (0, 1)
    assert equal_shares((frozenset({2}),), 3, 0) == ()
    with pytest.raises(ValueError):
        equal_shares((), 2, 3)


def test_anonymous():
    rng = random.Random(6)
    profiles = [random_approval_profile(rng, 5, 5, 0.4) for _ in range(60)]
    assert check_anonymity(lambda P, m: equal_shares(P, m, 3), 5, 5, profiles=profiles) is None


def test_larger_instance():
    rng = random.Random(7)
    m, n, k = 30, 200, 10
    P = random_approval_profile(rng, m, n, 0.2)
    order, phase1, times = equal_shares_order(P, m, k)
    assert len(set(order)) == k and phase1 <= k

History

Peters and Skowron introduced the rule as Rule X at EC 2020, in a study of proportional rules beyond welfare maximization, and showed that it satisfies EJR in polynomial time. Peters, Pierczynski and Skowron (NeurIPS 2021) extended it to participatory budgeting with additive utilities, and the rule became known as the method of equal shares. In 2023 the city of Wieliczka in Poland used it for its participatory budget, the first use in a real election. The same year Aarau in Switzerland used it for its first participatory budget, and Swiecie in Poland used it in a vote held in September 2023 for its 2024 budget.

References

  1. Dominik Peters and Piotr Skowron, Proportionality and the limits of welfarism, Proceedings of EC 2020, 793-794, the introduction of Rule X, as cited by Lackner and Skowron for Rule 11 and Table 4.1
  2. Dominik Peters, Grzegorz Pierczynski and Piotr Skowron, Proportional participatory budgeting with additive utilities, Advances in Neural Information Processing Systems 34 (NeurIPS 2021), 12726-12737, the extension of the rule to participatory budgeting with costs and additive utilities
  3. Martin Lackner and Piotr Skowron, Multi-Winner Voting with Approval Preferences, arXiv 2007.01795, version of August 2022 (published by Springer, 2023), Rule 11, Examples 2.11 and 2.12, Table 3.1, Table 4.1 and Section 4.4
  4. Dominik Peters and others, equalshares.net, election reports for Wieliczka (2023), Aarau (2023) and Swiecie (vote of September 2023), read in November 2026, the pages elections/zielony-milion, elections/aarau-2023 and elections/swiecie-2024

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