cellscreen 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cellscreen/report.py ADDED
@@ -0,0 +1,1359 @@
1
+ """Self-contained interactive HTML report generator for CellScreen runs.
2
+
3
+ Aesthetic: Light scientific-editorial (Swiss lab-notebook clarity) with a standards-compliant
4
+ two-state dark-mode toggle (`color-scheme`, `light-dark()` + fallbacks), interactive SVG
5
+ perturbation-vs-gene LFC heatmap, interactive per-perturbation volcano/rank-effect plot,
6
+ and an accessible sortable/responsive candidate table — 100% offline with zero external CDNs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import html
12
+ import json
13
+ import math
14
+ import os
15
+ import statistics
16
+ import tempfile
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from cellscreen.constants import DATASET_REGISTRY
21
+ from cellscreen.schemas import RunManifest, ScreenResultRecord
22
+ from cellscreen.store import RunStore
23
+
24
+
25
+ def _build_report_payload(
26
+ manifest: RunManifest,
27
+ records: list[ScreenResultRecord],
28
+ *,
29
+ max_heatmap_genes: int = 24,
30
+ ) -> dict[str, Any]:
31
+ """Assemble compact, JSON-serializable data payload embedded in report.html."""
32
+ ok_records = [r for r in records if r.status == "ok"]
33
+ err_records = [r for r in records if r.status != "ok"]
34
+ ok_records.sort(key=lambda r: r.max_abs_lfc, reverse=True)
35
+
36
+ # Collect top genes across all completed perturbations for the comparison heatmap
37
+ gene_scores: dict[str, float] = {}
38
+ per_item_lfc: dict[str, dict[str, dict[str, Any]]] = {}
39
+
40
+ for rec in ok_records:
41
+ gmap: dict[str, dict[str, Any]] = {}
42
+ for eff in (*rec.top_up, *rec.top_down):
43
+ prev = gmap.get(eff.gene)
44
+ if prev is None or abs(eff.lfc) > abs(prev["lfc"]):
45
+ gmap[eff.gene] = {
46
+ "gene": eff.gene,
47
+ "direction": eff.direction,
48
+ "rank": eff.rank,
49
+ "control": round(eff.control_expr, 4),
50
+ "baseline": round(eff.baseline_expr, 4),
51
+ "predicted": round(eff.predicted_expr, 4),
52
+ "lfc": round(eff.lfc, 4),
53
+ "delta": round(eff.residual_delta, 4),
54
+ }
55
+ gene_scores[eff.gene] = max(gene_scores.get(eff.gene, 0.0), abs(eff.lfc))
56
+ per_item_lfc[rec.item_id] = gmap
57
+
58
+ heatmap_genes = [
59
+ g for g, _ in sorted(gene_scores.items(), key=lambda kv: kv[1], reverse=True)[:max_heatmap_genes]
60
+ ]
61
+
62
+ heatmap_matrix: list[dict[str, Any]] = []
63
+ max_hm_abs = 0.25
64
+ for rec in ok_records[:28]:
65
+ gmap = per_item_lfc.get(rec.item_id, {})
66
+ row_cells = []
67
+ for g in heatmap_genes:
68
+ entry = gmap.get(g)
69
+ val = float(entry["lfc"]) if entry else 0.0
70
+ max_hm_abs = max(max_hm_abs, abs(val))
71
+ row_cells.append(
72
+ {
73
+ "gene": g,
74
+ "lfc": round(val, 4),
75
+ "present": entry is not None,
76
+ "direction": entry["direction"] if entry else "none",
77
+ "rank": entry["rank"] if entry else None,
78
+ "control": entry["control"] if entry else None,
79
+ "predicted": entry["predicted"] if entry else None,
80
+ }
81
+ )
82
+ heatmap_matrix.append(
83
+ {
84
+ "item_id": rec.item_id,
85
+ "label": rec.label,
86
+ "modality": rec.modality,
87
+ "cells": row_cells,
88
+ }
89
+ )
90
+
91
+ items_payload: list[dict[str, Any]] = []
92
+ for rec in ok_records:
93
+ all_effects = list(per_item_lfc.get(rec.item_id, {}).values())
94
+ n_total = max(1, len(all_effects))
95
+ volcano_points = []
96
+ for eff in all_effects:
97
+ # Rank-derived salience score: higher ranks (closer to 0) appear higher on Y-axis
98
+ salience = -math.log10((eff["rank"] + 1.0) / (n_total + 2.0))
99
+ volcano_points.append(
100
+ {
101
+ **eff,
102
+ "salience": round(salience, 4),
103
+ }
104
+ )
105
+ items_payload.append(
106
+ {
107
+ "item_id": rec.item_id,
108
+ "label": rec.label,
109
+ "modality": rec.modality,
110
+ "cell_idx": rec.cell_idx,
111
+ "n_up": rec.n_up,
112
+ "n_down": rec.n_down,
113
+ "max_abs_lfc": round(rec.max_abs_lfc, 4),
114
+ "mean_abs_lfc": round(rec.mean_abs_lfc, 4),
115
+ "l2_lfc": round(rec.l2_lfc, 4),
116
+ "latency_ms": round(rec.latency_ms, 1),
117
+ "prompt_tokens": rec.prompt_tokens,
118
+ "completion_tokens": rec.completion_tokens,
119
+ "perturbation_text": rec.perturbation_text,
120
+ "top_up": [e.model_dump() for e in rec.top_up[:12]],
121
+ "top_down": [e.model_dump() for e in rec.top_down[:12]],
122
+ "volcano": volcano_points,
123
+ "metadata": rec.metadata,
124
+ }
125
+ )
126
+
127
+ latencies = [r.latency_ms for r in ok_records if r.latency_ms > 0]
128
+ deg_counts = [r.n_up + r.n_down for r in ok_records]
129
+ ds_info = DATASET_REGISTRY.get(manifest.dataset, {})
130
+
131
+ return {
132
+ "run_id": manifest.run_id,
133
+ "title": manifest.title,
134
+ "notes": manifest.notes,
135
+ "dataset": manifest.dataset,
136
+ "dataset_label": ds_info.get("label", manifest.dataset),
137
+ "dataset_description": ds_info.get("description", ""),
138
+ "model_id": manifest.model_id,
139
+ "cell_idx": manifest.cell_idx,
140
+ "created_at": manifest.created_at,
141
+ "stats": {
142
+ "total": len(manifest.perturbations),
143
+ "completed": len(ok_records),
144
+ "failed": len(err_records),
145
+ "pending": max(0, len(manifest.perturbations) - len(ok_records) - len(err_records)),
146
+ "median_degs": int(statistics.median(deg_counts)) if deg_counts else 0,
147
+ "max_abs_lfc": round(max((r.max_abs_lfc for r in ok_records), default=0.0), 3),
148
+ "mean_latency_ms": round(statistics.mean(latencies), 1) if latencies else 0.0,
149
+ },
150
+ "heatmap": {
151
+ "genes": heatmap_genes,
152
+ "rows": heatmap_matrix,
153
+ "max_abs": round(max_hm_abs, 4),
154
+ },
155
+ "items": items_payload,
156
+ "errors": [
157
+ {
158
+ "item_id": r.item_id,
159
+ "label": r.label,
160
+ "modality": r.modality,
161
+ "error": r.error or "Unknown error",
162
+ }
163
+ for r in err_records
164
+ ],
165
+ }
166
+
167
+
168
+ def _safe_json_for_script(obj: Any) -> str:
169
+ """Serialize JSON safely for embedding inside an HTML <script> tag."""
170
+ return json.dumps(obj, ensure_ascii=False).replace("</", "<\\/")
171
+
172
+
173
+ def _render_table_rows_html(items: list[dict[str, Any]]) -> str:
174
+ """Render semantic server-side HTML table rows so the report is readable even without JS."""
175
+ if not items:
176
+ return (
177
+ '<tr><td colspan="8" class="empty-cell">'
178
+ "No completed perturbations yet. Run <code>cellscreen run &lt;run_dir&gt;</code> to populate results."
179
+ "</td></tr>"
180
+ )
181
+ parts: list[str] = []
182
+ for idx, item in enumerate(items):
183
+ top_u = ", ".join(g["gene"] for g in item["top_up"][:3]) or "—"
184
+ top_d = ", ".join(g["gene"] for g in item["top_down"][:3]) or "—"
185
+ selected_cls = " is-selected" if idx == 0 else ""
186
+ parts.append(
187
+ f'<tr class="cand-row{selected_cls}" data-item-id="{html.escape(item["item_id"])}" '
188
+ f'data-modality="{html.escape(item["modality"])}" '
189
+ f'data-search="{html.escape((item["label"] + " " + top_u + " " + top_d + " " + item["modality"]).lower())}">'
190
+ f'<th scope="row">'
191
+ f'<button type="button" class="row-select-btn" data-select-id="{html.escape(item["item_id"])}">'
192
+ f'{html.escape(item["label"])}</button></th>'
193
+ f'<td><span class="badge badge-{html.escape(item["modality"])}">{html.escape(item["modality"].replace("_", " "))}</span></td>'
194
+ f'<td class="num up-text" data-value="{item["n_up"]}">+{item["n_up"]}</td>'
195
+ f'<td class="num down-text" data-value="{item["n_down"]}">−{item["n_down"]}</td>'
196
+ f'<td class="num strong-num" data-value="{item["max_abs_lfc"]}">{item["max_abs_lfc"]:.3f}</td>'
197
+ f'<td class="num" data-value="{item["l2_lfc"]}">{item["l2_lfc"]:.3f}</td>'
198
+ f'<td class="num muted-text" data-value="{item["latency_ms"]}">{item["latency_ms"] / 1000:.0f}</td>'
199
+ f'<td class="gene-preview"><span class="up-text">↑ {html.escape(top_u)}</span> '
200
+ f'<span class="sep">·</span> <span class="down-text">↓ {html.escape(top_d)}</span></td>'
201
+ f"</tr>"
202
+ )
203
+ return "\n".join(parts)
204
+
205
+
206
+ def render_report_html(manifest: RunManifest, records: list[ScreenResultRecord]) -> str:
207
+ """Render the complete standalone interactive HTML report string."""
208
+ payload = _build_report_payload(manifest, records)
209
+ stats = payload["stats"]
210
+ rows_html = _render_table_rows_html(payload["items"])
211
+ data_json = _safe_json_for_script(payload)
212
+
213
+ title_esc = html.escape(manifest.title)
214
+ run_id_esc = html.escape(manifest.run_id)
215
+ dataset_label_esc = html.escape(payload["dataset_label"])
216
+ dataset_esc = html.escape(manifest.dataset)
217
+ model_esc = html.escape(manifest.model_id)
218
+ notes_esc = html.escape(manifest.notes)
219
+
220
+ modalities = sorted({i["modality"] for i in payload["items"]})
221
+ mod_options = "\n".join(
222
+ f'<option value="{html.escape(m)}">{html.escape(m.replace("_", " ").title())}</option>'
223
+ for m in modalities
224
+ )
225
+ item_options = "\n".join(
226
+ f'<option value="{html.escape(i["item_id"])}">{html.escape(i["label"])}</option>'
227
+ for i in payload["items"]
228
+ )
229
+
230
+ error_section = ""
231
+ if payload["errors"]:
232
+ err_items = "\n".join(
233
+ f'<li><strong>{html.escape(e["label"])}</strong> '
234
+ f'<code>({html.escape(e["item_id"])})</code>: {html.escape(e["error"])}</li>'
235
+ for e in payload["errors"]
236
+ )
237
+ error_section = f"""
238
+ <section class="panel error-panel" aria-labelledby="errors-heading">
239
+ <div class="panel-head">
240
+ <h2 id="errors-heading">Failed Perturbations ({len(payload["errors"])})</h2>
241
+ <span class="mono-note">Re-run with <code>cellscreen run &lt;run_dir&gt; --retry-errors</code></span>
242
+ </div>
243
+ <ul class="error-list">{err_items}</ul>
244
+ </section>
245
+ """
246
+
247
+ return f"""<!DOCTYPE html>
248
+ <html lang="en">
249
+ <head>
250
+ <meta charset="utf-8">
251
+ <meta name="viewport" content="width=device-width, initial-scale=1">
252
+ <meta name="color-scheme" content="light dark">
253
+ <script>
254
+ try {{
255
+ var savedScheme = localStorage.getItem("cellscreen-color-scheme");
256
+ document.querySelector('meta[name="color-scheme"]').content = savedScheme ?? "light dark";
257
+ }} catch (e) {{}}
258
+ </script>
259
+ <title>{title_esc} · CellScreen Report</title>
260
+ <style>
261
+ :root {{
262
+ /* Scientific-Editorial Light & Dark Palette Tokens */
263
+ --bg-light: #fafaf7;
264
+ --bg-dark: #111317;
265
+ --surface-light: #ffffff;
266
+ --surface-dark: #181b21;
267
+ --surface-alt-light: #f2f2ec;
268
+ --surface-alt-dark: #1f232b;
269
+ --ink-light: #16181d;
270
+ --ink-dark: #edeff3;
271
+ --ink-muted-light: #5a606c;
272
+ --ink-muted-dark: #9ba3b2;
273
+ --rule-light: #e2e2da;
274
+ --rule-dark: #2c313c;
275
+ --accent-light: #0f6b6e;
276
+ --accent-dark: #4ec4c8;
277
+ --up-light: #c4432b;
278
+ --up-dark: #f07b67;
279
+ --down-light: #255ba8;
280
+ --down-dark: #6ba5f2;
281
+ --warn-light: #9a5b13;
282
+ --warn-dark: #ebb35c;
283
+
284
+ /* Fallback defaults (light) for browsers without light-dark() */
285
+ --bg: var(--bg-light);
286
+ --surface: var(--surface-light);
287
+ --surface-alt: var(--surface-alt-light);
288
+ --ink: var(--ink-light);
289
+ --ink-muted: var(--ink-muted-light);
290
+ --rule: var(--rule-light);
291
+ --accent: var(--accent-light);
292
+ --up: var(--up-light);
293
+ --down: var(--down-light);
294
+ --warn: var(--warn-light);
295
+
296
+ @media (prefers-color-scheme: dark) {{
297
+ --bg: var(--bg-dark);
298
+ --surface: var(--surface-dark);
299
+ --surface-alt: var(--surface-alt-dark);
300
+ --ink: var(--ink-dark);
301
+ --ink-muted: var(--ink-muted-dark);
302
+ --rule: var(--rule-dark);
303
+ --accent: var(--accent-dark);
304
+ --up: var(--up-dark);
305
+ --down: var(--down-dark);
306
+ --warn: var(--warn-dark);
307
+ }}
308
+
309
+ @supports (color: light-dark(white, black)) {{
310
+ --bg: light-dark(var(--bg-light), var(--bg-dark));
311
+ --surface: light-dark(var(--surface-light), var(--surface-dark));
312
+ --surface-alt: light-dark(var(--surface-alt-light), var(--surface-alt-dark));
313
+ --ink: light-dark(var(--ink-light), var(--ink-dark));
314
+ --ink-muted: light-dark(var(--ink-muted-light), var(--ink-muted-dark));
315
+ --rule: light-dark(var(--rule-light), var(--rule-dark));
316
+ --accent: light-dark(var(--accent-light), var(--accent-dark));
317
+ --up: light-dark(var(--up-light), var(--up-dark));
318
+ --down: light-dark(var(--down-light), var(--down-dark));
319
+ --warn: light-dark(var(--warn-light), var(--warn-dark));
320
+ }}
321
+
322
+ color-scheme: light dark;
323
+ accent-color: var(--accent);
324
+
325
+ --font-sans: -apple-system, BlinkMacSystemFont, "Inter", "Helvetica Neue", Helvetica, Arial, sans-serif;
326
+ --font-serif: "Iowan Old Style", "Palatino Linotype", Georgia, serif;
327
+ --font-mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
328
+ --radius: 10px;
329
+ }}
330
+
331
+ :root:has(> head > meta[name="color-scheme"][content="dark"]) {{
332
+ color-scheme: dark;
333
+ }}
334
+ :root:has(> head > meta[name="color-scheme"][content="light"]) {{
335
+ color-scheme: light;
336
+ }}
337
+
338
+ * {{ box-sizing: border-box; }}
339
+
340
+ body {{
341
+ margin: 0;
342
+ background: var(--bg);
343
+ color: var(--ink);
344
+ font-family: var(--font-sans);
345
+ font-size: 14.5px;
346
+ line-height: 1.55;
347
+ -webkit-font-smoothing: antialiased;
348
+ }}
349
+
350
+ .sr-only {{
351
+ position: absolute;
352
+ width: 1px;
353
+ height: 1px;
354
+ clip-path: inset(50%);
355
+ overflow: hidden;
356
+ white-space: nowrap;
357
+ }}
358
+
359
+ .shell {{
360
+ max-width: 1320px;
361
+ margin: 0 auto;
362
+ padding: 28px 24px 64px;
363
+ }}
364
+
365
+ /* Editorial Masthead */
366
+ .masthead {{
367
+ display: flex;
368
+ flex-wrap: wrap;
369
+ justify-content: space-between;
370
+ align-items: flex-start;
371
+ gap: 16px;
372
+ padding-bottom: 20px;
373
+ border-bottom: 1.5px solid var(--ink);
374
+ margin-bottom: 22px;
375
+ }}
376
+
377
+ .kicker {{
378
+ font-family: var(--font-mono);
379
+ font-size: 11px;
380
+ letter-spacing: 0.1em;
381
+ text-transform: uppercase;
382
+ color: var(--accent);
383
+ font-weight: 600;
384
+ margin-bottom: 6px;
385
+ }}
386
+
387
+ .masthead h1 {{
388
+ margin: 0 0 6px;
389
+ font-family: var(--font-serif);
390
+ font-size: clamp(1.6rem, 2.6vw, 2.2rem);
391
+ font-weight: 600;
392
+ letter-spacing: -0.02em;
393
+ line-height: 1.18;
394
+ }}
395
+
396
+ .subtitle {{
397
+ margin: 0;
398
+ color: var(--ink-muted);
399
+ max-width: 72ch;
400
+ }}
401
+
402
+ .meta-strip {{
403
+ display: flex;
404
+ flex-wrap: wrap;
405
+ gap: 10px 18px;
406
+ margin-top: 10px;
407
+ font-family: var(--font-mono);
408
+ font-size: 12px;
409
+ color: var(--ink-muted);
410
+ }}
411
+ .meta-strip strong {{ color: var(--ink); font-weight: 600; }}
412
+
413
+ .toolbar {{
414
+ display: flex;
415
+ align-items: center;
416
+ gap: 8px;
417
+ flex-wrap: wrap;
418
+ }}
419
+
420
+ .btn {{
421
+ appearance: none;
422
+ border: 1px solid var(--rule);
423
+ background: var(--surface);
424
+ color: var(--ink);
425
+ padding: 7px 12px;
426
+ border-radius: 7px;
427
+ font-family: var(--font-sans);
428
+ font-size: 12.5px;
429
+ font-weight: 500;
430
+ cursor: pointer;
431
+ display: inline-flex;
432
+ align-items: center;
433
+ gap: 6px;
434
+ min-height: 34px;
435
+ transition: border-color 0.15s ease, background-color 0.15s ease;
436
+ }}
437
+ .btn:hover {{ border-color: var(--accent); }}
438
+ .btn:focus-visible {{ outline: 2px solid var(--accent); outline-offset: 2px; }}
439
+
440
+ /* Two-state theme toggle icons driven by CSS scheme state */
441
+ .theme-opt-dark {{ display: inline-flex; align-items: center; gap: 6px; }}
442
+ .theme-opt-light {{ display: none; align-items: center; gap: 6px; }}
443
+
444
+ @media (prefers-color-scheme: dark) {{
445
+ :root:not(:has(> head > meta[name="color-scheme"][content="light"])) .theme-opt-dark {{ display: none; }}
446
+ :root:not(:has(> head > meta[name="color-scheme"][content="light"])) .theme-opt-light {{ display: inline-flex; }}
447
+ }}
448
+ :root:has(> head > meta[name="color-scheme"][content="dark"]) .theme-opt-dark {{ display: none; }}
449
+ :root:has(> head > meta[name="color-scheme"][content="dark"]) .theme-opt-light {{ display: inline-flex; }}
450
+ :root:has(> head > meta[name="color-scheme"][content="light"]) .theme-opt-dark {{ display: inline-flex; }}
451
+ :root:has(> head > meta[name="color-scheme"][content="light"]) .theme-opt-light {{ display: none; }}
452
+
453
+ /* KPI Strip */
454
+ .kpi-grid {{
455
+ display: grid;
456
+ grid-template-columns: repeat(auto-fit, minmax(185px, 1fr));
457
+ gap: 12px;
458
+ margin-bottom: 22px;
459
+ }}
460
+
461
+ .kpi {{
462
+ background: var(--surface);
463
+ border: 1px solid var(--rule);
464
+ border-radius: var(--radius);
465
+ padding: 14px 16px;
466
+ }}
467
+
468
+ .kpi-label {{
469
+ font-family: var(--font-mono);
470
+ font-size: 11px;
471
+ text-transform: uppercase;
472
+ letter-spacing: 0.06em;
473
+ color: var(--ink-muted);
474
+ margin-bottom: 6px;
475
+ }}
476
+
477
+ .kpi-value {{
478
+ font-family: var(--font-mono);
479
+ font-size: 1.45rem;
480
+ font-weight: 600;
481
+ font-variant-numeric: tabular-nums;
482
+ line-height: 1.2;
483
+ }}
484
+ .kpi-sub {{
485
+ font-size: 12px;
486
+ color: var(--ink-muted);
487
+ margin-top: 4px;
488
+ }}
489
+
490
+ /* Panels */
491
+ .viz-grid {{
492
+ display: grid;
493
+ grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.9fr);
494
+ gap: 18px;
495
+ margin-bottom: 22px;
496
+ }}
497
+
498
+ @media (max-width: 980px) {{
499
+ .viz-grid {{ grid-template-columns: 1fr; }}
500
+ }}
501
+
502
+ .panel {{
503
+ background: var(--surface);
504
+ border: 1px solid var(--rule);
505
+ border-radius: var(--radius);
506
+ padding: 18px 20px;
507
+ margin-bottom: 20px;
508
+ }}
509
+ .viz-grid .panel {{ margin-bottom: 0; }}
510
+
511
+ .panel-head {{
512
+ display: flex;
513
+ flex-wrap: wrap;
514
+ align-items: center;
515
+ justify-content: space-between;
516
+ gap: 10px;
517
+ margin-bottom: 14px;
518
+ padding-bottom: 10px;
519
+ border-bottom: 1px solid var(--rule);
520
+ }}
521
+
522
+ .panel-head h2 {{
523
+ margin: 0;
524
+ font-size: 15px;
525
+ font-weight: 600;
526
+ letter-spacing: -0.01em;
527
+ }}
528
+
529
+ .mono-note {{
530
+ font-family: var(--font-mono);
531
+ font-size: 11.5px;
532
+ color: var(--ink-muted);
533
+ }}
534
+
535
+ .controls-row {{
536
+ display: flex;
537
+ flex-wrap: wrap;
538
+ gap: 8px;
539
+ align-items: center;
540
+ }}
541
+
542
+ input[type="search"], select {{
543
+ background: var(--surface-alt);
544
+ color: var(--ink);
545
+ border: 1px solid var(--rule);
546
+ border-radius: 6px;
547
+ padding: 6px 10px;
548
+ font-family: var(--font-sans);
549
+ font-size: 13px;
550
+ min-height: 32px;
551
+ }}
552
+
553
+ .chart-box {{
554
+ position: relative;
555
+ width: 100%;
556
+ overflow-x: auto;
557
+ }}
558
+
559
+ svg.chart-svg {{
560
+ display: block;
561
+ width: 100%;
562
+ height: auto;
563
+ font-family: var(--font-mono);
564
+ }}
565
+
566
+ .legend-bar {{
567
+ display: flex;
568
+ align-items: center;
569
+ gap: 14px;
570
+ font-family: var(--font-mono);
571
+ font-size: 11.5px;
572
+ color: var(--ink-muted);
573
+ margin-top: 8px;
574
+ flex-wrap: wrap;
575
+ }}
576
+ .swatch {{
577
+ display: inline-block;
578
+ width: 10px;
579
+ height: 10px;
580
+ border-radius: 2px;
581
+ margin-right: 4px;
582
+ vertical-align: -1px;
583
+ }}
584
+
585
+ /* Inspector */
586
+ .inspector-grid {{
587
+ display: grid;
588
+ grid-template-columns: repeat(2, minmax(0, 1fr));
589
+ gap: 16px;
590
+ margin-top: 12px;
591
+ }}
592
+ @media (max-width: 720px) {{
593
+ .inspector-grid {{ grid-template-columns: 1fr; }}
594
+ }}
595
+
596
+ .pert-pre {{
597
+ margin: 0 0 12px;
598
+ padding: 10px 12px;
599
+ background: var(--surface-alt);
600
+ border: 1px solid var(--rule);
601
+ border-radius: 6px;
602
+ font-family: var(--font-mono);
603
+ font-size: 12px;
604
+ white-space: pre-wrap;
605
+ word-break: break-word;
606
+ max-height: 110px;
607
+ overflow: auto;
608
+ }}
609
+
610
+ .gene-list {{
611
+ list-style: none;
612
+ margin: 0;
613
+ padding: 0;
614
+ display: grid;
615
+ gap: 6px;
616
+ }}
617
+ .gene-row {{
618
+ display: grid;
619
+ grid-template-columns: 82px 1fr 68px;
620
+ align-items: center;
621
+ gap: 8px;
622
+ font-family: var(--font-mono);
623
+ font-size: 12px;
624
+ }}
625
+ .gene-bar-track {{
626
+ height: 8px;
627
+ background: var(--surface-alt);
628
+ border-radius: 4px;
629
+ overflow: hidden;
630
+ }}
631
+ .gene-bar-fill {{
632
+ height: 100%;
633
+ border-radius: 4px;
634
+ }}
635
+ .gene-bar-fill.up {{ background: var(--up); }}
636
+ .gene-bar-fill.down {{ background: var(--down); }}
637
+
638
+ /* Responsive Sortable Data Table (Modern Web Guidance) */
639
+ .table-wrapper {{
640
+ overflow: auto;
641
+ max-inline-size: 100%;
642
+ max-block-size: min(560px, 75vh);
643
+ container-type: inline-size;
644
+ border: 1px solid var(--rule);
645
+ border-radius: 8px;
646
+ }}
647
+ .table-wrapper:focus-visible {{
648
+ outline: 2px solid var(--accent);
649
+ outline-offset: 2px;
650
+ }}
651
+
652
+ table.screen-table {{
653
+ width: 100%;
654
+ min-inline-size: 760px;
655
+ border-collapse: separate;
656
+ border-spacing: 0;
657
+ font-size: 13.5px;
658
+ }}
659
+
660
+ table.screen-table caption {{
661
+ text-align: left;
662
+ padding: 10px 14px;
663
+ font-family: var(--font-mono);
664
+ font-size: 11.5px;
665
+ color: var(--ink-muted);
666
+ border-bottom: 1px solid var(--rule);
667
+ background: var(--surface-alt);
668
+ }}
669
+
670
+ table.screen-table thead {{
671
+ position: sticky;
672
+ inset-block-start: 0;
673
+ z-index: 2;
674
+ background: var(--surface-alt);
675
+ }}
676
+
677
+ table.screen-table th,
678
+ table.screen-table td {{
679
+ padding: 9px 12px;
680
+ border-bottom: 1px solid var(--rule);
681
+ text-align: left;
682
+ vertical-align: middle;
683
+ }}
684
+
685
+ table.screen-table thead th {{
686
+ font-family: var(--font-mono);
687
+ font-size: 11.5px;
688
+ text-transform: uppercase;
689
+ letter-spacing: 0.04em;
690
+ color: var(--ink-muted);
691
+ font-weight: 600;
692
+ white-space: nowrap;
693
+ }}
694
+
695
+ table.screen-table thead th:has(> button) {{
696
+ padding: 0;
697
+ }}
698
+
699
+ table.screen-table thead th > button {{
700
+ appearance: none;
701
+ background: transparent;
702
+ border: 0;
703
+ color: inherit;
704
+ font: inherit;
705
+ text-transform: inherit;
706
+ letter-spacing: inherit;
707
+ width: 100%;
708
+ min-height: 36px;
709
+ padding: 9px 12px;
710
+ text-align: left;
711
+ cursor: pointer;
712
+ display: inline-flex;
713
+ align-items: center;
714
+ justify-content: space-between;
715
+ gap: 6px;
716
+ }}
717
+ table.screen-table thead th > button:focus-visible {{
718
+ outline: 2px solid var(--accent);
719
+ outline-offset: -2px;
720
+ }}
721
+
722
+ .sort-icon::after {{
723
+ content: "⇅";
724
+ opacity: 0.38;
725
+ font-size: 11px;
726
+ }}
727
+ th[aria-sort="ascending"] .sort-icon::after {{
728
+ content: "▲";
729
+ opacity: 1;
730
+ color: var(--accent);
731
+ }}
732
+ th[aria-sort="descending"] .sort-icon::after {{
733
+ content: "▼";
734
+ opacity: 1;
735
+ color: var(--accent);
736
+ }}
737
+
738
+ table.screen-table tbody th {{
739
+ position: sticky;
740
+ inset-inline-start: 0;
741
+ background: var(--surface);
742
+ font-weight: 600;
743
+ z-index: 1;
744
+ }}
745
+
746
+ table.screen-table tbody tr {{
747
+ view-transition-name: match-element;
748
+ }}
749
+
750
+ table.screen-table tbody tr:hover td,
751
+ table.screen-table tbody tr:hover th {{
752
+ background: var(--surface-alt);
753
+ }}
754
+
755
+ table.screen-table tbody tr.is-selected th,
756
+ table.screen-table tbody tr.is-selected td {{
757
+ background: color-mix(in srgb, var(--accent) 10%, var(--surface));
758
+ }}
759
+
760
+ .row-select-btn {{
761
+ appearance: none;
762
+ background: transparent;
763
+ border: 0;
764
+ color: var(--ink);
765
+ font: inherit;
766
+ font-weight: 600;
767
+ cursor: pointer;
768
+ padding: 2px 0;
769
+ text-align: left;
770
+ }}
771
+ .row-select-btn:hover {{ color: var(--accent); text-decoration: underline; }}
772
+
773
+ .num {{
774
+ font-family: var(--font-mono);
775
+ font-variant-numeric: tabular-nums;
776
+ text-align: right;
777
+ }}
778
+ .strong-num {{ font-weight: 600; }}
779
+ .up-text {{ color: var(--up); }}
780
+ .down-text {{ color: var(--down); }}
781
+ .muted-text {{ color: var(--ink-muted); }}
782
+ .sep {{ color: var(--rule); margin: 0 4px; }}
783
+ .gene-preview {{ font-family: var(--font-mono); font-size: 12px; white-space: nowrap; }}
784
+ .empty-cell {{ padding: 24px; text-align: center; color: var(--ink-muted); }}
785
+
786
+ .badge {{
787
+ display: inline-block;
788
+ padding: 2px 7px;
789
+ border-radius: 999px;
790
+ font-family: var(--font-mono);
791
+ font-size: 11px;
792
+ border: 1px solid var(--rule);
793
+ background: var(--surface-alt);
794
+ white-space: nowrap;
795
+ }}
796
+
797
+ .tooltip {{
798
+ position: fixed;
799
+ pointer-events: none;
800
+ z-index: 40;
801
+ background: var(--surface);
802
+ color: var(--ink);
803
+ border: 1px solid var(--ink);
804
+ border-radius: 6px;
805
+ padding: 7px 10px;
806
+ font-family: var(--font-mono);
807
+ font-size: 11.5px;
808
+ line-height: 1.4;
809
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.14);
810
+ opacity: 0;
811
+ transition: opacity 0.1s ease;
812
+ max-width: 260px;
813
+ }}
814
+ .tooltip.visible {{ opacity: 1; }}
815
+
816
+ .error-panel {{ border-color: var(--up); }}
817
+ .error-list {{ margin: 0; padding-left: 18px; font-family: var(--font-mono); font-size: 12px; }}
818
+
819
+ .footer {{
820
+ margin-top: 28px;
821
+ padding-top: 14px;
822
+ border-top: 1px solid var(--rule);
823
+ font-family: var(--font-mono);
824
+ font-size: 11.5px;
825
+ color: var(--ink-muted);
826
+ display: flex;
827
+ flex-wrap: wrap;
828
+ justify-content: space-between;
829
+ gap: 8px;
830
+ }}
831
+
832
+ @media (prefers-reduced-motion: reduce) {{
833
+ ::view-transition-group(*),
834
+ ::view-transition-old(*),
835
+ ::view-transition-new(*) {{
836
+ animation: none;
837
+ }}
838
+ }}
839
+ </style>
840
+ </head>
841
+ <body>
842
+ <div class="shell">
843
+ <header class="masthead">
844
+ <div>
845
+ <div class="kicker">CellScreen · CellGemma E4B</div>
846
+ <h1>{title_esc}</h1>
847
+ {f'<p class="subtitle">{notes_esc}</p>' if notes_esc else ''}
848
+ <div class="meta-strip">
849
+ <span>Run: <strong>{run_id_esc}</strong></span>
850
+ <span>Decoder: <strong>{dataset_label_esc}</strong> (<code>{dataset_esc}</code>)</span>
851
+ <span>Control Cell: <strong>#{manifest.cell_idx}</strong></span>
852
+ <span>Model: <strong>{model_esc}</strong></span>
853
+ </div>
854
+ </div>
855
+ <div class="toolbar">
856
+ <button type="button" class="btn" id="export-csv-btn">Export CSV</button>
857
+ <button type="button" class="btn" id="export-json-btn">Export JSON</button>
858
+ <button type="button" class="btn" id="theme-toggle-btn" aria-label="Toggle color theme">
859
+ <span class="theme-opt-dark">◐ Dark</span>
860
+ <span class="theme-opt-light">☀ Light</span>
861
+ </button>
862
+ </div>
863
+ </header>
864
+
865
+ <section class="kpi-grid" aria-label="Screen summary metrics">
866
+ <div class="kpi">
867
+ <div class="kpi-label">Perturbations</div>
868
+ <div class="kpi-value">{stats["completed"]} / {stats["total"]}</div>
869
+ <div class="kpi-sub">{stats["pending"]} pending · {stats["failed"]} failed</div>
870
+ </div>
871
+ <div class="kpi">
872
+ <div class="kpi-label">Strongest Max |LFC|</div>
873
+ <div class="kpi-value">{stats["max_abs_lfc"]:.3f}</div>
874
+ <div class="kpi-sub">Stage-2 ExpressionDecoder</div>
875
+ </div>
876
+ <div class="kpi">
877
+ <div class="kpi-label">Median Residual DEGs</div>
878
+ <div class="kpi-value">{stats["median_degs"]}</div>
879
+ <div class="kpi-sub">+GENE / −GENE per condition</div>
880
+ </div>
881
+ <div class="kpi">
882
+ <div class="kpi-label">Mean Latency</div>
883
+ <div class="kpi-value">{stats["mean_latency_ms"] / 1000:.0f} s</div>
884
+ <div class="kpi-sub">Per perturbation, including queueing</div>
885
+ </div>
886
+ </section>
887
+
888
+ <div class="viz-grid">
889
+ <section class="panel" aria-labelledby="volcano-heading">
890
+ <div class="panel-head">
891
+ <h2 id="volcano-heading">Transcriptional Shift Profile (Volcano / Rank Salience)</h2>
892
+ <div class="controls-row">
893
+ <label for="pert-select" class="sr-only">Select perturbation</label>
894
+ <select id="pert-select">{item_options}</select>
895
+ </div>
896
+ </div>
897
+ <div class="chart-box" id="volcano-container"></div>
898
+ <div class="legend-bar">
899
+ <span><span class="swatch" style="background: var(--up);"></span>Upregulated (+GENE)</span>
900
+ <span><span class="swatch" style="background: var(--down);"></span>Downregulated (−GENE)</span>
901
+ <span>Y-axis: rank salience <code>−log10((rank+1)/(N+2))</code></span>
902
+ </div>
903
+ </section>
904
+
905
+ <section class="panel" aria-labelledby="inspector-heading">
906
+ <div class="panel-head">
907
+ <h2 id="inspector-heading">Selected Perturbation Inspector</h2>
908
+ <span class="mono-note" id="inspector-meta"></span>
909
+ </div>
910
+ <pre class="pert-pre" id="inspector-prompt"></pre>
911
+ <div class="inspector-grid">
912
+ <div>
913
+ <div class="kpi-label up-text">Top Upregulated (LFC)</div>
914
+ <ul class="gene-list" id="inspector-up"></ul>
915
+ </div>
916
+ <div>
917
+ <div class="kpi-label down-text">Top Downregulated (LFC)</div>
918
+ <ul class="gene-list" id="inspector-down"></ul>
919
+ </div>
920
+ </div>
921
+ </section>
922
+ </div>
923
+
924
+ <section class="panel" aria-labelledby="heatmap-heading">
925
+ <div class="panel-head">
926
+ <h2 id="heatmap-heading">Cross-Perturbation LFC Comparison Matrix (Top Variable Genes)</h2>
927
+ <span class="mono-note">Click any row to inspect its volcano profile</span>
928
+ </div>
929
+ <div class="chart-box" id="heatmap-container"></div>
930
+ <div class="legend-bar">
931
+ <span><span class="swatch" style="background: var(--down);"></span>Negative LFC (repressed)</span>
932
+ <span><span class="swatch" style="background: var(--surface-alt); border: 1px solid var(--rule);"></span>0 / unchanged</span>
933
+ <span><span class="swatch" style="background: var(--up);"></span>Positive LFC (induced)</span>
934
+ </div>
935
+ </section>
936
+
937
+ <section class="panel" aria-labelledby="table-heading">
938
+ <div class="panel-head">
939
+ <h2 id="table-heading">Candidate Perturbations</h2>
940
+ <div class="controls-row">
941
+ <label for="table-search" class="sr-only">Filter perturbations or genes</label>
942
+ <input type="search" id="table-search" placeholder="Filter label or gene…">
943
+ <label for="modality-filter" class="sr-only">Filter modality</label>
944
+ <select id="modality-filter">
945
+ <option value="">All modalities</option>
946
+ {mod_options}
947
+ </select>
948
+ </div>
949
+ </div>
950
+ <div class="sr-only" role="status" id="sort-status"></div>
951
+ <div tabindex="0" role="region" aria-labelledby="candidates-caption" class="table-wrapper">
952
+ <table class="screen-table" id="candidates-table">
953
+ <caption id="candidates-caption">
954
+ Stateless CellScreen results reconstructed via {dataset_label_esc} ExpressionDecoder. Click headers to sort or any row to inspect.
955
+ </caption>
956
+ <thead>
957
+ <tr>
958
+ <th scope="col" data-type="string">
959
+ <button type="button" commandfor="candidates-table" command="--sort" aria-description="Sortable">
960
+ Perturbation <span class="sort-icon" aria-hidden="true"></span>
961
+ </button>
962
+ </th>
963
+ <th scope="col" data-type="string">
964
+ <button type="button" commandfor="candidates-table" command="--sort" aria-description="Sortable">
965
+ Modality <span class="sort-icon" aria-hidden="true"></span>
966
+ </button>
967
+ </th>
968
+ <th scope="col" data-type="number">
969
+ <button type="button" commandfor="candidates-table" command="--sort" aria-description="Sortable">
970
+ +DEGs <span class="sort-icon" aria-hidden="true"></span>
971
+ </button>
972
+ </th>
973
+ <th scope="col" data-type="number">
974
+ <button type="button" commandfor="candidates-table" command="--sort" aria-description="Sortable">
975
+ −DEGs <span class="sort-icon" aria-hidden="true"></span>
976
+ </button>
977
+ </th>
978
+ <th scope="col" data-type="number" aria-sort="descending">
979
+ <button type="button" commandfor="candidates-table" command="--sort" aria-description="Sortable">
980
+ Max |LFC| <span class="sort-icon" aria-hidden="true"></span>
981
+ </button>
982
+ </th>
983
+ <th scope="col" data-type="number">
984
+ <button type="button" commandfor="candidates-table" command="--sort" aria-description="Sortable">
985
+ L2 LFC <span class="sort-icon" aria-hidden="true"></span>
986
+ </button>
987
+ </th>
988
+ <th scope="col" data-type="number">
989
+ <button type="button" commandfor="candidates-table" command="--sort" aria-description="Sortable">
990
+ Latency (s) <span class="sort-icon" aria-hidden="true"></span>
991
+ </button>
992
+ </th>
993
+ <th scope="col">Top Residual Genes</th>
994
+ </tr>
995
+ </thead>
996
+ <tbody>
997
+ {rows_html}
998
+ </tbody>
999
+ </table>
1000
+ </div>
1001
+ </section>
1002
+
1003
+ {error_section}
1004
+
1005
+ <footer class="footer">
1006
+ <span>Generated deterministically from stateless run files (<code>manifest.json</code> + <code>results.jsonl</code>).</span>
1007
+ <span>Research use only — validate predictions experimentally.</span>
1008
+ </footer>
1009
+ </div>
1010
+
1011
+ <div class="tooltip" id="chart-tooltip" role="tooltip"></div>
1012
+
1013
+ <script id="cellscreen-data" type="application/json">{data_json}</script>
1014
+ <script>
1015
+ (() => {{
1016
+ const DATA = JSON.parse(document.getElementById("cellscreen-data").textContent);
1017
+ const STORAGE_KEY = "cellscreen-color-scheme";
1018
+ const metaScheme = document.querySelector('meta[name="color-scheme"]');
1019
+ const tooltip = document.getElementById("chart-tooltip");
1020
+
1021
+ // --- 1. Modern Web Guidance Two-State Dark Mode Toggle ---
1022
+ const mqDark = window.matchMedia("(prefers-color-scheme: dark)");
1023
+ function getStoredScheme() {{
1024
+ try {{ return localStorage.getItem(STORAGE_KEY); }} catch {{ return null; }}
1025
+ }}
1026
+ function setStoredScheme(val) {{
1027
+ try {{
1028
+ if (val === null) localStorage.removeItem(STORAGE_KEY);
1029
+ else localStorage.setItem(STORAGE_KEY, val);
1030
+ }} catch {{}}
1031
+ }}
1032
+ function currentRenderedScheme() {{
1033
+ const stored = getStoredScheme();
1034
+ if (stored === "light" || stored === "dark") return stored;
1035
+ return mqDark.matches ? "dark" : "light";
1036
+ }}
1037
+ document.getElementById("theme-toggle-btn").addEventListener("click", () => {{
1038
+ const rendered = currentRenderedScheme();
1039
+ const target = rendered === "dark" ? "light" : "dark";
1040
+ const sys = mqDark.matches ? "dark" : "light";
1041
+ if (target === sys) {{
1042
+ setStoredScheme(null);
1043
+ metaScheme.content = "light dark";
1044
+ }} else {{
1045
+ setStoredScheme(target);
1046
+ metaScheme.content = target;
1047
+ }}
1048
+ renderHeatmap();
1049
+ if (selectedId) renderVolcano(selectedId);
1050
+ }});
1051
+ window.addEventListener("storage", (e) => {{
1052
+ if (e.key === STORAGE_KEY) {{
1053
+ metaScheme.content = e.newValue ?? "light dark";
1054
+ }}
1055
+ }});
1056
+
1057
+ // --- 2. Tooltip helpers ---
1058
+ // Escape run data (user-supplied labels and ids, gene names) before inserting it as HTML.
1059
+ const esc = (value) => String(value).replace(/[&<>"']/g, (ch) => ({{"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}})[ch]);
1060
+
1061
+ function showTip(evt, htmlContent) {{
1062
+ tooltip.innerHTML = htmlContent;
1063
+ tooltip.classList.add("visible");
1064
+ const pad = 14;
1065
+ const x = Math.min(window.innerWidth - 270, evt.clientX + pad);
1066
+ const y = Math.min(window.innerHeight - 110, evt.clientY + pad);
1067
+ tooltip.style.left = Math.max(8, x) + "px";
1068
+ tooltip.style.top = Math.max(8, y) + "px";
1069
+ }}
1070
+ function hideTip() {{ tooltip.classList.remove("visible"); }}
1071
+
1072
+ // --- 3. SVG Volcano / Rank-Salience Plot ---
1073
+ function renderVolcano(itemId) {{
1074
+ const box = document.getElementById("volcano-container");
1075
+ const item = DATA.items.find((i) => i.item_id === itemId);
1076
+ if (!item || !item.volcano.length) {{
1077
+ box.innerHTML = '<p class="mono-note">No reconstructed residual genes for this perturbation.</p>';
1078
+ return;
1079
+ }}
1080
+ const W = 620, H = 320;
1081
+ const M = {{ top: 20, right: 24, bottom: 38, left: 48 }};
1082
+ const pw = W - M.left - M.right;
1083
+ const ph = H - M.top - M.bottom;
1084
+
1085
+ const maxAbsX = Math.max(0.5, ...item.volcano.map((p) => Math.abs(p.lfc))) * 1.12;
1086
+ const maxY = Math.max(1.0, ...item.volcano.map((p) => p.salience)) * 1.12;
1087
+
1088
+ const sx = (v) => M.left + ((v + maxAbsX) / (2 * maxAbsX)) * pw;
1089
+ const sy = (v) => M.top + ph - (v / maxY) * ph;
1090
+
1091
+ const zeroX = sx(0);
1092
+ const ticksX = [-maxAbsX * 0.75, -maxAbsX * 0.375, 0, maxAbsX * 0.375, maxAbsX * 0.75];
1093
+ const gridLines = ticksX.map((t) =>
1094
+ `<line x1="${{sx(t).toFixed(1)}}" y1="${{M.top}}" x2="${{sx(t).toFixed(1)}}" y2="${{M.top + ph}}" stroke="var(--rule)" stroke-dasharray="${{t === 0 ? '' : '3 3'}}" stroke-width="${{t === 0 ? 1.4 : 1}}" />` +
1095
+ `<text x="${{sx(t).toFixed(1)}}" y="${{H - 14}}" text-anchor="middle" fill="var(--ink-muted)" font-size="10">${{t.toFixed(2)}}</text>`
1096
+ ).join("");
1097
+
1098
+ const topLabeled = new Set([
1099
+ ...item.top_up.slice(0, 5).map((g) => g.gene),
1100
+ ...item.top_down.slice(0, 5).map((g) => g.gene),
1101
+ ]);
1102
+
1103
+ const dots = item.volcano.map((p, idx) => {{
1104
+ const cx = sx(p.lfc).toFixed(1);
1105
+ const cy = sy(p.salience).toFixed(1);
1106
+ const fill = p.direction === "up" ? "var(--up)" : "var(--down)";
1107
+ const r = topLabeled.has(p.gene) ? 5 : 3.6;
1108
+ return `<circle class="v-dot" data-idx="${{idx}}" cx="${{cx}}" cy="${{cy}}" r="${{r}}" fill="${{fill}}" fill-opacity="0.82" stroke="var(--surface)" stroke-width="1" style="cursor:pointer" />`;
1109
+ }}).join("");
1110
+
1111
+ const labels = item.volcano.filter((p) => topLabeled.has(p.gene)).map((p) => {{
1112
+ const cx = sx(p.lfc);
1113
+ const cy = sy(p.salience);
1114
+ const dx = p.lfc >= 0 ? 7 : -7;
1115
+ const anchor = p.lfc >= 0 ? "start" : "end";
1116
+ return `<text x="${{(cx + dx).toFixed(1)}}" y="${{(cy + 3).toFixed(1)}}" text-anchor="${{anchor}}" fill="var(--ink)" font-size="10.5" font-weight="600">${{esc(p.gene)}}</text>`;
1117
+ }}).join("");
1118
+
1119
+ box.innerHTML = `
1120
+ <svg class="chart-svg" viewBox="0 0 ${{W}} ${{H}}" role="img" aria-label="Volcano plot for ${{esc(item.label)}}">
1121
+ ${{gridLines}}
1122
+ <line x1="${{M.left}}" y1="${{M.top + ph}}" x2="${{M.left + pw}}" y2="${{M.top + ph}}" stroke="var(--ink-muted)" stroke-width="1" />
1123
+ <line x1="${{M.left}}" y1="${{M.top}}" x2="${{M.left}}" y2="${{M.top + ph}}" stroke="var(--ink-muted)" stroke-width="1" />
1124
+ <text x="${{(M.left + pw / 2).toFixed(1)}}" y="${{H - 2}}" text-anchor="middle" fill="var(--ink-muted)" font-size="10.5">Predicted Log-Fold Change (LFC)</text>
1125
+ <text x="14" y="${{(M.top + ph / 2).toFixed(1)}}" text-anchor="middle" fill="var(--ink-muted)" font-size="10.5" transform="rotate(-90 14 ${{(M.top + ph / 2).toFixed(1)}})">Rank Salience</text>
1126
+ ${{dots}}
1127
+ ${{labels}}
1128
+ </svg>`;
1129
+
1130
+ box.querySelectorAll(".v-dot").forEach((el) => {{
1131
+ el.addEventListener("mousemove", (ev) => {{
1132
+ const p = item.volcano[Number(el.dataset.idx)];
1133
+ showTip(ev, `<strong>${{esc(p.gene)}}</strong> (${{p.direction.toUpperCase()}} #${{p.rank + 1}})<br>LFC: ${{p.lfc >= 0 ? '+' : ''}}${{p.lfc.toFixed(4)}}<br>Expr: ${{p.control.toFixed(3)}} → ${{p.predicted.toFixed(3)}}`);
1134
+ }});
1135
+ el.addEventListener("mouseleave", hideTip);
1136
+ }});
1137
+ }}
1138
+
1139
+ // --- 4. Selected Perturbation Inspector ---
1140
+ function renderInspector(itemId) {{
1141
+ const item = DATA.items.find((i) => i.item_id === itemId);
1142
+ const metaEl = document.getElementById("inspector-meta");
1143
+ const promptEl = document.getElementById("inspector-prompt");
1144
+ const upEl = document.getElementById("inspector-up");
1145
+ const downEl = document.getElementById("inspector-down");
1146
+ if (!item) {{
1147
+ metaEl.textContent = "—";
1148
+ promptEl.textContent = "No completed perturbations available.";
1149
+ upEl.innerHTML = "";
1150
+ downEl.innerHTML = "";
1151
+ return;
1152
+ }}
1153
+ metaEl.textContent = `${{item.modality}} · +${{item.n_up}} / −${{item.n_down}} DEGs · ${{(item.latency_ms / 1000).toFixed(0)}} s`;
1154
+ promptEl.textContent = item.perturbation_text || item.label;
1155
+
1156
+ const maxMag = Math.max(0.1, item.max_abs_lfc);
1157
+ const mkList = (arr, cls) => arr.length ? arr.slice(0, 8).map((g) => {{
1158
+ const pct = Math.min(100, (Math.abs(g.lfc) / maxMag) * 100).toFixed(1);
1159
+ return `<li class="gene-row"><span>${{esc(g.gene)}}</span><span class="gene-bar-track"><span class="gene-bar-fill ${{cls}}" style="width:${{pct}}%"></span></span><span class="num ${{cls}}-text">${{g.lfc >= 0 ? '+' : ''}}${{g.lfc.toFixed(3)}}</span></li>`;
1160
+ }}).join("") : '<li class="mono-note">None</li>';
1161
+
1162
+ upEl.innerHTML = mkList(item.top_up, "up");
1163
+ downEl.innerHTML = mkList(item.top_down, "down");
1164
+ }}
1165
+
1166
+ // --- 5. SVG Cross-Perturbation LFC Heatmap ---
1167
+ function renderHeatmap() {{
1168
+ const box = document.getElementById("heatmap-container");
1169
+ const hm = DATA.heatmap;
1170
+ if (!hm.genes.length || !hm.rows.length) {{
1171
+ box.innerHTML = '<p class="mono-note">Run at least one perturbation to render the LFC comparison matrix.</p>';
1172
+ return;
1173
+ }}
1174
+ const labelW = 190;
1175
+ const cellW = 38;
1176
+ const cellH = 26;
1177
+ const topPad = 68;
1178
+ const W = Math.max(580, labelW + hm.genes.length * cellW + 24);
1179
+ const H = topPad + hm.rows.length * cellH + 16;
1180
+
1181
+ const colHeaders = hm.genes.map((g, ci) => {{
1182
+ const x = labelW + ci * cellW + cellW / 2;
1183
+ return `<text x="${{x}}" y="${{topPad - 8}}" text-anchor="start" fill="var(--ink-muted)" font-size="10.5" transform="rotate(-48 ${{x}} ${{topPad - 8}})">${{esc(g)}}</text>`;
1184
+ }}).join("");
1185
+
1186
+ const rowsSvg = hm.rows.map((row, ri) => {{
1187
+ const y = topPad + ri * cellH;
1188
+ const lbl = row.label.length > 24 ? row.label.slice(0, 23) + "…" : row.label;
1189
+ const cells = row.cells.map((c, ci) => {{
1190
+ const x = labelW + ci * cellW;
1191
+ const intensity = Math.min(1, Math.abs(c.lfc) / Math.max(0.05, hm.max_abs));
1192
+ const fill = !c.present ? "var(--surface-alt)" : (c.lfc >= 0 ? "var(--up)" : "var(--down)");
1193
+ const opacity = !c.present ? 0.55 : (0.14 + 0.86 * intensity).toFixed(2);
1194
+ return `<rect class="hm-cell" data-ri="${{ri}}" data-ci="${{ci}}" x="${{x + 1}}" y="${{y + 1}}" width="${{cellW - 2}}" height="${{cellH - 2}}" rx="3" fill="${{fill}}" fill-opacity="${{opacity}}" style="cursor:pointer" />`;
1195
+ }}).join("");
1196
+ return `<g class="hm-row" data-item-id="${{esc(row.item_id)}}"><text x="${{labelW - 10}}" y="${{y + cellH / 2 + 4}}" text-anchor="end" fill="var(--ink)" font-size="11.5" style="cursor:pointer">${{esc(lbl)}}</text>${{cells}}</g>`;
1197
+ }}).join("");
1198
+
1199
+ box.innerHTML = `<svg class="chart-svg" style="min-width:${{W}}px" viewBox="0 0 ${{W}} ${{H}}" role="img" aria-label="Perturbation by gene LFC heatmap">${{colHeaders}}${{rowsSvg}}</svg>`;
1200
+
1201
+ box.querySelectorAll(".hm-cell").forEach((el) => {{
1202
+ el.addEventListener("mousemove", (ev) => {{
1203
+ const row = hm.rows[Number(el.dataset.ri)];
1204
+ const c = row.cells[Number(el.dataset.ci)];
1205
+ const detail = c.present
1206
+ ? `LFC: ${{c.lfc >= 0 ? '+' : ''}}${{c.lfc.toFixed(4)}} (${{c.direction.toUpperCase()}} #${{c.rank + 1}})`
1207
+ : "Not in top residual DEGs";
1208
+ showTip(ev, `<strong>${{esc(row.label)}}</strong><br>Gene: <strong>${{esc(c.gene)}}</strong><br>${{detail}}`);
1209
+ }});
1210
+ el.addEventListener("mouseleave", hideTip);
1211
+ el.addEventListener("click", () => {{
1212
+ const row = hm.rows[Number(el.dataset.ri)];
1213
+ selectPerturbation(row.item_id);
1214
+ }});
1215
+ }});
1216
+ box.querySelectorAll(".hm-row text").forEach((el) => {{
1217
+ el.addEventListener("click", () => selectPerturbation(el.parentElement.dataset.itemId));
1218
+ }});
1219
+ }}
1220
+
1221
+ // --- 6. Selection Coordination ---
1222
+ const pertSelect = document.getElementById("pert-select");
1223
+ let selectedId = DATA.items.length ? DATA.items[0].item_id : null;
1224
+
1225
+ function selectPerturbation(itemId) {{
1226
+ selectedId = itemId;
1227
+ if (pertSelect) pertSelect.value = itemId;
1228
+ document.querySelectorAll("tr.cand-row").forEach((tr) => {{
1229
+ tr.classList.toggle("is-selected", tr.dataset.itemId === itemId);
1230
+ }});
1231
+ renderVolcano(itemId);
1232
+ renderInspector(itemId);
1233
+ }}
1234
+
1235
+ if (pertSelect) {{
1236
+ pertSelect.addEventListener("change", () => selectPerturbation(pertSelect.value));
1237
+ }}
1238
+ document.querySelectorAll(".row-select-btn").forEach((btn) => {{
1239
+ btn.addEventListener("click", () => selectPerturbation(btn.dataset.selectId));
1240
+ }});
1241
+
1242
+ // --- 7. Modern Web Guidance Sortable Table (invoker commands + fallback) ---
1243
+ const table = document.getElementById("candidates-table");
1244
+ const tbody = table.tBodies[0];
1245
+ const sortStatus = document.getElementById("sort-status");
1246
+ const collator = new Intl.Collator(undefined, {{ numeric: true, sensitivity: "base" }});
1247
+
1248
+ function reorderRows(ordered) {{
1249
+ const move = (row) => {{
1250
+ if (typeof tbody.moveBefore === "function") tbody.moveBefore(row, null);
1251
+ else tbody.appendChild(row);
1252
+ }};
1253
+ if (typeof table.startViewTransition === "function") {{
1254
+ table.startViewTransition(() => ordered.forEach(move));
1255
+ }} else {{
1256
+ ordered.forEach(move);
1257
+ }}
1258
+ }}
1259
+
1260
+ function sortBy(button) {{
1261
+ const th = button.closest("th");
1262
+ const direction = th.getAttribute("aria-sort") === "ascending" ? "descending" : "ascending";
1263
+ for (const header of table.tHead.rows[0].cells) header.removeAttribute("aria-sort");
1264
+ th.setAttribute("aria-sort", direction);
1265
+
1266
+ const idx = th.cellIndex;
1267
+ const type = th.dataset.type || "string";
1268
+ const factor = direction === "ascending" ? 1 : -1;
1269
+ const rows = [...tbody.querySelectorAll("tr.cand-row")];
1270
+ const keyed = rows.map((row) => {{
1271
+ const cell = row.cells[idx];
1272
+ const raw = cell.dataset.value ?? cell.textContent.trim();
1273
+ return {{ row, val: type === "number" ? Number(raw) : raw }};
1274
+ }});
1275
+ keyed.sort((a, b) => factor * (type === "number" ? a.val - b.val : collator.compare(a.val, b.val)));
1276
+ reorderRows(keyed.map((k) => k.row));
1277
+ sortStatus.textContent = `Sorted by ${{button.textContent.trim()}}, ${{direction}}, ${{rows.length}} rows`;
1278
+ }}
1279
+
1280
+ table.addEventListener("command", (ev) => {{
1281
+ if (ev.command === "--sort") sortBy(ev.source);
1282
+ }});
1283
+ if (!("commandForElement" in HTMLButtonElement.prototype)) {{
1284
+ for (const btn of table.tHead.querySelectorAll('button[command="--sort"]')) {{
1285
+ btn.addEventListener("click", () => sortBy(btn));
1286
+ }}
1287
+ }}
1288
+
1289
+ // --- 8. Search & Modality Filtering ---
1290
+ const searchInput = document.getElementById("table-search");
1291
+ const modFilter = document.getElementById("modality-filter");
1292
+ function applyFilters() {{
1293
+ const q = (searchInput.value || "").trim().toLowerCase();
1294
+ const mod = modFilter.value;
1295
+ for (const row of tbody.querySelectorAll("tr.cand-row")) {{
1296
+ const matchQ = !q || (row.dataset.search || "").includes(q);
1297
+ const matchM = !mod || row.dataset.modality === mod;
1298
+ row.hidden = !(matchQ && matchM);
1299
+ }}
1300
+ }}
1301
+ searchInput.addEventListener("input", applyFilters);
1302
+ modFilter.addEventListener("change", applyFilters);
1303
+
1304
+ // --- 9. Offline CSV / JSON Export ---
1305
+ function downloadBlob(filename, content, mime) {{
1306
+ const blob = new Blob([content], {{ type: mime }});
1307
+ const url = URL.createObjectURL(blob);
1308
+ const a = document.createElement("a");
1309
+ a.href = url;
1310
+ a.download = filename;
1311
+ a.click();
1312
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
1313
+ }}
1314
+ document.getElementById("export-json-btn").addEventListener("click", () => {{
1315
+ downloadBlob(`${{DATA.run_id}}-summary.json`, JSON.stringify(DATA, null, 2), "application/json");
1316
+ }});
1317
+ document.getElementById("export-csv-btn").addEventListener("click", () => {{
1318
+ const cols = ["item_id", "label", "modality", "n_up", "n_down", "max_abs_lfc", "mean_abs_lfc", "l2_lfc", "latency_ms"];
1319
+ const lines = [cols.join(",")];
1320
+ for (const item of DATA.items) {{
1321
+ lines.push(cols.map((c) => JSON.stringify(item[c] ?? "")).join(","));
1322
+ }}
1323
+ downloadBlob(`${{DATA.run_id}}-summary.csv`, lines.join("\\n") + "\\n", "text/csv");
1324
+ }});
1325
+
1326
+ // Initial render
1327
+ renderHeatmap();
1328
+ if (selectedId) selectPerturbation(selectedId);
1329
+ }})();
1330
+ </script>
1331
+ </body>
1332
+ </html>
1333
+ """
1334
+
1335
+
1336
+ def generate_report(run_dir: str | Path, *, output_path: str | Path | None = None) -> Path:
1337
+ """Deterministically generate report.html from a run directory's manifest.json + results.jsonl."""
1338
+ store = RunStore(run_dir)
1339
+ manifest = store.load_manifest()
1340
+ latest = store.load_latest_results()
1341
+ ordered_records = [
1342
+ latest[spec.item_id] for spec in manifest.perturbations if spec.item_id in latest
1343
+ ]
1344
+ html_content = render_report_html(manifest, ordered_records)
1345
+
1346
+ target = Path(output_path).expanduser().resolve() if output_path else store.report_path
1347
+ target.parent.mkdir(parents=True, exist_ok=True)
1348
+ fd, tmp_name = tempfile.mkstemp(prefix=".report.", suffix=".html", dir=target.parent)
1349
+ try:
1350
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
1351
+ fh.write(html_content)
1352
+ fh.flush()
1353
+ os.fsync(fh.fileno())
1354
+ os.replace(tmp_name, target)
1355
+ except Exception:
1356
+ if os.path.exists(tmp_name):
1357
+ os.unlink(tmp_name)
1358
+ raise
1359
+ return target