-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
640 lines (577 loc) · 23.4 KB
/
Copy pathapp.js
File metadata and controls
640 lines (577 loc) · 23.4 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
const appState = {
data: null,
system: "fhn",
density: null,
policy: "bbht",
boundary: "noise",
playing: true,
seed: 17,
points: [],
orders: {},
startedAt: performance.now(),
lastCanvasWidth: 0
};
const colors = {
bbht: "#168f8a",
best: "#d8941f",
random: "#2c3432",
marked: "#d94b2b",
point: "#bec9c5",
ink: "#18201f",
muted: "#63706d",
line: "#d7dfdc",
grid: "#e7ecea"
};
const methodFallbacks = {
random: "Random",
lhs: "Latin hypercube",
sobol: "Sobol",
cross_entropy: "Cross-entropy",
subset: "Subset",
gp_lcb: "GP LCB",
rank_gaussian: "Rank Gaussian",
local_cma: "Local CMA-ES",
turbo_like: "TuRBO-like",
bbht: "BBHT"
};
const $ = (selector) => document.querySelector(selector);
const $$ = (selector) => Array.from(document.querySelectorAll(selector));
function escapeHtml(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function statMean(stat) {
return stat && Number.isFinite(stat.mean) ? stat.mean : null;
}
function fmt(value, digits = 1) {
if (value === null || value === undefined || Number.isNaN(Number(value))) return "-";
const n = Number(value);
if (Math.abs(n) >= 1000) return n.toLocaleString(undefined, { maximumFractionDigits: 0 });
if (Math.abs(n) >= 100) return n.toLocaleString(undefined, { maximumFractionDigits: 1 });
if (Math.abs(n) >= 10) return n.toLocaleString(undefined, { maximumFractionDigits: digits });
if (Math.abs(n) >= 1) return n.toLocaleString(undefined, { maximumFractionDigits: digits + 1 });
return n.toLocaleString(undefined, { maximumSignificantDigits: 3 });
}
function fmtRatio(stat) {
const n = statMean(stat);
return n === null ? "-" : `${fmt(n, 2)}×`;
}
function fmtCi(stat) {
if (!stat) return "-";
return `${fmt(stat.low, 1)}-${fmt(stat.high, 1)} 95% CI`;
}
function fmtFraction(value) {
if (value === null || value === undefined) return "-";
const pct = Number(value) * 100;
if (pct < 0.1) return `${pct.toFixed(3)}%`;
if (pct < 1) return `${pct.toFixed(2)}%`;
return `${pct.toFixed(1)}%`;
}
function fmtPct(value) {
if (value === null || value === undefined) return "-";
return `${(Number(value) * 100).toFixed(0)}%`;
}
function methodLabel(key) {
return appState.data?.meta?.methods?.[key] || methodFallbacks[key] || String(key).replaceAll("_", " ");
}
function systemLabel(key) {
return appState.data?.meta?.systems?.[key] || String(key).replaceAll("_", " ");
}
function densityKey(value) {
return Number(value).toFixed(6);
}
function seededRandom(seed) {
let t = seed >>> 0;
return () => {
t += 0x6d2b79f5;
let r = Math.imul(t ^ (t >>> 15), 1 | t);
r ^= r + Math.imul(r ^ (r >>> 7), 61 | r);
return ((r ^ (r >>> 14)) >>> 0) / 4294967296;
};
}
function clamp(value, low, high) {
return Math.max(low, Math.min(high, value));
}
function getSystemRow(system = appState.system, density = appState.density) {
const key = densityKey(density);
return appState.data.systems.find((row) => row.system === system && densityKey(row.target_fraction) === key);
}
function getDensityRow(density = appState.density) {
const key = densityKey(density);
return appState.data.density.find((row) => densityKey(row.target_fraction) === key);
}
function getBreakEvenRow(density = appState.density) {
const key = densityKey(density);
return appState.data.break_even.find((row) => densityKey(row.target_fraction) === key);
}
function getPolicyStats(row) {
const bestKey = row?.best_classical_method || "cross_entropy";
return {
bbht: {
label: "BBHT",
stat: row?.bbht_stat || row?.methods?.bbht,
color: colors.bbht
},
best: {
label: methodLabel(bestKey),
stat: row?.best_classical_stat || row?.methods?.[bestKey],
color: colors.best
},
random: {
label: "Random",
stat: row?.methods?.random,
color: colors.random
}
};
}
function scoreForSystem(system, x, y, rand) {
const jitter = 0.012 * rand();
if (system === "vdp") return Math.abs(x - 0.5) + 0.08 * Math.abs(y - 0.5) + jitter;
if (system === "spring") return Math.min(Math.abs(x - 0.32), Math.abs(y - 0.68)) + jitter;
if (system === "pendulum") return Math.abs(y - (0.5 + 0.22 * Math.sin(7.2 * x))) + 0.04 * Math.abs(x - 0.7) + jitter;
if (system === "lorenz") return Math.abs((x - 0.52) * (x - 0.52) + (y - 0.48) * (y - 0.48) - 0.105) + jitter;
if (system === "duffing") return Math.abs(Math.sin(8.5 * x) * Math.cos(7.5 * y) - 0.12) + 0.05 * Math.abs(x - y) + jitter;
if (system === "coupled_fhn") {
const r1 = Math.abs(Math.hypot(x - 0.34, y - 0.58) - 0.18);
const r2 = Math.abs(Math.hypot(x - 0.68, y - 0.42) - 0.14);
const bridge = Math.abs(y - (0.62 - 0.45 * x));
return Math.min(r1, r2, bridge) + jitter;
}
return Math.abs(y - (0.48 + 0.23 * Math.sin(9.5 * x + 1.1))) + 0.025 * Math.abs(x - 0.52) + jitter;
}
function shuffle(items, rand) {
const out = items.slice();
for (let i = out.length - 1; i > 0; i -= 1) {
const j = Math.floor(rand() * (i + 1));
[out[i], out[j]] = [out[j], out[i]];
}
return out;
}
function regenerateArena() {
const rand = seededRandom(appState.seed + Math.floor(Number(appState.density || 0.001) * 1000000));
const n = 760;
const m = Math.max(1, Math.round(n * Number(appState.density || 0.001)));
const raw = [];
for (let i = 0; i < n; i += 1) {
const x = 0.035 + 0.93 * rand();
const y = 0.035 + 0.93 * rand();
raw.push({ id: i, x, y, score: scoreForSystem(appState.system, x, y, rand), marked: false });
}
const orderedByScore = raw.slice().sort((a, b) => a.score - b.score);
const markedIds = new Set(orderedByScore.slice(0, m).map((p) => p.id));
appState.points = raw.map((p) => ({ ...p, marked: markedIds.has(p.id) }));
const randomRand = seededRandom(appState.seed * 97 + 11);
const bestRand = seededRandom(appState.seed * 131 + 5);
const bbhtRand = seededRandom(appState.seed * 173 + 29);
const ids = appState.points.map((p) => p.id);
const randomOrder = shuffle(ids, randomRand);
const bestOrder = appState.points
.slice()
.sort((a, b) => (a.score + 0.045 * bestRand()) - (b.score + 0.045 * bestRand()))
.map((p) => p.id);
const bbhtOrder = shuffle(ids, bbhtRand);
appState.orders = { random: randomOrder, best: bestOrder, bbht: bbhtOrder };
appState.startedAt = performance.now();
}
function firstMarkedIndex(order) {
for (let i = 0; i < order.length; i += 1) {
if (appState.points[order[i]]?.marked) return i;
}
return order.length - 1;
}
function setCanvasSize(canvas) {
const rect = canvas.getBoundingClientRect();
const ratio = window.devicePixelRatio || 1;
const width = Math.max(480, Math.floor(rect.width * ratio));
const height = Math.max(260, Math.floor(rect.height * ratio));
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
return { width, height, ratio };
}
function drawArena(now) {
const canvas = $("#arena");
if (!canvas || !appState.points.length) return;
const ctx = canvas.getContext("2d");
const { width, height, ratio } = setCanvasSize(canvas);
const pad = 36 * ratio;
const row = getSystemRow();
const stats = getPolicyStats(row);
const means = Object.values(stats).map((entry) => statMean(entry.stat)).filter((v) => v !== null);
const worst = Math.max(...means, 1);
const elapsed = appState.playing ? now - appState.startedAt : appState.pausedAt - appState.startedAt;
const phase = ((elapsed / 7200) % 1);
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "#fbfcfb";
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = colors.grid;
ctx.lineWidth = 1 * ratio;
for (let i = 0; i <= 8; i += 1) {
const x = pad + (i / 8) * (width - 2 * pad);
const y = pad + (i / 8) * (height - 2 * pad);
ctx.beginPath();
ctx.moveTo(x, pad);
ctx.lineTo(x, height - pad);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(pad, y);
ctx.lineTo(width - pad, y);
ctx.stroke();
}
ctx.strokeStyle = colors.line;
ctx.strokeRect(pad, pad, width - 2 * pad, height - 2 * pad);
const toCanvas = (point) => ({
x: pad + point.x * (width - 2 * pad),
y: pad + (1 - point.y) * (height - 2 * pad)
});
for (const point of appState.points) {
const pos = toCanvas(point);
ctx.beginPath();
ctx.fillStyle = point.marked ? "rgba(217, 75, 43, 0.78)" : "rgba(190, 201, 197, 0.62)";
ctx.arc(pos.x, pos.y, point.marked ? 3.0 * ratio : 2.1 * ratio, 0, Math.PI * 2);
ctx.fill();
}
for (const policy of ["random", "best", "bbht"]) {
const order = appState.orders[policy] || [];
const mean = statMean(stats[policy]?.stat) || worst;
const hitIndex = firstMarkedIndex(order);
const hitPhase = clamp((mean / worst) * 0.78 + 0.09, 0.08, 0.95);
const visible = clamp(Math.floor((phase / hitPhase) * (hitIndex + 1)), 1, hitIndex + 1);
const alpha = policy === appState.policy ? 0.92 : 0.26;
const lineWidth = policy === appState.policy ? 3.1 * ratio : 1.5 * ratio;
ctx.strokeStyle = hexToRgba(stats[policy].color, alpha);
ctx.fillStyle = hexToRgba(stats[policy].color, alpha);
ctx.lineWidth = lineWidth;
ctx.beginPath();
for (let i = 0; i < visible; i += 1) {
const point = appState.points[order[i]];
if (!point) continue;
const pos = toCanvas(point);
if (i === 0) ctx.moveTo(pos.x, pos.y);
else ctx.lineTo(pos.x, pos.y);
}
ctx.stroke();
for (let i = Math.max(0, visible - 11); i < visible; i += 1) {
const point = appState.points[order[i]];
if (!point) continue;
const pos = toCanvas(point);
ctx.beginPath();
ctx.arc(pos.x, pos.y, policy === appState.policy ? 4.5 * ratio : 3.2 * ratio, 0, Math.PI * 2);
ctx.fill();
}
if (phase >= hitPhase) {
const hitPoint = appState.points[order[hitIndex]];
if (hitPoint) {
const pos = toCanvas(hitPoint);
const pulse = 1 + 0.22 * Math.sin(now / 210);
ctx.beginPath();
ctx.strokeStyle = hexToRgba(stats[policy].color, policy === appState.policy ? 0.95 : 0.45);
ctx.lineWidth = (policy === appState.policy ? 4 : 2) * ratio;
ctx.arc(pos.x, pos.y, (12 + 7 * pulse) * ratio, 0, Math.PI * 2);
ctx.stroke();
}
}
}
drawCanvasHud(ctx, width, height, ratio, row, stats);
}
function drawCanvasHud(ctx, width, height, ratio, row, stats) {
const x = 52 * ratio;
const y = 52 * ratio;
const w = 310 * ratio;
const h = 92 * ratio;
ctx.fillStyle = "rgba(255, 255, 255, 0.88)";
roundRect(ctx, x, y, w, h, 8 * ratio);
ctx.fill();
ctx.fillStyle = colors.ink;
ctx.font = `${15 * ratio}px system-ui, sans-serif`;
ctx.fillText(`${systemLabel(row.system)} at ${fmtFraction(row.target_fraction)} marked`, x + 16 * ratio, y + 28 * ratio);
ctx.fillStyle = colors.muted;
ctx.font = `${12 * ratio}px system-ui, sans-serif`;
const selected = stats[appState.policy];
const mean = statMean(selected.stat);
ctx.fillText(`${selected.label}: ${fmt(mean)} mean first-hit queries`, x + 16 * ratio, y + 55 * ratio);
ctx.fillText(`Exact marked set in this view: ${Math.max(1, Math.round(appState.points.length * row.target_fraction))}/${appState.points.length}`, x + 16 * ratio, y + 76 * ratio);
}
function roundRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.arcTo(x + width, y, x + width, y + height, radius);
ctx.arcTo(x + width, y + height, x, y + height, radius);
ctx.arcTo(x, y + height, x, y, radius);
ctx.arcTo(x, y, x + width, y, radius);
ctx.closePath();
}
function hexToRgba(hex, alpha) {
const value = hex.replace("#", "");
const r = parseInt(value.slice(0, 2), 16);
const g = parseInt(value.slice(2, 4), 16);
const b = parseInt(value.slice(4, 6), 16);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
function renderMetrics() {
const row = getSystemRow();
if (!row) return;
const breakEven = getBreakEvenRow();
$("#metric-bbht").textContent = fmt(statMean(row.bbht_stat));
$("#metric-bbht-ci").textContent = fmtCi(row.bbht_stat);
$("#metric-best").textContent = fmt(statMean(row.best_classical_stat));
$("#metric-best-label").textContent = methodLabel(row.best_classical_method);
$("#metric-ratio").innerHTML = fmtRatio(row.best_classical_over_bbht);
$("#metric-win").textContent = `${fmtPct(row.bbht_win_rate)} BBHT win rate across configs`;
$("#metric-break-even").innerHTML = breakEven ? fmtRatio(breakEven.oracle_break_even_multiplier) : "-";
$("#arena-subtitle").textContent = `${systemLabel(row.system)}, ${fmtFraction(row.target_fraction)} marked, ${row.n_configs} configurations in this slice.`;
}
function renderDensityChart() {
const host = $("#density-chart");
const rows = appState.data.density;
const methods = [
["bbht", "BBHT", "line-bbht"],
["cross_entropy", "Cross-entropy", "line-ce"],
["subset", "Subset", "line-subset"],
["random", "Random", "line-random"]
];
const values = [];
for (const row of rows) {
for (const [key] of methods) {
const mean = statMean(row.methods?.[key]);
if (mean !== null) values.push(mean);
}
}
const w = 760;
const h = 330;
const m = { left: 54, right: 24, top: 22, bottom: 56 };
const yMin = Math.log10(Math.max(1, Math.min(...values)));
const yMax = Math.log10(Math.max(...values) * 1.12);
const xAt = (i) => m.left + (rows.length === 1 ? 0.5 : i / (rows.length - 1)) * (w - m.left - m.right);
const yAt = (v) => h - m.bottom - ((Math.log10(Math.max(1, v)) - yMin) / (yMax - yMin || 1)) * (h - m.top - m.bottom);
const grid = [0, 0.25, 0.5, 0.75, 1].map((t) => {
const y = m.top + t * (h - m.top - m.bottom);
return `<line class="grid-line" x1="${m.left}" y1="${y}" x2="${w - m.right}" y2="${y}"></line>`;
}).join("");
const lines = methods.map(([key, label, cls]) => {
const points = rows.map((row, i) => `${xAt(i)},${yAt(statMean(row.methods?.[key]) || 1)}`).join(" ");
return `<polyline class="${cls}" points="${points}"><title>${escapeHtml(label)}</title></polyline>`;
}).join("");
const ticks = rows.map((row, i) => {
const x = xAt(i);
return `<g><line class="axis" x1="${x}" y1="${h - m.bottom}" x2="${x}" y2="${h - m.bottom + 5}"></line><text class="chart-label" x="${x}" y="${h - 24}" text-anchor="middle">${fmtFraction(row.target_fraction)}</text></g>`;
}).join("");
const legend = methods.map(([key, label, cls], i) => {
const x = m.left + i * 138;
return `<g><line class="${cls}" x1="${x}" y1="18" x2="${x + 24}" y2="18"></line><text class="chart-label" x="${x + 31}" y="22">${escapeHtml(label)}</text></g>`;
}).join("");
host.innerHTML = `
<svg viewBox="0 0 ${w} ${h}" role="img" aria-label="Density scaling line chart">
${grid}
<line class="axis" x1="${m.left}" y1="${h - m.bottom}" x2="${w - m.right}" y2="${h - m.bottom}"></line>
<line class="axis" x1="${m.left}" y1="${m.top}" x2="${m.left}" y2="${h - m.bottom}"></line>
${lines}
${ticks}
<text class="chart-label" x="${m.left}" y="${h - 6}">marked fraction</text>
<text class="chart-label" x="14" y="${m.top + 8}" transform="rotate(-90 14 ${m.top + 8})">log query scale</text>
${legend}
</svg>
`;
}
function renderSystemBars() {
const host = $("#system-bars");
const rareDensity = Math.min(...appState.data.density.map((row) => row.target_fraction));
const rows = appState.data.systems
.filter((row) => densityKey(row.target_fraction) === densityKey(rareDensity))
.map((row) => ({ ...row, ratio: statMean(row.best_classical_over_bbht) || 0 }))
.sort((a, b) => b.ratio - a.ratio);
const maxRatio = Math.max(...rows.map((row) => row.ratio), 1);
host.innerHTML = rows.map((row) => `
<div class="bar-row">
<span class="bar-name">${escapeHtml(row.label)}</span>
<span class="bar-track"><i class="bar-fill" style="width:${clamp((row.ratio / maxRatio) * 100, 2, 100)}%"></i></span>
<span class="bar-value">${fmt(row.ratio, 2)}×</span>
</div>
`).join("");
}
function miniStat(label, value, extra = "") {
return `<div class="mini-stat"><span>${escapeHtml(label)}</span><strong>${value}</strong>${extra ? `<em>${escapeHtml(extra)}</em>` : ""}</div>`;
}
function renderBoundary() {
if (appState.boundary === "noise") renderNoiseBoundary();
else if (appState.boundary === "oracle") renderOracleBoundary();
else if (appState.boundary === "continuous") renderContinuousBoundary();
else renderOnlineBoundary();
}
function renderNoiseBoundary() {
const host = $("#boundary-view");
const groups = new Map();
for (const row of appState.data.noise) {
if (!groups.has(row.noise_model)) groups.set(row.noise_model, []);
groups.get(row.noise_model).push(row);
}
host.innerHTML = `<div class="noise-grid">${Array.from(groups.entries()).map(([model, rows]) => {
const body = rows.map((row) => `
<div class="compact-row">
<span>${fmt(row.eta_over_p, 2)} eta/p</span>
<strong>${fmtRatio(row.best_nonquantum_over_bbht)}</strong>
<em>${fmtPct(row.bbht_win_rate)} win</em>
</div>
`).join("");
return `
<div class="mini-panel">
<h3>${escapeHtml(model.replaceAll("_", " "))}</h3>
<p>Performance is reported at the rarest density in the noise sweep.</p>
<div class="compact-list">${body}</div>
</div>
`;
}).join("")}</div>`;
}
function renderOracleBoundary() {
const host = $("#boundary-view");
const rows = appState.data.break_even;
host.innerHTML = `<div class="oracle-grid">${rows.map((row) => `
<div class="mini-panel">
<h3>${fmtFraction(row.target_fraction)} marked</h3>
${miniStat("oracle break-even", fmtRatio(row.oracle_break_even_multiplier))}
${miniStat("no-qRAM single run", fmtRatio(row.no_qram_single_run_multiplier))}
${miniStat("median amortization", fmt(row.median_min_amortized_runs_for_unit_oracle_win, 0))}
${miniStat("state-prep cancels", fmtPct(row.state_prep_cancels_single_run_rate))}
</div>
`).join("")}</div>`;
}
function renderContinuousBoundary() {
const host = $("#boundary-view");
const rows = appState.data.continuous;
const embedded = appState.data.embedded_32d;
host.innerHTML = `
<div class="continuous-grid">
${rows.map((row) => `
<div class="mini-panel">
<h3>${escapeHtml(row.label)}</h3>
${miniStat("best method", escapeHtml(methodLabel(row.best_method)))}
${miniStat("first-hit evals", fmt(statMean(row.best_evals)))}
${miniStat("success rate", fmtPct(row.success_rate))}
</div>
`).join("")}
${embedded.map((row) => `
<div class="mini-panel feature-panel">
<h3>32D embedded FHN, ${fmtFraction(row.target_fraction)}</h3>
${miniStat("best continuous", escapeHtml(methodLabel(row.best_continuous_method)))}
${miniStat("continuous / BBHT", fmtRatio(row.best_continuous_over_bbht))}
${miniStat("success rate", fmtPct(row.best_continuous_success_rate))}
</div>
`).join("")}
</div>
`;
}
function renderOnlineBoundary() {
const host = $("#boundary-view");
const qpuLookup = new Map(appState.data.qpu.map((row) => [`${row.simulator}:${densityKey(row.target_fraction)}`, row]));
host.innerHTML = `<div class="online-grid">${appState.data.online.map((row) => {
const qpu = qpuLookup.get(`${row.simulator}:${densityKey(row.target_fraction)}`);
const cycles = qpu?.max_logical_oracle_cycles?.["1 MHz"] || qpu?.max_logical_oracle_cycles?.["100 kHz"] || null;
return `
<div class="mini-panel">
<h3>${escapeHtml(row.simulator.replaceAll("_", " "))}</h3>
${miniStat("query ratio", fmtRatio(row.best_classical_over_bbht_queries))}
${miniStat("time-proxy ratio", fmtRatio(row.best_classical_over_bbht_time_proxy))}
${miniStat("CPU loop time", `${fmt(statMean(row.best_classical_wall_time_s), 3)} s`)}
${miniStat("max oracle cycles", cycles ? fmt(statMean(cycles), 0) : "-")}
</div>
`;
}).join("")}</div>`;
}
function renderControls() {
const systems = Array.from(new Map(appState.data.systems.map((row) => [row.system, row.label])).entries());
const densities = appState.data.density.map((row) => row.target_fraction);
if (!systems.some(([key]) => key === appState.system)) appState.system = systems[0][0];
if (appState.density === null) appState.density = Math.min(...densities);
$("#system-select").innerHTML = systems.map(([key, label]) => `<option value="${escapeHtml(key)}">${escapeHtml(label)}</option>`).join("");
$("#density-select").innerHTML = densities.map((value) => `<option value="${value}">${fmtFraction(value)}</option>`).join("");
$("#system-select").value = appState.system;
$("#density-select").value = String(appState.density);
}
function renderSourceLine() {
const sources = appState.data.meta.sources || [];
$("#source-line").textContent = `Generated ${appState.data.meta.generated_at} from ${sources.length} hashed result artifacts. Static bundle uses relative paths only.`;
$("#meta-configs").textContent = `${fmt(appState.data.meta.n_final_configs, 0)} configs`;
$("#meta-trials").textContent = `${fmt(appState.data.meta.n_final_trials, 0)} trials`;
}
function renderAll() {
renderControls();
renderMetrics();
renderDensityChart();
renderSystemBars();
renderBoundary();
}
function attachEvents() {
$("#system-select").addEventListener("change", (event) => {
appState.system = event.target.value;
regenerateArena();
renderMetrics();
});
$("#density-select").addEventListener("change", (event) => {
appState.density = Number(event.target.value);
regenerateArena();
renderMetrics();
});
$$("[data-policy]").forEach((button) => {
button.addEventListener("click", () => {
$$("[data-policy]").forEach((item) => item.classList.remove("is-active"));
button.classList.add("is-active");
appState.policy = button.dataset.policy;
renderMetrics();
});
});
$$("[data-boundary]").forEach((button) => {
button.addEventListener("click", () => {
$$("[data-boundary]").forEach((item) => item.classList.remove("is-active"));
button.classList.add("is-active");
appState.boundary = button.dataset.boundary;
renderBoundary();
});
});
$("#play-toggle").addEventListener("click", () => {
appState.playing = !appState.playing;
const button = $("#play-toggle");
if (appState.playing) {
appState.startedAt = performance.now() - (appState.pausedAt - appState.startedAt);
button.textContent = "Pause";
} else {
appState.pausedAt = performance.now();
button.textContent = "Play";
}
});
$("#reseed-button").addEventListener("click", () => {
appState.seed += 101;
regenerateArena();
});
window.addEventListener("resize", () => drawArena(performance.now()));
}
async function init() {
try {
const response = await fetch("data/qcphast_webapp_data.json", { cache: "no-store" });
if (!response.ok) throw new Error(`Data bundle request failed with ${response.status}`);
appState.data = await response.json();
renderSourceLine();
renderControls();
attachEvents();
regenerateArena();
renderAll();
requestAnimationFrame(loop);
} catch (error) {
document.body.innerHTML = `
<main class="load-error">
<h1>QC-PHAST Evidence Explorer</h1>
<p>The static data bundle could not be loaded. Run the data builder and serve the webapp over HTTP.</p>
<pre>${escapeHtml(error.message)}</pre>
</main>
`;
}
}
function loop(now) {
drawArena(now);
requestAnimationFrame(loop);
}
init();