Algorithm Search⌘K

Algorithmadvanced

Proportional approval voting

Also called PAV, Thiele's method.

Elects the committee that maximizes the sum over voters of 1 + 1/2 + ... + 1/j, where j is the number of approved members.

Time
O(k^3 m n log k) 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
Thorvald N. Thiele, Haris Aziz, Edith Elkind, Martin Lackner, Piotr Skowron, 1895

Proportional approval voting (PAV) is a multiwinner voting rule for approval ballots. A voter with jj approved members in the committee gets the satisfaction 1+1/2+⋯+1/j1 + 1/2 + \cdots + 1/j, and PAV elects the committee of size kk with the largest total satisfaction. It gives each cohesive group of voters a share of the seats in proportion to its size, which is the property called extended justified representation. Finding a PAV committee is NP-hard, but a local search version runs in polynomial time and keeps the same proportionality guarantee.

In plain words

Every voter marks the candidates it likes. A council of kk people is to be elected. Each voter is happy with each approved council member, but the second one makes it less happy than the first, the third less than the second, and so on. So the rule does not give all seats to the largest group: after that group has some seats, one more seat for a smaller group adds more happiness. The rule picks the council with the most happiness in total. The effect is that a group with a third of the voters, who agree on enough candidates, gets about a third of the seats. With parties, this is the classical method that parliaments use to share seats.

The problem

The input is an approval profile: 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. Let H(j)=1+1/2+⋯+1/jH(j) = 1 + 1/2 + \cdots + 1/j be the jj-th harmonic number, with H(0)=0H(0) = 0 (see harmonic series). The PAV score of a committee WW is

pav(W)=∑i=1nH(∣Ai∩W∣).\mathrm{pav}(W) = \sum_{i=1}^{n} H(|A_i \cap W|).

PAV elects a committee of size kk with the largest score. Ties go to the lexicographically first committee, written as a sorted list of candidate indices.

A committee WW satisfies extended justified representation (EJR) if for every ℓ\ell with 1≤ℓ≤k1 \le \ell \le k and every group SS of at least ℓn/k\ell n / k voters who all approve the same ℓ\ell candidates, some voter in SS approves at least ℓ\ell members of WW. The page gives the exact rule and the local search algorithm that finds a committee with EJR in polynomial time.

The algorithm

The local search starts from some committee, by default the output of sequential PAV. It swaps one member for one non-member while a swap raises the PAV score by at least n/k2n / k^2. With xi=∣Ai∩W∣x_i = |A_i \cap W|, a voter gains 1/(xi+1)1/(x_i + 1) when an approved candidate joins and loses 1/xi1/x_i when an approved member leaves.

  1. LS-PAV(A_1, ..., A_n, m, k, start) ▷ start defaults to the committee of sequential PAV
  2. 1W ← start, sorted; if n = 0 or k = 0 or k = m then return W
  3. 2ε ← n / k^2
  4. 3x_i ← |A_i ∩ W| for every voter i
  5. 4repeat
  6. 5for each w ∈ W and each c ∉ W, in increasing order
  7. 6if Σ_{i : c ∈ A_i, w ∉ A_i} 1/(x_i + 1) - Σ_{i : w ∈ A_i, c ∉ A_i} 1/x_i ≥ ε then take the swap (w, c) and end the scan
  8. 7if no swap was taken then return W
  9. 8W ← (W \ {w}) ∪ {c}
  10. 9x_i ← x_i - [w ∈ A_i] + [c ∈ A_i] for every voter i

The exact rule tries all (mk)\binom{m}{k} committees and keeps the first one with the largest score. Sequential PAV starts with the empty committee and adds, kk times, the candidate with the largest gain ∑i:c∈Ai1/(xi+1)\sum_{i : c \in A_i} 1/(x_i + 1), ties to the smallest index. Every score is an exact fraction.

Example

This is Example 2.5 of Lackner and Skowron. The candidates are a,b,c,da, b, c, d, k=2k = 2, and n=23n = 23 voters have the ballots

