import {escape} from './common.js';
import {NeuronModel,AssociationModel} from './brain-activity-models.js?v=brain-discovery-45';
const sources={neuron:['Neuronal Dynamics · integrate-and-fire models','https://neuronaldynamics.epfl.ch/online/Ch1.S3.html'],blind:['Exploratorium · Blind Spot activity','https://www.exploratorium.edu/snacks/blind-spot'],learning:['Rescorla & Wagner · original 1972 paper','https://bpb-us-w2.wpmucdn.com/about.illinoisstate.edu/dist/6/45/files/2021/01/RescorlaWagner.1972.pdf']};
function source(key){const [name,url]=sources[key];return `${name} ↗`}
const button=(id,label,primary=false)=>``;
function slider(id,label,value,min,max,step=1,unit=''){return ``}
function stats(items){return `
${items.map(([id,label,value])=>`
${label}
${value}
`).join('')}
`}
function shell(root,badge,title,intro,body){root.innerHTML=`${badge}
${title}
${intro}
${body}`;}
function axes(canvas,{min=-75,max=25,xLabel='Simulation time · ms',yLabel='Membrane voltage · mV'}={}){
const targetWidth=Math.max(320,Math.round(canvas.clientWidth));if(canvas.width!==targetWidth)canvas.width=targetWidth;const c=canvas.getContext('2d'),w=canvas.width,h=canvas.height,p={l:64,r:w-24,t:34,b:h-48};c.clearRect(0,0,w,h);c.fillStyle='#fafbf4';c.fillRect(0,0,w,h);c.font='14px sans-serif';c.textAlign='right';
for(let i=0;i<=4;i++){const v=min+(max-min)*i/4,y=p.b-(p.b-p.t)*i/4;c.strokeStyle='#dce5d3';c.beginPath();c.moveTo(p.l,y);c.lineTo(p.r,y);c.stroke();c.fillStyle='#61775c';c.fillText(v.toFixed(max-min<5?1:0),p.l-10,y+5);}
c.textAlign='left';c.fillStyle='#61775c';c.fillText(yLabel,p.l,21);c.fillText(xLabel,p.l,h-12);return {c,p,y:v=>p.b-(v-min)/(max-min)*(p.b-p.t),x:(v,total)=>p.l+v/Math.max(1,total)*(p.r-p.l)};
}
function linkToAnatomy(){return 'Connect this with the 3D brain explorer ↗'}
export function neuronSignals(root){
const model=new NeuronModel();let running=false,raf,last,alive=true;
shell(root,'CELLS · ELECTRICAL SIGNALS · CLASSROOM MODEL','When does a neuron fire?','Add excitation, oppose it with inhibition, and watch a model neuron add up its input. A spike is recorded when the voltage reaches the threshold.',`
${slider('signal-excite','Excitatory drive',18,0,40,1,' mV eq.')}${slider('signal-inhibit','Inhibitory drive',0,0,40,1,' mV eq.')}${slider('signal-threshold','Firing threshold',-50,-60,-35,1,' mV')}${slider('signal-tau','Membrane time constant',20,5,50,1,' ms')}${slider('signal-refractory','Recovery after a spike',4,1,15,1,' ms')}
${button('signal-run','Start simulation',true)}${button('signal-step','Advance 20 ms')}${button('signal-batch','Run 500 ms')}${button('signal-pulse','Add a brief pulse')}${button('signal-reset','Reset trace')}
${stats([['signal-voltage','Current voltage','−65 mV'],['signal-count','Recorded spikes','0'],['signal-rate','Recent rate · up to 500 ms','0 Hz'],['signal-time','Simulated time','0 ms']])}
Ready. Try Run 500 ms, then increase inhibition and run another 500 ms.
From one cell to brain systems
Connect this idea to other cells and named brain landmarks in Neurons & Brain Circuits.
Keep excitation at 18, run 500 ms, then set inhibition to 18 and run again. Does the voltage still reach the threshold? Switch to pulsed input to see the membrane rise and leak back toward rest.
What the model represents
The membrane integrates input, leaks toward its resting voltage, and resets after crossing a threshold. The tall marks indicate spike times; they do not reproduce an action potential’s shape. Excitation and inhibition are expressed as equivalent voltage drives in this simplified model.
See the rule and assumptions
Between spikes: τ dV/dt = −(V + 65) + excitation − inhibition. Rest and reset are −65 mV. Each step of at most 0.5 ms uses the exponential solution for its constant input. A spike resets the voltage and starts the selected recovery interval. A brief pulse raises the voltage by 8 mV unless the neuron is recovering.
${source('neuron')} ${linkToAnatomy()}`);
const $=s=>root.querySelector(s),params=()=>({excitation:+$('#signal-excite').value,inhibition:+$('#signal-inhibit').value,threshold:+$('#signal-threshold').value,tau:+$('#signal-tau').value,refractory:+$('#signal-refractory').value,pattern:$('#signal-pattern').value});
function drawNeuron(){const canvas=$('#signal-neuron'),w=Math.max(320,Math.round(canvas.clientWidth));if(canvas.width!==w)canvas.width=w;const c=canvas.getContext('2d'),compact=w<700,cx=compact?125:250,ix=compact?30:65,radius=compact?38:52,end=w-30,start=cx+radius+8;c.clearRect(0,0,w,200);c.fillStyle='#edf3e4';c.fillRect(0,0,w,200);c.lineWidth=4;
for(const [y,color] of [[55,'#5d9772'],[145,'#b77e85']]){c.strokeStyle=color;c.beginPath();c.moveTo(ix,y);c.lineTo(cx,100);c.stroke();c.fillStyle=color;c.beginPath();c.arc(ix,y,compact?18:23,0,7);c.fill();c.fillStyle='white';c.font='25px sans-serif';c.textAlign='center';c.fillText(y===55?'+':'−',ix,y+8);}
c.strokeStyle='#73916d';c.beginPath();c.moveTo(cx+radius,100);c.lineTo(end,100);c.stroke();for(let x=start+15;x0?'#dac28b':'#6c9378';c.beginPath();c.ellipse(cx,100,radius,radius+2,0,0,7);c.fill();c.fillStyle='white';c.font='17px sans-serif';c.textAlign='center';c.fillText(model.v.toFixed(1),cx,106);
for(const t of model.spikes){const age=model.t-t;if(age>=0&&age<60){c.fillStyle='#c99235';c.beginPath();c.arc(start+age/60*(end-start),100,7,0,7);c.fill();}}
c.fillStyle='#506b4d';c.font='14px sans-serif';c.textAlign='left';c.fillText(compact?'Excite':'Excitation',compact?9:102,compact?22:36);c.fillText(compact?'Inhibit':'Inhibition',compact?9:102,compact?189:175);c.textAlign='center';c.fillText(model.refractory>0?'Recovering':'Cell body',cx,181);c.fillText(compact?'Axon · slowed':'Schematic axon · slowed display',(start+end)/2,158);
}
function draw(){const par=params(),{c,p,y,x}=axes($('#signal-chart'),{min:Math.min(-75,...model.trace.map(r=>r.v))-3}),begin=Math.max(0,model.t-1000),span=Math.max(100,Math.min(1000,model.t));c.strokeStyle='#b88f44';c.setLineDash([7,5]);c.beginPath();c.moveTo(p.l,y(par.threshold));c.lineTo(p.r,y(par.threshold));c.stroke();c.setLineDash([]);c.strokeStyle='#3e7a61';c.lineWidth=2;c.beginPath();let first=true;for(const row of model.trace){if(row.t{if(running){pause();$('#signal-status').textContent='Paused at '+model.t.toFixed(0)+' simulated ms.';}else{running=true;last=undefined;$('#signal-run').textContent='Pause simulation';$('#signal-step').disabled=true;$('#signal-batch').disabled=true;$('#signal-status').textContent='Running. Change one input at a time to compare its effect.';raf=requestAnimationFrame(frame);}};
for(const [id,ms] of [['signal-step',20],['signal-batch',500]])$("#"+id).onclick=()=>{model.step(ms,params());draw();$('#signal-status').textContent=`Advanced ${ms} ms. ${model.count} spikes recorded in ${model.t.toFixed(0)} simulated ms.`;};
$('#signal-pulse').onclick=()=>{const recovering=model.refractory>0;model.pulse(8,params());if(!running)model.step(.5,params());draw();$('#signal-status').textContent=recovering?'The pulse arrived during recovery; voltage stayed at reset.':'An 8 mV pulse was added. Watch whether it reaches threshold.';};
$('#signal-reset').onclick=()=>{pause();model.reset();draw();$('#signal-status').textContent='Trace reset. Your input settings are kept.';};
root.querySelectorAll('input[type=range]').forEach(input=>input.oninput=()=>{$('#'+input.id+'-value').textContent=input.value+input.dataset.unit;draw()});$('#signal-pattern').onchange=draw;window.addEventListener('resize',draw);draw();return()=>{alive=false;cancelAnimationFrame(raf);window.removeEventListener('resize',draw)};
}
export function blindSpot(root){
let records=[];
shell(root,'PERCEPTION · RETINA · TRY IT YOURSELF','Find the gap in your visual field.','The target stays on the screen. Keep looking at the + with one eye while changing the dot’s spacing or your viewing distance. Log what you actually notice.',`
${slider('blind-gap','Dot separation',35,12,60,1,'% of board width')}${slider('blind-size','Dot diameter',12,4,24,1,' px')}
Close your left eye. Keep your right eye on the + at the left; notice the dot to its right without looking toward it.
+
Change the separation slowly while keeping your gaze on the +. On a small screen, landscape gives you more space.
${button('blind-gone','I noticed the dot disappear',true)}${button('blind-visible','I can see the dot')}${button('blind-clear','Clear observations')}
Your observations · reported by you
Observation
Eye
Spacing
Diameter
Line
No observations yet. The app does not detect your gaze or decide whether the dot disappeared.
Why a visible dot can disappear
At the optic disc, nerve fibers leave the retina and there are no light receptors. With the dot aligned to that part of one eye’s visual field, it may disappear from awareness. The surrounding pattern can appear to continue across the gap: try adding the line.
Make a comparison
Keep the same eye and viewing distance, then compare two spacings. Repeat with the other eye. These are your observations in screen pixels, not a calibrated retinal measurement or a clinical vision test.
${source('blind')} ${linkToAnatomy()}`);
const $=s=>root.querySelector(s);
function draw(){const right=$('#blind-eye').value==='right',gap=+$('#blind-gap').value,origin=right?20:80;$('#blind-fixation').style.left=origin+'%';$('#blind-dot').style.left=(origin+(right?gap:-gap))+'%';$('#blind-dot').style.width=$('#blind-size').value+'px';$('#blind-dot').style.height=$('#blind-size').value+'px';$('#blind-line-drawing').hidden=!$('#blind-line').checked;$('#blind-instruction').textContent=right?'Close your left eye. Keep your right eye on the + at the left; notice the dot to its right without looking toward it.':'Close your right eye. Keep your left eye on the + at the right; notice the dot to its left without looking toward it.';}
function render(){const body=$('#blind-records');body.innerHTML=records.length?records.slice(-20).reverse().map(r=>`
${r.observation}
${r.eye}
${r.spacing.toFixed(0)} px
${r.size} px
${r.line?'On':'Off'}
`).join(''):'
No observations yet. The app does not detect your gaze or decide whether the dot disappeared.
';}
function record(observation){const cross=$('#blind-fixation').getBoundingClientRect(),dot=$('#blind-dot').getBoundingClientRect();records.push({observation,eye:$('#blind-eye').value,spacing:Math.abs(dot.x+dot.width/2-cross.x-cross.width/2),size:+$('#blind-size').value,line:$('#blind-line').checked});render();$('#blind-status').textContent='Recorded your observation: '+observation.toLowerCase()+'. The dot itself stays visible in the page.';}
$('#blind-gone').onclick=()=>record('Disappeared');$('#blind-visible').onclick=()=>record('Visible');$('#blind-clear').onclick=()=>{records=[];render();$('#blind-status').textContent='Observations cleared. Keep your gaze on the + when you try again.'};
for(const id of ['blind-eye','blind-line'])$('#'+id).onchange=draw;root.querySelectorAll('input[type=range]').forEach(input=>input.oninput=()=>{$('#'+input.id+'-value').textContent=input.value+input.dataset.unit;draw()});draw();return()=>{};
}
export function predictionLearning(root){
const model=new AssociationModel();
shell(root,'LEARNING · EXPECTATION · CLASSROOM MODEL','Learn from a surprise.','Pair a cue with an outcome and watch its learned value change. This model updates most when the outcome differs from the expectation.',`
${stats([['predict-trial','Completed trials','0'],['predict-a','Learned value · cue A','0.00'],['predict-b','Learned value · cue B','0.00'],['predict-error','Last prediction error','—']])}
Green: cue AGold: cue B
Start with A and outcome 1. Run 10 trials, then change the outcome to 0 and repeat.
Try a guided experiment
${button('predict-acquire','1 · Teach A')}${button('predict-extinguish','2 · Omit the outcome')}${button('predict-block','Try blocking: A, then A + B')}
Teach A starts a new learner and gives 10 A + outcome trials. Omit the outcome keeps its learning and runs 10 A-only trials. Blocking starts fresh, teaches A for 20 trials, then pairs A + B with the same outcome for 20 more.
Latest trials · expectation before the update
Trial
Cues
Expected
Actual
Error
Run a trial to see the first update.
Why does the second cue learn less?
Once A predicts the outcome, adding B creates little surprise. In this model the two cues share a prediction error, so B gains little value. Omitting an expected outcome produces a negative error and lowers the active cue’s learned value.
See the learning rule
For each cue present: change in value = learning rate × (actual outcome − sum of present cue values). Only present cues update. This is a Rescorla–Wagner model with one shared effective learning rate. Values are expectation strengths, not measured brain activity or probabilities. The model illustrates selected aspects of conditioning and does not describe every kind of learning.
${source('learning')}`);
const $=s=>root.querySelector(s),cues=()=>$('#predict-cues').value.split(''),rate=()=>+$('#predict-rate').value;
function preview(){$('#predict-cue-label').textContent=$('#predict-cues').selectedOptions[0].textContent;$('#predict-expect').textContent=cues().reduce((sum,c)=>sum+model.weights[c],0).toFixed(2);$('#predict-result').textContent=$('#predict-outcome').value;}
function draw(){const h=model.history,lo=Math.min(-.1,...h.map(r=>Math.min(r.A,r.B))),hi=Math.max(1.1,...h.map(r=>Math.max(r.A,r.B))),{c,p,y,x}=axes($('#predict-chart'),{min:lo,max:hi,xLabel:'Completed trials',yLabel:'Learned cue value'});
for(const [key,color] of [['A','#3e7a61'],['B','#bc9147']]){c.strokeStyle=color;c.lineWidth=3;c.beginPath();c.moveTo(p.l,y(0));h.forEach(row=>c.lineTo(x(row.trial,Math.max(10,h.length)),y(row[key])));c.stroke();}c.fillStyle='#61775c';c.font='13px sans-serif';c.fillText('0',p.l,p.b+20);c.fillText(Math.max(10,h.length),p.r-20,p.b+20);
$('#predict-trial').textContent=h.length;$('#predict-a').textContent=model.weights.A.toFixed(3);$('#predict-b').textContent=model.weights.B.toFixed(3);$('#predict-error').textContent=h.length?h.at(-1).error.toFixed(3):'—';$('#predict-records').innerHTML=h.length?h.slice(-12).reverse().map(r=>`
${r.trial}
${r.cues}
${r.prediction.toFixed(3)}
${r.outcome}
${r.error.toFixed(3)}
`).join(''):'
Run a trial to see the first update.
';preview();}
function trials(n,cs=cues(),outcome=+$('#predict-outcome').value){try{for(let i=0;itrials(1);$('#predict-ten').onclick=()=>trials(10);$('#predict-reset').onclick=()=>{model.reset();draw();$('#predict-status').textContent='Learning reset. Both cue values are zero.'};
$('#predict-acquire').onclick=()=>{model.reset();settings('A','1');trials(10)};$('#predict-extinguish').onclick=()=>{settings('A','0');trials(10)};$('#predict-block').onclick=()=>{model.reset();settings('A','1');trials(20);settings('AB','1');trials(20);$('#predict-status').textContent=`Blocking experiment finished: A = ${model.weights.A.toFixed(3)}, B = ${model.weights.B.toFixed(3)}. A already predicted the outcome when B appeared.`;};
$('#predict-rate').oninput=e=>{$('#predict-rate-value').textContent=Number(e.target.value).toFixed(2)};$('#predict-cues').onchange=preview;$('#predict-outcome').onchange=preview;window.addEventListener('resize',draw);draw();return()=>window.removeEventListener('resize',draw);
}
export const brainActivities=[
{id:'neuron-signals',name:'Neuron Signal Lab',icon:'ϟ',tag:'EXCITATION · INHIBITION · SPIKES',title:'Small inputs. A firing decision.',description:'Adjust excitation, inhibition, threshold, and recovery. Watch the voltage and spike times in a live neuron model.',local:true,run:neuronSignals},
{id:'blind-spot',name:'Blind Spot Explorer',icon:'⊕',tag:'RETINA · PERCEPTION · OBSERVATION',title:'A dot on the screen. A gap in perception.',description:'Find your eye’s blind spot with a fixed target, compare both eyes, and record your own observations.',local:true,run:blindSpot},
{id:'prediction-learning',name:'Learning from Surprise',icon:'∆',tag:'CUES · EXPECTATIONS · LEARNING',title:'Expect something. Learn from the difference.',description:'Teach a model that a cue predicts an outcome. Explore acquisition, extinction, and blocking with visible trial-by-trial updates.',local:true,run:predictionLearning}
];
export const brainActivityInstructions={
'neuron-signals':{goal:'Explore how excitation, inhibition, leak, and a firing threshold affect a model neuron.',steps:[['Run a short comparison','Press Run 500 ms with the default settings. Notice the spike count and voltage trace.'],['Change one input','Raise inhibitory drive to 18, then run another 500 ms. Compare the new section of the trace.'],['Explore the timing','Try pulsed input, change the recovery interval, or add a brief pulse. The clock shows simulated time.']],controls:[['Start / Pause','Run the model at the selected playback speed or freeze it for inspection.'],['Advance 20 ms','Take a small, reproducible step.'],['Reset trace','Clear the recorded simulation while keeping your parameter choices.']]},
'blind-spot':{goal:'Observe your own blind spot with a target that stays on screen.',steps:[['Choose one eye','Select the eye you are using and close the other one. Keep your gaze on the +.'],['Adjust slowly','Change the dot spacing or your viewing distance without looking toward the dot. Notice whether it disappears and reappears.'],['Record and compare','Use the observation buttons, then try the other eye or add a line through the target. The page does not automatically detect disappearance.']],controls:[['Dot separation','Move the target farther from or closer to the fixation mark.'],['Observation buttons','Record only what you actually noticed.'],['Add a line','Explore whether the pattern appears continuous across the gap.']]},
'prediction-learning':{goal:'Explore how a model learns associations when outcomes differ from expectations.',steps:[['Teach a cue','Keep A and outcome 1 selected, then run 10 trials. Compare the first and later prediction errors.'],['Omit the outcome','Select outcome 0 and run more trials. Watch how an expected outcome’s absence changes A.'],['Try blocking','Run the blocking experiment: A learns first, then A + B predict the same outcome. Compare how much B learns.']],controls:[['One trial','Make one visible prediction and update.'],['Learning rate','Set how strongly a prediction error changes the active cues.'],['Reset learning','Clear all cue values and the trial history.']]}
};