Algorithm Search⌘K

Algorithmadvanced

Chamberlin-Courant rule

Also called Chamberlin-Courant.

Elects the committee of k candidates that maximizes the total satisfaction of the voters with their favourite member. NP-hard in general, polynomial on single-peaked profiles.

Time
O(m^2 (n + k)) worst
Space
O(m^2 + m n) extra
Where
k = the committee size; m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
John R. Chamberlin, Paul N. Courant, Ariel D. Procaccia, Tyler Lu, Craig Boutilier, Nadja Betzler, Arkadii Slinko, Johannes Uhlmann, 1983

The Chamberlin-Courant rule is a multiwinner voting rule. It elects a committee of kk candidates, and each voter counts as represented by the member it likes best. The rule chooses the committee that makes the total satisfaction of the voters with their representatives as large as possible, where the satisfaction is the Borda score of the representative. Finding this committee is NP-hard, but on single-peaked profiles a dynamic program over the axis finds it in O(m2(n+k))O(m^2 (n + k)) time.

In plain words

A town elects kk people to a council. Each voter only cares about one council member: the one it likes best, who will speak for it. If your favourite candidate is elected, you are fully happy; if only your third choice is elected, you are less happy. The rule looks for the council that makes the voters happiest in total in this sense. A candidate who is the second choice of everyone is not needed if every voter already has someone better on the council. So the rule favours a council that covers the different groups of voters, which is a form of proportional representation.

The problem

The input is a preference profile P=(≻1,…,≻n)P = (\succ_1, \ldots, \succ_n) of strict rankings of the candidates 0,…,m−10, \ldots, m - 1 and a committee size kk with 1≤k≤m1 \le k \le m. Let ri(c)r_i(c) be the position of cc in ≻i\succ_i, with 00 for the top. A committee WW of size kk has misrepresentation and satisfaction

ρ(W)=∑i=1nmin⁡c∈Wri(c),f(W)=∑i=1nmax⁡c∈W(m−1−ri(c))=n(m−1)−ρ(W).\rho(W) = \sum_{i=1}^{n} \min_{c \in W} r_i(c), \qquad f(W) = \sum_{i=1}^{n} \max_{c \in W} \bigl(m - 1 - r_i(c)\bigr) = n(m - 1) - \rho(W).

The rule elects a committee of size kk with the least ρ\rho, which is the same as the largest ff. Ties go to the lexicographically first committee, written as a sorted list of candidate indices. Chamberlin and Courant used Borda scores; any scoring by positions, or approval ballots with score 11 for an approved member, gives a version of the same rule.

In general no polynomial algorithm is known: the problem is NP-hard. The page gives the exact algorithm for profiles that are single-peaked on a known axis, and the greedy approximation for all profiles.

The algorithm

Let the profile be single-peaked on the axis a0⊲a1⊲⋯⊲am−1a_0 \lhd a_1 \lhd \cdots \lhd a_{m-1}, and let qiq_i be the place of the peak of voter ii. Each voter is best represented by the nearest member on the left of its peak or the nearest member on the right. So the cost of a committee splits into the cost of the voters left of the first member, the cost of the voters between each pair of consecutive members, and the cost of the voters right of the last member.

  1. CC-SINGLE-PEAKED(P, k, axis a_0, ..., a_{m-1}) ▷ κ_i(t) = r_i(a_t), q_i = place of the peak of voter i
  2. 1head[t] ← Σ_{i : q_i < t} κ_i(t); tail[t] ← Σ_{i : q_i ≥ t} κ_i(t), for t = 0, ..., m - 1
  3. 2seg[s][t] ← Σ_{i : s ≤ q_i < t} min(κ_i(s), κ_i(t)), for 0 ≤ s < t ≤ m - 1
  4. 3F[1][t] ← head[t] for every t
  5. 4for j ← 2 to k do
  6. 5for t ← j - 1 to m - 1 do
  7. 6F[j][t] ← min over j - 2 ≤ s < t of F[j - 1][s] + seg[s][t]; back[j][t] ← the best s
  8. 7t ← the place that minimizes F[k][t] + tail[t]
  9. 8follow back[k][t], back[k - 1][...], ... to read the places t_k > ... > t_1
  10. 9return {a_{t_1}, ..., a_{t_k}} and its misrepresentation

