Algorithm Search⌘K

Algorithmadvanced

Phragmen's sequential method

Also called seq-Phragmen, Phragmen's method.

Elects committee members one by one. Each member costs 1, shared by its supporters, and the next member is the one that keeps the largest load on a voter as small as possible.

Time
O(k m 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
Lars Edvard Phragmen, Markus Brill, Rupert Freeman, Svante Janson, Martin Lackner, 1894

Phragmen's sequential method (seq-Phragmen) is a multiwinner voting rule for approval ballots. Each elected candidate has a cost, or load, of 11 that its supporters share. The method elects candidates one at a time, and each time it picks the candidate whose cost can be shared so that its supporters end with the smallest possible largest load. It runs in polynomial time, adds members without removing any as the committee grows, and satisfies proportional justified representation.

In plain words

Think of each voter as earning money at the same steady rate. A candidate costs one unit of money, and only the voters who approve it may pay. As soon as the supporters of some candidate have one unit between them, they buy that candidate for the committee and spend all their money. Voters who paid start again from zero, and the others keep their savings. A large group earns money faster, so it buys more members, but it must spend on each one. A small group saves for longer and still gets its turn. The process stops when the committee is full.

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. For a candidate cc, N(c)N(c) is the set of voters who approve cc. The output is a committee of kk candidates, listed in the order of election, together with the final load yiy_i of each voter.

Ties go to the smallest candidate index. If no unelected candidate has a supporter, the method elects the smallest unelected index, at no cost.

The algorithm

  1. SEQ-PHRAGMEN(A_1, ..., A_n, m, k)
  2. 1y_i ← 0 for every voter i; W ← empty list
  3. 2for r ← 1 to k do
  4. 3for each c ∉ W with N(c) ≠ ∅: t(c) ← (1 + Σ_{i ∈ N(c)} y_i) / |N(c)|
  5. 4c_r ← the c with the least t(c), ties to the smallest index
  6. 5append c_r to W
  7. 6y_i ← t(c_r) for every i ∈ N(c_r)
  8. 7return W and the loads y

The value t(c)t(c) is the load that every supporter of cc would carry if they shared all their loads and the new cost of 11 equally. In the money picture, it is the first time at which the supporters of cc have one unit in total.

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\}.
round t(a)t(a) t(b)t(b) t(c)t(c) t(d)t(d) elected
1 1/41/4 1/31/3 1/51/5 1/41/4 cc
2 7/207/20 1/31/3 2/52/5 bb
3 31/6031/60 29/6029/60 dd

In round 1 the five supporters of cc share its cost, so each carries 1/51/5. In round 2, aa would need (1+1/5+1/5)/4=7/20(1 + 1/5 + 1/5)/4 = 7/20, while the three supporters of bb have no load yet and need only 1/31/3. In round 3, dd needs (1+3⋅1/5+1/3)/4=29/60(1 + 3 \cdot 1/5 + 1/3)/4 = 29/60. The committee is {b,c,d}\{b, c, d\}, and the final loads 29/60,29/60,29/60,1/3,1/3,1/5,1/5,29/6029/60, 29/60, 29/60, 1/3, 1/3, 1/5, 1/5, 29/60 add up to 33. The method of equal shares elects {a,c,d}\{a, c, d\} on the same profile.

Correctness

The full proof is in proofs/correctness.md. The times t(c1)≤t(c2)≤⋯t(c_1) \le t(c_2) \le \cdots never decrease, every load is at most the last time, and the supporters of crc_r pay 11 in total for it. So the sum of all loads is the number of elected candidates.

For PJR, suppose a group SS of s≥ℓn/ks \ge \ell n / k voters approves ℓ\ell common candidates, but its members together approve fewer than ℓ\ell elected members. Then SS paid at most ℓ−1\ell - 1 in total, and one common candidate cc is never elected. At the time ℓ/s\ell / s, the voters of SS alone could pay s⋅ℓ/s−(ℓ−1)=1s \cdot \ell / s - (\ell - 1) = 1 for cc, so every round ends no later than ℓ/s\ell / s. Then all voters together paid at most (n−s)ℓ/s+ℓ−1≤k−1(n - s) \ell / s + \ell - 1 \le k - 1, but they paid kk for the kk members, a contradiction.

Proof: Sequential Phragmen is committee monotone, extends D'Hondt and satisfies proportional justified representationfull

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. For a candidate cc, N(c)={i:c∈Ai}N(c) = \{i : c \in A_i\} is the set of its supporters. The method keeps a load yiy_i for each voter, starting at 00. In round rr it computes, for every candidate cc not yet elected with N(c)≠∅N(c) \ne \emptyset,