3×{a,b},6×{a,d},4×{b},5×{c},5×{c,d}.3 \times \{a, b\}, \quad 6 \times \{a, d\}, \quad 4 \times \{b\}, \quad 5 \times \{c\}, \quad 5 \times \{c, d\}.

The scores of the six committees are:

committee {a,b}\{a, b\} {a,c}\{a, c\} {a,d}\{a, d\} {b,c}\{b, c\} {b,d}\{b, d\} {c,d}\{c, d\}
PAV score 29/229/2 1919 1717 1717 1818 37/237/2

PAV elects {a,c}\{a, c\}: every voter except the four {b}\{b\} voters gets one approved member. Sequential PAV first takes dd, which has the most approvals (1111). Then the gains are 3+6/2=63 + 6/2 = 6 for aa, 3+4=73 + 4 = 7 for bb and 5+5/2=15/25 + 5/2 = 15/2 for cc, so it takes cc and elects {c,d}\{c, d\} with score 37/237/2. Started from {c,d}\{c, d\}, the local search tries the swaps; the best one, dd for aa, gains only 1/21/2, less than ε=23/4\varepsilon = 23/4, so it stops at once. Both {a,c}\{a, c\} and {c,d}\{c, d\} satisfy EJR.

Correctness

The full proof is in proofs/correctness.md. The key step is a swap lemma. Suppose WW violates EJR for a group SS with ∣S∣≥ℓn/k|S| \ge \ell n / k that approves ℓ\ell common candidates. Then one of these candidates cc is not in WW, and adding cc raises the score by G≥∣S∣/ℓ≥n/kG \ge |S| / \ell \ge n / k, because each voter of SS has fewer than ℓ\ell approved members. In W∪{c}W \cup \{c\}, the losses of removing the kk members of WW add up to at most n−Gn - G, so one member ww costs at most (n−G)/k(n - G)/k. The swap of ww for cc gains at least G(1+1/k)−n/k≥n/k2G(1 + 1/k) - n/k \ge n / k^2.

So a committee from which no swap gains n/k2n / k^2 satisfies EJR. The local search stops only at such a committee (line L7), and an optimal PAV committee has no improving swap at all. The score lies between 00 and nH(k)n H(k), and each swap adds at least n/k2n / k^2, so there are at most k2H(k)k^2 H(k) swaps.

Proof: Exact PAV and local-search PAV satisfy extended justified representation, and local search stops after at most k^2 H(k) swapsfull

An approval profile has ballots A1,…,An⊆{0,…,m−1}A_1, \ldots, A_n \subseteq \{0, \ldots, m - 1\}, and kk is the committee size with 0≤k≤m0 \le k \le m. Let H(j)=1+1/2+⋯+1/jH(j) = 1 + 1/2 + \cdots + 1/j, with H(0)=0H(0) = 0. The PAV score of a committee WW is

pav(W)=∑i=1nH(∣Ai∩W∣).\mathrm{pav}(W) = \sum_{i=1}^{n} H(|A_i \cap W|).

Since H(j+1)−H(j)=1/(j+1)H(j + 1) - H(j) = 1/(j + 1), a voter with jj approved members gains 1/(j+1)1/(j + 1) when one more approved candidate joins, and loses 1/j1/j when one of its jj approved members leaves.

pav computes pav(W)\mathrm{pav}(W) for every WW of size kk, in the lexicographic order of sorted tuples, and keeps a new committee only when its score is strictly larger. So it returns the lexicographically first committee with the largest score. Every score is an exact fraction, so no rounding can change a comparison.

Sequential PAV

By the remark above, the gain of adding c∉Wc \notin W is

Δ(W,c)=pav(W∪{c})−pav(W)=∑i:c∈Ai1∣Ai∩W∣+1.\Delta(W, c) = \mathrm{pav}(W \cup \{c\}) - \mathrm{pav}(W) = \sum_{i : c \in A_i} \frac{1}{|A_i \cap W| + 1}.

seq_pav keeps xi=∣Ai∩W∣x_i = |A_i \cap W| for each voter, computes Δ(W,c)\Delta(W, c) by this formula, and adds a candidate with the largest gain, ties to the smallest index. It does this kk times, so it is the greedy algorithm for the PAV score.