F[j][t]F[j][t] is the least cost of the voters with peaks left of place tt, over the committees with jj members whose rightmost member is at place tt. Line L6 tries every place ss of the member just left of tt. Line L7 adds the cost of the voters at or right of the last member.

For profiles that are not single-peaked, the exact search tries all (mk)\binom{m}{k} committees. The greedy algorithm starts with the empty committee and adds, kk times, the candidate with the largest gain in satisfaction, ties to the smallest index.

Example

The axis is 0⊲1⊲2⊲3⊲40 \lhd 1 \lhd 2 \lhd 3 \lhd 4, k=2k = 2, and five voters have the rankings

01234,10234,23140,32410,43210.01234, \quad 10234, \quad 23140, \quad 32410, \quad 43210.

Each is single-peaked on the axis. With one seat, the misrepresentations head[t]+tail[t]\mathrm{head}[t] + \mathrm{tail}[t] of the five candidates are 13,9,7,8,1313, 9, 7, 8, 13, so candidate 22, the Borda winner, is best alone. With two seats the dynamic program gives:

last member tt best first member ss F[2][t]F[2][t] tail[t]\mathrm{tail}[t] total
1 0 0 8 8
2 0 1 3 4
3 0 2 1 3
4 1 5 0 5

The optimum is {0,3}\{0, 3\} with misrepresentation 33 and satisfaction 5⋅4−3=175 \cdot 4 - 3 = 17. Voters 1 and 2 get candidate 00, in positions 00 and 11, and voters 3, 4 and 5 get candidate 33, in positions 11, 00 and 11. The greedy algorithm first takes the Borda winner 22 and then 00, and {0,2}\{0, 2\} has misrepresentation 44: the best single candidate need not be in the best committee.

Correctness

The proof is in proofs/correctness.md. On a single-peaked ranking, among the members on one side of the peak the one nearest to the peak is best. So with the members at places t1<⋯<tkt_1 < \cdots < t_k, a voter with peak between tjt_j and tj+1t_{j+1} is represented by one of these two, and the misrepresentation is

ρ=head[t1]+∑j=1k−1seg[tj][tj+1]+tail[tk].\rho = \mathrm{head}[t_1] + \sum_{j=1}^{k-1} \mathrm{seg}[t_j][t_{j+1}] + \mathrm{tail}[t_k].

An induction on jj shows that F[j][t]F[j][t] is the least value of the first two parts over all choices with tj=tt_j = t, so line L7 finds the optimum. For the greedy algorithm, ff is monotone and submodular, and the argument of Nemhauser, Wolsey and Fisher gives f(greedy)≥(1−(1−1/k)k) f(optimum)>(1−1/e) f(optimum)≈0.632 f(optimum)f(\text{greedy}) \ge (1 - (1 - 1/k)^k)\, f(\text{optimum}) > (1 - 1/e)\, f(\text{optimum}) \approx 0.632\, f(\text{optimum}).

Proof: The dynamic program is exact on single-peaked profiles, and greedy reaches 1 - (1 - 1/k)^k of the optimal satisfactionfull

A profile P=(≻1,…,≻n)P = (\succ_1, \ldots, \succ_n) ranks the candidates 0,…,m−10, \ldots, m - 1. For a voter ii and a candidate cc, ri(c)r_i(c) is the position of cc in ≻i\succ_i, with 00 for the top. The misrepresentation of a committee WW is ρ(W)=∑imin⁡c∈Wri(c)\rho(W) = \sum_i \min_{c \in W} r_i(c), and its satisfaction is f(W)=∑imax⁡c∈W(m−1−ri(c))f(W) = \sum_i \max_{c \in W} (m - 1 - r_i(c)), with f(∅)=0f(\emptyset) = 0. For ∣W∣≥1|W| \ge 1, f(W)=n(m−1)−ρ(W)f(W) = n(m - 1) - \rho(W), so the committees of size kk with the least ρ\rho are those with the largest ff.

chamberlin_courant computes ρ(W)\rho(W) for every WW of size kk, in the lexicographic order of sorted tuples, and keeps a new committee only when its value is strictly smaller. So it returns the lexicographically first committee with the least misrepresentation.

