⟵ Back to projects

The Mathematical Beauty of a Neuron

Project Overview

A neuron is a handful of numbers that change over time, plus rules for how they change. Those rules are differential equations, and a computer can't solve them exactly. It takes small steps, and the way it steps decides whether you get biology or nonsense.

This post builds one tool and then puts it under more and more load. It starts with the fourth-order Runge–Kutta method (RK4), tests it on the chaotic Lorenz attractor, then uses it to run leaky integrate-and-fire neurons and their relatives, connects two of them with a synapse, and adds spike-timing-dependent plasticity. It ends with a single neuron that learns which of its 400 inputs belong together, with every equation running at once.

Your brain cells follow rules you can write down. The rules say how a cell's voltage rises and falls, when it fires, and how its connections get stronger or weaker. A computer can follow those rules too, by taking lots of tiny steps forward in time.

On this page you'll learn how those steps work, see why they need to be careful (with a famous butterfly-shaped pattern), and then build a brain cell piece by piece. At the end, one simulated cell teaches itself which of its 400 inputs are worth listening to.

Numerical Methods Chaos Spiking Neuron Models Synaptic Plasticity Computational Neuroscience
A note on simplifications

The brain cells on this page are simplified on purpose. Real cells fire because tiny gates in their skin let salt in and out. These models skip the gates. They only track when a cell fires, and some versions don't draw the spike at all: the voltage hits a line and jumps back down.

That shortcut is what makes it possible to simulate thousands of cells and watch them learn. A future post will open up the gates with the Hodgkin–Huxley model, where the spike comes out of the chemistry itself.

The neurons in this post are integrate-and-fire models. They describe when a neuron fires, not the sodium and potassium channels that actually produce the spike. In the simplest version the spike isn't modeled at all: the voltage reaches a threshold and is reset.

That simplification is what makes these models fast enough to run thousands of neurons and to study learning. A future post will cover the Hodgkin–Huxley model, where the spike emerges from the channel dynamics themselves. One Hodgkin–Huxley spike does appear here, in Section 4, as a reference to compare against.

A simulated brain cell, live. Its voltage drifts up as input arrives, and when it crosses the red line it fires (the black lines) and starts over. Hold the button to push more current in and watch it fire faster.A leaky integrate-and-fire neuron with noisy input current, integrated with RK4 at 0.1 ms steps and shown at half speed. Each time V crosses the threshold θ it is reset. The black lines are drawn on afterward: the model itself never produces a spike shape. Hold the button to raise the mean input.

0. A neuron is an equation that keeps changing

A brain cell has a voltage, a small electrical difference between its inside and outside. Input from other cells pushes the voltage up. Left alone, it leaks back down to a resting level. If enough input arrives fast enough, the voltage crosses a tipping point and the cell fires: a quick electrical pulse that travels to other cells.

Each of those sentences is a rule about how fast the voltage is changing right now. Rules like that are called differential equations. They don't tell you where the voltage will be in a second. They only tell you which way it's heading at this instant. To find out where it ends up, you take a small step in that direction, look again, and repeat. Everything on this page is built on doing that well.

The state of a model neuron is a short list of numbers: its membrane voltage \(V\), maybe a slow adaptation current \(w\), and the currents arriving at its synapses. The model doesn't say what those numbers will be later. It says how fast each one is changing now, as a function of all of them:

$$\frac{d\mathbf{y}}{dt} = \mathbf{f}(t, \mathbf{y}).$$

That is an ordinary differential equation (ODE). For almost every model worth studying there is no formula for \(\mathbf{y}(t)\), so we integrate numerically: start from a known state, use \(\mathbf{f}\) to estimate where the state will be a short time \(h\) later, and repeat. The choice of how to make that estimate is the first decision in any neuron simulation, and it's the one people think about least. So that's where we start.

1. Taking steps: from Euler to RK4

The simplest way to take a step: look at which way things are heading, and go that way for a bit. That's called Euler's method. It sounds fine, but there's a catch. The direction changes during the step, and Euler doesn't notice. On a curving path it always overshoots to the outside of the curve.

Below is a weight bouncing on a spring. Its real path is a perfect circle (the dashed line): it trades speed for stretch and back, forever. Euler (red) spirals outward, inventing energy from nothing. RK4 (blue) stays on the circle.

The simplest scheme is Euler's method: assume the slope stays constant over the step.

$$\mathbf{y}_{n+1} = \mathbf{y}_n + h\,\mathbf{f}(t_n, \mathbf{y}_n).$$

The error it makes on each step is \(O(h^2)\), so the error accumulated over a fixed time is \(O(h)\): halve the step, halve the error. That's slow. Worse, the errors aren't random. On a rotation, Euler always steps along the tangent, which points outside the circle, so every step adds a little energy. Below is the harmonic oscillator \(\ddot x = -x\), written as \(\dot x = v,\ \dot v = -x\). Its exact orbit is the unit circle.

