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