The dynamic program on single-peaked profiles

Let the profile be single-peaked on the axis a0⊲a1⊲⋯⊲am−1a_0 \lhd a_1 \lhd \cdots \lhd a_{m-1}. We work with places on the axis: c(t)=atc(t) = a_t, qiq_i is the place of the peak of voter ii, and κi(t)=ri(at)\kappa_i(t) = r_i(a_t).

Lemma 1. If s<t≤qis < t \le q_i, then κi(t)<κi(s)\kappa_i(t) < \kappa_i(s). If qi≤t<sq_i \le t < s, then κi(t)<κi(s)\kappa_i(t) < \kappa_i(s).

Proof. If t=qit = q_i, ata_t is the top of voter ii. Otherwise as,at,aqia_s, a_t, a_{q_i} lie in this order on the axis (or in the reverse order), and a single-peaked ranking has no valley at ata_t, so at≻iasa_t \succ_i a_s because aqi≻iata_{q_i} \succ_i a_t already. □\square

Lemma 2. Let the committee have the places t1<t2<⋯<tkt_1 < t_2 < \cdots < t_k. Voter ii is best represented by at1a_{t_1} if qi<t1q_i < t_1, by atka_{t_k} if qi≥tkq_i \ge t_k, and otherwise by the better of atja_{t_j} and atj+1a_{t_{j+1}}, where tj≤qi<tj+1t_j \le q_i < t_{j+1}.

Proof. By Lemma 1, among the members at places at most qiq_i the one with the largest place is best, and among those at places above qiq_i the one with the smallest place is best. If qi<t1q_i < t_1 there are no members on the left, and if qi≥tkq_i \ge t_k none on the right. □\square

For places s<ts < t, line L1 and line L2 compute

head(t)=∑i:qi<tκi(t),tail(t)=∑i:qi≥tκi(t),seg(s,t)=∑i:s≤qi<tmin⁡(κi(s),κi(t)).\mathrm{head}(t) = \sum_{i : q_i < t} \kappa_i(t), \qquad \mathrm{tail}(t) = \sum_{i : q_i \ge t} \kappa_i(t), \qquad \mathrm{seg}(s, t) = \sum_{i : s \le q_i < t} \min(\kappa_i(s), \kappa_i(t)).

The intervals q<t1q < t_1, t1≤q<t2t_1 \le q < t_2, ..., tk−1≤q<tkt_{k-1} \le q < t_k and q≥tkq \ge t_k split the voters, so Lemma 2 gives

ρ({at1,…,atk})=head(t1)+∑j=1k−1seg(tj,tj+1)+tail(tk).(1)\rho(\{a_{t_1}, \ldots, a_{t_k}\}) = \mathrm{head}(t_1) + \sum_{j=1}^{k-1} \mathrm{seg}(t_j, t_{j+1}) + \mathrm{tail}(t_k). \tag{1}

Claim. After lines L3 to L6, F[j][t]F[j][t] is the least value of head(t1)+∑l=1j−1seg(tl,tl+1)\mathrm{head}(t_1) + \sum_{l=1}^{j-1} \mathrm{seg}(t_l, t_{l+1}) over all places t1<⋯<tj=tt_1 < \cdots < t_j = t, for 1≤j≤k1 \le j \le k and j−1≤t≤m−1j - 1 \le t \le m - 1.

Proof. By induction on jj. For j=1j = 1 the only choice is t1=tt_1 = t, and line L3 sets F[1][t]=head(t)F[1][t] = \mathrm{head}(t). For j≥2j \ge 2, a choice t1<⋯<tj−1<tj=tt_1 < \cdots < t_{j-1} < t_j = t has tj−1=st_{j-1} = s with j−2≤s<tj - 2 \le s < t, and its value is the value of the first j−1j - 1 places plus seg(s,t)\mathrm{seg}(s, t). For a fixed ss, the least value of the first part is F[j−1][s]F[j-1][s] by induction, and line L6 takes the minimum over all ss. □\square

