chiark / gitweb /
03f16d8d0e418d2488e30a4011f1e92b9a6342b0
[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     # $signum==+1 means choose candidates with more early preferences
99
100     return $choices[0] if @choices < 2;
101
102     my $compare = sub {
103         foreach my $sr (@stagerecord) {
104             my $d = ($sr->{ $a->{Cand} }//0) <=> ($sr->{ $b->{Cand} }//0);
105             return -$d * $signum if $d;
106         }
107         return 0;
108     };
109
110     @choices = sort $compare @choices;
111
112     print DEBUG "historically_prefer\n",
113         Data::Dumper->Dump([\@choices, \@stagerecord],
114                            [qw(_@choices _@stagerecord)]);
115
116     foreach my $s (@choices) {
117         my $c = $s->{Cand};
118         printf " %6s %10s |", 'tiebrk', $c;
119         foreach my $sr (@stagerecord) {
120             my $p = pr($sr->{$c} // 0);
121             $p =~ s/\.0+\b//g;
122             $p =~ s/ //g;
123             print "$p|";
124         }
125         print "\n";
126     }
127
128     $a = $choices[0];
129     my $numequal = 1;
130     for (;;) {
131         last if $numequal >= @choices;
132         $b = $choices[$numequal];
133         last if $compare->();
134         $numequal++;
135     }
136
137     die 'random choice unimplemented' if $numequal > 1;
138     return $choices[0];
139 }
140
141 foreach my $c (keys %continuing) {
142     $sorted{$c} = {
143         Cand => $c,
144         Votes => [],
145     };
146 }
147
148 for (;;) {
149     $stage++;
150
151     printf "----- stage %d -----\n", $stage;
152
153     print DEBUG "#################### $stage ####################\n",
154         Data::Dumper->Dump(
155 [ \@stagerecord, \@elected, \@unsorted, \%sorted, \@surpluses, \%continuing ],
156 [qw( _@stagerecord _@elected _@unsorted _%sorted _@surpluses _%continuing )]
157            );
158
159     my $placesremain = $places - @elected;
160
161     unless ($placesremain > 0) {
162         printf "Complete: @elected\n";
163         last;
164     }
165
166     while (my $vote = shift @unsorted) {
167         my ($firstpref) = voteliveprefs $vote;
168         if (!defined $firstpref) {
169             votelog $vote, "ballot exhausted";
170             push @exhausted, $vote;
171         } else {
172             push @{ $sorted{$firstpref}{Votes} }, $vote;
173         }
174     }
175     foreach my $firstpref (sort keys %sorted) {
176         foreach my $vote (@{ $sorted{$firstpref}{Votes} }) {
177             votelog $vote, "counted for $firstpref ".pr $vote->{Weight};
178         }
179     }
180     my @sorted;
181     my $things_update = sub {
182         foreach my $s (values %sorted) {
183             $s->{Total} = sum0 map { $_->{Weight} } @{ $s->{Votes } };
184         }
185         @sorted = nsort_by { -$_->{Total} } values %sorted;
186     };
187     $things_update->();
188
189     print DEBUG "SORTED\n", Dumper(\@sorted);
190
191     push @stagerecord, { map { ($_->{Cand}, $_->{Total}) } @sorted };
192
193     my $totalvalid = 0/1;
194     my $countvalid = sub {
195         my ($l, $what) = @_;
196         foreach my $s (@$l) {
197             printf "%-7s %10s %s\n", $what, $s->{Cand}, pr $s->{Total};
198             $totalvalid += $s->{Total};
199         }
200     };
201     $countvalid->(\@sorted,    '1stpref');
202     $countvalid->(\@surpluses, 'surplus');
203
204     printf "%7s %10s %s\n", 'TOTAL', '-----', pr $totalvalid;
205
206     unless ($totalvalid > 0) {
207         printf "No more votes!\n";
208         last;
209     }
210
211     my $quota = $totalvalid / ($placesremain + 1);
212     printf "%7s %10s %s\n", 'quota', '', pr $quota;
213
214     my $need_to_transfer_surplus = 1;
215
216     my @newsurpluses;
217
218     # Look for people to elect.
219     # We elect as many as we can, rather than recomputing the (lower) quota
220     # (ERS rules 5.4.9)
221     for (;;) {
222         my $s = $sorted[0];
223         my $topvoters = $s->{Total};
224         my $surplus = $topvoters - $quota;
225         last unless $surplus >= 0;
226         last unless $placesremain;
227
228         my @elect = equalpiles 'elect?', @sorted;
229
230         if (@elect > $placesremain) {
231             # oh my god
232             @elect = historically_prefer +1, @elect;
233             printf "%7s %10s\n", 'tie!', $elect[0]{Cand};
234         }
235
236         foreach $s (@elect) {
237             printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
238             push @elected, $s->{Cand};
239
240             foreach my $vote (@{ $s->{Votes} }) {
241                 votelog $vote, "elected $s->{Cand}";
242             }
243
244             $s->{Surplus} = $surplus;
245             push @newsurpluses, $s;
246             delete $sorted{ $s->{Cand} };
247             delete $continuing{ $s->{Cand} };
248             $placesremain--;
249         }
250
251         $things_update->();
252     }
253
254     foreach my $s (@newsurpluses) {
255         # calculate the transfer value of each surplus
256         # we do this simultaneously, but based on the number of
257         # continuing candidates (excluding all the ones elected already)
258         # ERS rule 5.3.3
259
260         my $votes = $s->{Votes};
261         my $surplus = $s->{Surplus};
262         my $transferrable =
263             sum0
264             map { $_->{Weight} }
265             grep { !!voteliveprefs $_ }
266             @$votes;
267
268         my $derate = 1/1;
269         printf "%7s %10s %s\n", 'xfrable', $s->{Cand}, pr $transferrable;
270         if ($transferrable > $surplus) {
271             $derate = $transferrable / $surplus;
272             printf "%7s %10s %s\n", 'derate', $s->{Cand}, pr $derate;
273             foreach my $vote (@{ $s->{Votes} }) {
274                 votelog $vote, "part of surplus, derated ". pr $derate;
275                 $vote->{Weight} /= $derate;
276             }
277         }
278         $s->{Total} = $transferrable / $derate;
279
280         push @surpluses, $s;
281
282         $things_update->();
283         printf "%7s %10s %s\n", 'surplus', $s->{Cand}, pr $s->{Total};
284
285         $need_to_transfer_surplus = 0;
286         # before actually transferring a surplus, we will consider
287         # eliminating, and then reconsider with a lower quota
288     }
289
290     my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
291     printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
292
293     # Look for people to eliminate
294     # We eliminate before trying to transfer surpluses
295     # ERS 5.2.5
296     my $elimvotebefore = 0/1;
297     for (;;) {
298         last unless @sorted;
299
300         if ($elimvotebefore) {
301             printf "%18s %s\n", 'elimination, sofar', pr $elimvotebefore;
302         } elsif (@surpluses) {
303             printf "%18s\n", 'elimination, maybe';
304         } else {
305             printf "%18s\n", 'elimination, starts';
306         }
307
308         my @elim = equalpiles 'elim?', reverse @sorted;
309         my $elimvotenow = sum0 map { $_->{Total} } @elim;
310
311         if (@surpluses || $elimvotebefore) {
312             # rule 5.2.2
313             if (@sorted == @elim) {
314                 printf "%18s\n", 'no-elim (all-equal)';
315                 last;
316             }
317             my $nextup = $sorted[ $#sorted - @elim ];
318             printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
319                 pr $nextup->{Total};
320             my $aheadby = $nextup->{Total} - ($elimvotenow + $elimvotebefore);
321             unless ($deferredsurplus <= $aheadby) {
322                 # rule 5.2.2 (b)
323                 printf "%18s %s\n", 'no-elim (nextup)', pr $aheadby;
324                 last;
325             }
326         }
327
328         my $elim_tie =
329             @elim > 1 &&
330             (scalar keys %continuing) - (scalar @elim) < $placesremain;
331         if ($elim_tie) {
332             # eliminate only one then, and try again
333             printf "elim-tie!\n";
334             @elim = historically_prefer -1, @elim;
335         }
336
337         foreach my $s (@elim) {
338             my $c = $s->{Cand};
339             printf "%7s %10s %s\n", 'ELIM', $c, '----------';
340             my $votes = $s->{Votes};
341             votelogfull $_, "failed to stop $c elimination" foreach @$votes;
342             $elimvotebefore += $s->{Total};
343             delete $continuing{$c};
344             delete $sorted{$c};
345             push @unsorted, @$votes;
346         }
347         
348         $things_update->();
349         $need_to_transfer_surplus = 0;
350         last if $elim_tie; # no more, then!
351     }
352     
353     next unless $need_to_transfer_surplus;
354
355     @surpluses = nsort_by { $_->{Total} } @surpluses;
356     my @surplusxfer = equalpiles 'xfer?', @surpluses;
357     die unless @surplusxfer;
358
359     if (@surplusxfer > 1) {
360         @surplusxfer = historically_prefer +1, @surplusxfer;
361     }
362
363     my $s = $surplusxfer[0];
364     my $c = $s->{Cand};
365     printf "%7s %10s\n", 'xfer', $c;
366     my $votes = $s->{Votes};
367     votelogfull $_, "surplus transferred" foreach @$votes;
368     @surpluses = grep { $_->{Cand} ne $c } @surpluses;
369     push @unsorted, @$votes;
370 }
371
372 print "done.\n";