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";
52 my ($cand, $why) = @_;
53 foreach my $vote (@allvotes) {
54 my $oldprefs = $vote->{Prefs};
55 my @prefs = grep { $_ ne $cand } $oldprefs;
56 next if @prefs == @$oldprefs;
57 votelog $vote, "crossed out candidate $cand: $why";
61 our @elected; # $elected[] = $candidate
63 our @unsorted = @allvotes;
66 # $sorted{$firstpref}{Votes} = [ $vote, ... ]
67 # $sorted{$firstpref}{Cand} = $firstpref
68 # $sorted{$firstpref}{Total} = $totalweight
69 our @surpluses; # values same as %sorted
71 our @exhausted; # votes
73 our %continuing; # $continuing{$candidate}=1
75 our @stagerecord; # $stagerecord[]{$candidate} = $total
77 foreach my $vote (@allvotes) {
78 $continuing{$_}=1 foreach @{ $vote->{Prefs} };
82 my ($how, @sorted) = @_;
83 return () unless @sorted;
85 my $eqtotal = $s->{Total};
87 while ($count < @sorted && $sorted[$count]{Total} == $eqtotal) {
88 printf "%7s %10s %s\n", $how, $sorted[$count]{Cand},
89 pr $sorted[$count]{Total};
92 return @sorted[ 0 .. $count-1 ];
95 sub historically_prefer ($@) {
96 my ($signum, @choices) = @_;
98 return $choices[0] if @choices < 2;
101 foreach my $sr (@stagerecord) {
102 my $d = $sr->{ $a->{Cand} } <=> $sr->{ $b->{Cand} };
103 return $d * $signum if $d;
108 @choices = sort $compare, @choices;
112 last unless $numequal >= @choices;
113 $b = $choices[$numequal];
114 last if $compare->();
117 die 'random choice unimplemented' if $numequal > 1;
124 printf "----- stage %d -----\n", $stage;
126 print DEBUG "#################### $stage ####################\n",
128 [ \@stagerecord, \@elected, \@unsorted, \%sorted, \@surpluses, \%continuing ],
129 [qw( _@stagerecord _@elected _@unsorted _%sorted _@surpluses _%continuing )]
132 while (my $vote = shift @unsorted) {
133 my ($firstpref) = grep { $continuing{$_} } @{ $vote->{Prefs} };
134 if (!defined $firstpref) {
135 votelog $vote, "ballot exhausted";
136 push @exhausted, $vote;
138 push @{ $sorted{$firstpref}{Votes} }, $vote;
141 $sorted{$_}{Cand} = $_ foreach keys %sorted;
142 foreach my $firstpref (sort keys %sorted) {
143 $sorted{$firstpref}{Total} = 0; # recount
144 foreach my $vote (@{ $sorted{$firstpref}{Votes} }) {
145 votelog $vote, "counted $vote->{Weight} for $firstpref";
146 $sorted{$firstpref}{Total} += $vote->{Weight};
150 my $sort_update = sub {
151 @sorted = nsort_by { -$_->{Total} } values %sorted;
155 print DEBUG "SORTED\n", Dumper(\@sorted);
157 push @stagerecord, { map { ($_->{Cand}, $_->{Total}) } @sorted };
160 my $countvalid = sub {
162 foreach my $s (@$l) {
163 printf "%-7s %10s %s\n", $what, $s->{Cand}, pr $s->{Total};
164 $totalvalid += $s->{Total};
167 $countvalid->(\@sorted, '1stpref');
168 $countvalid->(\@surpluses, 'surplus');
170 printf "%7s %10s %s\n", 'TOTAL', '-----', pr $totalvalid;
172 unless ($totalvalid > 0) {
173 printf "No more votes!\n";
177 my $placesremain = $places - @elected;
179 unless ($placesremain > 0) {
180 printf "Complete.\n";
184 my $quota = $totalvalid / ($placesremain + 1);
185 printf "%7s %10s %s\n", 'quota', '', pr $quota;
187 my $need_to_transfer_surplus = 1;
189 # Look for people to elect.
190 # We elect as many as we can, rather than recomputing the (lower) quota
194 my $topvoters = $s->{Total};
195 my $surplus = $topvoters - $quota;
196 last unless $surplus > 0;
198 printf "%7s %10s ***************\n", 'ELECTED', $s->{Cand};
199 push @elected, $s->{Cand};
201 my $derate = $topvoters / $surplus;
202 printf "%7s %10s %s\n", 'derate', $s->{Cand}, pr $derate;
204 foreach my $vote (@{ $s->{Votes} }) {
205 votelog $vote, "elected $s->{Cand}, derated $derate";
206 $vote->{Weight} /= $derate;
209 delete $sorted{ $s->{Cand} };
210 delete $continuing{ $s->{Cand} };
213 $need_to_transfer_surplus = 0;
214 # before actually transferring a surplus, we will consider
215 # eliminating, and then reconsider with a lower quota
218 my $deferredsurplus = sum0 map { $_->{Total} } @surpluses;
219 printf "%18s %s\n", 'deferred surplus', pr $deferredsurplus;
221 # Look for people to eliminate
222 # We eliminate before trying to transfer surpluses
227 printf "%18s\n", 'elimination round';
229 my @elim = equalpiles 'elim?', reverse @sorted;
230 my $elimvotetotal = sum0 map { $_->{Total} } @elim;
233 if (@sorted == @elim) {
234 printf "%18s\n", 'no-elim, un-defer, (all-equal)';
237 my $nextup = $sorted[ $#sorted - @elim ];
238 printf "%7s %10s %s\n", 'nextup', $nextup->{Cand},
240 my $aheadby = $nextup->{Total} - $elimvotetotal;
241 unless ($deferredsurplus <= $aheadby) {
243 printf "%18s %s\n", 'no-elim, un-defer', pr $aheadby;
248 if ((scalar keys %continuing) - (scalar @elim) < $placesremain) {
249 # eliminate only one then, and try again
250 printf "elim-tie!\n";
251 @elim = historically_prefer -1, @elim;
254 foreach my $s (@elim) {
256 printf "%7s %10s %s\n", 'ELIM', $c, '----------';
257 my $votes = $s->{Votes};
258 votelog $_, "failed to stop $c elimination" foreach @$votes;
259 delete $continuing{$c};
261 push @unsorted, @$votes;
265 $need_to_transfer_surplus = 0;
268 next unless $need_to_transfer_surplus;
270 @surpluses = nsort_by { $_->{Total} } @surpluses;
271 my @surplusxfer = equalpiles 'xfer?', @surpluses;
272 die unless @surplusxfer;
274 if (@surplusxfer > 1) {
275 @surplusxfer = historically_prefer +1, @surplusxfer;
278 my $s = $surplusxfer[0];
280 printf "%7s %10s\n", 'xfer', $c;
281 my $votes = $s->{Votes};
282 votelog $_, "surplus transferred" foreach @$votes;
283 @surpluses = grep { $_->{Cand} ne $c } @surpluses;
284 push @unsorted, @$votes;