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 %tiebreak; # $tiebreak{ winningcand }{ losingcand } = 1
25 while (@ARGV && $ARGV[0] =~ m/[<>]/) {
26 my ($losers, $winners) = ($? eq '<' ? ($`, $') : ($', $`));
27 my @losers = sort split /\,/, $losers;
28 my @winners = sort split /\,/, $winners;
29 die "@losers @winners" if @losers>1 && @winners>1;
30 my @all = sort @losers, @winners;
32 my ($how, $howers) = @_;
33 return unless @$howers == 1;
34 die "@all $how" if defined $tiebreak{$how}{"@all"};
35 $tiebreak{$how}{"@all"} = $howers->[0];
37 $record->('winner', \@winners);
38 $record->('loser', \@losers);
42 our $places = shift @ARGV;
43 die unless $places eq ($places + 0);
45 open DEBUG, ">.stv.log" or die $!;
49 m/^(\w+) ([A-Z]+)$/ or die "$_ ?";
54 Prefs => [ split //, $prefs ],
56 push @allvotes, $vote;
61 confess unless defined $f;
62 return sprintf "%10.6f = %-10s", $f, $f;
67 push @{ $vote->{Log} }, "stage $stage: $m";
70 our @elected; # $elected[] = $candidate
72 our @unsorted = @allvotes;
75 # $sorted{$firstpref}{Votes} = [ $vote, ... ]
76 # $sorted{$firstpref}{Cand} = $firstpref
77 # $sorted{$firstpref}{Total} = $totalweight
78 our @surpluses; # values same as %sorted
80 our @exhausted; # votes
82 our %continuing; # $continuing{$candidate}=1
84 our @stagerecord; # $stagerecord[]{$candidate} = $total
86 sub voteliveprefs ($) {
88 grep { $continuing{$_} } @{ $vote->{Prefs} };
91 sub votelogfull ($$) {
94 votelog $vote, ("continuing prefs: ". join ' ', voteliveprefs $vote);
97 foreach my $vote (@allvotes) {
98 $continuing{$_}=1 foreach @{ $vote->{Prefs} };
101 sub equalpiles ($@) {
102 my ($how, @sorted) = @_;
103 return () unless @sorted;
105 my $eqtotal = $s->{Total};
107 while ($count < @sorted && $sorted[$count]{Total} == $eqtotal) {
108 printf "%7s %10s %s\n", $how, $sorted[$count]{Cand},
109 pr $sorted[$count]{Total};
112 return @sorted[ 0 .. $count-1 ];
115 sub historically_prefer ($@) {
116 my ($signum, @choices) = @_;
117 # $signum==+1 means choose candidates with more early preferences
119 return $choices[0] if @choices < 2;
122 foreach my $sr (@stagerecord) {
123 my $d = ($sr->{ $a->{Cand} }//0) <=> ($sr->{ $b->{Cand} }//0);
124 return -$d * $signum if $d;
129 @choices = sort $compare @choices;
131 print DEBUG "historically_prefer\n",
132 Data::Dumper->Dump([\@choices, \@stagerecord],
133 [qw(_@choices _@stagerecord)]);
135 foreach my $s (@choices) {
137 printf " %6s %10s |", 'tiebrk', $c;
138 foreach my $sr (@stagerecord) {
139 my $p = pr($sr->{$c} // 0);
150 last if $numequal >= @choices;
151 $b = $choices[$numequal];
152 last if $compare->();
157 my $how = $signum > 0 ? 'winner' : 'loser';
158 my @all = sort map { $_->{Cand} } @choices[ 0 .. $numequal-1 ];
159 my $hower = $tiebreak{$how}{"@all"};
160 if (defined $hower) {
161 printf "%7.7s %10s !!!!!!!!!!\n", "TIE".(uc $how), $hower;
162 return grep { $_->{Cand} eq $hower } @choices;
164 die "need tie break for $how between @all\n";
170 foreach my $c (keys %continuing) {
180 printf "----- stage %d -----\n", $stage;
182 print DEBUG "#################### $stage ####################\n",
184 [ \@stagerecord, \@elected, \@unsorted, \%sorted, \@surpluses, \%continuing ],
185 [qw( _@stagerecord _@elected _@unsorted _%sorted _@surpluses _%continuing )]
188 my $placesremain = $places - @elected;
190 unless ($placesremain > 0) {
191 printf "Complete: @elected\n";
195 while (my $vote = shift @unsorted) {
196 my ($firstpref) = voteliveprefs $vote;
197 if (!defined $firstpref) {
198 votelog $vote, "ballot exhausted";
199 push @exhausted, $vote;
201 push @{ $sorted{$firstpref}{Votes} }, $vote;
204 foreach my $firstpref (sort keys %sorted) {
205 foreach my $vote (@{ $sorted{$firstpref}{Votes} }) {
206 votelog $vote, "counted for $firstpref ".pr $vote->{Weight};
210 my $things_update = sub {
211 foreach my $s (values %sorted) {
212 $s->{Total} = sum0 map { $_->{Weight} } @{ $s->{Votes } };
214 @sorted = nsort_by { -$_->{Total} } values %sorted;
218 print DEBUG "SORTED\n", Dumper(\@sorted);
220 push @stagerecord, { map { ($_->{Cand}, $_->{Total}) } @sorted };
222 my $totalvalid = 0/1;
223 my $countvalid = sub {
225 foreach my $s (@$l) {
226 printf "%-7s %10s %s\n", $what, $s->{Cand}, pr $s->{Total};
227 $totalvalid += $s->{Total};
230 $countvalid->(\@sorted, '1stpref');
231 $countvalid->(\@surpluses, 'surplus');
233 printf "%7s %10s %s\n", 'TOTAL', '-----', pr $totalvalid;
235 unless ($totalvalid > 0) {
236 printf "No more votes!\n";
240 my $quota = $totalvalid / ($placesremain + 1);
241 printf "%7s %10s %s\n", 'quota', '', pr $quota;
243 my $need_to_transfer_surplus = 1;
247 # Look for people to elect.
248 # We elect as many as we can, rather than recomputing the (lower) quota
252 my $topvoters = $s->{Total};
253 my $surplus = $topvoters - $quota;
254 last unless $surplus >= 0;
255 last unless $placesremain;
257 my @elect = equalpiles 'elect?', @sorted;
259 if (@elect > $placesremain) {
261 @elect = historically_prefer +1, @elect;
262 printf "%7s %10s\n", 'tie!', $elect[0]{Cand};
265 foreach $s (@elect) {
266 printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
267 push @elected, $s->{Cand};
269 foreach my $vote (@{ $s->{Votes} }) {
270 votelog $vote, "elected $s->{Cand}";
273 $s->{Surplus} = $surplus;
274 push @newsurpluses, $s;
275 delete $sorted{ $s->{Cand} };
276 delete $continuing{ $s->{Cand} };
283 foreach my $s (@newsurpluses) {
284 # calculate the transfer value of each surplus
285 # we do this simultaneously, but based on the number of
286 # continuing candidates (excluding all the ones elected already)
289 my $votes = $s->{Votes};
290 my $surplus = $s->{Surplus};
294 grep { !!voteliveprefs $_ }
298 printf "%7s %10s %s\n", 'xfrable', $s->{Cand}, pr $transferrable;
299 if ($transferrable > $surplus) {
300 $derate = $transferrable / $surplus;
301 printf "%7s %10s %s\n", 'derate', $s->{Cand}, pr $derate;
302 foreach my $vote (@{ $s->{Votes} }) {
303 votelog $vote, "part of surplus, derated ". pr $derate;
304 $vote->{Weight} /= $derate;
307 $s->{Total} = $transferrable / $derate;
312 printf "%7s %10s %s\n", 'surplus', $s->{Cand}, pr $s->{Total};
314 $need_to_transfer_surplus = 0;
315 # before actually transferring a surplus, we will consider
316 # eliminating, and then reconsider with a lower quota
319 my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
320 printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
322 # Look for people to eliminate
323 # We eliminate before trying to transfer surpluses
325 my $elimvotebefore = 0/1;
329 if ($elimvotebefore) {
330 printf "%18s %s\n", 'elimination, sofar', pr $elimvotebefore;
331 } elsif (@surpluses) {
332 printf "%18s\n", 'elimination, maybe';
334 printf "%18s\n", 'elimination, starts';
337 my @elim = equalpiles 'elim?', reverse @sorted;
338 my $elimvotenow = sum0 map { $_->{Total} } @elim;
340 if (@surpluses || $elimvotebefore) {
342 if (@sorted == @elim) {
343 printf "%18s\n", 'no-elim (all-equal)';
346 my $nextup = $sorted[ $#sorted - @elim ];
347 printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
349 my $aheadby = $nextup->{Total} - ($elimvotenow + $elimvotebefore);
350 unless ($deferredsurplus <= $aheadby) {
352 printf "%18s %s\n", 'no-elim (nextup)', pr $aheadby;
359 (scalar keys %continuing) - (scalar @elim) < $placesremain;
361 # eliminate only one then, and try again
362 printf "elim-tie!\n";
363 @elim = historically_prefer -1, @elim;
366 foreach my $s (@elim) {
368 printf "%7s %10s %s\n", 'ELIM', $c, '----------';
369 my $votes = $s->{Votes};
370 votelogfull $_, "failed to stop $c elimination" foreach @$votes;
371 $elimvotebefore += $s->{Total};
372 delete $continuing{$c};
374 push @unsorted, @$votes;
378 $need_to_transfer_surplus = 0;
379 last if $elim_tie; # no more, then!
382 next unless $need_to_transfer_surplus;
384 @surpluses = nsort_by { $_->{Total} } @surpluses;
385 my @surplusxfer = equalpiles 'xfer?', @surpluses;
386 die unless @surplusxfer;
388 if (@surplusxfer > 1) {
389 @surplusxfer = historically_prefer +1, @surplusxfer;
392 my $s = $surplusxfer[0];
394 printf "%7s %10s\n", 'xfer', $c;
395 my $votes = $s->{Votes};
396 votelogfull $_, "surplus transferred" foreach @$votes;
397 @surpluses = grep { $_->{Cand} ne $c } @surpluses;
398 push @unsorted, @$votes;
401 open VL, ">.stv.votes" or die $!;
402 foreach my $vote (@allvotes) {
403 print VL "----------------------------------------\n";
404 print VL "voter $vote->{Voter}\n";
405 print VL "prefs ". (join " ", @{ $vote->{Prefs} }). "\n";
406 print VL $_, "\n" foreach @{ $vote->{Log} };
408 print VL "========================================\n";