/[gentoo-src]/votify/Votify.pm
Gentoo

Contents of /votify/Votify.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.2 - (show annotations) (download) (as text)
Mon May 16 04:03:46 2005 UTC (13 years, 5 months ago) by agriffis
Branch: MAIN
Changes since 1.1: +387 -137 lines
File MIME type: text/x-perl
add first pass at countify --rank

1 # $Id: votify,v 1.3 2005/05/09 23:12:02 agriffis Exp $
2 #
3 # Copyright 2005 Gentoo Foundation
4 # Distributed under the terms of the GNU General Public License v2
5 #
6 # votify.pm: common classes for votify and countify
7 #
8
9 package Votify;
10
11 use POSIX;
12 use List::Util;
13 use strict;
14
15 our ($datadir) = '/home/agriffis/elections';
16 (our $zero = $0) =~ s,.*/,,;
17
18 sub import {
19 my ($class, $mode) = @_;
20 $Votify::mode = $mode;
21 }
22
23 ######################################################################
24 # OfficialList
25 ######################################################################
26
27 package OfficialList;
28
29 sub new {
30 my ($class, $election) = @_;
31 my ($self) = {
32 election => $election,
33 officials => [],
34 };
35
36 # no point in waiting to load
37 open(F, "<$Votify::datadir/officials-$election")
38 or die("failed to open officials file");
39 chomp(@{$self->{'officials'}} = <F>);
40 close(F);
41
42 bless $self, $class;
43 return $self;
44 }
45
46 sub officials {
47 my ($self) = @_;
48 @{$self->{'officials'}};
49 }
50
51 ######################################################################
52 # VoterList
53 ######################################################################
54
55 package VoterList;
56
57 sub new {
58 my ($class, $election) = @_;
59 my (@voterlist, $r);
60 my ($self) = {
61 election => $election,
62 default_filename => "$Votify::datadir/confs-$election",
63 filename => '',
64 voters => {}, # confnum => voter
65 confs => {}, # voter => confnum
66 };
67
68 # no point in waiting to load
69 open(F, "<$Votify::datadir/voters-$election")
70 or die("failed to open voters file");
71 chomp(@voterlist = <F>);
72 close(F);
73
74 # assign confirmation numbers randomly
75 for my $v (@voterlist) {
76 do { $r = int rand 0xffff } while exists $self->{'voters'}{$r};
77 $self->{'voters'}{$r} = $v;
78 $self->{'confs'}{$v} = $r;
79 }
80
81 unless (keys %{$self->{'voters'}} == keys %{$self->{'confs'}}) {
82 die("discrepancy deteced in VoterList");
83 }
84
85 bless $self, $class;
86 return $self;
87 }
88
89 sub confs {
90 my ($self) = @_;
91 sort keys %{$self->{'voters'}};
92 }
93
94 sub voters {
95 my ($self) = @_;
96 sort keys %{$self->{'confs'}};
97 }
98
99 sub getvoter {
100 my ($self, $conf) = @_;
101 return $self->{'voters'}{$conf};
102 }
103
104 sub getconf {
105 my ($self, $voter) = @_;
106 return $self->{'confs'}{$voter};
107 }
108
109 sub write {
110 my ($self, $filename) = @_;
111
112 $filename ||= $self->{'default_filename'};
113 $self->{'filename'} = $filename;
114
115 if (-f $filename) {
116 die "$filename already exists; please remove it first";
117 }
118
119 open(F, ">$filename") or die("can't write to $filename");
120 for my $c ($self->confs) {
121 printf F "%04x %s\n", $c, $self->getvoter($c);
122 }
123 close F;
124 }
125
126 ######################################################################
127 # MasterBallot
128 ######################################################################
129
130 package MasterBallot;
131
132 use Data::Dumper;
133
134 sub new {
135 my ($class, $election, $vl) = @_;
136 my ($self) = {
137 election => $election,
138 default_filename => "$Votify::datadir/master-$election",
139 filename => '',
140 voterlist => $vl,
141 ballots => {}, # indexed by conf num
142 candidates => undef, # indexed by long name
143 table => undef, # indexed by row+column
144 };
145
146 bless $self, $class;
147 return $self;
148 }
149
150 sub collect {
151 my ($self, @voters) = @_;
152 my ($c, $v, $home, @pwentry);
153
154 for my $v (@voters) {
155 unless (defined ($c = $self->{'voterlist'}->getconf($v))) {
156 die "$v does not correspond to any confirmation number";
157 }
158
159 @pwentry = getpwnam($v);
160 unless (@pwentry) {
161 print STDERR "Warning: unknown user: $v\n";
162 next;
163 }
164
165 $home = $pwentry[7];
166 unless (-d $home) {
167 print STDERR "Warning: no directory: $home\n";
168 next;
169 }
170
171 if (-f "$home/.ballot-$self->{election}-submitted") {
172 my ($b) = Ballot->new($self->{'election'});
173 $b->read("$home/.ballot-$self->{election}-submitted");
174 if ($b->verify) {
175 print STDERR "Errors found in ballot: $v\n";
176 next;
177 }
178 $self->{'ballots'}{$c} = $b;
179 }
180 elsif (-f "$home/.ballot-$self->{election}") {
181 print STDERR "Warning: $v did not submit their ballot\n";
182 }
183 }
184 }
185
186 sub write {
187 my ($self, $filename) = @_;
188
189 $filename ||= $self->{'default_filename'};
190 $self->{'filename'} = $filename;
191
192 if (-f $filename) {
193 die "$filename already exists; please remove it first";
194 }
195
196 open(F, ">$filename") or die("can't write to $filename");
197 for my $c (sort keys %{$self->{'ballots'}}) {
198 printf F "--------- confirmation %04x ---------\n", $c;
199 print F $self->{'ballots'}{$c}->to_s
200 }
201 close F;
202 }
203
204 sub read {
205 my ($self, $filename) = @_;
206 my ($election, $entries) = $self->{'election'};
207
208 $filename ||= $self->{'default_filename'};
209 $self->{'filename'} = $filename;
210
211 open(F, "<$filename") or die("can't read $filename");
212 { local $/ = undef; $entries = <F>; }
213 for my $e (split /^--------- confirmation /m, $entries) {
214 next unless $e; # skip the first zero-length record
215 unless ($e =~ /^([[:xdigit:]]{4}) ---------\n(.*)$/s) {
216 die "error parsing entry:\n$e";
217 }
218 my ($c, $s, $b) = ($1, $2, Ballot->new($election));
219 $b->from_s($s);
220 $self->{'ballots'}{hex($c)} = $b;
221 }
222 }
223
224 sub generate_candidates {
225 my ($self) = @_;
226 my ($B, @C, $s);
227
228 # nb: would need to scan all the ballots to support write-ins
229 $B = Ballot->new($self->{'election'});
230 $B->populate;
231 @C = sort @{$B->choices};
232 for my $c (map $_->[0], @C) {
233 for (my $i=1; $i<=length($c); $i++) {
234 $s = substr $c, 0, $i;
235 last unless grep(/^$s/, @C) > 1;
236 }
237 $self->{'candidates'}{$c} = $s;
238 }
239 }
240
241 sub tabulate {
242 my ($self) = @_;
243 my (@candidates); # full candidate list
244 my (%table); # resulting table, row.colum where row defeats column
245 $self->{'table'} = \%table;
246
247 $self->generate_candidates unless $self->{'candidates'};
248 @candidates = keys %{$self->{'candidates'}};
249 for my $c1 (@candidates) {
250 for my $c2 (@candidates) {
251 $table{"$c1+$c2"} = 0;
252 }
253 $table{"$c1+$c1"} = '-';
254 }
255
256 # generate the table first;
257 # walk through the ballots, tallying the rankings expressed by each ballot
258 for my $b (values %{$self->{'ballots'}}) {
259 my (@choices, %ranks);
260
261 #print "looking at ballot:\n", $b->to_s, "\n";
262
263 # first determine the ranking of each candidate. default ranking is
264 # scalar @candidates.
265 @choices = @{$b->choices};
266 @ranks{@candidates} = (scalar @candidates) x @candidates;
267 #print "ranks before determining:\n", Dumper(\%ranks);
268 for (my $i = 0; $i < @choices; $i++) {
269 @ranks{@{$choices[$i]}} = ($i) x @{$choices[$i]};
270 }
271 #print "ranks after determining:\n", Dumper(\%ranks);
272
273 # second add the results of all the pairwise races into our table
274 for my $c1 (@candidates) {
275 for my $c2 (@candidates) {
276 next if $c1 eq $c2;
277 $table{"$c1+$c2"}++ if $ranks{$c1} < $ranks{$c2};
278 }
279 }
280 #print "table after adding:\n";
281 #$self->display_table;
282 }
283
284 # now display the table
285 $self->display_table;
286 }
287
288 sub display_table {
289 my ($self) = @_;
290 my (@longnames, @shortnames);
291 my ($minlen, $maxlen, $formatstr) = (0, 4, '');
292
293 $self->generate_candidates unless $self->{'candidates'};
294 @longnames = sort keys %{$self->{'candidates'}};
295 @shortnames = sort values %{$self->{'candidates'}};
296 $minlen = length scalar keys %{$self->{'ballots'}};
297 $minlen = 5 if $minlen < 5;
298
299 # build the format string
300 for my $s (@shortnames) {
301 if (length($s) > $minlen) {
302 $formatstr .= " %" . length($s) . "s";
303 } else {
304 $formatstr .= " %${minlen}s";
305 }
306 }
307 map { $maxlen = length($_) if length($_) > $maxlen } @longnames;
308
309 # prepend the row header; append newline
310 $formatstr = "%${maxlen}s" . $formatstr . "\n";
311
312 # column headers
313 printf $formatstr, '', @shortnames;
314
315 # rows
316 for my $l (@longnames) {
317 printf $formatstr, $l, @{$self->{'table'}}{map "$l+$_", @longnames};
318 }
319 }
320
321 # utility for cssd
322 sub defeats {
323 my ($self, $o1, $o2) = @_;
324 return 0 if $o1 eq $o2;
325 $self->{'table'}{"$o1+$o2"} > $self->{'table'}{"$o2+$o1"};
326 }
327
328 # utility for cssd
329 sub is_weaker_defeat {
330 my ($self, $A, $X, $B, $Y) = @_;
331 die unless $self->defeats($A, $X);
332 die unless $self->defeats($B, $Y);
333 return (
334 $self->{'table'}{"$A+$X"} < $self->{'table'}{"$B+$Y"} or
335 (
336 $self->{'table'}{"$A+$X"} == $self->{'table'}{"$B+$Y"} and
337 $self->{'table'}{"$X+$A"} > $self->{'table'}{"$Y+$B"}
338 )
339 );
340 }
341
342 sub cssd {
343 my ($self) = @_;
344 my (@candidates);
345
346 @candidates = sort keys %{$self->{'candidates'}};
347
348 while (1) {
349 my (%transitive_defeats);
350 my (@active, @plist);
351
352 ######################################################################
353 # 5. From the list of [undropped] pairwise defeats, we generate a
354 # set of transitive defeats.
355 # 1. An option A transitively defeats an option C if A
356 # defeats C or if there is some other option B where A
357 # defeats B AND B transitively defeats C.
358 for my $o1 (@candidates) {
359 for my $o2 (@candidates) {
360 $transitive_defeats{"$o1+$o2"} = 1 if $self->defeats($o1, $o2);
361 }
362 }
363 for my $i (@candidates) {
364 for my $j (@candidates) {
365 for my $k (@candidates) {
366 if (exists $transitive_defeats{"$j+$i"} and
367 exists $transitive_defeats{"$i+$k"})
368 {
369 $transitive_defeats{"$j+$k"} = 1;
370 }
371 }
372 }
373 }
374
375 ######################################################################
376 # 6. We construct the Schwartz set from the set of transitive
377 # defeats.
378 # 1. An option A is in the Schwartz set if for all options B,
379 # either A transitively defeats B, or B does not
380 # transitively defeat A.
381 print "\n";
382 A: for my $A (@candidates) {
383 for my $B (@candidates) {
384 next if $transitive_defeats{"$A+$B"} or not $transitive_defeats{"$B+$A"};
385 print "option $A is eliminated ($A does not beat $B and $B beats $A)\n";
386 next A;
387 }
388 push @active, $A;
389 }
390 print "the Schwartz set is {", join(", ", @active), "}\n";
391 @candidates = @active;
392
393 ######################################################################
394 # 7. If there are defeats between options in the Schwartz set, we
395 # drop the weakest such defeats from the list of pairwise
396 # defeats, and return to step 5.
397 # 1. A defeat (A,X) is weaker than a defeat (B,Y) if V(A,X)
398 # is less than V(B,Y). Also, (A,X) is weaker than (B,Y) if
399 # V(A,X) is equal to V(B,Y) and V(X,A) is greater than V
400 # (Y,B).
401 # 2. A weakest defeat is a defeat that has no other defeat
402 # weaker than it. There may be more than one such defeat.
403 for my $o1 (@candidates) {
404 for my $o2 (@candidates) {
405 push @plist, [ $o1, $o2 ] if $self->defeats($o1, $o2);
406 }
407 }
408 last unless @plist;
409 @plist = sort {
410 return -1 if $self->is_weaker_defeat(@$a, @$b);
411 return +1 if $self->is_weaker_defeat(@$b, @$a);
412 return 0;
413 } @plist;
414 for my $dx (@plist) {
415 my ($o1, $o2) = @$dx;
416 print(@$dx, " ",
417 $self->{'table'}{"$o1+$o2"}, " ",
418 $self->{'table'}{"$o2+$o1"}, "\n");
419 }
420 my ($o1, $o2) = @{$plist[0]};
421 $self->{'table'}{"$o1+$o2"} = 0;
422 $self->{'table'}{"$o2+$o1"} = 0;
423 }
424
425 ######################################################################
426 # 8. If there are no defeats within the Schwartz set, then the
427 # winner is chosen from the options in the Schwartz set. If
428 # there is only one such option, it is the winner. If there
429 # are multiple options, the elector with the casting vote
430 # chooses which of those options wins.
431 print "\n";
432 if (@candidates > 1) {
433 print "result: tie between options ", join(", ", @candidates), "\n";
434 } else {
435 print "result: option @candidates wins\n";
436 }
437 }
438
439 ######################################################################
440 # Ballot
441 ######################################################################
442
443 package Ballot;
444
445 sub new {
446 my ($class, $election) = @_;
447 my ($self) = {
448 election => $election,
449 filename => '',
450 default_filename => $ENV{'HOME'}."/.ballot-$election",
451 choices => [],
452 };
453
454 # Bless me, I'm a ballot!
455 bless $self, $class;
456 return $self;
457 }
458
459 sub from_s {
460 my ($self, $s) = @_;
461 my (@choices);
462
463 for (split "\n", $s) {
464 s/#.*//;
465 next unless /\S/;
466 push @choices, [ split(' ', $_) ];
467 }
468 die("No data in string") unless @choices;
469
470 $self->{'choices'} = \@choices;
471 }
472
473 sub read {
474 my ($self, $filename) = @_;
475
476 $filename ||= $self->{'default_filename'};
477 $self->{'filename'} = $filename;
478
479 # Load the data file
480 open(F, "<$filename") or die("couldn't open $filename");
481 { local $/ = undef; $self->from_s(<F>); }
482 close(F);
483 }
484
485 sub populate {
486 my ($self) = @_;
487 $self->read("$Votify::datadir/ballot-$self->{election}");
488 @{$self->{'choices'}} = List::Util::shuffle(@{$self->{'choices'}});
489 }
490
491 sub choices {
492 my ($self) = @_;
493 $self->{'choices'};
494 }
495
496 sub write {
497 my ($self, $filename) = @_;
498
499 if ($Votify::mode ne 'user') {
500 die("we don't write ballots in official mode");
501 }
502
503 $filename ||= $self->{'default_filename'};
504 $self->{'filename'} = $filename;
505
506 # Don't ever overwrite a ballot
507 die("File already exists; please remove $filename\n") if -e $filename;
508
509 # Write the user's ballot
510 open(F, ">$filename") or die "Failed writing $filename";
511 print F <<EOT;
512 # This is a ballot for the $self->{election} election.
513 # Please rank your choices in order; first choice at the top and last choice at
514 # the bottom. You can put choices on the same line to indicate no preference
515 # between them. Any choices you omit from this file are implicitly added at the
516 # end.
517 #
518 # When you're finished editing this, the next step is to verify your ballot
519 # with:
520 #
521 # $Votify::zero --verify $self->{election}
522 #
523 # When that passes and you're satisfied, the final step is to submit your vote:
524 #
525 # $Votify::zero --submit $self->{election}
526 #
527
528 EOT
529 for (@{$self->{'choices'}}) { print F "@$_\n"; }
530 close(F);
531 }
532
533 sub verify {
534 my ($self) = @_;
535 my (%h, $master, %mh);
536 my (@dups, @missing, @extra);
537 my ($errors_found);
538
539 # Load %h from the user's ballot
540 for my $line (@{$self->{'choices'}}) {
541 for my $entry (@$line) {
542 $h{$entry}++;
543 }
544 }
545
546 # Load the master ballot into another hash and compare them.
547 # The master ballots always do one entry per line, making this a little
548 # easier.
549 $master = Ballot->new($self->{'election'});
550 $master->populate;
551 %mh = map(($_->[0] => 1), @{$master->{'choices'}});
552
553 # Check for extra entries (write-ins should be supported in the future)
554 for (keys %h) {
555 push @extra, $_ unless exists $mh{$_};
556 }
557
558 # Check for duplicate entries
559 @dups = grep { $h{$_} > 1 } keys %h;
560
561 # Check for missing entries (not necessarily an error)
562 for (keys %mh) {
563 push @missing, $_ unless exists $h{$_};
564 }
565
566 # Report errors and warnings
567 if (@extra) {
568 if ($Votify::mode eq 'user') {
569 print <<EOT;
570 Your ballot has some extra entries that are not part of this election. Sorry,
571 but write-ins are not (yet) supported. Please remove these from your ballot:
572
573 EOT
574 print map "\t$_\n", @extra;
575 print "\n";
576 }
577 $errors_found++;
578 }
579 if (@dups) {
580 if ($Votify::mode eq 'user') {
581 print <<EOT;
582 Your ballot has some duplicate entries. Please resolve these to a single entry
583 to avoid ambiguities:
584
585 EOT
586 print map "\t$_\n", @dups;
587 print "\n";
588 }
589 $errors_found++;
590 }
591 if (@{$self->{'choices'}} == 0) {
592 if ($Votify::mode eq 'user') {
593 print <<EOT;
594 Your ballot doesn't contain any entries. You can start over by first removing
595 the existing ballot, then using --new to generate a new ballot. See --help for
596 more information.
597
598 EOT
599 }
600 $errors_found++;
601 }
602 elsif (@missing and $Votify::mode eq 'user') {
603 print <<EOT;
604 Your ballot is missing some entries. This is not an error, but note that these
605 will be implied as a final line, with no preference between them, like this:
606
607 EOT
608 print "\t", join(" ", @missing), "\n";
609 print "\n";
610 }
611 if ($Votify::mode eq 'user' and !$errors_found and
612 @{$self->{'choices'}} == 1 and
613 scalar(keys %h) == scalar(keys %mh))
614 {
615 print <<EOT;
616 Your ballot contains all the candidates on a single line! This means you have
617 no preference between the candidates. This is not an error, but note that this
618 is a meaningless ballot that will have no effect on the election.
619
620 EOT
621 }
622
623 # Stop if there were errors
624 if ($Votify::mode eq 'user' and $errors_found) {
625 print("There were errors found in your ballot.\n");
626 die("Please correct them and try again.\n\n");
627 }
628 return $errors_found;
629 }
630
631 sub to_s {
632 my ($self) = @_;
633 join '', map "@$_\n", @{$self->{'choices'}};
634 }
635
636 1;
637
638 __END__
639
640 $Log: votify,v $
641
642 __END__
643
644 $Log: votify,v $
645 Revision 1.3 2005/05/09 23:12:02 agriffis
646 Add support for registered voters
647
648 Revision 1.2 2005/05/05 23:03:46 agriffis
649 Fix indentation (and some output as well)
650
651 Revision 1.1 2005/05/05 22:05:34 agriffis
652 first pass at Gentoo Foundation voting program
653
654 # vim:sw=4 et

  ViewVC Help
Powered by ViewVC 1.1.20