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 $c->{History}[$stage-1] = $c->{Total};
161 foreach my $c (reverse sort total_history_cmp values %cands) {
162 prf "candidate %-10s: %10s votes\n", $c->{Cand}, $c->{Total};
166 sub computequota () {
168 $totalvalid += $_->{Total} foreach values %cands;
169 $quota = ($totalvalid / (1 + $seats)) -> bfloor();
170 prf "quota %10s\n", $quota;
173 sub total_history_cmp () {
174 my $ha = $a->{History};
175 my $hb = $b->{History};
176 foreach my $s (reverse 0 .. $stage-1) {
177 my $d = $ha->[$s] <=> $hb->[$s];
179 print DEBUG "history cmp $a->{Cand} $b->{Cand}".
180 " => $d (#$s $ha->[$s] $hb->[$s])\n";
187 grep { !$_->{NonCont} } values %cands;
190 sub select_best_worst ($$$$) {
191 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
192 # $wantcand->($c) = boolish
193 # $wanttiebreak->($total) = boolish
194 # Firstly candidates not meeting $wantcand are ignored
195 # Then we pick the best (worst) candiate by Total (or vote history).
196 # (SLGEO 49(2) and 51(2).
197 # If this does not help then totals are equal and we call wanttiebreak.
198 # If it returns 0 we return alphabetically first CAND. Otherwise
201 my @maybe = grep { $wantcand->($_) } continuing();
202 @maybe = sort total_history_cmp @maybe;
203 @maybe = reverse @maybe if $signum > 0;
205 return undef unless @maybe;
210 my $nextc = $maybe[$nequal];
212 # Only interested in those who compare equal according to the
213 # history (SLGEO 49(2)); NB our history includes the current
216 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
220 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
221 # ... if equal for election we can do them one by one, since
222 # order does not matter (SLGEO 49 talks about `two or more
229 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
230 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
231 $selectcand = $tie{"@all"}{$tiekey};
232 die "need tie break, want $tiekey from @all"
233 unless defined $selectcand;
234 prf "$what %s due to tie break amongst %s\n",
237 $selectcand = $maybe[0]{Cand};
238 prf "$what %s\n", $selectcand;
241 return $cands{$selectcand};
246 prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
247 $c->{NonCont} = 'Elected';
255 sortballots @allvotes if $stage == 1;
257 my $seats_remain = $seats
258 - grep { ($_->{NonCont} // '') eq 'Elected' } values %cands;
259 if (continuing() <= $seats_remain) {
260 foreach my $c (continuing()) {
261 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
269 computequota if $stage == 1;
271 my $c = select_best_worst
272 sub { $_->{Total} >= $quota },
278 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
281 my $surplus = $c->{Total} - $quota;
291 prf "surplus %10s\n", $surplus;
293 foreach my $v (@{ $c->{Votes} }) {
294 my $previously = $v->{TransferredSurplus};
295 push @$previously, $c->{Cand};
297 my $A = $surplus * $v->{Weight};
299 my $xfervalue = ((($A * $F) / $B) -> bfloor() ) / $F;
300 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
301 # but always rounding down
302 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
303 $v->{Weight} = $xfervalue;
305 if (defined $tspr{"@$previously"}) {
306 die unless $tspr{"@$previously"} == $xfervalue;
308 $tspr{"@$previously"} = $xfervalue;
309 prf "transfer value of ballots %s: %10s\n",
310 "@$previously", $xfervalue;
314 $c->{Votes} = { }; # will crash if we access it again
318 # No-one to elect, must eliminate
319 $c = select_best_worst
325 prf "=== eliminating %s (%s) ===\n", $c->{Cand}, $c->{Desc};
326 $c->{NonCont} = 'Eliminated';