The gain of a swap

Let w∈Ww \in W, c∉Wc \notin W and W′=(W∖{w})∪{c}W' = (W \setminus \{w\}) \cup \{c\}. For a voter ii with xi=∣Ai∩W∣x_i = |A_i \cap W|:

  • if c∈Aic \in A_i and w∉Aiw \notin A_i, then ∣Ai∩W′∣=xi+1|A_i \cap W'| = x_i + 1 and the voter gains 1/(xi+1)1/(x_i + 1);
  • if w∈Aiw \in A_i and c∉Aic \notin A_i, then xi≥1x_i \ge 1, ∣Ai∩W′∣=xi−1|A_i \cap W'| = x_i - 1, and the voter loses 1/xi1/x_i;
  • otherwise ∣Ai∩W′∣=xi|A_i \cap W'| = x_i and nothing changes.

swap_gain adds exactly these terms, so it returns pav(W′)−pav(W)\mathrm{pav}(W') - \mathrm{pav}(W). Line L9 updates xix_i by the same three cases.

The swap lemma

A committee WW of size kk violates extended justified representation (EJR) if there are an integer ℓ\ell with 1≤ℓ≤k1 \le \ell \le k and a nonempty group SS of voters such that ∣S∣≥ℓn/k|S| \ge \ell n / k, ∣⋂i∈SAi∣≥ℓ|\bigcap_{i \in S} A_i| \ge \ell, and ∣Ai∩W∣<ℓ|A_i \cap W| < \ell for every i∈Si \in S.

Lemma. Let n≥1n \ge 1 and 1≤k<m1 \le k < m. If WW violates EJR, then some swap of a member w∈Ww \in W for a candidate c∉Wc \notin W raises the PAV score by at least n/k2n / k^2.

Proof. Take ℓ\ell and SS as in the definition, and let T=⋂i∈SAiT = \bigcap_{i \in S} A_i. Pick any i∈Si \in S. Then ∣T∩W∣≤∣Ai∩W∣≤ℓ−1<ℓ≤∣T∣|T \cap W| \le |A_i \cap W| \le \ell - 1 < \ell \le |T|, so some c∈Tc \in T is not in WW.

Write xi=∣Ai∩W∣x_i = |A_i \cap W|. Every voter of SS approves cc and has xi≤ℓ−1x_i \le \ell - 1, so

G=Δ(W,c)≥∑i∈S1xi+1≥∣S∣ℓ≥nk.G = \Delta(W, c) \ge \sum_{i \in S} \frac{1}{x_i + 1} \ge \frac{|S|}{\ell} \ge \frac{n}{k}.

Let W+=W∪{c}W^+ = W \cup \{c\} and yi=∣Ai∩W+∣y_i = |A_i \cap W^+|. For w∈Ww \in W, let L(w)=pav(W+)−pav(W+∖{w})L(w) = \mathrm{pav}(W^+) - \mathrm{pav}(W^+ \setminus \{w\}) be the loss when ww leaves W+W^+. A voter that approves ww loses 1/yi1/y_i, so

∑w∈WL(w)=∑i=1n∣Ai∩W∣yi,\sum_{w \in W} L(w) = \sum_{i=1}^{n} \frac{|A_i \cap W|}{y_i},

where a term with yi=0y_i = 0 is 00. If c∈Aic \in A_i, then yi=xi+1y_i = x_i + 1 and the term is 1−1/(xi+1)1 - 1/(x_i + 1). If c∉Aic \notin A_i, the term is at most 11. Hence

∑w∈WL(w)≤∑i:c∈Ai(1−1xi+1)+∑i:c∉Ai1=n−G.\sum_{w \in W} L(w) \le \sum_{i : c \in A_i} \Bigl(1 - \frac{1}{x_i + 1}\Bigr) + \sum_{i : c \notin A_i} 1 = n - G.

So some w∈Ww \in W has L(w)≤(n−G)/kL(w) \le (n - G)/k. The swap of ww for cc gives the committee W+∖{w}W^+ \setminus \{w\}, and

pav(W+∖{w})−pav(W)=G−L(w)≥G−n−Gk=G(1+1k)−nk≥nk(1+1k)−nk=nk2.□\mathrm{pav}(W^+ \setminus \{w\}) - \mathrm{pav}(W) = G - L(w) \ge G - \frac{n - G}{k} = G \Bigl(1 + \frac{1}{k}\Bigr) - \frac{n}{k} \ge \frac{n}{k}\Bigl(1 + \frac{1}{k}\Bigr) - \frac{n}{k} = \frac{n}{k^2}. \qquad \square

Exact PAV satisfies EJR

If n=0n = 0 or k=0k = 0 there is no group to check. If k=mk = m, then WW contains every candidate, and a voter of an ℓ\ell-cohesive group approves at least ℓ\ell members. Otherwise, let WW have the largest PAV score. No swap raises the score, and n/k2>0n / k^2 > 0, so by the lemma WW satisfies EJR. This holds for every optimal committee, so it holds for the one that pav returns.

Local-search PAV

Result. ls_pav stops, and its output satisfies EJR.

Termination. The early return after line L1 covers n=0n = 0, k=0k = 0 and k=mk = m, where EJR holds as shown above. Otherwise each pass of the loop L4 to L9 either returns (line L7) or makes a swap with gain at least ε=n/k2\varepsilon = n / k^2 (lines L6 and L8). The score is at least 00 and at most nH(k)n H(k), because each voter has at most kk approved members. So there are at most

nH(k)n/k2=k2H(k)\frac{n H(k)}{n / k^2} = k^2 H(k)

swaps, and the loop stops.

EJR. Line L7 returns only when lines L5 and L6 found no swap with gain at least n/k2n / k^2. By the lemma, the committee does not violate EJR.

Running time. Each pass tries at most k(m−k)k (m - k) swaps, and each call of swap_gain takes O(n)O(n) arithmetic operations, with a membership test in O(1)O(1) time on a 0/1 table of the ballots. With k2H(k)+1k^2 H(k) + 1 passes and H(k)=O(log⁡k)H(k) = O(\log k), the local search uses O(k3mnlog⁡k)O(k^3 m n \log k) arithmetic operations, and the start by sequential PAV adds O(kmn)O(k m n).

Party-list profiles

Suppose the voters split into parties, the voters of party pp all approve the same list of kk candidates, the lists are disjoint, and party pp has vpv_p voters. A committee with sps_p members from list pp has score ∑pvpH(sp)\sum_p v_p H(s_p), and vpH(s)=∑t=1svp/tv_p H(s) = \sum_{t=1}^{s} v_p / t. The terms vp/tv_p / t decrease in tt, so the largest score with ∑psp=k\sum_p s_p = k is the sum of the kk largest numbers among all vp/tv_p / t, which is what the D'Hondt method of highest averages selects. So the seat counts of PAV are a D'Hondt allocation, up to ties.

Complexity

Each pass of lines L5 and L6 tries at most k(m−k)k(m - k) swaps of O(n)O(n) arithmetic operations each, and there are at most k2H(k)+1k^2 H(k) + 1 passes. With H(k)=O(log⁡k)H(k) = O(\log k) this gives O(k3mnlog⁡k)O(k^3 m n \log k) arithmetic operations in the word RAM model, and O(mn)O(mn) extra space for the ballots. Sequential PAV takes O(kmn)O(kmn) and the exact search O((mk)nk)O(\binom{m}{k} n k).

Computing a PAV committee is NP-hard (Skowron, Faliszewski and Lang 2016, Theorem 5). Sequential PAV reaches at least 1−(1−1/k)k≥1−1/e1 - (1 - 1/k)^k \ge 1 - 1/e of the optimal score, because the score is a monotone submodular function (Lackner and Skowron, Theorem 5.3). Dudycz, Manurangsi, Marcinkowski and Sornat (2020) gave a 0.79650.7965 approximation, which is tight unless P = NP. For exact solutions, the most common method is a binary integer program (Lackner and Skowron, Chapter 5).

Properties

  • Extended justified representation. Every PAV committee satisfies EJR, and so also PJR and JR (Aziz et al. 2017; Lackner and Skowron, Theorem 4.3). The local search committee satisfies EJR too.
  • Proportionality degree. In an ℓ\ell-cohesive group, the average voter approves more than ℓ−1\ell - 1 members (Lackner and Skowron, Theorem 4.3). This is the best possible degree.
  • D'Hondt on party lists. When the voters split into parties with disjoint lists, PAV gives the seat counts of the D'Hondt method (Lackner and Skowron, Theorem 4.1). PAV is the only rule that extends D'Hondt and is neutral, anonymous, consistent and continuous (Theorem 4.2).
  • Anonymous, and neutral as a correspondence. The resolute rule with lexicographic tie-breaking is not neutral.
  • Pareto efficient and consistent, but not committee monotone: the PAV committee for k+1k + 1 seats need not contain the one for kk seats (Lackner and Skowron, Table 3.1).
  • Not in the core. PAV can violate the core (Lackner and Skowron, Example 4.7). Whether the core of an approval election is always nonempty is open (Lackner and Skowron, Section 4.4, version of August 2022).

Variants and improvements

  • Thiele methods. "Thiele's method" often means PAV, but Thiele defined a family: any nondecreasing weight function ww with w(0)=0w(0) = 0 gives a rule that maximizes ∑iw(∣Ai∩W∣)\sum_i w(|A_i \cap W|). Approval voting uses w(j)=jw(j) = j, the approval Chamberlin-Courant rule uses w(j)=min⁡(j,1)w(j) = \min(j, 1), and PAV uses w(j)=H(j)w(j) = H(j). The weights 1,1/3,1/5,…1, 1/3, 1/5, \ldots give a rule that extends the Sainte-Lague method.
  • Sequential PAV. The greedy version is fast and also extends D'Hondt, but it fails EJR (Lackner and Skowron, Section 4.2). Reverse sequential PAV removes candidates one by one from the full set and fails EJR as well.
  • Local search threshold. With the threshold n/k2n / k^2 the number of swaps is polynomial. With an arbitrarily small threshold and improving swaps chosen in lexicographic order, the search can need Ω(klog⁡k)\Omega(k^{\log k}) swaps, which is not polynomial in kk (Kraiczy and Elkind 2024).
  • Other rules with EJR. The method of equal shares satisfies EJR in polynomial time without local search, and Phragmen's sequential method satisfies the weaker PJR.

When to use it

Use PAV to elect a committee, a board or a short list from approval ballots when seats should follow the size of the groups of like-minded voters, and the number of candidates is small enough for an exact solver. When a polynomial guarantee matters, use the local search or the method of equal shares. For budgets with costs, see participatory budgeting. For one representative per voter, use the Chamberlin-Courant rule.

Pitfalls

  • Taking sequential PAV for PAV. In the example they elect different committees. Sequential PAV fails EJR, and the local search need not find the PAV optimum.
  • Floating point. Sums of 1/j1/j in floating point can make two equal scores look different and change the result. Use exact fractions, or multiply all weights by lcm(1,…,k)\mathrm{lcm}(1, \ldots, k).
  • Tiny swap thresholds. A local search that accepts every improving swap can run for a very long time. Keep the threshold n/k2n / k^2.
  • Ties. Many committees can have the same score. State the tie-breaking rule, here the lexicographically first committee.

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))
proportional_approval_voting.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/proportional-approval-voting/. The authors are listed in prov/95W632.jsonl.
"""Proportional approval voting (PAV), Thiele's rule with harmonic weights.

An approval profile is a sequence of n ballots, each a set of candidates among 0, ..., m - 1.
A voter with j approved members in the committee W contributes H(j) = 1 + 1/2 + ... + 1/j to
the PAV score of W. PAV elects a committee of size k with the largest score. Every score is
an exact Fraction.

Three algorithms:
- pav: exact search over all committees, ties to the lexicographically first;
- seq_pav: sequential PAV, a greedy rule that adds the candidate with the largest gain;
- ls_pav: local search with swaps of gain at least n / k^2 (Aziz et al. 2018), polynomial,
  and its output satisfies extended justified representation.
"""