By (1) and the claim, the value of line L7, min⁡tF[k][t]+tail(t)\min_t F[k][t] + \mathrm{tail}(t), is the least misrepresentation of a committee of size kk. Line L6 records the ss that gives each minimum, so line L8 follows these records back from the best tt and reads kk places tk>tk−1>⋯>t1t_k > t_{k-1} > \cdots > t_1 whose value in (1) is this minimum. The test test_dp_matches_exact_search_on_random_single_peaked_profiles checks the value against the exact search for every kk on random single-peaked profiles.

Running time. Lines L1 take O(mn)O(mn) time. Line L2 adds, for each voter, one term to seg(s,t)\mathrm{seg}(s, t) for each s≤qi<ts \le q_i < t, at most m2/4m^2/4 terms, so O(m2n)O(m^2 n) time in all. Lines L4 to L6 take O(km2)O(k m^2) time. The total is O(m2(n+k))O(m^2 (n + k)) time and O(m2+mn)O(m^2 + mn) space.

The greedy algorithm

The function ff is monotone: adding a candidate never lowers any voter's best score. It is submodular: for X⊆YX \subseteq Y and a candidate cc, the gain f(X∪{c})−f(X)=∑imax⁡(0,si(c)−max⁡Xsi)f(X \cup \{c\}) - f(X) = \sum_i \max(0, s_i(c) - \max_{X} s_i), with si(c)=m−1−ri(c)s_i(c) = m - 1 - r_i(c) and the maximum over the empty set equal to 00, is at least the gain for YY, because each term is nonincreasing in the best score so far.

Let OO be an optimal committee of size kk, OPT=f(O)\mathrm{OPT} = f(O), and WjW_j the greedy committee after jj steps. Each step picks a candidate of largest gain; candidates already in WjW_j have gain 00, so the step has a gain at least as large as every candidate of OO. By monotonicity and submodularity,

OPT≤f(Wj∪O)≤f(Wj)+∑o∈O(f(Wj∪{o})−f(Wj))≤f(Wj)+k(f(Wj+1)−f(Wj)).\mathrm{OPT} \le f(W_j \cup O) \le f(W_j) + \sum_{o \in O} \bigl(f(W_j \cup \{o\}) - f(W_j)\bigr) \le f(W_j) + k \bigl(f(W_{j+1}) - f(W_j)\bigr).

So OPT−f(Wj+1)≤(1−1/k)(OPT−f(Wj))\mathrm{OPT} - f(W_{j+1}) \le (1 - 1/k)(\mathrm{OPT} - f(W_j)), and after kk steps OPT−f(Wk)≤(1−1/k)k OPT\mathrm{OPT} - f(W_k) \le (1 - 1/k)^k \, \mathrm{OPT}, since f(W0)=0f(W_0) = 0. This gives f(Wk)≥(1−(1−1/k)k) OPT>(1−1/e) OPTf(W_k) \ge (1 - (1 - 1/k)^k)\,\mathrm{OPT} > (1 - 1/e)\,\mathrm{OPT}. This is the bound of Nemhauser, Wolsey and Fisher (1978) for monotone submodular functions. The test test_greedy_guarantee checks it exactly in Fraction against the exact search.

The bound is for satisfaction. It says nothing about the ratio of misrepresentations: in the example on the page the greedy committee has misrepresentation 44 and the optimum 33.

Complexity

Line L1 takes O(mn)O(mn) time. Line L2 adds one term for each voter ii and each pair s≤qi<ts \le q_i < t, O(m2n)O(m^2 n) time in all. Lines L4 to L6 take O(km2)O(k m^2) time. The total is O(m2(n+k))O(m^2 (n + k)) time in the word RAM model and O(m2+mn)O(m^2 + mn) space. Betzler, Slinko and Uhlmann state their dynamic program as O(nm2)O(n m^2) time (Theorem 8). The axis can be found first by single-peaked recognition in O(mn)O(mn) time.

In general the exact search takes O((mk)nk)O(\binom{m}{k} n k) time and the greedy algorithm O(kmn)O(k m n). Winner determination is NP-hard with approval scores (Procaccia, Rosenschein and Zohar 2008) and with Borda scores (Lu and Boutilier 2011, Theorem 8), and W[2]-hard with the committee size kk as the parameter (Betzler, Slinko and Uhlmann 2013, Theorems 1 and 2). So an exact algorithm in time f(k)⋅poly(n,m)f(k) \cdot \mathrm{poly}(n, m) is unlikely.

