| 1 | --- |
| 2 | tags: python, technical, example |
| 3 | date: 2016-05-26 11:00 |
| 4 | title: Exploring Voting Systems with Hypothesis |
| 5 | author: drmaciver |
| 6 | --- |
| 7 | |
| 8 | Hypothesis is, of course, a library for writing tests. |
| 9 | |
| 10 | But from an *implementation* point of view this is hardly noticeable. |
| 11 | Really it's a library for constructing and exploring data and using it |
| 12 | to prove or disprove hypotheses about it. It then has a small testing |
| 13 | library built on top of it. |
| 14 | |
| 15 | It's far more widely used as a testing library, and that's really where |
| 16 | the focus of its development lies, but with the *find* function you can |
| 17 | use it just as well to explore your data interactively. |
| 18 | |
| 19 | In this article we'll go through an example of doing this, by using it |
| 20 | to take a brief look at one of my other favourite subjects: Voting |
| 21 | systems. |
| 22 | |
| 23 | <!--more--> |
| 24 | |
| 25 | We're going to focus entirely on single winner preferential voting |
| 26 | systems: You have a set of candidates, and every voter gives a complete |
| 27 | ordering of the candidates from their favourite to their least |
| 28 | favourite. The voting system then tries to select a single candidate and |
| 29 | declare them the winner. |
| 30 | |
| 31 | The general Python interface for a voting system we'll use is things |
| 32 | that look like the following: |
| 33 | |
| 34 | ```python |
| 35 | def plurality_winner(election): |
| 36 | counts = Counter(vote[0] for vote in election) |
| 37 | alternatives = candidates_for_election(election) |
| 38 | winning_score = max(counts.values()) |
| 39 | winners = [c for c, v in counts.items() if v == winning_score] |
| 40 | if len(winners) > 1: |
| 41 | return None |
| 42 | else: |
| 43 | return winners[0] |
| 44 | ``` |
| 45 | |
| 46 | That is, they take a list of individual votes, each expressed |
| 47 | as a list putting the candidates in order, and return a candidate that |
| 48 | is an unambiguous winner or None in the event of a tie. |
| 49 | |
| 50 | The above implements plurality voting, what most people might think of |
| 51 | as "normal voting": The candidate with the most first preference votes |
| 52 | wins. |
| 53 | |
| 54 | The other main voting system we'll consider is Instant Runoff Voting ( |
| 55 | which you might know under the name "Alternative Vote" if you follow |
| 56 | British politics): |
| 57 | |
| 58 | ```python |
| 59 | def irv_winner(election): |
| 60 | candidates = candidates_for_election(election) |
| 61 | while len(candidates) > 1: |
| 62 | scores = Counter() |
| 63 | for vote in election: |
| 64 | for c in vote: |
| 65 | if c in candidates: |
| 66 | scores[c] += 1 |
| 67 | break |
| 68 | losing_score = min(scores[c] for c in candidates) |
| 69 | candidates = [c for c in candidates if scores[c] > losing_score] |
| 70 | if not candidates: |
| 71 | return None |
| 72 | else: |
| 73 | return candidates[0] |
| 74 | ``` |
| 75 | |
| 76 | In IRV, we run the vote in multiple rounds until we've eliminated all |
| 77 | but one candidate. In each round, we give each candidate a score which |
| 78 | is the number of voters who have ranked that candidate highest amongst |
| 79 | all the ones remaining. The candidates with the joint lowest score |
| 80 | drop out. |
| 81 | |
| 82 | At the end, we'll either have either zero or one candidates remaining ( |
| 83 | we can have zero if all candidates are tied for joint lowest score at |
| 84 | some point). If we have zero, that's a draw. If we have one, that's a |
| 85 | victory. |
| 86 | |
| 87 | It seems pretty plausible that these would not produce the same answer |
| 88 | all the time (it would be surprising if they did!), but it's maybe not |
| 89 | obvious how you would go about constructing an example that shows it. |
| 90 | |
| 91 | Fortunately, we don't have to because Hypothesis can do it for us! |
| 92 | |
| 93 | We first create a strategy which generates elections, using Hypothesis's |
| 94 | composite decorator: |
| 95 | |
| 96 | ```python |
| 97 | import hypothesis.strategies as st |
| 98 | |
| 99 | |
| 100 | @st.composite |
| 101 | def election(draw): |
| 102 | candidates = list(range(draw(st.integers(2, 10)))) |
| 103 | return draw(st.lists(st.permutations(candidates), min_size=1)) |
| 104 | ``` |
| 105 | |
| 106 | This first draws the set of candidates as a list of integers of size |
| 107 | between 2 and 10 (it doesn't really matter what our candidates are as |
| 108 | long as they're distinct, so we use integers for simplicity). It then |
| 109 | draws an election as lists of permutations of those candidates, as we |
| 110 | defined it above. |
| 111 | |
| 112 | We now write a condition to look for: |
| 113 | |
| 114 | ```python |
| 115 | def differing_without_ties(election): |
| 116 | irv = irv_winner(election) |
| 117 | if irv is None: |
| 118 | return False |
| 119 | plurality = plurality_winner(election) |
| 120 | if plurality is None: |
| 121 | return False |
| 122 | return irv != plurality |
| 123 | ``` |
| 124 | |
| 125 | That is, we're interested in elections where neither plurality nor IRV |
| 126 | resulted in a tie, but they resulted in distinct candidates winning. |
| 127 | |
| 128 | We can now run this in the console: |
| 129 | |
| 130 | ``` |
| 131 | >>> from hypothesis import find |
| 132 | >>> import voting as v |
| 133 | >>> distinct = find(v.election(), v.differing_without_ties) |
| 134 | >>> distinct |
| 135 | [[0, 1, 2], |
| 136 | [0, 1, 2], |
| 137 | [1, 0, 2], |
| 138 | [2, 1, 0], |
| 139 | [0, 1, 2], |
| 140 | [0, 1, 2], |
| 141 | [1, 0, 2], |
| 142 | [1, 0, 2], |
| 143 | [2, 1, 0]] |
| 144 | ``` |
| 145 | |
| 146 | The example is a bit large, mostly because we insisted on there being |
| 147 | no ties: If we'd broken ties arbitrarily (e.g. preferring the lower |
| 148 | numbered candidates) we could have found a smaller one. Also, in some |
| 149 | runs Hypothesis ends up finding a slightly smaller election but with |
| 150 | four candidates instead of three. |
| 151 | |
| 152 | We can check to make sure that these really do give different results: |
| 153 | |
| 154 | ``` |
| 155 | >>> v.irv_winner(distinct) |
| 156 | 1 |
| 157 | |
| 158 | >>> v.plurality_winner(distinct) |
| 159 | 0 |
| 160 | ``` |
| 161 | |
| 162 | There are a lot of other interesting properties of voting systems to |
| 163 | explore, but this is an article about Hypothesis rather than one about |
| 164 | voting, so I'll stop here. However the interested reader might want to |
| 165 | try to build on this to: |
| 166 | |
| 167 | 1. Find an election which has a [Condorcet Cycle](https://en.wikipedia.org/wiki/Voting_paradox) |
| 168 | 2. Find elections in which the majority prefers the plurality winner to |
| 169 | the IRV winner and vice versa. |
| 170 | 3. Use @given rather than find and write some tests verifying some of |
| 171 | [the classic properties of election systems](https://en.wikipedia.org/wiki/Voting_system#Evaluating_voting_systems_using_criteria). |
| 172 | |
| 173 | And the reader who isn't that interested in voting systems might still |
| 174 | want to think about how this could be useful in other areas: Development |
| 175 | is often a constant series of small experiments and, while testing is |
| 176 | often a good way to perform them, sometimes you just have a more |
| 177 | exploratory "I wonder if...?" question to answer, and it can be |
| 178 | extremely helpful to be able to bring Hypothesis to bear there too. |