from fractions import Fraction
from itertools import combinations
from typing import Optional, Sequence, Tuple


def harmonic(j: int) -> Fraction:
    """Return H(j) = 1 + 1/2 + ... + 1/j, with H(0) = 0."""
    return sum((Fraction(1, t) for t in range(1, j + 1)), Fraction(0))


def pav_score(profile, committee) -> Fraction:
    """Return the PAV score: the sum over voters of H(number of approved members)."""
    W = set(committee)
    return sum((harmonic(len(W & set(A))) for A in profile), Fraction(0))


def pav(profile, m: int, k: int) -> Tuple[int, ...]:
    """Return the lexicographically first committee of size k with the largest PAV score.

    Exact search over all C(m, k) committees: O(C(m, k) n k) time.
    """
    if not 0 <= k <= m:
        raise ValueError("need 0 <= k <= m")
    H = [harmonic(j) for j in range(k + 1)]
    ballots = [set(A) for A in profile]
    best, best_score = None, None
    for W in combinations(range(m), k):
        s = sum((H[sum(1 for c in W if c in A)] for A in ballots), Fraction(0))
        if best_score is None or s > best_score:
            best, best_score = W, s
    return best


def seq_pav(profile, m: int, k: int) -> Tuple[int, ...]:
    """Sequential PAV: k times, add the candidate with the largest gain in PAV score.

    A voter with j approved members so far gains 1 / (j + 1) if the new candidate is approved.
    Ties go to the smallest index. O(k m n) time.
    """
    if not 0 <= k <= m:
        raise ValueError("need 0 <= k <= m")
    ballots = [set(A) for A in profile]
    cnt = [0] * len(ballots)
    W = []
    for _ in range(k):
        pick, pick_gain = None, None
        for c in range(m):
            if c in W:
                continue
            g = sum((Fraction(1, x + 1) for A, x in zip(ballots, cnt) if c in A), Fraction(0))
            if pick_gain is None or g > pick_gain:
                pick, pick_gain = c, g
        W.append(pick)
        cnt = [x + (1 if pick in A else 0) for A, x in zip(ballots, cnt)]
    return tuple(sorted(W))


