Spaces:
Running
Split demo.html into modular CSS/JS assets
Browse filesdemo.html had grown to 6477 lines with a single inline <style> (1240
lines) and a single inline <script> (4358 lines) — every change meant
hunting through one giant scrollback and risked breaking unrelated
sections. Extracted into /assets/:
styles/ 14 files, ~1280 lines: base, header, banner, layout
(incl. new section--two-col), controls, sequence,
section-{folding,umap,tree,vep,species}, recipe, sandbox,
footer
js/shared/ helpers.js (lerp, logprobRgb, renderSeq…) + config.js
(fetchConfig, loadConfig, loadGenes)
js/sections/ one IIFE per demo card: completion, vep, track, species,
folding, tokenizer, loss, data, architecture, sandbox,
umap, tree
js/ banner.js (DNA helix Canvas 2D), tabs.js (hash routing
+ bootstrap loadConfig)
Strategy: plain <script> tags, not ES modules. Each IIFE was extracted
verbatim and globals stay global — minimum behavioural risk. Migrating
to import/export is a separate refactor.
demo.html is now 918 lines of pure structure + <link>/<script> tags.
app.py mounts /assets as StaticFiles and the no-cache middleware
(previously /experiments/-only) now also covers /assets/ so Safari
doesn't serve stale CSS/JS during the design loop.
Also includes the §5 Folding two-column layout (.section--two-col):
narrative rail (eyebrow + title + lede + takeaway) sticks at 248px on
the left, demo claims the rest. Takeaway is softened to a margin-note
treatment in 2-col mode and restored to its green-bar look on mobile
where it stacks back to single-col.
Co-authored-by: Cursor <cursoragent@cursor.com>
Files changed (32)
- app.py+24-8
- assets/js/banner.jsAdded+308
- assets/js/sections/architecture.jsAdded+37
- assets/js/sections/completion.jsAdded+337
- assets/js/sections/data.jsAdded+115
- assets/js/sections/folding.jsAdded+647
- assets/js/sections/loss.jsAdded+163
- assets/js/sections/sandbox.jsAdded+465
- assets/js/sections/species.jsAdded+241
- assets/js/sections/tokenizer.jsAdded+81
- assets/js/sections/track.jsAdded+261
- assets/js/sections/tree.jsAdded+340
- assets/js/sections/umap.jsAdded+926
- assets/js/sections/vep.jsAdded+274
- assets/js/shared/config.jsAdded+33
- assets/js/shared/helpers.jsAdded+75
- assets/js/tabs.jsAdded+52
- assets/styles/banner.cssAdded+92
- assets/styles/base.cssAdded+26
- assets/styles/controls.cssAdded+64
- assets/styles/footer.cssAdded+11
- assets/styles/header.cssAdded+61
- assets/styles/layout.cssAdded+160
- assets/styles/recipe.cssAdded+10
- assets/styles/sandbox.cssAdded+177
- assets/styles/section-folding.cssAdded+137
- assets/styles/section-species.cssAdded+38
- assets/styles/section-tree.cssAdded+207
- assets/styles/section-umap.cssAdded+126
- assets/styles/section-vep.cssAdded+32
- assets/styles/sequence.cssAdded+139
- demo.html
76 unmodified lines7778798081828384858687888990919293948 unmodified lines10310410594959697989910610710810911011111211311411511610111711810311912012112276 unmodified linesapp.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=6)app.mount("/img", StaticFiles(directory=os.path.join(HERE, "img")), name="img")
# Modular CSS / JS for demo.html. demo.html used to be a 6 kLOC monolith# with a single inline <style> and <script>; the assets/ tree splits it# into per-section files. Mounted as static so the browser can fetch# them by relative URL (/assets/styles/*.css, /assets/js/**/*.js).ASSETS = os.path.join(HERE, "assets")if os.path.isdir(ASSETS): app.mount( "/assets", StaticFiles(directory=ASSETS), name="assets", )
# Side-by-side prototypes for alternate UMAP annotation styles. Mounted as a# static directory so the HTML files can fetch /umap and /umap_labels without# CORS, and so changes are picked up without restarting uvicorn (--reload).8 unmodified lines )
# Disable browser caching for everything under /experiments. These are dev-# only prototypes we iterate on quickly — Safari and Chrome both cache# .js/.css aggressively by default (often serving a stale file even after a# soft reload) and that has burned the design loop more than once. The cost# of always refetching a 30 KB scatter.js is negligible vs the cost of "I# don't see my changes, are you sure you saved it?".# Disable browser caching for paths we iterate on during dev (the# experiments/ playground and assets/ where the split CSS/JS live).# Safari and Chrome both cache .js/.css aggressively by default (often# serving a stale file even after a soft reload) and that has burned# the design loop more than once. The cost of always refetching a# 30 KB module is negligible vs the cost of "I don't see my changes,# are you sure you saved it?"._NO_CACHE_PREFIXES = ("/experiments/", "/assets/")
@app.middleware("http")async def no_cache_experiments(request: Request, call_next):async def no_cache_dev_assets(request: Request, call_next): response = await call_next(request) if request.url.path.startswith("/experiments/"): if request.url.path.startswith(_NO_CACHE_PREFIXES): response.headers["Cache-Control"] = "no-store, must-revalidate" response.headers["Pragma"] = "no-cache" response.headers["Expires"] = "0"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308// =========================================================================// Carbon banner — animated DNA helix (Canvas 2D)//// Original implementation rendered ~960 SVG <path> mutations per frame, which// pinned the main thread at ~25% CPU non-stop. Canvas 2D draws the whole// scene to a bitmap each frame with no DOM mutations — typically 10-50× cheaper// for this kind of frame-by-frame animation. Math/colors are unchanged so the// visual is pixel-equivalent.// =========================================================================(function initCarbonBanner() { const banner = document.querySelector(".carbon-banner"); if (!banner) return; const canvas = banner.querySelector(".cb-helix-canvas"); if (!canvas) return; const ctx = canvas.getContext("2d");
const prefersReduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches; const sequence = ["A","T","A","A","C","G","A","C","T","T","C","C","C","T","A","T","T","G"]; const complement = { A: "T", T: "A", C: "G", G: "C" };
// All physical parameters live in the original SVG viewBox coordinate // system. The applyVbTransform() call below maps that system onto the // canvas backing store (DPR-aware), so we can keep the math identical. const helix = { startX: 868, endX: 1988, centerY: 318, amplitude: 88, cycles: 3.62, speed: 0.00015, // Doubled vs the original SVG (96 → 192). On <canvas> the per-segment cost // is negligible, and tighter sampling kills the staircasing visible on // the ribbon edges at high DPR. rungCount: 27, segmentCount: 192, bodyRadius: 6.4, shadowRadius: 8.4, // glyphGap is half the punch-through height around each letter. Bumped vs // the SVG-era 13.5 because rounded line caps eat ~0.7px of the visible // gap on each side at this stroke width, making the rung feel cramped. rungInset: 9.2, glyphGap: 16.5, }; // Helix bbox in viewBox coords. The CSS-positioned <canvas> mirrors this // box exactly (see .cb-helix-canvas in <style>). const VB = { x: 858, y: 220, w: 1140, h: 196 };
const COLORS = { shadow: "#aeb5ad", body: "#e4e5dc", bodyStroke: "rgba(49, 127, 63, 0.14)", edge: "#2d332e", green: "#317f3f", };
// Stroke-only ATCG glyphs — same path strings the SVG version used. // Path2D parses an SVG path string directly; ctx.stroke(path2d) is fast. const glyphPaths = { A: new Path2D("M -5 8 L 0 -8 L 5 8 M -3.1 2 L 3.1 2"), C: new Path2D("M 5 -6 C 1 -9 -6 -7 -6 0 C -6 7 1 9 5 6"), G: new Path2D("M 5 -6 C 1 -9 -6 -7 -6 0 C -6 7 1 9 5 6 M 5 1 L 1 1 M 5 1 L 5 6"), T: new Path2D("M -6 -7 L 6 -7 M 0 -7 L 0 8"), };
// --- Canvas sizing (DPR + viewBox→pixels mapping) --------------------- let cssW = 0, cssH = 0, dpr = 1, uniformScale = 1, offsetX = 0, offsetY = 0; function resize() { const rect = canvas.getBoundingClientRect(); if (rect.width === 0 || rect.height === 0) return; cssW = rect.width; cssH = rect.height; // Use the device's full DPR (typically 2 or 3 on Retina displays). // The banner is small (~600×100 CSS px) so even DPR 3 stays cheap. dpr = window.devicePixelRatio || 1; canvas.width = Math.round(cssW * dpr); canvas.height = Math.round(cssH * dpr); const sx = canvas.width / VB.w; const sy = canvas.height / VB.h; uniformScale = Math.min(sx, sy); offsetX = (canvas.width - VB.w * uniformScale) / 2; offsetY = (canvas.height - VB.h * uniformScale) / 2; } function applyVbTransform() { ctx.setTransform( uniformScale, 0, 0, uniformScale, -VB.x * uniformScale + offsetX, -VB.y * uniformScale + offsetY, ); } // Convert a CSS-pixel size to viewBox units (so strokes/fonts stay crisp // regardless of the canvas size — equivalent to vector-effect:non-scaling-stroke). function px(cssPx) { return (cssPx * dpr) / uniformScale; }
// --- Math (verbatim from the SVG version) ----------------------------- function pointAt(x, offset, phase) { const t = (x - helix.startX) / (helix.endX - helix.startX); const theta = t * helix.cycles * Math.PI * 2 + phase + offset; const slope = Math.cos(theta) * helix.amplitude * helix.cycles * Math.PI * 2 / (helix.endX - helix.startX); const normalLength = Math.hypot(slope, 1); return { x, y: helix.centerY + Math.sin(theta) * helix.amplitude, z: Math.cos(theta), nx: -slope / normalLength, ny: 1 / normalLength, }; }
// Pre-allocate sample buffers — never reallocated per frame. const pointsA = new Array(helix.segmentCount + 1); const pointsB = new Array(helix.segmentCount + 1); function fillSamples(buf, offset, phase) { const span = helix.endX - helix.startX; for (let i = 0; i <= helix.segmentCount; i++) { buf[i] = pointAt(helix.startX + (span * i) / helix.segmentCount, offset, phase); } }
// Pre-allocated segment list (avoids GC churn). const segs = new Array(helix.segmentCount * 2); for (let i = 0; i < segs.length; i++) segs[i] = { a: null, b: null, z: 0 }; function fillSegments() { const N = helix.segmentCount; for (let i = 0; i < N; i++) { const a0 = pointsA[i], b0 = pointsA[i + 1]; const a1 = pointsB[i], b1 = pointsB[i + 1]; const s0 = segs[2 * i]; s0.a = a0; s0.b = b0; s0.z = (a0.z + b0.z) * 0.5; const s1 = segs[2 * i + 1]; s1.a = a1; s1.b = b1; s1.z = (a1.z + b1.z) * 0.5; } }
// --- Drawing primitives (operate in viewBox space) -------------------- function ribbonPath(a, b, radius) { ctx.beginPath(); ctx.moveTo(a.x + a.nx * radius, a.y + a.ny * radius); ctx.lineTo(b.x + b.nx * radius, b.y + b.ny * radius); ctx.lineTo(b.x - b.nx * radius, b.y - b.ny * radius); ctx.lineTo(a.x - a.nx * radius, a.y - a.ny * radius); ctx.closePath(); } function lineEdge(a, b, radius) { ctx.beginPath(); ctx.moveTo(a.x + a.nx * radius, a.y + a.ny * radius); ctx.lineTo(b.x + b.nx * radius, b.y + b.ny * radius); } function drawSegment(seg) { const z = seg.z; const front = Math.max(0, Math.min(1, (z + 1) / 2)); const a = seg.a, b = seg.b; // Soft outer shadow (depth cue) ctx.globalAlpha = 0.05 + front * 0.12; ctx.fillStyle = COLORS.shadow; ribbonPath(a, b, helix.shadowRadius); ctx.fill(); // Body ribbon (fill + thin green outline, same alpha — matches SVG opacity behavior) ctx.globalAlpha = 0.5 + front * 0.42; ribbonPath(a, b, helix.bodyRadius); ctx.fillStyle = COLORS.body; ctx.fill(); ctx.strokeStyle = COLORS.bodyStroke; ctx.lineWidth = px(0.8); ctx.stroke(); // Edges (top + bottom ink lines) ctx.globalAlpha = 0.2 + front * 0.68; ctx.strokeStyle = COLORS.edge; ctx.lineWidth = px(1.15); ctx.lineCap = "round"; ctx.lineJoin = "round"; lineEdge(a, b, helix.bodyRadius + 0.35); ctx.stroke(); lineEdge(a, b, -(helix.bodyRadius + 0.35)); ctx.stroke(); } function drawRung(x, yStart, letterYs, yEnd, gap) { const start = Math.min(yStart, yEnd); const end = Math.max(yStart, yEnd); // Compute gaps where letters punch through the rung. const ranges = []; for (const y of letterYs) { const f = Math.max(start, y - gap); const t = Math.min(end, y + gap); if (t > f) ranges.push([f, t]); } ranges.sort((u, v) => u[0] - v[0]); const merged = []; for (const r of ranges) { const last = merged[merged.length - 1]; if (!last || r[0] > last[1]) merged.push([r[0], r[1]]); else last[1] = Math.max(last[1], r[1]); } ctx.beginPath(); let cursor = start; for (const [f, t] of merged) { if (f - cursor > 0.7) { ctx.moveTo(x, cursor); ctx.lineTo(x, f); } cursor = t; } if (end - cursor > 0.7) { ctx.moveTo(x, cursor); ctx.lineTo(x, end); } ctx.stroke(); } function drawGlyph(letter, x, y) { ctx.save(); ctx.translate(x, y); ctx.stroke(glyphPaths[letter]); ctx.restore(); }
// --- Frame ------------------------------------------------------------ function drawFrame(phase) { if (cssW === 0 || cssH === 0) return; // Identity transform to clear the raw pixel grid, then re-apply viewBox map. ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); applyVbTransform();
fillSamples(pointsA, 0, phase); fillSamples(pointsB, Math.PI, phase); fillSegments(); segs.sort((u, v) => u.z - v.z);
// Pass 1: back segments (z < 0) — drawn under rungs/glyphs. let i = 0; for (; i < segs.length && segs[i].z < 0; i++) drawSegment(segs[i]);
// Rungs + ATCG glyphs (only those whose rung span makes them visible). for (let k = 0; k < helix.rungCount; k++) { const t = k / (helix.rungCount - 1); const x = helix.startX + (helix.endX - helix.startX) * t; const a = pointAt(x, 0, phase); const b = pointAt(x, Math.PI, phase); const yTop = Math.min(a.y, b.y); const yBottom = Math.max(a.y, b.y); const span = yBottom - yTop; const inset = Math.min(helix.rungInset, Math.max(0, span * 0.5 - 3)); const visible = Math.max(0, Math.min(1, (span - 34) / 70)); const aLetterY = a.y + (b.y - a.y) * 0.34; const bLetterY = b.y + (a.y - b.y) * 0.34; const letterGap = Math.min(helix.glyphGap, Math.max(8.5, span * 0.16));
ctx.globalAlpha = 0.18 + visible * 0.72; ctx.strokeStyle = COLORS.green; ctx.lineWidth = px(1.35); ctx.lineCap = "round"; drawRung(x, yTop + inset, [aLetterY, bLetterY], yBottom - inset, letterGap);
ctx.globalAlpha = 0.16 + visible * 0.84; ctx.lineWidth = px(1.8); ctx.lineCap = "square"; ctx.lineJoin = "miter"; const letter = sequence[k % sequence.length]; drawGlyph(letter, x, aLetterY); drawGlyph(complement[letter], x, bLetterY); }
// Pass 2: front segments (z >= 0) — drawn on top of rungs/glyphs. for (; i < segs.length; i++) drawSegment(segs[i]);
ctx.globalAlpha = 1; }
resize();
// Static frame for users who prefer reduced motion. if (prefersReduced) { drawFrame(0.6); return; }
// --- Animation loop, paused off-screen and on hidden tab -------------- // 30fps is visually indistinguishable from 60fps at this rotation speed // and halves the paint workload. const FRAME_INTERVAL_MS = 1000 / 30; let rafId = 0, running = false, inViewport = true, lastFrameTs = 0; function tick(ts) { if (!running) return; if (ts - lastFrameTs >= FRAME_INTERVAL_MS) { lastFrameTs = ts; drawFrame(ts * helix.speed); } rafId = requestAnimationFrame(tick); } function start() { if (running || !inViewport || document.hidden) return; running = true; lastFrameTs = 0; rafId = requestAnimationFrame(tick); } function stop() { if (!running) return; running = false; cancelAnimationFrame(rafId); }
const io = new IntersectionObserver(entries => { inViewport = entries[0].isIntersecting; if (inViewport) start(); else stop(); }, { rootMargin: "100px" }); io.observe(banner);
document.addEventListener("visibilitychange", () => { if (document.hidden) stop(); else start(); });
// Re-size the backing store when the banner is resized (responsive layout). const ro = new ResizeObserver(() => { resize(); drawFrame(lastFrameTs * helix.speed); }); ro.observe(canvas);
drawFrame(0); start();})();
12345678910111213141516171819202122232425262728293031323334353637// =========================================================================// §10 — Architecture table// =========================================================================(function initDemo10() { const tbl = document.getElementById("d10-arch"); const ROWS = [ ["Layers", "30", "32"], ["Hidden size", "3,072", "4,096"], ["FFN hidden size", "8,448", "14,336"], ["Attention heads", "32", "32"], ["KV groups (GQA)", "4", "8"], ["Head dim", "96", "128"], ["Activation", "SwiGLU", "SwiGLU"], ["Normalization", "RMSNorm", "RMSNorm"], ["Position encoding", "RoPE (θ=500k)", "RoPE (θ=500k)"], ["Tied I/O embeddings", "✓", "✓"], ["Context length", "8,192 tokens (≈49 kbp)", "8,192 tokens (≈49 kbp)"], ]; let html = `<thead> <tr> <th style="text-align:left;padding:10px 6px 8px;border-bottom:1px solid #ddd;font-size:10px;color:#888;text-transform:uppercase;letter-spacing:1.5px;font-weight:400"></th> <th style="text-align:left;padding:10px 12px 8px;border-bottom:1px solid #ddd;font-size:11px;color:#1f1f1d;letter-spacing:1px">Carbon · 3B</th> <th style="text-align:left;padding:10px 12px 8px;border-bottom:1px solid #ddd;font-size:11px;color:#1f1f1d;letter-spacing:1px">Carbon · 8B</th> </tr> </thead><tbody>`; ROWS.forEach((r, i) => { const bg = i % 2 === 0 ? "#f7f5ee" : "#fff"; html += `<tr style="background:${bg}"> <td style="padding:6px;color:#666;font-size:10px;text-transform:uppercase;letter-spacing:1px">${r[0]}</td> <td style="padding:6px 12px;color:#1f1f1d">${r[1]}</td> <td style="padding:6px 12px;color:#1f1f1d">${r[2]}</td> </tr>`; }); html += `</tbody>`; tbl.innerHTML = html;})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337// =========================================================================// §1 — Gene completion + annotation overlay// =========================================================================(function initDemo1() { const els = { pills: document.getElementById("d1-pills"), info: document.getElementById("d1-info"), track: document.getElementById("d1-track"), seq: document.getElementById("d1-seq"), go: document.getElementById("d1-go"), stop: document.getElementById("d1-stop"), status: document.getElementById("d1-status"), statusText: document.querySelector("#d1-status span:last-child"), id: document.getElementById("d1-id"), idExon: document.getElementById("d1-id-exon"), idIntron:document.getElementById("d1-id-intron"), tok: document.getElementById("d1-tok"), lp: document.getElementById("d1-lp"), ppl: document.getElementById("d1-ppl"), };
let gene = null; let prefixStart = 0; let prefixEnd = 200; let genEnd = 260; // end of generated region (genLen = genEnd - prefixEnd) const MIN_PROMPT_BP = 6; // at least one BPE token's worth const MIN_GEN_BP = 6; const DEFAULT_GEN_BP = 60; let abortCtrl = null; let dragging = null; // "start" | "end" | "genend" | null
let promptBases = ""; let genText = ""; let genTokens = []; // [{text, logprob}] let genTokenAtBase = []; // index into genTokens for each generated base
function setStatus(text, mode = "") { els.statusText.textContent = text; els.status.className = "status" + (mode ? " " + mode : ""); }
function renderTrack() { const W = 1000, H = 40; if (!gene) { els.track.innerHTML = ""; return; } const scaleX = (bp) => (bp / gene.length) * W; // Track body sits y=8..32; arrows live at y=0..8 (start, top) and y=32..40 (end, bottom). const TRACK_TOP = 8, TRACK_BOT = 32, INTRON_Y = 20, EXON_Y = 14, EXON_H = 12; let svg = ""; // Background line through introns svg += `<line class="intron" x1="0" y1="${INTRON_Y}" x2="${W}" y2="${INTRON_Y}"/>`; // Exon rectangles for (const e of gene.exons) { const x = scaleX(e.start); const w = Math.max(1, scaleX(e.end - e.start)); svg += `<rect class="exon" x="${x.toFixed(1)}" y="${EXON_Y}" width="${w.toFixed(1)}" height="${EXON_H}"/>`; } // Selected prompt region (very faint, between handles) const xStart = scaleX(prefixStart); const xEnd = scaleX(prefixEnd); svg += `<rect class="prompt-region" x="${xStart.toFixed(1)}" y="${TRACK_TOP}" width="${(xEnd - xStart).toFixed(1)}" height="${TRACK_BOT - TRACK_TOP}"/>`; // Generated region (muted green box, between prompt-end and gen-end handles) const xGenEnd = scaleX(genEnd); svg += `<rect class="gen-region" x="${xEnd.toFixed(1)}" y="${TRACK_TOP}" width="${(xGenEnd - xEnd).toFixed(1)}" height="${TRACK_BOT - TRACK_TOP}"/>`; // START handle: vertical line through the track body + downward triangle on top. svg += `<g class="handle${dragging === "start" ? " dragging" : ""}" data-role="start" transform="translate(${xStart.toFixed(1)},0)">` + `<line x1="0" y1="${TRACK_TOP}" x2="0" y2="${TRACK_BOT}"/>` + `<polygon points="-4,0 4,0 0,${TRACK_TOP}"/>` + `<rect x="-8" y="0" width="16" height="${H}" fill="transparent"/>` + `</g>`; // END handle (prompt end / gen start): vertical line + upward triangle on bottom. svg += `<g class="handle${dragging === "end" ? " dragging" : ""}" data-role="end" transform="translate(${xEnd.toFixed(1)},0)">` + `<line x1="0" y1="${TRACK_TOP}" x2="0" y2="${TRACK_BOT}"/>` + `<polygon points="0,${TRACK_BOT} -4,${H} 4,${H}"/>` + `<rect x="-8" y="0" width="16" height="${H}" fill="transparent"/>` + `</g>`; // GEN-END handle: vertical line + downward triangle on top, green. svg += `<g class="handle gen${dragging === "genend" ? " dragging" : ""}" data-role="genend" transform="translate(${xGenEnd.toFixed(1)},0)">` + `<line x1="0" y1="${TRACK_TOP}" x2="0" y2="${TRACK_BOT}"/>` + `<polygon points="-4,0 4,0 0,${TRACK_TOP}"/>` + `<rect x="-8" y="0" width="16" height="${H}" fill="transparent"/>` + `</g>`; els.track.innerHTML = svg; }
function bpFromClientX(clientX) { if (!gene) return 0; const rect = els.track.getBoundingClientRect(); const frac = (clientX - rect.left) / rect.width; return Math.max(0, Math.min(gene.length, Math.round(frac * gene.length))); }
function renderInfo() { if (!gene) { els.info.textContent = "loading genes…"; return; } const promptLen = prefixEnd - prefixStart; const genLen = genEnd - prefixEnd; els.info.innerHTML = `<strong>${gene.symbol}</strong> · ${gene.blurb} · <span style="color:#888">${gene.length.toLocaleString("en-US")} bp</span>` + ` · <span style="color:#888">prompt: ${prefixStart}–${prefixEnd} (${promptLen} bp)</span>` + ` · <span style="color:#317f3f">generate: ${prefixEnd}–${genEnd} (${genLen} bp)</span>`; }
function basesPerLine() { // Match the existing index.html dynamic computation, but coarser. const cs = getComputedStyle(els.seq); const padL = parseFloat(cs.paddingLeft) || 0; const padR = parseFloat(cs.paddingRight) || 0; const contentW = els.seq.clientWidth - padL - padR; // Approx ~9px per character at 12px JBM with 1px letter-spacing const charW = 8.4; const prefixW = 7 * charW; // " N " const blockW = 10 * charW + charW; // 10 bases + space if (contentW <= prefixW) return 60; const blocks = Math.floor((contentW - prefixW) / blockW); return Math.max(20, Math.min(blocks, 12) * 10); }
function annotationAt(idx) { if (!gene) return "intergenic"; for (const e of gene.exons) if (idx >= e.start && idx < e.end) return "exon"; return "intron"; }
function renderSequenceAndRef() { const bpl = basesPerLine(); const prompt = promptBases; const total = prompt + genText; const lpRange = lpRangeOf(genTokens);
// Output: prompt in gray; generated colored by logprob, underlined green/red by ref match. const colorOutput = (absIdx, base) => { if (absIdx < prompt.length) { return { style: `color:rgb(${PROMPT_RGB.join(",")})` }; } const genIdx = absIdx - prompt.length; const tok = genTokens[genTokenAtBase[genIdx]]; const [r, g, b] = logprobRgb(tok ? tok.logprob : null, lpRange); const refBase = gene ? gene.seq[prefixEnd + genIdx] : undefined; const ulColor = refBase == null ? "transparent" : (base === refBase ? "#317f3f" : "#b00020"); return { style: `color:rgb(${r},${g},${b});` + `text-decoration:underline;` + `text-decoration-color:${ulColor};` + `text-decoration-thickness:1.5px;` + `text-underline-offset:2px` }; }; renderSeq(els.seq, total, bpl, colorOutput); }
function updateStats() { if (!gene || genText.length === 0) { [els.id, els.idExon, els.idIntron, els.tok, els.lp, els.ppl].forEach(e => { e.textContent = "—"; e.classList.add("muted"); }); return; } const refSlice = gene.seq.slice(prefixEnd, prefixEnd + genText.length); let match = 0, total = 0; let exonMatch = 0, exonTotal = 0; let intronMatch = 0, intronTotal = 0; for (let i = 0; i < genText.length; i++) { if (i >= refSlice.length) break; total++; const ok = genText[i] === refSlice[i]; if (ok) match++; const ann = annotationAt(prefixEnd + i); if (ann === "exon") { exonTotal++; if (ok) exonMatch++; } else if (ann === "intron") { intronTotal++; if (ok) intronMatch++; } } const pct = (n, d) => d > 0 ? `${((n/d)*100).toFixed(0)}%` : "—"; els.id.textContent = `${pct(match, total)} (${match}/${total})`; els.idExon.textContent = exonTotal > 0 ? `${pct(exonMatch, exonTotal)} (${exonMatch}/${exonTotal})` : "—"; els.idIntron.textContent = intronTotal > 0 ? `${pct(intronMatch, intronTotal)} (${intronMatch}/${intronTotal})` : "—"; els.tok.textContent = String(genTokens.length); const mlp = meanLogprob(genTokens); els.lp.textContent = mlp == null ? "—" : mlp.toFixed(2); els.ppl.textContent = mlp == null ? "—" : Math.exp(-mlp).toFixed(1); [els.id, els.idExon, els.idIntron, els.tok, els.lp, els.ppl].forEach(e => e.classList.remove("muted")); }
function reset() { promptBases = gene ? gene.seq.slice(prefixStart, prefixEnd) : ""; genText = ""; genTokens = []; genTokenAtBase = []; renderInfo(); renderTrack(); renderSequenceAndRef(); updateStats(); }
async function generate() { if (abortCtrl || !gene) return; reset(); abortCtrl = new AbortController(); els.go.disabled = true; els.stop.disabled = false; setStatus("connecting…", "streaming");
const genLen = genEnd - prefixEnd;
try { const resp = await fetch("/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: promptBases, max_tokens: Math.ceil(genLen / 6) + 4, // tokens are ~6 bases each temperature: 0.5, top_p: 0.9, }), signal: abortCtrl.signal, }); if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`); setStatus("streaming", "streaming");
const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const events = buffer.split("\n\n"); buffer = events.pop(); for (const ev of events) { const line = ev.trim(); if (!line.startsWith("data:")) continue; const data = JSON.parse(line.slice(5).trim()); if (data.error) throw new Error(data.error); if (data.done) continue; if (data.logprobs) { const lp = data.logprobs; for (let i = 0; i < lp.tokens.length; i++) { const tokIdx = genTokens.length; genTokens.push({ text: lp.tokens[i], logprob: lp.token_logprobs[i] }); for (let j = 0; j < lp.tokens[i].length; j++) genTokenAtBase.push(tokIdx); } } if (data.text) { const cleaned = data.text.toUpperCase().replace(/[^ACGTN]/g, ""); // Stop appending once we've covered the requested gen window. const room = Math.max(0, genLen - genText.length); genText += cleaned.slice(0, room); renderSequenceAndRef(); updateStats(); if (genText.length >= genLen) abortCtrl?.abort(); } } } setStatus("done"); } catch (e) { if (e.name === "AbortError") setStatus("done"); else setStatus(e.message, "error"); } finally { abortCtrl = null; els.go.disabled = false; els.stop.disabled = true; renderSequenceAndRef(); updateStats(); } }
function stop() { if (abortCtrl) abortCtrl.abort(); }
function selectGene(symbol) { const g = GENES.find(x => x.symbol === symbol); if (!g) return; gene = g; // Reset prompt + generate windows to defaults, clamped to this gene's length. prefixStart = 0; prefixEnd = Math.min(200, Math.max(MIN_PROMPT_BP, gene.length - DEFAULT_GEN_BP)); genEnd = Math.min(gene.length, prefixEnd + DEFAULT_GEN_BP); els.pills.querySelectorAll(".pill").forEach(p => p.classList.toggle("active", p.dataset.gene === symbol)); reset(); }
function bindPills(container, attr, onSelect) { container.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => { container.querySelectorAll(".pill").forEach(x => x.classList.remove("active")); p.classList.add("active"); onSelect(p.dataset[attr]); }); }); }
// Bootstrap loadGenes().then(genes => { els.pills.innerHTML = genes.map((g, i) => `<button class="pill${i === 0 ? " active" : ""}" data-gene="${g.symbol}">${g.symbol}</button>` ).join(""); bindPills(els.pills, "gene", selectGene); selectGene(genes[0].symbol); }).catch(e => { els.info.textContent = "failed to load genes: " + e.message; });
els.go.addEventListener("click", generate); els.stop.addEventListener("click", stop);
// Drag handles on the track to set the prompt range. els.track.addEventListener("pointerdown", (e) => { const target = e.target.closest(".handle"); if (!target || !gene) return; dragging = target.dataset.role; els.track.setPointerCapture(e.pointerId); renderTrack(); // re-render so the picked handle shows its `.dragging` style e.preventDefault(); }); els.track.addEventListener("pointermove", (e) => { if (!dragging || !gene) return; const bp = bpFromClientX(e.clientX); if (dragging === "start") { prefixStart = Math.max(0, Math.min(bp, prefixEnd - MIN_PROMPT_BP)); } else if (dragging === "end") { prefixEnd = Math.max(prefixStart + MIN_PROMPT_BP, Math.min(bp, genEnd - MIN_GEN_BP)); } else if (dragging === "genend") { genEnd = Math.max(prefixEnd + MIN_GEN_BP, Math.min(bp, gene.length)); } reset(); }); const endDrag = (e) => { if (!dragging) return; dragging = null; try { els.track.releasePointerCapture(e.pointerId); } catch (_) {} renderTrack(); }; els.track.addEventListener("pointerup", endDrag); els.track.addEventListener("pointercancel", endDrag);
window.addEventListener("resize", () => { if (gene) renderSequenceAndRef(); });})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115// =========================================================================// §9 — Data composition + signal-to-noise// =========================================================================(function initDemo9() { const pieEl = document.getElementById("d9-pie"); const legendEl = document.getElementById("d9-legend"); const snrEl = document.getElementById("d9-snr"); const tplEl = document.getElementById("d9-templates");
const COMPOSITION = [ { label: "GENERator-v2", pct: 70, color: "#317f3f", desc: "annotation-aware functional genomic backbone (eukaryotic, gene-centric)" }, { label: "mRNA", pct: 16, color: "#2c5aa0", desc: "OpenGenome2 mature transcripts · RNA-level functional context" }, { label: "GTDB", pct: 10, color: "#c08030", desc: "OpenGenome2 prokaryotic genomes · compact bacterial structure" }, { label: "mRNA-splice", pct: 4, color: "#7a4baa", desc: "OpenGenome2 transcript-derived · splice-related signal" }, ];
const TEMPLATES = [ { pct: "50.0%", body: "<dna>SEQUENCE</dna>", note: "no metadata · default pre-training format" }, { pct: "16.7%", body: "<species_type><gene_type><dna>SEQUENCE</dna>", note: "both metadata fields" }, { pct: "16.7%", body: "<species_type><dna>SEQUENCE</dna>", note: "species-conditioned only" }, { pct: "16.7%", body: "<gene_type><dna>SEQUENCE</dna>", note: "gene-type-conditioned only" }, ];
function renderPie() { const cx = 100, cy = 100, r = 88; let acc = 0; let svg = ""; for (const slice of COMPOSITION) { const start = acc / 100 * Math.PI * 2 - Math.PI / 2; acc += slice.pct; const end = acc / 100 * Math.PI * 2 - Math.PI / 2; const large = slice.pct > 50 ? 1 : 0; const x1 = cx + r * Math.cos(start), y1 = cy + r * Math.sin(start); const x2 = cx + r * Math.cos(end), y2 = cy + r * Math.sin(end); svg += `<path d="M ${cx} ${cy} L ${x1.toFixed(1)} ${y1.toFixed(1)} A ${r} ${r} 0 ${large} 1 ${x2.toFixed(1)} ${y2.toFixed(1)} Z" fill="${slice.color}" opacity="0.85"/>`; // Percentage label inside slice if room if (slice.pct >= 8) { const mid = (start + end) / 2; const lr = r * 0.62; const lx = cx + lr * Math.cos(mid); const ly = cy + lr * Math.sin(mid); svg += `<text x="${lx.toFixed(1)}" y="${(ly + 4).toFixed(1)}" font-family="JetBrains Mono" font-size="11" fill="#fff" text-anchor="middle" font-weight="500">${slice.pct}%</text>`; } } // Inner hole for donut svg += `<circle cx="${cx}" cy="${cy}" r="${r * 0.42}" fill="#f7f5ee"/>`; svg += `<text x="${cx}" y="${cy - 2}" font-family="JetBrains Mono" font-size="11" fill="#1f1f1d" text-anchor="middle" font-weight="500">CARBON</text>`; svg += `<text x="${cx}" y="${cy + 12}" font-family="JetBrains Mono" font-size="9" fill="#888" text-anchor="middle">corpus</text>`; pieEl.innerHTML = svg; }
function renderLegend() { legendEl.innerHTML = COMPOSITION.map(s => ` <div style="display:flex;align-items:flex-start;gap:10px;padding:6px 0;border-bottom:1px solid #f0f0f0"> <span style="display:inline-block;flex:0 0 12px;height:12px;background:${s.color};border-radius:2px;margin-top:3px"></span> <div style="flex:1"> <div><strong style="color:#1f1f1d">${s.label}</strong> <span style="color:#888">· ${s.pct}%</span></div> <div style="color:#888;font-size:10px;margin-top:1px">${s.desc}</div> </div> </div> `).join(""); }
function renderSNR() { const W = 1000, H = 90; const rowY = [22, 60]; const segH = 18; let svg = ""; // Two rows: raw genome (sparse signal) vs curated (dense signal) // Each row has a sequence of background + functional segments. function paintRow(y, segs, label) { svg += `<text x="6" y="${y + 13}" font-family="JetBrains Mono" font-size="10" fill="#666" letter-spacing="1">${label}</text>`; // gutter for the label const padL = 110; let cursor = padL; const rowW = W - padL - 12; for (const seg of segs) { const w = (seg.frac * rowW); svg += `<rect x="${cursor.toFixed(1)}" y="${y}" width="${Math.max(0.5, w).toFixed(1)}" height="${segH}" fill="${seg.func ? '#317f3f' : '#ddd'}"/>`; cursor += w; } } // Raw: ~5% functional, scattered const rawSegs = [ { frac: 0.18 }, { frac: 0.015, func: true }, { frac: 0.10 }, { frac: 0.02, func: true }, { frac: 0.30 }, { frac: 0.005, func: true }, { frac: 0.05 }, { frac: 0.01, func: true }, { frac: 0.18 }, { frac: 0.005, func: true }, { frac: 0.115 }, ]; paintRow(rowY[0], rawSegs, "RAW (5%)"); // Curated: ~46% functional, denser const curSegs = [ { frac: 0.06 }, { frac: 0.10, func: true }, { frac: 0.04 }, { frac: 0.12, func: true }, { frac: 0.06 }, { frac: 0.08, func: true }, { frac: 0.05 }, { frac: 0.10, func: true }, { frac: 0.04 }, { frac: 0.06, func: true }, { frac: 0.05 }, { frac: 0.10, func: true }, { frac: 0.04 }, ]; paintRow(rowY[1], curSegs, "CURATED (46%)"); snrEl.innerHTML = svg; }
function renderTemplates() { let html = ""; for (const t of TEMPLATES) { html += `<div style="text-align:right;color:#317f3f;font-weight:500">${t.pct}</div>`; html += `<div><span style="background:#f4f4f4;padding:2px 6px;border-radius:2px;color:#1f1f1d">${t.body.replace(/</g,"<").replace(/>/g,">")}</span> <span style="color:#888;font-size:10px;margin-left:8px">${t.note}</span></div>`; } tplEl.innerHTML = html; }
renderPie(); renderLegend(); renderSNR(); renderTemplates();})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647// =========================================================================// §5 — Folding (Carbon → ESMFold → 3Dmol side-by-side)//// Pipeline per click:// reference : gene.seq exons concatenated → mRNA → longest ORF → AA// carbon : gene.seq[0..prefix] → /generate (temp=0.7) → DNA continuation// → longest ORF across 3 frames → AA// both AA strings → POST /fold in parallel → 3Dmol cartoons// stats : pLDDT mean for each, 1D identity between the two AA strings//// Reference uses exon annotation (a biological prior the model never sees)// so we get the "true" protein for the chosen gene. Carbon gets only raw// bases and has to figure the ORF out by itself — the asymmetry is exactly// the point of the section.// =========================================================================(function initDemoFold() { // --- Standard genetic code (canonical, no selenocysteine handling) ----- // Indexed by uppercase 3-letter codon. "*" marks the three stop codons. const CODON_TABLE = { TTT:"F",TTC:"F",TTA:"L",TTG:"L", CTT:"L",CTC:"L",CTA:"L",CTG:"L", ATT:"I",ATC:"I",ATA:"I",ATG:"M", GTT:"V",GTC:"V",GTA:"V",GTG:"V", TCT:"S",TCC:"S",TCA:"S",TCG:"S", CCT:"P",CCC:"P",CCA:"P",CCG:"P", ACT:"T",ACC:"T",ACA:"T",ACG:"T", GCT:"A",GCC:"A",GCA:"A",GCG:"A", TAT:"Y",TAC:"Y",TAA:"*",TAG:"*", CAT:"H",CAC:"H",CAA:"Q",CAG:"Q", AAT:"N",AAC:"N",AAA:"K",AAG:"K", GAT:"D",GAC:"D",GAA:"E",GAG:"E", TGT:"C",TGC:"C",TGA:"*",TGG:"W", CGT:"R",CGC:"R",CGA:"R",CGG:"R", AGT:"S",AGC:"S",AGA:"R",AGG:"R", GGT:"G",GGC:"G",GGA:"G",GGG:"G", };
// Walk a DNA string in 3-base steps starting at `frame`, look for ATG // start codons, and translate from each one. Prefers an ORF ending on a // clean stop codon; falls back to a truncated ORF (reached the end of // `dna` with no stop) — that happens when Carbon mutates the canonical // stop and the translation reads into the 3'UTR. Truncated ORFs are // tagged so the UI can hint at that. function findLongestORF(dna, minAA = 30) { let bestClean = null; let bestTrunc = null; for (let frame = 0; frame < 3; frame++) { let i = frame; while (i <= dna.length - 3) { if (dna.slice(i, i + 3) !== "ATG") { i += 3; continue; } let aa = ""; let j = i; let stoppedCleanly = false; let invalid = false; while (j + 3 <= dna.length) { const a = CODON_TABLE[dna.slice(j, j + 3)]; if (!a) { invalid = true; break; } // Non-ACGT codon — bail. if (a === "*") { stoppedCleanly = true; break; } aa += a; j += 3; } if (!invalid && aa.length >= minAA) { const entry = { aa, frame, startBP: i, endBP: j, lenBP: j - i, truncated: !stoppedCleanly }; if (stoppedCleanly) { if (!bestClean || aa.length > bestClean.aa.length) bestClean = entry; } else { if (!bestTrunc || aa.length > bestTrunc.aa.length) bestTrunc = entry; } } i += 3; } } return bestClean || bestTrunc; }
// Splice exons out of a (genomic) DNA string using the given exon // coordinates and return the mature mRNA. Exons whose `end` exceeds the // DNA length are truncated; exons fully past the end are dropped. This // lets us reuse the same routine for the reference (full genomic seq) // and for Carbon's continuation (which may be shorter than the gene). function spliceExons(dna, exons) { const parts = []; for (const e of exons) { if (e.start >= dna.length) break; parts.push(dna.slice(e.start, Math.min(e.end, dna.length))); } return parts.join(""); }
function translateReference(gene) { return findLongestORF(spliceExons(gene.seq, gene.exons), 30); }
// A gene is "demo-friendly" if Carbon can plausibly generate enough DNA // in one shot to cover all exons. Anything past ~2500 bp of genomic DNA // takes minutes on the live endpoint, so we hard-cap there and surface // the limitation in the UI instead of silently producing a broken ORF. const MAX_GENOMIC_BP = 2500; function geneFeasibility(gene) { const lastExonEnd = gene.exons.length ? gene.exons[gene.exons.length - 1].end : 0; return { lastExonEnd, feasible: lastExonEnd <= MAX_GENOMIC_BP }; }
// Fraction of positions where two AA strings match. Compared over the // shorter of the two — Carbon and ref may have wildly different ORF // lengths (or the same), and we just want a 0-1 number for the stat row. function identity1D(a, b) { const n = Math.min(a.length, b.length); if (n === 0) return 0; let m = 0; for (let i = 0; i < n; i++) if (a[i] === b[i]) m++; return m / n; }
// Drain the SSE response from /generate and return the concatenated DNA. // Matches the framing already in §1 (one event per "data: …\n\n" block). async function streamGenerate(prompt, maxTokens, temperature, abortSignal) { const resp = await fetch("/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt, max_tokens: maxTokens, temperature, top_p: 1.0 }), signal: abortSignal, }); if (!resp.ok) throw new Error(`/generate HTTP ${resp.status}`); const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buf = ""; let out = ""; while (true) { const { value, done } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); const events = buf.split("\n\n"); buf = events.pop(); for (const ev of events) { const line = ev.trim(); if (!line.startsWith("data:")) continue; const data = JSON.parse(line.slice(5).trim()); if (data.error) throw new Error(data.error); if (data.text) out += data.text; } } return out.toUpperCase().replace(/[^ACGT]/g, ""); }
// --- DOM --------------------------------------------------------------- let GENES_LOCAL = null; let currentGeneSymbol = null; let prefixLen = 200; let viewerCarbon = null; let viewerRef = null; let abortCtrl = null;
const els = { pills: document.getElementById("dfold-pills"), prefixPills: document.getElementById("dfold-prefix-pills"), info: document.getElementById("dfold-info"), mrna: document.getElementById("dfold-mrna"), aa: document.getElementById("dfold-aa"), aaLabel: document.getElementById("dfold-aa-label"), refAa: document.getElementById("dfold-ref-aa"), refAaLabel: document.getElementById("dfold-ref-aa-label"), go: document.getElementById("dfold-go"), status: document.getElementById("dfold-status"), statusText: document.querySelector("#dfold-status span:last-child"), vCarbon: document.getElementById("dfold-viewer-carbon"), vRef: document.getElementById("dfold-viewer-ref"), nRes: document.getElementById("dfold-n"), plddtC: document.getElementById("dfold-plddt-c"), plddtR: document.getElementById("dfold-plddt-r"), identity: document.getElementById("dfold-id"), };
// No-ops gracefully when the status indicator isn't rendered (current // cached-only UI doesn't ship one). All call sites are kept so the // live-fold path stays a drop-in restore. function setStatus(text, cls) { if (!els.status) return; els.status.className = "status" + (cls ? " " + cls : ""); if (els.statusText) els.statusText.textContent = text; }
function renderInfo(extra = "") { const g = GENES_LOCAL?.find(x => x.symbol === currentGeneSymbol); if (!g) { els.info.textContent = "—"; return; } const blurb = g.blurb ? ` · ${g.blurb}` : ""; els.info.innerHTML = `<strong>${g.symbol}</strong> · ${g.length.toLocaleString("en-US")} bp${blurb}` + (extra ? ` · ${extra}` : ""); }
// Render the "DNA → mRNA → protein" progression for the current gene // by reusing the same splicing + ORF logic the rest of the pipeline // runs on the reference side. The numbers shown are gene-intrinsic // (architecture of the gene + canonical reference protein), so they // hold whether the user has clicked fold yet or not — they materialise // the splicing step that's otherwise invisible between the toolbar // and the AA block. // // Prefix is "reference:" because every number here comes from the canonical // sequence in genes.json, NOT from Carbon's prediction. Without the prefix // it's easy to read the strip, scroll past it, and assume the AA block // below shows that same length — but Carbon's ORF is usually shorter // (e.g. HBB ref 147 aa vs Carbon 131 aa). function renderMRNAInfo() { const g = GENES_LOCAL?.find(x => x.symbol === currentGeneSymbol); if (!g) { els.mrna.textContent = "—"; return; } const mrna = spliceExons(g.seq, g.exons); const orf = findLongestORF(mrna, 30); const genomicBP = g.length; const mrnaBP = mrna.length; const nExons = g.exons.length; if (!orf) { els.mrna.innerHTML = `<strong>${genomicBP.toLocaleString("en-US")} bp</strong> genomic` + ` · <strong>${nExons}</strong> exon${nExons === 1 ? "" : "s"}` + ` <span class="arrow">→</span> <strong>${mrnaBP.toLocaleString("en-US")} bp</strong> mRNA` + ` <span class="arrow">→</span> no ORF ≥30 aa`; return; } const trunc = orf.truncated ? `<span class="mrna-trunc">truncated · no stop codon</span>` : ""; els.mrna.innerHTML = `<strong>${genomicBP.toLocaleString("en-US")} bp</strong> genomic` + ` · <strong>${nExons}</strong> exon${nExons === 1 ? "" : "s"}` + ` <span class="arrow">→</span> <strong>${mrnaBP.toLocaleString("en-US")} bp</strong> mRNA` + ` <span class="arrow">→</span> <strong>${orf.aa.length} aa</strong>` + ` from ATG @ ${orf.startBP + 1}${trunc}`; }
// Render Carbon's translated protein AND the reference protein side by // side, with mismatches highlighted in red on both rows so the visitor // can read the divergence in either direction. Mirrors §1's two-row // model-output / reference layout so the visual grammar carries over. // // Length asymmetry handling: // - When Carbon's ORF is shorter than the reference (typical case), // positions past Carbon's end are highlighted on the reference row // only — they materialise "Carbon stopped early". // - When Carbon's ORF is longer than the reference (rarer), positions // past the reference's end are highlighted on Carbon's row — they // materialise "Carbon kept reading past the real stop codon". function renderAAComparison(carbonAA, refAA) { const nC = carbonAA.length; const nR = refAA.length;
// Carbon row: render every position of carbon, highlight when c[i] != r[i] // (or when ref ran out at i — extra Carbon residue). const cParts = new Array(nC); for (let i = 0; i < nC; i++) { const c = carbonAA[i], r = refAA[i]; cParts[i] = (r === undefined || c !== r) ? `<span class="ref-mismatch">${c}</span>` : c; } // Reference row: symmetric — render every position of ref, highlight // when r[i] != c[i] (or when carbon ran out — Carbon stopped early). const rParts = new Array(nR); for (let i = 0; i < nR; i++) { const r = refAA[i], c = carbonAA[i]; rParts[i] = (c === undefined || r !== c) ? `<span class="ref-mismatch">${r}</span>` : r; } // Soft-wrap at 40 chars — the two columns are narrower than §1's // single-column block, so a tighter wrap keeps lines from spilling // and lets the eye scan Carbon ↔ Reference at the same y position. const wrap = parts => { let out = ""; for (let i = 0; i < parts.length; i += 40) out += parts.slice(i, i + 40).join("") + "\n"; return out; }; els.aa.innerHTML = wrap(cParts); els.refAa.innerHTML = wrap(rParts);
// Length-aware labels — the visitor sees that 131 ≠ 147 at a glance and // doesn't have to cross-reference with the stat row at the bottom. const lenTag = (n, prefix) => `<span class="aa-len-tag">${prefix}${n} aa</span>`; const mismatches = (() => { const k = Math.min(nC, nR); let m = 0; for (let i = 0; i < k; i++) if (carbonAA[i] !== refAA[i]) m++; return m; })(); els.aaLabel.innerHTML = `<span class="seq-tag carbon">carbon</span>` + lenTag(nC, "") + `<span class="seq-label-stat">· ${mismatches} mismatches</span>`; els.refAaLabel.innerHTML = `<span class="seq-tag ref">reference</span>` + lenTag(nR, ""); }
// Hydrate the viewers and stat row from a precomputed `fold_example` // shipped in genes.json by scripts/precompute.py. Avoids a cold-start // round-trip to the inference endpoints on first paint; the visitor // can still trigger a fresh run with the ▶ fold button. function hydrateFoldExample(ex) { if (!ensureViewers()) return false; setPending(false); // clear any leftover "fixture pending" state renderStructure(viewerCarbon, ex.carbon_pdb); renderStructure(viewerRef, ex.ref_pdb); els.nRes.textContent = `${ex.carbon_aa.length} / ${ex.ref_aa.length}`; els.plddtC.textContent = (ex.carbon_plddt_mean ?? 0).toFixed(1); els.plddtR.textContent = (ex.ref_plddt_mean ?? 0).toFixed(1); els.identity.textContent = (ex.identity_1d * 100).toFixed(1) + "%"; for (const el of [els.nRes, els.plddtC, els.plddtR, els.identity]) { el.classList.remove("muted"); } renderAAComparison(ex.carbon_aa, ex.ref_aa); setStatus("cached example", ""); return true; }
// Used when a gene has no precomputed fold_example. In the shipped // cached-only build this happens for genes whose fixture is still // queued for precompute (e.g. when the Carbon HF endpoint was in // error during the last `python scripts/precompute.py --folds` run). // We surface that state explicitly via an overlay on both viewers so // it doesn't read as a bug. function resetFoldUI() { els.aa.innerHTML = "— fixture pending · precompute hasn't run yet for this gene —"; for (const el of [els.nRes, els.plddtC, els.plddtR, els.identity]) { el.textContent = "—"; el.classList.add("muted"); } if (viewerCarbon) { viewerCarbon.removeAllModels(); viewerCarbon.render(); } if (viewerRef) { viewerRef.removeAllModels(); viewerRef.render(); } if (ensureViewers()) setPending(true, "fixture pending"); }
function selectGene(symbol) { currentGeneSymbol = symbol; els.pills.querySelectorAll(".pill").forEach(p => p.classList.toggle("active", p.dataset.gene === symbol) ); renderInfo(); renderMRNAInfo(); const g = GENES_LOCAL?.find(x => x.symbol === symbol); if (g?.fold_example) { // 3Dmol might not be loaded on the very first paint; retry shortly. if (!hydrateFoldExample(g.fold_example)) { setTimeout(() => hydrateFoldExample(g.fold_example), 300); } } else { setStatus("idle", ""); resetFoldUI(); } }
// No-ops in the cached-only build — the prefix selector isn't rendered. // Kept here so re-adding the .pills element in the toolbar wires it // back up without a JS change. function bindPrefixPills() { if (!els.prefixPills) return; els.prefixPills.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => { prefixLen = +p.dataset.prefix; els.prefixPills.querySelectorAll(".pill").forEach(x => x.classList.remove("active")); p.classList.add("active"); }); }); }
async function postFold(sequence) { const resp = await fetch("/fold", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sequence }), }); return resp.json(); }
function makeViewer(host) { if (!window.$3Dmol) return null; host.innerHTML = ""; const v = $3Dmol.createViewer(host, { backgroundColor: "#fafaf7", antialias: true }); // 3Dmol installs a wheel listener on its internal canvas that zooms // the camera AND preventDefaults the page scroll. We only want orbit // controls; scroll should keep scrolling the page. Intercept wheel // events at the host in capture phase and stopImmediatePropagation // so 3Dmol never sees them. No preventDefault → browser scroll runs. // We also use this hook to bump the idle-rotation timer below so // ambient spin pauses the instant the visitor touches a viewer. host.addEventListener("wheel", (e) => { e.stopImmediatePropagation(); bumpInteraction(); }, { capture: true, passive: true }); for (const ev of ["pointerdown", "touchstart"]) { host.addEventListener(ev, bumpInteraction, { capture: true, passive: true }); } return v; }
// ── Idle auto-rotation ──────────────────────────────────────────── // Gentle constant-velocity Y-spin while the visitor isn't interacting, // to give the side-by-side comparison some life without forcing them // to drag every time. Any pointer/wheel input pauses immediately; // after IDLE_DELAY_MS of silence we ramp the spin back in over RAMP_MS // with an ease-in-out so the resume isn't jarring. We rotate only // viewerCarbon — linkViewer mirrors it onto viewerRef in the same // frame, so the two cartoons stay perfectly in sync. const IDLE_ROT_DELAY_MS = 2500; const IDLE_ROT_RAMP_MS = 900; const IDLE_ROT_MAX_DPS = 1; // ~one revolution per minute const PREFERS_REDUCED_MOTION = window.matchMedia ? window.matchMedia("(prefers-reduced-motion: reduce)").matches : false; let lastInteractionAt = performance.now(); let idleRotRAF = 0; let idleRotLastT = 0; let idleRotSectionVisible = true; function bumpInteraction() { lastInteractionAt = performance.now(); } function idleRotStep(now) { idleRotRAF = 0; if (!viewerCarbon || !viewerRef) return; const dt = idleRotLastT ? Math.min(100, now - idleRotLastT) : 16; idleRotLastT = now; const idle = now - lastInteractionAt; if (idle >= IDLE_ROT_DELAY_MS && idleRotSectionVisible && !PREFERS_REDUCED_MOTION) { const k = Math.min(1, (idle - IDLE_ROT_DELAY_MS) / IDLE_ROT_RAMP_MS); const eased = k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2; const deg = IDLE_ROT_MAX_DPS * eased * (dt / 1000); if (deg > 0) viewerCarbon.rotate(deg, "y", 0, false); } idleRotRAF = requestAnimationFrame(idleRotStep); } function startIdleRotation() { if (idleRotRAF || PREFERS_REDUCED_MOTION) return; idleRotLastT = 0; idleRotRAF = requestAnimationFrame(idleRotStep); }
// Pause the rAF loop when the §5 section is offscreen — no point // burning frames on cartoons the visitor can't see. function watchFoldingVisibility() { const section = document.getElementById("folding"); if (!section || !window.IntersectionObserver) return; new IntersectionObserver((entries) => { for (const e of entries) idleRotSectionVisible = e.isIntersecting; }, { threshold: 0.01 }).observe(section); } watchFoldingVisibility();
// Create both viewers (idempotent) and link them so an orbit drag on // one propagates to the other. Mirrors the side-by-side "synced // cameras" setup PyMOL/ChimeraX use for structure comparison — the // visitor sees the same orientation of both proteins, which is what // makes the visual comparison meaningful. (Wheel zoom is intentionally // disabled in makeViewer so scroll keeps scrolling the page.) let viewersLinked = false; function ensureViewers() { if (!window.$3Dmol) return false; if (!viewerCarbon) { viewerCarbon = makeViewer(els.vCarbon); attachOverlay(els.vCarbon); } if (!viewerRef) { viewerRef = makeViewer(els.vRef); attachOverlay(els.vRef); } if (!viewersLinked && viewerCarbon && viewerRef && typeof viewerCarbon.linkViewer === "function") { viewerCarbon.linkViewer(viewerRef); viewerRef.linkViewer(viewerCarbon); viewersLinked = true; } startIdleRotation(); return !!(viewerCarbon && viewerRef); }
// Inject the "running" overlay once per viewer host. CSS keeps it // hidden until the host gets the .running class via setRunning(). function attachOverlay(host) { if (host.querySelector(".fold-overlay")) return; const o = document.createElement("div"); o.className = "fold-overlay"; o.innerHTML = '<span class="dot"></span><span class="fold-overlay-label">computing</span>'; host.appendChild(o); }
// Toggle the running state on both viewers + the stat row. The cached // cartoon stays underneath at low opacity so the visitor still has // visual context while waiting (vs blanking everything to a spinner). function setRunning(running, label = "computing") { for (const host of [els.vCarbon, els.vRef]) { host.classList.toggle("running", running); if (running) { const t = host.querySelector(".fold-overlay-label"); if (t) t.textContent = label; } } for (const el of [els.nRes, els.plddtC, els.plddtR, els.identity]) { el.classList.toggle("muted", running); } if (els.go) els.go.textContent = running ? "running…" : "▶ fold"; }
// Mirror of setRunning for the "fixture not ready" state. Reuses the // same overlay markup but a different CSS class, so the two states // can never visually conflict. function setPending(pending, label = "fixture pending") { for (const host of [els.vCarbon, els.vRef]) { host.classList.toggle("pending", pending); if (pending) { const t = host.querySelector(".fold-overlay-label"); if (t) t.textContent = label; } } }
// Editorial pLDDT palette. The three anchor colours match the legend // bar under the viewers (#b00020 demo-red / #f0e8e0 paper-beige / // #2c5aa0 demo-blue) — same tones used throughout §1 mismatches and // §2 base coloring, so the cartoons land in the same visual world as // the rest of the page instead of 3Dmol's stock primary rwb. const PLDDT_STOPS = [ { v: 50, rgb: [0xb0, 0x00, 0x20] }, { v: 75, rgb: [0xf0, 0xe8, 0xe0] }, { v: 100, rgb: [0x2c, 0x5a, 0xa0] }, ]; function plddtToColor(plddt) { const x = Math.max(PLDDT_STOPS[0].v, Math.min(PLDDT_STOPS[PLDDT_STOPS.length - 1].v, plddt)); for (let i = 0; i < PLDDT_STOPS.length - 1; i++) { const a = PLDDT_STOPS[i], b = PLDDT_STOPS[i + 1]; if (x >= a.v && x <= b.v) { const k = (x - a.v) / (b.v - a.v); const r = Math.round(a.rgb[0] + (b.rgb[0] - a.rgb[0]) * k); const g = Math.round(a.rgb[1] + (b.rgb[1] - a.rgb[1]) * k); const bl = Math.round(a.rgb[2] + (b.rgb[2] - a.rgb[2]) * k); return (r << 16) | (g << 8) | bl; } } return 0x888888; }
function renderStructure(viewer, pdb) { if (!viewer) return; viewer.removeAllModels(); viewer.addModel(pdb, "pdb"); // Slightly thinner ribbons + softer arrows than the 3Dmol defaults // to better match the demo's "editorial diagram" feel rather than a // textbook figure. colorfunc reads pLDDT from the PDB B-factor column. viewer.setStyle({}, { cartoon: { colorfunc: (atom) => plddtToColor(atom.b || 50), thickness: 0.5, arrows: true, tubes: false, opacity: 0.95, }, }); viewer.zoomTo(); viewer.render(); // No spin — the linked viewers share the camera, so a manual drag // by the visitor rotates both at once. Two independent spin loops // would desynchronise the cartoons visually. }
async function runFold() { if (!window.$3Dmol) { setStatus("3Dmol not loaded — retry in a sec", "error"); return; } const gene = GENES_LOCAL?.find(g => g.symbol === currentGeneSymbol); if (!gene) return;
// Bail early on genes whose introns push the last exon past our live- // demo budget. The pipeline would otherwise spend minutes generating // intronic filler that gets spliced out anyway. const f = geneFeasibility(gene); if (!f.feasible) { setStatus( `${gene.symbol} spans ${f.lastExonEnd.toLocaleString("en-US")} bp of genomic DNA — ` + `outside what Carbon can generate live. Try HBB or INS.`, "error" ); return; }
abortCtrl?.abort(); abortCtrl = new AbortController(); if (els.go) els.go.disabled = true; ensureViewers(); // overlay must exist before we toggle .running on it
try { // --- Reference: spliced mRNA → longest ORF → AA ------------------- const refORF = translateReference(gene); if (!refORF) throw new Error(`reference ${gene.symbol} has no valid ORF`);
// --- Carbon: prompt → /generate → splice → ORF → AA --------------- // We ask Carbon to extend the prompt far enough to cover the gene's // last exon. Then we apply the SAME exon coordinates as the reference // to assemble a mature mRNA from Carbon's output. Without this splice // step the Carbon side reads through introns and produces nonsense // that has nothing to do with the model's actual coding-region skill. const promptDNA = gene.seq.slice(0, prefixLen).toUpperCase().replace(/[^ACGT]/g, ""); const targetBP = f.lastExonEnd; const genBP = Math.max(0, targetBP - prefixLen) + 60; // 60-bp safety margin const maxTokens = Math.ceil(genBP / 6) + 8;
setRunning(true, `generating · ${targetBP} bp`); setStatus(`carbon generating (${prefixLen}→${targetBP} bp)…`, "streaming"); const continuation = await streamGenerate(promptDNA, maxTokens, 0.7, abortCtrl.signal); const carbonDNA = (promptDNA + continuation).slice(0, prefixLen + genBP); const carbonMRNA = spliceExons(carbonDNA, gene.exons); const carbonORF = findLongestORF(carbonMRNA, 30); if (!carbonORF) { throw new Error( "Carbon's spliced mRNA didn't yield an ORF ≥30 aa — likely a premature stop in an early exon" ); }
// --- Fold both in parallel ---------------------------------------- setRunning(true, "folding · esmfold"); setStatus("folding both…", "streaming"); const [carbonR, refR] = await Promise.all([ postFold(carbonORF.aa), postFold(refORF.aa), ]); if (carbonR.error) throw new Error("carbon fold: " + carbonR.error); if (refR.error) throw new Error("ref fold: " + refR.error);
// --- Render ------------------------------------------------------- renderStructure(viewerCarbon, carbonR.pdb); renderStructure(viewerRef, refR.pdb);
const idn = identity1D(carbonORF.aa, refORF.aa); els.nRes.textContent = `${carbonORF.aa.length} / ${refORF.aa.length}`; els.plddtC.textContent = (carbonR.plddt_mean ?? 0).toFixed(1); els.plddtR.textContent = (refR.plddt_mean ?? 0).toFixed(1); els.identity.textContent = (idn * 100).toFixed(1) + "%"; for (const el of [els.nRes, els.plddtC, els.plddtR, els.identity]) { el.classList.remove("muted"); }
renderAAComparison(carbonORF.aa, refORF.aa);
const cacheTag = (carbonR.cached || refR.cached) ? " (cache hit)" : ""; setStatus("done" + cacheTag, ""); } catch (e) { if (e.name === "AbortError") setStatus("aborted", ""); else setStatus("error: " + (e.message || e), "error"); } finally { setRunning(false); abortCtrl = null; if (els.go) els.go.disabled = false; } }
// --- Bootstrap --------------------------------------------------------- loadGenes().then(genes => { GENES_LOCAL = genes; els.pills.innerHTML = genes.map((g, i) => `<button class="pill${i === 0 ? " active" : ""}" data-gene="${g.symbol}">${g.symbol}</button>` ).join(""); els.pills.querySelectorAll(".pill").forEach(p => p.addEventListener("click", () => selectGene(p.dataset.gene)) ); selectGene(genes[0].symbol); bindPrefixPills(); els.go?.addEventListener("click", runFold); }).catch(e => { els.info.textContent = "failed to load genes: " + (e.message || e); });})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163// =========================================================================// §8 — Training objective: CE vs FNS// =========================================================================(function initDemo8() { const targetPills = document.getElementById("d8-target-pills"); const modePills = document.getElementById("d8-mode-pills"); const canvas = document.getElementById("d8-canvas"); const schedule = document.getElementById("d8-schedule");
let target = "TATATA"; let mode = "ce";
// Stable candidate set per target (target itself + near-misses + far-miss + unrelated) function candidatesFor(t) { // Generate near-misses: flip one base at each of a few positions const flip = (s, i, b) => s.slice(0,i) + b + s.slice(i+1); const t1 = flip(t, 5, t[5] === "A" ? "T" : "A"); // last base flipped const t2 = flip(flip(t, 4, t[4] === "A" ? "G" : "A"), 5, t[5] === "A" ? "G" : "A"); // 2 flipped const t3 = flip(flip(flip(t, 0, t[0] === "A" ? "C" : "A"), 2, t[2] === "T" ? "G" : "T"), 4, t[4] === "A" ? "C" : "A"); // 3 flipped const tFar = "CGCGCG"; // mostly different const candidates = [t, t1, t2, t3, tFar]; return [...new Set(candidates)].slice(0, 5); }
function nMatches(a, b) { let n = 0; for (let i = 0; i < 6; i++) if (a[i] === b[i]) n++; return n; }
function ceCredit(c, t) { return c === t ? 1.0 : 0.0; // all-or-nothing } function fnsCredit(c, t) { return nMatches(c, t) / 6.0; // fraction of bases matching }
function render() { const cands = candidatesFor(target); let html = ""; html += `<div style="display:grid;grid-template-columns:140px 1fr 1fr;gap:8px 14px;align-items:center;font-family:'JetBrains Mono',monospace;font-size:11px">`; // Header html += `<div></div>`; html += `<div style="font-size:9px;color:${mode==='fns'?'#aaa':'#1f1f1d'};text-transform:uppercase;letter-spacing:1.5px">${mode==='fns'?'cross-entropy':'cross-entropy'} <span style="font-weight:500">${mode==='ce'||mode==='both'?'· active':''}</span></div>`; html += `<div style="font-size:9px;color:${mode==='ce'?'#aaa':'#1f1f1d'};text-transform:uppercase;letter-spacing:1.5px">FNS <span style="font-weight:500">${mode==='fns'||mode==='both'?'· active':''}</span></div>`;
cands.forEach(c => { const isTarget = c === t1Equal(c, target); // Highlight matching positions let badges = ""; for (let i = 0; i < 6; i++) { const match = c[i] === target[i]; const color = match ? "#317f3f" : "#bc2e25"; const bg = match ? "rgba(49,127,63,0.10)" : "rgba(188,46,37,0.08)"; badges += `<span style="display:inline-block;background:${bg};color:${color};padding:2px 5px;margin:1px;border-radius:2px;font-weight:${match?500:400}">${c[i]}</span>`; } const isExact = c === target; const labelText = isExact ? "exact target" : `${nMatches(c, target)}/6 match`; html += `<div style="display:flex;flex-direction:column;gap:2px"> <div>${badges}</div> <div style="font-size:9px;color:${isExact?'#317f3f':'#888'};letter-spacing:1px;text-transform:uppercase;padding-left:4px">${labelText}</div> </div>`;
// CE column const ceVal = ceCredit(c, target); html += creditCell(ceVal, mode === "fns", c === target ? "credit = 1" : "credit = 0", "#317f3f", "#bc2e25");
// FNS column const fnsVal = fnsCredit(c, target); const fnsLabel = c === target ? "credit = 1" : `credit = ${fnsVal.toFixed(2)} (${nMatches(c, target)}/6)`; html += creditCell(fnsVal, mode === "ce", fnsLabel, "#317f3f", "#bc2e25"); }); html += `</div>`; canvas.innerHTML = html;
renderSchedule(); }
function t1Equal(a, b) { return a; } // helper kept for symmetry
function creditCell(value, dimmed, label, posColor, negColor) { // value in [0, 1]; render as a horizontal bar const w = (value * 100).toFixed(0); const opacity = dimmed ? 0.25 : 1; const barColor = value === 0 ? negColor : (value < 1 ? "#888" : posColor); return `<div style="opacity:${opacity}"> <div style="position:relative;height:10px;background:#f0f0f0;border-radius:2px;overflow:hidden"> <div style="position:absolute;inset:0 auto 0 0;width:${w}%;background:${barColor}"></div> </div> <div style="font-size:9px;color:#888;margin-top:3px;letter-spacing:0.5px">${label}</div> </div>`; }
function renderSchedule() { const W = 1000, H = 110, padL = 24, padR = 24, padT = 14, padB = 28; const innerW = W - padL - padR; const switchAt = 0.65; // where CE→FNS switch happens const switchX = padL + innerW * switchAt; let svg = "";
// Background two-tone (CE phase + FNS phase) svg += `<rect x="${padL}" y="${padT}" width="${(switchX - padL).toFixed(1)}" height="${H - padT - padB}" fill="#1f1f1d" opacity="0.04"/>`; svg += `<rect x="${switchX.toFixed(1)}" y="${padT}" width="${(W - padR - switchX).toFixed(1)}" height="${H - padT - padB}" fill="#317f3f" opacity="0.06"/>`;
// Mock loss curve: smooth descent then a "staircase" that gets cleaned by the FNS switch const points = []; const N = 200; for (let i = 0; i <= N; i++) { const x = padL + (i / N) * innerW; const t = i / N; let lp; if (t < switchAt) { // Smooth-ish descent, with a small wobble approaching switch lp = 4.0 * Math.exp(-3.5 * t) + 1.2 + 0.04 * Math.sin(t * 30); if (t > switchAt - 0.08) lp += 0.5 * (t - (switchAt - 0.08)) / 0.08; // staircase climb } else { // After switch, smooth continued descent const dt = t - switchAt; lp = 1.4 + 0.7 * Math.exp(-6 * dt); } const y = padT + (1 - (lp - 1.0) / 4.0) * (H - padT - padB); points.push([x, y]); } let d = ""; points.forEach(([x, y], i) => { d += (i === 0 ? "M" : "L") + x.toFixed(1) + " " + y.toFixed(1); }); svg += `<path d="${d}" fill="none" stroke="#1f1f1d" stroke-width="1.4"/>`;
// Switch marker svg += `<line x1="${switchX.toFixed(1)}" y1="${padT}" x2="${switchX.toFixed(1)}" y2="${H - padB}" stroke="#317f3f" stroke-width="1.5" stroke-dasharray="3,3"/>`; svg += `<text x="${switchX.toFixed(1)}" y="${(padT - 4)}" font-family="JetBrains Mono" font-size="9" fill="#317f3f" text-anchor="middle" letter-spacing="1">CE → FNS</text>`;
// Phase labels svg += `<text x="${(padL + (switchX - padL) / 2).toFixed(1)}" y="${(H - padB + 14).toFixed(1)}" font-family="JetBrains Mono" font-size="10" fill="#666" text-anchor="middle" letter-spacing="1">CROSS-ENTROPY · learn joint structure</text>`; svg += `<text x="${(switchX + (W - padR - switchX) / 2).toFixed(1)}" y="${(H - padB + 14).toFixed(1)}" font-family="JetBrains Mono" font-size="10" fill="#317f3f" text-anchor="middle" letter-spacing="1">FNS · smooth, BF16-stable refinement</text>`; // y-axis label svg += `<text x="${padL}" y="${(padT - 4)}" font-family="JetBrains Mono" font-size="9" fill="#aaa" letter-spacing="0.5">training loss</text>`; // staircase callout const staircaseX = padL + innerW * (switchAt - 0.04); svg += `<text x="${staircaseX.toFixed(1)}" y="${(H - padB - 4).toFixed(1)}" font-family="JetBrains Mono" font-size="9" fill="#bc2e25" text-anchor="end">↑ staircase</text>`;
schedule.innerHTML = svg; }
// Bind targetPills.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => { targetPills.querySelectorAll(".pill").forEach(x => x.classList.remove("active")); p.classList.add("active"); target = p.dataset.target; render(); }); }); modePills.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => { modePills.querySelectorAll(".pill").forEach(x => x.classList.remove("active")); p.classList.add("active"); mode = p.dataset.mode; render(); }); }); render();})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465// =========================================================================// Sandbox (tab 3) — DNA continuation playground// =========================================================================(function initSandbox() { const els = { prompt: document.getElementById("sb-prompt"), maxTokens: document.getElementById("sb-max-tokens"), temperature: document.getElementById("sb-temperature"), topP: document.getElementById("sb-top-p"), generate: document.getElementById("sb-generate-btn"), stop: document.getElementById("sb-stop-btn"), clear: document.getElementById("sb-clear-btn"), modeBtns: document.getElementById("sb-mode-btns"), copy: document.getElementById("sb-copy-btn"), seq: document.getElementById("sb-seq"), meta: document.getElementById("sb-meta"), status: document.getElementById("sb-status"), statusText: document.getElementById("sb-status-text"), legend: document.getElementById("sb-legend"), statPrompt: document.getElementById("sb-stat-prompt"), statGen: document.getElementById("sb-stat-gen"), statTok: document.getElementById("sb-stat-tok"), statTime: document.getElementById("sb-stat-time"), statRate: document.getElementById("sb-stat-rate"), statGc: document.getElementById("sb-stat-gc"), statLp: document.getElementById("sb-stat-lp"), statPpl: document.getElementById("sb-stat-ppl"), };
const BASE_RGB = { A: [58, 138, 62], C: [46, 107, 184], G: [181, 137, 30], T: [181, 58, 58], N: [136, 136, 136], }; const PROMPT_RGB_S = [170, 170, 170]; const DARK_RGB_S = [31, 31, 29]; const MID_RGB_S = [136, 136, 136]; const RED_RGB_S = [188, 46, 37]; const BG_ALPHA = 0.12;
let promptBases = ""; let genText = ""; let genTokens = []; let genTokenAtBase = []; let abortCtrl = null; let startTime = 0; let timer = null; let colorMode = "none"; let charMetrics = null; let lpRange = null;
function recomputeLpRange() { if (!genTokens.length) { lpRange = null; updateLegend(); return; } let min = Infinity, max = -Infinity, sum = 0, n = 0; for (const t of genTokens) { if (t.logprob == null || isNaN(t.logprob)) continue; if (t.logprob < min) min = t.logprob; if (t.logprob > max) max = t.logprob; sum += t.logprob; n++; } lpRange = n ? { min, mid: sum / n, max } : null; updateLegend(); } function updateLegend() { const minEl = document.getElementById("sb-lp-min"); const midEl = document.getElementById("sb-lp-mid"); const maxEl = document.getElementById("sb-lp-max"); const bar = document.getElementById("sb-legend-bar"); if (!lpRange) { minEl.textContent = midEl.textContent = maxEl.textContent = "—"; bar.style.background = "linear-gradient(to right, #bc2e25, #888, #1f1f1d)"; } else { const { min, mid, max } = lpRange; minEl.textContent = min.toFixed(1); midEl.textContent = mid.toFixed(1); maxEl.textContent = max.toFixed(1); const midPct = max > min ? ((mid - min) / (max - min)) * 100 : 50; bar.style.background = `linear-gradient(to right, #bc2e25 0%, #888 ${midPct.toFixed(1)}%, #1f1f1d 100%)`; } updateLpChart(); } function updateLpChart() { const svg = document.getElementById("sb-lp-chart"); if (!svg) return; if (!lpRange || genTokens.length < 2) { svg.innerHTML = ""; return; } const W = 200, H = 40, pad = 2; const { min, max } = lpRange; const yTop = pad, yBot = H - pad; const yScale = (lp) => yTop + (1 - (lp - min) / Math.max(1e-9, max - min)) * (yBot - yTop); const n = genTokens.length; const target = 1000; let step = 1; while (Math.ceil(n / step) > target) step *= 2; const xScale = (i) => (n === 1 ? W / 2 : pad + (i / (n - 1)) * (W - 2 * pad)); let d = ""; let started = false; for (let i = 0; i < n; i += step) { const lp = genTokens[i].logprob; if (lp == null || isNaN(lp)) continue; d += (started ? "L" : "M") + xScale(i).toFixed(1) + " " + yScale(lp).toFixed(1); started = true; } if ((n - 1) % step !== 0) { const lp = genTokens[n - 1].logprob; if (lp != null && !isNaN(lp)) { d += "L" + xScale(n - 1).toFixed(1) + " " + yScale(lp).toFixed(1); } } const midPct = max > min ? ((lpRange.mid - min) / (max - min)) * 100 : 50; svg.setAttribute("viewBox", `0 0 ${W} ${H}`); svg.innerHTML = ` <defs> <linearGradient id="sb-lp-grad" gradientUnits="userSpaceOnUse" x1="0" y1="${H - pad}" x2="0" y2="${pad}"> <stop offset="0%" stop-color="#bc2e25"/> <stop offset="${midPct.toFixed(1)}%" stop-color="#888"/> <stop offset="100%" stop-color="#1f1f1d"/> </linearGradient> </defs> <path d="${d}" fill="none" stroke="url(#sb-lp-grad)" stroke-width="1.2" stroke-linejoin="round" stroke-linecap="round"/> `; } function logprobRgbSb(lp) { if (lp == null || isNaN(lp) || !lpRange) return DARK_RGB_S; const { min, mid, max } = lpRange; if (max === min) return MID_RGB_S; if (lp >= mid) { const denom = max - mid; const t = denom > 0 ? Math.min(1, Math.max(0, (max - lp) / denom)) : 0; return lerpRgb(DARK_RGB_S, MID_RGB_S, t); } const denom = mid - min; const t = denom > 0 ? Math.min(1, Math.max(0, (mid - lp) / denom)) : 0; return lerpRgb(MID_RGB_S, RED_RGB_S, t); }
function autoGrow() { els.prompt.style.height = "auto"; els.prompt.style.height = els.prompt.scrollHeight + "px"; } function cleanPrompt(s) { return s.toUpperCase().replace(/[^ACGTN]/g, ""); }
els.prompt.addEventListener("input", () => { const cleaned = cleanPrompt(els.prompt.value); if (cleaned !== els.prompt.value) { const pos = els.prompt.selectionStart; els.prompt.value = cleaned; els.prompt.setSelectionRange(pos, pos); } autoGrow(); });
function rgbForBase(absIdx, base) { if (absIdx < promptBases.length) return PROMPT_RGB_S; if (colorMode === "bases") return BASE_RGB[base] || DARK_RGB_S; if (colorMode === "logprob") { const genIdx = absIdx - promptBases.length; const tok = genTokens[genTokenAtBase[genIdx]]; return tok ? logprobRgbSb(tok.logprob) : DARK_RGB_S; } return DARK_RGB_S; } function measureSeqChars() { const probe = document.createElement("div"); probe.style.cssText = "position:absolute;visibility:hidden;top:-9999px;font-family:'JetBrains Mono',monospace;font-size:12px;font-weight:400;letter-spacing:1.5px;white-space:pre"; probe.textContent = " 1 "; document.body.appendChild(probe); const prefixW = probe.getBoundingClientRect().width; probe.textContent = "AAAAAAAAAA "; const blockW = probe.getBoundingClientRect().width; document.body.removeChild(probe); charMetrics = { prefixW, blockW }; } function basesPerLineSb() { if (!charMetrics) measureSeqChars(); const cs = getComputedStyle(els.seq); const padL = parseFloat(cs.paddingLeft) || 0; const padR = parseFloat(cs.paddingRight) || 0; const contentW = els.seq.clientWidth - padL - padR; if (contentW <= 0 || !charMetrics.blockW) return 60; const blocks = Math.floor((contentW - charMetrics.prefixW) / charMetrics.blockW); return Math.max(10, Math.min(blocks, 30) * 10); } function colorKey(absIdx, base) { if (absIdx < promptBases.length) return "p"; if (colorMode === "none") return "g"; if (colorMode === "bases") return "b" + base; if (colorMode === "logprob") return "t" + genTokenAtBase[absIdx - promptBases.length]; return "g"; } function buildLineHTML(start, lineBases) { const pos = String(start + 1).padStart(5, " "); let html = `<span class="sb-pos">${pos}</span> `; let j = 0; while (j < lineBases.length) { if (j > 0 && j % 10 === 0) html += " "; const startAbs = start + j; const startKey = colorKey(startAbs, lineBases[j]); const blockEnd = Math.min(lineBases.length, Math.floor(j / 10) * 10 + 10); let runEnd = j + 1; while (runEnd < blockEnd && colorKey(start + runEnd, lineBases[runEnd]) === startKey) runEnd++; const runText = lineBases.slice(j, runEnd); const [r, g, b] = rgbForBase(startAbs, lineBases[j]); const tinted = colorMode !== "none" && startAbs >= promptBases.length; const bg = tinted ? `;background:rgba(${r},${g},${b},${BG_ALPHA})` : ""; html += `<span style="color:rgb(${r},${g},${b})${bg}">${runText}</span>`; j = runEnd; } return html; } function updateTail() { const prev = els.seq.querySelector(".sb-seq-line.tail"); if (prev) prev.classList.remove("tail"); const last = els.seq.lastElementChild; if (abortCtrl && last && last.classList.contains("sb-seq-line")) last.classList.add("tail"); } function lpRangeShifted(prev, curr) { if (!prev || !curr) return prev !== curr; const range = Math.max(0.1, prev.max - prev.min); const tol = Math.max(0.2, range * 0.05); return Math.abs(prev.min - curr.min) > tol || Math.abs(prev.mid - curr.mid) > tol || Math.abs(prev.max - curr.max) > tol; } let lastRenderedMode = null; let lastRenderedBpl = null; let lastRenderedLpRange = null; function fullRender(bpl) { const total = promptBases + genText; if (!total) { els.seq.classList.add("empty"); els.seq.textContent = "prompt + generated bases will stream here"; } else { els.seq.classList.remove("empty"); const parts = []; for (let i = 0; i < total.length; i += bpl) { parts.push(`<div class="sb-seq-line">${buildLineHTML(i, total.slice(i, i + bpl))}</div>`); } els.seq.innerHTML = parts.join(""); } lastRenderedMode = colorMode; lastRenderedBpl = bpl; lastRenderedLpRange = lpRange ? { ...lpRange } : null; updateTail(); } function incrementalRender(bpl) { const total = promptBases + genText; const totalLines = Math.ceil(total.length / bpl); const lineDivs = els.seq.children; if (lineDivs.length > 0) { const lastIdx = lineDivs.length - 1; const start = lastIdx * bpl; lineDivs[lastIdx].innerHTML = buildLineHTML(start, total.slice(start, start + bpl)); } if (totalLines > lineDivs.length) { const parts = []; for (let li = lineDivs.length; li < totalLines; li++) { const start = li * bpl; parts.push(`<div class="sb-seq-line">${buildLineHTML(start, total.slice(start, start + bpl))}</div>`); } els.seq.insertAdjacentHTML("beforeend", parts.join("")); } lastRenderedLpRange = lpRange ? { ...lpRange } : null; updateTail(); } function renderSequence() { if (colorMode === "logprob") recomputeLpRange(); const total = promptBases + genText; els.copy.disabled = total.length === 0; const bpl = basesPerLineSb(); const totalLines = total ? Math.ceil(total.length / bpl) : 0; const renderedLines = els.seq.children.length; const needFull = !total || lastRenderedMode !== colorMode || lastRenderedBpl !== bpl || totalLines < renderedLines || (colorMode === "logprob" && lpRangeShifted(lastRenderedLpRange, lpRange)); if (needFull) fullRender(bpl); else incrementalRender(bpl); } let renderQueued = false; function scheduleRender() { if (renderQueued) return; renderQueued = true; requestAnimationFrame(() => { renderQueued = false; renderSequence(); }); } function gcContent(s) { if (!s) return null; let gc = 0; for (const c of s) if (c === "G" || c === "C") gc++; return (gc / s.length) * 100; } function meanLpSb() { if (!genTokens.length) return null; let sum = 0, n = 0; for (const t of genTokens) { if (t.logprob != null && !isNaN(t.logprob)) { sum += t.logprob; n++; } } return n ? sum / n : null; } function updateStats() { els.statPrompt.innerHTML = `${promptBases.length}<span class="sb-unit">bp</span>`; els.statGen.innerHTML = `${genText.length}<span class="sb-unit">bp</span>`; els.statTok.textContent = genTokens.length; const elapsed = startTime ? (performance.now() - startTime) / 1000 : 0; els.statTime.innerHTML = `${elapsed.toFixed(1)}<span class="sb-unit">s</span>`; const rate = elapsed > 0 ? Math.round(genText.length / elapsed) : 0; els.statRate.innerHTML = `${rate}<span class="sb-unit">bp/s</span>`; const gc = gcContent(genText); els.statGc.textContent = gc == null ? "—" : `${gc.toFixed(1)}%`; const mlp = meanLpSb(); els.statLp.textContent = mlp == null ? "—" : mlp.toFixed(2); els.statPpl.textContent = mlp == null ? "—" : Math.exp(-mlp).toFixed(1); } function setStatus(text, mode = "") { els.statusText.textContent = text; els.status.className = "sb-status" + (mode ? " " + mode : ""); }
els.modeBtns.querySelectorAll(".sb-mode-btn").forEach(b => { b.addEventListener("click", () => { colorMode = b.dataset.mode; els.modeBtns.querySelectorAll(".sb-mode-btn").forEach(x => x.classList.toggle("active", x === b)); els.legend.classList.toggle("show", colorMode === "logprob"); renderSequence(); }); });
async function generate() { if (abortCtrl) return; promptBases = cleanPrompt(els.prompt.value); genText = ""; genTokens = []; genTokenAtBase = []; startTime = performance.now(); abortCtrl = new AbortController(); els.generate.disabled = true; els.stop.disabled = false; setStatus("connecting…", "streaming"); renderSequence(); updateStats(); timer = setInterval(updateStats, 100); const body = { prompt: promptBases, max_tokens: parseInt(els.maxTokens.value), temperature: parseFloat(els.temperature.value), top_p: parseFloat(els.topP.value), }; try { const resp = await fetch("/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal: abortCtrl.signal, }); if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`); setStatus("streaming", "streaming"); const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const events = buffer.split("\n\n"); buffer = events.pop(); for (const ev of events) { const line = ev.trim(); if (!line.startsWith("data:")) continue; const data = JSON.parse(line.slice(5).trim()); if (data.error) throw new Error(data.error); if (data.done) continue; if (data.logprobs) { const lp = data.logprobs; for (let i = 0; i < lp.tokens.length; i++) { const tokIdx = genTokens.length; genTokens.push({ text: lp.tokens[i], logprob: lp.token_logprobs[i], top: lp.top_logprobs[i], }); for (let j = 0; j < lp.tokens[i].length; j++) genTokenAtBase.push(tokIdx); } } if (data.text) { genText += cleanPrompt(data.text); scheduleRender(); } } } setStatus("done"); } catch (e) { if (e.name === "AbortError") setStatus("stopped"); else setStatus(e.message, "error"); } finally { abortCtrl = null; clearInterval(timer); updateStats(); renderSequence(); els.generate.disabled = false; els.stop.disabled = true; } } function stop() { if (abortCtrl) abortCtrl.abort(); } function clearAll() { if (abortCtrl) return; promptBases = ""; genText = ""; genTokens = []; genTokenAtBase = []; startTime = 0; renderSequence(); updateStats(); setStatus("idle"); } els.generate.addEventListener("click", generate); els.stop.addEventListener("click", stop); els.clear.addEventListener("click", clearAll); els.copy.addEventListener("click", async () => { const text = promptBases + genText; if (!text) return; try { await navigator.clipboard.writeText(text); els.copy.classList.add("copied"); els.copy.textContent = "copied"; } catch { els.copy.textContent = "failed"; } setTimeout(() => { els.copy.classList.remove("copied"); els.copy.textContent = "copy"; }, 1200); }); els.prompt.addEventListener("keydown", e => { if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); generate(); } }); document.querySelectorAll("#panel-sandbox .sb-ex-btn").forEach(btn => { btn.addEventListener("click", () => { els.prompt.value = btn.dataset.ex; autoGrow(); els.prompt.focus(); }); }); // Init meta from /config (fires regardless of which tab is active). // Reuses the shared promise from fetchConfig() — no double network roundtrip. fetchConfig().then(cfg => { els.meta.textContent = `${cfg.model} · ${cfg.endpoint}`; }).catch(() => { els.meta.textContent = "config unavailable"; });
updateStats(); autoGrow();
let roPending = false; const ro = new ResizeObserver(() => { if (roPending) return; roPending = true; requestAnimationFrame(() => { roPending = false; renderSequence(); }); }); ro.observe(els.seq); if (document.fonts && document.fonts.ready) { document.fonts.ready.then(() => { charMetrics = null; renderSequence(); }); }})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241// =========================================================================// §4 — Same gene across species// =========================================================================(function initDemo4() { const els = { pills: document.getElementById("d4-pills"), prefixPills: document.getElementById("d4-prefix-pills"), genPills: document.getElementById("d4-gen-pills"), info: document.getElementById("d4-info"), rows: document.getElementById("d4-rows"), go: document.getElementById("d4-go"), status: document.getElementById("d4-status"), statusText: document.querySelector("#d4-status span:last-child"), };
let SPECIES_DATA = null; let entry = null; // { symbol, species: [...] } let prefixLen = 200; let genLen = 200; // Per species: { genText, genTokens, genTokenAtBase, status } let runState = {};
function setStatus(text, mode = "") { els.statusText.textContent = text; els.status.className = "status" + (mode ? " " + mode : ""); }
function basesPerLine(el) { const cs = getComputedStyle(el); const padL = parseFloat(cs.paddingLeft) || 0; const padR = parseFloat(cs.paddingRight) || 0; const contentW = el.clientWidth - padL - padR; const charW = 7.4; const prefixW = 7 * charW; const blockW = 10 * charW + charW; if (contentW <= prefixW) return 60; const blocks = Math.floor((contentW - prefixW) / blockW); return Math.max(20, Math.min(blocks, 12) * 10); }
function renderRow(s) { const wrap = document.createElement("div"); wrap.className = "species-row"; wrap.dataset.id = s.species_id;
const stat = runState[s.species_id] || {}; const genText = stat.genText || ""; const refSlice = s.seq.slice(prefixLen, prefixLen + genLen); let match = 0, total = 0; for (let i = 0; i < genText.length && i < refSlice.length; i++) { total++; if (genText[i] === refSlice[i]) match++; } const idPct = total > 0 ? `${((match / total) * 100).toFixed(0)}%` : "—"; const meanLp = stat.genTokens ? meanLogprob(stat.genTokens) : null;
wrap.innerHTML = ` <div class="species-meta"> <div class="species-name" style="border-left-color:${s.color}">${s.common}</div> <div class="species-sub">${s.ortholog_symbol}</div> <div class="species-sub">chr${s.chrom} · strand ${s.strand}</div> </div> <div> <div class="species-seq" data-role="output">— click "run all" to generate —</div> <div class="species-seq" data-role="ref" style="margin-top:4px"></div> </div> <div class="species-stats"> <div class="stat-id">${idPct}</div> <div class="stat-sub">${total > 0 ? `${match}/${total} bases` : "not run"}</div> ${meanLp == null ? "" : `<div class="stat-sub">logP ${meanLp.toFixed(2)}</div>`} </div> `;
const outEl = wrap.querySelector('[data-role="output"]'); const refEl = wrap.querySelector('[data-role="ref"]');
if (genText.length === 0 && (stat.status === "idle" || !stat.status)) { outEl.classList.add("empty"); outEl.textContent = "— click \"run all\" to generate —"; refEl.style.display = "none"; } else if (stat.status === "error") { outEl.classList.add("empty"); outEl.style.color = "#b00020"; outEl.textContent = stat.error || "error"; refEl.style.display = "none"; } else { outEl.classList.remove("empty"); const bpl = basesPerLine(outEl); const total = (s.seq.slice(0, prefixLen) + genText); const lpRange = stat.genTokens ? lpRangeOf(stat.genTokens) : null; const colorOut = (absIdx) => { if (absIdx < prefixLen) return { style: `color:rgb(${PROMPT_RGB.join(",")})` }; const tok = stat.genTokens && stat.genTokenAtBase ? stat.genTokens[stat.genTokenAtBase[absIdx - prefixLen]] : null; const [r, g, b] = logprobRgb(tok ? tok.logprob : null, lpRange); return { style: `color:rgb(${r},${g},${b})` }; }; renderSeq(outEl, total, bpl, colorOut);
// Reference (only the generated span) if (genText.length > 0) { const refSpanStart = prefixLen; const refSpanEnd = Math.min(s.length, prefixLen + genLen); const refSeq = s.seq.slice(refSpanStart, refSpanEnd); const colorRef = (absIdx, base) => { // absIdx is local to refSeq (starts at 0) const genIdx = absIdx; if (genIdx >= genText.length) return { style: "color:#ccc" }; const matches = genText[genIdx] === base; return matches ? { style: "color:#bbb" } : { style: "color:#b00020;background:rgba(188,46,37,0.18)" }; }; const bpl2 = basesPerLine(refEl); renderSeq(refEl, refSeq, bpl2, colorRef); refEl.style.display = ""; } else { refEl.style.display = "none"; } }
els.rows.appendChild(wrap); }
function renderAll() { els.rows.innerHTML = ""; if (!entry) return; for (const s of entry.species) renderRow(s); }
async function generateForSpecies(s) { const prompt = s.seq.slice(0, prefixLen); const stat = { genText: "", genTokens: [], genTokenAtBase: [], status: "running" }; runState[s.species_id] = stat; renderAll(); try { const resp = await fetch("/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt, max_tokens: Math.ceil(genLen / 6) + 4, temperature: 1.0, top_p: 1.0, }), }); if (!resp.ok) throw new Error(`HTTP ${resp.status}`); const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const events = buffer.split("\n\n"); buffer = events.pop(); for (const ev of events) { const line = ev.trim(); if (!line.startsWith("data:")) continue; const data = JSON.parse(line.slice(5).trim()); if (data.error) throw new Error(data.error); if (data.done) continue; if (data.logprobs) { const lp = data.logprobs; for (let i = 0; i < lp.tokens.length; i++) { const tokIdx = stat.genTokens.length; stat.genTokens.push({ text: lp.tokens[i], logprob: lp.token_logprobs[i] }); for (let j = 0; j < lp.tokens[i].length; j++) stat.genTokenAtBase.push(tokIdx); } } if (data.text) { const cleaned = data.text.toUpperCase().replace(/[^ACGTN]/g, ""); const room = Math.max(0, genLen - stat.genText.length); stat.genText += cleaned.slice(0, room); renderAll(); if (stat.genText.length >= genLen) return; } } } stat.status = "done"; } catch (e) { stat.status = "error"; stat.error = e.message; throw e; } finally { renderAll(); } }
async function runAll() { if (!entry) return; runState = {}; setStatus("running…", "streaming"); els.go.disabled = true; try { for (const s of entry.species) { try { await generateForSpecies(s); } catch (e) { /* keep going across species */ } } setStatus("done"); } finally { els.go.disabled = false; } }
function selectGene(symbol) { entry = SPECIES_DATA.find(x => x.symbol === symbol); if (!entry) return; els.pills.querySelectorAll(".pill").forEach(p => p.classList.toggle("active", p.dataset.gene === symbol)); els.info.innerHTML = `<strong>${entry.symbol}</strong> · same gene, ${entry.species.length} species · prefix from each species' own canonical transcript`; runState = {}; renderAll(); setStatus("idle"); }
function bindPills(container, attr, onSelect) { container.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => { container.querySelectorAll(".pill").forEach(x => x.classList.remove("active")); p.classList.add("active"); onSelect(p.dataset[attr]); }); }); }
fetch("/species").then(r => r.json()).then(data => { SPECIES_DATA = data; els.pills.innerHTML = data.map((g, i) => `<button class="pill${i === 0 ? " active" : ""}" data-gene="${g.symbol}">${g.symbol}</button>` ).join(""); els.pills.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => selectGene(p.dataset.gene)); }); selectGene(data[0].symbol); }).catch(e => { els.info.textContent = "failed to load species: " + e.message; });
bindPills(els.prefixPills, "prefix", (v) => { prefixLen = +v; runState = {}; renderAll(); }); bindPills(els.genPills, "gen", (v) => { genLen = +v; runState = {}; renderAll(); }); els.go.addEventListener("click", runAll); window.addEventListener("resize", () => renderAll());})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081// =========================================================================// §7 — Tokenizer (1-mer vs 6-mer)// =========================================================================(function initDemo7() { const els = { input: document.getElementById("d7-input"), len: document.getElementById("d7-len"), oneSeq: document.getElementById("d7-1mer"), sixSeq: document.getElementById("d7-6mer"), oneTok: document.getElementById("d7-1mer-tok"), sixTok: document.getElementById("d7-6mer-tok"), oneAtt: document.getElementById("d7-1mer-att"), sixAtt: document.getElementById("d7-6mer-att"), bars: document.getElementById("d7-bars"), speedup: document.getElementById("d7-speedup"), }; // 8-color palette for 6-mer tokens (cycle); 1-mer uses base coloring. const TOKEN_PALETTE = ["#317f3f","#2c5aa0","#c08030","#7a4baa","#2a8a8a","#b03b6e","#5a6e30","#a87a30"]; const BASE_FILL = { A:"#3a8a3e", C:"#2e6bb8", G:"#b5891e", T:"#b53a3a", N:"#888" };
function clean(s) { return (s || "").toUpperCase().replace(/[^ACGTN]/g, ""); }
function render() { const seq = clean(els.input.value); els.len.textContent = `${seq.length} bp`;
// 1-mer: each base its own pill let one = ""; for (let i = 0; i < seq.length; i++) { const b = seq[i]; one += `<span style="display:inline-block;background:${BASE_FILL[b]||"#888"};color:#fff;padding:2px 4px;margin:1px;border-radius:2px;font-size:10px;letter-spacing:0">${b}</span>`; } els.oneSeq.classList.toggle("empty", seq.length === 0); els.oneSeq.innerHTML = seq.length ? one : "—";
// 6-mer: chunks of 6, alternating palette colors let six = ""; for (let i = 0; i < seq.length; i += 6) { const chunk = seq.slice(i, i + 6); const isFull = chunk.length === 6; const c = TOKEN_PALETTE[(i / 6) % TOKEN_PALETTE.length]; const padded = isFull ? chunk : chunk + "•".repeat(6 - chunk.length); six += `<span style="display:inline-block;background:${c};color:#fff;padding:3px 7px;margin:2px;border-radius:3px;font-size:11px;letter-spacing:1px;${isFull?"":"opacity:0.55"}">${padded}</span>`; } els.sixSeq.classList.toggle("empty", seq.length === 0); els.sixSeq.innerHTML = seq.length ? six : "—";
const n1 = seq.length; const n6 = Math.ceil(seq.length / 6); els.oneTok.textContent = n1.toLocaleString("en-US"); els.sixTok.textContent = n6.toLocaleString("en-US"); els.oneAtt.innerHTML = `${(n1*n1).toLocaleString("en-US")}<span style="color:#999;font-size:9px;margin-left:3px">L²</span>`; els.sixAtt.innerHTML = `${(n6*n6).toLocaleString("en-US")}<span style="color:#999;font-size:9px;margin-left:3px">L²</span>`;
// Speedup bars: visualize attention cost ratio const maxCost = n1 * n1 || 1; const W = 1000, H = 70, padL = 110, padR = 80, rowH = 18, padT = 12; let svg = ""; const rows = [ { label: "1-mer", n: n1, cost: n1 * n1, color: "#888" }, { label: "6-mer", n: n6, cost: n6 * n6, color: "#317f3f" }, ]; rows.forEach((r, i) => { const y = padT + i * (rowH + 8); svg += `<text x="${padL - 8}" y="${y + 13}" font-family="JetBrains Mono" font-size="11" fill="#333" text-anchor="end">${r.label}</text>`; const w = (r.cost / maxCost) * (W - padL - padR); svg += `<rect x="${padL}" y="${y}" width="${Math.max(2, w)}" height="${rowH}" fill="${r.color}"/>`; svg += `<text x="${padL + w + 6}" y="${y + 13}" font-family="JetBrains Mono" font-size="10" fill="#333">${r.cost.toLocaleString("en-US")}</text>`; }); els.bars.setAttribute("viewBox", `0 0 ${W} ${H}`); els.bars.style.height = `${H}px`; els.bars.innerHTML = svg;
const ratio = n1 > 0 ? (n1 * n1) / Math.max(1, n6 * n6) : 36; els.speedup.textContent = `${ratio.toFixed(1)}× cheaper attention`; }
els.input.addEventListener("input", render); render();})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261// =========================================================================// §3 — Likelihood track over a real gene// =========================================================================(function initDemo3() { const els = { pills: document.getElementById("d3-pills"), info: document.getElementById("d3-info"), track: document.getElementById("d3-track"), chart: document.getElementById("d3-chart"), bpLabel: document.getElementById("d3-bp-label"), go: document.getElementById("d3-go"), status: document.getElementById("d3-status"), statusText: document.querySelector("#d3-status span:last-child"), meanExon: document.getElementById("d3-mean-exon"), meanIntron: document.getElementById("d3-mean-intron"), delta: document.getElementById("d3-delta"), tokens: document.getElementById("d3-tokens"), mean: document.getElementById("d3-mean"), };
let gene = null; let scoreData = null; // { tokens, token_logprobs, scoredLength } const cache = {}; // cache scored data by gene symbol so re-clicking is instant const MAX_WINDOW = 6000;
function setStatus(text, mode = "") { els.statusText.textContent = text; els.status.className = "status" + (mode ? " " + mode : ""); }
function renderTrack(scoredLen) { const W = 1000, H = 28; if (!gene) { els.track.innerHTML = ""; return; } const total = scoredLen || gene.length; const scaleX = (bp) => (bp / total) * W; let svg = ""; svg += `<line class="intron" x1="0" y1="${H/2}" x2="${W}" y2="${H/2}"/>`; for (const e of gene.exons) { if (e.start > total) continue; const x = scaleX(e.start); const w = Math.max(1, scaleX(Math.min(e.end, total) - e.start)); svg += `<rect class="exon" x="${x.toFixed(1)}" y="6" width="${w.toFixed(1)}" height="16"/>`; } els.track.innerHTML = svg; }
function renderChart() { const W = 1000, H = 140, padT = 6, padB = 16; if (!scoreData || !gene) { els.chart.innerHTML = `<text x="${W/2}" y="${H/2}" text-anchor="middle" font-family="JetBrains Mono" font-size="11" fill="#bbb">— score the gene to see the likelihood track —</text>`; return; } const tokens = scoreData.tokens; const lps = scoreData.token_logprobs; const padBases = scoreData.pad_bases || 0; // Skip <dna>, plus the first DNA token when it contains left-pad phantoms. const points = []; let cursor = 0; // bp into the *padded* sequence let firstDnaSkipped = false; for (let i = 0; i < tokens.length; i++) { const tlen = tokens[i].length; if (tokens[i] === "<dna>") continue; if (padBases > 0 && !firstDnaSkipped) { firstDnaSkipped = true; cursor += tlen; continue; } const lp = lps[i]; if (lp != null && !isNaN(lp)) { // Map midpoint back to gene-relative coords const genePos = (cursor - padBases) + tlen / 2; points.push({ pos: genePos, lp }); } cursor += tlen; } if (!points.length) { els.chart.innerHTML = `<text x="${W/2}" y="${H/2}" text-anchor="middle" font-family="JetBrains Mono" font-size="11" fill="#bbb">no logprobs returned</text>`; return; } const scoredLen = scoreData.scoredLength;
// Y range let lpMin = Infinity, lpMax = -Infinity; for (const p of points) { if (p.lp < lpMin) lpMin = p.lp; if (p.lp > lpMax) lpMax = p.lp; } // Pad a touch so extremes don't touch the edges const lpPad = Math.max(0.2, (lpMax - lpMin) * 0.05); const yMin = lpMin - lpPad; const yMax = lpMax + lpPad; const xScale = (bp) => (bp / scoredLen) * W; const yScale = (lp) => padT + (1 - (lp - yMin) / Math.max(1e-9, yMax - yMin)) * (H - padT - padB);
let svg = "";
// Exon shading background bands for (const e of gene.exons) { if (e.start > scoredLen) continue; const x = xScale(e.start); const w = xScale(Math.min(e.end, scoredLen)) - x; svg += `<rect x="${x.toFixed(1)}" y="0" width="${Math.max(1, w).toFixed(1)}" height="${H}" fill="#317f3f" opacity="0.08"/>`; }
// Smoothed line: a moving average over the points (window=5) const win = 5; const smoothed = points.map((p, i) => { let s = 0, c = 0; for (let j = Math.max(0, i - win); j <= Math.min(points.length - 1, i + win); j++) { s += points[j].lp; c++; } return { pos: p.pos, lp: s / c }; });
// Raw points as faint dots let dots = ""; for (const p of points) { dots += `<circle cx="${xScale(p.pos).toFixed(1)}" cy="${yScale(p.lp).toFixed(1)}" r="0.9" fill="#888" opacity="0.35"/>`; } svg += dots;
// Smoothed path on top let d = ""; smoothed.forEach((p, i) => { d += (i === 0 ? "M" : "L") + xScale(p.pos).toFixed(1) + " " + yScale(p.lp).toFixed(1); }); svg += `<path d="${d}" fill="none" stroke="#1f1f1d" stroke-width="1.2" stroke-linejoin="round"/>`;
// Y-axis ticks const tickLps = [yMin + (yMax - yMin) * 0.1, yMin + (yMax - yMin) * 0.5, yMin + (yMax - yMin) * 0.9]; for (const tl of tickLps) { const ty = yScale(tl).toFixed(1); svg += `<line x1="0" y1="${ty}" x2="${W}" y2="${ty}" stroke="#eee" stroke-width="1"/>`; svg += `<text x="4" y="${(parseFloat(ty) - 2).toFixed(1)}" font-family="JetBrains Mono" font-size="9" fill="#aaa">${tl.toFixed(1)}</text>`; }
els.chart.innerHTML = svg; els.bpLabel.textContent = `${scoredLen.toLocaleString("en-US")} bp scored`; }
function updateStats() { if (!scoreData || !gene) { [els.meanExon, els.meanIntron, els.delta, els.tokens, els.mean].forEach(e => { e.textContent = "—"; e.classList.add("muted"); }); return; } const tokens = scoreData.tokens; const lps = scoreData.token_logprobs; const padBases = scoreData.pad_bases || 0; let cursor = 0; let firstDnaSkipped = false; let exonSum = 0, exonN = 0; let intronSum = 0, intronN = 0; let allSum = 0, allN = 0; function annAt(idx) { for (const e of gene.exons) if (idx >= e.start && idx < e.end) return "exon"; return "intron"; } for (let i = 0; i < tokens.length; i++) { if (tokens[i] === "<dna>") continue; const tlen = tokens[i].length; if (padBases > 0 && !firstDnaSkipped) { firstDnaSkipped = true; cursor += tlen; continue; } const lp = lps[i]; if (lp != null && !isNaN(lp)) { const mid = (cursor - padBases) + tlen / 2; const a = annAt(Math.floor(mid)); if (a === "exon") { exonSum += lp; exonN++; } else { intronSum += lp; intronN++; } allSum += lp; allN++; } cursor += tlen; } const fmt = (s, n) => n > 0 ? (s / n).toFixed(2) : "—"; els.meanExon.textContent = fmt(exonSum, exonN); els.meanIntron.textContent = fmt(intronSum, intronN); if (exonN > 0 && intronN > 0) { const d = (exonSum / exonN) - (intronSum / intronN); els.delta.textContent = (d >= 0 ? "+" : "") + d.toFixed(2); } else { els.delta.textContent = "—"; } els.tokens.textContent = String(allN); els.mean.textContent = fmt(allSum, allN); [els.meanExon, els.meanIntron, els.delta, els.tokens, els.mean].forEach(e => e.classList.remove("muted")); }
async function score() { if (!gene) return; const cached = cache[gene.symbol]; if (cached) { scoreData = cached; renderTrack(scoreData.scoredLength); renderChart(); updateStats(); setStatus("cached"); return; } setStatus("scoring (cold endpoint takes ~30s)…", "streaming"); els.go.disabled = true; try { const seq = gene.seq.slice(0, MAX_WINDOW); const r = await fetch("/score", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sequence: seq, max_window: MAX_WINDOW }), }); const data = await r.json(); if (data.error) throw new Error(data.error); data.scoredLength = seq.length; cache[gene.symbol] = data; scoreData = data; renderTrack(data.scoredLength); renderChart(); updateStats(); setStatus("done"); } catch (e) { setStatus(e.message, "error"); } finally { els.go.disabled = false; } }
function selectGene(symbol) { const g = GENES.find(x => x.symbol === symbol); if (!g) return; gene = g; els.pills.querySelectorAll(".pill").forEach(p => p.classList.toggle("active", p.dataset.gene === symbol)); els.info.innerHTML = `<strong>${gene.symbol}</strong> · ${gene.blurb} · <span style="color:#888">${Math.min(gene.length, MAX_WINDOW).toLocaleString("en-US")} bp will be scored${gene.length > MAX_WINDOW ? ` (of ${gene.length.toLocaleString("en-US")})` : ""}</span>`; scoreData = cache[symbol] || null; renderTrack(scoreData ? scoreData.scoredLength : Math.min(gene.length, MAX_WINDOW)); renderChart(); updateStats(); setStatus(scoreData ? "cached" : "idle"); }
loadGenes().then(genes => { // Hydrate cache from precomputed tracks for (const g of genes) { if (g.track) { cache[g.symbol] = { tokens: g.track.tokens, token_logprobs: g.track.token_logprobs, scoredLength: g.track.scored_length, pad_bases: g.track.pad_bases || 0, }; } } els.pills.innerHTML = genes.map((g, i) => `<button class="pill${i === 0 ? " active" : ""}" data-gene="${g.symbol}">${g.symbol}</button>` ).join(""); els.pills.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => selectGene(p.dataset.gene)); }); selectGene(genes[0].symbol); });
els.go.addEventListener("click", score);})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340// =========================================================================// §7 — Species tree (Carbon-derived phylogeny)//// Renders the precomputed species_tree.json (built once by// scripts/build_species_tree.py) as:// - an SVG dendrogram spine on the left, with rounded Bezier elbows// so the branches feel organic rather than CAD-like// - a column of right-aligned data tracks (italic name, kingdom chip,// log-scaled sequence count bar, NCBI agreement glyph)// The two halves share the same row height (ROW_H px) so each leaf in// the SVG lines up exactly with its row in the data tracks.//// User can toggle:// - linkage = ward | upgma → swaps the precomputed layout// - scope = kingdom | sister → swaps the NCBI agreement metric// Hovering a row pops a tooltip listing the top-3 nearest neighbours// in embedding space + their cosine distances.// =========================================================================(function initDemoSpeciesTree() { const root = document.getElementById("demoSpeciesTree"); if (!root) return;
const ROW_H = 22; // px — must match .tree-row height in CSS // SVG-internal padding kept at 0: vertical alignment with the rows // grid is handled entirely by the CSS padding on .tree-spine / // .tree-rows (both = 12px top). Doubling it would shift the spine // down by 12px relative to the row labels. const SPINE_PAD_TOP = 0; const SPINE_PAD_BOTTOM = 0; const ROWS_PAD_TOP = 12; // must match .tree-rows padding const ROWS_PAD_BOTTOM = 28; const SPINE_LABEL_INSET = 4; // tiny gap between spine tip and labels
const KINGDOM_COLOR = { vertebrates: "#1f1f1d", invertebrates: "#7a6242", plants: "#317f3f", fungi: "#a9762f", bacteria: "#b00020", viruses: "#2c5aa0", };
const els = { spine: document.getElementById("dtree-spine"), svg: document.getElementById("dtree-svg"), rows: document.getElementById("dtree-rows"), info: document.getElementById("dtree-info"), score: document.getElementById("dtree-score"), scoreSx: document.getElementById("dtree-score-suffix"), nSp: document.getElementById("dtree-n"), nSeq: document.getElementById("dtree-nseq"), tooltip: document.getElementById("dtree-tooltip"), frame: root.querySelector(".tree-frame"), pillsLink: document.getElementById("dtree-link-pills"), pillsScope: document.getElementById("dtree-scope-pills"), };
let tree = null; let state = { linkage: "ward", scope: "kingdom" }; let agreement = {}; // species -> 'match' | 'mismatch' | 'solo' let nnTop = {}; // species -> [{name, dist, sameKingdom, sameClade}, ...]
// -------- nearest-neighbour computation -------- function buildNN() { const sp = tree.species; const D = tree.distance_matrix; const kingdom = Object.fromEntries(sp.map((s, i) => [s, tree.kingdom[i]])); const clade = Object.fromEntries(sp.map((s, i) => [s, tree.expected_clade[i]])); const cladeSize = {}; sp.forEach(s => { const c = clade[s]; cladeSize[c] = (cladeSize[c] || 0) + 1; });
nnTop = {}; agreement = {}; for (let i = 0; i < sp.length; i++) { // sort other species by distance ascending const ranked = []; for (let j = 0; j < sp.length; j++) { if (j === i) continue; ranked.push({ name: sp[j], dist: D[i][j], sameKingdom: kingdom[sp[j]] === kingdom[sp[i]], sameClade: clade[sp[j]] === clade[sp[i]], }); } ranked.sort((a, b) => a.dist - b.dist); nnTop[sp[i]] = ranked.slice(0, 3);
// agreement state for the active scope const nn = ranked[0]; if (state.scope === "kingdom") { agreement[sp[i]] = nn.sameKingdom ? "match" : "mismatch"; } else { if ((cladeSize[clade[sp[i]]] || 0) <= 1) agreement[sp[i]] = "solo"; else agreement[sp[i]] = nn.sameClade ? "match" : "mismatch"; } } }
// -------- score chip -------- function updateScore() { let m = 0, total = 0; Object.values(agreement).forEach(v => { if (v === "solo") return; total += 1; if (v === "match") m += 1; }); const pct = total ? Math.round(100 * m / total) : 0; els.score.textContent = `${m} / ${total}`; els.scoreSx.textContent = `match ncbi ${state.scope} (${pct}%)`; }
// -------- SVG dendrogram spine -------- // scipy gives icoord/dcoord for each merge: // icoord = [xL, xL, xR, xR] (in "leaf-index space": leaves at 5,15,25,...) // dcoord = [yChildL, yMerge, yMerge, yChildR] (in distance space) // We need to render this with leaf-index → vertical row position // and distance → horizontal x position (with root on the LEFT, tips // on the RIGHT, so labels sit next to the leaves). function renderSpine() { const layout = tree[state.linkage === "ward" ? "layout_ward" : "layout_upgma"]; const leafOrder = layout.leaf_order; const ic = layout.icoord; const dc = layout.dcoord;
const N = leafOrder.length; const innerH = N * ROW_H; const totalH = innerH + SPINE_PAD_TOP + SPINE_PAD_BOTTOM;
const w = els.spine.clientWidth || 320; els.svg.style.height = totalH + "px"; els.svg.setAttribute("viewBox", `0 0 ${w} ${totalH}`);
// distance domain let dmax = 0; dc.forEach(arr => arr.forEach(v => { if (v > dmax) dmax = v; })); if (dmax === 0) dmax = 1;
// In mobile (<=720px) the right-hand .tree-rows block stacks BELOW // the spine instead of beside it, so the spine renders inline labels // (kingdom chip + species name) at each tip — otherwise the user sees // an unlabelled dendrogram followed by a list, which doesn't connect. const isMobile = window.matchMedia("(max-width: 720px)").matches; const padL = 4; // a hair from the SVG left edge (= root) const padR = isMobile ? 130 : SPINE_LABEL_INSET; // room for inline labels in mobile const innerW = w - padL - padR;
const xOfDist = d => padL + (1 - d / dmax) * innerW; const yOfLeafIdx = idx => SPINE_PAD_TOP + (idx + 0.5) * ROW_H; const yOfICoord = ix => yOfLeafIdx((ix - 5) / 10);
// Classic dendrogram elbows: top arm horizontal → vertical → bottom // arm horizontal, sharp 90° corners. Single <path> for perf. let d = ""; for (let i = 0; i < ic.length; i++) { const xs = ic[i], ys = dc[i]; const yTop = yOfICoord(xs[0]); const yBot = yOfICoord(xs[3]); const xMerge = xOfDist(ys[1]); const xTopArm = xOfDist(ys[0]); const xBotArm = xOfDist(ys[3]); d += ` M ${xTopArm} ${yTop}` + ` L ${xMerge} ${yTop}` + ` L ${xMerge} ${yBot}` + ` L ${xBotArm} ${yBot}`; }
// Pastilles at each leaf tip — coloured by kingdom — that visually // connect the muted-grey tree spine to the kingdom-coloured tracks // on the right. They also act as a discrete "row marker" so the eye // can follow horizontally even where the spine background tint is // very pale (chicken / frog / zebrafish in the vertebrate band). const kingdom = Object.fromEntries(tree.species.map((s, i) => [s, tree.kingdom[i]])); let tips = ""; for (let i = 0; i < leafOrder.length; i++) { const sp = leafOrder[i]; const cy = yOfLeafIdx(i); const cx = w - padR; const k = kingdom[sp]; const fill = ( k === "vertebrates" ? "#1f1f1d" : k === "invertebrates" ? "#7a6242" : k === "plants" ? "#317f3f" : k === "fungi" ? "#a9762f" : k === "bacteria" ? "#b00020" : k === "viruses" ? "#2c5aa0" : "#888" ); tips += `<circle cx="${cx}" cy="${cy}" r="2.4" fill="${fill}" stroke="#fff" stroke-width="0.8"/>`; if (isMobile) { // chip + species label rendered inline at the tip — only visible // in mobile (desktop hides them via CSS, see .leaf-svg-label). tips += `<rect class="leaf-svg-chip" x="${cx + 6}" y="${cy - 4}" width="8" height="8" fill="${fill}"/>`; tips += `<text class="leaf-svg-label" x="${cx + 18}" y="${cy + 3.5}" fill="${fill}">${sp.replace(/_/g, " ")}</text>`; } }
els.svg.innerHTML = `<path d="${d}" fill="none" stroke="#bbb8ad" stroke-width="1" stroke-linecap="square" stroke-linejoin="miter" shape-rendering="crispEdges" />` + tips; return leafOrder; }
// -------- rows -------- function renderRows(leafOrder) { const counts = Object.fromEntries(tree.species.map((s, i) => [s, tree.counts[i]])); const kingdom = Object.fromEntries(tree.species.map((s, i) => [s, tree.kingdom[i]])); const maxLog = Math.log10(Math.max(...tree.counts) + 1);
let html = ""; for (let i = 0; i < leafOrder.length; i++) { const sp = leafOrder[i]; const k = kingdom[sp]; const c = counts[sp]; const logFrac = Math.log10(c + 1) / maxLog; const a = agreement[sp] || "solo"; const glyph = a === "match" ? "✓" : a === "mismatch" ? "✗" : "—"; html += `<div class="tree-row" data-species="${sp}" data-kingdom="${k}">` + `<div class="tree-chip" style="background:${KINGDOM_COLOR[k]}"></div>` + `<div class="tree-name">${sp.replace(/_/g, " ")}</div>` + `<div class="tree-bar">` + `<div class="bar-track">` + `<div class="bar-fill" style="width:${(logFrac * 100).toFixed(1)}%"></div>` + `</div>` + `<div class="bar-num">${c.toLocaleString("en-US")}</div>` + `</div>` + `<div class="tree-ncbi" data-state="${a}">${glyph}</div>` + `</div>`; } els.rows.innerHTML = html; bindRowHover(); }
// -------- hover tooltip -------- function bindRowHover() { els.rows.querySelectorAll(".tree-row").forEach(rowEl => { rowEl.addEventListener("mouseenter", () => { const sp = rowEl.dataset.species; const top = nnTop[sp] || []; const expected = state.scope === "kingdom" ? "same kingdom" : "same ncbi sister clade"; let tt = `<div class="tt-title">${sp.replace(/_/g, " ")} · top neighbours</div>`; top.forEach((nb, i) => { const isExpected = state.scope === "kingdom" ? nb.sameKingdom : nb.sameClade; const cls = isExpected ? "tt-name expected" : "tt-name"; const glyph = isExpected ? "✓" : "·"; tt += `<div class="tt-pair">` + `<span class="tt-glyph">${glyph}</span>` + `<span class="${cls}">${nb.name.replace(/_/g, " ")}</span>` + `<span class="tt-dist">${nb.dist.toFixed(4)}</span>` + `</div>`; }); tt += `<div class="tt-pair" style="margin-top:6px;color:#888">` + `<span class="tt-glyph"></span>` + `<span style="font-size:9px">match = ${expected}</span></div>`; els.tooltip.innerHTML = tt; els.tooltip.classList.add("show"); }); rowEl.addEventListener("mousemove", (ev) => { const fr = els.frame.getBoundingClientRect(); const tt = els.tooltip; const x = ev.clientX - fr.left + 12; const y = ev.clientY - fr.top + 12; // keep on-screen const ttw = tt.offsetWidth, tth = tt.offsetHeight; const fitX = (x + ttw > fr.width) ? (ev.clientX - fr.left - ttw - 12) : x; const fitY = (y + tth > fr.height) ? (ev.clientY - fr.top - tth - 12) : y; tt.style.left = fitX + "px"; tt.style.top = fitY + "px"; }); rowEl.addEventListener("mouseleave", () => { els.tooltip.classList.remove("show"); }); }); }
// -------- toggles -------- function bindToggles() { els.pillsLink.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => { if (p.classList.contains("active")) return; els.pillsLink.querySelectorAll(".pill").forEach(b => b.classList.remove("active")); p.classList.add("active"); state.linkage = p.dataset.link; rerender(); }); }); els.pillsScope.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => { if (p.classList.contains("active")) return; els.pillsScope.querySelectorAll(".pill").forEach(b => b.classList.remove("active")); p.classList.add("active"); state.scope = p.dataset.scope; // scope only changes agreement, not layout — but it's cheap to redo all buildNN(); const layout = tree[state.linkage === "ward" ? "layout_ward" : "layout_upgma"]; renderRows(layout.leaf_order); updateScore(); }); }); }
function rerender() { buildNN(); const order = renderSpine(); renderRows(order); updateScore(); }
// -------- bootstrap -------- fetch("/species_tree") .then(r => r.json()) .then(t => { tree = t; els.nSp.textContent = tree.species.length; els.nSeq.textContent = tree.n_total_points.toLocaleString("en-US"); bindToggles(); rerender(); // The SVG width depends on the laid-out grid → recompute on resize. const ro = new ResizeObserver(() => { const order = renderSpine(); renderRows(order); // re-bind row hover after rebuild }); ro.observe(els.spine); // matchMedia covers the exact breakpoint transition where the // spine width may not actually change (e.g. desktop window shrunk // to 720px → still occupies the same column width but switches // role from "tree" to "tree + inline labels"). const mq = window.matchMedia("(max-width: 720px)"); const onMQ = () => { const order = renderSpine(); renderRows(order); }; if (mq.addEventListener) mq.addEventListener("change", onMQ); else mq.addListener(onMQ); // Safari < 14 fallback }) .catch(err => { els.info.textContent = "failed to load species tree: " + (err.message || err); });})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926// =========================================================================// §6 — UMAP scatter (WebGL, 571K points)//// Loads a binary-packed scatter (int16 quantized 2D positions + 4 uint8 category// columns — species, biotype, strand, gc_content) and renders it via WebGL// gl.POINTS with a 1D palette texture for coloring. Toggle between coloring axes// (species / biotype / strand / gc) rebinds a single byte-attribute buffer and// swaps the palette texture — no re-upload of the 571K vertex stream. Hover// lookup uses a flat grid index so picking stays O(small) regardless of total// point count.// =========================================================================(function initDemoUmap() { const canvas = document.getElementById("dumap-canvas"); if (!canvas) return; const tooltip = document.getElementById("dumap-tooltip"); const overlay = document.getElementById("dumap-overlay"); const info = document.getElementById("dumap-info"); const legend = document.getElementById("dumap-legend"); const resetBtn = document.getElementById("dumap-reset"); // The UMAP toolbar used to ship a `<span class="status">` indicator that // showed "loading…" / "loaded 571k pts · 1274 ms" / "error" next to the // pills. Removed because (a) loading is already explained by the fullscreen // overlay, (b) the post-load metric was telemetry-grade detail not visitor- // grade insight. Calls into setStatus below survive as no-ops so the live // load path doesn't have to be rewritten. const status = null; const statusText = null; const colorPills = document.querySelectorAll("#dumap-color-pills .pill"); const elN = document.getElementById("dumap-n"); const elNsp = document.getElementById("dumap-nsp"); const elFps = document.getElementById("dumap-fps"); const annContainer = document.getElementById("dumap-annotations");
// ---- Palettes ---------------------------------------------------------- // 27 species grouped into 6 kingdoms — each kingdom gets a hue band. // Within a band, lightness varies to keep adjacent species distinguishable. // Order MUST match labels.species (= the order from scripts/build_real_umap.py). const SPECIES_PALETTE = [ // vertebrates (10) — blue/indigo/violet band [40,80,160], [60,100,180], [80,120,195], [100,140,210], [120,160,225], [140,100,200], [160,120,215], [125,90,170], [105,75,150], [85,60,130], // invertebrates (2) — orange band [220,110,30], [240,160,70], // plants (5) — olive/lime band (intentionally different from Carbon's // signal-green #317f3f so the UI chrome doesn't blend with the data) [85,140,55], [115,170,75], [145,200,100], [175,220,135], [205,240,170], // fungi (5) — magenta/rose band [180,40,110], [200,70,140], [220,100,160], [235,130,175], [245,160,190], // bacteria (3) — ochre/amber band [180,140,40], [200,160,60], [220,180,80], // viruses (2) — deep red band (outliers, intentionally dramatic) [160,30,40], [200,50,55], ]; // protein_coding is ~80% of the points — using a saturated colour for it // floods the canvas and erases the three minority biotypes. We give it a // washed-out sage instead (still readable as "the green class") and crank // the saturation on the rare classes so they pop on top of the carpet. const BIOTYPE_PALETTE = [ [180,205,180], // protein_coding — washed sage (volume class) [210,55,45], // lncRNA — vivid Carbon red [40,100,200], // snRNA — vivid blue [240,160,30], // misc_RNA — amber (was gray, invisible) ]; const STRAND_PALETTE = [ [49,127,63], // + (forward) [188,46,37], // - (reverse) ]; // Continuous gradient for gc_content (uint8 0..255 → [0, 1]). // 3-stop: low GC (AT-rich) reads as cool steel, mid as neutral, high // GC (GC-rich) as warm amber — natural "density" feel without // colliding with the categorical palettes. function buildGCPalette() { const out = []; for (let i = 0; i < 256; i++) { const t = i / 255; let r, g, b; if (t < 0.5) { const u = t * 2; r = Math.round(60 + (170 - 60) * u); g = Math.round(90 + (170 - 90) * u); b = Math.round(160 + (170 - 160) * u); } else { const u = (t - 0.5) * 2; r = Math.round(170 + (230 - 170) * u); g = Math.round(170 + (190 - 170) * u); b = Math.round(170 + (50 - 170) * u); } out.push([r, g, b]); } return out; } const GC_PALETTE = buildGCPalette(); // Continuous gradient for log10(gene length). Sequential single-hue // ordering (deep teal → warm sand → terracotta) so the eye reads it as // "more vs less" rather than "category A vs B". Picked to be visually // distinct from GC's divergent steel→amber ramp so the two continuous // overlays don't read as the same axis at a glance. function buildLengthPalette() { const out = []; const A = [25, 70, 90]; // 0% short const B = [180, 165, 130]; // 50% mid const C = [200, 105, 65]; // 100% long for (let i = 0; i < 256; i++) { const t = i / 255; let lo, hi, u; if (t < 0.5) { lo = A; hi = B; u = t * 2; } else { lo = B; hi = C; u = (t - 0.5) * 2; } out.push([ Math.round(lo[0] + (hi[0] - lo[0]) * u), Math.round(lo[1] + (hi[1] - lo[1]) * u), Math.round(lo[2] + (hi[2] - lo[2]) * u), ]); } return out; } const LENGTH_PALETTE = buildLengthPalette(); const PALETTES = { species: SPECIES_PALETTE, biotype: BIOTYPE_PALETTE, strand: STRAND_PALETTE, gc: GC_PALETTE, length: LENGTH_PALETTE, };
// Format a bp count for the hover tooltip: "873 bp", "12.4 kb", "2.4 Mb". // Picks the smallest unit that keeps the displayed number under ~1000, // mirroring how genome browsers (UCSC, Ensembl) write spans. function formatBp(bp) { if (!Number.isFinite(bp) || bp < 0) return "—"; if (bp < 1000) return `${bp.toLocaleString("en-US")} bp`; if (bp < 1_000_000) return `${(bp / 1000).toFixed(bp < 10_000 ? 2 : 1)} kb`; return `${(bp / 1_000_000).toFixed(bp < 10_000_000 ? 2 : 1)} Mb`; }
// ---- State ------------------------------------------------------------- let gl, program; let posBuf; // int16 interleaved x,y let catBufs = {}; // { species|biotype|strand|gc|length: GLBuffer of uint8 } let paletteTex; let n = 0; let labels = null; // see scripts/build_real_umap.py for the full schema // Raw category bytes — kept on CPU side too for tooltip lookups. let cats = { species: null, biotype: null, strand: null, gc: null, length: null }; // Per-point gene names — lazy-fetched from /umap_names AFTER the WebGL // render is up so the heavy text strip never gates first paint. Stays // null in the window between scatter render and names land; tooltip // falls back to em-dash in that interval. Re-aligned to the shuffled // order via `shufflePerm` so names line up with positions. let names = null; let shufflePerm = null; // World bounds + current colorBy axis. let bounds = [0,0,0,0]; let colorBy = "species"; // Viewport: translate (tx, ty) + scale around origin, in NDC space. // The whole world is fit into [-0.95, 0.95]² at initial zoom. let view = { tx: 0, ty: 0, scale: 1 }; let dpr = Math.max(1, window.devicePixelRatio || 1); let needsRedraw = false; // Spatial grid for hover (built once after data load, in normalized world space). let grid = null;
function setStatus(state, text) { if (!status) return; status.classList.remove("streaming", "error"); if (state === "streaming") status.classList.add("streaming"); if (state === "error") status.classList.add("error"); statusText.textContent = text; }
// ---- WebGL setup ------------------------------------------------------- const VS = ` attribute vec2 a_pos; // raw int16, normalized via attribPointer (-1..1) attribute float a_cat; // category index (uint8 -> float) uniform vec3 u_xform; // x: scale, y: tx, z: ty uniform float u_pointSize; varying float v_cat; void main() { vec2 world = a_pos * u_xform.x + vec2(u_xform.y, u_xform.z); gl_Position = vec4(world, 0.0, 1.0); gl_PointSize = u_pointSize; v_cat = a_cat; } `; const FS = ` precision mediump float; varying float v_cat; uniform sampler2D u_palette; uniform float u_paletteN; uniform float u_alpha; void main() { vec2 d = gl_PointCoord - 0.5; float r = length(d); float aa = smoothstep(0.50, 0.42, r); if (aa <= 0.001) discard; float a = aa * u_alpha; float t = (v_cat + 0.5) / u_paletteN; vec3 color = texture2D(u_palette, vec2(t, 0.5)).rgb; // Pre-multiplied output matches blendFunc(ONE, ONE_MINUS_SRC_ALPHA) // and prevents the dense-overlap brightening you get with straight // alpha (which would need blendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA)). gl_FragColor = vec4(color * a, a); } `; function compile(type, src) { const sh = gl.createShader(type); gl.shaderSource(sh, src); gl.compileShader(sh); if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) { throw new Error("shader compile: " + gl.getShaderInfoLog(sh)); } return sh; } function setupGL() { gl = canvas.getContext("webgl", { antialias: true, alpha: true, premultipliedAlpha: true, preserveDrawingBuffer: false, }); if (!gl) throw new Error("WebGL unavailable"); program = gl.createProgram(); gl.attachShader(program, compile(gl.VERTEX_SHADER, VS)); gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FS)); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw new Error("program link: " + gl.getProgramInfoLog(program)); } gl.useProgram(program);
// Standard premultiplied-alpha additive-ish blending — points blend over // the paper background and over each other cleanly at dense overlaps. gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // Transparent clear — the .umap-frame CSS background (paper tone) shows // through, keeping the canvas in tune with the rest of the page. gl.clearColor(0, 0, 0, 0);
paletteTex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, paletteTex); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); }
function uploadPalette(palette) { const n = palette.length; const buf = new Uint8Array(n * 3); for (let i = 0; i < n; i++) { buf[i*3] = palette[i][0]; buf[i*3+1] = palette[i][1]; buf[i*3+2] = palette[i][2]; } gl.bindTexture(gl.TEXTURE_2D, paletteTex); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, n, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, buf); gl.uniform1f(gl.getUniformLocation(program, "u_paletteN"), n); }
// ---- Data load --------------------------------------------------------- // Mulberry32: tiny seeded PRNG, ~10 lines, good enough for visual shuffling. // Picked over Math.random() because we want the same layout across reloads // (so users can describe what they see and we can reproduce it). function mulberry32(seed) { return function() { seed = (seed + 0x6D2B79F5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
// Fisher-Yates over N parallel arrays: pos16 (2 entries / point, x then y) // and catArrays (1 entry / point, e.g. species / biotype / strand / gc). // Mutating the typed arrays in place avoids allocating a 16 MB reshuffled // buffer — important at 571 K points. // // Returns a Uint32Array `perm` where perm[i] = original-index now sitting // at slot i. We use it to re-align the deferred-loaded gene names strip // onto the same shuffled order without re-running the PRNG (which would // require keeping its state in sync, fragile). function shuffleParallel(pos16, catArrays, n, seed) { const rand = mulberry32(seed); const perm = new Uint32Array(n); for (let i = 0; i < n; i++) perm[i] = i; for (let i = n - 1; i > 0; i--) { const j = (rand() * (i + 1)) | 0; if (i === j) continue; const xi = pos16[2*i], yi = pos16[2*i + 1]; pos16[2*i] = pos16[2*j]; pos16[2*i + 1] = pos16[2*j + 1]; pos16[2*j] = xi; pos16[2*j + 1] = yi; for (const a of catArrays) { const t = a[i]; a[i] = a[j]; a[j] = t; } const pt = perm[i]; perm[i] = perm[j]; perm[j] = pt; } return perm; }
async function loadData() { setStatus("streaming", "loading…"); const t0 = performance.now(); const [binResp, labelsResp] = await Promise.all([ fetch("/umap"), fetch("/umap_labels"), ]); if (!binResp.ok) throw new Error("fetch /umap failed: " + binResp.status); const buf = await binResp.arrayBuffer(); labels = await labelsResp.json();
// Parse header (matches scripts/build_real_umap.py — 64-byte header). // Layout: // u32 [magic, n_points, n_species, n_biotypes, n_strands, flags] (24 b) // f32 [x2d_min, x2d_max, y2d_min, y2d_max] (16 b) // f32 [x3d_min, x3d_max, y3d_min, y3d_max, z3d_min, z3d_max] (24 b) // flags bit0 = has_3D, bit1 = has gc_content, bit2 = has length. const hdrU32 = new Uint32Array(buf, 0, 6); const magic = hdrU32[0]; if (magic !== 0xCAB0FA1D) throw new Error("bad magic: " + magic.toString(16)); n = hdrU32[1]; const flags = hdrU32[5]; const has3D = (flags & 0b001) !== 0; const hasGC = (flags & 0b010) !== 0; const hasLen = (flags & 0b100) !== 0; const hdrF32 = new Float32Array(buf, 24, 10); bounds = [hdrF32[0], hdrF32[1], hdrF32[2], hdrF32[3]]; // bounds_3d (hdrF32[4..10]) is parsed but unused — the v1 viewer // renders the 2D projection only. Kept in the binary so a future // 3D mode can switch attribute streams without re-fetching.
let off = 64; const pos16 = new Int16Array(buf, off, n * 2); off += n * 2 * 2; if (has3D) { // Skip pos_3d (int16 × 3 × n). Loaded into RAM is unnecessary // for v1 — the binary stays small enough that re-fetching for // a 3D mode is fine, and skipping keeps GPU memory tight. off += n * 3 * 2; } cats.species = new Uint8Array(buf, off, n); off += n; cats.biotype = new Uint8Array(buf, off, n); off += n; cats.strand = new Uint8Array(buf, off, n); off += n; if (hasGC) { cats.gc = new Uint8Array(buf, off, n); off += n; } if (hasLen) { cats.length = new Uint8Array(buf, off, n); off += n; } const catKeys = ["species", "biotype", "strand"]; if (hasGC) catKeys.push("gc"); if (hasLen) catKeys.push("length");
// Deterministic shuffle of the parallel arrays. The binary is sorted by // species (= order of viz.csv), so without this protein_coding (≈80% of // points) systematically lands on top of the minority biotypes/rare // species and visually erases them. A fixed seed keeps the layout stable // across reloads — same dot in the same place every time. Mulberry32 is // good enough and one line; Fisher-Yates over 571 K entries is ~30 ms. shufflePerm = shuffleParallel(pos16, catKeys.map(k => cats[k]), n, 0xC4B0FA1D);
// Upload to GPU. posBuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, posBuf); gl.bufferData(gl.ARRAY_BUFFER, pos16, gl.STATIC_DRAW); for (const key of catKeys) { const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, cats[key], gl.STATIC_DRAW); catBufs[key] = b; }
// Wire attributes (position is constant; category attribute is rebound on toggle). const posLoc = gl.getAttribLocation(program, "a_pos"); gl.bindBuffer(gl.ARRAY_BUFFER, posBuf); gl.enableVertexAttribArray(posLoc); // normalize=true → int16 mapped to [-1, 1] in shader — exactly the // quantization we did in the Python packer. gl.vertexAttribPointer(posLoc, 2, gl.SHORT, true, 0, 0);
// Build spatial grid (in [-1, 1]² normalized world space). buildGrid(pos16);
// Annotations are computed *after* the data is in: the cluster centroids // they pin to are read off the actual UMAP layout we just loaded, so // labels point at where vertebrates / fungi / lncRNAs / etc. ended up // landing in this run — not at hardcoded positions that would drift if // Dana ever re-runs the projection with different params. buildAnnotations(pos16);
elN.textContent = n.toLocaleString("en-US"); elN.classList.remove("muted"); elNsp.textContent = labels.species.length; elNsp.classList.remove("muted");
const ms = (performance.now() - t0) | 0; setStatus("idle", `loaded ${(n/1000)|0}k pts · ${ms} ms`); info.textContent = `${n.toLocaleString("en-US")} sequences · ${labels.species.length} species · drag to pan, wheel to zoom`; overlay.classList.add("hidden");
return pos16; }
// ---- Annotations ------------------------------------------------------- // Cluster names sit directly on top of each cluster centroid — no leader // lines, no margin labels, no body copy. Each annotation is just a // (mode, target, key) triple: the mode says which colorBy it applies // to, target is a data-space (-1..1) point, key is the bold name we // print on top of it. Different sets fire under different colorings // (kingdoms under "species", RNA-class pockets under "biotype", etc.), // and the labels track the cluster as the user pans/zooms. // // We render the label DOM once on data load and only mutate left/top // per frame, so updateAnnotations() runs in <0.1 ms. let annotations = [];
// Median over the (x, y) of points matching `predicate`. Median (vs mean) // because every UMAP cluster has a long tail; we want the dot on the // visible bulk, not drifting toward stragglers. // // Two-pass strategy: first try a strided sample (stride ≈ n/5000) to // stay <1 ms on 571 K points for the common case. If the predicate's // class is rare enough that the sample yields zero matches (e.g. viruses // here = 21 points across 571 K, ~0.004%), fall back to a full scan with // the same predicate — still <50 ms, and only happens once per dataset. function clusterCentroid(pos16, predicate) { const collect = (stride) => { const xs = [], ys = []; for (let i = 0; i < n; i += stride) { if (!predicate(i)) continue; xs.push(pos16[2*i] / 32767); ys.push(pos16[2*i + 1] / 32767); } return [xs, ys]; }; const stride = Math.max(1, (n / 5000) | 0); let [xs, ys] = collect(stride); if (xs.length === 0 && stride > 1) [xs, ys] = collect(1); if (xs.length === 0) return null; xs.sort((a, b) => a - b); ys.sort((a, b) => a - b); const m = xs.length >> 1; return [xs[m], ys[m]]; }
function buildAnnotations(pos16) { // Species → kingdom mapping is shipped in umap_labels.json by // scripts/build_real_umap.py (the same KINGDOMS dict that drives the // species ordering / palette banding). const speciesKingdom = labels.species_kingdom || {}; const kingdomOf = sIdx => speciesKingdom[labels.species[sIdx]] || null;
const ck = (k) => clusterCentroid(pos16, i => kingdomOf(cats.species[i]) === k); const cb = (id) => clusterCentroid(pos16, i => cats.biotype[i] === id); const gc = (lo, hi) => clusterCentroid(pos16, i => { const t = cats.gc ? cats.gc[i] / 255 : 0.5; return t >= lo && t <= hi; });
// Each entry: a target in data-space NDC and the cluster name to // print on top of it. No anchors, no body copy — the placement is // entirely data-driven (clusterCentroid) and the editorial commentary // lives in the "What to look for" prose under the chart. // // For "gc" we point at the high/low poles instead of the median (the // median sits in the middle of the bulk, where a gradient label // wouldn't help). For "strand" there's nothing to label — the // interesting fact is the *absence* of structure, not a location. annotations = [ // ---- species → kingdom macro-clusters { mode: "species", target: ck("vertebrates"), key: "Vertebrates" }, { mode: "species", target: ck("invertebrates"), key: "Invertebrates" }, { mode: "species", target: ck("plants"), key: "Plants" }, { mode: "species", target: ck("fungi"), key: "Fungi" }, { mode: "species", target: ck("bacteria"), key: "Bacteria" }, { mode: "species", target: ck("viruses"), key: "Viruses" },
// ---- biotype → RNA-class pockets { mode: "biotype", target: cb(0), key: "Protein-coding" }, { mode: "biotype", target: cb(1), key: "lncRNAs" }, { mode: "biotype", target: cb(2), key: "snRNAs" }, { mode: "biotype", target: cb(3), key: "misc_RNA" },
// ---- gc → composition poles. Thresholds picked from the actual // gc histogram of this dataset (peak ≈ 0.4): low ≤ 0.25 grabs the // AT-rich tail, high ≥ 0.60 grabs the GC-rich tail. { mode: "gc", target: gc(0.0, 0.25), key: "AT-rich" }, { mode: "gc", target: gc(0.60, 1.0), key: "GC-rich" }, ].filter(a => a.target);
renderAnnotationsDOM(); updateAnnotations(); }
// Build the label DOM *once* per dataset — subsequent updates only // mutate left/top, never innerHTML, so updateAnnotations() runs in // <0.1 ms and never triggers a layout thrash. function renderAnnotationsDOM() { if (!annContainer) return; annContainer.innerHTML = annotations .map((a, i) => `<div id="ann-label-${i}" class="ann-label">${a.key}</div>`) .join(""); }
// Per-frame: project each annotation's data-space target through the // current view transform and place the label on top of it (CSS handles // the centring via translate(-50%, -50%)). Annotations whose mode ≠ // colorBy or whose target sat off-canvas after pan/zoom get hidden. function updateAnnotations() { if (!annotations.length) return; const rect = canvas.getBoundingClientRect(); const W = rect.width, H = rect.height; if (W === 0 || H === 0) return;
const baseScale = 0.92; const dataToScreen = (dx, dy) => [ ((dx * baseScale * view.scale + view.tx) + 1) / 2 * W, (1 - (dy * baseScale * view.scale + view.ty)) / 2 * H, ]; // Margin so a label whose centre is just past the edge still shows // partially rather than popping. Tuned for the current font-size / // halo combo; bump if you grow the type. const margin = 60;
annotations.forEach((a, i) => { const label = document.getElementById(`ann-label-${i}`); if (!label) return;
const visible = a.mode === colorBy; if (!visible) { label.style.display = "none"; return; }
const [tx, ty] = dataToScreen(a.target[0], a.target[1]); if (tx < -margin || tx > W + margin || ty < -margin || ty > H + margin) { label.style.display = "none"; return; } label.style.display = ""; label.style.left = tx + "px"; label.style.top = ty + "px"; }); }
// ---- Spatial grid (hover picking) -------------------------------------- // We store, per cell, a list of point indices whose normalized (x,y) falls // in that cell. At hover, look up the cell under the cursor plus the 8 // neighbors, then scan for the nearest point within a screen-space radius. const GRID_N = 128; function buildGrid(pos16) { const cells = new Array(GRID_N * GRID_N); for (let i = 0; i < cells.length; i++) cells[i] = null; for (let i = 0; i < n; i++) { // pos16 entries are in [-32767, 32767] → normalize to [0, GRID_N). const x = (pos16[2*i] + 32767) / 65534; const y = (pos16[2*i + 1] + 32767) / 65534; const cx = Math.min(GRID_N - 1, Math.max(0, (x * GRID_N) | 0)); const cy = Math.min(GRID_N - 1, Math.max(0, (y * GRID_N) | 0)); const id = cy * GRID_N + cx; const list = cells[id]; if (list === null) cells[id] = [i]; else list.push(i); } grid = cells; }
// ---- Render ------------------------------------------------------------ function resize() { const rect = canvas.getBoundingClientRect(); if (rect.width === 0 || rect.height === 0) return false; dpr = Math.max(1, window.devicePixelRatio || 1); const w = Math.round(rect.width * dpr); const h = Math.round(rect.height * dpr); if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; } gl.viewport(0, 0, w, h); return true; }
let lastFrameTs = 0, frameCount = 0, fpsTs = 0; function draw() { needsRedraw = false; if (!resize()) return; gl.clear(gl.COLOR_BUFFER_BIT);
// The vertex shader does world = pos * scale + (tx, ty). We choose scale // so the data (normalized to [-1, 1]) fits in [-0.92, 0.92] of NDC at // zoom 1, with a tiny margin so points at the edge aren't clipped. const baseScale = 0.92; gl.uniform3f(gl.getUniformLocation(program, "u_xform"), baseScale * view.scale, view.tx, view.ty); // Point size scales sub-linearly with zoom — denser areas stay readable // but the dots get visibly bigger when you zoom in. const ps = Math.min(8.0, Math.max(1.4, 1.4 + 0.6 * Math.log2(view.scale + 1))) * dpr; gl.uniform1f(gl.getUniformLocation(program, "u_pointSize"), ps); // Alpha rises with zoom so individual dots stay readable, but starts low // so the dense 571 K cloud doesn't blow out at zoom 1. const alpha = Math.min(0.85, Math.max(0.22, 0.22 + 0.20 * Math.log2(view.scale + 1))); gl.uniform1f(gl.getUniformLocation(program, "u_alpha"), alpha);
gl.drawArrays(gl.POINTS, 0, n);
// Annotation overlay — labels and leader lines anchored to data-space // centroids. Cheap (<0.1 ms for ~5 visible labels), so we just run it // every frame instead of trying to detect view changes. updateAnnotations();
// FPS counter — sampled, not per-frame. const now = performance.now(); frameCount++; if (now - fpsTs > 500) { const fps = (frameCount * 1000) / (now - fpsTs); elFps.textContent = `${fps.toFixed(0)} fps`; elFps.classList.remove("muted"); fpsTs = now; frameCount = 0; } lastFrameTs = now; } function requestRedraw() { if (needsRedraw) return; needsRedraw = true; requestAnimationFrame(draw); }
// ---- Color toggle ------------------------------------------------------ function setColorBy(key) { colorBy = key; const catLoc = gl.getAttribLocation(program, "a_cat"); gl.bindBuffer(gl.ARRAY_BUFFER, catBufs[key]); gl.enableVertexAttribArray(catLoc); // Unnormalized — we want the raw byte value in the shader. gl.vertexAttribPointer(catLoc, 1, gl.UNSIGNED_BYTE, false, 0, 0); uploadPalette(PALETTES[key]); renderLegend(); requestRedraw(); }
// ---- Legend ------------------------------------------------------------ // Render a continuous-gradient legend bar for one of the two continuous // overlays (gc, length). Both share the same SVG shape; they just differ // in palette and tick labels — so we factor the duplication out. function renderGradientLegend(palette, ticksHtml) { const uid = Math.random().toString(36).slice(2, 8); const stops = palette .filter((_, i) => i % 8 === 0) // 32 stops is plenty for a 1D bar .map((c, i, a) => `<stop offset="${(i / (a.length - 1)) * 100}%" stop-color="rgb(${c[0]},${c[1]},${c[2]})"/>`) .join(""); legend.innerHTML = `<span class="item gc-grad"> <svg width="160" height="10" aria-hidden="true"> <defs><linearGradient id="umap-grad-${uid}" x1="0" x2="1">${stops}</linearGradient></defs> <rect width="160" height="10" fill="url(#umap-grad-${uid})"/> </svg> <span class="gc-ticks">${ticksHtml}</span> </span>`; } function renderLegend() { if (!labels) return; // gc_content is continuous — render a horizontal gradient bar with // 0.0 / 0.5 / 1.0 ticks instead of one swatch per value (would be // 256 entries, useless visually). if (colorBy === "gc") { renderGradientLegend(GC_PALETTE, "0.0 · 0.5 · 1.0"); return; } if (colorBy === "length") { // Tick labels span the full bp range using formatBp(). Geometric // midpoint (sqrt of low × high) rather than arithmetic so the // middle tick lands at the *log-scale* centre of the gradient, // which is what the colour ramp is keyed on. const lr = labels.length_bp_range; const ticks = lr ? `${formatBp(lr[0])} · ${formatBp(Math.round(Math.sqrt(lr[0] * lr[1])))} · ${formatBp(lr[1])}` : "short · mid · long"; renderGradientLegend(LENGTH_PALETTE, ticks); return; } const palette = PALETTES[colorBy]; const itemLabels = (colorBy === "species") ? labels.species : (colorBy === "biotype") ? labels.biotypes : labels.strands; legend.innerHTML = itemLabels.map((name, i) => { const [r, g, b] = palette[i % palette.length]; return `<span class="item"><span class="swatch" style="background:rgb(${r},${g},${b})"></span>${name}</span>`; }).join(""); }
// ---- Pan / zoom / hover ------------------------------------------------ // Reset is a no-op when we're already at the fit-the-data view, so the // button switches to a disabled state in that case — same affordance as // a back-button greying out at the top of the history stack. Avoids a // distracting always-active control on first paint. function updateResetEnabled() { if (!resetBtn) return; const atDefault = view.tx === 0 && view.ty === 0 && view.scale === 1; resetBtn.disabled = atDefault; } function resetView() { view = { tx: 0, ty: 0, scale: 1 }; updateResetEnabled(); requestRedraw(); }
// Keep the viewport always full of data. The data spans [-0.92, 0.92]·scale // in world space; the viewport spans [-1, 1]. As long as 0.92·scale ≥ 1 // (zoom ≥ ~1.087), there's "slack" we can pan within: |tx| ≤ 0.92·scale-1. // Below that — i.e. at minimum zoom where the UMAP fits the viewport with // margin — we snap to (0, 0) so the data stays centered and no white edge // creeps in. Paired with the scale clamp in the wheel handler, this means // "fully zoomed out" = "UMAP exactly fit, perfectly centered". function clampPan() { const m = Math.max(0, 0.92 * view.scale - 1); if (m === 0) { view.tx = 0; view.ty = 0; } else { view.tx = Math.max(-m, Math.min(m, view.tx)); view.ty = Math.max(-m, Math.min(m, view.ty)); } }
// Convert a clientX/Y to NDC (-1..1) and to normalized data space ([-1, 1]). function clientToNDC(e) { const rect = canvas.getBoundingClientRect(); return { x: ((e.clientX - rect.left) / rect.width) * 2 - 1, y: -((e.clientY - rect.top) / rect.height) * 2 + 1, }; } function ndcToData(ndc) { const baseScale = 0.92; return { x: (ndc.x - view.tx) / (baseScale * view.scale), y: (ndc.y - view.ty) / (baseScale * view.scale), }; }
let panning = false, panLast = null; canvas.addEventListener("pointerdown", e => { canvas.setPointerCapture(e.pointerId); panning = true; panLast = { x: e.clientX, y: e.clientY }; canvas.classList.add("panning"); hideTooltip(); }); canvas.addEventListener("pointermove", e => { if (panning) { const rect = canvas.getBoundingClientRect(); const dx = ((e.clientX - panLast.x) / rect.width) * 2; const dy = -((e.clientY - panLast.y) / rect.height) * 2; view.tx += dx; view.ty += dy; clampPan(); updateResetEnabled(); panLast = { x: e.clientX, y: e.clientY }; requestRedraw(); } else { handleHover(e); } }); function endPan(e) { if (!panning) return; panning = false; canvas.classList.remove("panning"); try { canvas.releasePointerCapture(e.pointerId); } catch {} } canvas.addEventListener("pointerup", endPan); canvas.addEventListener("pointercancel", endPan); canvas.addEventListener("pointerleave", () => hideTooltip());
canvas.addEventListener("wheel", e => { e.preventDefault(); const ndc = clientToNDC(e); // Zoom factor — natural feeling on both trackpad and mouse wheel. const factor = Math.exp(-e.deltaY * 0.0018); // Min scale = 1 means "fully zoomed out = UMAP fits the viewport". We // intentionally don't let the visitor zoom out further: there's no // information past the data bounds, and the empty margin makes the // dataset feel small. Max 50× keeps individual points pickable. const newScale = Math.min(50, Math.max(1, view.scale * factor)); const k = newScale / view.scale; // Zoom around the cursor: shift translate so the point under the cursor // stays under the cursor. view.tx = ndc.x - (ndc.x - view.tx) * k; view.ty = ndc.y - (ndc.y - view.ty) * k; view.scale = newScale; clampPan(); updateResetEnabled(); requestRedraw(); hideTooltip(); }, { passive: false });
resetBtn.addEventListener("click", resetView);
// ---- Hover picking ----------------------------------------------------- // De-quantise a uint8 length byte back to bp. Inverse of the // packing step in scripts/build_real_umap.py: // bp = round(10 ** (log_min + b/255 * (log_max - log_min))) function lengthBpAt(idx) { if (!cats.length || !labels || !labels.length_log10_range) return null; const [lo, hi] = labels.length_log10_range; const t = cats.length[idx] / 255; return Math.round(Math.pow(10, lo + t * (hi - lo))); } function escapeHtml(s) { return String(s).replace(/[&<>"']/g, (c) => ( { "&": "&", "<": "<", ">": ">", "\"": """, "'": "'" }[c] )); } function showTooltip(idx, x, y) { const sp = labels.species[cats.species[idx]]; const bt = labels.biotypes[cats.biotype[idx]]; const st = labels.strands[cats.strand[idx]]; const gc = cats.gc ? (cats.gc[idx] / 255).toFixed(2) : "—"; const bp = lengthBpAt(idx); const lenStr = bp == null ? "—" : formatBp(bp); // `names` may still be null if the user hovers very early (race // between WebGL paint and /umap_names landing) — fall back to em- // dash; the row will silently fill in once the strip arrives. const nameStr = names ? escapeHtml(names[idx] || "—") : "—"; tooltip.innerHTML = `<div><span class="t-label">name</span>${nameStr}</div>` + `<div><span class="t-label">species</span>${sp}</div>` + `<div><span class="t-label">biotype</span>${bt}</div>` + `<div><span class="t-label">length</span>${lenStr}</div>` + `<div><span class="t-label">strand</span>${st} <span class="t-label">gc</span>${gc}</div>`; tooltip.style.left = x + "px"; tooltip.style.top = y + "px"; tooltip.classList.add("visible"); } function hideTooltip() { tooltip.classList.remove("visible"); }
function handleHover(e) { if (!grid) return; const ndc = clientToNDC(e); const data = ndcToData(ndc); // Convert data-space (-1..1) into grid coords. const gx = (data.x + 1) * 0.5 * GRID_N; const gy = (data.y + 1) * 0.5 * GRID_N; const cx = Math.floor(gx), cy = Math.floor(gy); if (cx < -1 || cx > GRID_N || cy < -1 || cy > GRID_N) return hideTooltip();
// Adaptive search radius: at higher zoom, we want a tighter pick radius. // ~8px screen radius converted to data space. const rect = canvas.getBoundingClientRect(); const screenR = 8; const dataR = (screenR / rect.width) * 2 / (0.92 * view.scale); const dataR2 = dataR * dataR;
let best = -1, bestD2 = dataR2; const cellSpan = Math.max(1, Math.ceil(dataR * GRID_N * 0.5) + 1); for (let dy = -cellSpan; dy <= cellSpan; dy++) { const yy = cy + dy; if (yy < 0 || yy >= GRID_N) continue; for (let dx = -cellSpan; dx <= cellSpan; dx++) { const xx = cx + dx; if (xx < 0 || xx >= GRID_N) continue; const list = grid[yy * GRID_N + xx]; if (!list) continue; for (let k = 0; k < list.length; k++) { const idx = list[k]; // Recompute the point's normalized [-1, 1] position from posBuf16 // — we don't keep it on CPU, but we can re-derive from int16 cheaply. const px = posSnapshot[2*idx] / 32767; const py = posSnapshot[2*idx + 1] / 32767; const ex = px - data.x, ey = py - data.y; const d2 = ex*ex + ey*ey; if (d2 < bestD2) { bestD2 = d2; best = idx; } } } } if (best === -1) return hideTooltip(); // Place tooltip near cursor, offset to the right & above. const relX = e.clientX - rect.left; const relY = e.clientY - rect.top; showTooltip(best, relX, relY); }
// We need an unattached CPU-side copy of positions for hover hit-testing // because WebGL buffers aren't readable from JS without a roundtrip. let posSnapshot = null;
// ---- Bootstrap --------------------------------------------------------- setupGL();
colorPills.forEach(p => { p.addEventListener("click", () => { colorPills.forEach(x => x.classList.toggle("active", x === p)); setColorBy(p.dataset.color); }); });
// Defer loading until the umap section is near the viewport — 571K points // doesn't need to fight for bandwidth on first paint. const io = new IntersectionObserver(async (entries) => { if (!entries[0].isIntersecting) return; io.disconnect(); try { const pos16 = await loadData(); posSnapshot = pos16; setColorBy("species"); // initial coloring + first draw
// Two-phase load: heavy gene-name strip (~6.5 MB plain text, // ~1.9 MB gzipped) lands AFTER the WebGL render is up. The // tooltip silently upgrades from "—" to the real name as soon // as it's parsed and re-aligned to the shuffled order. Failures // here are non-fatal — the scatter still works without names. if (labels && labels.has_names) { fetch("/umap_names") .then(r => r.ok ? r.text() : Promise.reject(new Error("names " + r.status))) .then(txt => { const raw = txt.split("\n"); if (raw.length < n) { console.warn(`/umap_names short: ${raw.length} < ${n}, ignoring`); return; } const aligned = new Array(n); for (let i = 0; i < n; i++) aligned[i] = raw[shufflePerm[i]]; names = aligned; }) .catch(err => console.warn("gene names load failed:", err)); } } catch (err) { console.error(err); setStatus("error", "load failed"); overlay.textContent = "load failed · " + err.message; } }, { rootMargin: "400px" }); io.observe(canvas);
window.addEventListener("resize", () => requestRedraw());})();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274// =========================================================================// §2 — VEP: ref vs alt allele likelihood// =========================================================================(function initDemo2() { const els = { pills: document.getElementById("d2-pills"), info: document.getElementById("d2-info"), window: document.getElementById("d2-window"), result: document.getElementById("d2-result"), bars: document.getElementById("d2-bars"), go: document.getElementById("d2-go"), all: document.getElementById("d2-all"), status: document.getElementById("d2-status"), statusText: document.querySelector("#d2-status span:last-child"), };
let VARIANTS = null; let selected = null; const cache = {}; // by rs id → { refSum, altSum, refLps, altLps }
function setStatus(text, mode = "") { els.statusText.textContent = text; els.status.className = "status" + (mode ? " " + mode : ""); }
function altWindow(v) { return v.ref_window.slice(0, v.var_offset) + v.alt + v.ref_window.slice(v.var_offset + 1); }
function renderWindowDisplay(v, mode = "ref") { if (!v) { els.window.innerHTML = "—"; return; } const left = v.ref_window.slice(0, v.var_offset); const right = v.ref_window.slice(v.var_offset + 1); const cls = mode === "ref" ? "var-ref" : "var-alt"; const base = mode === "ref" ? v.ref : v.alt; els.window.innerHTML = `<span class="ctx">${left}</span><span class="${cls}">${base}</span><span class="ctx">${right}</span>`; }
function renderResult(v) { if (!v) { els.result.innerHTML = ""; return; } const c = cache[v.rs]; if (!c) { els.result.innerHTML = `<div style="grid-column:1/-1;color:#aaa;font-style:italic">click "score" to compute likelihoods…</div>`; return; } // Map sums to a common scale: take min/max across both for visual ratio. const lo = Math.min(c.refSum, c.altSum); const hi = Math.max(c.refSum, c.altSum); // Logprobs are negative; scale bar width as |sum| / |min(both)| so the more-negative gets a longer bar. const range = Math.abs(lo); const wRef = (Math.abs(c.refSum) / range) * 100; const wAlt = (Math.abs(c.altSum) / range) * 100; const delta = c.altSum - c.refSum; const dColor = delta < -0.5 ? "#bc2e25" : (delta > 0.5 ? "#317f3f" : "#888"); els.result.innerHTML = ` <div class="row-label">ref · ${v.ref}</div> <div class="row-bar ref"><div class="fill" style="width:${wRef.toFixed(1)}%"></div></div> <div class="row-val">${c.refSum.toFixed(2)}</div> <div class="row-label">alt · ${v.alt}</div> <div class="row-bar alt"><div class="fill" style="width:${wAlt.toFixed(1)}%"></div></div> <div class="row-val">${c.altSum.toFixed(2)}</div> <div class="row-label">Δ</div> <div></div> <div class="row-val row-delta" style="color:${dColor}">${(delta >= 0 ? "+" : "") + delta.toFixed(2)}</div> `; }
function renderForestBars() { if (!VARIANTS) return; const W = 1000, rowH = 32, padL = 280, padR = 60, padT = 36, padB = 50; // Sort variants by Δ ascending (most surprising-to-the-model first), but // keep unscored ones at the bottom in their original order. const indexed = VARIANTS.map((v, i) => ({ v, idx: i, d: cache[v.rs] ? cache[v.rs].altSum - cache[v.rs].refSum : null })); const scored = indexed.filter(x => x.d != null).sort((a, b) => a.d - b.d); const unscored = indexed.filter(x => x.d == null); const ordered = scored.concat(unscored); const H = padT + ordered.length * rowH + padB; els.bars.setAttribute("viewBox", `0 0 ${W} ${H}`); els.bars.setAttribute("height", H);
if (!scored.length) { els.bars.innerHTML = `<text x="${W/2}" y="${H/2}" text-anchor="middle" font-family="JetBrains Mono" font-size="11" fill="#bbb">— score variants to populate the comparison —</text>`; return; } const absMax = Math.max(2, ...scored.map(x => Math.abs(x.d))); const innerW = W - padL - padR; const center = padL + innerW / 2; const scale = (innerW / 2) / absMax; const sigColor = (s) => s === "Pathogenic" ? "#bc2e25" : s === "Benign" ? "#317f3f" : "#e69500";
// Bar color: encode the *model's* opinion of the alt allele // - Δ < 0 : red (model finds alt unusual). Saturation ~ |Δ|. // - Δ > 0 : charcoal (model is fine with / prefers alt). // - |Δ| ≈ 0 : muted gray. function barColor(d) { const ad = Math.abs(d); if (ad < 0.5) return "#bbb"; const t = Math.min(1, ad / 4); // 4 = saturation point; bigger Δ doesn't get redder if (d < 0) { // gray → red return `rgb(${lerp(170, 216, t)},${lerp(170, 58, t)},${lerp(170, 42, t)})`; } // gray → charcoal return `rgb(${lerp(170, 40, t)},${lerp(170, 40, t)},${lerp(170, 40, t)})`; } const VALUE_INSIDE_MIN = 44;
let svg = "";
// --- Top axis: directional caption --- svg += `<text x="${padL.toFixed(1)}" y="14" font-family="JetBrains Mono" font-size="9" fill="#bc2e25" letter-spacing="1">← MODEL SURPRISED BY ALT</text>`; svg += `<text x="${(W - padR).toFixed(1)}" y="14" font-family="JetBrains Mono" font-size="9" fill="#333" letter-spacing="1" text-anchor="end">MODEL FINE WITH ALT →</text>`; svg += `<text x="${center.toFixed(1)}" y="14" font-family="JetBrains Mono" font-size="9" fill="#888" text-anchor="middle" letter-spacing="1">Δ (alt − ref)</text>`; svg += `<text x="${(padL - 12).toFixed(1)}" y="14" font-family="JetBrains Mono" font-size="9" fill="#888" text-anchor="end" letter-spacing="1">VARIANT</text>`;
// Faint shading: pathogenic-expected zone (left of 0) svg += `<rect x="${padL.toFixed(1)}" y="${(padT - 4).toFixed(1)}" width="${(center - padL).toFixed(1)}" height="${(ordered.length * rowH + 8).toFixed(1)}" fill="#bc2e25" opacity="0.04"/>`;
// Center line svg += `<line x1="${center}" y1="${padT - 4}" x2="${center}" y2="${H - padB + 4}" stroke="#bbb" stroke-width="1"/>`; // Axis ticks for (const t of [-absMax, -absMax/2, 0, absMax/2, absMax]) { const x = center + t * scale; svg += `<line x1="${x.toFixed(1)}" y1="${(H - padB).toFixed(1)}" x2="${x.toFixed(1)}" y2="${(H - padB + 4).toFixed(1)}" stroke="#aaa"/>`; svg += `<text x="${x.toFixed(1)}" y="${(H - padB + 14).toFixed(1)}" font-family="JetBrains Mono" font-size="9" fill="#888" text-anchor="middle">${t.toFixed(1)}</text>`; }
// --- Rows --- ordered.forEach(({ v, d }, i) => { const y = padT + i * rowH + rowH / 2;
// Curated category dot next to the variant name const dotR = 4; const dotX = padL - 12 - dotR; svg += `<circle cx="${dotX.toFixed(1)}" cy="${(y - 0.5).toFixed(1)}" r="${dotR}" fill="${sigColor(v.sig)}"><title>${v.sig}</title></circle>`;
// Variant name + tiny category label svg += `<text x="${(dotX - dotR - 6).toFixed(1)}" y="${(y - 1).toFixed(1)}" font-family="JetBrains Mono" font-size="11" fill="#222" text-anchor="end">${v.name}</text>`; svg += `<text x="${(dotX - dotR - 6).toFixed(1)}" y="${(y + 11).toFixed(1)}" font-family="JetBrains Mono" font-size="9" fill="${sigColor(v.sig)}" text-anchor="end">${v.sig.toLowerCase()}</text>`;
if (d == null) { svg += `<text x="${(center + 6).toFixed(1)}" y="${(y + 4).toFixed(1)}" font-family="JetBrains Mono" font-size="10" fill="#ccc">— not scored —</text>`; return; }
const x = center + d * scale; const color = barColor(d); const barX = Math.min(center, x); const barW = Math.max(2, Math.abs(x - center)); svg += `<rect x="${barX.toFixed(1)}" y="${(y - 8).toFixed(1)}" width="${barW.toFixed(1)}" height="14" fill="${color}" stroke="${v === selected ? '#1f1f1d' : 'none'}" stroke-width="${v === selected ? 1 : 0}"/>`;
const label = (d >= 0 ? "+" : "") + d.toFixed(2); const insideOK = barW >= VALUE_INSIDE_MIN && Math.abs(d) >= 0.5; // color is dark enough only away from neutral if (insideOK) { const tx = x + (d >= 0 ? -5 : 5); const anchor = d >= 0 ? "end" : "start"; svg += `<text x="${tx.toFixed(1)}" y="${(y + 3.5).toFixed(1)}" font-family="JetBrains Mono" font-size="10" fill="#fff" text-anchor="${anchor}" font-weight="500">${label}</text>`; } else { const tx = x + (d >= 0 ? 5 : -5); const anchor = d >= 0 ? "start" : "end"; svg += `<text x="${tx.toFixed(1)}" y="${(y + 3.5).toFixed(1)}" font-family="JetBrains Mono" font-size="10" fill="#333" text-anchor="${anchor}">${label}</text>`; } });
// --- Bottom caption --- const capY = H - padB + 32; svg += `<text x="${padL.toFixed(1)}" y="${capY}" font-family="JetBrains Mono" font-size="9" fill="#888" letter-spacing="0.5">expected for pathogenic loss-of-function: Δ ≪ 0 · expected for benign / common: Δ ≈ 0</text>`;
els.bars.innerHTML = svg; }
async function scoreOne(v) { if (cache[v.rs]) return cache[v.rs]; const ref = v.ref_window; const alt = altWindow(v); // Score both in parallel const [refResp, altResp] = await Promise.all([ fetch("/score", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ sequence: ref }) }).then(r => r.json()), fetch("/score", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ sequence: alt }) }).then(r => r.json()), ]); if (refResp.error) throw new Error("ref: " + refResp.error); if (altResp.error) throw new Error("alt: " + altResp.error); const sumLp = (lps) => { let s = 0, n = 0; for (const lp of lps) { if (lp != null && !isNaN(lp)) { s += lp; n++; } } return { sum: s, n }; }; const r = sumLp(refResp.token_logprobs); const a = sumLp(altResp.token_logprobs); const result = { refSum: r.sum, altSum: a.sum, n: r.n, refLps: refResp.token_logprobs, altLps: altResp.token_logprobs, }; cache[v.rs] = result; return result; }
async function scoreSelected() { if (!selected) return; setStatus(`scoring ${selected.name}…`, "streaming"); els.go.disabled = true; els.all.disabled = true; try { await scoreOne(selected); renderResult(selected); renderForestBars(); setStatus("done"); } catch (e) { setStatus(e.message, "error"); } finally { els.go.disabled = false; els.all.disabled = false; } }
async function scoreAll() { setStatus("scoring all…", "streaming"); els.go.disabled = true; els.all.disabled = true; try { // Sequential to be polite to the endpoint and to allow incremental UI updates. for (const v of VARIANTS) { if (cache[v.rs]) continue; await scoreOne(v); renderForestBars(); } if (selected) renderResult(selected); setStatus("done"); } catch (e) { setStatus(e.message, "error"); } finally { els.go.disabled = false; els.all.disabled = false; } }
function selectVariant(rs) { const v = VARIANTS.find(x => x.rs === rs); if (!v) return; selected = v; els.pills.querySelectorAll(".pill").forEach(p => p.classList.toggle("active", p.dataset.rs === rs)); els.info.innerHTML = `<strong>${v.name}</strong> · ${v.blurb} · <span style="color:#888">chr${v.chrom}:${v.pos.toLocaleString("en-US")} · ${v.ref}>${v.alt} (gene strand)</span>`; renderWindowDisplay(v, "ref"); renderResult(v); renderForestBars(); }
fetch("/variants").then(r => r.json()).then(data => { VARIANTS = data; // Hydrate cache from precomputed scores if present for (const v of data) { if (v.score) { cache[v.rs] = { refSum: v.score.ref_sum, altSum: v.score.alt_sum, refLps: v.score.ref_logprobs, altLps: v.score.alt_logprobs, n: v.score.n, }; } } els.pills.innerHTML = data.map((v, i) => `<button class="pill sig-${v.sig}${i === 0 ? " active" : ""}" data-rs="${v.rs}" title="${v.blurb}">${v.gene} ${v.ref}>${v.alt}</button>` ).join(""); els.pills.querySelectorAll(".pill").forEach(p => { p.addEventListener("click", () => selectVariant(p.dataset.rs)); }); selectVariant(data[0].rs); }).catch(e => { els.info.textContent = "failed to load variants: " + e.message; });
els.go.addEventListener("click", scoreSelected); els.all.addEventListener("click", scoreAll);})();
123456789101112131415161718192021222324252627282930313233// =========================================================================// Init: config + load gene catalog (used by §1, §3)// =========================================================================// Memoize the *promise* (not the value) so concurrent callers share one fetch.// The previous "if (GENES) return GENES" pattern was racy: two callers firing// before the first response landed both triggered a network request.let CONFIG_PROMISE = null;function fetchConfig() { if (!CONFIG_PROMISE) { CONFIG_PROMISE = fetch("/config").then(r => r.json()); } return CONFIG_PROMISE;}async function loadConfig() { try { const cfg = await fetchConfig(); document.getElementById("meta").textContent = cfg.model; document.getElementById("footer-model").textContent = cfg.model; } catch { document.getElementById("meta").textContent = "config unavailable"; }}
// Keep the resolved value on the global `GENES` for downstream code that// reaches into it synchronously inside loadGenes().then() callbacks.let GENES = null;let GENES_PROMISE = null;function loadGenes() { if (!GENES_PROMISE) { GENES_PROMISE = fetch("/genes").then(r => r.json()).then(g => { GENES = g; return g; }); } return GENES_PROMISE;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475// =========================================================================// Shared helpers// =========================================================================const DARK_RGB = [31, 31, 29];const MID_RGB = [136, 136, 136];const RED_RGB = [188, 46, 37];const PROMPT_RGB = [170, 170, 170];
function lerp(a, b, t) { return Math.round(a + (b - a) * t); }function lerpRgb(c1, c2, t) { return [lerp(c1[0], c2[0], t), lerp(c1[1], c2[1], t), lerp(c1[2], c2[2], t)];}function logprobRgb(lp, range) { if (lp == null || isNaN(lp) || !range) return DARK_RGB; const { min, mid, max } = range; if (max === min) return MID_RGB; if (lp >= mid) { const denom = max - mid; const t = denom > 0 ? Math.min(1, Math.max(0, (max - lp) / denom)) : 0; return lerpRgb(DARK_RGB, MID_RGB, t); } const denom = mid - min; const t = denom > 0 ? Math.min(1, Math.max(0, (mid - lp) / denom)) : 0; return lerpRgb(MID_RGB, RED_RGB, t);}function lpRangeOf(tokens) { let min = Infinity, max = -Infinity, sum = 0, n = 0; for (const t of tokens) { const lp = t.logprob; if (lp == null || isNaN(lp)) continue; if (lp < min) min = lp; if (lp > max) max = lp; sum += lp; n++; } return n ? { min, mid: sum / n, max } : null;}function meanLogprob(tokens) { const r = lpRangeOf(tokens); return r ? r.mid : null;}
// Render a sequence line-by-line with optional per-base coloring fn `colorAt(absIdx, base)`.// 10-bp blocks separated by 2 spaces, position number prefix.function renderSeq(el, seq, basesPerLine, colorAt) { if (!seq) { el.classList.add("empty"); el.textContent = "—"; return; } el.classList.remove("empty"); const parts = []; for (let i = 0; i < seq.length; i += basesPerLine) { const lineSeq = seq.slice(i, i + basesPerLine); const pos = String(i + 1).padStart(5, " "); let html = `<span class="pos">${pos}</span> `; let j = 0; while (j < lineSeq.length) { if (j > 0 && j % 10 === 0) html += " "; const absIdx = i + j; const c = colorAt(absIdx, lineSeq[j]); // Group identical-style runs within the 10-base block. const blockEnd = Math.min(lineSeq.length, Math.floor(j / 10) * 10 + 10); let runEnd = j + 1; while (runEnd < blockEnd) { const cn = colorAt(i + runEnd, lineSeq[runEnd]); if (cn.style !== c.style) break; runEnd++; } html += `<span style="${c.style}">${lineSeq.slice(j, runEnd)}</span>`; j = runEnd; } parts.push(`<div>${html}</div>`); } el.innerHTML = parts.join("");}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152// =========================================================================// Tab switching + hash routing// =========================================================================(function initTabs() { const TABS = ["demo", "model", "sandbox"]; const tabButtons = document.querySelectorAll("#tab-nav .tab"); const panels = document.querySelectorAll(".tab-panel");
function setTab(name, opts = {}) { if (!TABS.includes(name)) name = "demo"; document.body.dataset.tab = name; tabButtons.forEach(b => b.classList.toggle("active", b.dataset.tab === name)); panels.forEach(p => p.classList.toggle("active", p.dataset.tab === name)); if (opts.scroll !== false) window.scrollTo({ top: 0, behavior: opts.smooth ? "smooth" : "auto" }); if (opts.updateHash !== false) { // Preserve any anchor inside the tab if requested if (opts.anchor) location.hash = opts.anchor; else if (location.hash.replace("#", "") !== name) location.hash = name; } }
// Map a section anchor → which tab contains it const SECTION_TO_TAB = { completion: "demo", vep: "demo", track: "demo", species: "demo", folding: "demo", umap: "demo", tokenizer: "model", loss: "model", data: "model", architecture: "model", sandbox: "sandbox", };
function applyHash() { const hash = location.hash.replace(/^#/, ""); if (!hash) { setTab("demo", { updateHash: false }); return; } if (TABS.includes(hash)) { setTab(hash, { updateHash: false }); return; } if (SECTION_TO_TAB[hash]) { setTab(SECTION_TO_TAB[hash], { updateHash: false, scroll: false }); // Defer scroll until panel is visible requestAnimationFrame(() => { const el = document.getElementById(hash); if (el) el.scrollIntoView({ behavior: "smooth", block: "start" }); }); return; } setTab("demo", { updateHash: false }); }
tabButtons.forEach(b => { b.addEventListener("click", () => setTab(b.dataset.tab)); }); window.addEventListener("hashchange", applyHash); applyHash();})();
loadConfig();1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192/* banner.css — editorial Carbon hero banner. Scoped to .carbon-banner. The SVG self-sizes from its viewBox aspect ratio (drives the banner height); the animated DNA helix is rendered on a Canvas overlay positioned to mirror the original helix bbox. */
.banner-wrap { max-width: 1080px; margin: 0 auto; padding: 24px 32px 0;}.carbon-banner { --paper: #f7f5ee; --ink: #1f1f1d; --muted: #8c918b; --hairline: #b9bcb7; --green: #317f3f; --red: #bc2e25;
display: block; width: 100%; position: relative; overflow: hidden; background: radial-gradient(circle at 22% 32%, rgba(0, 0, 0, 0.035), transparent 1px), radial-gradient(circle at 78% 64%, rgba(0, 0, 0, 0.03), transparent 1px), linear-gradient(90deg, rgba(49, 127, 63, 0.025), transparent 34%, transparent 66%, rgba(49, 127, 63, 0.025)), var(--paper); background-size: 7px 7px, 11px 11px, auto, auto; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;}/* SVG self-sizes from its viewBox aspect ratio — drives the banner height. */.carbon-banner .carbon-art { display: block; width: 100%; height: auto; }/* Canvas overlay for the animated DNA helix. Positioned to mirror the original helix bbox in viewBox space: x ∈ [858, 1998] of [40, 2010] → left 41.52%, width 57.87% y ∈ [220, 416] of [50, 590] → top 31.48%, height 36.30% */.carbon-banner .cb-helix-canvas { position: absolute; left: 41.52%; top: 31.48%; width: 57.87%; height: 36.30%; pointer-events: none; display: block;}.carbon-banner .cb-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; letter-spacing: 0.24em; text-transform: uppercase;}.carbon-banner .cb-rule { stroke: var(--hairline); stroke-width: 1; vector-effect: non-scaling-stroke; }.carbon-banner .cb-label { fill: var(--ink); font-size: 17px; letter-spacing: 0.24em; }.carbon-banner .cb-label-green { fill: var(--green); }.carbon-banner .cb-label-red { fill: var(--red); }.carbon-banner .cb-carbon-word { fill: var(--ink); font-family: "Arial Narrow", "Helvetica Neue", Arial, sans-serif; font-size: 255px; font-stretch: condensed; font-weight: 900; letter-spacing: -0.02em;}.carbon-banner .cb-paper-grain { mix-blend-mode: multiply; opacity: 0.62; pointer-events: none; }.carbon-banner .cb-helix-shadow { fill: #aeb5ad; opacity: 0.15; }.carbon-banner .cb-helix-body { fill: #e4e5dc; stroke: rgba(49, 127, 63, 0.14); stroke-width: 0.8;}.carbon-banner .cb-helix-edge { fill: none; stroke: #2d332e; stroke-width: 1.15; stroke-linecap: round; stroke-linejoin: round; vector-effect: non-scaling-stroke;}.carbon-banner .cb-helix-texture { fill: url(#cb-helixGrain); opacity: 0.46; }.carbon-banner .cb-base-pair { fill: none; stroke: var(--green); stroke-width: 1.35; stroke-linecap: round; vector-effect: non-scaling-stroke;}.carbon-banner .cb-base-letter-node { will-change: transform, opacity; transform-box: fill-box; transform-origin: 0 0;}.carbon-banner .cb-base-glyph { fill: none; stroke: var(--green); stroke-width: 1.8; stroke-linecap: square; stroke-linejoin: miter; vector-effect: non-scaling-stroke;}.carbon-banner .cb-tiny-bars rect { fill: var(--green); }@media (max-width: 760px) { .banner-wrap { padding: 12px 16px 0; }}1234567891011121314151617181920212223242526/* base.css — global reset, page background, container, scrollbar. Defines the @keyframes (pulse) referenced from .status, sandbox, and .fold-viewer.running so it has to load before any consumer. */
* { margin: 0; padding: 0; box-sizing: border-box; }html { scroll-behavior: smooth; }body { font-family: "Inter", "Helvetica Neue", sans-serif; font-size: 13px; font-weight: 300; line-height: 1.7; color: #1f1f1d; background: radial-gradient(circle at 22% 32%, rgba(0, 0, 0, 0.035), transparent 1px), radial-gradient(circle at 78% 64%, rgba(0, 0, 0, 0.03), transparent 1px), linear-gradient(90deg, rgba(49, 127, 63, 0.025), transparent 34%, transparent 66%, rgba(49, 127, 63, 0.025)), #f7f5ee; background-size: 7px 7px, 11px 11px, auto, auto; padding: 0;}.container { max-width: 760px; margin: 0 auto; padding: 48px 32px 96px; }.container.wide { max-width: 1080px; }
@keyframes pulse { 50% { opacity: 0.3; } }
::-webkit-scrollbar { width: 8px; height: 8px; }::-webkit-scrollbar-thumb { background: #ccc; border-radius: 4px; }::-webkit-scrollbar-track { background: transparent; }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364/* controls.css — shared interactive atoms used by every demo card: the demo card frame, demo-toolbar row, action buttons, pill toggles, stub placeholders for unbuilt demos, and the .status pill (idle / streaming / error). */
/* --- Demo card (the interactive box inside each section) --- */.demo { background: #fff; border: 1px solid #ddd; padding: 24px; margin: 24px 0;}.demo-toolbar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 16px; font-family: "JetBrains Mono", monospace; font-size: 10px; color: #666; text-transform: uppercase; letter-spacing: 1px;}.demo-toolbar .spacer { flex: 1; }
/* --- Buttons --- */button.action, .pill { font-family: "JetBrains Mono", monospace; font-size: 10px; font-weight: 400; padding: 5px 11px; border: 1px solid #ccc; border-radius: 3px; background: #fff; color: #555; cursor: pointer; text-transform: uppercase; letter-spacing: 1.5px; transition: all 0.15s;}button.action:hover, .pill:hover { border-color: #888; color: #1f1f1d; }button.action.primary { background: #1f1f1d; color: #fff; border-color: #1f1f1d; }button.action.primary:hover { background: #000; }button.action:disabled { opacity: 0.4; cursor: not-allowed; }button.action.primary:disabled { background: #888; border-color: #888; }.pill.active { background: #1f1f1d; color: #fff; border-color: #1f1f1d; }.pills { display: inline-flex; gap: 4px; }.pills .pill { font-size: 9px; padding: 4px 8px; }
/* --- Stub placeholder for unbuilt demos --- */.stub { padding: 48px 24px; text-align: center; color: #999; font-family: "JetBrains Mono", monospace; font-size: 11px; text-transform: uppercase; letter-spacing: 2px; border: 1px dashed #ddd; background: #fff;}.stub-tag { display: inline-block; padding: 2px 8px; border: 1px solid #ddd; border-radius: 2px; font-size: 9px; color: #aaa; margin-bottom: 8px;}
/* --- Status pill (idle / streaming / error) shared by demo toolbars --- */.status { font-family: "JetBrains Mono", monospace; font-size: 10px; color: #666; text-transform: uppercase; letter-spacing: 1.5px; display: inline-flex; align-items: center; gap: 6px; margin-left: 8px;}.status .dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: #888;}/* `pulse` keyframe lives in base.css so it's defined before any consumer. */.status.streaming .dot { background: #317f3f; animation: pulse 1.2s ease-in-out infinite; }.status.error { color: #b00020; }1234567891011/* footer.css — page footer: model identifier line at the bottom. */
footer { text-align: center; padding: 48px 32px; color: #999; font-size: 11px; font-family: "JetBrains Mono", monospace; letter-spacing: 1px; text-transform: uppercase; border-top: 1px solid #eee;}footer a { color: #666; text-decoration: none; }footer a:hover { color: #1f1f1d; }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061/* header.css — sticky page header (CARBON title + tagline + tab strip) and the tab-panel show/hide toggles driven by .active. */
header { border-bottom: 1px solid #ccc; /* separator line under the tab strip */ padding: 24px 32px 0; /* no bottom padding — tabs sit on the line */ margin-bottom: 0; background: radial-gradient(circle at 22% 32%, rgba(0, 0, 0, 0.035), transparent 1px), radial-gradient(circle at 78% 64%, rgba(0, 0, 0, 0.03), transparent 1px), linear-gradient(90deg, rgba(49, 127, 63, 0.025), transparent 34%, transparent 66%, rgba(49, 127, 63, 0.025)), #f7f5ee; background-size: 7px 7px, 11px 11px, auto, auto; position: sticky; top: 0; z-index: 10; /* Promote to its own compositing layer so the gradient pattern doesn't force the entire viewport to repaint on every scroll event. */ will-change: transform;}.header-inner { max-width: 1080px; margin: 0 auto; display: flex; justify-content: space-between; align-items: flex-end; flex-wrap: wrap; gap: 16px 32px;}.header-title { padding-bottom: 14px; }h1 { font-family: "JetBrains Mono", monospace; font-size: 16px; font-weight: 400; letter-spacing: 2px;}.tagline { font-family: "JetBrains Mono", monospace; color: #888; font-size: 10px; font-weight: 300; letter-spacing: 1px; margin-top: 4px; text-transform: uppercase;}nav#tab-nav { display: flex; font-family: "JetBrains Mono", monospace; font-size: 11px; text-transform: uppercase; letter-spacing: 1.5px; margin-bottom: -1px; /* tabs overlap header's bottom border by 1px */ position: relative; z-index: 1;}nav#tab-nav .tab { width: 130px; padding: 10px 14px; font-family: inherit; font-size: 11px; letter-spacing: 1.5px; text-transform: uppercase; color: #888; background: #f0f0f0; border: 1px solid #ccc; border-radius: 3px 3px 0 0; cursor: pointer; transition: background 0.15s, color 0.15s;}nav#tab-nav .tab + .tab { margin-left: -1px; } /* shared border between adjacent tabs */nav#tab-nav .tab:hover { color: #1f1f1d; background: #f6f6f6; }nav#tab-nav .tab.active { color: #1f1f1d; background: #f7f5ee; border-bottom-color: #f7f5ee; /* hides bottom border so tab merges into content */ z-index: 2;}
/* --- Tab panels --- */.tab-panel { display: none; }.tab-panel.active { display: block; }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160/* layout.css — page-wide structural primitives: tab-lede (paragraph below banner), default vertical section rhythm, part dividers (DEMO / MODEL signposts), section eyebrow / title / lede / takeaway typography, and the .section--two-col layout that parks narrative in a sticky rail next to the demo. */
/* --- Tab lede (short narrative paragraph below the banner) --- */.tab-lede { max-width: 1080px; margin: 4px auto 0; padding: 14px 32px 0;}.tab-lede p { color: #555; font-size: 14px; line-height: 1.7; max-width: 760px; margin: 0;}
/* --- Sections --- */section { border-bottom: 1px solid #eee; padding: 64px 0;}section:last-of-type { border-bottom: none; }
/* --- Part dividers (DEMO / MODEL) --- */.part-divider { text-align: center; padding: 80px 32px 48px; border-top: 1px solid #eee; border-bottom: 1px solid #eee; background: linear-gradient(to bottom, rgba(49,127,63,0.04), transparent);}.part-divider .part-eyebrow { font-family: "JetBrains Mono", monospace; font-size: 10px; color: #317f3f; letter-spacing: 4px; text-transform: uppercase; margin-bottom: 6px;}.part-divider h2 { font-family: "JetBrains Mono", monospace; font-size: 26px; font-weight: 300; letter-spacing: -0.3px; margin-bottom: 8px;}.part-divider p { color: #666; font-size: 13px; max-width: 580px; margin: 0 auto;}
.section-num { font-family: "JetBrains Mono", monospace; font-size: 10px; color: #317f3f; letter-spacing: 2px; text-transform: uppercase; margin-bottom: 8px;}.section-title { font-family: "JetBrains Mono", monospace; font-size: 22px; font-weight: 400; letter-spacing: -0.3px; margin-bottom: 24px; color: #1f1f1d;}.lede { color: #444; font-size: 14px; margin-bottom: 32px; max-width: 640px;}.takeaway { margin-top: 32px; padding: 16px 20px; border-left: 3px solid #317f3f; background: #f4f8f4; color: #333; font-size: 13px; max-width: 640px;}.takeaway strong { font-family: "JetBrains Mono", monospace; font-weight: 500; letter-spacing: 1px; text-transform: uppercase; font-size: 10px; color: #317f3f; display: block; margin-bottom: 4px;}
/* === Two-column section layout ========================================= The default layout stacks vertically: title → lede → demo → takeaway. For demo-heavy sections that means narrative and visualization never share visual space — by the time the visitor is mid-demo, the lede is scrolled away, and the takeaway only appears after they've finished. .section--two-col places the narrative (eyebrow + title + lede + takeaway) in a sticky rail on the left and lets the demo claim the bulk of the width on the right. Narration stays in view while the visitor scrolls through the demo, turning the takeaway into a live margin note rather than a post-mortem.
Layout math: container.wide is 1080px max with 32px padding => 1016px usable. 248px rail + 32px gap + 736px demo. Below 900px we collapse to single-column and unstick the rail. */.section--two-col { display: grid; grid-template-columns: 248px 1fr; column-gap: 32px; align-items: start; /* Land cleanly under the sticky header on anchor jumps (#folding). */ scroll-margin-top: 104px;}.section--two-col .section-narrative { position: sticky; /* Sticky header is ~88px tall (title + tab strip on its border); +16px so the rail doesn't kiss the underline. */ top: 104px; align-self: start; /* Cap on short viewports so a tall narrative still fits without pushing demo content off-screen. The narrative scrolls inside its own track if it ever overflows. */ max-height: calc(100vh - 120px); overflow-y: auto; scrollbar-width: thin;}/* The 640px cap on .lede / .takeaway exists to keep line length readable in the single-column layout. Inside a 248px rail that cap is moot — drop it so the text fills the rail. */.section--two-col .section-narrative .lede,.section--two-col .section-narrative .takeaway { max-width: none;}.section--two-col .section-narrative .lede { font-size: 13px; margin-bottom: 20px;}/* In 2-col mode the takeaway sits next to the demo as a margin note, so the heavy green-bar treatment becomes too loud. Soften to a calm hairline + neutral type. */.section--two-col .section-narrative .takeaway { margin-top: 0; padding: 14px 16px; border-left: 2px solid #d8d5c8; background: transparent; font-size: 12px; color: #555;}.section--two-col .section-narrative .takeaway strong { color: #1f1f1d;}/* The demo claims its full grid track. The default 24px y-margin was for the single-column rhythm and isn't needed here. */.section--two-col .demo { margin: 0;}@media (max-width: 900px) { .section--two-col { grid-template-columns: 1fr; row-gap: 16px; } .section--two-col .section-narrative { position: static; max-height: none; overflow: visible; } .section--two-col .section-narrative .takeaway { /* Restore a touch of the editorial green band on mobile, since it's no longer competing with a sticky sibling. */ margin-top: 8px; border-left-color: #317f3f; background: #f4f8f4; } .section--two-col .demo { margin: 8px 0 0; }}12345678910/* recipe.css — overrides for the Recipe panel demos (tokenizer, loss, data, architecture). Most of those demos rely on the shared .demo / .stat-row / .seq-block primitives, so this file only carries the narrow-viewport overrides their inline grid layouts need. */
/* Model section responsive overrides */@media (max-width: 720px) { #demo7 #d7-cols { grid-template-columns: 1fr !important; } #demo9 > div:first-child { grid-template-columns: 1fr !important; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177/* sandbox.css — Sandbox panel scoped styles (every selector is prefixed with #panel-sandbox to avoid leaking onto the Demo / Recipe panels). Originally ported from the legacy index.html sandbox. */
#panel-sandbox .sb-section-title { font-family: "JetBrains Mono", monospace; font-size: 11px; font-weight: 400; text-transform: uppercase; letter-spacing: 2px; color: #444; margin-top: 24px; margin-bottom: 8px; border-bottom: 1px solid #ccc; padding-bottom: 4px;}#panel-sandbox .sb-examples { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 6px; align-items: center;}#panel-sandbox .sb-examples-label { font-family: "JetBrains Mono", monospace; font-size: 10px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-right: 4px;}#panel-sandbox .sb-ex-btn { font-family: "JetBrains Mono", monospace; font-size: 10px; padding: 3px 8px; border: 1px solid #ddd; border-radius: 3px; background: #fff; color: #666; cursor: pointer; transition: all 0.15s;}#panel-sandbox .sb-ex-btn:hover { border-color: #888; color: #1f1f1d; }#panel-sandbox .sb-ex-btn .sb-ex-label { color: #aaa; font-size: 9px; margin-left: 6px; text-transform: uppercase; letter-spacing: 0.5px;}#panel-sandbox .sb-prompt-area, #panel-sandbox input[type=number] { font-family: "JetBrains Mono", monospace; font-size: 12px; font-weight: 300; color: #1f1f1d; background: #fff; border: 1px solid #ddd; border-radius: 3px; padding: 8px 12px; outline: none; transition: border 0.15s;}#panel-sandbox .sb-prompt-area:focus,#panel-sandbox input[type=number]:focus { border-color: #1f1f1d; }#panel-sandbox .sb-prompt-area { width: 100%; resize: none; overflow: hidden; letter-spacing: 1px; line-height: 1.7; min-height: 36px;}#panel-sandbox .sb-controls { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; margin-top: 10px;}#panel-sandbox .sb-control { display: flex; align-items: center; gap: 6px; font-family: "JetBrains Mono", monospace; font-size: 10px; color: #666; text-transform: uppercase; letter-spacing: 1px;}#panel-sandbox .sb-control input[type=number] { width: 64px; padding: 4px 6px; font-size: 11px; text-align: right;}#panel-sandbox .sb-mode-group { display: flex; align-items: center; gap: 6px; font-family: "JetBrains Mono", monospace; font-size: 10px; color: #666; text-transform: uppercase; letter-spacing: 1px;}#panel-sandbox .sb-mode-btns { display: flex; }#panel-sandbox .sb-mode-btn { font-family: "JetBrains Mono", monospace; font-size: 10px; padding: 4px 9px; border: 1px solid #ccc; border-right: none; background: #fff; color: #666; cursor: pointer; text-transform: uppercase; letter-spacing: 1px; transition: all 0.15s;}#panel-sandbox .sb-mode-btn:first-child { border-radius: 3px 0 0 3px; }#panel-sandbox .sb-mode-btn:last-child { border-right: 1px solid #ccc; border-radius: 0 3px 3px 0; }#panel-sandbox .sb-mode-btn:hover { color: #1f1f1d; }#panel-sandbox .sb-mode-btn.active { background: #1f1f1d; color: #fff; border-color: #1f1f1d; }
#panel-sandbox .sb-button-row { margin-left: auto; display: flex; gap: 6px; }
#panel-sandbox .sb-status { font-family: "JetBrains Mono", monospace; font-size: 10px; color: #666; text-transform: uppercase; letter-spacing: 1.5px; margin-top: 10px; min-height: 14px;}#panel-sandbox .sb-status.error { color: #b00020; text-transform: none; letter-spacing: 0.3px; }#panel-sandbox .sb-status .dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: #888; margin-right: 6px; vertical-align: middle;}/* `pulse` keyframe lives in base.css. */#panel-sandbox .sb-status.streaming .dot { background: #317f3f; animation: pulse 1.2s ease-in-out infinite; }
#panel-sandbox .sb-output-row { display: grid; grid-template-columns: minmax(0, 1fr) 200px; gap: 16px; align-items: start;}@media (max-width: 720px) { #panel-sandbox .sb-output-row { grid-template-columns: 1fr; }}
#panel-sandbox .sb-seq-wrap { position: relative; }#panel-sandbox .sb-copy-btn { position: absolute; top: 8px; right: 8px; z-index: 2; font-family: "JetBrains Mono", monospace; font-size: 9px; font-weight: 400; padding: 3px 8px; border: 1px solid #ddd; border-radius: 3px; background: #fff; color: #666; cursor: pointer; text-transform: uppercase; letter-spacing: 1px; transition: all 0.15s;}#panel-sandbox .sb-copy-btn:hover { border-color: #888; color: #1f1f1d; }#panel-sandbox .sb-copy-btn:disabled { opacity: 0; pointer-events: none; }#panel-sandbox .sb-copy-btn.copied { background: #317f3f; color: #fff; border-color: #317f3f; }
#panel-sandbox .sb-seq-block { font-family: "JetBrains Mono", monospace; background: #f4f4f4; border: 1px solid #ddd; padding: 16px 20px; overflow-x: auto; white-space: pre; font-size: 12px; font-weight: 400; line-height: 1.85; letter-spacing: 1.5px; min-height: 80px;}#panel-sandbox .sb-seq-block.empty { color: #aaa; font-weight: 300; letter-spacing: normal; }#panel-sandbox .sb-seq-line { white-space: pre; }#panel-sandbox .sb-pos { color: #bbb; user-select: none; font-weight: 300; }#panel-sandbox .sb-seq-line.tail::after { content: ""; display: inline-block; width: 7px; height: 14px; background: #1f1f1d; vertical-align: text-bottom; margin-left: 2px; animation: blink 1s step-end infinite;}@keyframes blink { 50% { opacity: 0; } }
#panel-sandbox .sb-stats { position: sticky; top: 120px; border: 1px solid #ddd; background: #fff;}#panel-sandbox .sb-stat { display: flex; justify-content: space-between; align-items: baseline; padding: 8px 12px; border-bottom: 1px solid #eee; font-family: "JetBrains Mono", monospace;}#panel-sandbox .sb-stat:last-child { border-bottom: none; }#panel-sandbox .sb-stat-label { font-size: 9px; color: #999; text-transform: uppercase; letter-spacing: 1.2px; font-weight: 300;}#panel-sandbox .sb-stat-value { font-size: 12px; font-weight: 400; color: #1f1f1d; font-variant-numeric: tabular-nums;}#panel-sandbox .sb-stat-value .sb-unit { font-size: 9px; color: #999; margin-left: 3px; font-weight: 300; }
#panel-sandbox .sb-legend { margin-top: 8px; padding: 8px 12px; background: #fff; border: 1px solid #ddd; font-family: "JetBrains Mono", monospace; font-size: 9px; color: #888; text-transform: uppercase; letter-spacing: 1px; display: none;}#panel-sandbox .sb-legend.show { display: block; }#panel-sandbox .sb-legend-bar { height: 6px; margin: 4px 0 3px; background: linear-gradient(to right, #bc2e25, #888, #1f1f1d); border-radius: 1px;}#panel-sandbox .sb-legend-row { display: flex; justify-content: space-between; }#panel-sandbox .sb-lp-chart { display: block; width: 100%; height: 40px; margin-top: 8px;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137/* section-folding.css — §5 Folding viewers and AA pair grid. Two square 3Dmol canvases side by side, optional loading overlay, pLDDT colour legend, mRNA flow strip, and the carbon/reference AA row pair with its shared mismatch legend. */
/* --- §5 Folding viewers --- *//* Two square 3Dmol canvases side by side. On narrow screens (<720px) we stack them vertically so each viewer keeps a comfortable size. */.fold-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 12px;}.fold-viewer-col { display: flex; flex-direction: column; }.fold-viewer-label { font-family: "JetBrains Mono", monospace; font-size: 9px; color: #888; text-transform: uppercase; letter-spacing: 1.5px; margin-bottom: 4px;}.fold-viewer { position: relative; width: 100%; aspect-ratio: 1 / 1; background: #fafaf7; border: 1px solid #eee; overflow: hidden;}.fold-viewer canvas { display: block; transition: opacity .15s ease-out; }.fold-viewer .fold-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-family: "JetBrains Mono", monospace; font-size: 10px; color: #bbb; letter-spacing: 1.5px; text-transform: uppercase; pointer-events: none;}/* Loading overlay shown over the cartoon while runFold() is in flight. The cached cartoon stays dimly visible underneath so the visitor can still compare to it once the fresh result lands. */.fold-viewer .fold-overlay { position: absolute; inset: 0; display: none; align-items: center; justify-content: center; gap: 8px; background: rgba(250, 250, 247, 0.72); font-family: "JetBrains Mono", monospace; font-size: 10px; color: #555; letter-spacing: 1.5px; text-transform: uppercase; pointer-events: none;}.fold-viewer .fold-overlay .dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: #317f3f; animation: pulse 1.2s ease-in-out infinite;}.fold-viewer.running .fold-overlay { display: flex; }.fold-viewer.running canvas { opacity: 0.28; }/* Same overlay reused for genes whose precomputed fixture isn't ready yet (HF endpoint downtime, fresh symbol added to the list, etc.). Canvas fades almost fully so the empty WebGL frame doesn't read as a bug — the overlay carries the explanation instead. */.fold-viewer.pending .fold-overlay { display: flex; }.fold-viewer.pending canvas { opacity: 0.08; }.fold-legend { font-family: "JetBrains Mono", monospace; font-size: 9px; color: #888; text-transform: uppercase; letter-spacing: 1.2px; display: flex; align-items: center; gap: 8px; margin-top: 10px;}/* pLDDT colour key: red = low confidence, beige = mid, blue = high. These three anchor colours are mirrored in plddtToColor() (JS) so the cartoon ribbons land in the same palette as this legend bar. */.fold-legend-bar { width: 120px; height: 6px; background: linear-gradient(to right, #b00020 0%, #f0e8e0 50%, #2c5aa0 100%); border-radius: 1px;}/* Inline warning chip used when a gene is too long for the live fold pipeline (introns push the last exon past our generation budget). */.fold-warn { color: #b00020; background: rgba(188, 46, 37, 0.10); padding: 1px 6px; border-radius: 2px;}/* Materialises the DNA → mRNA → protein arrow under the gene info, using the same monospace family/colour family as the rest of the metadata strip. The chevron is drawn with → to read as a flow, not a list. */.mrna-info { font-family: "JetBrains Mono", monospace; font-size: 11px; color: #888; margin: 4px 0 16px; letter-spacing: 0.3px;}.mrna-info .arrow { color: #b8b8b6; padding: 0 6px; }.mrna-info strong { color: #555; font-weight: 500; }.mrna-info .mrna-trunc { color: #b00020; background: rgba(188, 46, 37, 0.08); padding: 0 4px; margin-left: 6px; border-radius: 2px;}/* Two-column AA grid: Carbon (left) / Reference (right), mirroring the fold-grid below so the eye lines up "carbon prediction → carbon fold" on one side and "reference truth → reference fold" on the other. Stacks on narrow screens to keep each line readable. */.fold-aa-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 4px;}.fold-aa-col { display: flex; flex-direction: column; min-width: 0; }/* Soft-wrap as a safety net if the wrapped 40-char line ever still overflows (very narrow viewport, big font-size override, etc.). The JS still inserts \n every 40 chars so Carbon and Reference line up row-by-row in the common case. */.fold-aa-col .seq-block { white-space: pre-wrap; word-break: break-all; overflow-x: visible; }@media (max-width: 720px) { .fold-grid { grid-template-columns: 1fr; } .fold-aa-grid { grid-template-columns: 1fr; }}
/* Shared highlight legend for the carbon/reference AA pair. The legend sat duplicated inside each row's seq-label, which crowded the labels to two lines at half-card width. Lifting it out (mirrors how .fold-legend works for the pLDDT viewers below) lets each row's label stay on a single line. */.fold-aa-legend { font-family: "JetBrains Mono", monospace; font-size: 9px; color: #888; text-transform: uppercase; letter-spacing: 1.2px; display: flex; align-items: center; flex-wrap: wrap; gap: 4px 10px; margin-top: 10px;}.fold-aa-legend-swatch { display: inline-block; width: 10px; height: 10px; background: rgba(188, 46, 37, 0.18); border: 1px solid rgba(188, 46, 37, 0.35); border-radius: 1px;}.fold-aa-legend-sep { color: #c8c5b8; }1234567891011121314151617181920212223242526272829303132333435363738/* section-species.css — §4 Same gene across species. Each species gets a row with three columns: meta (kingdom-coloured name), aligned sequence block, and identity stats. */
.species-row { display: grid; grid-template-columns: 140px 1fr 110px; gap: 16px; align-items: start; padding: 14px 0; border-top: 1px solid #eee;}.species-row:first-child { border-top: none; }.species-meta { font-family: "JetBrains Mono", monospace; font-size: 11px;}.species-name { font-weight: 500; color: #1f1f1d; text-transform: uppercase; letter-spacing: 1px; font-size: 11px; border-left: 4px solid; padding-left: 8px;}.species-sub { color: #888; font-size: 10px; margin-top: 4px; padding-left: 12px; }.species-stats { text-align: right; font-family: "JetBrains Mono", monospace; font-size: 11px; color: #666;}.species-stats .stat-id { font-size: 16px; color: #1f1f1d; font-weight: 500; font-variant-numeric: tabular-nums; }.species-stats .stat-sub { font-size: 10px; color: #999; margin-top: 2px; }.species-seq { font-family: "JetBrains Mono", monospace; background: #f7f5ee; border: 1px solid #eee; padding: 8px 12px; overflow-x: auto; white-space: pre; font-size: 11px; line-height: 1.7; letter-spacing: 0.5px;}.species-seq.empty { color: #ccc; padding: 18px 12px; text-align: center; }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207/* section-tree.css — §7 Species tree (Carbon-derived phylogeny). Layout mirrors §6's editorial card. The grid is a 2-column structure: left = SVG dendrogram spine (Bezier elbows), right = aligned data tracks (italic name + kingdom chip + log count bar + NCBI agreement). Every row gets a subtle kingdom background tint so the eye reads coherent blocks without us drawing extra lines. */
.tree-toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; font-family: "JetBrains Mono", monospace; font-size: 11px; color: #666; margin-bottom: 14px;}.tree-toolbar .spacer { flex: 1; }.tree-toolbar .pills { display: inline-flex; gap: 0; border: 1px solid #d8d5c8; border-radius: 3px; overflow: hidden;}.tree-toolbar .pills .pill { background: #fff; border: 0; padding: 5px 11px; font: inherit; color: #666; cursor: pointer; border-right: 1px solid #d8d5c8; text-transform: lowercase;}.tree-toolbar .pills .pill:last-child { border-right: 0; }.tree-toolbar .pills .pill.active { background: #1f1f1d; color: #f7f5ee;}/* Big agreement score chip up top — the headline metric for §7. */.tree-score { display: inline-flex; align-items: baseline; gap: 8px; background: #f0eee5; border: 1px solid #d8d5c8; padding: 6px 12px; border-radius: 3px; font-family: "JetBrains Mono", monospace; color: #1f1f1d;}.tree-score-num { font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; color: #317f3f;}.tree-score-suffix { font-size: 10px; color: #888; text-transform: uppercase; letter-spacing: 1.2px;}/* Main grid : SVG spine on the left, aligned tracks on the right. The spine's height matches exactly N * row_h so each leaf lands on its track row. We never use grid here (rows differ in semantics) — just two columns of equal-height children rendered in JS. */.tree-grid { display: grid; grid-template-columns: minmax(280px, 1.5fr) minmax(0, 1.6fr); gap: 0; margin-top: 6px; background: #fff; border: 1px solid #e5e3da;}.tree-spine { position: relative; padding: 12px 0 28px 12px;}.tree-spine svg { display: block; width: 100%; height: 100%; overflow: visible;}/* Inline labels at each tip — only used in mobile (where the .tree-rows panel stacks below). On desktop they're rendered but hidden so we don't have to invalidate the SVG on viewport changes. */.tree-spine svg .leaf-svg-label,.tree-spine svg .leaf-svg-chip { display: none; }.tree-spine svg .leaf-svg-label { font-family: "JetBrains Mono", monospace; font-size: 11px; font-style: italic; dominant-baseline: middle;}.tree-spine .axis-label { position: absolute; bottom: 6px; left: 12px; font-family: "JetBrains Mono", monospace; font-size: 9px; color: #888; text-transform: uppercase; letter-spacing: 1.2px;}.tree-rows { display: flex; flex-direction: column; padding: 12px 0 28px 0;}.tree-row { display: grid; /* chip · name · bar · ncbi — name column is FIXED width so every row's bar starts at the exact same X. (max-content gets broken here by .tree-name's overflow:hidden, which makes each cell size to its own content instead of the column's longest item.) */ grid-template-columns: 10px 115px minmax(60px, 1fr) 24px; gap: 10px; align-items: center; padding: 0 14px 0 12px; height: 22px; /* must equal ROW_H in the JS tree renderer */ transition: background 0.12s ease-out; cursor: default;}.tree-row:hover { background: rgba(31, 31, 29, 0.04); }.tree-row.dim { opacity: 0.35; }/* Subtle background stripe by kingdom — matches the §6 palette */.tree-row[data-kingdom="vertebrates"] { background-image: linear-gradient(to right, rgba(31, 31, 29, 0.04), transparent 40px); }.tree-row[data-kingdom="invertebrates"] { background-image: linear-gradient(to right, rgba(122, 98, 66, 0.07), transparent 40px); }.tree-row[data-kingdom="plants"] { background-image: linear-gradient(to right, rgba(49, 127, 63, 0.07), transparent 40px); }.tree-row[data-kingdom="fungi"] { background-image: linear-gradient(to right, rgba(169, 118, 47, 0.07), transparent 40px); }.tree-row[data-kingdom="bacteria"] { background-image: linear-gradient(to right, rgba(176, 0, 32, 0.07), transparent 40px); }.tree-row[data-kingdom="viruses"] { background-image: linear-gradient(to right, rgba(44, 90, 160, 0.07), transparent 40px); }.tree-row .tree-name { font-family: "JetBrains Mono", monospace; font-size: 12px; font-style: italic; color: #1f1f1d; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}.tree-row[data-kingdom="vertebrates"] .tree-name { color: #1f1f1d; }.tree-row[data-kingdom="invertebrates"] .tree-name { color: #7a6242; }.tree-row[data-kingdom="plants"] .tree-name { color: #317f3f; }.tree-row[data-kingdom="fungi"] .tree-name { color: #a9762f; }.tree-row[data-kingdom="bacteria"] .tree-name { color: #b00020; }.tree-row[data-kingdom="viruses"] .tree-name { color: #2c5aa0; }.tree-row .tree-chip { width: 10px; height: 10px; border-radius: 2px;}.tree-row .tree-bar { /* Two-column inner grid so the rail always spans 1fr (= same start AND same end across rows), and the count sits in a fixed-width right column → chiffres et fin de rail s'alignent partout. */ display: grid; grid-template-columns: 1fr 46px; gap: 8px; align-items: center; height: 22px;}.tree-row .tree-bar .bar-track { position: relative; height: 6px; background: #efece1; border-radius: 1.5px; overflow: hidden;}.tree-row .tree-bar .bar-fill { position: absolute; left: 0; top: 0; bottom: 0; background: #c8c4b3; border-radius: 1.5px;}.tree-row .tree-bar .bar-num { font-family: "JetBrains Mono", monospace; font-size: 9px; color: #888; font-variant-numeric: tabular-nums; white-space: nowrap; text-align: right;}.tree-row .tree-ncbi { text-align: center; font-family: "JetBrains Mono", monospace; font-size: 14px; font-weight: 700; line-height: 1; user-select: none;}.tree-row .tree-ncbi[data-state="match"] { color: #317f3f; }.tree-row .tree-ncbi[data-state="mismatch"] { color: #b00020; }.tree-row .tree-ncbi[data-state="solo"] { color: #c8c5b9; }/* Tooltip floats over the grid on row hover, fed with top-3 NN. */.tree-tooltip { position: absolute; background: #1f1f1d; color: #f7f5ee; font-family: "JetBrains Mono", monospace; font-size: 10px; padding: 8px 11px; border-radius: 3px; pointer-events: none; z-index: 50; box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18); opacity: 0; transition: opacity 0.1s ease-out; line-height: 1.5; white-space: nowrap;}.tree-tooltip.show { opacity: 1; }.tree-tooltip .tt-title { text-transform: uppercase; letter-spacing: 1.2px; font-size: 9px; color: #888; margin-bottom: 4px;}.tree-tooltip .tt-pair { display: flex; gap: 10px; align-items: baseline; font-variant-numeric: tabular-nums;}.tree-tooltip .tt-glyph { color: #888; width: 14px; }.tree-tooltip .tt-name { color: #f7f5ee; }.tree-tooltip .tt-name.expected { color: #317f3f; font-weight: 600; }.tree-tooltip .tt-dist { color: #888; margin-left: auto; }.tree-frame { position: relative; } /* anchor for the tooltip *//* Footer legend strip + scoping caption */.tree-legend { display: flex; gap: 18px; flex-wrap: wrap; margin-top: 10px; font-family: "JetBrains Mono", monospace; font-size: 10px; color: #666;}.tree-legend-item { display: flex; align-items: center; gap: 5px; }.tree-legend-swatch { width: 9px; height: 9px; border-radius: 2px; }.tree-legend-glyph { font-size: 12px; font-weight: 700; line-height: 1; }.tree-caption { margin-top: 6px; font-family: "JetBrains Mono", monospace; font-size: 10px; color: #999; line-height: 1.6;}@media (max-width: 720px) { .tree-grid { grid-template-columns: 1fr; } .tree-spine { border-bottom: 1px solid #e5e3da; padding-right: 12px; } .tree-spine svg .leaf-svg-label, .tree-spine svg .leaf-svg-chip { display: inline; } .tree-row { grid-template-columns: 10px 110px minmax(60px, 1fr) 22px; padding: 0 10px; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126/* section-umap.css — §6 Embedding space (WebGL scatter, 571K points) styling: framing canvas, hover tooltip, status overlay, in-place cluster annotations, and the colour legend strip below. */
.umap-frame { position: relative; width: 100%; aspect-ratio: 16 / 10; /* Slight off-white that matches the editorial paper tone (body uses #f7f5ee). Pure white made the desaturated minority biotypes vanish into the page and made the saturated palette look harsh. */ background: #fbfaf6; border: 1px solid #e5e3da; overflow: hidden;}.umap-canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none;}.umap-canvas.panning { cursor: grabbing; }.umap-tooltip { position: absolute; pointer-events: none; background: #1f1f1d; color: #f7f5ee; font-family: "JetBrains Mono", monospace; font-size: 10px; line-height: 1.4; padding: 6px 9px; border-radius: 2px; white-space: nowrap; opacity: 0; transform: translate(8px, -100%); transition: opacity 0.12s; z-index: 4;}.umap-tooltip.visible { opacity: 0.96; }.umap-tooltip .t-label { color: #8c918b; text-transform: uppercase; letter-spacing: 1px; font-size: 8px; margin-right: 4px;}.umap-status-overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #aaa; font-family: "JetBrains Mono", monospace; font-size: 11px; letter-spacing: 1.5px; text-transform: uppercase; background: rgba(247, 245, 238, 0.85); pointer-events: none; transition: opacity 0.2s;}.umap-status-overlay.hidden { opacity: 0; }
/* Cluster-name annotations sit DIRECTLY on top of each cluster's centroid — no leader lines, no margin anchors, no body text. Editorial choice: the names *are* the annotation, set in heavier type with a strong paper-coloured halo so they read clean against coloured data underneath. Cf. classic Hillis radial trees, Tufte's "small multiples with labels-in-place". pointer-events:none so the canvas keeps every hover. */.umap-annotations { position: absolute; inset: 0; pointer-events: none; z-index: 3;}.ann-label { position: absolute; /* Centre on (left, top) — JS sets those to the screen-space coordinates of the cluster centroid. */ transform: translate(-50%, -50%); white-space: nowrap; font-family: "Inter", sans-serif; font-size: 13px; font-weight: 700; letter-spacing: 0.2px; color: #1f1f1d; /* Real glyph outline (not a rectangle, not a blurred halo). The trick is `paint-order: stroke fill` — without it `-webkit-text- stroke` paints centred on the glyph contour, eating half its inside and turning bold type into spindly outlined type. With stroke-then-fill, the cream stroke is painted first as a silhouette, then the dark fill drops on top at full thickness. Net visible: a clean ~2.5 px cream halo following each letter shape exactly. Reads cleanly over any colour underneath (including the saturated vertebrates blue + AT-rich teal that killed earlier blur-shadow attempts). */ -webkit-text-stroke: 5px #fbfaf6; text-stroke: 5px #fbfaf6; paint-order: stroke fill; transition: opacity 0.18s;}.umap-legend { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 10px; font-family: "JetBrains Mono", monospace; font-size: 10px; color: #666;}.umap-legend .swatch { display: inline-block; width: 9px; height: 9px; margin-right: 5px; vertical-align: middle; border-radius: 2px;}.umap-legend .item { display: inline-flex; align-items: center; cursor: default;}.umap-legend .item.gc-grad { gap: 8px;}.umap-legend .item.gc-grad svg { border-radius: 2px; display: block;}.umap-legend .item.gc-grad .gc-ticks { letter-spacing: 0.5px; color: #888;}1234567891011121314151617181920212223242526272829303132/* section-vep.css — §2 Variant effect predictor demo: the centred sequence window with ref/alt highlight, the per-allele likelihood bars, and the significance pills (.sig-Pathogenic / Risk / Benign) that decorate the gene chips in the toolbar. */
.vep-window { font-family: "JetBrains Mono", monospace; background: #f7f7f7; border: 1px solid #e0e0e0; padding: 14px 18px; margin: 8px 0; font-size: 13px; line-height: 1.6; letter-spacing: 1px; overflow-x: auto; white-space: pre; text-align: center;}.vep-window .ctx { color: #888; }.vep-window .var-ref { background: rgba(49, 127, 63, 0.18); color: #215a2a; padding: 0 4px; border-radius: 2px; font-weight: 500; }.vep-window .var-alt { background: rgba(188, 46, 37, 0.20); color: #b00020; padding: 0 4px; border-radius: 2px; font-weight: 500; }.vep-result { display: grid; grid-template-columns: 100px 1fr 80px; gap: 8px 12px; align-items: center; margin-top: 12px; font-family: "JetBrains Mono", monospace; font-size: 11px;}.vep-result .row-label { color: #666; text-transform: uppercase; letter-spacing: 1px; font-size: 10px; }.vep-result .row-bar { height: 14px; background: #f0f0f0; border-radius: 2px; position: relative; overflow: hidden; }.vep-result .row-bar .fill { position: absolute; top: 0; bottom: 0; left: 0; }.vep-result .row-bar.ref .fill { background: #317f3f; }.vep-result .row-bar.alt .fill { background: #bc2e25; }.vep-result .row-val { text-align: right; color: #1f1f1d; font-variant-numeric: tabular-nums; }.vep-result .row-delta { font-weight: 500; }
.pill.sig-Pathogenic { border-left: 3px solid #bc2e25; }.pill.sig-Risk { border-left: 3px solid #e69500; }.pill.sig-Benign { border-left: 3px solid #317f3f; }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139/* sequence.css — utilities for any section that displays nucleotide or amino-acid sequences: gene track SVG (used by §1, §3, §5), the .seq- label header (with carbon/reference chips and length tags), the .seq-block monospace box, the .stat-row at the bottom of demos, and small reference-mismatch highlight styles shared by §1 and §5. */
/* --- Gene track + gene-info (shared by §1, §3, §5) --- */.gene-info { font-family: "JetBrains Mono", monospace; font-size: 11px; color: #666; margin: 4px 0 12px; min-height: 14px;}.gene-info strong { color: #1f1f1d; font-weight: 500; }.gene-track { width: 100%; height: 28px; display: block; margin: 4px 0 8px;}.gene-track.draggable { height: 40px; touch-action: none; }.gene-track .exon { fill: #317f3f; }.gene-track .intron { stroke: #aaa; stroke-width: 1; }.gene-track .playhead { stroke: #bc2e25; stroke-width: 2; }.gene-track .gen-region { fill: #317f3f; opacity: 0.15; }.gene-track .prompt-region { fill: #1f1f1d; opacity: 0.04; }.gene-track .handle { cursor: ew-resize; }.gene-track .handle line { stroke: #1f1f1d; stroke-width: 1.5; }.gene-track .handle polygon { fill: #1f1f1d; }.gene-track .handle:hover line,.gene-track .handle.dragging line { stroke: #000; stroke-width: 2; }.gene-track .handle:hover polygon,.gene-track .handle.dragging polygon { fill: #000; }.gene-track .handle.gen line { stroke: #317f3f; }.gene-track .handle.gen polygon { fill: #317f3f; }.gene-track .handle.gen:hover line,.gene-track .handle.gen.dragging line { stroke: #1f5024; stroke-width: 2; }.gene-track .handle.gen:hover polygon,.gene-track .handle.gen.dragging polygon { fill: #1f5024; }.gene-track text { font-family: "JetBrains Mono", monospace; font-size: 9px; fill: #888; }
/* Instant tooltips (no native-title delay) for legend items. */.legend-tip { position: relative; }.legend-tip:hover::after { content: attr(data-tip); position: absolute; bottom: calc(100% + 8px); left: 50%; transform: translateX(-50%); background: #1f1f1d; color: #f7f5ee; padding: 6px 10px; border-radius: 3px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); font-family: 'Inter', sans-serif; font-size: 11px; font-weight: 400; letter-spacing: normal; text-transform: none; white-space: normal; width: max-content; max-width: 260px; line-height: 1.4; z-index: 10; pointer-events: none;}.legend-tip:hover::before { content: ""; position: absolute; bottom: calc(100% + 2px); left: 50%; transform: translateX(-50%); border: 4px solid transparent; border-top-color: #1f1f1d; z-index: 10; pointer-events: none;}.track-axis-label { font-family: "JetBrains Mono", monospace; font-size: 9px; color: #888; text-transform: uppercase; letter-spacing: 1px; display: flex; justify-content: space-between; margin-top: -4px;}
/* --- seq-label header row + chips + length tag (used by §1, §3, §5) --- */.seq-label { font-family: "JetBrains Mono", monospace; font-size: 9px; color: #888; text-transform: uppercase; letter-spacing: 1.5px; margin-top: 14px; margin-bottom: 4px; display: flex; gap: 12px; align-items: center;}.seq-label .legend-swatch { display: inline-block; width: 8px; height: 8px; vertical-align: middle; margin-right: 4px; border-radius: 1px;}/* Inline tag chips used in §5 to disambiguate carbon vs reference rows. Same shape/size, different colour band so the eye instantly maps a row of AAs to the correct identity without re-reading the full label. */.seq-label .seq-tag { display: inline-block; font-size: 9px; letter-spacing: 1.5px; padding: 1px 6px; margin-right: 8px; border-radius: 2px; text-transform: uppercase; font-weight: 600;}.seq-label .seq-tag.carbon { background: #1f1f1d; color: #f7f5ee; }.seq-label .seq-tag.ref { background: #f0eee5; color: #555; border: 1px solid #d8d5c8; }.seq-label .aa-len-tag { color: #1f1f1d; font-variant-numeric: tabular-nums; text-transform: none; letter-spacing: 0.3px;}/* In-label red stat used by the carbon row (e.g. "· 96 mismatches"). Defined as a class so the JS doesn't have to inline color styles. */.seq-label .seq-label-stat { color: #b00020; }
/* --- stat row at the bottom of every demo --- */.stat-row { display: flex; flex-wrap: wrap; gap: 24px; margin-top: 14px; padding-top: 12px; border-top: 1px solid #eee; font-family: "JetBrains Mono", monospace; font-size: 11px;}.stat-pair { display: flex; flex-direction: column; gap: 2px; }.stat-pair-label { font-size: 9px; color: #999; text-transform: uppercase; letter-spacing: 1.2px; }.stat-pair-val { color: #1f1f1d; font-variant-numeric: tabular-nums; }.stat-pair-val.muted { color: #aaa; }
/* --- Sequence display (shared with sandbox, used outside #panel-sandbox) --- */.seq-block { font-family: "JetBrains Mono", monospace; background: #f7f7f7; border: 1px solid #e0e0e0; padding: 14px 18px; overflow-x: auto; white-space: pre; font-size: 12px; font-weight: 400; line-height: 1.85; letter-spacing: 1px;}.seq-block.empty { color: #aaa; font-weight: 300; letter-spacing: normal; }.pos { color: #bbb; user-select: none; font-weight: 300; }
/* Mismatch highlighting in reference row (§1, §5). */.ref-mismatch { background: rgba(188, 46, 37, 0.18); color: #b00020; }.ref-match { color: #999; }