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;
63 if ($opt =~ m/^[A-Z]/) {
64 die "unknown option $_ for $what";
65 } elsif ($opt =~ m/^[a-z]/) {
66 print STDERR "warning (line $.): unknown option $_ for $what\n";
73 foreach $_ (split / /, $') {
74 if (m/^_?[Ss]eats=(\d+)/) {
76 } elsif (m/^_?[Tt]ie=(.*)\>(.*)$/) {
77 my @more = split /\,/, $1;
78 my @less = split /\,/, $2;
79 my @all = join ',', sort (@more, @less);
80 $tie{"@all"}{Win} = $more[0] if @more == 1;
81 $tie{"@all"}{Lose} = $less[0] if @less == 1;
83 unkopt "election", $_;
86 } elsif (m/^(\w+) = (\S*) \|/) {
87 my ($cand,$desc) = ($1,$2);
88 unkopt "candidate $cand", $_ foreach split / /, $';
89 $cands{$cand}{Desc} = $desc;
90 } elsif (m/^(\w*) :\s*(.*)\s*\|(.*)/) {
91 my ($voter,$prefs,$opts) = ($1,$2,$3);
92 my $v = { Voter => $voter, Prefs => [ ] };
93 push @{ $v->{Prefs} }, [ $_ =~ m/\w+/g ]
94 foreach split /\s+/, $prefs;
95 foreach $_ (split / /, $opts) {
96 if (m/^_?[Ww]eight=(\d+)\/(\d+)$/) {
97 $v->{Weight} = $1 / $2;
98 } elsif (m/^_?[Ww]eight=([0-9.]+)$/) {
99 $v->{Weight} = new Math::BigRat $1;
101 unkopt "voter $v->{Voter}", $_;
112 $cands{$_}{Cand} = $_ foreach keys %cands;
113 $_->{Weight} //= 1/1 foreach @allvotes;
114 $_->{TransferredSurplus} //= [ ] foreach @allvotes;
115 $_->{OrigPrefs} //= [ @{ $_->{Prefs} } ] foreach @allvotes;
119 push @{ $vote->{Log} }, "stage $stage: $m";
123 sub sortballots (@) {
124 # Takes each argument, which should be a ballot, sorts
125 # it into $cand{CAND}{Votes} according to first preference.
126 # Strips that first preference from the ballot.
127 # If the first preference has been eliminated, strips it
128 # and looks for further preferences.
129 print DEBUG "sortballots ".(scalar @_)."...\n";
131 my $firstprefs = shift @{ $v->{Prefs} };
132 my $w = $v->{Weight};
133 if (!$firstprefs || !@$firstprefs) {
134 votelog $v, "no more preferences, non transferable";
135 push @non_transferable, $v;
138 if (@$firstprefs > 1) {
139 votelog $v, "splitting due to several equal first preferences";
140 foreach my $fpref (@$firstprefs) {
143 Weight => $w / @$firstprefs,
144 Prefs => [ [ $fpref ], @{ $v->{Prefs} } ],
146 votelog $v, "split for $fpref";
150 my $fp = $firstprefs->[0];
152 my $noncont = $c->{NonCont};
154 votelog $v, "dropping pref $fp, $noncont";
158 votelog $v, "sorted into pile for candidate $fp weight $w";
159 push @{ $c->{Votes} }, $v;
165 $v = new Math::BigRat $v; # we need a copy
171 my $v = new Math::BigRat $in; # just in case
172 my $intpart = floor($v);
173 my $frac = $v - $intpart;
174 my $good = floor($frac * $F);
175 my $bad = $frac * $F - $good;
176 my $s = sprintf "%7d", $intpart;
178 $s .= sprintf ".%0${DIGS}d", $good;
179 $s .= sprintf "%-4s", ($bad ? "+$bad" : "");
181 $s .= sprintf " %${DIGS}s%4s", '', '';
183 #print STDERR "# $in => $s # (intpart=$intpart frac=$frac)\n";
189 printf "stage %d: ".$fmt, $stage, @_;
192 sub countballots () {
193 foreach my $c (values %cands) {
194 next if $c->{NonCont};
196 $c->{Total} += $_->{Weight} foreach @{ $c->{Votes} };
197 print DEBUG "counted $c->{Cand} $c->{Total}\n";
198 $c->{History}[$stage-1] = $c->{Total};
201 foreach my $c (reverse sort total_history_cmp
202 grep { !$_->{NonCont} } values %cands) {
203 prf "candidate %-10s: %s votes\n", $c->{Cand}, sv $c->{Total};
207 sub computequota () {
208 my $totalvalid = 0/1;
209 $totalvalid += $_->{Total} foreach values %cands;
210 $quota = floor($totalvalid / (1 + $seats));
211 prf "quota %s\n", sv $quota;
214 sub total_history_cmp () {
215 my $ha = $a->{History};
216 my $hb = $b->{History};
217 my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
218 print DEBUG "$m...\n";
219 foreach my $s (reverse 0 .. $stage-1) {
220 my $d = $ha->[$s] <=> $hb->[$s];
222 print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
225 print DEBUG "$m => 0\n";
230 grep { !$_->{NonCont} } values %cands;
233 sub select_best_worst ($$$$) {
234 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
235 # $wantcand->($c) = boolish
236 # $wanttiebreak->($total) = boolish
237 # Firstly candidates not meeting $wantcand are ignored
238 # Then we pick the best (worst) candiate by Total (or vote history).
239 # (SLGEO 49(2) and 51(2).
240 # If this does not help then totals are equal and we call wanttiebreak.
241 # If it returns 0 we return alphabetically first CAND. Otherwise
244 my @maybe = grep { $wantcand->($_) } continuing();
245 @maybe = sort total_history_cmp @maybe;
246 @maybe = reverse @maybe if $signum > 0;
248 return undef unless @maybe;
253 my $nextc = $maybe[$nequal];
256 # Only interested in those who compare equal according to the
257 # history (SLGEO 49(2)); NB our history includes the current
260 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
264 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
265 # ... if equal for election we can do them one by one, since
266 # order does not matter (SLGEO 49 talks about `two or more
273 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
274 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
275 $selectcand = $tie{"@all"}{$tiekey};
276 die "need tie break, want $tiekey from @all"
277 unless defined $selectcand;
278 prf "$what %s due to tie break amongst %s\n",
281 $selectcand = $maybe[0]{Cand};
282 prf "$what %s\n", $selectcand;
285 return $cands{$selectcand};
290 prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
291 $c->{NonCont} = 'Elected';
300 sortballots @allvotes if $stage == 1;
302 my $seats_remain = $seats - @elected;
304 prf "seats remaining %d\n", $seats_remain;
306 last unless $seats_remain;
308 if (continuing() <= $seats_remain) {
309 foreach my $c (continuing()) {
310 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
318 computequota if $stage == 1;
320 my $c = select_best_worst
321 sub { $_->{Total} >= $quota },
327 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
330 my $surplus = $c->{Total} - $quota;
332 if ($surplus <= 0/1) {
340 prf "surplus %s\n", sv $surplus;
342 foreach my $v (@{ $c->{Votes} }) {
343 my $previously = $v->{TransferredSurplus};
344 push @$previously, $c->{Cand};
346 my $A = $surplus * $v->{Weight};
347 my $xfervalue = floor(($A * $F) / $B) / $F;
348 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
349 # but always rounding down
350 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
351 $v->{Weight} = $xfervalue;
353 if (defined $tspr{"@$previously"}) {
354 die unless $tspr{"@$previously"} == $xfervalue;
356 $tspr{"@$previously"} = $xfervalue;
357 prf "transfer value of ballots %s: %s\n",
358 "@$previously", sv $xfervalue;
361 sortballots @{ $c->{Votes} };
363 $c->{Votes} = { }; # will crash if we access it again
367 # No-one to elect, must eliminate
368 $c = select_best_worst
374 prf "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
375 $c->{NonCont} = 'Eliminated';
377 sortballots @{ $c->{Votes} };
386 foreach my $i (0..$#elected) {
387 my $c = $elected[$i];
388 printf " %3d. %-10s %s\n", $i+1, $c->{Cand}, $c->{Desc};