chiark / gitweb /
compute-scottish-stv: Fix tie breaks
[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 sub prfm {
211     prf @_ unless $for_compare;
212 }
213
214 sub countballots () {
215     my @pr;
216
217     foreach my $c (values %cands) {
218         next if $c->{NonCont};
219         $c->{Total} = 0/1;
220         $c->{Total} += $_->{Weight} foreach @{ $c->{Votes} };
221         print DEBUG "counted $c->{Cand} $c->{Total}\n";
222         $c->{History}[$stage-1] = $c->{Total};
223         push @pr, $c;
224     }
225
226     if ($for_compare) {
227         # for comparison with OpenSTV, which always prints
228         # the quota for every elected candidate
229         push @pr, { %$_, Total => $quota } foreach @elected;
230     }
231
232     foreach my $c (reverse sort $display_cmp @pr) {
233         prf "candidate %-10s: %s votes\n", $c->{Cand}, sv $c->{Total};
234     }
235 }
236
237 sub computequota () {
238     my $totalvalid = 0/1;
239     $totalvalid += $_->{Total} foreach values %cands;
240     $quota = floor($totalvalid / (1 + $seats) + 1);
241     prfm "total valid %s\n", sv $totalvalid;
242     prf  "quota       %s\n", sv $quota;
243 }
244
245 sub total_history_cmp () {
246     my $ha = $a->{History};
247     my $hb = $b->{History};
248     my $m = "stage $stage history cmp $a->{Cand} $b->{Cand}";
249     print DEBUG  "$m...\n";
250     foreach my $s (reverse 0 .. $stage-1) {
251         my $d = $ha->[$s] <=> $hb->[$s];
252         next unless $d;
253         print DEBUG "$m => $d (#$s $ha->[$s] $hb->[$s])\n";
254         return $d;
255     }
256     print DEBUG "$m => 0\n";
257     return 0;
258 }
259
260 sub continuing () {
261     grep { !$_->{NonCont} } values %cands;
262 }
263
264 sub select_best_worst ($$$$) {
265     my ($wantcand, $wanttiebreak, $signum, $what) = @_;
266     # $wantcand->($c) = boolish
267     # $wanttiebreak->($total) = boolish
268     # Firstly candidates not meeting $wantcand are ignored
269     # Then we pick the best (worst) candiate by Total (or vote history).
270     # (SLGEO 49(2) and 51(2).
271     # If this does not help then totals are equal and we call wanttiebreak.
272     # If it returns 0 we return alphabetically first CAND.  Otherwise
273     # we tie break.
274
275     my @maybe = grep { $wantcand->($_) } continuing();
276     @maybe = sort total_history_cmp @maybe;
277     @maybe = reverse @maybe if $signum > 0;
278
279     return undef unless @maybe;
280
281     my $nequal = 1;
282
283     for (;;) {
284         my $nextc = $maybe[$nequal];
285         last unless $nextc;
286
287         # Only interested in those who compare equal according to the
288         # history (SLGEO 49(2)); NB our history includes the current
289         # round.
290         
291         last if $signum*($a = $maybe[0], $b = $nextc, total_history_cmp) > 0;
292         $nequal++;
293     }
294
295     if ($nequal > 1 && !$wanttiebreak->($maybe[0]{Total})) {
296         # ... if equal for election we can do them one by one, since
297         # order does not matter (SLGEO 49 talks about `two or more
298         # ... exceeds').
299         $nequal = 1;
300     }
301
302     my $selectcand;
303     if ($nequal > 1) {
304         my @all = sort map { $_->{Cand} } @maybe[0 .. $nequal-1];
305         my $tiekey = $signum > 0 ? 'Win' : 'Lose';
306         $selectcand = $tie{"@all"}{$tiekey};
307         die "need tie break, want $tiekey from @all"
308             unless defined $selectcand;
309         prf "$what %s due to tie break amongst %s\n",
310             $selectcand, "@all";
311     } else {
312         $selectcand = $maybe[0]{Cand};
313         prfm "$what %s\n", $selectcand;
314     }
315
316     return $cands{$selectcand};
317 }
318
319 sub elect_core ($) {
320     my ($c) = @_;
321     prfm "*** ELECT %s \`%s' ***\n", $c->{Cand}, $c->{Desc};
322     $c->{NonCont} = 'Elected';
323     push @elected, $c;
324 }
325
326 $stage = 0;
327
328 for (;;) {
329     $stage++;
330     printf "stage %3d:\n", $stage;
331
332     sortballots @allvotes if $stage == 1;
333
334     my $seats_remain = $seats - @elected;
335
336     prfm "seats remaining %d\n", $seats_remain;
337
338     last unless $seats_remain;
339
340     if (continuing() <= $seats_remain) {
341         foreach my $c (continuing()) {
342             prf "electing %s to fill remaining place(s)\n", $c->{Cand};
343             elect_core $c;
344         }
345         countballots() if $for_compare;
346         last;
347     }
348
349     countballots();
350
351     computequota if $stage == 1;
352
353     my $c = select_best_worst
354         sub { $_->{Total} >= $quota },
355         sub { $_ > $quota },
356         +1, 'electing';
357
358     if ($c) {
359         elect_core $c;
360         votelog $_, "helped elect $c->{Cand}" foreach @{ $c->{Votes} };
361         
362         # SLGEO 48
363         my $surplus = $c->{Total} - $quota;
364
365         if ($surplus <= 0/1) {
366             prf "no surplus\n";
367             next;
368         }
369
370         last if $seats_remain == 1; # don't bother doing more transfers
371
372         my $B = $c->{Total};
373         my %tspr;
374
375         prf "surplus %s\n", sv $surplus;
376
377         foreach my $v (@{ $c->{Votes} }) {
378             my $previously = $v->{TransferredSurplus};
379             push @$previously, $c->{Cand};
380
381             my $A = $surplus * $v->{Weight};
382             my $xfervalue = floor(($A * $F) / $B) / $F;
383             # SLGEO 48(3): we do arithmetic to 5 d3ecimal places,
384             # but always rounding down
385             votelog $v, "transferring with value $xfervalue (A=$A B=$B)";
386             $v->{Weight} = $xfervalue;
387
388             if (defined $tspr{"@$previously"}) {
389                 die unless $tspr{"@$previously"} == $xfervalue;
390             } else {
391                 $tspr{"@$previously"} = $xfervalue;
392                 prfm "transfer value of ballots %20s: %s\n",
393                     "@$previously", sv $xfervalue;
394             }
395         }
396         sortballots @{ $c->{Votes} };
397
398         $c->{Votes} = { }; # will crash if we access it again
399         next;
400     }
401
402     # No-one to elect, must eliminate
403     $c = select_best_worst
404         sub { 1; },
405         sub { 1; },
406         -1, 'eliminating';
407
408     if ($c) {
409         prfm "=== eliminating %s \`%s' ===\n", $c->{Cand}, $c->{Desc};
410         $c->{NonCont} = 'Eliminated';
411
412         sortballots @{ $c->{Votes} };
413         next;
414     }
415
416     die;
417 }
418
419 print "Winners:\n"; 
420
421 if ($for_compare) {
422     foreach my $c (sort { $a->{Cand} cmp $b->{Cand} } @elected) {
423         printf "  %s\n", $c->{Cand};
424     }
425 } else {
426     foreach my $i (0..$#elected) {
427         my $c = $elected[$i];
428         printf " %3d. %-10s %s\n", $i+1, $c->{Cand}, $c->{Desc};
429     }
430 }
431
432 print "done.\n";