Count/Method/Cascade.pm untested

filter: Statementstmt 0.0% 0 / 223 Branchbran 0.0% 0 / 52 Conditioncond 0.0% 0 / 6 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 318 CC 27 SCAR 33.6
CC
27
Cov
0%
Conduct
90.0
_finalphase
56.0
_automatic_defeat
20.0
CRAP 28.7
1 use strict;
2 use warnings;
3 use 5.024;
4  
5 package Vote::Count::Method::Cascade;
6 use namespace::autoclean;
7 use Moose;
8 extends 'Vote::Count::Charge::Cascade';
9  
10 no warnings 'experimental';
11 use feature qw /postderef signatures/;
12  
13 use Vote::Count::TextTableTiny qw/generate_table/;
14 use Vote::Count::Method::CondorcetIRV;
15 # import Vote::Count::Method::CondorcetIRV;
16  
17 use Storable 3.15 'dclone';
18 use Sort::Hash;
19 use Data::Dumper;
20 use Try::Tiny;
21 use Path::Tiny;
22 use Carp;
23  
24 our $VERSION='2.02';
25  
26 =head1 NAME
27  
28 Vote::Count::Method::Cascade
29  
30 =head1 VERSION 2.02
31  
32 =cut
33  
34 # ABSTRACT: A Proposal of a Complete Method using Full Cascade Vote Charging.
35  
36 =pod
37  
38 =head1 SYNOPSIS
39  
40 ....
41  
42 =head1 Description
43  
44 Experimental Implementation of a method using Full Cascade Charging.
45  
46 =head1 The Rules
47  
48 ...
49  
50 =cut
51  
52 # Values 'none', NthApproval
53 has 'AutomaticDefeat' => (
54 is => 'ro',
55 isa => 'Str',
56 default => 'NthApproval',
57 );
58  
59 has 'CalculatedPrecedenceFile' => (
60 is => 'ro',
61 isa => 'Str',
62 default => '/tmp/vote_count_method_charge_precedence.txt',
63 );
64  
65 has 'FloorRule' => (
66 is => 'rw',
67 isa => 'Str',
68 default => 'Approval',
69 );
70  
71 has 'FloorThresshold' => (
72 is => 'ro',
73 isa => 'Num',
74 default => 1,
75 );
76  
77 # values topcount, bottomrunoff, approval
78 has 'DropRule' => (
79 is => 'rw',
80 isa => 'Str',
81 default => 'topcount',
82 );
83  
84 has 'FinalPhase' => (
85 is => 'rw',
86 isa => 'Bool',
87 default => 0,
88 );
89  
90 has 'FinalPhaseMethod' => (
91 is => 'rw',
92 isa => 'Str',
93 default => 'approval',
94 );
95  
96 has 'TieBreakMethod' => (
97 is => 'rw',
98 isa => 'Str',
99 default => 'buildprecedence',
100 );
101  
102 has 'QuotaTrigger' => (
103 is => 'rw',
104 isa => 'Int',
105 required => 1,
106 );
107  
108 sub BUILD {
109 my $self = shift @_;
110 my $tbm = $self->TieBreakMethod();
111 unless ( $tbm eq 'precedence' || $tbm eq 'buildprecedence' ) {
112 die "TieBreaker is restricted to precedence or buildprecedence, $tbm is invalid\n"
113 }
114 }
115  
116 sub _automatic_defeat ($I) {
117 my @defeated = ();
118 my $rule = $I->AutomaticDefeat();
119 if ( $rule eq 'NthApproval' ) { @defeated = NthApproval($I); }
120 elsif ( lc($rule) eq 'none' ) { return 0 }
121 else { ... } # other rules might be available in the future.
122 for (@defeated) { $I->Defeat($_) }
123 if (@defeated) {
124 $I->logt( "Defeated by $rule: " . join( ', ', @defeated ) . '.' );
125 $I->STVEvent( { round => $I->Round, defeat => \@defeated } );
126 return 1;
127 }
128 else {
129 $I->logt("No Defeats by $rule.");
130 return 0;
131 }
132 }
133  
134 sub _set_quota ($I) {
135 my $tc = $I->TCStats();
136 my $av = $tc->{active_vote_value};
137 my $quota = $I->SetQuota();
138 $I->logv("Active Vote Value: $av (${\ int ( $av / $I->VoteValue()) }) ");
139 $I->logt("Quota is $quota (${\ int $quota / $I->VoteValue() })");
140 return $quota;
141 }
142  
143 sub _check_quota_changed ($I, $quota) {
144 return 0 unless $I->Elected();
145 my $qf = $I->{'lastquota'} - ( $I->VoteValue * $I->QuotaTrigger );
146 if ( $quota < $qf ) { return 1 }
147 return 0;
148 }
149  
150 sub _check_seatschoices ($I ) {
151 my @active = $I->GetActiveList();
152 my $seats = $I->SeatsOpen();
153 # FinalPhase is responsible for the last seat
154 if ( $I->FinalPhase && $seats == 1 ) { return 0 }
155 # Start filling seats if running out of choices.
156 # Necessary to charge so that votes don't transfer.
157 if ( $seats >= @active ) {
158 my @sorted = $I->UnTieList( 'TopCount', @active );
159 my $elect = $sorted[0];
160 $I->Elect($elect);
161 $I->Charge( $elect, 0 ); # No Quota.
162 $I->logt(
163 "Seats Open: ${seats}. Choices: ${\ scalar(@active) }. Electing: ${elect}"
164 );
165 $I->{'lastcharge'}{$elect} = $I->VoteValue;
166 $I->STVEvent(
167 {
168 round => $I->Round,
169 quota => 0,
170 charge => $I->VoteValue,
171 iterations => 0,
172 detail => $I->{'lastcharge'},
173 }
174 );
175 $I->NewRound;
176 return 1;
177 }
178 return 0;
179 }
180  
181 sub _do_charge ( $I, $quota, @elected ) {
182 my $chargecalc = $I->CalcCharge($quota);
183 my $result =
184 FullCascadeCharge( $I->GetBallots, $quota, $chargecalc, $I->GetActive,
185 $I->VoteValue );
186 $I->{'lastcharge'} = $chargecalc;
187 $I->logv( ChargeTable( $chargecalc, $result ) );
188 $I->STVEvent(
189 { round => $I->Round, elected => [@elected],
190 result => $result, charge => $chargecalc, } );
191 return $chargecalc;
192 }
193  
194 sub _re_charge ( $I, $quota ) {
195 # my $chargecalc = $I->CalcCharge($quota);
196 # my $result =
197 # FullCascadeCharge( $I->GetBallots, $quota, $chargecalc, $I->GetActive,
198 # $I->VoteValue );
199 # return { charge => $chargecalc, result => $result }
200 die 'recharge';
201 }
202  
203 sub _do_drop ( $I ) {
204 if ( $I->DropRule eq 'bottomrunoff' ) {
205 return $I->BottomRunOff }
206 elsif ( $I->DropRule eq 'approval' ) {
207 return
208 [ $I->UntieActive( 'Approval', 'precedence' )->OrderedList() ]->[-1];
209 }
210 elsif ( $I->DropRule eq 'topcount' ) {
211 return
212 [ $I->UntieActive( 'TopCount', 'precedence' )->OrderedList() ]->[-1];
213 }
214 else { die "Invalid DropRule: ${\ $I->DropRule }\n" }
215 }
216  
217 sub _finalphase ($I) {
218 return 0 unless $I->FinalPhase;
219 return 0 unless $I->SeatsOpen == 1;
220 my $finalmthd = $I->FinalPhaseMethod;
221 my @suspended = $I->Suspended();
222 $I->Reinstate( @suspended );
223 # my @defeated = $I->Defeated();
224 # for my $choice (@defeated) {
225 # $I->{'choice_status'}->{$choice}{'state'} = 'hopeful';
226 # $I->{'Active'}{$choice} = 1;
227 # }
228  
229 # path('/tmp/mockd.pl')->spew( Dumper $I->BallotSet() );
230 # path('/tmp/mockdactive.txt')->spew( map { "$_\n"} ( $I->GetActiveList));
231 $I->logv("Only One Seat Remains, Elect last choice by $finalmthd");
232 $I->logv("reinstating ${\ join ', ', } ") if @suspended;
233 $I->logv( WeightedTable($I) );
234 my $winner = undef;
235 if ( $finalmthd =~ /Approval|TopCount/ ) {
236 $winner = do {
237 my @l = $I->UntieActive( $finalmthd, 'precedence' )->OrderedList();
238 $l[0];
239 };
240 }
241 elsif ( $finalmthd eq 'IRV' ) {
242 $winner = $I->RunIRV()->{'winner'};
243 } elsif ( $finalmthd =~ /smith/i ) {
244 # die "Smith IRV is unweighted aborting";
245 warn "precedencefile ${\ $I->PrecedenceFile }";
246 my $CIRV = Vote::Count::Method::CondorcetIRV->new(
247 BallotSet => $I->BallotSet(),
248 TieBreakMethod => 'precedence',
249 PrecedenceFile => $I->PrecedenceFile,
250 );
251 $CIRV->SetActive( dclone $I->GetActive );
252 warn "CIRV active = @{[ $CIRV->GetActiveList ]}" ;
253 $winner = $CIRV->SmithSetIRV()->{'winner'};
254 # die $CIRV->logd;
255 $I->logv( $CIRV->PairMatrix->MatrixTable );
256 $I->logv( $CIRV->PairMatrix->ScoreTable );
257 $I->logv( $CIRV->PairMatrix->PairingVotesTable );
258 $I->logv( $CIRV->logv );
259 }
260 $I->logt("Last Seat By ${finalmthd}. Elected: $winner");
261 $I->STVEvent(
262 { round => $I->Round,
263 finalphase => 'approval',
264 winner => $winner,
265 approval => $I->Approval->RawCount
266 }
267 );
268 $I->Elect($winner);
269 return 1;
270 }
271  
272 sub StartElection ( $Election ) {
273 $Election->STVFloor();
274 my @precedence = ();
275 if ( $Election->TieBreakMethod() eq 'precedence' ) {
276 @precedence =
277 path( $Election->PrecedenceFile() )->lines( { chomp => 1 } );
278 $Election->logv(qq/## Tie Breaker Precedence:/);
279 }
280 else {
281 @precedence =
282 $Election->UntieActive( 'TopCount', 'Approval' )->OrderedList;
283 path( $Election->CalculatedPrecedenceFile )
284 ->spew( map { "$_\n" } (@precedence) );
285 $Election->PrecedenceFile( $Election->CalculatedPrecedenceFile );
286 $Election->TieBreakMethod('Precedence');
287 $Election->logv(
288 qq/## Tie Breaker Precedence from Top Count, Approval, FallBack:/);
289 }
290 my $prec = 0;
291 $Election->logv( map { "${\ ++$prec }. $_" } @precedence );
292 $Election->{'lastquota'} = 0;
293 }
294  
295 sub Conduct ( $I ) {
296 my $forever = () = $I->GetChoices;
297 $forever += 2;
298 # Check Complete is in loop condition
299 CONDUCTCASCADELOOP: while ( $I->SeatsOpen() ) {
300 # uncoverable something
301 if ( $forever-- < 0 ) {
302 warn "infinite loop break from CONDUCTCASCADELOOP\n";
303 last CONDUCTCASCADELOOP;
304 }
305 $I->logt("## Round ${\ $I->Round() }");
306 # Quota
307 my $quota = $I->_set_quota();
308 my $changed = $I->_check_quota_changed( $quota ) ;
309 warn "--- changed $changed";
310 warn "*** quota set $quota . check changed $changed *** ${\ $I->{lastquota} } - " ; $changed = $I->_check_quota_changed( $quota ) ;
311 warn "^^^ quota set $quota . check changed $changed *** ${\ $I->{lastquota} } - " ;
312 if ( $I->_check_quota_changed( $quota ) ) {
313 my $maxtries = 10;
314 my $result = {};
315 warn "maxtries $maxtries --- " . $I->_check_quota_changed( $quota );
316 warn ~~$I->_check_quota_changed . " $maxtries";
317 until ( ! $I->_check_quota_changed ) {
318 last unless $maxtries;
319 die 'here' ;
320 $result = $I->_re_charge( $quota );
321 $maxtries--;
322 $I->{'lastquota'} = $quota;
323 $quota = $I->_set_quota();
324 }
325 $I->STVEvent( { round => $I->Round, quota => $quota } );
326 $I->Logv( "Recharge Round ${\ $I->Round }\n" .
327 ChargeTable( $result->{charge}, $result->{result} ) );
328 }
329 $I->STVEvent(
330 {
331 round => $I->Round,
332 approval => $I->Approval->RawCount,
333 topcount => $I->TopCount->RawCount
334 }
335 );
336 $I->logv( WeightedTable($I) );
337 # Automatic Defeat
338 if ($I->_automatic_defeat() ) {
339 $I->NewRound($quota);
340 next CONDUCTCASCADELOOP;
341 }
342 # Check Seats vs remaining.
343 # Start Electing Remaining Choices, apply Final Phase if applicable.
344 if ($I->_check_seatschoices()) {
345 $I->NewRound($quota);
346 next CONDUCTCASCADELOOP;
347 }
348  
349 # Elect
350 my @elected = $I->QuotaElectDo($quota);
351 # Charge
352 if (@elected) {
353 $I->logt( "Elected: " . join( ', ', @elected ) );
354 my $charge = $I->_do_charge( $quota, @elected );
355 $I->NewRound( $quota, $charge );
356 next CONDUCTCASCADELOOP;
357 }
358 else {
359 $I->logv('No Choices Meet Quota');
360 }
361 next CONDUCTCASCADELOOP if $I->_finalphase();
362 # Drop Rule
363 if ( my $defeat = $I->_do_drop() ) {
364 $I->Suspend($defeat);
365 $I->logv("Suspending: $defeat");
366 $I->STVEvent( { round => $I->Round, suspend => [$defeat] } );
367 $I->NewRound($quota);
368 next CONDUCTCASCADELOOP;
369 }
370 ENDROUND:
371  
372 }
373 $I->logt( "Elected: " . join ', ', ( sort $I->Elected ) );
374 $I->STVEvent( { elected => [ sort $I->Elected ] } );
375 $I->WriteSTVEvent;
376 return sort $I->Elected;
377 }
378  
379 1;
380  
381 #FOOTER
382  
383 =pod
384  
385 BUG TRACKER
386  
387 L<https://github.com/brainbuz/Vote-Count/issues>
388  
389 AUTHOR
390  
391 John Karr (BRAINBUZ) brainbuz@cpan.org
392  
393 CONTRIBUTORS
394  
395 Copyright 2019-2021 by John Karr (BRAINBUZ) brainbuz@cpan.org.
396  
397 LICENSE
398  
399 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>.
400  
401 SUPPORT
402  
403 This software is provided as is, per the terms of the GNU Public License. Professional support and customisation services are available from the author.
404  
405 =cut
406