Properties

  • One representative for each voter. Only the best member counts. A committee with many members that a voter likes is no better for that voter than one with its favourite alone.
  • Anonymous. The result depends only on the multiset of rankings.
  • Neutral as a correspondence. The set of optimal committees is renamed with the candidates. The resolute rule with lexicographic tie-breaking is not neutral.
  • Diverse, not proportional in size. A group of voters with the same favourite needs only that one member, whatever its size, so a large group does not get more seats than a small one. With approval ballots the rule and its greedy version satisfy justified representation, but not the stronger proportional or extended justified representation (Lackner and Skowron, Table 4.1).
  • Approval version. With approval scores, f(W)f(W) is the number of voters who approve some member of WW, and the rule is the maximum coverage problem with voters as elements and candidates as sets.

Variants and improvements

  • Monroe's rule. Each member represents about n/kn/k voters, so the representation is balanced in size. It stays NP-hard on single-peaked profiles (Betzler, Slinko and Uhlmann 2013).
  • Minimax versions. Minimize the largest misrepresentation of a voter instead of the sum. On single-peaked profiles this version is solved by a greedy algorithm (Betzler, Slinko and Uhlmann 2013, Section 5.1).
  • Other domains. On single-crossing profiles an optimal committee can be found in polynomial time, because some optimal committee represents intervals of the voter order. On profiles single-peaked on a tree the rule stays NP-complete, even with Borda scores (Elkind, Lackner and Peters, Section 6.2.1).
  • Approximation. The greedy algorithm is the greedy max coverage algorithm applied to a weighted coverage function. The same structure appears in the k-median problem, with candidates as facilities and Borda positions as distances.

When to use it

Use it to choose a committee or a set of options where each voter will use one of them: a set of products to stock, a panel of experts, a set of movies to show on a flight. Do not use it when seats should be shared in proportion to group sizes, as in a parliament; use proportional approval voting, the method of equal shares or an apportionment method instead. For many candidates, use the dynamic program when the profile is single-peaked, and an integer program or the greedy algorithm otherwise.

Pitfalls

  • Choosing the top kk Borda candidates. That is a different rule. In the example, the two best Borda candidates are 22 and 33, with misrepresentation 55, while the optimum is 33.
  • Greedy and misrepresentation. The guarantee 1−1/e1 - 1/e is for satisfaction. In misrepresentation the greedy committee can be much worse in ratio: in the example it is 44 against 33.
  • Using the dynamic program on the wrong axis. The cost formula holds only if every voter is single-peaked on the given axis. On other profiles the program returns some committee, not the optimum.
  • Ties. The optimum is often not unique. 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))
chamberlin_courant_rule.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chamberlin-courant-rule/. The authors are listed in prov/EKGPRX.jsonl.
"""The Chamberlin-Courant rule with Borda misrepresentation.

A profile is a sequence of n rankings of the candidates 0, ..., m - 1, best first. A voter is
represented by the member of the committee W that it ranks highest. Its misrepresentation is
the position of that member in its ranking (0 for the top), and its satisfaction is m - 1 minus
this position, the Borda score. The rule elects a committee of k candidates with the least
total misrepresentation, which is the same as the largest total satisfaction.

Three algorithms:
- chamberlin_courant: exact search over all committees, ties to the lexicographically first;
- cc_single_peaked: exact dynamic program for profiles single-peaked on a given axis;
- greedy_cc: the greedy algorithm, a 1 - 1/e approximation of the satisfaction.
"""

from itertools import combinations
from typing import Sequence, Tuple


def _positions(profile, m):
    pos = []
    for r in profile:
        p = [0] * m
        for i, a in enumerate(r):
            p[a] = i
        pos.append(p)
    return pos


def misrepresentation(profile, m: int, committee) -> int:
    """Total Borda misrepresentation: the sum over voters of the best position of a member."""
    pos = _positions(profile, m)
    return sum(min(p[c] for c in committee) for p in pos)


def satisfaction(profile, m: int, committee) -> int:
    """Total Borda satisfaction: n (m - 1) minus the misrepresentation; 0 for the empty committee."""
    if not committee:
        return 0
    return len(profile) * (m - 1) - misrepresentation(profile, m, committee)


