-
Notifications
You must be signed in to change notification settings - Fork 1
/
overall.html
1025 lines (966 loc) · 50.7 KB
/
overall.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 -->
<!-- Bootstrap -->
<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">
$(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();});
$("input[type=text]").focus(function(){this.select();});
$("#risk").change(function(){updateRisk();});
});
// ------------ Functions implementing tool-----------
//Global declaration of variables
var risk;
var constArray = [];
var partyArray = [];
//Functions implementing our tool
/*Function called when the risk value is changed
No Parameters
Returns true upon successfull execution*/
function updateRisk(){
try{
risk = parsePercent($("#risk").val());
if(risk>1 || risk<0)
throw 'Risk percentage should be between 0% and 100% only';
}
catch(e){
$("#risk").val("10%");
risk = parsePercent($("#risk").val());
alert(e);
}
return true;
}
/*Clearing the audit requirements for the previous audit
No Parameters
Returns true on successful execution*/
function refreshFile(){
constArray = [];
partyArray = [];
//$("#contestInfo form").reset();
$("#voteTally div").html('');
$("#auditParam div").html('');
$("#computeRisk div").html('');
document.getElementById("metaData").style=("display: none;");
return true;
}
/*Function called when a new file is selected
It calls upon to build the overall matrix when the input file has proper format
No Parameters
No return value*/
function loadFile(){
refreshFile();
//Bringing back the tools to life when file is loaded properly
document.getElementById("contestInfo").style="display: block;";
document.getElementById("voteTally").style="display: block;";
document.getElementById("auditParam").style="display: block;";
document.getElementById("computeRisk").style="display: block;";
//Parsing the input csv file
Papa.parse(document.getElementById("inputFile").files[0], {
header:true,
complete: function(results) {
buildOverallMat(results.data);
}
});
}
/*Function to determine is a party is already present in the list of parties
Parameters: The party array, party name
Returns index of party name if present, else -1*/
function partyPresent(partyArray, p){
for(var i=0; i<partyArray.length; i++){
if(partyArray[i]==p.toUpperCase())
return i;
}
return -1;
}
/*Function to determine if a constituency is already present in list of constituencies
Parameters: Constituency array, constituency name
Returns index of constituency if present, else -1*/
function constPresent(constArray, c){
for(var i=0; i<constArray.length; i++){
if(constArray[i]==c)
return i;
}
return -1;
}
/*Function to build the overall input table for votes for parties in every constituency
No Parameters
Return type: boolean*/
function buildOverallMat(dataIn) {
// console.log(dataIn);
var curConst;
var c, p, v;
for(var i=0; i<dataIn.length-1; i++){ //VT: Not sure why this only runs to length-1. VM: Somehow the last row in dataIn is null always
curConst=dataIn[i]["STATE NAME"]+"_"+dataIn[i]["CONSTITUENCY NAME"];
if(constPresent(constArray, curConst)==-1){
constArray.push(curConst);
}
if(dataIn[i]["PARTY NAME"]!="IND" && dataIn[i]["VOTES SECURED"]>=dataIn[i]["TOTAL VOTES POLLED IN CONSTITUENCY"]/100
&& partyPresent(partyArray, dataIn[i]["PARTY NAME"])==-1){
partyArray.push(dataIn[i]["PARTY NAME"].toUpperCase());
}
}
//Placing values in the palce holders in HTML form
$("#nSeats").val(constArray.length);
$("#nCandi").val(partyArray.length);
nConstituencies = constArray.length;
var str = '<div><table class="table table-striped table-bordered" id="overallMat">'+
'<thead></thead><tbody></tbody></table></div>';
$(".overallTable").empty();
$(".overallTable").append(str);
str = '';
str += '<tr><th></th>';
//Placing the parties names on the first row of the table
for (var W=0; W < partyArray.length; W++) {
str += '<th class="text-left success" id="Tcandidate_' + 0 + '_' + W + '">' +
'<label><input type="checkbox" value="" id="coalition_' + W + '"></label>'+
partyArray[W] + ' </th>';
}
$("#candidateStatistic thead").empty();
$("#candidateStatistic thead").append(str);
str='';
//Placing constituency names and votes in subsequent rows
for (var i=0; i < constArray.length; i++) {
str += '</tr>';
str += '<tr id="Tconsti_' + i + '"><td class="info">'+
constArray[i] + ' '+
'<label><input type="checkbox" value="" id="consti_' + i + '"></label> </td>';
for (var W=0; W < partyArray.length; W++) {
str += '<td class="text-left"><input type="number" id="votes_for_' + i + '_' + W +
'" value="0"/></td>';
}
str += '</tr>';
}
$("#candidateStatistic tbody").empty();
$("#candidateStatistic tbody").append(str);
//Changing the values of votes received by parties in resepective constituencies
for(var i=0; i<dataIn.length-1; i++){
if(dataIn[i]["PARTY NAME"]!="IND" && dataIn[i]["VOTES SECURED"]>=dataIn[i]["TOTAL VOTES POLLED IN CONSTITUENCY"]/100){
c=constPresent(constArray, dataIn[i]["STATE NAME"]+"_"+dataIn[i]["CONSTITUENCY NAME"]);
p=partyPresent(partyArray, dataIn[i]["PARTY NAME"]);
$("#votes_for_" + c + "_" + p).val(dataIn[i]["VOTES SECURED"]);
}
}
return(true);
}
/*Function to convert the votes for every constituency into percentages for the parties
No parameters
Return Value: 2D array storing the percentages of votes for parties in every constituency*/
function convToPerc(){
var percArray = [];
var dataArray = [];
var sumArray = new Array(constArray.length).fill(0);
for (var i=0; i < constArray.length; i++) {
dataArray[i]=[];
for (var W=0; W < partyArray.length; W++) {
dataArray[i][W]=parseInt($("#votes_for_" + i + "_" + W).val());
sumArray[i]+=parseInt($("#votes_for_" + i + "_" + W).val());
}
try{
if(sumArray[i]==0)
throw('Invalid data for constituency '+ constArray[i]+'');
}
catch(e){
alert(e);
return undefined;
}
}
for(var i=0; i<constArray.length; i++){
percArray[i]=[];
for (var W=0; W < partyArray.length; W++) {
percArray[i][W]=dataArray[i][W]/sumArray[i];
}
}
return percArray;
}
/*Function to find the diluted margin in every constituency
**(This is called mu_i in our paper.)
No Parameters
Return value: 1D array storing the diluted margins.*/
function findMargins(){
try{
var percArray =convToPerc();
if(percArray==undefined)
throw('Invalid Percentage Data');
}
catch(e){
alert(e);
return undefined;
}
var margArray = new Array(constArray.length);
var sortedArray = [];
for(var i=0; i<constArray.length; i++){
sortedArray = percArray[i].slice().sort(numberLessThan).reverse();
margArray[i]=sortedArray[0]-sortedArray[1];
}
return margArray;
}
/*Function to find the fraction of votes in every constituency
**that were given to either the winner or the runner-up.
**(This is called p_wl in our paper.)
No Parameters
Return value: 1D array storing the summed fractions of
winner's and runner-up's votes.*/
function findPercWL(){
try{
var percArray =convToPerc();
if(percArray==undefined)
throw('Invalid Percentage Data');
}
catch(e){
alert(e);
return undefined;
}
var percWLArray = new Array(constArray.length);
var sortedArray = [];
for(var i=0; i<constArray.length; i++){
sortedArray = percArray[i].slice().sort(numberLessThan).reverse();
percWLArray[i] = sortedArray[0]+sortedArray[1];
}
return percWLArray;
}
/*Function to find the BRAVO Cost factor for the winner's constituencies
defined as 1/(mu*mu*p_wl)
Parameters: None
Returns: Array storing the cost factors*/
function findBRAVOcf(){
try{
var margins = findMargins();
if(margins==undefined)
throw('Error at finding BRAVO cost factors. Invalid margins');
var PWLArray = findPercWL();
if(PWLArray==undefined)
throw('Error at finding BRAVO cost factors. Invalid PWLArray');
}catch(e){
alert(e);
return undefined;
}
var BRAVOcfArray = [];
for (var i = 0; i < constArray.length; i++) {
BRAVOcfArray.push(1/(Math.pow(margins[i], 2)*PWLArray[i]));
}
return BRAVOcfArray;
}
/*Function to find the winners in every constituency
No Parameters
Return Value: 1D array storing Winning Party number in every constituency*/
function findWinners(){
try{
var percArray =convToPerc();
if(percArray==undefined)
throw('Invalid Percentage Data');
}
catch(e){
alert(e);
return undefined;
}
var winArray = new Array(constArray.length);
var maxIdx; //temporary variable to store the winner's index
for(var i=0; i<constArray.length; i++){
maxIdx = 0;
for(var j=1; j<partyArray.length; j++){
if(percArray[i][j]>percArray[i][maxIdx])
maxIdx = j;
}
winArray[i]=maxIdx;
}
return winArray;
}
/*Function to find the number of seats that every party has secured in the overall results
No parameters
Return value: 1D array storing the number of seats secures by every party*/
function findSeats(){
try{
var winArray =findWinners();
if(winArray==undefined)
throw('Invalid winner\'s Array');
}
catch(e){
alert(e);
return undefined;
}
var seats = new Array(partyArray.length).fill(0);
var winner=0;
for(var i=0; i<winArray.length; i++){
seats[winArray[i]]++;
}
return seats;
}
/*Function to find the overall winner of the elections
No parameters
Return value: Winning party number*/
function findOverWin(){
try{
var winArray =findWinners();
if(winArray==undefined)
throw('Invalid Winner\'s Array');
var seats =findSeats();
if(seats==undefined)
throw('Invalid Seats');
}catch(e){
alert(e);
return undefined;
}
var winner = 0;
for(var i=1; i<seats.length; i++){
if(seats[i]>seats[winner])
winner=i;
}
return winner;
}
/*Function which finds the coalition of the selected parties
No Parameters
Returns an array storing the indices of the parties in the coalition*/
function findCoalition(){
try{
if(partyArray.length==0)
throw('Error at Finding Coalition. Check the parties.');
}catch(e){
alert(e);
return undefined;
}
var coalition = new Array();
var check;
for (var j=0; j < partyArray.length; j++) {
check = document.getElementById('coalition_' + j);
if(check.checked){
coalition.push(j);
}
}
return coalition;
}
/*Function to find the toppling margin = votes for coalition-half of seats
No parameters
Returns toppling margin if coalition is successfull, else -1*/
function findToppleMargin(){
try{
var coalition =findCoalition();
if(coalition==undefined)
throw('Error at finding toppling Margin. Coalition undefined');
var seats =findSeats();
if(seats==undefined)
throw('Error at finding toppling Margin. Seats undefined.');
}catch(e){
alert(e);
return undefined;
}
var sum=0;
try{
for (var i=0; i < coalition.length; i++) {
sum+=seats[coalition[i]];
}
if(sum>=Math.floor(constArray.length/2)+1)
return (sum-Math.floor(constArray.length/2));
else
console.log(coalition);
throw('Not sufficient seats in coalition to form government');
}
catch(e){
alert(e);
return undefined;
}
}
/*Function which determines if party p is present in the coalition*/
function inCoalition(p){
try{
var coalition =findCoalition();
if(coalition==undefined)
throw('Error at verifying membership in coalition. Check coalition.');
}catch(e){
alert(e);
return undefined;
}
for(var i=0; i<coalition.length; i++){
if(coalition[i]==p)
return true;
}
return false;
}
/*Function to find the diluted margins in constituencies wherer the winning party was elected
No Parameters
Return value: 1D array storing the diluted margins*/
function findWinMarg(){
try{
var margArray =findMargins();
if(margArray==undefined)
throw('Error at finding Winner\'s margins. Invalid Margins Array.');
var BRAVOcfArray = findBRAVOcf();
if(BRAVOcfArray==undefined)
throw('Error at finding P_WL\'s margins. Invalid P_WL Array.');
var winArray =findWinners();
if(winArray==undefined)
throw('Error at finding Winner\'s margins. Invalid Winner\'s Array.');
var winner = findOverWin();
if(winner==undefined)
throw('Error at finding Winner\'s margins. Invalid winner.');
var coalition = findCoalition();
if(coalition==undefined)
throw('Error at finding Winner\'s margins. Invalid coalition Array.');
}catch(e){
alert(e);
return undefined;
}
var winMargArray = [];
var winBCFArray = [];
var check=0;
for(var i=0; i<constArray.length; i++){
check = document.getElementById('consti_' + i);
if(inCoalition(winArray[i]) && !check.checked){
winMargArray.push(margArray[i]);
winBCFArray.push(BRAVOcfArray[i]);
}
}
return [winMargArray, winBCFArray];
}
/*Auxiliary function to find the expected factor for the number of votes in the
BRAVO method
Parameters: Array storing the BRAVO cost factors for the winner's constituencies
in descending order, Idx-number of constituencies to drop.
Return value: Expected factor*/
function findBRAVOExpec(sortWinBCFArray, idx){
var toppleMargin = findToppleMargin();
if(toppleMargin==undefined)
throw('Error at finding expected number of ballots. Invalid toppling Margin.');
var sum=0.0;
for(var j=idx; j<sortWinBCFArray.length; j++){
sum+=sortWinBCFArray[j];
}
sum*=1.0/(toppleMargin-idx);
console.log(sum);
return sum;
}
/*Auxilliary function to find the expected factor for the number of votes in auditing
using LSKM, a particular subset of constituencies where the winner has won.
Parameters: Index of constituency after which constituencies are only audited (when
sorted in non-decreasing order of diluted margins)
Return value: Expected factor*/
function findLSKMExpec(sortWinMargArray, idx){
try{
var coalition =findCoalition();
if(coalition==undefined)
throw('Error at finding LSKM expected number of ballots. Invalid coalition array.');
var toppleMargin = findToppleMargin();
if(toppleMargin==undefined)
throw('Error at finding LSKM expected number of ballots. Invalid toppling Margin.');
}catch(e){
alert(e);
return undefined;
}
var sum=0.0;
for(var j=idx; j<sortWinMargArray.length; j++){
sum+=1.0/sortWinMargArray[j];
}
sum*=1.0/(toppleMargin-idx);
console.log(sum);
return sum;
}
/*Main auxilliary function to find the risks upto which the constituencies should be audited
No Parameters
Return value: 1D array storing the risks*/
function findOverRisks(){
try{
var margArray =findMargins();
if(margArray==undefined)
throw('Error at finding overall risks. Invalid margins array.');
var BRAVOcfArray=findBRAVOcf();
if(BRAVOcfArray==undefined)
throw('Error at finding overall risks. Invalid BRAVO cf array.');
var winArray = findWinners();
if(winArray==undefined)
throw('Error at finding overall risks. Invalid winner\'s array.');
var winner = findOverWin();
if(winner==undefined)
throw('Error at finding overall risks. Invalid winner.');
var winTuple = findWinMarg();
if(winTuple==undefined)
throw('Error at finding overall risks. Invalid winTuple.');
var winMargArray =winTuple[0];
if(winMargArray==undefined)
throw('Error at finding overall risks. Invalid winner\'s margins array.');
var sortWinMargArray=(winTuple[0].sort(numberLessThan)); //ascending order
if(sortWinMargArray==undefined)
throw('Error at finding overall risks. Invalid sorted winner\'s margins array.');
var winBCFArray = winTuple[1];
if(winBCFArray==undefined)
throw('Error at finding overall risks. Invalid winner\'s BCF array.');
var sortWinBCFArray=(winTuple[1].sort(numberLessThan).reverse()); //descending order
if(sortWinBCFArray==undefined)
throw('Error at finding overall risks. Invalid sorted winner\'s BCF array.');
var coalition =findCoalition();
if(coalition==undefined)
throw('Error at finding overall risks. Invalid coalition array.');
var risk = parsePercent($("#risk").val());
if(risk==undefined)
throw('Error at finding overall risks. Invalid risk.');
var toppleMargin =findToppleMargin();
if(toppleMargin==undefined)
throw('Error at finding overall risks. Invalid toppling margin.');
var auditMethod=$('input[name=auditMethod]:checked').val();
}catch(e){
alert(e);
return undefined;
}
var riskArray = []; //Stores the risk limit for every constituency
console.log(toppleMargin);
if(sortWinMargArray.length<toppleMargin){
for(var i=0; i<constArray.length; i++){
riskArray[i]=0;
}
$("#expecAudit").val(0);
}
else{
var expecCost = 0.0;
var tempCost = 0.0;
var minIdx=0;
var minMargin=0;
var maxBCF = 0;
var count=0, dCount=0, check; //Counter for audited and dropped constituencies
var dropStr=''; //String storing the names of dropped constituencies
if(toppleMargin>1){
if(auditMethod=="LSKMComparison")
expecCost = findLSKMExpec(sortWinMargArray, 0);
else
expecCost = findBRAVOExpec(sortWinBCFArray, 0);
}
for(var i=1; i<toppleMargin; i++){
if(auditMethod=="LSKMComparison")
tempCost = findLSKMExpec(sortWinMargArray, i);
else
tempCost = findBRAVOExpec(sortWinBCFArray, i);
if(expecCost>tempCost){
expecCost = tempCost;
minIdx = i;
}
}
if(auditMethod=="LSKMComparison"){
minMargin = sortWinMargArray[minIdx];
}
else{
maxBCF = sortWinBCFArray[minIdx];
}
// console.log(auditMethod);
// console.log(minMargin);
// console.log(maxBCF);
// console.log(expecCost);
// console.log(minIdx);
// console.log("Start");
// console.log(sortWinBCFArray);
for(i=0; i<constArray.length; i++){
check = document.getElementById('consti_' + i);
if(check.checked)
riskArray[i]=0;
else if(inCoalition(winArray[i])){ //If not a winner's constituency, no need to audit
// console.log(BRAVOcfArray[i]);
if((auditMethod=="LSKMComparison" && margArray[i]<minMargin) //Filter constituencies having greater margin
|| (auditMethod=="BRAVOBallotPolling" && BRAVOcfArray[i]>maxBCF)){ //Filter const. having lesser cost fac
dCount++;
riskArray[i]=0;
dropStr+=constArray[i];
dropStr+='; ';
}
else{ //If diluted margin within the desired upper bound.
riskArray[i]=Math.pow(risk, 1.0/(toppleMargin-minIdx));
count++;
}
}
else{
riskArray[i]=0;
}
}
$("#expecAudit").val(Math.ceil(expecCost*Math.log(1/risk)));
}
//Changing the meta-data of current Audit
document.getElementById("metaData").style="display: block;";
$("#winConst").val(count+dCount);
$("#dropConst").val(dCount);
if(dropStr!='')
$("#dropConstNames").val(dropStr);
else
$("#dropConstNames").val("No constituencies were dropped");
return riskArray;
}
/*Function called whenever "Compute" is clicked
No Parameters
Creates the table showing the various risks for every constituency
Returns true upon successfull execution*/
function findRisks(){
try{
var riskArray = findOverRisks();
if(riskArray==undefined)
throw('Error at finding risks. Invalid risk array.');
}catch(e){
alert(e);
return undefined;
}
//Building the risk matrix
var str='';
str = '<div class="table-responsive">'+
'<table class="table table-bordered table-striped" id="riskMat">'+
'<thead></thead><tbody></tbody></table></div>';
$(".newRisks").empty();
$(".newRisks").append(str);
str = '';
str+='<tr>';
//Placing the constituency names at the headers of every column
for(var i=0; i<constArray.length; i++){
str+='<th class="candidateRow text-left">'+ constArray[i] +'</th>';
}
str+='</tr>';
$("#riskMat thead").append(str);
str='';
str+='<tr>';
//Placing the risk limit values under the respective constituency names
for(var i=0; i<nConstituencies; i++){
str+='<td class="text-left">'+ roundToDig(riskArray[i], 2) + '</td>';
}
str+='</tr>';
$("#riskMat tbody").append(str);
return true;
}
//General-purpose utilities function
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);
}
}
// parse a number that contains a % sign to turn it into a decimal fraction
function parsePercent(s) {
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);
}
}
// removes commas from a string
function removeCommas(s) {
return(s.replace(/,/gm,''));
}
// remove leading and trailing spaces
function trimBlanks(s) {
s = s.replace(/^ +/gm,'');
s = s.replace(/ +$/gm,'');
return(s);
}
</script>
<title>Efficient Auditing of Indian Elections</title>
</head>
<body style="font-family: Montserrat;">
</head>
<div id="bodyDiv">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<!-- 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="overall.html">EFFICIENT AUDITING OF INDIAN ELECTIONS</a>
</ul>
<!--ul class="nav navbar-nav">
<li><a href="simpleBP.html">SIMPLE BALLOT POLLING AUDIT<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">LSKM BALLOT-LEVEL COMPARISON AUDIT</a></li></ul>
<ul class="nav navbar-nav">
<li><a href="https://www.stat.berkeley.edu/~stark/Vote/ballotPollTools.htm">BRAVO BALLOT POLLING AUDIT</a></li></ul>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="developersOverall.html">DEVELOPERS</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<h1>
<center>EFFICIENT AUDITING OF INDIAN ELECTIONS</center>
</h1>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#background" aria-controls="background" role="tab" data-toggle="tab">HOME</a></li>
<li role="presentation"><a href="#tool" aria-controls="tool" role="tab" data-toggle="tab">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="background">
<!-- <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">BACKGROUND</div>
<div class="panel-body">
<p>
This page implements the tools for finding out the <b>Risk Limits</b> for auditing of multi-level
elections as is the case in India. It considers a one-time contest for electing a single Party or Coalition
to power in the Central Government. The definition of winning is to win a majority of seats in the lok sabha (parliament).
</p>
<p> All Indian Electronic Voting Machines will be equipped with Voter-Verifiable Paper Audit Trails (VVPATs) in time for the 2019 general election, following demonstrations that the machines are <A HREF="https://indiaevm.org">susceptible to manipulation</A>. VVPATs provide evidence that each vote has been recorded as the voter intended, without having to trust the perfection or security of the machines. However, confidence in the result should only follow if the VVPAT is actually used to check the announced election result. A full manual recount of all constituencies could be prohibitively expensive and time-consuming.
<A HREF="https://www.stat.berkeley.edu/~stark/Preprints/gentle12.pdf">Risk Limiting Audits</A> could provide a high degree of confidence in an Indian election result and typically require much less manual inspection than a full hand recount of all VVPATs when the reported results are correct.
This website guides you through applying Risk Limiting Audits to Indian parliamentary elections. We use two existing risk-limiting audit methods by Lindeman, Stark et al, based on ballot-level comparisons and ballot polling.
Finally, and most importantly, we derive a novel and efficient method for auditing the overall parliamentary election result.
<b>Risk limiting audits</b> are an effective and practical method for post-election verification of the election outcome across various electoral systems. In this, we manually inspect the ballots produced by the VVPAT machine, until we are sufficiently confident that the election result is right, or we have decided to perform a full manual recount.
The election outcome can be confirmed if we audit the ballots until we know that the probability of failing to detect a wrong election result is below a certain level,
known as the <em><b>risk limit</b></em> \((\alpha\)) which can be set to arbitrarily small values.
<P>Decreasing the risk limit would lead to an increase in the expected number of ballots to be audited.
</p>
<p>
Our <b>Risk-Computing Tool</b>
The tools can be used to estimate the best way of combining individual-constituency audits to efficeintly check the overall parliamentary election
result. They compute the most efficient risk-limits to which to
perform risk-limit auditing in constituencies, given the kind of audit, assuming that the announced results are correct.
We then direct the user to perform the risk-limiting audit on each constituency using
Philip Stark's online tools.
</p>
<p>
Our new <A HREF="TBA"> paper</A> gives the technical details for efficient parliamentary audits. The desired confidence level in the overall
elections can be shared by individual constituencies.
<!-- The product of the risk limits in the
individual constituencies is the overall risk limit. -->
When a coalition wins the elections,
auditing is done in those constituencies where the parties belonging to that particular
coalition have won. The sharing of the risk limits is done assuming that the election outcome
is correct in the audited constituencies. If during the audit the result in any constituency
does change, then the risk limits to which the other constituencies have been audited must be
changed. This will require auditing more votes in those constituencies.
The new risk-limits will be reflected in the tools developed by us by simply feeding in
new election results for that particular constituency.
</p>
</div>
</div>
</p>
</div>
<div role="tabpanel" class="tab-pane" id="tool">
<div class="panel panel-primary">
<div class="panel-heading">INPUT FILE FORMAT</div>
<div class="panel-body">
The input file must be in the <b>.csv</b> format and should have the following column headers.
<ul>
<li>STATE NAME</li>
<li>CONSTITUENCY NAME</li>
<li>PARTY NAME</li>
<li>VOTES SECURED</li>
<li>TOTAL VOTES POLLED IN CONSTITUENCY</li>
</ul>
The csv input file may contain some other headers as well. You could download
the file format from the following <a href="inputFormat.csv" download>Input Format</a>.
It contains the column headers and you just have to fill in the data. Sample filled in
input file <a href="trial.csv" download>Sample Input</a>. The excel file containing results
from the 2014 General Elections is available at <a href="http://eci.nic.in/eci_main/archiveofge2014/33.ConstituencyWiseDetailedResultPC.xlsx">
Constituency wise detailed result</a>. The CSV file of the 2014 General Elections having the appropriate headers is available at <a href="ConstituencyWise.csv" download>2014 GE CSV</a>.
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">INSTRUCTIONS</div>
<div class="panel-body">
<p>
The tools on this page work as follows:
</p>
<ul>
<li>Select an input file having extension .csv in the format as mentioned in the TOOL tab.</li>
<li>Select an audit method for the individual constituencies.
<li>Select the checkboxes in the first row against the parties which form the winning coalition</li>
<li>Select the constituencies in the first column for which the data is known perfectly. For example,
in constituencies where full manual recounting has been performed, we know the ground truth.
</li>
<li>Set the desired overall risk limit.</li>
<li>Click on compute when you have successfully filled in all the fields.</li>
<li>Audit the constituencies simultaneously using one of RLA tools whose links
are present on the top of this webpage. Update the table in case any audit fails and hence recompute the risk limits and continue the overall audit.
</li>
</ul>
<p>Note: these are prototype tools designed as part of a student project. Although we have done our best to make them accurate and robust, we don't offer any warranty that the answers are perfectly correct. Please check the outputs before using for binding audits. </p>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">RISK COMPUTING TOOL</div>
<div class="panel-body">
<form action="#" method="get">
<div class="panel panel-default">
<div class="panel-heading">File Selection</div>
<div class="panel-body">
<label for="csvFile">Select a .csv file of the specified format.</label>
<label class="btn btn-danger">Browse
<input type="file" id="inputFile" onchange="loadFile()" accept=".csv" style="display: none;">
</label>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Audit Method</div>
<div class="panel-body">
<label for="auditMethod">Select Audit Method:</label>
<br>
<input type="radio" name="auditMethod" value="LSKMComparison" checked> LSKM Comparison</input><br>
<input type="radio" name="auditMethod" value="BRAVOBallotPolling"> Bravo Ballot Polling</input>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Contest Information</div>
<div class="panel-body" id="contestInfo" style="display: none;">
<div class="form-group">
<label for="nSeats">Total Number of Seats</label>
<input class="form-control" placeholder="Number of Constituencies eg.543" type="number" min="0" size="10" name="nSeats" id="nSeats" value="0" readonly/> <br>
<label for="nCandi">Number of Parties:</label>
<input class="form-control" placeholder="Number of Parties eg.10" value="0" type="number" min="0" size="10" name="nCandi" id="nCandi" readonly /> <br>
<label for="contestName' + conStr + '">Contest Name: </label>
<input class="form-control" type="text" size="80" placeholder="Contest" id="contestName' + 0 + '" class="contestName" />
</div>
</div>
</div>
<div class="panel panel-default" id="candidateStatistic" >
<div class="panel-heading">Vote Tally</div>
<div class="panel-body" id="voteTally" style="display: none;">
<div class="overallTable"></div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Audit parameters</div>
<div class="panel-body" id="auditParam" style="display: none;">
<label for="risk">Overall Risk limit:</label>
<input class="form-control" type="text" size="10" name="risk" id="risk" value="5%" />
</div>
</div>
</form>
<div class="panel panel-default">
<div class="panel-heading">Risk-limits for various constituencies</div>
<div class="panel-body" id="computeRisk" style="display: none;">
<button type="button" class="btn btn-success" onclick="findRisks()">Compute</button>
<br>
<div class="newRisks"></div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Meta-data of the current Audit</div>
<div class="panel-body" id="metaData" style="display: none;">
<label for="winConst">Number of constituencies of winning coalition</label>
<input class="form-control" type="number" min="0" size="10" name="winConst" id="winConst" value="0" readonly/> <br>
<label for="dropConst">Number of Dropped Constituencies</label>
<input class="form-control" value="0" type="number" min="0" size="10" name="dropConst" id="dropConst" readonly /> <br>
<label for="dropConstNames">Dropped Constituencies Names (with STATE NAME prefix)</label>
<input class="form-control" placeholder="Dropped Constituencies names" type="text" name="dropConstNames" id="dropConstNames" readonly /> <br>
<label for="expecAudit">Expected number of ballots to audit in case election outcome is correct in all audited constituencies</label>
<input class="form-control" value="0" type="number" min="0" size="10" name="expecAudit" id="expecAudit" readonly /> <br>
</div>
</div>
</div>
</div>
</div>
<!-- Tab panes -->
<div role="tabpanel" class="tab-pane" id="technical">
<div class="panel panel-primary">
<div class="panel-heading">Technical Notes</div>
<div class="panel-body">
<p >
Suppose the desired overall risk limit is \(\alpha.\)
</p>
<p>This is the probability of (mistakenly) accepting an election result that is actually wrong. The probability is over the random choices of the audit.</p>
<p >
We can audit constituency <em>i</em> in which the winner has won to risk limit
\(\alpha_i,\)
</p>
<p >
where \(\alpha_i\) is some constant between 0 and 1. A <em>flipset</em> is a set of constituencies