tr(c)=1+∑i∈N(c)yi∣N(c)∣,t_r(c) = \frac{1 + \sum_{i \in N(c)} y_i}{|N(c)|},

elects the candidate crc_r with the least tr(c)t_r(c) (ties to the smallest index), sets tr=tr(cr)t_r = t_r(c_r), and sets yi=try_i = t_r for every i∈N(cr)i \in N(c_r). If no unelected candidate has a supporter, it elects the smallest unelected index, which changes no load.

What the code computes

seq_phragmen keeps the list of supporters of each candidate, computes tr(c)t_r(c) by the formula with exact fractions, keeps the first candidate with the least value, and updates the loads of its supporters. So it computes the method as defined, with the stated tie-breaking.

Loads and times

Lemma 1. Let t0=0t_0 = 0. After round rr, every load is at most trt_r, and t1≤t2≤⋯t_1 \le t_2 \le \cdots over the rounds that elect a supported candidate.

Proof. By induction on rr. Before round rr, every load is at most tr−1t_{r-1} (the time of the last round with a supported candidate, or 00). For a supporter ii of crc_r the new load is trt_r. The other loads do not change.

To show tr−1≤trt_{r-1} \le t_r, let round r′<rr' < r be the last round before rr that elected a supported candidate, so tr−1=tr′t_{r-1} = t_{r'}. Loads only grow over time: a supporter ii of cr′c_{r'} had yi≤tr′−1≤tr′y_i \le t_{r'-1} \le t_{r'} by induction, and its new load is tr′t_{r'}. So for each candidate cc the value t(c)t(c) does not decrease from round r′r' to round rr, and crc_r was a candidate in round r′r' as well. Hence tr=tr(cr)≥tr′(cr)≥tr′t_r = t_r(c_r) \ge t_{r'}(c_r) \ge t_{r'}. □\square

Lemma 2. When crc_r is elected, its supporters pay tr−yi≥0t_r - y_i \ge 0 each, and these payments add up to 11. So after the method ends, ∑iyi\sum_i y_i equals the number of supported candidates elected, and yiy_i is the total that voter ii paid.

Proof. By Lemma 1, yi≤try_i \le t_r before round rr. The payments add up to ∣N(cr)∣ tr−∑i∈N(cr)yi=1|N(c_r)| \, t_r - \sum_{i \in N(c_r)} y_i = 1 by the definition of trt_r. □\square

This is the continuous form of the method: each voter earns money at rate 11, and tr(c)t_r(c) is the first time at which the supporters of cc have 11 in total, counting what each has left after its earlier payments.

Committee monotonicity

Rounds 1,…,k1, \ldots, k do not depend on kk. So the committee for k+1k + 1 seats is the committee for kk seats plus one candidate.

Proportional justified representation

A committee WW of size kk violates proportional justified representation (PJR) if there are an integer ℓ\ell with 1≤ℓ≤k1 \le \ell \le k and a 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, such that ∣W∩⋃i∈SAi∣<ℓ|W \cap \bigcup_{i \in S} A_i| < \ell.

Theorem. The committee of sequential Phragmen satisfies PJR.

Proof. Suppose that WW violates PJR with ℓ\ell and SS, and let s=∣S∣≥1s = |S| \ge 1. The members of WW that some voter of SS approves are fewer than ℓ\ell. Each voter of SS pays only for members that it approves, and the total payment for one member is 11. By Lemma 2, ∑i∈Syi≤ℓ−1\sum_{i \in S} y_i \le \ell - 1 at every point of the method.

The common set T=⋂i∈SAiT = \bigcap_{i \in S} A_i has at least ℓ\ell candidates, and at most ℓ−1\ell - 1 of them are in WW. So some c∈Tc \in T is never elected, and cc is a candidate with S⊆N(c)S \subseteq N(c) in every round. Let t∗=ℓ/st^* = \ell / s, so t∗≤k/nt^* \le k / n.

We show by induction that tr≤t∗t_r \le t^* for every round rr that elects a supported candidate. Suppose all earlier times are at most t∗t^*. By Lemma 1 every load is at most t∗t^*, so

∣N(c)∣ t∗−∑i∈N(c)yi=∑i∈N(c)(t∗−yi)≥∑i∈S(t∗−yi)≥st∗−(ℓ−1)=1.|N(c)| \, t^* - \sum_{i \in N(c)} y_i = \sum_{i \in N(c)} (t^* - y_i) \ge \sum_{i \in S} (t^* - y_i) \ge s t^* - (\ell - 1) = 1.

