optorigbench-tools / app /static /bench.html
imaan3's picture
Bench: loosen rate limits; fix T1 heading spacing
56ba4d7
Raw History Blame Contribute Delete
41.6 kB
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>T1 culture bench</title>
<link rel="stylesheet" href="static/elmdin.css">
<style>
/* Layout: an instrument bench, in Elmdin's look (static/elmdin.css). The camera and its traces on the left; the
agent's controls beside them; the truth drawer below, set apart in its own tint. */
:root {
/* the bench's own names, mapped onto Elmdin's tokens */
--panel: var(--bg2); --fg: var(--ink); --chip: var(--bg3); --ink-on-accent: var(--on-accent);
--gfp: var(--live); --truth: var(--lav); --truth-bg: var(--lav-wash); --warn: var(--sand); --bad: var(--fail);
}
[hidden] { display: none !important }
body { padding: 0 0 48px }
.wrap { max-width: 1320px; margin: 0 auto; padding: 0 var(--gut); display: grid; gap: 20px; min-width: 0 }
header.head { display: grid; gap: 4px; padding-top: 28px; min-width: 0 }
header.head h1 { margin: 0 0 6px }
header.head .intro { margin: 0; color: var(--ink2); max-width: 78ch }
.back { font: 400 12.5px var(--mono); color: var(--muted); text-decoration: none; margin-bottom: 10px; justify-self: start }
.back:hover { color: var(--ink); text-decoration: underline }
.pills { display: flex; flex-wrap: wrap; gap: 6px; font: 500 12px/1.7 var(--mono); margin-top: 10px }
.pill { border: 1px solid var(--line); color: var(--ink2); padding: 1px 9px; font-variant-numeric: tabular-nums; white-space: nowrap }
.pill.rec { color: var(--fail); border-color: color-mix(in srgb, var(--fail) 45%, transparent); background: var(--fail-wash) }
.pill.warn { color: var(--sand); border-color: color-mix(in srgb, var(--sand) 45%, transparent); background: var(--sand-wash) }
.bench { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(0, 1fr); gap: 20px; align-items: start }
@media (max-width: 900px) { .bench { grid-template-columns: minmax(0, 1fr) } }
.scope { display: grid; gap: 12px; min-width: 0 }
.view { position: relative; background: #000; overflow: hidden; aspect-ratio: 4 / 3; max-width: 100%; cursor: crosshair; border: 1px solid var(--line) }
.view canvas { position: absolute; inset: 0; width: 100%; height: 100% }
#loading { position: absolute; inset: 0; display: grid; place-content: center; gap: 6px; text-align: center; color: #CFCFCF;
font: 13px var(--mono); padding: 16px }
#loading b { font: 700 17px var(--display); color: #F4F4F4 }
.viewbar { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; font-size: 14px }
.viewbar label { display: inline-flex; gap: 6px; align-items: center; color: var(--ink2) }
.legend { display: flex; flex-wrap: wrap; gap: 4px 14px; font: 12px var(--mono); color: var(--muted) }
.sw { display: inline-block; width: 10px; height: 10px; vertical-align: -1px; margin-right: 4px; border: 2px solid currentColor }
.panel { background: var(--panel); border: 1px solid var(--line); padding: 18px; display: grid; gap: 14px; min-width: 0 }
h2.sec { font: 700 17px/1.4 var(--display); letter-spacing: -.012em; color: var(--ink); margin: 0 }
h1 .tk { letter-spacing: .04em } /* the heading's tight tracking ran the T into the 1 */
h3 { font: 700 15px/1.4 var(--display); margin: 0 }
.truth { background: var(--truth-bg); border-color: color-mix(in srgb, var(--truth) 45%, var(--line)) }
.truth .truth-head { display: grid; gap: 2px }
.group { display: grid; gap: 10px; padding-top: 14px; border-top: 1px solid var(--line); min-width: 0 }
.group:first-of-type { border-top: 0; padding-top: 0 }
.row { display: flex; flex-wrap: wrap; gap: 8px; align-items: end }
.field input, .field select { width: 96px }
button.go { background: var(--stim); border-color: var(--stim); color: var(--on-accent) }
button.go:hover:not(:disabled) { color: var(--on-accent); border-color: var(--stim); filter: brightness(1.08) }
button.tr { background: var(--truth); border-color: var(--truth); color: var(--on-accent) }
button.tr:hover:not(:disabled) { color: var(--on-accent); border-color: var(--truth); filter: brightness(1.08) }
.hint { font-size: 13.5px; line-height: 1.6; color: var(--muted); margin: 0; max-width: 70ch }
.chart { width: 100%; height: 170px; display: block; background: var(--bg2); border: 1px solid var(--line) }
.log { font: 12px/1.5 var(--mono); max-height: 280px; overflow: auto; display: grid; gap: 6px; margin: 0; padding: 0; list-style: none }
.log li { border-left: 3px solid var(--line); padding-left: 8px; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--ink2) }
.log li.err { border-left-color: var(--fail) }
.log li b { font-weight: 500; color: var(--ink) }
.log img { display: block; max-width: 100%; margin-top: 4px }
.truthgrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 20px }
.truthgrid > .group { border: 0; padding: 0 }
.table { overflow: auto; max-height: 340px; border: 1px solid var(--line); background: var(--bg2) }
table { font: 12px var(--mono); }
th, td { padding: 5px 9px; text-align: right; white-space: nowrap }
thead th { position: sticky; top: 0; font-size: 11.5px; letter-spacing: .04em }
td:first-child, th:first-child { text-align: left }
tr.d td { color: var(--stim); font-weight: 500 } tr.s1 td { color: var(--sand) } tr.s2 td { color: var(--truth) }
.bar { display: inline-block; height: 7px; background: var(--gfp); vertical-align: 0 }
.facts { font: 12px/1.55 var(--mono); margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--ink2) }
.switches { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 160px), 1fr)); gap: 6px }
.switches label { display: flex; gap: 8px; align-items: center; background: var(--bg2); border: 1px solid var(--line); padding: 6px 9px; font-size: 14px }
</style>
</head><body>
<nav class="sitebar" aria-label="Site"><a class="brand" href="./">OptoRigBench</a><div class="sb-links"><a href="./">Tools</a><a href="bench" aria-current="page">Culture bench</a><a href="replay">Replay</a><a href="https://imaan3-optorigbench-viewer.static.hf.space/" target="_blank" rel="noopener">Run viewer &#x2197;</a></div></nav>
<div class="wrap">
<header class="head">
<div class="kicker">OptoRigBench / Tools</div>
<h1><span class="tk">T1</span> culture bench</h1>
<p class="intro">The benchmark's T1 culture simulator, running on this server: one simulator per open page, at most 3 per visitor (IP address) and 4 in all; a session ends after 15 minutes idle or 60 minutes in all. The left side acts through the agents' T1 tool calls, all of them except the room camera and Python; the purple drawer below shows and edits the truth the agent never sees.</p>
<div class="pills" id="pills" aria-live="polite"><span class="pill">loading</span></div>
</header>
<section class="bench">
<div class="scope">
<div class="view" id="view">
<canvas id="cam" width="768" height="576" aria-label="Live camera image of the culture"></canvas>
<canvas id="ovl" width="768" height="576"></canvas>
<div id="loading"><b>Starting the simulator</b><span id="loadmsg">Starting a simulator on the server</span></div>
</div>
<div class="viewbar">
<button id="run" aria-pressed="true">Pause</button>
<label>Speed <select id="speed"><option value="0.5">0.5&#xd7;</option><option value="1" selected>1&#xd7;</option><option value="2">2&#xd7;</option><option value="5">5&#xd7;</option></select></label>
<label><input type="checkbox" id="showRois" checked> Segmented cells</label>
<label>Display max <input type="number" id="vmax" value="" min="200" max="4095" step="100" placeholder="agent" style="width:70px"></label>
<label>Gamma <input type="number" id="gamma" value="" min="0.5" max="3" step="0.1" placeholder="agent" style="width:62px"></label>
</div>
<p class="hint" id="clickhint">Click a cell to stimulate it with the settings on the right. Click empty tissue to stimulate a control spot there.</p>
<h2 class="sec">Live traces (the agent's live_traces view, dF/F)</h2>
<canvas class="chart" id="live" width="900" height="170" aria-label="Live dF/F traces"></canvas>
<div class="legend" id="liveLegend"></div>
</div>
<div class="panel" id="agent">
<h2 class="sec">Agent tools</h2>
<div class="group">
<h3>Bench</h3>
<div class="row">
<button data-op="load_culture,dish">Dish on stage</button>
<button data-op="place_cover,stage">Cover on</button>
<button data-op="remove_cover,stage">Cover off</button>
<button id="lightsOff">Room lights off</button>
</div>
<div class="row">
<label class="field">Component<select id="part" style="width:190px">
<option value="microcontroller_jumper">microcontroller jumper</option><option value="trigger_cable">trigger cable</option>
<option value="camera_usb">camera USB</option><option value="hdmi_cable">HDMI cable</option>
<option value="projector_power">projector power</option><option value="led_power">LED power</option></select></label>
<button id="reseat">Reseat</button>
<button id="inspect">Ask the operator to look</button>
</div>
</div>
<div class="group">
<h3>LEDs and flood</h3>
<div class="row">
<label class="field">Red mW/mm&#xb2;<input type="number" id="ledRed" value="0" min="0" max="12" step="0.5"></label>
<label class="field">Blue mW/mm&#xb2;<input type="number" id="ledBlue" value="0.2" min="0" max="2" step="0.05"></label>
<button id="setLed">Set LEDs</button>
</div>
<div class="row">
<label class="field">Flood s<input type="number" id="floodS" value="10" min="1" max="120"></label>
<button id="flood">Record flood</button>
<label class="field">Threshold<input type="number" id="thr" value="" step="10"></label>
<button id="segment">Segment</button>
</div>
</div>
<div class="group">
<h3>Imaging and recording</h3>
<div class="row">
<label class="field">Imaging mask<select id="mask"><option value="full_field">full field</option><option value="rois">segmented cells</option><option value="off">off</option></select></label>
<button id="setMask">Set mask</button>
<button id="recStart">Start recording</button>
<button id="recStop">Stop recording</button>
<button id="capture">Capture image</button>
</div>
</div>
<div class="group">
<h3>Any other tool</h3>
<div class="row">
<label class="field">Tool<select id="anyTool" style="width:170px"></select></label>
<label class="field" style="flex:1">Arguments (JSON)<input type="text" id="anyArgs" value="{}" style="width:100%;font-family:var(--mono)"></label>
<button id="anyCall">Call</button>
</div>
<p class="hint" id="anyHint">Every T1 tool the agent has, without its turn clock or decision limits. The room camera (<code>view_rig</code>) and the <code>python</code> sandbox do not run on this hosted bench.</p>
</div>
<div class="group">
<h3>Stimulation</h3>
<div class="row">
<label class="field">Red mW/mm&#xb2;<input type="number" id="sRed" value="5" min="0" max="12" step="0.5"></label>
<label class="field">Pulse ms<input type="number" id="sPulse" value="10" min="0.1" max="1000"></label>
<label class="field">Repeats<input type="number" id="sRep" value="5" min="1" max="30"></label>
<label class="field">Interval s<input type="number" id="sInt" value="2" min="0.05" max="60" step="0.05"></label>
</div>
<div class="row">
<label class="field">Target<input type="text" id="sTarget" placeholder="cell id or control:x,y" style="width:170px"></label>
<button class="go" id="stim">Stimulate</button>
<button id="stimStop">Cancel train</button>
</div>
<p class="hint">Each pulse is one <code>stimulate</code> call with repeats 1; the train plays out as time passes.</p>
</div>
<div class="group">
<h3>Tool calls</h3>
<ul class="log" id="log"></ul>
</div>
</div>
</section>
<section class="panel truth" id="truth">
<div class="truth-head">
<h2 class="sec">Simulator truth (hidden from the agent)</h2>
<span class="hint" id="keynote"></span>
</div>
<div class="truthgrid">
<div class="group">
<h3>Culture</h3>
<div class="row">
<label class="field">Scenario<select id="scen" style="width:150px"><option>none</option></select></label>
<label class="field">Seed<input type="number" id="seed" value="200001" placeholder="random"></label>
<label class="field">Neurons<input type="number" id="ncells" value="" min="20" max="80" placeholder="task"></label>
<button class="tr" id="rebuild">New dish</button>
</div>
<p class="hint">Seeds are practice seeds (200000&#x2013;299999), never the benchmark's dev or test seeds: any other number is mapped into that range, and a blank seed picks one at random. Leave Neurons blank for T1's own count (26&#x2013;30), or choose 20 to 80. Larger dishes take longer to build, and frames slow as cells are added.</p>
<h3>Overlay</h3>
<div class="row">
<label><input type="checkbox" id="showTruth"> True cells and wiring</label>
<label><input type="checkbox" id="showFired" checked> Cells that fired on the last pulse</label>
</div>
<h3>Edit wiring</h3>
<div class="row">
<button id="editMode" aria-pressed="false">Pick A then B</button>
<label class="field">Weight<input type="number" id="wgt" value="0.6" min="0" max="1" step="0.05"></label>
<span class="hint" id="editMsg">Weight 0 removes the synapse.</span>
</div>
<h3>Faults</h3>
<div class="switches">
<label><input type="checkbox" data-fault="room_light"> Room lights on</label>
<label><input type="checkbox" data-fault="loose_wire"> Loose jumper</label>
<label><input type="checkbox" data-fault="mask_flip"> Mask flip</label>
<label><input type="checkbox" data-fault="stale_frames"> Stale frames</label>
<label><input type="checkbox" data-fault="hdmi_loose"> HDMI loose</label>
<label><input type="checkbox" data-fault="trigger_cable_loose"> Trigger cable loose</label>
<label><input type="checkbox" data-fault="usb_loose"> Camera USB loose</label>
<label><input type="checkbox" data-fault="led_power_loose"> LED power loose</label>
</div>
<p class="hint">Each switch starts or ends the fault now, with the symptoms its scenario has mid-session. A loose cable is also fixed by the agent's Reseat.</p>
</div>
<div class="group">
<h3>Last pulse (truth)</h3>
<pre class="facts" id="lastStim">No pulse yet.</pre>
<h3>Calcium (truth, &#x394;F/F units of one event)</h3>
<canvas class="chart" id="cal" width="700" height="170" aria-label="True calcium of the stimulated cell and its partners"></canvas>
<div class="legend" id="calLegend"></div>
</div>
<div class="group">
<h3>Wiring and answer key</h3>
<pre class="facts" id="keyFacts"></pre>
<div class="table"><table><thead><tr><th>A &#x2192; B</th><th>weight</th><th>P(B | spot on A)</th><th>graded</th></tr></thead><tbody id="edges"></tbody></table></div>
</div>
<div class="group">
<h3>Per-cell state</h3>
<div class="table"><table><thead><tr><th>cell</th><th>roi</th><th>opsin</th><th>fires @limits</th><th>calcium</th><th>opsin left</th></tr></thead><tbody id="cells"></tbody></table></div>
</div>
</div>
</section>
</div>
<script>
"use strict";
// The simulator runs on the server: the page posts {id, cmd, args} messages and gets {id, ok, result, frame, ms}
// replies over HTTP.
class RemoteWorker {
constructor() {
this.onmessage = null; this.onerror = null; this.sid = null; this.t0 = performance.now();
this.ready = this._start();
this.ready.catch(() => {});
addEventListener("pagehide", () => { if (this.sid) navigator.sendBeacon("api/bench/" + this.sid + "/end"); });
}
_emit(data) { if (this.onmessage) this.onmessage({ data }); else setTimeout(() => this._emit(data), 20); }
async _start() {
this._emit({ progress: "Starting a simulator on the server", s: 0 });
let r;
try { r = await fetch("api/bench/session", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }); }
catch (e) { this._emit({ fatal: "The server could not be reached: " + e.message }); throw e; }
const j = await r.json().catch(() => ({}));
if (!r.ok) { this._emit(j.busy ? { busy: j.error } : { fatal: j.error || j.detail || ("HTTP " + r.status) }); throw new Error("no session"); }
this.sid = j.sid;
this._emit({ progress: "ready", s: (performance.now() - this.t0) / 1000 });
}
postMessage({ id, cmd, args }) {
this.ready.then(async () => {
const r = await fetch("api/bench/" + this.sid + "/" + cmd, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(args || {}) });
const m = await r.json().catch(() => ({ ok: false, error: "HTTP " + r.status }));
if (r.status === 410 || m.gone) { this._emit({ gone: m.error }); return; }
if (!r.ok) { this._emit({ id, ok: false, error: m.error || m.detail || ("HTTP " + r.status) }); return; }
if (m.frame) { const b = atob(m.frame), u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); m.frame = u; }
this._emit({ id, ...m });
}).catch((e) => { if (this.sid) this._emit({ id, ok: false, error: "network: " + e.message }); });
}
}
</script>
<script>
"use strict";
const $ = (id) => document.getElementById(id);
const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
let worker, nextId = 1, waiting = new Map();
let SCEN = [], TOOLS = [];
let G = null, WIRING = null, STATUS = null, STATE = null, LIVE = null;
let faultVersion = 0, faultPending = 0; // fault switches: a step sent before a change must not undo it
let running = true, lastT = 0, lastLive = 0, stimCell = null, stimRoi = null, editA = null, editMode = false;
const stimTimes = []; // clock s of every pulse, for chart markers
const perf = { frames: 0, since: performance.now(), fps: 0, sim: 0, frame: 0 };
// One message to the worker at a time. The owner's commands go first; the animation loop sends a step only when
// nothing else is waiting.
const outbox = []; let inFlight = false;
function pump() {
if (inFlight || !outbox.length) return;
const job = outbox.shift(); inFlight = true;
const id = nextId++;
waiting.set(id, { res: (m) => { inFlight = false; job.res(m); pump(); }, rej: (e) => { inFlight = false; job.rej(e); pump(); } });
worker.postMessage({ id, cmd: job.cmd, args: job.args });
}
function send(c, a) { return new Promise((res, rej) => { outbox.push({ cmd: c, args: a, res, rej }); pump(); }); }
function cmd(c, a) { return send(c, a); }
const idle = () => !inFlight && !outbox.length;
function boot() {
const t0 = performance.now();
worker = new RemoteWorker();
worker.onmessage = (ev) => {
const m = ev.data;
if (m.progress) { $("loadmsg").textContent = m.progress === "ready" ? "Building the dish" : m.progress + "\u2026"; if (m.progress === "ready") window.__boot = { python_s: m.s }; return; }
if (m.busy) { $("loading").hidden = false; $("loading").innerHTML = "<b>The bench is busy</b><span></span>"; $("loading").lastChild.textContent = m.busy; return; }
if (m.gone) { running = false; G = null; $("loading").hidden = false; $("loading").innerHTML = "<b>Session ended</b><span></span>"; $("loading").lastChild.textContent = m.gone; return; }
if (m.fatal) { $("loading").hidden = false; $("loading").innerHTML = "<b>The simulator did not start</b><span></span>"; $("loading").lastChild.textContent = m.fatal; return; }
const w = waiting.get(m.id); if (!w) return; waiting.delete(m.id);
m.ok ? w.res(m) : w.rej(new Error(m.error));
};
worker.onerror = (e) => { $("loading").innerHTML = "<b>The worker failed</b><span></span>"; $("loading").lastChild.textContent = e.message || "unknown error"; };
cmd("scenarios", {}).then((r) => {
SCEN = r.result;
$("scen").innerHTML = SCEN.map(s => `<option value="${s.name}">${s.name}${s.held_out ? " (held out)" : ""}</option>`).join("");
$("scen").value = "none";
}).then(() => newDish(true)).then(() => { window.__boot = Object.assign(window.__boot || {}, { total_s: (performance.now() - t0) / 1000 }); });
}
async function newDish(first) {
$("loading").hidden = false; $("loadmsg").textContent = first ? "Starting a simulator on the server\u2026" : "Building the dish\u2026";
const n = $("ncells").value ? +$("ncells").value : null;
const args = { scenario: $("scen").value };
if ($("seed").value !== "") args.seed = +$("seed").value;
if (n) args.n_cells = n;
stimTimes.length = 0; stimCell = stimRoi = null; editA = null;
$("log").innerHTML = "";
try {
const r = await cmd("new", args); absorb(r.result);
if (G && G.seed != null) $("seed").value = G.seed; // the seed the server used (practice seeds only)
$("loadmsg").textContent = "Dish on the stage, flood and segmentation\u2026";
if (!TOOLS.length) {
TOOLS = (await cmd("tools", {})).result;
$("anyTool").innerHTML = TOOLS.map(t => `<option>${t}</option>`).join("");
$("anyTool").value = "get_status";
}
const p = await cmd("prepare", {}); absorb(p.result); p.result.result.forEach(logCall);
const th = await cmd("suggested_threshold", {}); if (th.result != null) $("thr").value = th.result;
for (const [name, a] of [["set_imaging_mask", { kind: "full_field" }]]) {
const q = await cmd("agent", { name, args: a }); absorb(q.result); logCall(q.result.result);
}
$("loading").hidden = true;
} catch (e) { $("loading").hidden = false; $("loading").innerHTML = "<b>Could not build the dish</b><span></span>"; $("loading").lastChild.textContent = e.message; }
}
function absorb(r) {
if (r.geometry) G = r.geometry;
if (r.wiring) { WIRING = r.wiring; renderWiring(); }
if (r.status) { STATUS = r.status; renderStatus(); }
}
async function agent(name, args) {
const r = await cmd("agent", { name, args });
absorb(r.result); logCall(r.result.result); return r.result.result;
}
function logCall(c) {
const li = document.createElement("li"); if (c.error) li.className = "err";
const b = document.createElement("b"); b.textContent = `${c.tool} \u00b7 clock ${c.clock_s.toFixed(1)} s\n`; li.appendChild(b);
li.appendChild(document.createTextNode(c.text.length > 700 ? c.text.slice(0, 700) + "\u2026" : c.text));
for (const im of c.images || []) { const img = document.createElement("img"); img.alt = im.name; img.src = "data:image/png;base64," + im.png; li.appendChild(img); }
const log = $("log"); log.prepend(li); while (log.children.length > 40) log.lastChild.remove();
}
// ------------------------------------------------------------------ animation loop
function partnersOf(cell) { return WIRING ? WIRING.edges.filter(e => e.a === cell).map(e => e.b) : []; }
// the camera's display scaling: blank fields keep the agent's own
function displayArgs() {
const d = {};
if ($("vmax").value !== "") d.vmax = +$("vmax").value;
if ($("gamma").value !== "") d.gamma = +$("gamma").value;
return d;
}
async function loop(now) {
requestAnimationFrame(loop);
if (!G || !running || !$("loading").hidden) { lastT = now; return; }
if (!idle()) return; // the time spent waiting is simulated on the next step
const dt = Math.min(0.5, Math.max(0, (now - lastT) / 1000)) * +$("speed").value;
lastT = now;
const cells = stimCell == null ? [] : [stimCell, ...partnersOf(stimCell)].slice(0, 8);
const rois = cells.map(c => G.cells[c] && G.cells[c].roi).filter(r => r != null);
const wantLive = now - lastLive > 300; // the live_traces call is the costly part of a step
if (wantLive) lastLive = now;
const fv = faultVersion;
let m;
try { m = await send("step", { dt, rois, live: wantLive, truth_cells: cells, seconds: 10, display: displayArgs() }); }
catch (e) { running = false; logCall({ tool: "step", clock_s: 0, text: e.message, error: true }); return; }
const r = m.result;
for (const c of r.calls) { logCall(c); if (!c.error) stimTimes.push(c.clock_s); }
STATUS = r.status; STATE = r.state; if (r.live) LIVE = r.live;
drawFrame(m.frame); drawOverlay(); drawLive(); drawCalcium(); renderStatus(fv === faultVersion && !faultPending); renderCells(); renderLastStim();
perf.frames++; perf.sim = m.ms.sim; perf.frame = m.ms.frame;
if (now - perf.since > 1000) { perf.fps = perf.frames * 1000 / (now - perf.since); perf.frames = 0; perf.since = now; }
window.__perf = { fps: perf.fps, sim_ms: perf.sim, frame_ms: perf.frame, pending: r.pending };
}
const camCtx = $("cam").getContext("2d"), off = document.createElement("canvas"); let offCtx = null, img = null;
function drawFrame(buf) {
const w = G.width_px, h = G.height_px;
if (!img || img.width !== w) { off.width = w; off.height = h; offCtx = off.getContext("2d"); img = offCtx.createImageData(w, h); }
const d = img.data;
for (let i = 0, j = 0; i < buf.length; i++, j += 4) { d[j] = 0; d[j + 1] = buf[i]; d[j + 2] = 0; d[j + 3] = 255; }
offCtx.putImageData(img, 0, 0);
camCtx.imageSmoothingEnabled = true; camCtx.imageSmoothingQuality = "high";
camCtx.drawImage(off, 0, 0, $("cam").width, $("cam").height);
}
const toPx = (x, y) => { const k = $("ovl").width / G.width_px; return [(x / G.um_per_px + G.width_px / 2) * k, (y / G.um_per_px + G.height_px / 2) * k]; };
const toUm = (px, py) => { const k = $("ovl").width / G.width_px; return [(px / k - G.width_px / 2) * G.um_per_px, (py / k - G.height_px / 2) * G.um_per_px]; };
const umR = (r) => r / G.um_per_px * ($("ovl").width / G.width_px);
function drawOverlay() {
const c = $("ovl").getContext("2d"), W = $("ovl").width;
c.clearRect(0, 0, W, $("ovl").height); c.font = "12px " + css("--mono"); c.lineWidth = 1.5;
if ($("showRois").checked) {
c.strokeStyle = "rgba(255,255,255,.55)"; c.fillStyle = "rgba(255,255,255,.8)";
for (const r of G.rois) { const [x, y] = toPx(r.x_um, r.y_um); c.beginPath(); c.arc(x, y, umR(r.radius_um) + 3, 0, 7); c.stroke(); c.fillText(r.id, x + umR(r.radius_um) + 4, y - 4); }
}
if ($("showTruth").checked) {
for (const e of WIRING.edges) {
const a = G.cells[e.a], b = G.cells[e.b]; const [x1, y1] = toPx(a.x_um, a.y_um), [x2, y2] = toPx(b.x_um, b.y_um);
c.strokeStyle = e.graded ? "rgba(190,160,255,.95)" : "rgba(190,160,255,.55)"; c.setLineDash(e.graded ? [] : [5, 4]); c.lineWidth = 1 + 2.5 * e.w;
const ang = Math.atan2(y2 - y1, x2 - x1), rb = umR(b.radius_um) + 4, ra = umR(a.radius_um) + 4;
const sx = x1 + Math.cos(ang) * ra, sy = y1 + Math.sin(ang) * ra, ex = x2 - Math.cos(ang) * rb, ey = y2 - Math.sin(ang) * rb;
c.beginPath(); c.moveTo(sx, sy); c.lineTo(ex, ey); c.stroke(); c.setLineDash([]);
c.beginPath(); c.moveTo(ex, ey); c.lineTo(ex - 10 * Math.cos(ang - .4), ey - 10 * Math.sin(ang - .4)); c.lineTo(ex - 10 * Math.cos(ang + .4), ey - 10 * Math.sin(ang + .4)); c.closePath(); c.fillStyle = c.strokeStyle; c.fill();
}
c.lineWidth = 1.5;
for (const cell of G.cells) {
const [x, y] = toPx(cell.x_um, cell.y_um); c.strokeStyle = cell.opsin ? "rgba(255,180,90,.9)" : "rgba(160,160,170,.8)";
c.setLineDash(cell.opsin ? [] : [3, 3]); c.beginPath(); c.arc(x, y, umR(cell.radius_um) + 1, 0, 7); c.stroke(); c.setLineDash([]);
c.fillStyle = "rgba(220,200,255,.95)"; c.fillText("c" + cell.id, x - umR(cell.radius_um) - 22, y + umR(cell.radius_um) + 12);
}
}
if (editA != null) { const a = G.cells[editA]; const [x, y] = toPx(a.x_um, a.y_um); c.strokeStyle = "#c9b6ff"; c.lineWidth = 3; c.beginPath(); c.arc(x, y, umR(a.radius_um) + 7, 0, 7); c.stroke(); c.lineWidth = 1.5; }
const s = STATE && STATE.last_stim;
if (s) {
const age = STATE.clock_s - s.t_light;
if (age < 2.5) {
const fade = Math.max(0, 1 - age / 2.5);
const [ax, ay] = toPx(s.aim[0], s.aim[1]), [lx, ly] = toPx(s.landed[0], s.landed[1]);
c.strokeStyle = `rgba(255,255,255,${fade})`; c.beginPath(); c.moveTo(ax - 7, ay); c.lineTo(ax + 7, ay); c.moveTo(ax, ay - 7); c.lineTo(ax, ay + 7); c.stroke();
if (s.lit) { c.fillStyle = `rgba(255,70,40,${0.55 * fade})`; c.beginPath(); c.arc(lx, ly, umR(6), 0, 7); c.fill(); }
if ($("showFired").checked) {
const ring = (ids, col, rad) => { c.strokeStyle = col; c.lineWidth = 2.5; for (const i of ids) { const g = G.cells[i]; const [x, y] = toPx(g.x_um, g.y_um); c.beginPath(); c.arc(x, y, umR(g.radius_um) + rad, 0, 7); c.stroke(); } };
ring(s.direct, `rgba(255,90,50,${fade})`, 5); ring(s.first, `rgba(255,190,60,${fade})`, 5); ring(s.second, `rgba(190,160,255,${fade})`, 5); c.lineWidth = 1.5;
}
}
}
}
// ------------------------------------------------------------------ charts
const PALETTE = ["#ff6a3d", "#4fd68a", "#6aa8ff", "#f0b443", "#c58cff", "#5fd3d3", "#ff8ac0", "#b8c46a"];
function chart(canvas, t, series, labelsEl, yLabel, now) {
const dpr = window.devicePixelRatio || 1, W = canvas.clientWidth, H = canvas.clientHeight;
if (canvas.width !== Math.round(W * dpr)) { canvas.width = Math.round(W * dpr); canvas.height = Math.round(H * dpr); }
const c = canvas.getContext("2d"); c.setTransform(dpr, 0, 0, dpr, 0, 0); c.clearRect(0, 0, W, H);
const L = 44, R = 8, T = 8, B = 22, pw = W - L - R, ph = H - T - B;
let lo = 0, hi = 0.2; for (const s of series) for (const v of s.v) { if (v < lo) lo = v; if (v > hi) hi = v; }
hi *= 1.08; const x = (tt) => L + (tt + 10) / 10 * pw, y = (v) => T + (hi - v) / (hi - lo) * ph;
c.font = "11px " + css("--mono"); c.fillStyle = css("--muted"); c.strokeStyle = css("--line"); c.lineWidth = 1;
for (let k = 0; k <= 4; k++) { const v = lo + (hi - lo) * k / 4, yy = y(v); c.beginPath(); c.moveTo(L, yy); c.lineTo(W - R, yy); c.stroke(); c.fillText(v.toFixed(2), 4, yy + 4); }
for (let s = -10; s <= 0; s += 2) c.fillText((s === 0 ? "now" : s + " s"), x(s) - 10, H - 6);
c.strokeStyle = css("--stim"); c.setLineDash([3, 3]);
for (const ts of stimTimes) { const rel = ts - now; if (rel > -10 && rel <= 0) { c.beginPath(); c.moveTo(x(rel), T); c.lineTo(x(rel), T + ph); c.stroke(); } }
c.setLineDash([]);
series.forEach((s, k) => { c.strokeStyle = PALETTE[k % PALETTE.length]; c.lineWidth = k === 0 ? 2 : 1.3; c.beginPath(); s.v.forEach((v, i) => { const xx = x(s.t ? s.t[i] : t[i]); i ? c.lineTo(xx, y(v)) : c.moveTo(xx, y(v)); }); c.stroke(); });
labelsEl.innerHTML = series.map((s, k) => `<span><span class="sw" style="color:${PALETTE[k % PALETTE.length]}"></span>${s.label}</span>`).join("") || `<span>${yLabel}</span>`;
}
function drawLive() {
if (!LIVE) return;
const now = STATE.clock_s, lag = 0;
const series = LIVE.cells.map(({ roi, dff: v }) => {
const cell = G.rois[roi] ? G.rois[roi].cell : null;
const role = cell === stimCell ? "stimulated" : "partner";
return { label: `roi ${roi} (${role}${cell != null && cell >= 0 ? ", c" + cell : ""})`, v };
});
chart($("live"), LIVE.t.map(t => t - lag), series, $("liveLegend"), stimCell == null ? "Stimulate a cell to follow it and its true partners." : "The stimulated cell and its partners are not segmented.", now);
}
function drawCalcium() {
const h = STATE && STATE.history;
if (!h) { chart($("cal"), [], [], $("calLegend"), "Stimulate a cell to see its true calcium and its partners'.", STATE ? STATE.clock_s : 0); return; }
const series = h.cells.map(({ cell: c, calcium: v }) => ({ label: `c${c}${c === stimCell ? " (stimulated)" : ""}`, v }));
chart($("cal"), h.t, series, $("calLegend"), "", STATE.clock_s);
}
// ------------------------------------------------------------------ panels
function renderStatus(syncSwitches = true) {
if (!STATUS) return; const s = STATUS, f = s.faults;
const p = [`<span class="pill">clock ${s.clock_s.toFixed(1)} s</span>`,
s.recording ? `<span class="pill rec">recording ${s.recording} \u00b7 ${s.frames_saved} frames</span>` : `<span class="pill">not recording</span>`,
`<span class="pill">imaging ${s.imaging} \u00b7 blue ${s.blue}</span>`, `<span class="pill">${s.segmented} cells segmented</span>`,
`<span class="pill">${s.stimulations} pulses</span>`, `<span class="pill">health ${s.health}</span>`,
`<span class="pill">dose red ${s.dose.red} \u00b7 blue ${s.dose.blue} mJ/mm\u00b2</span>`];
if (!f.cover_on) p.push(`<span class="pill warn">cover off</span>`);
if (!f.frames_fresh) p.push(`<span class="pill warn">frames not fresh</span>`);
for (const a of f.active) p.push(`<span class="pill warn">${a}</span>`);
if (window.__perf && window.__perf.fps) p.push(`<span class="pill">${window.__perf.fps.toFixed(1)} fps \u00b7 frame ${window.__perf.frame_ms.toFixed(0)} ms</span>`);
$("pills").innerHTML = p.join("");
if (syncSwitches) document.querySelectorAll("[data-fault]").forEach(el => { el.checked = !!f[el.dataset.fault]; });
}
function renderWiring() {
const w = WIRING;
$("edges").innerHTML = w.edges.map(e => `<tr><td>c${e.a} \u2192 c${e.b}</td><td>${e.w.toFixed(2)}</td><td>${e.p_std.toFixed(2)}</td><td>${e.graded ? "yes" : "no"}</td></tr>`).join("") || `<tr><td colspan="4">No synapses.</td></tr>`;
const f = (ps) => ps.map(p => `c${p[0]}\u2013c${p[1]}`).join(", ") || "none";
$("keyFacts").textContent = `${w.edges.length} synapses, ${w.edges.filter(e => e.graded).length} graded (from stimulable cells, weight \u2265 floor)\n` +
`stimulable at the limits: ${w.stimulable.length} cells\nspill that must be flagged: ${f(w.spill_must)}\n` +
`indirect that must be flagged: ${w.indirect_must.map(p => "c" + p[0] + "\u2192c" + p[1]).join(", ") || "none"}\n` +
`answer key (standard protocol): ${w.key.connections.length} responses \u2265 0.5, ${w.key.spill.length} spill, ${w.key.indirect.length} indirect` +
(w.edits.length ? `\nyour edits: ${w.edits.map(e => `c${e.a}\u2192c${e.b}=${e.weight}`).join(", ")}` : "");
$("keynote").textContent = w.key_exact ? "Answer key: exact." : "Answer key: approximate (too many cells in reach of one spot for the exact count).";
}
function renderCells() {
if (!STATE) return; const s = STATE.last_stim, fresh = s && STATE.clock_s - s.t_light < 2.5;
const role = (i) => !fresh ? "" : s.direct.includes(i) ? "d" : s.first.includes(i) ? "s1" : s.second.includes(i) ? "s2" : "";
$("cells").innerHTML = G.cells.map(c => { const ca = STATE.calcium[c.id];
return `<tr class="${role(c.id)}"><td>c${c.id}</td><td>${c.roi ?? "\u2013"}</td><td>${c.opsin ? (c.expression ?? 1).toFixed(2) : "none"}</td><td>${(WIRING.fire_at_limits[c.id] ?? 0).toFixed(2)}</td>` +
`<td><span class="bar" style="width:${Math.min(60, ca * 30).toFixed(0)}px"></span> ${ca.toFixed(2)}</td><td>${STATE.opsin_available[c.id].toFixed(2)}</td></tr>`; }).join("");
}
function renderLastStim() {
const s = STATE && STATE.last_stim; if (!s) return;
const ago = (STATE.clock_s - s.t_light).toFixed(1), cs = (a) => a.length ? a.map(i => "c" + i).join(" ") : "none";
$("lastStim").textContent = `pulse ${s.index} on ${s.target}, ${ago} s ago \u00b7 ${s.lit ? `light on the spot ${s.red_act} mW/mm\u00b2` : "NO LIGHT reached the stage"}\n` +
`aimed (${s.aim.map(v => v.toFixed(1)).join(", ")}) um, landed (${s.landed.map(v => v.toFixed(1)).join(", ")}) um\n` +
`fired directly: ${cs(s.direct)}\nthrough one synapse: ${cs(s.first)}\nthrough two: ${cs(s.second)}\nvalid trial (truth): ${s.valid ? "yes" : "no"}`;
}
// ------------------------------------------------------------------ controls
function nearestCell(list, x, y, slack) {
let best = null, bd = 1e9; for (const c of list) { const d = Math.hypot(c.x_um - x, c.y_um - y); if (d < bd) { bd = d; best = c; } }
return best && bd <= best.radius_um + slack ? best : null;
}
$("view").addEventListener("click", async (ev) => {
if (!G || !$("loading").hidden) return;
const r = $("ovl").getBoundingClientRect(), k = $("ovl").width / r.width;
const [x, y] = toUm((ev.clientX - r.left) * k, (ev.clientY - r.top) * k);
if (editMode) {
const c = nearestCell(G.cells, x, y, 8); if (!c) { $("editMsg").textContent = "No cell there; click on a cell body."; return; }
if (editA == null) { editA = c.id; $("editMsg").textContent = `A = c${c.id}. Now click cell B.`; drawOverlay(); return; }
if (c.id === editA) { $("editMsg").textContent = "Pick a different cell for B."; return; }
const a = editA; editA = null; $("editMsg").textContent = `Setting c${a} \u2192 c${c.id}\u2026`;
try { const res = await cmd("set_connection", { a, b: c.id, weight: +$("wgt").value }); absorb(res.result);
$("editMsg").textContent = `c${a} \u2192 c${c.id} set to ${(+$("wgt").value).toFixed(2)}; key and render rebuilt.`; }
catch (e) { $("editMsg").textContent = e.message; }
return;
}
const roi = nearestCell(G.rois, x, y, 4);
$("sTarget").value = roi ? String(roi.id) : `control:${x.toFixed(1)},${y.toFixed(1)}`;
stimulate();
});
async function stimulate() {
const t = $("sTarget").value.trim();
if (!t) { logCall({ tool: "stimulate", clock_s: STATUS ? STATUS.clock_s : 0, error: true,
text: "No target: click a cell on the image, or type a cell id or control:x,y." }); return; }
const roi = /^\d+$/.test(t) ? +t : null;
if (roi != null && G.rois[roi]) { stimRoi = roi; stimCell = G.rois[roi].cell >= 0 ? G.rois[roi].cell : null; }
else { const [x, y] = t.replace("control:", "").split(",").map(Number); const c = nearestCell(G.cells, x, y, 6); stimCell = c ? c.id : null; stimRoi = null; }
const args = { targets: [t], red: +$("sRed").value, pulse_ms: +$("sPulse").value, repeats: +$("sRep").value, interval_s: +$("sInt").value };
try { await cmd("queue_stimulation", args);
logCall({ tool: "queue_stimulation", clock_s: STATUS ? STATUS.clock_s : 0, text: JSON.stringify(args) }); }
catch (e) { logCall({ tool: "queue_stimulation", clock_s: STATUS ? STATUS.clock_s : 0, text: e.message, error: true }); }
}
$("stim").onclick = stimulate;
$("stimStop").onclick = () => cmd("cancel_stimulation", {})
.then(() => logCall({ tool: "cancel_stimulation", clock_s: STATUS ? STATUS.clock_s : 0, text: "Queued pulses canceled." }))
.catch((e) => logCall({ tool: "cancel_stimulation", clock_s: STATUS ? STATUS.clock_s : 0, text: e.message, error: true }));
$("run").onclick = () => { running = !running; $("run").textContent = running ? "Pause" : "Run"; $("run").setAttribute("aria-pressed", running); };
document.querySelectorAll("[data-op]").forEach(b => b.onclick = () => { const [action, component] = b.dataset.op.split(","); agent("request_operator", { action, component, details: b.textContent }); });
$("setLed").onclick = () => agent("set_led", { red: +$("ledRed").value, blue: +$("ledBlue").value });
$("flood").onclick = async () => { await agent("record_flood", { duration_s: +$("floodS").value }); const th = await cmd("suggested_threshold", {}); if (th.result != null) $("thr").value = th.result; };
$("segment").onclick = () => agent("segment", { threshold: +$("thr").value });
$("setMask").onclick = () => agent("set_imaging_mask", { kind: $("mask").value });
$("recStart").onclick = () => agent("start_recording", {});
$("recStop").onclick = () => agent("stop_recording", {});
$("capture").onclick = () => agent("capture_microscope", {});
$("lightsOff").onclick = () => agent("set_room_lights", { state: "off" });
$("reseat").onclick = () => agent("request_operator", { action: "reseat", component: $("part").value, details: "reseat it" });
$("inspect").onclick = () => agent("request_operator", { action: "inspect", component: $("part").value, details: "how does it look?" });
$("anyCall").onclick = () => { let a; try { a = JSON.parse($("anyArgs").value || "{}"); } catch (e) { $("anyHint").textContent = "Arguments: " + e.message; return; }
agent($("anyTool").value, a); };
$("scen").onchange = () => { const s = SCEN.find(x => x.name === $("scen").value); $("seed").value = s && s.seed != null ? s.seed : ""; };
$("rebuild").onclick = () => newDish(false);
$("editMode").onclick = () => { editMode = !editMode; editA = null; $("editMode").setAttribute("aria-pressed", editMode);
$("clickhint").textContent = editMode ? "Wiring edit: click cell A, then cell B (purple drawer sets the weight)." : "Click a cell to stimulate it with the settings on the right. Click empty tissue to stimulate a control spot there.";
if (editMode && !$("showTruth").checked) $("showTruth").checked = true; };
document.querySelectorAll("[data-fault]").forEach(el => el.onchange = async () => {
faultVersion++; faultPending++;
try { const r = await cmd("set_fault", { name: el.dataset.fault, on: el.checked }); faultPending--; absorb(r.result); }
catch (e) { faultPending--; logCall({ tool: "set_fault", clock_s: STATUS ? STATUS.clock_s : 0, text: e.message, error: true }); } });
["showRois", "showTruth", "showFired"].forEach(id => $(id).onchange = () => G && drawOverlay());
boot();
requestAnimationFrame(loop);
</script>
</body></html>