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