So tr(c)≤t∗t_r(c) \le t^*, and tr≤tr(c)≤t∗t_r \le t_r(c) \le t^*. Also cc always has a supporter, so every round elects a supported candidate.

At the end, all kk elected candidates are supported, every load is at most t∗t^*, and by Lemma 2

k=∑i∉Syi+∑i∈Syi≤(n−s) t∗+ℓ−1=ℓns−1≤k−1,k = \sum_{i \notin S} y_i + \sum_{i \in S} y_i \le (n - s) \, t^* + \ell - 1 = \frac{\ell n}{s} - 1 \le k - 1,

which is a contradiction. □\square

PJR implies justified representation (the case ℓ=1\ell = 1). The method does not satisfy extended justified representation: Example 6 of Brill, Freeman, Janson and Lackner, which the tests check, has n=24n = 24, k=12k = 12 and four voters who approve aa and bb but get only one approved member each.

Party lists

Let the voters split into parties, the vpv_p voters of party pp all approve the same list of kk candidates, and the lists be disjoint. If party pp has sps_p elected members, its voters all have the load sp/vps_p / v_p, because each member costs 11 and is shared equally by the same vpv_p voters. So the next candidate of party pp has t=(1+sp)/vpt = (1 + s_p) / v_p, and the method elects from the party with the largest vp/(sp+1)v_p / (s_p + 1). This is the D'Hondt rule of highest averages, with ties to the party whose candidates have smaller indices.

Running time

Each round computes tr(c)t_r(c) for at most mm candidates, with ∣N(c)∣|N(c)| additions each, so a round takes O(m+∑c∣N(c)∣)=O(mn)O(m + \sum_c |N(c)|) = O(mn) arithmetic operations, and the kk rounds take O(kmn)O(kmn). The supporter lists take O(mn)O(mn) space.

Complexity

Line L3 adds ∣N(c)∣|N(c)| loads for each unelected candidate, O(mn)O(mn) arithmetic operations in each round, so the method takes O(kmn)O(kmn) operations in the word RAM model and O(mn)O(mn) space for the lists of supporters. With exact fractions the numbers grow: the denominators can reach nkn^k, and Brill, Freeman, Janson and Lackner bound the bit complexity by O(k3mn(log⁡n)2)O(k^3 m n (\log n)^2) (Theorem 5). Floating point is faster but can break ties wrongly.

Properties

  • Proportional justified representation. A group of at least ℓn/k\ell n / k voters with ℓ\ell common approved candidates approves at least ℓ\ell members in total (Brill et al., Theorem 7). It follows that justified representation holds as well.
  • Not extended justified representation. In Example 6 of Brill et al., with n=24n = 24 and k=12k = 12, four voters who approve aa and bb form a 22-cohesive group, but the committee {c1,…,c12}\{c_1, \ldots, c_{12}\} gives each of them only one approved member.
  • Committee monotone. The committee for k+1k + 1 seats contains the committee for kk seats. Few proportional rules have this property; PAV and the method of equal shares do not (Lackner and Skowron, Table 3.1).
  • D'Hondt on party lists. With disjoint party lists, the next member of a party with vv voters and ss seats costs (s+1)/v(s + 1)/v, so the method is the D'Hondt method (Lackner and Skowron, Theorem 4.1).
  • Priceable and laminar proportional (Peters and Skowron, as listed in Lackner and Skowron, Table 4.1).
  • Anonymous. The resolute rule with fixed tie-breaking is not neutral; the set of committees over all tie-breaking orders is.
  • Not Pareto efficient and not consistent (Lackner and Skowron, Table 3.1).

Variants and improvements

  • Leximax-Phragmen. Choose the whole committee and a split of its costs so that the sorted vector of loads is lexicographically smallest. It is NP-hard to compute (Brill et al., Theorem 2) and also satisfies PJR.
  • Variance-Phragmen. Minimize the variance of the loads. On party lists it gives the Sainte-Lague method.
  • Method of equal shares. Give each voter a budget of k/nk/n at the start instead of a steady income. This small change gives extended justified representation.
  • Eneström-Phragmen. A quota rule for approval ballots that works like the single transferable vote.
  • Validator selection. Variants of the sequential method choose validators in nominated proof-of-stake blockchains (Brill et al., Section 1).

When to use it

Use it to elect a committee or a ranked list from approval ballots when proportional outcomes matter, the result must be computed exactly in polynomial time, and the committee must grow in a consistent way, for example a shortlist where the top kk for every kk should make sense. If extended justified representation is required, use the method of equal shares or proportional approval voting instead.

