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 sub countballots () {
214 foreach my $c (values %cands) {
215 next if $c->{NonCont};
217 $c->{Total} += $_->{Weight} foreach @{ $c->{Votes} };
218 print DEBUG "counted $c->{Cand} $c->{Total}\n";
219 $c->{History}[$stage-1] = $c->{Total};
224 # for comparison with OpenSTV, which always prints
225 # the quota for every elected candidate
226 push @pr, { %$_, Total => $quota } foreach @elected;
229 foreach my $c (reverse sort $display_cmp @pr) {
230 prf "candidate %-10s: %s votes\n", $c->{Cand}, sv $c->{Total};
234 sub computequota () {
235 my $totalvalid = 0/1;
236 $totalvalid += $_->{Total} foreach values %cands;
237 $quota = floor($totalvalid / (1 + $seats) + 1);
238 prf "total valid %s\n", sv $totalvalid;
239 prf "quota %s\n", sv $quota;
242 sub total_history_cmp () {
243 my $ha = $a->{History};
244 my $hb = $b->{History};
245 my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
246 print DEBUG "$m...\n";
247 foreach my $s (reverse 0 .. $stage-1) {
248 my $d = $ha->[$s] <=> $hb->[$s];
250 print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
253 print DEBUG "$m => 0\n";
258 grep { !$_->{NonCont} } values %cands;
261 sub select_best_worst ($$$$) {
262 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
263 # $wantcand->($c) = boolish
264 # $wanttiebreak->($total) = boolish
265 # Firstly candidates not meeting $wantcand are ignored
266 # Then we pick the best (worst) candiate by Total (or vote history).
267 # (SLGEO 49(2) and 51(2).
268 # If this does not help then totals are equal and we call wanttiebreak.
269 # If it returns 0 we return alphabetically first CAND. Otherwise
272 my @maybe = grep { $wantcand->($_) } continuing();
273 @maybe = sort total_history_cmp @maybe;
274 @maybe = reverse @maybe if $signum > 0;
276 return undef unless @maybe;
281 my $nextc = $maybe[$nequal];
284 # Only interested in those who compare equal according to the
285 # history (SLGEO 49(2)); NB our history includes the current
288 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
292 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
293 # ... if equal for election we can do them one by one, since
294 # order does not matter (SLGEO 49 talks about `two or more
301 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
302 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
303 $selectcand = $tie{"@all"}{$tiekey};
304 die "need tie break, want $tiekey from @all"
305 unless defined $selectcand;
306 prf "$what %s due to tie break amongst %s\n",
309 $selectcand = $maybe[0]{Cand};
310 prf "$what %s\n", $selectcand;
313 return $cands{$selectcand};
318 prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
319 $c->{NonCont} = 'Elected';
327 printf "stage %3d:\n", $stage;
329 sortballots @allvotes if $stage == 1;
331 my $seats_remain = $seats - @elected;
333 prf "seats remaining %d\n", $seats_remain;
335 last unless $seats_remain;
337 if (continuing() <= $seats_remain) {
338 foreach my $c (continuing()) {
339 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
342 countballots() if $for_compare;
348 computequota if $stage == 1;
350 my $c = select_best_worst
351 sub { $_->{Total} >= $quota },
357 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
360 my $surplus = $c->{Total} - $quota;
362 if ($surplus <= 0/1) {
367 last if $seats_remain == 1; # don't bother doing more transfers
372 prf "surplus %s\n", sv $surplus;
374 foreach my $v (@{ $c->{Votes} }) {
375 my $previously = $v->{TransferredSurplus};
376 push @$previously, $c->{Cand};
378 my $A = $surplus * $v->{Weight};
379 my $xfervalue = floor(($A * $F) / $B) / $F;
380 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
381 # but always rounding down
382 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
383 $v->{Weight} = $xfervalue;
385 if (defined $tspr{"@$previously"}) {
386 die unless $tspr{"@$previously"} == $xfervalue;
388 $tspr{"@$previously"} = $xfervalue;
389 prf "transfer value of ballots %20s: %s\n",
390 "@$previously", sv $xfervalue;
393 sortballots @{ $c->{Votes} };
395 $c->{Votes} = { }; # will crash if we access it again
399 # No-one to elect, must eliminate
400 $c = select_best_worst
406 prf "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
407 $c->{NonCont} = 'Eliminated';
409 sortballots @{ $c->{Votes} };
419 foreach my $c (sort { $a->{Cand} cmp $b->{Cand} } @elected) {
420 printf " %s\n", $c->{Cand};
423 foreach my $i (0..$#elected) {
424 my $c = $elected[$i];
425 printf " %3d. %-10s %s\n", $i+1, $c->{Cand}, $c->{Desc};