-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalg.js
More file actions
837 lines (755 loc) · 29.7 KB
/
valg.js
File metadata and controls
837 lines (755 loc) · 29.7 KB
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
var elections = {
"2009": election2009,
"2013": election2013,
"2017": election2017,
"2021": election2021,
"2025": election2025,
};
var election;
var voteTab = document.getElementById("votestab");
var seatTab = document.getElementById("seatstab");
var teamTab = document.getElementById("teamstab");
var distTab = document.getElementById("diststab");
var calcTab = document.getElementById("calcstab");
var tabs = [distTab, voteTab, seatTab, teamTab, calcTab];
var voteTable = document.getElementById("votes");
var seatTable = document.getElementById("seats");
var teamTable = document.getElementById("teams");
var statTable = document.getElementById("stats");
var distTable = document.getElementById("dists");
var logOutput = document.getElementById("log");
var voteLink = document.getElementById("voteslink");
var seatLink = document.getElementById("seatslink");
var teamLink = document.getElementById("teamslink");
var distLink = document.getElementById("distslink");
var calcLink = document.getElementById("calcslink");
var links = [distLink, voteLink, seatLink, teamLink, calcLink];
var LANG = "no-NO";
distTable.sortColumn = "Valgdistrikt";
voteTable.sortColumn = "Valgdistrikt";
voteTable.sortRow = "Totalt";
seatTable.sortColumn = "Valgdistrikt";
seatTable.sortRow = "Totalt";
teamTable.sortColumn = "Posisjon";
// Add event listeners for help buttons
for (const fieldset of document.getElementsByTagName("fieldset")) {
for (const label of fieldset.getElementsByTagName("label")) { // const fixes label in the function closure
for (const a of label.getElementsByTagName("a")) {
a.addEventListener("click", function (e) {
alert(label.title);
e.preventDefault(); // prevent link click from toggling/focusing input field
});
}
}
}
// Cut off remaining decimals
function truncate(number, decimals) {
if (number < 0) {
return -truncate(-number, decimals);
}
return Math.floor(number * 10**decimals) / 10**decimals;
};
function clearLog() {
log = "";
};
function printLog(line) {
log += line + '\n';
};
function flushLog() {
logOutput.innerHTML = log;
};
function createCell(tag, text) {
var cell = document.createElement(tag);
cell.innerText = text;
return cell;
}
function printTable(table, data, districts, parties, firstHeader, showTotals, format, fractional) {
// Reset table
const thead = table.tHead;
const tbody = table.tBodies[0];
thead.innerHTML = "";
tbody.innerHTML = "";
if (showTotals) {
const totalDistrict = {};
for (const party of parties) {
totalDistrict[party] = 0;
}
var globalTotal = 0;
for (const district in data) {
var districtTotal = 0;
for (const party in data[district]) {
const contrib = data[district][party];
districtTotal += contrib;
totalDistrict[party] += contrib;
globalTotal += contrib;
}
data[district]["Totalt"] = districtTotal;
}
data["Totalt"] = totalDistrict;
data["Totalt"]["Totalt"] = globalTotal;
}
if (fractional) {
for (const district in data) {
for (const party in data[district]) {
data[district][party] /= data[district]["Totalt"];
}
}
format = (x) => truncate(100*x, 1).toFixed(1).toLocaleString(LANG) + " %"; // TODO: decimals
}
if (table.sortColumn) {
districts.sort(function (d1, d2) {
const have1 = table.sortColumn in data[d1];
const have2 = table.sortColumn in data[d2];
if (!have1 && !have2) return d1.localeCompare(d2); // alphabetically ascending
if (!have1) return +1; // prefer d2 (as if district1 is zero)
if (!have2) return -1; // prefer d1 (as if district2 is zero)
return data[d2][table.sortColumn] - data[d1][table.sortColumn]; // numerically descending
});
var levelingIndex = districts.indexOf("Utjevningsmandater");
if (levelingIndex != -1) {
districts.push(districts.splice(levelingIndex, 1)[0]); // remove and re-add at the end
}
}
if (table.sortRow) {
parties.sort(function (p1, p2) {
const have1 = p1 in data[table.sortRow];
const have2 = p2 in data[table.sortRow];
if (!have1 && !have2) return p1.localeCompare(p2); // alphabetically ascending
if (!have1) return +1; // prefer p2 (as if district1 is zero)
if (!have2) return -1; // prefer p1 (as if district2 is zero)
return data[table.sortRow][p2] - data[table.sortRow][p1]; // numerically descending
});
}
// Print table
const head = thead.insertRow();
head.appendChild(createCell("th", firstHeader));
for (const party of parties) {
head.appendChild(createCell("th", party));
}
if (showTotals) {
head.appendChild(createCell("th", "Totalt"));
}
for (var district of districts) {
const row = tbody.insertRow();
row.appendChild(createCell("th", district));
for (var i = 0; i < parties.length; i++) {
var party = parties[i];
row.appendChild(createCell("td", party in data[district] ? format(data[district][party], i) : ""));
}
if (showTotals) {
row.appendChild(createCell("th", format(data[district]["Totalt"], 0)));
}
}
if (showTotals) {
const tfoot = table.tFoot;
tfoot.innerHTML = "";
const row = tfoot.insertRow();
row.appendChild(createCell("th", "Totalt"));
for (const party of parties) {
row.appendChild(createCell("th", format(data["Totalt"][party], 0)));
}
if (showTotals) {
row.appendChild(createCell("th", format(data["Totalt"]["Totalt"], 0)));
}
const cell = tfoot.children[0].children[0];
cell.addEventListener("click", function (e) {
table.sortRow = cell.innerText;
update();
});
}
const toggleShowFraction = function (e) {
if (table.showFraction) {
table.showFraction = !table.showFraction;
} else {
table.showFraction = true;
}
update(); // could just re-render table?
};
for (const row of tbody.children) {
if (showTotals) {
const cell = row.children[0];
cell.addEventListener("click", function (e) {
table.sortRow = cell.innerText;
update();
});
}
for (let i = 1; i < row.children.length; i++) {
const cell = row.children[i];
cell.addEventListener("click", toggleShowFraction);
}
}
for (const cell of thead.children[0].children) {
cell.addEventListener("click", function (e) {
table.sortColumn = cell.innerText;
update();
});
}
// Highlight sorted columns/rows
if (table.sortColumn) {
var i = 0;
for (var i = 0; i < thead.children[0].children.length; i++) {
if (thead.children[0].children[i].innerText == table.sortColumn) break;
}
thead.children[0].children[i].classList.add("sorted");
for (const row of tbody.children) {
row.children[i].classList.add("sorted");
}
const tfoot = table.tFoot;
if (showTotals) {
tfoot.children[0].children[i].classList.add("sorted");
}
}
if (table.sortRow) {
const tfoot = table.tFoot;
for (const row of tbody.children) {
if (row.children[0].innerText == table.sortRow) {
for (const cell of row.children) {
cell.classList.add("sorted");
}
break;
}
}
if (table.sortRow == tfoot.children[0].children[0].innerText) {
for (const cell of tfoot.children[0].children) {
cell.classList.add("sorted");
}
}
}
}
function sumLocal(local) {
var global = {};
for (var district in local) {
for (var party in local[district]) {
if (!(party in global)) {
global[party] = 0;
}
global[party] += local[district][party];
}
}
return global;
};
function sumGlobal(global) {
var total = 0;
for (var party in global) {
total += global[party];
}
return total;
}
function sainteLague14(votes, seats, totalVotes, totalSeats) {
return votes / (seats == 0 ? 1.4 : (2*seats + 1));
}
function sainteLague12(votes, seats, totalVotes, totalSeats) {
return votes / (seats == 0 ? 1.2 : (2*seats + 1));
}
function sainteLague10(votes, seats, totalVotes, totalSeats) {
return votes / (2*seats + 1);
}
function dHondt(votes, seats, totalVotes, totalSeats) {
return votes / (seats + 1);
}
function hamilton(votes, seats, totalVotes, totalSeats) {
return votes * totalSeats - seats * totalVotes; // equivalent to votes/totalVotes * totalSeats - seats, but avoids any divison by zero
}
function winnerTakesItAll(votes, seats, totalVotes, totalSeats) {
return votes;
}
var scoreFunctions = {
"Sainte-Laguë fra 1,4": sainteLague14,
"Sainte-Laguë fra 1,2": sainteLague12,
"Sainte-Laguë fra 1,0": sainteLague10,
"D’Hondt": dHondt,
"Hare/Hamilton": hamilton,
"Vinneren tar alt": winnerTakesItAll,
};
function calculateSeats(votes, totalSeats, methodName) {
var scoreFunction = scoreFunctions[methodName];
var seats = {};
for (var party in votes) {
seats[party] = 0;
}
var totalVotes = sumGlobal(votes);
var tiedParty = undefined;
for (var seat = 1; seat <= totalSeats + 1; seat++) {
var bestScore = Number.MIN_VALUE;
var bestParty = null;
for (var party in votes) {
var score = scoreFunction(votes[party], seats[party], totalVotes, totalSeats);
if (score > bestScore) {
bestScore = score;
bestParty = party;
tiedParty = undefined;
} else if (score == bestScore) {
tiedParty = party;
}
}
if (seat <= totalSeats) {
printLog(" " + seat + ". mandat til " + bestParty + " med " + bestScore + " poeng (" + seats[bestParty] + " mandater fra før)");
seats[bestParty] += 1;
} else {
printLog(" Neste mandat ville gått til " + bestParty + " med " + bestScore + " poeng (" + seats[bestParty] + " mandater fra før)");
}
}
if (tiedParty !== undefined) {
printLog(" ADVARSEL: " + bestParty + " og " + party + " har begge poengsum " + score + "; foretrekker " + bestParty); // TODO: implement edge case handling
}
return seats;
};
function calculateSeatCounts(districts, seatCount, areaFactor, minSeatsPerDistrict) {
var scores = {};
for (var district in districts) {
scores[district] = districts[district].population + areaFactor*districts[district].area
}
var success = false;
var finalSeatCounts = {};
for (var attempt = 1; !success; attempt++) {
var method = "Sainte-Laguë fra 1,0";
printLog(attempt + ". forsøk: Fordeler " + seatCount + " seter mellom " + Object.keys(districts).length + " distrikter med arealfaktor " + areaFactor + " og minst " + minSeatsPerDistrict + " seter til hvert distrikt med " + method);
var seatCounts = calculateSeats(scores, seatCount, method);
success = true;
for (var district in seatCounts) {
if (seatCounts[district] < minSeatsPerDistrict) {
printLog(" " + district + " fikk bare " + seatCounts[district] + " seter; reserverer " + minSeatsPerDistrict + " seter og holder dem utenfor kommende omfordeling");
finalSeatCounts[district] = minSeatsPerDistrict;
seatCount -= minSeatsPerDistrict;
delete scores[district];
success = false;
}
}
if (success) {
for (var district in seatCounts) {
finalSeatCounts[district] = seatCounts[district];
}
} else {
printLog("");
}
}
return finalSeatCounts;
};
function calculateAllSeatCounts(districts, totalSeatCount, globalSeatsPerDistrict, areaFactor, minSeatsPerDistrict) {
var districtCount = Object.keys(districts).length;
var globalSeatCount = globalSeatsPerDistrict * districtCount;
var localSeatCounts = calculateSeatCounts(districts, totalSeatCount, areaFactor, minSeatsPerDistrict);
printLog("");
for (var district in localSeatCounts) {
printLog("Deler " + localSeatCounts[district] + " mandater i " + district + " mellom " + (localSeatCounts[district] - globalSeatsPerDistrict) + " distriktsmandater og " + globalSeatsPerDistrict + " utjevningsmandater");
localSeatCounts[district] -= globalSeatsPerDistrict;
}
return [localSeatCounts, globalSeatCount];
};
function calculateLocalSeats(votes, localSeatCounts, methodName, localThreshold, globalThreshold) {
var seats = {};
var partyTotalVotes = sumLocal(votes);
var globalTotalVotes = sumGlobal(partyTotalVotes);
for (var district in votes) {
var localTotalVotes = sumGlobal(votes[district]);
var votesAboveThreshold = {};
for (var party in votes[district]) {
if (votes[district][party] * 100 >= localThreshold * localTotalVotes && partyTotalVotes[party] * 100 >= globalThreshold * globalTotalVotes) {
votesAboveThreshold[party] = votes[district][party];
}
}
printLog("");
printLog("Fordeler " + localSeatCounts[district] + " distriktsmandater i " + district + " mellom " + Object.keys(votesAboveThreshold).join(", ") + " (fikk minst " + localThreshold + " % av stemmene i distriktet og " + globalThreshold + " % av stemme nasjonalt) med " + methodName);
seats[district] = calculateSeats(votesAboveThreshold, localSeatCounts[district], methodName);
}
return seats;
};
function calculateGlobalSeats(localVotes, localSeats, globalSeatCount, globalThreshold, methodName, negativeGlobalSeats, requireGlobalRepresentation, exemptGlobalThresholdIflocalSeats) {
printLog("");
// Accumulate votes from each district
var globalVotes = sumLocal(localVotes);
var totalVotes = sumGlobal(globalVotes);
// Nationwide results when leveling mandates are excluded
localSeats = sumLocal(localSeats);
// Decide which parties are eligible for leveling mandates. They must meet all of these conditions:
// * run for election in all districts (can be turned off)
// * have at least 4% of the national votes (electoral threshold)
for (var party in globalVotes) {
if (party.toUpperCase() == "ANDRE") {
printLog(party + " holdes alltid utenfor fordelingen av utjevningsmandater");
delete globalVotes[party];
} else if (globalVotes[party] * 100 < globalThreshold * totalVotes) { // globalThreshold is in percent
var exempt = exemptGlobalThresholdIflocalSeats && (party in localSeats) && localSeats[party] > 0;
if (exempt) {
printLog(party + " unntas fra sperregrensen for utjevningsmandater fordi de har minst ett distriktsmandat");
} else {
printLog(party + " (" + (globalVotes[party]*100/totalVotes) + " % av nasjonale stemmer) kom under sperregrensen (" + globalThreshold + " %) og holdes utenfor fordelingen av utjevningsmandater");
delete globalVotes[party]; // party is below electoral threshold
}
} else if (requireGlobalRepresentation) {
for (var district in localVotes) {
if (!(party in localVotes[district])) {
printLog(party + " stiller ikke til valg i alle distrikter og holdes utenfor fordelingen av utjevningsmandater")
delete globalVotes[party]; // party is not registered all districts
break;
}
}
}
}
for (var attempt = 1; true; attempt++) { // may have to repeat
// Allocate all seats including leveling mandates, but exclude ineligible parties
var totalSeatCount = globalSeatCount;
for (var party in globalVotes) {
totalSeatCount += localSeats[party]; // allocate mandates for eligible parties only
}
printLog("");
printLog(attempt + ". forsøk: Fordeler " + totalSeatCount + " mandater nasjonalt mellom " + Object.keys(globalVotes).join(", ") + " (" + (totalSeatCount - globalSeatCount) + " distriktsmandater + " + globalSeatCount + " utjevningsmandater) med " + methodName);
// Nationwide results when leveling mandates are included
var globalSeats = calculateSeats(globalVotes, totalSeatCount, methodName);
// Set number of leveling mandates from difference between nationwide allocations with and without leveling mandates
// Check that no parties got fewer mandates with leveling mandates included; otherwise exclude them and repeat
var success = true;
for (var party in globalSeats) {
if (party in localSeats) {
globalSeats[party] = globalSeats[party] - localSeats[party];
}
printLog(party + " fikk " + globalSeats[party] + " utjevningsmandater (" + (localSeats[party] + globalSeats[party]) + " mandater i nasjonal fordeling - " + localSeats[party] + " distriktsmandater fra før)");
if (!negativeGlobalSeats && globalSeats[party] < 0) {
printLog(party + " fikk færre mandater i den nasjonale fordelingen med utjevningsmandater enn de har distriktsmandater fra før; holder dem utenfor kommende omfordeling");
delete globalVotes[party];
success = false;
}
}
if (success) {
return globalSeats;
}
}
};
function calculateAllSeats(votes, localSeatCounts, globalSeatCount, localThreshold, globalThreshold, localGlobalThreshold, methodName, negativeGlobalSeats, requireGlobalRepresentation, exemptGlobalThresholdIflocalSeats) {
var seats = calculateLocalSeats(votes, localSeatCounts, methodName, localThreshold, localGlobalThreshold);
seats["Utjevningsmandater"] = calculateGlobalSeats(votes, seats, globalSeatCount, globalThreshold, methodName, negativeGlobalSeats, requireGlobalRepresentation, exemptGlobalThresholdIflocalSeats);
return seats;
};
function calculateTeams(friends) {
function dfs(team, teams) {
for (var team2 of teams) {
if (team.length == team2.length) {
var isSubset = true;
for (var party of team) {
if (!team2.includes(party)) {
isSubset = false;
break;
}
}
if (isSubset) {
return; // team already explored
}
}
}
teams.push(team.slice()); // register team
// Explore new teams by adding parties that are friends with everyone already in the team
for (var newParty in friends) {
var friendsWithEveryone = true;
for (var party of team) {
if (!friends[party].includes(newParty)) {
friendsWithEveryone = false;
break;
}
}
if (friendsWithEveryone) {
team.push(newParty);
dfs(team, teams);
team.splice(team.indexOf(newParty), 1);
}
}
return teams;
};
return dfs([], []).slice(1); // drop empty team
};
function mergeDistrictData(datasets, districts, newDistrict) {
for (var dataset of datasets) {
dataset[newDistrict] = {};
for (var district of districts) {
for (var party in dataset[district]) {
if (!(party in dataset[newDistrict])) {
dataset[newDistrict][party] = 0;
}
dataset[newDistrict][party] += dataset[district][party];
}
delete dataset[district];
}
}
};
function applyDefaults(defaults) {
for (var id in defaults) {
var val = defaults[id];
var el = document.getElementById(id);
if (typeof(val) == "boolean") {
el.checked = val;
} else {
el.value = val;
}
}
};
function setElection() {
election = document.getElementById("election").value;
if (!(election in elections)) {
alert("Unknown election " + election);
}
election = elections[election];
if ("defaults" in election) {
applyDefaults(election["defaults"]);
}
update();
}
function deepcopy(a) {
if (typeof(a) != "object") {
return a;
}
const b = {};
for (const k in a) {
b[k] = deepcopy(a[k]);
}
return b;
}
function update() {
clearLog();
// Deep copy votes, so original data is not modified
var votes = deepcopy(election.votes);
var districts = deepcopy(election.districts);
var localThreshold = parseFloat(document.getElementById("localthreshold").value);
var globalThreshold = parseFloat(document.getElementById("globalthreshold").value);
var localGlobalThreshold = document.getElementById("globalthresholdonlyleveling").checked ? 0.0 : globalThreshold;
var totalSeatCount = parseInt(document.getElementById("totalseats").value);
var negativeGlobalSeats = !document.getElementById("minzeroglobalseats").checked;
var areaFactor = parseFloat(document.getElementById("areafactor").value);
var requireGlobalRepresentation = document.getElementById("requireglobalrepresentation").checked;
var exemptGlobalThresholdIflocalSeats = document.getElementById("exemptglobalthreshold").checked;
var methodName = document.getElementById("method").value;
var extraVotesInput = document.getElementById("extravotes");
var extraPartyInput = document.getElementById("extraparty");
var extraDistrictInput = document.getElementById("extradistrict");
var extraVotes = parseInt(extraVotesInput.value);
var extraParty = extraPartyInput.value;
var extraDistrict = extraDistrictInput.value;
var districtCount = parseInt(document.getElementById("mergedistricts").value.split(" ")[0]); // 19, 18, 11, 15 or 1
if (districtCount <= 18) {
mergeDistrictData([votes, districts], ["Sør-Trøndelag", "Nord-Trøndelag"], "Trøndelag");
}
if (districtCount <= 15) {
mergeDistrictData([votes, districts], ["Oppland", "Hedmark"], "Innlandet");
mergeDistrictData([votes, districts], ["Sogn og Fjordane", "Hordaland"], "Vestland");
mergeDistrictData([votes, districts], ["Aust-Agder", "Vest-Agder"], "Agder");
}
if (districtCount <= 11) {
mergeDistrictData([votes, districts], ["Buskerud", "Akershus", "Østfold"], "Viken");
mergeDistrictData([votes, districts], ["Vestfold", "Telemark"], "Vestfold og Telemark");
mergeDistrictData([votes, districts], ["Troms", "Finnmark"], "Troms og Finnmark");
}
if (districtCount <= 1) {
mergeDistrictData([votes, districts], Object.keys(districts), "Norge"); // merge all remaining districts
}
if (!(extraDistrict in Object.keys(districts))) {
extraDistrictInput.value = ""; // de-select invalid extra vote district if not part of new merged districts
}
document.getElementById("minlocalseats").max = Math.floor(totalSeatCount/districtCount);
document.getElementById("globalseatsperdistrict").max = Math.floor(totalSeatCount/districtCount);
var minSeatsPerDistrict = parseInt(document.getElementById("minlocalseats").value);
var globalSeatsPerDistrict = parseInt(document.getElementById("globalseatsperdistrict").value);
if (extraParty && extraDistrict && !isNaN(extraVotes)) {
if (!(extraParty in votes[extraDistrict])) {
votes[extraDistrict][extraParty] = 0; // if party did not run in that district originally, make it run
}
votes[extraDistrict][extraParty] += extraVotes;
}
var [localSeatCounts, globalSeatCount] = calculateAllSeatCounts(districts, totalSeatCount, globalSeatsPerDistrict, areaFactor, minSeatsPerDistrict);
var seats = calculateAllSeats(votes, localSeatCounts, globalSeatCount, localThreshold, globalThreshold, localGlobalThreshold, methodName, negativeGlobalSeats, requireGlobalRepresentation, exemptGlobalThresholdIflocalSeats);
var globalSeats = sumLocal(seats);
var globalVotes = sumLocal(votes);
var totalVotes = sumGlobal(globalVotes);
// Build sorted list of unique parties
var parties = [];
for (var district in votes) {
for (var party in votes[district]) {
if (!parties.includes(party)) {
parties.push(party);
}
}
}
parties.sort();
var fullParties = parties.slice(); // always refers to full party list (copy for safety)
// Compute statistics (before any merging of parties takes place)
var LSq = 0.0;
var LH = 0.0;
for (var party of parties) {
var seatFrac = party in globalSeats ? globalSeats[party] / totalSeatCount : 0;
var voteFrac = globalVotes[party] / totalVotes;
var diff = voteFrac - seatFrac;
LSq += diff**2;
LH += Math.abs(diff);
}
LSq = Math.sqrt(LSq / 2);
LH = LH / 2;
var data = {"LSq": {"Verdi": LSq*100}, "LH": {"Verdi": LH*100}};
printTable(statTable, data, ["LSq", "LH"], ["Verdi"], "Variabel", false, x => truncate(x, 1).toFixed(1).toLocaleString(LANG) + " %");
// Merge parties with no seats as "ANDRE", if requested
var groupOtherParties = document.getElementById("groupotherparties").checked;
var newParties = ["ANDRE"];
if (groupOtherParties) {
globalVotes["ANDRE"] = 0;
globalSeats["ANDRE"] = 0;
parties = parties.filter(function(party) {
if (globalSeats[party] == 0 || !(party in globalSeats)) {
for (data of [votes, seats]) {
for (var district in data) {
if (party in data[district]) {
if (!("ANDRE" in data[district])) {
data[district]["ANDRE"] = 0;
}
data[district]["ANDRE"] += data[district][party];
delete data[district][party];
}
}
}
for (data of [globalSeats, globalVotes]) {
data["ANDRE"] += data[party];
delete data[party];
}
return false;
}
return true;
});
parties.push("ANDRE");
}
var districtList = Object.keys(votes);
var districtListWithGlobal = districtList.slice();
districtListWithGlobal.push("Utjevningsmandater");
// Read graph of friend parties
var friendsInput = document.getElementById("friends");
var friendsText = friendsInput.value.trim();
var friends = {};
for (var party of fullParties) {
friends[party] = [];
}
var valid = true;
if (friendsText.length > 0) {
for (var text of friendsText.split(/\s*,\s*/)) {
var friendList = text.split(/\s*\+\s*/);
for (var party1 of friendList) {
if (!fullParties.includes(party1)) {
valid = false;
break;
}
for (var party2 of friendList) {
if (party1 != party2 && !friends[party1].includes(party2)) { // don't be friends with oneself
friends[party1].push(party2);
}
}
}
}
}
// Do not let unrepresented parties be part of coalitions
for (var party in friends) {
if (globalSeats[party] == 0 || !(party in globalSeats)) {
delete friends[party];
}
}
// Color input field depending on validity of input formatting
friendsInput.setCustomValidity(valid ? "" : "Ugyldig");
if (valid) {
var teamList = calculateTeams(friends);
// add parties with no votes as "empty teams"
for (var party of parties) {
if (globalSeats[party] == 0) {
teamList.push([party]);
}
}
var teams = {};
var totalLocalSeats = sumLocal(localSeatCounts);
for (var team of teamList) {
var name = team.join(" + ");
teams[name] = {"Stemmer": 0, "Posisjon": 0, "Utjevningsmandater": 0};
for (const party of team) {
if (party in seats["Utjevningsmandater"]) {
teams[name]["Utjevningsmandater"] += seats["Utjevningsmandater"][party];
}
if (party in globalSeats) {
teams[name]["Posisjon"] += globalSeats[party];
}
teams[name]["Stemmer"] += globalVotes[party];
}
teams[name]["Distriktsmandater"] = teams[name]["Posisjon"] - teams[name]["Utjevningsmandater"];
teams[name]["Opposisjon"] = totalSeatCount - teams[name]["Posisjon"];
teams[name]["Andel mandater"] = teams[name]["Posisjon"] / totalSeatCount;
teams[name]["Andel stemmer"] = teams[name]["Stemmer"] / totalVotes;
teams[name]["Overrepresentasjon"] = teams[name]["Andel mandater"] - teams[name]["Andel stemmer"];
teams[name]["Stemmer per mandat"] = Math.ceil(teams[name]["Stemmer"] / teams[name]["Posisjon"]);
}
printTable(teamTable, teams, Object.keys(teams), ["Posisjon", "Opposisjon", "Andel mandater", "Andel stemmer", "Overrepresentasjon", "Stemmer per mandat", "Distriktsmandater", "Utjevningsmandater", "Stemmer"], "Partier i posisjon", false, (x, i) => i >= 2 && i <= 4 ? truncate(100*x, 1).toFixed(1).toLocaleString(LANG) + " %" : x.toLocaleString(LANG));
}
printTable(voteTable, votes, districtList, parties, "Valgdistrikt", true, x => x.toLocaleString(LANG), voteTable.showFraction);
printTable(seatTable, seats, districtListWithGlobal, parties, "Valgdistrikt", true, x => x.toLocaleString(LANG), seatTable.showFraction);
var totalPopulation = 0;
for (var district in districts) {
totalPopulation += districts[district]["population"];
}
for (var district in districts) {
districts[district]["Fordelingstall"] = truncate(districts[district]["population"] * areaFactor + districts[district]["area"], 0); // TODO: don't duplicate!
districts[district]["Distriktsmandater"] = localSeatCounts[district];
districts[district]["Utjevningsmandater"] = globalSeatsPerDistrict;
districts[district]["Mandater"] = districts[district]["Distriktsmandater"] + districts[district]["Utjevningsmandater"];
districts[district]["Befolkningsandel"] = districts[district]["population"] / totalPopulation;
districts[district]["Mandatandel"] = districts[district]["Mandater"] / totalSeatCount;
districts[district]["Overrepresentasjon"] = districts[district]["Mandatandel"] - districts[district]["Befolkningsandel"];
districts[district]["Innbyggere per mandat"] = Math.ceil(districts[district]["population"] / districts[district]["Mandater"], 0);
districts[district]["Folketall"] = districts[district]["population"];
districts[district]["Areal / km²"] = districts[district]["area"];
}
printTable(distTable, districts, districtList, ["Folketall", "Areal / km²", "Fordelingstall", "Mandater", "Distriktsmandater", "Utjevningsmandater", "Innbyggere per mandat", "Mandatandel", "Befolkningsandel", "Overrepresentasjon"], "Valgdistrikt", false, (x, i) => i >= 7 && i <= 9 ? truncate(100*x, 1).toFixed(1).toLocaleString(LANG) + " %" : x.toLocaleString(LANG));
extraPartyInput.innerHTML = "";
for (var party of fullParties) {
var el = document.createElement("option");
el.innerHTML = party;
extraPartyInput.appendChild(el);
}
extraPartyInput.value = extraParty; // restore selection
extraDistrictInput.innerHTML = "";
for (var district of districtList) {
var el = document.createElement("option");
el.innerHTML = district;
extraDistrictInput.appendChild(el);
}
extraDistrictInput.value = extraDistrict; // restore selection
// extraVotesInput.step = extraVotes == 0 ? 1 : 10 ** Math.floor(Math.log10(Math.abs(extraVotes)));;
flushLog();
// Update URL parameters, unless requested not to
setURLFromInputs();
};
function showTab(tab) {
for (var i = 0; i < tabs.length; i++) {
if (tab == i) {
tabs[i].style["display"] = "block";
links[i].className = "activetab";
} else {
tabs[i].style["display"] = "none";
links[i].removeAttribute("class");
}
}
};
// Add all input element IDs and their values to the URL query parameters
function setURLFromInputs() {
const url = new URL(window.location.href);
for (const el of document.querySelectorAll("input, select")) {
if (el.id) { // avoid e.g. reset button with no ID
url.searchParams.set(el.id, el.value);
}
}
window.history.pushState({}, "", url.toString());
}
// Read the URL query parameters and set all input element IDs and their values ("reverse" of the above)
function setInputsFromURL(url) {
for (const keyval of url.searchParams) {
const id = keyval[0];
const value = keyval[1];
const el = document.getElementById(id);
if (el) {
el.value = value;
}
}
}
showTab(1); // show vote tab by default
const url = new URL(window.location.href); // save URL before update() in setElection() modifies it
setInputsFromURL(url); // some URL parameters must take effect before setting election (e.g. "election")
setElection(); // run once on page load, but don't set input fields from URL parameters
setInputsFromURL(url); // other URL parameters should override defaults after setting the election
update(false); // now set input fields from any URL parameters