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";
204 printf "stage %d: ".$fmt, $stage, @_;
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 quota %s\n", (sv $totalvalid), (sv $quota);
229 sub total_history_cmp () {
230 my $ha = $a->{History};
231 my $hb = $b->{History};
232 my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
233 print DEBUG "$m...\n";
234 foreach my $s (reverse 0 .. $stage-1) {
235 my $d = $ha->[$s] <=> $hb->[$s];
237 print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
240 print DEBUG "$m => 0\n";
245 grep { !$_->{NonCont} } values %cands;
248 sub select_best_worst ($$$$) {
249 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
250 # $wantcand->($c) = boolish
251 # $wanttiebreak->($total) = boolish
252 # Firstly candidates not meeting $wantcand are ignored
253 # Then we pick the best (worst) candiate by Total (or vote history).
254 # (SLGEO 49(2) and 51(2).
255 # If this does not help then totals are equal and we call wanttiebreak.
256 # If it returns 0 we return alphabetically first CAND. Otherwise
259 my @maybe = grep { $wantcand->($_) } continuing();
260 @maybe = sort total_history_cmp @maybe;
261 @maybe = reverse @maybe if $signum > 0;
263 return undef unless @maybe;
268 my $nextc = $maybe[$nequal];
271 # Only interested in those who compare equal according to the
272 # history (SLGEO 49(2)); NB our history includes the current
275 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
279 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
280 # ... if equal for election we can do them one by one, since
281 # order does not matter (SLGEO 49 talks about `two or more
288 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
289 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
290 $selectcand = $tie{"@all"}{$tiekey};
291 die "need tie break, want $tiekey from @all"
292 unless defined $selectcand;
293 prf "$what %s due to tie break amongst %s\n",
296 $selectcand = $maybe[0]{Cand};
297 prf "$what %s\n", $selectcand;
300 return $cands{$selectcand};
305 prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
306 $c->{NonCont} = 'Elected';
315 sortballots @allvotes if $stage == 1;
317 my $seats_remain = $seats - @elected;
319 prf "seats remaining %d\n", $seats_remain;
321 last unless $seats_remain;
323 if (continuing() <= $seats_remain) {
324 foreach my $c (continuing()) {
325 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
333 computequota if $stage == 1;
335 my $c = select_best_worst
336 sub { $_->{Total} >= $quota },
342 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
345 my $surplus = $c->{Total} - $quota;
347 if ($surplus <= 0/1) {
352 last if $seats_remain == 1; # don't bother doing more transfers
357 prf "surplus %s\n", sv $surplus;
359 foreach my $v (@{ $c->{Votes} }) {
360 my $previously = $v->{TransferredSurplus};
361 push @$previously, $c->{Cand};
363 my $A = $surplus * $v->{Weight};
364 my $xfervalue = floor(($A * $F) / $B) / $F;
365 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
366 # but always rounding down
367 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
368 $v->{Weight} = $xfervalue;
370 if (defined $tspr{"@$previously"}) {
371 die unless $tspr{"@$previously"} == $xfervalue;
373 $tspr{"@$previously"} = $xfervalue;
374 prf "transfer value of ballots %20s: %s\n",
375 "@$previously", sv $xfervalue;
378 sortballots @{ $c->{Votes} };
380 $c->{Votes} = { }; # will crash if we access it again
384 # No-one to elect, must eliminate
385 $c = select_best_worst
391 prf "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
392 $c->{NonCont} = 'Eliminated';
394 sortballots @{ $c->{Votes} };
403 foreach my $i (0..$#elected) {
404 my $c = $elected[$i];
405 printf " %3d. %-10s %s\n", $i+1, $c->{Cand}, $c->{Desc};