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;
36 our $F = (new Math::BigRat 10)->bpow($DIGS);
38 open DEBUG, ">.compute.log" or die $!;
42 print DEBUG Dumper(\%tie,
49 $SIG{__WARN__} = sub {
50 $SIG{__DIE__} = undef;
62 if ($opt =~ m/^[A-Z]/) {
63 die "unknown option $_ for $what";
64 } elsif ($opt =~ m/^[a-z]/) {
65 print STDERR "warning (line $.): unknown option $_ for $what\n";
72 foreach $_ (split / /, $') {
73 if (m/^_?[Ss]eats=(\d+)/) {
75 } elsif (m/^_?[Tt]ie=(.*)\>(.*)$/) {
76 my @more = split /\,/, $1;
77 my @less = split /\,/, $2;
78 my @all = join ',', sort (@more, @less);
79 $tie{"@all"}{Win} = $more[0] if @more == 1;
80 $tie{"@all"}{Lose} = $less[0] if @less == 1;
82 unkopt "election", $_;
85 } elsif (m/^(\w+) = (\S*) \|/) {
86 my ($cand,$desc) = ($1,$2);
87 unkopt "candidate $cand", $_ foreach split / /, $';
88 $cands{$cand}{Desc} = $desc;
89 } elsif (m/^(\w*) :\s*(.*)\s*\|(.*)/) {
90 my ($voter,$prefs,$opts) = ($1,$2,$3);
91 my $v = { Voter => $voter, Prefs => [ ] };
92 push @{ $v->{Prefs} }, [ $_ =~ m/\w+/g ]
93 foreach split /\s+/, $prefs;
94 foreach $_ (split / /, $opts) {
95 if (m/^_?[Ww]eight=(\d+)\/(\d+)$/) {
96 $v->{Weight} = $1 / $2;
97 } elsif (m/^_?[Ww]eight=([0-9.]+)$/) {
98 $v->{Weight} = new Math::BigRat $1;
100 unkopt "voter $v->{Voter}", $_;
111 $cands{$_}{Cand} = $_ foreach keys %cands;
112 $_->{Weight} //= 1/1 foreach @allvotes;
113 $_->{TransferredSurplus} //= [ ] foreach @allvotes;
114 $_->{OrigPrefs} //= [ @{ $_->{Prefs} } ] foreach @allvotes;
118 push @{ $vote->{Log} }, "stage $stage: $m";
122 sub sortballots (@) {
123 # Takes each argument, which should be a ballot, sorts
124 # it into $cand{CAND}{Votes} according to first preference.
125 # Strips that first preference from the ballot.
126 # If the first preference has been eliminated, strips it
127 # and looks for further preferences.
128 print DEBUG "sortballots ".(scalar @_)."...\n";
130 my $firstprefs = shift @{ $v->{Prefs} };
131 my $w = $v->{Weight};
132 if (!$firstprefs || !@$firstprefs) {
133 votelog $v, "no more preferences, non transferable";
134 push @non_transferable, $v;
137 if (@$firstprefs > 1) {
138 votelog $v, "splitting due to several equal first preferences";
139 foreach my $fpref (@$firstprefs) {
142 Weight => $w / @$firstprefs,
143 Prefs => [ [ $fpref ], @{ $v->{Prefs} } ],
145 votelog $v, "split for $fpref";
149 my $fp = $firstprefs->[0];
151 my $noncont = $c->{NonCont};
153 votelog $v, "dropping pref $fp, $noncont";
157 votelog $v, "sorted into pile for candidate $fp weight $w";
158 push @{ $c->{Votes} }, $v;
164 $v = new Math::BigRat $v; # we need a copy
170 my $v = new Math::BigRat $in; # just in case
171 my $intpart = floor($v);
172 my $frac = $v - $intpart;
173 my $good = floor($frac * $F);
174 my $bad = $frac * $F - $good;
175 my $s = sprintf "%7d", $intpart;
177 $s .= sprintf ".%0${DIGS}d", $good;
178 $s .= sprintf "%-4s", ($bad ? "+$bad" : "");
180 $s .= sprintf " %${DIGS}s%4s", '', '';
182 #print STDERR "# $in => $s # (intpart=$intpart frac=$frac)\n";
188 printf "stage %d: ".$fmt, $stage, @_;
191 sub countballots () {
192 foreach my $c (values %cands) {
193 next if $c->{NonCont};
195 $c->{Total} += $_->{Weight} foreach @{ $c->{Votes} };
196 print DEBUG "counted $c->{Cand} $c->{Total}\n";
197 $c->{History}[$stage-1] = $c->{Total};
200 foreach my $c (reverse sort total_history_cmp
201 grep { !$_->{NonCont} } values %cands) {
202 prf "candidate %-10s: %s votes\n", $c->{Cand}, sv $c->{Total};
206 sub computequota () {
207 my $totalvalid = 0/1;
208 $totalvalid += $_->{Total} foreach values %cands;
209 $quota = floor($totalvalid / (1 + $seats));
210 prf "quota %s\n", sv $quota;
213 sub total_history_cmp () {
214 my $ha = $a->{History};
215 my $hb = $b->{History};
216 my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
217 print DEBUG "$m...\n";
218 foreach my $s (reverse 0 .. $stage-1) {
219 my $d = $ha->[$s] <=> $hb->[$s];
221 print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
224 print DEBUG "$m => 0\n";
229 grep { !$_->{NonCont} } values %cands;
232 sub select_best_worst ($$$$) {
233 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
234 # $wantcand->($c) = boolish
235 # $wanttiebreak->($total) = boolish
236 # Firstly candidates not meeting $wantcand are ignored
237 # Then we pick the best (worst) candiate by Total (or vote history).
238 # (SLGEO 49(2) and 51(2).
239 # If this does not help then totals are equal and we call wanttiebreak.
240 # If it returns 0 we return alphabetically first CAND. Otherwise
243 my @maybe = grep { $wantcand->($_) } continuing();
244 @maybe = sort total_history_cmp @maybe;
245 @maybe = reverse @maybe if $signum > 0;
247 return undef unless @maybe;
252 my $nextc = $maybe[$nequal];
255 # Only interested in those who compare equal according to the
256 # history (SLGEO 49(2)); NB our history includes the current
259 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
263 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
264 # ... if equal for election we can do them one by one, since
265 # order does not matter (SLGEO 49 talks about `two or more
272 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
273 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
274 $selectcand = $tie{"@all"}{$tiekey};
275 die "need tie break, want $tiekey from @all"
276 unless defined $selectcand;
277 prf "$what %s due to tie break amongst %s\n",
280 $selectcand = $maybe[0]{Cand};
281 prf "$what %s\n", $selectcand;
284 return $cands{$selectcand};
289 prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
290 $c->{NonCont} = 'Elected';
298 sortballots @allvotes if $stage == 1;
300 my $seats_remain = $seats
301 - grep { ($_->{NonCont} // '') eq 'Elected' } values %cands;
302 if (continuing() <= $seats_remain) {
303 foreach my $c (continuing()) {
304 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
312 computequota if $stage == 1;
314 my $c = select_best_worst
315 sub { $_->{Total} >= $quota },
321 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
324 my $surplus = $c->{Total} - $quota;
326 if ($surplus <= 0/1) {
334 prf "surplus %s\n", sv $surplus;
336 foreach my $v (@{ $c->{Votes} }) {
337 my $previously = $v->{TransferredSurplus};
338 push @$previously, $c->{Cand};
340 my $A = $surplus * $v->{Weight};
341 my $xfervalue = floor(($A * $F) / $B) / $F;
342 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
343 # but always rounding down
344 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
345 $v->{Weight} = $xfervalue;
347 if (defined $tspr{"@$previously"}) {
348 die unless $tspr{"@$previously"} == $xfervalue;
350 $tspr{"@$previously"} = $xfervalue;
351 prf "transfer value of ballots %s: %s\n",
352 "@$previously", sv $xfervalue;
355 sortballots @{ $c->{Votes} };
357 $c->{Votes} = { }; # will crash if we access it again
361 # No-one to elect, must eliminate
362 $c = select_best_worst
368 prf "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
369 $c->{NonCont} = 'Eliminated';
371 sortballots @{ $c->{Votes} };