#!/usr/bin/perl -w
#
# parses some input about ballots and computes the result according
# to Debian Constitution A.6.
#
# usage: .../compute [...]
# (uses stdin if none supplied)
#
# input files can be in any order and should contain lines like:
#
# :: , (=), , ....
# V:
# =
# = [:]
# = [default]
# nodefault
# quorum =
#
# where
#
# is any non-whitespace characters
#
# and are abbreviations for choices on the ballot.
# They must be ASCII alphanumeric. Numeric preferences are
# not recommended as they are confusing (particularly when
# tally sheets are in use).
#
# It is best to avoid FD, SQ and NOTA except for the default
# option; if no default option is specified, it will default
# to one of these unless a "nodefault" line is found.
#
# In the "::" form, the commas are optional. Either ( ) or = may
# be used to indicate a set of equal preferences.
#
# is a tally sheet preference order: that is,
# a single uppercase base36 digit for each ballot choice,
# (in the order they were specified by "=" lines), giving
# the voter's preference rank for that option. The numbers
# need not be distinct or contiguous. "-" may be used for
# unranked preferences.
#
# : is the majority ratio for the option
#
# is the quorum
#
# and also allowed are
#
# #-comments } all
# blank lines } ignored
# lines starting with whitespace }
use strict;
use utf8;
use autodie;
use Graph::Directed;
use Graph::Writer::GraphViz;
binmode STDIN, 'encoding(UTF-8)';
binmode STDOUT, 'encoding(UTF-8)';
binmode STDERR, 'encoding(UTF-8)';
our @choices;
our %choices;
our @invotes_v;
our @invotes_cc;
our $defcho;
our $quorum = 0;
our $gfile;
while (@ARGV && $ARGV[0] =~ /^-/) {
local $_ = shift @ARGV;
if (m/^--?$/) {
last;
} elsif (s/^-g//) {
$gfile = $_;
} else {
die "bad usage\n";
}
}
sub addchoice {
my $choname = shift @_;
my $cho = $choices{$choname} = {
@_, Index => (scalar @choices)
};
push @choices, $choname;
return $cho;
}
while (<>) {
s/\s+$//;
next if m/^\s*\#/;
next unless m/\S/;
next if m/^\s/;
if (m/^([A-Z0-9]+)\s*\=\s*(\S.*)$/) {
my ($choname, $desc) = ($1,$2);
my $cho = addchoice($choname, Desc => $desc);
if ($desc =~ m/\[(\d+):(\d+)\]/) {
$cho->{Smaj} = [$1,$2];
} elsif ($desc =~ m/\[default\]/) {
$defcho = $cho;
}
} elsif (m/^V:\s+(\S+)\s+(\S.*)/) {
push @invotes_v, [ $1, $2 ];
} elsif (m/^(\S+)\s*\:\:\s*/) {
push @invotes_cc, [ $1, "$'" ];
} elsif (m/^quorum = ([0-9.]+)$/) {
$quorum = $1+0.0;
} elsif (m/^nodefault$/) {
$defcho = { Index => -1 }
} else {
die "invalid input";
}
}
our @vab;
# $vab[$ia][$ib] = V(A,B)
# Actually, it's a list of voters who prefer A to B (A.6(3)(1))
# Go through the voters and construct V(A,B)
print "\nParsing \`simple' style ballots\n# devotee-tally-begin\n"
if @invotes_cc;
# actually, we pre-parse them into @invotes_v
# since we want to show them as a tally sheet anyway
foreach my $iv (@invotes_cc) {
$_ = uc $iv->[1];
foreach my $chn (m/\b\w+\b/g) {
next if $choices{$chn};
addchoice($chn, Desc => "($chn from voter ballot)");
}
}
foreach my $iv (@invotes_cc) {
my ($voter) = $iv->[0];
$_ = uc $iv->[1];
s/\t/ /g;
s/\,/ /g;
while (s{\(([^()]+)\)}{
my $x = $1; $x =~ s/[ =]+/=/g; $x;
}ge) { }
s/[ =]*=[ =*]/=/g;
s/\s+/ /g;
print "# normalised $_ ($voter)\n";
my @ranks = (1000,) x @choices;
my $rank = 1;
foreach (split /\s+/) {
foreach (split /=/) {
my $cho = $choices{$_};
$cho or die "unknown choice $_ ($voter)";
my $ix = $cho->{Index};
$ranks[$ix] = $rank;
}
$rank++;
}
my $vstr = join '', map {
$_ == 1000 ? "-" :
$_ < 10 ? (sprintf "%d", $_) :
$_ < 36 ? (chr(ord('A') + $_ - 10)) : die
} @ranks;
print "V: $vstr $voter\n";
push @invotes_v, [ $vstr, $voter ];
}
print "# devotee-tally-end\n"
if @invotes_cc;
print "\nDetermining default option\n";
if ($defcho && $defcho->{Index} > -1) {
print "default option was specified: $choices[$defcho->{Index}]\n";
} elsif ($defcho) {
print "no default option\n";
} else {
foreach my $try (qw(FD SQ NOTA)) {
$defcho = $choices{$try};
last if $defcho;
}
if ($defcho) {
print "guessed default option: $choices[$defcho->{Index}]\n";
} else {
print "could not guess default option, assuming there is none\n";
}
}
my $defi = $defcho->{Index};
die "FD has smaj?!" if $defcho->{Smaj};
print "\nParsing devotee tally sheet ballots\n"
if @invotes_v > @invotes_cc;
foreach my $iv (@invotes_v) {
my ($votestr,$voter) = @$iv;
eval {
length $votestr eq @choices or die "wrong vote vector length";
my @vs = split //, $votestr;
foreach my $ix (0..$#vs) {
my $vchr = $vs[$ix];
if ($vchr eq '-') {
$vs[$ix] = 1000;
} elsif ($vchr =~ m/[0-9A-Z]/) {
$vs[$ix] = ord($vchr);
} else {
die "bad vote char";
}
}
foreach my $ia (0..$#vs) {
foreach my $ib ($ia+1..$#vs) {
my $va = $vs[$ia];
my $vb = $vs[$ib];
if ($va < $vb) { push @{ $vab[$ia][$ib] }, $voter }
elsif ($vb < $va) { push @{ $vab[$ib][$ia] }, $voter }
}
}
};
die "voter $voter $@" if $@;
}
print "\nPreference matrix\n";
our @ch = map { $choices{$_} } @choices;
# Print the counts V(A,B)
foreach my $iy (-2..$#ch) {
foreach my $ix (-2..$#ch) {
if ($iy==-1) {
if ($ix==-1) {
printf "+";
} else {
printf "------";
}
} elsif ($ix==-1) {
printf "|";
} elsif ($ix==-2 && $iy==-2) {
printf "V(Y,X)";
} elsif ($iy==-2) {
printf "%5s ", $choices[$ix];
} elsif ($ix==-2) {
printf "%5s ", $choices[$iy];
} else {
my $v = \( $vab[$iy][$ix] );
$$v ||= [ ];
if (@$$v) {
printf "%5d ", (scalar @$$v);
} else {
printf "%5s ", "";
}
}
}
printf "\n";
}
sub drop ($$) {
my ($i,$why) = @_;
print "dropping $choices[$i]: $why\n";
$ch[$i]{Dropped} = $why;
}
if (defined $defi) {
print "\nQuorum A.6(2) (quorum is $quorum)\n";
foreach my $i (0..$#choices) {
next if $ch[$i]{Dropped};
next if $i == $defi;
my $v = $vab[$i][$defi];
next if $v >= $quorum;
drop $i, "quorum ($v < $quorum)";
}
print "\nMajority ratio A.6(3)\n";
foreach my $i (0..$#choices) {
next if $ch[$i]{Dropped};
next if $i == $defi;
my $majr = $ch[$i]{Smaj};
$majr ||= [1,1]; # A.6(3)(3)
my $vad = scalar @{ $vab[$i][$defi] };
my $vda = scalar @{ $vab[$defi][$i] };
next if $vad * $majr->[1] > $vda * $majr->[0];
drop $i, "majority ratio ($vad:$vda <= $majr->[1]:$majr->[0])";
}
}
print "\nDefeats A.6(4)\n";
my $defeats = Graph::Directed->new;
sub chremain () {
return grep { !$ch[$_]{Dropped} } (0..$#ch);
}
foreach my $ia (0..$#ch) {
$defeats->add_vertex($choices[$ia]);
foreach my $ib (0..$#ch) {
my $vab = scalar @{ $vab[$ia][$ib] };
my $vba = scalar @{ $vab[$ib][$ia] };
next unless $vab > $vba;
my $diff = $vab - $vba;
print "defeat: $choices[$ia] beats $choices[$ib]",
" ($vab > $vba = +$diff)\n";
$defeats->add_edge($choices[$ia],$choices[$ib]);
my $label = "$diff($vab:$vba)";
if (@invotes_v < 10) {
$label .= "\n". join ' ', @{ $vab[$ia][$ib] };
$label .= "\n/". join ' ', @{ $vab[$ib][$ia] };
}
$defeats->set_edge_attribute($choices[$ia],$choices[$ib],
label => $label);
}
}
sub chvab ($$) {
my ($ca,$cb) = @_;
my $v = $vab[ $choices{$ca}{Index} ][ $choices{$cb}{Index} ];
return scalar @$v;
}
sub weaker ($$) {
# A.6(7)(1)
my ($def1,$def2) = @_;
my ($ca,$cx) = @$def1;
my ($cb,$cy) = @$def2;
return 1 if chvab($ca, $cx) < chvab($cb, $cy);
return 1 if chvab($ca, $cx) == chvab($cb, $cy)
&& chvab($cx, $ca) > chvab($cy, $cb);
return 0;
}
our $showg = $defeats->deep_copy();
foreach my $ix (0..$#ch) {
my $cho = $ch[$ix];
next unless $cho->{Dropped};
$defeats->delete_vertex($choices[$ix]);
}
our $schwartz;
for (my $dropiter = 1; ; $dropiter++) {
# loop from A6(5)
print "defeats graph: $defeats\n";
print "\nTransitive closure A.6(5) (iteration $dropiter)\n";
my $tdefeats = $defeats->transitive_closure();
# this makes the debugging output prettier
foreach my $ch (@choices) {
$tdefeats->delete_edge($ch,$ch);
}
print "closure graph: $tdefeats\n";
print "\nSchwartz set A.6(6)\n";
$schwartz = $defeats->copy();
foreach my $ia (chremain()) {
foreach my $ib (chremain()) {
next if $tdefeats->has_edge($choices[$ia],$choices[$ib]);
next if !$tdefeats->has_edge($choices[$ib],$choices[$ia]);
print "not in Schwartz set: $choices[$ia] because $choices[$ib]\n";
$schwartz->delete_vertex($choices[$ia]);
last;
}
}
print "set: ", (join " ", $schwartz->vertices()), "\n";
print "\nDropping weakest defeats A.6(7)\n";
our @weakest = ();
foreach my $edge ($schwartz->edges()) {
# print " considering @$edge\n";
if (!@weakest) {
# no weakest edges yet
} elsif (weaker($edge, $weakest[0])) {
# this edge is weaker than previous weakest, start new set
@weakest = ();
} elsif (weaker($weakest[0], $edge)) {
# weakest edge is weaker than this one, ignore this one
next;
} else {
# weakest edge is exactly as weak as this one, add this one
}
push @weakest, $edge;
}
last unless @weakest;
my $w = $weakest[0];
printf "weakest defeats are %d > %d\n",
chvab($w->[0], $w->[1]),
chvab($w->[1], $w->[0]);
foreach my $weakest (@weakest) {
my ($ca,$cb) = @$weakest;
print "a weakest defeat is $ca > $cb\n";
$defeats->delete_edge($ca,$cb);
my $label = $showg->get_edge_attribute($ca,$cb,'label');
$label .= "\ndropped - weakest in iter.$dropiter";
$showg->set_edge_attribute($ca,$cb,'label',$label);
$showg->set_edge_attribute($ca,$cb,'style','dotted');
$showg->set_edge_attribute($ca,$cb,'graphviz',{constraint=>0});
}
print "\nDefeats within the Schwartz set, go round again\n";
}
print "no defeats within the Schwartz set\n";
print "final schwartz set:\n\n";
my $winxlabel;
if ($schwartz->vertices() == 1) {
print "WINNER IS:\n";
$winxlabel = "winner";
} else {
print "WINNER IS ONE OF (CASTING VOTE DECIDES):\n";
$winxlabel = "potential winner";
}
printf " %-5s %s\n", $_, $choices{$_}{Desc}
foreach ($schwartz->vertices());
if (defined $gfile) {
foreach my $cho (values %choices) {
my $chn = $choices[$cho->{Index}];
my $label = "$chn\n$cho->{Desc}";
if ($cho->{Dropped}) {
$label .= "\nDropped: $cho->{Dropped}";
}
if ($schwartz->has_vertex($chn)) {
$label .= "\n$winxlabel";
}
$showg->set_vertex_attribute($chn, 'label', $label);
}
my $gwriter = new Graph::Writer::GraphViz -format => 'ps';
$gwriter->write_graph($showg, $gfile);
}
print ".\n";
#p %choices;
#p @vab;