def chamberlin_courant(profile, m: int, k: int) -> Tuple[int, ...]:
    """Return the lexicographically first committee of size k with the least misrepresentation.

    Exact search over all C(m, k) committees: O(C(m, k) n k) time after O(m n) setup.
    """
    if not 1 <= k <= m:
        raise ValueError("need 1 <= k <= m")
    pos = _positions(profile, m)
    best, best_cost = None, None
    for W in combinations(range(m), k):
        cost = sum(min(p[c] for c in W) for p in pos)
        if best_cost is None or cost < best_cost:
            best, best_cost = W, cost
    return best


def cc_single_peaked(profile, m: int, k: int, axis: Sequence[int]) -> Tuple[Tuple[int, ...], int]:
    """Return (committee, misrepresentation) of an optimal committee of size k.

    The profile must be single-peaked on the axis, a tuple of all candidates from left to right.
    Then every voter is best represented by the nearest chosen candidate on the left of its
    peak or the nearest one on the right, and a dynamic program over the axis finds the optimum
    in O(m^2 (n + k)) time and O(m^2 + m n) space.
    """
    if not 1 <= k <= m:
        raise ValueError("need 1 <= k <= m")
    pos = _positions(profile, m)
    where = {a: t for t, a in enumerate(axis)}
    peak = [where[r[0]] for r in profile]
    # cost[i][t]: misrepresentation of voter i by the candidate at axis place t
    cost = [[p[axis[t]] for t in range(m)] for p in pos]
    head = [0] * m  # @line L1
    tail = [0] * m
    for i in range(len(profile)):
        for t in range(m):
            if peak[i] < t:
                head[t] += cost[i][t]
            else:
                tail[t] += cost[i][t]
    seg = [[0] * m for _ in range(m)]  # @line L2
    for i in range(len(profile)):
        ci, q = cost[i], peak[i]
        for s in range(q + 1):
            for t in range(q + 1, m):
                seg[s][t] += min(ci[s], ci[t])
    INF = None
    F = [[INF] * m for _ in range(k + 1)]
    back = [[-1] * m for _ in range(k + 1)]
    for t in range(m):  # @line L3
        F[1][t] = head[t]
    for j in range(2, k + 1):  # @line L4
        for t in range(j - 1, m):  # @line L5
            best, arg = None, -1
            for s in range(j - 2, t):  # @line L6
                v = F[j - 1][s] + seg[s][t]
                if best is None or v < best:
                    best, arg = v, s
            F[j][t], back[j][t] = best, arg
    t_best, total = -1, None
    for t in range(k - 1, m):  # @line L7
        v = F[k][t] + tail[t]
        if total is None or v < total:
            t_best, total = t, v
    chosen, t = [], t_best  # @line L8
    for j in range(k, 0, -1):
        chosen.append(axis[t])
        t = back[j][t]
    return tuple(sorted(chosen)), total  # @line L9


def greedy_cc(profile, m: int, k: int) -> Tuple[int, ...]:
    """Add k candidates one at a time, each with the largest gain in satisfaction.

    Ties go to the smallest index. O(k m n) time. The satisfaction of the result is at least
    1 - (1 - 1/k)^k > 1 - 1/e of the optimum.
    """
    if not 1 <= k <= m:
        raise ValueError("need 1 <= k <= m")
    pos = _positions(profile, m)
    best_sat = [0] * len(profile)  # satisfaction of each voter with the committee so far
    W = []
    for _ in range(k):
        pick, pick_gain = None, None
        for c in range(m):
            if c in W:
                continue
            gain = sum(max(0, m - 1 - p[c] - b) for p, b in zip(pos, best_sat))
            if pick_gain is None or gain > pick_gain:
                pick, pick_gain = c, gain
        W.append(pick)
        best_sat = [max(b, m - 1 - p[pick]) for p, b in zip(pos, best_sat)]
    return tuple(sorted(W))
test_chamberlin_courant_rule.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chamberlin-courant-rule/. The authors are listed in prov/EKGPRX.jsonl.

import itertools
import random
from fractions import Fraction

import pytest

from agtprefs import all_rankings, check_anonymity, is_single_peaked_on, random_profile
from chamberlin_courant_rule import (
    cc_single_peaked,
    chamberlin_courant,
    greedy_cc,
    misrepresentation,
    satisfaction,
)


