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;
74 while (@ARGV && $ARGV[0] =~ m/^\-/) {
78 } elsif (m/^--sort=alpha$/) {
79 $display_cmp = sub { $b->{Cand} cmp $a->{Cand} };
88 foreach $_ (split / /, $') {
89 if (m/^_?[Ss]eats=(\d+)/) {
91 } elsif (m/^_?[Tt]ie=(.*)\>(.*)$/) {
92 my @more = split /\,/, $1;
93 my @less = split /\,/, $2;
94 my @all = join ',', sort (@more, @less);
95 $tie{"@all"}{Win} = $more[0] if @more == 1;
96 $tie{"@all"}{Lose} = $less[0] if @less == 1;
98 unkopt "election", $_;
101 } elsif (m/^(\w+) = (\S*) \|/) {
102 my ($cand,$desc) = ($1,$2);
103 unkopt "candidate $cand", $_ foreach split / /, $';
104 $cands{$cand}{Desc} = $desc;
105 } elsif (m/^(\w*) :\s*(.*)\s*\|(.*)/) {
106 my ($voter,$prefs,$opts) = ($1,$2,$3);
107 my $v = { Voter => $voter, Prefs => [ ] };
108 push @{ $v->{Prefs} }, [ $_ =~ m/\w+/g ]
109 foreach split /\s+/, $prefs;
110 foreach $_ (split / /, $opts) {
111 if (m/^_?[Ww]eight=(\d+)\/(\d+)$/) {
112 $v->{Weight} = $1 / $2;
113 } elsif (m/^_?[Ww]eight=([0-9.]+)$/) {
114 $v->{Weight} = new Math::BigRat $1;
116 unkopt "voter $v->{Voter}", $_;
127 $cands{$_}{Cand} = $_ foreach keys %cands;
128 $_->{Weight} //= 1/1 foreach @allvotes;
129 $_->{TransferredSurplus} //= [ ] foreach @allvotes;
130 $_->{OrigPrefs} //= [ @{ $_->{Prefs} } ] foreach @allvotes;
134 push @{ $vote->{Log} }, "stage $stage: $m";
138 sub sortballots (@) {
139 # Takes each argument, which should be a ballot, sorts
140 # it into $cand{CAND}{Votes} according to first preference.
141 # Strips that first preference from the ballot.
142 # If the first preference has been eliminated, strips it
143 # and looks for further preferences.
144 print DEBUG "sortballots ".(scalar @_)."...\n";
146 my $firstprefs = shift @{ $v->{Prefs} };
147 my $w = $v->{Weight};
148 if (!$firstprefs || !@$firstprefs) {
149 votelog $v, "no more preferences, non transferable";
150 push @non_transferable, $v;
153 if (@$firstprefs > 1) {
154 votelog $v, "splitting due to several equal first preferences";
155 foreach my $fpref (@$firstprefs) {
158 Weight => $w / @$firstprefs,
159 Prefs => [ [ $fpref ], @{ $v->{Prefs} } ],
161 votelog $v, "split for $fpref";
165 my $fp = $firstprefs->[0];
167 my $noncont = $c->{NonCont};
169 votelog $v, "dropping pref $fp, $noncont";
173 votelog $v, "sorted into pile for candidate $fp weight $w";
174 push @{ $c->{Votes} }, $v;
180 $v = new Math::BigRat $v; # we need a copy
186 my $v = new Math::BigRat $in; # just in case
187 my $intpart = floor($v);
188 my $frac = $v - $intpart;
189 my $good = floor($frac * $F);
190 my $bad = $frac * $F - $good;
191 my $s = sprintf "%7d", $intpart;
193 $s .= sprintf ".%0${DIGS}d", $good;
194 $s .= sprintf "%-4s", ($bad ? "+$bad" : "");
196 $s .= sprintf " %${DIGS}s%4s", '', '';
198 #print STDERR "# $in => $s # (intpart=$intpart frac=$frac)\n";
207 sub countballots () {
208 foreach my $c (values %cands) {
209 next if $c->{NonCont};
211 $c->{Total} += $_->{Weight} foreach @{ $c->{Votes} };
212 print DEBUG "counted $c->{Cand} $c->{Total}\n";
213 $c->{History}[$stage-1] = $c->{Total};
216 foreach my $c (reverse sort $display_cmp
217 grep { !$_->{NonCont} } values %cands) {
218 prf "candidate %-10s: %s votes\n", $c->{Cand}, sv $c->{Total};
222 sub computequota () {
223 my $totalvalid = 0/1;
224 $totalvalid += $_->{Total} foreach values %cands;
225 $quota = floor($totalvalid / (1 + $seats) + 1);
226 prf "total valid %s\n", sv $totalvalid;
227 prf "quota %s\n", sv $quota;
230 sub total_history_cmp () {
231 my $ha = $a->{History};
232 my $hb = $b->{History};
233 my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
234 print DEBUG "$m...\n";
235 foreach my $s (reverse 0 .. $stage-1) {
236 my $d = $ha->[$s] <=> $hb->[$s];
238 print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
241 print DEBUG "$m => 0\n";
246 grep { !$_->{NonCont} } values %cands;
249 sub select_best_worst ($$$$) {
250 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
251 # $wantcand->($c) = boolish
252 # $wanttiebreak->($total) = boolish
253 # Firstly candidates not meeting $wantcand are ignored
254 # Then we pick the best (worst) candiate by Total (or vote history).
255 # (SLGEO 49(2) and 51(2).
256 # If this does not help then totals are equal and we call wanttiebreak.
257 # If it returns 0 we return alphabetically first CAND. Otherwise
260 my @maybe = grep { $wantcand->($_) } continuing();
261 @maybe = sort total_history_cmp @maybe;
262 @maybe = reverse @maybe if $signum > 0;
264 return undef unless @maybe;
269 my $nextc = $maybe[$nequal];
272 # Only interested in those who compare equal according to the
273 # history (SLGEO 49(2)); NB our history includes the current
276 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
280 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
281 # ... if equal for election we can do them one by one, since
282 # order does not matter (SLGEO 49 talks about `two or more
289 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
290 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
291 $selectcand = $tie{"@all"}{$tiekey};
292 die "need tie break, want $tiekey from @all"
293 unless defined $selectcand;
294 prf "$what %s due to tie break amongst %s\n",
297 $selectcand = $maybe[0]{Cand};
298 prf "$what %s\n", $selectcand;
301 return $cands{$selectcand};
306 prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
307 $c->{NonCont} = 'Elected';
315 printf "stage %3d:\n", $stage;
317 sortballots @allvotes if $stage == 1;
319 my $seats_remain = $seats - @elected;
321 prf "seats remaining %d\n", $seats_remain;
323 last unless $seats_remain;
325 if (continuing() <= $seats_remain) {
326 foreach my $c (continuing()) {
327 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
335 computequota if $stage == 1;
337 my $c = select_best_worst
338 sub { $_->{Total} >= $quota },
344 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
347 my $surplus = $c->{Total} - $quota;
349 if ($surplus <= 0/1) {
354 last if $seats_remain == 1; # don't bother doing more transfers
359 prf "surplus %s\n", sv $surplus;
361 foreach my $v (@{ $c->{Votes} }) {
362 my $previously = $v->{TransferredSurplus};
363 push @$previously, $c->{Cand};
365 my $A = $surplus * $v->{Weight};
366 my $xfervalue = floor(($A * $F) / $B) / $F;
367 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
368 # but always rounding down
369 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
370 $v->{Weight} = $xfervalue;
372 if (defined $tspr{"@$previously"}) {
373 die unless $tspr{"@$previously"} == $xfervalue;
375 $tspr{"@$previously"} = $xfervalue;
376 prf "transfer value of ballots %20s: %s\n",
377 "@$previously", sv $xfervalue;
380 sortballots @{ $c->{Votes} };
382 $c->{Votes} = { }; # will crash if we access it again
386 # No-one to elect, must eliminate
387 $c = select_best_worst
393 prf "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
394 $c->{NonCont} = 'Eliminated';
396 sortballots @{ $c->{Votes} };
405 foreach my $i (0..$#elected) {
406 my $c = $elected[$i];
407 printf " %3d. %-10s %s\n", $i+1, $c->{Cand}, $c->{Desc};