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