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
162 grep { !$_->{NonCont} } values %cands) {
163 prf "candidate %-10s: %10s votes\n", $c->{Cand}, $c->{Total};
167 sub computequota () {
169 $totalvalid += $_->{Total} foreach values %cands;
170 $quota = ($totalvalid / (1 + $seats)) -> bfloor();
171 prf "quota %10s\n", $quota;
174 sub total_history_cmp () {
175 my $ha = $a->{History};
176 my $hb = $b->{History};
177 my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
178 print DEBUG "$m...\n";
179 foreach my $s (reverse 0 .. $stage-1) {
180 my $d = $ha->[$s] <=> $hb->[$s];
182 print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
185 print DEBUG "$m => 0\n";
190 grep { !$_->{NonCont} } values %cands;
193 sub select_best_worst ($$$$) {
194 my ($wantcand, $wanttiebreak, $signum, $what) = @_;
195 # $wantcand->($c) = boolish
196 # $wanttiebreak->($total) = boolish
197 # Firstly candidates not meeting $wantcand are ignored
198 # Then we pick the best (worst) candiate by Total (or vote history).
199 # (SLGEO 49(2) and 51(2).
200 # If this does not help then totals are equal and we call wanttiebreak.
201 # If it returns 0 we return alphabetically first CAND. Otherwise
204 my @maybe = grep { $wantcand->($_) } continuing();
205 @maybe = sort total_history_cmp @maybe;
206 @maybe = reverse @maybe if $signum > 0;
208 return undef unless @maybe;
213 my $nextc = $maybe[$nequal];
216 # Only interested in those who compare equal according to the
217 # history (SLGEO 49(2)); NB our history includes the current
220 last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
224 if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
225 # ... if equal for election we can do them one by one, since
226 # order does not matter (SLGEO 49 talks about `two or more
233 my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
234 my $tiekey = $signum > 0 ? 'Win' : 'Lose';
235 $selectcand = $tie{"@all"}{$tiekey};
236 die "need tie break, want $tiekey from @all"
237 unless defined $selectcand;
238 prf "$what %s due to tie break amongst %s\n",
241 $selectcand = $maybe[0]{Cand};
242 prf "$what %s\n", $selectcand;
245 return $cands{$selectcand};
250 prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
251 $c->{NonCont} = 'Elected';
259 sortballots @allvotes if $stage == 1;
261 my $seats_remain = $seats
262 - grep { ($_->{NonCont} // '') eq 'Elected' } values %cands;
263 if (continuing() <= $seats_remain) {
264 foreach my $c (continuing()) {
265 prf "electing %s to fill remaining place(s)\n", $c->{Cand};
273 computequota if $stage == 1;
275 my $c = select_best_worst
276 sub { $_->{Total} >= $quota },
282 votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
285 my $surplus = $c->{Total} - $quota;
295 prf "surplus %10s\n", $surplus;
297 foreach my $v (@{ $c->{Votes} }) {
298 my $previously = $v->{TransferredSurplus};
299 push @$previously, $c->{Cand};
301 my $A = $surplus * $v->{Weight};
303 my $xfervalue = ((($A * $F) / $B) -> bfloor() ) / $F;
304 # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
305 # but always rounding down
306 votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
307 $v->{Weight} = $xfervalue;
309 if (defined $tspr{"@$previously"}) {
310 die unless $tspr{"@$previously"} == $xfervalue;
312 $tspr{"@$previously"} = $xfervalue;
313 prf "transfer value of ballots %s: %10s\n",
314 "@$previously", $xfervalue;
318 $c->{Votes} = { }; # will crash if we access it again
322 # No-one to elect, must eliminate
323 $c = select_best_worst
329 prf "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
330 $c->{NonCont} = 'Eliminated';