chiark / gitweb /
stv: correct surplus transfer value
[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;
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 $vote->{Weight} for $firstpref";
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;
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         printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
209         push @elected, $s->{Cand};
210
211         foreach my $vote (@{ $s->{Votes} }) {
212             votelog $vote, "elected $s->{Cand}";
213         }
214
215         $s->{Surplus} = $surplus;
216         push @newsurpluses, $s;
217         delete $sorted{ $s->{Cand} };
218         delete $continuing{ $s->{Cand} };
219
220         $things_update->();
221     }
222
223     foreach my $s (@newsurpluses) {
224         # calculate the transfer value of each surplus
225         # we do this simultaneously, but based on the number of
226         # continuing candidates (excluding all the ones elected already)
227         # ERS rule 5.3.3
228
229         my $votes = $s->{Votes};
230         my $surplus = $s->{Surplus};
231         my $transferrable =
232             sum0
233             map { $_->{Weight} }
234             grep { !!voteliveprefs $_ }
235             @$votes;
236
237         printf "%7s %10s %s\n", 'xfrable', $s->{Cand}, pr $transferrable;
238         if ($transferrable > $surplus) {
239             my $derate = $transferrable / $surplus;
240             printf "%7s %10s %s\n", 'derate', $s->{Cand}, pr $derate;
241             foreach my $vote (@{ $s->{Votes} }) {
242                 votelog $vote, "part of surplus, derated ". pr $derate;
243                 $vote->{Weight} /= $derate;
244             }
245         }
246         push @surpluses, $s;
247
248         $things_update->();
249         printf "%7s %10s %s\n", 'surplus', $s->{Cand}, pr $s->{Total};
250
251         $need_to_transfer_surplus = 0;
252         # before actually transferring a surplus, we will consider
253         # eliminating, and then reconsider with a lower quota
254     }
255
256     my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
257     printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
258
259     # Look for people to eliminate
260     # We eliminate before trying to transfer surpluses
261     # ERS 5.2.5
262     my $elimvotebefore = 0;
263     for (;;) {
264         last unless @sorted;
265
266         if ($elimvotebefore) {
267             printf "%18s %s\n", 'elimination, sofar', pr $elimvotebefore;
268         } elsif (@surpluses) {
269             printf "%18s\n", 'elimination, maybe';
270         } else {
271             printf "%18s\n", 'elimination, starts';
272         }
273
274         my @elim = equalpiles 'elim?', reverse @sorted;
275         my $elimvotenow = sum0 map { $_->{Total} } @elim;
276
277         if (@surpluses || $elimvotebefore) {
278             # rule 5.2.2
279             if (@sorted == @elim) {
280                 printf "%18s\n", 'no-elim (all-equal)';
281                 last;
282             }
283             my $nextup = $sorted[ $#sorted - @elim ];
284             printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
285                 pr $nextup->{Total};
286             my $aheadby = $nextup->{Total} - ($elimvotenow + $elimvotebefore);
287             unless ($deferredsurplus <= $aheadby) {
288                 # rule 5.2.2 (b)
289                 printf "%18s %s\n", 'no-elim (nextup)', pr $aheadby;
290                 last;
291             }
292         }
293
294         my $elim_tie =
295             @elim > 1 &&
296             (scalar keys %continuing) - (scalar @elim) < $placesremain;
297         if ($elim_tie) {
298             # eliminate only one then, and try again
299             printf "elim-tie!\n";
300             @elim = historically_prefer -1, @elim;
301         }
302
303         foreach my $s (@elim) {
304             my $c = $s->{Cand};
305             printf "%7s %10s %s\n", 'ELIM', $c, '----------';
306             my $votes = $s->{Votes};
307             votelogfull $_, "failed to stop $c elimination" foreach @$votes;
308             $elimvotebefore += $s->{Total};
309             delete $continuing{$c};
310             delete $sorted{$c};
311             push @unsorted, @$votes;
312         }
313         
314         $things_update->();
315         $need_to_transfer_surplus = 0;
316         last if $elim_tie; # no more, then!
317     }
318     
319     next unless $need_to_transfer_surplus;
320
321     @surpluses = nsort_by { $_->{Total} } @surpluses;
322     my @surplusxfer = equalpiles 'xfer?', @surpluses;
323     die unless @surplusxfer;
324
325     if (@surplusxfer > 1) {
326         @surplusxfer = historically_prefer +1, @surplusxfer;
327     }
328
329     my $s = $surplusxfer[0];
330     my $c = $s->{Cand};
331     printf "%7s %10s\n", 'xfer', $c;
332     my $votes = $s->{Votes};
333     votelogfull $_, "surplus transferred" foreach @$votes;
334     @surpluses = grep { $_->{Cand} ne $c } @surpluses;
335     push @unsorted, @$votes;
336 }
337
338 print "done.\n";