-
Notifications
You must be signed in to change notification settings - Fork 1
/
simpleBP.html
1400 lines (1285 loc) · 67.8 KB
/
simpleBP.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:pref="http://www.w3.org/2002/Math/preference"
pref:renderer="css">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<link href="./css/bootstrap.min.css" rel="stylesheet">
<link rel="shortcut icon" href="./voteIcon.ico"/>
<link rel="shortcut icon" href="./voteIcon.ico"/>
<link rel="stylesheet" type="text/css" href="./vmDefault.css"/>
<link rel="stylesheet" type="text/css" href="./css/jquery-ui.min.css" />
<link rel="stylesheet" type="text/css" href="./css/googlefonts.css" />
<script language="JavaScript1.4" type="text/javascript">
pageModDate = "3 June 2018 18:00 AEST";
// last edited by Vishal Mohanty
</script>
<script src="./js/alasql.min.js"></script>
<script lang="javascript" src="./js/xlsx.full.min.js"></script>
<script type="text/javascript" src="./js//papaparse.min.js"></script>
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript" src="./js/jquery-ui.min.js"></script>
<script type="text/javascript" src="./js/jquery.flot.js"></script>
<script type="text/javascript" src="./js/bootstrap.min.js"></script>
<script type="text/javascript" async
src="./js/MathJax/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<script type="text/javascript" src="./sha256.js"></script>
<script type="text/javascript" src="./BigInt.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// Starting sample size notes
$("a.toggleStartingSampleNotes").click(function(){
$(".startingSampleNotes").toggle();
if ($("a.toggleStartingSampleNotes").text() == 'Show Technical Notes') {
$("a.toggleStartingSampleNotes").text('Hide technical notes.');
} else {
$("a.toggleStartingSampleNotes").text('Show Technical Notes');
}
return(false);
}
);
// Ending sample size notes
$("a.toggleEndingSampleNotes").click(function(){
$(".endingSampleNotes").toggle();
if ($("a.toggleEndingSampleNotes").text() == 'Show Technical Notes') {
$("a.toggleEndingSampleNotes").text('Hide technical notes.');
} else {
$("a.toggleEndingSampleNotes").text('Show Technical Notes');
}
return(false);
}
);
// Random sampling notes
$("a.toggleRandomSampleNotes").click(function(){
$(".randomSampleNotes").toggle();
if ($("a.toggleRandomSampleNotes").text() == 'Show Technical Notes') {
$("a.toggleRandomSampleNotes").text('Hide technical notes.');
} else {
$("a.toggleRandomSampleNotes").text('Show Technical Notes');
}
return(false);
}
);
$(".notes").hide();
$(".notes").css({color:"#333", 'font-size':"80%", 'margin-left':"5%", 'background-color':'#eee'});
$("#hideAllProse").click(function(){$("p:not(form p),pre:not(form pre),table:not(form table),ul:not(form ul),li:not(form li),#visualizing,#placeholder,#plotTitle,#considerations" ).toggle();$(".notes").hide();$("#hideAll").show();});
// set up the first contest
addContest();
$("#nBallots").change(function(){$('#nObj').val(this.value);updateVotes();});
//$("#addContestButton").click(function(){addContest();});
//$("#removeContestButton").click(function(){removeContest();});
$("input[type=text]").focus(function(){this.select();});
$("#risk").change(function(){updateVotes();});
$("#nextItem").click(function(){nextSample();});
$("#reset").click(function(){resetMe();});
//$("#voteForContest").change(function(){updateVotes();});
$("#showSequence").change(function(){writeList();});
$("#showHash").change(function(){writeList();});
$("#lookUpBallot").click(function(){
lookUpBallots($('#ballotList').val().split(',').sort(numberLessThan), true);
});
});
// ------------------------------------
/*Global variables declaration*/
var candidates = [];
var winners = [];
var losers = [];
var names = [];
var waldFactor = [];
var ballots;
var risk;
var wf1=0.0; //Wald factor 1
var wf2 = 0.0; //Wald factor 2
/*finding the minimum margin*/
var minMargin;
var testStatistics;
/*Hashing function*/
var hasher;
var sample = new Array(3);
sample[0] = new Array();
sample[1] = new Array();
sample[2] = new Array();
var manifest = null; //For parse manifest
/*Function which sets up the contest
No Parameters
Returns true upon successfull execution*/
function addContest() {
candidates.push([]); //Creates new contest
names.push([]);
winners.push([]);
losers.push([]);
var conStr = (candidates.length-1).toString();
//Setting up the contest name and adding and removing candidate buttons, also the candidate fields
var str = '<hr align="left" id="hrCon' + conStr + '"><div class="form-group" id="contest' + conStr + '" contest="' + conStr + '">' +
'<label for="contestName' + conStr + '">Contest Name: </label>' +
'<input class="form-control" type="text" size="80" placeholder="Contest" id="contestName' + conStr + '" class="contestName" /><br />' +
'<p><span class="label">Reported Votes:</span></p></div><br />' +
'<div class="addCandidate" id="addCandidate' + conStr + '" contest="' + conStr + '">' +
'<button class="btn btn-success" type="button" id="addCandidateButton' + conStr +
'" value="Add Candidate' +
'" contest="' + conStr + '">Add Candidate</button> ' +
'<button class="btn btn-danger" type="button" id="removeCandidateButton' + conStr +
'" value="Remove Last Candidate' +
'" contest="' + conStr + '">Remove Last Candidate</button></div>';
$(".contestList").append(str);
//Add initially 2 candidates
$("#contest" + (candidates.length-1).toString()).append(addCandidate(candidates.length-1));
$("#contest" + (candidates.length-1).toString()).append(addCandidate(candidates.length-1));
//Setting up the Add Candidate and Remove Candidate functionalities
var conRef = "#contest" + conStr;
var candRefLast = '.candidate.contest' + candidates.length + ':last';
var thisContest = candidates.length-1;
$("#contestName" + conStr).blur(function(){names[conStr][0] = this.value;});
$("#addCandidateButton" + conStr).click(function(){$(conRef).append(addCandidate(conStr));updateVotes();});
$("#removeCandidateButton" + conStr).click(function(){$(candRefLast).remove();
candidates[thisContest].pop();
names[thisContest].pop();
updateVotes();}
);
return(true);
}
/*Function which removes most recently added contest
Not needed currently
function removeContest(){
var conStr = (candidates.length-1).toString();
$("#hrCon" + conStr).remove();
$("#contest" + conStr).remove();
$("#addCandidateButton" + conStr).remove();
$("#removeCandidateButton" + conStr).remove();
candidates.pop();
names.pop();
return(true);
}*/
/*Function to add a single candidate
No Parameters
Returns a fully setup candidate field*/
function addCandidate(contest) {
candidates[contest].push(0); //Adding candidate to current contest
var theCandidate = (parseInt(contest)+1).toString() + '_' + candidates[contest].length.toString(); //Address next candidate
//Sets up fields for candidate name and number of votes secured
return('<form class="form-inline"><div class="candidate contest' + (parseInt(contest)+1).toString() + '" ' +
'id="candidate_' + theCandidate + '">' +
'<label for="name' + theCandidate + '">Candidate ' + candidates[contest].length + ' Name: </label> ' +
'<input class="form-control" type="text" value="Candidate '+ candidates[contest].length.toString()+'" size="40" id="name' + theCandidate + '" onblur="names[' + contest + '][' +
(candidates[contest].length-1) + ']=this.value;" />' +
'<label for="nBallots' + theCandidate + '"> Votes: ' + '</label>' +
'<input class="form-control" type="number" value="0" min="0" size="10" id="nBallots' + theCandidate + '" onblur="updateVotes()"/></div></form>');
}
/*Builds the matrix of test statistics and populates the Audit Progress matrix.
Assumes that winners[] and losers[] have been populated.
No Parameters
Returns true upon completion
*/
function buildTestMatrix() {
//Setting up the table
var str = '<div class="testStatistic" id="testStatistic" >' +
'<table class="table table-nonfluid" id="testMatrix"><tbody></tbody></table></div>';
//Clearing the existing table
$(".testTable").empty();
$(".testTable").append(str);
str = '';
str += '<tr><th>Audited Votes</th>';
for (var i=0; i < candidates.length; i++) {
//Create the winner's names headers
for (var W=0; W < winners[i].length; W++) {
str += '<th class="info" id="Twinner_' + i + '_' + winners[i][W] + '">' + names[i][winners[i][W]] +
' <input type="text" class="voteSpinner" id="votes_for_' + i + '_' + winners[i][W] +
'" value="0" /></th>';
}
str += '</tr>';
//Creating the first loser
str += '<tr id="Tloser_' + i + '_' + losers[0][0] + '"><th class="info">' + names[0][losers[0][0]] +
' <input type="text" class="voteSpinner" id="votes_for_' + i + '_' + losers[0][0] +
'" value="0" /></th>';
//The field reflecting the progress of the auditing
str += '<td id="T_' + [i, losers[0][0], winners[0][0]].join('_') + '">1</td>';
//Populating the remaining losers
for (var L=1; L < losers[i].length; L++) {
str += '<tr id="Tloser_' + i + '_' + losers[i][L] + '"><th class="info">' + names[i][losers[i][L]] +
' <input type="text" class="voteSpinner" id="votes_for_' + i + '_' + losers[i][L] +
'" value="0" /></th>';
str += '</tr>';
}
}
$("#testStatistic tbody").append(str);
$("#testStatistic td").css('backgroundColor', '#E55');
$(".voteRow").css('backgroundColor', '#999');
$(".voteSpinner").spinner({min: 0});
//In case the number of votes seen for a particular candidate changes, call updateTestStatistic
for (var i=0; i< candidates.length; i++) {
$("[id^=votes_for_" + i + "]").change(
(function(x){ return function(){updateTestStatistic(x);}})(i));
}
$('.ui-spinner-button').click(function() {$(this).siblings('input').change();});
/*
// populate the Wald factor matrix
waldFactor = [];
for (var i=0; i < candidates.length; i++) {
waldFactor.push({});
for (var W=0; W < winners[i].length; W++) {
for (var L=0; L < losers[i].length; L++) {
hashString = winners[i][W] + ',' + losers[i][L];
waldFactor[i][hashString] = candidates[i][winners[i][W]] /
(candidates[i][winners[i][W]] + candidates[i][losers[i][L]]);
}
}
}*/
//Wald factors necessary for our computation
var dum = candidates[0].slice().sort(numberLessThan).reverse();
wf1 = 2.0*dum[0]/(dum[0]+dum[1]);
wf2 = 2.0*(ballots-dum[0])/(2.0*ballots-dum[0]-dum[1]);
return(true);
}
/*Function to test the progress of the audit
Parameters: Contest i which in our case is 0 always
No return value*/
function updateTestStatistic(i) {
risk = parsePercent($("#risk").val());
var totVotes = totWinVotes = totLosVotes = 0;
for (var W=0; W < winners[i].length; W++) {
vW = parseInt($("#votes_for_" + i + '_' + winners[i][W]).spinner('value'));
totVotes += vW;
totWinVotes += vW;}
for (var L=0; L < losers[i].length; L++) {
vL = parseInt($("#votes_for_" + i + '_' + losers[i][L]).spinner('value'));
totVotes += vL;
totLosVotes += vL;
}
ts = 1.0/(Math.pow(wf1, totWinVotes) * Math.pow(wf2, totLosVotes));
$("#T_" + [0, losers[0][0], winners[0][0]].join('_')).text(roundToDig(ts, 2));
if (ts <= risk) {
$("#T_" + [0, losers[0][0], winners[0][0]].join('_')).css('backgroundColor', '#5E5');
} else {
$("#T_" + [0, losers[0][0], winners[0][0]].join('_')).css('backgroundColor', '#E55');
}
$("#sizeSoFar_" + i).text("Audited votes for " + $("#contestName" + i).val() + ": " + commify(totVotes));
}
/*Function to hash the next sequence number
No Parameters
No return value*/
function hashMe() {
hasher = new jsSHA($("#seedValue").val() + "," +
$("#samNum").val(), "ASCII");
$("#nObj").val(parseInt($("#nObj").val()));
if ($("#nObj").val() == 'NaN') {
$("#nObj").val(1);
}
try {
sample[0].push($("#samNum").val());
sample[1].push(hasher.getHash("SHA-256", "HEX"));
sample[2].push(1 +
modInt( str2bigInt(hasher.getHash("SHA-256", "HEX"), 16, 0),
parseInt($("#nObj").val())
)
);
writeList();
$("#sortedList").val(sample[2].slice().sort(numberLessThan).join(','));
$("#ballotList").val($("#sortedList").val());
var deDupeList = sortMultiple(sample[2], numberLessThan);
$("#sortedDedupeList").val(deDupeList[0].join(','));
if (vMinMax(deDupeList[1])[1] > 1) {
$("#duplicates").val('Ballot, multiplicity\n' + arrayToString(findRepeats(deDupeList)));
}
} catch(e) {
}
}
/*Function to write the list of ballots selected
No Parameters
Returns true on successfull execution*/
function writeList() { // writes the list of ballots selected
if ($("#showSequence").prop('checked') &
$("#showHash").prop('checked') ) {
$("#list").val('sequence_number, hash value, ballot\n' + arrayToString(sample));
} else if ($("#showSequence").prop('checked')) {
$("#list").val('sequence_number, ballot\n' + arrayToString([sample[0],sample[2]]));
} else if ($("#showHash").prop('checked')) {
$("#list").val('hash, ballot\n' + arrayToString([sample[1],sample[2]]));
} else {
$("#list").val(sample[2].join(','));
}
return(true);
}
/*Initialization function
No Parameters
No return value*/
function startMe() {
clearList();
hashMe();
}
/*Function to clear the lists created
No Parameters
No return value*/
function clearList() { // clear the lists
sample = new Array(3);
sample[0] = new Array();
sample[1] = new Array();
sample[2] = new Array();
$("#list").val('');
$("#sortedList").val('');
$("#sortedDedupeList").val('');
$("#ballotList").val('');
$("#duplicates").val('');
if(findMinMargin()) {
buildTestMatrix();
}
}
/*Reset function to reset everything to defaults
No Parameters
No return value*/
function resetMe() {
clearList();
$("#samNum").val('0');
}
/*Function which draws the next sample, of #samMany ballots
No Parameters
No return value*/
function nextSample() {
for (var i=0; i < parseInt($("#samMany").val()); i++) {
$("#samNum").val(parseInt($("#samNum").val()) + 1);
hashMe();
}
}
/*Function which segregatest the candidates into winners and losers and also computes
the Average Sample Number (ASN) of votes
No Parameters
Returns whether there are sufficient candidates & Min Margin is calculated &
sum of votes for candidates doesn't exceed total number of votes*/
function findMinMargin() {
ballots = parseInt($("#nBallots").val());
if (candidates.length > 0) {
minMargin = ballots;
} else {
minMargin = Number.NaN;
}
var ballOk = !isNaN(ballots);
var opsOk = true;
var votesOk = true;
var asn = Number.NaN;
//Reading candidate votes into candidate[] Array
try {
asn = 0;
for (var i=0; i < candidates.length; i++) {
var cani = 1; //Number of winners
if (candidates[i].length < cani ) { // not enough candidates
opsOk = false;
}
for (var j=0; j < candidates[i].length; j++) {
candidates[i][j] = parseInt($("#nBallots" + (i+1).toString() + '_' + (j+1).toString()).val());
}
if (vSum(candidates[i]) > cani*ballots) { // too many votes
votesOk = false;
}
//Spliting the group into winners and losers
var dum = candidates[i].slice().sort(numberLessThan).reverse(); //duplicates and sorts
minMargin = Math.min(minMargin, dum[cani-1] - dum[cani]);
winners[i] = [];
losers[i] = [];
for (var j=0; j < candidates[i].length; j++) { // set colors; build winner and loser lists
var theCandidate = (i+1).toString() + '_' + (j+1).toString();
if (candidates[i][j] > dum[cani]) {
$("#candidate_" + theCandidate).css('backgroundColor', '#5e5');
winners[i].push(j);
} else {
$("#candidate_" + theCandidate).css('backgroundColor', '');
losers[i].push(j);
}
}
/* If risk limit has been set; we can calculate sample size if all margins are
defined.*/
if (parsePercent($("#risk").val())){
asn = Math.max(asn, findAsn(ballots,
dum[cani-1],
dum[cani]));
}
}
}
//Catching and reporting exceptions
//Reseting values in case of error
catch(e) {
minMargin = 'undefined';
asn = 'undefined';
alert(e);
}
if (!opsOk | isNaN(minMargin)) {
minMargin = 'undefined';
asn = 'undefined';
$("#theDilutedMargin").text('Diluted margin: undefined');
$("#theMargin").text('Smallest margin (votes): undefined');
$("#asn").text('Expected sample size: undefined');
}
//If there are sufficient candidates and min Margin is calculated successfully
else {
$("#theMargin").text('Smallest margin (votes): ' + commify(minMargin) + '');
$("#theDilutedMargin").text(' Diluted margin: ' + commify(doubleToStr(100*minMargin/ballots,2)) + '%');
$("#asn").text('Expected sample size: ' + commify(asn) + '');
buildTestMatrix();
}
if (!(opsOk & votesOk & ballOk)) {
try {
for (var i=0; i < candidates.length; i++) {
var vf = 1;
if (candidates[i].length < vf ) {
throw 'Fewer candidates than voting opportunities in contest!';
}
if (vSum(candidates[i]) > vf*ballots) {
throw 'More votes than voting opportunities in contest!';
}
}
} catch(e) {
alert(e);
}
}
return(opsOk & votesOk & ballOk);
}
/* returns Wald's "average sample number" (ASN)
Refer Mohanty Vanessa et. al. for the ASN formula*/
function findAsn(ballots, vw, vl) { //
/* ballots = total ballots in the contest
vw = ballots cast for the winner of the pair
vl = ballots cast for the loser of the pair
*/
try {
risk = parsePercent($("#risk").val());
if (vw > vl) {
pw = vw/ballots;
pl = vl/ballots;
zw = Math.log(2.0*pw/(pw+pl));
zl = Math.log(2.0*(1-pw)/(2.0-pw-pl));
console.log(pw, pl, zw, zl);
asn = Math.ceil(
(Math.log(1.0/risk))/(pw*zw + (1-pw)*zl));
} else {
asn = 'undefined';
}
} catch(e) {
asn = 'undefined';
}
return(asn);
}
/*Function called when the number of votes are updated*/
function updateVotes() {
clearSampleSizes();
//findMinMargin();
return(true);
}
/*Function to clear the sample sizes*/
function clearSampleSizes() {
$('#startSampleSize').html('…');
if (findMinMargin()) {
buildTestMatrix();
}
return(true);
}
/*Ballot manifest function to look up the ballots as presented in the webpage*/
function lookUpBallots(whichBallots, sort) {
for (var i=0; i < whichBallots.length; i++) {
whichBallots[i] = parseInt(whichBallots[i]); // the ballots to find
}
if (parseManifest()) {
if (vSum(manifest[1]) != $("#nObj").val()) {
alert('Error: Number of ballots in the manifest, ' + vSum(manifest[1]).toString() +
' is not equal to the number of ballots in the contest, ' + $("#nObj").val() +'!');
return(Number.NaN);
} else if (vMinMax(whichBallots)[1] > vSum(manifest[1])) {
alert('Error: Requested ballot exceeds the number of ballots in the manifest!');
return(Number.NaN);
} else if (vMinMax(whichBallots)[0] < 1) {
alert('Error: Requested ballot number is negative!');
return(Number.NaN);
}
var manCum = new Array(manifest[0].length); // cumulative number of ballots in batches
manCum[0] = 0;
for (var i=1; i < manifest[0].length; i++) {
manCum[i] = manCum[i-1] + manifest[1][i-1];
}
var lookUp = new Array(3); // ballot (absolute numbering), batch, identifier_in_batch
lookUp[0] = whichBallots;
lookUp[1] = new Array(whichBallots.length);
lookUp[2] = new Array(whichBallots.length);
for (var i = 0; i < whichBallots.length; i++) {
var j = 0;
while (manCum[j] < whichBallots[i]) {
j++;
}
j--;
lookUp[1][i] = manifest[0][j];
if (typeof(manifest[2][j]) == 'object') {
lookUp[2][i] = manifest[2][j][whichBallots[i] - manCum[j] - 1];
} else {
lookUp[2][i] = whichBallots[i] - manCum[j] + manifest[2][j] - 1;
}
}
var str = 'sorted_number, ballot, batch_label, which_ballot_in_batch\n';
for (var i=0; i < lookUp[0].length; i++ ) {
str += (i+1).toString() + ', ' + lookUp[0][i].toString() + ', ' +
lookUp[1][i].toString() + ', ' + lookUp[2][i].toString() + '\n';
}
} else {
str = 'The manifest cannot be parsed.\n' +
'Be sure that the each line of the manifest consists of a batch ' +
'label followed by a comma and a number or ' +
'a colon-separated ballot range or a list of identifiers in parentheses. ' +
'There must be exactly one comma per line.\n';
$("#manifest").val(str + $("#manifest").val());
}
$("#lookUp").val(str);
}
/*Function used to parse through the Ballot input by the user
No Parameters
Returns true on successfull parsing else false*/
function parseManifest() {
var stuff = $("#manifest").val().replace(/\n+/gi,'\n').split('\n');
var grabBagRegExp = /^ *\(.+\) *$/i
var batches = new Array(3);
batches[0] = new Array(); // batch labels
batches[1] = new Array(); // number of ballots in the batch
batches[2] = new Array(); // number of the first ballot in the batch, or an array of identifiers
success = true;
var j = 0;
for (var i=0; i < stuff.length; i++) {
if (typeof(stuff[i]) == 'undefined' || stuff[i] == null || stuff[i] == '') {
continue;
} else if (stuff[i].indexOf(',') < 0) {
alert('Error! Line ' + (i+1).toString() + ' of the manifest has no commas: ' +
stuff[i].toString());
success = false;
} else {
var dum = stuff[i].split(',');
if (dum.length != 2) {
alert('Error! Line ' + (i+1).toString() + ' of the manifest does not parse: ' +
stuff[i].toString() +
' Be sure it has exactly one comma, separating the label from the ' +
'number of ballots or the ballot range.' );
success = false;
} else {
batches[0][j] = dum[0];
if (dum[1].indexOf(':') >= 0) {
var mRange = dum[1].split(':');
batches[1][j] = parseInt(mRange[1]) - parseInt(mRange[0]) + 1;
batches[2][j] = parseInt(mRange[0]);
} else if (grabBagRegExp.test(dum[1])) {
batches[2][j] = new Array();
batches[2][j] = dum[1].replace(/( *\( *| *\) *)/g,'').replace(/ +/g,' ').split(' ');
batches[1][j] = batches[2][j].length;
} else {
batches[1][j] = parseInt(dum[1]);
batches[2][j] = 1;
}
j++;
}
}
}
if (success) {
manifest = batches;
} else {
manifest = null;
}
return(success);
}
// General-purpose utilities
function numberLessThan(a,b) { // numerical ordering for javascript sort function
var diff = parseFloat(a)-parseFloat(b);
if (diff < 0) {
return(-1);
} else if (diff == 0) {
return(0);
} else {
return(1);
}
}
function sortMultiple(list,order) { // sort a list, tabulate multiplicity of items. list is unchanged
var ans = null;
if (list.length > 0) {
var temp = list.slice();
if (typeof(order) != 'undefined' && order != null) {
temp.sort(order);
} else {
temp.sort();
}
ans = new Array(2);
ans[0] = new Array();
ans[1] = new Array();
ans[0][0] = temp[0];
ans[1][0] = 1;
for (var i=1; i < temp.length; i++) {
if (temp[i] == ans[0].slice(-1)) {
ans[1][ans[1].length-1]++;
} else {
ans[0].push(temp[i]);
ans[1].push(1);
}
}
}
return(ans);
}
function findRepeats(list) { // find elements with multiplicity greater than one
// in an array generated by sortMultiple()
var ans = new Array(2);
ans[0] = new Array();
ans[1] = new Array();
for (var i = 0; i < list[0].length; i++) {
if (list[1][i] > 1) {
ans[0].push(list[0][i]);
ans[1].push(list[1][i]);
}
}
return(ans);
}
function arrayToString(arr) { // formats an array
var str = '';
var cols = arr.length;
var rows = arr[0].length;
for (var j=0; j < rows; j++) {
for (var i=0; i < cols; i++) {
str+= arr[i][j] + ',';
}
str = str.replace(/,$/,'\n');
}
return(str);
}
function vCum(list) { // vector of cumulative sum
var list2 = list;
for (var i = 1; i < list.length; i++ ) {
list2[i] += list2[i-1];
}
return(list2);
}
function vMinMax(list){ // returns min and max of list
var mn;
var mx;
if (list.length == 'undefined' || list.length == 0) {
mn = list;
mx = list;
} else {
mn = list[0];
mx = list[0];
for (var i=1; i < list.length; i++) {
if (mn > list[i]) mn = list[i];
if (mx < list[i]) mx = list[i];
}
}
var vmnmx = new Array(mn,mx);
return(vmnmx);
}
function vSum(list) { // computes the sum of the elements of list
var tot = 0.0;
for (var i = 0; i < list.length; i++) {
tot += list[i];
}
return(tot);
}
function removeAllBlanks(s){
return(s.replace(/ +/gm,''));
}
function commify(num) { // punctuate number strings greater than 1,000 in magnitude
var str;
var strA = (removeAllBlanks(num.toString())).toLowerCase();
if ( (strA.indexOf('e') > -1) || (strA.indexOf('d') > -1) ) {
str = strA; // don't mess with exponential notation
} else {
str = strA;
var curLoc = str.length;
if ( str.indexOf('.') > -1 ) {
curLoc = str.indexOf('.');
}
var negSign = str.indexOf('-');
for (var loc = curLoc-4; loc > negSign; loc -= 3) {
str = str.substr(0,loc+1) + ',' + str.substr(loc+1, str.length);
}
}
return(str);
}
function parsePercent(s) {
// parse a number that contains a % sign to turn it into a decimal fraction
var value;
if (s.indexOf('%') == -1) {
value = parseFloat(trimBlanks(removeCommas(s)))
} else {
while (s.indexOf('%') != -1) {
s = s.substring(0,s.indexOf('%')) +
s.substring(s.indexOf('%')+1,s.length)
}
value = parseFloat(trimBlanks(removeCommas(s)))/100;
}
return(value);
}
function roundToDig(num, dig) { // rounds a number or list to dig digits after the decimal place
var powOfTen = Math.pow(10,dig);
if ((typeof(num)).toLowerCase() == 'number') {
var fmt = Math.round(num*powOfTen)/powOfTen;
return(fmt);
} else if ((typeof(num)).toLowerCase() == 'object' ||
(typeof(num)).toLowerCase() == 'array') {
var fmt = new Array(num.length);
for (var i = 0; i < num.length; i++) {
fmt[i] = Math.round(num[i]*powOfTen)/powOfTen;
}
return(fmt);
} else {
alert('Error #1 in roundToDig(): argument (' + num.toString() + ') is not a number or an array');
return(Math.NaN);
}
}
function doubleToStr(num,dig) {
// returns a string representation of num, rounded to dig digits after the decimal
return(removeAllBlanks(roundToDig(num,dig).toString()));
}
function removeCommas(s) { // removes commas from a string
return(s.replace(/,/gm,''));
}
function trimBlanks(s) { // remove leading and trailing spaces
s = s.replace(/^ +/gm,'');
s = s.replace(/ +$/gm,'');
return(s);
}
// -->
</script>
<title>Simple Ballot Polling Audit for India</title>
</head>
<body onload="startMe();resetMe();" style="font-family: Montserrat;">
</head>
<div id="bodyDiv">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<!--div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Home</a>
</div-->
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="simpleBP.html">HOME</a>
</ul>
<ul class="nav navbar-nav">
<li><a href="overall.html">EFFICIENT AUDITING OF INDIAN ELECTIONS<span class="sr-only">(current)</span></a></li>
</ul>
<ul class="nav navbar-nav">
<li><a href="https://www.stat.berkeley.edu/~stark/Vote/auditTools.htm">STARK'S BALLOT COMPARISON AUDIT</a></li></ul>
<ul class="nav navbar-nav">
<li><a href="https://www.stat.berkeley.edu/~stark/Vote/ballotPollTools.htm">STARK'S BALLOT POLLING AUDIT</a></li></ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="developersSimpleBP.html">DEVELOPERS</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<h1>
<center>SIMPLE BALLOT POLLING FOR INDIA</center>
</h1>
<div>
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#theory" aria-controls="theory" role="tab" data-toggle="tab">THEORY</a></li>
<li role="presentation"><a href="#contest" aria-controls="contest" role="tab" data-toggle="tab">CONTEST DETAILS</a></li>
<li role="presentation"><a href="#sampling" aria-controls="sampling" role="tab" data-toggle="tab">RANDOM SAMPLING</a></li>
<li role="presentation"><a href="#lookup" aria-controls="lookup" role="tab" data-toggle="tab">BALLOT LOOK-UP</a></li>
<li role="presentation"><a href="#wald" aria-controls="wald" role="tab" data-toggle="tab">AUDIT PROGRESS TOOL</a></li>
<!--li role="presentation"><a href="#technical" aria-controls="technical" role="tab" data-toggle="tab">Technical Notes</a></li-->
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="theory">
<p>
This page implements some tools to conduct <b>Simple Ballot-Polling</b> risk-limiting audits as described in
<a href="#">Auditing of Indian Elections</a>, by Mohanty, Vanessa et.al.
For the previous versions of <b>Ballot Polling</b> risk-limiting audit go to Philip Stark's page
using the navbar on the top.
For an implementation of tools for <b>Ballot Comparison</b> risk-limiting audits navigate to
Philip Stark's webpage titled "Ballot Comparison Audit".
</p>
<!--p id="hideAll">
To hide or show everything but the tools <button type="button" class="btn btn-default" id="hideAllProse">Click Here</button>
</p-->
<div class="panel panel-primary">
<div class="panel-heading">THEORY</div>
<div class="panel-body">
<p>
A <b>Risk-Limiting Audit</b>, also sometimes referred to as the Result-Conforming Audit
is a method of post-election audit designed to confirm the election results by examining a small sample of
the votes. The <b>Risk Limit</b> is the maximum probability that the audit will not detect
any error in election result when it is present. The error here refers to the case when the
candidate/party declared as the winner in a given constituency is not the actual winner who
would be reported by a full-hand manual count of the votes.
</p>
<p>
There are quite a many tools for performing risk-limiting audit, the prominent of them being the
Ballot Polling and the Ballot Comparison Audit. This page implemenets the tools for performing
Ballot Polling Audit in a simpler manner. The original Ballot Polling audit as implemented by
Philip Stark can be found on his webpage. Stark has also developed tools for <b>Ballot Comparison Audit</b>
which can be reached using the navigation links on the top of the page.
</p>
<p>
The expected sample size calculations for this method depend on the risk limit and the
reported margins. It is calculated assuming that the reported margins are correct.
</p>
<p>
Risk limiting method audits the ballots at random using a random number generator. If the random sample gives
sufficient evidence that the election outcome is correct then the audit stops. Else if convincing evidence
is not attained, we keep auditing the ballots until we have audited all the ballots, in which case the
exact election outcome is known to us. This is based on the assumption that the manual auditing represents
the ground truth and is error-free.
</p>
<p>
The tools on this webpage have been divided into sections depending upon their usage. The following lists the
tools and their utility in the audit process.
</p>
<ul>
<li><b>Contest Details: </b> In this you have to fill in the information about the contest which will help in
interpreting the results. </li>
<li><b>Random Sampling: </b>This helps you to generate a random sequence of numbers which
tell the sequence in which the ballots should be audited.</li>
<li><b>Ballot Look-up: </b>This will help find those ballots using a ballot manifest</li>
<li><b>Wald's Probability Ratio Test: </b>This is a live tool used to determine whether the audit can stop,
given the votes on the ballots in the sample.</li>
</ul>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="contest">
<div class="panel panel-primary">
<div class="panel-heading">INITIAL SAMPLE SIZE</div>
<div class="panel-body">
<p>
The initial sample size tool lets you enter the particulars of the contest to be
audited, the total ballots cast in the contest, and the vote totals for each
candidate in the contest.
The form helps you anticipate the number of randomly selected
ballots that might need to be inspected to attain a given limit on the risk,
under the assumption that the reported percentages for each candidate
are correct.
It is completely legitimate to sample one at a time and check whether enough have been
sampled using the <b>Audit Progress Tool</b> but this
form can help auditors anticipate how many ballots the audit is likely to require
and to retrieve ballots more efficiently, by reducing the number of times a given batch of
ballots is opened.
</p>
<p>
Enter the details in the form as per the following guidelines.
<ul>
<li>Enter the total number of ballots cast in the contest.</li>
<li>Specify the name of the contest.</li>
<li>Add or remove the required number of candidates using the appropriate buttons.</li>
<li>Enter the candidate name and the reported number of votes secured by him/her in the contest.</li>
<li>Specify the risk-limit to which to audit the contest.
</ul>
</p>
<p>
Once you are done filling up all the details, kindly proceed to the next tab to find the random
sample of ballots to be audited.
</p>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">CONTEST INFORMATION</div>
<div class="panel-body">
<form action="#" method="get">
<div class="form-group">
<div class="panel panel-default">
<div class="panel-heading">CONTEST INFORMATION</div>
<div class="panel-body">
<label for="nBallots">Ballots cast in all precincts:</label>
<input class="form-control" type="number" min="0" value="0" size="10" name="nBallots" id="nBallots" />
<span class="label label-default" id="theMargin">Smallest margin (votes): undefined </span>
<span class="label label-default" id="theDilutedMargin">Diluted margin: undefined</span>
<div class="contestList"></div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">AUDIT PARAMETERS</div>
<div class="panel-body">
<label for="risk">Risk limit:</label>
<input class="form-control" type="text" size="10" name="risk" id="risk" value="5%" />
<span class="label label-default" id="asn">Expected sample size: undefined</span>
</div>
</div>
</div>
</form>
</div>
</div>
<!--div class="panel panel-info">
<div class="panel-heading">Considerations for deciding which contests to audit together</div>
<div class="panel-body">
<p>
Taking a larger initial sample can avoid needing to expand the sample later,
depending on the rate of ballots for each candidate in the sample.
Avoiding "escalation" can make the audit less complicated.
</p>
<p>
The number of ballots the audit must examine before stopping depends on the smallest
diluted margin among the contests to be audited together (as well as the risk limit,
the errors the audit finds, and so on).
All else equal, the larger the diluted margin is, the smaller the sample size needs to be.
</p>