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) = @_;
99 return $choices[0] if @choices < 2;
102 foreach my $sr (@stagerecord) {
103 my $d = $sr->{ $a->{Cand} } <=> $sr->{ $b->{Cand} };
104 return $d * $signum if $d;
109 @choices = sort $compare, @choices;
113 last unless $numequal >= @choices;
114 $b = $choices[$numequal];
115 last if $compare->();
118 die 'random choice unimplemented' if $numequal > 1;
122 foreach my $c (keys %continuing) {
132 printf "----- stage %d -----\n", $stage;
134 print DEBUG "#################### $stage ####################\n",
136 [ \@stagerecord, \@elected, \@unsorted, \%sorted, \@surpluses, \%continuing ],
137 [qw( _@stagerecord _@elected _@unsorted _%sorted _@surpluses _%continuing )]
140 my $placesremain = $places - @elected;
142 unless ($placesremain > 0) {
143 printf "Complete: @elected\n";
147 while (my $vote = shift @unsorted) {
148 my ($firstpref) = voteliveprefs $vote;
149 if (!defined $firstpref) {
150 votelog $vote, "ballot exhausted";
151 push @exhausted, $vote;
153 push @{ $sorted{$firstpref}{Votes} }, $vote;
156 foreach my $firstpref (sort keys %sorted) {
157 foreach my $vote (@{ $sorted{$firstpref}{Votes} }) {
158 votelog $vote, "counted for $firstpref ".pr $vote->{Weight};
162 my $things_update = sub {
163 foreach my $s (@surpluses, values %sorted) {
164 $s->{Total} = sum0 map { $_->{Weight} } @{ $s->{Votes } };
166 @sorted = nsort_by { -$_->{Total} } values %sorted;
170 print DEBUG "SORTED\n", Dumper(\@sorted);
172 push @stagerecord, { map { ($_->{Cand}, $_->{Total}) } @sorted };
174 my $totalvalid = 0/1;
175 my $countvalid = sub {
177 foreach my $s (@$l) {
178 printf "%-7s %10s %s\n", $what, $s->{Cand}, pr $s->{Total};
179 $totalvalid += $s->{Total};
182 $countvalid->(\@sorted, '1stpref');
183 $countvalid->(\@surpluses, 'surplus');
185 printf "%7s %10s %s\n", 'TOTAL', '-----', pr $totalvalid;
187 unless ($totalvalid > 0) {
188 printf "No more votes!\n";
192 my $quota = $totalvalid / ($placesremain + 1);
193 printf "%7s %10s %s\n", 'quota', '', pr $quota;
195 my $need_to_transfer_surplus = 1;
199 # Look for people to elect.
200 # We elect as many as we can, rather than recomputing the (lower) quota
204 my $topvoters = $s->{Total};
205 my $surplus = $topvoters - $quota;
206 last unless $surplus >= 0;
208 my @elect = equalpiles 'elect?', @sorted;
210 if (@elect > $placesremain) {
212 @elect = historically_prefer +1, @elect;
213 printf "%7s %10s\n", 'tie!', $elect[0]{Cand};
216 foreach $s (@elect) {
217 printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
218 push @elected, $s->{Cand};
220 foreach my $vote (@{ $s->{Votes} }) {
221 votelog $vote, "elected $s->{Cand}";
224 $s->{Surplus} = $surplus;
225 push @newsurpluses, $s;
226 delete $sorted{ $s->{Cand} };
227 delete $continuing{ $s->{Cand} };
233 foreach my $s (@newsurpluses) {
234 # calculate the transfer value of each surplus
235 # we do this simultaneously, but based on the number of
236 # continuing candidates (excluding all the ones elected already)
239 my $votes = $s->{Votes};
240 my $surplus = $s->{Surplus};
244 grep { !!voteliveprefs $_ }
247 printf "%7s %10s %s\n", 'xfrable', $s->{Cand}, pr $transferrable;
248 if ($transferrable > $surplus) {
249 my $derate = $transferrable / $surplus;
250 printf "%7s %10s %s\n", 'derate', $s->{Cand}, pr $derate;
251 foreach my $vote (@{ $s->{Votes} }) {
252 votelog $vote, "part of surplus, derated ". pr $derate;
253 $vote->{Weight} /= $derate;
259 printf "%7s %10s %s\n", 'surplus', $s->{Cand}, pr $s->{Total};
261 $need_to_transfer_surplus = 0;
262 # before actually transferring a surplus, we will consider
263 # eliminating, and then reconsider with a lower quota
266 my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
267 printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
269 # Look for people to eliminate
270 # We eliminate before trying to transfer surpluses
272 my $elimvotebefore = 0/1;
276 if ($elimvotebefore) {
277 printf "%18s %s\n", 'elimination, sofar', pr $elimvotebefore;
278 } elsif (@surpluses) {
279 printf "%18s\n", 'elimination, maybe';
281 printf "%18s\n", 'elimination, starts';
284 my @elim = equalpiles 'elim?', reverse @sorted;
285 my $elimvotenow = sum0 map { $_->{Total} } @elim;
287 if (@surpluses || $elimvotebefore) {
289 if (@sorted == @elim) {
290 printf "%18s\n", 'no-elim (all-equal)';
293 my $nextup = $sorted[ $#sorted - @elim ];
294 printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
296 my $aheadby = $nextup->{Total} - ($elimvotenow + $elimvotebefore);
297 unless ($deferredsurplus <= $aheadby) {
299 printf "%18s %s\n", 'no-elim (nextup)', pr $aheadby;
306 (scalar keys %continuing) - (scalar @elim) < $placesremain;
308 # eliminate only one then, and try again
309 printf "elim-tie!\n";
310 @elim = historically_prefer -1, @elim;
313 foreach my $s (@elim) {
315 printf "%7s %10s %s\n", 'ELIM', $c, '----------';
316 my $votes = $s->{Votes};
317 votelogfull $_, "failed to stop $c elimination" foreach @$votes;
318 $elimvotebefore += $s->{Total};
319 delete $continuing{$c};
321 push @unsorted, @$votes;
325 $need_to_transfer_surplus = 0;
326 last if $elim_tie; # no more, then!
329 next unless $need_to_transfer_surplus;
331 @surpluses = nsort_by { $_->{Total} } @surpluses;
332 my @surplusxfer = equalpiles 'xfer?', @surpluses;
333 die unless @surplusxfer;
335 if (@surplusxfer > 1) {
336 @surplusxfer = historically_prefer +1, @surplusxfer;
339 my $s = $surplusxfer[0];
341 printf "%7s %10s\n", 'xfer', $c;
342 my $votes = $s->{Votes};
343 votelogfull $_, "surplus transferred" foreach @$votes;
344 @surpluses = grep { $_->{Cand} ne $c } @surpluses;
345 push @unsorted, @$votes;