Left: the spring's position and speed, traced over time. Right: how much energy each method has made up, on a scale where every gridline is 10,000 times bigger than the one below it.Left: phase portrait. Right: relative energy error on a log scale. Euler's energy grows by a factor of \(1+h^2\) every step. RK4 at the same \(h\) loses energy too (it isn't symplectic), but at a rate of order \(h^6\) per step.
Try this
  1. Press Play at the default step size and watch Euler spiral out.
  2. Drag the step size down to 0.05. Euler gets better but still drifts. RK4's error drops by a huge amount.
  3. Drag it up to 1. Now even RK4 visibly cuts corners, but it still stays near the circle while Euler flies off.

So how does RK4 do so much better? Instead of looking once, it looks four times. It checks the direction where it is, then peeks halfway along, then peeks halfway again using what it just learned, then peeks at the end. It averages those four directions, giving the middle two double weight, and takes one step with the average. Four looks cost four times the work, but the answer can be thousands of times more accurate.

RK4 samples the slope four times inside each step and combines them:

$$\begin{aligned} \mathbf{k}_1 &= \mathbf{f}(t_n,\ \mathbf{y}_n) \\ \mathbf{k}_2 &= \mathbf{f}(t_n + \tfrac{h}{2},\ \mathbf{y}_n + \tfrac{h}{2}\mathbf{k}_1) \\ \mathbf{k}_3 &= \mathbf{f}(t_n + \tfrac{h}{2},\ \mathbf{y}_n + \tfrac{h}{2}\mathbf{k}_2) \\ \mathbf{k}_4 &= \mathbf{f}(t_n + h,\ \mathbf{y}_n + h\,\mathbf{k}_3) \\ \mathbf{y}_{n+1} &= \mathbf{y}_n + \tfrac{h}{6}\left(\mathbf{k}_1 + 2\mathbf{k}_2 + 2\mathbf{k}_3 + \mathbf{k}_4\right) \end{aligned}$$

Each probe uses the previous one to decide where to look. The weights 1, 2, 2, 1 are Simpson's rule: if \(\mathbf{f}\) depended only on \(t\), RK4 would be exactly Simpson integration of the slope. The figure below takes one step apart on \(y' = y\cos t\), whose exact solution \(y = e^{\sin t}\) lets us check every number.

The grey dashes show which way things are heading everywhere. The black curve is the true path. Each colored dot is one of RK4's four looks, with a short bar showing the direction it saw. The white circle is where the step should land.Slope field of \(y' = y\cos t\), the exact solution through \((t_0, y_0)\), and the four RK4 probes. Dashed lines show the trial step that placed each probe. Each short bar is the slope \(k_i\) sampled there. The open circle is the exact value at \(t_0 + h\).
Try this
  1. Drag the starting point to the top of a hump, where the path curves hardest. Euler's red arrow shoots off. RK4's black arrow still lands near the white circle.
  2. Make the step huge (above 2). Watch the four probes spread out and RK4 finally miss too. No method saves you from steps that are too big.
Graduate: order, stability, and what RK4 doesn't promise

RK4's local truncation error is \(O(h^5)\) and its global error is \(O(h^4)\). The figure below measures this directly: the global error at \(t = 6\) falls with slope 4 on a log–log plot, against slope 1 for Euler, until it hits the floor set by 64-bit rounding.

