3 # parses some input about ballots and computes the result according
4 # to Debian Constitution A.6.
6 # usage: .../compute [<input files>...]
7 # (uses stdin if none supplied)
9 # input files can be in any order and should contain lines like:
11 # <votername> :: <PREF>, (<PREF>=<PREF>), <PREF>, ....
12 # V: <tallyprefs> <votername>
13 # <ABBREV> = <description...>
14 # <ABBREV> = <description...> [<rat>:<io>]
15 # <ABBREV> = <description...> [default]
21 # <votername> is any non-whitespace characters
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).
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.
32 # In the "::" form, the commas are optional. Either ( ) or = may
33 # be used to indicate a set of equal preferences.
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.
42 # <rat>:<io> is the majority ratio for the option
44 # <quorum> is the quorum
46 # and also allowed are
49 # blank lines } ignored
50 # lines starting with whitespace }
57 use Graph::Writer::GraphViz;
59 binmode STDIN, 'encoding(UTF-8)';
60 binmode STDOUT, 'encoding(UTF-8)';
61 binmode STDERR, 'encoding(UTF-8)';
72 while (@ARGV && $ARGV[0] =~ /^-/) {
73 local $_ = shift @ARGV;
84 my $choname = shift @_;
85 my $cho = $choices{$choname} = {
86 @_, Index => (scalar @choices)
88 push @choices, $choname;
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\]/) {
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.]+)$/) {
111 } elsif (m/^nodefault$/) {
112 $defcho = { Index => -1 }
119 # $vab[$ia][$ib] = V(A,B)
120 # Actually, it's a list of voters who prefer A to B (A.6(3)(1))
122 # Go through the voters and construct V(A,B)
124 print "\nParsing \`simple' style ballots\n# devotee-tally-begin\n"
126 # actually, we pre-parse them into @invotes_v
127 # since we want to show them as a tally sheet anyway
129 foreach my $iv (@invotes_cc) {
131 foreach my $chn (m/\b\w+\b/g) {
132 next if $choices{$chn};
133 addchoice($chn, Desc => "($chn from voter ballot)");
137 foreach my $iv (@invotes_cc) {
138 my ($voter) = $iv->[0];
143 while (s{\(([^()]+)\)}{
144 my $x = $1; $x =~ s/[ =]+/=/g; $x;
148 print "# normalised $_ ($voter)\n";
150 my @ranks = (1000,) x @choices;
152 foreach (split /\s+/) {
153 foreach (split /=/) {
154 my $cho = $choices{$_};
155 $cho or die "unknown choice $_ ($voter)";
156 my $ix = $cho->{Index};
161 my $vstr = join '', map {
163 $_ < 10 ? (sprintf "%d", $_) :
164 $_ < 36 ? (chr(ord('A') + $_ - 10)) : die
166 print "V: $vstr $voter\n";
167 push @invotes_v, [ $vstr, $voter ];
170 print "# devotee-tally-end\n"
173 print "\nDetermining default option\n";
175 if ($defcho && $defcho->{Index} > -1) {
176 print "default option was specified: $choices[$defcho->{Index}]\n";
178 print "no default option\n";
180 foreach my $try (qw(FD SQ NOTA)) {
181 $defcho = $choices{$try};
185 print "guessed default option: $choices[$defcho->{Index}]\n";
187 print "could not guess default option, assuming there is none\n";
191 my $defi = $defcho->{Index};
192 die "FD has smaj?!" if $defcho->{Smaj};
194 print "\nParsing devotee tally sheet ballots\n"
195 if @invotes_v > @invotes_cc;
197 foreach my $iv (@invotes_v) {
198 my ($votestr,$voter) = @$iv;
200 length $votestr eq @choices or die "wrong vote vector length";
201 my @vs = split //, $votestr;
202 foreach my $ix (0..$#vs) {
206 } elsif ($vchr =~ m/[0-9a-z]/) {
207 $vs[$ix] = ord($vchr);
212 foreach my $ia (0..$#vs) {
213 foreach my $ib ($ia+1..$#vs) {
216 if ($va < $vb) { push @{ $vab[$ia][$ib] }, $voter }
217 elsif ($vb < $va) { push @{ $vab[$ib][$ia] }, $voter }
221 die "voter $voter $@" if $@;
224 print "\nPreference matrix\n";
226 our @ch = map { $choices{$_} } @choices;
228 # Print the counts V(A,B)
229 foreach my $iy (-2..$#ch) {
230 foreach my $ix (-2..$#ch) {
239 } elsif ($ix==-2 && $iy==-2) {
242 printf "%5s ", $choices[$ix];
244 printf "%5s ", $choices[$iy];
246 my $v = \( $vab[$iy][$ix] );
249 printf "%5d ", (scalar @$$v);
260 print "dropping $choices[$i]: $why\n";
261 $ch[$i]{Dropped} = $why;
265 print "\nQuorum A.6(2) (quorum is $quorum)\n";
267 foreach my $i (0..$#choices) {
268 next if $ch[$i]{Dropped};
270 my $v = $vab[$i][$defi];
271 next if $v >= $quorum;
272 drop $i, "quorum ($v < $quorum)";
275 print "\nMajority ratio A.6(3)\n";
277 foreach my $i (0..$#choices) {
278 next if $ch[$i]{Dropped};
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])";
289 print "\nDefeats A.6(4)\n";
291 my $defeats = Graph::Directed->new;
294 return grep { !$ch[$_]{Dropped} } (0..$#ch);
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 $label .= "\n". join ' ', @{ $vab[$ia][$ib] };
309 $label .= "\n/". join ' ', @{ $vab[$ib][$ia] };
310 $defeats->set_edge_attribute($choices[$ia],$choices[$ib],
317 my $v = $vab[ $choices{$ca}{Index} ][ $choices{$cb}{Index} ];
323 my ($def1,$def2) = @_;
324 my ($ca,$cx) = @$def1;
325 my ($cb,$cy) = @$def2;
326 return 1 if chvab($ca, $cx) < chvab($cb, $cy);
327 return 1 if chvab($ca, $cx) == chvab($cb, $cy)
328 && chvab($cx, $ca) > chvab($cy, $cb);
332 our $showg = $defeats->deep_copy();
334 foreach my $ix (0..$#ch) {
336 next unless $cho->{Dropped};
337 $defeats->delete_vertex($choices[$ix]);
345 print "defeats graph: $defeats\n";
347 print "\nTransitive closure A.6(5)\n";
349 my $tdefeats = $defeats->transitive_closure();
351 # this makes the debugging output prettier
352 foreach my $ch (@choices) {
353 $tdefeats->delete_edge($ch,$ch);
355 print "closure graph: $tdefeats\n";
357 print "\nSchwartz set A.6(6)\n";
359 $schwartz = $defeats->copy();
361 foreach my $ia (chremain()) {
362 foreach my $ib (chremain()) {
363 next if $tdefeats->has_edge($choices[$ia],$choices[$ib]);
364 next if !$tdefeats->has_edge($choices[$ib],$choices[$ia]);
365 print "not in Schwartz set: $choices[$ia] because $choices[$ib]\n";
366 $schwartz->delete_vertex($choices[$ia]);
371 print "set: ", (join " ", $schwartz->vertices()), "\n";
373 print "\nDropping weakest defeats A.6(7)\n";
377 foreach my $edge ($schwartz->edges()) {
378 # print " considering @$edge\n";
380 # no weakest edges yet
381 } elsif (weaker($edge, $weakest[0])) {
382 # this edge is weaker than previous weakest, start new set
384 } elsif (weaker($weakest[0], $edge)) {
385 # weakest edge is weaker than this one, ignore this one
388 # weakest edge is exactly as weak as this one, add this one
390 push @weakest, $edge;
393 last unless @weakest;
396 printf "weakest defeats are %d > %d\n",
397 chvab($w->[0], $w->[1]),
398 chvab($w->[1], $w->[0]);
399 foreach my $weakest (@weakest) {
400 my ($ca,$cb) = @$weakest;
401 print "a weakest defeat is $ca > $cb\n";
402 $defeats->delete_edge($ca,$cb);
405 print "\nDefeats within the Schwartz set, go round again\n";
408 print "no defeats within the Schwartz set\n";
409 print "final schwartz set:\n\n";
411 if ($schwartz->vertices() == 1) {
412 print "WINNER IS:\n";
414 print "WINNER IS ONE OF (CASTING VOTE DECIDES):\n";
417 printf " %-5s %s\n", $_, $choices{$_}{Desc}
418 foreach ($schwartz->vertices());
420 if (defined $gfile) {
421 foreach my $cho (values %choices) {
422 my $chn = $choices[$cho->{Index}];
423 my $label = "\\N\n$cho->{Desc}";
424 if ($cho->{Dropped}) {
425 $label .= "\nDropped: $cho->{Dropped}";
427 $showg->set_vertex_attribute($chn, 'label', $label);
430 my $gwriter = new Graph::Writer::GraphViz -format => 'ps';
431 $gwriter->write_graph($showg, $gfile);