/* CellGemma · Single-Cell Perturbation Studio — Dual-Theme Optical Canvas Engine */ (function () { "use strict"; const SVG_NS = "http://www.w3.org/2000/svg"; const appState = { theme: "dark", csrfToken: "", device: "cpu", dtype: "float32", presets: [], featuredGenes: [], baselineCells: {}, // Active Input Selection mode: "drug", activePresetId: "panobinostat", dataset: "tahoe", cellIdx: 0, drugName: "Panobinostat", smiles: "Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1", concentrationUm: 0.5, gene: "MYC", temperature: 0.0, inputViz: null, // Strict 3-Phase State Machine: "before" -> "running" -> "after" stageMode: "before", runPhase: "idle", runStartedAtMs: 0, elapsedSeconds: 0, statusText: "", currentResult: null, lastPrompt: "", lastRawText: "", lastPromptTokens: 0, revealProgress: 0, barAnimProgress: 0, cellAnimPhase: 0.6, // Interactive Focus hoveredGeneSym: "", selectedGeneSym: "", // 3D Molecule / STRING Network Rotation molRot: { yaw: 0.54, pitch: 0.28, dragging: false, lastX: 0, lastY: 0 }, // Transient Running Particles (STRICTLY empty unless stageMode === "running") inParticles: [], outParticles: [], renderedOrbs: [], animatedBarRects: [], activeAbort: null, liveGeneCount: 0, activeZeroGpuRunId: 0, }; // Curated Dual-Theme Optical Palettes (Zero Purple on Dark) const THEMES = { dark: { isDark: true, bgGeoStroke: "rgba(56, 139, 253, 0.085)", bgGeoNode: "rgba(96, 165, 250, 0.16)", floorShadowRgb: "0, 0, 0", floorShadowScale: 1.85, untreated: { core0: "rgba(28, 44, 76, 0.84)", core1: "rgba(14, 25, 48, 0.88)", core2: "rgba(42, 33, 24, 0.90)", rimGlow: "rgba(251, 191, 36, 0.22)", outerMem: "#f59e0b", innerMem: "rgba(251, 191, 36, 0.52)", lipidTick: "rgba(251, 191, 36, 0.24)", cytoRing: "rgba(251, 191, 36, 0.20)", filament: "rgba(148, 179, 224, 0.16)", junction: "rgba(251, 191, 36, 0.42)", receptor: "rgba(245, 158, 11, 0.52)", nucFill0: "rgba(30, 48, 84, 0.92)", nucFill1: "rgba(13, 24, 46, 0.95)", nucStroke: "#94a3b8", nucHalo: "rgba(96, 165, 250, 0.22)", chromatinA: "rgba(147, 197, 253, 0.52)", chromatinB: "rgba(251, 191, 36, 0.34)", }, predicted: { core0: "rgba(14, 52, 68, 0.82)", core1: "rgba(8, 30, 48, 0.88)", core2: "rgba(10, 62, 66, 0.90)", rimGlow: "rgba(45, 212, 191, 0.28)", outerMem: "#2dd4bf", innerMem: "rgba(94, 234, 212, 0.56)", lipidTick: "rgba(45, 212, 191, 0.26)", cytoRing: "rgba(45, 212, 191, 0.22)", filament: "rgba(94, 234, 212, 0.18)", junction: "rgba(45, 212, 191, 0.48)", receptor: "rgba(45, 212, 191, 0.65)", nucFill0: "rgba(20, 52, 76, 0.92)", nucFill1: "rgba(10, 26, 46, 0.96)", nucStroke: "#99f6e4", nucHalo: "rgba(45, 212, 191, 0.28)", chromatinA: "rgba(94, 234, 212, 0.64)", chromatinB: "rgba(125, 211, 252, 0.44)", }, podBg0: "#0d1a33", podBg1: "#060d1c", podRim: "#3b82f6", podOuterHalo: "rgba(43, 116, 255, 0.24)", podGrid: "rgba(96, 165, 250, 0.12)", podVectorHalo: "rgba(4, 10, 22, 0.88)", podVectorStroke: "#93c5fd", podTagBg: "#132546", podTagBorder: "rgba(96, 165, 250, 0.38)", podTagInk: "#f1f5f9", conduitIdle: "rgba(148, 163, 184, 0.34)", conduitActiveIn: "#60a5fa", placeholderFill: "rgba(11, 22, 42, 0.55)", placeholderStroke: "rgba(148, 179, 224, 0.30)", placeholderInner: "rgba(148, 179, 224, 0.16)", placeholderPillBg: "#112240", placeholderPillBorder: "rgba(96, 165, 250, 0.36)", placeholderPillInk: "#e2e8f0", captionTitle: "#f1f5f9", captionUntreatedSub: "#fbbf24", captionModelSub: "#94a3b8", captionPredSub: "#34d399", captionIdleSub: "#64748b", zoneMicroInk: "rgba(148, 163, 184, 0.46)", calloutBg: "rgba(11, 22, 42, 0.92)", calloutFocusBg: "#f8fafc", calloutFocusInk: "#091122", calloutUpInk: "#6ee7b7", calloutUpBorder: "rgba(52, 211, 153, 0.42)", calloutDnInk: "#fda4af", calloutDnBorder: "rgba(251, 113, 133, 0.42)", focusRing: "#f8fafc", ringBaseline: "rgba(147, 197, 253, 0.56)", ringTwoX: "rgba(148, 179, 224, 0.25)", ringScaleBg: "rgba(11, 22, 42, 0.90)", ringScaleBorder: "rgba(147, 197, 253, 0.36)", ringScaleInk: "#cbd5e1", ringTick: "#f1f5f9", barStubDown: "rgba(148, 163, 184, 0.22)", tetherUp: "rgba(52, 211, 153, 0.34)", tetherDn: "rgba(251, 113, 133, 0.34)", hoverCardBg: "rgba(8, 16, 32, 0.95)", hoverCardBorder: "rgba(96, 165, 250, 0.36)", hoverCardSub: "#cbd5e1", }, light: { isDark: false, bgGeoStroke: "rgba(26, 104, 232, 0.055)", bgGeoNode: "rgba(26, 104, 232, 0.11)", floorShadowRgb: "15, 23, 42", floorShadowScale: 1.0, untreated: { core0: "#ffffff", core1: "#f8fafd", core2: "#fef3d6", rimGlow: "rgba(245, 158, 11, 0.14)", outerMem: "#d97706", innerMem: "rgba(245, 158, 11, 0.56)", lipidTick: "rgba(217, 119, 6, 0.25)", cytoRing: "rgba(180, 83, 9, 0.16)", filament: "rgba(100, 116, 139, 0.16)", junction: "rgba(217, 119, 6, 0.36)", receptor: "rgba(217, 119, 6, 0.55)", nucFill0: "#ffffff", nucFill1: "#e6edf7", nucStroke: "#334155", nucHalo: "rgba(51, 65, 85, 0.12)", chromatinA: "rgba(51, 65, 85, 0.36)", chromatinB: "rgba(180, 83, 9, 0.24)", }, predicted: { core0: "#ffffff", core1: "#effcf9", core2: "#d2f7ef", rimGlow: "rgba(13, 148, 136, 0.16)", outerMem: "#0d9488", innerMem: "rgba(20, 184, 166, 0.55)", lipidTick: "rgba(13, 148, 136, 0.26)", cytoRing: "rgba(13, 148, 136, 0.18)", filament: "rgba(13, 148, 136, 0.17)", junction: "rgba(13, 148, 136, 0.42)", receptor: "rgba(13, 148, 136, 0.62)", nucFill0: "#ffffff", nucFill1: "#e2f2f0", nucStroke: "#1e3a4c", nucHalo: "rgba(13, 148, 136, 0.15)", chromatinA: "rgba(15, 118, 110, 0.44)", chromatinB: "rgba(37, 99, 235, 0.28)", }, podBg0: "#ffffff", podBg1: "#f1f6fd", podRim: "#1e293b", podOuterHalo: "rgba(15, 23, 42, 0.12)", podGrid: "rgba(37, 99, 235, 0.10)", podVectorHalo: "rgba(255, 255, 255, 0.94)", podVectorStroke: "#0f172a", podTagBg: "#0f172a", podTagBorder: "rgba(15, 23, 42, 0.2)", podTagInk: "#ffffff", conduitIdle: "#cbd5e1", conduitActiveIn: "#2563eb", placeholderFill: "rgba(248, 250, 252, 0.85)", placeholderStroke: "#94a3b8", placeholderInner: "#cbd5e1", placeholderPillBg: "#ffffff", placeholderPillBorder: "#cbd5e1", placeholderPillInk: "#0f172a", captionTitle: "#0f172a", captionUntreatedSub: "#b45309", captionModelSub: "#475569", captionPredSub: "#047857", captionIdleSub: "#64748b", zoneMicroInk: "rgba(71, 85, 105, 0.48)", calloutBg: "rgba(255, 255, 255, 0.96)", calloutFocusBg: "#0f172a", calloutFocusInk: "#ffffff", calloutUpInk: "#047857", calloutUpBorder: "#6ee7b7", calloutDnInk: "#be123c", calloutDnBorder: "#fda4af", focusRing: "#0f172a", ringBaseline: "rgba(30, 64, 175, 0.44)", ringTwoX: "rgba(71, 85, 105, 0.28)", ringScaleBg: "rgba(255, 255, 255, 0.96)", ringScaleBorder: "rgba(71, 85, 105, 0.44)", ringScaleInk: "#0f172a", ringTick: "#0f172a", barStubDown: "rgba(100, 116, 139, 0.18)", tetherUp: "rgba(5, 150, 105, 0.30)", tetherDn: "rgba(225, 29, 72, 0.30)", hoverCardBg: "#0f172a", hoverCardBorder: "rgba(59, 130, 246, 0.35)", hoverCardSub: "#cbd5e1", }, }; // CPK 3D Atom Palette (Zero Purple — Halogens use Deep Sapphire/Cyan/Teal) const CPK = { C: { light: "#94a3b8", mid: "#475569", dark: "#0f172a", r: 6.4 }, N: { light: "#93c5fd", mid: "#2563eb", dark: "#1e3a8a", r: 7.0 }, O: { light: "#fda4af", mid: "#e11d48", dark: "#881337", r: 6.8 }, S: { light: "#fde68a", mid: "#d97706", dark: "#78350f", r: 7.6 }, F: { light: "#6ee7b7", mid: "#059669", dark: "#064e3b", r: 6.1 }, Cl: { light: "#5eead4", mid: "#0d9488", dark: "#134e4a", r: 7.4 }, I: { light: "#7dd3fc", mid: "#0284c7", dark: "#0c4a6e", r: 8.0 }, }; // Subcellular anchors for Untreated Baseline Pearls (Surface, Cytoplasm, Nucleus) const BASELINE_PEARLS = [ { a: 0.38, d: 0.985 }, { a: 2.28, d: 0.985 }, { a: 4.42, d: 0.985 }, { a: 0.88, d: 0.67 }, { a: 1.72, d: 0.75 }, { a: 2.68, d: 0.58 }, { a: 3.58, d: 0.72 }, { a: 4.88, d: 0.63 }, { a: 5.62, d: 0.76 }, { a: 1.28, d: 0.51 }, { a: 3.98, d: 0.52 }, { a: 0.58, d: 0.19 }, { a: 2.62, d: 0.21 }, { a: 4.72, d: 0.18 }, ]; // Precomputed 3D Subdivided Geodesic Gene-Network Sphere const GEODESIC = (function buildGeodesicMesh() { const phi = (1 + Math.sqrt(5)) * 0.5; const raw = [ [-1, phi, 0], [1, phi, 0], [-1, -phi, 0], [1, -phi, 0], [0, -1, phi], [0, 1, phi], [0, -1, -phi], [0, 1, -phi], [phi, 0, -1], [phi, 0, 1], [-phi, 0, -1], [-phi, 0, 1], ]; const norm = (v) => { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; }; const verts = raw.map(norm); const faces = [ [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11], [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8], [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9], [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1], ]; const midCache = new Map(); const getMid = (i, j) => { const key = i < j ? i + ":" + j : j + ":" + i; if (midCache.has(key)) return midCache.get(key); const a = verts[i]; const b = verts[j]; const m = norm([(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5, (a[2] + b[2]) * 0.5]); const idx = verts.length; verts.push(m); midCache.set(key, idx); return idx; }; const subFaces = []; for (const [a, b, c] of faces) { const ab = getMid(a, b); const bc = getMid(b, c); const ca = getMid(c, a); subFaces.push([a, ab, ca], [b, bc, ab], [c, ca, bc], [ab, bc, ca]); } const edgeSet = new Set(); const edges = []; for (const [a, b, c] of subFaces) { for (const [u, v] of [[a, b], [b, c], [c, a]]) { const k = u < v ? u + ":" + v : v + ":" + u; if (!edgeSet.has(k)) { edgeSet.add(k); edges.push([u, v]); } } } return { verts, edges }; })(); function getPalette() { return THEMES[appState.theme] || THEMES.dark; } function isTransmitting() { return appState.stageMode === "running"; } function clearChildren(el) { if (el) el.replaceChildren(); } function getSortedByLfc(list) { return (list || []).slice().sort((a, b) => { const ma = Math.abs(Number(a.lfc || a.residual || 0)); const mb = Math.abs(Number(b.lfc || b.residual || 0)); return mb - ma; }); } function rotate3D(x, y, z, yaw, pitch) { const cy = Math.cos(yaw); const sy = Math.sin(yaw); const x1 = x * cy + z * sy; const z1 = -x * sy + z * cy; const cp = Math.cos(pitch); const sp = Math.sin(pitch); return { x: x1, y: y * cp - z1 * sp, z: y * sp + z1 * cp }; } function formatLocShort(loc) { if (loc === "surface") return "SURF"; if (loc === "nucleus") return "NUC"; return "CYTO"; } // ========================================================================= // 1. Ambient Geodesic Halo & Refractive Glass Sphere Primitives // ========================================================================= function drawAmbientGeodesicBackdrop(ctx, W, H, pal) { // Delicate 3D geodesic cellular-network clusters in far peripheral corners, // keeping the central optical arena 100% pure and uncluttered. const rCluster = Math.min(182, W * 0.13); const clusters = [ { cx: W * 0.935, cy: H * 0.12, yaw: 0.62, pitch: 0.34 }, { cx: W * 0.065, cy: H * 0.89, yaw: 1.48, pitch: -0.28 }, ]; ctx.save(); for (const cl of clusters) { const proj = GEODESIC.verts.map((v) => { const p = rotate3D(v[0], v[1], v[2], cl.yaw, cl.pitch); const persp = 3.8 / (3.8 - p.z * 0.38); return { x: cl.cx + p.x * rCluster * persp, y: cl.cy + p.y * rCluster * persp, z: p.z, }; }); ctx.strokeStyle = pal.bgGeoStroke; ctx.lineWidth = 1.0; ctx.beginPath(); for (const [u, v] of GEODESIC.edges) { const a = proj[u]; const b = proj[v]; if (a.z < -0.15 || b.z < -0.15) continue; ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); } ctx.stroke(); ctx.fillStyle = pal.bgGeoNode; for (const p of proj) { if (p.z < -0.1) continue; ctx.beginPath(); ctx.arc(p.x, p.y, p.z > 0.35 ? 2.1 : 1.5, 0, Math.PI * 2); ctx.fill(); } } ctx.restore(); } function drawFloorShadow(ctx, x, y, rx, ry, alpha, pal) { const effAlpha = Math.min(0.55, alpha * pal.floorShadowScale); ctx.save(); const g = ctx.createRadialGradient(x, y, 2, x, y, rx); g.addColorStop(0, "rgba(" + pal.floorShadowRgb + ", " + effAlpha.toFixed(3) + ")"); g.addColorStop(1, "rgba(" + pal.floorShadowRgb + ", 0)"); ctx.translate(x, y); ctx.scale(1, ry / rx); ctx.fillStyle = g; ctx.beginPath(); ctx.arc(0, 0, rx, 0, Math.PI * 2); ctx.fill(); ctx.restore(); } function drawAtomSphere(ctx, x, y, r, colLight, colMid, colDark) { if (r <= 0.5) return; ctx.save(); ctx.shadowColor = "rgba(0, 0, 0, 0.34)"; ctx.shadowBlur = Math.max(3, r * 0.55); ctx.shadowOffsetY = Math.max(1, r * 0.16); const grad = ctx.createRadialGradient( x - r * 0.34, y - r * 0.34, r * 0.06, x, y, r ); grad.addColorStop(0, "#ffffff"); grad.addColorStop(0.24, colLight); grad.addColorStop(0.72, colMid); grad.addColorStop(1, colDark); ctx.fillStyle = grad; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); ctx.restore(); } function drawJewelOrb(ctx, x, y, r, isUp, isFocus, pal, glyph) { if (r <= 0.6) return; ctx.save(); // 1. Soft Optical Bioluminescent Bloom (proportional to orb radius, zero sticker border!) const bloomR = r * (pal.isDark ? 1.95 : 1.55); const bloom = ctx.createRadialGradient(x, y, r * 0.25, x, y, bloomR); if (isUp) { bloom.addColorStop(0, pal.isDark ? "rgba(16, 185, 129, 0.42)" : "rgba(16, 185, 129, 0.24)"); bloom.addColorStop(0.55, pal.isDark ? "rgba(45, 212, 191, 0.16)" : "rgba(16, 185, 129, 0.08)"); bloom.addColorStop(1, "rgba(16, 185, 129, 0)"); } else { bloom.addColorStop(0, pal.isDark ? "rgba(244, 63, 94, 0.42)" : "rgba(244, 63, 94, 0.24)"); bloom.addColorStop(0.55, pal.isDark ? "rgba(251, 113, 133, 0.16)" : "rgba(244, 63, 94, 0.08)"); bloom.addColorStop(1, "rgba(244, 63, 94, 0)"); } ctx.fillStyle = bloom; ctx.beginPath(); ctx.arc(x, y, bloomR, 0, Math.PI * 2); ctx.fill(); // 2. Refractive 3D Glass Jewel Sphere Body const body = ctx.createRadialGradient( x - r * 0.32, y - r * 0.34, r * 0.06, x + r * 0.1, y + r * 0.12, r * 1.05 ); if (isUp) { body.addColorStop(0, "#ecfdf5"); body.addColorStop(0.24, "#6ee7b7"); body.addColorStop(0.68, "#10b981"); body.addColorStop(0.92, "#065f46"); body.addColorStop(1, "#34d399"); } else { body.addColorStop(0, "#fff1f2"); body.addColorStop(0.24, "#fda4af"); body.addColorStop(0.68, "#f43f5e"); body.addColorStop(0.92, "#881337"); body.addColorStop(1, "#fb7185"); } ctx.fillStyle = body; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); // 3. Delicate Glass Fresnel Rim + Specular Crescent ctx.strokeStyle = isUp ? "rgba(167, 243, 208, 0.72)" : "rgba(254, 205, 211, 0.72)"; ctx.lineWidth = 1.15; ctx.beginPath(); ctx.arc(x, y, r - 0.5, 0, Math.PI * 2); ctx.stroke(); if (r >= 7) { ctx.fillStyle = "rgba(255, 255, 255, 0.52)"; ctx.beginPath(); ctx.ellipse(x - r * 0.28, y - r * 0.30, r * 0.28, r * 0.15, -0.65, 0, Math.PI * 2); ctx.fill(); } // 4. Precision Focus Reticle Ring When Hovered or Selected if (isFocus) { ctx.strokeStyle = pal.focusRing; ctx.lineWidth = 2.2; ctx.beginPath(); ctx.arc(x, y, r + 4.5, 0, Math.PI * 2); ctx.stroke(); } // 5. Crisp Polarity Glyph Inside Medium/Large Orbs if (glyph && r >= 10.5) { ctx.fillStyle = "#ffffff"; ctx.font = "700 " + Math.round(Math.min(14, r * 0.80)) + "px 'Google Sans Mono', monospace"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(glyph, x, y + 0.5); } ctx.restore(); } // ========================================================================= // 2. Confocal / Optical Biological Cell Illustration (Zero "Bread Icons"!) // ========================================================================= function getMembraneWobble(th, phase) { return ( 1.0 + 0.022 * Math.sin(3 * th + phase) + 0.015 * Math.cos(4 * th - phase * 0.78) + 0.008 * Math.sin(6 * th + phase * 0.45 + 1.1) ); } function traceOrganicMembrane(ctx, cx, cy, baseR, phase) { const steps = 120; ctx.beginPath(); for (let i = 0; i <= steps; i++) { const th = (i / steps) * Math.PI * 2; const r = baseR * getMembraneWobble(th, phase); const px = cx + Math.cos(th) * r; const py = cy + Math.sin(th) * r; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.closePath(); } function getMembranePoint(cx, cy, baseR, th, phase) { const r = baseR * getMembraneWobble(th, phase); return { x: cx + Math.cos(th) * r, y: cy + Math.sin(th) * r, r }; } function isChromatinOpeningPerturbation() { if (appState.mode === "drug" && appState.activePresetId === "panobinostat") return true; if (appState.mode === "crispr" && (appState.gene === "DNMT1" || appState.gene === "HDAC1" || appState.gene === "EZH2")) { return true; } return false; } function drawSurfaceReceptorPins(ctx, cx, cy, R, phase, col, angles) { ctx.save(); ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = 1.45; ctx.lineCap = "round"; for (const th of angles) { const base = getMembranePoint(cx, cy, R, th, phase); const ux = Math.cos(th); const uy = Math.sin(th); const stalkX = base.x + ux * 7.5; const stalkY = base.y + uy * 7.5; ctx.beginPath(); ctx.moveTo(base.x - ux * 2, base.y - uy * 2); ctx.lineTo(stalkX, stalkY); // Y-shaped extracellular glycoprotein fork const forkL = 4.2; ctx.moveTo(stalkX, stalkY); ctx.lineTo(stalkX + Math.cos(th - 0.58) * forkL, stalkY + Math.sin(th - 0.58) * forkL); ctx.moveTo(stalkX, stalkY); ctx.lineTo(stalkX + Math.cos(th + 0.58) * forkL, stalkY + Math.sin(th + 0.58) * forkL); ctx.stroke(); } ctx.restore(); } function drawRoseChromatinCoils(ctx, cx, cy, nucR, spread, phase, colA, colB) { ctx.save(); // Parametric multi-lobed rose-curve chromatin loops (condenses or blooms!) const drawStrand = (lobeFreq, rotOffset, scaleMul, strokeCol, lineW) => { ctx.strokeStyle = strokeCol; ctx.lineWidth = lineW; ctx.beginPath(); const steps = 160; for (let i = 0; i <= steps; i++) { const t = (i / steps) * Math.PI * 2; const r = nucR * spread * scaleMul * (0.56 + 0.36 * Math.cos(lobeFreq * t + rotOffset) + 0.08 * Math.sin(7 * t - phase)); const px = cx + Math.cos(t) * r; const py = cy + Math.sin(t) * r; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.closePath(); ctx.stroke(); }; drawStrand(3, phase * 0.4 + 0.3, 1.0, colA, 1.5); drawStrand(3, -phase * 0.3 + 1.35, 0.88, colB, 1.25); drawStrand(5, phase * 0.2 + 0.8, 0.64, colA, 1.05); ctx.restore(); } function drawLivingCell(ctx, cx, cy, R, variant, phase, alpha, pal, surfaceOrbs) { const spec = variant === "untreated" ? pal.untreated : pal.predicted; const nucR = R * (0.39 + 0.005 * Math.cos(phase * 0.9)); const midZoneR = R * (0.67 + 0.008 * Math.sin(phase * 0.85)); ctx.save(); ctx.globalAlpha = alpha; drawFloorShadow(ctx, cx, cy + R + 18, R * 0.84, 14, 0.09, pal); // 1. Outer Optical Aura / Confocal Glow ctx.save(); ctx.shadowColor = spec.rimGlow; ctx.shadowBlur = pal.isDark ? 42 : 28; ctx.shadowOffsetY = pal.isDark ? 0 : 8; traceOrganicMembrane(ctx, cx, cy, R, phase); ctx.fillStyle = spec.core1; ctx.fill(); ctx.restore(); // 2. 3D Subsurface Spherical Cytoplasm Fill const cytoGrad = ctx.createRadialGradient( cx - R * 0.24, cy - R * 0.24, R * 0.06, cx, cy, R * 1.03 ); cytoGrad.addColorStop(0, spec.core0); cytoGrad.addColorStop(0.62, spec.core1); cytoGrad.addColorStop(1, spec.core2); traceOrganicMembrane(ctx, cx, cy, R, phase); ctx.fillStyle = cytoGrad; ctx.fill(); // 3. Restored Subcellular Inner Architecture: // (a) Concentric Perinuclear / Cytoplasmic Zone Ring (0.67 * R) ctx.save(); ctx.strokeStyle = spec.cytoRing; ctx.lineWidth = 1.2; ctx.setLineDash([5, 6]); ctx.beginPath(); ctx.arc(cx, cy, midZoneR, 0, Math.PI * 2); ctx.stroke(); ctx.restore(); // (b) 12 Curved Geodesic Cytoskeletal Filaments + Junction Pearls ctx.save(); ctx.strokeStyle = spec.filament; ctx.lineWidth = 1.15; const numFilaments = 12; for (let i = 0; i < numFilaments; i++) { const a0 = (i / numFilaments) * Math.PI * 2 + 0.18; const sway = Math.sin(phase * 0.72 + i * 0.85) * 0.032; const aMid = a0 + (i % 2 === 0 ? 0.14 : -0.14) + sway; const a1 = a0 + (i % 2 === 0 ? 0.06 : -0.06) + sway * 0.5; const sx = cx + Math.cos(a0) * (nucR + 3); const sy = cy + Math.sin(a0) * (nucR + 3); const qx = cx + Math.cos(aMid) * midZoneR; const qy = cy + Math.sin(aMid) * midZoneR; const pEnd = getMembranePoint(cx, cy, R - 9.5, a1, phase); ctx.beginPath(); ctx.moveTo(sx, sy); ctx.quadraticCurveTo(qx, qy, pEnd.x, pEnd.y); ctx.stroke(); // Geodesic cross-brace between adjacent mid-zone junctions const nextIdx = (i + 1) % numFilaments; const nextSway = Math.sin(phase * 0.72 + nextIdx * 0.85) * 0.032; const aNext = (nextIdx / numFilaments) * Math.PI * 2 + 0.18 + (nextIdx % 2 === 0 ? 0.14 : -0.14) + nextSway; if (i % 2 === 0) { ctx.beginPath(); ctx.moveTo(qx, qy); ctx.lineTo(cx + Math.cos(aNext) * midZoneR, cy + Math.sin(aNext) * midZoneR); ctx.stroke(); } ctx.fillStyle = spec.junction; ctx.beginPath(); ctx.arc(qx, qy, 2.0, 0, Math.PI * 2); ctx.fill(); } ctx.restore(); // 4. Phospholipid Bilayer Membrane + Radial Lipid Ticks + Transmembrane Receptors ctx.strokeStyle = spec.lipidTick; ctx.lineWidth = 1.15; const numTicks = 72; ctx.beginPath(); for (let i = 0; i < numTicks; i++) { const th = (i / numTicks) * Math.PI * 2; const pOut = getMembranePoint(cx, cy, R - 1, th, phase); const pIn = getMembranePoint(cx, cy, R - 8.5, th, phase); ctx.moveTo(pOut.x, pOut.y); ctx.lineTo(pIn.x, pIn.y); } ctx.stroke(); traceOrganicMembrane(ctx, cx, cy, R - 8.5, phase); ctx.strokeStyle = spec.innerMem; ctx.lineWidth = 1.5; ctx.stroke(); traceOrganicMembrane(ctx, cx, cy, R, phase); ctx.strokeStyle = spec.outerMem; ctx.lineWidth = 3.1; ctx.stroke(); // Baseline Surface Glycoprotein Receptor Pins const receptorAngles = [0.22, 0.78, 1.38, 1.98, 2.58, 3.36, 3.98, 4.58, 5.18, 5.76]; drawSurfaceReceptorPins(ctx, cx, cy, R, phase, spec.receptor, receptorAngles); // Polarized Active Surface Receptor Flags for Shifted Surface Genes (e.g. +CALR, +GYPB, -SERPINE1) if (surfaceOrbs && surfaceOrbs.length) { for (const so of surfaceOrbs) { if (so.loc !== "surface") continue; const ang = Math.atan2(so.y - cy, so.x - cx); const col = so.isUp ? "#10b981" : "#f43f5e"; ctx.save(); ctx.shadowColor = col; ctx.shadowBlur = 8; drawSurfaceReceptorPins(ctx, cx, cy, R + 2.5, phase, col, [ang - 0.08, ang + 0.08]); ctx.restore(); } } // 5. 3D Nucleus Envelope + Parametric Rose-Curve Chromatin Coils ctx.save(); ctx.shadowColor = spec.nucHalo; ctx.shadowBlur = 18; const nucGrad = ctx.createRadialGradient( cx - nucR * 0.25, cy - nucR * 0.25, 3, cx, cy, nucR ); nucGrad.addColorStop(0, spec.nucFill0); nucGrad.addColorStop(1, spec.nucFill1); ctx.fillStyle = nucGrad; ctx.beginPath(); ctx.arc(cx, cy, nucR, 0, Math.PI * 2); ctx.fill(); ctx.restore(); // Soft Nucleolus Core ctx.fillStyle = pal.isDark ? "rgba(148, 163, 184, 0.14)" : "rgba(100, 116, 139, 0.12)"; ctx.beginPath(); ctx.arc(cx - nucR * 0.20, cy - nucR * 0.16, nucR * 0.22, 0, Math.PI * 2); ctx.fill(); // Biologically Responsive Rose-Curve Chromatin (Unwinds on HDACi / DNMT1 knockdown!) const chromatinSpread = variant === "predicted" && isChromatinOpeningPerturbation() ? 0.82 : 0.60; drawRoseChromatinCoils( ctx, cx, cy, nucR, chromatinSpread, phase, spec.chromatinA, spec.chromatinB ); // Double Nuclear Envelope (Outer subtle ring + Nuclear Pore Complex dashed inner ring) ctx.strokeStyle = spec.cytoRing; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.arc(cx, cy, nucR + 4.5, 0, Math.PI * 2); ctx.stroke(); ctx.save(); ctx.strokeStyle = spec.nucStroke; ctx.lineWidth = 2.1; ctx.setLineDash([12, 4.5]); ctx.beginPath(); ctx.arc(cx, cy, nucR, 0, Math.PI * 2); ctx.stroke(); ctx.restore(); ctx.restore(); } function computeSunburstSpanPx(foldFactor, maxSpan) { // Smooth kink-free magnified regulated ruler: // foldFactor = exp(|lfc|) >= 1.0 (1.50x UP and -33.3% DOWN = 1/0.667 both equal 1.50!) // Zooms cleanly above CellGemma's 1.21x (-17%) regulated emission floor up to 2.75x (-64%), // with zero slope kink at 1.50x so top drug responders step down smoothly! const minCap = Math.max(4.5, maxSpan * 0.055); if (foldFactor <= 1.21) { return Math.max(3.6, ((foldFactor - 1.05) / 0.16) * minCap); } const norm = Math.min(1.06, Math.max(0, (foldFactor - 1.21) / (2.72 - 1.21))); return minCap + (maxSpan - minCap) * Math.pow(norm, 0.44); } function getPredictedRingMetrics(cellR) { // Magnified smooth outward radial equalizer anchored outside the living cell membrane: // midRingR = exact computeSunburstSpanPx(1.50) (1.5x UP / -33% DOWN reference arc) // outerRingR = exact computeSunburstSpanPx(2.50) (2.5x UP / -60% DOWN reference arc) const predR = cellR * 0.610; const baseRingR = predR + Math.max(8.5, cellR * 0.054); const maxSpan = cellR * 0.515; const midSpan = computeSunburstSpanPx(1.50, maxSpan); const outerSpan = computeSunburstSpanPx(2.50, maxSpan); const midRingR = baseRingR + midSpan; const outerRingR = baseRingR + outerSpan; return { predR, baseRingR, maxSpan, midSpan, outerSpan, midRingR, outerRingR }; } function drawPolarScaleArc(ctx, cx, cy, r, aStart, aEnd, tickAng, strokeCol, lineW, dash) { ctx.strokeStyle = strokeCol; ctx.lineWidth = lineW; ctx.setLineDash(dash); ctx.beginPath(); ctx.arc(cx, cy, r, aStart, aEnd, false); ctx.stroke(); ctx.setLineDash([]); const ux = Math.cos(tickAng); const uy = Math.sin(tickAng); ctx.beginPath(); ctx.moveTo(cx + ux * (r - 3.2), cy + uy * (r - 3.2)); ctx.lineTo(cx + ux * (r + 3.2), cy + uy * (r + 3.2)); ctx.stroke(); } function drawScalePill(ctx, cx, cy, text, active, pal) { ctx.save(); ctx.font = "700 8.8px 'Google Sans Mono', monospace"; const pw = ctx.measureText(text).width + 9; const ph = 14.5; ctx.fillStyle = pal.ringScaleBg; ctx.strokeStyle = active ? pal.ringScaleBorder : pal.placeholderStroke; ctx.lineWidth = 1.05; ctx.beginPath(); ctx.roundRect(cx - pw * 0.5, cy - ph * 0.5, pw, ph, 999); ctx.fill(); ctx.stroke(); ctx.fillStyle = active ? pal.ringScaleInk : pal.isDark ? "#94a3b8" : "#475569"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(text, cx, cy + 0.5); ctx.restore(); } function drawReferenceScaleRings(ctx, cx, cy, metrics, active, pal) { const { baseRingR, midRingR, outerRingR } = metrics; ctx.save(); // 1. Dedicated Top (↑ UP: 1.5×, 2.5×) & Bottom (↓ DOWN: −33%, −60%) Polar Reference Arcs // Starts at ±2.30 rad so scale pills sit cleanly above/below the center conduits with >85px clearance! const topStart = -2.30; const topEnd = -0.38; const botStart = 0.38; const botEnd = 2.30; const midStroke = active ? pal.ringBaseline : pal.placeholderInner; const outStroke = active ? pal.ringTwoX : pal.placeholderInner; drawPolarScaleArc(ctx, cx, cy, midRingR, topStart, topEnd, topStart, midStroke, 1.1, [3.5, 4.5]); drawPolarScaleArc(ctx, cx, cy, midRingR, botStart, botEnd, botEnd, midStroke, 1.1, [3.5, 4.5]); drawPolarScaleArc(ctx, cx, cy, outerRingR, topStart, topEnd, topStart, outStroke, 1.0, [2.5, 5.5]); drawPolarScaleArc(ctx, cx, cy, outerRingR, botStart, botEnd, botEnd, outStroke, 1.0, [2.5, 5.5]); // 2. Crisp 360-degree Regulated Baseline Collar Ring ctx.strokeStyle = active ? pal.ringBaseline : pal.placeholderStroke; ctx.lineWidth = active ? 1.5 : 1.3; ctx.setLineDash([5, 4]); ctx.beginPath(); ctx.arc(cx, cy, baseRingR, 0, Math.PI * 2); ctx.stroke(); ctx.setLineDash([]); // 3. "Base" Anchor Pill on Left Rim (centered cleanly between +/- incoming conduits) drawScalePill(ctx, cx - baseRingR, cy, "Base", active, pal); // 4. Pill-Backed Scale Labels at Left Tips of Top (+50%, +150%) & Bottom (−33%, −60%) Arcs const cosTop = Math.cos(topStart); const sinTop = Math.sin(topStart); const yMidTop = cy + sinTop * midRingR; const yOutTop = Math.min(yMidTop - 16.5, cy + sinTop * outerRingR); drawScalePill(ctx, cx + cosTop * midRingR - 22, yMidTop, "+50%", active, pal); drawScalePill(ctx, cx + cosTop * outerRingR - 22, yOutTop, "+150%", active, pal); const cosBot = Math.cos(botEnd); const sinBot = Math.sin(botEnd); const yMidBot = cy + sinBot * midRingR; const yOutBot = Math.max(yMidBot + 16.5, cy + sinBot * outerRingR); drawScalePill(ctx, cx + cosBot * midRingR - 22, yMidBot, "−33%", active, pal); drawScalePill(ctx, cx + cosBot * outerRingR - 22, yOutBot, "−60%", active, pal); ctx.restore(); } function drawBlueprintPlaceholderCell(ctx, cx, cy, cellR, pal) { const metrics = getPredictedRingMetrics(cellR); const R = metrics.predR; ctx.save(); drawFloorShadow(ctx, cx, cy + R + 18, R * 0.78, 12, 0.05, pal); ctx.fillStyle = pal.placeholderFill; ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill(); // Outer Membrane Reticle ctx.setLineDash([7, 5]); ctx.strokeStyle = pal.placeholderStroke; ctx.lineWidth = 1.8; ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.stroke(); // Cytoplasmic + Nuclear Precision Rings ctx.strokeStyle = pal.placeholderInner; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.arc(cx, cy, R * 0.67, 0, Math.PI * 2); ctx.stroke(); ctx.beginPath(); ctx.arc(cx, cy, R * 0.39, 0, Math.PI * 2); ctx.stroke(); ctx.setLineDash([]); // Blueprint Reference Scale Rings & Base Pill (drawn on top of membrane reticle so pill stays crisp!) drawReferenceScaleRings(ctx, cx, cy, metrics, false, pal); // Subtle Compartment Guide Label ctx.fillStyle = pal.zoneMicroInk; ctx.font = "600 9px 'Google Sans Mono', monospace"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText("MEMBRANE", cx, cy - R + 16); // Floating Action Prompt Pill const txt = "Click ▶ Run"; ctx.font = "600 12px 'Google Sans', sans-serif"; const pw = ctx.measureText(txt).width + 24; ctx.fillStyle = pal.placeholderPillBg; ctx.strokeStyle = pal.placeholderPillBorder; ctx.lineWidth = 1.25; ctx.beginPath(); ctx.roundRect(cx - pw * 0.5, cy - 14, pw, 28, 999); ctx.fill(); ctx.stroke(); ctx.fillStyle = pal.placeholderPillInk; ctx.fillText(txt, cx, cy + 0.5); ctx.restore(); } // ========================================================================= // 3. Elevated 3D Perturbation Optical Magnifier (Drug Conformer & STRING 3D) // ========================================================================= function draw3DMoleculeInside(ctx, cx, cy, maxRadius, viz, yaw, pitch, isDark) { if (!viz || !viz.nodes || !viz.nodes.length) return; let maxCoord = 1.8; for (const n of viz.nodes) { const m = Math.hypot(n.x || 0, n.y || 0, n.z || 0); if (m > maxCoord) maxCoord = m; } const scale = (maxRadius * 0.80) / maxCoord; const proj = viz.nodes.map((n) => { const r = rotate3D(n.x || 0, n.y || 0, n.z || 0, yaw, pitch); const persp = 4.6 / (4.6 - r.z * 0.35); return { sx: cx + r.x * scale * persp, sy: cy + r.y * scale * persp, z: r.z, persp, elem: n.elem || "C", }; }); const items = []; for (const ed of viz.edges || []) { const a = proj[ed.a]; const b = proj[ed.b]; if (!a || !b) continue; items.push({ kind: "bond", z: (a.z + b.z) * 0.5 - 0.06, a, b, order: ed.order || 1 }); } for (let i = 0; i < proj.length; i++) { items.push({ kind: "atom", z: proj[i].z, p: proj[i] }); } items.sort((u, v) => u.z - v.z); const bondBase = isDark ? "#64748b" : "#64748b"; const bondSpec = isDark ? "#cbd5e1" : "#e2e8f0"; for (const it of items) { if (it.kind === "bond") { const dx = it.b.sx - it.a.sx; const dy = it.b.sy - it.a.sy; const len = Math.hypot(dx, dy) || 1; const nx = -dy / len; const ny = dx / len; ctx.lineCap = "round"; if (it.order >= 2) { const off = 2.25; ctx.strokeStyle = bondBase; ctx.lineWidth = 2.1; ctx.beginPath(); ctx.moveTo(it.a.sx + nx * off, it.a.sy + ny * off); ctx.lineTo(it.b.sx + nx * off, it.b.sy + ny * off); ctx.moveTo(it.a.sx - nx * off, it.a.sy - ny * off); ctx.lineTo(it.b.sx - nx * off, it.b.sy - ny * off); ctx.stroke(); } else { ctx.strokeStyle = bondBase; ctx.lineWidth = 3.2; ctx.beginPath(); ctx.moveTo(it.a.sx, it.a.sy); ctx.lineTo(it.b.sx, it.b.sy); ctx.stroke(); ctx.strokeStyle = bondSpec; ctx.lineWidth = 1.0; ctx.beginPath(); ctx.moveTo(it.a.sx - nx * 0.6, it.a.sy - ny * 0.6); ctx.lineTo(it.b.sx - nx * 0.6, it.b.sy - ny * 0.6); ctx.stroke(); } } else { const st = CPK[it.p.elem] || CPK.C; const rad = st.r * it.p.persp * (maxRadius / 62); drawAtomSphere(ctx, it.p.sx, it.p.sy, rad, st.light, st.mid, st.dark); } } } function draw3DCrisprNetworkInside(ctx, cx, cy, maxRadius, viz, geneSym, yaw, pitch, isDark) { const netCY = cy - maxRadius * 0.11; // Subtle Cas9 Guide-RNA Orbital Ring around the 3D STRING Protein Network! ctx.save(); ctx.strokeStyle = isDark ? "rgba(244, 63, 94, 0.26)" : "rgba(225, 29, 72, 0.20)"; ctx.lineWidth = 1.35; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.ellipse(cx, netCY, maxRadius * 0.78, maxRadius * 0.32, -0.32, 0, Math.PI * 2); ctx.stroke(); ctx.restore(); if (viz && viz.nodes && viz.nodes.length > 1) { const scale = (maxRadius * 0.62) / 1.75; const proj = viz.nodes.map((n, idx) => { const r = rotate3D(n.x || 0, n.y || 0, n.z || 0, yaw, pitch); const persp = 4.5 / (4.5 - r.z * 0.35); return { idx, sx: cx + r.x * scale * persp, sy: netCY + r.y * scale * persp, z: r.z, persp, sym: n.elem || geneSym, isHub: Boolean(n.isHub || idx === 0), }; }); // Draw 3D STRING functional interaction spokes const hub = proj[0]; for (let i = 1; i < proj.length; i++) { const sp = proj[i]; ctx.save(); ctx.strokeStyle = isDark ? "rgba(96, 165, 250, 0.38)" : "rgba(37, 99, 235, 0.30)"; ctx.lineWidth = 1.35; ctx.setLineDash([3, 3]); ctx.beginPath(); ctx.moveTo(hub.sx, hub.sy); ctx.lineTo(sp.sx, sp.sy); ctx.stroke(); ctx.restore(); } // Depth-sort partner spheres + center silenced hub const order = proj.slice().sort((a, b) => a.z - b.z); let labeledCount = 0; for (const p of order) { if (p.isHub) { // Silenced Target Hub with Crimson CRISPR-i Halo const hr = 10.2 * (maxRadius / 62); ctx.save(); const hg = ctx.createRadialGradient(p.sx, p.sy, 2, p.sx, p.sy, hr * 2.1); hg.addColorStop(0, "rgba(244, 63, 94, 0.55)"); hg.addColorStop(1, "rgba(244, 63, 94, 0)"); ctx.fillStyle = hg; ctx.beginPath(); ctx.arc(p.sx, p.sy, hr * 2.1, 0, Math.PI * 2); ctx.fill(); ctx.restore(); drawAtomSphere(ctx, p.sx, p.sy, hr, "#fda4af", "#e11d48", "#881337"); } else { const sr = 5.0 * p.persp * (maxRadius / 62); drawAtomSphere(ctx, p.sx, p.sy, sr, "#93c5fd", "#2563eb", "#1e3a8a"); if (p.z > 0.32 && labeledCount < 3 && maxRadius >= 54 && p.sy < cy + maxRadius * 0.30) { labeledCount += 1; ctx.save(); ctx.font = "600 8.5px 'Google Sans Mono', monospace"; ctx.textAlign = "center"; ctx.textBaseline = "bottom"; ctx.lineJoin = "round"; ctx.lineWidth = 2.6; ctx.strokeStyle = isDark ? "rgba(8, 15, 30, 0.88)" : "rgba(255, 255, 255, 0.92)"; ctx.strokeText(p.sym, p.sx, p.sy - sr - 2); ctx.fillStyle = isDark ? "#e2e8f0" : "#0f172a"; ctx.fillText(p.sym, p.sx, p.sy - sr - 2); ctx.restore(); } } } } // Crisp CRISPR Target Knockout Pill at Bottom of Lens (clear of all 3D STRING nodes) const badgeText = "✕ " + geneSym; ctx.save(); ctx.font = "700 10px 'Google Sans Mono', monospace"; const bw = Math.max(48, ctx.measureText(badgeText).width + 12); const bh = 18; const by = cy + maxRadius * 0.58; ctx.shadowColor = "rgba(225, 29, 72, 0.42)"; ctx.shadowBlur = 10; ctx.fillStyle = "#e11d48"; ctx.beginPath(); ctx.roundRect(cx - bw * 0.5, by - bh * 0.5, bw, bh, 6); ctx.fill(); ctx.shadowBlur = 0; ctx.fillStyle = "#ffffff"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(badgeText, cx, by + 0.5); ctx.restore(); } function drawInputPod(ctx, podX, podY, podR, cellX, cellY, cellR, nowMs, pal) { // 1. Elevated Optical Glass Magnifier Lens ctx.save(); ctx.shadowColor = pal.podOuterHalo; ctx.shadowBlur = 32; ctx.shadowOffsetY = pal.isDark ? 6 : 10; const lensGrad = ctx.createRadialGradient( podX - podR * 0.25, podY - podR * 0.25, 4, podX, podY, podR ); lensGrad.addColorStop(0, pal.podBg0); lensGrad.addColorStop(1, pal.podBg1); ctx.fillStyle = lensGrad; ctx.beginPath(); ctx.arc(podX, podY, podR, 0, Math.PI * 2); ctx.fill(); ctx.restore(); // Subtle Optical Reticle Ring Inside Lens ctx.save(); ctx.strokeStyle = pal.podGrid; ctx.lineWidth = 1.0; ctx.beginPath(); ctx.arc(podX, podY, podR * 0.78, 0, Math.PI * 2); ctx.stroke(); ctx.beginPath(); ctx.arc(podX, podY, podR - 3, 0, Math.PI * 2); ctx.clip(); if (appState.mode === "drug") { // Smooth bounded 3D precession while running so chemical rings stay broadside and clear! const drugYaw = appState.molRot.yaw + (appState.stageMode === "running" ? Math.sin(nowMs * 0.0028) * 0.40 : 0); const drugPitch = appState.molRot.pitch + (appState.stageMode === "running" ? Math.cos(nowMs * 0.0021) * 0.15 : 0); draw3DMoleculeInside(ctx, podX, podY, podR - 4, appState.inputViz, drugYaw, drugPitch, pal.isDark); } else { const crisprYaw = appState.molRot.yaw + (appState.stageMode === "running" ? nowMs * 0.0014 : 0); draw3DCrisprNetworkInside( ctx, podX, podY, podR - 4, appState.inputViz, appState.gene, crisprYaw, appState.molRot.pitch, pal.isDark ); } ctx.restore(); // Specular Lens Bezel ctx.strokeStyle = pal.podRim; ctx.lineWidth = 2.2; ctx.beginPath(); ctx.arc(podX, podY, podR, 0, Math.PI * 2); ctx.stroke(); // 2. Precision Injection Vector Piercing Into Target Compartment const rimAng = 0.56; const startX = podX + Math.cos(rimAng) * (podR + 1.5); const startY = podY + Math.sin(rimAng) * (podR + 1.5); // CRISPR targets nuclear DNA; Small-molecule enters cytoplasmic/nuclear target! const endX = appState.mode === "crispr" ? cellX - cellR * 0.24 : cellX - cellR * 0.48; const endY = appState.mode === "crispr" ? cellY - cellR * 0.16 : cellY - cellR * 0.34; const ctrlX = (startX + endX) * 0.5 + 14; const ctrlY = (startY + endY) * 0.5 - 12; ctx.save(); ctx.lineCap = "round"; ctx.strokeStyle = pal.podVectorHalo; ctx.lineWidth = 5.8; ctx.beginPath(); ctx.moveTo(startX, startY); ctx.quadraticCurveTo(ctrlX, ctrlY, endX, endY); ctx.stroke(); ctx.strokeStyle = pal.podVectorStroke; ctx.lineWidth = 2.2; ctx.beginPath(); ctx.moveTo(startX, startY); ctx.quadraticCurveTo(ctrlX, ctrlY, endX, endY); ctx.stroke(); const ang = Math.atan2(endY - ctrlY, endX - ctrlX); ctx.fillStyle = pal.podVectorHalo; ctx.beginPath(); ctx.arc(endX, endY, 6.8, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = pal.podVectorStroke; ctx.beginPath(); ctx.moveTo(endX + Math.cos(ang) * 2, endY + Math.sin(ang) * 2); ctx.lineTo(endX - Math.cos(ang - 0.52) * 8.8, endY - Math.sin(ang - 0.52) * 8.8); ctx.lineTo(endX - Math.cos(ang + 0.52) * 8.8, endY - Math.sin(ang + 0.52) * 8.8); ctx.closePath(); ctx.fill(); ctx.restore(); // 3. Crisp Pill Label Above Optical Lens const podTag = appState.mode === "drug" ? appState.drugName : "CRISPR · −" + appState.gene; ctx.save(); ctx.font = "600 11.5px 'Google Sans', sans-serif"; const tw = ctx.measureText(podTag).width + 20; const ty = podY - podR - 14; ctx.fillStyle = pal.podTagBg; ctx.strokeStyle = pal.podTagBorder; ctx.lineWidth = 1.1; ctx.beginPath(); ctx.roundRect(podX - tw * 0.5, ty - 11, tw, 22, 999); ctx.fill(); ctx.stroke(); ctx.fillStyle = pal.podTagInk; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(podTag, podX, ty + 0.5); ctx.restore(); } // ========================================================================= // 4. CellGemma E4B Core (Wordmark + 3D Geodesic Mesh + Gemma 4 Star Reticle + Slim Decoder) // ========================================================================= function evalCubicBezier(p0, p1, p2, p3, t) { const u = 1 - t; const tt = t * t; const uu = u * u; const uuu = uu * u; const ttt = tt * t; return { x: uuu * p0.x + 3 * uu * t * p1.x + 3 * u * tt * p2.x + ttt * p3.x, y: uuu * p0.y + 3 * uu * t * p1.y + 3 * u * tt * p2.y + ttt * p3.y, }; } function getEngineBoxMetrics(W, H, mx, my) { const bw0 = 268; const bh0 = 188; const scale = Math.min(1.0, Math.max(0.74, Math.min(W / 1480, (H - 56) / 235))); const bw = bw0 * scale; const bh = bh0 * scale; const inEnd = mx - (bw0 * 0.5 + 12) * scale; const portOutX = mx + (bw0 * 0.5 + 19) * scale; const portUpY = my - 31 * scale; const portDnY = my + 31 * scale; return { bw0, bh0, scale, bw, bh, inEnd, portOutX, portUpY, portDnY }; } function getOutputBranchCurve(eng, my, rightCellEdge, cellR, isUp) { const startX = eng.portOutX; const startY = isUp ? eng.portUpY : eng.portDnY; const endX = rightCellEdge; const endY = isUp ? my - cellR * 0.25 : my + cellR * 0.25; const span = endX - startX; return { p0: { x: startX, y: startY }, p1: { x: startX + span * 0.45, y: startY }, p2: { x: startX + span * 0.55, y: endY }, p3: { x: endX, y: endY }, }; } function drawOfficialWordmarkInCore(ctx, cx, cy, targetH) { const logoImg = document.getElementById("brand-logo-dark"); if (logoImg && logoImg.complete && logoImg.naturalWidth > 0) { const aspect = logoImg.naturalWidth / logoImg.naturalHeight; const drawW = targetH * aspect; ctx.save(); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high"; ctx.drawImage(logoImg, cx - drawW * 0.5, cy - targetH * 0.5, drawW, targetH); ctx.restore(); return; } // Crisp immediate two-tone fallback on frame 0 before PNG decode completes ctx.save(); ctx.font = "600 18px 'Google Sans', sans-serif"; ctx.textBaseline = "middle"; const wCell = ctx.measureText("Cell").width; const wGemma = ctx.measureText("Gemma").width; const startX = cx - (wCell + wGemma) * 0.5; ctx.textAlign = "left"; ctx.fillStyle = "#ffffff"; ctx.fillText("Cell", startX, cy); ctx.fillStyle = "#4285ff"; ctx.fillText("Gemma", startX + wCell, cy); ctx.restore(); } function drawGemmaStarReticleEmblem(ctx, cx, cy, S, running, after, nowMs) { // Euclidean geometry for the Gemma 4 Star-Reticle emblem: // - Outer circle radius Rc = 0.72 * S // - Inscribed square half-side a = Rc / sqrt(2) // - 4 quarter-circle concave star arcs centered at (+-a, +-a) with radius a // - Tangent grid lines x = +-a, y = +-a extending to +-0.86 * S // - Cardinal crosshair rays from +-1.0 * S inward to the 4 star cusps (0, +-a), (+-a, 0) // - Two 45-degree diagonal struts from (-a, -a) and (+a, +a) meeting the concave arcs perpendicularly! const Rc = S * 0.72; const a = Rc * Math.SQRT1_2; const gridExt = S * 0.86; ctx.save(); // 1. Subtle Optical Aura Behind the Gemma Star const auraR = S * (running ? 1.15 + 0.08 * Math.sin(nowMs * 0.008) : 1.02); const aura = ctx.createRadialGradient(cx, cy, 2, cx, cy, auraR); if (running) { aura.addColorStop(0, "rgba(96, 165, 250, 0.52)"); aura.addColorStop(0.5, "rgba(43, 116, 255, 0.22)"); aura.addColorStop(1, "rgba(43, 116, 255, 0)"); } else if (after) { aura.addColorStop(0, "rgba(56, 189, 248, 0.34)"); aura.addColorStop(0.55, "rgba(43, 116, 255, 0.14)"); aura.addColorStop(1, "rgba(43, 116, 255, 0)"); } else { aura.addColorStop(0, "rgba(59, 130, 246, 0.24)"); aura.addColorStop(1, "rgba(59, 130, 246, 0)"); } ctx.fillStyle = aura; ctx.beginPath(); ctx.arc(cx, cy, auraR, 0, Math.PI * 2); ctx.fill(); // 2. Precision Reticle Construction Lines & Circle const lineCol = running ? "rgba(147, 197, 253, 0.76)" : after ? "rgba(125, 211, 252, 0.56)" : "rgba(148, 179, 224, 0.44)"; ctx.strokeStyle = lineCol; ctx.lineWidth = 1.35; ctx.lineCap = "round"; // Outer construction circle ctx.beginPath(); ctx.arc(cx, cy, Rc, 0, Math.PI * 2); ctx.stroke(); // 4 Tangent grid lines (x = +-a, y = +-a) ctx.beginPath(); ctx.moveTo(cx - gridExt, cy - a); ctx.lineTo(cx + gridExt, cy - a); ctx.moveTo(cx - gridExt, cy + a); ctx.lineTo(cx + gridExt, cy + a); ctx.moveTo(cx - a, cy - gridExt); ctx.lineTo(cx - a, cy + gridExt); ctx.moveTo(cx + a, cy - gridExt); ctx.lineTo(cx + a, cy + gridExt); // 4 Cardinal crosshair rays (stopping cleanly at the 4 cusps so the star center glows pure!) ctx.moveTo(cx, cy - S); ctx.lineTo(cx, cy - a); ctx.moveTo(cx, cy + a); ctx.lineTo(cx, cy + S); ctx.moveTo(cx - S, cy); ctx.lineTo(cx - a, cy); ctx.moveTo(cx + a, cy); ctx.lineTo(cx + S, cy); // 2 Signature 45-degree Euclidean radius struts (top-left & bottom-right quadrants) const diagMid = a * (1 - Math.SQRT1_2); ctx.moveTo(cx - a, cy - a); ctx.lineTo(cx - diagMid, cy - diagMid); ctx.moveTo(cx + a, cy + a); ctx.lineTo(cx + diagMid, cy + diagMid); ctx.stroke(); // Optional Rotating Optical Sweep Arc ONLY while running! if (running) { const sweepA = (nowMs * 0.0042) % (Math.PI * 2); ctx.strokeStyle = "#e0f2fe"; ctx.lineWidth = 2.2; ctx.beginPath(); ctx.arc(cx, cy, Rc, sweepA, sweepA + 1.05); ctx.stroke(); } // 3. Iconic Concave 4-Point Gemma Star (4 tangent quarter-circle arcs!) const traceGemmaStar = () => { ctx.beginPath(); ctx.moveTo(cx, cy - a); // Top cusp -> Right cusp (center at cx + a, cy - a; angles PI -> PI/2 anticlockwise) ctx.arc(cx + a, cy - a, a, Math.PI, Math.PI * 0.5, true); // Right cusp -> Bottom cusp (center at cx + a, cy + a; angles -PI/2 -> -PI anticlockwise) ctx.arc(cx + a, cy + a, a, -Math.PI * 0.5, -Math.PI, true); // Bottom cusp -> Left cusp (center at cx - a, cy + a; angles 0 -> -PI/2 anticlockwise) ctx.arc(cx - a, cy + a, a, 0, -Math.PI * 0.5, true); // Left cusp -> Top cusp (center at cx - a, cy - a; angles PI/2 -> 0 anticlockwise) ctx.arc(cx - a, cy - a, a, Math.PI * 0.5, 0, true); ctx.closePath(); }; const starFill = ctx.createRadialGradient(cx, cy, 1, cx, cy, a); if (running) { starFill.addColorStop(0, "rgba(224, 242, 254, 0.95)"); starFill.addColorStop(0.55, "rgba(59, 130, 246, 0.55)"); starFill.addColorStop(1, "rgba(37, 99, 235, 0.18)"); } else { starFill.addColorStop(0, "rgba(186, 230, 253, 0.42)"); starFill.addColorStop(0.65, "rgba(43, 116, 255, 0.20)"); starFill.addColorStop(1, "rgba(30, 64, 175, 0.08)"); } traceGemmaStar(); ctx.fillStyle = starFill; ctx.fill(); const starStroke = ctx.createLinearGradient(cx - a, cy - a, cx + a, cy + a); starStroke.addColorStop(0, "#ffffff"); starStroke.addColorStop(0.48, "#60a5fa"); starStroke.addColorStop(1, "#2b74ff"); ctx.strokeStyle = starStroke; ctx.lineWidth = 2.6; ctx.stroke(); ctx.restore(); } function draw3DGeodesicCoreMesh(ctx, cx, cy, radius, running, nowMs) { const yaw = running ? 0.5 + nowMs * 0.0009 : 0.55; const pitch = running ? 0.28 + Math.sin(nowMs * 0.0012) * 0.08 : 0.28; const proj = GEODESIC.verts.map((v) => { const p = rotate3D(v[0], v[1], v[2], yaw, pitch); const persp = 3.6 / (3.6 - p.z * 0.45); return { x: cx + p.x * radius * 1.18 * persp, y: cy + p.y * radius * 0.92 * persp, z: p.z, }; }); ctx.save(); for (const [u, v] of GEODESIC.edges) { const a = proj[u]; const b = proj[v]; const zAvg = (a.z + b.z) * 0.5; const alpha = running ? 0.14 + Math.max(0, zAvg + 0.6) * 0.24 : 0.09 + Math.max(0, zAvg + 0.6) * 0.16; ctx.strokeStyle = "rgba(56, 152, 255, " + alpha.toFixed(3) + ")"; ctx.lineWidth = zAvg > 0.2 ? 1.15 : 0.8; ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke(); } for (const p of proj) { if (p.z < -0.25) continue; const a = running ? 0.58 : 0.36; ctx.fillStyle = "rgba(125, 211, 252, " + a.toFixed(2) + ")"; ctx.beginPath(); ctx.arc(p.x, p.y, p.z > 0.35 ? 2.1 : 1.4, 0, Math.PI * 2); ctx.fill(); } ctx.restore(); } function drawCellGemmaEngine(ctx, eng, mx, my, leftCellEdge, rightCellEdge, cellR, nowMs, pal) { const bw = eng.bw0; const bh = eng.bh0; const bx = mx - bw * 0.5; const by = my - bh * 0.5; const running = isTransmitting(); const after = appState.stageMode === "after"; drawFloorShadow(ctx, mx, my + eng.bh * 0.5 + 20, eng.bw * 0.52, 13, 0.11, pal); // 1. Left Input Optical Conduit (Single Cell + Perturbation -> CellGemma Encoder) const inEnd = eng.inEnd; ctx.save(); const inCol = running ? pal.conduitActiveIn : pal.conduitIdle; ctx.fillStyle = inCol; ctx.beginPath(); ctx.arc(leftCellEdge, my, 3.8, 0, Math.PI * 2); ctx.fill(); ctx.strokeStyle = inCol; ctx.lineWidth = running ? 3.0 : 2.1; ctx.beginPath(); ctx.moveTo(leftCellEdge, my); ctx.lineTo(inEnd, my); ctx.stroke(); ctx.beginPath(); ctx.moveTo(inEnd, my); ctx.lineTo(inEnd - 8.5, my - 5); ctx.lineTo(inEnd - 8.5, my + 5); ctx.closePath(); ctx.fill(); ctx.restore(); // 2. Dual Bifurcated Output Optical Conduits (+UP Emerald & -DOWN Coral-Rose) const upCurve = getOutputBranchCurve(eng, my, rightCellEdge, cellR, true); const dnCurve = getOutputBranchCurve(eng, my, rightCellEdge, cellR, false); const drawBranch = (c, activeCol) => { const col = running || after ? activeCol : pal.conduitIdle; ctx.save(); if (running) { ctx.shadowColor = activeCol; ctx.shadowBlur = 12; } ctx.strokeStyle = col; ctx.lineWidth = running ? 3.0 : 2.1; ctx.beginPath(); ctx.moveTo(c.p0.x, c.p0.y); ctx.bezierCurveTo(c.p1.x, c.p1.y, c.p2.x, c.p2.y, c.p3.x, c.p3.y); ctx.stroke(); const ang = Math.atan2(c.p3.y - c.p2.y, c.p3.x - c.p2.x); ctx.fillStyle = col; ctx.beginPath(); ctx.moveTo(c.p3.x, c.p3.y); ctx.lineTo(c.p3.x - Math.cos(ang - 0.5) * 9, c.p3.y - Math.sin(ang - 0.5) * 9); ctx.lineTo(c.p3.x - Math.cos(ang + 0.5) * 9, c.p3.y - Math.sin(ang + 0.5) * 9); ctx.closePath(); ctx.fill(); ctx.restore(); }; drawBranch(upCurve, "#10b981"); drawBranch(dnCurve, "#f43f5e"); // Scale monolith body uniformly around (mx, my) so proportions stay razor-sharp on laptops ctx.save(); ctx.translate(mx, my); ctx.scale(eng.scale, eng.scale); ctx.translate(-mx, -my); // 3. 3D Beveled Obsidian-Sapphire Optical Monolith ctx.fillStyle = "#030712"; ctx.beginPath(); ctx.roundRect(bx, by + 6, bw, bh, 24); ctx.fill(); // Left Input Coupler Lug ctx.fillStyle = "#1e293b"; ctx.strokeStyle = "#334155"; ctx.lineWidth = 1.1; ctx.beginPath(); ctx.roundRect(bx - 8, my - 15, 11, 30, 5); ctx.fill(); ctx.stroke(); ctx.save(); ctx.shadowColor = running ? "rgba(43, 116, 255, 0.36)" : "rgba(3, 8, 20, 0.24)"; ctx.shadowBlur = running ? 34 : 20; ctx.shadowOffsetY = 8; const chGrad = ctx.createLinearGradient(bx, by, bx, by + bh); chGrad.addColorStop(0, "#101e38"); chGrad.addColorStop(0.52, "#071022"); chGrad.addColorStop(1, "#040915"); ctx.fillStyle = chGrad; ctx.beginPath(); ctx.roundRect(bx, by, bw, bh, 24); ctx.fill(); ctx.restore(); const bezelGrad = ctx.createLinearGradient(bx, by, bx, by + bh); bezelGrad.addColorStop(0, running ? "#60a5fa" : "rgba(147, 197, 253, 0.46)"); bezelGrad.addColorStop(0.45, running ? "#3b82f6" : "rgba(96, 165, 250, 0.26)"); bezelGrad.addColorStop(1, "rgba(30, 58, 138, 0.22)"); ctx.strokeStyle = bezelGrad; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.roundRect(bx + 0.75, by + 0.75, bw - 1.5, bh - 1.5, 23); ctx.stroke(); // Right Output Optical Port Caps (+ Emerald, − Coral-Rose) const drawPortCap = (py, activeBg, glyph) => { const capX = bx + bw - 6; const capW = 24; const capH = 24; ctx.save(); ctx.fillStyle = running || after ? activeBg : "#1e293b"; ctx.strokeStyle = "#060d1c"; ctx.lineWidth = 1.6; ctx.beginPath(); ctx.roundRect(capX, py - capH * 0.5, capW, capH, 7); ctx.fill(); ctx.stroke(); ctx.fillStyle = "#ffffff"; ctx.font = "700 13px 'Google Sans Mono', monospace"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(glyph, capX + capW * 0.5 + 0.5, py + 0.5); ctx.restore(); }; drawPortCap(my - 31, "#059669", "+"); drawPortCap(my + 31, "#e11d48", "−"); // 4. `CellGemma` Wordmark at Top of Core drawOfficialWordmarkInCore(ctx, mx - 14, by + 25, 18.0); // Subtle `E4B` Badge Beside Wordmark ctx.save(); ctx.fillStyle = "rgba(43, 116, 255, 0.20)"; ctx.strokeStyle = "rgba(96, 165, 250, 0.38)"; ctx.lineWidth = 1.0; ctx.beginPath(); ctx.roundRect(mx + 56, by + 17, 32, 18, 5); ctx.fill(); ctx.stroke(); ctx.fillStyle = "#93c5fd"; ctx.font = "600 9.5px 'Google Sans Mono', monospace"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText("E4B", mx + 72, by + 26.5); ctx.restore(); // 5. Recessed Optical Chamber: // Left/Center: 3D Geodesic Gene-Network Halo + Gemma-4 Star-Reticle // Right Strip: Slim Vertical `DECODER` Prism (Stage 2 Residual MLP) const winX = bx + 16; const winY = by + 46; const winW = bw - 34; const winH = 108; const decW = 34; const gemmaW = winW - decW - 6; ctx.save(); ctx.fillStyle = "#030814"; ctx.strokeStyle = "rgba(59, 130, 246, 0.20)"; ctx.lineWidth = 1.1; ctx.beginPath(); ctx.roundRect(winX, winY, gemmaW, winH, 14); ctx.fill(); ctx.stroke(); ctx.beginPath(); ctx.roundRect(winX + 1, winY + 1, gemmaW - 2, winH - 2, 13); ctx.clip(); const starCX = winX + gemmaW * 0.5; const starCY = winY + winH * 0.5; draw3DGeodesicCoreMesh(ctx, starCX, starCY, 46, running, nowMs); drawGemmaStarReticleEmblem(ctx, starCX, starCY, 38, running, after, nowMs); // Subtle Token Transfer Arrow Into Stage-2 Decoder While Running if (running) { const pulseX = starCX + 38 + ((nowMs * 0.08) % 26); ctx.fillStyle = "#7dd3fc"; ctx.beginPath(); ctx.arc(pulseX, starCY, 2.4, 0, Math.PI * 2); ctx.fill(); } ctx.restore(); // 3 Horizontal Latent-Embedding Micro-Traces Bridging Gemma 4 E4B -> Stage-2 Decoder Prism const decX = winX + gemmaW + 6; ctx.save(); ctx.strokeStyle = running ? "#60a5fa" : after ? "rgba(96, 165, 250, 0.58)" : "rgba(148, 179, 224, 0.25)"; ctx.lineWidth = 1.3; ctx.beginPath(); for (const dy of [-20, 0, 20]) { ctx.moveTo(winX + gemmaW, starCY + dy); ctx.lineTo(decX, starCY + dy); } ctx.stroke(); ctx.restore(); // Slim Vertical Stage-2 Expression Reconstruction Decoder Prism ctx.save(); const decGrad = ctx.createLinearGradient(decX, winY, decX, winY + winH); if (running || after) { decGrad.addColorStop(0, "rgba(16, 185, 129, 0.28)"); decGrad.addColorStop(0.5, "rgba(37, 99, 235, 0.22)"); decGrad.addColorStop(1, "rgba(244, 63, 94, 0.28)"); } else { decGrad.addColorStop(0, "rgba(30, 41, 59, 0.7)"); decGrad.addColorStop(1, "rgba(15, 23, 42, 0.7)"); } ctx.fillStyle = decGrad; ctx.strokeStyle = running ? "rgba(96, 165, 250, 0.55)" : "rgba(148, 179, 224, 0.26)"; ctx.lineWidth = 1.15; ctx.beginPath(); ctx.roundRect(decX, winY, decW, winH, 11); ctx.fill(); ctx.stroke(); // Continuous Residual Spectrum Micro-Ticks inside Decoder Top (+UP) & Bottom (-DOWN) const tickActive = running || after; const drawSpectrumTicks = (baseY, dir, col) => { ctx.strokeStyle = col; ctx.lineWidth = 1.4; ctx.lineCap = "round"; const widths = [14, 10, 6]; ctx.beginPath(); for (let k = 0; k < widths.length; k++) { const yk = baseY + dir * (k * 4.5); const hw = widths[k] * 0.5; ctx.moveTo(decX + decW * 0.5 - hw, yk); ctx.lineTo(decX + decW * 0.5 + hw, yk); } ctx.stroke(); }; drawSpectrumTicks( winY + 11, 1, tickActive ? "rgba(52, 211, 153, 0.78)" : "rgba(148, 163, 184, 0.28)" ); drawSpectrumTicks( winY + winH - 11, -1, tickActive ? "rgba(251, 113, 133, 0.78)" : "rgba(148, 163, 184, 0.28)" ); // Vertical `DECODER` Typography ctx.translate(decX + decW * 0.5, winY + winH * 0.5); ctx.rotate(-Math.PI * 0.5); ctx.fillStyle = running || after ? "#f1f5f9" : "#94a3b8"; ctx.font = "600 9.5px 'Google Sans Mono', monospace"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText("DECODER", 0, 0.5); ctx.restore(); // 6. Precision Status Footer Inside Core let statusStr = "Ready · 19.8k Gene Vocab"; let dotCol = "#64748b"; if (running) { const sec = ((performance.now() - appState.runStartedAtMs) / 1000).toFixed(1); if (appState.liveGeneCount > 0) { statusStr = "Streaming " + appState.liveGeneCount + " Genes · " + sec + "s"; } else if (appState.runPhase === "loading_model") { statusStr = "Loading E4B · " + sec + "s"; } else { statusStr = "Encoding Cell · " + sec + "s"; } dotCol = "#38bdf8"; } else if (after) { statusStr = "Complete · " + appState.elapsedSeconds.toFixed(1) + "s"; dotCol = "#10b981"; } ctx.save(); ctx.font = "600 10.5px 'Google Sans Mono', monospace"; const tw = ctx.measureText(statusStr).width; const stX = mx - (tw + 14) * 0.5; const stY = by + bh - 19; ctx.fillStyle = dotCol; ctx.beginPath(); ctx.arc(stX + 4, stY, 3.6, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = "#cbd5e1"; ctx.textAlign = "left"; ctx.textBaseline = "middle"; ctx.fillText(statusStr, stX + 13, stY + 0.5); ctx.restore(); // Restore outer unscaled canvas transform ctx.restore(); } // ========================================================================= // 5. Magnified Radial Sunburst Equalizer + Uniform Compartment Pins // ========================================================================= function lfcToFold(lfc) { return Math.exp(Number(lfc || 0)); } function formatLinearShiftLabel(lfc, isUp) { const fold = lfcToFold(lfc); if (isUp) { const pctGain = Math.max(0, (fold - 1.0) * 100); return "+" + pctGain.toFixed(1) + "%"; } const pctDrop = Math.max(0, (1.0 - fold) * 100); return "−" + pctDrop.toFixed(1) + "%"; } function getUnifiedPolarityGenes(res, isUp) { if (!res) return []; const raw = (res.top_up || []).concat(res.top_down || [], res.gene_stars || [], res.all_genes || []); const bySym = new Map(); const prefix = isUp ? "+" : "-"; const signedShift = (g) => { const v = Number(g.lfc !== undefined ? g.lfc : g.residual || 0); return isUp ? v : -v; }; for (const g of raw) { if (!g || !g.sym || !g.sym.startsWith(prefix)) continue; const prev = bySym.get(g.sym); const s = signedShift(g); const prevS = prev ? signedShift(prev) : -1e9; if (s > prevS) { bySym.set(g.sym, g); } } const allSorted = Array.from(bySym.values()).sort((a, b) => signedShift(b) - signedShift(a)); const aligned = allSorted.filter((g) => signedShift(g) > 0.0005); return aligned.length ? aligned : allSorted; } function pickStratifiedSunburstGenes(sortedPool, maxSpan, featuredSyms) { if (!sortedPool.length) return []; // Pin #0 (top fold-change leader) AND #1 (signature gene named in the verdict headline, // e.g. +CALR / -MDM2, falling back to #1 fold-change leader) into the two right-rail callout slots! let secondIdx = sortedPool.length > 1 ? 1 : -1; if (Array.isArray(featuredSyms) && featuredSyms.length > 0 && sortedPool.length > 1) { for (const fSym of featuredSyms) { const idx = sortedPool.findIndex((g) => g.sym === fSym); if (idx > 0) { secondIdx = idx; break; } } } if (sortedPool.length <= 6) { if (secondIdx <= 1) return sortedPool.slice(); const head = [sortedPool[0], sortedPool[secondIdx]]; for (let i = 1; i < sortedPool.length; i++) { if (i !== secondIdx) head.push(sortedPool[i]); } return head; } const head = [sortedPool[0], sortedPool[secondIdx]]; const used = new Set([0, secondIdx]); const refTopIdx = secondIdx === 1 ? 1 : 1; const hiSpan = computeSunburstSpanPx( Math.exp(Math.abs(Number(sortedPool[refTopIdx].lfc || sortedPool[refTopIdx].residual || 0))), maxSpan ); const loSpan = computeSunburstSpanPx( Math.exp( Math.abs( Number(sortedPool[sortedPool.length - 1].lfc || sortedPool[sortedPool.length - 1].residual || 0) ) ), maxSpan ); const tail = []; const fracs = [0.82, 0.55, 0.28, 0.0]; for (const frac of fracs) { const target = loSpan + (hiSpan - loSpan) * frac; let bestIdx = -1; let bestDist = 1e9; for (let i = 1; i < sortedPool.length; i++) { if (used.has(i)) continue; const mag = Math.abs(Number(sortedPool[i].lfc || sortedPool[i].residual || 0)); const s = computeSunburstSpanPx(Math.exp(mag), maxSpan); const d = Math.abs(s - target); if (d < bestDist) { bestDist = d; bestIdx = i; } } if (bestIdx >= 0) { used.add(bestIdx); tail.push(sortedPool[bestIdx]); } } tail.sort( (a, b) => Math.abs(Number(b.lfc || b.residual || 0)) - Math.abs(Number(a.lfc || a.residual || 0)) ); return head.concat(tail); } function buildPredictedOrbsLayout(cx, cy, cellR, res, reveal) { if (!res) return []; const metrics = getPredictedRingMetrics(cellR); const { predR, baseRingR, maxSpan } = metrics; const featUp = res.verdict && Array.isArray(res.verdict.featured_up) ? res.verdict.featured_up : []; const featDn = res.verdict && Array.isArray(res.verdict.featured_down) ? res.verdict.featured_down : []; const topUp = pickStratifiedSunburstGenes(getUnifiedPolarityGenes(res, true), maxSpan, featUp); const topDn = pickStratifiedSunburstGenes(getUnifiedPolarityGenes(res, false), maxSpan, featDn); if (!topUp.length && !topDn.length) return []; const placed = []; const placePolarityGroup = (list, isUp) => { const n = list.length; for (let i = 0; i < n; i++) { const g = list[i]; const locKey = g.loc === "surface" || g.loc === "nucleus" ? g.loc : "cytoplasm"; const t = n === 1 ? 0.15 : i / (n - 1); // Rank #1 starts on right (±0.54 rad) and fans smoothly leftward (±2.28 rad) const barAng = isUp ? -0.54 - t * 1.74 : 0.54 + t * 1.74; const ux = Math.cos(barAng); const uy = Math.sin(barAng); // Place uniform compartment pin along exact same radial ray so tethers never cross! let pinFrac = 0.63; if (locKey === "surface") { pinFrac = 0.955; } else if (locKey === "cytoplasm") { pinFrac = i % 2 === 0 ? 0.69 : 0.55; } else { pinFrac = i % 2 === 0 ? 0.25 : 0.165; } const pinDist = predR * pinFrac; const lfcNum = Number(g.lfc || g.residual || 0); const mag = Math.abs(lfcNum); const fold = lfcToFold(lfcNum); const foldFactor = Math.exp(mag); const fullSpanPx = computeSunburstSpanPx(foldFactor, maxSpan); const spanPx = Math.max(3.2, fullSpanPx * reveal); const tipR = baseRingR + spanPx; const anchorR = tipR + 3.5; placed.push({ sym: g.sym, gene: g, loc: locKey, rankIdx: i, isUp, fold, foldFactor, absMag: mag, targetR: fullSpanPx, rPx: 8.5, pinR: 4.2, x: cx + ux * pinDist, y: cy + uy * pinDist, barAng, ux, uy, baseRingR, tipR, barBaseX: cx + ux * baseRingR, barBaseY: cy + uy * baseRingR, barStartX: cx + ux * baseRingR, barStartY: cy + uy * baseRingR, barEndX: cx + ux * tipR, barEndY: cy + uy * tipR, anchorX: cx + ux * anchorR, anchorY: cy + uy * anchorR, calloutBox: null, }); } }; placePolarityGroup(topUp, true); placePolarityGroup(topDn, false); return placed; } function drawPredictedSunburstOverlays(ctx, cx, cy, metrics, orbs, pal) { drawReferenceScaleRings(ctx, cx, cy, metrics, true, pal); if (!orbs.length) return; // 1. Pure Radial Dashed Tethers From Subcellular Locus Pins -> Regulated Baseline Ring ctx.save(); for (const o of orbs) { const isFocus = o.sym === appState.hoveredGeneSym || o.sym === appState.selectedGeneSym; ctx.strokeStyle = isFocus ? pal.focusRing : o.isUp ? pal.tetherUp : pal.tetherDn; ctx.lineWidth = isFocus ? 1.65 : 1.05; ctx.setLineDash([2.2, 3.2]); ctx.beginPath(); ctx.moveTo(o.x, o.y); ctx.lineTo(o.barBaseX, o.barBaseY); ctx.stroke(); } ctx.restore(); // 2. Uniform Crisp Compartment Locus Pins Inside Nucleus / Cytoplasm / Membrane for (const o of orbs) { const isFocus = o.sym === appState.hoveredGeneSym || o.sym === appState.selectedGeneSym; const pinCol = o.isUp ? "#10b981" : "#f43f5e"; const rad = isFocus ? 5.8 : o.pinR; ctx.save(); if (isFocus) { ctx.shadowColor = pinCol; ctx.shadowBlur = 10; } ctx.fillStyle = pinCol; ctx.strokeStyle = isFocus ? pal.focusRing : "#ffffff"; ctx.lineWidth = isFocus ? 2.1 : 1.35; ctx.beginPath(); ctx.arc(o.x, o.y, rad, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); ctx.restore(); } // 3. Outward Magnified Radial Equalizer Bars (Top: Emerald ↑ UP, Bottom: Crimson ↓ DOWN) for (const o of orbs) { const isFocus = o.sym === appState.hoveredGeneSym || o.sym === appState.selectedGeneSym; const barW = isFocus ? 8.4 : 6.2; const spanPx = Math.max(3.2, o.tipR - o.baseRingR); ctx.save(); ctx.translate(cx, cy); ctx.rotate(o.barAng); if (isFocus) { ctx.shadowColor = o.isUp ? "rgba(52, 211, 153, 0.55)" : "rgba(251, 113, 133, 0.55)"; ctx.shadowBlur = 10; } const grad = ctx.createLinearGradient(o.baseRingR, 0, o.baseRingR + spanPx, 0); if (o.isUp) { grad.addColorStop(0, "#059669"); grad.addColorStop(1, "#34d399"); ctx.strokeStyle = isFocus ? pal.focusRing : "rgba(167, 243, 208, 0.78)"; } else { grad.addColorStop(0, "#be123c"); grad.addColorStop(1, "#fb7185"); ctx.strokeStyle = isFocus ? pal.focusRing : "rgba(254, 205, 211, 0.78)"; } ctx.fillStyle = grad; ctx.lineWidth = isFocus ? 1.85 : 0.95; ctx.beginPath(); ctx.roundRect(o.baseRingR, -barW * 0.5, spanPx, barW, 3.1); ctx.fill(); ctx.stroke(); // Crisp Baseline Anchor Tick Across Every Bar Base ctx.shadowBlur = 0; ctx.strokeStyle = isFocus ? pal.focusRing : pal.ringTick; ctx.lineWidth = 1.4; ctx.beginPath(); ctx.moveTo(o.baseRingR, -barW * 0.72); ctx.lineTo(o.baseRingR, barW * 0.72); ctx.stroke(); ctx.restore(); } } function drawRightRailCallouts(ctx, W, cx, cy, metrics, orbs, pal) { if (!orbs.length) return; // Choose #1 and #2 UP + #1 and #2 DOWN (always on the right sector, so leader lines never cross!) const rightItems = orbs.filter((o) => o.rankIdx < 2); if (!rightItems.length) return; rightItems.sort((a, b) => a.anchorY - b.anchorY); ctx.save(); ctx.font = "700 11px 'Google Sans Mono', monospace"; const padX = 9.5; const boxH = 24; let maxBoxW = 118; let maxAnchorX = cx + metrics.midRingR; const labels = rightItems.map((o) => { if (o.anchorX > maxAnchorX) maxAnchorX = o.anchorX; const shiftStr = formatLinearShiftLabel(o.gene.lfc || o.gene.residual || 0, o.isUp); const lbl = (o.isUp ? "↑ " : "↓ ") + o.gene.gene + " " + shiftStr; const bw = ctx.measureText(lbl).width + padX * 2; if (bw > maxBoxW) maxBoxW = bw; return { lbl, bw }; }); const desiredPillX = Math.max(cx + metrics.midRingR + 22, maxAnchorX + 20); const pillX = Math.min(W - maxBoxW - 12, desiredPillX); const elbowX = Math.min(pillX - 8, Math.max(maxAnchorX + 7, pillX - 16)); const minY = cy - metrics.outerRingR * 0.78; const maxY = cy + metrics.outerRingR * 0.78; const minGap = 32; const ys = rightItems.map((o) => Math.max(minY, Math.min(maxY, o.anchorY))); for (let i = 1; i < ys.length; i++) { if (ys[i] - ys[i - 1] < minGap) ys[i] = ys[i - 1] + minGap; } if (ys[ys.length - 1] > maxY) { const overflow = ys[ys.length - 1] - maxY; for (let i = 0; i < ys.length; i++) ys[i] -= overflow; } const calledOutSyms = new Set(); for (let i = 0; i < rightItems.length; i++) { const o = rightItems[i]; calledOutSyms.add(o.sym); const ly = ys[i]; const { lbl, bw } = labels[i]; const isFocus = o.sym === appState.hoveredGeneSym || o.sym === appState.selectedGeneSym; const lineCol = isFocus ? pal.focusRing : o.isUp ? "#10b981" : "#f43f5e"; ctx.strokeStyle = lineCol; ctx.lineWidth = isFocus ? 1.85 : 1.3; ctx.beginPath(); ctx.moveTo(o.anchorX, o.anchorY); ctx.lineTo(elbowX, ly); ctx.lineTo(pillX, ly); ctx.stroke(); ctx.fillStyle = lineCol; ctx.beginPath(); ctx.arc(o.anchorX, o.anchorY, 2.1, 0, Math.PI * 2); ctx.fill(); ctx.save(); ctx.shadowColor = pal.isDark ? "rgba(0, 0, 0, 0.45)" : "rgba(15, 23, 42, 0.08)"; ctx.shadowBlur = 10; ctx.shadowOffsetY = 2; ctx.fillStyle = isFocus ? pal.calloutFocusBg : pal.calloutBg; ctx.strokeStyle = isFocus ? pal.focusRing : o.isUp ? pal.calloutUpBorder : pal.calloutDnBorder; ctx.lineWidth = 1.25; ctx.beginPath(); ctx.roundRect(pillX, ly - boxH * 0.5, bw, boxH, 7.5); ctx.fill(); ctx.stroke(); ctx.restore(); ctx.fillStyle = isFocus ? pal.calloutFocusInk : o.isUp ? pal.calloutUpInk : pal.calloutDnInk; ctx.textAlign = "left"; ctx.textBaseline = "middle"; ctx.fillText(lbl, pillX + padX, ly + 0.5); o.calloutBox = { x: pillX, y: ly - boxH * 0.5, w: bw, h: boxH }; } // Local radial tip badge when hovering/clicking rank #3..#6 (so no wire ever crosses the sunburst!) const focusSym = appState.hoveredGeneSym || appState.selectedGeneSym; if (focusSym && !calledOutSyms.has(focusSym)) { const fo = orbs.find((x) => x.sym === focusSym); if (fo) { const shiftStr = formatLinearShiftLabel(fo.gene.lfc || fo.gene.residual || 0, fo.isUp); const fLbl = (fo.isUp ? "↑ " : "↓ ") + fo.gene.gene + " " + shiftStr; const fW = ctx.measureText(fLbl).width + padX * 2; const outR = Math.max(fo.tipR, metrics.baseRingR) + 18; const bx = Math.max(12, Math.min(W - fW - 12, cx + fo.ux * outR - fW * 0.5)); const by = Math.max(66, Math.min(cy + metrics.outerRingR + 6, cy + fo.uy * outR - boxH * 0.5)); ctx.fillStyle = pal.calloutFocusBg; ctx.strokeStyle = pal.focusRing; ctx.lineWidth = 1.4; ctx.beginPath(); ctx.roundRect(bx, by, fW, boxH, 7.5); ctx.fill(); ctx.stroke(); ctx.fillStyle = pal.calloutFocusInk; ctx.textAlign = "left"; ctx.textBaseline = "middle"; ctx.fillText(fLbl, bx + padX, by + boxH * 0.5 + 0.5); } } ctx.restore(); } function drawCanvasHoverCard(ctx, W, res, pal) { const sym = appState.hoveredGeneSym || appState.selectedGeneSym; if (!sym || !res) return; const all = getUnifiedPolarityGenes(res, true).concat(getUnifiedPolarityGenes(res, false)); const g = all.find((x) => x.sym === sym); if (!g) return; const isUp = g.sym.startsWith("+"); const lfcNum = Number(g.lfc || 0); const fold = lfcToFold(lfcNum); const linearDesc = formatLinearShiftLabel(lfcNum, isUp) + " (" + fold.toFixed(2) + "×)"; const lfcStr = (lfcNum >= 0 ? "+" : "−") + Math.abs(lfcNum).toFixed(2) + " Δlog"; const line1 = g.sym + " · " + g.nick; const line2 = g.loc.toUpperCase() + " | " + linearDesc + " · Untreated: " + Number(g.ctrl_expr).toFixed(2) + " → Predicted: " + Number(g.pred_expr).toFixed(2) + " (" + lfcStr + ")"; ctx.save(); ctx.font = "600 12.5px 'Google Sans', sans-serif"; const w1 = ctx.measureText(line1).width; ctx.font = "500 11px 'Google Sans Mono', monospace"; const w2 = ctx.measureText(line2).width; const cardW = Math.max(w1, w2) + 32; const cardH = 48; const cx = W * 0.5 - cardW * 0.5; const cy = 15; ctx.shadowColor = "rgba(0, 0, 0, 0.32)"; ctx.shadowBlur = 20; ctx.shadowOffsetY = 6; ctx.fillStyle = pal.hoverCardBg; ctx.strokeStyle = pal.hoverCardBorder; ctx.lineWidth = 1.15; ctx.beginPath(); ctx.roundRect(cx, cy, cardW, cardH, 11); ctx.fill(); ctx.stroke(); ctx.restore(); ctx.save(); ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = isUp ? "#34d399" : "#fb7185"; ctx.font = "600 12.5px 'Google Sans', sans-serif"; ctx.fillText(line1, W * 0.5, cy + 16); ctx.fillStyle = pal.hoverCardSub; ctx.font = "500 11px 'Google Sans Mono', monospace"; ctx.fillText(line2, W * 0.5, cy + 34); ctx.restore(); } // ========================================================================= // 6. Transient Particle Simulation (Strictly Active ONLY During "running") // ========================================================================= function stepParticles(dtSec) { if (!isTransmitting()) { if (appState.inParticles.length) appState.inParticles.length = 0; if (appState.outParticles.length) appState.outParticles.length = 0; return; } if (appState.inParticles.length < 4 && Math.random() < dtSec * 4.5) { appState.inParticles.push({ t: 0, spread: (Math.random() - 0.5) * 12 }); } for (let i = appState.inParticles.length - 1; i >= 0; i--) { appState.inParticles[i].t += dtSec * 1.18; if (appState.inParticles[i].t >= 1) appState.inParticles.splice(i, 1); } if (appState.outParticles.length < 6 && Math.random() < dtSec * 5.2) { appState.outParticles.push({ t: 0, isUp: Math.random() >= 0.48, }); } for (let i = appState.outParticles.length - 1; i >= 0; i--) { appState.outParticles[i].t += dtSec * 1.18; if (appState.outParticles[i].t >= 1) appState.outParticles.splice(i, 1); } } function stepAnimatedBars(dtSec) { if (!appState.animatedBarRects.length) return; const target = appState.stageMode === "before" ? 0 : 1; appState.barAnimProgress += (target - appState.barAnimProgress) * Math.min(1, dtSec * 9.0); for (const item of appState.animatedBarRects) { const w = Math.max(0, item.targetW * appState.barAnimProgress); item.rect.setAttribute("width", w.toFixed(1)); } } // ========================================================================= // 7. Master 60fps Hero Canvas Render Loop // ========================================================================= let prevMs = performance.now(); function renderHeroStage(nowMs) { const dt = Math.min(0.08, Math.max(0.001, (nowMs - prevMs) / 1000)); prevMs = nowMs; stepParticles(dt); stepAnimatedBars(dt); const targetReveal = appState.stageMode === "before" ? 0 : 1; appState.revealProgress += (targetReveal - appState.revealProgress) * Math.min(1, dt * 7.5); const canvas = document.getElementById("hero-canvas"); if (!canvas) return; const W = Math.max(320, canvas.clientWidth || 1280); const H = Math.max(280, canvas.clientHeight || 420); const dpr = Math.min(2.5, window.devicePixelRatio || 1); if (canvas.width !== Math.floor(W * dpr) || canvas.height !== Math.floor(H * dpr)) { canvas.width = Math.floor(W * dpr); canvas.height = Math.floor(H * dpr); } const ctx = canvas.getContext("2d"); if (!ctx) return; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, W, H); const pal = getPalette(); // Subtle Geodesic Constellation in Peripheral Depth-of-Field drawAmbientGeodesicBackdrop(ctx, W, H, pal); const leftX = W * 0.192; const modelX = W * 0.442; const rightX = W * 0.728; const centerY = (H - 34) * 0.495; const cellR = Math.min(164, W * 0.103, (H - 54) * 0.365); const predMetrics = getPredictedRingMetrics(cellR); const engMetrics = getEngineBoxMetrics(W, H, modelX, centerY); // Continuous living biological cell motion (before, running, AND after!), // while transmission particles & radial fold bars strictly settle once running completes. const cellWaveSpeed = appState.stageMode === "running" ? 2.35 : 1.55; appState.cellAnimPhase += dt * cellWaveSpeed; const leftPhase = appState.cellAnimPhase; const rightPhase = appState.cellAnimPhase + 1.55; // 1. Left Untreated Biological Cell + Translucent Baseline Pearls drawLivingCell(ctx, leftX, centerY, cellR, "untreated", leftPhase, 1.0, pal); for (const bp of BASELINE_PEARLS) { const bx = leftX + Math.cos(bp.a) * (cellR * bp.d); const by = centerY + Math.sin(bp.a) * (cellR * bp.d); if (pal.isDark) { drawAtomSphere(ctx, bx, by, 4.8, "#cbd5e1", "#64748b", "#1e293b"); } else { drawAtomSphere(ctx, bx, by, 4.8, "#e2e8f0", "#64748b", "#334155"); } } // 2. Upper-Left 3D Drug / STRING-CRISPR Optical Magnifier const podR = Math.min(66, cellR * 0.41); const podX = leftX - cellR * 0.90; const podY = centerY - cellR * 0.66; drawInputPod(ctx, podX, podY, podR, leftX, centerY, cellR, nowMs, pal); // 3. Center CellGemma E4B Core & Dual +/- Conduits (Plugged Into 1.0x Baseline Ring) const leftEdge = leftX + cellR + 10; const rightEdge = rightX - predMetrics.baseRingR - 22; drawCellGemmaEngine(ctx, engMetrics, modelX, centerY, leftEdge, rightEdge, cellR, nowMs, pal); // 4. Transient Running Photons Riding Exact Conduits (Strictly ONLY while running!) if (isTransmitting()) { const inX2 = engMetrics.inEnd; for (const p of appState.inParticles) { const px = leftEdge + (inX2 - leftEdge) * p.t; const py = centerY + Math.sin(p.t * Math.PI) * (p.spread * 0.35); drawAtomSphere(ctx, px, py, 6.2, "#bae6fd", "#3b82f6", "#1e3a8a"); } const upCurve = getOutputBranchCurve(engMetrics, centerY, rightEdge, cellR, true); const dnCurve = getOutputBranchCurve(engMetrics, centerY, rightEdge, cellR, false); for (const q of appState.outParticles) { const curve = q.isUp ? upCurve : dnCurve; const pt = evalCubicBezier(curve.p0, curve.p1, curve.p2, curve.p3, q.t); drawJewelOrb(ctx, pt.x, pt.y, 8.0, q.isUp, false, pal, q.isUp ? "+" : "−"); } } // 5. Right Predicted Single Cell + 1.0x Radial Sunburst Equalizer Ring + Compartment Pins if (appState.stageMode === "before" && appState.revealProgress < 0.05) { drawBlueprintPlaceholderCell(ctx, rightX, centerY, cellR, pal); appState.renderedOrbs = []; } else { const rev = Math.max(0.15, appState.revealProgress); const orbs = buildPredictedOrbsLayout(rightX, centerY, cellR, appState.currentResult, rev); appState.renderedOrbs = orbs; drawLivingCell(ctx, rightX, centerY, predMetrics.predR, "predicted", rightPhase, rev, pal, orbs); drawPredictedSunburstOverlays(ctx, rightX, centerY, predMetrics, orbs, pal); if (rev > 0.6) { drawRightRailCallouts(ctx, W, rightX, centerY, predMetrics, orbs, pal); } } // 6. Crisp 2-Line Stage Captions const labelY = Math.min(H - 27, Math.max(centerY + cellR + 28, centerY + predMetrics.outerRingR + 18)); const cellName = appState.dataset === "tahoe" ? "Untreated A549 Cell #" + appState.cellIdx : "Untreated K562 Cell #" + appState.cellIdx; const pertPill = appState.mode === "drug" ? "+ " + appState.drugName + " (" + appState.concentrationUm.toFixed(2) + " µM)" : "CRISPR Knockdown · −" + appState.gene; drawStageCaption(ctx, leftX, labelY, cellName, pertPill, pal.captionTitle, pal.captionUntreatedSub); drawStageCaption( ctx, modelX, labelY, "Gemma 4 E4B + Residual Decoder", "Single-Cell Perturbation Model", pal.captionTitle, pal.captionModelSub ); drawStageCaption( ctx, rightX, labelY, "Predicted Single Cell", appState.currentResult ? "Radial bar length = % expression shift vs baseline" : "Awaiting simulation", pal.captionTitle, appState.currentResult ? pal.captionPredSub : pal.captionIdleSub ); // 7. Optional Hover/Selection Inspector Card drawCanvasHoverCard(ctx, W, appState.currentResult, pal); const pop = document.getElementById("customize-popover"); if (pop && !pop.classList.contains("hidden")) { renderPopoverMolecule(nowMs, pal); } } function drawStageCaption(ctx, x, y, title, sub, titleColor, subColor) { ctx.save(); ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = titleColor; ctx.font = "600 13.5px 'Google Sans', sans-serif"; ctx.fillText(title, x, y); ctx.fillStyle = subColor; ctx.font = "500 11.5px 'Google Sans Text', sans-serif"; ctx.fillText(sub, x, y + 17); ctx.restore(); } function renderPopoverMolecule(nowMs, pal) { const c = document.getElementById("mini-mol-canvas"); if (!c) return; const w = Math.max(120, c.clientWidth || 204); const h = Math.max(100, c.clientHeight || 156); const dpr = Math.min(2, window.devicePixelRatio || 1); if (c.width !== Math.floor(w * dpr) || c.height !== Math.floor(h * dpr)) { c.width = Math.floor(w * dpr); c.height = Math.floor(h * dpr); } const ctx = c.getContext("2d"); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h); if (appState.mode === "drug") { draw3DMoleculeInside( ctx, w * 0.5, h * 0.5, Math.min(w, h) * 0.44, appState.inputViz, appState.molRot.yaw, appState.molRot.pitch, pal.isDark ); } else { draw3DCrisprNetworkInside( ctx, w * 0.5, h * 0.5, Math.min(w, h) * 0.44, appState.inputViz, appState.gene, appState.molRot.yaw + nowMs * 0.0008, appState.molRot.pitch, pal.isDark ); } } // ========================================================================= // 8. Monotonic Equalizer Bars With Compartment Badges & Zero-Shift Empty State // ========================================================================= function buildCleanBarSvg(fraction, isUp, isEmpty) { const W = 200; const H = 9; const svg = document.createElementNS(SVG_NS, "svg"); svg.setAttribute("viewBox", "0 0 " + W + " " + H); svg.setAttribute("class", "bar-svg"); svg.setAttribute("aria-hidden", "true"); const track = document.createElementNS(SVG_NS, "rect"); track.setAttribute("x", "0"); track.setAttribute("y", "1"); track.setAttribute("width", String(W)); track.setAttribute("height", "7"); track.setAttribute("rx", "3.5"); track.setAttribute("class", "bar-track"); svg.appendChild(track); if (!isEmpty) { const targetW = Math.max(10, Math.min(W, fraction * W)); const initW = Math.max(0, targetW * appState.barAnimProgress); const fill = document.createElementNS(SVG_NS, "rect"); fill.setAttribute("x", "0"); fill.setAttribute("y", "1"); fill.setAttribute("width", initW.toFixed(1)); fill.setAttribute("height", "7"); fill.setAttribute("rx", "3.5"); fill.setAttribute("class", isUp ? "bar-fill-up" : "bar-fill-down"); svg.appendChild(fill); appState.animatedBarRects.push({ rect: fill, targetW }); } return svg; } function createEmptyBarRow(isUp) { const row = document.createElement("div"); row.className = "bar-row empty-slot"; row.setAttribute("aria-hidden", "true"); const sym = document.createElement("span"); sym.className = "bar-sym empty"; sym.textContent = "—"; const locBadge = document.createElement("span"); locBadge.className = "bar-loc-pill empty"; locBadge.textContent = "···"; const role = document.createElement("span"); role.className = "bar-role"; const ph = document.createElement("span"); ph.className = "bar-role-placeholder"; role.appendChild(ph); const barSvg = buildCleanBarSvg(0, isUp, true); const delta = document.createElement("span"); delta.className = "bar-delta empty"; delta.textContent = "—"; row.appendChild(sym); row.appendChild(locBadge); row.appendChild(role); row.appendChild(barSvg); row.appendChild(delta); return row; } function createBarRow(g, isUp) { const btn = document.createElement("button"); btn.type = "button"; btn.className = "bar-row" + (appState.hoveredGeneSym === g.sym || appState.selectedGeneSym === g.sym ? " focused" : ""); const sym = document.createElement("span"); sym.className = "bar-sym"; sym.textContent = g.sym; const locBadge = document.createElement("span"); locBadge.className = "bar-loc-pill"; locBadge.textContent = formatLocShort(g.loc); const role = document.createElement("span"); role.className = "bar-role"; role.textContent = g.nick; const lfcNum = Number(g.lfc || g.residual || 0); const foldFactor = Math.exp(Math.abs(lfcNum)); // Smooth magnified regulated-shift ruler matching the top radial sunburst: const frac = Math.min(0.99, computeSunburstSpanPx(foldFactor, 100.0) / 100.0); const barSvg = buildCleanBarSvg(frac, isUp, false); const delta = document.createElement("span"); delta.className = "bar-delta " + (isUp ? "up" : "down"); const mainVal = document.createElement("span"); mainVal.textContent = formatLinearShiftLabel(lfcNum, isUp); const subVal = document.createElement("span"); subVal.className = "bar-delta-sub"; subVal.textContent = "(" + (lfcNum >= 0 ? "+" : "−") + Math.abs(lfcNum).toFixed(2) + ")"; delta.appendChild(mainVal); delta.appendChild(subVal); btn.appendChild(sym); btn.appendChild(locBadge); btn.appendChild(role); btn.appendChild(barSvg); btn.appendChild(delta); btn.addEventListener("mouseenter", () => { appState.hoveredGeneSym = g.sym; }); btn.addEventListener("mouseleave", () => { appState.hoveredGeneSym = ""; }); btn.addEventListener("click", () => { appState.selectedGeneSym = appState.selectedGeneSym === g.sym ? "" : g.sym; if (appState.currentResult) renderBottomOutcome(appState.currentResult); }); return btn; } function getActiveCellLineLabel() { return appState.dataset === "tahoe" ? "A549 Lung Carcinoma · Single Cell #" + appState.cellIdx : "K562 Chronic Myeloid Leukemia · Single Cell #" + appState.cellIdx; } function renderEmptyBottomOutcome(headlineText, isSimulating) { const hl = document.getElementById("verdict-headline"); hl.textContent = headlineText; hl.classList.toggle("muted-state", !isSimulating); document.getElementById("verdict-sub").textContent = getActiveCellLineLabel(); const upPill = document.getElementById("count-up-pill"); const dnPill = document.getElementById("count-down-pill"); upPill.textContent = "↑ — UP"; dnPill.textContent = "↓ — DOWN"; upPill.classList.add("pill-stat-muted"); dnPill.classList.add("pill-stat-muted"); const upList = document.getElementById("bars-up-list"); const dnList = document.getElementById("bars-down-list"); clearChildren(upList); clearChildren(dnList); appState.animatedBarRects = []; for (let i = 0; i < 5; i++) { upList.appendChild(createEmptyBarRow(true)); dnList.appendChild(createEmptyBarRow(false)); } } function renderBottomOutcome(res) { const hl = document.getElementById("verdict-headline"); hl.textContent = res.verdict && res.verdict.headline ? res.verdict.headline : "Predicted Single-Cell Gene Shifts"; hl.classList.remove("muted-state"); document.getElementById("verdict-sub").textContent = res.cell_line + " · Single Cell #" + res.cell_idx; const upPill = document.getElementById("count-up-pill"); const dnPill = document.getElementById("count-down-pill"); upPill.textContent = "↑ " + res.count_up + " UP"; dnPill.textContent = "↓ " + res.count_down + " DOWN"; upPill.classList.remove("pill-stat-muted"); dnPill.classList.remove("pill-stat-muted"); const upList = document.getElementById("bars-up-list"); const dnList = document.getElementById("bars-down-list"); clearChildren(upList); clearChildren(dnList); appState.animatedBarRects = []; const topUp = getUnifiedPolarityGenes(res, true).slice(0, 5); const topDn = getUnifiedPolarityGenes(res, false).slice(0, 5); for (let i = 0; i < 5; i++) { if (i < topUp.length) upList.appendChild(createBarRow(topUp[i], true)); else upList.appendChild(createEmptyBarRow(true)); if (i < topDn.length) dnList.appendChild(createBarRow(topDn[i], false)); else dnList.appendChild(createEmptyBarRow(false)); } } // ========================================================================= // 9. Theme Toggle, Presets, State Machine, & Live Model Execution // ========================================================================= function setTheme(nextTheme) { appState.theme = nextTheme === "light" ? "light" : "dark"; const rootEl = document.documentElement; if (rootEl && rootEl.classList) { rootEl.classList.add("theme-switching"); rootEl.classList.toggle("theme-dark", appState.theme === "dark"); rootEl.classList.toggle("theme-light", appState.theme === "light"); } if (document.body && document.body.classList) { document.body.classList.toggle("theme-dark", appState.theme === "dark"); document.body.classList.toggle("theme-light", appState.theme === "light"); } const lbl = document.getElementById("theme-toggle-label"); if (lbl) { lbl.textContent = appState.theme === "dark" ? "Light" : "Dark"; } if (rootEl && rootEl.classList) { void rootEl.offsetHeight; rootEl.classList.remove("theme-switching"); } } function showError(msg) { const el = document.getElementById("error-banner"); if (!el) return; if (!msg) { el.textContent = ""; el.classList.add("hidden"); } else { el.textContent = msg; el.classList.remove("hidden"); } } function hasParentZeroGpuBridge() { try { return Boolean( window.parent && window.parent !== window && typeof window.parent.__triggerCellGemmaZeroGPU === "function" ); } catch (_e) { return false; } } function formatTemperatureReadout(tempVal) { return tempVal <= 0.01 ? "0.0 (Deterministic)" : tempVal.toFixed(1) + " (Sampled)"; } function closePromptModal() { const bd = document.getElementById("prompt-modal-backdrop"); if (bd) bd.classList.add("hidden"); } function openPromptModal() { const bd = document.getElementById("prompt-modal-backdrop"); if (!bd) return; const res = appState.currentResult; const metaEl = document.getElementById("prompt-modal-meta"); if (metaEl) { const cellPart = res ? res.cell_line + " · Single Cell #" + res.cell_idx : getActiveCellLineLabel(); const tempPart = appState.temperature <= 0.01 ? "Temp 0.0 (Greedy)" : "Temp " + appState.temperature.toFixed(1); const tokPart = appState.lastPromptTokens ? " · " + appState.lastPromptTokens + " prompt tokens" : ""; metaEl.textContent = cellPart + " · " + tempPart + tokPart; } const inBox = document.getElementById("prompt-modal-input"); if (inBox) { inBox.textContent = appState.lastPrompt || "(Stage 1 prompt not captured for this run)"; } const outBox = document.getElementById("prompt-modal-output"); if (outBox) { outBox.textContent = appState.lastRawText || "(No regulated residual tokens emitted)"; } bd.classList.remove("hidden"); } function escapeCsvCell(val, isNumeric) { const str = String(val == null ? "" : val); if (isNumeric) return str; // Prevent spreadsheet formula injection while preserving RFC-4180 quoting const safe = /^[=+\-@\t\r]/.test(str) ? "'" + str : str; if (/[",\r\n]/.test(safe)) { return '"' + safe.replace(/"/g, '""') + '"'; } return safe; } function downloadPredictionsCsv() { const res = appState.currentResult; if (!res) return; const allRows = Array.isArray(res.all_genes) && res.all_genes.length ? res.all_genes : getUnifiedPolarityGenes(res, true).concat(getUnifiedPolarityGenes(res, false)); if (!allRows.length) return; const lines = [ "gene,direction,compartment,description,untreated_log_expr,global_mean_log_expr,predicted_log_expr,delta_log_expr,pct_change,fold_change", ]; for (const g of allRows) { const isUp = String(g.sym || "").startsWith("+"); const lfcNum = Number(g.lfc != null ? g.lfc : g.residual || 0); const foldNum = Math.exp(lfcNum); const pctNum = (foldNum - 1.0) * 100.0; const baseVal = Number(g.base_expr != null ? g.base_expr : g.mean_expr || 0); const row = [ escapeCsvCell(g.gene || String(g.sym || "").replace(/^[+-]/, ""), false), escapeCsvCell(isUp ? "UP" : "DOWN", false), escapeCsvCell(g.loc || "cytoplasm", false), escapeCsvCell(g.nick || "", false), escapeCsvCell(Number(g.ctrl_expr || 0).toFixed(4), true), escapeCsvCell(baseVal.toFixed(4), true), escapeCsvCell(Number(g.pred_expr || 0).toFixed(4), true), escapeCsvCell(lfcNum.toFixed(4), true), escapeCsvCell(pctNum.toFixed(2), true), escapeCsvCell(foldNum.toFixed(4), true), ]; lines.push(row.join(",")); } const csvBlob = new Blob([lines.join("\n") + "\n"], { type: "text/csv;charset=utf-8" }); const url = URL.createObjectURL(csvBlob); const pertSlug = (appState.mode === "drug" ? appState.drugName : "crispr_" + appState.gene) .toLowerCase() .replace(/[^a-z0-9]+/g, "_") .replace(/^_+|_+$/g, ""); const fname = "cellgemma_" + (appState.dataset === "tahoe" ? "a549" : "k562") + "_cell" + appState.cellIdx + "_" + (pertSlug || "perturbation") + ".csv"; const link = document.createElement("a"); link.href = url; link.download = fname; document.body.appendChild(link); link.click(); document.body.removeChild(link); setTimeout(() => URL.revokeObjectURL(url), 1000); } function resetToBeforeState() { appState.activeZeroGpuRunId += 1; if (appState.activeAbort) { appState.activeAbort.abort(); appState.activeAbort = null; } if (appState.stageMode === "running" && hasParentZeroGpuBridge()) { try { if (typeof window.parent.__cancelCellGemmaZeroGPU === "function") { window.parent.__cancelCellGemmaZeroGPU(); } } catch (_e) { // Ignore cross-frame cancellation errors } } closePromptModal(); appState.stageMode = "before"; appState.runPhase = "idle"; appState.liveGeneCount = 0; appState.inParticles = []; appState.outParticles = []; appState.renderedOrbs = []; appState.animatedBarRects = []; appState.currentResult = null; appState.lastPrompt = ""; appState.lastRawText = ""; appState.lastPromptTokens = 0; appState.revealProgress = 0; appState.barAnimProgress = 0; appState.hoveredGeneSym = ""; appState.selectedGeneSym = ""; syncUI(); } function syncUI() { const resetBtn = document.getElementById("reset-btn"); if (resetBtn) { resetBtn.classList.toggle( "can-reset", appState.stageMode !== "before" || Boolean(appState.currentResult) ); } const runBtn = document.getElementById("run-btn"); runBtn.disabled = appState.stageMode === "running"; runBtn.textContent = appState.stageMode === "running" ? "Simulating…" : "▶ Run CellGemma"; const promptBtn = document.getElementById("view-prompt-btn"); if (promptBtn) { const canShowPrompt = appState.stageMode === "after" && Boolean(appState.currentResult) && Boolean(appState.lastPrompt || appState.lastRawText); promptBtn.classList.toggle("hidden", !canShowPrompt); } const csvBtn = document.getElementById("download-csv-btn"); if (csvBtn) { const canShowCsv = appState.stageMode === "after" && Boolean(appState.currentResult); csvBtn.classList.toggle("hidden", !canShowCsv); } if (appState.stageMode === "before") { renderEmptyBottomOutcome("Awaiting Simulation — Click ▶ Run CellGemma", false); } else if (appState.stageMode === "running") { if (appState.currentResult) { renderBottomOutcome(appState.currentResult); } else { renderEmptyBottomOutcome( appState.statusText || "CellGemma E4B is predicting single-cell transcriptional shifts…", true ); } } else if (appState.currentResult) { renderBottomOutcome(appState.currentResult); } } function renderPresetPills() { const drugWrap = document.getElementById("drug-preset-pills"); const crisprWrap = document.getElementById("crispr-preset-pills"); clearChildren(drugWrap); clearChildren(crisprWrap); for (const p of appState.presets) { const btn = document.createElement("button"); btn.type = "button"; btn.className = "preset-pill" + (appState.activePresetId === p.id ? " active" : ""); btn.textContent = p.name; btn.addEventListener("click", () => applyPreset(p)); if (p.kind === "drug") drugWrap.appendChild(btn); else crisprWrap.appendChild(btn); } } function renderFeaturedGeneChips() { const wrap = document.getElementById("featured-gene-chips"); clearChildren(wrap); for (const sym of appState.featuredGenes) { const chip = document.createElement("button"); chip.type = "button"; chip.className = "pop-gene-chip" + (appState.gene === sym ? " active" : ""); chip.textContent = sym; chip.addEventListener("click", async () => { showError(""); resetToBeforeState(); appState.mode = "crispr"; appState.dataset = "k562"; appState.gene = sym; const m = appState.presets.find((p) => p.kind === "crispr" && p.gene === sym); appState.activePresetId = m ? m.id : ""; document.getElementById("gene-input").value = sym; syncPopoverTabs(); renderPresetPills(); renderFeaturedGeneChips(); await fetchGeneGraph3D(sym); syncUI(); }); wrap.appendChild(chip); } } function syncPopoverTabs() { const isDrug = appState.mode === "drug"; document.getElementById("pop-tab-drug").classList.toggle("active", isDrug); document.getElementById("pop-tab-crispr").classList.toggle("active", !isDrug); document.getElementById("pop-drug-fields").classList.toggle("hidden", !isDrug); document.getElementById("pop-crispr-fields").classList.toggle("hidden", isDrug); } async function applyPreset(preset) { showError(""); resetToBeforeState(); appState.activePresetId = preset.id; appState.mode = preset.kind; appState.dataset = preset.dataset; appState.cellIdx = preset.cell_idx || 0; document.getElementById("cell-idx-slider").value = String(appState.cellIdx); document.getElementById("cell-idx-readout").textContent = "Cell #" + appState.cellIdx; if (preset.kind === "drug") { appState.drugName = preset.name; appState.smiles = preset.smiles; appState.concentrationUm = preset.concentration_um || 0.5; document.getElementById("smiles-input").value = appState.smiles; document.getElementById("dose-slider").value = String(appState.concentrationUm); document.getElementById("dose-readout").textContent = appState.concentrationUm.toFixed(2) + " µM"; } else { appState.gene = preset.gene; document.getElementById("gene-input").value = appState.gene; } syncPopoverTabs(); renderPresetPills(); renderFeaturedGeneChips(); if (preset.kind === "drug") { await fetchMolecule3D(appState.smiles); } else { await fetchGeneGraph3D(appState.gene); } syncUI(); } async function fetchMolecule3D(smilesStr) { try { const resp = await fetch("/api/molecule?smiles=" + encodeURIComponent(smilesStr)); if (!resp.ok) { showError("Invalid SMILES formula."); return; } showError(""); const data = await resp.json(); appState.inputViz = data; const metaEl = document.getElementById("mol-meta-readout"); if (metaEl && data.num_atoms && data.mol_weight) { metaEl.textContent = data.num_atoms + " atoms · " + data.mol_weight + " Da"; } } catch (_e) { showError("Could not parse chemical structure."); } } async function fetchGeneGraph3D(geneSym) { try { const resp = await fetch("/api/gene_graph?gene=" + encodeURIComponent(geneSym)); if (!resp.ok) { showError("Unknown human gene symbol."); return; } showError(""); const data = await resp.json(); appState.inputViz = data; document.getElementById("kg-edge-readout").textContent = data.total_edges + " STRING links"; } catch (_e) { showError("Could not load gene target."); } } function handleStreamEventObject(ev) { if (!ev || typeof ev !== "object") return; if (ev.type === "error") { appState.stageMode = "before"; appState.runPhase = "idle"; appState.liveGeneCount = 0; appState.inParticles = []; appState.outParticles = []; showError(ev.message || "Prediction interrupted — please try clicking Run CellGemma again."); syncUI(); return; } if (ev.input_viz) appState.inputViz = ev.input_viz; if (ev.type === "heartbeat" || ev.type === "started") { if (ev.phase) appState.runPhase = ev.phase; appState.statusText = ev.message || "Running CellGemma E4B…"; syncUI(); } else if (ev.type === "partial") { appState.runPhase = "streaming_genes"; appState.liveGeneCount = Number(ev.gene_count || 0); appState.currentResult = ev.state; syncUI(); } else if (ev.type === "complete") { appState.stageMode = "after"; appState.runPhase = "complete"; appState.inParticles = []; appState.outParticles = []; appState.elapsedSeconds = ev.elapsed_s || (performance.now() - appState.runStartedAtMs) / 1000; appState.currentResult = ev.state; appState.lastPrompt = ev.prompt || (ev.state && ev.state.prompt) || ""; appState.lastRawText = ev.raw_text || (ev.state && ev.state.raw_text) || ""; appState.lastPromptTokens = Number( ev.prompt_tokens || (ev.state && ev.state.prompt_tokens) || 0 ); syncUI(); } } function buildRequestPayload() { return { dataset: appState.dataset, cell_idx: appState.cellIdx, kind: appState.mode, drug_name: appState.drugName || "Custom Compound", smiles: appState.mode === "drug" ? appState.smiles : "", concentration_um: appState.concentrationUm, gene: appState.mode === "crispr" ? appState.gene : "", max_new_tokens: 180, temperature: appState.temperature, }; } async function startLiveRun() { if (appState.stageMode === "running") return; showError(""); appState.stageMode = "running"; appState.runPhase = "encoding_cell"; appState.liveGeneCount = 0; appState.runStartedAtMs = performance.now(); appState.currentResult = null; appState.revealProgress = 0.05; appState.barAnimProgress = 0.05; appState.statusText = "Acquiring GPU & encoding single cell…"; syncUI(); const payload = buildRequestPayload(); // Primary ZeroGPU path via parent Gradio Blocks event bridge if (hasParentZeroGpuBridge()) { const runId = ++appState.activeZeroGpuRunId; window.__onZeroGpuStream = (rawJsonStr) => { if (runId !== appState.activeZeroGpuRunId || appState.stageMode !== "running") return; try { handleStreamEventObject(JSON.parse(rawJsonStr)); } catch (_e) { // Ignore malformed chunk } }; window.__onZeroGpuDone = (_lastVal) => { if (runId !== appState.activeZeroGpuRunId) return; if (appState.stageMode === "running") { appState.stageMode = "before"; appState.runPhase = "idle"; appState.liveGeneCount = 0; appState.inParticles = []; appState.outParticles = []; showError("GPU queue busy or quota reached — please try again shortly."); syncUI(); } }; const dispatched = window.parent.__triggerCellGemmaZeroGPU(JSON.stringify(payload)); if (dispatched) return; } // Fallback direct NDJSON streaming path when opened outside the Gradio wrapper const ctrl = new AbortController(); appState.activeAbort = ctrl; try { const resp = await fetch("/api/predict_stream", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRF-Token": appState.csrfToken, }, body: JSON.stringify(payload), signal: ctrl.signal, }); if (!resp.ok || !resp.body) throw new Error("Request rejected"); const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buf = ""; while (true) { const { value, done } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); const lines = buf.split("\n"); buf = lines.pop() || ""; for (const ln of lines) { if (!ln.trim()) continue; handleStreamEventObject(JSON.parse(ln)); } } } catch (err) { if (err && err.name === "AbortError") return; appState.stageMode = "before"; appState.runPhase = "idle"; appState.liveGeneCount = 0; appState.inParticles = []; appState.outParticles = []; showError("Prediction interrupted — please try clicking Run CellGemma again."); syncUI(); } finally { appState.activeAbort = null; } } // ========================================================================= // 10. Event Listeners & Interactive Canvas Inspector // ========================================================================= function bindEvents() { const themeBtn = document.getElementById("theme-toggle-btn"); if (themeBtn) { themeBtn.addEventListener("click", () => { setTheme(appState.theme === "dark" ? "light" : "dark"); }); } const onById = (id, evName, handler) => { const el = document.getElementById(id); if (el) el.addEventListener(evName, handler); }; const custBtn = document.getElementById("customize-btn"); const pop = document.getElementById("customize-popover"); const closePop = () => { if (pop) pop.classList.add("hidden"); if (custBtn) { custBtn.classList.remove("open"); custBtn.setAttribute("aria-expanded", "false"); } }; if (custBtn && pop) { custBtn.addEventListener("click", () => { const opening = pop.classList.contains("hidden"); pop.classList.toggle("hidden", !opening); custBtn.classList.toggle("open", opening); custBtn.setAttribute("aria-expanded", String(opening)); }); } onById("popover-close-btn", "click", closePop); onById("pop-tab-drug", "click", () => { const p = appState.presets.find((x) => x.kind === "drug"); if (p) applyPreset(p); }); onById("pop-tab-crispr", "click", () => { const p = appState.presets.find((x) => x.kind === "crispr"); if (p) applyPreset(p); }); const resetBtn = document.getElementById("reset-btn"); if (resetBtn) { resetBtn.addEventListener("click", () => { closePop(); showError(""); appState.molRot.yaw = 0.54; appState.molRot.pitch = 0.28; resetToBeforeState(); }); } onById("run-btn", "click", () => { closePop(); startLiveRun(); }); let smiTimer = null; onById("smiles-input", "input", (e) => { const val = e.target.value.trim(); resetToBeforeState(); appState.activePresetId = ""; appState.drugName = "Custom Molecule"; appState.smiles = val; renderPresetPills(); syncUI(); if (smiTimer) clearTimeout(smiTimer); smiTimer = setTimeout(() => { if (val) fetchMolecule3D(val); }, 280); }); onById("dose-slider", "input", (e) => { resetToBeforeState(); appState.concentrationUm = parseFloat(e.target.value) || 0.5; const dr = document.getElementById("dose-readout"); if (dr) dr.textContent = appState.concentrationUm.toFixed(2) + " µM"; syncUI(); }); let geneTimer = null; onById("gene-input", "input", (e) => { const sym = e.target.value.trim().toUpperCase(); resetToBeforeState(); appState.gene = sym; const m = appState.presets.find((p) => p.kind === "crispr" && p.gene === sym); appState.activePresetId = m ? m.id : ""; renderPresetPills(); renderFeaturedGeneChips(); syncUI(); if (geneTimer) clearTimeout(geneTimer); geneTimer = setTimeout(() => { if (sym.length >= 2) fetchGeneGraph3D(sym); }, 260); }); onById("cell-idx-slider", "input", (e) => { resetToBeforeState(); appState.cellIdx = parseInt(e.target.value, 10) || 0; const cr = document.getElementById("cell-idx-readout"); if (cr) cr.textContent = "Cell #" + appState.cellIdx; syncUI(); }); const tempSlider = document.getElementById("temp-slider"); if (tempSlider) { tempSlider.addEventListener("input", (e) => { const val = Math.max(0, Math.min(1.0, parseFloat(e.target.value) || 0)); appState.temperature = val; const tempReadout = document.getElementById("temp-readout"); if (tempReadout) tempReadout.textContent = formatTemperatureReadout(val); }); } const promptBtn = document.getElementById("view-prompt-btn"); if (promptBtn) { promptBtn.addEventListener("click", openPromptModal); } const csvBtn = document.getElementById("download-csv-btn"); if (csvBtn) { csvBtn.addEventListener("click", downloadPredictionsCsv); } const closeModalBtn = document.getElementById("close-prompt-modal-btn"); if (closeModalBtn) { closeModalBtn.addEventListener("click", closePromptModal); } const modalBackdrop = document.getElementById("prompt-modal-backdrop"); if (modalBackdrop) { modalBackdrop.addEventListener("click", (e) => { if (e.target === modalBackdrop) closePromptModal(); }); } const copyPromptBtn = document.getElementById("copy-prompt-btn"); if (copyPromptBtn) { copyPromptBtn.addEventListener("click", async () => { const textToCopy = appState.lastPrompt || ""; if (!textToCopy || !navigator.clipboard) return; try { await navigator.clipboard.writeText(textToCopy); copyPromptBtn.textContent = "Copied ✓"; setTimeout(() => { copyPromptBtn.textContent = "Copy Prompt"; }, 1400); } catch (_e) { // Clipboard permission declined } }); } document.addEventListener("keydown", (e) => { if (e.key === "Escape") closePromptModal(); }); const attachSpin = (el) => { el.addEventListener("pointerdown", (e) => { appState.molRot.dragging = true; appState.molRot.lastX = e.clientX; appState.molRot.lastY = e.clientY; el.setPointerCapture(e.pointerId); }); el.addEventListener("pointermove", (e) => { if (!appState.molRot.dragging) return; const dx = e.clientX - appState.molRot.lastX; const dy = e.clientY - appState.molRot.lastY; appState.molRot.lastX = e.clientX; appState.molRot.lastY = e.clientY; appState.molRot.yaw += dx * 0.014; appState.molRot.pitch = Math.max(-1.2, Math.min(1.2, appState.molRot.pitch + dy * 0.014)); }); el.addEventListener("pointerup", () => { appState.molRot.dragging = false; }); }; attachSpin(document.getElementById("mini-mol-box")); const pointToSegDist = (px, py, ax, ay, bx, by) => { const vx = bx - ax; const vy = by - ay; const lenSq = vx * vx + vy * vy; if (lenSq < 1e-4) return Math.hypot(px - ax, py - ay); const t = Math.max(0, Math.min(1, ((px - ax) * vx + (py - ay) * vy) / lenSq)); return Math.hypot(px - (ax + t * vx), py - (ay + t * vy)); }; const hitTestRenderedGene = (mx, my) => { let hit = null; let best = 999; for (const o of appState.renderedOrbs) { if ( o.calloutBox && mx >= o.calloutBox.x && mx <= o.calloutBox.x + o.calloutBox.w && my >= o.calloutBox.y && my <= o.calloutBox.y + o.calloutBox.h ) { return o; } const dPin = Math.hypot(mx - o.x, my - o.y); if (dPin <= 10.5 && dPin < best) { best = dPin; hit = o; } const dBar = pointToSegDist(mx, my, o.barStartX, o.barStartY, o.barEndX, o.barEndY); if (dBar <= 9.0 && dBar < best) { best = dBar; hit = o; } } return hit; }; const heroWrap = document.getElementById("hero-canvas-wrap"); heroWrap.addEventListener("pointerdown", (e) => { const rect = heroWrap.getBoundingClientRect(); const mx = e.clientX - rect.left; const my = e.clientY - rect.top; if (mx < rect.width * 0.34 && my < rect.height * 0.62) { appState.molRot.dragging = true; appState.molRot.lastX = e.clientX; appState.molRot.lastY = e.clientY; heroWrap.setPointerCapture(e.pointerId); } }); heroWrap.addEventListener("pointermove", (e) => { if (appState.molRot.dragging) { const dx = e.clientX - appState.molRot.lastX; const dy = e.clientY - appState.molRot.lastY; appState.molRot.lastX = e.clientX; appState.molRot.lastY = e.clientY; appState.molRot.yaw += dx * 0.014; appState.molRot.pitch = Math.max(-1.2, Math.min(1.2, appState.molRot.pitch + dy * 0.014)); return; } const rect = heroWrap.getBoundingClientRect(); const mx = e.clientX - rect.left; const my = e.clientY - rect.top; const hit = hitTestRenderedGene(mx, my); const nextSym = hit ? hit.sym : ""; if (nextSym !== appState.hoveredGeneSym) { appState.hoveredGeneSym = nextSym; if (appState.currentResult) renderBottomOutcome(appState.currentResult); } }); heroWrap.addEventListener("pointerup", (e) => { appState.molRot.dragging = false; const rect = heroWrap.getBoundingClientRect(); const mx = e.clientX - rect.left; const my = e.clientY - rect.top; const hit = hitTestRenderedGene(mx, my); if (hit) { appState.selectedGeneSym = appState.selectedGeneSym === hit.sym ? "" : hit.sym; if (appState.currentResult) renderBottomOutcome(appState.currentResult); } }); } async function bootstrap() { setTheme("dark"); bindEvents(); try { const resp = await fetch("/api/bootstrap"); if (!resp.ok) throw new Error("Bootstrap failed"); const data = await resp.json(); appState.csrfToken = data.csrf_token || ""; appState.device = data.device || "cpu"; appState.dtype = data.dtype || "float32"; appState.presets = data.presets || []; appState.featuredGenes = data.featured_genes || []; appState.baselineCells = data.baseline_cells || {}; if (appState.presets.length) { await applyPreset(appState.presets[0]); } } catch (_e) { showError("Could not connect to CellGemma backend."); } function frame(nowMs) { renderHeroStage(nowMs); requestAnimationFrame(frame); } requestAnimationFrame(frame); } window.__CELLGEMMA_INSPECT__ = { getTheme: () => appState.theme, setTheme: (t) => setTheme(t), getStageMode: () => appState.stageMode, getCellAnimPhase: () => appState.cellAnimPhase, isTransmitting: () => isTransmitting(), injectStreamEvent: (ev) => { handleStreamEventObject(ev); appState.revealProgress = 1.0; appState.barAnimProgress = 1.0; }, getCounts: () => ({ inputPulses: appState.inParticles.length, outputPulses: appState.outParticles.length, projectedOrbs: appState.renderedOrbs.length, upKnobs: appState.currentResult ? (appState.currentResult.top_up || []).length : 0, downKnobs: appState.currentResult ? (appState.currentResult.top_down || []).length : 0, }), getOrbRadiiByMagnitude: () => appState.renderedOrbs.map((o) => ({ sym: o.sym, absRes: o.absMag, rad3D: Number(o.targetR.toFixed(3)), })), }; if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", bootstrap); } else { bootstrap(); } })();