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 if $numequal >= @choices;
114 $b = $choices[$numequal];
115 last if $compare->();
119 die 'random choice unimplemented' if $numequal > 1;
123 foreach my $c (keys %continuing) {
133 printf "----- stage %d -----\n", $stage;
135 print DEBUG "#################### $stage ####################\n",
137 [ \@stagerecord, \@elected, \@unsorted, \%sorted, \@surpluses, \%continuing ],
138 [qw( _@stagerecord _@elected _@unsorted _%sorted _@surpluses _%continuing )]
141 my $placesremain = $places - @elected;
143 unless ($placesremain > 0) {
144 printf "Complete: @elected\n";
148 while (my $vote = shift @unsorted) {
149 my ($firstpref) = voteliveprefs $vote;
150 if (!defined $firstpref) {
151 votelog $vote, "ballot exhausted";
152 push @exhausted, $vote;
154 push @{ $sorted{$firstpref}{Votes} }, $vote;
157 foreach my $firstpref (sort keys %sorted) {
158 foreach my $vote (@{ $sorted{$firstpref}{Votes} }) {
159 votelog $vote, "counted for $firstpref ".pr $vote->{Weight};
163 my $things_update = sub {
164 foreach my $s (@surpluses, values %sorted) {
165 $s->{Total} = sum0 map { $_->{Weight} } @{ $s->{Votes } };
167 @sorted = nsort_by { -$_->{Total} } values %sorted;
171 print DEBUG "SORTED\n", Dumper(\@sorted);
173 push @stagerecord, { map { ($_->{Cand}, $_->{Total}) } @sorted };
175 my $totalvalid = 0/1;
176 my $countvalid = sub {
178 foreach my $s (@$l) {
179 printf "%-7s %10s %s\n", $what, $s->{Cand}, pr $s->{Total};
180 $totalvalid += $s->{Total};
183 $countvalid->(\@sorted, '1stpref');
184 $countvalid->(\@surpluses, 'surplus');
186 printf "%7s %10s %s\n", 'TOTAL', '-----', pr $totalvalid;
188 unless ($totalvalid > 0) {
189 printf "No more votes!\n";
193 my $quota = $totalvalid / ($placesremain + 1);
194 printf "%7s %10s %s\n", 'quota', '', pr $quota;
196 my $need_to_transfer_surplus = 1;
200 # Look for people to elect.
201 # We elect as many as we can, rather than recomputing the (lower) quota
205 my $topvoters = $s->{Total};
206 my $surplus = $topvoters - $quota;
207 last unless $surplus >= 0;
209 my @elect = equalpiles 'elect?', @sorted;
211 if (@elect > $placesremain) {
213 @elect = historically_prefer +1, @elect;
214 printf "%7s %10s\n", 'tie!', $elect[0]{Cand};
217 foreach $s (@elect) {
218 printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
219 push @elected, $s->{Cand};
221 foreach my $vote (@{ $s->{Votes} }) {
222 votelog $vote, "elected $s->{Cand}";
225 $s->{Surplus} = $surplus;
226 push @newsurpluses, $s;
227 delete $sorted{ $s->{Cand} };
228 delete $continuing{ $s->{Cand} };
234 foreach my $s (@newsurpluses) {
235 # calculate the transfer value of each surplus
236 # we do this simultaneously, but based on the number of
237 # continuing candidates (excluding all the ones elected already)
240 my $votes = $s->{Votes};
241 my $surplus = $s->{Surplus};
245 grep { !!voteliveprefs $_ }
248 printf "%7s %10s %s\n", 'xfrable', $s->{Cand}, pr $transferrable;
249 if ($transferrable > $surplus) {
250 my $derate = $transferrable / $surplus;
251 printf "%7s %10s %s\n", 'derate', $s->{Cand}, pr $derate;
252 foreach my $vote (@{ $s->{Votes} }) {
253 votelog $vote, "part of surplus, derated ". pr $derate;
254 $vote->{Weight} /= $derate;
260 printf "%7s %10s %s\n", 'surplus', $s->{Cand}, pr $s->{Total};
262 $need_to_transfer_surplus = 0;
263 # before actually transferring a surplus, we will consider
264 # eliminating, and then reconsider with a lower quota
267 my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
268 printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
270 # Look for people to eliminate
271 # We eliminate before trying to transfer surpluses
273 my $elimvotebefore = 0/1;
277 if ($elimvotebefore) {
278 printf "%18s %s\n", 'elimination, sofar', pr $elimvotebefore;
279 } elsif (@surpluses) {
280 printf "%18s\n", 'elimination, maybe';
282 printf "%18s\n", 'elimination, starts';
285 my @elim = equalpiles 'elim?', reverse @sorted;
286 my $elimvotenow = sum0 map { $_->{Total} } @elim;
288 if (@surpluses || $elimvotebefore) {
290 if (@sorted == @elim) {
291 printf "%18s\n", 'no-elim (all-equal)';
294 my $nextup = $sorted[ $#sorted - @elim ];
295 printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
297 my $aheadby = $nextup->{Total} - ($elimvotenow + $elimvotebefore);
298 unless ($deferredsurplus <= $aheadby) {
300 printf "%18s %s\n", 'no-elim (nextup)', pr $aheadby;
307 (scalar keys %continuing) - (scalar @elim) < $placesremain;
309 # eliminate only one then, and try again
310 printf "elim-tie!\n";
311 @elim = historically_prefer -1, @elim;
314 foreach my $s (@elim) {
316 printf "%7s %10s %s\n", 'ELIM', $c, '----------';
317 my $votes = $s->{Votes};
318 votelogfull $_, "failed to stop $c elimination" foreach @$votes;
319 $elimvotebefore += $s->{Total};
320 delete $continuing{$c};
322 push @unsorted, @$votes;
326 $need_to_transfer_surplus = 0;
327 last if $elim_tie; # no more, then!
330 next unless $need_to_transfer_surplus;
332 @surpluses = nsort_by { $_->{Total} } @surpluses;
333 my @surplusxfer = equalpiles 'xfer?', @surpluses;
334 die unless @surplusxfer;
336 if (@surplusxfer > 1) {
337 @surplusxfer = historically_prefer +1, @surplusxfer;
340 my $s = $surplusxfer[0];
342 printf "%7s %10s\n", 'xfer', $c;
343 my $votes = $s->{Votes};
344 votelogfull $_, "surplus transferred" foreach @$votes;
345 @surpluses = grep { $_->{Cand} ne $c } @surpluses;
346 push @unsorted, @$votes;