def swap_gain(ballots, cnt, out_c: int, in_c: int) -> Fraction:
    """Return PAV(W - out_c + in_c) - PAV(W), where cnt[i] = |A_i & W|, out_c in W, in_c not."""
    g = Fraction(0)
    for A, x in zip(ballots, cnt):
        a_in, a_out = in_c in A, out_c in A
        if a_in and not a_out:
            g += Fraction(1, x + 1)
        elif a_out and not a_in:
            g -= Fraction(1, x)
    return g


def ls_pav(profile, m: int, k: int, start: Optional[Sequence[int]] = None) -> Tuple[int, ...]:
    """Local search PAV: swap a member for a non-member while the PAV score rises by n / k^2.

    Starts from seq_pav unless a start committee is given. Each swap raises the score by at
    least n / k^2 and the score is at most n H(k), so there are at most k^2 H(k) swaps; each
    scan tries k (m - k) swaps in O(n) time each.
    """
    if not 0 <= k <= m:
        raise ValueError("need 0 <= k <= m")
    n = len(profile)
    ballots = [set(A) for A in profile]
    W = sorted(seq_pav(profile, m, k) if start is None else start)  # @line L1
    if n == 0 or k == 0 or k == m:
        return tuple(W)
    eps = Fraction(n, k * k)  # @line L2
    cnt = [len(A & set(W)) for A in ballots]  # @line L3
    while True:  # @line L4
        found = None
        for w in W:  # @line L5
            for c in range(m):
                if c in W:
                    continue
                if swap_gain(ballots, cnt, w, c) >= eps:  # @line L6
                    found = (w, c)
                    break
            if found:
                break
        if found is None:  # @line L7
            return tuple(W)
        w, c = found  # @line L8
        W.remove(w)
        W.append(c)
        W.sort()
        cnt = [x - (w in A) + (c in A) for A, x in zip(ballots, cnt)]  # @line L9
