Repository navigation
Expand file tree
/
Copy pathbuild_site_ipw3.py
More file actions
2447 lines (2122 loc) · 107 KB
/
Copy pathbuild_site_ipw3.py
File metadata and controls
2447 lines (2122 loc) · 107 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
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
"""
Build the IPW3 post-processing comparison website.
This file is the main site builder. Plot-specific logic is split into:
- cutdata_builder.py
- iceshape_builder.py
- convergence_data_builder.py
The data reader/scanner remains gatherParticipantData.py.
"""
from __future__ import annotations
import argparse
import math
from pathlib import Path
from html import escape
import html
import re
import shutil
from tools.gatherParticipantData import CASE_SLICES, VALID_CASES, VALID_GRID_LEVELS, HighlightPointsByCase, cleanup_generated_sidecars, collect_case_ids, scan_all_participants
from tools.cutdata_builder import build_combined_levels_cutdata_section, build_grid_level_cutdata_plots
from tools.iceshape_builder import build_combined_levels_ice_shape_section, build_ice_shape_section
from tools.convergence_data_builder import build_ae3933_ice_mass_comparison_section, build_beta_max_analysis_section, build_grid_convergence_section, build_water_mass_analysis_section
from tools import convergence_data_builder, cutdata_builder, iceshape_builder
from tools.participant_style import PARTICIPANTS, PREVIEW_PARTICIPANT_NAME, normalize_participant_id, participant_color, participant_info, preview_participant_name
ROOT_DIR = Path(".")
OUTPUT_DIR = ROOT_DIR / "PREVIEW"
OUTPUT_HTML = OUTPUT_DIR / "index.html"
PAGES_DIR = OUTPUT_DIR / "PAGES"
VARIABLE_FILTER_SCRIPT = """
<script>
document.addEventListener("DOMContentLoaded", () => {
const checkedValues = (root, selector) => new Set(
Array.from(root.querySelectorAll(selector)).filter((input) => input.checked).map((input) => input.value)
);
document.querySelectorAll(".plot-filter-scope").forEach((scope, scopeIndex) => {
const controls = scope.querySelector(":scope > .variable-filter-controls");
const sections = Array.from(scope.querySelectorAll(":scope > .plot-subsection[data-variable-key]"));
if (!controls || sections.length === 0) {
if (controls) {
controls.hidden = true;
}
} else {
const title = controls.dataset.filterTitle || "Variables";
const seen = new Map();
sections.forEach((section) => {
const key = section.dataset.variableKey || "";
const label = section.dataset.variableLabel || key;
if (key && !seen.has(key)) {
seen.set(key, label);
}
});
const checkboxHtml = Array.from(seen.entries()).map(([key, label], index) => {
const id = `variable-filter-${scopeIndex}-${index}`;
return `
<label class="variable-filter-option" for="${id}">
<input id="${id}" type="checkbox" value="${key}" checked />
<span>${label}</span>
</label>
`;
}).join("");
controls.innerHTML = `
<div class="variable-filter-header">
<span>${title}</span>
<button type="button" data-filter-action="all">All</button>
<button type="button" data-filter-action="none">None</button>
</div>
<div class="variable-filter-options">${checkboxHtml}</div>
`;
const update = () => {
const activeKeys = checkedValues(controls, "input[type='checkbox']");
sections.forEach((section) => {
section.hidden = !activeKeys.has(section.dataset.variableKey || "");
});
scope.dispatchEvent(new CustomEvent("plot-filter:update"));
};
controls.addEventListener("change", update);
controls.addEventListener("click", (event) => {
const button = event.target.closest("button[data-filter-action]");
if (!button) {
return;
}
const checked = button.dataset.filterAction === "all";
controls.querySelectorAll("input[type='checkbox']").forEach((input) => {
input.checked = checked;
});
update();
});
update();
}
const iceControls = scope.querySelector(":scope > .ice-shape-filter-controls");
if (!iceControls) {
return;
}
const groups = Array.from(scope.querySelectorAll(".ice-shape-subsection .slice-plot-group[data-slice-key][data-roughness-key]"));
if (groups.length === 0) {
iceControls.hidden = true;
return;
}
const slices = new Map();
const roughnessBySlice = new Map();
groups.forEach((group) => {
const sliceKey = group.dataset.sliceKey || "";
const sliceLabel = group.dataset.sliceLabel || sliceKey;
const roughnessKey = group.dataset.roughnessKey || "";
const roughnessLabel = group.dataset.roughnessLabel || roughnessKey;
if (!slices.has(sliceKey)) {
slices.set(sliceKey, sliceLabel);
}
if (!roughnessBySlice.has(sliceKey)) {
roughnessBySlice.set(sliceKey, new Map());
}
roughnessBySlice.get(sliceKey).set(roughnessKey, roughnessLabel);
});
const sliceCheckboxHtml = Array.from(slices.entries()).map(([key, label], index) => {
const id = `ice-slice-filter-${scopeIndex}-${index}`;
return `
<label class="variable-filter-option" for="${id}">
<input id="${id}" type="checkbox" value="${key}" data-ice-slice-toggle checked />
<span>${label}</span>
</label>
`;
}).join("");
const onlyCombinedRoughness = Array.from(roughnessBySlice.values()).every((options) =>
options.size === 1 && options.has("all_roughness")
);
const roughnessHtml = Array.from(slices.entries()).map(([sliceKey, sliceLabel], sliceIndex) => {
const options = Array.from(roughnessBySlice.get(sliceKey).entries()).map(([roughnessKey, roughnessLabel], roughnessIndex) => {
const id = `ice-roughness-filter-${scopeIndex}-${sliceIndex}-${roughnessIndex}`;
return `
<label class="variable-filter-option" for="${id}">
<input id="${id}" type="checkbox" value="${roughnessKey}" data-ice-roughness-toggle data-slice-key="${sliceKey}" checked />
<span>${roughnessLabel}</span>
</label>
`;
}).join("");
return `
<div class="ice-roughness-filter-group" data-slice-key="${sliceKey}">
<div class="variable-filter-header">
<span>${sliceLabel}</span>
<button type="button" data-slice-key="${sliceKey}" data-roughness-action="all">All</button>
<button type="button" data-slice-key="${sliceKey}" data-roughness-action="none">None</button>
</div>
<div class="variable-filter-options">${options}</div>
</div>
`;
}).join("");
iceControls.innerHTML = `
<div class="variable-filter-header">
<span>Ice-shape slices</span>
<button type="button" data-slice-action="all">All</button>
<button type="button" data-slice-action="none">None</button>
</div>
<div class="variable-filter-options">${sliceCheckboxHtml}</div>
<div class="ice-roughness-filter-list" ${onlyCombinedRoughness ? "hidden" : ""}>${roughnessHtml}</div>
`;
const updateIceFilters = () => {
const activeSlices = checkedValues(iceControls, "input[data-ice-slice-toggle]");
groups.forEach((group) => {
const sliceKey = group.dataset.sliceKey || "";
const roughnessKey = group.dataset.roughnessKey || "";
const activeRoughness = checkedValues(iceControls, `input[data-ice-roughness-toggle][data-slice-key="${sliceKey}"]`);
group.hidden = !activeSlices.has(sliceKey) || !activeRoughness.has(roughnessKey);
});
iceControls.querySelectorAll(".ice-roughness-filter-group").forEach((group) => {
group.hidden = !activeSlices.has(group.dataset.sliceKey || "");
});
};
iceControls.addEventListener("change", updateIceFilters);
iceControls.addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) {
return;
}
if (button.dataset.sliceAction) {
const checked = button.dataset.sliceAction === "all";
iceControls.querySelectorAll("input[data-ice-slice-toggle]").forEach((input) => {
input.checked = checked;
});
updateIceFilters();
}
if (button.dataset.roughnessAction) {
const checked = button.dataset.roughnessAction === "all";
const sliceKey = button.dataset.sliceKey || "";
iceControls.querySelectorAll(`input[data-ice-roughness-toggle][data-slice-key="${sliceKey}"]`).forEach((input) => {
input.checked = checked;
});
updateIceFilters();
}
});
scope.addEventListener("plot-filter:update", updateIceFilters);
updateIceFilters();
});
document.querySelectorAll("button[data-page-filter-action]").forEach((button) => {
button.addEventListener("click", () => {
const checked = button.dataset.pageFilterAction === "show";
document.querySelectorAll(".plot-filter-scope input[type='checkbox']").forEach((input) => {
input.checked = checked;
});
document.querySelectorAll(".plot-filter-scope .variable-filter-controls").forEach((controls) => {
controls.dispatchEvent(new Event("change", { bubbles: true }));
});
});
});
});
</script>
"""
# HTML plot categories selected by --convergence, --cutdata, and --iceshape.
# With no category flags, all three categories are enabled.
HTML_BUILD_SECTIONS: set[str] = {"convergence", "cutdata", "iceshape"}
def html_section_enabled(section: str) -> bool:
return section in HTML_BUILD_SECTIONS
PARTICIPANT_DETAILS_SCRIPT = """
<script>
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll("[data-participant-dialog-open]").forEach((button) => {
button.addEventListener("click", () => {
const dialog = document.getElementById(button.dataset.participantDialogOpen || "");
if (dialog) {
dialog.showModal();
}
});
});
document.querySelectorAll("[data-participant-dialog-close]").forEach((button) => {
button.addEventListener("click", () => button.closest("dialog")?.close());
});
document.querySelectorAll(".participant-dialog").forEach((dialog) => {
dialog.addEventListener("click", (event) => {
if (event.target === dialog) {
dialog.close();
}
});
});
});
</script>
"""
SITE_SIDEBAR_SCRIPT = """
<script>
document.addEventListener("DOMContentLoaded", () => {
const sidebar = document.querySelector("[data-site-sidebar]");
const hideButton = document.querySelector("[data-site-sidebar-hide]");
const showButton = document.querySelector("[data-site-sidebar-show]");
if (!sidebar || !hideButton || !showButton) return;
const setHidden = (hidden) => {
document.body.classList.toggle("site-sidebar-hidden", hidden);
showButton.hidden = !hidden;
try { localStorage.setItem("ipw3-sidebar-hidden", hidden ? "1" : "0"); } catch (_) {}
};
let initiallyHidden = false;
try { initiallyHidden = localStorage.getItem("ipw3-sidebar-hidden") === "1"; } catch (_) {}
setHidden(initiallyHidden);
hideButton.addEventListener("click", () => setHidden(true));
showButton.addEventListener("click", () => setHidden(false));
});
</script>
"""
PLOT_DOWNLOAD_SCRIPT = """
<script>
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll("[data-plot-download]").forEach((button) => {
button.addEventListener("click", async () => {
const shell = button.closest(".plot-download-shell");
const graph = shell?.querySelector(".plotly-graph-div");
if (!shell || !graph || !window.Plotly) return;
const withLegend = button.dataset.plotDownload === "with-legend";
const original = {
showlegend: graph.layout.showlegend,
titleText: graph.layout.title?.text || "",
titleX: graph.layout.title?.x,
marginRight: graph.layout.margin?.r,
marginTop: graph.layout.margin?.t,
};
const filename = shell.dataset.plotFilename || "plot";
const title = shell.dataset.plotTitle || "";
const downloadWidth = Number(shell.dataset.downloadWidth) || 1350;
const downloadHeight = Number(shell.dataset.downloadHeight) || 900;
button.disabled = true;
try {
await Plotly.relayout(graph, {
showlegend: withLegend,
"title.text": title,
"title.x": 0.5,
"title.xanchor": "center",
"margin.t": 100,
"margin.r": withLegend ? 260 : 60,
});
await Plotly.downloadImage(graph, {
format: "png",
filename: filename,
width: downloadWidth,
height: downloadHeight,
scale: 3,
});
} finally {
await Plotly.relayout(graph, {
showlegend: original.showlegend,
"title.text": original.titleText,
"title.x": original.titleX,
"margin.r": original.marginRight,
"margin.t": original.marginTop,
});
button.disabled = false;
}
});
});
});
</script>
"""
LINKED_CONVERGENCE_LEGEND_SCRIPT = r"""
<script>
document.addEventListener("DOMContentLoaded", () => {
const participantId = (trace) => {
const text = `${trace?.name || ""} ${trace?.legendgroup || ""}`;
return text.match(/(?:^|\D)(\d{3})(?!\d)/)?.[1] || "";
};
const finite = (values) => values.map(Number).filter(Number.isFinite).sort((a, b) => a - b);
const percentile = (values, fraction) => {
if (!values.length) return null;
const index = (values.length - 1) * fraction;
const lower = Math.floor(index);
const upper = Math.ceil(index);
return values[lower] + (values[upper] - values[lower]) * (index - lower);
};
const format = (value, percent = false) => {
if (value === null || !Number.isFinite(value)) return "n/a";
return `${Number(value.toPrecision(6))}${percent ? "%" : ""}`;
};
document.querySelectorAll('[data-linked-participant-legend="grid-convergence"]').forEach((group) => {
const frames = Array.from(group.querySelectorAll("iframe.plotly-lazy-frame"));
let attempts = 0;
const retryWhenPlotsReady = () => {
if (attempts++ < 100) setTimeout(initialize, 100);
};
const initialize = () => {
if (group.dataset.linkedLegendReady === "1") return;
const graphs = frames.length
? frames.flatMap((frame) => {
try { return Array.from(frame.contentDocument?.querySelectorAll(".plotly-graph-div") || []); }
catch (_) { return []; }
})
: Array.from(group.querySelectorAll(".plotly-graph-div"));
if (graphs.length < 3 || graphs.some((graph) => !graph.data || typeof graph.on !== "function")) {
retryWhenPlotsReady();
return;
}
const [rawGraph, relativeGraph] = graphs;
const boxGraph = graphs.find((graph, index) => index >= 2 &&
(graph.data || []).some((trace) => trace.type === "box" && trace.customdata));
const table = group.querySelector(".statistical-table");
const participantSummary = group.querySelector(".statistical-participants");
if (!boxGraph || !table) {
retryWhenPlotsReady();
return;
}
const relativePlotly = relativeGraph.ownerDocument.defaultView?.Plotly;
const boxPlotly = boxGraph.ownerDocument.defaultView?.Plotly;
if (!relativePlotly || !boxPlotly) {
retryWhenPlotsReady();
return;
}
group.dataset.linkedLegendReady = "1";
const pointRecords = [];
(boxGraph.data || []).forEach((trace, traceIndex) => {
const id = participantId(trace) || String(trace.customdata?.[0]?.[0] || "");
const level = String(trace.x?.[0] || "").toUpperCase();
const value = Number(trace.y?.[0]);
if (trace.type === "box" && id && level && Number.isFinite(value)) {
pointRecords.push({id, level, value, traceIndex});
}
});
const summaryTraceByLevel = new Map();
(boxGraph.data || []).forEach((trace, traceIndex) => {
if (trace.type === "box" && !trace.customdata && /^L[1-4]$/i.test(String(trace.name || ""))) {
summaryTraceByLevel.set(String(trace.name).toUpperCase(), traceIndex);
}
});
const activeParticipants = () => new Set(
(rawGraph.data || [])
.filter((trace) => trace.visible !== false && trace.visible !== "legendonly")
.map(participantId)
.filter(Boolean)
);
const updateDependents = async () => {
const active = activeParticipants();
const relativeVisibility = (relativeGraph.data || []).map((trace) => {
const id = participantId(trace);
return id ? (active.has(id) ? true : "legendonly") : trace.visible;
});
await relativePlotly.restyle(relativeGraph, {visible: relativeVisibility});
const boxVisibility = (boxGraph.data || []).map((trace) => {
const id = participantId(trace) || String(trace.customdata?.[0]?.[0] || "");
return id ? (active.has(id) ? true : false) : trace.visible;
});
for (const level of ["L1", "L2", "L3", "L4"]) {
const values = finite(pointRecords.filter((point) => point.level === level && active.has(point.id)).map((point) => point.value));
const traceIndex = summaryTraceByLevel.get(level);
if (traceIndex !== undefined) {
await boxPlotly.restyle(boxGraph, {y: [values]}, [traceIndex]);
}
const row = Array.from(table.tBodies[0]?.rows || []).find((candidate) => candidate.cells[0]?.textContent.trim() === level);
if (!row) continue;
const mean = values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : null;
const median = percentile(values, 0.5);
const q1 = percentile(values, 0.25);
const q3 = percentile(values, 0.75);
const standardDeviation = values.length > 1
? Math.sqrt(values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / (values.length - 1))
: null;
const coefficientOfVariation = standardDeviation !== null && Math.abs(mean) > 1e-15
? standardDeviation / Math.abs(mean) * 100 : null;
const iqr = q1 === null ? null : q3 - q1;
const relativeIqr = iqr !== null && Math.abs(median) > 1e-15 ? iqr / Math.abs(median) * 100 : null;
[mean, median, standardDeviation, coefficientOfVariation, q1, q3, iqr, relativeIqr]
.forEach((value, index) => { row.cells[index + 1].textContent = format(value, index === 3 || index === 7); });
}
await boxPlotly.restyle(boxGraph, {visible: boxVisibility});
const includedIds = [...new Set(pointRecords.filter((point) => active.has(point.id)).map((point) => point.id))].sort();
if (participantSummary) {
participantSummary.textContent = `Number of participants considered = ${includedIds.length} | IDs: ${includedIds.join(", ")}`;
}
};
let updateQueued = false;
const queueDependentUpdate = () => {
if (updateQueued) return;
updateQueued = true;
requestAnimationFrame(() => {
updateQueued = false;
updateDependents().catch((error) => console.error("Linked convergence plot update failed", error));
});
};
// Keep Plotly's native single-click and double-click legend behavior.
// Synchronize only after Plotly has committed the raw plot visibility.
rawGraph.on("plotly_restyle", queueDependentUpdate);
rawGraph.on("plotly_legendclick", () => setTimeout(queueDependentUpdate, 0));
rawGraph.on("plotly_legenddoubleclick", () => setTimeout(queueDependentUpdate, 0));
queueDependentUpdate();
};
frames.forEach((frame) => frame.addEventListener("load", initialize));
initialize();
});
});
</script>
"""
PLOT_IDENTITY_SCRIPT = r"""
<script>
document.addEventListener("DOMContentLoaded", () => {
const identityToggle = document.querySelector("[data-participant-legend-toggle]");
if (!identityToggle) return;
let identitiesHidden = false;
try { identitiesHidden = localStorage.getItem("ipw3-participant-identities-hidden") === "1"; } catch (_) {}
const participantIdPattern = /\b(?:Participant\s+)?\d{3}(?:\.[A-Za-z0-9_-]+)?\b/g;
const anonymizeText = (value) => String(value).replace(participantIdPattern, "Participant");
const updateTextIdentity = (element) => {
if (!element.dataset.identityVisibleText) element.dataset.identityVisibleText = element.textContent || "";
element.textContent = identitiesHidden ? anonymizeText(element.dataset.identityVisibleText) : element.dataset.identityVisibleText;
};
const updatePlotIdentity = async (plotDocument) => {
const plotly = plotDocument?.defaultView?.Plotly;
if (!plotly) return;
for (const graph of plotDocument.querySelectorAll(".plotly-graph-div")) {
if (!graph._ipw3VisibleTraceText) {
graph._ipw3VisibleTraceText = (graph.data || []).map((trace) => ({ name: trace.name, hovertemplate: trace.hovertemplate }));
}
const visible = graph._ipw3VisibleTraceText;
const names = visible.map((trace) => identitiesHidden ? anonymizeText(trace.name || "") : trace.name);
const hovertemplates = visible.map((trace) =>
identitiesHidden && typeof trace.hovertemplate === "string" ? anonymizeText(trace.hovertemplate) : trace.hovertemplate
);
await plotly.relayout(graph, { showlegend: !identitiesHidden });
await plotly.restyle(graph, { name: names, hovertemplate: hovertemplates });
}
};
const updateAllIdentities = async () => {
identityToggle.textContent = identitiesHidden ? "Show participant IDs and legends" : "Hide participant IDs and legends";
identityToggle.setAttribute("aria-pressed", String(identitiesHidden));
document.querySelectorAll(".slideshow-slide-header h2, .slide-sidebar-view a, .combined-grid-card h5, .combined-beta-card h4").forEach(updateTextIdentity);
await updatePlotIdentity(document);
for (const frame of document.querySelectorAll("iframe.plotly-lazy-frame")) {
try { if (frame.contentDocument) await updatePlotIdentity(frame.contentDocument); } catch (_) {}
}
};
document.addEventListener("load", (event) => {
if (event.target instanceof HTMLIFrameElement && event.target.matches("iframe.plotly-lazy-frame")) {
try { void updatePlotIdentity(event.target.contentDocument); } catch (_) {}
}
}, true);
identityToggle.addEventListener("click", () => {
identitiesHidden = !identitiesHidden;
try { localStorage.setItem("ipw3-participant-identities-hidden", identitiesHidden ? "1" : "0"); } catch (_) {}
void updateAllIdentities();
});
void updateAllIdentities();
});
</script>
"""
SLIDESHOW_SCRIPT = r"""
<script>
document.addEventListener("DOMContentLoaded", () => {
const deck = document.querySelector("[data-slideshow-deck]");
const source = document.querySelector("[data-slideshow-source]");
const sidebar = document.querySelector("[data-slide-sidebar]");
const layout = document.querySelector("[data-slideshow-layout]");
const sidebarToggle = document.querySelector("[data-sidebar-toggle]");
const counter = document.querySelector("[data-slide-counter]");
const previousButton = document.querySelector("[data-slide-previous]");
const nextButton = document.querySelector("[data-slide-next]");
if (!deck || !source || !sidebar || !layout || !sidebarToggle || !counter || !previousButton || !nextButton) {
return;
}
const slides = [];
const groups = new Map();
const plotContainers = Array.from(source.querySelectorAll(".plot-container")).filter(
(container) => !container.closest(".plotly-graph-div")
);
plotContainers.forEach((plotContainer, index) => {
const sourceGroup = plotContainer.closest("[data-slide-case][data-slide-view]");
if (!sourceGroup) {
return;
}
const plotSection = plotContainer.closest(".plot-subsection[data-variable-label]");
const localGroup = plotContainer.closest(".slice-plot-group, .beta-mini-plot, .combined-beta-card");
const caseLabel = sourceGroup.dataset.slideCase;
const viewLabel = sourceGroup.dataset.slideView;
const plotLabel = plotSection?.dataset.variableLabel
|| plotSection?.querySelector("h4")?.textContent?.trim()
|| "Plot";
const detailLabel = localGroup?.querySelector("h5, h4")?.textContent?.trim() || "";
const title = detailLabel && detailLabel !== plotLabel ? `${plotLabel} — ${detailLabel}` : plotLabel;
const slideId = `slide-${index + 1}`;
const slide = document.createElement("article");
slide.className = "slideshow-slide";
slide.id = slideId;
slide.hidden = true;
const slideHeader = document.createElement("header");
slideHeader.className = "slideshow-slide-header";
const slideContext = document.createElement("p");
slideContext.textContent = `${caseLabel} · ${viewLabel}`;
const slideTitle = document.createElement("h2");
slideTitle.textContent = title;
slideHeader.append(slideContext, slideTitle);
slide.appendChild(slideHeader);
const description = plotSection?.querySelector(":scope > .plot-description");
if (description) {
slide.appendChild(description.cloneNode(true));
}
slide.appendChild(plotContainer);
deck.appendChild(slide);
slides.push(slide);
const groupKey = JSON.stringify([caseLabel, viewLabel]);
if (!groups.has(groupKey)) {
groups.set(groupKey, { caseLabel, viewLabel, items: [] });
}
groups.get(groupKey).items.push({ title, slideId, index });
});
source.remove();
sidebarToggle.addEventListener("click", () => {
const collapsed = layout.classList.toggle("sidebar-collapsed");
sidebarToggle.setAttribute("aria-expanded", String(!collapsed));
sidebarToggle.textContent = collapsed ? "Show sidebar" : "Hide sidebar";
});
let currentCase = "";
let currentCaseGroup = null;
groups.forEach((group) => {
if (group.caseLabel !== currentCase) {
currentCaseGroup = document.createElement("details");
currentCaseGroup.className = "slide-sidebar-case";
currentCaseGroup.open = true;
const caseSummary = document.createElement("summary");
caseSummary.textContent = group.caseLabel;
currentCaseGroup.appendChild(caseSummary);
sidebar.appendChild(currentCaseGroup);
currentCase = group.caseLabel;
}
const viewGroup = document.createElement("details");
viewGroup.className = "slide-sidebar-view";
viewGroup.open = true;
const viewSummary = document.createElement("summary");
viewSummary.textContent = group.viewLabel;
viewGroup.appendChild(viewSummary);
group.items.forEach((item) => {
const link = document.createElement("a");
link.href = `#${item.slideId}`;
link.dataset.slideIndex = String(item.index);
link.textContent = item.title;
viewGroup.appendChild(link);
});
currentCaseGroup.appendChild(viewGroup);
});
let activeIndex = 0;
const materializationPromises = new Map();
const materializeSlide = (index) => {
if (index < 0 || index >= slides.length) {
return Promise.resolve();
}
if (materializationPromises.has(index)) {
return materializationPromises.get(index);
}
const promise = (async () => {
const frames = Array.from(slides[index].querySelectorAll("iframe.plotly-lazy-frame[data-plot-src]"));
for (const frame of frames) {
if (frame.src) {
continue;
}
const loaded = new Promise((resolve) => {
frame.addEventListener("load", resolve, { once: true });
frame.addEventListener("error", resolve, { once: true });
});
frame.src = frame.dataset.plotSrc;
await loaded;
frame.parentNode.querySelectorAll(":scope > .plot-loading").forEach((loading) => loading.remove());
}
})();
materializationPromises.set(index, promise);
return promise;
};
const loadCurrentAndNext = async () => {
await materializeSlide(activeIndex);
window.dispatchEvent(new Event("resize"));
void materializeSlide(activeIndex + 1);
};
const showSlide = (requestedIndex, updateHash = true) => {
if (slides.length === 0) {
counter.textContent = "No plots found";
previousButton.disabled = true;
nextButton.disabled = true;
return;
}
activeIndex = Math.max(0, Math.min(requestedIndex, slides.length - 1));
slides.forEach((slide, index) => {
slide.hidden = index !== activeIndex;
});
sidebar.querySelectorAll("a[data-slide-index]").forEach((link) => {
const active = Number(link.dataset.slideIndex) === activeIndex;
link.classList.toggle("active", active);
link.setAttribute("aria-current", active ? "page" : "false");
if (active) {
link.closest(".slide-sidebar-view").open = true;
link.closest(".slide-sidebar-case").open = true;
link.scrollIntoView({ block: "nearest" });
}
});
counter.textContent = `Plot ${activeIndex + 1} of ${slides.length}`;
previousButton.disabled = activeIndex === 0;
nextButton.disabled = activeIndex === slides.length - 1;
if (updateHash) {
history.replaceState(null, "", `#${slides[activeIndex].id}`);
}
void loadCurrentAndNext();
};
sidebar.addEventListener("click", (event) => {
const link = event.target.closest("a[data-slide-index]");
if (!link) {
return;
}
event.preventDefault();
showSlide(Number(link.dataset.slideIndex));
});
previousButton.addEventListener("click", () => showSlide(activeIndex - 1));
nextButton.addEventListener("click", () => showSlide(activeIndex + 1));
document.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") {
showSlide(activeIndex - 1);
} else if (event.key === "ArrowRight") {
showSlide(activeIndex + 1);
}
});
const hashIndex = slides.findIndex((slide) => `#${slide.id}` === window.location.hash);
showSlide(hashIndex >= 0 ? hashIndex : 0, hashIndex < 0);
});
</script>
"""
def load_participants(root_dir: Path, highlight_points_by_case: HighlightPointsByCase | None = None, clean_s_cache: bool = False, participant_id: str | None = None):
participants = scan_all_participants(root_dir)
if participant_id is not None:
normalized_id = normalize_participant_id(participant_id)
participants = [participant for participant in participants if normalize_participant_id(participant.participant_id) == normalized_id]
for participant in participants:
participant.read_files(highlight_points_by_case=highlight_points_by_case, clean_s_cache=clean_s_cache)
return participants
def get_case_ids(participants) -> list[str]:
"""Return the cases that should be printed on the website.
The restructured gatherParticipantData hierarchy is:
participant.cases[case_id].grid_levels[grid_level].datasets[dataset_id]
Therefore, case IDs are collected directly from participant.cases instead of
from the old participant.datasets[...] structure.
VALID_CASES are always printed first so cases with no data still appear with
the "No matching ..." warning boxes. Any extra detected case folder is
appended afterwards.
"""
discovered = collect_case_ids(participants)
ordered_valid_cases = sorted(VALID_CASES)
extra_detected_cases = sorted(discovered - set(ordered_valid_cases))
return ordered_valid_cases + extra_detected_cases
def order_slideshow_cases(case_ids: list[str]) -> list[str]:
"""Use the presentation order requested for the IPW3 cases."""
preferred = ["TC_NACA0012_AE3932", "TC_NACA0012_AE3933", "TC_ONERAM6"]
return [case_id for case_id in preferred if case_id in case_ids] + [
case_id for case_id in case_ids if case_id not in preferred
]
def participant_readme_path(participant_id: str) -> Path | None:
"""Return the README belonging to a participant ID, if one is present."""
prefix = f"{normalize_participant_id(participant_id)}_"
for participant_dir in sorted(ROOT_DIR.iterdir()):
readme_path = participant_dir / "README.md"
if participant_dir.is_dir() and participant_dir.name.startswith(prefix) and readme_path.is_file():
return readme_path
return None
def render_inline_markdown(text: str) -> str:
"""Render the small inline Markdown subset used by participant READMEs."""
rendered = html.escape(text)
rendered = re.sub(r"`([^`]+)`", r"<code>\1</code>", rendered)
rendered = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", rendered)
rendered = re.sub(r"\[([^\]]+)\]\((https?://[^)]+)\)", r'<a href="\2" target="_blank" rel="noopener">\1</a>', rendered)
return rendered
def render_readme_markdown(markdown_text: str) -> str:
"""Convert participant README Markdown to safe, readable modal HTML."""
lines = markdown_text.splitlines()
output: list[str] = []
paragraph: list[str] = []
list_type: str | None = None
in_code_block = False
code_lines: list[str] = []
index = 0
def flush_paragraph() -> None:
if paragraph:
output.append(f"<p>{render_inline_markdown(' '.join(part.strip() for part in paragraph))}</p>")
paragraph.clear()
def close_list() -> None:
nonlocal list_type
if list_type:
output.append(f"</{list_type}>")
list_type = None
while index < len(lines):
line = lines[index].rstrip()
stripped = line.strip()
if stripped.startswith("```"):
flush_paragraph()
close_list()
if in_code_block:
output.append(f"<pre><code>{html.escape(chr(10).join(code_lines))}</code></pre>")
code_lines.clear()
in_code_block = False
else:
in_code_block = True
index += 1
continue
if in_code_block:
code_lines.append(line)
index += 1
continue
if stripped.startswith("|") and index + 1 < len(lines) and re.match(r"^\s*\|?[\s:|-]+\|?\s*$", lines[index + 1]):
flush_paragraph()
close_list()
table_lines = [line]
index += 2
while index < len(lines) and lines[index].strip().startswith("|"):
table_lines.append(lines[index])
index += 1
rows = [[cell.strip().rstrip("\\") for cell in table_line.strip().strip("|").split("|")] for table_line in table_lines]
header_row, *body_rows = rows
output.append("<div class=\"readme-table-wrapper\"><table><thead><tr>")
output.extend(f"<th>{render_inline_markdown(cell)}</th>" for cell in header_row)
output.append("</tr></thead><tbody>")
for row in body_rows:
output.append("<tr>")
output.extend(f"<td>{render_inline_markdown(cell)}</td>" for cell in row)
output.append("</tr>")
output.append("</tbody></table></div>")
continue
heading = re.match(r"^(#{1,6})\s+(.+)$", stripped)
if heading:
flush_paragraph()
close_list()
level = min(len(heading.group(1)) + 1, 6)
output.append(f"<h{level}>{render_inline_markdown(heading.group(2))}</h{level}>")
elif re.match(r"^[-*]\s+", stripped):
flush_paragraph()
if list_type != "ul":
close_list()
output.append("<ul>")
list_type = "ul"
output.append(f"<li>{render_inline_markdown(re.sub(r'^[-*]\\s+', '', stripped))}</li>")
elif re.match(r"^\d+[.)]\s+", stripped):
flush_paragraph()
if list_type != "ol":
close_list()
output.append("<ol>")
list_type = "ol"
output.append(f"<li>{render_inline_markdown(re.sub(r'^\\d+[.)]\\s+', '', stripped))}</li>")
elif not stripped:
flush_paragraph()
close_list()
else:
close_list()
paragraph.append(stripped)
index += 1
if in_code_block:
output.append(f"<pre><code>{html.escape(chr(10).join(code_lines))}</code></pre>")
flush_paragraph()
close_list()
return "\n".join(output)
def build_participants_table(participants_metadata: list[dict[str, str]], participant_id: str | None = None) -> str:
header_cells = ["Participant ID", "Organization", "Solver(s)", "Name(s)"]
header_cells_with_color = header_cells + ["Color", "Information"]
normalized_filter = normalize_participant_id(participant_id) if participant_id is not None else None
rows = []
for participant in participants_metadata:
metadata_id = normalize_participant_id(participant.get("Participant ID", ""))
if normalized_filter is not None and metadata_id != normalized_filter:
continue
color = participant_color(metadata_id)
readme_path = participant_readme_path(metadata_id)
row_html = "<tr>"
for header in header_cells:
row_html += f"<td>{html.escape(participant.get(header, ''))}</td>"
row_html += f"""
<td>
<span class="participant-color-line" style="background-color: {html.escape(color)};"></span>
<span>{html.escape(color)}</span>
</td>
"""
show_information = participant.get("Show Information on Index", True)
if show_information and readme_path:
dialog_id = f"participant-details-{metadata_id}"
details_html = render_readme_markdown(readme_path.read_text(encoding="utf-8"))
participant_label = f"{metadata_id} — {participant.get('Organization', 'Participant')}"
row_html += f"""
<td>
<button class="participant-details-button" type="button"
data-participant-dialog-open="{dialog_id}"
aria-haspopup="dialog">
View details
</button>
<dialog class="participant-dialog" id="{dialog_id}" aria-labelledby="{dialog_id}-title">
<div class="participant-dialog-shell">
<header class="participant-dialog-header">
<div>
<span class="participant-dialog-eyebrow">Participant information</span>
<h2 id="{dialog_id}-title">{html.escape(participant_label)}</h2>
</div>
<button class="participant-dialog-close" type="button"
data-participant-dialog-close aria-label="Close participant details">×</button>
</header>
<div class="participant-readme">
{details_html}
</div>
</div>
</dialog>
</td>
"""
else:
row_html += """
<td>
<button class="participant-details-button" type="button" disabled title="No participant details available">
No details
</button>
</td>
"""
row_html += "</tr>"
rows.append(row_html)
header_html = "<tr>"
for header in header_cells_with_color:
header_html += f"<th>{html.escape(header)}</th>"
header_html += "</tr>"
if not rows:
rows_html = f"""
<tr>
<td colspan="{len(header_cells_with_color)}">No participants found in participant_style.py.</td>
</tr>
"""
else:
rows_html = "\n".join(rows)
return f"""
<section class="participant-section">
<h2>Participants</h2>
<div class="participant-table-wrapper">
<table class="participant-table">
<thead>
{header_html}
</thead>
<tbody>
{rows_html}
</tbody>
</table>
</div>
</section>
"""
def normal_grid_roughness_filter(case_id: str):