3 # Does STV according to
4 # http://www.rosenstiel.co.uk/stvrules/av/index.htm
7 # ./stv [TIEBREAK ...] PLACES [INPUT-FILES ...]
9 # PLACES is the number of seats to be filled
11 # INPUT-FILES are in the format:
13 # where P, Q, R, etc. are candidates. Candidates
14 # must be single letters.
25 use List::Util qw(sum0);
26 use List::MoreUtils qw(nsort_by);
36 our %tiebreak; # $tiebreak{ winningcand }{ losingcand } = 1
38 while (@ARGV && $ARGV[0] =~ m/[<>]/) {
39 my ($losers, $winners) = ($? eq '<' ? ($`, $') : ($', $`));
40 my @losers = sort split /\,/, $losers;
41 my @winners = sort split /\,/, $winners;
42 die "@losers @winners" if @losers>1 && @winners>1;
43 my @all = sort @losers, @winners;
45 my ($how, $howers) = @_;
46 return unless @$howers == 1;
47 die "@all $how" if defined $tiebreak{$how}{"@all"};
48 $tiebreak{$how}{"@all"} = $howers->[0];
50 $record->('winner', \@winners);
51 $record->('loser', \@losers);
55 our $places = shift @ARGV;
56 die unless $places eq ($places + 0);
58 open DEBUG, ">.stv.log" or die $!;
62 m/^(\w+) ([A-Z]+)$/ or die "$_ ?";
67 Prefs => [ split //, $prefs ],
69 push @allvotes, $vote;
74 confess unless defined $f;
75 return sprintf "%10.6f = %-10s", $f, $f;
80 push @{ $vote->{Log} }, "stage $stage: $m";
83 our @elected; # $elected[] = $candidate
85 our @unsorted = @allvotes;
88 # $sorted{$firstpref}{Votes} = [ $vote, ... ]
89 # $sorted{$firstpref}{Cand} = $firstpref
90 # $sorted{$firstpref}{Total} = $totalweight
91 our @surpluses; # values same as %sorted
93 our @exhausted; # votes
95 our %continuing; # $continuing{$candidate}=1
97 our @stagerecord; # $stagerecord[]{$candidate} = $total
99 sub voteliveprefs ($) {
101 grep { $continuing{$_} } @{ $vote->{Prefs} };
104 sub votelogfull ($$) {
107 votelog $vote, ("continuing prefs: ". join ' ', voteliveprefs $vote);
110 foreach my $vote (@allvotes) {
111 $continuing{$_}=1 foreach @{ $vote->{Prefs} };
114 sub equalpiles ($@) {
115 my ($how, @sorted) = @_;
116 return () unless @sorted;
118 my $eqtotal = $s->{Total};
120 while ($count < @sorted && $sorted[$count]{Total} == $eqtotal) {
121 printf "%7s %10s %s\n", $how, $sorted[$count]{Cand},
122 pr $sorted[$count]{Total};
125 return @sorted[ 0 .. $count-1 ];
128 sub historically_prefer ($@) {
129 my ($signum, @choices) = @_;
130 # $signum==+1 means choose candidates with more early preferences
132 return $choices[0] if @choices < 2;
135 foreach my $sr (@stagerecord) {
136 my $d = ($sr->{ $a->{Cand} }//0) <=> ($sr->{ $b->{Cand} }//0);
137 return -$d * $signum if $d;
142 @choices = sort $compare @choices;
144 print DEBUG "historically_prefer\n",
145 Data::Dumper->Dump([\@choices, \@stagerecord],
146 [qw(_@choices _@stagerecord)]);
148 foreach my $s (@choices) {
150 printf " %6s %10s |", 'tiebrk', $c;
151 foreach my $sr (@stagerecord) {
152 my $p = pr($sr->{$c} // 0);
163 last if $numequal >= @choices;
164 $b = $choices[$numequal];
165 last if $compare->();
170 my $how = $signum > 0 ? 'winner' : 'loser';
171 my @all = sort map { $_->{Cand} } @choices[ 0 .. $numequal-1 ];
172 my $hower = $tiebreak{$how}{"@all"};
173 if (defined $hower) {
174 printf "%7.7s %10s !!!!!!!!!!\n", "TIE".(uc $how), $hower;
175 return grep { $_->{Cand} eq $hower } @choices;
177 die "need tie break for $how between @all\n";
183 foreach my $c (keys %continuing) {
193 printf "----- stage %d -----\n", $stage;
195 print DEBUG "#################### $stage ####################\n",
197 [ \@stagerecord, \@elected, \@unsorted, \%sorted, \@surpluses, \%continuing ],
198 [qw( _@stagerecord _@elected _@unsorted _%sorted _@surpluses _%continuing )]
201 my $placesremain = $places - @elected;
203 unless ($placesremain > 0) {
204 printf "Complete: @elected\n";
208 while (my $vote = shift @unsorted) {
209 my ($firstpref) = voteliveprefs $vote;
210 if (!defined $firstpref) {
211 votelog $vote, "ballot exhausted";
212 push @exhausted, $vote;
214 push @{ $sorted{$firstpref}{Votes} }, $vote;
217 foreach my $firstpref (sort keys %sorted) {
218 foreach my $vote (@{ $sorted{$firstpref}{Votes} }) {
219 votelog $vote, "counted for $firstpref ".pr $vote->{Weight};
223 my $things_update = sub {
224 foreach my $s (values %sorted) {
225 $s->{Total} = sum0 map { $_->{Weight} } @{ $s->{Votes } };
227 @sorted = nsort_by { -$_->{Total} } values %sorted;
231 print DEBUG "SORTED\n", Dumper(\@sorted);
233 push @stagerecord, { map { ($_->{Cand}, $_->{Total}) } @sorted };
235 my $totalvalid = 0/1;
236 my $countvalid = sub {
238 foreach my $s (@$l) {
239 printf "%-7s %10s %s\n", $what, $s->{Cand}, pr $s->{Total};
240 $totalvalid += $s->{Total};
243 $countvalid->(\@sorted, '1stpref');
244 $countvalid->(\@surpluses, 'surplus');
246 printf "%7s %10s %s\n", 'TOTAL', '-----', pr $totalvalid;
248 unless ($totalvalid > 0) {
249 printf "No more votes!\n";
253 my $quota = $totalvalid / ($placesremain + 1);
254 printf "%7s %10s %s\n", 'quota', '', pr $quota;
256 my $need_to_transfer_surplus = 1;
260 # Look for people to elect.
261 # We elect as many as we can, rather than recomputing the (lower) quota
265 my $topvoters = $s->{Total};
266 my $surplus = $topvoters - $quota;
267 last unless $surplus >= 0;
268 last unless $placesremain;
270 my @elect = equalpiles 'elect?', @sorted;
272 if (@elect > $placesremain) {
274 @elect = historically_prefer +1, @elect;
275 printf "%7s %10s\n", 'tie!', $elect[0]{Cand};
278 foreach $s (@elect) {
279 printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
280 push @elected, $s->{Cand};
282 foreach my $vote (@{ $s->{Votes} }) {
283 votelog $vote, "elected $s->{Cand}";
286 $s->{Surplus} = $surplus;
287 push @newsurpluses, $s;
288 delete $sorted{ $s->{Cand} };
289 delete $continuing{ $s->{Cand} };
296 foreach my $s (@newsurpluses) {
297 # calculate the transfer value of each surplus
298 # we do this simultaneously, but based on the number of
299 # continuing candidates (excluding all the ones elected already)
302 my $votes = $s->{Votes};
303 my $surplus = $s->{Surplus};
307 grep { !!voteliveprefs $_ }
311 printf "%7s %10s %s\n", 'xfrable', $s->{Cand}, pr $transferrable;
312 if ($transferrable > $surplus) {
313 $derate = $transferrable / $surplus;
314 printf "%7s %10s %s\n", 'derate', $s->{Cand}, pr $derate;
315 foreach my $vote (@{ $s->{Votes} }) {
316 votelog $vote, "part of surplus, derated ". pr $derate;
317 $vote->{Weight} /= $derate;
320 $s->{Total} = $transferrable / $derate;
325 printf "%7s %10s %s\n", 'surplus', $s->{Cand}, pr $s->{Total};
327 $need_to_transfer_surplus = 0;
328 # before actually transferring a surplus, we will consider
329 # eliminating, and then reconsider with a lower quota
332 my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
333 printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
335 # Look for people to eliminate
336 # We eliminate before trying to transfer surpluses
338 my $elimvotebefore = 0/1;
342 if ($elimvotebefore) {
343 printf "%18s %s\n", 'elimination, sofar', pr $elimvotebefore;
344 } elsif (@surpluses) {
345 printf "%18s\n", 'elimination, maybe';
347 printf "%18s\n", 'elimination, starts';
350 my @elim = equalpiles 'elim?', reverse @sorted;
351 my $elimvotenow = sum0 map { $_->{Total} } @elim;
353 if (@surpluses || $elimvotebefore) {
355 if (@sorted == @elim) {
356 printf "%18s\n", 'no-elim (all-equal)';
359 my $nextup = $sorted[ $#sorted - @elim ];
360 printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
362 my $aheadby = $nextup->{Total} - ($elimvotenow + $elimvotebefore);
363 unless ($deferredsurplus <= $aheadby) {
365 printf "%18s %s\n", 'no-elim (nextup)', pr $aheadby;
372 (scalar keys %continuing) - (scalar @elim) < $placesremain;
374 # eliminate only one then, and try again
375 printf "elim-tie!\n";
376 @elim = historically_prefer -1, @elim;
379 foreach my $s (@elim) {
381 printf "%7s %10s %s\n", 'ELIM', $c, '----------';
382 my $votes = $s->{Votes};
383 votelogfull $_, "failed to stop $c elimination" foreach @$votes;
384 $elimvotebefore += $s->{Total};
385 delete $continuing{$c};
387 push @unsorted, @$votes;
391 $need_to_transfer_surplus = 0;
392 last if $elim_tie; # no more, then!
395 next unless $need_to_transfer_surplus;
397 @surpluses = nsort_by { $_->{Total} } @surpluses;
398 my @surplusxfer = equalpiles 'xfer?', @surpluses;
399 die unless @surplusxfer;
401 if (@surplusxfer > 1) {
402 @surplusxfer = historically_prefer +1, @surplusxfer;
405 my $s = $surplusxfer[0];
407 printf "%7s %10s\n", 'xfer', $c;
408 my $votes = $s->{Votes};
409 votelogfull $_, "surplus transferred" foreach @$votes;
410 @surpluses = grep { $_->{Cand} ne $c } @surpluses;
411 push @unsorted, @$votes;
414 open VL, ">.stv.votes" or die $!;
415 foreach my $vote (@allvotes) {
416 print VL "----------------------------------------\n";
417 print VL "voter $vote->{Voter}\n";
418 print VL "prefs ". (join " ", @{ $vote->{Prefs} }). "\n";
419 print VL $_, "\n" foreach @{ $vote->{Log} };
421 print VL "========================================\n";