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 () {
212 foreach my $c (values %cands) {
213 next if $c->{NonCont};
215 $c->{Total} += $_->{Weight} foreach @{ $c->{Votes} };
216 print DEBUG "counted $c->{Cand} $c->{Total}\n";
217 $c->{History}[$stage-1] = $c->{Total};
220 foreach my $c (reverse sort $display_cmp
221 grep { !$_->{NonCont} } values %cands) {
222 prf "candidate %-10s: %s votes\n", $c->{Cand}, sv $c->{Total};
226 sub computequota () {
227 my $totalvalid = 0/1;
228 $totalvalid += $_->{Total} foreach values %cands;
229 $quota = floor($totalvalid / (1 + $seats) + 1);
230 prf "total valid %s\n", sv $totalvalid;
231 prf "quota %s\n", sv $quota;
234 sub total_history_cmp () {
235 my $ha = $a->{History};
236 my $hb = $b->{History};
237 my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
238 print DEBUG "$m...\n";
239 foreach my $s (reverse 0 .. $stage-1) {
240 my $d = $ha->[$s] <=> $hb->[$s];
242 print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
245 print DEBUG "$m => 0\n";
250 grep { !$_->{NonCont} } values %cands;
253 sub select_best_worst ($$$$) {
254 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
255 # $wantcand->($c) = boolish
256 # $wanttiebreak->($total) = boolish
257 # Firstly candidates not meeting $wantcand are ignored
258 # Then we pick the best (worst) candiate by Total (or vote history).
259 # (SLGEO 49(2) and 51(2).
260 # If this does not help then totals are equal and we call wanttiebreak.
261 # If it returns 0 we return alphabetically first CAND. Otherwise
264 my @maybe = grep { $wantcand->($_) } continuing();
265 @maybe = sort total_history_cmp @maybe;
266 @maybe = reverse @maybe if $signum > 0;
268 return undef unless @maybe;
273 my $nextc = $maybe[$nequal];
276 # Only interested in those who compare equal according to the
277 # history (SLGEO 49(2)); NB our history includes the current
280 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
284 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
285 # ... if equal for election we can do them one by one, since
286 # order does not matter (SLGEO 49 talks about `two or more
293 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
294 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
295 $selectcand = $tie{"@all"}{$tiekey};
296 die "need tie break, want $tiekey from @all"
297 unless defined $selectcand;
298 prf "$what %s due to tie break amongst %s\n",
301 $selectcand = $maybe[0]{Cand};
302 prf "$what %s\n", $selectcand;
305 return $cands{$selectcand};
310 prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
311 $c->{NonCont} = 'Elected';
319 printf "stage %3d:\n", $stage;
321 sortballots @allvotes if $stage == 1;
323 my $seats_remain = $seats - @elected;
325 prf "seats remaining %d\n", $seats_remain;
327 last unless $seats_remain;
329 if (continuing() <= $seats_remain) {
330 foreach my $c (continuing()) {
331 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
334 countballots() if $for_compare;
340 computequota if $stage == 1;
342 my $c = select_best_worst
343 sub { $_->{Total} >= $quota },
349 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
352 my $surplus = $c->{Total} - $quota;
354 if ($surplus <= 0/1) {
359 last if $seats_remain == 1; # don't bother doing more transfers
364 prf "surplus %s\n", sv $surplus;
366 foreach my $v (@{ $c->{Votes} }) {
367 my $previously = $v->{TransferredSurplus};
368 push @$previously, $c->{Cand};
370 my $A = $surplus * $v->{Weight};
371 my $xfervalue = floor(($A * $F) / $B) / $F;
372 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
373 # but always rounding down
374 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
375 $v->{Weight} = $xfervalue;
377 if (defined $tspr{"@$previously"}) {
378 die unless $tspr{"@$previously"} == $xfervalue;
380 $tspr{"@$previously"} = $xfervalue;
381 prf "transfer value of ballots %20s: %s\n",
382 "@$previously", sv $xfervalue;
385 sortballots @{ $c->{Votes} };
387 $c->{Votes} = { }; # will crash if we access it again
391 # No-one to elect, must eliminate
392 $c = select_best_worst
398 prf "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
399 $c->{NonCont} = 'Eliminated';
401 sortballots @{ $c->{Votes} };
411 foreach my $c (sort { $a->{Cand} cmp $b->{Cand} } @elected) {
412 printf " %s\n", $c->{Cand};
415 foreach my $i (0..$#elected) {
416 my $c = $elected[$i];
417 printf " %3d. %-10s %s\n", $i+1, $c->{Cand}, $c->{Desc};