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

Contents of /votify/Votify.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.3 - (show annotations) (download) (as text)
Mon May 16 18:10:46 2005 UTC (13 years, 4 months ago) by agriffis
Branch: MAIN
Changes since 1.2: +19 -10 lines
File MIME type: text/x-perl
ranking works completely now, even if it needs badly to be refactored

1 # $Id: Votify.pm,v 1.2 2005/05/16 04:03:46 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
285 sub display_table {
286 my ($self) = @_;
287 my (@longnames, @shortnames);
288 my ($minlen, $maxlen, $formatstr) = (0, 4, '');
289
290 $self->generate_candidates unless $self->{'candidates'};
291 @longnames = sort keys %{$self->{'candidates'}};
292 @shortnames = sort values %{$self->{'candidates'}};
293 $minlen = length scalar keys %{$self->{'ballots'}};
294 $minlen = 5 if $minlen < 5;
295
296 # build the format string
297 for my $s (@shortnames) {
298 if (length($s) > $minlen) {
299 $formatstr .= " %" . length($s) . "s";
300 } else {
301 $formatstr .= " %${minlen}s";
302 }
303 }
304 map { $maxlen = length($_) if length($_) > $maxlen } @longnames;
305
306 # prepend the row header; append newline
307 $formatstr = "%${maxlen}s" . $formatstr . "\n";
308
309 # column headers
310 printf $formatstr, '', @shortnames;
311
312 # rows
313 for my $l (@longnames) {
314 printf $formatstr, $l, @{$self->{'table'}}{map "$l+$_", @longnames};
315 }
316 }
317
318 # utility for cssd
319 sub defeats {
320 my ($self, $o1, $o2) = @_;
321 return 0 if $o1 eq $o2;
322 $self->{'table'}{"$o1+$o2"} > $self->{'table'}{"$o2+$o1"};
323 }
324
325 # utility for cssd
326 sub is_weaker_defeat {
327 my ($self, $A, $X, $B, $Y) = @_;
328 die unless $self->defeats($A, $X);
329 die unless $self->defeats($B, $Y);
330 return (
331 $self->{'table'}{"$A+$X"} < $self->{'table'}{"$B+$Y"} or
332 (
333 $self->{'table'}{"$A+$X"} == $self->{'table'}{"$B+$Y"} and
334 $self->{'table'}{"$X+$A"} > $self->{'table'}{"$Y+$B"}
335 )
336 );
337 }
338
339 sub cssd {
340 my ($self) = @_;
341 my (@candidates);
342
343 @candidates = sort keys %{$self->{'candidates'}};
344
345 while (1) {
346 my (%transitive_defeats);
347 my (@active, @plist);
348
349 ######################################################################
350 # 5. From the list of [undropped] pairwise defeats, we generate a
351 # set of transitive defeats.
352 # 1. An option A transitively defeats an option C if A
353 # defeats C or if there is some other option B where A
354 # defeats B AND B transitively defeats C.
355 for my $o1 (@candidates) {
356 for my $o2 (@candidates) {
357 $transitive_defeats{"$o1+$o2"} = 1 if $self->defeats($o1, $o2);
358 }
359 }
360 for my $i (@candidates) {
361 for my $j (@candidates) {
362 for my $k (@candidates) {
363 if (exists $transitive_defeats{"$j+$i"} and
364 exists $transitive_defeats{"$i+$k"})
365 {
366 $transitive_defeats{"$j+$k"} = 1;
367 }
368 }
369 }
370 }
371
372 ######################################################################
373 # 6. We construct the Schwartz set from the set of transitive
374 # defeats.
375 # 1. An option A is in the Schwartz set if for all options B,
376 # either A transitively defeats B, or B does not
377 # transitively defeat A.
378 print "\n";
379 A: for my $A (@candidates) {
380 for my $B (@candidates) {
381 next if $transitive_defeats{"$A+$B"} or not $transitive_defeats{"$B+$A"};
382 # countify marks entries +++ instead of *** when they've already
383 # been ranked.
384 if ($self->{'table'}{"$A+$A"} eq '***') {
385 print "option $A is eliminated ($A does not beat $B and $B beats $A)\n";
386 }
387 next A;
388 }
389 push @active, $A;
390 }
391 print "the Schwartz set is {", join(", ", @active), "}\n";
392 @candidates = @active;
393
394 ######################################################################
395 # 7. If there are defeats between options in the Schwartz set, we
396 # drop the weakest such defeats from the list of pairwise
397 # defeats, and return to step 5.
398 # 1. A defeat (A,X) is weaker than a defeat (B,Y) if V(A,X)
399 # is less than V(B,Y). Also, (A,X) is weaker than (B,Y) if
400 # V(A,X) is equal to V(B,Y) and V(X,A) is greater than V
401 # (Y,B).
402 # 2. A weakest defeat is a defeat that has no other defeat
403 # weaker than it. There may be more than one such defeat.
404 for my $o1 (@candidates) {
405 for my $o2 (@candidates) {
406 push @plist, [ $o1, $o2 ] if $self->defeats($o1, $o2);
407 }
408 }
409 last unless @plist;
410 @plist = sort {
411 return -1 if $self->is_weaker_defeat(@$a, @$b);
412 return +1 if $self->is_weaker_defeat(@$b, @$a);
413 return 0;
414 } @plist;
415 for my $dx (@plist) {
416 my ($o1, $o2) = @$dx;
417 print("$o1+$o2 ",
418 $self->{'table'}{"$o1+$o2"}, " $o2+$o1 ",
419 $self->{'table'}{"$o2+$o1"}, "\n");
420 }
421 my ($o1, $o2) = @{$plist[0]};
422 $self->{'table'}{"$o1+$o2"} = 0;
423 $self->{'table'}{"$o2+$o1"} = 0;
424 }
425
426 ######################################################################
427 # 8. If there are no defeats within the Schwartz set, then the
428 # winner is chosen from the options in the Schwartz set. If
429 # there is only one such option, it is the winner. If there
430 # are multiple options, the elector with the casting vote
431 # chooses which of those options wins.
432 print "\n";
433 if (@candidates > 1) {
434 print "result: tie between options ", join(", ", @candidates), "\n";
435 } else {
436 print "result: option @candidates wins\n";
437 }
438
439 return @candidates;
440 }
441
442 ######################################################################
443 # Ballot
444 ######################################################################
445
446 package Ballot;
447
448 sub new {
449 my ($class, $election) = @_;
450 my ($self) = {
451 election => $election,
452 filename => '',
453 default_filename => $ENV{'HOME'}."/.ballot-$election",
454 choices => [],
455 };
456
457 # Bless me, I'm a ballot!
458 bless $self, $class;
459 return $self;
460 }
461
462 sub from_s {
463 my ($self, $s) = @_;
464 my (@choices);
465
466 for (split "\n", $s) {
467 s/#.*//;
468 next unless /\S/;
469 push @choices, [ split(' ', $_) ];
470 }
471 die("No data in string") unless @choices;
472
473 $self->{'choices'} = \@choices;
474 }
475
476 sub read {
477 my ($self, $filename) = @_;
478
479 $filename ||= $self->{'default_filename'};
480 $self->{'filename'} = $filename;
481
482 # Load the data file
483 open(F, "<$filename") or die("couldn't open $filename");
484 { local $/ = undef; $self->from_s(<F>); }
485 close(F);
486 }
487
488 sub populate {
489 my ($self) = @_;
490 $self->read("$Votify::datadir/ballot-$self->{election}");
491 @{$self->{'choices'}} = List::Util::shuffle(@{$self->{'choices'}});
492 }
493
494 sub choices {
495 my ($self) = @_;
496 $self->{'choices'};
497 }
498
499 sub write {
500 my ($self, $filename) = @_;
501
502 if ($Votify::mode ne 'user') {
503 die("we don't write ballots in official mode");
504 }
505
506 $filename ||= $self->{'default_filename'};
507 $self->{'filename'} = $filename;
508
509 # Don't ever overwrite a ballot
510 die("File already exists; please remove $filename\n") if -e $filename;
511
512 # Write the user's ballot
513 open(F, ">$filename") or die "Failed writing $filename";
514 print F <<EOT;
515 # This is a ballot for the $self->{election} election.
516 # Please rank your choices in order; first choice at the top and last choice at
517 # the bottom. You can put choices on the same line to indicate no preference
518 # between them. Any choices you omit from this file are implicitly added at the
519 # end.
520 #
521 # When you're finished editing this, the next step is to verify your ballot
522 # with:
523 #
524 # $Votify::zero --verify $self->{election}
525 #
526 # When that passes and you're satisfied, the final step is to submit your vote:
527 #
528 # $Votify::zero --submit $self->{election}
529 #
530
531 EOT
532 for (@{$self->{'choices'}}) { print F "@$_\n"; }
533 close(F);
534 }
535
536 sub verify {
537 my ($self) = @_;
538 my (%h, $master, %mh);
539 my (@dups, @missing, @extra);
540 my ($errors_found);
541
542 # Load %h from the user's ballot
543 for my $line (@{$self->{'choices'}}) {
544 for my $entry (@$line) {
545 $h{$entry}++;
546 }
547 }
548
549 # Load the master ballot into another hash and compare them.
550 # The master ballots always do one entry per line, making this a little
551 # easier.
552 $master = Ballot->new($self->{'election'});
553 $master->populate;
554 %mh = map(($_->[0] => 1), @{$master->{'choices'}});
555
556 # Check for extra entries (write-ins should be supported in the future)
557 for (keys %h) {
558 push @extra, $_ unless exists $mh{$_};
559 }
560
561 # Check for duplicate entries
562 @dups = grep { $h{$_} > 1 } keys %h;
563
564 # Check for missing entries (not necessarily an error)
565 for (keys %mh) {
566 push @missing, $_ unless exists $h{$_};
567 }
568
569 # Report errors and warnings
570 if (@extra) {
571 if ($Votify::mode eq 'user') {
572 print <<EOT;
573 Your ballot has some extra entries that are not part of this election. Sorry,
574 but write-ins are not (yet) supported. Please remove these from your ballot:
575
576 EOT
577 print map "\t$_\n", @extra;
578 print "\n";
579 }
580 $errors_found++;
581 }
582 if (@dups) {
583 if ($Votify::mode eq 'user') {
584 print <<EOT;
585 Your ballot has some duplicate entries. Please resolve these to a single entry
586 to avoid ambiguities:
587
588 EOT
589 print map "\t$_\n", @dups;
590 print "\n";
591 }
592 $errors_found++;
593 }
594 if (@{$self->{'choices'}} == 0) {
595 if ($Votify::mode eq 'user') {
596 print <<EOT;
597 Your ballot doesn't contain any entries. You can start over by first removing
598 the existing ballot, then using --new to generate a new ballot. See --help for
599 more information.
600
601 EOT
602 }
603 $errors_found++;
604 }
605 elsif (@missing and $Votify::mode eq 'user') {
606 print <<EOT;
607 Your ballot is missing some entries. This is not an error, but note that these
608 will be implied as a final line, with no preference between them, like this:
609
610 EOT
611 print "\t", join(" ", @missing), "\n";
612 print "\n";
613 }
614 if ($Votify::mode eq 'user' and !$errors_found and
615 @{$self->{'choices'}} == 1 and
616 scalar(keys %h) == scalar(keys %mh))
617 {
618 print <<EOT;
619 Your ballot contains all the candidates on a single line! This means you have
620 no preference between the candidates. This is not an error, but note that this
621 is a meaningless ballot that will have no effect on the election.
622
623 EOT
624 }
625
626 # Stop if there were errors
627 if ($Votify::mode eq 'user' and $errors_found) {
628 print("There were errors found in your ballot.\n");
629 die("Please correct them and try again.\n\n");
630 }
631 return $errors_found;
632 }
633
634 sub to_s {
635 my ($self) = @_;
636 join '', map "@$_\n", @{$self->{'choices'}};
637 }
638
639 1;
640
641 __END__
642
643 $Log: Votify.pm,v $
644 Revision 1.2 2005/05/16 04:03:46 agriffis
645 add first pass at countify --rank
646
647
648 __END__
649
650 $Log: Votify.pm,v $
651 Revision 1.2 2005/05/16 04:03:46 agriffis
652 add first pass at countify --rank
653
654 Revision 1.3 2005/05/09 23:12:02 agriffis
655 Add support for registered voters
656
657 Revision 1.2 2005/05/05 23:03:46 agriffis
658 Fix indentation (and some output as well)
659
660 Revision 1.1 2005/05/05 22:05:34 agriffis
661 first pass at Gentoo Foundation voting program
662
663 # vim:sw=4 et

  ViewVC Help
Powered by ViewVC 1.1.20