Pitfalls

  • Forgetting the old loads. A voter who already paid for a member carries its load into later rounds. A method that resets everyone each round is a different rule.
  • Floating point ties. Many values of t(c)t(c) are equal in small instances, as in Example 2.9 of Lackner and Skowron where bb and cc tie. Use exact fractions and state the tie-breaking rule.
  • Unsupported candidates. A candidate with no supporters has no defined t(c)t(c). Elect such candidates only when no supported candidate is left.
  • Expecting EJR. The method satisfies PJR, not EJR.

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))
phragmen_sequential_method.py 52 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phragmen-sequential-method/. The authors are listed in prov/EVEFGB.jsonl.
"""Phragmen's sequential method (seq-Phragmen) for approval ballots.

An approval profile is a sequence of n ballots, each a set of candidates among 0, ..., m - 1.
Each elected candidate has a cost (load) of 1 that its supporters share. In each round the
method elects the candidate whose cost can be shared so that the largest load of its
supporters is smallest, and every supporter then carries that load. Ties go to the smallest
candidate index. Every load is an exact Fraction.
"""

from fractions import Fraction
from typing import List, Tuple


def seq_phragmen(profile, m: int, k: int) -> Tuple[Tuple[int, ...], List[Fraction], List[Fraction]]:
    """Return (order, times, loads).

    order lists the k elected candidates in the order of election, times[r] is the load at
    which order[r] was elected, and loads[i] is the final load of voter i. A candidate that
    no voter approves is elected only when no approved candidate is left; it costs nothing
    and its time is None. O(k (m n + sum of ballot sizes)) arithmetic operations.
    """
    if not 0 <= k <= m:
        raise ValueError("need 0 <= k <= m")
    n = len(profile)
    supporters = [[i for i in range(n) if c in profile[i]] for c in range(m)]
    y = [Fraction(0)] * n  # @line L1
    order, times = [], []
    chosen = [False] * m
    for _ in range(k):  # @line L2
        best, best_t = None, None
        for c in range(m):  # @line L3
            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:  # @line L4
                best, best_t = c, t
        if best is None:
            best = min(c for c in range(m) if not chosen[c])
        chosen[best] = True  # @line L5
        order.append(best)
        times.append(best_t)
        if best_t is not None:
            for i in supporters[best]:  # @line L6
                y[i] = best_t
    return tuple(order), times, y  # @line L7


def phragmen_committee(profile, m: int, k: int) -> Tuple[int, ...]:
    """Return the committee of seq-Phragmen as a sorted tuple."""
    return tuple(sorted(seq_phragmen(profile, m, k)[0]))
test_phragmen_sequential_method.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phragmen-sequential-method/. The authors are listed in prov/EVEFGB.jsonl.

import itertools
import random
from fractions import Fraction as F

import pytest

from agtprefs import check_anonymity, random_approval_profile
from phragmen_sequential_method import phragmen_committee, seq_phragmen


def ballots(*groups):
    """groups of (count, set of candidates) -> an approval profile."""
    return tuple(frozenset(A) for count, A in groups for _ in range(count))


