4 # The Scottish Local Government Elections Order 2007
16 # Prefs => [ [ CAND, ...], ... ],
18 # We edit Prefs as we go
24 # $cands{CAND}{NonCont} # undef, or Elected or Eliminated
29 our @non_transferable;
37 our $F = (new Math::BigRat 10)->bpow($DIGS);
39 open DEBUG, ">.compute.log" or die $!;
43 print DEBUG Dumper(\%tie,
50 $SIG{__WARN__} = sub {
51 $SIG{__DIE__} = undef;
61 sub total_history_cmp ();
65 if ($opt =~ m/^[A-Z]/) {
66 die "unknown option $_ for $what";
67 } elsif ($opt =~ m/^[a-z]/) {
68 print STDERR "warning (line $.): unknown option $_ for $what\n";
72 my $display_cmp = \&total_history_cmp;
75 while (@ARGV && $ARGV[0] =~ m/^\-/) {
79 } elsif (m/^--sort=alpha$/) {
80 $display_cmp = sub { $b->{Cand} cmp $a->{Cand} };
81 } elsif (m/^--for-compare$/) {
83 unshift @ARGV, '--sort=alpha';
92 foreach $_ (split / /, $') {
93 if (m/^_?[Ss]eats=(\d+)/) {
95 } elsif (m/^_?[Tt]ie=(.*)\>(.*)$/) {
96 my @more = split /\,/, $1;
97 my @less = split /\,/, $2;
98 my @all = join ',', sort (@more, @less);
99 $tie{"@all"}{Win} = $more[0] if @more == 1;
100 $tie{"@all"}{Lose} = $less[0] if @less == 1;
102 unkopt "election", $_;
105 } elsif (m/^(\w+) = (\S*) \|/) {
106 my ($cand,$desc) = ($1,$2);
107 unkopt "candidate $cand", $_ foreach split / /, $';
108 $cands{$cand}{Desc} = $desc;
109 } elsif (m/^(\w*) :\s*(.*)\s*\|(.*)/) {
110 my ($voter,$prefs,$opts) = ($1,$2,$3);
111 my $v = { Voter => $voter, Prefs => [ ] };
112 push @{ $v->{Prefs} }, [ $_ =~ m/\w+/g ]
113 foreach split /\s+/, $prefs;
114 foreach $_ (split / /, $opts) {
115 if (m/^_?[Ww]eight=(\d+)\/(\d+)$/) {
116 $v->{Weight} = $1 / $2;
117 } elsif (m/^_?[Ww]eight=([0-9.]+)$/) {
118 $v->{Weight} = new Math::BigRat $1;
120 unkopt "voter $v->{Voter}", $_;
131 $cands{$_}{Cand} = $_ foreach keys %cands;
132 $_->{Weight} //= 1/1 foreach @allvotes;
133 $_->{TransferredSurplus} //= [ ] foreach @allvotes;
134 $_->{OrigPrefs} //= [ @{ $_->{Prefs} } ] foreach @allvotes;
138 push @{ $vote->{Log} }, "stage $stage: $m";
142 sub sortballots (@) {
143 # Takes each argument, which should be a ballot, sorts
144 # it into $cand{CAND}{Votes} according to first preference.
145 # Strips that first preference from the ballot.
146 # If the first preference has been eliminated, strips it
147 # and looks for further preferences.
148 print DEBUG "sortballots ".(scalar @_)."...\n";
150 my $firstprefs = shift @{ $v->{Prefs} };
151 my $w = $v->{Weight};
152 if (!$firstprefs || !@$firstprefs) {
153 votelog $v, "no more preferences, non transferable";
154 push @non_transferable, $v;
157 if (@$firstprefs > 1) {
158 votelog $v, "splitting due to several equal first preferences";
159 foreach my $fpref (@$firstprefs) {
162 Weight => $w / @$firstprefs,
163 Prefs => [ [ $fpref ], @{ $v->{Prefs} } ],
165 votelog $v, "split for $fpref";
169 my $fp = $firstprefs->[0];
171 my $noncont = $c->{NonCont};
173 votelog $v, "dropping pref $fp, $noncont";
177 votelog $v, "sorted into pile for candidate $fp weight $w";
178 push @{ $c->{Votes} }, $v;
184 $v = new Math::BigRat $v; # we need a copy
190 my $v = new Math::BigRat $in; # just in case
191 my $intpart = floor($v);
192 my $frac = $v - $intpart;
193 my $good = floor($frac * $F);
194 my $bad = $frac * $F - $good;
195 my $s = sprintf "%7d", $intpart;
197 $s .= sprintf ".%0${DIGS}d", $good;
198 $s .= sprintf "%-4s", ($bad ? "+$bad" : "");
200 $s .= sprintf " %${DIGS}s%4s", '', '';
202 #print STDERR "# $in => $s # (intpart=$intpart frac=$frac)\n";
211 prf @_ unless $for_compare;
214 sub countballots () {
217 foreach my $c (values %cands) {
218 next if $c->{NonCont};
220 $c->{Total} += $_->{Weight} foreach @{ $c->{Votes} };
221 print DEBUG "counted $c->{Cand} $c->{Total}\n";
222 $c->{History}[$stage-1] = $c->{Total};
227 # for comparison with OpenSTV, which always prints
228 # the quota for every elected candidate
229 push @pr, { %$_, Total => $quota } foreach @elected;
232 foreach my $c (reverse sort $display_cmp @pr) {
233 prf "candidate %-10s: %s votes\n", $c->{Cand}, sv $c->{Total};
237 sub computequota () {
238 my $totalvalid = 0/1;
239 $totalvalid += $_->{Total} foreach values %cands;
240 $quota = floor($totalvalid / (1 + $seats) + 1);
241 prfm "total valid %s\n", sv $totalvalid;
242 prf "quota %s\n", sv $quota;
245 sub total_history_cmp () {
246 my $ha = $a->{History};
247 my $hb = $b->{History};
248 my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
249 print DEBUG "$m...\n";
250 foreach my $s (reverse 0 .. $stage-1) {
251 my $d = $ha->[$s] <=> $hb->[$s];
253 print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
256 print DEBUG "$m => 0\n";
261 grep { !$_->{NonCont} } values %cands;
264 sub select_best_worst ($$$$) {
265 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
266 # $wantcand->($c) = boolish
267 # $wanttiebreak->($total) = boolish
268 # Firstly candidates not meeting $wantcand are ignored
269 # Then we pick the best (worst) candiate by Total (or vote history).
270 # (SLGEO 49(2) and 51(2).
271 # If this does not help then totals are equal and we call wanttiebreak.
272 # If it returns 0 we return alphabetically first CAND. Otherwise
275 my @maybe = grep { $wantcand->($_) } continuing();
276 @maybe = sort total_history_cmp @maybe;
277 @maybe = reverse @maybe if $signum > 0;
279 return undef unless @maybe;
284 my $nextc = $maybe[$nequal];
287 # Only interested in those who compare equal according to the
288 # history (SLGEO 49(2)); NB our history includes the current
291 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
295 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
296 # ... if equal for election we can do them one by one, since
297 # order does not matter (SLGEO 49 talks about `two or more
304 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
305 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
306 $selectcand = $tie{"@all"}{$tiekey};
307 die "need tie break, want $tiekey from @all"
308 unless defined $selectcand;
309 prf "$what %s due to tie break amongst %s\n",
312 $selectcand = $maybe[0]{Cand};
313 prfm "$what %s\n", $selectcand;
316 return $cands{$selectcand};
321 prfm "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
322 $c->{NonCont} = 'Elected';
330 printf "stage %3d:\n", $stage;
332 sortballots @allvotes if $stage == 1;
334 my $seats_remain = $seats - @elected;
336 prfm "seats remaining %d\n", $seats_remain;
338 last unless $seats_remain;
340 if (continuing() <= $seats_remain) {
341 foreach my $c (continuing()) {
342 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
345 countballots() if $for_compare;
351 computequota if $stage == 1;
353 my $c = select_best_worst
354 sub { $_->{Total} >= $quota },
360 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
363 my $surplus = $c->{Total} - $quota;
365 if ($surplus <= 0/1) {
370 last if $seats_remain == 1; # don't bother doing more transfers
375 prf "surplus %s\n", sv $surplus;
377 foreach my $v (@{ $c->{Votes} }) {
378 my $previously = $v->{TransferredSurplus};
379 push @$previously, $c->{Cand};
381 my $A = $surplus * $v->{Weight};
382 my $xfervalue = floor(($A * $F) / $B) / $F;
383 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
384 # but always rounding down
385 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
386 $v->{Weight} = $xfervalue;
388 if (defined $tspr{"@$previously"}) {
389 die unless $tspr{"@$previously"} == $xfervalue;
391 $tspr{"@$previously"} = $xfervalue;
392 prfm "transfer value of ballots %20s: %s\n",
393 "@$previously", sv $xfervalue;
396 sortballots @{ $c->{Votes} };
398 $c->{Votes} = { }; # will crash if we access it again
402 # No-one to elect, must eliminate
403 $c = select_best_worst
409 prfm "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
410 $c->{NonCont} = 'Eliminated';
412 sortballots @{ $c->{Votes} };
422 foreach my $c (sort { $a->{Cand} cmp $b->{Cand} } @elected) {
423 printf " %s\n", $c->{Cand};
426 foreach my $i (0..$#elected) {
427 my $c = $elected[$i];
428 printf " %3d. %-10s %s\n", $i+1, $c->{Cand}, $c->{Desc};