def random_sp_ranking(rng, axis):
    """A random ranking single-peaked on the axis: a random peak, then grow left or right."""
    m = len(axis)
    lo = hi = rng.randrange(m)
    r = [axis[lo]]
    while len(r) < m:
        if hi == m - 1 or (lo > 0 and rng.random() < 0.5):
            lo -= 1
            r.append(axis[lo])
        else:
            hi += 1
            r.append(axis[hi])
    return tuple(r)


def random_sp_profile(rng, m, n):
    axis = tuple(rng.sample(range(m), m))
    return axis, tuple(random_sp_ranking(rng, axis) for _ in range(n))


def optimum(profile, m, k):
    return min(misrepresentation(profile, m, W) for W in itertools.combinations(range(m), k))


def test_exact_search_and_tie_breaking():
    rng = random.Random(1)
    for _ in range(150):
        m = rng.randint(1, 6)
        n = rng.randint(1, 6)
        k = rng.randint(1, m)
        P = random_profile(rng, m, n)
        W = chamberlin_courant(P, m, k)
        best = optimum(P, m, k)
        assert len(W) == k and misrepresentation(P, m, W) == best
        first = next(V for V in itertools.combinations(range(m), k) if misrepresentation(P, m, V) == best)
        assert W == first
        assert satisfaction(P, m, W) == n * (m - 1) - best


def test_dp_matches_exact_search_on_random_single_peaked_profiles():
    rng = random.Random(2)
    for _ in range(300):
        m = rng.randint(1, 7)
        n = rng.randint(0, 7)
        axis, P = random_sp_profile(rng, m, n)
        assert is_single_peaked_on(P, axis)
        for k in range(1, m + 1):
            W, cost = cc_single_peaked(P, m, k, axis)
            assert len(set(W)) == k
            assert cost == misrepresentation(P, m, W) == optimum(P, m, k)
            assert cc_single_peaked(P, m, k, axis[::-1])[1] == cost


def test_dp_on_every_small_single_peaked_profile():
    m, axis = 4, (0, 1, 2, 3)
    R = [r for r in all_rankings(m) if is_single_peaked_on((r,), axis)]
    assert len(R) == 2 ** (m - 1)
    for P in itertools.product(R, repeat=3):
        for k in range(1, m + 1):
            assert cc_single_peaked(P, m, k, axis)[1] == optimum(P, m, k)


def test_greedy_guarantee():
    rng = random.Random(3)
    for _ in range(200):
        m = rng.randint(2, 7)
        n = rng.randint(1, 8)
        k = rng.randint(1, m)
        P = random_profile(rng, m, n)
        g = satisfaction(P, m, greedy_cc(P, m, k))
        opt = n * (m - 1) - optimum(P, m, k)
        assert Fraction(g) >= (1 - (1 - Fraction(1, k)) ** k) * opt
        assert g <= opt


def test_greedy_can_miss_the_optimum():
    P = ((0, 1, 2, 3, 4), (1, 0, 2, 3, 4), (2, 3, 1, 4, 0), (3, 2, 4, 1, 0), (4, 3, 2, 1, 0))
    assert chamberlin_courant(P, 5, 1) == (2,)
    assert greedy_cc(P, 5, 2) == (0, 2)
    assert misrepresentation(P, 5, (0, 2)) == 4
    assert chamberlin_courant(P, 5, 2) == (0, 3)
    assert misrepresentation(P, 5, (0, 3)) == 3
    Q = ((3, 1, 2, 0), (0, 3, 1, 2), (2, 1, 0, 3))
    assert greedy_cc(Q, 4, 2) == (0, 1) and misrepresentation(Q, 4, (0, 1)) == 2
    assert chamberlin_courant(Q, 4, 2) == (2, 3) and misrepresentation(Q, 4, (2, 3)) == 1


def test_one_seat_is_the_borda_winner():
    rng = random.Random(4)
    for _ in range(100):
        m = rng.randint(1, 6)
        n = rng.randint(1, 6)
        P = random_profile(rng, m, n)
        borda = [sum(m - 1 - r.index(c) for r in P) for c in range(m)]
        assert chamberlin_courant(P, m, 1) == (borda.index(max(borda)),)