test_proportional_approval_voting.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/proportional-approval-voting/. The authors are listed in prov/95W632.jsonl.

import itertools
import random
from fractions import Fraction

import pytest

from agtprefs import check_anonymity, random_approval_profile
from proportional_approval_voting import harmonic, ls_pav, pav, pav_score, seq_pav, swap_gain


def ejr_violation(P, m, k, W):
    """Brute force: an l-cohesive group (|S| >= l n / k, all approve l common candidates)
    whose members each approve fewer than l members of W. Returns None or (l, T, S)."""
    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 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]))


# Lackner and Skowron, Example 2.5: a, b, c, d = 0, 1, 2, 3.
EXAMPLE = (frozenset({0, 1}),) * 3 + (frozenset({0, 3}),) * 6 + (frozenset({1}),) * 4 \
    + (frozenset({2}),) * 5 + (frozenset({2, 3}),) * 5


def test_harmonic():
    assert harmonic(0) == 0 and harmonic(1) == 1 and harmonic(4) == Fraction(25, 12)


def test_exact_search_and_tie_breaking():
    rng = random.Random(1)
    for _ in range(200):
        m, n, k, P = random_instance(rng)
        W = pav(P, m, k)
        best = max(pav_score(P, V) for V in itertools.combinations(range(m), k))
        assert pav_score(P, W) == best
        assert W == next(V for V in itertools.combinations(range(m), k) if pav_score(P, V) == best)


