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