-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui-2024W.js
1169 lines (1123 loc) · 37.9 KB
/
gui-2024W.js
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
/* using:
sql.js
plotly
codemirror
codemirror-theme-vars
fflate
*/
let plotlyUserSettings = {
'yaxis.type': 'linear'
};
let DBConfig;
let inputsElm = document.getElementById('inputs');
let execBtn = document.getElementById("execute");
let loadingElm = document.getElementById('loading');
let SQLLoadingElm = document.getElementById('sql-status');
let outputElm = document.getElementById('output');
let errorElm = document.getElementById('error');
let commandsElm = document.getElementById('commands');
let savedbElm = document.getElementById('savedb');
let tab0Rad = document.getElementById("tab0");
let tab1Rad = document.getElementById("tab1");
let tab2Rad = document.getElementById("tab2");
let tab3Rad = document.getElementById("tab3");
let tab4Rad = document.getElementById("tab4");
let tab5Rad = document.getElementById("tab5");
let tableHallOfFameBtn = document.getElementById('tableHallOfFame');
let tableBeliefAdoptionBtn = document.getElementById('tableBeliefAdoption');
let tablePolicyAdoptionBtn = document.getElementById('tablePolicyAdoption');
let tableTechResearchBtn = document.getElementById('tableTechResearch');
let tableWonderConstructionBtn = document.getElementById('tableWonderConstruction');
let gameSelHead = document.getElementById('gameID-select-head');
let datasetSelHead = document.getElementById('dataset-select-head');
let playerSelHead = document.getElementById('playerID-select-head');
let datasetSelHead2 = document.getElementById('dataset-select-head-2');
let compareSelHead = document.getElementById('compare-group-select-head');
let datasetSelHead3 = document.getElementById('dataset-select-head-3');
let compareGroupArithmeticMeanRad = document.getElementById('compare-group-arithmeticMean');
let compareGroupWinsorizedMeanRad = document.getElementById('compare-group-winsorizedMean');
let compareGroupMedianRad = document.getElementById('compare-group-median');
let sankeyGroups1Rad = document.getElementById('sankey-groups1');
let sankeyGroups2Rad = document.getElementById('sankey-groups2');
let sankeyGroups3Rad = document.getElementById('sankey-groups3');
let dbsizeLbl = document.getElementById('dbsize');
const btn = document.querySelector("#darkThemeToggle");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
const currentTheme = localStorage.getItem("theme");
if (currentTheme === "dark") {
document.body.classList.toggle("dark-theme");
} else if (currentTheme === "light") {
document.body.classList.toggle("light-theme");
}
btn.addEventListener("click", function () {
let theme;
if (prefersDarkScheme.matches) {
document.body.classList.toggle("light-theme");
theme = document.body.classList.contains("light-theme")
? "light"
: "dark";
}
else {
document.body.classList.toggle("dark-theme");
theme = document.body.classList.contains("dark-theme")
? "dark"
: "light";
}
localStorage.setItem("theme", theme);
});
// Start the worker in which sql.js will run
let worker = new Worker("worker.sql-wasm.js");
worker.onerror = error;
worker.onmessage = function (event) {
console.log("e", event);
let results = event.data.results;
let id = event.data.id;
// on db load
if (event.data.ready === true) {
toc("Loading database from file");
loadingElm.innerHTML = '';
fillSelects();
doPlot();
tableHallOfFameBtn.click();
return;
}
// export db
if (event.data?.buffer?.length) {
toc("Exporting the database");
let arraybuff = event.data.buffer;
let blob = new Blob([arraybuff]);
let a = document.createElement("a");
document.body.appendChild(a);
a.href = window.URL.createObjectURL(blob);
a.download = "sql.db";
a.onclick = function () {
setTimeout(function () {
window.URL.revokeObjectURL(a.href);
}, 1500);
};
a.click();
return;
}
if (event?.data?.error?.length)
{
SQLLoadingElm.textContent = `${event.data.error}`;
error({message: `${event.data.error}`});
return;
}
if (!results) {
error({message: event.data.error || 'No data!'});
return;
}
if (results.length === 0) {
SQLLoadingElm.textContent = `No results found!`;
error({message: `No results found!`});
return;
}
toc("Executing SQL");
tic();
// plot data
if (id === 0) {
let conf = Object.assign(...results[0].values.map(([k, v]) => ({ [k]: v })));
let data = [];
// bar plot
if (conf.type === 'bar') {
let tracesData = results[1].values.map(([k, _]) => (k));
console.log('tracesData', tracesData);
let arrX = Object.assign(...Object.values(tracesData).map((v) => ({ [v]: [] }))),
arrY = Object.assign(...Object.values(tracesData).map((v) => ({ [v]: [] })));
for (let i = 0; i < results[2].values.length; i++) {
arrX[results[2].values[i][0]].push(results[2].values[i][1]);
arrY[results[2].values[i][0]].push(results[2].values[i][2]);
}
tracesData.forEach((i, n) => {
data.push({
x: arrX[i],
y: arrY[i],
type: 'bar',
showlegend: true,
name: i,
color: colors[n % colors.length]
});
});
}
// sankey plot
else if (conf.type === 'sankey') {
let keysData = Object.assign(...results[1].values.map((k) => ({ [k[0]]: k[1] }))),
blob = { s: {}, t: {}, v: {} },
arrL = [], arrLL = [], mask = new Array(conf.numEntries - 1),
nextId = 0, groupLabels = (conf.groups > 1) ? JSON.parse(conf.labels) : [' '];
results[2].values.forEach((el) => {
let arr = JSON.parse(el[0]);
let winID = (conf.groups > 1) ? el[1] : 0;
for (let i = 0; i < arr.length; i++) {
if (mask[i] === undefined) mask[i] = {};
if (i === arr.length - 1) {
if (!mask[i][arr[i]]) {
mask[i][arr[i]] = nextId++;
arrL.push(keysData[arr[i]]);
}
continue;
}
if (blob.s[i] === undefined) {
blob.s[i] = Array.from({length: conf.groups}, _=>[]);
blob.t[i] = Array.from({length: conf.groups}, _=>[]);
blob.v[i] = Array.from({length: conf.groups}, _=>[]);
}
let fg = false;
for (let j = 0; j < blob.s[i][winID].length; j++) {
if (blob.s[i][winID][j] === arr[i] && blob.t[i][winID][j] === arr[i + 1]) {
fg = true;
blob.v[i][winID][j]++;
break;
}
}
if (!fg) {
if (mask[i][arr[i]] === undefined) {
mask[i][arr[i]] = nextId++;
arrL.push(keysData[arr[i]]);
}
blob.s[i][winID].push(arr[i]);
blob.t[i][winID].push(arr[i + 1]);
blob.v[i][winID].push(1);
}
}
});
let arrS = [], arrT = [], arrV = [], arrCl = [];
for (let k in blob.s) {
Object.keys(blob.v[k]).forEach((el) => {
blob.s[k][el].forEach((el2, i2) => {blob.s[k][el][i2] = mask[k][el2]});
blob.t[k][el].forEach((el2, i2) => {blob.t[k][el][i2] = mask[(parseInt(k) + 1).toString()][el2]});
arrS.push(...blob.s[k][el]);
arrT.push(...blob.t[k][el]);
arrV.push(...blob.v[k][el]);
blob.v[k][el].forEach((_) => {
arrCl.push(conf.groups === 2 ? (el > 0 ? winColors.anyWin : winColors[el]) : winColors[el]);
arrLL.push(groupLabels[el]);
});
});
}
// fix wrong x node coords for incomplete branches
// ref. https://community.plotly.com/t/sankey-avoid-placing-incomplete-branches-to-the-right/44873
let dummyId = nextId++;
for (let k in blob.t) {
if (!blob.s[(parseInt(k) + 1).toString()]) continue;
let a = new Set(Object.values(blob.s[(parseInt(k) + 1).toString()]).flat());
let b = new Set(Object.values(blob.t[k]).flat());
// select nodes with no outgoing links
let res = [...new Set([...b].filter(x => !a.has(x)))];
// create a dummy node that continues all incomplete branches and make it invisible
arrS.push(...res);
arrT.push(...res.map(_ => dummyId));
arrV.push(...res.map(_ => 0.001));
arrCl.push(...res.map(_ => 'rgba(0,0,0,0)'));
arrLL.push(...res.map(_ => ''));
}
data = [{
type: "sankey",
arrangement: "freeform",
node: {
pad: 35,
thickness: 30,
line: { width: 0 },
label: arrL,
color: arrL.map((el) => colors[[...new Set(arrL)].indexOf(el) % colors.length]).concat('rgba(0,0,0,0)')
},
link: {
source: arrS,
target: arrT,
value: arrV,
color: arrCl,
customdata: Array.from({length: arrLL.length}, (el,i)=>{return {extra:(arrV[i] / results[2].values.length * 100).toFixed(1) + '%', value: arrV[i], label: arrLL[i]}}),
hovertemplate: `<b>%{customdata.label}</b><br><br>source: %{source.label}<br>target: %{target.label}<extra>%{customdata.value}<br>%{customdata.extra}</extra>`
},
textfont: { size: 12 }
}];
Plotly.newPlot('plotOut', data, { title: conf.title, font: { size: 25 } });
toc("Displaying results");
return;
}
// scatter plot
else if (conf.type === 'scatter') {
let gamesData = Object.assign(...results[1].values.map(([k, v]) => ({ [k]: v })));
Object.entries(gamesData).forEach(([k, v]) => {
if (!v) gamesData[k] = 330;
});
let tracesData = Object.assign(...results[2].values.map((k) => {
return { [k[1]]: Object.assign(...k.map((d,i) => {
return { [results[2].columns[i]]: d }
})) }
}
));
Object.values(tracesData).forEach((v) => {
if (!v.QuitTurn) {
v.QuitTurn = gamesData[v.GameID];
}
});
let arrX = Object.assign(...Object.values(tracesData).map((v) => ({ [v.rowid]: [] }))),
arrY = Object.assign(...Object.values(tracesData).map((v) => ({ [v.rowid]: [] })));
let curX = Object.assign(...Object.values(tracesData).map((v) => ({ [v.rowid]: 0 }))),
curY = Object.assign(...Object.values(tracesData).map((v) => ({ [v.rowid]: 0 })));
for (let i = 0; i < results[3].values.length; i++) {
let lastTurn = tracesData[results[3].values[i][0]].QuitTurn ?? gamesData[tracesData[results[3].values[i][0]].GameID];
if (results[3].values[i][1] < lastTurn) {
// fill gaps
while (results[3].values[i][1] > (curX[results[3].values[i][0]] + 1)) {
// increment turn while value stays the same
curX[results[3].values[i][0]]++;
arrX[results[3].values[i][0]].push(curX[results[3].values[i][0]]);
arrY[results[3].values[i][0]].push(curY[results[3].values[i][0]]);
}
curX[results[3].values[i][0]] = results[3].values[i][1];
curY[results[3].values[i][0]] = results[3].values[i][2];
arrX[results[3].values[i][0]].push(results[3].values[i][1]);
arrY[results[3].values[i][0]].push(results[3].values[i][2]);
}
}
let blob = Array.from({length: 3}, _=>[]);
if (conf.aggregate) {
conf.aggregate = JSON.parse(conf.aggregate);
}
Object.keys(tracesData).forEach((i, n) => {
// fill data for yet alive players
let curX = arrX[i].at(-1), curY = arrY[i].at(-1);
let lastTurn = tracesData[i].QuitTurn ?? gamesData[tracesData[i].GameID];
while (curX < lastTurn) {
// increment turn while value stays the same
curX++;
arrX[i].push(curX);
arrY[i].push(curY);
}
if (conf.aggregate) {
let groupId;
if (conf.aggregate.group === 'generic') {
if (conf.aggregate.id === 0) {
conf.aggregate.name = 'Winners';
groupId = tracesData[i].Standing === 1 ? 0 : 1;
}
else if (conf.aggregate.id === 1) {
conf.aggregate.name = 'Playoff Players';
groupId = [101, 102, 103, 201, 202, 203].includes(tracesData[i].GameID) ? 0 : 1;
}
else if (conf.aggregate.id === 2) {
conf.aggregate.name = 'Final Game Players';
groupId = (tracesData[i].GameID === 301) ? 0 : 1;
}
}
else if (conf.aggregate.group === 'civs') {
conf.aggregate.name = conf.aggregate.id;
groupId = tracesData[i].TraceName === conf.aggregate.id ? 0 : 1;
}
else if (conf.aggregate.group === 'players') {
conf.aggregate.name = conf.aggregate.id;
groupId = tracesData[i].TraceName === conf.aggregate.id ? 0 : 1;
}
else if (conf.aggregate.group === 'wonders') {
conf.aggregate.name = conf.aggregate.id + ' builders';
groupId = tracesData[i].GroupID;
}
arrY[i].forEach((j,k)=>{
if (blob[groupId][k] === undefined)
blob[groupId][k] = [k, []];
blob[groupId][k][1].push(j);
if (blob[2][k] === undefined)
blob[2][k] = [k, []];
blob[2][k][1].push(j);
})
}
else {
data.push({
x: arrX[i],
y: arrY[i],
mode: conf.mode,
type: conf.type,
line: {
shape: 'spline',
color: colors[n % colors.length]
},
legendgroup: `group${i}`,
showlegend: true,
name: tracesData[i].TraceName
});
if (tracesData[i].Standing) {
// mark winner
if (tracesData[i].Standing === 1) {
data.push({
x: [arrX[i].at(-1)],
y: [arrY[i].at(-1)],
mode: 'markers',
type: conf.type,
marker: {
size: 12,
color: colors[n % colors.length],
symbol: 'star'
},
legendgroup: `group${i}`,
showlegend: false,
hoverinfo: 'skip'
})
}
// add X marker when player "dies"
else {
data.push({
x: [arrX[i].at(-1)],
y: [arrY[i].at(-1)],
mode: 'markers',
type: conf.type,
marker: {
size: 12,
color: colors[n % colors.length],
symbol: 'x-dot'
},
legendgroup: `group${i}`,
showlegend: false,
hoverinfo: 'skip'
})
}
}
}
});
if (conf.aggregate) {
//console.log('blob', blob);
blob.forEach((group, n)=>{
if (conf.aggregate.method === 0) { // Arithmetic mean
arrY = Array.from({length: group.length}, (el, i)=>blob[n][i][1].reduce((acc,it)=>acc+it,0)/blob[n][i][1].length);
}
else if (conf.aggregate.method === 1) { // 20% winsorized mean
arrY = Array.from({length: group.length}, (el, i)=> {
let s = [...blob[n][i][1]].sort((a,b)=>a-b);
let LBound = Math.trunc(s.length * 0.2);
let UBound = s.length - LBound - 1;
return s.reduce((acc,it,wi,arr)=>{
let r = (wi < LBound) ? arr[LBound] : ((wi > UBound) ? arr[UBound] : it);
return acc + r;
})/s.length;
});
}
else if (conf.aggregate.method === 2) { // Median
arrY = Array.from({length: group.length}, (el, i)=>{
let s = [...blob[n][i][1]].sort((a,b)=>a-b);
return (s[Math.floor(s.length / 2) - 1] + s[Math.ceil(s.length / 2) - 1]) / 2;
});
}
data.push({
x: Array.from({length: group.length}, (el, i)=>blob[n][i][0]),
y: arrY,
mode: conf.mode,
type: conf.type,
line: {
shape: 'spline',
color: colors[n % colors.length]
},
showlegend: true,
name: Array(`${conf.aggregate.name} average`, `All except ${conf.aggregate.name}`, 'All average')[n]
});
});
}
}
let layout = {
hovermode: "x unified",
barmode: 'relative',
xaxis: {
title: conf.xaxis
},
yaxis: {
title: conf.yaxis ?? 'TODO',
type: plotlyUserSettings['yaxis.type']
},
legend: {
orientation: "v",
bgcolor: '#E2E2E2',
bordercolor: '#FFFFFF',
borderwidth: 2
},
updatemenus: [{
y: 1.1,
xanchor: 'auto',
active: plotlyUserSettings['yaxis.type'] === 'linear' ? 0 : 1,
buttons: [
{
label: 'Linear Scale',
method: 'relayout',
args: [{'yaxis.type': 'linear'}]
},
{
label: 'Log Scale',
method: 'relayout',
args: [{'yaxis.type': 'log'}]
}
]
}]
};
let config = {
responsive: true,
toImageButtonOptions: {
format: 'png', // one of png, svg, jpeg, webp
filename: `TODO`,
height: 2160,
width: 3840,
scale: 1 // Multiply title/legend/axis/canvas sizes by this factor
},
};
Plotly.newPlot('plotOut', data, layout, config).then(
document.querySelector("#plotOut").on('plotly_relayout', (e)=>{
if (e['yaxis.type']) { // save user preference on linear/log scale change
plotlyUserSettings['yaxis.type'] = e['yaxis.type'];
}
})
);
}
// fill games select
else if (id === 1) {
[gameSelHead, playerSelHead, compareSelHead, datasetSelHead, datasetSelHead2, datasetSelHead3].forEach((el, n)=>{
n = (n > 2) ? 3 : n; // all dataset dropdowns utilize the same data
for (let i = 0; i < results[n].values.length; i++) {
if (results[n].values[i][1] === 'groupSeparator') {
const b = document.createElement("b");
b.innerHTML = results[n].values[i][0];
b.classList.add('sp');
b.tabIndex = -1;
el.nextElementSibling.appendChild(b);
}
else {
const sp = document.createElement("span");
sp.value = results[n].values[i][1];
sp.innerHTML = `${results[n].values[i][0].replace(/\[([^\]]+)\]/g, (_, a) => IconMarkups[a] ? `<img class="ico" src="images/${IconMarkups[a]}"/>` : `[${a}]`)}`;
sp.classList.add('sp', 'dropdownItem');
sp.addEventListener('mousedown', (e) => {
el.innerHTML = sp.innerHTML;
el.value = sp.value;
sp.parentElement.style.visibility = 'hidden';
doPlot(e);
});
el.nextElementSibling.appendChild(sp);
}
}
el.innerHTML = el.nextElementSibling.querySelector('span').innerHTML;
el.value = el.nextElementSibling.querySelector('span').value;
el.addEventListener('click', (_)=>{
el.nextElementSibling.style.visibility = (el.nextElementSibling.style.visibility === 'visible') ? 'hidden' : 'visible';
});
el.parentElement.addEventListener('focusout', (e)=>{
if (!el.nextElementSibling.contains(e.explicitOriginalTarget))
el.nextElementSibling.style.visibility = 'hidden';
});
let temp = el.parentElement.parentElement.style.display;
el.parentElement.parentElement.style.display = 'block';
el.style.minWidth = el.nextElementSibling.getBoundingClientRect().width + 'px';
el.parentElement.parentElement.style.display = temp;
});
}
// fill Games front tab
else if (id === "plot-games-victories") {
console.log('results:', results);
let annotations = [
{
text: '<span style=\'font-size:1.7vw;\'>Civilization Standings</span>',
showarrow: false,
x: 0.33, //position in x domain
y: 1.01, // position in y domain
xref: 'paper',
yref: 'paper',
xanchor: 'center',
yanchor: 'bottom',
},
{
text: '<span style=\'font-size:1.7vw;\'>Victory Types and Ideologies</span>',
showarrow: false,
x: 0.80, //position in x domain
y: 1.01, // position in y domain
xref: 'paper',
yref: 'paper',
xanchor: 'center',
yanchor: 'bottom',
},
{
text: '<span style=\'font-size:1.7vw;\'>% of Qualification Games Played</span>',
showarrow: false,
x: 0.80, //position in x domain
y: 0.41, //position in y domain
xref: 'paper',
yref: 'paper',
xanchor: 'center',
yanchor: 'bottom',
},
];
let data = [
Object.assign({}, ...results[0].columns.map((n, index) => ({[n]: JSON.parse(results[0].values[0][index])}))),
{
x: results[2].values.map(a => a[0]),
y: results[2].values.map(a => a[1]),
type: 'bar',
showlegend: false,
offsetgroup: '1',
legendgroup: '1',
},
];
Object.assign(data[0], {
branchvalues: "total",
texttemplate: `%{label}<br>%{value} (%{percentEntry})`,
hovertemplate: '%{label}<br>%{value} (%{percentRoot:%})<extra></extra>',
hoverlabel: { align: 'left' },
type: 'sunburst',
domain: { x: [0.6, 1], y: [0.5, 1] },
marker: {colors: data[0].labels.map(l => civColorsDict[l] ?? null)}
});
results[1].columns.slice(3).forEach((name, i) => {
data.push({
x: results[1].values.map(a => a[i + 3] / a[1]),
y: results[1].values.map(a => a[0]),
type: 'bar',
name: name,
hovertext: results[1].values.map(a => `${a[i + 3]} games`),
showlegend: false,
orientation: 'h',
offsetgroup: '0',
xaxis: 'x2',
yaxis: 'y2',
marker: { color: colorscaleViridis[i] },
});
});
results[1].values.forEach((a, i) => {
annotations.push({
x: -0.01,
y: i,
text: a[0],
xref: 'x2',
yref: 'y2',
xanchor: 'right',
showarrow: false,
yshift: 0
},
{
x: 1.01,
y: i,
text: a[2],
xref: 'x2',
yref: 'y2',
xanchor: 'left',
showarrow: false,
yshift: 0
})
});
console.log('data:', data);
let layout = {
barmode: 'stack',
yaxis: {
domain: [0.1, 0.4],
anchor: 'x'
},
xaxis: {
domain: [0.7, 0.9],
anchor: 'y'
},
yaxis2: {
domain: [0, 1],
showticklabels: false,
showgrid: false
},
xaxis2: {
domain: [0, 0.6],
anchor: 'y',
showticklabels: false,
showgrid: false
},
annotations: annotations,
};
Plotly.newPlot('plotOut', data, layout);
}
// fill table
else {
outputElm.innerHTML = "";
SQLLoadingElm.innerHTML = "";
console.log('results:', results);
let blob = {};
// check if first table contains names of other tables
if (results[0].columns[0] === 'tableName') {
blob = Object.assign(...results.map((t, i) => ({ [results[0].values[i]]: t })));
delete blob.config;
}
else {
blob = Object.assign(...results.map((t, i) => ({ [`Table ${i}`]: t })));
}
console.log('table blob', blob);
Object.entries(blob).forEach((t, _)=>{
outputElm.appendChild(tableCreate(t[0], t[1].columns, t[1].values));
});
const allTables = document.querySelectorAll("table");
for (const table of allTables) {
const tBody = table.tBodies[0];
const rows = Array.from(tBody.rows);
const headerCells = table.tHead.rows[0].cells;
for (const th of headerCells) {
const cellIndex = th.cellIndex;
th.addEventListener("click", () => {
let dir = th.classList.contains("sort-desc");
th.parentElement.childNodes.forEach(el=>el.classList.remove("sort-asc", "sort-desc"));
th.classList.add(dir === true ? "sort-asc" : "sort-desc");
rows.sort((tr1, tr2) => {
const tr1Text = tr1.cells[cellIndex].textContent;
const tr2Text = tr2.cells[cellIndex].textContent;
return dir ? 1 : -1 * tr2Text.localeCompare(tr1Text, undefined, { numeric: true });
});
tBody.append(...rows);
});
}
}
}
toc("Displaying results");
};
function error(e) {
console.log(e);
errorElm.style.height = '2em';
errorElm.textContent = e.message;
}
function noerror() {
errorElm.style.height = '0';
}
// Run a command in the database
function execute(commands) {
tic();
SQLLoadingElm.textContent = "Fetching results...";
worker.postMessage({ action: 'exec', sql: commands });
}
function fillSelects() {
worker.postMessage({ action: 'exec', id: 1, sql: sqlQueries.fillSelects });
}
// Create an HTML table
let tableCreate = function () {
function valconcat(vals, tagName) {
if (vals.length === 0) return '';
let open = '<' + tagName + '>', close = '</' + tagName + '>';
return open + vals.join(close + open).replace(/\[([^\]]+)\]/g, (_, a) => IconMarkups[a] ? `<img class="ico" src="images/${IconMarkups[a]}"/>` : `[${a}]`) + close;
}
return function (name, columns, values) {
let div = document.createElement('div');
div.classList.add('table-cont');
let ttl = document.createElement('span');
ttl.textContent = name;
ttl.classList.add('sp');
ttl.style.fontSize = '22px';
div.appendChild(ttl);
let tbl = document.createElement('table');
let html = '<thead>' + valconcat(columns, 'th') + '</thead>';
let rows = values.map(function (v) { return valconcat(v, 'td'); });
html += '<tbody>' + valconcat(rows, 'tr') + '</tbody>';
tbl.innerHTML = html;
div.appendChild(tbl);
return div;
}
}();
// Execute the commands when the button is clicked
function execEditorContents() {
noerror();
execute(editor.getValue() + ';');
}
execBtn.addEventListener("click", execEditorContents, true);
// Performance measurement functions
let tictime;
if (!window.performance || !performance.now) { window.performance = { now: Date.now } }
function tic() { tictime = performance.now() }
function toc(msg) {
let dt = performance.now() - tictime;
console.log((msg || 'toc') + ": " + dt + "ms");
}
// Add syntax highlighting to the textarea
let editor = CodeMirror.fromTextArea(commandsElm, {
mode: 'text/x-mysql',
viewportMargin: Infinity,
indentWithTabs: true,
smartIndent: true,
lineNumbers: true,
matchBrackets: true,
autofocus: true,
extraKeys: {
"Ctrl-Enter": execEditorContents,
"Ctrl-S": savedb,
},
theme: 'vars'
});
const resizeWatcher = new ResizeObserver(entries => {
for (const entry of entries){
if (entry.contentRect.width !== 0) {
editor.refresh();
}
}
});
resizeWatcher.observe(document.getElementById("sqlBox"));
// Load a db from URL
function fetchdb() {
let r = new XMLHttpRequest();
r.open('GET', 'sample2.zip', true);
r.responseType = 'arraybuffer';
r.onload = function () {
toc('loading DB');
inputsElm.style.display = 'block';
const uInt8Array = new Uint8Array(r.response);
tic();
const unzipped = fflate.unzipSync(uInt8Array)['sample2.db'];
DBConfig = JSON.parse(String.fromCharCode.apply(null, fflate.unzipSync(uInt8Array)['config.json']));
toc('decompression finished');
let b = uInt8Array.length;
let b2 = unzipped.length;
dbsizeLbl.textContent = `DB size is ${(b2/Math.pow(1024,~~(Math.log2(b2)/10))).toFixed(2)} \
${("KMGTPEZY"[~~(Math.log2(b2)/10)-1]||"") + "B"} \
(${(b / Math.pow(1024, ~~(Math.log2(b) / 10))).toFixed(2)} \
${("KMGTPEZY"[~~(Math.log2(b) / 10) - 1] || "") + "B"} compressed)`;
tic();
try {
worker.postMessage({ action: 'open', buffer: unzipped }, [unzipped]);
}
catch (exception) {
worker.postMessage({ action: 'open', buffer: unzipped });
}
};
tic();
r.send();
}
fetchdb();
// Save the db to a file
function savedb() {
tic();
worker.postMessage({ action: 'export' });
}
savedbElm.addEventListener("click", savedb, true);
function doPlot(e) {
Plotly.purge('plotOut');
if (tab0Rad.checked) {
worker.postMessage({ action: 'exec', sql: sqlQueries["plot-games-victories"], id: "plot-games-victories" });
return;
}
if (tab5Rad.checked)
return;
tic();
noerror();
let target = e?.target.id;
let gameID = gameSelHead.value ? gameSelHead.value : 1;
let dataset = datasetSelHead.value ? datasetSelHead : {value: DBConfig.DefaultDatasetID, textContent: DBConfig.DefaultDatasetKey};
let playerName = playerSelHead.value ? playerSelHead.textContent : DBConfig.DefaultPlayer;
let dataset2 = datasetSelHead2.value ? datasetSelHead2 : {value: DBConfig.DefaultDatasetID, textContent: DBConfig.DefaultDatasetKey};
let compareGroup = compareSelHead.value ? compareSelHead : {value: JSON.stringify(DBConfig.DefaultCompareGroup), textContent: DBConfig.DefaultCompareGroupKey};
let dataset3 = datasetSelHead3.value ? datasetSelHead3 : {value: DBConfig.DefaultDatasetID, textContent: DBConfig.DefaultDatasetKey};
let condition1 = `Games.GameID = 1`;
let condition2 = `ReplayDataSetKeys.ReplayDataSetID = ${DBConfig.DefaultDatasetID}`;
let traceName = `Games.Player`;
let yaxisName = ``;
let aggregate, aggregateMethod, supplement, groupID;
if (compareGroupArithmeticMeanRad.checked) {
aggregateMethod = 0;
}
else if (compareGroupWinsorizedMeanRad.checked) {
aggregateMethod = 1;
}
else if (compareGroupMedianRad.checked) {
aggregateMethod = 2;
}
if (target === 'plotAllGames') {
condition1 = '';
condition2 = `ReplayDataSetsChanges.ReplayDataSetID = ${dataset.value}`;
traceName = `Games.Player || ' (' || Games.PlayerGameNumber || ')'`;
yaxisName = dataset.textContent;
}
else if (target === 'plotAllPlayers') {
condition1 = '';
condition2 = `ReplayDataSetsChanges.ReplayDataSetID = ${dataset2.value}`;
traceName = `Games.Player || ' ' || Games.PlayerGameNumber || ': ' || CivKeys.CivKey`;
yaxisName = dataset2.textContent;
}
// Plot by Game
else if (tab1Rad.checked) {
condition1 = `Games.GameID = ${gameID}`;
condition2 = `ReplayDataSetsChanges.ReplayDataSetID = ${dataset.value}`;
traceName = `Games.Player||' ('||CivKeys.CivKey||')'`;
yaxisName = dataset.textContent;
}
// Plot by Player
else if (tab2Rad.checked) {
condition1 = `Games.Player = '${playerName.replace(/'/g, "''")}'`;
condition2 = `ReplayDataSetsChanges.ReplayDataSetID = ${dataset2.value}`;
traceName = `Games.PlayerGameNumber || ': ' || CivKeys.CivKey`;
yaxisName = dataset2.textContent;
}
// Compare Average
else if (tab3Rad.checked) {
let val = JSON.parse(compareGroup.value);
if (val.group === 'generic') {
traceName = `Games.Player`;
aggregate = `{"group":"generic","method":${aggregateMethod},"id":${val.id}}`;
}
else if (val.group === 'civs') {
traceName = `CivKeys.CivKey`;
aggregate = `{"group":"civs","method":${aggregateMethod},"id":"${compareGroup.textContent}"}`;
}
else if (val.group === 'players') {
traceName = `Games.Player`;
aggregate = `{"group":"players","method":${aggregateMethod},"id":"${val.id}"}`;
}
else if (val.group === 'wonders') {
traceName = `Games.Player`;
aggregate = `{"group":"wonders","method":${aggregateMethod},"id":"${val.id}"}`;
supplement = `
LEFT JOIN (
SELECT GameID, PlayerID, 0 AS GroupID FROM ReplayEvents
JOIN BuildingKeys ON BuildingKeys.BuildingID = Num2
JOIN BuildingClassKeys ON BuildingClassKeys.BuildingClassID = BuildingKeys.BuildingClassID
JOIN GameSeeds ON GameSeeds.GameSeed = ReplayEvents.GameSeed
WHERE ReplayEventType = 78 AND BuildingClassKeys.TypeID = 2 AND BuildingClassKeys.BuildingClassKey = "${val.id}"
) T1 ON T1.GameID = Games.GameID AND T1.PlayerID = Games.PlayerID
`;
groupID = 'IFNULL(GroupID, 1)';
}
condition1 = '';
condition2 = `ReplayDataSetsChanges.ReplayDataSetID = ${dataset3.value}`;
yaxisName = dataset3.textContent;
}
// Plot Distribution
else if (tab4Rad.checked) {
doBarPlot(e);
return;
}
let msg = `
WITH
config(Key,Value) AS (
VALUES('type','scatter'),
('mode', 'lines'),
('xaxis','Turn'),
('yaxis',"${yaxisName}")
${aggregate ? `,('aggregate', '${aggregate}')` : ''}
)
SELECT * FROM config
;
WITH
gamesData AS (
SELECT GameSeeds.GameID, GameSeeds.EndTurn FROM GameSeeds
JOIN Games ON Games.GameID = GameSeeds.GameID
${condition1 ? `WHERE ${condition1}` : ''}
GROUP BY Games.GameID
)
SELECT * FROM gamesData
;
WITH
tracesData AS (
SELECT Games.GameID, Games.rowid, ${traceName} AS TraceName, Standing, PlayerQuitTurn AS QuitTurn ${groupID ? `, ${groupID} AS GroupID` : ''}
FROM Games
JOIN GameSeeds ON GameSeeds.GameID = Games.GameID
JOIN Players ON Players.GameSeed = GameSeeds.GameSeed AND Players.PlayerID = Games.PlayerID
JOIN CivKeys ON CivKeys.CivID = Players.CivID
${supplement || ''}
${condition1 ? `WHERE ${condition1}` : ''}
)
SELECT * FROM tracesData
;
SELECT Games.rowid, Turn AS x,
SUM(ReplayDataSetsChanges.Value) OVER (PARTITION by Games.GameID, Games.Player ORDER BY Turn) y
FROM ReplayDataSetsChanges
JOIN GameSeeds ON GameSeeds.GameSeed = ReplayDataSetsChanges.GameSeed
JOIN Games ON Games.GameID = GameSeeds.GameID AND Games.PlayerID = ReplayDataSetsChanges.PlayerID
WHERE ${condition1 ? condition1 : ''} ${condition2 ? (condition1 ? `AND ${condition2}` : condition2) : ''}
;
`;
console.log(msg);
worker.postMessage({ action: 'exec', id: 0, sql: msg });
}
function doBarPlot(e) {
noerror();
let target = e?.target.id;
let msg;
if (target === 'policies-time') {
msg = sqlQueries["plot-bar-policies-time"];
}
else if (target === 'techs-time') {
msg = sqlQueries["plot-bar-techs-time"];
}
else if (tab4Rad.checked || target === 'beliefs-time') {
msg = sqlQueries["plot-bar-beliefs-time"];
}
console.log('msg', msg);
worker.postMessage({ action: 'exec', id: 0, sql: msg });
}
let lastSankeyId, lastSankeyTitle;
function doSankeyPlot(e) {
let target = e?.target.id;
let msg = '';
let pols, numEntries = 7,
numGroups, groupLabels, groupSelector;
if (e?.target.classList.contains('sankey-clk') && e?.target?.type !== 'radio') {
lastSankeyId = target;
lastSankeyTitle = e.target.textContent;
}
if (['sankey-groups1', 'sankey-groups2', 'sankey-groups3'].includes(target)) {
if (lastSankeyId === undefined) return;
target = lastSankeyId;
}
if (sankeyGroups1Rad.checked) {
numGroups = 1;
groupSelector = '0';
groupLabels = '[]';
}
else if (sankeyGroups2Rad.checked) {
numGroups = 2;
groupSelector = 'WinID > 0';
groupLabels = '["Losers","Winners"]';
}
else if (sankeyGroups3Rad.checked) {