chiark / gitweb /
compute: handle >9 candidates properly
[appendix-a6.git] / compute
1 #!/usr/bin/perl -w
2 #
3 # parses some input about ballots and computes the result according
4 # to Debian Constitution A.6.
5 #
6 # usage: .../compute [<input files>...]
7 #  (uses stdin if none supplied)
8 #
9 # input files can be in any order and should contain lines like:
10 #
11 #   <votername> :: <PREF>, (<PREF>=<PREF>), <PREF>, ....
12 #   V: <tallyprefs> <votername>
13 #   <ABBREV> = <description...>
14 #   <ABBREV> = <description...> [<rat>:<io>]
15 #   <ABBREV> = <description...> [default]
16 #   nodefault
17 #   quorum = <quorum>
18 #
19 # where
20 #
21 #   <votername> is any non-whitespace characters
22 #
23 #   <ABBREV> and <PREF> are abbreviations for choices on the ballot.
24 #      They must be ASCII alphanumeric.  Numeric preferences are
25 #      not recommended as they are confusing (particularly when
26 #      tally sheets are in use).
27 #
28 #      It is best to avoid FD, SQ and NOTA except for the default
29 #      option; if no default option is specified, it will default
30 #      to one of these unless a "nodefault" line is found.
31 #
32 #      In the "::" form, the commas are optional.  Either ( ) or = may
33 #      be used to indicate a set of equal preferences.
34 #
35 #   <tallyprefs> is a tally sheet preference order: that is,
36 #      a single uppercase base36 digit for each ballot choice,
37 #      (in the order they were specified by "=" lines), giving
38 #      the voter's preference rank for that option.  The numbers
39 #      need not be distinct or contiguous.  "-" may be used for
40 #      unranked preferences.
41 #
42 #   <rat>:<io> is the majority ratio for the option
43 #
44 #   <quorum> is the quorum
45 #
46 # and also allowed are
47 #
48 #   #-comments                            } all
49 #   blank lines                           } ignored
50 #   lines starting with whitespace        }
51
52 use strict;
53 use utf8;
54 use autodie;
55
56 use Graph::Directed;
57 use Graph::Writer::GraphViz;
58
59 binmode STDIN, 'encoding(UTF-8)';
60 binmode STDOUT, 'encoding(UTF-8)';
61 binmode STDERR, 'encoding(UTF-8)';
62
63 our @choices;
64 our %choices;
65 our @invotes_v;
66 our @invotes_cc;
67 our $defcho;
68 our $quorum = 0;
69
70 our $gfile;
71
72 while (@ARGV && $ARGV[0] =~ /^-/) {
73     local $_ = shift @ARGV;
74     if (m/^--?$/) {
75         last;
76     } elsif (s/^-g//) {
77         $gfile = $_;
78     } else {
79         die "bad usage\n";
80     }
81 }
82
83 sub addchoice {
84     my $choname = shift @_;
85     my $cho = $choices{$choname} = {
86         @_, Index => (scalar @choices)
87     };
88     push @choices, $choname;
89     return $cho;
90 }
91
92 while (<>) {
93     s/\s+$//;
94     next if m/^\s*\#/;
95     next unless m/\S/;
96     next if m/^\s/;
97     if (m/^([A-Z0-9]+)\s*\=\s*(\S.*)$/) {
98         my ($choname, $desc) = ($1,$2);
99         my $cho = addchoice($choname, Desc => $desc);
100         if ($desc =~ m/\[(\d+):(\d+)\]/) {
101             $cho->{Smaj} = [$1,$2];
102         } elsif ($desc =~ m/\[default\]/) {
103             $defcho = $cho;
104         }
105     } elsif (m/^V:\s+(\S+)\s+(\S.*)/) {
106         push @invotes_v, [ $1, $2 ];
107     } elsif (m/^(\S+)\s*\:\:\s*/) {
108         push @invotes_cc, [ $1, "$'" ];
109     } elsif (m/^quorum = ([0-9.]+)$/) {
110         $quorum = $1+0.0;
111     } elsif (m/^nodefault$/) {
112         $defcho = { Index => -1 }
113     } else {
114         die "invalid input";
115     }
116 }
117
118 our @vab;
119 # $vab[$ia][$ib] = V(A,B)
120 # Actually, it's a list of voters who prefer A to B (A.6(3)(1))
121
122 # Go through the voters and construct V(A,B)
123
124 print "\nParsing \`simple' style ballots\n# devotee-tally-begin\n"
125         if @invotes_cc;
126 # actually, we pre-parse them into @invotes_v
127 # since we want to show them as a tally sheet anyway
128
129 foreach my $iv (@invotes_cc) {
130     $_ = uc $iv->[1];
131     foreach my $chn (m/\b\w+\b/g) {
132         next if $choices{$chn};
133         addchoice($chn, Desc => "($chn from voter ballot)");
134     }
135 }
136
137 foreach my $iv (@invotes_cc) {
138     my ($voter) = $iv->[0];
139     $_ = uc $iv->[1];
140
141     s/\t/ /g;
142     s/\,/ /g;
143     while (s{\(([^()]+)\)}{
144         my $x = $1; $x =~ s/[ =]+/=/g; $x;
145     }ge) { }
146     s/[ =]*=[ =*]/=/g;
147     s/\s+/ /g;
148     print "# normalised $_ ($voter)\n";
149
150     my @ranks = (1000,) x @choices;
151     my $rank = 1;
152     foreach (split /\s+/) {
153         foreach (split /=/) {
154             my $cho = $choices{$_};
155             $cho or die "unknown choice $_ ($voter)";
156             my $ix = $cho->{Index};
157             $ranks[$ix] = $rank;
158         }
159         $rank++;
160     }
161     my $vstr = join '', map {
162         $_ == 1000 ? "-" :
163         $_ < 10 ? (sprintf "%d", $_) :
164         $_ < 36 ? (chr(ord('A') + $_ - 10)) : die
165     } @ranks;
166     print "V: $vstr $voter\n";
167     push @invotes_v, [ $vstr, $voter ];
168 }
169
170 print "# devotee-tally-end\n"
171         if @invotes_cc;
172
173 print "\nDetermining default option\n";
174
175 if ($defcho && $defcho->{Index} > -1) {
176     print "default option was specified: $choices[$defcho->{Index}]\n";
177 } elsif ($defcho) {
178     print "no default option\n";
179 } else {
180     foreach my $try (qw(FD SQ NOTA)) {
181         $defcho = $choices{$try};
182         last if $defcho;
183     }
184     if ($defcho) {
185         print "guessed default option: $choices[$defcho->{Index}]\n";
186     } else {
187         print "could not guess default option, assuming there is none\n";
188     }
189 }
190
191 my $defi = $defcho->{Index};
192 die "FD has smaj?!" if $defcho->{Smaj};
193
194 print "\nParsing devotee tally sheet ballots\n" 
195     if @invotes_v > @invotes_cc;
196
197 foreach my $iv (@invotes_v) {
198     my ($votestr,$voter) = @$iv;
199     eval {
200         length $votestr eq @choices or die "wrong vote vector length";
201         my @vs = split //, $votestr;
202         foreach my $ix (0..$#vs) {
203             my $vchr = $vs[$ix];
204             if ($vchr eq '-') {
205                 $vs[$ix] = 1000;
206             } elsif ($vchr =~ m/[0-9A-Z]/) {
207                 $vs[$ix] = ord($vchr);
208             } else {
209                 die "bad vote char";
210             }
211         }
212         foreach my $ia (0..$#vs) {
213             foreach my $ib ($ia+1..$#vs) {
214                 my $va = $vs[$ia];
215                 my $vb = $vs[$ib];
216                 if ($va < $vb) { push @{ $vab[$ia][$ib] }, $voter }
217                 elsif ($vb < $va) { push @{ $vab[$ib][$ia] }, $voter }
218             }
219         }
220     };
221     die "voter $voter $@" if $@;
222 }
223
224 print "\nPreference matrix\n";
225
226 our @ch = map { $choices{$_} } @choices;
227
228 # Print the counts V(A,B)
229 foreach my $iy (-2..$#ch) {
230     foreach my $ix (-2..$#ch) {
231         if ($iy==-1) {
232             if ($ix==-1) {
233                 printf "+";
234             } else {
235                 printf "------";
236             }
237         } elsif ($ix==-1) {
238             printf "|";
239         } elsif ($ix==-2 && $iy==-2) {
240             printf "V(Y,X)";
241         } elsif ($iy==-2) {
242             printf "%5s ", $choices[$ix];
243         } elsif ($ix==-2) {
244             printf "%5s ", $choices[$iy];
245         } else {
246             my $v = \( $vab[$iy][$ix] );
247             $$v ||= [ ];
248             if (@$$v) {
249                 printf "%5d ", (scalar @$$v);
250             } else {
251                 printf "%5s ", "";
252             }
253         }
254     }
255     printf "\n";
256 }
257
258 sub drop ($$) {
259     my ($i,$why) = @_;
260     print "dropping $choices[$i]: $why\n";
261     $ch[$i]{Dropped} = $why;
262 }
263
264 if (defined $defi) {
265     print "\nQuorum A.6(2) (quorum is $quorum)\n";
266
267     foreach my $i (0..$#choices) {
268         next if $ch[$i]{Dropped};
269         next if $i == $defi;
270         my $v = $vab[$i][$defi];
271         next if $v >= $quorum;
272         drop $i, "quorum ($v < $quorum)";
273     }
274
275     print "\nMajority ratio A.6(3)\n";
276
277     foreach my $i (0..$#choices) {
278         next if $ch[$i]{Dropped};
279         next if $i == $defi;
280         my $majr = $ch[$i]{Smaj};
281         $majr ||= [1,1]; # A.6(3)(3)
282         my $vad = scalar @{ $vab[$i][$defi] };
283         my $vda = scalar @{ $vab[$defi][$i] };
284         next if $vad * $majr->[1] > $vda * $majr->[0];
285         drop $i, "majority ratio ($vad:$vda <= $majr->[1]:$majr->[0])";
286     }
287 }
288
289 print "\nDefeats A.6(4)\n";
290
291 my $defeats = Graph::Directed->new;
292
293 sub chremain () {
294     return grep { !$ch[$_]{Dropped} } (0..$#ch);
295 }
296
297 foreach my $ia (0..$#ch) {
298     $defeats->add_vertex($choices[$ia]);
299     foreach my $ib (0..$#ch) {
300         my $vab = scalar @{ $vab[$ia][$ib] };
301         my $vba = scalar @{ $vab[$ib][$ia] };
302         next unless $vab > $vba;
303         my $diff = $vab - $vba;
304         print "defeat: $choices[$ia] beats $choices[$ib]",
305             " ($vab > $vba = +$diff)\n";
306         $defeats->add_edge($choices[$ia],$choices[$ib]);
307         my $label = "$diff($vab:$vba)";
308         if (@invotes_v < 10) {
309             $label .= "\n". join ' ', @{ $vab[$ia][$ib] };
310             $label .= "\n/". join ' ', @{ $vab[$ib][$ia] };
311         }
312         $defeats->set_edge_attribute($choices[$ia],$choices[$ib],
313                                      label => $label);
314     }
315 }
316
317 sub chvab ($$) {
318     my ($ca,$cb) = @_;
319     my $v = $vab[ $choices{$ca}{Index} ][ $choices{$cb}{Index} ];
320     return scalar @$v;
321 }
322
323 sub weaker ($$) {
324     # A.6(7)(1)
325     my ($def1,$def2) = @_;
326     my ($ca,$cx) = @$def1;
327     my ($cb,$cy) = @$def2;
328     return 1 if chvab($ca, $cx) < chvab($cb, $cy);
329     return 1 if chvab($ca, $cx) == chvab($cb, $cy)
330               && chvab($cx, $ca) > chvab($cy, $cb);
331     return 0;
332 }
333
334 our $showg = $defeats->deep_copy();
335
336 foreach my $ix (0..$#ch) {
337     my $cho = $ch[$ix];
338     next unless $cho->{Dropped};
339     $defeats->delete_vertex($choices[$ix]);
340 }
341
342 our $schwartz;
343
344 for (my $dropiter = 1; ; $dropiter++) {
345     # loop from A6(5)
346
347     print "defeats graph: $defeats\n";
348
349     print "\nTransitive closure A.6(5) (iteration $dropiter)\n";
350
351     my $tdefeats = $defeats->transitive_closure();
352
353     # this makes the debugging output prettier
354     foreach my $ch (@choices) {
355         $tdefeats->delete_edge($ch,$ch);
356     }
357     print "closure graph: $tdefeats\n";
358
359     print "\nSchwartz set A.6(6)\n";
360     
361     $schwartz = $defeats->copy();
362
363     foreach my $ia (chremain()) {
364         foreach my $ib (chremain()) {
365             next if $tdefeats->has_edge($choices[$ia],$choices[$ib]);
366             next if !$tdefeats->has_edge($choices[$ib],$choices[$ia]);
367             print "not in Schwartz set: $choices[$ia] because $choices[$ib]\n";
368             $schwartz->delete_vertex($choices[$ia]);
369             last;
370         }
371     }
372
373     print "set: ", (join " ", $schwartz->vertices()), "\n";
374
375     print "\nDropping weakest defeats A.6(7)\n";
376
377     our @weakest = ();
378
379     foreach my $edge ($schwartz->edges()) {
380 #       print " considering @$edge\n";
381         if (!@weakest) {
382             # no weakest edges yet
383         } elsif (weaker($edge, $weakest[0])) {
384             # this edge is weaker than previous weakest, start new set
385             @weakest = ();
386         } elsif (weaker($weakest[0], $edge)) {
387             # weakest edge is weaker than this one, ignore this one
388             next;
389         } else {
390             # weakest edge is exactly as weak as this one, add this one
391         }
392         push @weakest, $edge;
393     }
394
395     last unless @weakest;
396
397     my $w = $weakest[0];
398     printf "weakest defeats are %d > %d\n", 
399         chvab($w->[0], $w->[1]),
400         chvab($w->[1], $w->[0]);
401     foreach my $weakest (@weakest) {
402         my ($ca,$cb) = @$weakest;
403         print "a weakest defeat is $ca > $cb\n";
404         $defeats->delete_edge($ca,$cb);
405         my $label = $showg->get_edge_attribute($ca,$cb,'label');
406         $label .= "\ndropped - weakest in iter.$dropiter";
407         $showg->set_edge_attribute($ca,$cb,'label',$label);
408         $showg->set_edge_attribute($ca,$cb,'style','dotted');
409         $showg->set_edge_attribute($ca,$cb,'graphviz',{constraint=>0});
410     }
411
412     print "\nDefeats within the Schwartz set, go round again\n";
413 }
414
415 print "no defeats within the Schwartz set\n";
416 print "final schwartz set:\n\n";
417
418 my $winxlabel;
419 if ($schwartz->vertices() == 1) {
420     print "WINNER IS:\n";
421     $winxlabel = "winner";
422 } else {
423     print "WINNER IS ONE OF (CASTING VOTE DECIDES):\n";
424     $winxlabel = "potential winner";
425 }
426
427 printf "    %-5s %s\n", $_, $choices{$_}{Desc}
428     foreach ($schwartz->vertices());
429
430 if (defined $gfile) {
431     foreach my $cho (values %choices) {
432         my $chn = $choices[$cho->{Index}];
433         my $label = "\\$chn\n$cho->{Desc}";
434         if ($cho->{Dropped}) {
435             $label .= "\nDropped: $cho->{Dropped}";
436         }
437         if ($schwartz->has_vertex($chn)) {
438             $label .= "\n$winxlabel";
439         }
440         $showg->set_vertex_attribute($chn, 'label', $label);
441     }
442
443     my $gwriter = new Graph::Writer::GraphViz -format => 'ps';
444     $gwriter->write_graph($showg, $gfile);
445 }
446
447 print ".\n";
448
449 #p %choices;
450 #p @vab;