forked from vishalmohanty/Indian_audit_tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoverall.html
914 lines (825 loc) · 41.9 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
<!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="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/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="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<link href="https://fonts.googleapis.com/css?family=PT+Sans|Poppins|Roboto|Lobster|Bree+Serif|Product+Sans|Montserrat" rel="stylesheet">
<script language="JavaScript1.4" type="text/javascript">
pageModDate = "21 July 2017 10:27 AEST";
// last edited by Vishal Mohanty
</script>
<script src="http://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script>
<script lang="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.6/xlsx.full.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.3.2/papaparse.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/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) {
var curConst;
var c, p, v;
for(var i=0; i<dataIn.length-1; i++){
curConst=dataIn[i]["State Name"]+"_"+dataIn[i]["PC NAME"];
if(constPresent(constArray, curConst)==-1){
constArray.push(curConst);
}
if(dataIn[i]["PARTY NAME"]!="IND" && dataIn[i]["OVER TOTAL VOTES POLLED IN CONSTITUENCY"]>=1
&& 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]["OVER TOTAL VOTES POLLED IN CONSTITUENCY"]>=1){
c=constPresent(constArray, dataIn[i]["State Name"]+"_"+dataIn[i]["PC NAME"]);
p=partyPresent(partyArray, dataIn[i]["PARTY NAME"]);
$("#votes_for_" + c + "_" + p).val(dataIn[i]["TOTAL"]);
}
}
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
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 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
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 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 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]);
}
}
return winMargArray;
}
/*Auxilliary function to find the expected factor for the number of votes in auditing
a particular subset of constituencies where the winner has won.
Parameters: Index of constiteuncy after which constituencies are only audited (when
sorted in non-decreasing order of diluted margins)
Return value: Expected factor*/
function findExpec(sortWinMargArray, idx){
try{
var coalition =findCoalition();
if(coalition==undefined)
throw('Error at finding expected number of ballots. Invalid coalition array.');
var toppleMargin = findToppleMargin();
if(toppleMargin==undefined)
throw('Error at finding 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);
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 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 winMargArray =findWinMarg();
if(winMargArray==undefined)
throw('Error at finding overall risks. Invalid winner\'s margins array.');
var sortWinMargArray=(findWinMarg().sort(numberLessThan));
if(sortWinMargArray==undefined)
throw('Error at finding overall risks. Invalid sorted winner\'s margins 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.');
}catch(e){
alert(e);
return undefined;
}
var minIdx=0, minMargin;
var riskArray = []; //Stores the risk limit for every constituency
var count=0, dCount=0, check; //Counter for audited and dropped constituencies
var dropStr=''; //String storing the names of dropped constituencies
if(sortWinMargArray.length<toppleMargin){
for(var i=0; i<constArray.length; i++){
riskArray[i]=0;
}
$("#expecAudit").val(0);
}
else{
for(var i=1; i<toppleMargin; i++){
if(findExpec(sortWinMargArray, minIdx)>findExpec(sortWinMargArray, i))
minIdx = i;
}
winMargArray.sort(numberLessThan); //Non-decereasing order
minMargin = winMargArray[minIdx];
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
if(margArray[i]<minMargin){ //If diluted margin in winner's constituency is more
dCount++; //than the prescribed upper limit, no need to audit
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(findExpec(sortWinMargArray, minIdx)*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">HOME</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">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>
<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="#theory" aria-controls="theory" role="tab" data-toggle="tab">THEORY</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="theory">
<!--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 features a one-time contest for electing a single Party or Coalition
to power in the Central Government.
</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-->
<p>
<div class="panel panel-primary">
<div class="panel-heading">THEORY</div>
<div class="panel-body">
<p>
A <b>Risk-Computing Tool</b> is a tool used to compute the most efficient risk-limits to which to
perform risk-limit auditing in constituencies while determining the overall election result.
There are quite a many tools for performing risk-limiting audit, the prominent of them being the
Ballot Polling Audit. Tools for performing that is present in Vanessa's webpage titled
<b>Simple Ballot Polling Audit</b>. You could alternatively use Stark's Ballot Polling tools at
<b>Stark's Ballot Polling Audit</b>.
</p>
<p>
Multi-level elections can be efficiently audited. The desired confidence level in the overall
elections can be shared by individual constituencies. The product of the risk limits in the
individual constituencies results in the overall risk limit. When a coalition wins the elections,
auditing is done in those constituencies where the parties belonging to that particular
coalition has 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 number of 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>
<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 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 e.g.
in constituencies where full manual recounting has been performed, we know the ground truth.
</li>
<li>Set the desired 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 constituency outcome
changes and hence recompute the risk limits and continue the audit.
</li>
</ul>
</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 be similar in structure to the csv
version of the following file released by the Election Commission of India
<a href="http://eci.nic.in/eci_main/archiveofge2014/33.ConstituencyWiseDetailedResultPC.xlsx">
Constituency wise detailed result</a>.
Delete the first two rows from the excel file and save the file in CSV(Comma Separated
Values) format. The file should then have the first row containing the following headers:
<ul>
<li>State Name</li>
<li>PC NAME</li>
<li>CANDIDATE NAME</li>
<li>PARTY NAME</li>
<li>TOTAL</li>
<li>OVER TOTAL VOTES POLLED IN CONSTITUENCY</li>
</ul>
Only when the file contains all of these headers will the tool be able to process it.
Although it may contain some other headers as well. Alternatively you could download
the file format from the following link <a href="inputFormat.csv" download>Input Format</a>.
It contains the column headers and you just have to fill in the data.
</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">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 >
Say the desired overall confidence level is $$ 1 - \epsilon $$
</p>
<p >
We can audit the constituency <em>i</em> in which the winner has won to confidence level
$$1-\epsilon^{\alpha_i} $$
</p>
<p >
where \(\alpha_i\) is some constant between 0 and 1. A <em>flipset</em> is a set of constituencies
whose result when flipped will alter the election results. The \(\alpha_i\) must be such that
in any <em>flipset</em>, the sum of the \(\alpha_i\) of the constituencies must sum up to greater than
1.
</p>
<p >
The cost of auditing constituency i to risk limit \(\alpha_i\) where the diluted margin is
\(\mu_i\) is proportional to \(\frac{\alpha_i}{\mu_i}\). Our tool solves the Linear Program
of minimizing the total cost of auditing the constituencies in which the winner won subject to
the constraints that \(0\leqslant \alpha_i\leqslant 1\) and for every minimal flipset, \(\sum \alpha_i \geqslant 1\).
</p>
</div>
</div>
</div>
</div>
</body>
</html>