def test_example_of_lackner_and_skowron():
    m, k = 4, 2
    assert pav(EXAMPLE, m, k) == (0, 2) and pav_score(EXAMPLE, (0, 2)) == 19
    assert seq_pav(EXAMPLE, m, k) == (2, 3) and pav_score(EXAMPLE, (2, 3)) == Fraction(37, 2)
    # the best swap gains only 1/2 < n / k^2 = 23/4, so local search keeps {c, d}
    assert ls_pav(EXAMPLE, m, k) == (2, 3)
    assert ejr_violation(EXAMPLE, m, k, (2, 3)) is None
    for start in itertools.combinations(range(m), k):
        assert ejr_violation(EXAMPLE, m, k, ls_pav(EXAMPLE, m, k, start=start)) is None


def test_pav_satisfies_ejr():
    rng = random.Random(2)
    for _ in range(250):
        m, n, k, P = random_instance(rng)
        assert ejr_violation(P, m, k, pav(P, m, k)) is None


def test_local_search_satisfies_ejr_from_any_start():
    rng = random.Random(3)
    for _ in range(250):
        m, n, k, P = random_instance(rng)
        start = rng.sample(range(m), k)
        W = ls_pav(P, m, k, start=start)
        assert len(set(W)) == k
        assert ejr_violation(P, m, k, W) is None
        assert pav_score(P, W) >= pav_score(P, start)


def test_swap_lemma():
    """If W violates EJR, some swap raises the PAV score by at least n / k^2."""
    rng = random.Random(4)
    seen = 0
    for _ in range(1500):
        m, n, k, P = random_instance(rng)
        if k == m:
            continue
        W = rng.sample(range(m), k)
        if ejr_violation(P, m, k, W) is None:
            continue
        seen += 1
        ballots = [set(A) for A in P]
        cnt = [len(A & set(W)) for A in ballots]
        best = max(swap_gain(ballots, cnt, w, c) for w in W for c in range(m) if c not in W)
        assert best >= Fraction(n, k * k)
        w, c = max(((w, c) for w in W for c in range(m) if c not in W),
                   key=lambda wc: swap_gain(ballots, cnt, *wc))
        V = [x for x in W if x != w] + [c]
        assert pav_score(P, V) - pav_score(P, W) == swap_gain(ballots, cnt, w, c)
    assert seen > 50


def dhondt(votes, k):
    """Seats by the highest averages v / (s + 1); ties to the smaller party index."""
    seats = [0] * len(votes)
    for _ in range(k):
        j = max(range(len(votes)), key=lambda p: (Fraction(votes[p], seats[p] + 1), -p))
        seats[j] += 1
    return seats


