3 # Does STV according to
4 # http://www.rosenstiel.co.uk/stvrules/av/index.htm
12 use List::Util qw(sum0);
13 use List::MoreUtils qw(nsort_by);
23 our $places = shift @ARGV;
24 die unless $places eq ($places + 0);
26 open DEBUG, ">.stv.log" or die $!;
30 m/^(\w+) ([A-Z]+)$/ or die "$_ ?";
35 Prefs => [ split //, $prefs ],
37 push @allvotes, $vote;
42 confess unless defined $f;
43 return sprintf "%10.6f = %-10s", $f, $f;
48 push @{ $vote->{Log} }, "stage $stage: $m";
51 our @elected; # $elected[] = $candidate
53 our @unsorted = @allvotes;
56 # $sorted{$firstpref}{Votes} = [ $vote, ... ]
57 # $sorted{$firstpref}{Cand} = $firstpref
58 # $sorted{$firstpref}{Total} = $totalweight
59 our @surpluses; # values same as %sorted
61 our @exhausted; # votes
63 our %continuing; # $continuing{$candidate}=1
65 our @stagerecord; # $stagerecord[]{$candidate} = $total
67 sub voteliveprefs ($) {
69 grep { $continuing{$_} } @{ $vote->{Prefs} };
72 sub votelogfull ($$) {
75 votelog $vote, ("continuing prefs: ". join ' ', voteliveprefs $vote);
78 foreach my $vote (@allvotes) {
79 $continuing{$_}=1 foreach @{ $vote->{Prefs} };
83 my ($how, @sorted) = @_;
84 return () unless @sorted;
86 my $eqtotal = $s->{Total};
88 while ($count < @sorted && $sorted[$count]{Total} == $eqtotal) {
89 printf "%7s %10s %s\n", $how, $sorted[$count]{Cand},
90 pr $sorted[$count]{Total};
93 return @sorted[ 0 .. $count-1 ];
96 sub historically_prefer ($@) {
97 my ($signum, @choices) = @_;
98 # $signum==+1 means choose candidates with more early preferences
100 return $choices[0] if @choices < 2;
103 foreach my $sr (@stagerecord) {
104 my $d = ($sr->{ $a->{Cand} }//0) <=> ($sr->{ $b->{Cand} }//0);
105 return -$d * $signum if $d;
110 @choices = sort $compare @choices;
112 print DEBUG "historically_prefer\n",
113 Data::Dumper->Dump([\@choices, \@stagerecord],
114 [qw(_@choices _@stagerecord)]);
116 foreach my $s (@choices) {
118 printf " %6s %10s |", 'tiebrk', $c;
119 foreach my $sr (@stagerecord) {
120 my $p = pr($sr->{$c} // 0);
131 last if $numequal >= @choices;
132 $b = $choices[$numequal];
133 last if $compare->();
137 die 'random choice unimplemented' if $numequal > 1;
141 foreach my $c (keys %continuing) {
151 printf "----- stage %d -----\n", $stage;
153 print DEBUG "#################### $stage ####################\n",
155 [ \@stagerecord, \@elected, \@unsorted, \%sorted, \@surpluses, \%continuing ],
156 [qw( _@stagerecord _@elected _@unsorted _%sorted _@surpluses _%continuing )]
159 my $placesremain = $places - @elected;
161 unless ($placesremain > 0) {
162 printf "Complete: @elected\n";
166 while (my $vote = shift @unsorted) {
167 my ($firstpref) = voteliveprefs $vote;
168 if (!defined $firstpref) {
169 votelog $vote, "ballot exhausted";
170 push @exhausted, $vote;
172 push @{ $sorted{$firstpref}{Votes} }, $vote;
175 foreach my $firstpref (sort keys %sorted) {
176 foreach my $vote (@{ $sorted{$firstpref}{Votes} }) {
177 votelog $vote, "counted for $firstpref ".pr $vote->{Weight};
181 my $things_update = sub {
182 foreach my $s (values %sorted) {
183 $s->{Total} = sum0 map { $_->{Weight} } @{ $s->{Votes } };
185 @sorted = nsort_by { -$_->{Total} } values %sorted;
189 print DEBUG "SORTED\n", Dumper(\@sorted);
191 push @stagerecord, { map { ($_->{Cand}, $_->{Total}) } @sorted };
193 my $totalvalid = 0/1;
194 my $countvalid = sub {
196 foreach my $s (@$l) {
197 printf "%-7s %10s %s\n", $what, $s->{Cand}, pr $s->{Total};
198 $totalvalid += $s->{Total};
201 $countvalid->(\@sorted, '1stpref');
202 $countvalid->(\@surpluses, 'surplus');
204 printf "%7s %10s %s\n", 'TOTAL', '-----', pr $totalvalid;
206 unless ($totalvalid > 0) {
207 printf "No more votes!\n";
211 my $quota = $totalvalid / ($placesremain + 1);
212 printf "%7s %10s %s\n", 'quota', '', pr $quota;
214 my $need_to_transfer_surplus = 1;
218 # Look for people to elect.
219 # We elect as many as we can, rather than recomputing the (lower) quota
223 my $topvoters = $s->{Total};
224 my $surplus = $topvoters - $quota;
225 last unless $surplus >= 0;
226 last unless $placesremain;
228 my @elect = equalpiles 'elect?', @sorted;
230 if (@elect > $placesremain) {
232 @elect = historically_prefer +1, @elect;
233 printf "%7s %10s\n", 'tie!', $elect[0]{Cand};
236 foreach $s (@elect) {
237 printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
238 push @elected, $s->{Cand};
240 foreach my $vote (@{ $s->{Votes} }) {
241 votelog $vote, "elected $s->{Cand}";
244 $s->{Surplus} = $surplus;
245 push @newsurpluses, $s;
246 delete $sorted{ $s->{Cand} };
247 delete $continuing{ $s->{Cand} };
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)
260 my $votes = $s->{Votes};
261 my $surplus = $s->{Surplus};
265 grep { !!voteliveprefs $_ }
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;
278 $s->{Total} = $transferrable / $derate;
283 printf "%7s %10s %s\n", 'surplus', $s->{Cand}, pr $s->{Total};
285 $need_to_transfer_surplus = 0;
286 # before actually transferring a surplus, we will consider
287 # eliminating, and then reconsider with a lower quota
290 my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
291 printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
293 # Look for people to eliminate
294 # We eliminate before trying to transfer surpluses
296 my $elimvotebefore = 0/1;
300 if ($elimvotebefore) {
301 printf "%18s %s\n", 'elimination, sofar', pr $elimvotebefore;
302 } elsif (@surpluses) {
303 printf "%18s\n", 'elimination, maybe';
305 printf "%18s\n", 'elimination, starts';
308 my @elim = equalpiles 'elim?', reverse @sorted;
309 my $elimvotenow = sum0 map { $_->{Total} } @elim;
311 if (@surpluses || $elimvotebefore) {
313 if (@sorted == @elim) {
314 printf "%18s\n", 'no-elim (all-equal)';
317 my $nextup = $sorted[ $#sorted - @elim ];
318 printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
320 my $aheadby = $nextup->{Total} - ($elimvotenow + $elimvotebefore);
321 unless ($deferredsurplus <= $aheadby) {
323 printf "%18s %s\n", 'no-elim (nextup)', pr $aheadby;
330 (scalar keys %continuing) - (scalar @elim) < $placesremain;
332 # eliminate only one then, and try again
333 printf "elim-tie!\n";
334 @elim = historically_prefer -1, @elim;
337 foreach my $s (@elim) {
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};
345 push @unsorted, @$votes;
349 $need_to_transfer_surplus = 0;
350 last if $elim_tie; # no more, then!
353 next unless $need_to_transfer_surplus;
355 @surpluses = nsort_by { $_->{Total} } @surpluses;
356 my @surplusxfer = equalpiles 'xfer?', @surpluses;
357 die unless @surplusxfer;
359 if (@surplusxfer > 1) {
360 @surplusxfer = historically_prefer +1, @surplusxfer;
363 my $s = $surplusxfer[0];
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;