Two caveats matter for everything that follows. First, RK4 is explicit, so it is only stable when \(h\lambda\) lies inside its stability region (roughly \(|h\lambda| \lesssim 2.8\) on the negative real axis, where \(\lambda\) ranges over the Jacobian's eigenvalues). A membrane with \(\tau = 10\) ms has \(\lambda = -0.1\ \text{ms}^{-1}\), so steps of 0.1–0.25 ms are far inside the region. Stiff systems such as Hodgkin–Huxley channel kinetics or detailed calcium dynamics push \(\lambda\) much more negative and favor implicit methods. Second, RK4 is not symplectic. On Hamiltonian systems its energy error grows slowly but without bound. For long orbital or molecular simulations you would use a symplectic integrator such as leapfrog/Verlet. For dissipative neuron models, which forget their initial energy anyway, RK4's accuracy per unit of work is hard to beat.

2. Stress-testing the solver: the Lorenz butterfly

In 1963, the weather scientist Edward Lorenz wrote down three simple rules for air rising and falling in a heated box. He found something strange. If he restarted his simulation from numbers rounded to three digits instead of six, the forecast came out completely different after a while. The tiniest difference grew and grew until it took over. This became known as the butterfly effect: the idea that a butterfly flapping its wings could change the weather weeks later.

Below, two paths start almost exactly at the same spot, differing by one part in 100 million. For a while they move together. Then they split up and loop around different wings of the butterfly. Yet both keep tracing the same butterfly shape. You can't predict where one path will be, but you can trust the shape.

The Lorenz system is three coupled equations, originally a drastically reduced model of convection:

$$\dot x = \sigma(y - x), \qquad \dot y = x(\rho - z) - y, \qquad \dot z = xy - \beta z.$$

At Lorenz's parameters \(\sigma = 10,\ \rho = 28,\ \beta = 8/3\), trajectories never settle and never repeat. They wind around two unstable fixed points, switching between the two wings in an order that looks random. Nearby trajectories separate exponentially, \(|\delta(t)| \approx |\delta_0|\, e^{\lambda t}\) with \(\lambda \approx 0.906\). That is what chaos means here: sensitive dependence on initial conditions, inside a bounded region of state space.

That makes Lorenz a hard test for a solver. Any numerical error acts like a perturbation and grows at the same exponential rate. Two trajectories that start \(10^{-8}\) apart below will lose each other after about \(\ln(10^{9})/0.906 \approx 23\) time units, no matter how good the integrator is.

Left: the two paths in 3D (drag to turn it). Right: the distance between them. Each gridline up is 10 times farther apart. A straight climb on this kind of scale means the gap keeps multiplying.Left: two trajectories, \(x_0 = 1\) and \(x_0 = 1 + 10^{-8}\), over a faint reference attractor computed with RK4 at \(h = 0.002\). Right: \(|\delta(t)|\) on a log scale, with \(e^{\lambda t}\) dashed.
Try this
  1. Press Play and watch the distance climb in a straight line until the two paths are on different wings.
  2. Switch the solver to Euler and Play. The paths still look chaotic, but compare them with the faint grey cloud. Then raise the step size: Euler's butterfly smears and swells while RK4's still matches the grey shape. At the largest steps Euler blows up entirely.
  3. Slide ρ down below 24. The butterfly collapses: paths spiral into one of two resting points. Chaos is something these equations do only for some settings.

The lesson for brain cells: when inputs are noisy, you can't predict the exact moment a cell will fire. What you can trust is the pattern, like how often it fires and how its connections change on average. That's what we'll watch.

The lesson to carry forward: with chaos, or with noise, individual trajectories can't be trusted for long, but their statistics can. A good solver keeps the shape of the attractor (where trajectories spend their time) even after the trajectory itself has diverged. Euler at a large step distorts the shape. RK4 at the same step preserves it. When we drive neurons with random input, the spike times will be different every run. The firing rates and the weight changes are what we'll read.

Graduate: why a wrong trajectory can still be a right answer

For uniformly hyperbolic systems, the shadowing lemma guarantees that a numerical trajectory with small per-step errors stays close to some exact trajectory with a slightly different initial condition. The computed orbit is wrong as a prediction but typical as a sample. The Lorenz attractor isn't uniformly hyperbolic, but Tucker (2002) proved, using rigorous interval-arithmetic numerics, that a robust strange attractor exists at the classical parameters. That computer-assisted proof answered Smale's fourteenth problem. The predictability horizon is \(t^* \approx \lambda^{-1}\ln(\Delta/\delta_0)\): a better solver lowers \(\delta_0\), but only buys time logarithmically.

3. The leaky integrate-and-fire neuron

Now for the brain cell. Picture a bucket with a small hole in the bottom. Pour water in (that's the input) and the level rises. The hole lets it leak back out, so if you stop pouring, the level falls to empty. Draw a line near the top. When the water reaches the line, the cell fires: the bucket is dumped and it starts again.

That's the whole model, called the leaky integrate-and-fire neuron. "Integrate" means it adds up input. "Leaky" means it slowly forgets. "Fire" means it fires at the line. With a gentle trickle the leak wins and the level settles below the line: no firing at all. Pour harder and it fills and fires again and again, faster the harder you pour.

The leaky integrate-and-fire (LIF) neuron treats the membrane as a capacitor in parallel with a leak resistor. One ODE and one reset rule:

$$C\frac{dV}{dt} = -g_L\,(V - E_L) + I(t), \qquad V \ge \theta \;\Rightarrow\; \text{spike},\ V \leftarrow V_r .$$

With \(C = 200\) pF and \(g_L = 10\) nS, the membrane time constant is \(\tau = C/g_L = 20\) ms. Under a constant current, \(V\) relaxes exponentially toward \(V_\infty = E_L + I/g_L\). If \(V_\infty\) stays below threshold, the neuron never fires. The smallest current that fires it is the rheobase, \(I_{\text{rh}} = g_L(\theta - E_L)\). Above it, the time from reset to threshold can be solved exactly, and with a refractory period \(t_{\text{ref}}\) after each spike, the firing rate is

$$f(I) = \left[\,t_{\text{ref}} + \tau \ln\frac{V_\infty - V_r}{V_\infty - \theta}\,\right]^{-1}.$$

That closed form is a gift: it lets us check the simulation. The dashed curve in the right panel is the formula. The dots are measured by running the RK4 neuron for a simulated second at each current.

Left: the cell's voltage while input is switched on (orange strip). Right: how fast it fires for each amount of input. The orange dot is your current setting.Left: \(V(t)\) for a current step from 50 to 350 ms. Grey dashed: \(V_\infty\). Right: the f–I curve, analytic (dashed) against simulated (dots). The orange dot is the rate at the current setting.
Try this
  1. Set the input to 140 pA. The voltage settles just under the line and never fires. Now try 160.
  2. Press “Measure the whole curve”. The dots land on the formula. That's the solver passing a test.
  3. Raise the rest after a spike to 10 ms and measure again. The curve flattens at the top: a cell that has to rest can't fire faster than once per rest period.

The reset is a cliff, and RK4 can't see cliffs

RK4's accuracy comes from assuming the solution is smooth across the step. The reset breaks that assumption: \(V\) jumps from \(\theta\) to \(V_r\) instantly. If the code only checks for \(V \ge \theta\) at the end of each step and resets there, every spike is late by up to one step. Spike times carry the information downstream, and STDP in Section 6 depends on them at the millisecond level, so this matters. The fix is to find the crossing inside the step (here by linear interpolation), reset at that moment, and integrate the rest of the step from \(V_r\).

Constant input, so the exact spike times are known in closed form (grey ticks). With large steps, the end-of-step rule delays every spike, the delays add up, and spikes go missing.
Graduate: exact integration and event handling

Linear interpolation of the crossing is \(O(h^2)\) accurate, which caps the spike-time accuracy below RK4's \(O(h^4)\). Cubic Hermite interpolation using the derivative at both ends, or a few Newton steps on RK4's dense output, recovers the full order. For the LIF with exponential synapses there is a better option: the subthreshold dynamics are linear, so the state can be propagated exactly with a matrix exponential, \(\mathbf{y}_{n+1} = e^{Ah}\mathbf{y}_n\)(Rotter & Diesmann, 1999). That is what simulators like NEST do. I use RK4 throughout this post on purpose, so one integrator handles linear and nonlinear models alike.

4. A zoo of integrate-and-fire neurons

The bucket model is simple, maybe too simple. Its voltage creeps up to the line and then jumps back down: there's no actual spike, just a rule that says "fire now." Scientists have built better versions by changing one thing: how the voltage speeds up as it gets close to the tipping point. In a real cell, once the voltage gets high enough, it starts pushing itself up faster and faster. That runaway rise is the spike.

  • LIF: the bucket. The voltage slows down as it approaches the line and is reset by a rule.
  • QIF: near the tipping point, the voltage starts racing upward by itself.
  • EIF: the same idea with an even sharper takeoff, which matches real cells well.
  • AdEx: EIF plus tiredness. Each spike makes the next one a little harder.

The LIF's weakness shows in its equation: below threshold, \(dV/dt\) only ever pulls \(V\) back toward rest, harder the higher \(V\) goes. Nothing in the dynamics makes a spike. Real neurons have sodium channels that open as \(V\) rises, adding positive feedback, and that runaway upswing is the spike. The family of integrate-and-fire models differs mainly in one term: how \(dV/dt\) depends on \(V\).

$$\begin{aligned} \text{LIF:}\quad & C\dot V = -g_L(V - E_L) + I \\ \text{QIF:}\quad & C\dot V = k\,(V - E_L)(V - V_T) + I \\ \text{EIF:}\quad & C\dot V = -g_L(V - E_L) + g_L\Delta_T\, e^{(V - V_T)/\Delta_T} + I \\ \text{AdEx:}\quad & C\dot V = -g_L(V - E_L) + g_L\Delta_T\, e^{(V - V_T)/\Delta_T} - w + I, \quad \tau_w \dot w = a(V - E_L) - w \end{aligned}$$

In QIF and EIF the right-hand side turns upward and diverges, so \(V\) shoots off to infinity in finite time by itself. The simulation stops it at a peak and resets it. The exponential term in the EIF has a sharpness \(\Delta_T\). As \(\Delta_T \to 0\) it becomes a hard threshold and the EIF turns back into the LIF. Fits to cortical pyramidal cells give \(\Delta_T \approx 1\)–3 mV (Badel et al., 2008). AdEx adds a second variable \(w\), an adaptation current that jumps by \(b\) at every spike and decays with time constant \(\tau_w\).

Anatomy of a spike, model by model

Below, the faint dashed curve is the shape of a real spike, simulated with the full gate-by-gate model (Hodgkin–Huxley). Its parts are labeled: rest, tipping point, the fast rise, the top, the fall, the dip below rest, and a short time when it's hard to fire again. Pick a model to lay its spike on top and see which parts it gets.

The faint curve below is one action potential from the Hodgkin–Huxley model (squid axon parameters), integrated with the same RK4 code. Its phases are labeled. Each integrate-and-fire model is driven with a strong current step until its first spike, then the current is switched off so it can recover. All the spikes are aligned at the moment of the spike. The table separates what each model produces from its own dynamics from what is imposed by a reset rule or a cutoff.

A ✓ means the model's own rule creates that part of the spike. A ~ means it's faked by hand, for example by resetting below rest to make a dip. A ✗ means it's missing.Top: one spike per model against the Hodgkin–Huxley reference (dashed), aligned at the spike. The purple band marks the first 4 ms after it. Bottom: the intrinsic dynamics \(f(V)\), i.e. \(dV/dt\) with no input, for each model, with the Hodgkin–Huxley spike plotted the same way. Filled dot: stable rest. Open dot: the unstable fixed point where the threshold emerges.
Try this
  1. Start with LIF. It rises slowly, then just jumps down. No rise, no top.
  2. Switch to QIF, then EIF. The fast rise appears. EIF's is sharper and closer to the real one.
  3. Switch to AdEx. The spike looks like EIF, but afterward the voltage stays lower for longer. That's the tiredness current at work.

The bottom panel is the key idea of this section: the shape of the upstroke is the shape of \(f(V)\). Where \(f\) crosses zero going downward, there is a stable rest state. Where it crosses going upward, there is an unstable point: push \(V\) past it and \(f\) keeps pushing. LIF's line never turns up, so its threshold has to be added as a rule. In QIF and EIF the threshold comes out of the equation, as the unstable fixed point. None of them repolarizes by itself. That needs a second, slower variable that pulls \(V\) back down, which is exactly what potassium channels do in Hodgkin–Huxley and what \(w\) does, crudely, in AdEx.

Firing patterns: what a second variable buys you

Real brain cells don't all fire the same way. Some tick like a metronome. Some start fast and tire. Some fire in bursts. The AdEx model can do all of these, just by changing a few numbers in its tiredness rule. Turn the tiredness off and every pattern turns back into the plain metronome.

One extra variable is enough to reproduce most of the firing patterns seen in cortical recordings. The presets below are parameter sets from Naud et al. (2008), each driven by the same kind of current step. The right panel is the \((V, w)\) phase plane, the same idea as the Lorenz picture but in two dimensions and with jumps. The dashed curves are nullclines, where \(\dot V = 0\) (green) or \(\dot w = 0\) (purple). Between spikes the trajectory follows the vector field. At each spike it leaves the right edge and is reinjected at \((V_r,\ w + b)\).

Top: the voltage. Bottom: the tiredness, which jumps up at every spike and slowly fades. The traces play back slowly so you can follow them.Left: \(V(t)\) and \(w(t)\) for a current step at 50 ms, played back at quarter speed. Right: the trajectory in the \((V,w)\) plane over the vector field and nullclines. Dashed grey lines are reset jumps.
Try this
  1. Compare Tonic and Adapting. Same model, but in Adapting each spike adds a lot of tiredness that fades slowly, so the gaps between spikes stretch out.
  2. Pick Bursting and watch the phase plane: a few fast loops, then a long slow drift down before the next burst.
  3. Tick the box that removes adaptation. Every preset becomes a metronome.
Graduate: excitability classes and bifurcations

The QIF is the normal form of a saddle-node bifurcation on an invariant circle. Near rheobase its rate grows like \(f \propto \sqrt{I - I_{\text{rh}}}\): it can fire arbitrarily slowly (Hodgkin's class I excitability). The change of variables \(V = \tan(\vartheta/2)\) turns it into the Ermentrout–Kopell theta neuron. The LIF's rate instead rises from zero with an infinite slope and \(1/\ln\) behavior. In AdEx the parameter \(a\) decides how rest loses stability. For small \(a\) it is a saddle-node, giving class I firing. For larger \(a\), rest can lose stability through an Andronov–Hopf bifurcation, giving class II behavior with subthreshold oscillations and a nonzero minimum rate (Touboul & Brette, 2008). Where the reset lands relative to the \(\dot V = 0\) nullcline decides whether the neuron bursts, which is why bursting shows up as two different speeds in the phase plane.

5. Connecting neurons: synapses

One cell on its own doesn't do much. Cells talk through connections called synapses. When cell A fires, it gives cell B a short kick of current, which raises B's voltage a little for a few milliseconds. One kick is usually not enough to make B fire. Several kicks close together add up.

Each connection also has a strength. A strong connection gives a big kick. A weak one barely registers. Learning, as we'll see next, is mostly about changing these strengths.

The simplest synapse model is a current that jumps when the presynaptic neuron spikes and decays exponentially:

$$\tau_s \frac{dI_{\text{syn}}}{dt} = -I_{\text{syn}}, \qquad \text{presynaptic spike: } I_{\text{syn}} \leftarrow I_{\text{syn}} + w\,J .$$

\(I_{\text{syn}}\) feeds into neuron B's membrane equation as its input current. The state is now \([V_B, I_{\text{syn}}]\), integrated together with RK4. Filtering an exponential current through the membrane gives the familiar postsynaptic potential (PSP): a fast rise and a slower decay, here about 8 mV at peak for \(w = 1\). B's threshold is 15 mV above rest, so B fires only when several PSPs arrive within about one membrane time constant. This is temporal summation. The weight \(w\) is the number learning will change.

Top: when A fires. Middle: the kick of current A sends into B. Bottom: B's voltage and its firing line.Top: presynaptic spikes. Middle: \(I_{\text{syn}}(t)\). Bottom: \(V_B(t)\) and the threshold. Shown at a tenth of real time.
Try this
  1. Click Fire A once and wait. Then click it three times as fast as you can. Only the quick burst gets B over the line.
  2. Make the kick last longer (20 ms). Now kicks that are spaced out still pile up.
  3. Let A fire on its own at 40 Hz and raise the connection strength until B starts following A.
Graduate: current versus conductance

Real synapses open channels with a reversal potential, so the injected current is \(g_{\text{syn}}(t)(E_{\text{syn}} - V)\), not a fixed waveform. That makes excitation weaker as \(V\) approaches \(E_{\text{syn}}\) and, more importantly, adds \(g_{\text{syn}}\) to the total membrane conductance. Under heavy balanced input the effective time constant \(C/(g_L + \sum g_{\text{syn}})\)can shrink several-fold: the high-conductance state (Destexhe, Rudolph & Paré, 2003). That makes the neuron a sharper coincidence detector. I use current-based synapses here because they keep the subthreshold dynamics linear and the PSP shape fixed, which makes the STDP analysis below cleaner.

6. STDP: learning from timing

How does a connection know whether to get stronger? Through timing. If A fires just before B, A probably helped make B fire. That connection is useful, so it gets stronger. If A fires just after B, A had nothing to do with it, and the connection gets weaker. The closer together the two spikes, the bigger the change. This rule is called spike-timing-dependent plasticity, or STDP. It's often summed up as "fire together, wire together," but order matters.

How does a connection remember when its spikes happened? Each side keeps a fading memory of its last spike, like a footprint in sand. When B fires, the connection checks how fresh A's footprint is. When A fires, it checks B's.

Spike-timing-dependent plasticity, measured in hippocampal cultures by Bi & Poo (1998), changes a weight according to the relative timing \(\Delta t = t_{\text{post}} - t_{\text{pre}}\) of spike pairs:

$$\Delta w = \begin{cases} +A_+\, e^{-\Delta t/\tau_+} & \Delta t > 0 \quad (\text{pre before post: LTP}) \\ -A_-\, e^{\,\Delta t/\tau_-} & \Delta t < 0 \quad (\text{post before pre: LTD}) \end{cases}$$

A synapse doesn't store spike times. It keeps two decaying traces, which are ODEs just like everything else:

$$\tau_+\frac{dx}{dt} = -x \ \ (x \mathrel{+}= 1 \text{ at pre}), \qquad \tau_-\frac{dy}{dt} = -y \ \ (y \mathrel{+}= 1 \text{ at post}).$$

At each postsynaptic spike the weight gains \(A_+x\). At each presynaptic spike it loses \(A_-y\). Summed over a pair, that is exactly the window above. The figure runs the standard lab protocol: pair a pre and a post spike \(\Delta t\) apart, repeat 60 times at 1 Hz, and record the total change. The window isn't drawn in. It builds up from measurements.

Top left: one pairing, with each spike's fading memory. Bottom left: the connection's strength over the last 60 pairings. Right: every measurement you've made. The dashed curve is the formula.Top left: one pairing with traces \(x\) and \(y\). Bottom left: \(w\) over the last protocol. Right: measured \(\Delta w\) after 60 pairings, against the additive prediction (dashed). Multiplicative: \(\Delta w_+ \propto (1 - w)\), \(\Delta w_- \propto w\).
Try this
  1. Press “Try every gap”. The two-sided window draws itself, one measurement at a time.
  2. Switch to Multiplicative and sweep again. The window keeps its shape but shrinks: every change gets smaller as the connection nears its limit, so no timing can push it all the way to full strength or to zero.
  3. Set the gap to +5 ms and pair 60 times with each rule. Additive climbs in a straight line until it hits the ceiling. Multiplicative curves gently toward it.

The two rules differ in a way that matters for networks. In the additive rule a weight's change doesn't depend on the weight itself, so weights pushed in one direction keep going until they hit a bound. Under competition this gives a bimodal distribution: weights end up near 0 or near the maximum. The multiplicative rule adds a pull toward the middle that keeps weights unimodal and spread out (van Rossum, Bi & Turrigiano, 2000). The finale uses the additive rule because its winner-take-all behavior is easy to see.

Graduate: pairs aren't the whole story

The pair rule with all-to-all trace interactions predicts that LTP and LTD simply add up as pairing frequency rises. Experiments disagree: at high frequency, potentiation dominates even for negative \(\Delta t\) (Sjöström, Turrigiano & Nelson, 2001). The triplet rule (Pfister & Gerstner, 2006) adds a slower postsynaptic trace that gates LTP. That reproduces the frequency dependence and reduces to a BCM-like rule for Poisson firing. Restricting interactions to nearest-neighbour spikes, instead of all-to-all, changes the effective window at high rates too. Gütig et al. (2003) interpolate between the additive and multiplicative rules with a weight-dependence exponent \(\mu\), and show that the split between bimodal and unimodal weights is a transition at small \(\mu\).

7. Finale: how the equations play together

Time to put everything together. One cell listens to 400 inputs. Every input fires about 20 times a second, at random. But there's a secret: half of the inputs are partly copying a hidden source. Now and then the source fires, and about one in five of those inputs fire at the same moment. Look at any single input and you can't tell which half it's in, since they all fire just as often. The only clue is that some of them tend to fire together.

The cell has no teacher and no score. It only has the timing rule from the last section. Press Play and watch: the connections from the inputs that fire together grow strong, and the rest fade away. The cell has found the hidden group by itself.

Now everything runs at once. One LIF neuron receives 400 Poisson inputs at 20 Hz each, through current-based exponential synapses, and every synapse runs the additive STDP rule. Inputs 1–200 share a hidden source: each source spike is copied by every one of them independently with probability \(c = 0.2\), and each makes up the rest of its 20 Hz independently. Inputs 201–400 are independent Poisson. Single-input rates are identical, so only correlations distinguish the groups. The window is slightly depression-dominated, \(A_-\tau_- = 1.05\,A_+\tau_+\). That is the regime Song, Miller & Abbott (2000) showed makes STDP competitive.

The full state, integrated together at \(h = 0.25\) ms, is \(V\), the synaptic current \(I\), the postsynaptic trace \(y\), 400 presynaptic traces \(x_i\), and 400 weights \(w_i\). The panel on the right lights up each equation as it acts. Notice the timescales: \(V\) and \(I\) move in milliseconds, the traces in tens of milliseconds, and the weights over tens of seconds.

Top left: the last half-second of spikes from 60 inputs of each group, plus the hidden source and the cell's output. Darker dots come from stronger connections. Middle left: the strength of all 400 connections. Right: average strength of each group over time, and which rule is acting right now.Top left: raster of 60 inputs per group (opacity = weight), the hidden source, and output spikes. Middle left: all 400 weights. Right: mean weight per group over time, and the model's equations, lit when they act. The output's locking to the source is measured as the fraction of output spikes within 5 ms after a source spike. Chance is about 10%.
Try this
  1. Press Play at 10×. Within about a minute of simulated time the blue bars climb to the top, and the grey ones keep sinking after that.
  2. Watch the output row in the raster and the readout above it. From the start, most output spikes come right after a purple source spike: 40 inputs firing at once is a big kick. While the blue bars grow, extra spikes driven by the background creep in and the share drops. Once the grey bars fade, those extra spikes go away and the share climbs back up.
  3. Untick Learning partway through. The weights freeze but the neuron keeps firing. All the change came from that one timing rule.
  4. Start over a few times. The details change, but the correlated group wins every time.

Why does it work? When several inputs fire at the same moment, their kicks add up and often make the cell fire right after. So inputs from the hidden group often fire just before the cell, and the timing rule strengthens them. The inputs that fire on their own are as likely to fire just after the cell as just before. The rule is tuned to weaken slightly more than it strengthens, so on balance they fade. Strong connections make the cell fire even more in step with the group, so the effect feeds itself.

Why it works: a correlated input often fires together with others in its group, their PSPs sum, and the neuron tends to spike a few milliseconds later. So correlated inputs get more pre-before-post pairings than chance would give, and net LTP. An independent input's timing relative to the output is nearly random. It samples both lobes of the window equally, and because the LTD lobe is slightly larger, it drifts down. The weights that win make the output follow the source more closely, which strengthens the correlation they feed on: positive feedback, held in check by the hard bound \(w \le 1\). Depression dominance also keeps the output rate bounded. As weights grow, extra output spikes bring extra LTD.

Graduate: averaging, drift, and the clock

Because \(A_\pm\) are small, weights change slowly compared with the neural dynamics, and the learning can be averaged (Kempter, Gerstner & van Hemmen, 1999). For Poisson input with rate \(\nu_i\) and output rate \(\nu_{\text{out}}\), the mean drift is

$$\frac{dw_i}{dt} \approx \nu_i\,\nu_{\text{out}} \int W(s)\,ds \;+\; \int W(s)\, C_i(s)\, ds,$$

where \(W\) is the STDP window and \(C_i(s)\) is the covariance between input \(i\) and the output at lag \(s\). The first term is negative here (\(\int W < 0\)) and the same for every input. The second is positive for every input, through its own PSP's effect on the output, and much larger for the correlated group, whose members also share each other's influence. Competition is the first term pushing everything down while the second lifts only some.

On the numerics: with \(h = 0.25\) ms and \(\tau_s = 2\) ms, \(h/\tau_s = 0.125\), comfortably accurate for RK4. The traces have closed-form solutions between spikes, so the code updates each \(x_i\) lazily, only when it is read, instead of decaying 400 numbers every step. This is the core trick of event-driven simulation. A fully event-driven simulator would do the same for \(V\) using the exact LIF propagator and jump straight from spike to spike.

The honest fine print

  • Everything here is a point neuron. No dendrites, no axon, no ion channels (apart from the one Hodgkin–Huxley reference spike). Where on a dendrite a synapse sits changes both its PSP and its plasticity, and none of that is modeled.
  • The finale is a toy. 400 inputs instead of thousands, no inhibition, current-based synapses, constant input rates, and an output rate of 20–55 Hz, higher than most cortical neurons. With Song et al.’s conductance-based setup and balanced inhibition, the same competition happens at more realistic rates.
  • Why correlated inputs and not a hidden spike pattern. A more dramatic version of this experiment hides a repeating spatiotemporal spike pattern in the noise, and the neuron learns to fire at its start (Masquelier, Guyonneau & Thorpe, 2008). In a scaled-down version I tested, the neuron learned the pattern in only about half of the random seeds, so I used the more robust correlated-input version here.
  • STDP is not one rule. The window's shape and even its sign vary across brain areas, cell types, and dendritic locations, and depend on firing rate and neuromodulators. The pair rule is the textbook starting point, not the final word.
  • Parameters. The AdEx firing patterns use parameter sets from Naud et al. (2008). The Hodgkin–Huxley spike uses the classic squid-axon parameters at 6.3 °C. Everything else was chosen to be in a physiological range and easy to see, not fitted to data.

Words to know

  • Differential equation: a rule for how fast something is changing right now, given its current state.
  • Step size (\(h\)): how far forward in time the solver jumps each step. Smaller is more accurate and slower.
  • Euler / RK4: two ways of taking a step. Euler looks once. RK4 looks four times and averages.
  • Attractor: the shape a system's state settles onto over time, like the Lorenz butterfly.
  • Chaos: tiny differences in the starting point grow exponentially, so long-range prediction is impossible even though the rules are exact.
  • Membrane potential (\(V\)): the voltage across a neuron's membrane, about −65 mV at rest.
  • Threshold (\(\theta\)): the voltage at which the neuron fires.
  • Rheobase: the smallest constant input current that makes a neuron fire at all.
  • Refractory period: a short time after a spike when the neuron can't fire, or fires only with difficulty.
  • Adaptation: a slow current that builds up with each spike and makes the next one harder.
  • PSP: the small voltage bump a synaptic input causes in the receiving neuron.
  • LTP / LTD: long-term potentiation and depression, a lasting strengthening or weakening of a synapse.
  • STDP: spike-timing-dependent plasticity. Input before output strengthens a synapse. Output before input weakens it.
  • Trace: a decaying memory of recent spikes that a synapse uses to apply STDP.

References

  • Lorenz, E. N. (1963). Deterministic nonperiodic flow. Journal of the Atmospheric Sciences, 20(2).
  • Tucker, W. (2002). A rigorous ODE solver and Smale’s 14th problem. Foundations of Computational Mathematics, 2(1).
  • Hodgkin, A. L. & Huxley, A. F. (1952). A quantitative description of membrane current and its application to conduction and excitation in nerve. Journal of Physiology, 117(4).
  • Gerstner, W., Kistler, W. M., Naud, R. & Paninski, L. (2014). Neuronal Dynamics: From Single Neurons to Networks and Models of Cognition. Cambridge University Press.
  • Brette, R. & Gerstner, W. (2005). Adaptive exponential integrate-and-fire model as an effective description of neuronal activity. Journal of Neurophysiology, 94(5).
  • Naud, R., Marcille, N., Clopath, C. & Gerstner, W. (2008). Firing patterns in the adaptive exponential integrate-and-fire model. Biological Cybernetics, 99(4–5).
  • Touboul, J. & Brette, R. (2008). Dynamics and bifurcations of the adaptive exponential integrate-and-fire model. Biological Cybernetics, 99(4–5).
  • Badel, L. et al. (2008). Dynamic I-V curves are reliable predictors of naturalistic pyramidal-neuron voltage traces. Journal of Neurophysiology, 99(2).
  • Rotter, S. & Diesmann, M. (1999). Exact digital simulation of time-invariant linear systems with applications to neuronal modeling. Biological Cybernetics, 81(5–6).
  • Destexhe, A., Rudolph, M. & Paré, D. (2003). The high-conductance state of neocortical neurons in vivo. Nature Reviews Neuroscience, 4(9).
  • Bi, G. & Poo, M. (1998). Synaptic modifications in cultured hippocampal neurons: dependence on spike timing, synaptic strength, and postsynaptic cell type. Journal of Neuroscience, 18(24).
  • Song, S., Miller, K. D. & Abbott, L. F. (2000). Competitive Hebbian learning through spike-timing-dependent synaptic plasticity. Nature Neuroscience, 3(9).
  • van Rossum, M. C. W., Bi, G. Q. & Turrigiano, G. G. (2000). Stable Hebbian learning from spike timing-dependent plasticity. Journal of Neuroscience, 20(23).
  • Gütig, R., Aharonov, R., Rotter, S. & Sompolinsky, H. (2003). Learning input correlations through nonlinear temporally asymmetric Hebbian plasticity. Journal of Neuroscience, 23(9).
  • Kempter, R., Gerstner, W. & van Hemmen, J. L. (1999). Hebbian learning and spiking neurons. Physical Review E, 59(4).
  • Sjöström, P. J., Turrigiano, G. G. & Nelson, S. B. (2001). Rate, timing, and cooperativity jointly determine cortical synaptic plasticity. Neuron, 32(6).
  • Pfister, J.-P. & Gerstner, W. (2006). Triplets of spikes in a model of spike timing-dependent plasticity. Journal of Neuroscience, 26(38).
  • Masquelier, T., Guyonneau, R. & Thorpe, S. J. (2008). Spike timing dependent plasticity finds the start of repeating patterns in continuous spike trains. PLoS ONE, 3(1).
Gunnar E
© 2026 All Rights Reserved