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