chiark / gitweb /
12645fd4d64da0ce5b13aea6f435afc48c8935d9
[appendix-a6.git] / compute-scottish-stv
1 #!/usr/bin/perl -w
2
3 # Reference:
4 # The Scottish Local Government Elections Order 2007
5
6 use strict;
7 use Carp;
8 use Data::Dumper;
9 use Math::BigRat;
10 use bigrat;
11
12 # Data structures:
13 #
14 # vote is
15 #   { Voter => opaque,
16 #     Prefs => [ [ CAND, ...], ... ],
17 #     Weight => 1.0 }
18 # We edit Prefs as we go
19
20 # $cands{CAND}{Cand}
21 # $cands{CAND}{Desc}
22 # $cands{CAND}{Votes}
23 # $cands{CAND}{Total}
24 # $cands{CAND}{NonCont} # undef, or Elected or Eliminated
25
26 our $seats=0;
27
28 our @allvotes;
29 our @non_transferable;
30 our %cands;
31 our $stage=0;
32 our $quota;
33 our %tie;
34 our @elected;
35
36 our $DIGS = 5;
37 our $F = (new Math::BigRat 10)->bpow($DIGS);
38
39 open DEBUG, ">.compute.log" or die $!;
40 DEBUG->autoflush(1);
41
42 sub debug_dump () {
43     print DEBUG Dumper(\%tie,
44                        \@non_transferable,
45                        \%cands,
46                        \@allvotes,
47                        $stage, $quota);
48 }
49
50 $SIG{__WARN__} = sub {
51     $SIG{__DIE__} = undef;
52     debug_dump;
53     confess $_[0];
54 };
55
56 $SIG{__DIE__} = sub {
57     debug_dump;
58     die $_[0];
59 };
60
61 sub total_history_cmp ();
62
63 sub unkopt ($$) {
64     my ($what,$opt) = @_;
65     if ($opt =~ m/^[A-Z]/) {
66         die "unknown option $_ for $what";
67     } elsif ($opt =~ m/^[a-z]/) {
68         print STDERR "warning (line $.): unknown option $_ for $what\n";
69     }
70 }
71
72 my $display_cmp = \&total_history_cmp;
73 my $for_compare = 0;
74
75 while (@ARGV && $ARGV[0] =~ m/^\-/) {
76     $_ = shift @ARGV;
77     if (m/^--$/) {
78         last;
79     } elsif (m/^--sort=alpha$/) {
80         $display_cmp = sub { $b->{Cand} cmp $a->{Cand} };
81     } elsif (m/^--for-compare$/) {
82         $for_compare = 1;
83         unshift @ARGV, '--sort=alpha';
84     } else {
85         die;
86     }
87 }
88
89 for (;;) {
90     $_ = <>;
91     if (m/^\| /) {
92         foreach $_ (split / /, $') {
93             if (m/^_?[Ss]eats=(\d+)/) {
94                 $seats = $1;
95             } elsif (m/^_?[Tt]ie=(.*)\>(.*)$/) {
96                 my @more = split /\,/, $1;
97                 my @less = split /\,/, $2;
98                 my @all = join ',', sort (@more, @less);
99                 $tie{"@all"}{Win}  = $more[0] if @more == 1;
100                 $tie{"@all"}{Lose} = $less[0] if @less == 1;
101             } else {
102                 unkopt "election", $_;
103             }
104         }
105     } elsif (m/^(\w+) = (\S*) \|/) {
106         my ($cand,$desc) = ($1,$2);
107         unkopt "candidate $cand", $_ foreach split / /, $';
108         $cands{$cand}{Desc} = $desc;
109     } elsif (m/^(\w*) :\s*(.*)\s*\|(.*)/) {
110         my ($voter,$prefs,$opts) = ($1,$2,$3);
111         my $v = { Voter => $voter, Prefs => [ ] };
112         push @{ $v->{Prefs} }, [ $_ =~ m/\w+/g ]
113             foreach split /\s+/, $prefs;
114         foreach $_ (split / /, $opts) {
115             if (m/^_?[Ww]eight=(\d+)\/(\d+)$/) {
116                 $v->{Weight} = $1 / $2;
117             } elsif (m/^_?[Ww]eight=([0-9.]+)$/) {
118                 $v->{Weight} = new Math::BigRat $1;
119             } else {
120                 unkopt "voter $v->{Voter}", $_;
121             }
122         }
123         push @allvotes, $v;
124     } elsif (m/^\.$/) {
125         last;
126     } else {
127         die "$_ ?";
128     }
129 }
130
131 $cands{$_}{Cand} = $_ foreach keys %cands;
132 $_->{Weight} //= 1/1 foreach @allvotes;
133 $_->{TransferredSurplus} //= [ ] foreach @allvotes;
134 $_->{OrigPrefs} //= [ @{ $_->{Prefs} } ] foreach @allvotes;
135
136 sub votelog ($$) {
137     my ($vote,$m) = @_;
138     push @{ $vote->{Log} }, "stage $stage: $m";
139 }
140
141 sub sortballots (@);
142 sub sortballots (@) {
143     # Takes each argument, which should be a ballot, sorts
144     # it into $cand{CAND}{Votes} according to first preference.
145     # Strips that first preference from the ballot.
146     # If the first preference has been eliminated, strips it
147     # and looks for further preferences.
148     print DEBUG "sortballots ".(scalar @_)."...\n";
149     foreach my $v (@_) {
150         my $firstprefs = shift @{ $v->{Prefs} };
151         my $w = $v->{Weight};
152         if (!$firstprefs || !@$firstprefs) {
153             votelog $v, "no more preferences, non transferable";
154             push @non_transferable, $v;
155             next;
156         }
157         if (@$firstprefs > 1) {
158             votelog $v, "splitting due to several equal first preferences";
159             foreach my $fpref (@$firstprefs) {
160                 my $v2 = {
161                     %$v,
162                     Weight => $w / @$firstprefs,
163                     Prefs => [ [ $fpref ], @{ $v->{Prefs} } ],
164                 };
165                 votelog $v, "split for $fpref";
166             }
167             next;
168         }
169         my $fp = $firstprefs->[0];
170         my $c = $cands{$fp};
171         my $noncont = $c->{NonCont};
172         if ($noncont) {
173             votelog $v, "dropping pref $fp, $noncont";
174             sortballots $v;
175             next;
176         }
177         votelog $v, "sorted into pile for candidate $fp weight $w";
178         push @{ $c->{Votes} }, $v;
179     }
180 }
181
182 sub floor ($) {
183     my ($v) = @_;
184     $v = new Math::BigRat $v; # we need a copy
185     return $v->bfloor();
186 }
187
188 sub sv ($) {
189     my ($in) = @_;
190     my $v = new Math::BigRat $in; # just in case
191     my $intpart = floor($v);
192     my $frac = $v - $intpart;
193     my $good = floor($frac * $F);
194     my $bad = $frac * $F - $good;
195     my $s = sprintf "%7d", $intpart;
196     if ($frac) {
197         $s .= sprintf ".%0${DIGS}d", $good;
198         $s .= sprintf "%-4s", ($bad ? "+$bad" : "");
199     } else {
200         $s .= sprintf " %${DIGS}s%4s", '', '';
201     }
202 #print STDERR "# $in => $s # (intpart=$intpart frac=$frac)\n";
203     return $s;
204 }
205
206 sub prf {
207     my $fmt = shift;
208     printf " ".$fmt, @_;
209 }
210
211 sub countballots () {
212     foreach my $c (values %cands) {
213         next if $c->{NonCont};
214         $c->{Total} = 0/1;
215         $c->{Total} += $_->{Weight} foreach @{ $c->{Votes} };
216         print DEBUG "counted $c->{Cand} $c->{Total}\n";
217         $c->{History}[$stage-1] = $c->{Total};
218     }
219
220     foreach my $c (reverse sort $display_cmp
221                    grep { !$_->{NonCont} } values %cands) {
222         prf "candidate %-10s: %s votes\n", $c->{Cand}, sv $c->{Total};
223     }
224 }
225
226 sub computequota () {
227     my $totalvalid = 0/1;
228     $totalvalid += $_->{Total} foreach values %cands;
229     $quota = floor($totalvalid / (1 + $seats) + 1);
230     prf "total valid %s\n", sv $totalvalid;
231     prf "quota       %s\n", sv $quota;
232 }
233
234 sub total_history_cmp () {
235     my $ha = $a->{History};
236     my $hb = $b->{History};
237     my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
238     print DEBUG  "$m...\n";
239     foreach my $s (reverse 0 .. $stage-1) {
240         my $d = $ha->[$s] <=> $hb->[$s];
241         next unless $d;
242         print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
243         return $d;
244     }
245     print DEBUG "$m => 0\n";
246     return 0;
247 }
248
249 sub continuing () {
250     grep { !$_->{NonCont} } values %cands;
251 }
252
253 sub select_best_worst ($$$$) {
254     my ($wantcand, $wanttiebreak, $signum, $what) = @_;
255     # $wantcand->($c) = boolish
256     # $wanttiebreak->($total) = boolish
257     # Firstly candidates not meeting $wantcand are ignored
258     # Then we pick the best (worst) candiate by Total (or vote history).
259     # (SLGEO 49(2) and 51(2).
260     # If this does not help then totals are equal and we call wanttiebreak.
261     # If it returns 0 we return alphabetically first CAND.  Otherwise
262     # we tie break.
263
264     my @maybe = grep { $wantcand->($_) } continuing();
265     @maybe = sort total_history_cmp @maybe;
266     @maybe = reverse @maybe if $signum > 0;
267
268     return undef unless @maybe;
269
270     my $nequal = 1;
271
272     for (;;) {
273         my $nextc = $maybe[$nequal];
274         last unless $nextc;
275
276         # Only interested in those who compare equal according to the
277         # history (SLGEO 49(2)); NB our history includes the current
278         # round.
279         
280         last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
281         $nequal++;
282     }
283
284     if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
285         # ... if equal for election we can do them one by one, since
286         # order does not matter (SLGEO 49 talks about `two or more
287         # ... exceeds').
288         $nequal = 1;
289     }
290
291     my $selectcand;
292     if ($nequal > 1) {
293         my @all = map { $_->{Cand} } @maybe[0 .. $nequal-1];
294         my $tiekey = $signum > 0 ? 'Win' : 'Lose';
295         $selectcand = $tie{"@all"}{$tiekey};
296         die "need tie break, want $tiekey from @all"
297             unless defined $selectcand;
298         prf "$what %s due to tie break amongst %s\n",
299             $selectcand, "@all";
300     } else {
301         $selectcand = $maybe[0]{Cand};
302         prf "$what %s\n", $selectcand;
303     }
304
305     return $cands{$selectcand};
306 }
307
308 sub elect_core ($) {
309     my ($c) = @_;
310     prf "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
311     $c->{NonCont} = 'Elected';
312     push @elected, $c;
313 }
314
315 $stage = 0;
316
317 for (;;) {
318     $stage++;
319     printf "stage %3d:\n", $stage;
320
321     sortballots @allvotes if $stage == 1;
322
323     my $seats_remain = $seats - @elected;
324
325     prf "seats remaining %d\n", $seats_remain;
326
327     last unless $seats_remain;
328
329     if (continuing() <= $seats_remain) {
330         foreach my $c (continuing()) {
331             prf "electing %s to fill remaining place(s)\n", $c->{Cand};
332             elect_core $c;
333         }
334         countballots() if $for_compare;
335         last;
336     }
337
338     countballots();
339
340     computequota if $stage == 1;
341
342     my $c = select_best_worst
343         sub { $_->{Total} >= $quota },
344         sub { $_ > $quota },
345         +1, 'electing';
346
347     if ($c) {
348         elect_core $c;
349         votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
350         
351         # SLGEO 48
352         my $surplus = $c->{Total} - $quota;
353
354         if ($surplus <= 0/1) {
355             prf "no surplus\n";
356             next;
357         }
358
359         last if $seats_remain == 1; # don't bother doing more transfers
360
361         my $B = $c->{Total};
362         my %tspr;
363
364         prf "surplus %s\n", sv $surplus;
365
366         foreach my $v (@{ $c->{Votes} }) {
367             my $previously = $v->{TransferredSurplus};
368             push @$previously, $c->{Cand};
369
370             my $A = $surplus * $v->{Weight};
371             my $xfervalue = floor(($A * $F) / $B) / $F;
372             # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
373             # but always rounding down
374             votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
375             $v->{Weight} = $xfervalue;
376
377             if (defined $tspr{"@$previously"}) {
378                 die unless $tspr{"@$previously"} == $xfervalue;
379             } else {
380                 $tspr{"@$previously"} = $xfervalue;
381                 prf "transfer value of ballots %20s: %s\n",
382                     "@$previously", sv $xfervalue;
383             }
384         }
385         sortballots @{ $c->{Votes} };
386
387         $c->{Votes} = { }; # will crash if we access it again
388         next;
389     }
390
391     # No-one to elect, must eliminate
392     $c = select_best_worst
393         sub { 1; },
394         sub { 1; },
395         -1, 'eliminating';
396
397     if ($c) {
398         prf "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
399         $c->{NonCont} = 'Eliminated';
400
401         sortballots @{ $c->{Votes} };
402         next;
403     }
404
405     die;
406 }
407
408 print "Winners:\n"; 
409
410 if ($for_compare) {
411     foreach my $c (sort { $a->{Cand} cmp $b->{Cand} } @elected) {
412         printf "  %s\n", $c->{Cand};
413     }
414 } else {
415     foreach my $i (0..$#elected) {
416         my $c = $elected[$i];
417         printf " %3d. %-10s %s\n", $i+1, $c->{Cand}, $c->{Desc};
418     }
419 }
420
421 print "done.\n";