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;
35 open DEBUG, ">.compute.log" or die $!;
38 $SIG{__WARN__} = sub {
39 print DEBUG Dumper(\%tie,
49 if ($opt =~ m/^[A-Z]/) {
50 die "unknown option $_ for $what";
51 } elsif ($opt =~ m/^[a-z]/) {
52 print STDERR "warning (line $.): unknown option $_ for $what\n";
59 foreach $_ (split / /, $') {
60 if (m/^_?[Ss]eats=(\d+)/) {
62 } elsif (m/^_?[Tt]ie=(.*)\>(.*)$/) {
63 my @more = split /\,/, $1;
64 my @less = split /\,/, $2;
65 my @all = join ',', sort (@more, @less);
66 $tie{"@all"}{Win} = $more[0] if @more == 1;
67 $tie{"@all"}{Lose} = $less[0] if @less == 1;
69 unkopt "election", $_;
72 } elsif (m/^(\w+) = (\S*) \|/) {
73 my ($cand,$desc) = ($1,$2);
74 unkopt "candidate $cand", $_ foreach split / /, $';
75 $cands{$cand}{Desc} = $desc;
76 } elsif (m/^(\w*) :\s*(.*)\s*\|(.*)/) {
77 my ($voter,$prefs,$opts) = ($1,$2,$3);
78 my $v = { Voter => $voter, Prefs => [ ] };
79 push @{ $v->{Prefs} }, [ $_ =~ m/\w+/g ]
80 foreach split /\s+/, $prefs;
81 foreach $_ (split / /, $opts) {
82 if (m/^_?[Ww]eight=(\d+)\/(\d+)$/) {
83 $v->{Weight} = $1 / $2;
84 } elsif (m/^_?[Ww]eight=([0-9.]+)$/) {
85 $v->{Weight} = new Math::BigRat $1;
87 unkopt "voter $v->{Voter}", $_;
98 $cands{$_}{Cand} = $_ foreach keys %cands;
99 $_->{Weight} //= 1/1 foreach @allvotes;
100 $_->{TransferredSurplus} //= [ ] foreach @allvotes;
104 push @{ $vote->{Log} }, "stage $stage: $m";
108 sub sortballots (@) {
109 # Takes each argument, which should be a ballot, sorts
110 # it into $cand{CAND}{Votes} according to first preference.
111 # Strips that first preference from the ballot.
112 # If the first preference has been eliminated, strips it
113 # and looks for further preferences.
115 my $firstprefs = shift @{ $v->{Prefs} };
116 my $w = $v->{Weight};
117 if (!$firstprefs || !@$firstprefs) {
118 votelog $v, "no more preferences, non transferable";
119 push @non_transferable, $v;
122 if (@$firstprefs > 1) {
123 votelog $v, "splitting due to several equal first preferences";
124 foreach my $fpref (@$firstprefs) {
127 Weight => $w / @$firstprefs,
128 Prefs => [ [ $fpref ], @{ $v->{Prefs} } ],
130 votelog $v, "split for $fpref";
134 my $fp = $firstprefs->[0];
136 my $noncont = $c->{NonCont};
138 votelog $v, "dropping pref $fp, $noncont";
142 votelog $v, "sorted into pile for candidate $fp weight $w";
143 push @{ $c->{Votes} }, $v;
149 printf "stage %d: ".$fmt, $stage, @_;
152 sub countballots () {
153 foreach my $cand (sort keys %cands) {
154 my $c = $cands{$cand};
155 next if $c->{NonCont};
157 $c->{Total} += $_->{Weight} foreach @{ $c->{Votes} };
158 prf "candidate %-10s: %10s votes\n", $cand, $c->{Total};
159 $c->{History}[$stage-1] = $c->{Total};
163 sub computequota () {
165 $totalvalid += $_->{Total} foreach values %cands;
166 $quota = ($totalvalid / (1 + $seats)) -> bfloor();
167 prf "quota %10s\n", $quota;
170 sub total_history_cmp () {
171 my $ha = $a->{History};
172 my $hb = $b->{History};
173 foreach my $s (reverse 0 .. $stage-1) {
174 my $d = $ha->[$s] <=> $hb->[$s];
176 print DEBUG "history cmp $a->{Cand} $b->{Cand}".
177 " => $d (#$s $ha->[$s] $hb->[$s])\n";
184 grep { !$_->{NonCont} } values %cands;
187 sub select_best_worst ($$$$) {
188 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
189 # $wantcand->($c) = boolish
190 # $wanttiebreak->($total) = boolish
191 # Firstly candidates not meeting $wantcand are ignored
192 # Then we pick the best (worst) candiate by Total (or vote history).
193 # (SLGEO 49(2) and 51(2).
194 # If this does not help then totals are equal and we call wanttiebreak.
195 # If it returns 0 we return alphabetically first CAND. Otherwise
198 my @maybe = grep { $wantcand->($_) } continuing();
199 @maybe = sort total_history_cmp @maybe;
200 @maybe = reverse @maybe if $signum > 0;
202 return undef unless @maybe;
207 my $nextc = $maybe[$nequal];
209 # Only interested in those who compare equal according to the
210 # history (SLGEO 49(2)); NB our history includes the current
213 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
217 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
218 # ... if equal for election we can do them one by one, since
219 # order does not matter (SLGEO 49 talks about `two or more
226 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
227 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
228 $selectcand = $tie{"@all"}{$tiekey};
229 die "need tie break, want $tiekey from @all"
230 unless defined $selectcand;
231 prf "$what %s due to tie break amongst %s\n",
234 $selectcand = $maybe[0]{Cand};
235 prf "$what %s\n", $selectcand;
238 return $cands{$selectcand};
243 prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
244 $c->{NonCont} = 'Elected';
252 sortballots @allvotes if $stage == 1;
254 my $seats_remain = $seats
255 - grep { ($_->{NonCont} // '') eq 'Elected' } values %cands;
256 if (continuing() <= $seats_remain) {
257 foreach my $c (continuing()) {
258 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
266 computequota if $stage == 1;
268 my $c = select_best_worst
269 sub { $_->{Total} >= $quota },
275 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
278 my $surplus = $c->{Total} - $quota;
288 prf "surplus %10s\n", $surplus;
290 foreach my $v (@{ $c->{Votes} }) {
291 my $previously = $v->{TransferredSurplus};
292 push @$previously, $c->{Cand};
294 my $A = $surplus * $v->{Weight};
296 my $xfervalue = ((($A * $F) / $B) -> bfloor() ) / $F;
297 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
298 # but always rounding down
299 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
300 $v->{Weight} = $xfervalue;
302 if (defined $tspr{"@$previously"}) {
303 die unless $tspr{"@$previously"} == $xfervalue;
305 $tspr{"@$previously"} = $xfervalue;
306 prf "transfer value of ballots %s: %10s\n",
307 "@$previously", $xfervalue;
311 $c->{Votes} = { }; # will crash if we access it again
315 # No-one to elect, must eliminate
316 $c = select_best_worst
322 prf "=== eliminating %s (%s) ===\n", $c->{Cand}, $c->{Desc};
323 $c->{NonCont} = 'Eliminated';