def test_party_lists_give_dhondt():
    rng = random.Random(5)
    for _ in range(40):
        parties = rng.randint(1, 3)
        k = rng.randint(1, 4)
        votes = [rng.randint(1, 7) for _ in range(parties)]
        # party p has the candidates p k, ..., p k + k - 1, approved by all its voters
        m = parties * k
        P = tuple(frozenset(range(p * k, p * k + k)) for p in range(parties) for _ in range(votes[p]))
        seats = dhondt(votes, k)
        W = [p * k + s for p in range(parties) for s in range(seats[p])]
        assert pav_score(P, W) == pav_score(P, pav(P, m, k))


def test_one_seat_is_approval_voting():
    rng = random.Random(6)
    for _ in range(100):
        m, n, k, P = random_instance(rng)
        score = [sum(1 for A in P if c in A) for c in range(m)]
        assert pav(P, m, 1) == seq_pav(P, m, 1) == (score.index(max(score)),)


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


def test_anonymous():
    rng = random.Random(7)
    profiles = [random_approval_profile(rng, 4, 4, 0.5) for _ in range(40)]
    assert check_anonymity(lambda P, m: pav(P, m, 2), 4, 4, profiles=profiles) is None


def test_larger_local_search():
    rng = random.Random(8)
    m, n, k = 12, 60, 5
    P = random_approval_profile(rng, m, n, 0.3)
    W = ls_pav(P, m, k)
    assert ejr_violation(P, m, k, W) is None

History

Thiele (1895) defined PAV, together with the family of rules that now carry his name. Aziz, Brill, Conitzer, Elkind, Freeman and Walsh (2015, journal version 2017) defined justified representation and EJR, and proved that PAV satisfies EJR. Skowron, Faliszewski and Lang (2016) proved that computing it is NP-hard, and Aziz, Elkind, Huang, Lackner, Sanchez-Fernandez and Skowron (2018) gave the local search version that satisfies EJR in polynomial time. Lackner and Skowron characterized PAV as the unique extension of D'Hondt with neutrality, anonymity, consistency and continuity.

References

  1. Thorvald N. Thiele, Om flerfoldsvalg, Oversigt over det Kongelige Danske Videnskabernes Selskabs Forhandlinger (1895), 415-441, the rule with the weights 1, 1/2, 1/3, ..., as reported by Lackner and Skowron (Rule 4)
  2. Haris Aziz, Markus Brill, Vincent Conitzer, Edith Elkind, Rupert Freeman and Toby Walsh, Justified representation in approval-based committee voting, Social Choice and Welfare 48(2) (2017), 461-485, the definitions of JR and EJR and the proof that PAV satisfies EJR
  3. Haris Aziz, Edith Elkind, Shenwei Huang, Martin Lackner, Luis Sanchez-Fernandez and Piotr Skowron, On the complexity of extended and proportional justified representation, Proceedings of AAAI 2018, 902-909, the local search version of PAV with swap threshold n/k^2, and the proportionality degree l - 1
  4. Piotr Skowron, Piotr Faliszewski and Jerome Lang, Finding a collective set of items: from proportional multirepresentation to group recommendation, Artificial Intelligence 241 (2016), 191-216, Theorem 5 (NP-hardness of a class of Thiele methods that includes PAV)
  5. Martin Lackner and Piotr Skowron, Multi-Winner Voting with Approval Preferences, arXiv 2007.01795, version of August 2022 (published by Springer, 2023), Rule 4, Example 2.5, Table 3.1, Theorems 4.1 to 4.3, Section 4.4 (the core), Table 4.1, Theorem 5.3 and Table 5.1
  6. Szymon Dudycz, Pasin Manurangsi, Jan Marcinkowski and Krzysztof Sornat, Tight approximation for Proportional Approval Voting, Proceedings of IJCAI 2020, 276-282, the approximation ratio 0.7965, tight unless P = NP
  7. Sonja Kraiczy and Edith Elkind, A lower bound for local search proportional approval voting, arXiv 2408.02300, August 2024 (ESA 2024), the lower bound of k^(log k) swaps for arbitrarily small thresholds, with improving swaps chosen in lexicographic order

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