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