def test_full_committee_and_errors():
    P = ((2, 0, 1), (1, 0, 2))
    assert misrepresentation(P, 3, chamberlin_courant(P, 3, 3)) == 0
    assert satisfaction(P, 3, ()) == 0
    with pytest.raises(ValueError):
        chamberlin_courant(P, 3, 0)
    with pytest.raises(ValueError):
        cc_single_peaked(P, 3, 4, (2, 0, 1))


def test_page_example():
    axis = (0, 1, 2, 3, 4)
    P = ((0, 1, 2, 3, 4), (1, 0, 2, 3, 4), (2, 3, 1, 4, 0), (3, 2, 4, 1, 0), (4, 3, 2, 1, 0))
    assert is_single_peaked_on(P, axis)
    W, cost = cc_single_peaked(P, 5, 2, axis)
    assert cost == 3 and misrepresentation(P, 5, W) == 3
    assert chamberlin_courant(P, 5, 2) == (0, 3)
    assert satisfaction(P, 5, (0, 3)) == 17


def test_anonymous():
    rng = random.Random(5)
    profiles = [random_profile(rng, 4, 3) for _ in range(40)]
    rule = lambda P, m: chamberlin_courant(P, m, 2)
    assert check_anonymity(rule, 4, 3, profiles=profiles) is None


def test_large_single_peaked_instance():
    rng = random.Random(6)
    axis, P = random_sp_profile(rng, 30, 200)
    W, cost = cc_single_peaked(P, 30, 5, axis)
    assert cost == misrepresentation(P, 30, W)
    g = greedy_cc(P, 30, 5)
    assert misrepresentation(P, 30, g) >= cost

History

Chamberlin and Courant (1983) proposed the rule as a form of proportional representation built on the Borda count: each voter is assigned to its best representative, and the assignment with the highest total Borda score wins. Monroe (1995) added a balance condition on the number of voters per representative. Procaccia, Rosenschein and Zohar (2008) proved that both rules are NP-hard to compute, Lu and Boutilier (2011) studied them as budgeted social choice and used the greedy algorithm, and Betzler, Slinko and Uhlmann (2013) mapped the parameterized complexity and gave the dynamic program for single-peaked profiles.

References

  1. John R. Chamberlin and Paul N. Courant, Representative deliberations and representative decisions: proportional representation and the Borda rule, American Political Science Review 77(3) (1983), 718-733, the rule that assigns each voter to its best committee member and maximizes the total Borda score
  2. Ariel D. Procaccia, Jeffrey S. Rosenschein and Aviv Zohar, On the complexity of achieving proportional representation, Social Choice and Welfare 30(3) (2008), 353-362, NP-completeness of winner determination with approval misrepresentation
  3. Tyler Lu and Craig Boutilier, Budgeted social choice: from consensus to personalized decision making, Proceedings of IJCAI 2011, 280-286, Theorem 8 (NP-hardness with Borda scores) and the greedy algorithm with the 1 - 1/e guarantee
  4. Nadja Betzler, Arkadii Slinko and Johannes Uhlmann, On the computation of fully proportional representation, Journal of Artificial Intelligence Research 47 (2013), 475-519, Section 5.1.1, Theorem 8 and Algorithm 2 (the dynamic program for single-peaked profiles, O(n m^2) time); Theorems 1 and 2 (W[2]-hardness in the committee size)
  5. George L. Nemhauser, Laurence A. Wolsey and Marshall L. Fisher, An analysis of approximations for maximizing submodular set functions I, Mathematical Programming 14(1) (1978), 265-294, the greedy bound 1 - (1 - 1/k)^k for monotone submodular functions
  6. Edith Elkind, Martin Lackner and Dominik Peters, Preference restrictions in computational social choice: a survey, arXiv 2205.09092, version 2, March 2025, Section 6.2.1 (Theorem 6.2 for single-peaked profiles, Proposition 6.3 for single-crossing profiles, and trees)
  7. Martin Lackner and Piotr Skowron, Multi-Winner Voting with Approval Preferences, arXiv 2007.01795, version of August 2022 (published by Springer, 2023), Table 4.1 (CC satisfies JR, not PJR or EJR)

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