chiark / gitweb /
stv: fix ties
[appendix-a6.git] / stv
1 #!/usr/bin/perl -w
2 #
3 # Does STV according to
4 #  http://www.rosenstiel.co.uk/stvrules/av/index.htm
5
6 use strict;
7 use utf8;
8 use autodie;
9 use bigrat;
10 use Carp;
11 use Data::Dumper;
12 use List::Util qw(sum0);
13 use List::MoreUtils qw(nsort_by);
14
15 # vote is
16 #  { Voter => opaque,
17 #    Prefs => [ list ],
18 #    Weight => 1.0 }
19
20 our $stage=0;
21 our @allvotes;
22
23 our $places = shift @ARGV;
24 die unless $places eq ($places + 0);
25
26 open DEBUG, ">.stv.log" or die $!;
27
28 while (<>) {
29     next if m/^\w+$/;
30     m/^(\w+) ([A-Z]+)$/ or die "$_ ?";
31     my $prefs = $2;
32     my $vote = {
33         Voter => $1,
34         Weight => 1.0,
35         Prefs => [ split //, $prefs ],
36     };
37     push @allvotes, $vote;
38 }
39
40 sub pr ($) {
41     my ($f) = @_;
42     confess unless defined $f;
43     return sprintf "%10.6f = %-10s", $f, $f;
44 }
45
46 sub votelog ($$) {
47     my ($vote,$m) = @_;
48     push @{ $vote->{Log} }, "stage $stage: $m";
49 }
50
51 our @elected; # $elected[] = $candidate
52
53 our @unsorted = @allvotes;
54
55 our %sorted;
56 # $sorted{$firstpref}{Votes} = [ $vote, ... ]
57 # $sorted{$firstpref}{Cand} = $firstpref
58 # $sorted{$firstpref}{Total} = $totalweight
59 our @surpluses; # values same as %sorted
60
61 our @exhausted; # votes
62
63 our %continuing; # $continuing{$candidate}=1
64
65 our @stagerecord; # $stagerecord[]{$candidate} = $total
66
67 sub voteliveprefs ($) {
68     my ($vote) = @_;
69     grep { $continuing{$_} } @{ $vote->{Prefs} };
70 }
71
72 sub votelogfull ($$) {
73     my ($vote,$m) = @_;
74     votelog $vote, $m;
75     votelog $vote, ("continuing prefs: ". join ' ', voteliveprefs $vote);
76 }
77
78 foreach my $vote (@allvotes) {
79     $continuing{$_}=1 foreach @{ $vote->{Prefs} };
80 }
81
82 sub equalpiles ($@) {
83     my ($how, @sorted) = @_;
84     return () unless @sorted;
85     my $s = $sorted[0];
86     my $eqtotal = $s->{Total};
87     my $count = 0/1;
88     while ($count < @sorted && $sorted[$count]{Total} == $eqtotal) {
89         printf "%7s %10s %s\n", $how, $sorted[$count]{Cand},
90             pr $sorted[$count]{Total};
91         $count++;
92     }
93     return @sorted[ 0 .. $count-1 ];
94 }
95
96 sub historically_prefer ($@) {
97     my ($signum, @choices) = @_;
98
99     return $choices[0] if @choices < 2;
100
101     my $compare = sub {
102         foreach my $sr (@stagerecord) {
103             my $d = $sr->{ $a->{Cand} } <=> $sr->{ $b->{Cand} };
104             return $d * $signum if $d;
105         }
106         return 0;
107     };
108
109     @choices = sort $compare, @choices;
110     $a = $choices[0];
111     my $numequal = 0;
112     for (;;) {
113         last unless $numequal >= @choices;
114         $b = $choices[$numequal];
115         last if $compare->();
116     }
117
118     die 'random choice unimplemented' if $numequal > 1;
119     return $choices[0];
120 }
121
122 foreach my $c (keys %continuing) {
123     $sorted{$c} = {
124         Cand => $c,
125         Votes => [],
126     };
127 }
128
129 for (;;) {
130     $stage++;
131
132     printf "----- stage %d -----\n", $stage;
133
134     print DEBUG "#################### $stage ####################\n",
135         Data::Dumper->Dump(
136 [ \@stagerecord, \@elected, \@unsorted, \%sorted, \@surpluses, \%continuing ],
137 [qw( _@stagerecord _@elected _@unsorted _%sorted _@surpluses _%continuing )]
138            );
139
140     my $placesremain = $places - @elected;
141
142     unless ($placesremain > 0) {
143         printf "Complete: @elected\n";
144         last;
145     }
146
147     while (my $vote = shift @unsorted) {
148         my ($firstpref) = voteliveprefs $vote;
149         if (!defined $firstpref) {
150             votelog $vote, "ballot exhausted";
151             push @exhausted, $vote;
152         } else {
153             push @{ $sorted{$firstpref}{Votes} }, $vote;
154         }
155     }
156     foreach my $firstpref (sort keys %sorted) {
157         foreach my $vote (@{ $sorted{$firstpref}{Votes} }) {
158             votelog $vote, "counted for $firstpref ".pr $vote->{Weight};
159         }
160     }
161     my @sorted;
162     my $things_update = sub {
163         foreach my $s (@surpluses, values %sorted) {
164             $s->{Total} = sum0 map { $_->{Weight} } @{ $s->{Votes } };
165         }
166         @sorted = nsort_by { -$_->{Total} } values %sorted;
167     };
168     $things_update->();
169
170     print DEBUG "SORTED\n", Dumper(\@sorted);
171
172     push @stagerecord, { map { ($_->{Cand}, $_->{Total}) } @sorted };
173
174     my $totalvalid = 0/1;
175     my $countvalid = sub {
176         my ($l, $what) = @_;
177         foreach my $s (@$l) {
178             printf "%-7s %10s %s\n", $what, $s->{Cand}, pr $s->{Total};
179             $totalvalid += $s->{Total};
180         }
181     };
182     $countvalid->(\@sorted,    '1stpref');
183     $countvalid->(\@surpluses, 'surplus');
184
185     printf "%7s %10s %s\n", 'TOTAL', '-----', pr $totalvalid;
186
187     unless ($totalvalid > 0) {
188         printf "No more votes!\n";
189         last;
190     }
191
192     my $quota = $totalvalid / ($placesremain + 1);
193     printf "%7s %10s %s\n", 'quota', '', pr $quota;
194
195     my $need_to_transfer_surplus = 1;
196
197     my @newsurpluses;
198
199     # Look for people to elect.
200     # We elect as many as we can, rather than recomputing the (lower) quota
201     # (ERS rules 5.4.9)
202     for (;;) {
203         my $s = $sorted[0];
204         my $topvoters = $s->{Total};
205         my $surplus = $topvoters - $quota;
206         last unless $surplus >= 0;
207
208         my @elect = equalpiles 'elect?', @sorted;
209
210         if (@elect > $placesremain) {
211             # oh my god
212             @elect = historically_prefer +1, @elect;
213             printf "%7s %10s\n", 'tie!', $elect[0]{Cand};
214         }
215
216         foreach $s (@elect) {
217             printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
218             push @elected, $s->{Cand};
219
220             foreach my $vote (@{ $s->{Votes} }) {
221                 votelog $vote, "elected $s->{Cand}";
222             }
223
224             $s->{Surplus} = $surplus;
225             push @newsurpluses, $s;
226             delete $sorted{ $s->{Cand} };
227             delete $continuing{ $s->{Cand} };
228         }
229
230         $things_update->();
231     }
232
233     foreach my $s (@newsurpluses) {
234         # calculate the transfer value of each surplus
235         # we do this simultaneously, but based on the number of
236         # continuing candidates (excluding all the ones elected already)
237         # ERS rule 5.3.3
238
239         my $votes = $s->{Votes};
240         my $surplus = $s->{Surplus};
241         my $transferrable =
242             sum0
243             map { $_->{Weight} }
244             grep { !!voteliveprefs $_ }
245             @$votes;
246
247         printf "%7s %10s %s\n", 'xfrable', $s->{Cand}, pr $transferrable;
248         if ($transferrable > $surplus) {
249             my $derate = $transferrable / $surplus;
250             printf "%7s %10s %s\n", 'derate', $s->{Cand}, pr $derate;
251             foreach my $vote (@{ $s->{Votes} }) {
252                 votelog $vote, "part of surplus, derated ". pr $derate;
253                 $vote->{Weight} /= $derate;
254             }
255         }
256         push @surpluses, $s;
257
258         $things_update->();
259         printf "%7s %10s %s\n", 'surplus', $s->{Cand}, pr $s->{Total};
260
261         $need_to_transfer_surplus = 0;
262         # before actually transferring a surplus, we will consider
263         # eliminating, and then reconsider with a lower quota
264     }
265
266     my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
267     printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
268
269     # Look for people to eliminate
270     # We eliminate before trying to transfer surpluses
271     # ERS 5.2.5
272     my $elimvotebefore = 0/1;
273     for (;;) {
274         last unless @sorted;
275
276         if ($elimvotebefore) {
277             printf "%18s %s\n", 'elimination, sofar', pr $elimvotebefore;
278         } elsif (@surpluses) {
279             printf "%18s\n", 'elimination, maybe';
280         } else {
281             printf "%18s\n", 'elimination, starts';
282         }
283
284         my @elim = equalpiles 'elim?', reverse @sorted;
285         my $elimvotenow = sum0 map { $_->{Total} } @elim;
286
287         if (@surpluses || $elimvotebefore) {
288             # rule 5.2.2
289             if (@sorted == @elim) {
290                 printf "%18s\n", 'no-elim (all-equal)';
291                 last;
292             }
293             my $nextup = $sorted[ $#sorted - @elim ];
294             printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
295                 pr $nextup->{Total};
296             my $aheadby = $nextup->{Total} - ($elimvotenow + $elimvotebefore);
297             unless ($deferredsurplus <= $aheadby) {
298                 # rule 5.2.2 (b)
299                 printf "%18s %s\n", 'no-elim (nextup)', pr $aheadby;
300                 last;
301             }
302         }
303
304         my $elim_tie =
305             @elim > 1 &&
306             (scalar keys %continuing) - (scalar @elim) < $placesremain;
307         if ($elim_tie) {
308             # eliminate only one then, and try again
309             printf "elim-tie!\n";
310             @elim = historically_prefer -1, @elim;
311         }
312
313         foreach my $s (@elim) {
314             my $c = $s->{Cand};
315             printf "%7s %10s %s\n", 'ELIM', $c, '----------';
316             my $votes = $s->{Votes};
317             votelogfull $_, "failed to stop $c elimination" foreach @$votes;
318             $elimvotebefore += $s->{Total};
319             delete $continuing{$c};
320             delete $sorted{$c};
321             push @unsorted, @$votes;
322         }
323         
324         $things_update->();
325         $need_to_transfer_surplus = 0;
326         last if $elim_tie; # no more, then!
327     }
328     
329     next unless $need_to_transfer_surplus;
330
331     @surpluses = nsort_by { $_->{Total} } @surpluses;
332     my @surplusxfer = equalpiles 'xfer?', @surpluses;
333     die unless @surplusxfer;
334
335     if (@surplusxfer > 1) {
336         @surplusxfer = historically_prefer +1, @surplusxfer;
337     }
338
339     my $s = $surplusxfer[0];
340     my $c = $s->{Cand};
341     printf "%7s %10s\n", 'xfer', $c;
342     my $votes = $s->{Votes};
343     votelogfull $_, "surplus transferred" foreach @$votes;
344     @surpluses = grep { $_->{Cand} ne $c } @surpluses;
345     push @unsorted, @$votes;
346 }
347
348 print "done.\n";