brain-lab / brain_lab /static /brain-circuit.js
Chungulus's picture
Deploy Brain Lab CPU classroom app with verified saved research playback
4155f6b verified
Raw History Blame Contribute Delete
14.1 kB
import {escape,state} from './common.js';
import {BrainCircuitModel,circuitStages} from './brain-circuit-model.js?v=brain-circuit-47';
import {brainScene} from './brain-scene.js?v=brain-circuit-47';
import {setBrainFocus} from './brain-focus.js?v=brain-circuit-47';
export async function brainCircuit(root){
const model=new BrainCircuitModel();let selected=2,running=false,alive=true,raf,last,view=null;
root.innerHTML=`<article class="discovery circuit-lab"><header class="discovery-header"><span class="eyebrow">NEURONS → CIRCUITS → BRAIN LANDMARKS</span><h2>Connect a firing cell to the bigger picture.</h2><p>Explore six connected model neurons beside their anatomical landmarks. Select a stage to learn its role, then change the model and compare the signals that reach the output.</p></header>
<nav class="neuron-scale-nav" aria-label="Neuron scale"><a href="#neuron-signals">One neuron</a><a href="#brain-circuit" aria-current="page">Neurons &amp; brain parts</a></nav>
<div class="discovery-controls"><label>Input drive <output id="circuit-drive-value">22 mV eq.</output><input id="circuit-drive" type="range" min="0" max="40" value="22"></label><label>Connection strength <output id="circuit-strength-value">18 mV / event</output><input id="circuit-strength" type="range" min="0" max="30" value="18"></label><label>Transmission delay <output id="circuit-delay-value">6 ms / connection</output><input id="circuit-delay" type="range" min="1" max="30" value="6"></label><label>Add inhibition at<select id="circuit-inhibit-stage">${circuitStages.map((s,i)=>`<option value="${i}" ${i===2?'selected':''}>${escape(s.name)}</option>`).join('')}</select></label><label>Inhibitory drive <output id="circuit-inhibition-value">0 mV eq.</output><input id="circuit-inhibition" type="range" min="0" max="25" value="0"></label><label>Playback speed<select id="circuit-speed"><option value="50">50 simulated ms / second</option><option value="200" selected>200 simulated ms / second</option><option value="1000">1,000 simulated ms / second</option></select></label></div>
<p class="circuit-scope">Six toy neurons illustrate signal transmission. Each regional label stands for a much larger, interacting system. This chain is not a complete biological pathway, and its numbers are model settings.</p>
<p class="circuit-direction">Model signal direction: input → relay → visual → context → plan → output.</p>
<div class="circuit-stage-grid" aria-label="Select a model neuron and its brain landmark">${circuitStages.map((s,i)=>`<button class="circuit-stage" data-circuit-stage="${i}" aria-pressed="${i===selected}"><span class="circuit-stage-top"><b>${i+1}</b><span class="circuit-lamp" aria-hidden="true"></span></span><strong>${escape(s.name)}</strong><span class="circuit-stage-count" id="circuit-count-${i}">0 model spikes</span><span class="circuit-stage-voltage" id="circuit-voltage-${i}">−65.0 mV</span></button>`).join('')}</div>
<div class="discovery-actions"><button class="primary" id="circuit-run">Start circuit</button><button class="secondary" id="circuit-step">Advance 10 ms</button><button class="secondary" id="circuit-batch">Run circuit 500 ms</button><button class="secondary" id="circuit-reset">Reset trace</button><button class="secondary" id="circuit-restore">Restore all model stages</button></div>
<p class="discovery-status" id="circuit-status" role="status">Ready. Run 500 ms to establish a baseline, then change one setting and reset the trace for a fair comparison.</p>
<div class="circuit-anatomy"><section><div class="circuit-brain-stage"><canvas id="circuit-brain" tabindex="0" aria-label="Interactive 3D brain linked to the selected model stage. Drag to rotate or click a brain landmark."></canvas><span>ANATOMICAL CORTEX · SCHEMATIC LANDMARKS</span></div><div class="discovery-actions"><button class="secondary" id="circuit-inside">Look inside</button><button class="secondary" id="circuit-outside">Outside view</button><a class="secondary" id="circuit-full-explorer" href="#brain">Open selected part in the full explorer ↗</a></div><p class="circuit-anatomy-note" id="circuit-anatomy-note">Loading the anatomical view…</p></section>
<section class="circuit-part" aria-live="polite"><span class="eyebrow">SELECTED LANDMARK</span><h3 id="circuit-part-name"></h3><h4>In the brain</h4><p id="circuit-part-role"></p><h4>In this model</h4><p id="circuit-part-model"></p><label class="circuit-enable"><input type="checkbox" id="circuit-enable" checked> Enable this model neuron</label><p class="circuit-toggle-note">This switch controls one artificial unit. It does not simulate the effects of disabling a human brain region.</p></section></div>
<canvas class="discovery-chart" id="circuit-raster" width="960" height="330" role="img" aria-label="Raster of calculated firing events for all six model neurons over the last 1,000 simulated milliseconds"></canvas>
<dl class="discovery-stats"><div><dt>Simulated time</dt><dd id="circuit-time">0 ms</dd></div><div><dt>Input-unit spikes</dt><dd id="circuit-input-spikes">0</dd></div><div><dt>Output-unit spikes</dt><dd id="circuit-output-spikes">0</dd></div><div><dt>Events in transit</dt><dd id="circuit-in-transit">0</dd></div></dl>
<section class="discovery-explain"><h3>From a cell to a system</h3><p>A neuron can influence another cell through its connections. In this model, an upstream spike schedules a delayed voltage pulse for the next unit. Whether that unit fires depends on its voltage, recovery, incoming pulse, and inhibitory drive.</p><p>The first landmarks connect visual input, thalamus, and visual cortex. The later stages add a simplified seeing-to-acting story about context, planning, and motor output. Real systems contain many cells, parallel routes, and feedback connections absent here.</p><h3>Try it</h3><p>Record the output after a 500 ms baseline. Add inhibitory drive of 20 at Visual processing, reset, and run another 500 ms. Then restore inhibition to 0, disable that model neuron, reset, and repeat. Compare downstream spikes with upstream activity.</p><a class="discovery-source" href="https://www.nei.nih.gov/research-and-training/research-labs-and-branches/thalamocortical-visual-processing-section" target="_blank" rel="noreferrer">NEI · visual brain circuits ↗</a><a class="discovery-source" href="https://neuronaldynamics.epfl.ch/online/Ch3.S1.html" target="_blank" rel="noreferrer">Neuronal Dynamics · synaptic transmission ↗</a></section></article>`;
const $=s=>root.querySelector(s),params=()=>({drive:+$('#circuit-drive').value,strength:+$('#circuit-strength').value,delay:+$('#circuit-delay').value,inhibition:+$('#circuit-inhibition').value,inhibitUnit:+$('#circuit-inhibit-stage').value});
function choose(index,updateBrain=true){selected=index;const stage=circuitStages[index];root.querySelectorAll('[data-circuit-stage]').forEach((button,i)=>button.setAttribute('aria-pressed',String(i===index)));$('#circuit-part-name').textContent=stage.landmark;$('#circuit-part-role').textContent=stage.role;$('#circuit-part-model').textContent=stage.model;$('#circuit-enable').checked=model.enabled[index];if(updateBrain&&view){view.mode('inside');view.select(stage.region);} }
function raster(){const canvas=$('#circuit-raster'),width=Math.max(320,Math.round(canvas.clientWidth));if(canvas.width!==width)canvas.width=width;const c=canvas.getContext('2d'),left=width<600?92:160,right=width-20,top=42,bottom=280,begin=Math.max(0,model.t-1000),span=Math.max(100,Math.min(1000,model.t));c.clearRect(0,0,width,330);c.fillStyle='#f8faf1';c.fillRect(0,0,width,330);c.font='14px sans-serif';c.fillStyle='#617857';c.fillText('Calculated model spike times',18,22);
circuitStages.forEach((s,i)=>{const y=top+(i+.5)/6*(bottom-top);c.strokeStyle='#dce5d1';c.beginPath();c.moveTo(left,y);c.lineTo(right,y);c.stroke();c.fillStyle=model.enabled[i]?'#63795a':'#9e9c8c';c.textAlign='right';c.fillText(width<600?['Input','Relay','Visual','Context','Plan','Output'][i]:s.name,left-10,y+4);});
for(const event of model.events){if(event.t<begin)continue;const x=left+(event.t-begin)/span*(right-left),y=top+(event.unit+.5)/6*(bottom-top);c.strokeStyle=event.unit===selected?'#b68c3b':'#467c5c';c.lineWidth=2;c.beginPath();c.moveTo(x,y-10);c.lineTo(x,y+10);c.stroke();}c.fillStyle='#657c5b';c.textAlign='left';c.fillText(begin.toFixed(0)+' ms',left,310);c.textAlign='right';c.fillText((begin+span).toFixed(0)+' ms',right,310);
}
function draw(){model.units.forEach((unit,index)=>{const button=root.querySelector(`[data-circuit-stage="${index}"]`);button.classList.toggle('circuit-disabled',!model.enabled[index]);button.classList.toggle('circuit-firing',model.enabled[index]&&unit.spikes.length>0&&model.t-unit.spikes.at(-1)<20);$('#circuit-count-'+index).textContent=unit.count+' model spikes';$('#circuit-voltage-'+index).textContent=unit.v.toFixed(1)+' mV';});$('#circuit-time').textContent=model.t.toFixed(0)+' ms';$('#circuit-input-spikes').textContent=model.units[0].count;$('#circuit-output-spikes').textContent=model.units.at(-1).count;$('#circuit-in-transit').textContent=model.pending.length;raster();}
function pause(){running=false;cancelAnimationFrame(raf);last=undefined;$('#circuit-run').textContent='Start circuit';$('#circuit-step').disabled=$('#circuit-batch').disabled=false;}
function tick(now){if(!alive||!running)return;if(last!==undefined&&!document.hidden)model.step(Math.min(100,now-last)*+$('#circuit-speed').value/1000,params());last=now;draw();raf=requestAnimationFrame(tick);}
$('#circuit-run').onclick=()=>{if(running){pause();$('#circuit-status').textContent='Paused at '+model.t.toFixed(0)+' simulated ms.';}else{running=true;last=undefined;$('#circuit-run').textContent='Pause circuit';$('#circuit-step').disabled=$('#circuit-batch').disabled=true;$('#circuit-status').textContent='Running six connected model neurons. Select a stage to inspect its anatomical landmark.';raf=requestAnimationFrame(tick);}};
for(const [id,duration] of [['circuit-step',10],['circuit-batch',500]])$('#'+id).onclick=()=>{model.step(duration,params());draw();$('#circuit-status').textContent=`Advanced ${duration} ms. Input: ${model.units[0].count} spikes; output: ${model.units.at(-1).count} spikes. These are toy-model events.`;};
$('#circuit-reset').onclick=()=>{pause();model.reset();draw();$('#circuit-status').textContent='Trace reset. Current parameters and enabled model stages are kept.';};$('#circuit-restore').onclick=()=>{pause();model.enabled.fill(true);model.reset();choose(selected);draw();$('#circuit-status').textContent='All model neurons restored and trace reset. Your input parameters are kept.';};
root.querySelectorAll('[data-circuit-stage]').forEach(button=>button.onclick=()=>{choose(+button.dataset.circuitStage);draw()});$('#circuit-enable').onchange=event=>{model.setEnabled(selected,event.target.checked);draw();$('#circuit-status').textContent=`${circuitStages[selected].name} model neuron ${event.target.checked?'enabled':'disabled'}. Reset the trace before making a baseline comparison.`;};
const units={drive:' mV eq.',strength:' mV / event',delay:' ms / connection',inhibition:' mV eq.'};for(const id of Object.keys(units))$('#circuit-'+id).oninput=event=>{$('#circuit-'+id+'-value').textContent=event.target.value+units[id];draw()};
$('#circuit-inside').onclick=()=>view?.mode('inside');$('#circuit-outside').onclick=()=>view?.mode('outside');$('#circuit-full-explorer').onclick=()=>setBrainFocus(circuitStages[selected].region);
window.addEventListener('resize',draw);choose(selected);draw();
// Start the local model independently of WebGL. A failed anatomy renderer leaves it usable.
brainScene($('#circuit-brain'),{onSelect:region=>{const index=circuitStages.findIndex(s=>s.region===region);if(index>=0){choose(index,false);draw();}else{const part=state.anatomy.find(p=>p.id===region);$('#circuit-anatomy-note').textContent=part?part.name+': '+part.biology:'Choose one of the six stages to return to the illustrated circuit.';}}}).then(scene=>{if(!alive||!root.isConnected){scene.destroy();return;}view=scene;view.mode('inside');view.opacity(.25);view.route(circuitStages.map(stage=>stage.region),false);view.select(circuitStages[selected].region);$('#circuit-anatomy-note').textContent='Select a model stage to highlight its landmark. You can also rotate the brain or click a mapped part. The connecting line is an illustration between landmarks, not a traced fiber pathway or measured activity.';}).catch(()=>{if(alive)$('#circuit-anatomy-note').textContent='The 3D view is unavailable here. The circuit, stage descriptions, and spike raster still work.';});
return()=>{alive=false;cancelAnimationFrame(raf);window.removeEventListener('resize',draw);view?.destroy()};
}
export const brainCircuitActivity={id:'brain-circuit',name:'Neurons & Brain Circuits',icon:'⌁',tag:'CELLS · CONNECTIONS · BRAIN PARTS',title:'A cell fires.<br><em>A circuit carries it forward.</em>',description:'Connect six model neurons, inspect their brain landmarks, and compare signal flow with inhibition or an interrupted model stage.',local:true,run:brainCircuit};
export const brainCircuitInstructions={goal:'Connect individual model neurons with anatomical landmarks and see how transmission depends on their connections.',steps:[['Establish a baseline','Run circuit 500 ms. Compare each model neuron’s spike count and the raster.'],['Inspect a brain part','Select a stage to highlight its brain landmark and read both the biological role and the model’s much simpler role.'],['Change one thing','Add inhibition at a chosen stage, or disable its model neuron. Reset the trace and run another 500 ms. Compare upstream activity with the output.']],controls:[['Connection strength','Voltage added when a scheduled model event arrives.'],['Transmission delay','The chosen delay for each artificial connection.'],['Enable this model neuron','Controls the selected unit only; it is not a human lesion simulation.'],['Open selected part in the full explorer','Keeps your anatomical selection when you open the 3D explorer.']]};