def pjr_violation(P, m, k, W):
    """A group S of at least l n / k voters with l common approvals whose members approve
    fewer than l members of W in total. Supersets of S only help, so the smallest S suffice."""
    n = len(P)
    W = set(W)
    for l in range(1, k + 1):
        size = -(-l * n // k)
        for T in itertools.combinations(range(m), l):
            NT = [i for i, A in enumerate(P) if set(T) <= A]
            for S in itertools.combinations(NT, size):
                if len(set().union(*(P[i] for i in S)) & W) < l:
                    return l, T, S
    return None


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 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_running_example_of_lackner_and_skowron():
    # Example 2.9: a, ..., g = 0, ..., 6
    P = ballots((3, {0, 1}), (3, {0, 2}), (2, {0, 3}), (1, {1, 2, 5}), (1, {4}), (1, {5}), (1, {6}))
    order, times, loads = seq_phragmen(P, 7, 4)
    t1, t2, t3, t4 = F(1, 8), F(11, 32), F(55, 128), F(5, 8)
    assert order == (0, 1, 2, 3)
    assert times == [t1, t2, t3, t4]
    assert loads == [t2, t2, t2, t3, t3, t3, t4, t4, t3, 0, 0, 0]


def test_second_example_of_lackner_and_skowron():
    # Example 2.12: seq-Phragmen elects c, b, d at 1/5, 1/3 and 29/60
    P = ballots((3, {2, 3}), (2, {0, 1}), (2, {0, 2}), (1, {1, 3}))
    order, times, _ = seq_phragmen(P, 4, 3)
    assert order == (2, 1, 3)
    assert times == [F(1, 5), F(1, 3), F(29, 60)]


def test_ejr_counterexample_of_brill_et_al():
    # Example 6 of Brill, Freeman, Janson and Lackner: a, b = 0, 1 and c_j = j + 1
    c = list(range(2, 14))
    P = ballots((2, {0, 1, c[0]}), (2, {0, 1, c[1]}), (6, set(c)), (5, set(c[1:])), (9, set(c[2:])))
    W = phragmen_committee(P, 14, 12)
    assert W == tuple(c)
    assert ejr_violation(P, 14, 12, W) == (2, (0, 1), [0, 1, 2, 3])
    l, T, S = ejr_violation(P, 14, 12, W)
    # PJR holds: the four voters together approve c_1 and c_2
    assert len(set().union(*(P[i] for i in S)) & set(W)) == 2


def test_proportional_justified_representation():
    rng = random.Random(1)
    for _ in range(300):
        m, n, k, P = random_instance(rng)
        assert pjr_violation(P, m, k, phragmen_committee(P, m, k)) is None


def test_committee_monotone_and_loads():
    rng = random.Random(2)
    for _ in range(200):
        m, n, k, P = random_instance(rng)
        order, times, loads = seq_phragmen(P, m, k)
        assert len(set(order)) == k
        assert seq_phragmen(P, m, k - 1)[0] == order[:-1]
        paid = [t for t in times if t is not None]
        assert paid == sorted(paid)
        assert sum(loads) == len(paid)
        assert all(0 <= y <= (paid[-1] if paid else 0) for y in loads)


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 = phragmen_committee(P, parties * k, k)
        assert [sum(1 for c in W if c // k == p) for p in range(parties)] == seats


def test_one_seat_is_approval_voting():
    rng = random.Random(4)
    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 phragmen_committee(P, m, 1) == (score.index(max(score)),)


def test_unapproved_candidates_and_errors():
    P = ballots((2, {2}),)
    order, times, loads = seq_phragmen(P, 4, 3)
    assert order == (2, 0, 1) and times == [F(1, 2), None, None] and loads == [F(1, 2)] * 2
    assert seq_phragmen((), 2, 2)[0] == (0, 1)
    assert seq_phragmen(P, 4, 0) == ((), [], [0, 0])
    with pytest.raises(ValueError):
        seq_phragmen(P, 2, 3)


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


def test_larger_instance():
    rng = random.Random(6)
    m, n, k = 40, 300, 15
    P = random_approval_profile(rng, m, n, 0.2)
    order, times, loads = seq_phragmen(P, m, k)
    assert len(set(order)) == k and sum(loads) == k and times == sorted(times)

History

Phragmen, a Swedish mathematician, proposed the method in a series of papers from 1894 to 1899, as a generalization of the D'Hondt method to elections without party lists, and discussed the optimization variants in 1896. Variants of his methods were used in Swedish parliamentary elections to distribute seats within parties (Brill et al.). Interest returned with the conference version of Brill, Freeman, Janson and Lackner (2017), which proved PJR for the sequential method; Peters and Skowron (2020) showed that it is priceable and introduced the method of equal shares as a variant with EJR.

References

  1. Edvard Phragmen, Sur une methode nouvelle pour realiser, dans les elections, la representation proportionnelle des partis, Ofversigt af Kongliga Vetenskaps-Akademiens Forhandlingar 51(3) (1894), 133-137, the first paper on the sequential method, as cited by Brill, Freeman, Janson and Lackner (reference 43)
  2. Markus Brill, Rupert Freeman, Svante Janson and Martin Lackner, Phragmen's voting methods and justified representation, arXiv 2102.12305, version 2, February 2023 (Mathematical Programming 203 (2024), 47-76), Section 4 (the method and its history), Theorem 5 (running time with exact fractions), Theorem 7 (PJR) and Example 6 (EJR fails)
  3. Markus Brill, Rupert Freeman, Svante Janson and Martin Lackner, Phragmen's voting methods and justified representation, Mathematical Programming 203 (2024), 47-76, the journal version of the arXiv paper above
  4. Martin Lackner and Piotr Skowron, Multi-Winner Voting with Approval Preferences, arXiv 2007.01795, version of August 2022 (published by Springer, 2023), Rule 9, Examples 2.9 and 2.12, Table 3.1, Theorem 4.1 (D'Hondt) and Table 4.1
  5. Dominik Peters and Piotr Skowron, Proportionality and the limits of welfarism, Proceedings of EC 2020, 793-794, priceability and laminar proportionality of the method, as listed in Lackner and Skowron (Table 4.1)

Where this leads

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