Count/TieBreaker.pm

filter: Statementstmt 98.3% 175 / 178 Branchbran 94.1% 64 / 68 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 20 / 20 Podpod 33.3% 2 / 6 totaltotal 95.9% 261 / 272 CC 47 SCAR 21.2
CC
47
Cov
97%
TieBreaker
16.0
TieBreakerGrandJunction
12.0
UntieActive
8.0
CRAP 8.4
« buildpod.pl ↑ Summary Count/Method/CondorcetDropping.pm »
1 25 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 25 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 25 ▶use 5.022;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 25 ▶use feature qw /postderef signatures/;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 package Vote::Count::TieBreaker;
8 25 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 25 ▶no warnings 'experimental';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 25 ▶use List::Util qw( min max sum );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 25 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 25 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 25 ▶use Vote::Count::RankCount;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 25 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 25 our $VERSION = '1.10';
18  
19 =head1 NAME
20  
21 Vote::Count::TieBreaker
22  
23 =head1 VERSION 1.10
24  
25 =head1 Synopsis
26  
27 my $Election = Vote::Count->new(
28 BallotSet => $ballotsirvtie2,
29 TieBreakMethod => 'approval'
30 );
31  
32 =cut
33  
34 # ABSTRACT: TieBreaker object for Vote::Count. Toolkit for vote counting.
35  
36 =head1 Tie Breakers
37  
38 The most important thing for a Tie Breaker to do is it should use some reproducible difference in the Ballots to pick a winner from a Tie. The next thing it should do is make sense. Finally, the ideal Tie Breaker will resolve when there is any difference to be found. Arguably the best use of Borda Count is as a Tie Breaker, First Choice votes and Approval are also other great choices.
39  
40 TieBreakMethod is specified as an argument to Vote::Count->new(). The TieBreaker is called internally from the resolution method via the TieBreaker function, which requires the caller to pass its TieBreakMethod.
41  
42 =head1 TieBreakMethod argument to Vote::Count->new
43  
44 'approval'
45 'all' [ eliminate all tied choices ]
46 'borda' [ applies Borda Count to current Active set ]
47 'grandjunction' [ more resolveable than simple TopCount would be ]
48 'none' [ eliminate no choices ]
49 'precedence' [ requires also setting PrecedenceFile ]
50  
51 =head1 Grand Junction
52  
53 The Grand Junction (also known as Bucklin) method is one of the simplest and easiest to Hand Count RCV resolution methods. Other than that it is generally not considered a good method.
54  
55 Because it is simple, and always resolves, except when ballots are perfectly matched up, it is a great TieBreaker. It is not Later Harm Safe, but heavily favors higher rankings. It is the Vote::Count author's preferred Tie-Breaker.
56  
57 =head2 The (Standard) Grand Junction Method
58  
59 Only the Tie-Breaker variant is currently implemented in Vote::Count.
60  
61 =over
62  
63 =item 1
64  
65 Count the Ballots to determine the quota for a majority.
66  
67 =item 2
68  
69 Count the first choices and elect a choice which has a majority.
70  
71 =item 3
72  
73 If there is no winner add the second choices to the totals and elect the choice which has a majority (or the most votes if more than one choice reaches a majority).
74  
75 =item 4
76  
77 Keep adding the next rank to the totals until either there is a winner or all ballots are exhausted.
78  
79 =item 5
80  
81 When all ballots are exhausted the choice with the highest total wins.
82  
83 =back
84  
85 =head2 As a Tie Breaker
86  
87 The Tie Breaker Method is modified.
88  
89 Instead of Majority, any choice with a current total less than another is eliminated. This allows resolution of any number of choices in a tie.
90  
91 The winner is the last choice remaining.
92  
93 =head2 TieBreakerGrandJunction
94  
95 my $resolve = $Election->TieBreakerGrandJunction( $choice1, $choice2 [ $choice3 ... ] );
96 if ( $resolve->{'winner'}) { say "Tie Winner is $resolve->{'winner'}"}
97 elsif ( $resolve->{'tie'}) {
98 my @tied = $resolve->{'tied'}->@*;
99 say "Still tied between @tied."
100 }
101  
102 The Tie Breaking will be logged to the verbose log, any number of tied choices may be provided.
103  
104 =cut
105  
106 25 has 'TieBreakMethod' => (
107 is => 'rw',
108 isa => 'Str',
109 required => 0,
110 );
111  
112 # This is only used for the precedence tiebreaker and fallback!
113 25 has 'PrecedenceFile' => (
114 is => 'rw',
115 isa => 'Str',
116 required => 0,
117 trigger => \&_triggercheckprecedence,
118 );
119  
120 25 has 'TieBreakerFallBackPrecedence' => (
121 is => 'rw',
122 isa => 'Bool',
123 default => 0,
124 lazy => 0,
125 trigger => \&_triggercheckprecedence,
126 );
127  
128 12 ▶sub _triggercheckprecedence ( $I, $new, $old = undef ) {
Subroutine _triggercheckprecedence: called CC=3 SCAR=11.0
129 12 ▶ unless ( $I->PrecedenceFile() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($I->PrecedenceFile) 2 10 12
130 2 $I->PrecedenceFile('/tmp/precedence.txt');
131 2 $I->logt( "Generated FallBack TieBreaker Precedence Order: \n"
132 . join( ', ', $I->CreatePrecedenceRandom() ) );
133 }
134 12 $I->{'PRECEDENCEORDER'} = undef; # clear cached if the file changes.
135 }
136  
137 ▶sub TieBreakerGrandJunction ( $self, @tiedchoices ) {
Subroutine TieBreakerGrandJunction: called CC=12 SCAR=24.8
Pod documented
138 68 my $ballots = $self->BallotSet()->{'ballots'};
139 68 my %current = ( map { $_ => 0 } @tiedchoices );
140 68 my $deepest = 0;
141 68 for my $b ( keys $ballots->%* ) {
142 734 my $depth = scalar $ballots->{$b}{'votes'}->@*;
143 734 ▶ $deepest = $depth if $depth > $deepest;
Branch: 1 branch
BranchTrueFalseTotal
if $depth > $deepest 125 609 734
144 }
145 68 my $round = 1;
146 68 ▶ while ( $round <= $deepest ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($round <= $deepest) 128 16 144
147 128 $self->logv("Tie Breaker Round: $round");
148 128 for my $b ( keys $ballots->%* ) {
149 1350 ▶ my $pick = $ballots->{$b}{'votes'}[ $round - 1 ] or next;
Branch: 1 branch
BranchTrueFalseTotal
my $pick = $ballots->{$b}{"votes"}[$round - 1] or next 360 990 1350
150 990 ▶ if ( defined $current{$pick} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $current{$pick}) 222 768 990
151 222 $current{$pick} += $ballots->{$b}{'count'};
152 }
153 }
154 128 my $max = max( values %current );
155 128 for my $c ( sort @tiedchoices ) {
156 296 $self->logv("\t$c: $current{$c}");
157 }
158 128 for my $c ( sort @tiedchoices ) {
159 296 ▶ if ( $current{$c} < $max ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current{$c} < $max) 75 221 296
160 75 delete $current{$c};
161 75 $self->logv("Tie Breaker $c eliminated");
162 }
163 }
164 128 @tiedchoices = ( sort keys %current );
165 128 ▶ if ( 1 == @tiedchoices ) {
Branch: 1 branch
BranchTrueFalseTotal
if (1 == @tiedchoices) 52 76 128
166 52 $self->logv("Tie Breaker Won By: $tiedchoices[0]");
167 52 return { 'winner' => $tiedchoices[0], 'tie' => 0, 'tied' => [] };
168 }
169 76 $round++;
170 }
171 16 ▶ if ( $self->TieBreakerFallBackPrecedence() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->TieBreakerFallBackPrecedence) { } 3 13 16
172 3 $self->logv('Applying Precedence fallback');
173 3 return $self->TieBreakerPrecedence(@tiedchoices);
174 }
175 else {
176 13 return { 'winner' => 0, 'tie' => 1, 'tied' => \@tiedchoices };
177 }
178 }
179  
180 =head1 TieBreaker
181  
182 Implements some basic methods for resolving ties. The default value for IRV is 'all', and the default value for Matrix is 'none'. 'all' is inappropriate for Matrix, and 'none' is inappropriate for IRV.
183  
184 my @keep = $Election->TieBreaker( $tiebreaker, $active, @tiedchoices );
185  
186 TieBreaker returns a list containing the winner, if the method is 'all' the list is empty, if 'none' the original @tiedchoices list is returned. If the TieBreaker is a tie there will be multiple elements.
187  
188 =head1 Precedence
189  
190 Since many existing Elections Rules call for Random, and Vote::Count does not accept Random as the result will be different bewtween runs, Precedence allows the Administrators of an election to randomly or arbitrarily determine who will win ties before running Vote::Count.
191  
192 The Precedence list takes the choices of the election one per line. Choices defeat any choice lower than them in the list. When Precedence is used an additional attribute must be specified for the Precedence List.
193  
194 my $Election = Vote::Count->new(
195 BallotSet => read_ballots('somefile'),
196 TieBreakMethod => 'precedence',
197 PrecedenceFile => '/path/to/precedencefile');
198  
199 =head2 CreatePrecedenceRandom
200  
201 Creates a Predictable Psuedo Random Precedence file, and returns the list. Randomizes the choices using the number of ballots as the Random Seed for Perl's built in rand() function. For any given Ballot File, it will always return the same list. If the precedence filename argument is not given it defaults to '/tmp/precedence.txt'. This is the best solution to use where the Rules call for Random, in a large election the number of ballots cast will be sufficiently random, while anyone with access to Perl can reproduce the Precedence file.
202  
203 my @precedence = Vote::Count->new( BallotSet => read_ballots('somefile') )
204 ->CreatePrecedenceRandom( '/tmp/precedence.txt');
205  
206 =head2 TieBreakerFallBackPrecedence
207  
208 This optional argument enables or disables using precedence as a fallback, generates /tmp/precedence.txt if no PrecedenceFile is specified. Default is off.
209  
210 =head1 UntieList
211  
212 Sort a list in an order determined by a TieBreaker method, sorted in Descending Order. The TieBreaker must be a method that returns a RankCount object, Borda, TopCount, and Approval, Precedence. To guarrantee reliable resolution Precedence must be used or have been set for fallback.
213  
214 my @orderedlosers = $Election->UntieList( 'Approval', @unorderedlosers );
215  
216 =head1 UntieActive
217  
218 Produces a precedence list of all the active choices in the election. Takes a first and optional second method name, if one of the methods is not Precedence, TieBreakerPrecedence must be true. The methods may be TopCount, Approval, or any other method that returns a RankCount object. Returns a RankCount object (with the OrderedList method enabled).
219  
220 my $precedenceRankCount = $Election->UntieActive( 'TopCount', 'Approval');
221  
222 =cut
223  
224 ▶sub _precedence_sort ( $I, @list ) {
Subroutine _precedence_sort: called CC=5 SCAR=16.1
225 27 my %ordered = ();
226 27 my $start = 0;
227 27 ▶ if ( defined $I->{'PRECEDENCEORDER'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $I->{'PRECEDENCEORDER'}) { } 21 6 27
228 21 %ordered = $I->{'PRECEDENCEORDER'}->%*;
229 }
230 else {
231 6 for ( split /\n/, path( $I->PrecedenceFile() )->slurp() ) {
232 58 $_ =~ s/\s//g; #strip out any accidental white space
233 58 $ordered{$_} = ++$start;
234 }
235 6 for my $c ( $I->GetChoices ) {
236 58 ▶ unless ( defined $ordered{$c} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ordered{$c}) 0 58 58
237 0 croak "Choice $c missing from precedence file\n";
238 }
239 }
240 6 $I->{'PRECEDENCEORDER'} = \%ordered;
241 }
242 27 my %L = map { $ordered{$_} => $_ } @list;
243 27 return ( map { $L{$_} } ( sort { $a <=> $b } keys %L ) );
244 }
245  
246 ▶sub TieBreakerPrecedence ( $I, @tiedchoices ) {
Subroutine TieBreakerPrecedence: called CC=1 SCAR=0.0
Pod undocumented
247 14 my @list = $I->_precedence_sort(@tiedchoices);
248 14 return { 'winner' => $list[0], 'tie' => 0, 'tied' => [] };
249 }
250  
251 4 ▶sub CreatePrecedenceRandom ( $I, $outfile = '/tmp/precedence.txt' ) {
Subroutine CreatePrecedenceRandom: called CC=4 SCAR=13.9
Pod documented
252 4 my @choices = $I->GetActiveList();
253 4 my %randomized = ();
254 4 srand( $I->BallotSet()->{'votescast'} );
255 4 ▶ while (@choices) {
Branch: 1 branch
BranchTrueFalseTotal
if (@choices) 36 4 40
256 36 my $next = shift @choices;
257 36 my $random = int( rand(1000000) );
258 36 ▶ if ( defined $randomized{$random} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $randomized{$random}) { } 0 36 36
259 # collision, this choice needs to do again.
260 0 unshift @choices, ($next);
261 }
262 else {
263 36 $randomized{$random} = $next;
264 }
265 }
266 my @precedence =
267 4 ( map { $randomized{$_} } sort { $a <=> $b } ( keys %randomized ) );
268 4 path($outfile)->spew( join( "\n", @precedence ) . "\n" );
269 4 return @precedence;
270 }
271  
272 ▶sub TieBreaker ( $I, $tiebreaker, $active, @tiedchoices ) {
Subroutine TieBreaker: called CC=16 SCAR=27.7
Pod undocumented
273 25 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
274 259 ▶ if ( $tiebreaker eq 'none' ) { return @tiedchoices }
Branch: 1 branch
BranchTrueFalseTotal
if ($tiebreaker eq "none") 157 102 259
275 102 ▶ if ( $tiebreaker eq 'all' ) { return () }
Branch: 1 branch
BranchTrueFalseTotal
if ($tiebreaker eq "all") 17 85 102
276 85 my $choices_hashref = { map { $_ => 1 } @tiedchoices };
277 85 my $ranked = undef;
278 85 ▶ if ( $tiebreaker eq 'borda' ) {
Branch: 6 branches
BranchTrueFalseTotal
if ($tiebreaker eq 'borda') { } 3 82 85
elsif ($tiebreaker eq 'borda_all') { } 3 79 82
elsif ($tiebreaker eq 'approval') { } 12 67 79
elsif ($tiebreaker eq 'topcount') { } 2 65 67
elsif ($tiebreaker eq 'grandjunction') { } 62 3 65
elsif ($tiebreaker eq 'precedence') { } 2 1 3
279 3 $ranked = $I->Borda($active);
280 }
281 elsif ( $tiebreaker eq 'borda_all' ) {
282 3 $ranked = $I->Borda( $I->BallotSet()->{'choices'} );
283 }
284 elsif ( $tiebreaker eq 'approval' ) {
285 12 $ranked = $I->Approval($choices_hashref);
286 }
287 elsif ( $tiebreaker eq 'topcount' ) {
288 2 $ranked = $I->TopCount($choices_hashref);
289 }
290 elsif ( $tiebreaker eq 'grandjunction' ) {
291 62 my $GJ = $I->TieBreakerGrandJunction(@tiedchoices);
292 62 ▶ if ( $GJ->{'winner'} ) { return $GJ->{'winner'} }
Branch: 2 branches
BranchTrueFalseTotal
if ($GJ->{'winner'}) { } 50 12 62
elsif ($GJ->{'tie'}) { } 12 0 12
293 12 elsif ( $GJ->{'tie'} ) { return $GJ->{'tied'}->@* }
294 0 else { croak "unexpected (or no) result from $tiebreaker!\n" }
295 }
296 elsif ( $tiebreaker eq 'precedence' ) {
297 # The one nice thing about precedence is that there is always a winner.
298 2 return $I->TieBreakerPrecedence(@tiedchoices)->{'winner'};
299 }
300 1 else { croak "undefined tiebreak method $tiebreaker!\n" }
301 20 my @highchoice = ();
302 20 my $highest = 0;
303 20 my $counted = $ranked->RawCount();
304 20 for my $c (@tiedchoices) {
305 66 ▶ if ( $counted->{$c} > $highest ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($counted->{$c} > $highest) { } 25 41 66
elsif ($counted->{$c} == $highest) { } 37 4 41
306 25 @highchoice = ($c);
307 25 $highest = $counted->{$c};
308 }
309 elsif ( $counted->{$c} == $highest ) {
310 37 push @highchoice, $c;
311 }
312 }
313 20 my $terse =
314 "Tie Breaker $tiebreaker: "
315 . join( ', ', @tiedchoices )
316 . "\nwinner(s): "
317 . join( ', ', @highchoice );
318 20 $I->{'last_tiebreaker'} = {
319 'terse' => $terse,
320 'verbose' => $ranked->RankTable(),
321 };
322 20 ▶ if ( @highchoice > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@highchoice > 1) 11 9 20
323 11 ▶ if ( $I->TieBreakerFallBackPrecedence() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I->TieBreakerFallBackPrecedence) 8 3 11
324 8 return ( $I->TieBreakerPrecedence(@tiedchoices)->{'winner'} );
325 }
326 }
327 12 return (@highchoice);
328 }
329  
330 ▶sub UnTieList ( $I, $method, @tied ) {
Subroutine UnTieList: called CC=5 SCAR=16.1
Pod undocumented
331 12 ▶ return $I->_precedence_sort( @tied ) if ( lc($method) eq 'precedence' );
Branch: 1 branch
BranchTrueFalseTotal
if lc $method eq "precedence" 1 11 12
332 11 ▶ unless ( $I->TieBreakerFallBackPrecedence() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($I->TieBreakerFallBackPrecedence) 1 10 11
333 1 croak
334 "TieBreakerFallBackPrecedence must be enabled or the specified method must be precedence to use UnTieList";
335 }
336 10 my @ordered = ();
337 10 my %active = ( map { $_ => 1 } @tied );
338 # method should be topcount borda or approval which all take argument of active.
339 10 my $RC = $I->$method(\%active)->HashByRank();
340  
341 # my $nonrc = 0;
342 10 for my $level ( sort { $a <=> $b } ( keys $RC->%* ) ) {
343 22 my @l = @{ $RC->{$level} };
344 my @suborder =
345 22 ( 1 == @{ $RC->{$level} } )
346 22 ▶ ? @{ $RC->{$level} }
Branch: 1 branch
BranchTrueFalseTotal
1 == @{$RC->{$level};} ? : 11 11 22
347 : $I->_precedence_sort( @l );
348 22 push @ordered, @suborder;
349 }
350 10 return @ordered;
351 }
352  
353 5 ▶sub UntieActive ( $I, $method1, $method2='precedence' ) {
Subroutine UntieActive: called CC=8 SCAR=20.8
Pod undocumented
354 5 ▶ if ( lc($method1) eq 'precedence' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $method1 eq "precedence") 1 4 5
355 1 return Vote::Count::RankCount->newFromList(
356 $I->_precedence_sort( $I->GetActiveList() ));
357 }
358 4 my $hasprecedence = 0;
359 4 ▶ $hasprecedence = 1 if 1 == $I->TieBreakerFallBackPrecedence();
Branch: 1 branch
BranchTrueFalseTotal
if 1 == $I->TieBreakerFallBackPrecedence 3 1 4
360 4 ▶ $hasprecedence = 1 if lc($method2) eq 'precedence';
Branch: 1 branch
BranchTrueFalseTotal
if lc $method2 eq "precedence" 0 4 4
361 4 ▶ unless ($hasprecedence) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hasprecedence) 1 3 4
362 1 croak
363 "TieBreakerFallBackPrecedence must be enabled or one of the specified methods must be precedence to use UntieActive";
364 }
365 3 my @ordered = ();
366 3 my $first = $I->$method1()->HashByRank();
367  
368 3 for my $level ( sort { $a <=> $b } ( keys %{$first} ) ) {
369 18 my @l = @{ $first->{$level} };
370 my @suborder =
371 18 ( 1 == @{ $first->{$level} } )
372 18 ▶ ? @{ $first->{$level} }
Branch: 1 branch
BranchTrueFalseTotal
1 == @{$first->{$level};} ? : 10 8 18
373 : $I->UnTieList( $method2, @l );
374 18 push @ordered, @suborder;
375 }
376 3 my $position = 0;
377 3 return Vote::Count::RankCount->newFromList( @ordered );
378 }
379  
380 25 1;
381  
382 #FOOTER
383  
384 =pod
385  
386 BUG TRACKER
387  
388 L<https://github.com/brainbuz/Vote-Count/issues>
389  
390 AUTHOR
391  
392 John Karr (BRAINBUZ) brainbuz@cpan.org
393  
394 CONTRIBUTORS
395  
396 Copyright 2019 by John Karr (BRAINBUZ) brainbuz@cpan.org.
397  
398 LICENSE
399  
400 This module is released under the GNU Public License Version 3. See license file for details. For more information on this license visit L<http://fsf.org>.
401  
402 =cut
« buildpod.pl ↑ Summary Count/Method/CondorcetDropping.pm »