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 $vote->{Weight} for $firstpref";
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 };
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 printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
209 push @elected, $s->{Cand};
211 foreach my $vote (@{ $s->{Votes} }) {
212 votelog $vote, "elected $s->{Cand}";
215 $s->{Surplus} = $surplus;
216 push @newsurpluses, $s;
217 delete $sorted{ $s->{Cand} };
218 delete $continuing{ $s->{Cand} };
223 foreach my $s (@newsurpluses) {
224 # calculate the transfer value of each surplus
225 # we do this simultaneously, but based on the number of
226 # continuing candidates (excluding all the ones elected already)
229 my $votes = $s->{Votes};
230 my $surplus = $s->{Surplus};
234 grep { !!voteliveprefs $_ }
237 printf "%7s %10s %s\n", 'xfrable', $s->{Cand}, pr $transferrable;
238 if ($transferrable > $surplus) {
239 my $derate = $transferrable / $surplus;
240 printf "%7s %10s %s\n", 'derate', $s->{Cand}, pr $derate;
241 foreach my $vote (@{ $s->{Votes} }) {
242 votelog $vote, "part of surplus, derated ". pr $derate;
243 $vote->{Weight} /= $derate;
249 printf "%7s %10s %s\n", 'surplus', $s->{Cand}, pr $s->{Total};
251 $need_to_transfer_surplus = 0;
252 # before actually transferring a surplus, we will consider
253 # eliminating, and then reconsider with a lower quota
256 my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
257 printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
259 # Look for people to eliminate
260 # We eliminate before trying to transfer surpluses
262 my $elimvotebefore = 0;
266 if ($elimvotebefore) {
267 printf "%18s %s\n", 'elimination, sofar', pr $elimvotebefore;
268 } elsif (@surpluses) {
269 printf "%18s\n", 'elimination, maybe';
271 printf "%18s\n", 'elimination, starts';
274 my @elim = equalpiles 'elim?', reverse @sorted;
275 my $elimvotenow = sum0 map { $_->{Total} } @elim;
277 if (@surpluses || $elimvotebefore) {
279 if (@sorted == @elim) {
280 printf "%18s\n", 'no-elim (all-equal)';
283 my $nextup = $sorted[ $#sorted - @elim ];
284 printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
286 my $aheadby = $nextup->{Total} - ($elimvotenow + $elimvotebefore);
287 unless ($deferredsurplus <= $aheadby) {
289 printf "%18s %s\n", 'no-elim (nextup)', pr $aheadby;
296 (scalar keys %continuing) - (scalar @elim) < $placesremain;
298 # eliminate only one then, and try again
299 printf "elim-tie!\n";
300 @elim = historically_prefer -1, @elim;
303 foreach my $s (@elim) {
305 printf "%7s %10s %s\n", 'ELIM', $c, '----------';
306 my $votes = $s->{Votes};
307 votelogfull $_, "failed to stop $c elimination" foreach @$votes;
308 $elimvotebefore += $s->{Total};
309 delete $continuing{$c};
311 push @unsorted, @$votes;
315 $need_to_transfer_surplus = 0;
316 last if $elim_tie; # no more, then!
319 next unless $need_to_transfer_surplus;
321 @surpluses = nsort_by { $_->{Total} } @surpluses;
322 my @surplusxfer = equalpiles 'xfer?', @surpluses;
323 die unless @surplusxfer;
325 if (@surplusxfer > 1) {
326 @surplusxfer = historically_prefer +1, @surplusxfer;
329 my $s = $surplusxfer[0];
331 printf "%7s %10s\n", 'xfer', $c;
332 my $votes = $s->{Votes};
333 votelogfull $_, "surplus transferred" foreach @$votes;
334 @surpluses = grep { $_->{Cand} ne $c } @surpluses;
335 push @unsorted, @$votes;